answer
stringlengths 15
1.25M
|
|---|
# Overview
Module Name: Scaleable Analytics Adapter
Module Type: Analytics Adapter
Maintainer: chris@scaleable.ai
# Description
Analytics adapter for scaleable.ai. Contact team@scaleable.ai for more information or to sign up for analytics.
# Implementation Code
pbjs.enableAnalytics({
provider: 'scaleable',
options: {
site: '' // Contact Scaleable to receive your unique site id
}
});
|
<?php
/**
* Selector that filters files based on their size.
*
* @author Hans Lellelid <hans@xmpl.org> (Phing)
* @author Bruce Atherton <bruce@callenish.com> (Ant)
* @package phing.types.selectors
*/
class SizeSelector extends BaseExtendSelector {
private $size = -1;
private $multiplier = 1;
private $sizelimit = -1;
private $cmp = 2;
const SIZE_KEY = "value";
const UNITS_KEY = "units";
const WHEN_KEY = "when";
private static $sizeComparisons = array("less", "more", "equal");
private static $byteUnits = array("K", "k", "kilo", "KILO",
"Ki", "KI", "ki", "kibi", "KIBI",
"M", "m", "mega", "MEGA",
"Mi", "MI", "mi", "mebi", "MEBI",
"G", "g", "giga", "GIGA",
"Gi", "GI", "gi", "gibi", "GIBI",
"T", "t", "tera", "TERA",
/* You wish! */ "Ti", "TI", "ti", "tebi", "TEBI"
);
public function toString() {
$buf = "{sizeselector value: ";
$buf .= $this->sizelimit;
$buf .= "compare: ";
if ($this->cmp === 0) {
$buf .= "less";
} elseif ($this->cmp === 1) {
$buf .= "more";
} else {
$buf .= "equal";
}
$buf .= "}";
return $buf;
}
public function setValue($size) {
$this->size = $size;
if (($this->multiplier !== 0) && ($this->size > -1)) {
$this->sizelimit = $size * $this->multiplier;
}
}
/**
* Sets the units to use for the comparison. This is a little
* complicated because common usage has created standards that
* play havoc with capitalization rules. Thus, some people will
* use "K" for indicating 1000's, when the SI standard calls for
* "k". Others have tried to introduce "K" as a multiple of 1024,
* but that falls down when you reach "M", since "m" is already
* defined as 0.001.
* <p>
* To get around this complexity, a number of standards bodies
* have proposed the 2^10 standard, and at least one has adopted
* it. But we are still left with a populace that isn't clear on
* how capitalization should work.
* <p>
* We therefore ignore capitalization as much as possible.
* Completely mixed case is not possible, but all upper and lower
* forms are accepted for all long and short forms. Since we have
* no need to work with the 0.001 case, this practice works here.
* <p>
* This function translates all the long and short forms that a
* unit prefix can occur in and translates them into a single
* multiplier.
*
* @param $units The units to compare the size to.
* @return void
*/
public function setUnits($units) {
$i = array_search($units, self::$byteUnits, true);
if ($i === false) $i = -1; // make it java-like
$this->multiplier = 0;
if (($i > -1) && ($i < 4)) {
$this->multiplier = 1000;
} elseif (($i > 3) && ($i < 9)) {
$this->multiplier = 1024;
} elseif (($i > 8) && ($i < 13)) {
$this->multiplier = 1000000;
} elseif (($i > 12) && ($i < 18)) {
$this->multiplier = 1048576;
} elseif (($i > 17) && ($i < 22)) {
$this->multiplier = 1000000000;
} elseif (($i > 21) && ($i < 27)) {
$this->multiplier = 1073741824;
} elseif (($i > 26) && ($i < 31)) {
$this->multiplier = 1000000000000;
} elseif (($i > 30) && ($i < 36)) {
$this->multiplier = 1099511627776;
}
if (($this->multiplier > 0) && ($this->size > -1)) {
$this->sizelimit = $this->size * $this->multiplier;
}
}
/**
* This specifies when the file should be selected, whether it be
* when the file matches a particular size, when it is smaller,
* or whether it is larger.
*
* @param cmp The comparison to perform, an EnumeratedAttribute
*/
public function setWhen($cmp) {
$c = array_search($cmp, self::$sizeComparisons, true);
if ($c !== false) {
$this->cmp = $c;
}
}
/**
* When using this as a custom selector, this method will be called.
* It translates each parameter into the appropriate setXXX() call.
*
* @param parameters the complete set of parameters for this selector
*/
public function setParameters($parameters) {
parent::setParameters($parameters);
if ($parameters !== null) {
for ($i = 0, $size=count($parameters); $i < $size; $i++) {
$paramname = $parameters[$i]->getName();
switch(strtolower($paramname)) {
case self::SIZE_KEY:
try {
$this->setValue($parameters[$i]->getValue());
} catch (Exception $nfe) {
$this->setError("Invalid size setting "
. $parameters[$i]->getValue());
}
break;
case self::UNITS_KEY:
$this->setUnits($parameters[$i]->getValue());
break;
case self::WHEN_KEY:
$this->setWhen($parameters[$i]->getValue());
break;
default:
$this->setError("Invalid parameter " . $paramname);
}
}
}
}
/**
* <p>Checks to make sure all settings are kosher. In this case, it
* means that the size attribute has been set (to a positive value),
* that the multiplier has a valid setting, and that the size limit
* is valid. Since the latter is a calculated value, this can only
* fail due to a programming error.
* </p>
* <p>If a problem is detected, the setError() method is called.
* </p>
*/
public function verifySettings() {
if ($this->size < 0) {
$this->setError("The value attribute is required, and must be positive");
} elseif ($this->multiplier < 1) {
$this->setError("Invalid Units supplied, must be K,Ki,M,Mi,G,Gi,T,or Ti");
} elseif ($this->sizelimit < 0) {
$this->setError("Internal error: Code is not setting sizelimit correctly");
}
}
/**
* The heart of the matter. This is where the selector gets to decide
* on the inclusion of a file in a particular fileset.
*
* @param basedir A PhingFile object for the base directory
* @param filename The name of the file to check
* @param file A PhingFile object for this filename
* @return whether the file should be selected or not
*/
public function isSelected(PhingFile $basedir, $filename, PhingFile $file) {
$this->validate();
// Directory size never selected for
if ($file->isDirectory()) {
return true;
}
if ($this->cmp === 0) {
return ($file->length() < $this->sizelimit);
} elseif ($this->cmp === 1) {
return ($file->length() > $this->sizelimit);
} else {
return ($file->length() === $this->sizelimit);
}
}
}
|
<!DOCTYPE HTML PUBLIC "-
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_j.html">
<link rel="alternate" hreflang="en" title="English" href="../en/dstat.html">
<link rel="stylesheet" href="../css_j.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - disk_status</title>
</head>
<body>
<div class="para func">
<h2>disk_status</h2>
<p> </p>
<pre>
DSTATUS disk_status (
BYTE <span class="arg">pdrv</span> <span class="c"></span>
);
</pre>
</div>
<div class="para arg">
<h4></h4>
<dl class="par">
<dt>pdrv</dt>
<dd>(0-9)10</dd>
</dl>
</div>
<div class="para ret">
<h4></h4>
<p> </p>
<dl class="ret">
<dt>STA_NOINIT</dt>
<dd> <tt>disk_initialize</tt>FatFs</dd>
<dt>STA_NODISK</dt>
<dd>FatFs</dd>
<dt>STA_PROTECT</dt>
<dd> </dd>
</dl>
</div>
<p class="foot"><a href="../00index_j.html"></a></p>
</body>
</html>
|
(function (enyo, scope) {
/**
* The {@link enyo.<API key>} [mixin]{@glossary mixin} contains methods and
* properties that are automatically applied to all children of {@link enyo.DataRepeater}
* to assist in selection support. (See {@link enyo.DataRepeater} for details on how to
* use selection support.) This mixin also [adds]{@link enyo.Repeater#decorateEvent} the
* `model`, `child` ([control]{@link enyo.Control} instance), and `index` properties to
* all [events]{@glossary event} emitted from the repeater's children.
*
* @mixin enyo.<API key>
* @public
*/
enyo.<API key> = {
/*
* @private
*/
name: '<API key>',
/**
* Indicates whether the current child is selected in the [repeater]{@link enyo.DataRepeater}.
*
* @type {Boolean}
* @default false
* @public
*/
selected: false,
/*
* @method
* @private
*/
selectedChanged: enyo.inherit(function (sup) {
return function () {
if (this.repeater.selection) {
this.addRemoveClass(this.selectedClass || 'selected', this.selected);
// for efficiency purposes, we now directly call this method as opposed to
// forcing a synchronous event dispatch
var idx = this.repeater.collection.indexOf(this.model);
if (this.selected && !this.repeater.isSelected(this.model)) {
this.repeater.select(idx);
} else if (!this.selected && this.repeater.isSelected(this.model)) {
this.repeater.deselect(idx);
}
}
sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
decorateEvent: enyo.inherit(function (sup) {
return function (sender, event) {
event.model = this.model;
event.child = this;
event.index = this.repeater.collection.indexOf(this.model);
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionHandler: function () {
if (this.repeater.selection && !this.get('disabled')) {
if (!this.repeater.groupSelection || !this.selected) {
this.set('selected', !this.selected);
}
}
},
/**
* Deliberately used to supersede the default method and set
* [owner]{@link enyo.Component#owner} to this [control]{@link enyo.Control} so that there
* are no name collisions in the instance [owner]{@link enyo.Component#owner}, and also so
* that [bindings]{@link enyo.Binding} will correctly map to names.
*
* @method
* @private
*/
<API key>: enyo.inherit(function () {
return function (components) {
this.createComponents(components, {owner: this});
};
}),
/**
* Used so that we don't stomp on any built-in handlers for the `ontap`
* {@glossary event}.
*
* @method
* @private
*/
dispatchEvent: enyo.inherit(function (sup) {
return function (name, event, sender) {
if (!event._fromRepeaterChild) {
if (!!~enyo.indexOf(name, this.repeater.selectionEvents)) {
this._selectionHandler();
event._fromRepeaterChild = true;
}
}
return sup.apply(this, arguments);
};
}),
/*
* @method
* @private
*/
constructed: enyo.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
var r = this.repeater,
s = r.selectionProperty;
// this property will only be set if the instance of the repeater needs
// to track the selected state from the view and model and keep them in sync
if (s) {
var bnd = this.binding({
from: 'model.' + s,
to: 'selected',
oneWay: false/*,
kind: enyo.BooleanBinding*/
});
this._selectionBindingId = bnd.euid;
}
};
}),
/*
* @method
* @private
*/
destroy: enyo.inherit(function (sup) {
return function () {
if (this._selectionBindingId) {
var b$ = enyo.Binding.find(this._selectionBindingId);
if (b$) {
b$.destroy();
}
}
sup.apply(this, arguments);
};
}),
/*
* @private
*/
_selectionBindingId: null
};
})(enyo, this);
|
<html>
<head>
<title>Check Box</title>
</head>
<body>
<input type="checkbox" id="opt1" value="Option 1" CHECKED> Option 1
<input type="checkbox" name="opt2" value="value2"> Option 2
<input type="checkbox" name="opt2" value="value3" CHECKED> Option 3
<input type="text" id="text1" />
</body>
</html>
|
This project uses the Natural Language API in a servlet to perform sentiment
analysis on text submitted by a user.


To run this example, first make sure your `<API key>`
environment variable is set and that you've enabled the
[Natural Language API](https://console.developers.google.com/apis/library/language.googleapis.com),
and then execute this command:
bash
mvn package appengine:run
Then navigate to `http://localhost:8080`.
|
#!/usr/bin/env bash
set -e
. ./test-lib.sh
setup_initsvn
setup_gitsvn
(
set -e
cd git-svn
git checkout -q -b work
echo "some work done on a branch" >> test
git add test; git commit -q -m "branch work"
echo "some other work done on a branch" >> test
git add test; git commit -q -m "branch work"
test_expect_success "git-cl upload wants a server" \
"$GIT_CL upload 2>&1 | grep -q 'You must configure'"
git config rietveld.server localhost:10000
test_expect_success "git-cl status has no issue" \
"$GIT_CL_STATUS | grep -q 'no issue'"
# Prevent the editor from coming up when you upload.
export GIT_EDITOR=$(which true)
test_expect_success "upload succeeds (needs a server running on localhost)" \
"$GIT_CL upload -m test master | grep -q 'Issue created'"
test_expect_success "git-cl status now knows the issue" \
"$GIT_CL_STATUS | grep -q 'Issue number'"
# Push a description to this URL.
URL=$($GIT_CL_STATUS | sed -ne '/Issue number/s/[^(]*(\(.*\))/\1/p')
curl --cookie dev_appserver_login="test@example.com:False" \
--data-urlencode subject="test" \
--data-urlencode description="foo-quux" \
--data-urlencode xsrf_token="$(print_xsrf_token)" \
$URL/edit
test_expect_success "git-cl dcommits ok" \
"$GIT_CL dcommit -f"
git checkout -q master
git svn -q rebase >/dev/null 2>&1
test_expect_success "dcommitted code has proper description" \
"git show | grep -q 'foo-quux'"
test_expect_success "issue no longer has a branch" \
"$GIT_CL_STATUS | grep -q 'work : None'"
test_expect_success "upstream svn has our commit" \
"svn log $REPO_URL 2>/dev/null | grep -q 'foo-quux'"
)
SUCCESS=$?
cleanup
if [ $SUCCESS == 0 ]; then
echo PASS
fi
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/gopherface.css" />
</head>
<body>
<h1>GopherFace - Video Preview</h1>
<div class="sectionContainer">
<div class="imageContainer">
<img src="{{.thumbnailPath}}">
</div>
<div class="videoContainer">
<video loop autoplay width="720">
<source src="{{.videoPath}}" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
</body>
</html>
|
#ifndef COLLECT_VIEW_H
#define COLLECT_VIEW_H
#include "contiki-conf.h"
#include "net/linkaddr.h"
#include "net/rime/collect.h"
struct <API key> {
uint16_t len;
uint16_t clock;
uint16_t timesynch_time;
uint16_t cpu;
uint16_t lpm;
uint16_t transmit;
uint16_t listen;
uint16_t parent;
uint16_t parent_etx;
uint16_t current_rtmetric;
uint16_t num_neighbors;
uint16_t beacon_interval;
uint16_t sensors[10];
};
void <API key>(struct <API key> *msg,
const linkaddr_t *parent,
uint16_t etx_to_parent,
uint16_t current_rtmetric,
uint16_t num_neighbors,
uint16_t beacon_interval);
void <API key>(struct <API key> *msg);
#endif /* COLLECT_VIEW_H */
|
<style>
li:first-letter { color: red; }
li.green:first-letter { color: green; }
</style>
<ul style="font-family: Ahem; font-size: 100px; -<API key>: none;">
<li id="target">a</li>
</ul>
<script>
document.body.offsetTop;
document.getElementById("target").className = "green";
</script>
|
#ifndef <API key>
#define <API key>
// Class handling all kinds of selection cuts for primary
// Authors: Svein Lindal, Daniel Lohner *
#include "AliAODpidUtil.h"
#include "AliAODTrack.h"
#include "AliESDtrack.h"
#include "AliVTrack.h"
#include "AliAODTrack.h"
#include "AliMCEvent.h"
#include "AliAnalysisCuts.h"
#include "AliESDtrackCuts.h"
#include "TH1F.h"
class AliESDEvent;
class AliAODEvent;
class <API key>;
class AliKFVertex;
class AliKFParticle;
class TH1F;
class TH2F;
class AliPIDResponse;
class AliAnalysisCuts;
class iostream;
class TList;
class AliAnalysisManager;
using namespace std;
class AliPrimaryPionCuts : public AliAnalysisCuts {
public:
enum cutIds {
kEtaCut,
kClsITSCut,
kClsTPCCut,
kDCACut,
kPtCut,
kPidedxSigmaITSCut,
kPidedxSigmaTPCCut,
kPiTOFSigmaPID,
kMassCut,
kNCuts
};
enum pionCuts {
kPionIn=0,
kNoTracks,
kTrackCuts,
kdEdxCuts,
kPionOut
};
Bool_t SetCutIds(TString cutString);
Int_t fCuts[kNCuts];
Bool_t SetCut(cutIds cutID, Int_t cut);
Bool_t UpdateCutString();
static const char * fgkCutNames[kNCuts];
Bool_t <API key>(const TString <API key>);
AliPrimaryPionCuts(const char *name="PionCuts", const char * title="Pion Cuts");
virtual ~AliPrimaryPionCuts(); //virtual destructor
virtual Bool_t IsSelected(TObject* /*obj*/){return kTRUE;}
virtual Bool_t IsSelected(TList* /*list*/) {return kTRUE;}
TString GetCutNumber();
// Cut Selection
Bool_t PionIsSelectedMC(Int_t labelParticle,AliMCEvent *mcEvent);
Bool_t TrackIsSelected(AliESDtrack* lTrack);
Bool_t PionIsSelected(AliESDtrack* lTrack);
static AliPrimaryPionCuts * <API key>();
static AliPrimaryPionCuts * <API key>();
Bool_t InitPIDResponse();
void SetPIDResponse(AliPIDResponse * pidResponse) {fPIDResponse = pidResponse;}
AliPIDResponse * GetPIDResponse() { return fPIDResponse;}
void PrintCuts();
void PrintCutsWithValues();
void SetLightOutput( Bool_t flag ){fDoLightOutput = flag; return;}
void InitCutHistograms(TString name="",Bool_t preCut = kTRUE,TString cutName="");
void <API key>(TString name="",Bool_t preCut = kTRUE,TString cutName=""){if(!fHistograms){InitCutHistograms(name,preCut,cutName);};}
TList *GetCutHistograms(){return fHistograms;}
static AliVTrack * GetTrack(AliVEvent * event, Int_t label);
Cut functions
Bool_t dEdxCuts(AliVTrack * track);
Bool_t <API key>(Int_t pidedxSigmaCut);
Bool_t <API key>(Int_t ededxSigmaCut);
Bool_t SetITSClusterCut(Int_t clsITSCut);
Bool_t SetTPCClusterCut(Int_t clsTPCCut);
Bool_t SetEtaCut(Int_t etaCut);
Bool_t SetPtCut(Int_t ptCut);
Bool_t SetDCACut(Int_t dcaCut);
void SetEtaShift(Double_t etaShift){fEtaShift = etaShift;}
Bool_t SetTOFPionPIDCut(Int_t TOFelectronPID);
Bool_t SetMassCut(Int_t massCut);
Double_t GetMassCut(){return fMassCut;}
// Request Flags
Double_t GetEtaCut(){ return fEtaCut;}
Double_t <API key>(AliESDtrack* lTrack);
Bool_t DoWeights(){return fDoWeights;}
Bool_t DoMassCut(){return fDoMassCut;}
protected:
TList *fHistograms;
Bool_t fDoLightOutput; ///< switch for running light output, kFALSE -> normal mode, kTRUE -> light mode
AliPIDResponse *fPIDResponse;
AliESDtrackCuts *fEsdTrackCuts;
Double_t fEtaCut;
Double_t fEtaShift;
Bool_t fDoEtaCut;
Double_t fPtCut;
Double_t fMinClsTPC; // minimum clusters in the TPC
Double_t fChi2PerClsTPC; // maximum Chi2 per cluster in the TPC
Bool_t fRequireTPCRefit; // require a refit in the TPC
Double_t fMinClsTPCToF; // minimum clusters to findable clusters
Bool_t fDodEdxSigmaITSCut; // flag to use the dEdxCut ITS based on sigmas
Bool_t fDodEdxSigmaTPCCut; // flag to use the dEdxCut TPC based on sigmas
Bool_t fDoTOFsigmaCut; // flag to use TOF pid cut RRnewTOF
Double_t <API key>; // sigma cut ITS
Double_t <API key>; // sigma cut ITS
Double_t <API key>; // sigma cut TPC
Double_t <API key>; // sigma cut TPC
Double_t <API key>; // sigma cut TOF
Double_t <API key>; // sigma cut TOF
Bool_t <API key>; // flag to use corrected tpc cl info
Bool_t fUseTOFpid; // flag to use tof pid
Bool_t fRequireTOF; //flg to analyze only tracks with TOF signal
Bool_t fDoMassCut;
Double_t fMassCut;
Bool_t fDoWeights;
Double_t fMaxDCAToVertexZ;
// Histograms
TObjString *fCutString; // cut number used for analysis
TString fCutStringRead;
TH1F *fHistCutIndex; // bookkeeping for cuts
TH1F *fHistdEdxCuts; // bookkeeping for dEdx cuts
TH2F *fHistITSdEdxbefore; // ITS dEdx before cuts
TH2F *fHistITSdEdxafter;
TH2F *fHistTPCdEdxbefore; // TPC dEdx before cuts
TH2F *fHistTPCdEdxafter; // TPC dEdx after cuts
TH2F *<API key>; //TPC dEdx signal before
TH2F *<API key>; //TPC dEdx signal after
TH2F *fHistTOFbefore; // TOF after cuts
TH2F *fHistTOFafter; // TOF after cuts
TH2F *<API key>;
TH2F *<API key>;
TH2F *<API key>;
TH2F *<API key>;
TH2F *<API key>;
TH2F *<API key>;
TString <API key>;
private:
AliPrimaryPionCuts(const AliPrimaryPionCuts&); // not implemented
AliPrimaryPionCuts& operator=(const AliPrimaryPionCuts&); // not implemented
ClassDef(AliPrimaryPionCuts,6)
};
#endif
|
<?php
namespace ZendTest\Db\RowGateway;
use Zend\Db\RowGateway\RowGateway;
class <API key> extends \<API key>
{
protected $mockAdapter = null;
/** @var RowGateway */
protected $rowGateway = null;
protected $mockResult = null;
public function setup()
{
// mock the adapter, driver, and parts
$mockResult = $this->getMock('Zend\Db\Adapter\Driver\ResultInterface');
$mockResult->expects($this->any())->method('getAffectedRows')->will($this->returnValue(1));
$this->mockResult = $mockResult;
$mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$mockStatement->expects($this->any())->method('execute')->will($this->returnValue($mockResult));
$mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($mockStatement));
$mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($mockConnection));
// setup mock adapter
$this->mockAdapter = $this->getMock('Zend\Db\Adapter\Adapter', null, array($mockDriver));
$this->rowGateway = $this-><API key>('Zend\Db\RowGateway\AbstractRowGateway');
$rgPropertyValues = array(
'primaryKeyColumn' => 'id',
'table' => 'foo',
'sql' => new \Zend\Db\Sql\Sql($this->mockAdapter)
);
$this->setRowGatewayState($rgPropertyValues);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetSet
*/
public function testOffsetSet()
{
// If we set with an index, both getters should retrieve the same value:
$this->rowGateway['testColumn'] = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__set
*/
public function test__set()
{
// If we set with a property, both getters should retrieve the same value:
$this->rowGateway->testColumn = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__isset
*/
public function test__isset()
{
// Test isset before and after assigning to a property:
$this->assertFalse(isset($this->rowGateway->foo));
$this->rowGateway->foo = 'bar';
$this->assertTrue(isset($this->rowGateway->foo));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetExists
*/
public function testOffsetExists()
{
// Test isset before and after assigning to an index:
$this->assertFalse(isset($this->rowGateway['foo']));
$this->rowGateway['foo'] = 'bar';
$this->assertTrue(isset($this->rowGateway['foo']));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__unset
*/
public function test__unset()
{
$this->rowGateway->foo = 'bar';
$this->assertEquals('bar', $this->rowGateway->foo);
unset($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway['foo']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetUnset
*/
public function testOffsetUnset()
{
$this->rowGateway['foo'] = 'bar';
$this->assertEquals('bar', $this->rowGateway['foo']);
unset($this->rowGateway['foo']);
$this->assertEmpty($this->rowGateway->foo);
$this->assertEmpty($this->rowGateway['foo']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::offsetGet
*/
public function testOffsetGet()
{
// If we set with an index, both getters should retrieve the same value:
$this->rowGateway['testColumn'] = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::__get
*/
public function test__get()
{
// If we set with a property, both getters should retrieve the same value:
$this->rowGateway->testColumn = 'test';
$this->assertEquals('test', $this->rowGateway->testColumn);
$this->assertEquals('test', $this->rowGateway['testColumn']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveInsert()
{
// test insert
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('id' => 5, 'name' => 'foo')));
$this->mockResult->expects($this->any())->method('getGeneratedValue')->will($this->returnValue(5));
$this->rowGateway->populate(array('name' => 'foo'));
$this->rowGateway->save();
$this->assertEquals(5, $this->rowGateway->id);
$this->assertEquals(5, $this->rowGateway['id']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function <API key>()
{
$this->rowGateway = $this-><API key>('Zend\Db\RowGateway\AbstractRowGateway');
$mockSql = $this-><API key>('Zend\Db\Sql\Sql', array($this->mockAdapter));
$rgPropertyValues = array(
'primaryKeyColumn' => array('one', 'two'),
'table' => 'foo',
'sql' => $mockSql
);
$this->setRowGatewayState($rgPropertyValues);
// test insert
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('one' => 'foo', 'two' => 'bar')));
// @todo Need to assert that $where was filled in
$refRowGateway = new \ReflectionObject($this->rowGateway);
$refRowGatewayProp = $refRowGateway->getProperty('primaryKeyData');
$refRowGatewayProp->setAccessible(true);
$this->rowGateway->populate(array('one' => 'foo', 'two' => 'bar'));
$this->assertNull($refRowGatewayProp->getValue($this->rowGateway));
// save should setup the primaryKeyData
$this->rowGateway->save();
$this->assertEquals(array('one' => 'foo', 'two' => 'bar'), $refRowGatewayProp->getValue($this->rowGateway));
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function testSaveUpdate()
{
// test update
$this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('id' => 6, 'name' => 'foo')));
$this->rowGateway->populate(array('id' => 6, 'name' => 'foo'), true);
$this->rowGateway->save();
$this->assertEquals(6, $this->rowGateway['id']);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::save
*/
public function <API key>()
{
// this mock is the select to be used to re-fresh the rowobject's data
$selectMock = $this->getMock('Zend\Db\Sql\Select', array('where'));
$selectMock->expects($this->once())
->method('where')
->with($this->equalTo(array('id' => 7)))
->will($this->returnValue($selectMock));
$sqlMock = $this->getMock('Zend\Db\Sql\Sql', array('select'), array($this->mockAdapter));
$sqlMock->expects($this->any())
->method('select')
->will($this->returnValue($selectMock));
$this->setRowGatewayState(array('sql' => $sqlMock));
// original mock returning updated data
$this->mockResult->expects($this->any())
->method('current')
->will($this->returnValue(array('id' => 7, 'name' => 'fooUpdated')));
// populate forces an update in save(), seeds with original data (from db)
$this->rowGateway->populate(array('id' => 6, 'name' => 'foo'), true);
$this->rowGateway->id = 7;
$this->rowGateway->save();
$this->assertEquals(array('id' => 7, 'name' => 'fooUpdated'), $this->rowGateway->toArray());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::delete
*/
public function testDelete()
{
$this->rowGateway->foo = 'bar';
$affectedRows = $this->rowGateway->delete();
$this->assertFalse($this->rowGateway->rowExistsInDatabase());
$this->assertEquals(1, $affectedRows);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::populate
* @covers Zend\Db\RowGateway\RowGateway::rowExistsInDatabase
*/
public function testPopulate()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'));
$this->assertEquals(5, $this->rowGateway['id']);
$this->assertEquals('foo', $this->rowGateway['name']);
$this->assertFalse($this->rowGateway->rowExistsInDatabase());
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertTrue($this->rowGateway->rowExistsInDatabase());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::<API key>
*/
public function <API key>()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this-><API key>('Zend\Db\RowGateway\Exception\RuntimeException', 'a known key id was not found');
$this->rowGateway->populate(array('boo' => 5, 'name' => 'foo'), true);
}
/**
* @covers Zend\Db\RowGateway\RowGateway::count
*/
public function testCount()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertEquals(2, $this->rowGateway->count());
}
/**
* @covers Zend\Db\RowGateway\RowGateway::toArray
*/
public function testToArray()
{
$this->rowGateway->populate(array('id' => 5, 'name' => 'foo'), true);
$this->assertEquals(array('id' => 5, 'name' => 'foo'), $this->rowGateway->toArray());
}
protected function setRowGatewayState(array $properties)
{
$refRowGateway = new \ReflectionObject($this->rowGateway);
foreach ($properties as $rgPropertyName => $rgPropertyValue) {
$refRowGatewayProp = $refRowGateway->getProperty($rgPropertyName);
$refRowGatewayProp->setAccessible(true);
$refRowGatewayProp->setValue($this->rowGateway, $rgPropertyValue);
}
}
}
|
import scala.scalajs.js
import scala.scalajs.js.Dynamic.global
import org.scalajs.jasminetest.JasmineTest
object ElementCreatorTest extends JasmineTest {
describe("ElementCreator") {
it("should be able to create an element in the body") {
// create the element
ElementCreator.create()
// jquery would make this easier, but I wanted to
// only use pure html in the test itself
val body = global.document.<API key>("body")
.asInstanceOf[js.Array[js.Dynamic]].head
// the Scala.js DOM API would make this easier
expect(body.lastChild.tagName.toString == "H1").toBeTruthy
expect(body.lastChild.innerHTML.toString == "Test").toBeTruthy
}
}
}
|
import os
from <API key> import <API key>
from model import Model, UnixName
from schema_loader import SchemaLoader
def _GenerateFilenames(full_namespace):
# Try to find the file defining the namespace. Eg. for
# nameSpace.sub_name_space.Type' the following heuristics looks for:
# 1. <API key>.json,
# 2. <API key>.idl,
# 3. sub_name_space.json,
# 4. sub_name_space.idl,
# 5. etc.
sub_namespaces = full_namespace.split('.')
filenames = [ ]
basename = None
for namespace in reversed(sub_namespaces):
if basename is not None:
basename = UnixName(namespace + '.' + basename)
else:
basename = UnixName(namespace)
for ext in ['json', 'idl']:
filenames.append('%s.%s' % (basename, ext))
return filenames
class NamespaceResolver(object):
'''Resolves a type name into the namespace the type belongs to.
- |root| path to the root directory.
- |path| path to the directory with the API header files, relative to the
root.
- |include_rules| List containing tuples with (path, <API key>)
used when searching for types.
- |<API key>| Default namespace pattern
'''
def __init__(self, root, path, include_rules, <API key>):
self._root = root
self._include_rules = [(path, <API key>)] + include_rules
def ResolveNamespace(self, full_namespace):
'''Returns the model.Namespace object associated with the |full_namespace|,
or None if one can't be found.
'''
filenames = _GenerateFilenames(full_namespace)
for path, cpp_namespace in self._include_rules:
<API key> = None
if cpp_namespace:
<API key> = <API key>(cpp_namespace)
for filename in reversed(filenames):
filepath = os.path.join(path, filename);
if os.path.exists(os.path.join(self._root, filepath)):
schema = SchemaLoader(self._root).LoadSchema(filepath)[0]
return Model().AddNamespace(
schema,
filepath,
environment=<API key>)
return None
def ResolveType(self, full_name, default_namespace):
'''Returns the model.Namespace object where the type with the given
|full_name| is defined, or None if one can't be found.
'''
name_parts = full_name.rsplit('.', 1)
if len(name_parts) == 1:
if full_name not in default_namespace.types:
return None
return default_namespace
full_namespace, type_name = full_name.rsplit('.', 1)
namespace = self.ResolveNamespace(full_namespace)
if namespace and type_name in namespace.types:
return namespace
return None
|
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: src/proto/grpc/testing/test.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Testing {
<summary>Holder for reflection information generated from src/proto/grpc/testing/test.proto</summary>
public static partial class TestReflection {
#region Descriptor
<summary>File descriptor for src/proto/grpc/testing/test.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TestReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>",
"<API key>"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Grpc.Testing.EmptyReflection.Descriptor, global::Grpc.Testing.MessagesReflection.Descriptor, },
new pbr::<API key>(null, null));
}
#endregion
}
}
#endregion Designer generated code
|
/* <API key>: GPL-2.0 */
#ifndef CGX_H
#define CGX_H
#include "mbox.h"
#include "cgx_fw_if.h"
#include "rpm.h"
/* PCI device IDs */
#define <API key> 0xA059
/* PCI BAR nos */
#define PCI_CFG_REG_BAR_NUM 0
#define CGX_ID_MASK 0x7
#define MAX_LMAC_PER_CGX 4
#define <API key> 32
#define CGX_FIFO_LEN 65536 /* 64K for both Rx & Tx */
#define CGX_OFFSET(x) ((x) * MAX_LMAC_PER_CGX)
/* Registers */
#define CGXX_CMRX_CFG 0x00
#define CMR_P2X_SEL_MASK GENMASK_ULL(61, 59)
#define CMR_P2X_SEL_SHIFT 59ULL
#define CMR_P2X_SEL_NIX0 1ULL
#define CMR_P2X_SEL_NIX1 2ULL
#define CMR_EN BIT_ULL(55)
#define DATA_PKT_TX_EN BIT_ULL(53)
#define DATA_PKT_RX_EN BIT_ULL(54)
#define CGX_LMAC_TYPE_SHIFT 40
#define CGX_LMAC_TYPE_MASK 0xF
#define CGXX_CMRX_INT 0x040
#define FW_CGX_INT BIT_ULL(1)
#define <API key> 0x058
#define CGXX_CMRX_RX_ID_MAP 0x060
#define CGXX_CMRX_RX_STAT0 0x070
#define CGXX_CMRX_RX_LMACS 0x128
#define <API key> (0x1F8 + mac_ops->csr_offset)
#define <API key> BIT_ULL(3)
#define CGX_DMAC_CAM_ACCEPT BIT_ULL(3)
#define <API key> BIT_ULL(2)
#define CGX_DMAC_MCAST_MODE BIT_ULL(1)
#define CGX_DMAC_BCAST_MODE BIT_ULL(0)
#define <API key> (0x200 + mac_ops->csr_offset)
#define <API key> BIT_ULL(48)
#define <API key> GENMASK_ULL(50, 49)
#define <API key> 0x400
#define <API key> GENMASK_ULL(47, 0)
#define CGXX_CMRX_TX_STAT0 0x700
#define CGXX_SCRATCH0_REG 0x1050
#define CGXX_SCRATCH1_REG 0x1058
#define CGX_CONST 0x2000
#define <API key> GENMASK_ULL(23, 0)
#define CGXX_SPUX_CONTROL1 0x10000
#define <API key> 0x10700
#define <API key> 0x10800
#define <API key> 0x10088
#define <API key> 0x10090
#define <API key> BIT_ULL(14)
#define <API key> 0x30000
#define <API key> BIT_ULL(14)
#define <API key> 0x20020
#define <API key> BIT_ULL(3)
#define <API key> BIT_ULL(12)
#define <API key> 0x38028
#define <API key> BIT_ULL(3)
#define <API key> BIT_ULL(12)
#define CGXX_SMUX_TX_CTL 0x20178
#define <API key> 0x20110
#define <API key> 0x20120
#define <API key> 0x38230
#define <API key> 0x38248
#define <API key> BIT_ULL(7)
#define CGXX_CMR_RX_OVR_BP 0x130
#define <API key>(X) BIT_ULL(((X) + 8))
#define <API key>(X) BIT_ULL(((X) + 4))
#define CGX_COMMAND_REG CGXX_SCRATCH1_REG
#define CGX_EVENT_REG CGXX_SCRATCH0_REG
#define CGX_CMD_TIMEOUT 2200 /* msecs */
#define DEFAULT_PAUSE_TIME 0x7FF
#define CGX_LMAC_FWI 0
enum cgx_nix_stat_type {
NIX_STATS_RX,
NIX_STATS_TX,
};
enum LMAC_TYPE {
LMAC_MODE_SGMII = 0,
LMAC_MODE_XAUI = 1,
LMAC_MODE_RXAUI = 2,
LMAC_MODE_10G_R = 3,
LMAC_MODE_40G_R = 4,
LMAC_MODE_QSGMII = 6,
LMAC_MODE_25G_R = 7,
LMAC_MODE_50G_R = 8,
LMAC_MODE_100G_R = 9,
LMAC_MODE_USXGMII = 10,
LMAC_MODE_MAX,
};
struct cgx_link_event {
struct cgx_link_user_info link_uinfo;
u8 cgx_id;
u8 lmac_id;
};
/**
* struct cgx_event_cb
* @notify_link_chg: callback for link change notification
* @data: data passed to callback function
*/
struct cgx_event_cb {
int (*notify_link_chg)(struct cgx_link_event *event, void *data);
void *data;
};
extern struct pci_driver cgx_driver;
int cgx_get_cgxcnt_max(void);
int cgx_get_cgxid(void *cgxd);
int cgx_get_lmac_cnt(void *cgxd);
void *cgx_get_pdata(int cgx_id);
int cgx_set_pkind(void *cgxd, u8 lmac_id, int pkind);
int <API key>(struct cgx_event_cb *cb, void *cgxd, int lmac_id);
int <API key>(void *cgxd, int lmac_id);
int cgx_get_tx_stats(void *cgxd, int lmac_id, int idx, u64 *tx_stat);
int cgx_get_rx_stats(void *cgxd, int lmac_id, int idx, u64 *rx_stat);
int <API key>(void *cgxd, int lmac_id, bool enable);
int cgx_lmac_tx_enable(void *cgxd, int lmac_id, bool enable);
int cgx_lmac_addr_set(u8 cgx_id, u8 lmac_id, u8 *mac_addr);
int cgx_lmac_addr_reset(u8 cgx_id, u8 lmac_id);
u64 cgx_lmac_addr_get(u8 cgx_id, u8 lmac_id);
int cgx_lmac_addr_add(u8 cgx_id, u8 lmac_id, u8 *mac_addr);
int cgx_lmac_addr_del(u8 cgx_id, u8 lmac_id, u8 index);
int <API key>(u8 cgx_id, u8 lmac_id);
void <API key>(int cgx_id, int lmac_id, bool enable);
void <API key>(void *cgxd, int lmac_id, bool enable);
int <API key>(void *cgxd, int lmac_id, bool enable);
int cgx_get_link_info(void *cgxd, int lmac_id,
struct cgx_link_user_info *linfo);
int <API key>(void *cgxd);
int cgx_get_fwdata_base(u64 *base);
int <API key>(void *cgxd, int lmac_id,
u8 *tx_pause, u8 *rx_pause);
int <API key>(void *cgxd, int lmac_id,
u8 tx_pause, u8 rx_pause);
void cgx_lmac_ptp_config(void *cgxd, int lmac_id, bool enable);
u8 cgx_lmac_get_p2x(int cgx_id, int lmac_id);
int cgx_set_fec(u64 fec, int cgx_id, int lmac_id);
int cgx_get_fec_stats(void *cgxd, int lmac_id, struct cgx_fec_stats_rsp *rsp);
int <API key>(void *cgxd, int lmac_id);
int cgx_set_link_mode(void *cgxd, struct <API key> args,
int cgx_id, int lmac_id);
u64 cgx_features_get(void *cgxd);
struct mac_ops *get_mac_ops(void *cgxd);
int cgx_get_nr_lmacs(void *cgxd);
u8 cgx_get_lmacid(void *cgxd, u8 lmac_index);
unsigned long cgx_get_lmac_bmap(void *cgxd);
void cgx_lmac_write(int cgx_id, int lmac_id, u64 offset, u64 val);
u64 cgx_lmac_read(int cgx_id, int lmac_id, u64 offset);
int <API key>(u8 cgx_id, u8 lmac_id, u8 *mac_addr, u8 index);
u64 cgx_read_dmac_ctrl(void *cgxd, int lmac_id);
u64 cgx_read_dmac_entry(void *cgxd, int index);
#endif /* CGX_H */
|
'use strict';
var vows = require('vows');
var assert = require('assert');
var async = require('async');
var tough = require('../lib/cookie');
var Cookie = tough.Cookie;
var CookieJar = tough.CookieJar;
var atNow = Date.now();
function at(offset) {
return {now: new Date(atNow + offset)};
}
vows
.describe('Regression tests')
.addBatch({
"Issue 1": {
topic: function () {
var cj = new CookieJar();
cj.setCookie('hello=world; path=/some/path/', 'http://domain/some/path/file', function (err, cookie) {
this.callback(err, {cj: cj, cookie: cookie});
}.bind(this));
},
"stored a cookie": function (t) {
assert.ok(t.cookie);
},
"getting it back": {
topic: function (t) {
t.cj.getCookies('http://domain/some/path/file', function (err, cookies) {
this.callback(err, {cj: t.cj, cookies: cookies || []});
}.bind(this));
},
"got one cookie": function (t) {
assert.lengthOf(t.cookies, 1);
},
"it's the right one": function (t) {
var c = t.cookies[0];
assert.equal(c.key, 'hello');
assert.equal(c.value, 'world');
}
}
}
})
.addBatch({
"trailing semi-colon set into cj": {
topic: function () {
var cb = this.callback;
var cj = new CookieJar();
var ex = 'http:
var tasks = [];
tasks.push(function (next) {
cj.setCookie('broken_path=testme; path=/;', ex, at(-1), next);
});
tasks.push(function (next) {
cj.setCookie('b=2; Path=/;;;;', ex, at(-1), next);
});
async.parallel(tasks, function (err, cookies) {
cb(null, {
cj: cj,
cookies: cookies
});
});
},
"check number of cookies": function (t) {
assert.lengthOf(t.cookies, 2, "didn't set");
},
"check *broken_path* was set properly": function (t) {
assert.equal(t.cookies[0].key, "broken_path");
assert.equal(t.cookies[0].value, "testme");
assert.equal(t.cookies[0].path, "/");
},
"check *b* was set properly": function (t) {
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
},
"retrieve the cookie": {
topic: function (t) {
var cb = this.callback;
t.cj.getCookies('http:
t.cookies = cookies;
cb(err, t);
});
},
"get the cookie": function (t) {
assert.lengthOf(t.cookies, 2);
assert.equal(t.cookies[0].key, 'broken_path');
assert.equal(t.cookies[0].value, 'testme');
assert.equal(t.cookies[1].key, "b");
assert.equal(t.cookies[1].value, "2");
assert.equal(t.cookies[1].path, "/");
}
}
}
})
.addBatch({
"tough-cookie throws exception on malformed URI (GH-32)": {
topic: function () {
var url = "http:
var cj = new CookieJar();
cj.setCookieSync("Test=Test", url);
return cj.getCookieStringSync(url);
},
"cookies are set": function (cookieStr) {
assert.strictEqual(cookieStr, "Test=Test");
}
}
})
.export(module);
|
<?php
return [
'Names' => [
'CDF' => [
0 => 'FC',
1 => 'franc congolais',
],
],
];
|
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.StreamAnalytics.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.StreamAnalytics;
using Newtonsoft.Json;
using System.Linq;
<summary>
Defines headers for Update operation.
</summary>
public partial class <API key>
{
<summary>
Initializes a new instance of the <API key> class.
</summary>
public <API key>()
{
CustomInit();
}
<summary>
Initializes a new instance of the <API key> class.
</summary>
<param name="eTag">The current entity tag for the function. This is
an opaque string. You can use it to detect whether the resource has
changed between requests. You can also use it in the If-Match or
If-None-Match headers for write operations for optimistic
concurrency.</param>
public <API key>(string eTag = default(string))
{
ETag = eTag;
CustomInit();
}
<summary>
An initialization method that performs custom operations like setting defaults
</summary>
partial void CustomInit();
<summary>
Gets or sets the current entity tag for the function. This is an
opaque string. You can use it to detect whether the resource has
changed between requests. You can also use it in the If-Match or
If-None-Match headers for write operations for optimistic
concurrency.
</summary>
[JsonProperty(PropertyName = "ETag")]
public string ETag { get; set; }
}
}
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function <API key>(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Promise = require('bluebird');
var MongoClient = require('mongodb');
function <API key>(session) {
// Copy each property of the session to a new object
var obj = {};
var prop = void 0;
for (prop in session) {
if (prop === 'cookie') {
// Convert the cookie instance to an object, if possible
// This gets rid of the duplicate object under session.cookie.data property
obj.cookie = session.cookie.toJSON ? session.cookie.toJSON() : session.cookie;
} else {
obj[prop] = session[prop];
}
}
return obj;
}
function <API key>(options, defaultStringify) {
if (options.serialize || options.unserialize) {
return {
serialize: options.serialize || <API key>,
unserialize: options.unserialize || function (x) {
return x;
}
};
}
if (options.stringify === false || defaultStringify === false) {
return {
serialize: <API key>,
unserialize: function (x) {
return x;
}
};
}
if (options.stringify === true || defaultStringify === true) {
return {
serialize: JSON.stringify,
unserialize: JSON.parse
};
}
}
module.exports = function connectMongo(connect) {
var Store = connect.Store || connect.session.Store;
var MemoryStore = connect.MemoryStore || connect.session.MemoryStore;
var MongoStore = function (_Store) {
_inherits(MongoStore, _Store);
function MongoStore(options) {
_classCallCheck(this, MongoStore);
options = options || {};
/* Fallback */
if (options.fallbackMemory && MemoryStore) {
var _ret;
return _ret = new MemoryStore(), <API key>(_this, _ret);
}
/* Options */
var _this = <API key>(this, Object.getPrototypeOf(MongoStore).call(this, options));
_this.ttl = options.ttl || 1209600; // 14 days
_this.collectionName = options.collection || 'sessions';
_this.autoRemove = options.autoRemove || 'native';
_this.autoRemoveInterval = options.autoRemoveInterval || 10;
_this.transformFunctions = <API key>(options, true);
_this.options = options;
_this.changeState('init');
var <API key> = function (err, db) {
if (err) {
_this.connectionFailed(err);
} else {
_this.<API key>(db);
}
};
if (options.url) {
// New native connection using url + mongoOptions
MongoClient.connect(options.url, options.mongoOptions || {}, <API key>);
} else if (options.mongooseConnection) {
// Re-use existing or upcoming mongoose connection
if (options.mongooseConnection.readyState === 1) {
_this.<API key>(options.mongooseConnection.db);
} else {
options.mongooseConnection.once('open', function () {
return _this.<API key>(options.mongooseConnection.db);
});
}
} else if (options.db && options.db.listCollections) {
// Re-use existing or upcoming native connection
if (options.db.openCalled || options.db.openCalled === undefined) {
// openCalled is undefined in mongodb@2.x
_this.<API key>(options.db);
} else {
options.db.open(<API key>);
}
} else if (options.dbPromise) {
options.dbPromise.then(function (db) {
return _this.<API key>(db);
}).catch(function (err) {
return _this.connectionFailed(err);
});
} else {
throw new Error('Connection strategy not found');
}
_this.changeState('connecting');
return _this;
}
_createClass(MongoStore, [{
key: 'connectionFailed',
value: function connectionFailed(err) {
this.changeState('disconnected');
throw err;
}
}, {
key: '<API key>',
value: function <API key>(db) {
var _this2 = this;
this.db = db;
return this.setCollection(db.collection(this.collectionName)).setAutoRemoveAsync().then(function () {
return _this2.changeState('connected');
});
}
}, {
key: 'setAutoRemoveAsync',
value: function setAutoRemoveAsync() {
var _this3 = this;
switch (this.autoRemove) {
case 'native':
return this.collection.ensureIndexAsync({ expires: 1 }, { expireAfterSeconds: 0 });
case 'interval':
var removeQuery = { expires: { $lt: new Date() } };
this.timer = setInterval(function () {
return _this3.collection.remove(removeQuery, { w: 0 });
}, this.autoRemoveInterval * 1000 * 60);
this.timer.unref();
return Promise.resolve();
default:
return Promise.resolve();
}
}
}, {
key: 'changeState',
value: function changeState(newState) {
if (newState !== this.state) {
this.state = newState;
this.emit(newState);
}
}
}, {
key: 'setCollection',
value: function setCollection(collection) {
if (this.timer) {
clearInterval(this.timer);
}
this.<API key> = undefined;
this.collection = collection;
// Promisify used collection methods
['count', 'findOne', 'remove', 'drop', 'update', 'ensureIndex'].forEach(function (method) {
collection[method + 'Async'] = Promise.promisify(collection[method], collection);
});
return this;
}
}, {
key: 'collectionReady',
value: function collectionReady() {
var _this4 = this;
var promise = this.<API key>;
if (!promise) {
promise = new Promise(function (resolve, reject) {
switch (_this4.state) {
case 'connected':
resolve(_this4.collection);
break;
case 'connecting':
_this4.once('connected', function () {
return resolve(_this4.collection);
});
break;
case 'disconnected':
reject(new Error('Not connected'));
break;
}
});
this.<API key> = promise;
}
return promise;
}
}, {
key: 'computeStorageId',
value: function computeStorageId(sessionId) {
if (this.options.transformId && typeof this.options.transformId === 'function') {
return this.options.transformId(sessionId);
} else {
return sessionId;
}
}
/* Public API */
}, {
key: 'get',
value: function get(sid, callback) {
var _this5 = this;
return this.collectionReady().then(function (collection) {
return collection.findOneAsync({
_id: _this5.computeStorageId(sid),
$or: [{ expires: { $exists: false } }, { expires: { $gt: new Date() } }]
});
}).then(function (session) {
if (session) {
var s = _this5.transformFunctions.unserialize(session.session);
if (_this5.options.touchAfter > 0 && session.lastModified) {
s.lastModified = session.lastModified;
}
_this5.emit('touch', sid);
return s;
}
}).nodeify(callback);
}
}, {
key: 'set',
value: function set(sid, session, callback) {
var _this6 = this;
// removing the lastModified prop from the session object before update
if (this.options.touchAfter > 0 && session && session.lastModified) {
delete session.lastModified;
}
var s;
try {
s = { _id: this.computeStorageId(sid), session: this.transformFunctions.serialize(session) };
} catch (err) {
return callback(err);
}
if (session && session.cookie && session.cookie.expires) {
s.expires = new Date(session.cookie.expires);
} else {
// If there's no expiration date specified, it is
// browser-session cookie or there is no cookie at all,
// as per the connect docs.
// So we set the expiration to two-weeks from now
// - as is common practice in the industry (e.g Django) -
// or the default specified in the options.
s.expires = new Date(Date.now() + this.ttl * 1000);
}
if (this.options.touchAfter > 0) {
s.lastModified = new Date();
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this6.computeStorageId(sid) }, s, { upsert: true });
}).then(function () {
return _this6.emit('set', sid);
}).nodeify(callback);
}
}, {
key: 'touch',
value: function touch(sid, session, callback) {
var _this7 = this;
var updateFields = {},
touchAfter = this.options.touchAfter * 1000,
lastModified = session.lastModified ? session.lastModified.getTime() : 0,
currentDate = new Date();
// if the given options has a touchAfter property, check if the
// current timestamp - lastModified timestamp is bigger than
// the specified, if it's not, don't touch the session
if (touchAfter > 0 && lastModified > 0) {
var timeElapsed = currentDate.getTime() - session.lastModified;
if (timeElapsed < touchAfter) {
return callback();
} else {
updateFields.lastModified = currentDate;
}
}
if (session && session.cookie && session.cookie.expires) {
updateFields.expires = new Date(session.cookie.expires);
} else {
updateFields.expires = new Date(Date.now() + this.ttl * 1000);
}
return this.collectionReady().then(function (collection) {
return collection.updateAsync({ _id: _this7.computeStorageId(sid) }, { $set: updateFields });
}).then(function (result) {
if (result.nModified === 0) {
throw new Error('Unable to find the session to touch');
} else {
_this7.emit('touch', sid);
}
}).nodeify(callback);
}
}, {
key: 'destroy',
value: function destroy(sid, callback) {
var _this8 = this;
return this.collectionReady().then(function (collection) {
return collection.removeAsync({ _id: _this8.computeStorageId(sid) });
}).then(function () {
return _this8.emit('destroy', sid);
}).nodeify(callback);
}
}, {
key: 'length',
value: function length(callback) {
return this.collectionReady().then(function (collection) {
return collection.countAsync({});
}).nodeify(callback);
}
}, {
key: 'clear',
value: function clear(callback) {
return this.collectionReady().then(function (collection) {
return collection.dropAsync();
}).nodeify(callback);
}
}, {
key: 'close',
value: function close() {
if (this.db) {
this.db.close();
}
}
}]);
return MongoStore;
}(Store);
return MongoStore;
};
|
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
|
from __future__ import division, absolute_import, print_function
import sys
import collections
import pickle
import warnings
from os import path
import numpy as np
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal, assert_array_equal,
<API key>, assert_raises, assert_warns
)
class TestFromrecords(TestCase):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
if sys.version_info[0] >= 3:
assert_equal(r['col2'].dtype.kind, 'U')
assert_equal(r['col2'].dtype.itemsize, 12)
else:
assert_equal(r['col2'].dtype.kind, 'S')
assert_equal(r['col2'].dtype.itemsize, 3)
assert_equal(r['col3'].dtype.kind, 'f')
def <API key>(self):
""" Verify fromrecords works with a 0-length input """
dtype = [('a', np.float), ('b', np.float)]
r = np.rec.fromrecords([], dtype=dtype)
assert_equal(r.shape, (0,))
def test_fromrecords_2d(self):
data = [
[(1, 2), (3, 4), (5, 6)],
[(6, 5), (4, 3), (2, 1)]
]
expected_a = [[1, 3, 5], [6, 4, 2]]
expected_b = [[2, 4, 6], [5, 3, 1]]
# try with dtype
r1 = np.rec.fromrecords(data, dtype=[('a', int), ('b', int)])
assert_equal(r1['a'], expected_a)
assert_equal(r1['b'], expected_b)
# try with names
r2 = np.rec.fromrecords(data, names=['a', 'b'])
assert_equal(r2['a'], expected_a)
assert_equal(r2['b'], expected_b)
assert_equal(r1, r2)
def test_method_array(self):
r = np.rec.array(b'abcdefg' * 100, formats='i2,a3,i4', shape=3, byteorder='big')
assert_equal(r[1].item(), (25444, b'efg', 1633837924))
def test_method_array2(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1].item(), (2, 22.0, b'b'))
def <API key>(self):
r = np.rec.array([(1, 11, 'a'), (2, 22, 'b'), (3, 33, 'c'), (4, 44, 'd'), (5, 55, 'ex'),
(6, 66, 'f'), (7, 77, 'g')], formats='u1,f4,a1')
assert_equal(r[1::2][1].item(), (4, 44.0, b'd'))
def <API key>(self):
x1 = np.array([1, 2, 3, 4])
x2 = np.array(['a', 'dd', 'xyz', '12'])
x3 = np.array([1.1, 2, 3, 4])
r = np.rec.fromarrays([x1, x2, x3], names='a,b,c')
assert_equal(r[1].item(), (2, 'dd', 2.0))
x1[1] = 34
assert_equal(r.a, np.array([1, 2, 3, 4]))
def <API key>(self):
data_dir = path.join(path.dirname(__file__), 'data')
filename = path.join(data_dir, 'recarray_from_file.fits')
fd = open(filename, 'rb')
fd.seek(2880 * 2)
r1 = np.rec.fromfile(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.seek(2880 * 2)
r2 = np.rec.array(fd, formats='f8,i4,a5', shape=3, byteorder='big')
fd.close()
assert_equal(r1, r2)
def <API key>(self):
count = 10
a = np.zeros(count, dtype='O')
b = np.zeros(count, dtype='f8')
c = np.zeros(count, dtype='f8')
for i in range(len(a)):
a[i] = list(range(1, 10))
mine = np.rec.fromarrays([a, b, c], names='date,data1,data2')
for i in range(len(a)):
assert_((mine.date[i] == list(range(1, 10))))
assert_((mine.data1[i] == 0.0))
assert_((mine.data2[i] == 0.0))
def <API key>(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
recordarr = np.rec.array(a)
recarr = a.view(np.recarray)
recordview = a.view(np.dtype((np.record, a.dtype)))
recordarr_r = eval("numpy." + repr(recordarr), {'numpy': np})
recarr_r = eval("numpy." + repr(recarr), {'numpy': np})
recordview_r = eval("numpy." + repr(recordview), {'numpy': np})
assert_equal(type(recordarr_r), np.recarray)
assert_equal(recordarr_r.dtype.type, np.record)
assert_equal(recordarr, recordarr_r)
assert_equal(type(recarr_r), np.recarray)
assert_equal(recarr_r.dtype.type, np.record)
assert_equal(recarr, recarr_r)
assert_equal(type(recordview_r), np.ndarray)
assert_equal(recordview.dtype.type, np.record)
assert_equal(recordview, recordview_r)
def test_recarray_views(self):
a = np.array([(1,'ABC'), (2, "DEF")],
dtype=[('foo', int), ('bar', 'S4')])
b = np.array([1,2,3,4,5], dtype=np.int64)
#check that np.rec.array gives right dtypes
assert_equal(np.rec.array(a).dtype.type, np.record)
assert_equal(type(np.rec.array(a)), np.recarray)
assert_equal(np.rec.array(b).dtype.type, np.int64)
assert_equal(type(np.rec.array(b)), np.recarray)
#check that viewing as recarray does the same
assert_equal(a.view(np.recarray).dtype.type, np.record)
assert_equal(type(a.view(np.recarray)), np.recarray)
assert_equal(b.view(np.recarray).dtype.type, np.int64)
assert_equal(type(b.view(np.recarray)), np.recarray)
#check that view to non-structured dtype preserves type=np.recarray
r = np.rec.array(np.ones(4, dtype="f4,i4"))
rv = r.view('f8').view('f4,i4')
assert_equal(type(rv), np.recarray)
assert_equal(rv.dtype.type, np.record)
#check that getitem also preserves np.recarray and np.record
r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
('c', 'i4,i4')]))
assert_equal(r['c'].dtype.type, np.record)
assert_equal(type(r['c']), np.recarray)
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
assert_equal(r[['a', 'b']].dtype.type, np.record)
assert_equal(type(r[['a', 'b']]), np.recarray)
#and that it preserves subclasses (gh-6949)
class C(np.recarray):
pass
c = r.view(C)
assert_equal(type(c['c']), C)
# check that accessing nested structures keep record type, but
# not for subarrays, non-void structures, non-structured voids
test_dtype = [('a', 'f4,f4'), ('b', 'V8'), ('c', ('f4',2)),
('d', ('i8', 'i4,i4'))]
r = np.rec.array([((1,1), b'11111111', [1,1], 1),
((1,1), b'11111111', [1,1], 1)], dtype=test_dtype)
assert_equal(r.a.dtype.type, np.record)
assert_equal(r.b.dtype.type, np.void)
assert_equal(r.c.dtype.type, np.float32)
assert_equal(r.d.dtype.type, np.int64)
# check the same, but for views
r = np.rec.array(np.ones(4, dtype='i4,i4'))
assert_equal(r.view('f4,f4').dtype.type, np.record)
assert_equal(r.view(('i4',2)).dtype.type, np.int32)
assert_equal(r.view('V8').dtype.type, np.void)
assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
#check that we can undo the view
arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
for arr in arrs:
rec = np.rec.array(arr)
# recommended way to view as an ndarray:
arr2 = rec.view(rec.dtype.fields or rec.dtype, np.ndarray)
assert_equal(arr2.dtype.type, arr.dtype.type)
assert_equal(type(arr2), type(arr))
def test_recarray_repr(self):
# make sure non-structured dtypes also show up as rec.array
a = np.array(np.ones(4, dtype='f8'))
assert_(repr(np.rec.array(a)).startswith('rec.array'))
# check that the 'np.record' part of the dtype isn't shown
a = np.rec.array(np.ones(3, dtype='i4,i4'))
assert_equal(repr(a).find('numpy.record'), -1)
a = np.rec.array(np.ones(3, dtype='i4'))
assert_(repr(a).find('dtype=int32') != -1)
def <API key>(self):
ra = np.rec.array([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
pa = np.rec.fromrecords([
(1, 'abc', 3.7000002861022949, 0),
(2, 'xy', 6.6999998092651367, 1),
(0, ' ', 0.40000000596046448, 0)],
names='c1, c2, c3, c4')
assert_(ra.dtype == pa.dtype)
assert_(ra.shape == pa.shape)
for k in range(len(ra)):
assert_(ra[k].item() == pa[k].item())
def <API key>(self):
ra = np.rec.array([(1, 'abc', 2.3), (2, 'xyz', 4.2),
(3, 'wrs', 1.3)],
names='field, shape, mean')
ra.mean = [1.1, 2.2, 3.3]
<API key>(ra['mean'], [1.1, 2.2, 3.3])
assert_(type(ra.mean) is type(ra.var))
ra.shape = (1, 3)
assert_(ra.shape == (1, 3))
ra.shape = ['A', 'B', 'C']
assert_array_equal(ra['shape'], [['A', 'B', 'C']])
ra.field = 5
assert_array_equal(ra['field'], [[5, 5, 5]])
assert_(isinstance(ra.field, collections.Callable))
def <API key>(self):
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')],
dtype=[('a', int), ('b', np.object)])
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
ndtype = np.dtype([('a', int), ('b', np.object)])
a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], dtype=ndtype)
assert_equal(a.a, [1, 2])
assert_equal(a[0].a, 1)
assert_equal(a.b, ['a', 'bbb'])
assert_equal(a[-1].b, 'bbb')
def <API key>(self):
# Issue #3993
a = np.array([('abc ', 1), ('abc', 2)],
dtype=[('foo', 'S4'), ('bar', int)])
a = a.view(np.recarray)
assert_equal(a.foo[0] == a.foo[1], False)
def <API key>(self):
qux_fields = {'C': (np.dtype('S5'), 0), 'D': (np.dtype('S5'), 6)}
a = np.rec.array([('abc ', (1,1), 1, ('abcde', 'fgehi')),
('abc', (2,3), 1, ('abcde', 'jklmn'))],
dtype=[('foo', 'S4'),
('bar', [('A', int), ('B', int)]),
('baz', int), ('qux', qux_fields)])
assert_equal(type(a.foo), np.ndarray)
assert_equal(type(a['foo']), np.ndarray)
assert_equal(type(a.bar), np.recarray)
assert_equal(type(a['bar']), np.recarray)
assert_equal(a.bar.dtype.type, np.record)
assert_equal(type(a['qux']), np.recarray)
assert_equal(a.qux.dtype.type, np.record)
assert_equal(dict(a.qux.dtype.fields), qux_fields)
assert_equal(type(a.baz), np.ndarray)
assert_equal(type(a['baz']), np.ndarray)
assert_equal(type(a[0].bar), np.record)
assert_equal(type(a[0]['bar']), np.record)
assert_equal(a[0].bar.A, 1)
assert_equal(a[0].bar['A'], 1)
assert_equal(a[0]['bar'].A, 1)
assert_equal(a[0]['bar']['A'], 1)
assert_equal(a[0].qux.D, b'fgehi')
assert_equal(a[0].qux['D'], b'fgehi')
assert_equal(a[0]['qux'].D, b'fgehi')
assert_equal(a[0]['qux']['D'], b'fgehi')
def <API key>(self):
# Test for #6430, based on the test case from #1901
cols = [['test'] * 3, [''] * 3]
rec = np.rec.fromarrays(cols)
assert_equal(rec['f0'], ['test', 'test', 'test'])
assert_equal(rec['f1'], ['', '', ''])
dt = np.dtype([('f0', '|S4'), ('f1', '|S')])
rec = np.rec.fromarrays(cols, dtype=dt)
assert_equal(rec.itemsize, 4)
assert_equal(rec['f0'], [b'test', b'test', b'test'])
assert_equal(rec['f1'], [b'', b'', b''])
class TestRecord(TestCase):
def setUp(self):
self.data = np.rec.fromrecords([(1, 2, 3), (4, 5, 6)],
dtype=[("col1", "<i4"),
("col2", "<i4"),
("col3", "<i4")])
def test_assignment1(self):
a = self.data
assert_equal(a.col1[0], 1)
a[0].col1 = 0
assert_equal(a.col1[0], 0)
def test_assignment2(self):
a = self.data
assert_equal(a.col1[0], 1)
a.col1[0] = 0
assert_equal(a.col1[0], 0)
def <API key>(self):
a = self.data
def <API key>(x):
x[0].col5 = 1
self.assertRaises(AttributeError, <API key>, a)
def <API key>(self):
# gh-8171
r = np.rec.array([(0,), (1,)], dtype=[('f', 'i4')])
r.flags.writeable = False
with assert_raises(ValueError):
r.f = [2, 3]
with assert_raises(ValueError):
r.setfield([2,3], *r.dtype.fields['f'])
def <API key>(self):
"""Ticket #1431."""
# this test will be invalid in 1.13
# suppress deprecation warning in 1.12 (remove in 1.13)
with assert_warns(FutureWarning):
x = self.data[['col1', 'col2']]
y = self.data[['col2', 'col1']]
assert_equal(x[0][0], y[0][1])
def test_pickle_1(self):
# Issue #1529
a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_2(self):
a = self.data
assert_equal(a, pickle.loads(pickle.dumps(a)))
assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
def test_pickle_3(self):
# Issue #7140
a = self.data
pa = pickle.loads(pickle.dumps(a[0]))
assert_(pa.flags.c_contiguous)
assert_(pa.flags.f_contiguous)
assert_(pa.flags.writeable)
assert_(pa.flags.aligned)
def test_objview_record(self):
dt = np.dtype([('foo', 'i8'), ('bar', 'O')])
r = np.zeros((1,3), dtype=dt).view(np.recarray)
r.foo = np.array([1, 2, 3]) # TypeError?
ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)])
with assert_warns(FutureWarning):
ra[['x','y']] # TypeError?
def <API key>(self):
rec = np.recarray(1, dtype=[('x', float, 5)])
rec[0].x = 1
assert_equal(rec[0].x, np.ones(5))
def test_missing_field(self):
arr = np.zeros((3,), dtype=[('x', int), ('y', int)])
assert_raises(ValueError, lambda: arr[['nofield']])
def test_find_duplicate():
l1 = [1, 2, 3, 4, 5, 6]
assert_(np.rec.find_duplicate(l1) == [])
l2 = [1, 2, 1, 4, 5, 6]
assert_(np.rec.find_duplicate(l2) == [1])
l3 = [1, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [1, 2])
l3 = [2, 2, 1, 4, 1, 6, 2, 3]
assert_(np.rec.find_duplicate(l3) == [2, 1])
if __name__ == "__main__":
run_module_suite()
|
// Use of this source code is governed by a BSD-style
package present // import "golang.org/x/tools/present"
|
## How does Bootstrap's test suite work?
Bootstrap uses [QUnit](https://qunitjs.com/), a powerful, easy-to-use JavaScript unit test framework. Each plugin has a file dedicated to its tests in `unit/<plugin-name>.js`.
* `unit/` contains the unit test files for each Bootstrap plugin.
* `vendor/` contains third-party testing-related code (QUnit and jQuery).
* `visual/` contains "visual" tests which are run interactively in real browsers and require manual verification by humans.
To run the unit test suite via [Karma](http://karma-runner.github.io/), run `npm run js-test`.
To run the unit test suite via a real web browser, open `index.html` in the browser.
## How do I add a new unit test?
1. Locate and open the file dedicated to the plugin which you need to add tests to (`unit/<plugin-name>.js`).
2. Review the [QUnit API Documentation](https://api.qunitjs.com/) and use the existing tests as references for how to structure your new tests.
3. Write the necessary unit test(s) for the new or revised functionality.
4. Run `npm run js-test` to see the results of your newly-added test(s).
**Note:** Your new unit tests should fail before your changes are applied to the plugin, and should pass after your changes are applied to the plugin.
## What should a unit test look like?
* Each test should have a unique name clearly stating what unit is being tested.
* Each test should test only one unit per test, although one test can include several assertions. Create multiple tests for multiple units of functionality.
* Each test should begin with [`assert.expect`](https://api.qunitjs.com/assert/expect/) to ensure that the expected assertions are run.
* Each test should follow the project's [JavaScript Code Guidelines](https://github.com/twbs/bootstrap/blob/master/CONTRIBUTING.md
Example tests
javascript
// Synchronous test
QUnit.test('should describe the unit being tested', function (assert) {
assert.expect(1)
var templateHTML = '<div class="alert alert-danger fade show">'
+ '<a class="close" href="
+ '<p><strong>Template necessary for the test.</p>'
+ '</div>'
var $alert = $(templateHTML).appendTo('#qunit-fixture').bootstrapAlert()
$alert.find('.close').trigger('click')
// Make assertion
assert.strictEqual($alert.hasClass('show'), false, 'remove .show class on .close click')
})
// Asynchronous test
QUnit.test('should describe the unit being tested', function (assert) {
assert.expect(1)
var done = assert.async()
$('<div title="tooltip title"></div>')
.appendTo('#qunit-fixture')
.on('shown.bs.tooltip', function () {
assert.ok(true, '"shown" event was fired after calling "show"')
done()
})
.bootstrapTooltip('show')
})
|
import * as RSVP from 'rsvp';
import { backburner, _rsvpErrorQueue } from '@ember/runloop';
import { getDispatchOverride } from '@ember/-internals/error-handling';
import { assert } from '@ember/debug';
RSVP.configure('async', (callback, promise) => {
backburner.schedule('actions', null, callback, promise);
});
RSVP.configure('after', cb => {
backburner.schedule(_rsvpErrorQueue, null, cb);
});
RSVP.on('error', onerrorDefault);
export function onerrorDefault(reason) {
let error = errorFor(reason);
if (error) {
let overrideDispatch = getDispatchOverride();
if (overrideDispatch) {
overrideDispatch(error);
} else {
throw error;
}
}
}
function errorFor(reason) {
if (!reason) return;
if (reason.errorThrown) {
return unwrapErrorThrown(reason);
}
if (reason.name === '<API key>') {
assert(`The URL '${reason.message}' did not match any routes in your application`, false);
return;
}
if (reason.name === 'TransitionAborted') {
return;
}
return reason;
}
function unwrapErrorThrown(reason) {
let error = reason.errorThrown;
if (typeof error === 'string') {
error = new Error(error);
}
Object.defineProperty(error, '<API key>', {
value: reason,
enumerable: false,
});
return error;
}
export default RSVP;
|
#include <stdio.h>
#include "Halide.h"
using namespace Halide;
// Override Halide's malloc and free
size_t custom_malloc_size = 0;
void *my_malloc(void *user_context, size_t x) {
custom_malloc_size = x;
void *orig = malloc(x+32);
void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
((void **)ptr)[-1] = orig;
return ptr;
}
void my_free(void *user_context, void *ptr) {
free(((void**)ptr)[-1]);
}
int main(int argc, char **argv) {
Var x, y;
{
Func f, g;
f(x, y) = x;
g(x, y) = f(x-1, y) + f(x, y-1);
f.store_root().compute_at(g, x);
g.<API key>(my_malloc, my_free);
Image<int> im = g.realize(1000, 1000);
// Should fold by a factor of two, but sliding window analysis makes it round up to 4.
if (custom_malloc_size == 0 || custom_malloc_size > 1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, 2*y) + g(2*x+1, 2*y+1);
// Each instance of f uses a non-overlapping 2x2 box of
// g. Should be able to fold storage of g down to a stack
// allocation.
g.compute_at(f, x).store_root();
f.<API key>(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * (2*y) + (2*x+1) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, 2*y) + g(x+3, 2*y+1);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in y, and is a stencil over x. Should be able to fold
// both x and y.
g.compute_at(f, x).store_root();
f.<API key>(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size != 0) {
printf("There should not have been a heap allocation\n");
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x * (2*y) + (x+3) * (2*y+1);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(2*x, y) + g(2*x+1, y+3);
// Each instance of f uses a non-overlapping 2-scanline slice
// of g in x, and is a stencil over y. We can't fold in x due
// to the stencil in y. We need to keep around entire
// scanlines.
g.compute_at(f, x).store_root();
f.<API key>(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 2*1002*4*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1002*4*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = (2*x) * y + (2*x+1) * (y+3);
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
{
custom_malloc_size = 0;
Func f, g;
g(x, y) = x * y;
f(x, y) = g(x, y);
Var yo, yi;
f.bound(y, 0, (f.output_buffer().height()/8)*8).split(y, yo, yi, 8);
g.compute_at(f, yo).store_root();
// The split logic shouldn't interfere with the ability to
// fold f down to an 8-scanline allocation, but it's only
// correct to fold if we know the output height is a multiple
// of the split factor.
f.<API key>(my_malloc, my_free);
Image<int> im = f.realize(1000, 1000);
if (custom_malloc_size == 0 || custom_malloc_size > 1000*8*sizeof(int)) {
printf("Scratch space allocated was %d instead of %d\n", (int)custom_malloc_size, (int)(1000*8*sizeof(int)));
return -1;
}
for (int y = 0; y < im.height(); y++) {
for (int x = 0; x < im.width(); x++) {
int correct = x*y;
if (im(x, y) != correct) {
printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct);
return -1;
}
}
}
}
printf("Success!\n");
return 0;
}
|
// <summary>Tests for ProjectItemInstance public members</summary>
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using <API key> = Microsoft.Build.Exceptions.<API key>;
namespace Microsoft.Build.UnitTests.OM.Instance
{
<summary>
Tests for ProjectItemInstance public members
</summary>
[TestClass]
public class <API key>
{
<summary>
The number of built-in metadata for items.
</summary>
public const int <API key> = 15;
<summary>
Basic ProjectItemInstance without metadata
</summary>
[TestMethod]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
}
<summary>
Basic ProjectItemInstance with metadata
</summary>
[TestMethod]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m1", "v0");
item.SetMetadata("m1", "v1");
item.SetMetadata("m2", "v2");
Assert.AreEqual("m1", item.GetMetadata("m1").Name);
Assert.AreEqual("m2", item.GetMetadata("m2").Name);
Assert.AreEqual("v1", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
}
<summary>
Get metadata not present
</summary>
[TestMethod]
public void GetMissingMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.AreEqual(null, item.GetMetadata("X"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("X"));
}
<summary>
Set include
</summary>
[TestMethod]
public void SetInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = "i1b";
Assert.AreEqual("i1b", item.EvaluatedInclude);
}
<summary>
Set include to empty string
</summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = String.Empty;
}
<summary>
Set include to invalid null value
</summary>
[TestMethod]
[ExpectedException(typeof(<API key>))]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = null;
}
<summary>
Create an item with a metadatum that has a null value
</summary>
[TestMethod]
public void <API key>()
{
Project project = new Project();
ProjectInstance projectInstance = project.<API key>();
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("m", null);
ProjectItemInstance item = projectInstance.AddItem("i", "i1", metadata);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
<summary>
Set metadata value
</summary>
[TestMethod]
public void SetMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
Assert.AreEqual("m1", item.GetMetadataValue("m"));
}
<summary>
Set metadata value to empty string
</summary>
[TestMethod]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", String.Empty);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
<summary>
Set metadata value to null value -- this is allowed, but
internally converted to the empty string.
</summary>
[TestMethod]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", null);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
<summary>
Set metadata with invalid empty name
</summary>
[TestMethod]
[ExpectedException(typeof(<API key>))]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(null, "m1");
}
<summary>
Set metadata with invalid empty name
</summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(String.Empty, "m1");
}
<summary>
Cast to ITaskItem
</summary>
[TestMethod]
public void CastToITaskItem()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(item.EvaluatedInclude, taskItem.ItemSpec);
Assert.AreEqual(1 + <API key>, taskItem.MetadataCount);
Assert.AreEqual(1 + <API key>, taskItem.MetadataNames.Count);
Assert.AreEqual("m1", taskItem.GetMetadata("m"));
taskItem.SetMetadata("m", "m2");
Assert.AreEqual("m2", item.GetMetadataValue("m"));
}
<summary>
Creates a ProjectItemInstance and casts it to ITaskItem2; makes sure that all escaped information is
maintained correctly. Also creates a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance
and verifies that none of the information is lost.
</summary>
[TestMethod]
public void <API key>()
{
Project project = new Project();
ProjectInstance projectInstance = project.<API key>();
ProjectItemInstance item = projectInstance.AddItem("EscapedItem", "esca%20ped%3bitem");
item.SetMetadata("m", "m1");
item.SetMetadata("m;", "m%3b1");
ITaskItem2 taskItem = (ITaskItem2)item;
Assert.AreEqual(taskItem.<API key>, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
Assert.AreEqual(taskItem.GetMetadata("m;"), "m;1");
Assert.AreEqual(taskItem.<API key>("m;"), "m%3b1");
Assert.AreEqual(taskItem.<API key>("m"), "m1");
Assert.AreEqual(taskItem.<API key>, "esca%20ped%3bitem");
Assert.AreEqual(taskItem.ItemSpec, "esca ped;item");
ITaskItem2 taskItem2 = new Microsoft.Build.Utilities.TaskItem(taskItem);
taskItem2.<API key>("m;", "m;2");
Assert.AreEqual(taskItem2.<API key>("m;"), "m%3b2");
Assert.AreEqual(taskItem2.GetMetadata("m;"), "m;2");
IDictionary<string, string> taskItem2Metadata = (IDictionary<string, string>)taskItem2.CloneCustomMetadata();
Assert.AreEqual(3, taskItem2Metadata.Count);
foreach (KeyValuePair<string, string> pair in taskItem2Metadata)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m;2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca ped;item", pair.Value);
}
}
IDictionary<string, string> <API key> = (IDictionary<string, string>)taskItem2.<API key>();
Assert.AreEqual(3, <API key>.Count);
foreach (KeyValuePair<string, string> pair in <API key>)
{
if (pair.Key.Equals("m"))
{
Assert.AreEqual("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.AreEqual("m%3b2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.AreEqual("esca%20ped%3bitem", pair.Value);
}
}
}
<summary>
Cast to ITaskItem
</summary>
[TestMethod]
public void <API key>()
{
ProjectItemInstance item = GetItemInstance();
ITaskItem taskItem = (ITaskItem)item;
Assert.AreEqual(0 + <API key>, taskItem.MetadataCount);
Assert.AreEqual(0 + <API key>, taskItem.MetadataNames.Count);
Assert.AreEqual(String.Empty, taskItem.GetMetadata("m"));
}
/*
* We must repeat all the evaluation-related tests here,
* to exercise the path that evaluates directly to instance objects.
* Although the Evaluator class is shared, its interactions with the two
* different item classes could be different, and shouldn't be.
*/
<summary>
No metadata, simple case
</summary>
[TestMethod]
public void NoMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i", item.ItemType);
Assert.AreEqual("i1", item.EvaluatedInclude);
Assert.AreEqual(false, item.Metadata.GetEnumerator().MoveNext());
Assert.AreEqual(0 + <API key>, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(0 + <API key>, item.MetadataCount);
}
<summary>
Read off metadata
</summary>
[TestMethod]
public void ReadMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("m1", itemMetadata[0].Name);
Assert.AreEqual("m2", itemMetadata[1].Name);
Assert.AreEqual("v1", itemMetadata[0].EvaluatedValue);
Assert.AreEqual("v2", itemMetadata[1].EvaluatedValue);
Assert.AreEqual(itemMetadata[0], item.GetMetadata("m1"));
Assert.AreEqual(itemMetadata[1], item.GetMetadata("m2"));
}
<summary>
Create a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance where the ProjectItemInstance
has item definition metadata on it.
Verify the Utilities task item gets the expanded metadata from the ItemDefintionGroup.
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>;x86;</m0>
<m1>%(FileName).extension</m1>
<m2>;%(FileName).extension;</m2>
<m3>v1</m3>
<m4>%3bx86%3b</m4>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='foo.proj'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Microsoft.Build.Utilities.TaskItem taskItem = new Microsoft.Build.Utilities.TaskItem(item);
Assert.AreEqual(";x86;", taskItem.GetMetadata("m0"));
Assert.AreEqual("foo.extension", taskItem.GetMetadata("m1"));
Assert.AreEqual(";foo.extension;", taskItem.GetMetadata("m2"));
Assert.AreEqual("v1", taskItem.GetMetadata("m3"));
Assert.AreEqual(";x86;", taskItem.GetMetadata("m4"));
}
<summary>
Get metadata values inherited from item definitions
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>v0</m0>
<m1>v1</m1>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='i1'>
<m1>v1b</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("v0", item.GetMetadataValue("m0"));
Assert.AreEqual("v1b", item.GetMetadataValue("m1"));
Assert.AreEqual("v2", item.GetMetadataValue("m2"));
Assert.AreEqual(3, Helpers.MakeList(item.Metadata).Count);
Assert.AreEqual(3 + <API key>, Helpers.MakeList(item.MetadataNames).Count);
Assert.AreEqual(3 + <API key>, item.MetadataCount);
}
<summary>
Exclude against an include with item vectors in it
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, x, z, a, c, u, w
Assert.AreEqual(9, items.Count);
<API key>(items, new string[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" });
}
<summary>
Exclude with item vectors against an include with item vectors in it
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
<j Include='b;y;v' />
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, z, a, c, u
Assert.AreEqual(7, items.Count);
<API key>(items, new string[] { "a", "b", "c", "z", "a", "c", "u" });
}
<summary>
Metadata on items can refer to metadata above
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>%(m1);v2;%(m0)</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.AreEqual(2, itemMetadata.Count);
Assert.AreEqual("v1;v2;", item.GetMetadataValue("m2"));
}
<summary>
Built-in metadata should work, too.
NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now.
It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed.
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
<summary>
Qualified built in metadata should work
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(i.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("i1", item.GetMetadataValue("m"));
}
<summary>
Mis-qualified built in metadata should not work
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(j.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual(String.Empty, item.GetMetadataValue("m"));
}
<summary>
Metadata condition should work correctly with built-in metadata
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m Condition=""'%(Identity)'=='i1'"">m1</m>
<n Condition=""'%(Identity)'=='i2'"">n1</n>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.AreEqual("m1", item.GetMetadataValue("m"));
Assert.AreEqual(String.Empty, item.GetMetadataValue("n"));
}
<summary>
Metadata on item condition not allowed (currently)
</summary>
[TestMethod]
[ExpectedException(typeof(<API key>))]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1' Condition=""'%(Identity)'=='i1'/>
</ItemGroup>
</Project>
";
GetOneItem(content);
}
<summary>
Two items should each get their own values for built-in metadata
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1.cpp;c:\bar\i2.cpp'>
<m>%(Filename).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i1.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"i2.obj", items[1].GetMetadataValue("m"));
}
<summary>
Items from another list, but with different metadata
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'>
<m>m1</m>
</h>
<h Include='h1'/>
<i Include='@(h)'>
<m>%(m)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"m1", items[0].GetMetadataValue("m"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m"));
}
<summary>
Items from another list, but with different metadata
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0.x'/>
<h Include='h1.y'/>
<i Include='@(h)'>
<m>%(extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@".x", items[0].GetMetadataValue("m"));
Assert.AreEqual(@".y", items[1].GetMetadataValue("m"));
}
<summary>
Two items coming from a transform
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include=""@(h->'%(Identity).baz')"">
<m>%(Filename)%(Extension).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"h0.baz.obj", items[0].GetMetadataValue("m"));
Assert.AreEqual(@"h1.baz.obj", items[1].GetMetadataValue("m"));
}
<summary>
Transform in the metadata value; no bare metadata involved
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0'/>
<i Include='i1;i2'>
<m>@(i);@(h->'%(Filename)')</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0;h0;h1", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0;h0;h1", items[2].GetMetadataValue("m"));
}
<summary>
Transform in the metadata value; bare metadata involved
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0.x'/>
<i Include='i1.y;i2'>
<m>@(i);@(h->'%(Filename)');%(Extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m"));
Assert.AreEqual(@"i0.x;h0;h1;", items[2].GetMetadataValue("m"));
}
<summary>
Metadata on items can refer to item lists
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1>@(h);@(i)</m1>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("h0;i0", items[1].GetMetadataValue("m1"));
}
<summary>
Metadata on items' conditions can refer to item lists
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1>
<m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("v1", items[1].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[1].GetMetadataValue("m2"));
}
<summary>
Metadata on items' conditions can refer to other metadata
</summary>
[TestMethod]
public void <API key>()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m0>0</m0>
<m1 Condition=""'%(m0)'=='0'"">1</m1>
<m2 Condition=""'%(m0)'=='3'"">2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.AreEqual("0", items[0].GetMetadataValue("m0"));
Assert.AreEqual("1", items[0].GetMetadataValue("m1"));
Assert.AreEqual(String.Empty, items[0].GetMetadataValue("m2"));
}
<summary>
Gets the first item of type 'i'
</summary>
private static ProjectItemInstance GetOneItem(string content)
{
return GetItems(content)[0];
}
<summary>
Get all items of type 'i'
</summary>
private static IList<ProjectItemInstance> GetItems(string content)
{
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectInstance project = new ProjectInstance(xml);
return Helpers.MakeList(project.GetItems("i"));
}
<summary>
Asserts that the list of items has the specified includes.
</summary>
private static void <API key>(IList<ProjectItemInstance> items, string[] includes)
{
for (int i = 0; i < includes.Length; i++)
{
Assert.AreEqual(includes[i], items[i].EvaluatedInclude);
}
}
<summary>
Get a single item instance
</summary>
private static ProjectItemInstance GetItemInstance()
{
Project project = new Project();
ProjectInstance projectInstance = project.<API key>();
ProjectItemInstance item = projectInstance.AddItem("i", "i1");
return item;
}
}
}
|
/**
@module ember
@submodule ember-runtime
*/
import Ember from 'ember-metal/core';
import { Mixin } from 'ember-metal/mixin';
import { get } from 'ember-metal/property_get';
import { deprecateProperty } from 'ember-metal/deprecate_property';
/**
`Ember.ActionHandler` is available on some familiar classes including
`Ember.Route`, `Ember.View`, `Ember.Component`, and `Ember.Controller`.
(Internally the mixin is used by `Ember.CoreView`, `Ember.ControllerMixin`,
and `Ember.Route` and available to the above classes through
inheritance.)
@class ActionHandler
@namespace Ember
@private
*/
var ActionHandler = Mixin.create({
mergedProperties: ['actions'],
/**
The collection of functions, keyed by name, available on this
`ActionHandler` as action targets.
These functions will be invoked when a matching `{{action}}` is triggered
from within a template and the application's current route is this route.
Actions can also be invoked from other parts of your application
via `ActionHandler#send`.
The `actions` hash will inherit action handlers from
the `actions` hash defined on extended parent classes
or mixins rather than just replace the entire hash, e.g.:
js
App.CanDisplayBanner = Ember.Mixin.create({
actions: {
displayBanner: function(msg) {
// ...
}
}
});
App.WelcomeRoute = Ember.Route.extend(App.CanDisplayBanner, {
actions: {
playMusic: function() {
// ...
}
}
});
// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');
Within a Controller, Route, View or Component's action handler,
the value of the `this` context is the Controller, Route, View or
Component object:
js
App.SongRoute = Ember.Route.extend({
actions: {
myAction: function() {
this.controllerFor("song");
this.transitionTo("other.route");
}
}
});
It is also possible to call `this._super.apply(this, arguments)` from within an
action handler if it overrides a handler defined on a parent
class or mixin:
Take for example the following routes:
js
App.DebugRoute = Ember.Mixin.create({
actions: {
<API key>: function() {
console.debug("trololo");
}
}
});
App.AnnoyingDebugRoute = Ember.Route.extend(App.DebugRoute, {
actions: {
<API key>: function() {
// also call the <API key> of mixed in App.DebugRoute
this._super.apply(this, arguments);
// show additional annoyance
window.alert(...);
}
}
});
## Bubbling
By default, an action will stop bubbling once a handler defined
on the `actions` hash handles it. To continue bubbling the action,
you must return `true` from the handler:
js
App.Router.map(function() {
this.route("album", function() {
this.route("song");
});
});
App.AlbumRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
}
}
});
App.AlbumSongRoute = Ember.Route.extend({
actions: {
startPlaying: function() {
// ...
if (<API key>) {
return true;
}
}
}
});
@property actions
@type Object
@default null
@public
*/
/**
Triggers a named action on the `ActionHandler`. Any parameters
supplied after the `actionName` string will be passed as arguments
to the action target function.
If the `ActionHandler` has its `target` property set, actions may
bubble to the `target`. Bubbling happens when an `actionName` can
not be found in the `ActionHandler`'s `actions` hash or if the
action target function returns `true`.
Example
js
App.WelcomeRoute = Ember.Route.extend({
actions: {
playTheme: function() {
this.send('playMusic', 'theme.mp3');
},
playMusic: function(track) {
// ...
}
}
});
@method send
@param {String} actionName The action to trigger
@param {*} context a context to send with the action
@public
*/
send(actionName, ...args) {
var target;
if (this.actions && this.actions[actionName]) {
var shouldBubble = this.actions[actionName].apply(this, args) === true;
if (!shouldBubble) { return; }
}
if (target = get(this, 'target')) {
Ember.assert('The `target` for ' + this + ' (' + target +
') does not have a `send` method', typeof target.send === 'function');
target.send(...arguments);
}
}
});
export default ActionHandler;
export function <API key>(factory) {
deprecateProperty(factory.prototype, '_actions', 'actions', {
id: 'ember-runtime.<API key>', until: '3.0.0'
});
}
|
using System;
using System.IO;
using System.Diagnostics;
using System.Resources;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Build.Shared;
namespace Microsoft.Build.Tasks
{
<summary>
Returns paths to the frameworks SDK.
</summary>
public class GetFrameworkSdkPath : TaskExtension
{
#region Properties
private static string s_path;
private static string s_version20Path;
private static string s_version35Path;
private static string s_version40Path;
private static string s_version45Path;
private static string s_version451Path;
private static string s_version46Path;
<summary>
The path to the latest .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string Path
{
get
{
if (s_path == null)
{
s_path = ToolLocationHelper.<API key>(<API key>.VersionLatest, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.VersionLatest, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.VersionLatest, VisualStudioVersion.VersionLatest)
);
s_path = String.Empty;
}
else
{
s_path = FileUtilities.EnsureTrailingSlash(s_path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_path);
}
}
return s_path;
}
set
{
// Does nothing; for backwards compatibility only
}
}
<summary>
The path to the v2.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version20Path == null)
{
s_version20Path = ToolLocationHelper.<API key>(<API key>.Version20);
if (String.IsNullOrEmpty(s_version20Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version20),
ToolLocationHelper.<API key>(<API key>.Version20)
);
s_version20Path = String.Empty;
}
else
{
s_version20Path = FileUtilities.EnsureTrailingSlash(s_version20Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version20Path);
}
}
return s_version20Path;
}
}
<summary>
The path to the v3.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version35Path == null)
{
s_version35Path = ToolLocationHelper.<API key>(<API key>.Version35, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version35Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version35, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.Version35, VisualStudioVersion.VersionLatest)
);
s_version35Path = String.Empty;
}
else
{
s_version35Path = FileUtilities.EnsureTrailingSlash(s_version35Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version35Path);
}
}
return s_version35Path;
}
}
<summary>
The path to the v4.0 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version40Path == null)
{
s_version40Path = ToolLocationHelper.<API key>(<API key>.Version40, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version40Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version40, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.Version40, VisualStudioVersion.VersionLatest)
);
s_version40Path = String.Empty;
}
else
{
s_version40Path = FileUtilities.EnsureTrailingSlash(s_version40Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version40Path);
}
}
return s_version40Path;
}
}
<summary>
The path to the v4.5 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version45Path == null)
{
s_version45Path = ToolLocationHelper.<API key>(<API key>.Version45, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version45Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version45, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.Version45, VisualStudioVersion.VersionLatest)
);
s_version45Path = String.Empty;
}
else
{
s_version45Path = FileUtilities.EnsureTrailingSlash(s_version45Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version45Path);
}
}
return s_version45Path;
}
}
<summary>
The path to the v4.5.1 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version451Path == null)
{
s_version451Path = ToolLocationHelper.<API key>(<API key>.Version451, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version451Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version451, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.Version451, VisualStudioVersion.VersionLatest)
);
s_version451Path = String.Empty;
}
else
{
s_version451Path = FileUtilities.EnsureTrailingSlash(s_version451Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version451Path);
}
}
return s_version451Path;
}
}
<summary>
The path to the v4.6 .NET SDK if it could be found. It will be String.Empty if the SDK was not found.
</summary>
[Output]
public string <API key>
{
get
{
if (s_version46Path == null)
{
s_version46Path = ToolLocationHelper.<API key>(<API key>.Version46, VisualStudioVersion.VersionLatest);
if (String.IsNullOrEmpty(s_version46Path))
{
Log.<API key>(
MessageImportance.High,
"GetFrameworkSdkPath.CouldNotFindSDK",
ToolLocationHelper.<API key>(<API key>.Version46, VisualStudioVersion.VersionLatest),
ToolLocationHelper.<API key>(<API key>.Version46, VisualStudioVersion.VersionLatest)
);
s_version46Path = String.Empty;
}
else
{
s_version46Path = FileUtilities.EnsureTrailingSlash(s_version46Path);
Log.<API key>(MessageImportance.Low, "GetFrameworkSdkPath.FoundSDK", s_version46Path);
}
}
return s_version46Path;
}
}
#endregion
#region ITask Members
<summary>
Get the SDK.
</summary>
<returns>true</returns>
public override bool Execute()
{
//Does Nothing: getters do all the work
return true;
}
#endregion
}
}
|
"use strict";
var CHARS = '<API key>'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i==23) {
uuid[i] = '-';
}
else if (i==14) {
uuid[i] = '4';
}
else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
r = rnd & 0xf;
rnd = rnd >> 4;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
return uuid.join('');
};
exports.in_array = function (item, array) {
return (array.indexOf(item) != -1);
};
exports.sort_keys = function (obj) {
return Object.keys(obj).sort();
};
exports.uniq = function (arr) {
var out = [];
var o = 0;
for (var i=0,l=arr.length; i < l; i++) {
if (out.length === 0) {
out.push(arr[i]);
}
else if (out[o] != arr[i]) {
out.push(arr[i]);
o++;
}
}
return out;
}
exports.ISODate = function (d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function _pad (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) +
' ' + d.toString().match(/\sGMT([+-]\d+)/)[1];
}
exports.decode_qp = function (line) {
line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n");
if (! /=/.test(line)) {
// this may be a pointless optimisation...
return new Buffer(line);
}
line = line.replace(/=\n/mg, '');
var buf = new Buffer(line.length);
var pos = 0;
for (var i=0,l=line.length; i < l; i++) {
if (line[i] === '=' &&
/=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) {
i++;
buf[pos] = parseInt(line[i] + line[i+1], 16);
i++;
}
else {
buf[pos] = line.charCodeAt(i);
}
pos++;
}
return buf.slice(0, pos);
}
function _char_to_qp (ch) {
return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2);
}
// Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code.
exports.encode_qp = function (str) {
str = str.replace(/([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) {
return _char_to_qp(p1);
}).replace(/([ \t]+)$/gm, function (orig, p1) {
return p1.split('').map(_char_to_qp).join('');
});
// Now shorten lines to 76 chars, but don't break =XX encodes.
// Method: iterate over to char 73.
// If char 74, 75 or 76 is = we need to break before the =.
// Otherwise break at 76.
var cur_length = 0;
var out = '';
for (var i=0; i<str.length; i++) {
if (str[i] === '\n') {
out += '\n';
cur_length = 0;
continue;
}
cur_length++;
if (cur_length <= 73) {
out += str[i];
}
else if (cur_length > 73 && cur_length < 76) {
if (str[i] === '=') {
out += '=\n=';
cur_length = 1;
}
else {
out += str[i];
}
}
else {
// Otherwise got to char 76
// Don't insert '=\n' if end of string or next char is already \n:
if ((i === (str.length - 1)) || (str[i+1] === '\n')) {
out += str[i];
}
else {
out += '=\n' + str[i];
cur_length = 1;
}
}
}
return out;
}
var versions = process.version.split('.'),
version = Number(versions[0].substring(1)),
subversion = Number(versions[1]);
exports.existsSync = require((version > 0 || subversion >= 8) ? 'fs' : 'path').existsSync;
exports.indexOfLF = function (buf, maxlength) {
for (var i=0; i<buf.length; i++) {
if (maxlength && (i === maxlength)) break;
if (buf[i] === 0x0a) return i;
}
return -1;
}
|
require 'spec_helper'
require 'puppet/transaction'
require 'puppet_spec/compiler'
require 'matchers/<API key>'
require 'matchers/include_in_order'
require 'matchers/resource'
describe Puppet::Transaction::<API key> do
include PuppetSpec::Compiler
include PuppetSpec::Files
include <API key>
include Matchers::Resource
let(:prioritizer) { Puppet::Graph::<API key>.new }
def find_vertex(graph, type, title)
graph.vertices.find {|v| v.type == type and v.title == title}
end
Puppet::Type.newtype(:generator) do
include PuppetSpec::Compiler
newparam(:name) do
isnamevar
end
newparam(:kind) do
defaultto :eval_generate
newvalues(:eval_generate, :generate)
end
newparam(:code)
def respond_to?(method_name)
method_name == self[:kind] || super
end
def eval_generate
eval_code
end
def generate
eval_code
end
def eval_code
if self[:code]
compile_to_ral(self[:code]).resources.select { |r| r.ref =~ /Notify/ }
else
[]
end
end
end
context "when applying eval_generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
<API key>(catalog, <API key>(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should add a sentinel whit for the resource" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
find_vertex(graph, :whit, "completed_thing").must be_a(Puppet::Type.type(:whit))
end
it "should replace dependencies on the resource with dependencies on the sentinel" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
notify { last: require => Generator['thing'] }
MANIFEST
expect(graph).to <API key>(
'Whit[completed_thing]', 'Notify[last]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to <API key>(
'Generator[thing]', 'Notify[hello]')
expect(graph).to <API key>(
'Generator[thing]', 'Notify[goodbye]')
end
it "should add an edge from each generated resource to the sentinel" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to <API key>(
'Notify[hello]', 'Whit[completed_thing]')
expect(graph).to <API key>(
'Notify[goodbye]', 'Whit[completed_thing]')
end
it "should add an edge from the resource to the sentinel" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
expect(graph).to <API key>(
'Generator[thing]', 'Whit[completed_thing]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
code => 'notify { hello: }'
}
}
include container
MANIFEST
<API key>(catalog, <API key>(catalog), 'Generator[thing]')
expect(catalog).to <API key>('Generator[thing]', 'Notify[hello]')
end
it "should return false if an error occurred when generating resources" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'fail("not a good generation")'
}
MANIFEST
generator = Puppet::Transaction::<API key>.new(catalog, <API key>(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
end
it "should return true if resources were generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
code => 'notify { hello: }'
}
MANIFEST
generator = Puppet::Transaction::<API key>.new(catalog, <API key>(catalog), prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(true)
end
it "should not add a sentinel if no resources are generated" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing: }
MANIFEST
relationship_graph = <API key>(catalog)
generator = Puppet::Transaction::<API key>.new(catalog, relationship_graph, prioritizer)
expect(generator.eval_generate(catalog.resource('Generator[thing]'))).
to eq(false)
expect(find_vertex(relationship_graph, :whit, "completed_thing")).to be_nil
end
it "orders generated resources with the generator" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
def <API key>(manifest, <API key>)
catalog = compile_to_ral(manifest)
relationship_graph = <API key>(catalog)
<API key>(catalog, relationship_graph, <API key>)
relationship_graph
end
def <API key>(catalog, relationship_graph, <API key>)
generator = Puppet::Transaction::<API key>.new(catalog, relationship_graph, prioritizer)
generator.eval_generate(catalog.resource(<API key>))
end
end
context "when applying generate" do
it "should add the generated resources to the catalog" do
catalog = compile_to_ral(<<-MANIFEST)
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
MANIFEST
<API key>(catalog, <API key>(catalog), 'Generator[thing]')
expect(catalog).to have_resource('Notify[hello]')
end
it "should contain the generated resources in the same container as the generator" do
catalog = compile_to_ral(<<-MANIFEST)
class container {
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
}
include container
MANIFEST
<API key>(catalog, <API key>(catalog), 'Generator[thing]')
expect(catalog).to <API key>('Generator[thing]', 'Notify[hello]')
end
it "should add an edge from the nearest ancestor to the generated resource" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
MANIFEST
expect(graph).to <API key>(
'Generator[thing]', 'Notify[hello]')
expect(graph).to <API key>(
'Generator[thing]', 'Notify[goodbye]')
end
it "orders generated resources with the generator" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: }'
}
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[after]"))
end
it "duplicate generated resources are made dependent on the generator" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
notify { hello: }
generator { thing:
kind => generate,
code => 'notify { before: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[hello]", "Generator[thing]", "Notify[before]", "Notify[third]", "Notify[after]"))
end
it "preserves dependencies on duplicate generated resources" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { before: }',
require => 'Notify[before]'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]", "Generator[thing]", "Notify[hello]", "Notify[third]", "Notify[after]"))
end
it "orders the generator in manifest order with dependencies" do
graph = <API key>(<<-MANIFEST, 'Generator[thing]')
notify { before: }
generator { thing:
kind => generate,
code => 'notify { hello: } notify { goodbye: }'
}
notify { third: require => Generator['thing'] }
notify { after: }
MANIFEST
expect(<API key>(graph)).to(
include_in_order("Notify[before]",
"Generator[thing]",
"Notify[hello]",
"Notify[goodbye]",
"Notify[third]",
"Notify[after]"))
end
def <API key>(manifest, <API key>)
catalog = compile_to_ral(manifest)
relationship_graph = <API key>(catalog)
<API key>(catalog, relationship_graph, <API key>)
relationship_graph
end
def <API key>(catalog, relationship_graph, <API key>)
generator = Puppet::Transaction::<API key>.new(catalog, relationship_graph, prioritizer)
generator.<API key>(catalog.resource(<API key>))
end
end
def <API key>(catalog)
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
relationship_graph.populate_from(catalog)
relationship_graph
end
def <API key>(relationships)
order_seen = []
relationships.traverse { |resource| order_seen << resource.ref }
order_seen
end
RSpec::Matchers.define :<API key> do |*resource_refs|
match do |catalog|
@containers = resource_refs.collect do |resource_ref|
catalog.container_of(catalog.resource(resource_ref)).ref
end
@containers.all? { |resource_ref| resource_ref == @containers[0] }
end
def <API key>
"expected #{@expected.join(', ')} to all be contained in the same resource but the containment was #{@expected.zip(@containers).collect { |(res, container)| res + ' => ' + container }.join(', ')}"
end
end
end
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>0.9.6: type_vec3.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">0.9.6
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.8 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">E:</a></li><li class="navelem"><a class="el" href="<API key>.html">Source</a></li><li class="navelem"><a class="el" href="<API key>.html">G-Truc</a></li><li class="navelem"><a class="el" href="<API key>.html">glm</a></li><li class="navelem"><a class="el" href="<API key>.html">glm</a></li><li class="navelem"><a class="el" href="<API key>.html">detail</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">type_vec3.hpp</div> </div>
</div><!--header
<div class="contents">
<a href="a00134.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span> </div>
<div class="line"><a name="l00033"></a><span class="lineno"> 33</span> <span class="preprocessor">#pragma once</span></div>
<div class="line"><a name="l00034"></a><span class="lineno"> 34</span> </div>
<div class="line"><a name="l00035"></a><span class="lineno"> 35</span> <span class="comment">//#include "../fwd.hpp"</span></div>
<div class="line"><a name="l00036"></a><span class="lineno"> 36</span> <span class="preprocessor">#include "<a class="code" href="a00131.html">type_vec.hpp</a>"</span></div>
<div class="line"><a name="l00037"></a><span class="lineno"> 37</span> <span class="preprocessor">#ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00038"></a><span class="lineno"> 38</span> <span class="preprocessor"># if <API key></span></div>
<div class="line"><a name="l00039"></a><span class="lineno"> 39</span> <span class="preprocessor"># include "<a class="code" href="a00004.html">_swizzle.hpp</a>"</span></div>
<div class="line"><a name="l00040"></a><span class="lineno"> 40</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00041"></a><span class="lineno"> 41</span> <span class="preprocessor"># include "<a class="code" href="a00005.html">_swizzle_func.hpp</a>"</span></div>
<div class="line"><a name="l00042"></a><span class="lineno"> 42</span> <span class="preprocessor"># endif</span></div>
<div class="line"><a name="l00043"></a><span class="lineno"> 43</span> <span class="preprocessor">#endif //GLM_SWIZZLE</span></div>
<div class="line"><a name="l00044"></a><span class="lineno"> 44</span> <span class="preprocessor">#include <cstddef></span></div>
<div class="line"><a name="l00045"></a><span class="lineno"> 45</span> </div>
<div class="line"><a name="l00046"></a><span class="lineno"> 46</span> <span class="keyword">namespace </span><a class="code" href="a00145.html">glm</a></div>
<div class="line"><a name="l00047"></a><span class="lineno"> 47</span> {</div>
<div class="line"><a name="l00048"></a><span class="lineno"> 48</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P = defaultp></div>
<div class="line"><a name="l00049"></a><span class="lineno"> 49</span>  <span class="keyword">struct </span>tvec3</div>
<div class="line"><a name="l00050"></a><span class="lineno"> 50</span>  { </div>
<div class="line"><a name="l00052"></a><span class="lineno"> 52</span>  <span class="comment">// Implementation detail</span></div>
<div class="line"><a name="l00053"></a><span class="lineno"> 53</span> </div>
<div class="line"><a name="l00054"></a><span class="lineno"> 54</span>  <span class="keyword">typedef</span> tvec3<T, P> type;</div>
<div class="line"><a name="l00055"></a><span class="lineno"> 55</span>  <span class="keyword">typedef</span> tvec3<bool, P> bool_type;</div>
<div class="line"><a name="l00056"></a><span class="lineno"> 56</span>  <span class="keyword">typedef</span> T value_type;</div>
<div class="line"><a name="l00057"></a><span class="lineno"> 57</span> </div>
<div class="line"><a name="l00059"></a><span class="lineno"> 59</span>  <span class="comment">// Data</span></div>
<div class="line"><a name="l00060"></a><span class="lineno"> 60</span> </div>
<div class="line"><a name="l00061"></a><span class="lineno"> 61</span> <span class="preprocessor"># if <API key></span></div>
<div class="line"><a name="l00062"></a><span class="lineno"> 62</span>  <span class="keyword">union</span></div>
<div class="line"><a name="l00063"></a><span class="lineno"> 63</span>  {</div>
<div class="line"><a name="l00064"></a><span class="lineno"> 64</span>  <span class="keyword">struct</span>{ T x, y, z; };</div>
<div class="line"><a name="l00065"></a><span class="lineno"> 65</span>  <span class="keyword">struct</span>{ T r, g, b; };</div>
<div class="line"><a name="l00066"></a><span class="lineno"> 66</span>  <span class="keyword">struct</span>{ T s, t, p; };</div>
<div class="line"><a name="l00067"></a><span class="lineno"> 67</span> </div>
<div class="line"><a name="l00068"></a><span class="lineno"> 68</span> <span class="preprocessor"># ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00069"></a><span class="lineno"> 69</span>  <API key>(T, P, tvec2, x, y, z)</div>
<div class="line"><a name="l00070"></a><span class="lineno"> 70</span>  <API key>(T, P, tvec2, r, g, b)</div>
<div class="line"><a name="l00071"></a><span class="lineno"> 71</span>  <API key>(T, P, tvec2, s, t, p)</div>
<div class="line"><a name="l00072"></a><span class="lineno"> 72</span>  <API key>(T, P, tvec3, x, y, z)</div>
<div class="line"><a name="l00073"></a><span class="lineno"> 73</span>  <API key>(T, P, tvec3, r, g, b)</div>
<div class="line"><a name="l00074"></a><span class="lineno"> 74</span>  <API key>(T, P, tvec3, s, t, p)</div>
<div class="line"><a name="l00075"></a><span class="lineno"> 75</span>  <API key>(T, P, tvec4, x, y, z)</div>
<div class="line"><a name="l00076"></a><span class="lineno"> 76</span>  <API key>(T, P, tvec4, r, g, b)</div>
<div class="line"><a name="l00077"></a><span class="lineno"> 77</span>  <API key>(T, P, tvec4, s, t, p)</div>
<div class="line"><a name="l00078"></a><span class="lineno"> 78</span> <span class="preprocessor"># endif//GLM_SWIZZLE</span></div>
<div class="line"><a name="l00079"></a><span class="lineno"> 79</span>  };</div>
<div class="line"><a name="l00080"></a><span class="lineno"> 80</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00081"></a><span class="lineno"> 81</span>  <span class="keyword">union </span>{ T x, r, s; };</div>
<div class="line"><a name="l00082"></a><span class="lineno"> 82</span>  <span class="keyword">union </span>{ T y, g, t; };</div>
<div class="line"><a name="l00083"></a><span class="lineno"> 83</span>  <span class="keyword">union </span>{ T z, b, p; };</div>
<div class="line"><a name="l00084"></a><span class="lineno"> 84</span> </div>
<div class="line"><a name="l00085"></a><span class="lineno"> 85</span> <span class="preprocessor"># ifdef GLM_SWIZZLE</span></div>
<div class="line"><a name="l00086"></a><span class="lineno"> 86</span>  <API key>(T, P, tvec3, tvec2, tvec3, tvec4)</div>
<div class="line"><a name="l00087"></a><span class="lineno"> 87</span> <span class="preprocessor"># endif//GLM_SWIZZLE</span></div>
<div class="line"><a name="l00088"></a><span class="lineno"> 88</span> <span class="preprocessor"># endif//GLM_LANG</span></div>
<div class="line"><a name="l00089"></a><span class="lineno"> 89</span> </div>
<div class="line"><a name="l00091"></a><span class="lineno"> 91</span>  <span class="comment">// Component accesses</span></div>
<div class="line"><a name="l00092"></a><span class="lineno"> 92</span> </div>
<div class="line"><a name="l00093"></a><span class="lineno"> 93</span> <span class="preprocessor"># ifdef GLM_FORCE_SIZE_FUNC</span></div>
<div class="line"><a name="l00094"></a><span class="lineno"> 94</span>  <span class="keyword">typedef</span> <span class="keywordtype">size_t</span> size_type;</div>
<div class="line"><a name="l00096"></a><span class="lineno"> 96</span>  GLM_FUNC_DECL GLM_CONSTEXPR size_type size() <span class="keyword">const</span>;</div>
<div class="line"><a name="l00097"></a><span class="lineno"> 97</span> </div>
<div class="line"><a name="l00098"></a><span class="lineno"> 98</span>  GLM_FUNC_DECL T & operator[](size_type i);</div>
<div class="line"><a name="l00099"></a><span class="lineno"> 99</span>  GLM_FUNC_DECL T <span class="keyword">const</span> & operator[](size_type i) <span class="keyword">const</span>;</div>
<div class="line"><a name="l00100"></a><span class="lineno"> 100</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00101"></a><span class="lineno"> 101</span>  <span class="keyword">typedef</span> length_t length_type;</div>
<div class="line"><a name="l00103"></a><span class="lineno"> 103</span>  GLM_FUNC_DECL GLM_CONSTEXPR length_type <a class="code" href="a00151.html#<API key>">length</a>() <span class="keyword">const</span>;</div>
<div class="line"><a name="l00104"></a><span class="lineno"> 104</span> </div>
<div class="line"><a name="l00105"></a><span class="lineno"> 105</span>  GLM_FUNC_DECL T & operator[](length_type i);</div>
<div class="line"><a name="l00106"></a><span class="lineno"> 106</span>  GLM_FUNC_DECL T <span class="keyword">const</span> & operator[](length_type i) <span class="keyword">const</span>;</div>
<div class="line"><a name="l00107"></a><span class="lineno"> 107</span> <span class="preprocessor"># endif//GLM_FORCE_SIZE_FUNC</span></div>
<div class="line"><a name="l00108"></a><span class="lineno"> 108</span> </div>
<div class="line"><a name="l00110"></a><span class="lineno"> 110</span>  <span class="comment">// Implicit basic constructors</span></div>
<div class="line"><a name="l00111"></a><span class="lineno"> 111</span> </div>
<div class="line"><a name="l00112"></a><span class="lineno"> 112</span>  GLM_FUNC_DECL tvec3();</div>
<div class="line"><a name="l00113"></a><span class="lineno"> 113</span>  <span class="keyword">template</span> <precision Q></div>
<div class="line"><a name="l00114"></a><span class="lineno"> 114</span>  GLM_FUNC_DECL tvec3(tvec3<T, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00115"></a><span class="lineno"> 115</span> </div>
<div class="line"><a name="l00117"></a><span class="lineno"> 117</span>  <span class="comment">// Explicit basic constructors</span></div>
<div class="line"><a name="l00118"></a><span class="lineno"> 118</span> </div>
<div class="line"><a name="l00119"></a><span class="lineno"> 119</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(ctor);</div>
<div class="line"><a name="l00120"></a><span class="lineno"> 120</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00121"></a><span class="lineno"> 121</span>  GLM_FUNC_DECL tvec3(T <span class="keyword">const</span> & a, T <span class="keyword">const</span> & b, T <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00122"></a><span class="lineno"> 122</span> </div>
<div class="line"><a name="l00124"></a><span class="lineno"> 124</span>  <span class="comment">// Conversion scalar constructors</span></div>
<div class="line"><a name="l00125"></a><span class="lineno"> 125</span> </div>
<div class="line"><a name="l00127"></a><span class="lineno"> 127</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, <span class="keyword">typename</span> C></div>
<div class="line"><a name="l00128"></a><span class="lineno"> 128</span>  GLM_FUNC_DECL tvec3(A <span class="keyword">const</span> & a, B <span class="keyword">const</span> & b, C <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00129"></a><span class="lineno"> 129</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, <span class="keyword">typename</span> C></div>
<div class="line"><a name="l00130"></a><span class="lineno"> 130</span>  GLM_FUNC_DECL tvec3(tvec1<A, P> <span class="keyword">const</span> & a, tvec1<B, P> <span class="keyword">const</span> & b, tvec1<C, P> <span class="keyword">const</span> & c);</div>
<div class="line"><a name="l00131"></a><span class="lineno"> 131</span> </div>
<div class="line"><a name="l00133"></a><span class="lineno"> 133</span>  <span class="comment">// Conversion vector constructors</span></div>
<div class="line"><a name="l00134"></a><span class="lineno"> 134</span> </div>
<div class="line"><a name="l00136"></a><span class="lineno"> 136</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00137"></a><span class="lineno"> 137</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec2<A, Q> <span class="keyword">const</span> & a, B <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00139"></a><span class="lineno"> 139</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00140"></a><span class="lineno"> 140</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec2<A, Q> <span class="keyword">const</span> & a, tvec1<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00142"></a><span class="lineno"> 142</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00143"></a><span class="lineno"> 143</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(A <span class="keyword">const</span> & a, tvec2<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00145"></a><span class="lineno"> 145</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> A, <span class="keyword">typename</span> B, precision Q></div>
<div class="line"><a name="l00146"></a><span class="lineno"> 146</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec1<A, Q> <span class="keyword">const</span> & a, tvec2<B, Q> <span class="keyword">const</span> & b);</div>
<div class="line"><a name="l00148"></a><span class="lineno"> 148</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00149"></a><span class="lineno"> 149</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec4<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00150"></a><span class="lineno"> 150</span> </div>
<div class="line"><a name="l00151"></a><span class="lineno"> 151</span> <span class="preprocessor"># ifdef <API key></span></div>
<div class="line"><a name="l00152"></a><span class="lineno"> 152</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00154"></a><span class="lineno"> 154</span>  GLM_FUNC_DECL <span class="keyword">explicit</span> tvec3(tvec3<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00155"></a><span class="lineno"> 155</span> <span class="preprocessor"># else</span></div>
<div class="line"><a name="l00156"></a><span class="lineno"> 156</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U, precision Q></div>
<div class="line"><a name="l00158"></a><span class="lineno"> 158</span>  GLM_FUNC_DECL tvec3(tvec3<U, Q> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00159"></a><span class="lineno"> 159</span> <span class="preprocessor"># endif</span></div>
<div class="line"><a name="l00160"></a><span class="lineno"> 160</span> </div>
<div class="line"><a name="l00162"></a><span class="lineno"> 162</span>  <span class="comment">// Swizzle constructors</span></div>
<div class="line"><a name="l00163"></a><span class="lineno"> 163</span> </div>
<div class="line"><a name="l00164"></a><span class="lineno"> 164</span> <span class="preprocessor"># if <API key> && defined(GLM_SWIZZLE)</span></div>
<div class="line"><a name="l00165"></a><span class="lineno"> 165</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1, <span class="keywordtype">int</span> E2></div>
<div class="line"><a name="l00166"></a><span class="lineno"> 166</span>  GLM_FUNC_DECL tvec3(detail::_swizzle<3, T, P, tvec3<T, P>, E0, E1, E2, -1> <span class="keyword">const</span> & that)</div>
<div class="line"><a name="l00167"></a><span class="lineno"> 167</span>  {</div>
<div class="line"><a name="l00168"></a><span class="lineno"> 168</span>  *<span class="keyword">this</span> = that();</div>
<div class="line"><a name="l00169"></a><span class="lineno"> 169</span>  }</div>
<div class="line"><a name="l00170"></a><span class="lineno"> 170</span> </div>
<div class="line"><a name="l00171"></a><span class="lineno"> 171</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1></div>
<div class="line"><a name="l00172"></a><span class="lineno"> 172</span>  GLM_FUNC_DECL tvec3(detail::_swizzle<2, T, P, tvec2<T, P>, E0, E1, -1, -2> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s)</div>
<div class="line"><a name="l00173"></a><span class="lineno"> 173</span>  {</div>
<div class="line"><a name="l00174"></a><span class="lineno"> 174</span>  *<span class="keyword">this</span> = tvec3<T, P>(v(), s);</div>
<div class="line"><a name="l00175"></a><span class="lineno"> 175</span>  }</div>
<div class="line"><a name="l00176"></a><span class="lineno"> 176</span> </div>
<div class="line"><a name="l00177"></a><span class="lineno"> 177</span>  <span class="keyword">template</span> <<span class="keywordtype">int</span> E0, <span class="keywordtype">int</span> E1></div>
<div class="line"><a name="l00178"></a><span class="lineno"> 178</span>  GLM_FUNC_DECL tvec3(T <span class="keyword">const</span> & s, detail::_swizzle<2, T, P, tvec2<T, P>, E0, E1, -1, -2> <span class="keyword">const</span> & v)</div>
<div class="line"><a name="l00179"></a><span class="lineno"> 179</span>  {</div>
<div class="line"><a name="l00180"></a><span class="lineno"> 180</span>  *<span class="keyword">this</span> = tvec3<T, P>(s, v());</div>
<div class="line"><a name="l00181"></a><span class="lineno"> 181</span>  }</div>
<div class="line"><a name="l00182"></a><span class="lineno"> 182</span> <span class="preprocessor"># endif// <API key> && defined(GLM_SWIZZLE)</span></div>
<div class="line"><a name="l00183"></a><span class="lineno"> 183</span> </div>
<div class="line"><a name="l00185"></a><span class="lineno"> 185</span>  <span class="comment">// Unary arithmetic operators</span></div>
<div class="line"><a name="l00186"></a><span class="lineno"> 186</span> </div>
<div class="line"><a name="l00187"></a><span class="lineno"> 187</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00188"></a><span class="lineno"> 188</span>  GLM_FUNC_DECL tvec3<T, P> & operator=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00189"></a><span class="lineno"> 189</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00190"></a><span class="lineno"> 190</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(U s);</div>
<div class="line"><a name="l00191"></a><span class="lineno"> 191</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00192"></a><span class="lineno"> 192</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00193"></a><span class="lineno"> 193</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00194"></a><span class="lineno"> 194</span>  GLM_FUNC_DECL tvec3<T, P> & operator+=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00195"></a><span class="lineno"> 195</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00196"></a><span class="lineno"> 196</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(U s);</div>
<div class="line"><a name="l00197"></a><span class="lineno"> 197</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00198"></a><span class="lineno"> 198</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00199"></a><span class="lineno"> 199</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00200"></a><span class="lineno"> 200</span>  GLM_FUNC_DECL tvec3<T, P> & operator-=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00201"></a><span class="lineno"> 201</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00202"></a><span class="lineno"> 202</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(U s);</div>
<div class="line"><a name="l00203"></a><span class="lineno"> 203</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00204"></a><span class="lineno"> 204</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00205"></a><span class="lineno"> 205</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00206"></a><span class="lineno"> 206</span>  GLM_FUNC_DECL tvec3<T, P> & operator*=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00207"></a><span class="lineno"> 207</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00208"></a><span class="lineno"> 208</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(U s);</div>
<div class="line"><a name="l00209"></a><span class="lineno"> 209</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00210"></a><span class="lineno"> 210</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00211"></a><span class="lineno"> 211</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00212"></a><span class="lineno"> 212</span>  GLM_FUNC_DECL tvec3<T, P> & operator/=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00213"></a><span class="lineno"> 213</span> </div>
<div class="line"><a name="l00215"></a><span class="lineno"> 215</span>  <span class="comment">// Increment and decrement operators</span></div>
<div class="line"><a name="l00216"></a><span class="lineno"> 216</span> </div>
<div class="line"><a name="l00217"></a><span class="lineno"> 217</span>  GLM_FUNC_DECL tvec3<T, P> & operator++();</div>
<div class="line"><a name="l00218"></a><span class="lineno"> 218</span>  GLM_FUNC_DECL tvec3<T, P> & operator--();</div>
<div class="line"><a name="l00219"></a><span class="lineno"> 219</span>  GLM_FUNC_DECL tvec3<T, P> operator++(<span class="keywordtype">int</span>);</div>
<div class="line"><a name="l00220"></a><span class="lineno"> 220</span>  GLM_FUNC_DECL tvec3<T, P> operator--(<span class="keywordtype">int</span>);</div>
<div class="line"><a name="l00221"></a><span class="lineno"> 221</span> </div>
<div class="line"><a name="l00223"></a><span class="lineno"> 223</span>  <span class="comment">// Unary bit operators</span></div>
<div class="line"><a name="l00224"></a><span class="lineno"> 224</span> </div>
<div class="line"><a name="l00225"></a><span class="lineno"> 225</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00226"></a><span class="lineno"> 226</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(U s);</div>
<div class="line"><a name="l00227"></a><span class="lineno"> 227</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00228"></a><span class="lineno"> 228</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00229"></a><span class="lineno"> 229</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00230"></a><span class="lineno"> 230</span>  GLM_FUNC_DECL tvec3<T, P> & operator%=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00231"></a><span class="lineno"> 231</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00232"></a><span class="lineno"> 232</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(U s);</div>
<div class="line"><a name="l00233"></a><span class="lineno"> 233</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00234"></a><span class="lineno"> 234</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00235"></a><span class="lineno"> 235</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00236"></a><span class="lineno"> 236</span>  GLM_FUNC_DECL tvec3<T, P> & operator&=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00237"></a><span class="lineno"> 237</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00238"></a><span class="lineno"> 238</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(U s);</div>
<div class="line"><a name="l00239"></a><span class="lineno"> 239</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00240"></a><span class="lineno"> 240</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00241"></a><span class="lineno"> 241</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00242"></a><span class="lineno"> 242</span>  GLM_FUNC_DECL tvec3<T, P> & operator|=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00243"></a><span class="lineno"> 243</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00244"></a><span class="lineno"> 244</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(U s);</div>
<div class="line"><a name="l00245"></a><span class="lineno"> 245</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00246"></a><span class="lineno"> 246</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00247"></a><span class="lineno"> 247</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00248"></a><span class="lineno"> 248</span>  GLM_FUNC_DECL tvec3<T, P> & operator^=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00249"></a><span class="lineno"> 249</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00250"></a><span class="lineno"> 250</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(U s);</div>
<div class="line"><a name="l00251"></a><span class="lineno"> 251</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00252"></a><span class="lineno"> 252</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00253"></a><span class="lineno"> 253</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00254"></a><span class="lineno"> 254</span>  GLM_FUNC_DECL tvec3<T, P> & operator<<=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00255"></a><span class="lineno"> 255</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00256"></a><span class="lineno"> 256</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(U s);</div>
<div class="line"><a name="l00257"></a><span class="lineno"> 257</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00258"></a><span class="lineno"> 258</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(tvec1<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00259"></a><span class="lineno"> 259</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> U></div>
<div class="line"><a name="l00260"></a><span class="lineno"> 260</span>  GLM_FUNC_DECL tvec3<T, P> & operator>>=(tvec3<U, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00261"></a><span class="lineno"> 261</span>  };</div>
<div class="line"><a name="l00262"></a><span class="lineno"> 262</span> </div>
<div class="line"><a name="l00263"></a><span class="lineno"> 263</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00264"></a><span class="lineno"> 264</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00265"></a><span class="lineno"> 265</span> </div>
<div class="line"><a name="l00266"></a><span class="lineno"> 266</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00267"></a><span class="lineno"> 267</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00268"></a><span class="lineno"> 268</span> </div>
<div class="line"><a name="l00269"></a><span class="lineno"> 269</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00270"></a><span class="lineno"> 270</span>  GLM_FUNC_DECL tvec3<T, P> operator+(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00271"></a><span class="lineno"> 271</span> </div>
<div class="line"><a name="l00272"></a><span class="lineno"> 272</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00273"></a><span class="lineno"> 273</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00274"></a><span class="lineno"> 274</span> </div>
<div class="line"><a name="l00275"></a><span class="lineno"> 275</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00276"></a><span class="lineno"> 276</span>  GLM_FUNC_DECL tvec3<T, P> operator+(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00277"></a><span class="lineno"> 277</span> </div>
<div class="line"><a name="l00278"></a><span class="lineno"> 278</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00279"></a><span class="lineno"> 279</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00280"></a><span class="lineno"> 280</span> </div>
<div class="line"><a name="l00281"></a><span class="lineno"> 281</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00282"></a><span class="lineno"> 282</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00283"></a><span class="lineno"> 283</span> </div>
<div class="line"><a name="l00284"></a><span class="lineno"> 284</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00285"></a><span class="lineno"> 285</span>  GLM_FUNC_DECL tvec3<T, P> operator-(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00286"></a><span class="lineno"> 286</span> </div>
<div class="line"><a name="l00287"></a><span class="lineno"> 287</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00288"></a><span class="lineno"> 288</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00289"></a><span class="lineno"> 289</span> </div>
<div class="line"><a name="l00290"></a><span class="lineno"> 290</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00291"></a><span class="lineno"> 291</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00292"></a><span class="lineno"> 292</span> </div>
<div class="line"><a name="l00293"></a><span class="lineno"> 293</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00294"></a><span class="lineno"> 294</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00295"></a><span class="lineno"> 295</span> </div>
<div class="line"><a name="l00296"></a><span class="lineno"> 296</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00297"></a><span class="lineno"> 297</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00298"></a><span class="lineno"> 298</span> </div>
<div class="line"><a name="l00299"></a><span class="lineno"> 299</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00300"></a><span class="lineno"> 300</span>  GLM_FUNC_DECL tvec3<T, P> operator*(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00301"></a><span class="lineno"> 301</span> </div>
<div class="line"><a name="l00302"></a><span class="lineno"> 302</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00303"></a><span class="lineno"> 303</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00304"></a><span class="lineno"> 304</span> </div>
<div class="line"><a name="l00305"></a><span class="lineno"> 305</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00306"></a><span class="lineno"> 306</span>  GLM_FUNC_DECL tvec3<T, P> operator*(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00307"></a><span class="lineno"> 307</span> </div>
<div class="line"><a name="l00308"></a><span class="lineno"> 308</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00309"></a><span class="lineno"> 309</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00310"></a><span class="lineno"> 310</span> </div>
<div class="line"><a name="l00311"></a><span class="lineno"> 311</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00312"></a><span class="lineno"> 312</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00313"></a><span class="lineno"> 313</span> </div>
<div class="line"><a name="l00314"></a><span class="lineno"> 314</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00315"></a><span class="lineno"> 315</span>  GLM_FUNC_DECL tvec3<T, P> operator/(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00316"></a><span class="lineno"> 316</span> </div>
<div class="line"><a name="l00317"></a><span class="lineno"> 317</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00318"></a><span class="lineno"> 318</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00319"></a><span class="lineno"> 319</span> </div>
<div class="line"><a name="l00320"></a><span class="lineno"> 320</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00321"></a><span class="lineno"> 321</span>  GLM_FUNC_DECL tvec3<T, P> operator/(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00322"></a><span class="lineno"> 322</span> </div>
<div class="line"><a name="l00323"></a><span class="lineno"> 323</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00324"></a><span class="lineno"> 324</span>  GLM_FUNC_DECL tvec3<T, P> operator-(tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00325"></a><span class="lineno"> 325</span> </div>
<div class="line"><a name="l00326"></a><span class="lineno"> 326</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00327"></a><span class="lineno"> 327</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00328"></a><span class="lineno"> 328</span> </div>
<div class="line"><a name="l00329"></a><span class="lineno"> 329</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00330"></a><span class="lineno"> 330</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00331"></a><span class="lineno"> 331</span> </div>
<div class="line"><a name="l00332"></a><span class="lineno"> 332</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00333"></a><span class="lineno"> 333</span>  GLM_FUNC_DECL tvec3<T, P> operator%(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00334"></a><span class="lineno"> 334</span> </div>
<div class="line"><a name="l00335"></a><span class="lineno"> 335</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00336"></a><span class="lineno"> 336</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00337"></a><span class="lineno"> 337</span> </div>
<div class="line"><a name="l00338"></a><span class="lineno"> 338</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00339"></a><span class="lineno"> 339</span>  GLM_FUNC_DECL tvec3<T, P> operator%(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00340"></a><span class="lineno"> 340</span> </div>
<div class="line"><a name="l00341"></a><span class="lineno"> 341</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00342"></a><span class="lineno"> 342</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00343"></a><span class="lineno"> 343</span> </div>
<div class="line"><a name="l00344"></a><span class="lineno"> 344</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00345"></a><span class="lineno"> 345</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00346"></a><span class="lineno"> 346</span> </div>
<div class="line"><a name="l00347"></a><span class="lineno"> 347</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00348"></a><span class="lineno"> 348</span>  GLM_FUNC_DECL tvec3<T, P> operator&(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00349"></a><span class="lineno"> 349</span> </div>
<div class="line"><a name="l00350"></a><span class="lineno"> 350</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00351"></a><span class="lineno"> 351</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00352"></a><span class="lineno"> 352</span> </div>
<div class="line"><a name="l00353"></a><span class="lineno"> 353</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00354"></a><span class="lineno"> 354</span>  GLM_FUNC_DECL tvec3<T, P> operator&(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00355"></a><span class="lineno"> 355</span> </div>
<div class="line"><a name="l00356"></a><span class="lineno"> 356</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00357"></a><span class="lineno"> 357</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00358"></a><span class="lineno"> 358</span> </div>
<div class="line"><a name="l00359"></a><span class="lineno"> 359</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00360"></a><span class="lineno"> 360</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00361"></a><span class="lineno"> 361</span> </div>
<div class="line"><a name="l00362"></a><span class="lineno"> 362</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00363"></a><span class="lineno"> 363</span>  GLM_FUNC_DECL tvec3<T, P> operator|(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00364"></a><span class="lineno"> 364</span> </div>
<div class="line"><a name="l00365"></a><span class="lineno"> 365</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00366"></a><span class="lineno"> 366</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00367"></a><span class="lineno"> 367</span> </div>
<div class="line"><a name="l00368"></a><span class="lineno"> 368</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00369"></a><span class="lineno"> 369</span>  GLM_FUNC_DECL tvec3<T, P> operator|(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00370"></a><span class="lineno"> 370</span> </div>
<div class="line"><a name="l00371"></a><span class="lineno"> 371</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00372"></a><span class="lineno"> 372</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00373"></a><span class="lineno"> 373</span> </div>
<div class="line"><a name="l00374"></a><span class="lineno"> 374</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00375"></a><span class="lineno"> 375</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00376"></a><span class="lineno"> 376</span> </div>
<div class="line"><a name="l00377"></a><span class="lineno"> 377</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00378"></a><span class="lineno"> 378</span>  GLM_FUNC_DECL tvec3<T, P> operator^(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00379"></a><span class="lineno"> 379</span> </div>
<div class="line"><a name="l00380"></a><span class="lineno"> 380</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00381"></a><span class="lineno"> 381</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00382"></a><span class="lineno"> 382</span> </div>
<div class="line"><a name="l00383"></a><span class="lineno"> 383</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00384"></a><span class="lineno"> 384</span>  GLM_FUNC_DECL tvec3<T, P> operator^(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00385"></a><span class="lineno"> 385</span> </div>
<div class="line"><a name="l00386"></a><span class="lineno"> 386</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00387"></a><span class="lineno"> 387</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00388"></a><span class="lineno"> 388</span> </div>
<div class="line"><a name="l00389"></a><span class="lineno"> 389</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00390"></a><span class="lineno"> 390</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00391"></a><span class="lineno"> 391</span> </div>
<div class="line"><a name="l00392"></a><span class="lineno"> 392</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00393"></a><span class="lineno"> 393</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(T const & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00394"></a><span class="lineno"> 394</span> </div>
<div class="line"><a name="l00395"></a><span class="lineno"> 395</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00396"></a><span class="lineno"> 396</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00397"></a><span class="lineno"> 397</span> </div>
<div class="line"><a name="l00398"></a><span class="lineno"> 398</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00399"></a><span class="lineno"> 399</span>  GLM_FUNC_DECL tvec3<T, P> operator<<(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00400"></a><span class="lineno"> 400</span> </div>
<div class="line"><a name="l00401"></a><span class="lineno"> 401</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00402"></a><span class="lineno"> 402</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v, T <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00403"></a><span class="lineno"> 403</span> </div>
<div class="line"><a name="l00404"></a><span class="lineno"> 404</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00405"></a><span class="lineno"> 405</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v, tvec1<T, P> <span class="keyword">const</span> & s);</div>
<div class="line"><a name="l00406"></a><span class="lineno"> 406</span> </div>
<div class="line"><a name="l00407"></a><span class="lineno"> 407</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00408"></a><span class="lineno"> 408</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(T <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00409"></a><span class="lineno"> 409</span> </div>
<div class="line"><a name="l00410"></a><span class="lineno"> 410</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00411"></a><span class="lineno"> 411</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec1<T, P> <span class="keyword">const</span> & s, tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00412"></a><span class="lineno"> 412</span> </div>
<div class="line"><a name="l00413"></a><span class="lineno"> 413</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P></div>
<div class="line"><a name="l00414"></a><span class="lineno"> 414</span>  GLM_FUNC_DECL tvec3<T, P> operator>>(tvec3<T, P> <span class="keyword">const</span> & v1, tvec3<T, P> <span class="keyword">const</span> & v2);</div>
<div class="line"><a name="l00415"></a><span class="lineno"> 415</span> </div>
<div class="line"><a name="l00416"></a><span class="lineno"> 416</span>  <span class="keyword">template</span> <<span class="keyword">typename</span> T, precision P> </div>
<div class="line"><a name="l00417"></a><span class="lineno"> 417</span>  GLM_FUNC_DECL tvec3<T, P> operator~(tvec3<T, P> <span class="keyword">const</span> & v);</div>
<div class="line"><a name="l00418"></a><span class="lineno"> 418</span> }<span class="comment">//namespace glm</span></div>
<div class="line"><a name="l00419"></a><span class="lineno"> 419</span> </div>
<div class="line"><a name="l00420"></a><span class="lineno"> 420</span> <span class="preprocessor">#ifndef <API key></span></div>
<div class="line"><a name="l00421"></a><span class="lineno"> 421</span> <span class="preprocessor">#include "type_vec3.inl"</span></div>
<div class="line"><a name="l00422"></a><span class="lineno"> 422</span> <span class="preprocessor">#endif//<API key></span></div>
<div class="ttc" id="a00005_html"><div class="ttname"><a href="a00005.html">_swizzle_func.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
<div class="ttc" id="<API key>"><div class="ttname"><a href="a00151.html#<API key>">glm::length</a></div><div class="ttdeci">GLM_FUNC_DECL T length(vecType< T, P > const &x)</div><div class="ttdoc">Returns the length of x, i.e., sqrt(x * x). </div></div>
<div class="ttc" id="a00145_html"><div class="ttname"><a href="a00145.html">glm</a></div><div class="ttdef"><b>Definition:</b> <a href="a00003_source.html#l00039">_noise.hpp:39</a></div></div>
<div class="ttc" id="a00131_html"><div class="ttname"><a href="a00131.html">type_vec.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
<div class="ttc" id="a00004_html"><div class="ttname"><a href="a00004.html">_swizzle.hpp</a></div><div class="ttdoc">OpenGL Mathematics (glm.g-truc.net) </div></div>
</div><!-- fragment --></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.8
</small></address>
</body>
</html>
|
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, <API key>, and (if you want functional tests) functionalSuites
define({
// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
// specified browser environments in the `environments` array below as well. See
// <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for
// different services.
// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
maxConcurrency: 2,
// Non-functional test suite(s) to run in each browser
suites: [ 'tests/plugin' ],
// A regular expression matching URLs to files that should not be included in code coverage analysis
<API key>: /^(?:tests|node_modules)\
});
|
import {LooseParser} from "./state"
import {isDummy} from "./parseutil"
import {tokTypes as tt} from ".."
const lp = LooseParser.prototype
lp.checkLVal = function(expr) {
if (!expr) return expr
switch (expr.type) {
case "Identifier":
case "MemberExpression":
return expr
case "<API key>":
expr.expression = this.checkLVal(expr.expression)
return expr
default:
return this.dummyIdent()
}
}
lp.parseExpression = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseMaybeAssign(noIn)
if (this.tok.type === tt.comma) {
let node = this.startNodeAt(start)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
lp.<API key> = function() {
this.pushCx()
this.expect(tt.parenL)
let val = this.parseExpression()
this.popCx()
this.expect(tt.parenR)
return val
}
lp.parseMaybeAssign = function(noIn) {
if (this.toks.isContextual("yield")) {
let node = this.startNode()
this.next()
if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
let start = this.storeCurrentPos()
let left = this.<API key>(noIn)
if (this.tok.type.isAssign) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "<API key>")
}
return left
}
lp.<API key> = function(noIn) {
let start = this.storeCurrentPos()
let expr = this.parseExprOps(noIn)
if (this.eat(tt.question)) {
let node = this.startNodeAt(start)
node.test = expr
node.consequent = this.parseMaybeAssign()
node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent()
return this.finishNode(node, "<API key>")
}
return expr
}
lp.parseExprOps = function(noIn) {
let start = this.storeCurrentPos()
let indent = this.curIndent, line = this.curLineStart
return this.parseExprOp(this.parseMaybeUnary(false), start, -1, noIn, indent, line)
}
lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) {
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left
let prec = this.tok.type.binop
if (prec != null && (!noIn || this.tok.type !== tt._in)) {
if (prec > minPrec) {
let node = this.startNodeAt(start)
node.left = left
node.operator = this.tok.value
this.next()
if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) {
node.right = this.dummyIdent()
} else {
let rightStart = this.storeCurrentPos()
node.right = this.parseExprOp(this.parseMaybeUnary(false), rightStart, prec, noIn, indent, line)
}
this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression")
return this.parseExprOp(node, start, minPrec, noIn, indent, line)
}
}
return left
}
lp.parseMaybeUnary = function(sawUnary) {
let start = this.storeCurrentPos(), expr
if (this.tok.type.prefix) {
let node = this.startNode(), update = this.tok.type === tt.incDec
if (!update) sawUnary = true
node.operator = this.tok.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(true)
if (update) node.argument = this.checkLVal(node.argument)
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else if (this.tok.type === tt.ellipsis) {
let node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(sawUnary)
expr = this.finishNode(node, "SpreadElement")
} else {
expr = this.parseExprSubscripts()
while (this.tok.type.postfix && !this.canInsertSemicolon()) {
let node = this.startNodeAt(start)
node.operator = this.tok.value
node.prefix = false
node.argument = this.checkLVal(expr)
this.next()
expr = this.finishNode(node, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar)) {
let node = this.startNodeAt(start)
node.operator = "**"
node.left = expr
node.right = this.parseMaybeUnary(false)
return this.finishNode(node, "BinaryExpression")
}
return expr
}
lp.parseExprSubscripts = function() {
let start = this.storeCurrentPos()
return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart)
}
lp.parseSubscripts = function(base, start, noCalls, startIndent, line) {
for (;;) {
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) {
if (this.tok.type == tt.dot && this.curIndent == startIndent)
--startIndent
else
return base
}
if (this.eat(tt.dot)) {
let node = this.startNodeAt(start)
node.object = base
if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine())
node.property = this.dummyIdent()
else
node.property = this.<API key>() || this.dummyIdent()
node.computed = false
base = this.finishNode(node, "MemberExpression")
} else if (this.tok.type == tt.bracketL) {
this.pushCx()
this.next()
let node = this.startNodeAt(start)
node.object = base
node.property = this.parseExpression()
node.computed = true
this.popCx()
this.expect(tt.bracketR)
base = this.finishNode(node, "MemberExpression")
} else if (!noCalls && this.tok.type == tt.parenL) {
let node = this.startNodeAt(start)
node.callee = base
node.arguments = this.parseExprList(tt.parenR)
base = this.finishNode(node, "CallExpression")
} else if (this.tok.type == tt.backQuote) {
let node = this.startNodeAt(start)
node.tag = base
node.quasi = this.parseTemplate()
base = this.finishNode(node, "<API key>")
} else {
return base
}
}
}
lp.parseExprAtom = function() {
let node
switch (this.tok.type) {
case tt._this:
case tt._super:
let type = this.tok.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
let start = this.storeCurrentPos()
let id = this.parseIdent()
return this.eat(tt.arrow) ? this.<API key>(this.startNodeAt(start), [id]) : id
case tt.regexp:
node = this.startNode()
let val = this.tok.value
node.regex = {pattern: val.pattern, flags: val.flags}
node.value = val.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt.num: case tt.string:
node = this.startNode()
node.value = this.tok.value
node.raw = this.input.slice(this.tok.start, this.tok.end)
this.next()
return this.finishNode(node, "Literal")
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true
node.raw = this.tok.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
let parenStart = this.storeCurrentPos()
this.next()
let inner = this.parseExpression()
this.expect(tt.parenR)
if (this.eat(tt.arrow)) {
return this.<API key>(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner]))
}
if (this.options.preserveParens) {
let par = this.startNodeAt(parenStart)
par.expression = inner
inner = this.finishNode(par, "<API key>")
}
return inner
case tt.bracketL:
node = this.startNode()
node.elements = this.parseExprList(tt.bracketR, true)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj()
case tt._class:
return this.parseClass()
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
return this.dummyIdent()
}
}
lp.parseNew = function() {
let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart
let meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
return this.finishNode(node, "MetaProperty")
}
let start = this.storeCurrentPos()
node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line)
if (this.tok.type == tt.parenL) {
node.arguments = this.parseExprList(tt.parenR)
} else {
node.arguments = []
}
return this.finishNode(node, "NewExpression")
}
lp.<API key> = function() {
let elem = this.startNode()
elem.value = {
raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'),
cooked: this.tok.value
}
this.next()
elem.tail = this.tok.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
lp.parseTemplate = function() {
let node = this.startNode()
this.next()
node.expressions = []
let curElt = this.<API key>()
node.quasis = [curElt]
while (!curElt.tail) {
this.next()
node.expressions.push(this.parseExpression())
if (this.expect(tt.braceR)) {
curElt = this.<API key>()
} else {
curElt = this.startNode()
curElt.value = {cooked: '', raw: ''}
curElt.tail = true
}
node.quasis.push(curElt)
}
this.expect(tt.backQuote)
return this.finishNode(node, "TemplateLiteral")
}
lp.parseObj = function() {
let node = this.startNode()
node.properties = []
this.pushCx()
let indent = this.curIndent + 1, line = this.curLineStart
this.eat(tt.braceL)
if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart }
while (!this.closes(tt.braceR, indent, line)) {
let prop = this.startNode(), isGenerator, start
if (this.options.ecmaVersion >= 6) {
start = this.storeCurrentPos()
prop.method = false
prop.shorthand = false
isGenerator = this.eat(tt.star)
}
this.parsePropertyName(prop)
if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue }
if (this.eat(tt.colon)) {
prop.kind = "init"
prop.value = this.parseMaybeAssign()
} else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) {
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator)
} else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
!prop.computed && (prop.key.name === "get" || prop.key.name === "set") &&
(this.tok.type != tt.comma && this.tok.type != tt.braceR)) {
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
} else {
prop.kind = "init"
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.eq)) {
let assign = this.startNodeAt(start)
assign.operator = "="
assign.left = prop.key
assign.right = this.parseMaybeAssign()
prop.value = this.finishNode(assign, "<API key>")
} else {
prop.value = prop.key
}
} else {
prop.value = this.dummyIdent()
}
prop.shorthand = true
}
node.properties.push(this.finishNode(prop, "Property"))
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(tt.braceR)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return this.finishNode(node, "ObjectExpression")
}
lp.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseExpression()
this.expect(tt.bracketR)
return
} else {
prop.computed = false
}
}
let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent()
prop.key = key || this.dummyIdent()
}
lp.<API key> = function() {
if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent()
}
lp.parseIdent = function() {
let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword
if (!name) return this.dummyIdent()
let node = this.startNode()
this.next()
node.name = name
return this.finishNode(node, "Identifier")
}
lp.initFunction = function(node) {
node.id = null
node.params = []
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
}
// Convert existing expression atom to assignable pattern
// if possible.
lp.toAssignable = function(node, binding) {
if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) {
// Okay
} else if (node.type == "<API key>") {
node.expression = this.toAssignable(node.expression, binding)
} else if (this.options.ecmaVersion < 6) {
return this.dummyIdent()
} else if (node.type == "ObjectExpression") {
node.type = "ObjectPattern"
let props = node.properties
for (let i = 0; i < props.length; i++)
props[i].value = this.toAssignable(props[i].value, binding)
} else if (node.type == "ArrayExpression") {
node.type = "ArrayPattern"
this.toAssignableList(node.elements, binding)
} else if (node.type == "SpreadElement") {
node.type = "RestElement"
node.argument = this.toAssignable(node.argument, binding)
} else if (node.type == "<API key>") {
node.type = "AssignmentPattern"
delete node.operator
} else {
return this.dummyIdent()
}
return node
}
lp.toAssignableList = function(exprList, binding) {
for (let i = 0; i < exprList.length; i++)
exprList[i] = this.toAssignable(exprList[i], binding)
return exprList
}
lp.parseFunctionParams = function(params) {
params = this.parseExprList(tt.parenR)
return this.toAssignableList(params, true)
}
lp.parseMethod = function(isGenerator) {
let node = this.startNode()
this.initFunction(node)
node.params = this.parseFunctionParams()
node.generator = isGenerator || false
node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "FunctionExpression")
}
lp.<API key> = function(node, params) {
this.initFunction(node)
node.params = this.toAssignableList(params, true)
node.expression = this.tok.type !== tt.braceL
node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock()
return this.finishNode(node, "<API key>")
}
lp.parseExprList = function(close, allowEmpty) {
this.pushCx()
let indent = this.curIndent, line = this.curLineStart, elts = []
this.next() // Opening bracket
while (!this.closes(close, indent + 1, line)) {
if (this.eat(tt.comma)) {
elts.push(allowEmpty ? null : this.dummyIdent())
continue
}
let elt = this.parseMaybeAssign()
if (isDummy(elt)) {
if (this.closes(close, indent, line)) break
this.next()
} else {
elts.push(elt)
}
this.eat(tt.comma)
}
this.popCx()
if (!this.eat(close)) {
// If there is no closing brace, make the node span to the start
// of the next token (this is useful for Tern)
this.last.end = this.tok.start
if (this.options.locations) this.last.loc.end = this.tok.loc.start
}
return elts
}
|
html, body {
color: rgba(0, 0, 0, 0.8);
min-height: 100vh;
}
@media (min-width: 992px) {
.content {
padding-left: 300px;
}
}
.hidden {
display: none !important;
}
.loading {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
color: #153d77;
z-index: 9999;
display: inline-block;
}
.loading > div {
top: 35%;
width: 80px;
margin: auto calc(50vw - 40px);
position: fixed;
text-align: center;
}
.loading img {
width: 100%;
}
.nonselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
}
.no-event {
pointer-events: none;
}
.due {
color: red;
}
.error {
margin: 0 0 20px 0;
color: red;
}
.clickable {
cursor: pointer;
}
.text-primary {
color: #153d77 !important;
}
.text-accent {
color: rgb(0,148,64) !important;
}
.primary {
background-color: #153d77 !important;
}
.primary.btn:hover, .primary.btn:active, .primary.btn:focus {
background-color: rgb(0,101,189) !important;
}
.accent{
background-color: rgb(0,148,64) !important;
}
.overlay {
width: 100%;
height: 100%;
position:
absolute;
top: 0;
left: 0;
z-index: 10;
}
.parrallax img {
background-image: url("/assets/meeting.jpg");
background-repeat: no-repeat;
background-position: top;
background-size: cover;
}
svg {
color: inherit;
fill: currentColor;
}
.toast {
background-color: #ff363e;
}
.section {
width: 100%;
}
.<API key> {
background-color: #153d77;
}
.<API key> {
background-color: #0e346b;
}
.picker__day.picker__day--today, .picker__close, .picker__today {
color: #153d77;
}
input:focus:not([readonly]), textarea:focus:not([readonly]), .chips.focus {
border-bottom: 1px solid #153d77 !important;
-webkit-box-shadow: 0 1px 0 0 #153d77 !important;
-moz-box-shadow: 0 1px 0 0 #153d77 !important;
box-shadow: 0 1px 0 0 #153d77 !important;
}
.subtle, .subtle:active, .subtle:focus {
border-bottom: 1px solid #153d77;
box-shadow: 0 1px 0 0 #153d77;
}
input[type=text].subtle {
border-bottom: 0 none white !important;
}
input[type=text]:focus:not([readonly]).subtle {
background: rgba(0, 0, 0, 0.05);
border-style: none !important;
border-width: 0 !important;
box-shadow: 0 0 0 0 white !important;
}
nav ul li a{
color: #153d77;
}
nav a i{
color: #153d77;
}
nav .nav-wrapper .brand-logo {
color: rgba(0, 0, 0, 0.8);
height: 64px;
text-align: center;
white-space: nowrap;
}
nav .nav-wrapper .brand-logo > span {
display: inline-block;
height: 95%;
margin-bottom: 5%;
vertical-align: middle;
font-size: 0.8em;
color: #153d77;
}
nav .nav-wrapper .brand-logo img {
height: 50px;
margin: 8px 8px 8px 8px;
vertical-align: middle;
}
@media (max-width: 600px) {
nav .nav-wrapper .brand-logo {
height: 56px;
}
nav .nav-wrapper .brand-logo img {
height: 40px;
}
}
.config-bar {
background: rgba(255,255,255,0.8);
position:relative;
z-index:1;
}
.config-bar > div:first-of-type {
height: 21.75px;
}
#port {
height:25px;
width:45px;
text-align:
right;
padding: 0 5px;
}
.input-card {
height: 70px;
margin: 0 0 1px 0;
}
.input-card input {
box-sizing: border-box;
font-size: inherit;
height: 70px;
padding: 0 20px;
}
.input-footer {
padding-top: 20px;
text-align: center;
color: rgba(0,0,0,0.4);
}
.input-footer a {
color: inherit;
}
.task-card {
font-size: 1.3em;
min-height: 70px;
margin: 0 0 1px 0;
}
.task-card.completed {
color: rgba(0,0,0,0.4);
text-decoration: line-through;
}
.task-card .checkbox {
width: 40px;
height: 40px;
margin: 0.75rem;
padding: 0;
background: url("/assets/icons/circle.svg");
background-repeat: no-repeat;
}
.task-card .duedate {
font-size: 0.65em;
width: 30%;
text-align: right;
}
.task-card .delete {
width: 24px;
height: 24px;
margin: 0.75rem;
margin-left: 0;
padding: 0;
padding-left: 10px;
background: rgba(0,0,0,0);
}
.task-card:hover .delete {
background: url("/assets/icons/delete.svg");
background-repeat: no-repeat;
}
.task-card .delete:hover {
background: url("/assets/icons/delete_now.svg");
background-repeat: no-repeat;
}
.task-card .edit {
width: 28px;
height: 22px;
margin: 0.75rem 0;
padding: 0;
padding-left: 10px;
background: rgba(0,0,0,0);
}
.task-card:hover .edit {
background: url("/assets/icons/edit.svg");
background-size: contain;
background-repeat: no-repeat;
}
.task-card .edit:hover {
background: url("/assets/icons/edit_filled.svg");
background-size: contain;
background-repeat: no-repeat;
}
.task-card img {
margin: auto auto;
padding: 0.5rem;
}
.task-card .checkbox img {
display: none;
}
.task-card.completed .checkbox img {
display: block;
}
.task-card .card-title {
/* Due date?? margins??*/
width: calc(100% - 4.5rem - 88px);
width: -webkit-calc(100% - 4.5rem - 88px);
width: -moz-calc(100% - 4.5rem - 88px);
}
.modal {
max-height: 80%;
}
.modal drop-zone#multifile-drop {
height: 100%;
padding: 12px;
margin: 12px;
width: calc(100% - 24px);
height: calc(100% - 56px - 24px);
}
.modal drop-zone#multifile-drop #drop-indicator {
/*Important: Cancel all pointer events on the overlay.*/
pointer-events: none;
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
display: none;
}
.modal drop-zone#multifile-drop.over #drop-indicator {
display: block;
background: rgba(255, 255, 255, 0.9);
border-style: dashed;
border-width: 4px;
border-color: rgb(150,150,150);
}
.modal drop-zone#multifile-drop #drop-indicator p{
color: rgb(150,150,150);
font-size: 24pt;
text-align: center;
margin-top: 40%;
}
.modal.modal-fixed-footer {
height: 80%;
}
@media (max-height: 720px) {
.modal .picker--opened .picker__frame {
top: 5%;
bottom: auto;
}
.modal {
top: 5% !important;
max-height: 90%;
}
.modal.modal-fixed-footer {
height: 90%;
}
}
.modal .card-title {
font-size: 32px;
font-weight: 300;
}
.modal .task-header {
text-decoration: none;
color: rgba(0, 0, 0, 0.8);
}
.modal .completed .task-header {
text-decoration: line-through;
color: rgba(0, 0, 0, 0.4);
}
.modal .task-header input {
box-sizing: border-box;
height: 70px;
padding: 0 20px;
margin-bottom: 0;
}
.modal .task-body {
width: 90%;
margin: 30px 5% 0 5%;
}
.modal .valign-wrapper {
margin: 0;
}
.modal hr {
width: 90%;
margin: 0 5%;
border-width: 0 0 0 0;
border-top: 1px solid rgba(0,0,0,0.1);
}
.modal h5 {
font-size: 18px;
}
.modal .description {
min-height: 10em;
}
.modal .attachment-field {
font-size: 11pt;
}
.modal .hint {
font-size: 10pt;
font-style: italic;
color: grey;
}
.modal .input-field {
margin-top: 0;
}
.modal .input-field h5 {
margin-top: 0;
}
.modal.list {
height: 400px;
}
.modal.list .edit-list-wrapper {
width: 90%;
margin: 15px 5% 0 5%;
}
.modal.list .task-card .card-title {
width: calc(100% - 3.0rem);
width: -webkit-calc(100% - 3.0rem);
width: -mozt-calc(100% - 3.0rem);
}
.modal.list.create {
margin-top: 100px;
height: 200px;
}
.modal.list.create .create-list-wrapper {
width: 90%;
margin: 15px 5% 0 5%;
}
.modal.list.create .create-list-wrapper .row {
margin: 0;
}
.waves-effect.waves-blue .waves-ripple {
background-color: rgba(21, 61, 119, 0.50);
}
.chip img {
padding: 4px 4px 4px 0;
}
h1 svg {
width: 60px;
vertical-align: middle;
}
.side-nav a {
height: 48px;
}
list-view .collection-item {
border-style: none !important;
padding: 0 !important;
}
list-view a {
padding:0 !important;
}
list-view .active a{
background: #153d77;
color: white;
}
list-view .active a:hover {
background: rgba(23,77,124, 1);
color: white;
}
list-view .list-title svg {
width: 25px;
vertical-align: middle;
margin-right: 5px;
fill: #153d77;
}
list-view .active .list-title svg {
fill: white;
}
list-view .list-title {
width:100%;
height:100%;
float: left;
padding-left: 10px;
background: inherit;
color: inherit;
}
list-view .active .list-title {
color: white
}
list-view .list-actions {
float: right;
height: 100%;
}
list-view .list-notifications {
width: 32px;
height:100%;
display: inline-block;
background: inherit;
color: inherit;
}
list-view .list-notifications .badge {
font-weight: 300;
}
list-view .active .list-notifications {
color: white
}
list-view .active .list-notifications .badge {
color: rgba(255, 255, 255, 0.7);
}
list-view .list-notifications .new.badge {
background-color: #153d77
}
list-view .active .list-notifications .new.badge {
color: #153d77;
background-color: rgba(255, 255, 255, 1.0);
}
list-view .active .list-notifications {
color: white
}
list-view .list-edit {
width: 28px;
height:100%;
display: inline-block;
background: inherit;
color: inherit;
}
list-view .list-edit .edit {
width: 28px;
height: 22px;
margin: 0.75rem 0;
padding: 0;
background: rgba(0,0,0,0);
}
list-view list-element:hover .edit {
background: url("/assets/icons/edit.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view list-element:hover .active .edit {
background: url("/assets/icons/edit_grey.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view .list-edit .edit:hover {
background: url("/assets/icons/edit_filled.svg");
background-size: contain;
background-repeat: no-repeat;
}
list-view list-element .active .edit:hover {
background: url("/assets/icons/edit_white.svg");
background-size: contain;
background-repeat: no-repeat;
}
/* BUG FIXES Materialize*/
.modal-overlay {
width: 100vw !important;
height: 100vh !important;
background: black !important;
position: absolute !important;
top: 0 !important;
}
/* ANIMATIONS */
.animated {
animation-duration: 0.5s;
animation-fill-mode: both;
<API key>: ease-in-out;
}
.animated.long {
animation-duration: 1.0s;
}
@keyframes shake {
0%, 100% {transform: translateX(0);}
10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);}
20%, 40%, 60%, 80% {transform: translateX(10px);}
}
.shake {
animation-name: shake;
}
@keyframes fadeOutUp {
from {
opacity: 1;
}
to {
opacity: 0;
transform: translate3d(0, -50%, 0);
}
}
.fadeOutUp {
animation-name: fadeOutUp;
}
|
#ifndef LINUX_MMC_HOST_H
#define LINUX_MMC_HOST_H
#include <linux/leds.h>
#include <linux/mmc/core.h>
struct mmc_ios {
unsigned int clock; /* clock rate */
unsigned short vdd;
/* vdd stores the bit number of the selected voltage range from below. */
unsigned char bus_mode; /* command output mode */
#define <API key> 1
#define <API key> 2
unsigned char chip_select; /* SPI chip select */
#define MMC_CS_DONTCARE 0
#define MMC_CS_HIGH 1
#define MMC_CS_LOW 2
unsigned char power_mode; /* power supply mode */
#define MMC_POWER_OFF 0
#define MMC_POWER_UP 1
#define MMC_POWER_ON 2
unsigned char bus_width; /* data bus width */
#define MMC_BUS_WIDTH_1 0
#define MMC_BUS_WIDTH_4 2
unsigned char timing; /* timing specification used */
#define MMC_TIMING_LEGACY 0
#define MMC_TIMING_MMC_HS 1
#define MMC_TIMING_SD_HS 2
};
struct mmc_host_ops {
void (*request)(struct mmc_host *host, struct mmc_request *req);
/*
* Avoid calling these three functions too often or in a "fast path",
* since underlaying controller might implement them in an expensive
* and/or slow way.
*
* Also note that these functions might sleep, so don't call them
* in the atomic contexts!
*
* Return values for the get_ro callback should be:
* 0 for a read/write card
* 1 for a read-only card
* -ENOSYS when not supported (equal to NULL callback)
* or a negative errno value when something bad happened
*
* Return values for the get_cd callback should be:
* 0 for a absent card
* 1 for a present card
* -ENOSYS when not supported (equal to NULL callback)
* or a negative errno value when something bad happened
*/
void (*set_ios)(struct mmc_host *host, struct mmc_ios *ios);
int (*get_ro)(struct mmc_host *host);
int (*get_cd)(struct mmc_host *host);
void (*enable_sdio_irq)(struct mmc_host *host, int enable);
};
struct mmc_card;
struct device;
struct mmc_host {
struct device *parent;
struct device class_dev;
int index;
const struct mmc_host_ops *ops;
unsigned int f_min;
unsigned int f_max;
u32 ocr_avail;
#define MMC_VDD_165_195 0x00000080 /* VDD voltage 1.65 - 1.95 */
#define MMC_VDD_20_21 0x00000100 /* VDD voltage 2.0 ~ 2.1 */
#define MMC_VDD_21_22 0x00000200 /* VDD voltage 2.1 ~ 2.2 */
#define MMC_VDD_22_23 0x00000400 /* VDD voltage 2.2 ~ 2.3 */
#define MMC_VDD_23_24 0x00000800 /* VDD voltage 2.3 ~ 2.4 */
#define MMC_VDD_24_25 0x00001000 /* VDD voltage 2.4 ~ 2.5 */
#define MMC_VDD_25_26 0x00002000 /* VDD voltage 2.5 ~ 2.6 */
#define MMC_VDD_26_27 0x00004000 /* VDD voltage 2.6 ~ 2.7 */
#define MMC_VDD_27_28 0x00008000 /* VDD voltage 2.7 ~ 2.8 */
#define MMC_VDD_28_29 0x00010000 /* VDD voltage 2.8 ~ 2.9 */
#define MMC_VDD_29_30 0x00020000 /* VDD voltage 2.9 ~ 3.0 */
#define MMC_VDD_30_31 0x00040000 /* VDD voltage 3.0 ~ 3.1 */
#define MMC_VDD_31_32 0x00080000 /* VDD voltage 3.1 ~ 3.2 */
#define MMC_VDD_32_33 0x00100000 /* VDD voltage 3.2 ~ 3.3 */
#define MMC_VDD_33_34 0x00200000 /* VDD voltage 3.3 ~ 3.4 */
#define MMC_VDD_34_35 0x00400000 /* VDD voltage 3.4 ~ 3.5 */
#define MMC_VDD_35_36 0x00800000 /* VDD voltage 3.5 ~ 3.6 */
unsigned long caps; /* Host capabilities */
#define MMC_CAP_4_BIT_DATA (1 << 0) /* Can the host do 4 bit transfers */
#define <API key> (1 << 1) /* Can do MMC high-speed timing */
#define <API key> (1 << 2) /* Can do SD high-speed timing */
#define MMC_CAP_SDIO_IRQ (1 << 3) /* Can signal pending SDIO IRQs */
#define MMC_CAP_SPI (1 << 4) /* Talks only SPI protocols */
#define MMC_CAP_NEEDS_POLL (1 << 5) /* Needs polling for card-detection */
/* host specific block data */
unsigned int max_seg_size; /* see <API key> */
unsigned short max_hw_segs; /* see <API key> */
unsigned short max_phys_segs; /* see <API key> */
unsigned short unused;
unsigned int max_req_size; /* maximum number of bytes in one req */
unsigned int max_blk_size; /* maximum size of one mmc block */
unsigned int max_blk_count; /* maximum number of blocks in one req */
/* private data */
spinlock_t lock; /* lock for claim and bus ops */
struct mmc_ios ios; /* current io bus settings */
u32 ocr; /* the current OCR setting */
/* group bitfields together to minimize padding */
unsigned int use_spi_crc:1;
unsigned int claimed:1; /* host exclusively claimed */
unsigned int bus_dead:1; /* bus has been released */
#ifdef CONFIG_MMC_DEBUG
unsigned int removed:1; /* host is being removed */
#endif
struct mmc_card *card; /* device attached to this host */
wait_queue_head_t wq;
struct delayed_work detect;
const struct mmc_bus_ops *bus_ops; /* current bus driver */
unsigned int bus_refs; /* reference counter */
unsigned int sdio_irqs;
struct task_struct *sdio_irq_thread;
atomic_t <API key>;
#ifdef <API key>
struct led_trigger *led; /* activity led */
#endif
struct dentry *debugfs_root;
unsigned long private[0] <API key>;
};
extern struct mmc_host *mmc_alloc_host(int extra, struct device *);
extern int mmc_add_host(struct mmc_host *);
extern void mmc_remove_host(struct mmc_host *);
extern void mmc_free_host(struct mmc_host *);
static inline void *mmc_priv(struct mmc_host *host)
{
return (void *)host->private;
}
#define mmc_host_is_spi(host) ((host)->caps & MMC_CAP_SPI)
#define mmc_dev(x) ((x)->parent)
#define mmc_classdev(x) (&(x)->class_dev)
#define mmc_hostname(x) (dev_name(&(x)->class_dev))
extern int mmc_suspend_host(struct mmc_host *, pm_message_t);
extern int mmc_resume_host(struct mmc_host *);
extern void mmc_detect_change(struct mmc_host *, unsigned long delay);
extern void mmc_request_done(struct mmc_host *, struct mmc_request *);
static inline void mmc_signal_sdio_irq(struct mmc_host *host)
{
host->ops->enable_sdio_irq(host, 0);
wake_up_process(host->sdio_irq_thread);
}
#endif
|
<?php
namespace Elasticsearch\Endpoints\Indices\Gateway;
use Elasticsearch\Endpoints\AbstractEndpoint;
class Snapshot extends AbstractEndpoint
{
/**
* @return string
*/
protected function getURI()
{
$index = $this->index;
$uri = "/_gateway/snapshot";
if (isset($index) === true) {
$uri = "/$index/_gateway/snapshot";
}
return $uri;
}
/**
* @return string[]
*/
protected function getParamWhitelist()
{
return [
'ignore_unavailable',
'allow_no_indices',
'expand_wildcards',
];
}
/**
* @return string
*/
protected function getMethod()
{
return 'POST';
}
}
|
<HTML>
<CENTER><A HREF = "http://lammps.sandia.gov">LAMMPS WWW Site</A> - <A HREF = "Manual.html">LAMMPS Documentation</A> - <A HREF = "Section_commands.html#comm">LAMMPS Commands</A>
</CENTER>
<HR>
<H3>compute rdf command
</H3>
<P><B>Syntax:</B>
</P>
<PRE>compute ID group-ID rdf Nbin itype1 jtype1 itype2 jtype2 ...
</PRE>
<UL><LI>ID, group-ID are documented in <A HREF = "compute.html">compute</A> command
<LI>rdf = style name of this compute command
<LI>Nbin = number of RDF bins
<LI>itypeN = central atom type for Nth RDF histogram (see asterisk form below)
<LI>jtypeN = distribution atom type for Nth RDF histogram (see asterisk form below)
</UL>
<P><B>Examples:</B>
</P>
<PRE>compute 1 all rdf 100
compute 1 all rdf 100 1 1
compute 1 all rdf 100 * 3
compute 1 fluid rdf 500 1 1 1 2 2 1 2 2
compute 1 fluid rdf 500 1*3 2 5 *10
</PRE>
<P><B>Description:</B>
</P>
<P>Define a computation that calculates the radial distribution function
(RDF), also called g(r), and the coordination number for a group of
particles. Both are calculated in histogram form by binning pairwise
distances into <I>Nbin</I> bins from 0.0 to the maximum force cutoff
defined by the <A HREF = "pair_style.html">pair_style</A> command. The bins are of
uniform size in radial distance. Thus a single bin encompasses a thin
shell of distances in 3d and a thin ring of distances in 2d.
</P>
<P>IMPORTANT NOTE: If you have a bonded system, then the settings of
<A HREF = "special_bonds.html">special_bonds</A> command can remove pairwise
interactions between atoms in the same bond, angle, or dihedral. This
is the default setting for the <A HREF = "special_bonds.html">special_bonds</A>
command, and means those pairwise interactions do not appear in the
neighbor list. Because this fix uses the neighbor list, it also means
those pairs will not be included in the RDF. One way to get around
this, is to write a dump file, and use the <A HREF = "rerun.html">rerun</A> command
to compute the RDF for snapshots in the dump file. The rerun script
can use a <A HREF = "special_bonds.html">special_bonds</A> command that includes all
pairs in the neighbor list.
</P>
<P>The <I>itypeN</I> and <I>jtypeN</I> arguments are optional. These arguments
must come in pairs. If no pairs are listed, then a single histogram
is computed for g(r) between all atom types. If one or more pairs are
listed, then a separate histogram is generated for each
<I>itype</I>,<I>jtype</I> pair.
</P>
<P>The <I>itypeN</I> and <I>jtypeN</I> settings can be specified in one of two
ways. An explicit numeric value can be used, as in the 4th example
above. Or a wild-card asterisk can be used to specify a range of atom
types. This takes the form "*" or "*n" or "n*" or "m*n". If N = the
number of atom types, then an asterisk with no numeric values means
all types from 1 to N. A leading asterisk means all types from 1 to n
(inclusive). A trailing asterisk means all types from n to N
(inclusive). A middle asterisk means all types from m to n
(inclusive).
</P>
<P>If both <I>itypeN</I> and <I>jtypeN</I> are single values, as in the 4th example
above, this means that a g(r) is computed where atoms of type <I>itypeN</I>
are the central atom, and atoms of type <I>jtypeN</I> are the distribution
atom. If either <I>itypeN</I> and <I>jtypeN</I> represent a range of values via
the wild-card asterisk, as in the 5th example above, this means that a
g(r) is computed where atoms of any of the range of types represented
by <I>itypeN</I> are the central atom, and atoms of any of the range of
types represented by <I>jtypeN</I> are the distribution atom.
</P>
<P>Pairwise distances are generated by looping over a pairwise neighbor
list, just as they would be in a <A HREF = "pair_style.html">pair_style</A>
computation. The distance between two atoms I and J is included in a
specific histogram if the following criteria are met:
</P>
<UL><LI>atoms I,J are both in the specified compute group
<LI>the distance between atoms I,J is less than the maximum force cutoff
<LI>the type of the I atom matches itypeN (one or a range of types)
<LI>the type of the J atom matches jtypeN (one or a range of types)
</UL>
<P>It is OK if a particular pairwise distance is included in more than
one individual histogram, due to the way the <I>itypeN</I> and <I>jtypeN</I>
arguments are specified.
</P>
<P>The g(r) value for a bin is calculated from the histogram count by
scaling it by the idealized number of how many counts there would be
if atoms of type <I>jtypeN</I> were uniformly distributed. Thus it
involves the count of <I>itypeN</I> atoms, the count of <I>jtypeN</I> atoms, the
volume of the entire simulation box, and the volume of the bin's thin
shell in 3d (or the area of the bin's thin ring in 2d).
</P>
<P>A coordination number coord(r) is also calculated, which is the number
of atoms of type <I>jtypeN</I> within the current bin or closer, averaged
over atoms of type <I>itypeN</I>. This is calculated as the area- or
volume-weighted sum of g(r) values over all bins up to and including
the current bin, multiplied by the global average volume density of
atoms of type jtypeN.
</P>
<P>The simplest way to output the results of the compute rdf calculation
to a file is to use the <A HREF = "fix_ave_time.html">fix ave/time</A> command, for
example:
</P>
<PRE>compute myRDF all rdf 50
fix 1 all ave/time 100 1 100 c_myRDF file tmp.rdf mode vector
</PRE>
<P><B>Output info:</B>
</P>
<P>This compute calculates a global array with the number of rows =
<I>Nbins</I>, and the number of columns = 1 + 2*Npairs, where Npairs is the
number of I,J pairings specified. The first column has the bin
coordinate (center of the bin), Each successive set of 2 columns has
the g(r) and coord(r) values for a specific set of <I>itypeN</I> versus
<I>jtypeN</I> interactions, as described above. These values can be used
by any command that uses a global values from a compute as input. See
<A HREF = "Section_howto.html#howto_15">Section_howto 15</A> for an overview of
LAMMPS output options.
</P>
<P>The array values calculated by this compute are all "intensive".
</P>
<P>The first column of array values will be in distance
<A HREF = "units.html">units</A>. The g(r) columns of array values are normalized
numbers >= 0.0. The coordination number columns of array values are
also numbers >= 0.0.
</P>
<P><B>Restrictions:</B>
</P>
<P>The RDF is not computed for distances longer than the force cutoff,
since processors (in parallel) don't know about atom coordinates for
atoms further away than that distance. If you want an RDF for larger
distances, you can use the <A HREF = "rerun.html">rerun</A> command to post-process
a dump file. The definition of g(r) used by LAMMPS is only appropriate
for characterizing atoms that are uniformly distributed throughout the
simulation cell. In such cases, the coordination number is still
correct and meaningful. As an example, if a large simulation cell
contains only one atom of type <I>itypeN</I> and one of <I>jtypeN</I>, then g(r)
will register an arbitrarily large spike at whatever distance they
happen to be at, and zero everywhere else. coord(r) will show a step
change from zero to one at the location of the spike in g(r).
</P>
<P><B>Related commands:</B>
</P>
<P><A HREF = "fix_ave_time.html">fix ave/time</A>
</P>
<P><B>Default:</B> none
</P>
</HTML>
|
#ifndef <API key>
#define <API key>
#include "titanic/carry/ear.h"
namespace Titanic {
class CPhonographEar : public CEar {
DECLARE_MESSAGE_MAP;
bool <API key>(<API key> *msg);
bool PETGainedObjectMsg(CPETGainedObjectMsg *msg);
bool TimerMsg(CTimerMsg *msg);
private:
bool _replacementEar;
public:
CLASSDEF;
CPhonographEar() : CEar(), _replacementEar(true) {}
/**
* Save the data for the class to file
*/
virtual void save(SimpleFile *file, int indent);
/**
* Load the data for the class from file
*/
virtual void load(SimpleFile *file);
};
} // End of namespace Titanic
#endif /* <API key> */
|
#ifndef __CONFIG_H
#define __CONFIG_H
#include <asm/arch/mx53.h>
/* High Level Configuration Options */
#define CONFIG_ARMV7 /* This is armv7 Cortex-A8 CPU core */
#define CONFIG_MXC
#define CONFIG_MX53
#define CONFIG_MX53_LOCO
#define CONFIG_FLASH_HEADER
#define <API key> 0x400
#define CONFIG_MX53_CLK32 32768
#define <API key>
#define <API key>
#define CONFIG_ARCH_MMU
#define <API key> 24000000
#define <API key> 400
#define CONFIG_SYS_AHB_PODF 2
#define <API key> 0
#define <API key> 1
#define <API key>
#define <API key>
#define <API key>
#define BOARD_LATE_INIT
/*
* Disabled for now due to build problems under Debian and a significant
* increase in the final file size: 144260 vs. 109536 Bytes.
*/
#define CONFIG_CMDLINE_TAG 1 /* enable passing of ATAGs */
#define CONFIG_REVISION_TAG 1
#define <API key> 1
#define CONFIG_INITRD_TAG 1
/*
* Size of malloc() pool
*/
#define <API key> (3 * 1024 * 1024)
/* size in bytes reserved for initial data */
#define <API key> 128
/*
* Hardware drivers
*/
#define CONFIG_MXC_UART 1
#define <API key> UART1_BASE_ADDR
/* allow to overwrite serial and ethaddr */
#define <API key>
#define CONFIG_CONS_INDEX 1
#define CONFIG_BAUDRATE 115200
#define <API key> {9600, 19200, 38400, 57600, 115200}
#include <config_cmd_default.h>
#define CONFIG_CMD_PING
#define CONFIG_CMD_DHCP
#define CONFIG_CMD_MII
#define CONFIG_CMD_NET
#define <API key> 100
#define CONFIG_NET_MULTI 1
#define <API key>
#define <API key>
#define CONFIG_BOOTP_DNS
#define CONFIG_CMD_MMC
#define CONFIG_CMD_ENV
#define CONFIG_CMD_IIM
#define CONFIG_CMD_CLOCK
#define CONFIG_REF_CLK_FREQ <API key>
#define CONFIG_CMD_SATA
#undef CONFIG_CMD_IMLS
#define CONFIG_BOOTDELAY 3
#define CONFIG_PRIME "FEC0"
#define CONFIG_LOADADDR 0x70800000 /* loadaddr env var */
#define CONFIG_RD_LOADADDR (CONFIG_LOADADDR + 0x300000)
#define <API key> \
"netdev=eth0\0" \
"ethprime=FEC0\0" \
"uboot=u-boot.bin\0" \
"kernel=uImage\0" \
"nfsroot=/opt/eldk/arm\0" \
"bootargs_base=setenv bootargs console=ttymxc0,115200\0"\
"bootargs_nfs=setenv bootargs ${bootargs} root=/dev/nfs "\
"ip=dhcp nfsroot=${serverip}:${nfsroot},v3,tcp\0"\
"bootcmd_net=run bootargs_base bootargs_nfs; " \
"tftpboot ${loadaddr} ${kernel}; bootm\0" \
"bootargs_mmc=setenv bootargs ${bootargs} ip=dhcp " \
"root=/dev/mmcblk0p1 rootwait rw\0" \
"bootcmd_mmc=run bootargs_base bootargs_mmc; " \
"mmc dev 0; " \
"mmc read ${loadaddr} 0x800 0x1800; bootm\0" \
"bootcmd=run bootcmd_mmc\0" \
\
#define CONFIG_ARP_TIMEOUT 200UL
/*
* Miscellaneous configurable options
*/
#define CONFIG_SYS_LONGHELP /* undef to save memory */
#define CONFIG_SYS_PROMPT "MX53-LOCO U-Boot > "
#define <API key>
#define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */
/* Print Buffer Size */
#define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE + sizeof(CONFIG_SYS_PROMPT) + 16)
#define CONFIG_SYS_MAXARGS 16 /* max number of command args */
#define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */
#define <API key> 0 /* memtest works on */
#define <API key> 0x10000
#undef <API key> /* everything, incl board info, in Hz */
#define <API key> CONFIG_LOADADDR
#define CONFIG_SYS_HZ 1000
#define <API key> 1
#define CONFIG_FEC0_IOBASE FEC_BASE_ADDR
#define CONFIG_FEC0_PINMUX -1
#define <API key> -1
#define CONFIG_FEC0_MIIBASE -1
#define <API key>
#define <API key> 0x24
#define CONFIG_MXC_FEC
#define CONFIG_MII
#define CONFIG_MII_GASKET
#define CONFIG_DISCOVER_PHY
/*
* FUSE Configs
* */
#ifdef CONFIG_CMD_IIM
#define CONFIG_IMX_IIM
#define IMX_IIM_BASE IIM_BASE_ADDR
#define CONFIG_IIM_MAC_BANK 1
#define CONFIG_IIM_MAC_ROW 9
#endif
/*
* I2C Configs
*/
#define CONFIG_CMD_I2C 1
#define CONFIG_HARD_I2C 1
#define CONFIG_I2C_MXC 1
#define CONFIG_SYS_I2C_PORT I2C1_BASE_ADDR
#define <API key> 100000
#define <API key> 0xfe
/*
* MMC Configs
*/
#ifdef CONFIG_CMD_MMC
#define CONFIG_MMC 1
#define CONFIG_GENERIC_MMC
#define CONFIG_IMX_MMC
#define <API key> 2
#define <API key> 0
#define <API key> 0
#define <API key> 1
#define CONFIG_CMD_FAT 1
#define CONFIG_CMD_EXT2 1
/* detect whether ESDHC1 or ESDHC3 is boot device */
#define <API key>
#define <API key>
#define <API key>
/* port 1 (ESDHC3) is 8 bit */
#define <API key> 0x2
#endif
/*
* SATA Configs
*/
#ifdef CONFIG_CMD_SATA
#define CONFIG_DWC_AHSATA
#define <API key> 1
#define <API key> 0
#define <API key> SATA_BASE_ADDR
#define CONFIG_LBA48
#define CONFIG_LIBATA
#endif
#define CONFIG_STACKSIZE (128 * 1024) /* regular stack */
#define <API key> 2
#define PHYS_SDRAM_1 CSD0_BASE_ADDR
#define PHYS_SDRAM_1_SIZE (512 * 1024 * 1024)
#define PHYS_SDRAM_2 CSD1_BASE_ADDR
#define PHYS_SDRAM_2_SIZE (512 * 1024 * 1024)
#define iomem_valid_addr(addr, size) \
((addr >= PHYS_SDRAM_1 && addr <= (PHYS_SDRAM_1 + PHYS_SDRAM_1_SIZE)) \
|| (addr >= PHYS_SDRAM_2 && addr <= (PHYS_SDRAM_2 + PHYS_SDRAM_2_SIZE)))
#define CONFIG_SYS_NO_FLASH
/* Monitor at beginning of flash */
#define <API key>
/* #define <API key> */
#define <API key> (8 * 1024)
#define CONFIG_ENV_SIZE <API key>
#if defined(<API key>)
#define <API key> 1
#define CONFIG_ENV_OFFSET 0x200000
#elif defined(<API key>)
#define <API key> 1
#define CONFIG_ENV_OFFSET (768 * 1024)
#elif defined(<API key>)
#define <API key> 1
#define CONFIG_SATA_ENV_DEV 0
#define CONFIG_ENV_OFFSET (768 * 1024)
#elif defined(<API key>)
#define <API key> 1
#define CONFIG_ENV_SPI_CS 1
#define CONFIG_ENV_OFFSET (768 * 1024)
#else
#define <API key> 1
#endif
#endif /* __CONFIG_H */
|
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/kernel_stat.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/vmpressure.h>
#include <linux/vmstat.h>
#include <linux/file.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/buffer_head.h> /* for try_to_release_page(),
<API key> */
#include <linux/mm_inline.h>
#include <linux/backing-dev.h>
#include <linux/rmap.h>
#include <linux/topology.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/compaction.h>
#include <linux/notifier.h>
#include <linux/rwsem.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/memcontrol.h>
#include <linux/delayacct.h>
#include <linux/sysctl.h>
#include <linux/oom.h>
#include <linux/prefetch.h>
#include <linux/printk.h>
#include <asm/tlbflush.h>
#include <asm/div64.h>
#include <linux/swapops.h>
#include <linux/balloon_compaction.h>
#include "internal.h"
#define CREATE_TRACE_POINTS
#include <trace/events/vmscan.h>
struct scan_control {
/* How many pages shrink_list() should reclaim */
unsigned long nr_to_reclaim;
/* This context's GFP mask */
gfp_t gfp_mask;
/* Allocation order */
int order;
/*
* Nodemask of nodes allowed by the caller. If NULL, all nodes
* are scanned.
*/
nodemask_t *nodemask;
/*
* The memory cgroup that hit its limit and as a result is the
* primary target of this reclaim invocation.
*/
struct mem_cgroup *target_mem_cgroup;
/* Scan (total_size >> priority) pages at once */
int priority;
unsigned int may_writepage:1;
/* Can mapped pages be reclaimed? */
unsigned int may_unmap:1;
/* Can pages be swapped as part of reclaim? */
unsigned int may_swap:1;
/* Can cgroups be reclaimed below their normal consumption range? */
unsigned int may_thrash:1;
unsigned int hibernation_mode:1;
/* One of the zones is ready for compaction */
unsigned int compaction_ready:1;
/* Incremented by the number of inactive pages that were scanned */
unsigned long nr_scanned;
/* Number of pages freed so far during a call to shrink_zones() */
unsigned long nr_reclaimed;
};
#define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
#ifdef ARCH_HAS_PREFETCH
#define <API key>(_page, _base, _field) \
do { \
if ((_page)->lru.prev != _base) { \
struct page *prev; \
\
prev = lru_to_page(&(_page->lru)); \
prefetch(&prev->_field); \
} \
} while (0)
#else
#define <API key>(_page, _base, _field) do { } while (0)
#endif
#ifdef ARCH_HAS_PREFETCHW
#define <API key>(_page, _base, _field) \
do { \
if ((_page)->lru.prev != _base) { \
struct page *prev; \
\
prev = lru_to_page(&(_page->lru)); \
prefetchw(&prev->_field); \
} \
} while (0)
#else
#define <API key>(_page, _base, _field) do { } while (0)
#endif
/*
* From 0 .. 100. Higher means more swappy.
*/
int vm_swappiness = 60;
/*
* The total number of pages which are beyond the high watermark within all
* zones.
*/
unsigned long vm_total_pages;
static LIST_HEAD(shrinker_list);
static DECLARE_RWSEM(shrinker_rwsem);
#ifdef CONFIG_MEMCG
static bool global_reclaim(struct scan_control *sc)
{
return !sc->target_mem_cgroup;
}
/**
* sane_reclaim - is the usual dirty throttling mechanism operational?
* @sc: scan_control in question
*
* The normal page dirty throttling mechanism in balance_dirty_pages() is
* completely broken with the legacy memcg and direct stalling in
* shrink_page_list() is used for throttling instead, which lacks all the
* niceties such as fairness, adaptive pausing, bandwidth proportional
* allocation and configurability.
*
* This function tests whether the vmscan currently in progress can assume
* that the normal dirty throttling mechanism is operational.
*/
static bool sane_reclaim(struct scan_control *sc)
{
struct mem_cgroup *memcg = sc->target_mem_cgroup;
if (!memcg)
return true;
#ifdef <API key>
if (cgroup_on_dfl(mem_cgroup_css(memcg)->cgroup))
return true;
#endif
return false;
}
#else
static bool global_reclaim(struct scan_control *sc)
{
return true;
}
static bool sane_reclaim(struct scan_control *sc)
{
return true;
}
#endif
static unsigned long <API key>(struct zone *zone)
{
int nr;
nr = zone_page_state(zone, NR_ACTIVE_FILE) +
zone_page_state(zone, NR_INACTIVE_FILE);
if (get_nr_swap_pages() > 0)
nr += zone_page_state(zone, NR_ACTIVE_ANON) +
zone_page_state(zone, NR_INACTIVE_ANON);
return nr;
}
bool zone_reclaimable(struct zone *zone)
{
return zone_page_state(zone, NR_PAGES_SCANNED) <
<API key>(zone) * 6;
}
static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
{
if (!mem_cgroup_disabled())
return <API key>(lruvec, lru);
return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
}
/*
* Add a shrinker callback to be called from the vm.
*/
int register_shrinker(struct shrinker *shrinker)
{
size_t size = sizeof(*shrinker->nr_deferred);
/*
* If we only have one possible node in the system anyway, save
* ourselves the trouble and disable NUMA aware behavior. This way we
* will save memory and some small loop time later.
*/
if (nr_node_ids == 1)
shrinker->flags &= ~SHRINKER_NUMA_AWARE;
if (shrinker->flags & SHRINKER_NUMA_AWARE)
size *= nr_node_ids;
shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
if (!shrinker->nr_deferred)
return -ENOMEM;
down_write(&shrinker_rwsem);
list_add_tail(&shrinker->list, &shrinker_list);
up_write(&shrinker_rwsem);
return 0;
}
EXPORT_SYMBOL(register_shrinker);
/*
* Remove one
*/
void unregister_shrinker(struct shrinker *shrinker)
{
down_write(&shrinker_rwsem);
list_del(&shrinker->list);
up_write(&shrinker_rwsem);
kfree(shrinker->nr_deferred);
}
EXPORT_SYMBOL(unregister_shrinker);
#define SHRINK_BATCH 128
static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
struct shrinker *shrinker,
unsigned long nr_scanned,
unsigned long nr_eligible)
{
unsigned long freed = 0;
unsigned long long delta;
long total_scan;
long freeable;
long nr;
long new_nr;
int nid = shrinkctl->nid;
long batch_size = shrinker->batch ? shrinker->batch
: SHRINK_BATCH;
freeable = shrinker->count_objects(shrinker, shrinkctl);
if (freeable == 0)
return 0;
/*
* copy the current shrinker scan count into a local variable
* and zero it so that other concurrent shrinker invocations
* don't also do this scanning work.
*/
nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
total_scan = nr;
delta = (4 * nr_scanned) / shrinker->seeks;
delta *= freeable;
do_div(delta, nr_eligible + 1);
total_scan += delta;
if (total_scan < 0) {
pr_err("shrink_slab: %pF negative objects to delete nr=%ld\n",
shrinker->scan_objects, total_scan);
total_scan = freeable;
}
/*
* We need to avoid excessive windup on filesystem shrinkers
* due to large numbers of GFP_NOFS allocations causing the
* shrinkers to return -1 all the time. This results in a large
* nr being built up so when a shrink that can do some work
* comes along it empties the entire cache due to nr >>>
* freeable. This is bad for sustaining a working set in
* memory.
*
* Hence only allow the shrinker to scan the entire cache when
* a large delta change is calculated directly.
*/
if (delta < freeable / 4)
total_scan = min(total_scan, freeable / 2);
/*
* Avoid risking looping forever due to too large nr value:
* never try to free more than twice the estimate number of
* freeable entries.
*/
if (total_scan > freeable * 2)
total_scan = freeable * 2;
<API key>(shrinker, shrinkctl, nr,
nr_scanned, nr_eligible,
freeable, delta, total_scan);
/*
* Normally, we should not scan less than batch_size objects in one
* pass to avoid too frequent shrinker calls, but if the slab has less
* than batch_size objects in total and we are really tight on memory,
* we will try to reclaim all available objects, otherwise we can end
* up failing allocations although there are plenty of reclaimable
* objects spread over several slabs with usage less than the
* batch_size.
*
* We detect the "tight on memory" situations by looking at the total
* number of objects we want to scan (total_scan). If it is greater
* than the total number of objects on slab (freeable), we must be
* scanning at high prio and therefore should try to reclaim as much as
* possible.
*/
while (total_scan >= batch_size ||
total_scan >= freeable) {
unsigned long ret;
unsigned long nr_to_scan = min(batch_size, total_scan);
shrinkctl->nr_to_scan = nr_to_scan;
ret = shrinker->scan_objects(shrinker, shrinkctl);
if (ret == SHRINK_STOP)
break;
freed += ret;
count_vm_events(SLABS_SCANNED, nr_to_scan);
total_scan -= nr_to_scan;
cond_resched();
}
/*
* move the unused scan count back into the shrinker in a
* manner that handles concurrent updates. If we exhausted the
* scan, there is no need to do an update.
*/
if (total_scan > 0)
new_nr = <API key>(total_scan,
&shrinker->nr_deferred[nid]);
else
new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
<API key>(shrinker, nid, freed, nr, new_nr, total_scan);
return freed;
}
/**
* shrink_slab - shrink slab caches
* @gfp_mask: allocation context
* @nid: node whose slab caches to target
* @memcg: memory cgroup whose slab caches to target
* @nr_scanned: pressure numerator
* @nr_eligible: pressure denominator
*
* Call the shrink functions to age shrinkable caches.
*
* @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
* unaware shrinkers will receive a node id of 0 instead.
*
* @memcg specifies the memory cgroup to target. If it is not NULL,
* only shrinkers with <API key> set will be called to scan
* objects from the memory cgroup specified. Otherwise all shrinkers
* are called, and memcg aware shrinkers are supposed to scan the
* global list then.
*
* @nr_scanned and @nr_eligible form a ratio that indicate how much of
* the available objects should be scanned. Page reclaim for example
* passes the number of pages scanned and the number of pages on the
* LRU lists that it considered on @nid, plus a bias in @nr_scanned
* when it encountered mapped pages. The ratio is further biased by
* the ->seeks setting of the shrink function, which indicates the
* cost to recreate an object relative to that of an LRU page.
*
* Returns the number of reclaimed slab objects.
*/
static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
struct mem_cgroup *memcg,
unsigned long nr_scanned,
unsigned long nr_eligible)
{
struct shrinker *shrinker;
unsigned long freed = 0;
if (memcg && !<API key>(memcg))
return 0;
if (nr_scanned == 0)
nr_scanned = SWAP_CLUSTER_MAX;
if (!down_read_trylock(&shrinker_rwsem)) {
/*
* If we would return 0, our callers would understand that we
* have nothing else to shrink and give up trying. By returning
* 1 we keep it going and assume we'll be able to shrink next
* time.
*/
freed = 1;
goto out;
}
list_for_each_entry(shrinker, &shrinker_list, list) {
struct shrink_control sc = {
.gfp_mask = gfp_mask,
.nid = nid,
.memcg = memcg,
};
if (memcg && !(shrinker->flags & <API key>))
continue;
if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
sc.nid = 0;
freed += do_shrink_slab(&sc, shrinker, nr_scanned, nr_eligible);
}
up_read(&shrinker_rwsem);
out:
cond_resched();
return freed;
}
void drop_slab_node(int nid)
{
unsigned long freed;
do {
struct mem_cgroup *memcg = NULL;
freed = 0;
do {
freed += shrink_slab(GFP_KERNEL, nid, memcg,
1000, 1000);
} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
} while (freed > 10);
}
void drop_slab(void)
{
int nid;
<API key>(nid)
drop_slab_node(nid);
}
static inline int <API key>(struct page *page)
{
/*
* A freeable page cache page is referenced only by the caller
* that isolated the page, the page cache radix tree and
* optional buffer heads at page->private.
*/
return page_count(page) - page_has_private(page) == 2;
}
static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
{
if (current->flags & PF_SWAPWRITE)
return 1;
if (!<API key>(inode))
return 1;
if (inode_to_bdi(inode) == current->backing_dev_info)
return 1;
return 0;
}
/*
* We detected a synchronous write error writing a page out. Probably
* -ENOSPC. We need to propagate that into the address_space for a subsequent
* fsync(), msync() or close().
*
* The tricky part is that after writepage we cannot touch the mapping: nothing
* prevents it from being freed up. But we have a ref on the page and once
* that page is locked, the mapping is pinned.
*
* We're allowed to run sleeping lock_page() here because we know the caller has
* __GFP_FS.
*/
static void handle_write_error(struct address_space *mapping,
struct page *page, int error)
{
lock_page(page);
if (page_mapping(page) == mapping)
mapping_set_error(mapping, error);
unlock_page(page);
}
/* possible outcome of pageout() */
typedef enum {
/* failed to write page out, page is locked */
PAGE_KEEP,
/* move page to the active list, page is locked */
PAGE_ACTIVATE,
/* page has been sent to the disk successfully, page is unlocked */
PAGE_SUCCESS,
/* page is clean and locked */
PAGE_CLEAN,
} pageout_t;
/*
* pageout is called by shrink_page_list() for each dirty page.
* Calls ->writepage().
*/
static pageout_t pageout(struct page *page, struct address_space *mapping,
struct scan_control *sc)
{
/*
* If the page is dirty, only perform writeback if that write
* will be non-blocking. To prevent this allocation from being
* stalled by pagecache activity. But note that there may be
* stalls if we need to run get_block(). We could test
* PagePrivate for that.
*
* If this process is currently in <API key>() against
* this page's queue, we can perform writeback even if that
* will block.
*
* If the page is swapcache, write it back even if that would
* block, for some throttling. This happens by accident, because
* <API key> is bust: it doesn't reflect the
* congestion state of the swapdevs. Easy to fix, if needed.
*/
if (!<API key>(page))
return PAGE_KEEP;
if (!mapping) {
/*
* Some data journaling orphaned pages can have
* page->mapping == NULL while being dirty with clean buffers.
*/
if (page_has_private(page)) {
if (try_to_free_buffers(page)) {
ClearPageDirty(page);
pr_info("%s: orphaned page\n", __func__);
return PAGE_CLEAN;
}
}
return PAGE_KEEP;
}
if (mapping->a_ops->writepage == NULL)
return PAGE_ACTIVATE;
if (!may_write_to_inode(mapping->host, sc))
return PAGE_KEEP;
if (<API key>(page)) {
int res;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = SWAP_CLUSTER_MAX,
.range_start = 0,
.range_end = LLONG_MAX,
.for_reclaim = 1,
};
SetPageReclaim(page);
res = mapping->a_ops->writepage(page, &wbc);
if (res < 0)
handle_write_error(mapping, page, res);
if (res == <API key>) {
ClearPageReclaim(page);
return PAGE_ACTIVATE;
}
if (!PageWriteback(page)) {
/* synchronous write or broken a_ops? */
ClearPageReclaim(page);
}
<API key>(page, trace_reclaim_flags(page));
inc_zone_page_state(page, NR_VMSCAN_WRITE);
return PAGE_SUCCESS;
}
return PAGE_CLEAN;
}
/*
* Same as remove_mapping, but if the page is removed from the mapping, it
* gets returned with a refcount of 0.
*/
static int __remove_mapping(struct address_space *mapping, struct page *page,
bool reclaimed)
{
unsigned long flags;
struct mem_cgroup *memcg;
BUG_ON(!PageLocked(page));
BUG_ON(mapping != page_mapping(page));
memcg = <API key>(page);
spin_lock_irqsave(&mapping->tree_lock, flags);
/*
* The non racy check for a busy page.
*
* Must be careful with the order of the tests. When someone has
* a ref to the page, it may be possible that they dirty it then
* drop the reference. So if PageDirty is tested before page_count
* here, then the following race may occur:
*
* get_user_pages(&page);
* [user mapping goes away]
* write_to(page);
* !PageDirty(page) [good]
* SetPageDirty(page);
* put_page(page);
* !page_count(page) [good, discard it]
*
* [oops, our write_to data is lost]
*
* Reversing the order of the tests ensures such a situation cannot
* escape unnoticed. The smp_rmb is needed to ensure the page->flags
* load is not satisfied before that of page->_count.
*
* Note that if SetPageDirty is always performed via set_page_dirty,
* and thus under tree_lock, then this ordering is not required.
*/
if (!page_freeze_refs(page, 2))
goto cannot_free;
/* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
if (unlikely(PageDirty(page))) {
page_unfreeze_refs(page, 2);
goto cannot_free;
}
if (PageSwapCache(page)) {
swp_entry_t swap = { .val = page_private(page) };
mem_cgroup_swapout(page, swap);
<API key>(page);
<API key>(&mapping->tree_lock, flags);
<API key>(memcg);
swapcache_free(swap);
} else {
void (*freepage)(struct page *);
void *shadow = NULL;
freepage = mapping->a_ops->freepage;
/*
* Remember a shadow entry for reclaimed file cache in
* order to detect refaults, thus thrashing, later on.
*
* But don't store shadows in an address space that is
* already exiting. This is not just an optizimation,
* inode reclaim needs to empty out the radix tree or
* the nodes are lost. Don't plant shadows behind its
* back.
*/
if (reclaimed && page_is_file_cache(page) &&
!mapping_exiting(mapping))
shadow = workingset_eviction(mapping, page);
<API key>(page, shadow, memcg);
<API key>(&mapping->tree_lock, flags);
<API key>(memcg);
if (freepage != NULL)
freepage(page);
}
return 1;
cannot_free:
<API key>(&mapping->tree_lock, flags);
<API key>(memcg);
return 0;
}
/*
* Attempt to detach a locked page from its ->mapping. If it is dirty or if
* someone else has a ref on the page, abort and return 0. If it was
* successfully detached, return 1. Assumes the caller has a single ref on
* this page.
*/
int remove_mapping(struct address_space *mapping, struct page *page)
{
if (__remove_mapping(mapping, page, false)) {
/*
* Unfreezing the refcount with 1 rather than 2 effectively
* drops the pagecache ref for us without requiring another
* atomic operation.
*/
page_unfreeze_refs(page, 1);
return 1;
}
return 0;
}
/**
* putback_lru_page - put previously isolated page onto appropriate LRU list
* @page: page to be put back to appropriate lru list
*
* Add previously isolated @page to appropriate LRU list.
* Page may still be unevictable for other reasons.
*
* lru_lock must not be held, interrupts must be enabled.
*/
void putback_lru_page(struct page *page)
{
bool is_unevictable;
int was_unevictable = PageUnevictable(page);
VM_BUG_ON_PAGE(PageLRU(page), page);
redo:
<API key>(page);
if (page_evictable(page)) {
/*
* For evictable pages, we can use the cache.
* In event of a race, worst case is we end up with an
* unevictable page on [in]active list.
* We know how to handle that.
*/
is_unevictable = false;
lru_cache_add(page);
} else {
/*
* Put unevictable pages directly on zone's unevictable
* list.
*/
is_unevictable = true;
<API key>(page);
/*
* When racing with an mlock or AS_UNEVICTABLE clearing
* (page is unlocked) make sure that if the other thread
* does not observe our setting of PG_lru and fails
* isolation/<API key>,
* we see PG_mlocked/AS_UNEVICTABLE cleared below and move
* the page back to the evictable list.
*
* The other side is <API key>() or shmem_lock().
*/
smp_mb();
}
/*
* page's status can change while we move it among lru. If an evictable
* page is on unevictable list, it never be freed. To avoid that,
* check after we added it to the list, again.
*/
if (is_unevictable && page_evictable(page)) {
if (!isolate_lru_page(page)) {
put_page(page);
goto redo;
}
/* This means someone else dropped this page from LRU
* So, it will be freed or putback to LRU again. There is
* nothing to do here.
*/
}
if (was_unevictable && !is_unevictable)
count_vm_event(<API key>);
else if (!was_unevictable && is_unevictable)
count_vm_event(<API key>);
put_page(page); /* drop ref from isolate */
}
enum page_references {
PAGEREF_RECLAIM,
<API key>,
PAGEREF_KEEP,
PAGEREF_ACTIVATE,
};
static enum page_references <API key>(struct page *page,
struct scan_control *sc)
{
int referenced_ptes, referenced_page;
unsigned long vm_flags;
referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
&vm_flags);
referenced_page = <API key>(page);
/*
* Mlock lost the isolation race with us. Let try_to_unmap()
* move the page to the unevictable list.
*/
if (vm_flags & VM_LOCKED)
return PAGEREF_RECLAIM;
if (referenced_ptes) {
if (PageSwapBacked(page))
return PAGEREF_ACTIVATE;
/*
* All mapped pages start out with page table
* references from the instantiating fault, so we need
* to look twice if a mapped file page is used more
* than once.
*
* Mark it and spare it for another trip around the
* inactive list. Another page table reference will
* lead to its activation.
*
* Note: the mark is set for activated pages as well
* so that recently deactivated but used pages are
* quickly recovered.
*/
SetPageReferenced(page);
if (referenced_page || referenced_ptes > 1)
return PAGEREF_ACTIVATE;
/*
* Activate file-backed executable pages after first usage.
*/
if (vm_flags & VM_EXEC)
return PAGEREF_ACTIVATE;
return PAGEREF_KEEP;
}
/* Reclaim if clean, defer dirty pages to writeback */
if (referenced_page && !PageSwapBacked(page))
return <API key>;
return PAGEREF_RECLAIM;
}
/* Check if a page is dirty or under writeback */
static void <API key>(struct page *page,
bool *dirty, bool *writeback)
{
struct address_space *mapping;
/*
* Anonymous pages are not handled by flushers and must be written
* from reclaim context. Do not stall reclaim based on them
*/
if (!page_is_file_cache(page)) {
*dirty = false;
*writeback = false;
return;
}
/* By default assume that the page flags are accurate */
*dirty = PageDirty(page);
*writeback = PageWriteback(page);
/* Verify dirty/writeback state if the filesystem supports it */
if (!page_has_private(page))
return;
mapping = page_mapping(page);
if (mapping && mapping->a_ops->is_dirty_writeback)
mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
}
/*
* shrink_page_list() returns the number of reclaimed pages
*/
static unsigned long shrink_page_list(struct list_head *page_list,
struct zone *zone,
struct scan_control *sc,
enum ttu_flags ttu_flags,
unsigned long *ret_nr_dirty,
unsigned long *<API key>,
unsigned long *ret_nr_congested,
unsigned long *ret_nr_writeback,
unsigned long *ret_nr_immediate,
bool force_reclaim)
{
LIST_HEAD(ret_pages);
LIST_HEAD(free_pages);
int pgactivate = 0;
unsigned long nr_unqueued_dirty = 0;
unsigned long nr_dirty = 0;
unsigned long nr_congested = 0;
unsigned long nr_reclaimed = 0;
unsigned long nr_writeback = 0;
unsigned long nr_immediate = 0;
cond_resched();
while (!list_empty(page_list)) {
struct address_space *mapping;
struct page *page;
int may_enter_fs;
enum page_references references = <API key>;
bool dirty, writeback;
cond_resched();
page = lru_to_page(page_list);
list_del(&page->lru);
if (!trylock_page(page))
goto keep;
VM_BUG_ON_PAGE(PageActive(page), page);
VM_BUG_ON_PAGE(page_zone(page) != zone, page);
sc->nr_scanned++;
if (unlikely(!page_evictable(page)))
goto cull_mlocked;
if (!sc->may_unmap && page_mapped(page))
goto keep_locked;
/* Double the slab pressure for mapped and swapcache pages */
if (page_mapped(page) || PageSwapCache(page))
sc->nr_scanned++;
may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
(PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
/*
* The number of dirty pages determines if a zone is marked
* reclaim_congested which affects wait_iff_congested. kswapd
* will stall and start writing pages if the tail of the LRU
* is all dirty unqueued pages.
*/
<API key>(page, &dirty, &writeback);
if (dirty || writeback)
nr_dirty++;
if (dirty && !writeback)
nr_unqueued_dirty++;
/*
* Treat this page as congested if the underlying BDI is or if
* pages are cycling through the LRU so quickly that the
* pages marked for immediate reclaim are making it to the
* end of the LRU a second time.
*/
mapping = page_mapping(page);
if (((dirty || writeback) && mapping &&
<API key>(mapping->host)) ||
(writeback && PageReclaim(page)))
nr_congested++;
/*
* If a page at the tail of the LRU is under writeback, there
* are three cases to consider.
*
* 1) If reclaim is encountering an excessive number of pages
* under writeback and this page is both under writeback and
* PageReclaim then it indicates that pages are being queued
* for IO but are being recycled through the LRU before the
* IO can complete. Waiting on the page itself risks an
* indefinite stall if it is impossible to writeback the
* page due to IO error or disconnected storage so instead
* note that the LRU is being scanned too quickly and the
* caller can stall after page list has been processed.
*
* 2) Global or new memcg reclaim encounters a page that is
* not marked for immediate reclaim, or the caller does not
* have __GFP_FS (or __GFP_IO if it's simply going to swap,
* not to fs). In this case mark the page for immediate
* reclaim and continue scanning.
*
* Require may_enter_fs because we would wait on fs, which
* may not have submitted IO yet. And the loop driver might
* enter reclaim, and deadlock if it waits on a page for
* which it is needed to do the write (loop masks off
* __GFP_IO|__GFP_FS for this reason); but more thought
* would probably show more reasons.
*
* 3) Legacy memcg encounters a page that is not already marked
* PageReclaim. memcg does not have any dirty pages
* throttling so we could easily OOM just because too many
* pages are in writeback and there is nothing else to
* reclaim. Wait for the writeback to complete.
*/
if (PageWriteback(page)) {
/* Case 1 above */
if (current_is_kswapd() &&
PageReclaim(page) &&
test_bit(ZONE_WRITEBACK, &zone->flags)) {
nr_immediate++;
goto keep_locked;
/* Case 2 above */
} else if (sane_reclaim(sc) ||
!PageReclaim(page) || !may_enter_fs) {
/*
* This is slightly racy - end_page_writeback()
* might have just cleared PageReclaim, then
* setting PageReclaim here end up interpreted
* as PageReadahead - but that does not matter
* enough to care. What we do want is for this
* page to have PageReclaim set next time memcg
* reclaim reaches the tests above, so it will
* then <API key>() to avoid OOM;
* and it's also appropriate in global reclaim.
*/
SetPageReclaim(page);
nr_writeback++;
goto keep_locked;
/* Case 3 above */
} else {
<API key>(page);
}
}
if (!force_reclaim)
references = <API key>(page, sc);
switch (references) {
case PAGEREF_ACTIVATE:
goto activate_locked;
case PAGEREF_KEEP:
goto keep_locked;
case PAGEREF_RECLAIM:
case <API key>:
; /* try to reclaim the page below */
}
/*
* Anonymous process memory has backing store?
* Try to allocate it some swap space here.
*/
if (PageAnon(page) && !PageSwapCache(page)) {
if (!(sc->gfp_mask & __GFP_IO))
goto keep_locked;
if (!add_to_swap(page, page_list))
goto activate_locked;
may_enter_fs = 1;
/* Adding to swap updated mapping */
mapping = page_mapping(page);
}
/*
* The page is mapped into the page tables of one or more
* processes. Try to unmap it here.
*/
if (page_mapped(page) && mapping) {
switch (try_to_unmap(page, ttu_flags)) {
case SWAP_FAIL:
goto activate_locked;
case SWAP_AGAIN:
goto keep_locked;
case SWAP_MLOCK:
goto cull_mlocked;
case SWAP_SUCCESS:
; /* try to free the page below */
}
}
if (PageDirty(page)) {
/*
* Only kswapd can writeback filesystem pages to
* avoid risk of stack overflow but only writeback
* if many dirty pages have been encountered.
*/
if (page_is_file_cache(page) &&
(!current_is_kswapd() ||
!test_bit(ZONE_DIRTY, &zone->flags))) {
/*
* Immediately reclaim when written back.
* Similar in principal to deactivate_page()
* except we already have the page isolated
* and know it's dirty
*/
inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
SetPageReclaim(page);
goto keep_locked;
}
if (references == <API key>)
goto keep_locked;
if (!may_enter_fs)
goto keep_locked;
if (!sc->may_writepage)
goto keep_locked;
/* Page is dirty, try to write it out here */
switch (pageout(page, mapping, sc)) {
case PAGE_KEEP:
goto keep_locked;
case PAGE_ACTIVATE:
goto activate_locked;
case PAGE_SUCCESS:
if (PageWriteback(page))
goto keep;
if (PageDirty(page))
goto keep;
/*
* A synchronous write - probably a ramdisk. Go
* ahead and try to reclaim the page.
*/
if (!trylock_page(page))
goto keep;
if (PageDirty(page) || PageWriteback(page))
goto keep_locked;
mapping = page_mapping(page);
case PAGE_CLEAN:
; /* try to free the page below */
}
}
/*
* If the page has buffers, try to free the buffer mappings
* associated with this page. If we succeed we try to free
* the page as well.
*
* We do this even if the page is PageDirty().
* try_to_release_page() does not perform I/O, but it is
* possible for a page to have PageDirty set, but it is actually
* clean (all its buffers are clean). This happens if the
* buffers were written out directly, with submit_bh(). ext3
* will do this, as well as the blockdev mapping.
* try_to_release_page() will discover that cleanness and will
* drop the buffers and mark the page clean - it can be freed.
*
* Rarely, pages can have buffers and no ->mapping. These are
* the pages which were not successfully invalidated in
* <API key>(). We try to drop those buffers here
* and if that worked, and the page is no longer mapped into
* process address space (page_count == 1) it can be freed.
* Otherwise, leave the page on the LRU so it is swappable.
*/
if (page_has_private(page)) {
if (!try_to_release_page(page, sc->gfp_mask))
goto activate_locked;
if (!mapping && page_count(page) == 1) {
unlock_page(page);
if (put_page_testzero(page))
goto free_it;
else {
/*
* rare race with speculative reference.
* the speculative reference will free
* this page shortly, so we may
* increment nr_reclaimed here (and
* leave it off the LRU).
*/
nr_reclaimed++;
continue;
}
}
}
if (!mapping || !__remove_mapping(mapping, page, true))
goto keep_locked;
/*
* At this point, we have no other references and there is
* no way to pick any more up (removed from LRU, removed
* from pagecache). Can use non-atomic bitops now (and
* we obviously don't have to worry about waking up a process
* waiting on the page lock, because there are no references.
*/
__clear_page_locked(page);
free_it:
nr_reclaimed++;
/*
* Is there need to periodically free_page_list? It would
* appear not as the counts should be low
*/
list_add(&page->lru, &free_pages);
continue;
cull_mlocked:
if (PageSwapCache(page))
try_to_free_swap(page);
unlock_page(page);
list_add(&page->lru, &ret_pages);
continue;
activate_locked:
/* Not a candidate for swapping, so reclaim swap space. */
if (PageSwapCache(page) && vm_swap_full())
try_to_free_swap(page);
VM_BUG_ON_PAGE(PageActive(page), page);
SetPageActive(page);
pgactivate++;
keep_locked:
unlock_page(page);
keep:
list_add(&page->lru, &ret_pages);
VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
}
<API key>(&free_pages);
<API key>(&free_pages, true);
list_splice(&ret_pages, page_list);
count_vm_events(PGACTIVATE, pgactivate);
*ret_nr_dirty += nr_dirty;
*ret_nr_congested += nr_congested;
*<API key> += nr_unqueued_dirty;
*ret_nr_writeback += nr_writeback;
*ret_nr_immediate += nr_immediate;
return nr_reclaimed;
}
unsigned long <API key>(struct zone *zone,
struct list_head *page_list)
{
struct scan_control sc = {
.gfp_mask = GFP_KERNEL,
.priority = DEF_PRIORITY,
.may_unmap = 1,
};
unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
struct page *page, *next;
LIST_HEAD(clean_pages);
<API key>(page, next, page_list, lru) {
if (page_is_file_cache(page) && !PageDirty(page) &&
!<API key>(page)) {
ClearPageActive(page);
list_move(&page->lru, &clean_pages);
}
}
ret = shrink_page_list(&clean_pages, zone, &sc,
TTU_UNMAP|TTU_IGNORE_ACCESS,
&dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
list_splice(&clean_pages, page_list);
mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
return ret;
}
/*
* Attempt to remove the specified page from its LRU. Only take this page
* if it is of the appropriate PageActive status. Pages which are being
* freed elsewhere are also ignored.
*
* page: page to consider
* mode: one of the LRU isolation modes defined above
*
* returns 0 on success, -ve errno on failure.
*/
int __isolate_lru_page(struct page *page, isolate_mode_t mode)
{
int ret = -EINVAL;
/* Only take pages on the LRU. */
if (!PageLRU(page))
return ret;
/* Compaction should not handle unevictable pages but CMA can do so */
if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
return ret;
ret = -EBUSY;
/*
* To minimise LRU disruption, the caller can indicate that it only
* wants to isolate pages it will be able to operate on without
* blocking - clean pages for the most part.
*
* ISOLATE_CLEAN means that only clean pages should be isolated. This
* is used by reclaim when it is cannot write to backing storage
*
* <API key> is used to indicate that it only wants to pages
* that it is possible to migrate without blocking
*/
if (mode & (ISOLATE_CLEAN|<API key>)) {
/* All the caller can do on PageWriteback is block */
if (PageWriteback(page))
return ret;
if (PageDirty(page)) {
struct address_space *mapping;
/* ISOLATE_CLEAN means only clean pages */
if (mode & ISOLATE_CLEAN)
return ret;
/*
* Only pages without mappings or that have a
* ->migratepage callback are possible to migrate
* without blocking
*/
mapping = page_mapping(page);
if (mapping && !mapping->a_ops->migratepage)
return ret;
}
}
if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
return ret;
if (likely(<API key>(page))) {
/*
* Be careful not to clear PageLRU until after we're
* sure the page is not being freed elsewhere -- the
* page release code relies on it.
*/
ClearPageLRU(page);
ret = 0;
}
return ret;
}
/*
* zone->lru_lock is heavily contended. Some of the functions that
* shrink the lists perform better by taking out a batch of pages
* and working on them outside the LRU lock.
*
* For pagecache intensive workloads, this function is the hottest
* spot in the kernel (apart from copy_*_user functions).
*
* Appropriate locks must be held before calling this function.
*
* @nr_to_scan: The number of pages to look through on the list.
* @lruvec: The LRU vector to pull pages from.
* @dst: The temp list to put pages on to.
* @nr_scanned: The number of pages that were scanned.
* @sc: The scan_control struct for this reclaim session
* @mode: One of the LRU isolation modes
* @lru: LRU list id for isolating
*
* returns how many pages were moved onto *@dst.
*/
static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
struct lruvec *lruvec, struct list_head *dst,
unsigned long *nr_scanned, struct scan_control *sc,
isolate_mode_t mode, enum lru_list lru)
{
struct list_head *src = &lruvec->lists[lru];
unsigned long nr_taken = 0;
unsigned long scan;
for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
struct page *page;
int nr_pages;
page = lru_to_page(src);
<API key>(page, src, flags);
VM_BUG_ON_PAGE(!PageLRU(page), page);
switch (__isolate_lru_page(page, mode)) {
case 0:
nr_pages = hpage_nr_pages(page);
<API key>(lruvec, lru, -nr_pages);
list_move(&page->lru, dst);
nr_taken += nr_pages;
break;
case -EBUSY:
/* else it is being freed elsewhere */
list_move(&page->lru, src);
continue;
default:
BUG();
}
}
*nr_scanned = scan;
<API key>(sc->order, nr_to_scan, scan,
nr_taken, mode, is_file_lru(lru));
return nr_taken;
}
/**
* isolate_lru_page - tries to isolate a page from its LRU list
* @page: page to isolate from its LRU list
*
* Isolates a @page from an LRU list, clears PageLRU and adjusts the
* vmstat statistic corresponding to whatever LRU list the page was on.
*
* Returns 0 if the page was removed from an LRU list.
* Returns -EBUSY if the page was not on an LRU list.
*
* The returned page will have PageLRU() cleared. If it was found on
* the active list, it will have PageActive set. If it was found on
* the unevictable list, it will have the PageUnevictable bit set. That flag
* may need to be cleared by the caller before letting the page go.
*
* The vmstat statistic corresponding to the list on which the page was
* found will be decremented.
*
* Restrictions:
* (1) Must be called with an elevated refcount on the page. This is a
* fundamentnal difference from isolate_lru_pages (which is called
* without a stable reference).
* (2) the lru_lock must not be held.
* (3) interrupts must be enabled.
*/
int isolate_lru_page(struct page *page)
{
int ret = -EBUSY;
VM_BUG_ON_PAGE(!page_count(page), page);
if (PageLRU(page)) {
struct zone *zone = page_zone(page);
struct lruvec *lruvec;
spin_lock_irq(&zone->lru_lock);
lruvec = <API key>(page, zone);
if (PageLRU(page)) {
int lru = page_lru(page);
get_page(page);
ClearPageLRU(page);
<API key>(page, lruvec, lru);
ret = 0;
}
spin_unlock_irq(&zone->lru_lock);
}
return ret;
}
/*
* A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
* then get resheduled. When there are massive number of tasks doing page
* allocation, such sleeping direct reclaimers may keep piling up on each CPU,
* the LRU list will go small and be scanned faster than necessary, leading to
* unnecessary swapping, thrashing and OOM.
*/
static int too_many_isolated(struct zone *zone, int file,
struct scan_control *sc)
{
unsigned long inactive, isolated;
if (current_is_kswapd())
return 0;
if (!sane_reclaim(sc))
return 0;
if (file) {
inactive = zone_page_state(zone, NR_INACTIVE_FILE);
isolated = zone_page_state(zone, NR_ISOLATED_FILE);
} else {
inactive = zone_page_state(zone, NR_INACTIVE_ANON);
isolated = zone_page_state(zone, NR_ISOLATED_ANON);
}
/*
* GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
* won't get blocked by normal direct-reclaimers, forming a circular
* deadlock.
*/
if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
inactive >>= 3;
return isolated > inactive;
}
static noinline_for_stack void
<API key>(struct lruvec *lruvec, struct list_head *page_list)
{
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
struct zone *zone = lruvec_zone(lruvec);
LIST_HEAD(pages_to_free);
/*
* Put back any unfreeable pages.
*/
while (!list_empty(page_list)) {
struct page *page = lru_to_page(page_list);
int lru;
VM_BUG_ON_PAGE(PageLRU(page), page);
list_del(&page->lru);
if (unlikely(!page_evictable(page))) {
spin_unlock_irq(&zone->lru_lock);
putback_lru_page(page);
spin_lock_irq(&zone->lru_lock);
continue;
}
lruvec = <API key>(page, zone);
SetPageLRU(page);
lru = page_lru(page);
<API key>(page, lruvec, lru);
if (is_active_lru(lru)) {
int file = is_file_lru(lru);
int numpages = hpage_nr_pages(page);
reclaim_stat->recent_rotated[file] += numpages;
}
if (put_page_testzero(page)) {
__ClearPageLRU(page);
__ClearPageActive(page);
<API key>(page, lruvec, lru);
if (unlikely(PageCompound(page))) {
spin_unlock_irq(&zone->lru_lock);
mem_cgroup_uncharge(page);
(*<API key>(page))(page);
spin_lock_irq(&zone->lru_lock);
} else
list_add(&page->lru, &pages_to_free);
}
}
/*
* To save our caller's stack, now use input list for pages to free.
*/
list_splice(&pages_to_free, page_list);
}
/*
* If a kernel thread (such as nfsd for loop-back mounts) services
* a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
* In that case we should only throttle if the backing device it is
* writing to is congested. In other cases it is safe to throttle.
*/
static int <API key>(void)
{
return !(current->flags & PF_LESS_THROTTLE) ||
current->backing_dev_info == NULL ||
bdi_write_congested(current->backing_dev_info);
}
/*
* <API key>() is a helper for shrink_zone(). It returns the number
* of reclaimed pages
*/
static noinline_for_stack unsigned long
<API key>(unsigned long nr_to_scan, struct lruvec *lruvec,
struct scan_control *sc, enum lru_list lru)
{
LIST_HEAD(page_list);
unsigned long nr_scanned;
unsigned long nr_reclaimed = 0;
unsigned long nr_taken;
unsigned long nr_dirty = 0;
unsigned long nr_congested = 0;
unsigned long nr_unqueued_dirty = 0;
unsigned long nr_writeback = 0;
unsigned long nr_immediate = 0;
isolate_mode_t isolate_mode = 0;
int file = is_file_lru(lru);
struct zone *zone = lruvec_zone(lruvec);
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
while (unlikely(too_many_isolated(zone, file, sc))) {
congestion_wait(BLK_RW_ASYNC, HZ/10);
/* We are about to die and free our memory. Return now. */
if (<API key>(current))
return SWAP_CLUSTER_MAX;
}
lru_add_drain();
if (!sc->may_unmap)
isolate_mode |= ISOLATE_UNMAPPED;
if (!sc->may_writepage)
isolate_mode |= ISOLATE_CLEAN;
spin_lock_irq(&zone->lru_lock);
nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
&nr_scanned, sc, isolate_mode, lru);
<API key>(zone, NR_LRU_BASE + lru, -nr_taken);
<API key>(zone, NR_ISOLATED_ANON + file, nr_taken);
if (global_reclaim(sc)) {
<API key>(zone, NR_PAGES_SCANNED, nr_scanned);
if (current_is_kswapd())
<API key>(PGSCAN_KSWAPD, zone, nr_scanned);
else
<API key>(PGSCAN_DIRECT, zone, nr_scanned);
}
spin_unlock_irq(&zone->lru_lock);
if (nr_taken == 0)
return 0;
nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
&nr_dirty, &nr_unqueued_dirty, &nr_congested,
&nr_writeback, &nr_immediate,
false);
spin_lock_irq(&zone->lru_lock);
reclaim_stat->recent_scanned[file] += nr_taken;
if (global_reclaim(sc)) {
if (current_is_kswapd())
<API key>(PGSTEAL_KSWAPD, zone,
nr_reclaimed);
else
<API key>(PGSTEAL_DIRECT, zone,
nr_reclaimed);
}
<API key>(lruvec, &page_list);
<API key>(zone, NR_ISOLATED_ANON + file, -nr_taken);
spin_unlock_irq(&zone->lru_lock);
<API key>(&page_list);
<API key>(&page_list, true);
/*
* If reclaim is isolating dirty pages under writeback, it implies
* that the long-lived page allocation rate is exceeding the page
* laundering rate. Either the global limits are not being effective
* at throttling processes due to the page distribution throughout
* zones or there is heavy usage of a slow backing device. The
* only option is to throttle from reclaim context which is not ideal
* as there is no guarantee the dirtying process is throttled in the
* same way balance_dirty_pages() manages.
*
* Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
* of pages under pages flagged for immediate reclaim and stall if any
* are encountered in the nr_immediate check below.
*/
if (nr_writeback && nr_writeback == nr_taken)
set_bit(ZONE_WRITEBACK, &zone->flags);
/*
* Legacy memcg will stall in page writeback so avoid forcibly
* stalling here.
*/
if (sane_reclaim(sc)) {
/*
* Tag a zone as congested if all the dirty pages scanned were
* backed by a congested BDI and wait_iff_congested will stall.
*/
if (nr_dirty && nr_dirty == nr_congested)
set_bit(ZONE_CONGESTED, &zone->flags);
/*
* If dirty pages are scanned that are not queued for IO, it
* implies that flushers are not keeping up. In this case, flag
* the zone ZONE_DIRTY and kswapd will start writing pages from
* reclaim context.
*/
if (nr_unqueued_dirty == nr_taken)
set_bit(ZONE_DIRTY, &zone->flags);
/*
* If kswapd scans pages marked marked for immediate
* reclaim and under writeback (nr_immediate), it implies
* that pages are cycling through the LRU faster than
* they are written so also forcibly stall.
*/
if (nr_immediate && <API key>())
congestion_wait(BLK_RW_ASYNC, HZ/10);
}
/*
* Stall direct reclaim for IO completions if underlying BDIs or zone
* is congested. Allow kswapd to continue until it starts encountering
* unqueued dirty pages or cycling through the LRU too quickly.
*/
if (!sc->hibernation_mode && !current_is_kswapd() &&
<API key>())
wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
<API key>(zone->zone_pgdat->node_id,
zone_idx(zone),
nr_scanned, nr_reclaimed,
sc->priority,
trace_shrink_flags(file));
return nr_reclaimed;
}
/*
* This moves pages from the active list to the inactive list.
*
* We move them the other way if the page is referenced by one or more
* processes, from rmap.
*
* If the pages are mostly unmapped, the processing is fast and it is
* appropriate to hold zone->lru_lock across the whole operation. But if
* the pages are mapped, the processing is slow (page_referenced()) so we
* should drop zone->lru_lock around each page. It's impossible to balance
* this, so instead we remove the pages from the LRU while processing them.
* It is safe to rely on PG_active against the non-LRU pages in here because
* nobody will play with that bit on a non-LRU page.
*
* The downside is that we have to touch page->_count against each page.
* But we had to alter page->flags anyway.
*/
static void <API key>(struct lruvec *lruvec,
struct list_head *list,
struct list_head *pages_to_free,
enum lru_list lru)
{
struct zone *zone = lruvec_zone(lruvec);
unsigned long pgmoved = 0;
struct page *page;
int nr_pages;
while (!list_empty(list)) {
page = lru_to_page(list);
lruvec = <API key>(page, zone);
VM_BUG_ON_PAGE(PageLRU(page), page);
SetPageLRU(page);
nr_pages = hpage_nr_pages(page);
<API key>(lruvec, lru, nr_pages);
list_move(&page->lru, &lruvec->lists[lru]);
pgmoved += nr_pages;
if (put_page_testzero(page)) {
__ClearPageLRU(page);
__ClearPageActive(page);
<API key>(page, lruvec, lru);
if (unlikely(PageCompound(page))) {
spin_unlock_irq(&zone->lru_lock);
mem_cgroup_uncharge(page);
(*<API key>(page))(page);
spin_lock_irq(&zone->lru_lock);
} else
list_add(&page->lru, pages_to_free);
}
}
<API key>(zone, NR_LRU_BASE + lru, pgmoved);
if (!is_active_lru(lru))
__count_vm_events(PGDEACTIVATE, pgmoved);
}
static void shrink_active_list(unsigned long nr_to_scan,
struct lruvec *lruvec,
struct scan_control *sc,
enum lru_list lru)
{
unsigned long nr_taken;
unsigned long nr_scanned;
unsigned long vm_flags;
LIST_HEAD(l_hold); /* The pages which were snipped off */
LIST_HEAD(l_active);
LIST_HEAD(l_inactive);
struct page *page;
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
unsigned long nr_rotated = 0;
isolate_mode_t isolate_mode = 0;
int file = is_file_lru(lru);
struct zone *zone = lruvec_zone(lruvec);
lru_add_drain();
if (!sc->may_unmap)
isolate_mode |= ISOLATE_UNMAPPED;
if (!sc->may_writepage)
isolate_mode |= ISOLATE_CLEAN;
spin_lock_irq(&zone->lru_lock);
nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
&nr_scanned, sc, isolate_mode, lru);
if (global_reclaim(sc))
<API key>(zone, NR_PAGES_SCANNED, nr_scanned);
reclaim_stat->recent_scanned[file] += nr_taken;
<API key>(PGREFILL, zone, nr_scanned);
<API key>(zone, NR_LRU_BASE + lru, -nr_taken);
<API key>(zone, NR_ISOLATED_ANON + file, nr_taken);
spin_unlock_irq(&zone->lru_lock);
while (!list_empty(&l_hold)) {
cond_resched();
page = lru_to_page(&l_hold);
list_del(&page->lru);
if (unlikely(!page_evictable(page))) {
putback_lru_page(page);
continue;
}
if (unlikely(<API key>)) {
if (page_has_private(page) && trylock_page(page)) {
if (page_has_private(page))
try_to_release_page(page, 0);
unlock_page(page);
}
}
if (page_referenced(page, 0, sc->target_mem_cgroup,
&vm_flags)) {
nr_rotated += hpage_nr_pages(page);
/*
* Identify referenced, file-backed active pages and
* give them one more trip around the active list. So
* that executable code get better chances to stay in
* memory under moderate memory pressure. Anon pages
* are not likely to be evicted by use-once streaming
* IO, plus JVM can create lots of anon VM_EXEC pages,
* so we ignore them here.
*/
if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
list_add(&page->lru, &l_active);
continue;
}
}
ClearPageActive(page); /* we are de-activating */
list_add(&page->lru, &l_inactive);
}
/*
* Move pages back to the lru list.
*/
spin_lock_irq(&zone->lru_lock);
/*
* Count referenced pages from currently used mappings as rotated,
* even though only some of them are actually re-activated. This
* helps balance scan pressure between file and anonymous pages in
* get_scan_count.
*/
reclaim_stat->recent_rotated[file] += nr_rotated;
<API key>(lruvec, &l_active, &l_hold, lru);
<API key>(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
<API key>(zone, NR_ISOLATED_ANON + file, -nr_taken);
spin_unlock_irq(&zone->lru_lock);
<API key>(&l_hold);
<API key>(&l_hold, true);
}
#ifdef CONFIG_SWAP
static int <API key>(struct zone *zone)
{
unsigned long active, inactive;
active = zone_page_state(zone, NR_ACTIVE_ANON);
inactive = zone_page_state(zone, NR_INACTIVE_ANON);
if (inactive * zone->inactive_ratio < active)
return 1;
return 0;
}
/**
* <API key> - check if anonymous pages need to be deactivated
* @lruvec: LRU vector to check
*
* Returns true if the zone does not have enough inactive anon pages,
* meaning some active anon pages need to be deactivated.
*/
static int <API key>(struct lruvec *lruvec)
{
/*
* If we don't have swap space, anonymous page deactivation
* is pointless.
*/
if (!total_swap_pages)
return 0;
if (!mem_cgroup_disabled())
return <API key>(lruvec);
return <API key>(lruvec_zone(lruvec));
}
#else
static inline int <API key>(struct lruvec *lruvec)
{
return 0;
}
#endif
/**
* <API key> - check if file pages need to be deactivated
* @lruvec: LRU vector to check
*
* When the system is doing streaming IO, memory pressure here
* ensures that active file pages get deactivated, until more
* than half of the file pages are on the inactive list.
*
* Once we get to that situation, protect the system's working
* set from being evicted by disabling active file page aging.
*
* This uses a different ratio than the anonymous pages, because
* the page cache uses a use-once replacement algorithm.
*/
static int <API key>(struct lruvec *lruvec)
{
unsigned long inactive;
unsigned long active;
inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
return active > inactive;
}
static int <API key>(struct lruvec *lruvec, enum lru_list lru)
{
if (is_file_lru(lru))
return <API key>(lruvec);
else
return <API key>(lruvec);
}
static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
struct lruvec *lruvec, struct scan_control *sc)
{
if (is_active_lru(lru)) {
if (<API key>(lruvec, lru))
shrink_active_list(nr_to_scan, lruvec, sc, lru);
return 0;
}
return <API key>(nr_to_scan, lruvec, sc, lru);
}
enum scan_balance {
SCAN_EQUAL,
SCAN_FRACT,
SCAN_ANON,
SCAN_FILE,
};
/*
* Determine how aggressively the anon and file LRU lists should be
* scanned. The relative value of each set of LRU lists is determined
* by looking at the fraction of the pages scanned we did rotate back
* onto the active list instead of evict.
*
* nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
* nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
*/
static void get_scan_count(struct lruvec *lruvec, int swappiness,
struct scan_control *sc, unsigned long *nr,
unsigned long *lru_pages)
{
struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
u64 fraction[2];
u64 denominator = 0; /* gcc */
struct zone *zone = lruvec_zone(lruvec);
unsigned long anon_prio, file_prio;
enum scan_balance scan_balance;
unsigned long anon, file;
bool force_scan = false;
unsigned long ap, fp;
enum lru_list lru;
bool some_scanned;
int pass;
/*
* If the zone or memcg is small, nr[l] can be 0. This
* results in no scanning on this priority and a potential
* priority drop. Global direct reclaim can go to the next
* zone and tends to have no problems. Global kswapd is for
* zone balancing and it needs to scan a minimum amount. When
* reclaiming for a memcg, a priority drop can cause high
* latencies, so it's better to scan a minimum amount there as
* well.
*/
if (current_is_kswapd()) {
if (!zone_reclaimable(zone))
force_scan = true;
if (!<API key>(lruvec))
force_scan = true;
}
if (!global_reclaim(sc))
force_scan = true;
/* If we have no swap space, do not bother scanning anon pages. */
if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
scan_balance = SCAN_FILE;
goto out;
}
/*
* Global reclaim will swap to prevent OOM even with no
* swappiness, but memcg users want to use this knob to
* disable swapping for individual groups completely when
* using the memory controller's swap limit feature would be
* too expensive.
*/
if (!global_reclaim(sc) && !swappiness) {
scan_balance = SCAN_FILE;
goto out;
}
/*
* Do not apply any pressure balancing cleverness when the
* system is close to OOM, scan both anon and file equally
* (unless the swappiness setting disagrees with swapping).
*/
if (!sc->priority && swappiness) {
scan_balance = SCAN_EQUAL;
goto out;
}
/*
* Prevent the reclaimer from falling into the cache trap: as
* cache pages start out inactive, every cache fault will tip
* the scan balance towards the file LRU. And as the file LRU
* shrinks, so does the window for rotation from references.
* This means we have a runaway feedback loop where a tiny
* thrashing file LRU becomes infinitely more attractive than
* anon pages. Try to detect this based on file LRU size.
*/
if (global_reclaim(sc)) {
unsigned long zonefile;
unsigned long zonefree;
zonefree = zone_page_state(zone, NR_FREE_PAGES);
zonefile = zone_page_state(zone, NR_ACTIVE_FILE) +
zone_page_state(zone, NR_INACTIVE_FILE);
if (unlikely(zonefile + zonefree <= high_wmark_pages(zone))) {
scan_balance = SCAN_ANON;
goto out;
}
}
/*
* There is enough inactive page cache, do not reclaim
* anything from the anonymous working set right now.
*/
if (!<API key>(lruvec)) {
scan_balance = SCAN_FILE;
goto out;
}
scan_balance = SCAN_FRACT;
/*
* With swappiness at 100, anonymous and file have the same priority.
* This scanning priority is essentially the inverse of IO cost.
*/
anon_prio = swappiness;
file_prio = 200 - anon_prio;
/*
* OK, so we have swap space and a fair amount of page cache
* pages. We use the recently rotated / recently scanned
* ratios to determine how valuable each cache is.
*
* Because workloads change over time (and to avoid overflow)
* we keep these statistics as a floating average, which ends
* up weighing recent references more than old ones.
*
* anon in [0], file in [1]
*/
anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
get_lru_size(lruvec, LRU_INACTIVE_ANON);
file = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
get_lru_size(lruvec, LRU_INACTIVE_FILE);
spin_lock_irq(&zone->lru_lock);
if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
reclaim_stat->recent_scanned[0] /= 2;
reclaim_stat->recent_rotated[0] /= 2;
}
if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
reclaim_stat->recent_scanned[1] /= 2;
reclaim_stat->recent_rotated[1] /= 2;
}
/*
* The amount of pressure on anon vs file pages is inversely
* proportional to the fraction of recently scanned pages on
* each list that were recently referenced and in active use.
*/
ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
ap /= reclaim_stat->recent_rotated[0] + 1;
fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
fp /= reclaim_stat->recent_rotated[1] + 1;
spin_unlock_irq(&zone->lru_lock);
fraction[0] = ap;
fraction[1] = fp;
denominator = ap + fp + 1;
out:
some_scanned = false;
/* Only use force_scan on second pass. */
for (pass = 0; !some_scanned && pass < 2; pass++) {
*lru_pages = 0;
<API key>(lru) {
int file = is_file_lru(lru);
unsigned long size;
unsigned long scan;
size = get_lru_size(lruvec, lru);
scan = size >> sc->priority;
if (!scan && pass && force_scan)
scan = min(size, SWAP_CLUSTER_MAX);
switch (scan_balance) {
case SCAN_EQUAL:
/* Scan lists relative to size */
break;
case SCAN_FRACT:
/*
* Scan types proportional to swappiness and
* their relative recent reclaim efficiency.
*/
scan = div64_u64(scan * fraction[file],
denominator);
break;
case SCAN_FILE:
case SCAN_ANON:
/* Scan one type exclusively */
if ((scan_balance == SCAN_FILE) != file) {
size = 0;
scan = 0;
}
break;
default:
/* Look ma, no brain */
BUG();
}
*lru_pages += size;
nr[lru] = scan;
/*
* Skip the second pass and don't force_scan,
* if we found something to scan.
*/
some_scanned |= !!scan;
}
}
}
/*
* This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
*/
static void shrink_lruvec(struct lruvec *lruvec, int swappiness,
struct scan_control *sc, unsigned long *lru_pages)
{
unsigned long nr[NR_LRU_LISTS];
unsigned long targets[NR_LRU_LISTS];
unsigned long nr_to_scan;
enum lru_list lru;
unsigned long nr_reclaimed = 0;
unsigned long nr_to_reclaim = sc->nr_to_reclaim;
struct blk_plug plug;
bool scan_adjusted;
get_scan_count(lruvec, swappiness, sc, nr, lru_pages);
/* Record the original scan target for proportional adjustments later */
memcpy(targets, nr, sizeof(nr));
/*
* Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
* event that can occur when there is little memory pressure e.g.
* multiple streaming readers/writers. Hence, we do not abort scanning
* when the requested number of pages are reclaimed when scanning at
* DEF_PRIORITY on the assumption that the fact we are direct
* reclaiming implies that kswapd is not keeping up and it is best to
* do a batch of work at once. For memcg reclaim one check is made to
* abort proportional reclaim if either the file or anon lru has already
* dropped to zero at the first pass.
*/
scan_adjusted = (global_reclaim(sc) && !current_is_kswapd() &&
sc->priority == DEF_PRIORITY);
blk_start_plug(&plug);
while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
nr[LRU_INACTIVE_FILE]) {
unsigned long nr_anon, nr_file, percentage;
unsigned long nr_scanned;
<API key>(lru) {
if (nr[lru]) {
nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
nr[lru] -= nr_to_scan;
nr_reclaimed += shrink_list(lru, nr_to_scan,
lruvec, sc);
}
}
if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
continue;
/*
* For kswapd and memcg, reclaim at least the number of pages
* requested. Ensure that the anon and file LRUs are scanned
* proportionally what was requested by get_scan_count(). We
* stop reclaiming one LRU and reduce the amount scanning
* proportional to the original scan target.
*/
nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
/*
* It's just vindictive to attack the larger once the smaller
* has gone to zero. And given the way we stop scanning the
* smaller below, this makes sure that we only make one nudge
* towards proportionality once we've got nr_to_reclaim.
*/
if (!nr_file || !nr_anon)
break;
if (nr_file > nr_anon) {
unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
targets[LRU_ACTIVE_ANON] + 1;
lru = LRU_BASE;
percentage = nr_anon * 100 / scan_target;
} else {
unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
targets[LRU_ACTIVE_FILE] + 1;
lru = LRU_FILE;
percentage = nr_file * 100 / scan_target;
}
/* Stop scanning the smaller of the LRU */
nr[lru] = 0;
nr[lru + LRU_ACTIVE] = 0;
/*
* Recalculate the other LRU scan count based on its original
* scan target and the percentage scanning already complete
*/
lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
nr_scanned = targets[lru] - nr[lru];
nr[lru] = targets[lru] * (100 - percentage) / 100;
nr[lru] -= min(nr[lru], nr_scanned);
lru += LRU_ACTIVE;
nr_scanned = targets[lru] - nr[lru];
nr[lru] = targets[lru] * (100 - percentage) / 100;
nr[lru] -= min(nr[lru], nr_scanned);
scan_adjusted = true;
}
blk_finish_plug(&plug);
sc->nr_reclaimed += nr_reclaimed;
/*
* Even if we did not try to evict anon pages at all, we want to
* rebalance the anon lru active/inactive ratio.
*/
if (<API key>(lruvec))
shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
sc, LRU_ACTIVE_ANON);
<API key>(sc->gfp_mask);
}
/* Use reclaim/compaction for costly allocs or under memory pressure */
static bool <API key>(struct scan_control *sc)
{
if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
(sc->order > <API key> ||
sc->priority < DEF_PRIORITY - 2))
return true;
return false;
}
/*
* Reclaim/compaction is used for high-order allocation requests. It reclaims
* order-0 pages before compacting the zone. <API key>() returns
* true if more pages should be reclaimed such that when the page allocator
* calls try_to_compact_zone() that it will have enough free pages to succeed.
* It will give up earlier than that if there is difficulty reclaiming pages.
*/
static inline bool <API key>(struct zone *zone,
unsigned long nr_reclaimed,
unsigned long nr_scanned,
struct scan_control *sc)
{
unsigned long <API key>;
unsigned long inactive_lru_pages;
/* If not in reclaim/compaction mode, stop */
if (!<API key>(sc))
return false;
/* Consider stopping depending on scan and reclaim activity */
if (sc->gfp_mask & __GFP_REPEAT) {
/*
* For __GFP_REPEAT allocations, stop reclaiming if the
* full LRU list has been scanned and we are still failing
* to reclaim pages. This full LRU scan is potentially
* expensive but a __GFP_REPEAT caller really wants to succeed
*/
if (!nr_reclaimed && !nr_scanned)
return false;
} else {
/*
* For non-__GFP_REPEAT allocations which can presumably
* fail without consequence, stop if we failed to reclaim
* any pages from the last SWAP_CLUSTER_MAX number of
* pages that were scanned. This will return to the
* caller faster at the risk reclaim/compaction and
* the resulting allocation attempt fails
*/
if (!nr_reclaimed)
return false;
}
/*
* If we have not reclaimed enough pages for compaction and the
* inactive lists are large enough, continue reclaiming
*/
<API key> = (2UL << sc->order);
inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
if (get_nr_swap_pages() > 0)
inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
if (sc->nr_reclaimed < <API key> &&
inactive_lru_pages > <API key>)
return true;
/* If compaction would go ahead or the allocation would succeed, stop */
switch (compaction_suitable(zone, sc->order, 0, 0)) {
case COMPACT_PARTIAL:
case COMPACT_CONTINUE:
return false;
default:
return true;
}
}
static bool shrink_zone(struct zone *zone, struct scan_control *sc,
bool is_classzone)
{
struct reclaim_state *reclaim_state = current->reclaim_state;
unsigned long nr_reclaimed, nr_scanned;
bool reclaimable = false;
do {
struct mem_cgroup *root = sc->target_mem_cgroup;
struct <API key> reclaim = {
.zone = zone,
.priority = sc->priority,
};
unsigned long zone_lru_pages = 0;
struct mem_cgroup *memcg;
nr_reclaimed = sc->nr_reclaimed;
nr_scanned = sc->nr_scanned;
memcg = mem_cgroup_iter(root, NULL, &reclaim);
do {
unsigned long lru_pages;
unsigned long scanned;
struct lruvec *lruvec;
int swappiness;
if (mem_cgroup_low(root, memcg)) {
if (!sc->may_thrash)
continue;
mem_cgroup_events(memcg, MEMCG_LOW, 1);
}
lruvec = <API key>(zone, memcg);
swappiness = <API key>(memcg);
scanned = sc->nr_scanned;
shrink_lruvec(lruvec, swappiness, sc, &lru_pages);
zone_lru_pages += lru_pages;
if (memcg && is_classzone)
shrink_slab(sc->gfp_mask, zone_to_nid(zone),
memcg, sc->nr_scanned - scanned,
lru_pages);
/*
* Direct reclaim and kswapd have to scan all memory
* cgroups to fulfill the overall scan target for the
* zone.
*
* Limit reclaim, on the other hand, only cares about
* nr_to_reclaim pages to be reclaimed and it will
* retry with decreasing priority if one round over the
* whole hierarchy is not sufficient.
*/
if (!global_reclaim(sc) &&
sc->nr_reclaimed >= sc->nr_to_reclaim) {
<API key>(root, memcg);
break;
}
} while ((memcg = mem_cgroup_iter(root, memcg, &reclaim)));
/*
* Shrink the slab caches in the same proportion that
* the eligible LRU pages were scanned.
*/
if (global_reclaim(sc) && is_classzone)
shrink_slab(sc->gfp_mask, zone_to_nid(zone), NULL,
sc->nr_scanned - nr_scanned,
zone_lru_pages);
if (reclaim_state) {
sc->nr_reclaimed += reclaim_state->reclaimed_slab;
reclaim_state->reclaimed_slab = 0;
}
vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
sc->nr_scanned - nr_scanned,
sc->nr_reclaimed - nr_reclaimed);
if (sc->nr_reclaimed - nr_reclaimed)
reclaimable = true;
} while (<API key>(zone, sc->nr_reclaimed - nr_reclaimed,
sc->nr_scanned - nr_scanned, sc));
return reclaimable;
}
/*
* Returns true if compaction should go ahead for a high-order request, or
* the high-order allocation would succeed without compaction.
*/
static inline bool compaction_ready(struct zone *zone, int order)
{
unsigned long balance_gap, watermark;
bool watermark_ok;
/*
* Compaction takes time to run and there are potentially other
* callers using the pages just freed. Continue reclaiming until
* there is a buffer of free pages available to give compaction
* a reasonable chance of completing and allocating the page
*/
balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
zone->managed_pages, <API key>));
watermark = high_wmark_pages(zone) + balance_gap + (2UL << order);
watermark_ok = <API key>(zone, 0, watermark, 0, 0);
/*
* If compaction is deferred, reclaim up to a point where
* compaction will have a chance of success when re-enabled
*/
if (compaction_deferred(zone, order))
return watermark_ok;
/*
* If compaction is not ready to start and allocation is not likely
* to succeed without it, then keep reclaiming.
*/
if (compaction_suitable(zone, order, 0, 0) == COMPACT_SKIPPED)
return false;
return watermark_ok;
}
/*
* This is the direct reclaim path, for page-allocating processes. We only
* try to reclaim pages from zones which will satisfy the caller's allocation
* request.
*
* We reclaim from a zone even if that zone is over high_wmark_pages(zone).
* Because:
* a) The caller may be trying to free *extra* pages to satisfy a higher-order
* allocation or
* b) The target zone may be at high_wmark_pages(zone) but the lower zones
* must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
* zone defense algorithm.
*
* If a zone is deemed to be full of pinned pages then just give it a light
* scan then give up on it.
*
* Returns true if a zone was reclaimable.
*/
static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
{
struct zoneref *z;
struct zone *zone;
unsigned long nr_soft_reclaimed;
unsigned long nr_soft_scanned;
gfp_t orig_mask;
enum zone_type requested_highidx = gfp_zone(sc->gfp_mask);
bool reclaimable = false;
/*
* If the number of buffer_heads in the machine exceeds the maximum
* allowed level, force direct reclaim to scan the highmem zone as
* highmem pages could be pinning lowmem pages storing buffer_heads
*/
orig_mask = sc->gfp_mask;
if (<API key>)
sc->gfp_mask |= __GFP_HIGHMEM;
<API key>(zone, z, zonelist,
requested_highidx, sc->nodemask) {
enum zone_type classzone_idx;
if (!populated_zone(zone))
continue;
classzone_idx = requested_highidx;
while (!populated_zone(zone->zone_pgdat->node_zones +
classzone_idx))
classzone_idx
/*
* Take care memory controller reclaiming has small influence
* to global LRU.
*/
if (global_reclaim(sc)) {
if (!cpuset_zone_allowed(zone,
GFP_KERNEL | __GFP_HARDWALL))
continue;
if (sc->priority != DEF_PRIORITY &&
!zone_reclaimable(zone))
continue; /* Let kswapd poll it */
/*
* If we already have plenty of memory free for
* compaction in this zone, don't free any more.
* Even though compaction is invoked for any
* non-zero order, only frequent costly order
* reclamation is disruptive enough to become a
* noticeable problem, like transparent huge
* page allocations.
*/
if (IS_ENABLED(CONFIG_COMPACTION) &&
sc->order > <API key> &&
zonelist_zone_idx(z) <= requested_highidx &&
compaction_ready(zone, sc->order)) {
sc->compaction_ready = true;
continue;
}
/*
* This steals pages from memory cgroups over softlimit
* and returns the number of reclaimed pages and
* scanned pages. This works for global memory pressure
* and balancing, not for a memcg's limit.
*/
nr_soft_scanned = 0;
nr_soft_reclaimed = <API key>(zone,
sc->order, sc->gfp_mask,
&nr_soft_scanned);
sc->nr_reclaimed += nr_soft_reclaimed;
sc->nr_scanned += nr_soft_scanned;
if (nr_soft_reclaimed)
reclaimable = true;
/* need some check for avoid more shrink_zone() */
}
if (shrink_zone(zone, sc, zone_idx(zone) == classzone_idx))
reclaimable = true;
if (global_reclaim(sc) &&
!reclaimable && zone_reclaimable(zone))
reclaimable = true;
}
/*
* Restore to original mask to avoid the impact on the caller if we
* promoted it to __GFP_HIGHMEM.
*/
sc->gfp_mask = orig_mask;
return reclaimable;
}
/*
* This is the main entry point to direct page reclaim.
*
* If a full scan of the inactive list fails to free enough memory then we
* are "out of memory" and something needs to be killed.
*
* If the caller is !__GFP_FS then the probability of a failure is reasonably
* high - the zone may be full of dirty or under-writeback pages, which this
* caller can't do much about. We kick the writeback threads and take explicit
* naps in the hope that some of these pages can be written. But if the
* allocating task holds filesystem locks which prevent writeout this might not
* work, and the allocation attempt will fail.
*
* returns: 0, if no pages reclaimed
* else, the number of pages reclaimed
*/
static unsigned long <API key>(struct zonelist *zonelist,
struct scan_control *sc)
{
int initial_priority = sc->priority;
unsigned long total_scanned = 0;
unsigned long writeback_threshold;
bool zones_reclaimable;
retry:
<API key>();
if (global_reclaim(sc))
count_vm_event(ALLOCSTALL);
do {
vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
sc->priority);
sc->nr_scanned = 0;
zones_reclaimable = shrink_zones(zonelist, sc);
total_scanned += sc->nr_scanned;
if (sc->nr_reclaimed >= sc->nr_to_reclaim)
break;
if (sc->compaction_ready)
break;
/*
* If we're getting trouble reclaiming, start doing
* writepage even in laptop mode.
*/
if (sc->priority < DEF_PRIORITY - 2)
sc->may_writepage = 1;
/*
* Try to write back as many pages as we just scanned. This
* tends to cause slow streaming writers to write data to the
* disk smoothly, at the dirtying rate, which is nice. But
* that's undesirable in laptop mode, where we *want* lumpy
* writeout. So in laptop mode, write out the whole world.
*/
writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
if (total_scanned > writeback_threshold) {
<API key>(laptop_mode ? 0 : total_scanned,
<API key>);
sc->may_writepage = 1;
}
} while (--sc->priority >= 0);
<API key>();
if (sc->nr_reclaimed)
return sc->nr_reclaimed;
/* Aborted reclaim to try compaction? don't OOM, then */
if (sc->compaction_ready)
return 1;
/* Untapped cgroup reserves? Don't OOM, retry. */
if (!sc->may_thrash) {
sc->priority = initial_priority;
sc->may_thrash = 1;
goto retry;
}
/* Any of the zones still reclaimable? Don't OOM. */
if (zones_reclaimable)
return 1;
return 0;
}
static bool <API key>(pg_data_t *pgdat)
{
struct zone *zone;
unsigned long pfmemalloc_reserve = 0;
unsigned long free_pages = 0;
int i;
bool wmark_ok;
for (i = 0; i <= ZONE_NORMAL; i++) {
zone = &pgdat->node_zones[i];
if (!populated_zone(zone) ||
<API key>(zone) == 0)
continue;
pfmemalloc_reserve += min_wmark_pages(zone);
free_pages += zone_page_state(zone, NR_FREE_PAGES);
}
/* If there are no reserves (unexpected config) then do not throttle */
if (!pfmemalloc_reserve)
return true;
wmark_ok = free_pages > pfmemalloc_reserve / 2;
/* kswapd must be awake if processes are being throttled */
if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
pgdat->classzone_idx = min(pgdat->classzone_idx,
(enum zone_type)ZONE_NORMAL);
<API key>(&pgdat->kswapd_wait);
}
return wmark_ok;
}
/*
* Throttle direct reclaimers if backing storage is backed by the network
* and the PFMEMALLOC reserve for the preferred node is getting dangerously
* depleted. kswapd will continue to make progress and wake the processes
* when the low watermark is reached.
*
* Returns true if a fatal signal was delivered during throttling. If this
* happens, the page allocator should not consider triggering the OOM killer.
*/
static bool <API key>(gfp_t gfp_mask, struct zonelist *zonelist,
nodemask_t *nodemask)
{
struct zoneref *z;
struct zone *zone;
pg_data_t *pgdat = NULL;
/*
* Kernel threads should not be throttled as they may be indirectly
* responsible for cleaning pages necessary for reclaim to make forward
* progress. kjournald for example may enter direct reclaim while
* committing a transaction where throttling it could forcing other
* processes to block on log_wait_commit().
*/
if (current->flags & PF_KTHREAD)
goto out;
/*
* If a fatal signal is pending, this process should not throttle.
* It should return quickly so it can exit and free its memory
*/
if (<API key>(current))
goto out;
/*
* Check if the pfmemalloc reserves are ok by finding the first node
* with a usable ZONE_NORMAL or lower zone. The expectation is that
* GFP_KERNEL will be required for allocating network buffers when
* swapping over the network so ZONE_HIGHMEM is unusable.
*
* Throttling is based on the first usable node and throttled processes
* wait on a queue until kswapd makes progress and wakes them. There
* is an affinity then between processes waking up and where reclaim
* progress has been made assuming the process wakes on the same node.
* More importantly, processes running on remote nodes will not compete
* for remote pfmemalloc reserves and processes on different nodes
* should make reasonable progress.
*/
<API key>(zone, z, zonelist,
gfp_zone(gfp_mask), nodemask) {
if (zone_idx(zone) > ZONE_NORMAL)
continue;
/* Throttle based on the first usable node */
pgdat = zone->zone_pgdat;
if (<API key>(pgdat))
goto out;
break;
}
/* If no zone was usable by the allocation flags then do not throttle */
if (!pgdat)
goto out;
/* Account for the throttling */
count_vm_event(<API key>);
/*
* If the caller cannot enter the filesystem, it's possible that it
* is due to the caller holding an FS lock or performing a journal
* transaction in the case of a filesystem like ext[3|4]. In this case,
* it is not safe to block on pfmemalloc_wait as kswapd could be
* blocked waiting on the same lock. Instead, throttle for up to a
* second before continuing.
*/
if (!(gfp_mask & __GFP_FS)) {
<API key>(pgdat->pfmemalloc_wait,
<API key>(pgdat), HZ);
goto check_pending;
}
/* Throttle until kswapd wakes the process */
wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
<API key>(pgdat));
check_pending:
if (<API key>(current))
return true;
out:
return false;
}
unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
gfp_t gfp_mask, nodemask_t *nodemask)
{
unsigned long nr_reclaimed;
struct scan_control sc = {
.nr_to_reclaim = SWAP_CLUSTER_MAX,
.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
.order = order,
.nodemask = nodemask,
.priority = DEF_PRIORITY,
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = 1,
};
/*
* Do not enter reclaim if fatal signal was delivered while throttled.
* 1 is returned so that the page allocator does not OOM kill at this
* point.
*/
if (<API key>(gfp_mask, zonelist, nodemask))
return 1;
<API key>(order,
sc.may_writepage,
gfp_mask);
nr_reclaimed = <API key>(zonelist, &sc);
<API key>(nr_reclaimed);
return nr_reclaimed;
}
#ifdef CONFIG_MEMCG
unsigned long <API key>(struct mem_cgroup *memcg,
gfp_t gfp_mask, bool noswap,
struct zone *zone,
unsigned long *nr_scanned)
{
struct scan_control sc = {
.nr_to_reclaim = SWAP_CLUSTER_MAX,
.target_mem_cgroup = memcg,
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = !noswap,
};
struct lruvec *lruvec = <API key>(zone, memcg);
int swappiness = <API key>(memcg);
unsigned long lru_pages;
sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
(<API key> & ~GFP_RECLAIM_MASK);
<API key>(sc.order,
sc.may_writepage,
sc.gfp_mask);
/*
* NOTE: Although we can get the priority field, using it
* here is not a good idea, since it limits the pages we can scan.
* if we don't reclaim here, the shrink_zone from balance_pgdat
* will pick up pages from other mem cgroup's as well. We hack
* the priority and make it zero.
*/
shrink_lruvec(lruvec, swappiness, &sc, &lru_pages);
<API key>(sc.nr_reclaimed);
*nr_scanned = sc.nr_scanned;
return sc.nr_reclaimed;
}
unsigned long <API key>(struct mem_cgroup *memcg,
unsigned long nr_pages,
gfp_t gfp_mask,
bool may_swap)
{
struct zonelist *zonelist;
unsigned long nr_reclaimed;
int nid;
struct scan_control sc = {
.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
(<API key> & ~GFP_RECLAIM_MASK),
.target_mem_cgroup = memcg,
.priority = DEF_PRIORITY,
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = may_swap,
};
/*
* Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
* take care of from where we get pages. So the node where we start the
* scan does not need to be the current node.
*/
nid = <API key>(memcg);
zonelist = NODE_DATA(nid)->node_zonelists;
<API key>(0,
sc.may_writepage,
sc.gfp_mask);
nr_reclaimed = <API key>(zonelist, &sc);
<API key>(nr_reclaimed);
return nr_reclaimed;
}
#endif
static void age_active_anon(struct zone *zone, struct scan_control *sc)
{
struct mem_cgroup *memcg;
if (!total_swap_pages)
return;
memcg = mem_cgroup_iter(NULL, NULL, NULL);
do {
struct lruvec *lruvec = <API key>(zone, memcg);
if (<API key>(lruvec))
shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
sc, LRU_ACTIVE_ANON);
memcg = mem_cgroup_iter(NULL, memcg, NULL);
} while (memcg);
}
static bool zone_balanced(struct zone *zone, int order,
unsigned long balance_gap, int classzone_idx)
{
if (!<API key>(zone, order, high_wmark_pages(zone) +
balance_gap, classzone_idx, 0))
return false;
if (IS_ENABLED(CONFIG_COMPACTION) && order && compaction_suitable(zone,
order, 0, classzone_idx) == COMPACT_SKIPPED)
return false;
return true;
}
/*
* pgdat_balanced() is used when checking if a node is balanced.
*
* For order-0, all zones must be balanced!
*
* For high-order allocations only zones that meet watermarks and are in a
* zone allowed by the callers classzone_idx are added to balanced_pages. The
* total of balanced pages must be at least 25% of the zones allowed by
* classzone_idx for the node to be considered balanced. Forcing all zones to
* be balanced for high orders can cause excessive reclaim when there are
* imbalanced zones.
* The choice of 25% is due to
* o a 16M DMA zone that is balanced will not balance a zone on any
* reasonable sized machine
* o On all other machines, the top zone must be at least a reasonable
* percentage of the middle zones. For example, on 32-bit x86, highmem
* would need to be at least 256M for it to be balance a whole node.
* Similarly, on x86-64 the Normal zone would need to be at least 1G
* to balance a node on its own. These seemed like reasonable ratios.
*/
static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
{
unsigned long managed_pages = 0;
unsigned long balanced_pages = 0;
int i;
/* Check the watermark levels */
for (i = 0; i <= classzone_idx; i++) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
managed_pages += zone->managed_pages;
/*
* A special case here:
*
* balance_pgdat() skips over all_unreclaimable after
* DEF_PRIORITY. Effectively, it considers them balanced so
* they must be considered balanced here as well!
*/
if (!zone_reclaimable(zone)) {
balanced_pages += zone->managed_pages;
continue;
}
if (zone_balanced(zone, order, 0, i))
balanced_pages += zone->managed_pages;
else if (!order)
return false;
}
if (order)
return balanced_pages >= (managed_pages >> 2);
else
return true;
}
/*
* Prepare kswapd for sleeping. This verifies that there are no processes
* waiting in <API key>() and that watermarks have been met.
*
* Returns true if kswapd is ready to sleep
*/
static bool <API key>(pg_data_t *pgdat, int order, long remaining,
int classzone_idx)
{
/* If a direct reclaimer woke kswapd within HZ/10, it's premature */
if (remaining)
return false;
/*
* The throttled processes are normally woken up in balance_pgdat() as
* soon as <API key>() is true. But there is a potential
* race between when kswapd checks the watermarks and a process gets
* throttled. There is also a potential race if processes get
* throttled, kswapd wakes, a large process exits thereby balancing the
* zones, which causes kswapd to exit balance_pgdat() before reaching
* the wake up checks. If kswapd is going to sleep, no process should
* be sleeping on pfmemalloc_wait, so wake them now if necessary. If
* the wake up is premature, processes will wake kswapd and get
* throttled again. The difference from wake ups in balance_pgdat() is
* that here we are under prepare_to_wait().
*/
if (waitqueue_active(&pgdat->pfmemalloc_wait))
wake_up_all(&pgdat->pfmemalloc_wait);
return pgdat_balanced(pgdat, order, classzone_idx);
}
/*
* kswapd shrinks the zone by the number of pages required to reach
* the high watermark.
*
* Returns true if kswapd scanned at least the requested number of pages to
* reclaim or if the lack of progress was due to pages under writeback.
* This is used to determine if the scanning priority needs to be raised.
*/
static bool kswapd_shrink_zone(struct zone *zone,
int classzone_idx,
struct scan_control *sc,
unsigned long *nr_attempted)
{
int testorder = sc->order;
unsigned long balance_gap;
bool lowmem_pressure;
/* Reclaim above the high watermark. */
sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
/*
* Kswapd reclaims only single pages with compaction enabled. Trying
* too hard to reclaim until contiguous free pages have become
* available can hurt performance by evicting too much useful data
* from memory. Do not reclaim more than needed for compaction.
*/
if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
compaction_suitable(zone, sc->order, 0, classzone_idx)
!= COMPACT_SKIPPED)
testorder = 0;
/*
* We put equal pressure on every zone, unless one zone has way too
* many pages free already. The "too many pages" is defined as the
* high wmark plus a "gap" where the gap is either the low
* watermark or 1% of the zone, whichever is smaller.
*/
balance_gap = min(low_wmark_pages(zone), DIV_ROUND_UP(
zone->managed_pages, <API key>));
/*
* If there is no low memory pressure or the zone is balanced then no
* reclaim is necessary
*/
lowmem_pressure = (<API key> && is_highmem(zone));
if (!lowmem_pressure && zone_balanced(zone, testorder,
balance_gap, classzone_idx))
return true;
shrink_zone(zone, sc, zone_idx(zone) == classzone_idx);
/* Account for the number of pages attempted to reclaim */
*nr_attempted += sc->nr_to_reclaim;
clear_bit(ZONE_WRITEBACK, &zone->flags);
/*
* If a zone reaches its high watermark, consider it to be no longer
* congested. It's possible there are dirty pages backed by congested
* BDIs but as pressure is relieved, speculatively avoid congestion
* waits.
*/
if (zone_reclaimable(zone) &&
zone_balanced(zone, testorder, 0, classzone_idx)) {
clear_bit(ZONE_CONGESTED, &zone->flags);
clear_bit(ZONE_DIRTY, &zone->flags);
}
return sc->nr_scanned >= sc->nr_to_reclaim;
}
/*
* For kswapd, balance_pgdat() will work across all this node's zones until
* they are all at high_wmark_pages(zone).
*
* Returns the final order kswapd was reclaiming at
*
* There is special handling here for zones which are full of pinned pages.
* This can happen if the pages are all mlocked, or if they are all used by
* device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
* What we do is to detect the case where all pages in the zone have been
* scanned twice and there has been zero successful reclaim. Mark the zone as
* dead and from now on, only perform a short scan. Basically we're polling
* the zone for when the problem goes away.
*
* kswapd scans the zones in the highmem->normal->dma direction. It skips
* zones which have free_pages > high_wmark_pages(zone), but once a zone is
* found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
* lower zones regardless of the number of free pages in the lower zones. This
* interoperates with the page allocator fallback scheme to ensure that aging
* of pages is balanced across the zones.
*/
static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
int *classzone_idx)
{
int i;
int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
unsigned long nr_soft_reclaimed;
unsigned long nr_soft_scanned;
struct scan_control sc = {
.gfp_mask = GFP_KERNEL,
.order = order,
.priority = DEF_PRIORITY,
.may_writepage = !laptop_mode,
.may_unmap = 1,
.may_swap = 1,
};
count_vm_event(PAGEOUTRUN);
do {
unsigned long nr_attempted = 0;
bool raise_priority = true;
bool <API key> = (order > 0);
sc.nr_reclaimed = 0;
/*
* Scan in the highmem->dma direction for the highest
* zone which needs scanning
*/
for (i = pgdat->nr_zones - 1; i >= 0; i
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
if (sc.priority != DEF_PRIORITY &&
!zone_reclaimable(zone))
continue;
/*
* Do some background aging of the anon list, to give
* pages a chance to be referenced before reclaiming.
*/
age_active_anon(zone, &sc);
/*
* If the number of buffer_heads in the machine
* exceeds the maximum allowed level and this node
* has a highmem zone, force kswapd to reclaim from
* it to relieve lowmem pressure.
*/
if (<API key> && is_highmem_idx(i)) {
end_zone = i;
break;
}
if (!zone_balanced(zone, order, 0, 0)) {
end_zone = i;
break;
} else {
/*
* If balanced, clear the dirty and congested
* flags
*/
clear_bit(ZONE_CONGESTED, &zone->flags);
clear_bit(ZONE_DIRTY, &zone->flags);
}
}
if (i < 0)
goto out;
for (i = 0; i <= end_zone; i++) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
/*
* If any zone is currently balanced then kswapd will
* not call compaction as it is expected that the
* necessary pages are already available.
*/
if (<API key> &&
zone_watermark_ok(zone, order,
low_wmark_pages(zone),
*classzone_idx, 0))
<API key> = false;
}
/*
* If we're getting trouble reclaiming, start doing writepage
* even in laptop mode.
*/
if (sc.priority < DEF_PRIORITY - 2)
sc.may_writepage = 1;
/*
* Now scan the zone in the dma->highmem direction, stopping
* at the last zone which needs scanning.
*
* We do this because the page allocator works in the opposite
* direction. This prevents the page allocator from allocating
* pages behind kswapd's direction of progress, which would
* cause too much scanning of the lower zones.
*/
for (i = 0; i <= end_zone; i++) {
struct zone *zone = pgdat->node_zones + i;
if (!populated_zone(zone))
continue;
if (sc.priority != DEF_PRIORITY &&
!zone_reclaimable(zone))
continue;
sc.nr_scanned = 0;
nr_soft_scanned = 0;
/*
* Call soft limit reclaim before calling shrink_zone.
*/
nr_soft_reclaimed = <API key>(zone,
order, sc.gfp_mask,
&nr_soft_scanned);
sc.nr_reclaimed += nr_soft_reclaimed;
/*
* There should be no need to raise the scanning
* priority if enough pages are already being scanned
* that that high watermark would be met at 100%
* efficiency.
*/
if (kswapd_shrink_zone(zone, end_zone,
&sc, &nr_attempted))
raise_priority = false;
}
/*
* If the low watermark is met there is no need for processes
* to be throttled on pfmemalloc_wait as they should not be
* able to safely make forward progress. Wake them
*/
if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
<API key>(pgdat))
wake_up_all(&pgdat->pfmemalloc_wait);
/*
* Fragmentation may mean that the system cannot be rebalanced
* for high-order allocations in all zones. If twice the
* allocation size has been reclaimed and the zones are still
* not balanced then recheck the watermarks at order-0 to
* prevent kswapd reclaiming excessively. Assume that a
* process requested a high-order can direct reclaim/compact.
*/
if (order && sc.nr_reclaimed >= 2UL << order)
order = sc.order = 0;
/* Check if kswapd should be suspending */
if (try_to_freeze() || kthread_should_stop())
break;
/*
* Compact if necessary and kswapd is reclaiming at least the
* high watermark number of pages as requsted
*/
if (<API key> && sc.nr_reclaimed > nr_attempted)
compact_pgdat(pgdat, order);
/*
* Raise priority if scanning rate is too low or there was no
* progress in reclaiming pages
*/
if (raise_priority || !sc.nr_reclaimed)
sc.priority
} while (sc.priority >= 1 &&
!pgdat_balanced(pgdat, order, *classzone_idx));
out:
/*
* Return the order we were reclaiming at so <API key>()
* makes a decision on the order we were last reclaiming at. However,
* if another caller entered the allocator slow path while kswapd
* was awake, order will remain at the higher level
*/
*classzone_idx = end_zone;
return order;
}
static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
{
long remaining = 0;
DEFINE_WAIT(wait);
if (freezing(current) || kthread_should_stop())
return;
prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
/* Try to sleep for a short interval */
if (<API key>(pgdat, order, remaining, classzone_idx)) {
remaining = schedule_timeout(HZ/10);
finish_wait(&pgdat->kswapd_wait, &wait);
prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
}
/*
* After a short sleep, check if it was a premature sleep. If not, then
* go fully to sleep until explicitly woken up.
*/
if (<API key>(pgdat, order, remaining, classzone_idx)) {
<API key>(pgdat->node_id);
/*
* vmstat counters are not perfectly accurate and the estimated
* value for counters such as NR_FREE_PAGES can deviate from the
* true value by nr_online_cpus * threshold. To avoid the zone
* watermarks being breached while under pressure, we reduce the
* per-cpu vmstat threshold while kswapd is awake and restore
* them before going back to sleep.
*/
<API key>(pgdat, <API key>);
/*
* Compaction records what page blocks it recently failed to
* isolate pages from and skips them in the future scanning.
* When kswapd is going to sleep, it is reasonable to assume
* that pages and compaction may succeed so reset the cache.
*/
<API key>(pgdat);
if (!kthread_should_stop())
schedule();
<API key>(pgdat, <API key>);
} else {
if (remaining)
count_vm_event(<API key>);
else
count_vm_event(<API key>);
}
finish_wait(&pgdat->kswapd_wait, &wait);
}
/*
* The background pageout daemon, started as a kernel thread
* from the init process.
*
* This basically trickles out pages so that we have _some_
* free memory available even if there is no other activity
* that frees anything up. This is needed for things like routing
* etc, where we otherwise might have all activity going on in
* asynchronous contexts that cannot page things out.
*
* If there are applications that are active memory-allocators
* (most normal use), this basically shouldn't matter.
*/
static int kswapd(void *p)
{
unsigned long order, new_order;
unsigned balanced_order;
int classzone_idx, new_classzone_idx;
int <API key>;
pg_data_t *pgdat = (pg_data_t*)p;
struct task_struct *tsk = current;
struct reclaim_state reclaim_state = {
.reclaimed_slab = 0,
};
const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
<API key>(GFP_KERNEL);
if (!cpumask_empty(cpumask))
<API key>(tsk, cpumask);
current->reclaim_state = &reclaim_state;
/*
* Tell the memory management that we're a "memory allocator",
* and that if we need more memory we should get access to it
* regardless (see "__alloc_pages()"). "kswapd" should
* never get caught in the normal page freeing logic.
*
* (Kswapd normally doesn't need memory anyway, but sometimes
* you need a small amount of memory in order to be able to
* page out something else, and this flag essentially protects
* us from recursively trying to free more memory as we're
* trying to free the first piece of memory in the first place).
*/
tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
set_freezable();
order = new_order = 0;
balanced_order = 0;
classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
<API key> = classzone_idx;
for ( ; ; ) {
bool ret;
/*
* If the last balance_pgdat was unsuccessful it's unlikely a
* new request of a similar or harder type will succeed soon
* so consider going to sleep on the basis we reclaimed at
*/
if (<API key> >= new_classzone_idx &&
balanced_order == new_order) {
new_order = pgdat->kswapd_max_order;
new_classzone_idx = pgdat->classzone_idx;
pgdat->kswapd_max_order = 0;
pgdat->classzone_idx = pgdat->nr_zones - 1;
}
if (order < new_order || classzone_idx > new_classzone_idx) {
/*
* Don't sleep if someone wants a larger 'order'
* allocation or has tigher zone constraints
*/
order = new_order;
classzone_idx = new_classzone_idx;
} else {
kswapd_try_to_sleep(pgdat, balanced_order,
<API key>);
order = pgdat->kswapd_max_order;
classzone_idx = pgdat->classzone_idx;
new_order = order;
new_classzone_idx = classzone_idx;
pgdat->kswapd_max_order = 0;
pgdat->classzone_idx = pgdat->nr_zones - 1;
}
ret = try_to_freeze();
if (kthread_should_stop())
break;
/*
* We can speed up thawing tasks if we don't call balance_pgdat
* after returning from the refrigerator
*/
if (!ret) {
<API key>(pgdat->node_id, order);
<API key> = classzone_idx;
balanced_order = balance_pgdat(pgdat, order,
&<API key>);
}
}
tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
current->reclaim_state = NULL;
<API key>();
return 0;
}
/*
* A zone is low on free memory, so wake its kswapd task to service it.
*/
void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
{
pg_data_t *pgdat;
if (!populated_zone(zone))
return;
if (!cpuset_zone_allowed(zone, GFP_KERNEL | __GFP_HARDWALL))
return;
pgdat = zone->zone_pgdat;
if (pgdat->kswapd_max_order < order) {
pgdat->kswapd_max_order = order;
pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
}
if (!waitqueue_active(&pgdat->kswapd_wait))
return;
if (zone_balanced(zone, order, 0, 0))
return;
<API key>(pgdat->node_id, zone_idx(zone), order);
<API key>(&pgdat->kswapd_wait);
}
#ifdef CONFIG_HIBERNATION
/*
* Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
* freed pages.
*
* Rather than trying to age LRUs the aim is to preserve the overall
* LRU order by reclaiming preferentially
* inactive > active > active referenced > active mapped
*/
unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
{
struct reclaim_state reclaim_state;
struct scan_control sc = {
.nr_to_reclaim = nr_to_reclaim,
.gfp_mask = <API key>,
.priority = DEF_PRIORITY,
.may_writepage = 1,
.may_unmap = 1,
.may_swap = 1,
.hibernation_mode = 1,
};
struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
struct task_struct *p = current;
unsigned long nr_reclaimed;
p->flags |= PF_MEMALLOC;
<API key>(sc.gfp_mask);
reclaim_state.reclaimed_slab = 0;
p->reclaim_state = &reclaim_state;
nr_reclaimed = <API key>(zonelist, &sc);
p->reclaim_state = NULL;
<API key>();
p->flags &= ~PF_MEMALLOC;
return nr_reclaimed;
}
#endif /* CONFIG_HIBERNATION */
/* It's optimal to keep kswapds on the same CPUs as their memory, but
not required for correctness. So if the last cpu in a node goes
away, we get changed to run anywhere: as the first one comes back,
restore their cpu bindings. */
static int cpu_callback(struct notifier_block *nfb, unsigned long action,
void *hcpu)
{
int nid;
if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
for_each_node_state(nid, N_MEMORY) {
pg_data_t *pgdat = NODE_DATA(nid);
const struct cpumask *mask;
mask = cpumask_of_node(pgdat->node_id);
if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
/* One of our CPUs online: restore mask */
<API key>(pgdat->kswapd, mask);
}
}
return NOTIFY_OK;
}
/*
* This kswapd start function will be called by init and node-hot-add.
* On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
*/
int kswapd_run(int nid)
{
pg_data_t *pgdat = NODE_DATA(nid);
int ret = 0;
if (pgdat->kswapd)
return 0;
pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
if (IS_ERR(pgdat->kswapd)) {
/* failure at boot is fatal */
BUG_ON(system_state == SYSTEM_BOOTING);
pr_err("Failed to start kswapd on node %d\n", nid);
ret = PTR_ERR(pgdat->kswapd);
pgdat->kswapd = NULL;
}
return ret;
}
/*
* Called by memory hotplug when all memory in a node is offlined. Caller must
* hold mem_hotplug_begin/end().
*/
void kswapd_stop(int nid)
{
struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
if (kswapd) {
kthread_stop(kswapd);
NODE_DATA(nid)->kswapd = NULL;
}
}
static int __init kswapd_init(void)
{
int nid;
swap_setup();
for_each_node_state(nid, N_MEMORY)
kswapd_run(nid);
hotcpu_notifier(cpu_callback, 0);
return 0;
}
module_init(kswapd_init)
#ifdef CONFIG_NUMA
/*
* Zone reclaim mode
*
* If non-zero call zone_reclaim when the number of free pages falls below
* the watermarks.
*/
int zone_reclaim_mode __read_mostly;
#define RECLAIM_OFF 0
#define RECLAIM_ZONE (1<<0) /* Run <API key> on the zone */
#define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
#define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */
/*
* Priority for ZONE_RECLAIM. This determines the fraction of pages
* of a node considered for each zone_reclaim. 4 scans 1/16th of
* a zone.
*/
#define <API key> 4
/*
* Percentage of pages in a zone that must be unmapped for zone_reclaim to
* occur.
*/
int <API key> = 1;
/*
* If the number of slab pages in a zone grows beyond this percentage then
* slab reclaim needs to occur.
*/
int <API key> = 5;
static inline unsigned long <API key>(struct zone *zone)
{
unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
zone_page_state(zone, NR_ACTIVE_FILE);
/*
* It's possible for there to be more file mapped pages than
* accounted for by the pages on the file LRU lists because
* tmpfs pages accounted for as ANON can also be FILE_MAPPED
*/
return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
}
/* Work out how many page cache pages we can reclaim in this reclaim_mode */
static long <API key>(struct zone *zone)
{
long <API key>;
long delta = 0;
/*
* If RECLAIM_UNMAP is set, then all file pages are considered
* potentially reclaimable. Otherwise, we have to worry about
* pages like swapcache and <API key>() provides
* a better estimate
*/
if (zone_reclaim_mode & RECLAIM_UNMAP)
<API key> = zone_page_state(zone, NR_FILE_PAGES);
else
<API key> = <API key>(zone);
/* If we can't clean pages, remove dirty pages from consideration */
if (!(zone_reclaim_mode & RECLAIM_WRITE))
delta += zone_page_state(zone, NR_FILE_DIRTY);
/* Watch for any possible underflows due to delta */
if (unlikely(delta > <API key>))
delta = <API key>;
return <API key> - delta;
}
/*
* Try to free up some pages from this zone through reclaim.
*/
static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
{
/* Minimum pages needed in order to stay on node */
const unsigned long nr_pages = 1 << order;
struct task_struct *p = current;
struct reclaim_state reclaim_state;
struct scan_control sc = {
.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
.gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
.order = order,
.priority = <API key>,
.may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
.may_unmap = !!(zone_reclaim_mode & RECLAIM_UNMAP),
.may_swap = 1,
};
cond_resched();
/*
* We need to be able to allocate from the reserves for RECLAIM_UNMAP
* and we also need to be able to write out pages for RECLAIM_WRITE
* and RECLAIM_UNMAP.
*/
p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
<API key>(gfp_mask);
reclaim_state.reclaimed_slab = 0;
p->reclaim_state = &reclaim_state;
if (<API key>(zone) > zone->min_unmapped_pages) {
/*
* Free memory by calling shrink zone with increasing
* priorities until we have enough memory freed.
*/
do {
shrink_zone(zone, &sc, true);
} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
}
p->reclaim_state = NULL;
current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
<API key>();
return sc.nr_reclaimed >= nr_pages;
}
int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
{
int node_id;
int ret;
/*
* Zone reclaim reclaims unmapped file backed pages and
* slab pages if we are over the defined limits.
*
* A small portion of unmapped file backed pages is needed for
* file I/O otherwise pages read by file I/O will be immediately
* thrown out if the zone is overallocated. So we do not reclaim
* if less than a specified percentage of the zone is used by
* unmapped file backed pages.
*/
if (<API key>(zone) <= zone->min_unmapped_pages &&
zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
return ZONE_RECLAIM_FULL;
if (!zone_reclaimable(zone))
return ZONE_RECLAIM_FULL;
/*
* Do not scan if the allocation should not be delayed.
*/
if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
return ZONE_RECLAIM_NOSCAN;
/*
* Only run zone reclaim on the local zone or on zones that do not
* have associated processors. This will favor the local processor
* over remote processors and spread off node memory allocations
* as wide as possible.
*/
node_id = zone_to_nid(zone);
if (node_state(node_id, N_CPU) && node_id != numa_node_id())
return ZONE_RECLAIM_NOSCAN;
if (test_and_set_bit(ZONE_RECLAIM_LOCKED, &zone->flags))
return ZONE_RECLAIM_NOSCAN;
ret = __zone_reclaim(zone, gfp_mask, order);
clear_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
if (!ret)
count_vm_event(<API key>);
return ret;
}
#endif
/*
* page_evictable - test whether a page is evictable
* @page: the page to test
*
* Test whether page is evictable--i.e., should be placed on active/inactive
* lists vs unevictable list.
*
* Reasons page might not be evictable:
* (1) page's mapping marked unevictable
* (2) page is part of an mlocked VMA
*
*/
int page_evictable(struct page *page)
{
return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
}
#ifdef CONFIG_SHMEM
/**
* <API key> - check pages for evictability and move to appropriate zone lru list
* @pages: array of pages to check
* @nr_pages: number of pages to check
*
* Checks pages for evictability and moves them to the appropriate lru list.
*
* This function is only used for SysV IPC SHM_UNLOCK.
*/
void <API key>(struct page **pages, int nr_pages)
{
struct lruvec *lruvec;
struct zone *zone = NULL;
int pgscanned = 0;
int pgrescued = 0;
int i;
for (i = 0; i < nr_pages; i++) {
struct page *page = pages[i];
struct zone *pagezone;
pgscanned++;
pagezone = page_zone(page);
if (pagezone != zone) {
if (zone)
spin_unlock_irq(&zone->lru_lock);
zone = pagezone;
spin_lock_irq(&zone->lru_lock);
}
lruvec = <API key>(page, zone);
if (!PageLRU(page) || !PageUnevictable(page))
continue;
if (page_evictable(page)) {
enum lru_list lru = page_lru_base_type(page);
VM_BUG_ON_PAGE(PageActive(page), page);
<API key>(page);
<API key>(page, lruvec, LRU_UNEVICTABLE);
<API key>(page, lruvec, lru);
pgrescued++;
}
}
if (zone) {
__count_vm_events(<API key>, pgrescued);
__count_vm_events(<API key>, pgscanned);
spin_unlock_irq(&zone->lru_lock);
}
}
#endif /* CONFIG_SHMEM */
|
#include <my_global.h>
#include <m_string.h>
#include <stdarg.h>
#include <m_ctype.h>
#define MAX_ARGS 32 /* max positional args count*/
#define MAX_PRINT_INFO 32 /* max print position count */
#define LENGTH_ARG 1
#define WIDTH_ARG 2
#define PREZERO_ARG 4
#define ESCAPED_ARG 8
typedef struct pos_arg_info ARGS_INFO;
typedef struct print_info PRINT_INFO;
struct pos_arg_info
{
char arg_type; /* argument type */
uint have_longlong; /* used from integer values */
char *str_arg; /* string value of the arg */
longlong longlong_arg; /* integer value of the arg */
double double_arg; /* double value of the arg */
};
struct print_info
{
char arg_type; /* argument type */
size_t arg_idx; /* index of the positional arg */
size_t length; /* print width or arg index */
size_t width; /* print width or arg index */
uint flags;
const char *begin;
const char *end;
};
/**
Calculates print length or index of positional argument
@param fmt processed string
@param length print length or index of positional argument
@param pre_zero returns flags with PREZERO_ARG set if necessary
@retval
string position right after length digits
*/
static const char *get_length(const char *fmt, size_t *length, uint *pre_zero)
{
for (; my_isdigit(&my_charset_latin1, *fmt); fmt++)
{
*length= *length * 10 + (uint)(*fmt - '0');
if (!*length)
*pre_zero|= PREZERO_ARG; /* first digit was 0 */
}
return fmt;
}
/**
Calculates print width or index of positional argument
@param fmt processed string
@param width print width or index of positional argument
@retval
string position right after width digits
*/
static const char *get_width(const char *fmt, size_t *width)
{
for (; my_isdigit(&my_charset_latin1, *fmt); fmt++)
{
*width= *width * 10 + (uint)(*fmt - '0');
}
return fmt;
}
/**
Calculates print width or index of positional argument
@param fmt processed string
@param have_longlong TRUE if longlong is required
@retval
string position right after modifier symbol
*/
static const char *check_longlong(const char *fmt, uint *have_longlong)
{
*have_longlong= 0;
if (*fmt == 'l')
{
fmt++;
if (*fmt != 'l')
*have_longlong= (sizeof(long) == sizeof(longlong));
else
{
fmt++;
*have_longlong= 1;
}
}
else if (*fmt == 'z')
{
fmt++;
*have_longlong= (sizeof(size_t) == sizeof(longlong));
}
return fmt;
}
/**
Returns escaped string
@param cs string charset
@param to buffer where escaped string will be placed
@param end end of buffer
@param par string to escape
@param par_len string length
@param quote_char character for quoting
@retval
position in buffer which points on the end of escaped string
*/
static char *backtick_string(CHARSET_INFO *cs, char *to, char *end,
char *par, size_t par_len, char quote_char)
{
uint char_len;
char *start= to;
char *par_end= par + par_len;
size_t buff_length= (size_t) (end - to);
if (buff_length <= par_len)
goto err;
*start++= quote_char;
for ( ; par < par_end; par+= char_len)
{
uchar c= *(uchar *) par;
if (!(char_len= my_mbcharlen(cs, c)))
char_len= 1;
if (char_len == 1 && c == (uchar) quote_char )
{
if (start + 1 >= end)
goto err;
*start++= quote_char;
}
if (start + char_len >= end)
goto err;
start= strnmov(start, par, char_len);
}
if (start + 1 >= end)
goto err;
*start++= quote_char;
return start;
err:
*to='\0';
return to;
}
/**
Prints string argument
*/
static char *process_str_arg(CHARSET_INFO *cs, char *to, char *end,
size_t width, char *par, uint print_type)
{
int well_formed_error;
size_t plen, left_len= (size_t) (end - to) + 1;
if (!par)
par = (char*) "(null)";
plen= strnlen(par, width);
if (left_len <= plen)
plen = left_len - 1;
plen= cs->cset->well_formed_len(cs, par, par + plen,
width, &well_formed_error);
if (print_type & ESCAPED_ARG)
to= backtick_string(cs, to, end, par, plen, '`');
else
to= strnmov(to,par,plen);
return to;
}
/**
Prints binary argument
*/
static char *process_bin_arg(char *to, char *end, size_t width, char *par)
{
DBUG_ASSERT(to <= end);
if (to + width + 1 > end)
width= end - to - 1; /* sign doesn't matter */
memmove(to, par, width);
to+= width;
return to;
}
/**
Prints double or float argument
*/
static char *process_dbl_arg(char *to, char *end, size_t width,
double par, char arg_type)
{
if (width == SIZE_T_MAX)
width= FLT_DIG; /* width not set, use default */
else if (width >= NOT_FIXED_DEC)
width= NOT_FIXED_DEC - 1; /* max.precision for my_fcvt() */
width= min(width, (size_t)(end-to) - 1);
if (arg_type == 'f')
to+= my_fcvt(par, (int)width , to, NULL);
else
to+= my_gcvt(par, MY_GCVT_ARG_DOUBLE, (int) width , to, NULL);
return to;
}
/**
Prints integer argument
*/
static char *process_int_arg(char *to, char *end, size_t length,
longlong par, char arg_type, uint print_type)
{
size_t res_length, to_length;
char *store_start= to, *store_end;
char buff[32];
if ((to_length= (size_t) (end-to)) < 16 || length)
store_start= buff;
if (arg_type == 'd' || arg_type == 'i')
store_end= longlong10_to_str(par, store_start, -10);
else if (arg_type == 'u')
store_end= longlong10_to_str(par, store_start, 10);
else if (arg_type == 'p')
{
store_start[0]= '0';
store_start[1]= 'x';
store_end= ll2str(par, store_start + 2, 16, 0);
}
else if (arg_type == 'o')
{
store_end= ll2str(par, store_start, 8, 0);
}
else
{
DBUG_ASSERT(arg_type == 'X' || arg_type =='x');
store_end= ll2str(par, store_start, 16, (arg_type == 'X'));
}
if ((res_length= (size_t) (store_end - store_start)) > to_length)
return to; /* num doesn't fit in output */
/* If %#d syntax was used, we have to pre-zero/pre-space the string */
if (store_start == buff)
{
length= min(length, to_length);
if (res_length < length)
{
size_t diff= (length- res_length);
bfill(to, diff, (print_type & PREZERO_ARG) ? '0' : ' ');
if (arg_type == 'p' && print_type & PREZERO_ARG)
{
if (diff > 1)
to[1]= 'x';
else
store_start[0]= 'x';
store_start[1]= '0';
}
to+= diff;
}
bmove(to, store_start, res_length);
}
to+= res_length;
return to;
}
/**
Procesed positional arguments.
@param cs string charset
@param to buffer where processed string will be place
@param end end of buffer
@param par format string
@param arg_index arg index of the first occurrence of positional arg
@param ap list of parameters
@retval
end of buffer where processed string is placed
*/
static char *process_args(CHARSET_INFO *cs, char *to, char *end,
const char* fmt, size_t arg_index, va_list ap)
{
ARGS_INFO args_arr[MAX_ARGS];
PRINT_INFO print_arr[MAX_PRINT_INFO];
uint idx= 0, arg_count= arg_index;
start:
/* Here we are at the beginning of positional argument, right after $ */
arg_index
print_arr[idx].flags= 0;
if (*fmt == '`')
{
print_arr[idx].flags|= ESCAPED_ARG;
fmt++;
}
if (*fmt == '-')
fmt++;
print_arr[idx].length= print_arr[idx].width= 0;
/* Get print length */
if (*fmt == '*')
{
fmt++;
fmt= get_length(fmt, &print_arr[idx].length, &print_arr[idx].flags);
print_arr[idx].length
DBUG_ASSERT(*fmt == '$' && print_arr[idx].length < MAX_ARGS);
args_arr[print_arr[idx].length].arg_type= 'd';
print_arr[idx].flags|= LENGTH_ARG;
arg_count= max(arg_count, print_arr[idx].length + 1);
fmt++;
}
else
fmt= get_length(fmt, &print_arr[idx].length, &print_arr[idx].flags);
if (*fmt == '.')
{
fmt++;
/* Get print width */
if (*fmt == '*')
{
fmt++;
fmt= get_width(fmt, &print_arr[idx].width);
print_arr[idx].width
DBUG_ASSERT(*fmt == '$' && print_arr[idx].width < MAX_ARGS);
args_arr[print_arr[idx].width].arg_type= 'd';
print_arr[idx].flags|= WIDTH_ARG;
arg_count= max(arg_count, print_arr[idx].width + 1);
fmt++;
}
else
fmt= get_width(fmt, &print_arr[idx].width);
}
else
print_arr[idx].width= SIZE_T_MAX;
fmt= check_longlong(fmt, &args_arr[arg_index].have_longlong);
if (*fmt == 'p')
args_arr[arg_index].have_longlong= (sizeof(void *) == sizeof(longlong));
args_arr[arg_index].arg_type= print_arr[idx].arg_type= *fmt;
print_arr[idx].arg_idx= arg_index;
print_arr[idx].begin= ++fmt;
while (*fmt && *fmt != '%')
fmt++;
if (!*fmt) /* End of format string */
{
uint i;
print_arr[idx].end= fmt;
/* Obtain parameters from the list */
for (i= 0 ; i < arg_count; i++)
{
switch (args_arr[i].arg_type) {
case 's':
case 'b':
args_arr[i].str_arg= va_arg(ap, char *);
break;
case 'f':
case 'g':
args_arr[i].double_arg= va_arg(ap, double);
break;
case 'd':
case 'i':
case 'u':
case 'x':
case 'X':
case 'o':
case 'p':
if (args_arr[i].have_longlong)
args_arr[i].longlong_arg= va_arg(ap,longlong);
else if (args_arr[i].arg_type == 'd' || args_arr[i].arg_type == 'i')
args_arr[i].longlong_arg= va_arg(ap, int);
else
args_arr[i].longlong_arg= va_arg(ap, uint);
break;
case 'c':
args_arr[i].longlong_arg= va_arg(ap, int);
break;
default:
DBUG_ASSERT(0);
}
}
/* Print result string */
for (i= 0; i <= idx; i++)
{
size_t width= 0, length= 0;
switch (print_arr[i].arg_type) {
case 's':
{
char *par= args_arr[print_arr[i].arg_idx].str_arg;
width= (print_arr[i].flags & WIDTH_ARG)
? (size_t)args_arr[print_arr[i].width].longlong_arg
: print_arr[i].width;
to= process_str_arg(cs, to, end, width, par, print_arr[i].flags);
break;
}
case 'b':
{
char *par = args_arr[print_arr[i].arg_idx].str_arg;
width= (print_arr[i].flags & WIDTH_ARG)
? (size_t)args_arr[print_arr[i].width].longlong_arg
: print_arr[i].width;
to= process_bin_arg(to, end, width, par);
break;
}
case 'c':
{
if (to == end)
break;
*to++= (char) args_arr[print_arr[i].arg_idx].longlong_arg;
break;
}
case 'f':
case 'g':
{
double d= args_arr[print_arr[i].arg_idx].double_arg;
width= (print_arr[i].flags & WIDTH_ARG) ?
(uint)args_arr[print_arr[i].width].longlong_arg : print_arr[i].width;
to= process_dbl_arg(to, end, width, d, print_arr[i].arg_type);
break;
}
case 'd':
case 'i':
case 'u':
case 'x':
case 'X':
case 'o':
case 'p':
{
/* Integer parameter */
longlong larg;
length= (print_arr[i].flags & LENGTH_ARG)
? (size_t)args_arr[print_arr[i].length].longlong_arg
: print_arr[i].length;
if (args_arr[print_arr[i].arg_idx].have_longlong)
larg = args_arr[print_arr[i].arg_idx].longlong_arg;
else if (print_arr[i].arg_type == 'd' || print_arr[i].arg_type == 'i' )
larg = (int) args_arr[print_arr[i].arg_idx].longlong_arg;
else
larg= (uint) args_arr[print_arr[i].arg_idx].longlong_arg;
to= process_int_arg(to, end, length, larg, print_arr[i].arg_type,
print_arr[i].flags);
break;
}
default:
break;
}
if (to == end)
break;
length= min(end - to , print_arr[i].end - print_arr[i].begin);
if (to + length < end)
length++;
to= strnmov(to, print_arr[i].begin, length);
}
DBUG_ASSERT(to <= end);
*to='\0'; /* End of errmessage */
return to;
}
else
{
/* Process next positional argument*/
DBUG_ASSERT(*fmt == '%');
print_arr[idx].end= fmt - 1;
idx++;
fmt++;
arg_index= 0;
fmt= get_width(fmt, &arg_index);
DBUG_ASSERT(*fmt == '$');
fmt++;
arg_count= max(arg_count, arg_index);
goto start;
}
return 0;
}
/**
Produces output string according to a format string
See the detailed documentation around <API key>
@param cs string charset
@param to buffer where processed string will be place
@param n size of buffer
@param par format string
@param ap list of parameters
@retval
length of result string
*/
size_t my_vsnprintf_ex(CHARSET_INFO *cs, char *to, size_t n,
const char* fmt, va_list ap)
{
char *start=to, *end=to+n-1;
size_t length, width;
uint print_type, have_longlong;
for (; *fmt ; fmt++)
{
if (*fmt != '%')
{
if (to == end) /* End of buffer */
break;
*to++= *fmt; /* Copy ordinary char */
continue;
}
fmt++; /* skip '%' */
length= width= 0;
print_type= 0;
/* Read max fill size (only used with %d and %u) */
if (my_isdigit(&my_charset_latin1, *fmt))
{
fmt= get_length(fmt, &length, &print_type);
if (*fmt == '$')
{
to= process_args(cs, to, end, (fmt+1), length, ap);
return (size_t) (to - start);
}
}
else
{
if (*fmt == '`')
{
print_type|= ESCAPED_ARG;
fmt++;
}
if (*fmt == '-')
fmt++;
if (*fmt == '*')
{
fmt++;
length= va_arg(ap, int);
}
else
fmt= get_length(fmt, &length, &print_type);
}
if (*fmt == '.')
{
fmt++;
if (*fmt == '*')
{
fmt++;
width= va_arg(ap, int);
}
else
fmt= get_width(fmt, &width);
}
else
width= SIZE_T_MAX;
fmt= check_longlong(fmt, &have_longlong);
if (*fmt == 's') /* String parameter */
{
reg2 char *par= va_arg(ap, char *);
to= process_str_arg(cs, to, end, width, par, print_type);
continue;
}
else if (*fmt == 'b') /* Buffer parameter */
{
char *par = va_arg(ap, char *);
to= process_bin_arg(to, end, width, par);
continue;
}
else if (*fmt == 'f' || *fmt == 'g')
{
double d= va_arg(ap, double);
to= process_dbl_arg(to, end, width, d, *fmt);
continue;
}
else if (*fmt == 'd' || *fmt == 'i' || *fmt == 'u' || *fmt == 'x' ||
*fmt == 'X' || *fmt == 'p' || *fmt == 'o')
{
/* Integer parameter */
longlong larg;
if (*fmt == 'p')
have_longlong= (sizeof(void *) == sizeof(longlong));
if (have_longlong)
larg = va_arg(ap,longlong);
else if (*fmt == 'd' || *fmt == 'i')
larg = va_arg(ap, int);
else
larg= va_arg(ap, uint);
to= process_int_arg(to, end, length, larg, *fmt, print_type);
continue;
}
else if (*fmt == 'c') /* Character parameter */
{
register int larg;
if (to == end)
break;
larg = va_arg(ap, int);
*to++= (char) larg;
continue;
}
/* We come here on '%%', unknown code or too long parameter */
if (to == end)
break;
*to++='%'; /* % used as % or unknown code */
}
DBUG_ASSERT(to <= end);
*to='\0'; /* End of errmessage */
return (size_t) (to - start);
}
/*
Limited snprintf() implementations
exported to plugins as a service, see the detailed documentation
around <API key>
*/
size_t my_vsnprintf(char *to, size_t n, const char* fmt, va_list ap)
{
return my_vsnprintf_ex(&my_charset_latin1, to, n, fmt, ap);
}
size_t my_snprintf(char* to, size_t n, const char* fmt, ...)
{
size_t result;
va_list args;
va_start(args,fmt);
result= my_vsnprintf(to, n, fmt, args);
va_end(args);
return result;
}
|
#define VPSS_SUBMODULE_NAME "DCTRL"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/sysfs.h>
#include <linux/kobject.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <mach/board-ti816x.h>
#include "core.h"
#include "system.h"
#include "dc.h"
static struct vps_dispctrl *disp_ctrl;
static void *dc_handle;
static struct vps_payload_info *dc_payload_info;
/*store the current VENC setting*/
static struct vps_dcvencinfo venc_info = {
{
{VPS_DC_VENC_HDMI,
{FVID2_STD_1080P_60, 1920, 1080, <API key>,\
148500, 60, 88, 148, 44, 4, 36, 5},
3, 0, 0},
{VPS_DC_VENC_DVO2,
{FVID2_STD_1080P_60, 1920, 1080, <API key>,\
148500, 60, 88, 148, 44, 4, 36, 5},
3, 0, 0},
{VPS_DC_VENC_SD,
{FVID2_STD_NTSC, 720, 480, FVID2_SF_INTERLACED,\
216000, 60, 12, 68, 64, 5, 41, 5},
0, 0, 0},
{VPS_DC_VENC_HDCOMP,
{FVID2_STD_1080I_60, 1920, 1080, <API key>,\
74250, 60, 88, 148, 44, 2, 15, 5},
2, 0, 0}
},
0,
VPS_DC_MAX_VENC,
};
/*store the current mode info*/
static const struct dc_vencmode_info vmode_info[] = {
{"ntsc", FVID2_STD_NTSC,
{FVID2_STD_NTSC, 720, 480, FVID2_SF_INTERLACED,
216000, 60, 12, 68, 64, 5, 41, 5}
},
{"pal", FVID2_STD_PAL,
{FVID2_STD_PAL, 720, 576, FVID2_SF_INTERLACED,
216000, 50, 16, 58, 64, 6, 31, 6}
},
{"1080p-60", FVID2_STD_1080P_60,
{FVID2_STD_1080P_60, 1920, 1080, <API key>,
148500, 60, 88, 148, 44, 4, 36, 5}
},
{"1920x1080@60", FVID2_STD_1080P_60,
{FVID2_STD_CUSTOM, 1920, 1080, <API key>,
148500, 60, 88, 148, 44, 4, 36, 5}
},
{"1080p-50", FVID2_STD_1080P_50,
{FVID2_STD_1080P_50, 1920, 1080, <API key>,
148500, 50, 528, 148, 44, 4, 36, 5}
},
{"1920x1080@50", FVID2_STD_1080P_50,
{FVID2_STD_CUSTOM, 1920, 1080, <API key>,
148500, 50, 528, 148, 44, 4, 36, 5}
},
{"1080p-30", FVID2_STD_1080P_30,
{FVID2_STD_1080P_30, 1920, 1080, <API key>,
74250, 30, 88, 148, 44, 4, 36, 5}
},
{"1920x1080@30", FVID2_STD_1080P_30,
{FVID2_STD_CUSTOM, 1920, 1080, <API key>,
74250, 30, 88, 148, 44, 4, 36, 5}
},
{"720p-60", FVID2_STD_720P_60,
{FVID2_STD_720P_60, 1280, 720, <API key>,
74250, 60, 110, 220, 40, 5, 20, 5}
},
{"1280x720@60", FVID2_STD_720P_60,
{FVID2_STD_CUSTOM, 1280, 720, <API key>,
74250, 60, 110, 220, 40, 5, 20, 5}
},
{"720p-50", FVID2_STD_720P_50,
{FVID2_STD_720P_50, 1280, 720, <API key>,
74250, 50, 440, 220, 40, 5, 20, 5}
},
{"1280x720@50", FVID2_STD_720P_50,
{ FVID2_STD_CUSTOM, 1280, 720, <API key>,
74250, 50, 440, 220, 40, 5, 20, 5}
},
{"1080i-60", FVID2_STD_1080I_60,
{FVID2_STD_1080I_60, 1920, 1080, FVID2_SF_INTERLACED,
74250, 60, 88, 148, 44, 2, 15, 5}
},
{"1920x1080@60i", FVID2_STD_1080I_60,
{FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_INTERLACED,
74250, 60, 88, 148, 44, 2, 15, 5}
},
{"1080i-50", FVID2_STD_1080I_50,
{FVID2_STD_1080I_50, 1920, 1080, FVID2_SF_INTERLACED,
742500, 50, 528, 148, 44, 2, 15, 5}
},
{"1920x1080@50i", FVID2_STD_1080I_50,
{FVID2_STD_CUSTOM, 1920, 1080, FVID2_SF_INTERLACED,
742500, 50, 528, 148, 44, 2, 15, 5}
},
/*VGA*/
{"640x480@60", FVID2_STD_VGA_60,
{FVID2_STD_CUSTOM, 640, 480, <API key>,
25088, 60, 16, 48, 96, 10, 33, 2}
},
{"640x480@72", FVID2_STD_VGA_72,
{FVID2_STD_CUSTOM, 640, 480, <API key>,
31488, 72, 24, 128, 40, 9, 29, 2}
},
{"640x480@75", FVID2_STD_VGA_75,
{FVID2_STD_CUSTOM, 640, 480, <API key>,
31488, 75, 16, 120, 64, 1, 16, 3}
},
{"640x480@85", FVID2_STD_VGA_85,
{FVID2_STD_CUSTOM, 640, 480, <API key>,
35840, 85, 56, 80, 56, 1, 25, 3}
},
/*SVGA*/
{"800x600@60", FVID2_STD_SVGA_60,
{FVID2_STD_CUSTOM, 800, 600, <API key>,
39936, 60, 40, 88, 128, 1, 23, 4}
},
{"800x600@72", FVID2_STD_SVGA_72,
{FVID2_STD_CUSTOM, 800, 600, <API key>,
49920, 72, 56, 64, 120, 37, 23, 6}
},
{"800x600@75", FVID2_STD_SVGA_75,
{FVID2_STD_CUSTOM, 800, 600, <API key>,
49400, 75, 16, 160, 80, 1, 21, 3}
},
{"800x600@85", FVID2_STD_SVGA_85,
{FVID2_STD_CUSTOM, 800, 600, <API key>,
56000, 85, 32, 152, 64, 1, 27, 3}
},
/*XGA*/
{"1024x768@60", FVID2_STD_XGA_60,
{FVID2_STD_XGA_60, 1024, 768, <API key>,
65000, 60, 24, 160, 136, 3, 29, 6}
},
{"1024x768@70", FVID2_STD_XGA_70,
{FVID2_STD_CUSTOM, 1024, 768, <API key>,
74752, 70, 24, 144, 136, 3, 29, 6}
},
{"1024x768@75", FVID2_STD_XGA_75,
{FVID2_STD_XGA_75, 1024, 768, <API key>,
78720, 75, 16, 176, 96, 1, 28, 3}
},
{"1024x768@85", FVID2_STD_XGA_85,
{FVID2_STD_CUSTOM, 1024, 768, <API key>,
94464, 85, 48, 208, 96, 1, 36, 3}
},
/*SXGA*/
{"1280x1024@60", FVID2_STD_SXGA_60,
{FVID2_STD_SXGA_60, 1280, 1024, <API key>,
108000, 60, 48, 248, 112, 1, 38, 3}
},
{"1280x1024@75", FVID2_STD_SXGA_75,
{FVID2_STD_SXGA_75, 1280, 1024, <API key>,
135000, 75, 16, 248, 144, 1, 38, 3}
},
{"1280x1024@85", FVID2_STD_SXGA_85,
{FVID2_STD_CUSTOM, 1280, 1024, <API key>,
157440, 85, 64, 224, 160, 1, 44, 3}
},
/*UXGA*/
{"1600x1200@60", FVID2_STD_UXGA_60,
{FVID2_STD_UXGA_60, 1600, 1200, <API key>,
162000, 60, 64, 304, 192, 1, 46, 3}
}
};
/*use for the venc name*/
static const struct dc_vencname_info venc_name[VPS_DC_MAX_VENC] = {
{"hdmi", VPS_DC_VENC_HDMI, VPS_DC_HDMI_BLEND, HDMI},
{"dvo2", VPS_DC_VENC_DVO2, VPS_DC_DVO2_BLEND, DVO2},
{"sd", VPS_DC_VENC_SD, VPS_DC_SDVENC_BLEND, SDVENC},
{"hdcomp", VPS_DC_VENC_HDCOMP, VPS_DC_HDCOMP_BLEND, HDCOMP}
};
/*use for pll sysfs*/
static const struct vps_sname_info pllvenc_name[] = {
{"rfclk", <API key>},
{"dclk", <API key>},
{"aclk", <API key>}
};
/*used for clock source sysfs*/
static const struct vps_sname_info vclksrc_name[] = {
{"dclk", VPS_DC_CLKSRC_VENCD},
{"dclkdiv2", <API key>},
{"dclkdiff", <API key>},
{"aclk", VPS_DC_CLKSRC_VENCA},
{"aclkdiv2", <API key>},
{"aclkdiff", <API key>}
};
/*used for output sysfs*/
static const struct vps_sname_info dfmt_name[VPS_DC_DVOFMT_MAX] = {
{"single", <API key>},
{"double", <API key>},
{"triple", <API key>},
{"triplediscrete", <API key>},
{"doublediscrete", <API key>},
};
/*used for output sysfs*/
static const struct vps_sname_info afmt_name[VPS_DC_A_OUTPUT_MAX] = {
{"composite", <API key>},
{"svideo", <API key>},
{"component", <API key>},
};
/*used for output sysfs*/
static const struct vps_sname_info datafmt_name[] = {
{"rgb888", FVID2_DF_RGB24_888},
{"yuv444p", FVID2_DF_YUV444P},
{"yuv422spuv", <API key>},
};
/*used for nodes sysfs*/
static const struct vps_sname_info dc_nodes[] = {
{"main", <API key>},
{"vcompmux", VPS_DC_VCOMP_MUX},
{"hdcompmux", VPS_DC_HDCOMP_MUX},
{"sdmux", VPS_DC_SDVENC_MUX },
{"aux", <API key>},
{"bp0", <API key>},
{"bp1", <API key>},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"sd", <API key>},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"dummy", VPS_DC_MAX_NODE_NUM},
{"vcomp", VPS_DC_VCOMP},
{"cigcons", <API key>},
{"cigin", <API key>},
{"cigncons", <API key>},
{"cigout", <API key>},
{"grpx0", <API key>},
{"grpx1", <API key>},
{"grpx2", <API key>},
{"hdmi", VPS_DC_HDMI_BLEND},
#ifdef CONFIG_ARCH_TI816X
{"hdcomp", VPS_DC_HDCOMP_BLEND},
{"dvo2", VPS_DC_DVO2_BLEND},
{"sd", VPS_DC_SDVENC_BLEND},
#else
{"dvo2", VPS_DC_DVO2_BLEND},
{"sd", VPS_DC_SDVENC_BLEND},
#endif
};
static inline void dc_lock(struct vps_dispctrl *dctrl)
{
mutex_lock(&dctrl->dcmutex);
}
static inline void dc_unlock(struct vps_dispctrl *dctrl)
{
mutex_unlock(&dctrl->dcmutex);
}
static inline bool isdigitalvenc(int vid)
{
if ((vid == VPS_DC_VENC_HDMI) ||
(vid == VPS_DC_VENC_DVO2))
return true;
return false;
}
static inline bool isdigitalclk(u32 clk)
{
if ((clk == VPS_DC_CLKSRC_VENCA) ||
(clk == <API key>) ||
(clk == <API key>))
return false;
return true;
}
static inline bool isvalidclksrc(int vid, enum vps_dcvencclksrcsel clk)
{
if ((vid == VPS_DC_VENC_HDMI) && (!isdigitalclk(clk)))
return false;
/*ti814x, DVO2 must be aclk*/
if (cpu_is_ti814x()) {
if ((vid == VPS_DC_VENC_DVO2) && (isdigitalclk(clk)))
return false;
}
return true;
}
static inline bool isvalidmode(int vid, int mid)
{
switch (vid) {
case VPS_DC_VENC_HDMI:
if (cpu_is_ti816x())
case VPS_DC_VENC_HDCOMP:
case VPS_DC_VENC_DVO2:
if ((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL))
return false;
break;
case VPS_DC_VENC_SD:
if (!((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL)))
return false;
break;
}
return true;
}
/*get the clock venc*/
static inline u32 get_plloutputvenc(int bidx)
{
struct vps_dcvencclksrc clksrc = disp_ctrl->blenders[bidx].clksrc;
if (bidx == SDVENC)
return <API key>;
if (cpu_is_ti814x())
return <API key>;
if (isdigitalclk(clksrc.clksrc))
return <API key>;
else
return <API key>;
}
/*get the pixel clock for the standard mode*/
static inline int get_pllclock(u32 mid, u32 *freq)
{
int i;
for (i = 0; i < ARRAY_SIZE(vmode_info); i++) {
if (vmode_info[i].standard == mid) {
*freq = vmode_info[i].minfo.pixelclock;
if ((mid == FVID2_STD_NTSC) ||
(mid == FVID2_STD_PAL)) {
if (cpu_is_ti814x())
*freq = 54000;
}
return 0;
}
}
return -EINVAL;
}
/*get the current format based on the mode id*/
static int <API key>(int mid,
u32 *width,
u32 *height,
u8 *scformat)
{
int i;
for (i = 0; i < ARRAY_SIZE(vmode_info); i++) {
if (mid == vmode_info[i].standard) {
*width = vmode_info[i].minfo.width;
*height = vmode_info[i].minfo.height;
*scformat = vmode_info[i].minfo.scanformat;
return 0;
}
}
return -EINVAL;
}
static int dc_get_timing(int mid, struct fvid2_modeinfo *minfo)
{
int i;
for (i = 0; i < ARRAY_SIZE(vmode_info); i++) {
if (mid == vmode_info[i].standard) {
memcpy(minfo, &vmode_info[i].minfo, sizeof(*minfo));
if ((mid == FVID2_STD_NTSC) || (mid == FVID2_STD_PAL)) {
if (cpu_is_ti814x())
minfo->pixelclock = 54000;
}
return 0;
}
}
return -EINVAL;
}
/*get the index of the desired venc id in the database*/
static int get_idx_from_vid(int vid, int *idx)
{
int i;
for (i = 0; i < disp_ctrl->numvencs; i++) {
if (vid == venc_name[i].vid) {
*idx = venc_name[i].idx;
return 0;
}
}
return -EINVAL;
}
/*get the venc id based on the name*/
static int dc_get_vencid(char *vname, int *vid)
{
int i;
for (i = 0; i < disp_ctrl->numvencs; i++) {
const struct dc_vencname_info *vnid = &venc_name[i];
if (sysfs_streq(vname, vnid->name)) {
*vid = vnid->vid;
return 0;
}
}
return -1;
}
/*get the blender id from the indx */
static int get_bid_from_idx(int idx, int *bid)
{
int i;
for (i = 0; i < disp_ctrl->numvencs; i++) {
const struct dc_vencname_info *vnid = &venc_name[i];
if (vnid->idx == idx) {
*bid = vnid->bid;
return 0;
}
}
return -1;
}
/*get the mode id based on the mode name*/
static int dc_get_modeid(char *mname, int *mid)
{
int i;
for (i = 0; i < ARRAY_SIZE(vmode_info); i++) {
const struct dc_vencmode_info *vinfo = &vmode_info[i];
if (sysfs_streq(mname, vinfo->name)) {
*mid = vinfo->standard;
return 0;
}
}
return -1;
}
/*get the node id based on the name*/
static int dc_get_nodeid(char *name, int *nid)
{
int i;
if (sysfs_streq(name, "dummy"))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(dc_nodes); i++) {
const struct vps_sname_info *ninfo = &dc_nodes[i];
if (sysfs_streq(name, ninfo->name)) {
*nid = ninfo->value;
return 0;
}
}
return -EINVAL;
}
/*get the venc information from M3*/
static int dc_get_vencinfo(struct vps_dcvencinfo *vinfo)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
memcpy(disp_ctrl->vinfo, vinfo, sizeof(struct vps_dcvencinfo));
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->vinfo_phy,
NULL);
if (r)
VPSSERR("failed to get venc info.\n");
else
memcpy(vinfo,
disp_ctrl->vinfo,
sizeof(struct vps_dcvencinfo));
return r;
}
/*is venc running*/
static int dc_isvencrunning(int vid)
{
struct vps_dcvencinfo vinfo;
int r = 0;
vinfo.numvencs = 1;
vinfo.modeinfo[0].vencid = vid;
r = dc_get_vencinfo(&vinfo);
if (!r)
return vinfo.modeinfo[0].isvencrunning;
return r;
}
/*Get the current VENC output info*/
static int dc_get_output(struct vps_dcoutputinfo *oinfo)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
/*get the venc output info*/
disp_ctrl->opinfo->vencnodenum = oinfo->vencnodenum;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->opinfo_phy,
NULL);
if (r)
VPSSERR("failed to get venc output info\n");
else
memcpy(oinfo,
disp_ctrl->opinfo,
sizeof(struct vps_dcoutputinfo));
return r;
}
/*Set the VENC outputs*/
static int dc_set_output(struct vps_dcoutputinfo *oinfo)
{
int r;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
memcpy(disp_ctrl->opinfo, oinfo, sizeof(struct vps_dcoutputinfo));
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->opinfo_phy,
NULL);
if (r)
VPSSERR("failed to set venc output\n");
return r;
}
/*set up the pll clock*/
static int dc_set_pllclock(int bidx, u32 clock)
{
struct vps_systemvpllclk pll;
int r = 0;
/*FIXME: call function of HDMI driver to set HDMI for ti814x*/
if (cpu_is_ti814x() && (bidx == HDMI))
return r;
pll.outputvenc = (enum vps_vplloutputclk)get_plloutputvenc(bidx);
pll.outputclk = clock;
r = vps_system_setpll(&pll);
return r;
}
static int dc_set_pll_by_mid(int bidx, int mid)
{
int r = 0;
u32 clock;
r = get_pllclock(mid, &clock);
if (r) {
VPSSERR("nonexit mode %d\n", mid);
return r;
}
r = dc_set_pllclock(bidx, clock);
return r;
}
/*get the clock source*/
static int dc_get_clksrc(struct vps_dcvencclksrc *clksrc)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
disp_ctrl->clksrc->venc = clksrc->venc;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->clksrc_phy,
NULL);
if (r)
VPSSERR("get clock source failed\n");
else
clksrc->clksrc = disp_ctrl->clksrc->clksrc;
return r;
}
/*set the clock source*/
static int dc_set_clksrc(struct vps_dcvencclksrc *clksrc)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
if (!isvalidclksrc(clksrc->venc, clksrc->clksrc)) {
VPSSERR("invalid clock source\n");
return -EINVAL;
}
disp_ctrl->clksrc->venc = clksrc->venc;
disp_ctrl->clksrc->clksrc = clksrc->clksrc;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->clksrc_phy,
NULL);
if (r)
VPSSERR("set clock source failed\n");
return r;
}
/*get the format based on the venc id*/
static int <API key>(int vid,
u32 *width,
u32 *height,
u8 *scformat)
{
int r = 0;
struct vps_dcvencinfo vinfo;
vinfo.numvencs = 1;
vinfo.modeinfo[0].vencid = vid;
r = dc_get_vencinfo(&vinfo);
if (r)
return -EINVAL;
if (vinfo.modeinfo[0].minfo.standard == FVID2_STD_CUSTOM) {
*width = vinfo.modeinfo[0].minfo.width;
*height = vinfo.modeinfo[0].minfo.height;
*scformat = vinfo.modeinfo[0].minfo.scanformat;
} else {
r = <API key>(vinfo.modeinfo[0].minfo.standard,
width,
height,
scformat);
}
return 0;
}
/*get the format based on the blender id*/
static int <API key>(int bid,
u32 *width,
u32 *height,
u8 *scformat)
{
int i;
int r = -EINVAL;
for (i = 0; i < disp_ctrl->numvencs; i++) {
if (bid == venc_name[i].bid) {
r = <API key>(venc_name[i].vid,
width,
height,
scformat);
break;
}
}
return r;
}
/*disable the desired vencs*/
static int dc_venc_disable(int vid)
{
int i = 0;
int r = 0;
struct vps_dcvencinfo vinfo;
int venc_ids = vid;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
if (vid == 0)
return 0;
if (vid & (~disp_ctrl->vencmask)) {
VPSSERR("wrong venc id.\n");
return -EINVAL;
}
VPSSDBG("enter venc disable\n");
vinfo.numvencs = 0;
/*get the id of each venc to be disabled*/
while (venc_ids >> i) {
if ((venc_ids >> i++) & 1)
vinfo.modeinfo[vinfo.numvencs++].vencid =
1 << (i - 1);
}
r = dc_get_vencinfo(&vinfo);
if (r) {
VPSSERR("faild to get venc info.\n");
return r;
}
venc_ids = vid;
for (i = 0; i < vinfo.numvencs; i++) {
if (vinfo.modeinfo[i].isvencrunning == 0) {
VPSSERR("venc %d already stop\n",
vinfo.modeinfo[i].vencid);
venc_ids &= ~vinfo.modeinfo[i].vencid;
}
}
if (venc_ids && !r) {
*disp_ctrl->dis_vencs = venc_ids;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->dis_vencsphy,
NULL);
if (r == 0) {
disp_ctrl->enabled_venc_ids &= ~venc_ids;
if (disp_ctrl->tiedvenc) {
disp_ctrl->tiedvenc &= ~venc_ids;
venc_ids = 0;
i = 0;
/*calculate how vencs left in tied list*/
while (disp_ctrl->tiedvenc >> i) {
if ((disp_ctrl->tiedvenc >> i++) & 1)
venc_ids++;
}
/*if one venc left,set tiedvenc to zero*/
if (venc_ids == 1)
disp_ctrl->tiedvenc = 0;
}
} else
VPSSERR("failed to disable the venc.\n");
}
return r;
}
/*set the mode for desired vencs*/
static int dc_set_vencmode(struct vps_dcvencinfo *vinfo)
{
int i, r = 0;
int vencs = 0;
struct vps_dcvencinfo vi;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
/*get the current setting based on the app inputs*/
for (i = 0; i < vinfo->numvencs; i++)
vi.modeinfo[i].vencid = vinfo->modeinfo[i].vencid;
vi.numvencs = vinfo->numvencs;
r = dc_get_vencinfo(&vi);
if (r) {
VPSSERR("failed to get venc info.\n");
goto exit;
}
/*make sure current venc status is matching */
disp_ctrl->vinfo->numvencs = 0;
disp_ctrl->vinfo->tiedvencs = 0;
for (i = 0; i < vinfo->numvencs; i++) {
if (vi.modeinfo[i].isvencrunning) {
if (vi.modeinfo[i].minfo.standard !=
vinfo->modeinfo[i].minfo.standard) {
r = -EINVAL;
VPSSERR("venc %d already running with \
different mode\n",
vi.modeinfo[i].vencid);
goto exit;
} else
VPSSDBG("venc %d already running\n",
vi.modeinfo[i].vencid);
} else {
memcpy(&disp_ctrl->vinfo->modeinfo \
[disp_ctrl->vinfo->numvencs++],
&vinfo->modeinfo[i],
sizeof(struct vps_dcmodeinfo));
vencs |= vinfo->modeinfo[i].vencid;
}
}
if (vinfo->tiedvencs) {
if ((vencs & vinfo->tiedvencs) != vinfo->tiedvencs) {
r = -EINVAL;
VPSSERR("can not tied venc\n");
goto exit;
} else
disp_ctrl->vinfo->tiedvencs = vinfo->tiedvencs;
}
if (disp_ctrl->vinfo->numvencs) {
/*set the VENC Mode*/
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->vinfo_phy,
NULL);
if (r) {
VPSSERR("failed to set venc mdoe.\n");
goto exit;
}
disp_ctrl->enabled_venc_ids |= vencs;
}
exit:
return r;
}
static int dc_enum_node_input(struct vps_dispctrl *dctrl,
struct vps_dcenumnodeinput *eninput)
{
int r = 0;
if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL))
return -EINVAL;
*dctrl->dceninput = *eninput;
r = vps_fvid2_control(dctrl->fvid2_handle,
<API key>,
(void *)dctrl->dceninput_phy,
NULL);
if (!r)
*eninput = *dctrl->dceninput;
return r;
}
static int dc_get_node_status(struct vps_dispctrl *dctrl,
struct vps_dcnodeinput *ninput)
{
int r = 0;
if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL))
return -EINVAL;
*dctrl->nodeinfo = *ninput;
r = vps_fvid2_control(dctrl->fvid2_handle,
<API key>,
(void *)dctrl->ninfo_phy,
NULL);
if (r)
VPSSERR("failed to get node status\n");
else
*ninput = *dctrl->nodeinfo;
return r;
}
static int <API key>(struct vps_dispctrl *dctrl,
struct vps_dccomprtconfig *compcfg)
{
int r = 0;
if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL))
return -EINVAL;
dctrl->comprtcfg->nodeid = compcfg->nodeid;
r = vps_fvid2_control(dctrl->fvid2_handle,
<API key>,
(void *)dctrl->comprtcfg_phy,
NULL);
if (r)
VPSSERR("Get compositor RT config failed\n");
else
*compcfg = *dctrl->comprtcfg;
return r;
}
static int <API key>(struct vps_dispctrl *dctrl,
struct vps_dccomprtconfig *compcfg)
{
int r = 0;
if ((dctrl == NULL) || (dctrl->fvid2_handle == NULL))
return -EINVAL;
*dctrl->comprtcfg = *compcfg;
r = vps_fvid2_control(dctrl->fvid2_handle,
<API key>,
(void *)dctrl->comprtcfg_phy,
NULL);
if (r)
VPSSERR("Set compositor RT config failed\n");
return r;
}
/*get the id(venc,blender,mode) based on the name*/
int vps_dc_get_id(char *name, int *id, enum dc_idtype type)
{
int r = -EINVAL;
switch (type) {
case DC_BLEND_ID:
case DC_NODE_ID:
r = dc_get_nodeid(name, id);
break;
case DC_VENC_ID:
r = dc_get_vencid(name, id);
break;
case DC_MODE_ID:
r = dc_get_modeid(name, id);
break;
}
return r;
}
/*get the tied venc information*/
int vps_dc_get_tiedvenc(u8 *tiedvenc)
{
*tiedvenc = disp_ctrl->tiedvenc;
return 0;
}
/*set the streaming on the blender, not used*/
void vps_dc_set_actnodes(u8 setflag, u8 bidx)
{
struct dc_blender_info *binfo = &disp_ctrl->blenders[bidx];
if (setflag)
binfo->actnodes++;
else
if (binfo->actnodes != 0)
binfo->actnodes
}
/*get the venc infor for the desired vencs*/
int vps_dc_get_vencinfo(struct vps_dcvencinfo *vinfo)
{
int r;
dc_lock(disp_ctrl);
r = dc_get_vencinfo(vinfo);
dc_unlock(disp_ctrl);
return r;
}
/*get the node name based on the id*/
int <API key>(int id, char *name)
{
int i;
for (i = 0; i < ARRAY_SIZE(dc_nodes); i++) {
const struct vps_sname_info *ninfo = &dc_nodes[i];
if (id == ninfo->value) {
strcpy(name, (char *)ninfo->name);
return 0;
}
}
return -EINVAL;
}
/*set dc config not used now*/
int vps_dc_set_config(struct vps_dcconfig *usercfg, int setflag)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
if (usercfg->vencinfo.numvencs > disp_ctrl->numvencs) {
VPSSERR("num vens (%d) over max\n",
usercfg->vencinfo.numvencs);
return -EINVAL;
}
if (usercfg->vencinfo.tiedvencs & (~disp_ctrl->tiedvenc)) {
VPSSERR("tied venc not match.\n");
return -EINVAL;
}
VPSSDBG("enter set config\n");
dc_lock(disp_ctrl);
memcpy(disp_ctrl->dccfg, usercfg, sizeof(struct vps_dcconfig));
if (setflag) {
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->dccfg_phy,
NULL);
if (r)
VPSSDBG("faield to set the DC config.\n");
} else {
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->dccfg_phy,
NULL);
if (r)
VPSSDBG("faield to clear the DC config.\n");
}
dc_unlock(disp_ctrl);
return r;
}
/*get current venc output format*/
int vps_dc_get_outpfmt(int id, u32 *width,
u32 *height,
u8 *scformat,
enum dc_idtype type)
{
int r;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
VPSSDBG("enter get output format\n");
dc_lock(disp_ctrl);
if (type == DC_VENC_ID)
r = <API key>(id, width, height, scformat);
else if (type == DC_BLEND_ID)
r = <API key>(id, width, height, scformat);
else if (type == DC_MODE_ID)
r = <API key>(id, width, height, scformat);
else
r = -EINVAL;
dc_unlock(disp_ctrl);
return r;
}
/* set/clear the node path/edge */
int vps_dc_set_node(u8 nodeid, u8 inputid, u8 enable)
{
int r = 0;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL))
return -EINVAL;
VPSSDBG("enter set node\n");
dc_lock(disp_ctrl);
disp_ctrl->nodeinfo->nodeid = nodeid;
disp_ctrl->nodeinfo->inputid = inputid;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->ninfo_phy,
NULL);
if (r) {
VPSSERR("failed to get node input status\n");
goto exit;
}
if (disp_ctrl->nodeinfo->isenable == enable) {
if (enable)
VPSSDBG("node already connected\n");
else
VPSSDBG("node already disconnected\n");
goto exit;
}
/*call ioctl to set/clear the node */
disp_ctrl->nodeinfo->isenable = enable;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->ninfo_phy,
NULL);
if (r)
VPSSERR("failed to enable node.\n");
exit:
dc_unlock(disp_ctrl);
return r;
}
int vps_dc_set_color(struct vps_dccigrtconfig *cigconfig)
{
int r;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL) ||
(cigconfig == NULL))
return -EINVAL;
VPSSDBG("set color\n");
dc_lock(disp_ctrl);
memcpy(disp_ctrl->cigcfg, cigconfig, sizeof(*cigconfig));
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->cigcfg_phy,
NULL);
if (r)
VPSSERR("failed to set CIG color\n");
dc_unlock(disp_ctrl);
return r;
}
int vps_dc_get_color(struct vps_dccigrtconfig *cigconfig)
{
int r;
if ((disp_ctrl == NULL) || (disp_ctrl->fvid2_handle == NULL) ||
(cigconfig == NULL))
return -EINVAL;
VPSSDBG("get color\n");
dc_lock(disp_ctrl);
disp_ctrl->cigcfg->nodeid = cigconfig->nodeid;
r = vps_fvid2_control(disp_ctrl->fvid2_handle,
<API key>,
(void *)disp_ctrl->cigcfg_phy,
NULL);
if (!r)
memcpy(cigconfig, disp_ctrl->cigcfg, sizeof(*cigconfig));
else
VPSSERR("failed to get cig color\n");
dc_unlock(disp_ctrl);
return r;
}
int <API key>(struct vps_dcenumnodeinput *eninput)
{
int r = 0;
VPSSDBG("enum node input\n");
dc_lock(disp_ctrl);
r = dc_enum_node_input(disp_ctrl, eninput);
dc_unlock(disp_ctrl);
return r;
}
int <API key>(struct vps_dcnodeinput *ninput)
{
int r = 0;
VPSSDBG("get node status\n");
dc_lock(disp_ctrl);
r = dc_get_node_status(disp_ctrl, ninput);
dc_unlock(disp_ctrl);
return r;
}
int vps_dc_get_timing(u32 bid, struct fvid2_modeinfo *tinfo)
{
int i;
for (i = 0; i < disp_ctrl->numvencs; i++) {
if (bid == venc_name[i].bid) {
*tinfo = venc_info.modeinfo[i].minfo;
if ((tinfo->standard == FVID2_STD_NTSC) ||
(tinfo->standard == FVID2_STD_PAL)) {
if (cpu_is_ti814x())
tinfo->pixelclock = 54000;
}
return 0;
}
}
return -EINVAL;
}
/*sysfs function for blender starting from here*/
static ssize_t blender_mode_show(struct dc_blender_info *binfo, char *buf)
{
int i;
u32 idx = binfo->idx;
int l = 0;
for (i = 0; i < ARRAY_SIZE(vmode_info); i++) {
u32 standard = venc_info.modeinfo[idx].minfo.standard;
if (standard == FVID2_STD_CUSTOM) {
if (venc_info.modeinfo[idx].minfo.scanformat ==
FVID2_SF_INTERLACED)
l = snprintf(buf, PAGE_SIZE, "%ux%u@%ui\n",
venc_info.modeinfo[idx].minfo.width,
venc_info.modeinfo[idx].minfo.height,
venc_info.modeinfo[idx].minfo.fps);
else
l = snprintf(buf, PAGE_SIZE, "%ux%u@%u\n",
venc_info.modeinfo[idx].minfo.width,
venc_info.modeinfo[idx].minfo.height,
venc_info.modeinfo[idx].minfo.fps);
} else if (vmode_info[i].standard == standard) {
l = snprintf(buf, PAGE_SIZE, "%s\n",
vmode_info[i].name);
break;
}
}
return l;
}
static ssize_t blender_mode_store(struct dc_blender_info *binfo,
const char *buf, size_t size)
{
int r = 0;
u32 idx = binfo->idx;
u32 mid;
dc_lock(binfo->dctrl);
/*venc should be stop before changes*/
if (dc_isvencrunning(venc_info.modeinfo[idx].vencid)) {
VPSSERR("stop venc before changing mode\n");
r = -EINVAL;
goto exit;
}
if (dc_get_modeid((char *)buf, &mid)) {
VPSSERR("failed to get the mode %s.", buf);
r = -EINVAL;
goto exit;
}
/*make sure the mode is supported by the venc*/
if (!isvalidmode(venc_info.modeinfo[idx].vencid, mid))
goto exit;
/*only set the PLL if it is auto mode*/
if (binfo->dctrl->automode) {
r = dc_set_pll_by_mid(binfo->idx, mid);
if (r)
goto exit;
}
venc_info.modeinfo[idx].minfo.standard = mid;
dc_get_timing(mid, &venc_info.modeinfo[idx].minfo);
#ifdef CONFIG_ARCH_TI816X
if (cpu_is_ti816x()) {
if ((binfo->idx == HDCOMP) && (binfo->isdeviceon == true)) {
if ((mid == FVID2_STD_1080P_60) ||
(mid == FVID2_STD_1080P_50))
r = <API key>(
<API key>);
else
r = <API key>(
<API key>);
if (r < 0) {
VPSSERR("failed to set THS filter\n");
goto exit;
}
}
}
#endif
r = size;
exit:
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t <API key>(struct dc_blender_info *binfo, char *buf)
{
int r;
struct fvid2_modeinfo *t;
t = &venc_info.modeinfo[binfo->idx].minfo;
r = snprintf(buf,
PAGE_SIZE,
"%u,%u/%u/%u/%u,%u/%u/%u/%u,%u\n",
t->pixelclock,
t->width, t->hfrontporch, t->hbackporch, t->hsynclen,
t->height, t->vfrontporch, t->vbackporch, t->vsynclen,
t->scanformat);
return r;
}
static ssize_t <API key>(struct dc_blender_info *binfo,
const char *buf, size_t size)
{
int r = 0;
struct fvid2_modeinfo t;
u32 num;
u32 vmode;
if (binfo->idx == SDVENC)
return -EINVAL;
dc_lock(binfo->dctrl);
/*venc should be stop before changes*/
if (dc_isvencrunning(venc_info.modeinfo[binfo->idx].vencid)) {
VPSSERR("stop venc before changing timing\n");
r = -EINVAL;
goto exit;
}
num = sscanf(buf, "%u,%u/%u/%u/%u,%u/%u/%u/%u,%u/%u",
&t.pixelclock,
&t.width, &t.hfrontporch, &t.hbackporch, &t.hsynclen,
&t.height, &t.vfrontporch, &t.vbackporch, &t.vsynclen,
&t.scanformat, &vmode);
if (!((num == 11) || (num == 10))) {
r = -EINVAL;
VPSSERR("wrong timing input %d\n", num);
goto exit;
}
/*if use did not assign mode, than we fix it to 1*/
if (num == 10)
vmode = 1;
memcpy(&venc_info.modeinfo[binfo->idx].minfo, &t, sizeof(t));
venc_info.modeinfo[binfo->idx].minfo.standard = FVID2_STD_CUSTOM;
venc_info.modeinfo[binfo->idx].mode = vmode;
/*calculate the refresh rate*/
venc_info.modeinfo[binfo->idx].minfo.fps =
(t.pixelclock * 1000) /
((t.width + t.hfrontporch + t.hbackporch + t.hsynclen) *
(t.height + t.vfrontporch + t.vbackporch + t.vsynclen));
if (t.scanformat == 0)
venc_info.modeinfo[binfo->idx].minfo.fps *= 2;
r = dc_set_pllclock(binfo->idx, t.pixelclock);
if (r) {
VPSSERR("failed to set %dKHz clock\n",
t.pixelclock);
r = -EINVAL;
goto exit;
}
r = size;
exit:
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t <API key>(struct dc_blender_info *binfo, char *buf)
{
int r;
struct vps_dcvencinfo vinfo;
dc_lock(binfo->dctrl);
vinfo.numvencs = 1;
vinfo.modeinfo[0].vencid = venc_name[binfo->idx].vid;
r = dc_get_vencinfo(&vinfo);
if (r) {
VPSSERR(" Failed to get venc infor\n");
r = -EINVAL;
goto exit;
}
r = snprintf(buf, PAGE_SIZE, "%d\n", vinfo.modeinfo[0].isvencrunning);
exit:
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t <API key>(struct dc_blender_info *binfo,
const char *buf,
size_t size)
{
int enabled;
int vid;
int r = 0;
enabled = simple_strtoul(buf, NULL, 10);
dc_lock(disp_ctrl);
/*get vid id*/
vid = venc_name[binfo->idx].vid;
if (enabled == 0) {
r = dc_venc_disable(vid);
if (r) {
VPSSERR("failed to disable %s venc\n",
binfo->name);
r = -EINVAL;
goto exit;
}
} else {
int idx;
struct vps_dcvencinfo vinfo;
get_idx_from_vid(vid, &idx);
memcpy(&vinfo.modeinfo[0],
&venc_info.modeinfo[idx],
sizeof(struct vps_dcvencinfo));
vinfo.numvencs = 1;
vinfo.tiedvencs = 0;
r = dc_set_vencmode(&vinfo);
if (r) {
VPSSERR("failed to enable venc %s\n",
binfo->name);
r = -EINVAL;
goto exit;
}
}
r = size;
exit:
dc_unlock(disp_ctrl);
return r;
}
static ssize_t blender_clksrc_show(struct dc_blender_info *binfo, char *buf)
{
int r = 0;
struct vps_dcvencclksrc *clksrc = &binfo->clksrc;
if (binfo->idx == SDVENC) {
VPSSERR("no clock soure for SD VENC\n");
return -EINVAL;
}
dc_lock(binfo->dctrl);
clksrc->venc = venc_name[binfo->idx].vid;
r = dc_get_clksrc(clksrc);
dc_unlock(binfo->dctrl);
if (r)
return r;
else
return snprintf(buf, PAGE_SIZE, "%s\n",
vclksrc_name[clksrc->clksrc].name);
}
static ssize_t <API key>(struct dc_blender_info *binfo,
const char *buf,
size_t size)
{
int r = 0, i;
struct vps_dcvencclksrc clksrc;
bool found = false;
if (binfo->idx == SDVENC) {
VPSSERR("no clock soure for SD VENC\n");
return -EINVAL;
}
dc_lock(binfo->dctrl);
clksrc.venc = venc_name[binfo->idx].vid;
if (dc_isvencrunning(clksrc.venc)) {
VPSSERR("please stop venc before changing clock source\n");
r = -EINVAL;
goto exit;
}
/*found the matching clock source*/
for (i = 0; i < ARRAY_SIZE(vclksrc_name); i++) {
if (sysfs_streq(buf, vclksrc_name[i].name)) {
clksrc.clksrc = vclksrc_name[i].value;
found = true;
break;
}
}
/*set the clock source*/
if (found == true) {
r = dc_set_clksrc(&clksrc);
if (!r) {
r = size;
/*store back*/
binfo->clksrc.clksrc = clksrc.clksrc;
}
} else {
r = -EINVAL;
VPSSERR("invalid clock source input\n");
}
exit:
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t blender_output_show(struct dc_blender_info *binfo, char *buf)
{
struct vps_dcoutputinfo oinfo;
int r = 0;
int l = 0, i;
oinfo.vencnodenum = venc_name[binfo->idx].vid;
dc_lock(binfo->dctrl);
r = dc_get_output(&oinfo);
dc_unlock(binfo->dctrl);
if (r)
return -EINVAL;
if (isdigitalvenc(oinfo.vencnodenum))
l += snprintf(buf + l,
PAGE_SIZE - l, "%s",
dfmt_name[oinfo.dvofmt].name);
else
l += snprintf(buf + l,
PAGE_SIZE - l, "%s",
afmt_name[oinfo.afmt].name);
for (i = 0 ; i < ARRAY_SIZE(datafmt_name); i++) {
if (datafmt_name[i].value == oinfo.dataformat)
l += snprintf(buf + l,
PAGE_SIZE - l, ",%s\n",
datafmt_name[i].name);
}
return l;
}
static ssize_t <API key>(struct dc_blender_info *binfo,
const char *buf,
size_t size)
{
struct vps_dcoutputinfo oinfo;
int r = 0;
char *input = (char *)buf;
char *ptr;
enum vps_dcdigitalfmt dfmt = VPS_DC_DVOFMT_MAX;
enum vps_dcanalogfmt afmt = VPS_DC_A_OUTPUT_MAX;
enum fvid2_dataformat fmt = FVID2_DF_MAX;
oinfo.vencnodenum = venc_name[binfo->idx].vid;
dc_lock(binfo->dctrl);
/*venc should be off before changed output*/
if (dc_isvencrunning(oinfo.vencnodenum)) {
VPSSERR("please disable VENC before changing output\n");
r = -EINVAL;
goto exit;
}
dc_get_output(&oinfo);
/*process the input buf*/
while ((ptr = strsep(&input, ",")) != NULL) {
int i;
bool found;
found = false;
/*check data format first*/
for (i = 0; i < ARRAY_SIZE(datafmt_name); i++) {
if (sysfs_streq(ptr, datafmt_name[i].name)) {
fmt = datafmt_name[i].value;
found = true;
}
}
/*check digital format or analog format based on current venc*/
if (!found) {
if (isdigitalvenc(oinfo.vencnodenum)) {
for (i = 0; i < VPS_DC_DVOFMT_MAX; i++)
if (sysfs_streq(ptr,
dfmt_name[i].name)) {
dfmt = dfmt_name[i].value;
found = true;
break;
}
} else {
for (i = 0; i < VPS_DC_A_OUTPUT_MAX; i++)
if (sysfs_streq(ptr,
afmt_name[i].name)) {
afmt = afmt_name[i].value;
found = true;
break;
}
}
if (found == false) {
VPSSERR("invalid output value %s\n", ptr);
r = -EINVAL;
goto exit;
}
}
if (input == NULL)
break;
}
/*make sure the input is right before send out to M3*/
if (isdigitalvenc(oinfo.vencnodenum)) {
if ((dfmt == VPS_DC_DVOFMT_MAX) && (fmt == FVID2_DF_MAX)) {
VPSSERR("no valid digital output settings\n");
r = -EINVAL;
goto exit;
}
if (dfmt != VPS_DC_DVOFMT_MAX)
oinfo.dvofmt = dfmt;
} else {
if ((afmt == VPS_DC_A_OUTPUT_MAX) && (fmt == FVID2_DF_MAX)) {
VPSSERR("no valid analog output settings\n");
r = -EINVAL;
goto exit;
}
if ((binfo->idx == SDVENC) &&
(afmt == <API key>)) {
VPSSERR("component out not supported on sdvenc\n");
r = -EINVAL;
goto exit;
}
if (afmt != VPS_DC_A_OUTPUT_MAX)
oinfo.afmt = afmt;
}
if (fmt != FVID2_DF_MAX)
oinfo.dataformat = fmt;
r = dc_set_output(&oinfo);
if (!r)
r = size;
exit:
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t blender_order_show(struct dc_blender_info *binfo, char *buf)
{
int r;
int l;
struct vps_dccomprtconfig comprtcfg;
r = get_bid_from_idx(binfo->idx, &comprtcfg.nodeid);
if (r)
return r;
dc_lock(binfo->dctrl);
r = <API key>(binfo->dctrl, &comprtcfg);
dc_unlock(binfo->dctrl);
if (r)
return r;
if (comprtcfg.<API key>)
l = snprintf(buf, PAGE_SIZE, "%u,%u/%u/%u/%u\n",
comprtcfg.<API key>,
comprtcfg.displayorder[0],
comprtcfg.displayorder[1],
comprtcfg.displayorder[2],
comprtcfg.displayorder[3]);
else
l = snprintf(buf, PAGE_SIZE, "%u,%u\n",
comprtcfg.<API key>,
comprtcfg.displayorder[0]);
return l;
}
static ssize_t blender_order_store(struct dc_blender_info *binfo,
const char *buf,
size_t size)
{
int r;
int num;
struct vps_dccomprtconfig comprtcfg;
r = get_bid_from_idx(binfo->idx, &comprtcfg.nodeid);
if (r)
return r;
num = sscanf(buf, "%u,%u/%u/%u/%u",
&comprtcfg.<API key>,
&comprtcfg.displayorder[0],
&comprtcfg.displayorder[1],
&comprtcfg.displayorder[2],
&comprtcfg.displayorder[3]);
/*error check*/
if (comprtcfg.<API key> == 1) {
if (num != 5) {
VPSSERR("Wrong display re-order format\n");
return -EINVAL;
}
} else {
if (num < 2) {
VPSSERR("Wrong display re-order format\n");
return -EINVAL;
}
}
dc_lock(binfo->dctrl);
r = <API key>(binfo->dctrl, &comprtcfg);
if (!r)
r = size;
dc_unlock(binfo->dctrl);
return r;
}
static ssize_t blender_name_show(struct dc_blender_info *binfo, char *buf)
{
return snprintf(buf, PAGE_SIZE,
"%s\n", venc_name[binfo->idx].name);
}
struct blender_attribute {
struct attribute attr;
ssize_t (*show)(struct dc_blender_info *, char *);
ssize_t (*store)(struct dc_blender_info *, const char *, size_t);
};
#define BLENDER_ATTR(_name, _mode, _show, _store) \
struct blender_attribute blender_attr_##_name = \
__ATTR(_name, _mode, _show, _store)
static BLENDER_ATTR(name, S_IRUGO, blender_name_show, NULL);
static BLENDER_ATTR(mode, S_IRUGO | S_IWUSR,
blender_mode_show, blender_mode_store);
static BLENDER_ATTR(timings, S_IRUGO | S_IWUSR,
<API key>, <API key>);
static BLENDER_ATTR(enabled, S_IRUGO | S_IWUSR,
<API key>, <API key>);
static BLENDER_ATTR(output, S_IRUGO | S_IWUSR,
blender_output_show, <API key>);
static BLENDER_ATTR(clksrc, S_IRUGO | S_IWUSR,
blender_clksrc_show, <API key>);
static BLENDER_ATTR(order, S_IRUGO | S_IWUSR,
blender_order_show, blender_order_store);
static struct attribute *blender_sysfs_attrs[] = {
&blender_attr_mode.attr,
&<API key>.attr,
&<API key>.attr,
&blender_attr_output.attr,
&blender_attr_clksrc.attr,
&blender_attr_order.attr,
&blender_attr_name.attr,
NULL
};
static ssize_t blender_attr_show(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
struct dc_blender_info *binfo = NULL;
struct blender_attribute *blend_attr = NULL;
binfo = container_of(kobj, struct dc_blender_info, kobj);
blend_attr = container_of(attr, struct blender_attribute, attr);
if (!blend_attr->show)
return -ENOENT;
return blend_attr->show(binfo, buf);
}
static ssize_t blender_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t size)
{
struct dc_blender_info *blend;
struct blender_attribute *blend_attr;
blend = container_of(kobj, struct dc_blender_info, kobj);
blend_attr = container_of(attr, struct blender_attribute, attr);
if (!blend_attr->store)
return -ENOENT;
return blend_attr->store(blend, buf, size);
}
static const struct sysfs_ops blender_sysfs_ops = {
.show = blender_attr_show,
.store = blender_attr_store,
};
static struct kobj_type blender_ktype = {
.sysfs_ops = &blender_sysfs_ops,
.default_attrs = blender_sysfs_attrs,
};
/*sysfs for the display controller*/
static ssize_t dctrl_pllclks_show(struct vps_dispctrl *dctrl, char *buf)
{
int r = 0, l = 0, i;
struct vps_systemvpllclk pllclk;
for (i = 0; i < <API key>; i++) {
pllclk.outputvenc = (enum vps_vplloutputclk)i;
/*no need for APLL for TI814X*/
if ((pllclk.outputvenc == <API key>) &&
cpu_is_ti814x())
continue;
r = vps_system_getpll(&pllclk);
if (r)
return -EINVAL;
if (i == 0)
l += snprintf(buf + l,
PAGE_SIZE - l,
"%s:%d",
pllvenc_name[i].name,
pllclk.outputclk);
else
l += snprintf(buf + l,
PAGE_SIZE - l,
",%s:%d",
pllvenc_name[i].name,
pllclk.outputclk);
}
l += snprintf(buf + l,
PAGE_SIZE - l,
"\n");
return l;
}
static ssize_t dctrl_pllclks_store(struct vps_dispctrl *dctrl,
const char *buf,
size_t size)
{
struct vps_systemvpllclk pllclk;
char *input = (char *)buf, *this_opt;
int r = 0;
if (dctrl->automode) {
VPSSERR("please turn off automode first\n");
return -EINVAL;
}
dc_lock(dctrl);
while (!r && (this_opt = strsep(&input, ",")) != NULL) {
char *p, *venc_str, *clk_str;
int i;
p = strchr(this_opt, ':');
if (!p)
break;
*p = 0;
venc_str = this_opt;
clk_str = p + 1;
pllclk.outputvenc = <API key>;
pllclk.outputclk = 0xFFFFFFFF;
/*get the output venc*/
for (i = 0; i < <API key>; i++) {
if (sysfs_streq(venc_str, pllvenc_name[i].name)) {
pllclk.outputvenc = pllvenc_name[i].value;
break;
}
}
if (i == <API key>) {
VPSSERR("wrong venc %s\n", venc_str);
r = -EINVAL;
goto exit;
}
if ((pllclk.outputvenc == <API key>) &&
cpu_is_ti814x()) {
VPSSERR("Invalid VENCA PLL\n");
r = -EINVAL;
goto exit;
}
/*get the pll clk*/
pllclk.outputclk = simple_strtoul((const char *)clk_str,
NULL,
10);
r = vps_system_setpll(&pllclk);
if (r)
VPSSERR("set freq %s for %s failed\n",
clk_str, venc_str);
if (input == NULL)
break;
}
if (!r)
r = size;
exit:
dc_unlock(dctrl);
return r;
}
static ssize_t dctrl_automode_show(struct vps_dispctrl *dctrl, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", dctrl->automode);
}
static ssize_t <API key>(struct vps_dispctrl *dctrl,
const char *buf,
size_t size)
{
int enabled;
enabled = simple_strtoul(buf, NULL, 10);
dctrl->automode = (bool)enabled;
return size;
}
static ssize_t <API key>(struct vps_dispctrl *dctrl, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", disp_ctrl->tiedvenc);
}
static ssize_t <API key>(struct vps_dispctrl *dctrl,
const char *buf,
size_t size)
{
int r = 0;
int vencs = 0;
int i = 0;
struct vps_dcvencinfo vinfo;
dc_lock(disp_ctrl);
vencs = simple_strtoul(buf, NULL, 10);
if (vencs & ~disp_ctrl->vencmask) {
r = -EINVAL;
VPSSERR("vencs %d over limit\n", vencs);
goto exit;
}
if ((vencs == 0) || (disp_ctrl->tiedvenc == vencs)) {
r = size;
goto exit;
}
vinfo.numvencs = 0;
vinfo.tiedvencs = vencs;
/*assemble the structure based on the venc id*/
while (vencs >> i) {
/*get id of each venc to be tied*/
if ((vencs >> i++) & 1) {
int idx;
int vid = 1 << (i - 1);
get_idx_from_vid(vid, &idx);
memcpy(&vinfo.modeinfo[vinfo.numvencs++],
&venc_info.modeinfo[idx],
sizeof(struct vps_dcmodeinfo));
}
}
if (vinfo.numvencs < 2) {
VPSSERR("at least 2 vencs to tied.\n");
r = -EINVAL;
goto exit;
}
/*set the tied venc mode*/
r = dc_set_vencmode(&vinfo);
if (r) {
VPSSERR("failed to set tied venc\n");
r = -EINVAL;
goto exit;
}
disp_ctrl->tiedvenc = vinfo.tiedvencs;
r = size;
exit:
dc_unlock(disp_ctrl);
return r;
}
struct dctrl_attribute {
struct attribute attr;
ssize_t (*show)(struct vps_dispctrl *, char *);
ssize_t (*store)(struct vps_dispctrl *, const char *, size_t);
};
#define DCTRL_ATTR(_name, _mode, _show, _store) \
struct dctrl_attribute dctrl_attr_##_name = \
__ATTR(_name, _mode, _show, _store)
static DCTRL_ATTR(tiedvencs, S_IRUGO | S_IWUSR,
<API key>, <API key>);
static DCTRL_ATTR(pllclks, S_IRUGO | S_IWUSR,
dctrl_pllclks_show, dctrl_pllclks_store);
static DCTRL_ATTR(automode, S_IRUGO | S_IWUSR,
dctrl_automode_show, <API key>);
static struct attribute *dctrl_sysfs_attrs[] = {
&<API key>.attr,
&dctrl_attr_pllclks.attr,
&dctrl_attr_automode.attr,
NULL
};
static ssize_t dctrl_attr_show(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
struct vps_dispctrl *dctrl = NULL;
struct dctrl_attribute *dctrl_attr = NULL;
dctrl = container_of(kobj, struct vps_dispctrl, kobj);
dctrl_attr = container_of(attr, struct dctrl_attribute, attr);
if (!dctrl_attr->show)
return -ENOENT;
return dctrl_attr->show(dctrl, buf);
}
static ssize_t dctrl_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t size)
{
struct vps_dispctrl *dctrl;
struct dctrl_attribute *dctrl_attr;
dctrl = container_of(kobj, struct vps_dispctrl, kobj);
dctrl_attr = container_of(attr, struct dctrl_attribute, attr);
if (!dctrl_attr->store)
return -ENOENT;
return dctrl_attr->store(dctrl, buf, size);
}
static const struct sysfs_ops dctrl_sysfs_ops = {
.show = dctrl_attr_show,
.store = dctrl_attr_store,
};
static struct kobj_type dctrl_ktype = {
.sysfs_ops = &dctrl_sysfs_ops,
.default_attrs = dctrl_sysfs_attrs,
};
/*end of sysfs function for display controller*/
static int parse_def_clksrc(const char *clksrc)
{
int r = 0, i;
char *str, *options, *this_opt;
if (clksrc == NULL)
return 0;
str = kmalloc(strlen(clksrc) + 1, GFP_KERNEL);
strcpy(str, clksrc);
options = str;
VPSSDBG("clksrc %s\n", clksrc);
while (!r && (this_opt = strsep(&options, ",")) != NULL) {
char *p, *venc, *csrc;
int vid, idx;
struct dc_blender_info *binfo;
p = strchr(this_opt, ':');
if (!p)
break;
*p = 0;
venc = this_opt;
csrc = p + 1;
/*parse the clock source for each possible venc input*/
for (i = 0; i < ARRAY_SIZE(vclksrc_name); i++) {
if (sysfs_streq(csrc, vclksrc_name[i].name)) {
if (dc_get_vencid(venc, &vid)) {
VPSSERR("wrong venc\n");
break;
}
/* no clock for SD VENC*/
if (vid == VPS_DC_VENC_SD)
break;
get_idx_from_vid(vid, &idx);
binfo = &disp_ctrl->blenders[idx];
/*is valid clock source*/
if (isvalidclksrc(vid,
vclksrc_name[i].value)) {
binfo->clksrc.clksrc =
vclksrc_name[i].value;
} else
VPSSERR("wrong clock source\n");
break;
}
}
if (i == ARRAY_SIZE(vclksrc_name))
VPSSERR("wrong clock source\n");
if (options == NULL)
break;
}
kfree(str);
return r;
}
static int parse_def_modes(const char *mode)
{
char *str, *options, *this_opt;
int r = 0;
struct vps_dcvencinfo *vinfo = &venc_info;
if (mode == NULL)
return 0;
str = kmalloc(strlen(mode) + 1, GFP_KERNEL);
strcpy(str, mode);
options = str;
VPSSDBG("mode %s\n", mode);
while (!r && (this_opt = strsep(&options, ",")) != NULL) {
char *p, *display_str, *mode_str;
int vid, mid;
int idx;
p = strchr(this_opt, ':');
if (!p) {
r = -EINVAL;
break;
}
*p = 0;
display_str = this_opt;
mode_str = p + 1;
if (dc_get_vencid(display_str, &vid)) {
VPSSERR("venc name(%s) not existing.\n",
display_str);
continue;
}
if (dc_get_modeid(mode_str, &mid)) {
VPSSERR("venc mode(%s) is not supported.\n",
mode_str);
continue;
}
if (!isvalidmode(vid, mid))
continue;
get_idx_from_vid(vid, &idx);
vinfo->modeinfo[idx].vencid = vid;
vinfo->modeinfo[idx].minfo.standard = mid;
dc_get_timing(mid, &vinfo->modeinfo[idx].minfo);
if (options == NULL)
break;
}
kfree(str);
return r;
}
void __init vps_dc_ctrl_init(struct vps_dispctrl *dctrl)
{
struct vps_dcedeconfig *edecfg = dctrl->dcedecfg;
dctrl->dccreatecfg->edeconfig =
(struct vps_dcedeconfig *)dctrl->dcede_phy;
/*setup default ede values*/
edecfg->ltienable = 0;
edecfg->horzpeaking = 0;
edecfg->ctienable = 0;
edecfg->transadjustenable = 0;
edecfg->lumapeaking = 0;
edecfg->chromapeaking = 0;
edecfg->minclipluma = 0;
edecfg->maxclipluma = 1023;
edecfg->minclipchroma = 0;
edecfg->maxclipchroma = 1023;
edecfg->bypass = 0;
}
static inline int get_payload_size(void)
{
int size = 0;
size = sizeof(struct vps_dccreateconfig);
size += sizeof(struct vps_dcedeconfig);
size += sizeof(u32);
size += sizeof(struct vps_dcconfig);
size += sizeof(struct vps_dcvencinfo);
size += sizeof(struct vps_dcnodeinput);
size += sizeof(struct vps_dcmodeinfo);
size += sizeof(struct vps_dcoutputinfo);
size += sizeof(struct vps_dcvencclksrc);
size += sizeof(struct vps_dccigrtconfig);
size += sizeof(struct vps_dcenumnodeinput);
size += sizeof(struct vps_dccomprtconfig);
size += sizeof(u32); /*this is for the disable venc command*/
/*FIXME add more here*/
return size;
}
static inline void assign_payload_addr(struct vps_dispctrl *dctrl,
struct vps_payload_info *pinfo,
u32 *buf_offset)
{
int offset = *buf_offset;
/*dc create config*/
dctrl->dccreatecfg = (struct vps_dccreateconfig *)setaddr(pinfo,
&offset,
&dctrl->dccreate_phy,
sizeof(struct vps_dccreateconfig));
/*ede config*/
dctrl->dcedecfg = (struct vps_dcedeconfig *)setaddr(pinfo,
&offset,
&dctrl->dcede_phy,
sizeof(struct vps_dcedeconfig));
/*return status*/
dctrl->dcrtstatus = (u32 *)setaddr(pinfo,
&offset,
&dctrl->dcrtst_phy,
sizeof(u32));
/*dc config */
dctrl->dccfg = (struct vps_dcconfig *)setaddr(pinfo,
&offset,
&dctrl->dccfg_phy,
sizeof(struct vps_dcconfig));
/* venc info*/
dctrl->vinfo = (struct vps_dcvencinfo *)setaddr(pinfo,
&offset,
&dctrl->vinfo_phy,
sizeof(struct vps_dcvencinfo));
/*node input*/
dctrl->nodeinfo = (struct vps_dcnodeinput *)setaddr(
pinfo,
&offset,
&dctrl->ninfo_phy,
sizeof(struct vps_dcnodeinput));
/*venc disable*/
dctrl->dis_vencs = (u32 *)setaddr(pinfo,
&offset,
&dctrl->dis_vencsphy,
sizeof(u32));
/*venc output infor*/
dctrl->opinfo = (struct vps_dcoutputinfo *)setaddr(
pinfo,
&offset,
&dctrl->opinfo_phy,
sizeof(struct vps_dcoutputinfo));
/*venc clock source*/
dctrl->clksrc = (struct vps_dcvencclksrc *)setaddr(
pinfo,
&offset,
&dctrl->clksrc_phy,
sizeof(struct vps_dcvencclksrc));
/*CIG runtime configuration*/
dctrl->cigcfg = (struct vps_dccigrtconfig *)setaddr(
pinfo,
&offset,
&dctrl->cigcfg_phy,
sizeof(struct vps_dccigrtconfig));
/*DC enum node input*/
dctrl->dceninput = (struct vps_dcenumnodeinput *)setaddr(
pinfo,
&offset,
&dctrl->dceninput_phy,
sizeof(struct vps_dcenumnodeinput));
/*COMP RT Config*/
dctrl->comprtcfg = (struct vps_dccomprtconfig *) setaddr(
pinfo,
&offset,
&dctrl->comprtcfg_phy,
sizeof(struct vps_dccomprtconfig));
*buf_offset = offset;
}
int __init vps_dc_init(struct platform_device *pdev,
const char *mode,
int tied_vencs,
const char *clksrc)
{
int r = 0;
int i;
int size = 0, offset = 0;
VPSSDBG("dctrl init\n");
dc_payload_info = kzalloc(sizeof(struct vps_payload_info),
GFP_KERNEL);
if (!dc_payload_info) {
VPSSERR("allocated payload info failed.\n");
return -ENOMEM;
}
/*allocate non-cacheable memory*/
size = get_payload_size();
dc_payload_info->vaddr = vps_sbuf_alloc(size, &dc_payload_info->paddr);
if (dc_payload_info->vaddr == NULL) {
VPSSERR("alloc dctrl dma buffer failed\n");
dc_payload_info->paddr = 0u;
r = -ENOMEM;
goto cleanup;
}
dc_payload_info->size = PAGE_ALIGN(size);
memset(dc_payload_info->vaddr, 0, dc_payload_info->size);
/*allocate display_control memory*/
disp_ctrl = kzalloc(sizeof(struct vps_dispctrl), GFP_KERNEL);
if (disp_ctrl == NULL) {
r = -ENOMEM;
goto cleanup;
}
disp_ctrl->automode = true;
disp_ctrl->numvencs = vps_get_numvencs();
venc_info.numvencs = disp_ctrl->numvencs;
disp_ctrl->vencmask = (1 << VPS_DC_MAX_VENC) - 1;
if (cpu_is_ti814x())
disp_ctrl->vencmask -= VPS_DC_VENC_HDCOMP;
assign_payload_addr(disp_ctrl, dc_payload_info, &offset);
vps_dc_ctrl_init(disp_ctrl);
/*get dc handle*/
dc_handle = vps_fvid2_create(FVID2_VPS_DCTRL_DRV,
VPS_DCTRL_INST_0,
(void *)disp_ctrl->dccreate_phy,
(void *)dc_payload_info->paddr,
NULL);
if (dc_handle == NULL) {
VPSSDBG("Create FVID2 DC handle status 0x%08x.\n",
*(u32 *)dc_payload_info->vaddr);
r = -EINVAL;
goto cleanup;
}
disp_ctrl->fvid2_handle = dc_handle;
mutex_init(&disp_ctrl->dcmutex);
r = <API key>(
&disp_ctrl->kobj,
&dctrl_ktype,
&pdev->dev.kobj,
"system");
if (r)
VPSSERR("failed to create dctrl sysfs file.\n");
/*create sysfs*/
for (i = 0; i < disp_ctrl->numvencs; i++) {
struct dc_blender_info *blend = &disp_ctrl->blenders[i];;
blend->idx = i;
blend->actnodes = 0;
blend->name = (char *)venc_name[i].name;
blend->dctrl = disp_ctrl;
blend->isdeviceon = true;
r = <API key>(
&blend->kobj, &blender_ktype,
&pdev->dev.kobj, "display%d", i);
if (r) {
VPSSERR("failed to create blender \
%d sysfs file.\n", i);
continue;
}
}
disp_ctrl->tiedvenc = tied_vencs;
venc_info.tiedvencs = disp_ctrl->tiedvenc;
/*parse the mode*/
r = parse_def_modes(mode);
if (r) {
VPSSERR("failed to parse mode.\n");
goto cleanup;
}
/*set up the default clksrc and output format*/
for (i = 0; i < disp_ctrl->numvencs; i++) {
struct vps_dcvencclksrc *clksrcp =
&disp_ctrl->blenders[i].clksrc;
struct vps_dcoutputinfo opinfo;
clksrcp->venc = venc_name[i].vid;
/*set the venc output*/
opinfo.dvofidpolarity = <API key>;
opinfo.dvohspolarity = <API key>;
opinfo.dvovspolarity = <API key>;
opinfo.dvoactvidpolarity = <API key>;
switch (i) {
case HDMI:
opinfo.vencnodenum = VPS_DC_VENC_HDMI;
opinfo.dvofmt = <API key>;
opinfo.dataformat = FVID2_DF_RGB24_888;
if (cpu_is_ti816x() && (<API key> ==
<API key>()))
clksrcp->clksrc = <API key>;
else
clksrcp->clksrc = VPS_DC_CLKSRC_VENCD;
break;
case DVO2:
opinfo.vencnodenum = VPS_DC_VENC_DVO2;
opinfo.dvofmt = <API key>;
opinfo.dataformat = <API key>;
if (cpu_is_ti816x()) {
if (<API key> ==
<API key>())
clksrcp->clksrc =
<API key>;
else
clksrcp->clksrc = VPS_DC_CLKSRC_VENCD;
} else
clksrcp->clksrc = VPS_DC_CLKSRC_VENCA;
break;
case SDVENC:
opinfo.vencnodenum = VPS_DC_VENC_SD;
if (cpu_is_ti816x())
opinfo.afmt = <API key>;
else
opinfo.afmt = <API key>;
opinfo.dataformat = FVID2_DF_RGB24_888;
break;
if (cpu_is_ti816x()) {
case HDCOMP:
opinfo.vencnodenum = VPS_DC_VENC_HDCOMP;
opinfo.afmt = <API key>;
opinfo.dataformat = <API key>;
clksrcp->clksrc = VPS_DC_CLKSRC_VENCA;
break;
}
}
r = dc_set_output(&opinfo);
if (r) {
VPSSERR("failed to set venc output\n");
goto cleanup;
}
}
/*parse command line clksrc*/
r = parse_def_clksrc(clksrc);
if (r) {
VPSSERR("failed to parse clock source\n");
goto cleanup;
}
/*set the clock source*/
for (i = 0; i < venc_info.numvencs; i++) {
if (disp_ctrl->blenders[i].idx != SDVENC) {
r = dc_set_clksrc(
&disp_ctrl->blenders[i].clksrc);
if (r) {
VPSSERR("failed to set clock resource");
goto cleanup;
}
}
}
/*config the PLL*/
for (i = 0; i < venc_info.numvencs; i++) {
r = dc_set_pll_by_mid(i, venc_info.modeinfo[i].minfo.standard);
if (r) {
VPSSERR("failed to set pll");
goto cleanup;
}
}
/*set the venc mode*/
r = dc_set_vencmode(&venc_info);
if (r) {
VPSSERR("Failed to set venc mode.\n");
goto cleanup;
}
/*set the the THS filter, device is still registered even
if setup is failed*/
#ifdef CONFIG_ARCH_TI816X
if (cpu_is_ti816x()) {
r = <API key>(<API key>);
if ((venc_info.modeinfo[HDCOMP].minfo.standard ==
FVID2_STD_1080P_60) ||
(venc_info.modeinfo[HDCOMP].minfo.standard ==
FVID2_STD_1080P_50))
r |= <API key>(
<API key>);
else
r |= <API key>(
<API key>);
if (r < 0) {
VPSSERR("setup 7375 filter failed\n");
disp_ctrl->blenders[HDCOMP].isdeviceon = false;
}
r = <API key>(<API key>);
if (r < 0) {
VPSSERR("setup 7360 filter failed.\n");
disp_ctrl->blenders[SDVENC].isdeviceon = false;
}
}
#endif
return 0;
cleanup:
vps_dc_deinit(pdev);
return r;
}
int __exit vps_dc_deinit(struct platform_device *pdev)
{
int r = 0;
int i;
VPSSDBG("dctrl deinit\n");
if (disp_ctrl) {
/*disable vencs*/
if (disp_ctrl->enabled_venc_ids != 0) {
r = dc_venc_disable(disp_ctrl->vencmask);
if (r) {
VPSSERR("Failed to disable vencs.\n");
return r;
}
}
kobject_del(&disp_ctrl->kobj);
kobject_put(&disp_ctrl->kobj);
for (i = 0; i < disp_ctrl->numvencs; i++) {
kobject_del(&disp_ctrl->blenders[i].kobj);
kobject_put(&disp_ctrl->blenders[i].kobj);
}
kfree(disp_ctrl);
disp_ctrl = NULL;
}
if (dc_payload_info) {
/*free memory*/
if (dc_payload_info->vaddr)
vps_sbuf_free(dc_payload_info->paddr,
dc_payload_info->vaddr,
dc_payload_info->size);
kfree(dc_payload_info);
dc_payload_info = NULL;
}
if (dc_handle) {
r = vps_fvid2_delete(dc_handle, NULL);
if (r) {
VPSSERR("failed to delete DC fvid2 handle.\n");
return r;
}
dc_handle = NULL;
}
return r;
}
|
.<API key> {
/** Toggle/FAQ **/
/** Tabs **/
/** Tour **/
/* Accordion */
/* Call to Action box **/
/* Separator */
/* Message box */
/* Bar Graph */
/* Button */
/** Colors */
/* Google maps */
}
.<API key> .clearfix {
*zoom: 1;
}
.<API key> .clearfix:before,
.<API key> .clearfix:after {
display: table;
content: "";
}
.<API key> .clearfix:after {
clear: both;
}
.<API key> .hide-text {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.<API key> .input-block-level {
display: block;
width: 100%;
min-height: 5px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
.<API key> #content h4.wpb_toggle,
.<API key> h4.wpb_toggle {
position: relative;
padding: 7px 15px 7px 35px;
border: 1px solid #f3f3f3;
border-left: 0;
border-right: 0;
margin: 0 0 10px 0;
font-weight: normal;
background: none;
-webkit-transition: color 0.3s ease-out;
-moz-transition: color 0.3s ease-out;
-ms-transition: color 0.3s ease-out;
-o-transition: color 0.3s ease-out;
transition: color 0.3s ease-out;
}
.<API key> #content h4.wpb_toggle:hover,
.<API key> h4.wpb_toggle:hover {
cursor: pointer;
}
.<API key> #content h4.wpb_toggle:hover,
.<API key> h4.wpb_toggle:hover {
color: #ffac14;
}
.<API key> #content h4.wpb_toggle.<API key>,
.<API key> h4.wpb_toggle.<API key> {
color: #ffac14;
border-top: 3px solid #ffac14;
padding-top: 5px;
}
.<API key> h4.wpb_toggle {
color: #333333;
}
.<API key> h4.wpb_toggle:before {
content: '';
display: block;
position: absolute;
left: 0px;
top: 0px;
width: 35px;
height: 100%;
font-weight: normal;
font-size: 15px;
line-height: 37px;
text-align: center;
background: url(../../images/toggle_open.png) no-repeat center center;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}
.<API key> h4.<API key>:before {
background-image: url(../../images/toggle_close.png);
}
.<API key> .wpb_toggle_content {
position: relative;
padding: 0px 15px 20px;
margin: 0;
}
.<API key> .wpb_content_element .<API key> .wpb_tab {
padding: 0;
background: none;
}
.<API key> .<API key> .wpb_tabs_nav {
padding: 0;
border-bottom: 1px solid #f3f3f3;
margin-bottom: 15px !important;
}
.<API key> .<API key> .wpb_tabs_nav li {
list-style: none;
margin: 0 15px 0 0;
float: left;
background: none;
}
.<API key> .<API key> .wpb_tabs_nav li a {
font-weight: normal;
margin: 0;
display: block;
padding: 8px 5px;
color: #ffac14;
opacity: 0.7;
filter: alpha(opacity=70);
-webkit-transition: color 0.3s ease-out;
-moz-transition: color 0.3s ease-out;
-ms-transition: color 0.3s ease-out;
-o-transition: color 0.3s ease-out;
transition: color 0.3s ease-out;
-webkit-transition: opacity 0.3s ease-out;
-moz-transition: opacity 0.3s ease-out;
-ms-transition: opacity 0.3s ease-out;
-o-transition: opacity 0.3s ease-out;
transition: opacity 0.3s ease-out;
}
.<API key> .<API key> .wpb_tabs_nav li.ui-state-active a {
color: #ffac14;
border-bottom: 3px solid #ffac14;
opacity: 1;
filter: alpha(opacity=100);
}
.<API key> .<API key> .wpb_tabs_nav li:hover a {
opacity: 1;
filter: alpha(opacity=100);
}
.<API key> .wpb_content_element.wpb_tour .<API key> .wpb_tab {
padding: 0 0px 0 22px;
}
.<API key> .wpb_tour .<API key> .<API key> a {
color: #ffac14;
border-color: #f3f3f3;
}
.<API key> .wpb_tour .<API key> .wpb_tabs_nav {
border-bottom: none;
border-top: 1px solid #f3f3f3;
}
.<API key> .wpb_tour .<API key> .wpb_tabs_nav li {
float: none;
margin: 0 0 1px 0;
}
.<API key> .wpb_tour .<API key> .wpb_tabs_nav li a {
border-bottom: 1px solid #f3f3f3;
}
.<API key> .wpb_tour .<API key> .wpb_tabs_nav li.ui-state-active a {
color: #ffac14;
border-bottom: 3px solid #ffac14;
opacity: 1;
filter: alpha(opacity=100);
padding: 8px 5px 6px 5px;
}
.<API key> .wpb_content_element .<API key> .<API key> {
padding: 0 15px 15px 15px;
background: #ffffff;
color: #333333;
}
.<API key> .<API key> {
margin-top: -2px;
position: relative;
top: 2px;
}
.<API key> .wpb_content_element .<API key> .<API key> {
color: #333333;
border: 1px solid #f3f3f3;
border-left: 0;
border-right: 0;
padding: 8px 15px;
background: none;
}
.<API key> .wpb_content_element .<API key> .<API key>:after {
content: "";
display: block;
position: absolute;
top: 0px;
right: 0px;
color: #f3f3f3;
background: #ffffff url(../../images/toggle_open.png) no-repeat center center;
width: 35px;
height: 100%;
}
.<API key> .wpb_content_element .<API key> .<API key>.ui-state-active {
border-bottom-color: transparent;
border-top: 3px solid #ffac14;
}
.<API key> .wpb_content_element .<API key> .<API key>.ui-state-active:after {
background-image: url(../../images/toggle_close.png);
}
.<API key> .wpb_content_element .<API key> .<API key>.ui-state-active:after,
.<API key> .wpb_content_element .<API key> .<API key>.ui-state-hover:after {
color: #ffac14;
}
.<API key> .wpb_content_element .<API key> .<API key> a:hover,
.<API key> .wpb_content_element .<API key> .<API key>.ui-state-active a {
color: #ffac14;
}
.<API key> .wpb_content_element .<API key> .<API key> a {
padding: 0;
color: inherit;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}
.<API key> .wpb_content_element .<API key> .<API key> > span {
display: none;
}
.<API key> .wpb_call_to_action {
background: none;
border: 1px solid #f3f3f3;
border-left: 0;
border-right: 0;
padding: 30px 25px;
position: relative;
}
.<API key> .wpb_call_to_action:before {
content: "";
display: block;
position: absolute;
bottom: -7px;
left: 0;
width: 100%;
height: 1px;
border-bottom: 3px solid #f3f3f3;
}
.<API key> .wpb_call_to_action .wpb_call_text {
font-weight: normal;
color: #ffac14;
}
.<API key> .wpb_separator,
.<API key> .vc_text_separator {
position: relative;
border-bottom: 1px solid #f3f3f3;
}
.<API key> .wpb_separator:after,
.<API key> .vc_text_separator:after {
content: "";
position: absolute;
top: 4px;
left: 0;
width: 100%;
height: 1px;
border-bottom: 3px solid #f3f3f3;
}
.<API key> .vc_text_separator div {
top: -9px;
color: #ffac14;
background: #ffffff;
position: relative;
z-index: 1;
-<API key>: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.<API key> .wpb_alert .messagebox_text {
padding-left: 40px;
}
.<API key> .wpb_alert {
color: #aa8a02;
border: 1px solid #fdda48;
text-shadow: none;
padding: 15px 25px;
-<API key>: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
.<API key> .wpb_alert-success {
border: 1px solid #6ab165;
}
.<API key> .wpb_alert-success p {
color: #2d532a;
}
.<API key> .wpb_alert-error {
border: 1px solid #d95757;
}
.<API key> .wpb_alert-error p {
color: #7b1c1c;
}
.<API key> .wpb_alert-info {
border: 1px solid #686b72;
}
.<API key> .wpb_alert-info p {
color: #1f2022;
}
.<API key> .vc_progress_bar .vc_single_bar {
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
border: 1px solid #f3f3f3;
background: none;
-<API key>: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
.<API key> .vc_progress_bar .vc_single_bar .vc_bar {
-<API key>: 0px;
-moz-border-radius: 0px;
border-radius: 0px;
}
.<API key> .vc_progress_bar .bar_grey .vc_label {
color: #ffffff;
}
.<API key> .vc_progress_bar .bar_grey .vc_bar {
background: #ffac14;
}
.<API key> .wpb_button {
border: 0;
padding: 6px 10px;
-<API key>: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-ms-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
text-shadow: none;
}
.<API key> .wpb_btn-mini {
padding: 3px 7px 4px 7px;
font-size: 85%;
line-height: 110%;
}
.<API key> .wpb_btn-small {
padding: 5px 10px 5px;
font-size: 85%;
line-height: 110%;
}
.<API key> .wpb_regularsize {
padding: 8px 20px;
}
.<API key> .wpb_btn-large {
padding: 10px 25px;
font-size: 120%;
}
.<API key> .wpb_wpb_button {
background: #ffac14;
color: #ffffff;
}
.<API key> .wpb_wpb_button:hover {
background: #404040;
}
.<API key> .wpb_btn-inverse {
background: #414141;
}
.<API key> .wpb_btn-inverse:hover {
background: #272727;
}
.<API key> .wpb_btn-danger {
background: #DA4F49;
}
.<API key> .wpb_btn-danger:hover {
background: #c72f29;
}
.<API key> .wpb_btn-success {
background: #5BB75B;
}
.<API key> .wpb_btn-success:hover {
background: #449b44;
}
.<API key> .wpb_btn-warning {
background: #FAA732;
}
.<API key> .wpb_btn-warning:hover {
background: #f39106;
}
.<API key> .wpb_gmaps_widget .wpb_map_wraper {
padding: 5px;
border: 1px solid #f3f3f3;
background-color: #f8f8f8;
background-image: -moz-linear-gradient(top, #f3f3f3, #ffffff);
background-image: -ms-linear-gradient(top, #f3f3f3, #ffffff);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f3f3f3), to(#ffffff));
background-image: -<API key>(top, #f3f3f3, #ffffff);
background-image: -o-linear-gradient(top, #f3f3f3, #ffffff);
background-image: linear-gradient(top, #f3f3f3, #ffffff);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3f3f3', endColorstr='#ffffff', GradientType=0);
-<API key>: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
|
#define __SDCC_FLOAT_LIB
#include <float.h>
#ifdef FLOAT_ASM_MCS51
static void dummy(void) __naked
{
__asm
.globl fs_round_and_return
fs_round_and_return:
#ifdef FLOAT_FULL_ACCURACY
// discard the extra 8 bits of precision we kept around in r1
cjne r1, #128, 00001$
mov a, r2
rrc a
cpl c
00001$:
jc fs_zerocheck_return
mov a, r2
add a,
mov r2, a
clr a
addc a, r3
mov r3, a
clr a
addc a, r4
mov r4, a
jnc fs_zerocheck_return
mov r4, #0x80
inc exp_a
#endif
.globl fs_zerocheck_return
fs_zerocheck_return:
// zero output is a special case
cjne r4, #0, fs_direct_return
cjne r3, #0, fs_direct_return
cjne r2, #0, fs_direct_return
.globl fs_return_zero
fs_return_zero:
clr a
mov b, a
mov dph, a
mov dpl, a
ret
.globl fs_direct_return
fs_direct_return:
// collect all pieces and return
mov c, sign_a
mov a, exp_a
rrc a
mov b, r4
mov b.7, c
mov dph, r3
mov dpl, r2
ret
.globl fs_return_inf
fs_return_inf:
clr a
mov dph, a
mov dpl, a
mov b, #0x80
cpl a
mov c, sign_a
rrc a
ret
.globl fs_return_nan
fs_return_nan:
clr a
mov dph, a
mov dpl, a
mov b, #0xC0
mov a, #0x7F
ret
__endasm;
}
#endif
|
// <API key>: GPL-2.0-only
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/gpio.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <mach/audio.h>
#include <mach/eseries-gpio.h>
#include <asm/mach-types.h>
static int e750_spk_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & <API key>)
gpio_set_value(<API key>, 0);
else if (event & <API key>)
gpio_set_value(<API key>, 1);
return 0;
}
static int e750_hp_amp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
if (event & <API key>)
gpio_set_value(<API key>, 0);
else if (event & <API key>)
gpio_set_value(<API key>, 1);
return 0;
}
static const struct snd_soc_dapm_widget e750_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_SPK("Speaker", NULL),
SND_SOC_DAPM_MIC("Mic (Internal)", NULL),
SND_SOC_DAPM_PGA_E("Headphone Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e750_hp_amp_event, <API key> |
<API key>),
SND_SOC_DAPM_PGA_E("Speaker Amp", SND_SOC_NOPM, 0, 0, NULL, 0,
e750_spk_amp_event, <API key> |
<API key>),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Headphone Amp", NULL, "HPOUTL"},
{"Headphone Amp", NULL, "HPOUTR"},
{"Headphone Jack", NULL, "Headphone Amp"},
{"Speaker Amp", NULL, "MONOOUT"},
{"Speaker", NULL, "Speaker Amp"},
{"MIC1", NULL, "Mic (Internal)"},
};
static struct snd_soc_dai_link e750_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "pxa2xx-ac97",
.codec_dai_name = "wm9705-hifi",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
/* use ops to check startup state */
},
{
.name = "AC97 Aux",
.stream_name = "AC97 Aux",
.cpu_dai_name = "pxa2xx-ac97-aux",
.codec_dai_name = "wm9705-aux",
.platform_name = "pxa-pcm-audio",
.codec_name = "wm9705-codec",
},
};
static struct snd_soc_card e750 = {
.name = "Toshiba e750",
.owner = THIS_MODULE,
.dai_link = e750_dai,
.num_links = ARRAY_SIZE(e750_dai),
.dapm_widgets = e750_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(e750_dapm_widgets),
.dapm_routes = audio_map,
.num_dapm_routes = ARRAY_SIZE(audio_map),
.fully_routed = true,
};
static struct gpio e750_audio_gpios[] = {
{ <API key>, GPIOF_OUT_INIT_HIGH, "Headphone amp" },
{ <API key>, GPIOF_OUT_INIT_HIGH, "Speaker amp" },
};
static int e750_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &e750;
int ret;
ret = gpio_request_array(e750_audio_gpios,
ARRAY_SIZE(e750_audio_gpios));
if (ret)
return ret;
card->dev = &pdev->dev;
ret = <API key>(&pdev->dev, card);
if (ret) {
dev_err(&pdev->dev, "<API key>() failed: %d\n",
ret);
gpio_free_array(e750_audio_gpios, ARRAY_SIZE(e750_audio_gpios));
}
return ret;
}
static int e750_remove(struct platform_device *pdev)
{
gpio_free_array(e750_audio_gpios, ARRAY_SIZE(e750_audio_gpios));
return 0;
}
static struct platform_driver e750_driver = {
.driver = {
.name = "e750-audio",
.pm = &snd_soc_pm_ops,
},
.probe = e750_probe,
.remove = e750_remove,
};
<API key>(e750_driver);
/* Module information */
MODULE_AUTHOR("Ian Molton <spyro@f2s.com>");
MODULE_DESCRIPTION("ALSA SoC driver for e750");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:e750-audio");
|
/*
* Toshiba MIPI-DSI-to-LVDS Bridge driver.
* Device Model TC358764XBG/65XBG.
* Reference document: <API key>.pdf
*
* The Host sends a DSI Generic Long Write packet (Data ID = 0x29) over the
* DSI link for each write access transaction to the chip configuration
* registers.
* Payload of this packet is 16-bit register address and 32-bit data.
* Multiple data values are allowed for sequential addresses.
*
* The Host sends a DSI Generic Read packet (Data ID = 0x24) over the DSI
* link for each read request transaction to the chip configuration
* registers. Payload of this packet is further defined as follows:
* 16-bit address followed by a 32-bit value (Generic Long Read Response
* packet).
*
* The bridge supports 5 GPIO lines controlled via the GPC register.
*
* The bridge support I2C Master/Slave.
* The I2C slave can be used for read/write to the bridge register instead of
* using the DSI interface.
* I2C slave address is 0x0F (read/write 0x1F/0x1E).
* The I2C Master can be used for communication with the panel if
* it has an I2C slave.
*
* NOTE: The I2C interface is not used in this driver.
* Only the DSI interface is used for read/write the bridge registers.
*
* Pixel data can be transmitted in non-burst or burst fashion.
* Non-burst refers to pixel data packet transmission time on DSI link
* being roughly the same (to account for packet overhead time)
* as active video line time on LVDS output (i.e. DE = 1).
* And burst refers to pixel data packet transmission time on DSI link
* being less than the active video line time on LVDS output.
* Video mode transmission is further differentiated by the types of
* timing events being transmitted.
* Video pulse mode refers to the case where both sync start and sync end
* events (for frame and line) are transmitted.
* Video event mode refers to the case where only sync start events
* are transmitted.
* This is configured via register bit VPCTRL.EVTMODE.
*
*/
/* #define DEBUG 1 */
/**
* Use the I2C master to control the panel.
*/
/* #define <API key> */
#define DRV_NAME "mipi_tc358764"
#include <linux/i2c.h>
#include <linux/delay.h>
#include <linux/pwm.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include "msm_fb.h"
#include "mipi_dsi.h"
#include "<API key>.h"
/* Registers definition */
/* DSI D-PHY Layer Registers */
#define D0W_DPHYCONTTX 0x0004 /* Data Lane 0 DPHY Tx Control */
#define CLW_DPHYCONTRX 0x0020 /* Clock Lane DPHY Rx Control */
#define D0W_DPHYCONTRX 0x0024 /* Data Lane 0 DPHY Rx Control */
#define D1W_DPHYCONTRX 0x0028 /* Data Lane 1 DPHY Rx Control */
#define D2W_DPHYCONTRX 0x002C /* Data Lane 2 DPHY Rx Control */
#define D3W_DPHYCONTRX 0x0030 /* Data Lane 3 DPHY Rx Control */
#define COM_DPHYCONTRX 0x0038 /* DPHY Rx Common Control */
#define CLW_CNTRL 0x0040 /* Clock Lane Control */
#define D0W_CNTRL 0x0044 /* Data Lane 0 Control */
#define D1W_CNTRL 0x0048 /* Data Lane 1 Control */
#define D2W_CNTRL 0x004C /* Data Lane 2 Control */
#define D3W_CNTRL 0x0050 /* Data Lane 3 Control */
#define DFTMODE_CNTRL 0x0054 /* DFT Mode Control */
/* DSI PPI Layer Registers */
#define PPI_STARTPPI 0x0104 /* START control bit of PPI-TX function. */
#define PPI_BUSYPPI 0x0108
#define PPI_LINEINITCNT 0x0110 /* Line Initialization Wait Counter */
#define PPI_LPTXTIMECNT 0x0114
#define PPI_LANEENABLE 0x0134 /* Enables each lane at the PPI layer. */
#define PPI_TX_RX_TA 0x013C /* DSI Bus Turn Around timing parameters */
/* Analog timer function enable */
#define PPI_CLS_ATMR 0x0140 /* Delay for Clock Lane in LPRX */
#define PPI_D0S_ATMR 0x0144 /* Delay for Data Lane 0 in LPRX */
#define PPI_D1S_ATMR 0x0148 /* Delay for Data Lane 1 in LPRX */
#define PPI_D2S_ATMR 0x014C /* Delay for Data Lane 2 in LPRX */
#define PPI_D3S_ATMR 0x0150 /* Delay for Data Lane 3 in LPRX */
#define <API key> 0x0164
#define <API key> 0x0168 /* For lane 1 */
#define <API key> 0x016C /* For lane 2 */
#define <API key> 0x0170 /* For lane 3 */
#define CLS_PRE 0x0180 /* Digital Counter inside of PHY IO */
#define D0S_PRE 0x0184 /* Digital Counter inside of PHY IO */
#define D1S_PRE 0x0188 /* Digital Counter inside of PHY IO */
#define D2S_PRE 0x018C /* Digital Counter inside of PHY IO */
#define D3S_PRE 0x0190 /* Digital Counter inside of PHY IO */
#define CLS_PREP 0x01A0 /* Digital Counter inside of PHY IO */
#define D0S_PREP 0x01A4 /* Digital Counter inside of PHY IO */
#define D1S_PREP 0x01A8 /* Digital Counter inside of PHY IO */
#define D2S_PREP 0x01AC /* Digital Counter inside of PHY IO */
#define D3S_PREP 0x01B0 /* Digital Counter inside of PHY IO */
#define CLS_ZERO 0x01C0 /* Digital Counter inside of PHY IO */
#define D0S_ZERO 0x01C4 /* Digital Counter inside of PHY IO */
#define D1S_ZERO 0x01C8 /* Digital Counter inside of PHY IO */
#define D2S_ZERO 0x01CC /* Digital Counter inside of PHY IO */
#define D3S_ZERO 0x01D0 /* Digital Counter inside of PHY IO */
#define PPI_CLRFLG 0x01E0 /* PRE Counters has reached set values */
#define PPI_CLRSIPO 0x01E4 /* Clear SIPO values, Slave mode use only. */
#define HSTIMEOUT 0x01F0 /* HS Rx Time Out Counter */
#define HSTIMEOUTENABLE 0x01F4 /* Enable HS Rx Time Out Counter */
#define DSI_STARTDSI 0x0204 /* START control bit of DSI-TX function */
#define DSI_BUSYDSI 0x0208
#define DSI_LANEENABLE 0x0210 /* Enables each lane at the Protocol layer. */
#define DSI_LANESTATUS0 0x0214 /* Displays lane is in HS RX mode. */
#define DSI_LANESTATUS1 0x0218 /* Displays lane is in ULPS or STOP state */
#define DSI_INTSTATUS 0x0220 /* Interrupt Status */
#define DSI_INTMASK 0x0224 /* Interrupt Mask */
#define DSI_INTCLR 0x0228 /* Interrupt Clear */
#define DSI_LPTXTO 0x0230 /* Low Power Tx Time Out Counter */
#define DSIERRCNT 0x0300 /* DSI Error Count */
#define APLCTRL 0x0400 /* Application Layer Control */
#define RDPKTLN 0x0404 /* Command Read Packet Length */
#define VPCTRL 0x0450 /* Video Path Control */
#define HTIM1 0x0454 /* Horizontal Timing Control 1 */
#define HTIM2 0x0458 /* Horizontal Timing Control 2 */
#define VTIM1 0x045C /* Vertical Timing Control 1 */
#define VTIM2 0x0460 /* Vertical Timing Control 2 */
#define VFUEN 0x0464 /* Video Frame Timing Update Enable */
/* Mux Input Select for LVDS LINK Input */
#define LVMX0003 0x0480 /* Bit 0 to 3 */
#define LVMX0407 0x0484 /* Bit 4 to 7 */
#define LVMX0811 0x0488 /* Bit 8 to 11 */
#define LVMX1215 0x048C /* Bit 12 to 15 */
#define LVMX1619 0x0490 /* Bit 16 to 19 */
#define LVMX2023 0x0494 /* Bit 20 to 23 */
#define LVMX2427 0x0498 /* Bit 24 to 27 */
#define LVCFG 0x049C /* LVDS Configuration */
#define LVPHY0 0x04A0 /* LVDS PHY 0 */
#define LVPHY1 0x04A4 /* LVDS PHY 1 */
#define SYSSTAT 0x0500 /* System Status */
#define SYSRST 0x0504 /* System Reset */
/* GPIO Registers */
#define GPIOC 0x0520 /* GPIO Control */
#define GPIOO 0x0524 /* GPIO Output */
#define GPIOI 0x0528 /* GPIO Input */
/* I2C Registers */
#define I2CTIMCTRL 0x0540 /* I2C IF Timing and Enable Control */
#define I2CMADDR 0x0544 /* I2C Master Addressing */
#define WDATAQ 0x0548 /* Write Data Queue */
#define RDATAQ 0x054C /* Read Data Queue */
/* Chip ID and Revision ID Register */
#define IDREG 0x0580
#define TC358764XBG_ID 0x00006500
/* Debug Registers */
#define DEBUG00 0x05A0 /* Debug */
#define DEBUG01 0x05A4 /* LVDS Data */
/* PWM */
#if defined(<API key>) \
|| defined(<API key>)
#define PWM_FREQ_HZ (5*1000) /* 33 KHZ */
#define PWM_LEVEL 200
#else
#define PWM_FREQ_HZ (66*1000) /* 66 KHZ */
#define PWM_LEVEL 15
#endif
#define PWM_PERIOD_USEC (USEC_PER_SEC / PWM_FREQ_HZ)
#define PWM_DUTY_LEVEL (PWM_PERIOD_USEC / PWM_LEVEL)
#if defined(<API key>) \
|| defined(<API key>)
#define PWM_DUTY_MAX PWM_DUTY_LEVEL
#define DUTY_DIM 5
#define DUTY_MIN 8
#define DUTY_25 20
#define DUTY_DEFAULT 70
#define DUTY_MAX 189
/* Backlight levels */
#define BRIGHTNESS_OFF 0
#define BRIGHTNESS_DIM 20
#define BRIGHTNESS_MIN 30
#define BRIGHTNESS_25 86
#define BRIGHTNESS_DEFAULT 140
#define BRIGHTNESS_MAX 255
#endif
#define CMD_DELAY 100
#define DSI_MAX_LANES 4
#define KHZ 1000
#define MHZ (1000*1000)
/**
* Command payload for DTYPE_GEN_LWRITE (0x29) / DTYPE_GEN_READ2 (0x24).
*/
struct wr_cmd_payload {
u16 addr;
u32 data;
} __packed;
/*
* Driver state.
*/
static struct <API key> *d2l_common_pdata;
struct msm_fb_data_type *d2l_mfd;
static struct dsi_buf d2l_tx_buf;
static struct dsi_buf d2l_rx_buf;
static int led_pwm;
static struct pwm_device *bl_pwm;
static int initial_powerseq;
static int bl_level;
#if defined(<API key>) \
|| defined(<API key>)
static struct delayed_work det_work;
#endif
static u32 d2l_gpio_out_mask;
static u32 d2l_gpio_out_val;
static int mipi_d2l_init(void);
/**
* Read a bridge register
*
* @param mfd
*
* @return register data value
*/
static u32 mipi_d2l_read_reg(struct msm_fb_data_type *mfd, u16 reg)
{
u32 data;
int len = 4;
struct dsi_cmd_desc cmd_read_reg = {
DTYPE_GEN_READ2, 1, 0, 1, 0, /* cmd 0x24 */
sizeof(reg), (char *) ®};
mipi_dsi_buf_init(&d2l_tx_buf);
mipi_dsi_buf_init(&d2l_rx_buf);
/* mutex had been acquried at dsi_on */
len = mipi_dsi_cmds_rx(mfd, &d2l_tx_buf, &d2l_rx_buf,
&cmd_read_reg, len);
data = *(u32 *)d2l_rx_buf.data;
if (len != 4)
pr_err("%s: invalid rlen=%d, expecting 4.\n", __func__, len);
pr_debug("%s: reg=0x%x.data=0x%08x.\n", __func__, reg, data);
return data;
}
/**
* Write a bridge register
*
* @param mfd
*
* @return register data value
*/
static u32 mipi_d2l_write_reg(struct msm_fb_data_type *mfd, u16 reg, u32 data)
{
struct wr_cmd_payload payload;
struct dsi_cmd_desc cmd_write_reg = {
DTYPE_GEN_LWRITE, 1, 0, 0, 0,
sizeof(payload), (char *)&payload};
payload.addr = reg;
payload.data = data;
/* mutex had been acquried at dsi_on */
mipi_dsi_cmds_tx(mfd, &d2l_tx_buf, &cmd_write_reg, 1);
pr_debug("%s: reg=0x%x. data=0x%x.\n", __func__, reg, data);
return data;
}
static int <API key>(struct msm_fb_data_type *mfd)
{
struct mipi_panel_info *mipi = &mfd->panel_info.mipi;
u32 lanes_enable;
u32 vpctrl;
u32 htime1 = 0x002C0028;
u32 vtime1 = 0x001E0008;
lanes_enable = 0x01; /* clock-lane enable */
lanes_enable |= (mipi->data_lane0 << 1);
lanes_enable |= (mipi->data_lane1 << 2);
lanes_enable |= (mipi->data_lane2 << 3);
lanes_enable |= (mipi->data_lane3 << 4);
if (mipi->traffic_mode == <API key>)
vpctrl = 0x01000120;
else if (mipi->traffic_mode == <API key>)
vpctrl = 0x01000100;
else {
pr_err("%s.unsupported traffic_mode %d.\n",
__func__, mipi->traffic_mode);
return -EINVAL;
}
pr_debug("%s.htime1=0x%x.\n", __func__, htime1);
pr_debug("%s.vtime1=0x%x.\n", __func__, vtime1);
pr_debug("%s.vpctrl=0x%x.\n", __func__, vpctrl);
pr_debug("%s.lanes_enable=0x%x.\n", __func__, lanes_enable);
#if defined(<API key>) \
|| defined(<API key>)
/* VESA format instead of JEIDA format for RGB888 */
mipi_d2l_write_reg(mfd, LVMX0003, 0x03020100);
mipi_d2l_write_reg(mfd, LVMX0407, 0x08050704);
mipi_d2l_write_reg(mfd, LVMX0811, 0x0F0E0A09);
mipi_d2l_write_reg(mfd, LVMX1215, 0x100D0C0B);
mipi_d2l_write_reg(mfd, LVMX1619, 0x12111716);
mipi_d2l_write_reg(mfd, LVMX2023, 0x1B151413);
mipi_d2l_write_reg(mfd, LVMX2427, 0x061A1918);
mipi_d2l_write_reg(mfd, PPI_TX_RX_TA, 0x00030005); /* BTA */
mipi_d2l_write_reg(mfd, PPI_LPTXTIMECNT, 0x00000003);
mipi_d2l_write_reg(mfd, <API key>, 0x00000002);
mipi_d2l_write_reg(mfd, <API key>, 0x00000002);
mipi_d2l_write_reg(mfd, <API key>, 0x00000002);
mipi_d2l_write_reg(mfd, <API key>, 0x00000002);
mipi_d2l_write_reg(mfd, PPI_LANEENABLE, 0x0000001F);
mipi_d2l_write_reg(mfd, DSI_LANEENABLE, 0x0000001F);
mipi_d2l_write_reg(mfd, PPI_STARTPPI, 0x00000001);
mipi_d2l_write_reg(mfd, DSI_STARTDSI, 0x00000001);
mipi_d2l_write_reg(mfd, VPCTRL, 0x03F00121); /* RGB888 + Event mode */
mipi_d2l_write_reg(mfd, HTIM1, 0x00140114);
mipi_d2l_write_reg(mfd, HTIM2, 0x00340400);
mipi_d2l_write_reg(mfd, VTIM1, 0x0022000A);
mipi_d2l_write_reg(mfd, VTIM1, 0x00150258);
mipi_d2l_write_reg(mfd, VFUEN, 0x00000001);
mipi_d2l_write_reg(mfd, LVPHY0, 0x0044802D);
udelay(20);
mipi_d2l_write_reg(mfd, LVPHY0, 0x0004802D);
mipi_d2l_write_reg(mfd, LVCFG, 0x00000101);
#else
mipi_d2l_write_reg(mfd, SYSRST, 0xFF);
msleep(30);
/* VESA format instead of JEIDA format for RGB888 */
mipi_d2l_write_reg(mfd, LVMX0003, 0x03020100);
mipi_d2l_write_reg(mfd, LVMX0407, 0x08050704);
mipi_d2l_write_reg(mfd, LVMX0811, 0x0F0E0A09);
mipi_d2l_write_reg(mfd, LVMX1215, 0x100D0C0B);
mipi_d2l_write_reg(mfd, LVMX1619, 0x12111716);
mipi_d2l_write_reg(mfd, LVMX2023, 0x1B151413);
mipi_d2l_write_reg(mfd, LVMX2427, 0x061A1918);
mipi_d2l_write_reg(mfd, PPI_TX_RX_TA, 0x00040004); /* BTA */
mipi_d2l_write_reg(mfd, PPI_LPTXTIMECNT, 0x00000004);
mipi_d2l_write_reg(mfd, <API key>, 0x00000003);
mipi_d2l_write_reg(mfd, <API key>, 0x00000003);
mipi_d2l_write_reg(mfd, <API key>, 0x00000003);
mipi_d2l_write_reg(mfd, <API key>, 0x00000003);
mipi_d2l_write_reg(mfd, PPI_LANEENABLE, lanes_enable);
mipi_d2l_write_reg(mfd, DSI_LANEENABLE, lanes_enable);
mipi_d2l_write_reg(mfd, PPI_STARTPPI, 0x00000001);
mipi_d2l_write_reg(mfd, DSI_STARTDSI, 0x00000001);
mipi_d2l_write_reg(mfd, VPCTRL, vpctrl); /* RGB888 + Event mode */
mipi_d2l_write_reg(mfd, HTIM1, htime1);
mipi_d2l_write_reg(mfd, VTIM1, vtime1);
mipi_d2l_write_reg(mfd, VFUEN, 0x00000001);
mipi_d2l_write_reg(mfd, LVCFG, 0x00000001); /* Enables LVDS tx */
#endif /* <API key> */
return 0;
}
#if defined(<API key>) \
|| defined(<API key>)
static int scale_pwm_dutycycle(int level)
{
int scaled_level = 0;
if (level == BRIGHTNESS_OFF)
scaled_level = BRIGHTNESS_OFF;
else if (level <= BRIGHTNESS_DIM)
scaled_level = PWM_DUTY_MAX*DUTY_DIM;
else if (level <= BRIGHTNESS_MIN)
scaled_level = (level - BRIGHTNESS_DIM) *
(PWM_DUTY_MAX * DUTY_MIN - PWM_DUTY_MAX * DUTY_DIM) /
(BRIGHTNESS_MIN - BRIGHTNESS_DIM) +
PWM_DUTY_MAX * DUTY_DIM;
else if (level <= BRIGHTNESS_25)
scaled_level = (level - BRIGHTNESS_MIN) *
(PWM_DUTY_MAX * DUTY_25 - PWM_DUTY_MAX * DUTY_MIN) /
(BRIGHTNESS_25 - BRIGHTNESS_MIN) +
PWM_DUTY_MAX * DUTY_MIN;
else if (level <= BRIGHTNESS_DEFAULT)
scaled_level = (level - BRIGHTNESS_25) *
(PWM_DUTY_MAX * DUTY_DEFAULT - PWM_DUTY_MAX * DUTY_25)
/ (BRIGHTNESS_DEFAULT - BRIGHTNESS_25) +
PWM_DUTY_MAX * DUTY_25;
else if (level <= BRIGHTNESS_MAX)
scaled_level = (level - BRIGHTNESS_DEFAULT) *
(PWM_DUTY_MAX * DUTY_MAX - PWM_DUTY_MAX * DUTY_DEFAULT)
/ (BRIGHTNESS_MAX - BRIGHTNESS_DEFAULT) +
PWM_DUTY_MAX * DUTY_DEFAULT;
return scaled_level;
}
#endif
/**
* Set Backlight level.
*
* @param pwm
* @param level
*
* @return int
*/
static int <API key>(struct pwm_device *pwm, int level)
{
int ret = 0;
pr_debug("%s: level=%d.\n", __func__, level);
#if defined(<API key>) \
|| defined(<API key>)
if ((pwm == NULL) || (level > BRIGHTNESS_MAX) || (level < 0)) {
pr_err("%s.pwm=NULL.\n", __func__);
return -EINVAL;
}
level = scale_pwm_dutycycle(level);
#else
if ((pwm == NULL) || (level > PWM_LEVEL) || (level < 0)) {
pr_err("%s.pwm=NULL.\n", __func__);
return -EINVAL;
}
#endif
ret = pwm_config(pwm, PWM_DUTY_LEVEL * level, PWM_PERIOD_USEC);
if (ret) {
pr_err("%s: pwm_config() failed err=%d.\n", __func__, ret);
return ret;
}
ret = pwm_enable(pwm);
if (ret) {
pr_err("%s: pwm_enable() failed err=%d\n",
__func__, ret);
return ret;
}
return 0;
}
#if defined(<API key>) \
|| defined(<API key>)
static void blenable_work_func(struct work_struct *work)
{
int ret = 0;
/* Set backlight via PWM */
if (bl_pwm) {
ret = <API key>(bl_pwm, bl_level);
if (ret)
pr_err("%s.<API key>.ret=%d",
__func__, ret);
}
}
#endif
/**
* LCD ON.
*
* Set LCD On via MIPI interface or I2C-Slave interface.
* Set Backlight on.
*
* @param pdev
*
* @return int
*/
static int mipi_d2l_lcd_on(struct platform_device *pdev)
{
int ret = 0;
u32 chip_id;
struct msm_fb_data_type *mfd;
pr_info("%s.\n", __func__);
/* wait for valid clock before sending data over DSI or I2C. */
msleep(30);
mfd = <API key>(pdev);
d2l_mfd = mfd;
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
chip_id = mipi_d2l_read_reg(mfd, IDREG);
if (chip_id != TC358764XBG_ID) {
pr_err("%s: invalid chip_id=0x%x", __func__, chip_id);
return -ENODEV;
}
ret = <API key>(mfd);
if (ret)
return ret;
mipi_d2l_write_reg(mfd, GPIOC, d2l_gpio_out_mask);
/* Set GPIOs: gpio#4=U/D=0 , gpio#3=L/R=1 , gpio#2,1=CABC=0. */
mipi_d2l_write_reg(mfd, GPIOO, d2l_gpio_out_val);
#if defined(<API key>) \
|| defined(<API key>)
if ((bl_level == 0) && (!initial_powerseq)) {
bl_level = BRIGHTNESS_DEFAULT ; /* Default ON value */
INIT_DELAYED_WORK(&det_work, blenable_work_func);
<API key>(&det_work, msecs_to_jiffies(250));
}
#else
if ((bl_level == 0) && (!initial_powerseq))
bl_level = PWM_LEVEL * 2 / 3 ; /* Default ON value */
/* Set backlight via PWM */
if (bl_pwm) {
ret = <API key>(bl_pwm, bl_level);
if (ret)
pr_err("%s.<API key>.ret=%d",
__func__, ret);
}
#endif
pr_info("%s.ret=%d.\n", __func__, ret);
/* Set power on flag */
initial_powerseq = 1;
return ret;
}
/**
* LCD OFF.
*
* @param pdev
*
* @return int
*/
static int mipi_d2l_lcd_off(struct platform_device *pdev)
{
int ret;
struct msm_fb_data_type *mfd;
pr_info("%s.\n", __func__);
mfd = <API key>(pdev);
if (!mfd)
return -ENODEV;
if (mfd->key != MFD_KEY)
return -EINVAL;
ret = <API key>(bl_pwm, 0);
pr_info("%s.ret=%d.\n", __func__, ret);
return ret;
}
static void <API key>(struct msm_fb_data_type *mfd)
{
int level = mfd->bl_level;
pr_debug("%s.lvl=%d.\n", __func__, level);
<API key>(bl_pwm, level);
bl_level = level;
}
static struct msm_fb_panel_data d2l_panel_data = {
.on = mipi_d2l_lcd_on,
.off = mipi_d2l_lcd_off,
.set_backlight = <API key>,
};
/**
* Probe for device.
*
* Both the "target" and "panel" device use the same probe function.
* "Target" device has id=0, "Panel" devic has non-zero id.
* Target device should register first, passing <API key>.
* Panel device passing msm_panel_info.
*
* @param pdev
*
* @return int
*/
static int __devinit mipi_d2l_probe(struct platform_device *pdev)
{
int ret = 0;
struct msm_panel_info *pinfo = NULL;
pr_debug("%s.id=%d.\n", __func__, pdev->id);
if (pdev->id == 0) {
/* d2l_common_pdata = <API key>(pdev); */
d2l_common_pdata = pdev->dev.platform_data;
if (d2l_common_pdata == NULL) {
pr_err("%s: no PWM gpio specified.\n", __func__);
return 0;
}
led_pwm = d2l_common_pdata->gpio_num[0];
d2l_gpio_out_mask = d2l_common_pdata->gpio_num[1] >> 8;
d2l_gpio_out_val = d2l_common_pdata->gpio_num[1] & 0xFF;
mipi_dsi_buf_alloc(&d2l_tx_buf, DSI_BUF_SIZE);
mipi_dsi_buf_alloc(&d2l_rx_buf, DSI_BUF_SIZE);
return 0;
}
if (d2l_common_pdata == NULL) {
pr_err("%s: d2l_common_pdata is NULL.\n", __func__);
return -ENODEV;
}
bl_pwm = NULL;
if (led_pwm >= 0) {
bl_pwm = pwm_request(led_pwm, "lcd-backlight");
if (bl_pwm == NULL || IS_ERR(bl_pwm)) {
pr_err("%s pwm_request() failed.id=%d.bl_pwm=%d.\n",
__func__, led_pwm, (int) bl_pwm);
bl_pwm = NULL;
return -EIO;
} else {
pr_debug("%s.pwm_request() ok.pwm-id=%d.\n",
__func__, led_pwm);
}
} else {
pr_info("%s. led_pwm is invalid.\n", __func__);
}
/* pinfo = <API key>(pdev); */
pinfo = pdev->dev.platform_data;
if (pinfo == NULL) {
pr_err("%s: pinfo is NULL.\n", __func__);
return -ENODEV;
}
d2l_panel_data.panel_info = *pinfo;
pdev->dev.platform_data = &d2l_panel_data;
msm_fb_add_device(pdev);
return ret;
}
/**
* Device removal notification handler.
*
* @param pdev
*
* @return int
*/
static int __devexit mipi_d2l_remove(struct platform_device *pdev)
{
/* Note: There are no APIs to remove fb device and free DSI buf. */
pr_debug("%s.\n", __func__);
if (bl_pwm) {
pwm_free(bl_pwm);
bl_pwm = NULL;
}
return 0;
}
/**
* Register the panel device.
*
* @param pinfo
* @param channel_id
* @param panel_id
*
* @return int
*/
int <API key>(struct msm_panel_info *pinfo,
u32 channel_id, u32 panel_id)
{
struct platform_device *pdev = NULL;
int ret;
/* Use DSI-to-LVDS bridge */
const char driver_name[] = "mipi_tc358764";
pr_debug("%s.\n", __func__);
ret = mipi_d2l_init();
if (ret) {
pr_err("mipi_d2l_init() failed with ret %u\n", ret);
return ret;
}
/* Note: the device id should be non-zero */
pdev = <API key>(driver_name, (panel_id << 8)|channel_id);
if (pdev == NULL)
return -ENOMEM;
pdev->dev.platform_data = pinfo;
ret = platform_device_add(pdev);
if (ret) {
pr_err("%s: <API key> failed!\n", __func__);
goto err_device_put;
}
return 0;
err_device_put:
platform_device_put(pdev);
return ret;
}
static struct platform_driver d2l_driver = {
.probe = mipi_d2l_probe,
.remove = __devexit_p(mipi_d2l_remove),
.driver = {
.name = DRV_NAME,
},
};
/**
* Module Init
*
* @return int
*/
static int mipi_d2l_init(void)
{
pr_debug("%s.\n", __func__);
return <API key>(&d2l_driver);
}
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Toshiba MIPI-DSI-to-LVDS bridge driver");
MODULE_AUTHOR("Amir Samuelov <amirs@codeaurora.org>");
|
<?php
/**
* nggPostThumbnail - Class for adding the post thumbnail feature
*
* @package NextGEN Gallery
* @author Alex Rabe
*
* @version 1.0.2
* @access internal
*/
class nggPostThumbnail {
/**
* PHP4 compatibility layer for calling the PHP5 constructor.
*
*/
function nggPostThumbnail() {
return $this->__construct();
}
/**
* Main constructor - Add filter and action hooks
*
*/
function __construct() {
add_filter( '<API key>', array( $this, '<API key>'), 10, 2 );
add_action( '<API key>', array( $this, '<API key>') );
// Adding filter for the new post_thumbnail
add_filter( 'post_thumbnail_html', array( $this, 'ngg_post_thumbnail'), 10, 5 );
return;
}
/**
* Filter for the post meta box. look for a NGG image if the ID is "ngg-<imageID>"
*
* @param string $content
* @return string html output
*/
function <API key>( $content, $post_id = null )
{
if ($post_id == null)
{
global $post;
if ( !is_object($post) )
return $content;
$post_id = $post->ID;
}
$thumbnail_id = get_post_meta($post_id, '_thumbnail_id', true);
// in the case it's a ngg image it return ngg-<imageID>
if ( strpos($thumbnail_id, 'ngg-') === false)
{
global $wp_version;
if (version_compare($wp_version, '3.5', '>=') && $thumbnail_id <= 0)
{
$iframe_src = <API key>('image');
$iframe_src = remove_query_arg('TB_iframe', $iframe_src);
$iframe_src = add_query_arg('tab', 'nextgen', $iframe_src);
$iframe_src = add_query_arg('chromeless', '1', $iframe_src);
$iframe_src = add_query_arg('TB_iframe', '1', $iframe_src);
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set NextGEN featured image' ) . '" href="' . nextgen_esc_url( $iframe_src ) . '" id="<API key>" class="thickbox">%s</a></p>';
$content .= sprintf($set_thumbnail_link, esc_html__( 'Set NextGEN featured image' ));
}
return $content;
}
// cut off the 'ngg-'
$thumbnail_id = substr( $thumbnail_id, 4);
return $this-><API key>( $thumbnail_id );
}
/**
* Filter for the post content
*
* @param string $html
* @param int $post_id
* @param int $post_thumbnail_id
* @param string|array $size Optional. Image size. Defaults to 'thumbnail'.
* @param string|array $attr Optional. Query string or array of attributes.
* @return string html output
*/
function ngg_post_thumbnail( $html, $post_id, $post_thumbnail_id, $size = 'post-thumbnail', $attr = '' ) {
global $post, $<API key>;
// in the case it's a ngg image it return ngg-<imageID>
if ( strpos($post_thumbnail_id, 'ngg-') === false)
return $html;
// cut off the 'ngg-'
$post_thumbnail_id = substr( $post_thumbnail_id, 4);
// get the options
$ngg_options = nggGallery::get_option('ngg_options');
// get the image data
$image = nggdb::find_image($post_thumbnail_id);
if (!$image)
return $html;
$img_src = false;
$class = 'wp-post-image ngg-image-' . $image->pid . ' ';
if (is_array($size) || is_array($<API key>) && isset($<API key>[$size])) {
$class .= isset($attr['class']) ? esc_attr($attr['class']) : '';
if( is_array($size)){
//the parameters is given as an array rather than a predfined image
$width = absint( $size[0] );
$height = absint( $size[1] );
if(isset($size[2]) && $size[2] === true) {
$mode = 'crop';
} else if(isset($size[2])){
$mode = $size[2];
} else {
$mode = '';
}
} else {
$width = absint( $<API key>[$size]['width'] );
$height = absint( $<API key>[$size]['height'] );
$mode = ($<API key>[$size]['crop']) ? 'crop' : '';
}
// check fo cached picture
if ( $post->post_status == 'publish' )
$img_src = $image-><API key>( $width, $height, $mode );
// if we didn't use a cached image then we take the on-the-fly mode
if ($img_src == false)
$img_src = trailingslashit( home_url() ) . 'index.php?callback=image&pid=' . $image->pid . '&width=' . $width . '&height=' . $height . '&mode=crop';
} else {
$img_src = $image->thumbURL;
}
$alttext = isset($attr['alt']) ? $attr['alt'] : $image->alttext;
$titletext = isset($attr['title']) ? $attr['title'] : $image->title;
$html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alttext) . '" title="' . esc_attr($titletext) .'" class="'.$class.'" />';
return $html;
}
/**
* nggPostThumbnail::<API key>()
*
* @return void
*/
function <API key>()
{
global $post_ID;
// check for correct capability
if ( !is_user_logged_in() )
die( '-1' );
// get the post id as global variable, otherwise the ajax_nonce failed later
$post_ID = intval( $_POST['post_id'] );
if ( !current_user_can( 'edit_post', $post_ID ) )
die( '-1' );
$thumbnail_id = intval( $_POST['thumbnail_id'] );
// delete the image
if ( $thumbnail_id == '-1' ) {
delete_post_meta( $post_ID, '_thumbnail_id' );
die('0');
}
if ($thumbnail_id != null)
{
$registry = <API key>::get_instance();
$imap = $registry->get_utility('I_Image_Mapper');
$storage = $registry->get_utility('I_Gallery_Storage');
$image = $imap->find($thumbnail_id);
// for NGG we look for the image id
if ($image)
{
$image_id = $thumbnail_id;
$args = array(
'post_type' => 'attachment',
'meta_key' => '_ngg_image_id',
'meta_compare' => '==',
'meta_value' => $image_id
);
$upload_dir = wp_upload_dir();
$basedir = $upload_dir['basedir'];
$thumbs_dir = path_join($basedir, 'ngg_featured');
$gallery_abspath = $storage->get_gallery_abspath($image->galleryid);
$image_abspath = $storage->get_full_abspath($image);
$target_path = null;
$posts = get_posts($args);
$attachment_id = null;
if ($posts != null)
{
$attachment_id = $posts[0]->ID;
}
else
{
$url = $storage->get_full_url($image);
$target_relpath = null;
$target_basename = basename($image_abspath);
if (strpos($image_abspath, $gallery_abspath) === 0)
{
$target_relpath = substr($image_abspath, strlen($gallery_abspath));
}
else if ($image->galleryid)
{
$target_relpath = path_join(strval($image->galleryid), $target_basename);
}
else
{
$target_relpath = $target_basename;
}
$target_relpath = trim($target_relpath, '\\/');
$target_path = path_join($thumbs_dir, $target_relpath);
$max_count = 100;
$count = 0;
while (file_exists($target_path) && $count <= $max_count)
{
$count++;
$pathinfo = pathinfo($target_path);
$dirname = $pathinfo['dirname'];
$filename = $pathinfo['filename'];
$extension = $pathinfo['extension'];
$rand = mt_rand(1, 9999);
$basename = $filename . '_' . sprintf('%04d', $rand) . '.' . $extension;
$target_path = path_join($dirname, $basename);
}
if (file_exists($target_path))
{
// XXX handle very rare case in which $max_count wasn't enough?
}
$target_dir = dirname($target_path);
wp_mkdir_p($target_dir);
if (@copy($image_abspath, $target_path))
{
$size = @getimagesize($target_path);
$image_type = ($size) ? $size['mime'] : 'image/jpeg';
$title = sanitize_file_name($image->alttext);
$caption = sanitize_file_name($image->description);
$attachment = array(
'post_title' => $title,
'post_content' => $caption,
'post_status' => 'attachment',
'post_parent' => 0,
'post_mime_type' => $image_type,
'guid' => $url
);
// Save the data
$attachment_id = <API key>($attachment, $target_path);
if ($attachment_id)
{
<API key>($attachment_id, <API key>($attachment_id, $target_path));
update_post_meta($attachment_id, '_ngg_image_id', $image_id);
}
}
}
if ($attachment_id)
{
//$attachment = get_post($attachment_id);
//$attachment_meta = <API key>($attachment_id);
$attachment_file = get_attached_file($attachment_id);
$target_path = $attachment_file;
if (filemtime($image_abspath) > filemtime($target_path))
{
if (@copy($image_abspath, $target_path))
{
<API key>($attachment_id, <API key>($attachment_id, $target_path));
}
}
die(strval($attachment_id));
}
}
}
die('0');
}
/**
* Output HTML for the post thumbnail meta-box.
*
* @see wp-admin\includes\post.php
* @param int $thumbnail_id ID of the image used for thumbnail
* @return string html output
*/
function <API key>( $thumbnail_id = NULL ) {
global $<API key>, $post_ID;
$set_thumbnail_link = '<p class="hide-if-no-js"><a title="' . esc_attr__( 'Set featured image' ) . '" href="' . nextgen_esc_url( <API key>('image') ) . '" id="set-post-thumbnail" class="thickbox">%s</a></p>';
$content = sprintf($set_thumbnail_link, esc_html__( 'Set featured image' ));
$image = nggdb::find_image($thumbnail_id);
$img_src = false;
// get the options
$ngg_options = nggGallery::get_option('ngg_options');
if ( $image ) {
if ( is_array($<API key>) && isset($<API key>['post-thumbnail']) ){
// Use post thumbnail settings if defined
$width = absint( $<API key>['post-thumbnail']['width'] );
$height = absint( $<API key>['post-thumbnail']['height'] );
$mode = $<API key>['post-thumbnail']['crop'] ? 'crop' : '';
// check fo cached picture
$img_src = $image-><API key>( $width, $height, $mode );
}
// if we didn't use a cached image then we take the on-the-fly mode
if ( $img_src == false )
$img_src = trailingslashit( home_url() ) . 'index.php?callback=image&pid=' . $image->pid . '&width=' . $width . '&height=' . $height . '&mode=crop';
$thumbnail_html = '<img width="266" src="'. $img_src . '" alt="'.$image->alttext.'" title="'.$image->alttext.'" />';
if ( !empty( $thumbnail_html ) ) {
$ajax_nonce = wp_create_nonce( "set_post_thumbnail-$post_ID" );
$content = sprintf($set_thumbnail_link, $thumbnail_html);
$content .= '<p class="hide-if-no-js"><a href="#" id="<API key>" onclick="WPRemoveThumbnail(\'' . $ajax_nonce . '\');return false;">' . esc_html__( 'Remove featured image' ) . '</a></p>';
}
}
return $content;
}
}
$nggPostThumbnail = new nggPostThumbnail();
|
<?php
// Protect from unauthorized access
defined('_JEXEC') or die();
/**
* MVC View for Log
*
*/
class AkeebaViewLog extends FOFViewHtml
{
public function onBrowse($tpl = null)
{
// Add live help
<API key>::addHelp('log');
// Get a list of log names
$model = $this->getModel();
$this->logs = $model->getLogList();
$tag = $model->getState('tag');
if(empty($tag)) $tag = null;
$this->tag = $tag;
// Get profile ID
$profileid = AEPlatform::getInstance()->get_active_profile();
$this->profileid = $profileid;
// Get profile name
$pmodel = FOFModel::getAnInstance('Profiles', 'AkeebaModel');
$pmodel->setId($profileid);
$profile_data = $pmodel->getItem();
$this->profilename = $profile_data->description;
return true;
}
public function onIframe($tpl = null)
{
$model = $this->getModel();
$tag = $model->getState('tag');
if(empty($tag)) $tag = null;
$this->tag = $tag;
return true;
}
}
|
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/<API key>";
export const definition: IconDefinition;
export const faGrinHearts: IconDefinition;
export const prefix: IconPrefix;
export const iconName: IconName;
export const width: number;
export const height: number;
export const ligatures: string[];
export const unicode: string;
export const svgPathData: string;
|
<?php
class Avada_Helper {
/**
* Return the value of an echo.
* example: Avada_Helper::get_echo( 'function' );
*/
public static function get_echo( $function, $args = '' ) {
// Early exit if function does not exist
if ( ! function_exists( $function ) ) {
return;
}
ob_start();
$function( $args );
$get_echo = ob_get_clean();
return $get_echo;
}
public static function slider_name( $name ) {
$type = '';
switch( $name ) {
case 'layer':
$type = 'slider';
break;
case 'flex':
$type = 'wooslider';
break;
case 'rev':
$type = 'revslider';
break;
case 'elastic':
$type = 'elasticslider';
break;
}
return $type;
}
public static function get_slider_type( $post_id ) {
return get_post_meta( $post_id, 'pyre_slider_type', true );
}
}
// Omit closing PHP tag to avoid "Headers already sent" issues.
|
using System.Collections.Generic;
using Nancy.Metadata.Module;
using Nancy.Swagger;
using OmniSharp.Common;
namespace OmniSharp.CurrentFileMembers.Metadata
{
public class <API key> : MetadataModule<SwaggerRouteData>
{
public <API key>()
{
Describe["<API key>"] = desc => desc.AsSwagger(builder => builder
.ResourcePath("/<API key>")
.BodyParam<<API key>>()
.Response(200)
.Model<IEnumerable<QuickFix>>());
}
}
}
|
Proj4js.defs["EPSG:32666"] = "+proj=tmerc +lat_0=0 +lon_0=-87 +k=0.9996 +x_0=500000.001016002 +y_0=0 +ellps=WGS84 +datum=WGS84 +to_meter=0.3048006096012192 +no_defs";
|
# This file is part of Canvas.
# Canvas is free software: you can redistribute it and/or modify it under
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# details.
class O<API key> < <API key>
<API key> :except => [:token, :destroy]
before_filter :run_login_hooks, :only => [:token]
skip_before_filter :<API key>
def auth
if params[:code] || params[:error]
# hopefully the user never sees this, since it's an oob response and the
# browser should be closed automatically. but we'll at least display
# something basic.
return render()
end
scopes = params.fetch(:scopes, '').split(',')
provider = Canvas::Oauth::Provider.new(params[:client_id], params[:redirect_uri], scopes, params[:purpose])
return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key?
return render(:status => 400, :json => { :message => "invalid redirect_uri" }) unless provider.has_valid_redirect?
session[:oauth2] = provider.session_hash
session[:oauth2][:state] = params[:state] if params.key?(:state)
if @current_pseudonym && !params[:force_login]
redirect_to Canvas::Oauth::Provider.<API key>(self, provider, @current_user)
else
redirect_to login_url(params.slice(:canvas_login, :pseudonym_session, :force_login, :<API key>))
end
end
def confirm
if session[:oauth2]
@provider = Canvas::Oauth::Provider.new(session[:oauth2][:client_id], session[:oauth2][:redirect_uri], session[:oauth2][:scopes], session[:oauth2][:purpose])
if mobile_device?
js_env :<API key> => Setting.get('<API key>', nil)
render :layout => 'mobile_auth', :action => 'confirm_mobile'
end
else
flash[:error] = t("Must submit new OAuth2 request")
redirect_to login_url
end
end
def accept
redirect_params = Canvas::Oauth::Provider.<API key>(session[:oauth2], @current_user, remember_access: params[:remember_access])
redirect_to Canvas::Oauth::Provider.final_redirect(self, redirect_params)
end
def deny
redirect_to Canvas::Oauth::Provider.final_redirect(self, :error => "access_denied")
end
def token
basic_user, basic_pass = ActionController::HttpAuthentication::Basic.<API key>(request) if request.authorization
client_id = params[:client_id].presence || basic_user
secret = params[:client_secret].presence || basic_pass
provider = Canvas::Oauth::Provider.new(client_id)
return render(:status => 400, :json => { :message => "invalid client_id" }) unless provider.has_valid_key?
return render(:status => 400, :json => { :message => "invalid client_secret" }) unless provider.is_authorized_by?(secret)
token = provider.token_for(params[:code])
return render(:status => 400, :json => { :message => "invalid code" }) unless token.is_for_valid_code?
token.<API key>(value_to_boolean(params[:replace_tokens]))
Canvas::Oauth::Token.expire_code(params[:code])
render :json => token
end
def destroy
logout_current_user if params[:expire_sessions]
return render :json => { :message => "can't delete OAuth access token when not using an OAuth access token" }, :status => 400 unless @access_token
@access_token.destroy
render :json => {}
end
end
|
(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f=
0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+
e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
|
/**
* Shopware Backend - ErrorReporter Main Model
*
* todo@all: Documentation
*/
Ext.define('Shopware.apps.UserManager.model.Locale', {
extend: 'Ext.data.Model',
fields: [ 'id', 'name' ]
});
|
#ifndef IVE_MATERIAL
#define IVE_MATERIAL 1
#include <osg/Material>
#include "ReadWrite.h"
namespace ive{
class Material : public osg::Material {
public:
void write(DataOutputStream* out);
void read(DataInputStream* in);
};
}
#endif
|
<?php
/* @var $installer <API key> */
$installer = $this;
$installer->startSetup();
$table = $installer->getConnection()
->newTable($installer->getTable('captcha/log'))
->addColumn('type', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array(
'nullable' => false,
'primary' => true,
), 'Type')
->addColumn('value', Varien_Db_Ddl_Table::TYPE_TEXT, 32, array(
'nullable' => false,
'unsigned' => true,
'primary' => true,
), 'Value')
->addColumn('count', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
'unsigned' => true,
'nullable' => false,
'default' => '0',
), 'Count')
->addColumn('updated_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(), 'Update Time')
->setComment('Count Login Attempts');
$installer->getConnection()->createTable($table);
$installer->endSetup();
|
package com.avast.android.dialogs.core;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
/**
* Internal base builder that holds common values for all dialog fragment builders.
*
* @author Tomas Vondracek
*/
public abstract class BaseDialogBuilder<T extends BaseDialogBuilder<T>> {
public final static String ARG_REQUEST_CODE = "request_code";
public final static String <API key> = "cancelable_oto";
public final static String DEFAULT_TAG = "simple_dialog";
private String mTag = DEFAULT_TAG;
public final static int <API key> = -42;
private int mRequestCode = <API key>;
public static String ARG_USE_DARK_THEME = "usedarktheme";
public static String ARG_USE_LIGHT_THEME = "uselighttheme";
protected final Context mContext;
protected final FragmentManager mFragmentManager;
protected final Class<? extends BaseDialogFragment> mClass;
private Fragment mTargetFragment;
private boolean mCancelable = true;
private boolean <API key> = true;
private boolean mUseDarkTheme = false;
private boolean mUseLightTheme = false;
public BaseDialogBuilder(Context context, FragmentManager fragmentManager, Class<? extends BaseDialogFragment> clazz) {
mFragmentManager = fragmentManager;
mContext = context.<API key>();
mClass = clazz;
}
protected abstract T self();
protected abstract Bundle prepareArguments();
public T setCancelable(boolean cancelable) {
mCancelable = cancelable;
return self();
}
public T <API key>(boolean cancelable) {
<API key> = cancelable;
if (cancelable) {
mCancelable = cancelable;
}
return self();
}
public T setTargetFragment(Fragment fragment, int requestCode) {
mTargetFragment = fragment;
mRequestCode = requestCode;
return self();
}
public T setRequestCode(int requestCode) {
mRequestCode = requestCode;
return self();
}
public T setTag(String tag) {
mTag = tag;
return self();
}
public T useDarkTheme() {
mUseDarkTheme = true;
return self();
}
public T useLightTheme() {
mUseLightTheme = true;
return self();
}
private BaseDialogFragment create() {
final Bundle args = prepareArguments();
final BaseDialogFragment fragment = (BaseDialogFragment) Fragment.instantiate(mContext, mClass.getName(), args);
args.putBoolean(<API key>, <API key>);
args.putBoolean(ARG_USE_DARK_THEME, mUseDarkTheme);
args.putBoolean(ARG_USE_LIGHT_THEME, mUseLightTheme);
if (mTargetFragment != null) {
fragment.setTargetFragment(mTargetFragment, mRequestCode);
} else {
args.putInt(ARG_REQUEST_CODE, mRequestCode);
}
fragment.setCancelable(mCancelable);
return fragment;
}
public DialogFragment show() {
BaseDialogFragment fragment = create();
fragment.show(mFragmentManager, mTag);
return fragment;
}
/**
* Like show() but allows the commit to be executed after an activity's state is saved. This
* is dangerous because the commit can be lost if the activity needs to later be restored from
* its state, so this should only be used for cases where it is okay for the UI state to change
* unexpectedly on the user.
*/
public DialogFragment <API key>() {
BaseDialogFragment fragment = create();
fragment.<API key>(mFragmentManager, mTag);
return fragment;
}
}
|
package proguard.gui.splash;
import java.awt.*;
/**
* This interface describes objects that can paint themselves, possibly varying
* as a function of time.
*
* @author Eric Lafortune
*/
public interface Sprite
{
/**
* Paints the object.
*
* @param graphics the Graphics to paint on.
* @param time the time since the start of the animation, expressed in
* milliseconds.
*/
public void paint(Graphics graphics, long time);
}
|
#ifndef __EXPORT_COMMON__
#define __EXPORT_COMMON__
#if defined(SHP)
#include <FBaseConfig.h>
#define EXPORT_DLL _EXPORT_
#elif defined(_WIN32) || defined(_WINRT) || defined(_WP8)
#if defined(_EXPORT_DLL_)
#define EXPORT_DLL __declspec(dllexport)
#elif defined(IGNORE_EXPORT)
#define EXPORT_DLL
#else /* use a DLL library */
#define EXPORT_DLL __declspec(dllimport)
#endif
#else
#if defined(_SHARED_)
#define EXPORT_DLL __attribute__((visibility("default")))
#elif defined(IGNORE_EXPORT)
#define EXPORT_DLL
#else
#define EXPORT_DLL
#endif
#endif
#endif // end of __EXPORT_COMMON__
|
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine
{
internal sealed class Vbc : VisualBasicCompiler
{
internal Vbc(string responseFile, BuildPaths buildPaths, string[] args, <API key> analyzerLoader)
: base(<API key>.Default, responseFile, args, buildPaths.ClientDirectory, buildPaths.WorkingDirectory, buildPaths.SdkDirectory, Environment.<API key>("LIB"), analyzerLoader)
{
}
internal static int Run(string[] args, BuildPaths buildPaths, TextWriter textWriter, <API key> analyzerLoader)
{
FatalError.Handler = FailFast.OnFatalException;
var responseFile = Path.Combine(buildPaths.ClientDirectory, VisualBasicCompiler.ResponseFileName);
var compiler = new Vbc(responseFile, buildPaths, args, analyzerLoader);
return ConsoleUtil.RunWithUtf8Output(compiler.Arguments.Utf8Output, textWriter, tw => compiler.Run(tw));
}
protected override uint GetSqmAppID()
{
return SqmServiceProvider.CSHARP_APPID;
}
protected override void CompilerSpecificSqm(IVsSqmMulti sqm, uint sqmSession)
{
sqm.SetDatapoint(sqmSession, SqmServiceProvider.<API key>, (uint)SqmServiceProvider.CompilerType.Compiler);
sqm.SetDatapoint(sqmSession, SqmServiceProvider.<API key>, (uint)Arguments.ParseOptions.LanguageVersion);
sqm.SetDatapoint(sqmSession, SqmServiceProvider.<API key>, (uint)Arguments.CompilationOptions.WarningLevel);
//Project complexity # of source files, # of references
sqm.SetDatapoint(sqmSession, SqmServiceProvider.<API key>, (uint)Arguments.SourceFiles.Count());
sqm.SetDatapoint(sqmSession, SqmServiceProvider.<API key>, (uint)Arguments.ReferencePaths.Count());
}
}
}
|
class Tinyumbrella < Cask
version '7.04'
sha256 '<SHA256-like>'
url 'http://cache.firmwareumbrella.com/downloads/TinyUmbrella-7.04.00.app.zip'
homepage 'http://blog.firmwareumbrella.com/'
link 'TinyUmbrella.app'
end
|
// <API key>: Apache-2.0 WITH LLVM-exception
// Implementation of COFF support for the MC-JIT runtime dynamic linker.
#include "RuntimeDyldCOFF.h"
#include "Targets/<API key>.h"
#include "Targets/RuntimeDyldCOFFI386.h"
#include "Targets/<API key>.h"
#include "Targets/<API key>.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/FormatVariadic.h"
using namespace llvm;
using namespace llvm::object;
#define DEBUG_TYPE "dyld"
namespace {
class <API key> final
: public <API key><<API key>,
RuntimeDyld::LoadedObjectInfo> {
public:
<API key>(
RuntimeDyldImpl &RTDyld,
RuntimeDyld::LoadedObjectInfo::ObjSectionToIDMap ObjSecToIDMap)
: <API key>(RTDyld, std::move(ObjSecToIDMap)) {}
OwningBinary<ObjectFile>
getObjectForDebug(const ObjectFile &Obj) const override {
return OwningBinary<ObjectFile>();
}
};
}
namespace llvm {
std::unique_ptr<RuntimeDyldCOFF>
llvm::RuntimeDyldCOFF::create(Triple::ArchType Arch,
RuntimeDyld::MemoryManager &MemMgr,
JITSymbolResolver &Resolver) {
switch (Arch) {
default: llvm_unreachable("Unsupported target for RuntimeDyldCOFF.");
case Triple::x86:
return std::make_unique<RuntimeDyldCOFFI386>(MemMgr, Resolver);
case Triple::thumb:
return std::make_unique<<API key>>(MemMgr, Resolver);
case Triple::x86_64:
return std::make_unique<<API key>>(MemMgr, Resolver);
case Triple::aarch64:
return std::make_unique<<API key>>(MemMgr, Resolver);
}
}
std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
RuntimeDyldCOFF::loadObject(const object::ObjectFile &O) {
if (auto ObjSectionToIDOrErr = loadObjectImpl(O)) {
return std::make_unique<<API key>>(*this, *ObjSectionToIDOrErr);
} else {
HasError = true;
raw_string_ostream ErrStream(ErrorStr);
<API key>(ObjSectionToIDOrErr.takeError(), ErrStream);
return nullptr;
}
}
uint64_t RuntimeDyldCOFF::getSymbolOffset(const SymbolRef &Sym) {
// The value in a relocatable COFF object is the offset.
return cantFail(Sym.getValue());
}
uint64_t RuntimeDyldCOFF::getDLLImportOffset(unsigned SectionID, StubMap &Stubs,
StringRef Name,
bool SetSectionIDMinus1) {
LLVM_DEBUG(dbgs() << "Getting DLLImport entry for " << Name << "... ");
assert(Name.startswith(<API key>()) && "Not a DLLImport symbol?");
RelocationValueRef Reloc;
Reloc.SymbolName = Name.data();
auto I = Stubs.find(Reloc);
if (I != Stubs.end()) {
LLVM_DEBUG(dbgs() << format("{0:x8}", I->second) << "\n");
return I->second;
}
assert(SectionID < Sections.size() && "SectionID out of range");
auto &Sec = Sections[SectionID];
auto EntryOffset = alignTo(Sec.getStubOffset(), PointerSize);
Sec.advanceStubOffset(EntryOffset + PointerSize - Sec.getStubOffset());
Stubs[Reloc] = EntryOffset;
RelocationEntry RE(SectionID, EntryOffset, PointerReloc, 0, false,
Log2_64(PointerSize));
// Hack to tell I386/Thumb resolveRelocation that this isn't section relative.
if (SetSectionIDMinus1)
RE.Sections.SectionA = -1;
<API key>(RE, Name.drop_front(<API key>().size()));
LLVM_DEBUG({
dbgs() << "Creating entry at "
<< formatv("{0:x16} + {1:x8} ( {2:x16} )", Sec.getLoadAddress(),
EntryOffset, Sec.getLoadAddress() + EntryOffset)
<< "\n";
});
return EntryOffset;
}
bool RuntimeDyldCOFF::isCompatibleFile(const object::ObjectFile &Obj) const {
return Obj.isCOFF();
}
} // namespace llvm
|
#include <stddef.h>
#include "sync/api/attachments/attachment_metadata.h"
namespace syncer {
AttachmentMetadata::AttachmentMetadata(const AttachmentId& id, size_t size)
: id_(id), size_(size) {
}
AttachmentMetadata::~AttachmentMetadata() {
}
const AttachmentId& AttachmentMetadata::GetId() const {
return id_;
}
size_t AttachmentMetadata::GetSize() const {
return size_;
}
} // namespace syncer
|
#include "webkit/browser/fileapi/<API key>.h"
#include <queue>
#include <string>
#include <vector>
#include "base/file_util.h"
#include "base/format_macros.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/strings/<API key>.h"
#include "base/strings/stringprintf.h"
#include "base/strings/<API key>.h"
#include "base/strings/<API key>.h"
#include "base/time/time.h"
#include "url/gurl.h"
#include "webkit/browser/fileapi/file_observers.h"
#include "webkit/browser/fileapi/file_system_context.h"
#include "webkit/browser/fileapi/<API key>.h"
#include "webkit/browser/fileapi/file_system_url.h"
#include "webkit/browser/fileapi/native_file_util.h"
#include "webkit/browser/fileapi/<API key>.h"
#include "webkit/browser/fileapi/<API key>.h"
#include "webkit/browser/fileapi/<API key>.h"
#include "webkit/browser/fileapi/<API key>.h"
#include "webkit/browser/fileapi/timed_task_helper.h"
#include "webkit/browser/quota/quota_manager.h"
#include "webkit/common/database/database_identifier.h"
#include "webkit/common/fileapi/file_system_util.h"
// Example of various paths:
// void ObfuscatedFileUtil::DoSomething(const FileSystemURL& url) {
// base::FilePath virtual_path = url.path();
// base::FilePath local_path = GetLocalFilePath(url);
// NativeFileUtil::DoSomething(local_path);
// file_util::DoAnother(local_path);
namespace fileapi {
namespace {
typedef <API key>::FileId FileId;
typedef <API key>::FileInfo FileInfo;
void InitFileInfo(
<API key>::FileInfo* file_info,
<API key>::FileId parent_id,
const base::FilePath::StringType& file_name) {
DCHECK(file_info);
file_info->parent_id = parent_id;
file_info->name = file_name;
}
// Costs computed as per crbug.com/86114, based on the LevelDB implementation of
// path storage under Linux. It's not clear if that will differ on Windows, on
// which base::FilePath uses wide chars [since they're converted to UTF-8 for
// storage anyway], but as long as the cost is high enough that one can't cheat
// on quota by storing data in paths, it doesn't need to be all that accurate.
const int64 <API key> = 146; // Bytes per inode, basically.
const int64 kPathByteQuotaCost = 2; // Bytes per byte of path length in UTF-8.
int64 UsageForPath(size_t length) {
return <API key> +
static_cast<int64>(length) * kPathByteQuotaCost;
}
bool AllocateQuota(<API key>* context, int64 growth) {
if (context-><API key>() == quota::QuotaManager::kNoLimit)
return true;
int64 new_quota = context-><API key>() - growth;
if (growth > 0 && new_quota < 0)
return false;
context-><API key>(new_quota);
return true;
}
void UpdateUsage(
<API key>* context,
const FileSystemURL& url,
int64 growth) {
context->update_observers()->Notify(
&FileUpdateObserver::OnUpdate, MakeTuple(url, growth));
}
void TouchDirectory(<API key>* db, FileId dir_id) {
DCHECK(db);
if (!db-><API key>(dir_id, base::Time::Now()))
NOTREACHED();
}
enum <API key> {
<API key>,
<API key>,
<API key>,
};
} // namespace
class <API key>
: public FileSystemFileUtil::<API key> {
public:
<API key>(
<API key>* db,
<API key>* context,
ObfuscatedFileUtil* <API key>,
const FileSystemURL& root_url,
bool recursive)
: db_(db),
context_(context),
<API key>(<API key>),
root_url_(root_url),
recursive_(recursive),
current_file_id_(0) {
base::FilePath root_virtual_path = root_url.path();
FileId file_id;
if (!db_->GetFileWithPath(root_virtual_path, &file_id))
return;
FileRecord record = { file_id, root_virtual_path };
recurse_queue_.push(record);
}
virtual ~<API key>() {}
virtual base::FilePath Next() OVERRIDE {
ProcessRecurseQueue();
if (display_stack_.empty())
return base::FilePath();
current_file_id_ = display_stack_.back();
display_stack_.pop_back();
FileInfo file_info;
base::FilePath platform_file_path;
base::File::Error error =
<API key>->GetFileInfoInternal(
db_, context_, root_url_, current_file_id_,
&file_info, &<API key>, &platform_file_path);
if (error != base::File::FILE_OK)
return Next();
base::FilePath virtual_path =
<API key>.Append(file_info.name);
if (recursive_ && file_info.is_directory()) {
FileRecord record = { current_file_id_, virtual_path };
recurse_queue_.push(record);
}
return virtual_path;
}
virtual int64 Size() OVERRIDE {
return <API key>.size;
}
virtual base::Time LastModifiedTime() OVERRIDE {
return <API key>.last_modified;
}
virtual bool IsDirectory() OVERRIDE {
return <API key>.is_directory;
}
private:
typedef <API key>::FileId FileId;
typedef <API key>::FileInfo FileInfo;
struct FileRecord {
FileId file_id;
base::FilePath virtual_path;
};
void ProcessRecurseQueue() {
while (display_stack_.empty() && !recurse_queue_.empty()) {
FileRecord entry = recurse_queue_.front();
recurse_queue_.pop();
if (!db_->ListChildren(entry.file_id, &display_stack_)) {
display_stack_.clear();
return;
}
<API key> = entry.virtual_path;
}
}
<API key>* db_;
<API key>* context_;
ObfuscatedFileUtil* <API key>;
FileSystemURL root_url_;
bool recursive_;
std::queue<FileRecord> recurse_queue_;
std::vector<FileId> display_stack_;
base::FilePath <API key>;
FileId current_file_id_;
base::File::Info <API key>;
};
class <API key>
: public ObfuscatedFileUtil::<API key> {
public:
typedef <API key>::OriginRecord OriginRecord;
<API key>(
<API key>* origin_database,
const base::FilePath& base_file_path)
: base_file_path_(base_file_path) {
if (origin_database)
origin_database->ListAllOrigins(&origins_);
}
virtual ~<API key>() {}
// Returns the next origin. Returns empty if there are no more origins.
virtual GURL Next() OVERRIDE {
OriginRecord record;
if (!origins_.empty()) {
record = origins_.back();
origins_.pop_back();
}
current_ = record;
return webkit_database::<API key>(record.origin);
}
// Returns the current origin's information.
virtual bool HasTypeDirectory(const std::string& type_string) const OVERRIDE {
if (current_.path.empty())
return false;
if (type_string.empty()) {
NOTREACHED();
return false;
}
base::FilePath path =
base_file_path_.Append(current_.path).AppendASCII(type_string);
return base::DirectoryExists(path);
}
private:
std::vector<OriginRecord> origins_;
OriginRecord current_;
base::FilePath base_file_path_;
};
ObfuscatedFileUtil::ObfuscatedFileUtil(
quota::<API key>* <API key>,
const base::FilePath& <API key>,
leveldb::Env* env_override,
base::SequencedTaskRunner* file_task_runner,
const <API key>& <API key>,
const std::set<std::string>& known_type_strings,
<API key>* sandbox_delegate)
: <API key>(<API key>),
<API key>(<API key>),
env_override_(env_override),
<API key>(10 * 60), // 10 mins.
file_task_runner_(file_task_runner),
<API key>(<API key>),
known_type_strings_(known_type_strings),
sandbox_delegate_(sandbox_delegate) {
}
ObfuscatedFileUtil::~ObfuscatedFileUtil() {
DropDatabases();
}
base::File ObfuscatedFileUtil::CreateOrOpen(
<API key>* context,
const FileSystemURL& url, int file_flags) {
base::File file = <API key>(context, url, file_flags);
if (file.IsValid() && file_flags & base::File::FLAG_WRITE &&
context->quota_limit_type() == quota::<API key> &&
sandbox_delegate_) {
sandbox_delegate_-><API key>(url.origin(), url.type());
}
return file.Pass();
}
base::File::Error ObfuscatedFileUtil::EnsureFileExists(
<API key>* context,
const FileSystemURL& url,
bool* created) {
<API key>* db = <API key>(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory())
return base::File::<API key>;
if (created)
*created = false;
return base::File::FILE_OK;
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File::<API key>;
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = CreateFile(context, base::FilePath(), url,
&file_info);
if (created && base::File::FILE_OK == error) {
*created = true;
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(url));
}
return error;
}
base::File::Error ObfuscatedFileUtil::CreateDirectory(
<API key>* context,
const FileSystemURL& url,
bool exclusive,
bool recursive) {
<API key>* db = <API key>(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (db->GetFileWithPath(url.path(), &file_id)) {
FileInfo file_info;
if (exclusive)
return base::File::FILE_ERROR_EXISTS;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::<API key>;
return base::File::FILE_OK;
}
std::vector<base::FilePath::StringType> components;
VirtualPath::GetComponents(url.path(), &components);
FileId parent_id = 0;
size_t index;
for (index = 0; index < components.size(); ++index) {
base::FilePath::StringType name = components[index];
if (name == FILE_PATH_LITERAL("/"))
continue;
if (!db->GetChildWithName(parent_id, name, &parent_id))
break;
}
if (!db->IsDirectory(parent_id))
return base::File::<API key>;
if (!recursive && components.size() - index > 1)
return base::File::<API key>;
bool first = true;
for (; index < components.size(); ++index) {
FileInfo file_info;
file_info.name = components[index];
if (file_info.name == FILE_PATH_LITERAL("/"))
continue;
file_info.modification_time = base::Time::Now();
file_info.parent_id = parent_id;
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error = db->AddFileInfo(file_info, &parent_id);
if (error != base::File::FILE_OK)
return error;
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateDirectory, MakeTuple(url));
if (first) {
first = false;
TouchDirectory(db, file_info.parent_id);
}
}
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::GetFileInfo(
<API key>* context,
const FileSystemURL& url,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
<API key>* db = <API key>(url, false);
if (!db)
return base::File::<API key>;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::<API key>;
FileInfo local_info;
return GetFileInfoInternal(db, context, url,
file_id, &local_info,
file_info, platform_file_path);
}
scoped_ptr<FileSystemFileUtil::<API key>>
ObfuscatedFileUtil::<API key>(
<API key>* context,
const FileSystemURL& root_url) {
return <API key>(context, root_url, false /* recursive */);
}
base::File::Error ObfuscatedFileUtil::GetLocalFilePath(
<API key>* context,
const FileSystemURL& url,
base::FilePath* local_path) {
<API key>* db = <API key>(url, false);
if (!db)
return base::File::<API key>;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::<API key>;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info) || file_info.is_directory()) {
NOTREACHED();
// Directories have no local file path.
return base::File::<API key>;
}
*local_path = DataPathToLocalPath(url, file_info.data_path);
if (local_path->empty())
return base::File::<API key>;
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::Touch(
<API key>* context,
const FileSystemURL& url,
const base::Time& last_access_time,
const base::Time& last_modified_time) {
<API key>* db = <API key>(url, false);
if (!db)
return base::File::<API key>;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::<API key>;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (file_info.is_directory()) {
if (!db-><API key>(file_id, last_modified_time))
return base::File::FILE_ERROR_FAILED;
return base::File::FILE_OK;
}
return NativeFileUtil::Touch(
DataPathToLocalPath(url, file_info.data_path),
last_access_time, last_modified_time);
}
base::File::Error ObfuscatedFileUtil::Truncate(
<API key>* context,
const FileSystemURL& url,
int64 length) {
base::File::Info file_info;
base::FilePath local_path;
base::File::Error error =
GetFileInfo(context, url, &file_info, &local_path);
if (error != base::File::FILE_OK)
return error;
int64 growth = length - file_info.size;
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
error = NativeFileUtil::Truncate(local_path, length);
if (error == base::File::FILE_OK) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(url));
}
return error;
}
base::File::Error ObfuscatedFileUtil::CopyOrMoveFile(
<API key>* context,
const FileSystemURL& src_url,
const FileSystemURL& dest_url,
CopyOrMoveOption option,
bool copy) {
// Cross-filesystem copies and moves should be handled via CopyInForeignFile.
DCHECK(src_url.origin() == dest_url.origin());
DCHECK(src_url.type() == dest_url.type());
<API key>* db = <API key>(src_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId src_file_id;
if (!db->GetFileWithPath(src_url.path(), &src_file_id))
return base::File::<API key>;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(),
&dest_file_id);
FileInfo src_file_info;
base::File::Info <API key>;
base::FilePath src_local_path;
base::File::Error error = GetFileInfoInternal(
db, context, src_url, src_file_id,
&src_file_info, &<API key>, &src_local_path);
if (error != base::File::FILE_OK)
return error;
if (src_file_info.is_directory())
return base::File::<API key>;
FileInfo dest_file_info;
base::File::Info <API key>; // overwrite case only
base::FilePath dest_local_path; // overwrite case only
if (overwrite) {
base::File::Error error = GetFileInfoInternal(
db, context, dest_url, dest_file_id,
&dest_file_info, &<API key>, &dest_local_path);
if (error == base::File::<API key>)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::<API key>;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::<API key>;
}
dest_file_info = src_file_info;
dest_file_info.parent_id = dest_parent_id;
dest_file_info.name =
VirtualPath::BaseName(dest_url.path()).value();
}
int64 growth = 0;
if (copy)
growth += <API key>.size;
else
growth -= UsageForPath(src_file_info.name.size());
if (overwrite)
growth -= <API key>.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
/*
* Copy-with-overwrite
* Just overwrite data file
* <API key>
* Copy backing file
* Create new metadata pointing to new backing file.
* Move-with-overwrite
* transaction:
* Remove source entry.
* Point target entry to source entry's backing file.
* Delete target entry's old backing file
* <API key>
* Just update metadata
*/
error = base::File::FILE_ERROR_FAILED;
if (copy) {
if (overwrite) {
error = NativeFileUtil::CopyOrMoveFile(
src_local_path,
dest_local_path,
option,
fileapi::NativeFileUtil::<API key>(
dest_url, true /* copy */));
} else { // non-overwrite
error = CreateFile(context, src_local_path, dest_url, &dest_file_info);
}
} else {
if (overwrite) {
if (db->OverwritingMoveFile(src_file_id, dest_file_id)) {
if (base::File::FILE_OK !=
NativeFileUtil::DeleteFile(dest_local_path))
LOG(WARNING) << "Leaked a backing file.";
error = base::File::FILE_OK;
} else {
error = base::File::FILE_ERROR_FAILED;
}
} else { // non-overwrite
if (db->UpdateFileInfo(src_file_id, dest_file_info))
error = base::File::FILE_OK;
else
error = base::File::FILE_ERROR_FAILED;
}
}
if (error != base::File::FILE_OK)
return error;
if (overwrite) {
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile,
MakeTuple(dest_url));
} else {
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFileFrom,
MakeTuple(dest_url, src_url));
}
if (!copy) {
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveFile, MakeTuple(src_url));
TouchDirectory(db, src_file_info.parent_id);
}
TouchDirectory(db, dest_file_info.parent_id);
UpdateUsage(context, dest_url, growth);
return error;
}
base::File::Error ObfuscatedFileUtil::CopyInForeignFile(
<API key>* context,
const base::FilePath& src_file_path,
const FileSystemURL& dest_url) {
<API key>* db = <API key>(dest_url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
base::File::Info <API key>;
if (!base::GetFileInfo(src_file_path, &<API key>))
return base::File::<API key>;
FileId dest_file_id;
bool overwrite = db->GetFileWithPath(dest_url.path(),
&dest_file_id);
FileInfo dest_file_info;
base::File::Info <API key>; // overwrite case only
if (overwrite) {
base::FilePath dest_local_path;
base::File::Error error = GetFileInfoInternal(
db, context, dest_url, dest_file_id,
&dest_file_info, &<API key>, &dest_local_path);
if (error == base::File::<API key>)
overwrite = false; // fallback to non-overwrite case
else if (error != base::File::FILE_OK)
return error;
else if (dest_file_info.is_directory())
return base::File::<API key>;
}
if (!overwrite) {
FileId dest_parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(dest_url.path()),
&dest_parent_id)) {
return base::File::<API key>;
}
if (!dest_file_info.is_directory())
return base::File::FILE_ERROR_FAILED;
InitFileInfo(&dest_file_info, dest_parent_id,
VirtualPath::BaseName(dest_url.path()).value());
}
int64 growth = <API key>.size;
if (overwrite)
growth -= <API key>.size;
else
growth += UsageForPath(dest_file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File::FILE_ERROR_NO_SPACE;
base::File::Error error;
if (overwrite) {
base::FilePath dest_local_path =
DataPathToLocalPath(dest_url, dest_file_info.data_path);
error = NativeFileUtil::CopyOrMoveFile(
src_file_path, dest_local_path,
FileSystemOperation::OPTION_NONE,
fileapi::NativeFileUtil::<API key>(dest_url,
true /* copy */));
} else {
error = CreateFile(context, src_file_path, dest_url, &dest_file_info);
}
if (error != base::File::FILE_OK)
return error;
if (overwrite) {
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(dest_url));
} else {
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(dest_url));
}
UpdateUsage(context, dest_url, growth);
TouchDirectory(db, dest_file_info.parent_id);
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteFile(
<API key>* context,
const FileSystemURL& url) {
<API key>* db = <API key>(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::<API key>;
FileInfo file_info;
base::File::Info platform_file_info;
base::FilePath local_path;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::<API key> &&
error != base::File::FILE_OK)
return error;
if (file_info.is_directory())
return base::File::<API key>;
int64 growth = -UsageForPath(file_info.name.size()) - platform_file_info.size;
AllocateQuota(context, growth);
if (!db->RemoveFileInfo(file_id)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveFile, MakeTuple(url));
if (error == base::File::<API key>)
return base::File::FILE_OK;
error = NativeFileUtil::DeleteFile(local_path);
if (base::File::FILE_OK != error)
LOG(WARNING) << "Leaked a backing file.";
return base::File::FILE_OK;
}
base::File::Error ObfuscatedFileUtil::DeleteDirectory(
<API key>* context,
const FileSystemURL& url) {
<API key>* db = <API key>(url, true);
if (!db)
return base::File::FILE_ERROR_FAILED;
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return base::File::<API key>;
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (!file_info.is_directory())
return base::File::<API key>;
if (!db->RemoveFileInfo(file_id))
return base::File::<API key>;
int64 growth = -UsageForPath(file_info.name.size());
AllocateQuota(context, growth);
UpdateUsage(context, url, growth);
TouchDirectory(db, file_info.parent_id);
context->change_observers()->Notify(
&FileChangeObserver::OnRemoveDirectory, MakeTuple(url));
return base::File::FILE_OK;
}
webkit_blob::ScopedFile ObfuscatedFileUtil::CreateSnapshotFile(
<API key>* context,
const FileSystemURL& url,
base::File::Error* error,
base::File::Info* file_info,
base::FilePath* platform_path) {
// We're just returning the local file information.
*error = GetFileInfo(context, url, file_info, platform_path);
if (*error == base::File::FILE_OK && file_info->is_directory) {
*file_info = base::File::Info();
*error = base::File::<API key>;
}
return webkit_blob::ScopedFile();
}
scoped_ptr<FileSystemFileUtil::<API key>>
ObfuscatedFileUtil::<API key>(
<API key>* context,
const FileSystemURL& root_url,
bool recursive) {
<API key>* db = <API key>(root_url, false);
if (!db) {
return scoped_ptr<<API key>>(new EmptyFileEnumerator());
}
return scoped_ptr<<API key>>(
new <API key>(db, context, this, root_url, recursive));
}
bool ObfuscatedFileUtil::IsDirectoryEmpty(
<API key>* context,
const FileSystemURL& url) {
<API key>* db = <API key>(url, false);
if (!db)
return true; // Not a great answer, but it's what others do.
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id))
return true; // Ditto.
FileInfo file_info;
if (!db->GetFileInfo(file_id, &file_info)) {
DCHECK(!file_id);
// It's the root directory and the database hasn't been initialized yet.
return true;
}
if (!file_info.is_directory())
return true;
std::vector<FileId> children;
// TODO(ericu): This could easily be made faster with help from the database.
if (!db->ListChildren(file_id, &children))
return true;
return children.empty();
}
base::FilePath ObfuscatedFileUtil::<API key>(
const GURL& origin,
const std::string& type_string,
bool create,
base::File::Error* error_code) {
base::FilePath origin_dir = <API key>(origin, create, error_code);
if (origin_dir.empty())
return base::FilePath();
if (type_string.empty())
return origin_dir;
base::FilePath path = origin_dir.AppendASCII(type_string);
base::File::Error error = base::File::FILE_OK;
if (!base::DirectoryExists(path) &&
(!create || !base::CreateDirectory(path))) {
error = create ?
base::File::FILE_ERROR_FAILED :
base::File::<API key>;
}
if (error_code)
*error_code = error;
return path;
}
bool ObfuscatedFileUtil::<API key>(
const GURL& origin,
const std::string& type_string) {
base::File::Error error = base::File::FILE_OK;
base::FilePath origin_type_path = <API key>(
origin, type_string, false, &error);
if (origin_type_path.empty())
return true;
if (error != base::File::<API key>) {
// TODO(dmikurube): Consider the return value of <API key>.
// We ignore its error now since 1) it doesn't matter the final result, and
// 2) it always returns false in Windows because of LevelDB's
// implementation.
// Information about failure would be useful for debugging.
if (!type_string.empty())
<API key>(origin, type_string);
if (!base::DeleteFile(origin_type_path, true /* recursive */))
return false;
}
base::FilePath origin_path = VirtualPath::DirName(origin_type_path);
DCHECK_EQ(origin_path.value(),
<API key>(origin, false, NULL).value());
if (!type_string.empty()) {
// At this point we are sure we had successfully deleted the origin/type
// directory (i.e. we're ready to just return true).
// See if we have other directories in this origin directory.
for (std::set<std::string>::iterator iter = known_type_strings_.begin();
iter != known_type_strings_.end();
++iter) {
if (*iter == type_string)
continue;
if (base::DirectoryExists(origin_path.AppendASCII(*iter))) {
// Other type's directory exists; just return true here.
return true;
}
}
}
// No other directories seem exist. Try deleting the entire origin directory.
InitOriginDatabase(origin, false);
if (origin_database_) {
origin_database_->RemovePathForOrigin(
webkit_database::<API key>(origin));
}
if (!base::DeleteFile(origin_path, true /* recursive */))
return false;
return true;
}
ObfuscatedFileUtil::<API key>*
ObfuscatedFileUtil::<API key>() {
std::vector<<API key>::OriginRecord> origins;
InitOriginDatabase(GURL(), false);
return new <API key>(
origin_database_.get(), <API key>);
}
bool ObfuscatedFileUtil::<API key>(
const GURL& origin,
const std::string& type_string) {
std::string key = <API key>(origin, type_string);
if (key.empty())
return true;
DirectoryMap::iterator iter = directories_.find(key);
if (iter != directories_.end()) {
<API key>* database = iter->second;
directories_.erase(iter);
delete database;
}
base::File::Error error = base::File::FILE_OK;
base::FilePath path = <API key>(
origin, type_string, false, &error);
if (path.empty() || error == base::File::<API key>)
return true;
return <API key>::DestroyDatabase(path, env_override_);
}
// static
int64 ObfuscatedFileUtil::ComputeFilePathCost(const base::FilePath& path) {
return UsageForPath(VirtualPath::BaseName(path).value().size());
}
void ObfuscatedFileUtil::<API key>(
const std::vector<std::string>& <API key>) {
<API key> database(<API key>,
env_override_);
std::string origin_string = database.GetPrimaryOrigin();
if (origin_string.empty() || !database.HasOriginPath(origin_string))
return;
const GURL origin = webkit_database::<API key>(origin_string);
// Prepopulate the directory database(s) if and only if this instance
// has primary origin and the directory database is already there.
for (size_t i = 0; i < <API key>.size(); ++i) {
const std::string type_string = <API key>[i];
// Only handles known types.
if (!ContainsKey(known_type_strings_, type_string))
continue;
base::File::Error error = base::File::FILE_ERROR_FAILED;
base::FilePath path = <API key>(
origin, type_string, false, &error);
if (error != base::File::FILE_OK)
continue;
scoped_ptr<<API key>> db(
new <API key>(path, env_override_));
if (db->Init(<API key>::FAIL_ON_CORRUPTION)) {
directories_[<API key>(origin, type_string)] = db.release();
MarkUsed();
// Don't populate more than one database, as it may rather hurt
// performance.
break;
}
}
}
base::FilePath ObfuscatedFileUtil::GetDirectoryForURL(
const FileSystemURL& url,
bool create,
base::File::Error* error_code) {
return <API key>(
url.origin(), <API key>(url), create, error_code);
}
std::string ObfuscatedFileUtil::<API key>(
const FileSystemURL& url) {
DCHECK(!<API key>.is_null());
return <API key>.Run(url);
}
base::File::Error ObfuscatedFileUtil::GetFileInfoInternal(
<API key>* db,
<API key>* context,
const FileSystemURL& url,
FileId file_id,
FileInfo* local_info,
base::File::Info* file_info,
base::FilePath* platform_file_path) {
DCHECK(db);
DCHECK(context);
DCHECK(file_info);
DCHECK(platform_file_path);
if (!db->GetFileInfo(file_id, local_info)) {
NOTREACHED();
return base::File::FILE_ERROR_FAILED;
}
if (local_info->is_directory()) {
file_info->size = 0;
file_info->is_directory = true;
file_info->is_symbolic_link = false;
file_info->last_modified = local_info->modification_time;
*platform_file_path = base::FilePath();
// We don't fill in ctime or atime.
return base::File::FILE_OK;
}
if (local_info->data_path.empty())
return base::File::<API key>;
base::FilePath local_path = DataPathToLocalPath(url, local_info->data_path);
base::File::Error error = NativeFileUtil::GetFileInfo(
local_path, file_info);
// We should not follow symbolic links in sandboxed file system.
if (base::IsLink(local_path)) {
LOG(WARNING) << "Found a symbolic file.";
error = base::File::<API key>;
}
if (error == base::File::FILE_OK) {
*platform_file_path = local_path;
} else if (error == base::File::<API key>) {
LOG(WARNING) << "Lost a backing file.";
<API key>(context, url.origin(), url.type());
if (!db->RemoveFileInfo(file_id))
return base::File::FILE_ERROR_FAILED;
}
return error;
}
base::File ObfuscatedFileUtil::CreateAndOpenFile(
<API key>* context,
const FileSystemURL& dest_url,
FileInfo* dest_file_info, int file_flags) {
<API key>* db = <API key>(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error = <API key>(db, context, dest_url, &root,
&dest_local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (base::PathExists(dest_local_path)) {
if (!base::DeleteFile(dest_local_path, true /* recursive */))
return base::File(base::File::FILE_ERROR_FAILED);
LOG(WARNING) << "A stray file detected";
<API key>(context, dest_url.origin(), dest_url.type());
}
base::File file = NativeFileUtil::CreateOrOpen(dest_local_path, file_flags);
if (!file.IsValid())
return file.Pass();
if (!file.created()) {
file.Close();
base::DeleteFile(dest_local_path, false /* recursive */);
return base::File(base::File::FILE_ERROR_FAILED);
}
error = CommitCreateFile(root, dest_local_path, db, dest_file_info);
if (error != base::File::FILE_OK) {
file.Close();
base::DeleteFile(dest_local_path, false /* recursive */);
return base::File(error);
}
return file.Pass();
}
base::File::Error ObfuscatedFileUtil::CreateFile(
<API key>* context,
const base::FilePath& src_file_path,
const FileSystemURL& dest_url,
FileInfo* dest_file_info) {
<API key>* db = <API key>(dest_url, true);
base::FilePath root, dest_local_path;
base::File::Error error = <API key>(db, context, dest_url, &root,
&dest_local_path);
if (error != base::File::FILE_OK)
return error;
bool created = false;
if (src_file_path.empty()) {
if (base::PathExists(dest_local_path)) {
if (!base::DeleteFile(dest_local_path, true /* recursive */))
return base::File::FILE_ERROR_FAILED;
LOG(WARNING) << "A stray file detected";
<API key>(context, dest_url.origin(), dest_url.type());
}
error = NativeFileUtil::EnsureFileExists(dest_local_path, &created);
} else {
error = NativeFileUtil::CopyOrMoveFile(
src_file_path, dest_local_path,
FileSystemOperation::OPTION_NONE,
fileapi::NativeFileUtil::<API key>(dest_url,
true /* copy */));
created = true;
}
if (error != base::File::FILE_OK)
return error;
if (!created)
return base::File::FILE_ERROR_FAILED;
return CommitCreateFile(root, dest_local_path, db, dest_file_info);
}
base::File::Error ObfuscatedFileUtil::CommitCreateFile(
const base::FilePath& root,
const base::FilePath& local_path,
<API key>* db,
FileInfo* dest_file_info) {
// This removes the root, including the trailing slash, leaving a relative
// path.
dest_file_info->data_path = base::FilePath(
local_path.value().substr(root.value().length() + 1));
FileId file_id;
base::File::Error error = db->AddFileInfo(*dest_file_info, &file_id);
if (error != base::File::FILE_OK)
return error;
TouchDirectory(db, dest_file_info->parent_id);
return base::File::FILE_OK;
}
base::FilePath ObfuscatedFileUtil::DataPathToLocalPath(
const FileSystemURL& url, const base::FilePath& data_path) {
base::File::Error error = base::File::FILE_OK;
base::FilePath root = GetDirectoryForURL(url, false, &error);
if (error != base::File::FILE_OK)
return base::FilePath();
return root.Append(data_path);
}
std::string ObfuscatedFileUtil::<API key>(
const GURL& origin, const std::string& type_string) {
if (type_string.empty()) {
LOG(WARNING) << "Unknown filesystem type requested:" << type_string;
return std::string();
}
// For isolated origin we just use a type string as a key.
return webkit_database::<API key>(origin) +
type_string;
}
// TODO(ericu): How to do the whole <API key> thing?
// We may not have quota even to create the database.
// Ah, in that case don't even get here?
// Still doesn't answer the quota issue, though.
<API key>* ObfuscatedFileUtil::<API key>(
const FileSystemURL& url, bool create) {
std::string key = <API key>(
url.origin(), <API key>(url));
if (key.empty())
return NULL;
DirectoryMap::iterator iter = directories_.find(key);
if (iter != directories_.end()) {
MarkUsed();
return iter->second;
}
base::File::Error error = base::File::FILE_OK;
base::FilePath path = GetDirectoryForURL(url, create, &error);
if (error != base::File::FILE_OK) {
LOG(WARNING) << "Failed to get origin+type directory: "
<< url.DebugString() << " error:" << error;
return NULL;
}
MarkUsed();
<API key>* database =
new <API key>(path, env_override_);
directories_[key] = database;
return database;
}
base::FilePath ObfuscatedFileUtil::<API key>(
const GURL& origin, bool create, base::File::Error* error_code) {
if (!InitOriginDatabase(origin, create)) {
if (error_code) {
*error_code = create ?
base::File::FILE_ERROR_FAILED :
base::File::<API key>;
}
return base::FilePath();
}
base::FilePath directory_name;
std::string id = webkit_database::<API key>(origin);
bool exists_in_db = origin_database_->HasOriginPath(id);
if (!exists_in_db && !create) {
if (error_code)
*error_code = base::File::<API key>;
return base::FilePath();
}
if (!origin_database_->GetPathForOrigin(id, &directory_name)) {
if (error_code)
*error_code = base::File::FILE_ERROR_FAILED;
return base::FilePath();
}
base::FilePath path = <API key>.Append(directory_name);
bool exists_in_fs = base::DirectoryExists(path);
if (!exists_in_db && exists_in_fs) {
if (!base::DeleteFile(path, true)) {
if (error_code)
*error_code = base::File::FILE_ERROR_FAILED;
return base::FilePath();
}
exists_in_fs = false;
}
if (!exists_in_fs) {
if (!create || !base::CreateDirectory(path)) {
if (error_code)
*error_code = create ?
base::File::FILE_ERROR_FAILED :
base::File::<API key>;
return base::FilePath();
}
}
if (error_code)
*error_code = base::File::FILE_OK;
return path;
}
void ObfuscatedFileUtil::<API key>(
<API key>* context,
const GURL& origin,
FileSystemType type) {
if (sandbox_delegate_)
sandbox_delegate_-><API key>(origin, type);
}
void ObfuscatedFileUtil::MarkUsed() {
if (!timer_)
timer_.reset(new TimedTaskHelper(file_task_runner_.get()));
if (timer_->IsRunning()) {
timer_->Reset();
} else {
timer_->Start(FROM_HERE,
base::TimeDelta::FromSeconds(<API key>),
base::Bind(&ObfuscatedFileUtil::DropDatabases,
base::Unretained(this)));
}
}
void ObfuscatedFileUtil::DropDatabases() {
origin_database_.reset();
<API key>(
directories_.begin(), directories_.end());
directories_.clear();
timer_.reset();
}
bool ObfuscatedFileUtil::InitOriginDatabase(const GURL& origin_hint,
bool create) {
if (origin_database_)
return true;
if (!create && !base::DirectoryExists(<API key>))
return false;
if (!base::CreateDirectory(<API key>)) {
LOG(WARNING) << "Failed to create FileSystem directory: " <<
<API key>.value();
return false;
}
<API key>* <API key> =
new <API key>(<API key>,
env_override_);
origin_database_.reset(<API key>);
if (origin_hint.is_empty() || !HasIsolatedStorage(origin_hint))
return true;
const std::string <API key> =
webkit_database::<API key>(origin_hint);
// TODO(kinuko): Deprecate this after a few release cycles, e.g. around M33.
base::FilePath isolated_origin_dir = <API key>.Append(
<API key>::<API key>);
if (base::DirectoryExists(isolated_origin_dir) &&
<API key>-><API key>()) {
<API key>::<API key>(
<API key>,
<API key>,
<API key>-><API key>());
}
<API key>-><API key>(
<API key>);
return true;
}
base::File::Error ObfuscatedFileUtil::<API key>(
<API key>* db,
<API key>* context,
const FileSystemURL& url,
base::FilePath* root,
base::FilePath* local_path) {
DCHECK(local_path);
int64 number;
if (!db || !db->GetNextInteger(&number))
return base::File::FILE_ERROR_FAILED;
base::File::Error error = base::File::FILE_OK;
*root = GetDirectoryForURL(url, false, &error);
if (error != base::File::FILE_OK)
return error;
// We use the third- and fourth-to-last digits as the directory.
int64 directory_number = number % 10000 / 100;
base::FilePath new_local_path = root->AppendASCII(
base::StringPrintf("%02" PRId64, directory_number));
error = NativeFileUtil::CreateDirectory(
new_local_path, false /* exclusive */, false /* recursive */);
if (error != base::File::FILE_OK)
return error;
*local_path =
new_local_path.AppendASCII(base::StringPrintf("%08" PRId64, number));
return base::File::FILE_OK;
}
base::File ObfuscatedFileUtil::<API key>(
<API key>* context,
const FileSystemURL& url, int file_flags) {
DCHECK(!(file_flags & (base::File::<API key> |
base::File::FLAG_HIDDEN | base::File::FLAG_EXCLUSIVE_READ |
base::File::<API key>)));
<API key>* db = <API key>(url, true);
if (!db)
return base::File(base::File::FILE_ERROR_FAILED);
FileId file_id;
if (!db->GetFileWithPath(url.path(), &file_id)) {
// The file doesn't exist.
if (!(file_flags & (base::File::FLAG_CREATE |
base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_OPEN_ALWAYS))) {
return base::File(base::File::<API key>);
}
FileId parent_id;
if (!db->GetFileWithPath(VirtualPath::DirName(url.path()), &parent_id))
return base::File(base::File::<API key>);
FileInfo file_info;
InitFileInfo(&file_info, parent_id,
VirtualPath::BaseName(url.path()).value());
int64 growth = UsageForPath(file_info.name.size());
if (!AllocateQuota(context, growth))
return base::File(base::File::FILE_ERROR_NO_SPACE);
base::File file = CreateAndOpenFile(context, url, &file_info, file_flags);
if (file.IsValid()) {
UpdateUsage(context, url, growth);
context->change_observers()->Notify(
&FileChangeObserver::OnCreateFile, MakeTuple(url));
}
return file.Pass();
}
if (file_flags & base::File::FLAG_CREATE)
return base::File(base::File::FILE_ERROR_EXISTS);
base::File::Info platform_file_info;
base::FilePath local_path;
FileInfo file_info;
base::File::Error error = GetFileInfoInternal(
db, context, url, file_id, &file_info, &platform_file_info, &local_path);
if (error != base::File::FILE_OK)
return base::File(error);
if (file_info.is_directory())
return base::File(base::File::<API key>);
int64 delta = 0;
if (file_flags & (base::File::FLAG_CREATE_ALWAYS |
base::File::FLAG_OPEN_TRUNCATED)) {
// The file exists and we're truncating.
delta = -platform_file_info.size;
AllocateQuota(context, delta);
}
base::File file = NativeFileUtil::CreateOrOpen(local_path, file_flags);
if (!file.IsValid()) {
error = file.error_details();
if (error == base::File::<API key>) {
// TODO(tzik): Also invalidate on-memory usage cache in UsageTracker.
// TODO(tzik): Delete database entry after ensuring the file lost.
<API key>(context, url.origin(), url.type());
LOG(WARNING) << "Lost a backing file.";
return base::File(base::File::FILE_ERROR_FAILED);
}
return file.Pass();
}
// If truncating we need to update the usage.
if (delta) {
UpdateUsage(context, url, delta);
context->change_observers()->Notify(
&FileChangeObserver::OnModifyFile, MakeTuple(url));
}
return file.Pass();
}
bool ObfuscatedFileUtil::HasIsolatedStorage(const GURL& origin) {
return <API key>.get() &&
<API key>->HasIsolatedStorage(origin);
}
} // namespace fileapi
|
export enum TagContentType {
RAW_TEXT,
ESCAPABLE_RAW_TEXT,
PARSABLE_DATA
}
export interface TagDefinition {
closedByParent: boolean;
<API key>: string|null;
contentType: TagContentType;
isVoid: boolean;
ignoreFirstLf: boolean;
canSelfClose: boolean;
isClosedByChild(name: string): boolean;
}
export function splitNsName(elementName: string): [string | null, string] {
if (elementName[0] != ':') {
return [null, elementName];
}
const colonIndex = elementName.indexOf(':', 1);
if (colonIndex == -1) {
throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
// `<ng-container>` tags work the same regardless the namespace
export function isNgContainer(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-container';
}
// `<ng-content>` tags work the same regardless the namespace
export function isNgContent(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-content';
}
// `<ng-template>` tags work the same regardless the namespace
export function isNgTemplate(tagName: string): boolean {
return splitNsName(tagName)[1] === 'ng-template';
}
export function getNsPrefix(fullName: string): string;
export function getNsPrefix(fullName: null): null;
export function getNsPrefix(fullName: string | null): string|null {
return fullName === null ? null : splitNsName(fullName)[0];
}
export function mergeNsAndName(prefix: string, localName: string): string {
return prefix ? `:${prefix}:${localName}` : localName;
}
// see http://www.w3.org/TR/html51/syntax.html#<API key>
// This list is not exhaustive to keep the compiler footprint low.
// The `{` / `ƫ` syntax should be used when the named character reference does not
// exist.
export const NAMED_ENTITIES: {[k: string]: string} = {
'Aacute': '\u00C1',
'aacute': '\u00E1',
'Acirc': '\u00C2',
'acirc': '\u00E2',
'acute': '\u00B4',
'AElig': '\u00C6',
'aelig': '\u00E6',
'Agrave': '\u00C0',
'agrave': '\u00E0',
'alefsym': '\u2135',
'Alpha': '\u0391',
'alpha': '\u03B1',
'amp': '&',
'and': '\u2227',
'ang': '\u2220',
'apos': '\u0027',
'Aring': '\u00C5',
'aring': '\u00E5',
'asymp': '\u2248',
'Atilde': '\u00C3',
'atilde': '\u00E3',
'Auml': '\u00C4',
'auml': '\u00E4',
'bdquo': '\u201E',
'Beta': '\u0392',
'beta': '\u03B2',
'brvbar': '\u00A6',
'bull': '\u2022',
'cap': '\u2229',
'Ccedil': '\u00C7',
'ccedil': '\u00E7',
'cedil': '\u00B8',
'cent': '\u00A2',
'Chi': '\u03A7',
'chi': '\u03C7',
'circ': '\u02C6',
'clubs': '\u2663',
'cong': '\u2245',
'copy': '\u00A9',
'crarr': '\u21B5',
'cup': '\u222A',
'curren': '\u00A4',
'dagger': '\u2020',
'Dagger': '\u2021',
'darr': '\u2193',
'dArr': '\u21D3',
'deg': '\u00B0',
'Delta': '\u0394',
'delta': '\u03B4',
'diams': '\u2666',
'divide': '\u00F7',
'Eacute': '\u00C9',
'eacute': '\u00E9',
'Ecirc': '\u00CA',
'ecirc': '\u00EA',
'Egrave': '\u00C8',
'egrave': '\u00E8',
'empty': '\u2205',
'emsp': '\u2003',
'ensp': '\u2002',
'Epsilon': '\u0395',
'epsilon': '\u03B5',
'equiv': '\u2261',
'Eta': '\u0397',
'eta': '\u03B7',
'ETH': '\u00D0',
'eth': '\u00F0',
'Euml': '\u00CB',
'euml': '\u00EB',
'euro': '\u20AC',
'exist': '\u2203',
'fnof': '\u0192',
'forall': '\u2200',
'frac12': '\u00BD',
'frac14': '\u00BC',
'frac34': '\u00BE',
'frasl': '\u2044',
'Gamma': '\u0393',
'gamma': '\u03B3',
'ge': '\u2265',
'gt': '>',
'harr': '\u2194',
'hArr': '\u21D4',
'hearts': '\u2665',
'hellip': '\u2026',
'Iacute': '\u00CD',
'iacute': '\u00ED',
'Icirc': '\u00CE',
'icirc': '\u00EE',
'iexcl': '\u00A1',
'Igrave': '\u00CC',
'igrave': '\u00EC',
'image': '\u2111',
'infin': '\u221E',
'int': '\u222B',
'Iota': '\u0399',
'iota': '\u03B9',
'iquest': '\u00BF',
'isin': '\u2208',
'Iuml': '\u00CF',
'iuml': '\u00EF',
'Kappa': '\u039A',
'kappa': '\u03BA',
'Lambda': '\u039B',
'lambda': '\u03BB',
'lang': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'lArr': '\u21D0',
'lceil': '\u2308',
'ldquo': '\u201C',
'le': '\u2264',
'lfloor': '\u230A',
'lowast': '\u2217',
'loz': '\u25CA',
'lrm': '\u200E',
'lsaquo': '\u2039',
'lsquo': '\u2018',
'lt': '<',
'macr': '\u00AF',
'mdash': '\u2014',
'micro': '\u00B5',
'middot': '\u00B7',
'minus': '\u2212',
'Mu': '\u039C',
'mu': '\u03BC',
'nabla': '\u2207',
'nbsp': '\u00A0',
'ndash': '\u2013',
'ne': '\u2260',
'ni': '\u220B',
'not': '\u00AC',
'notin': '\u2209',
'nsub': '\u2284',
'Ntilde': '\u00D1',
'ntilde': '\u00F1',
'Nu': '\u039D',
'nu': '\u03BD',
'Oacute': '\u00D3',
'oacute': '\u00F3',
'Ocirc': '\u00D4',
'ocirc': '\u00F4',
'OElig': '\u0152',
'oelig': '\u0153',
'Ograve': '\u00D2',
'ograve': '\u00F2',
'oline': '\u203E',
'Omega': '\u03A9',
'omega': '\u03C9',
'Omicron': '\u039F',
'omicron': '\u03BF',
'oplus': '\u2295',
'or': '\u2228',
'ordf': '\u00AA',
'ordm': '\u00BA',
'Oslash': '\u00D8',
'oslash': '\u00F8',
'Otilde': '\u00D5',
'otilde': '\u00F5',
'otimes': '\u2297',
'Ouml': '\u00D6',
'ouml': '\u00F6',
'para': '\u00B6',
'permil': '\u2030',
'perp': '\u22A5',
'Phi': '\u03A6',
'phi': '\u03C6',
'Pi': '\u03A0',
'pi': '\u03C0',
'piv': '\u03D6',
'plusmn': '\u00B1',
'pound': '\u00A3',
'prime': '\u2032',
'Prime': '\u2033',
'prod': '\u220F',
'prop': '\u221D',
'Psi': '\u03A8',
'psi': '\u03C8',
'quot': '\u0022',
'radic': '\u221A',
'rang': '\u27E9',
'raquo': '\u00BB',
'rarr': '\u2192',
'rArr': '\u21D2',
'rceil': '\u2309',
'rdquo': '\u201D',
'real': '\u211C',
'reg': '\u00AE',
'rfloor': '\u230B',
'Rho': '\u03A1',
'rho': '\u03C1',
'rlm': '\u200F',
'rsaquo': '\u203A',
'rsquo': '\u2019',
'sbquo': '\u201A',
'Scaron': '\u0160',
'scaron': '\u0161',
'sdot': '\u22C5',
'sect': '\u00A7',
'shy': '\u00AD',
'Sigma': '\u03A3',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sim': '\u223C',
'spades': '\u2660',
'sub': '\u2282',
'sube': '\u2286',
'sum': '\u2211',
'sup': '\u2283',
'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supe': '\u2287',
'szlig': '\u00DF',
'Tau': '\u03A4',
'tau': '\u03C4',
'there4': '\u2234',
'Theta': '\u0398',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thinsp': '\u2009',
'THORN': '\u00DE',
'thorn': '\u00FE',
'tilde': '\u02DC',
'times': '\u00D7',
'trade': '\u2122',
'Uacute': '\u00DA',
'uacute': '\u00FA',
'uarr': '\u2191',
'uArr': '\u21D1',
'Ucirc': '\u00DB',
'ucirc': '\u00FB',
'Ugrave': '\u00D9',
'ugrave': '\u00F9',
'uml': '\u00A8',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'upsilon': '\u03C5',
'Uuml': '\u00DC',
'uuml': '\u00FC',
'weierp': '\u2118',
'Xi': '\u039E',
'xi': '\u03BE',
'Yacute': '\u00DD',
'yacute': '\u00FD',
'yen': '\u00A5',
'yuml': '\u00FF',
'Yuml': '\u0178',
'Zeta': '\u0396',
'zeta': '\u03B6',
'zwj': '\u200D',
'zwnj': '\u200C',
};
// The &ngsp; pseudo-entity is denoting a space. see:
export const NGSP_UNICODE = '\uE500';
NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
|
// AKMixedFFT.h
// AudioKit
#import "AKParameter+Operation.h"
#import "AKFSignal.h"
/** Mix 'seamlessly' two pv signals. This opcode combines the most prominent
components of two pvoc streams into a single mixed stream.
*/
<API key>
@interface AKMixedFFT : AKFSignal
Create a mixture of two f-signal.
@param signal1 The first f-signal.
@param signal2 The second f-signal.
- (instancetype)initWithSignal1:(AKFSignal *)signal1
signal2:(AKFSignal *)signal2;
@end
<API key>
|
# coding: utf-8
#(ASCII)
#txt(10)
# n 9 n-1 910
# key key ( key 2
# a c z A )10
#1010
#key(10)
#( ord() chr() ord(x) x ASCII chr(n) n(ASCII)
# ord(a) 97 chr(97) 'a' a ASCII 97 )
fh = open(r'd:\temp\words.txt')
text = fh.read()
fh.close()
print(len(text))
print(text)
|
// SeqAn - The Library for Sequence Analysis
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
// The adaption of the meta profile and the setup for the banded chain
// alignment.
#ifndef <API key>
#define <API key>
namespace seqan {
// Forwards
// Tags, Classes, Enums
// Tag <API key>
// Specifies the first dp matrix that is computed.
struct <API key>;
typedef Tag<<API key>> <API key>;
// Tag <API key>
// Specifies the inner dp matrix that is computed.
struct <API key>;
typedef Tag<<API key>> <API key>;
// Tag <API key>
// Specifies the lasr dp matrix that is computed.
struct <API key>;
typedef Tag<<API key>> <API key>;
// Struct <API key>
// Algorithm tag for the banded chain alignments. The first type determines the
// free end-gaps and the second one which dp matrix is currently considered (initial, inner, final)
template <typename TSpec = FreeEndGaps_<>, typename TDPMatrixLocation = <API key>>
struct <API key>{};
// Class DPMetaColumn [FullColumn]
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType>
struct DPMetaColumn_<DPProfile_<<API key><TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>,
<API key><TColumnType, FullColumn> >
{
// If InitialColumn -> replaced, replaced, replaced
// If InnerColumn -> replaced, All, All
// If FinalColumn -> replaced, All, All
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef DPMetaCell_<<API key>, True> TFirstCell_;
typedef DPMetaCell_<<API key>, True> TInnerCell_;
typedef DPMetaCell_<<API key>, True> TLastCell_;
};
// Class DPMetaColumn [PartialColumnTop]
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType>
struct DPMetaColumn_<DPProfile_<<API key><TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>,
<API key><TColumnType, PartialColumnTop> >
{
// If InitialColumn -> replaced, replaced, replaced
// If InnerColumn -> replaced, All, LowerBand
// If FinalColumn -> replaced, All, LowerBand
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef DPMetaCell_<<API key>, True> TFirstCell_;
typedef DPMetaCell_<<API key>, True> TInnerCell_;
typedef DPMetaCell_<<API key>, True> TLastCell_;
};
// Class DPMetaColumn [PartialColumnMiddle]
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType>
struct DPMetaColumn_<DPProfile_<<API key><TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>,
<API key><TColumnType, PartialColumnMiddle> >
{
// If InitialColumn -> replaced, replaced, replaced
// If InnerColumn -> UpperDiagonal, All, LowerDiagonal
// If FinalColumn -> UpperDiagonal, All, LowerDiagonal
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef DPMetaCell_<<API key>, True> TFirstCell_;
typedef DPMetaCell_<<API key>, True> TInnerCell_;
typedef DPMetaCell_<<API key>, True> TLastCell_;
};
// Class DPMetaColumn [PartialColumnBottom]
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TGapCosts, typename TTraceback, typename TColumnType>
struct DPMetaColumn_<DPProfile_<<API key><TFreeEndGaps, TDPMatrixLocation>, TGapCosts, TTraceback>,
<API key><TColumnType, PartialColumnBottom> >
{
// If InitialColumn -> replaced, replaced, replaced
// If InnerColumn -> UpperDiagonal, All, All
// If FinalColumn -> UpperDiagonal, All, All
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef <API key> <API key>;
typedef DPMetaCell_<<API key>, True> TFirstCell_;
typedef DPMetaCell_<<API key>, True> TInnerCell_;
typedef DPMetaCell_<<API key>, True> TLastCell_;
};
// Metafunctions
// Metafunction IsGlobalAlignment_
template <typename TSpec, typename TDPMatrixLocation>
struct IsGlobalAlignment_<<API key><TSpec, TDPMatrixLocation> > : False{};
// Metafunction IsFreeEndGap_
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TDPSide>
struct IsFreeEndGap_<<API key><TFreeEndGaps, TDPMatrixLocation>, TDPSide> :
IsFreeEndGap_<TFreeEndGaps, TDPSide>
{};
template <typename TFreeEndGaps, typename TDPMatrixLocation, typename TDPSide>
struct IsFreeEndGap_<<API key><TFreeEndGaps, TDPMatrixLocation> const, TDPSide> :
IsFreeEndGap_<TFreeEndGaps const, TDPSide>
{};
// Metafunction <API key>
// Profile for <API key> algorithm
template <typename TAlignConfig, typename TGapCosts, typename TGapsPlacement>
struct <API key>
{
typedef typename <API key><TAlignConfig>::Type TFreeEndGaps_;
typedef DPProfile_<<API key><TFreeEndGaps_, <API key>>, TGapCosts, TracebackOn<TracebackConfig_<CompleteTrace,TGapsPlacement> > > Type;
};
// Functions
// Function <API key>()
template <typename TTraceSegment, typename TStringSetSpec, typename TSeeds, typename TSequenceH, typename TSequenceV,
typename TScoreValue, typename TScoreSpecAnchor, typename TScoreSpecGap, bool TFirstRow, bool TFirstColumn,
bool TLastColumn, bool TLastRow, typename TACSpec, typename TGapsPlacement>
inline TScoreValue
<API key>(StringSet<String<TTraceSegment>, TStringSetSpec> & globalTraceSet,
TSeeds const & seedSet,
TSequenceH const & seqH,
TSequenceV const & seqV,
Score<TScoreValue, TScoreSpecAnchor> const & scoringSchemeAnchor,
Score<TScoreValue, TScoreSpecGap> const & scoringSchemeGap,
AlignConfig<TFirstRow, TFirstColumn, TLastColumn, TLastRow, TACSpec> const &,
unsigned bandExtension,
TGapsPlacement const &)
{
//typedef typename Position<TSequenceH const>::Type TPosH;
//typedef typename Position<TSequenceV const>::Type TPosV;
typedef AlignConfig<TFirstRow, TFirstColumn, TLastColumn, TLastRow, TACSpec> TAlignConfig;
typedef Score<TScoreValue, TScoreSpecAnchor> <API key>;
typedef Score<TScoreValue, TScoreSpecGap> TScoringSchemeGap;
typedef typename <API key><<API key>, TSequenceH>::Type <API key>;
typedef typename <API key><<API key>, TSequenceV>::Type <API key>;
typedef typename <API key><TScoringSchemeGap, TSequenceH>::Type TSequenceHEntryGap;
typedef typename <API key><TScoringSchemeGap, TSequenceV>::Type TSequenceVEntryGap;
<API key> seqHEntryAnchor = <API key>(scoringSchemeAnchor, seqH, 0);
<API key> seqVEntryAnchor = <API key>(scoringSchemeAnchor, seqV, 0);
TSequenceHEntryGap seqHEntryGap = <API key>(scoringSchemeGap, seqH, 0);
TSequenceVEntryGap seqVEntryGap = <API key>(scoringSchemeGap, seqV, 0);
if (<API key>(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) !=
<API key>(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) ||
<API key>(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) !=
<API key>(scoringSchemeAnchor, seqHEntryAnchor, seqVEntryAnchor) ||
<API key>(scoringSchemeGap, seqHEntryGap, seqVEntryGap) !=
<API key>(scoringSchemeGap, seqHEntryGap, seqVEntryGap) ||
<API key>(scoringSchemeGap, seqHEntryGap, seqVEntryGap) !=
<API key>(scoringSchemeGap, seqHEntryGap, seqVEntryGap))
{
typedef typename <API key><TAlignConfig, AffineGaps, TGapsPlacement>::Type TDPProfile;
return _computeAlignment(globalTraceSet, seedSet, seqH, seqV, scoringSchemeAnchor, scoringSchemeGap, bandExtension,
TDPProfile());
}
else
{
typedef typename <API key><TAlignConfig, LinearGaps, TGapsPlacement>::Type TDPProfile;
return _computeAlignment(globalTraceSet, seedSet, seqH, seqV, scoringSchemeAnchor, scoringSchemeGap, bandExtension,
TDPProfile());
}
}
} // namespace seqan
#endif // #ifndef <API key>
|
var Model;
module("Ember.FilteredRecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 'abc', name: 'Charles'}
];
},
teardown: function() { }
});
test("must be created with a modelClass property", function() {
throws(function() {
Ember.FilteredRecordArray.create();
}, /<API key> must be created with a modelClass/);
});
test("must be created with a filterFunction property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model});
}, /<API key> must be created with a filterFunction/);
});
test("must be created with a filterProperties property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K});
}, /<API key> must be created with filterProperties/);
});
test("with a noop filter will return all the loaded records", function() {
expect(1);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: Ember.K,
filterProperties: []
});
equal(recordArray.get('length'), 3, "There are 3 records");
});
stop();
});
test("with a filter will return only the relevant loaded records", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 1, "There is still 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
stop();
});
test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() {
expect(3);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik' || record.get('name') === 'Kris';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 2, "There are 2 records");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches");
});
stop();
});
stop();
});
test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(5);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.fetch(2).then(function(record) {
start();
record.set('name', 'Estefan');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches");
});
stop();
});
stop();
});
test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(8);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
record.set('name', 'Ekris');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches");
record.set('name', 'Eskil');
equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches");
equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches");
});
stop();
});
stop();
});
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../libc/enum.fpos64_t.html">
</head>
<body>
<p>Redirecting to <a href="../../libc/enum.fpos64_t.html">../../libc/enum.fpos64_t.html</a>...</p>
<script>location.replace("../../libc/enum.fpos64_t.html" + location.search + location.hash);</script>
</body>
</html>
|
#ifndef <API key>
#define <API key>
#include <ngx_core.h>
#include <ngx_http.h>
typedef enum {
<API key>,
<API key>
} <API key>;
typedef struct {
ngx_array_t *types; /* of ngx_str_t */
ngx_array_t *statuses; /* of ngx_uint_t */
ngx_array_t *headers; /* of <API key> */
ngx_flag_t is_input;
} <API key>;
typedef struct {
ngx_array_t *cmds; /* of <API key> */
} <API key>;
typedef struct {
unsigned <API key>;
} <API key>;
typedef struct <API key>
<API key>;
typedef ngx_int_t (*<API key>)(ngx_http_request_t *r,
<API key> *hv, ngx_str_t *value);
typedef struct {
ngx_str_t name;
ngx_uint_t offset;
<API key> handler;
} <API key>;
struct <API key> {
<API key> value;
ngx_uint_t hash;
ngx_str_t key;
<API key> handler;
ngx_uint_t offset;
ngx_flag_t replace;
ngx_flag_t wildcard;
};
extern ngx_module_t <API key>;
extern unsigned <API key>;
extern unsigned <API key>;
#ifndef ngx_str_set
#define ngx_str_set(str, text) \
(str)->len = sizeof(text) - 1; (str)->data = (u_char *) text
#endif
#endif /* <API key> */
|
// Package binary implements sintax-sugar functions on top of the standard
// library binary package
package binary
import (
"bufio"
"encoding/binary"
"io"
"gopkg.in/src-d/go-git.v4/plumbing"
)
// Read reads structured binary data from r into data. Bytes are read and
// decoded in BigEndian order
// https://golang.org/pkg/encoding/binary/#Read
func Read(r io.Reader, data ...interface{}) error {
for _, v := range data {
if err := binary.Read(r, binary.BigEndian, v); err != nil {
return err
}
}
return nil
}
// ReadUntil reads from r untin delim is found
func ReadUntil(r io.Reader, delim byte) ([]byte, error) {
var buf [1]byte
value := make([]byte, 0, 16)
for {
if _, err := io.ReadFull(r, buf[:]); err != nil {
if err == io.EOF {
return nil, err
}
return nil, err
}
if buf[0] == delim {
return value, nil
}
value = append(value, buf[0])
}
}
// <API key> reads and returns an int in Git VLQ special format:
// Ordinary VLQ has some redundancies, example: the number 358 can be
// encoded as the 2-octet VLQ 0x8166 or the 3-octet VLQ 0x808166 or the
// 4-octet VLQ 0x80808166 and so forth.
// To avoid these redundancies, the VLQ format used in Git removes this
// prepending redundancy and extends the representable range of shorter
// VLQs by adding an offset to VLQs of 2 or more octets in such a way
// that the lowest possible value for such an (N+1)-octet VLQ becomes
// exactly one more than the maximum possible value for an N-octet VLQ.
// In particular, since a 1-octet VLQ can store a maximum value of 127,
// the minimum 2-octet VLQ (0x8000) is assigned the value 128 instead of
// 0. Conversely, the maximum value of such a 2-octet VLQ (0xff7f) is
// 16511 instead of just 16383. Similarly, the minimum 3-octet VLQ
// (0x808000) has a value of 16512 instead of zero, which means
// that the maximum 3-octet VLQ (0xffff7f) is 2113663 instead of
// just 2097151. And so forth.
// This is how the offset is saved in C:
// dheader[pos] = ofs & 127;
// while (ofs >>= 7)
// dheader[--pos] = 128 | (--ofs & 127);
func <API key>(r io.Reader) (int64, error) {
var c byte
if err := Read(r, &c); err != nil {
return 0, err
}
var v = int64(c & maskLength)
for c&maskContinue > 0 {
v++
if err := Read(r, &c); err != nil {
return 0, err
}
v = (v << lengthBits) + int64(c&maskLength)
}
return v, nil
}
const (
maskContinue = uint8(128) // 1000 000
maskLength = uint8(127) // 0111 1111
lengthBits = uint8(7) // subsequent bytes has 7 bits to store the length
)
// ReadUint64 reads 8 bytes and returns them as a BigEndian uint32
func ReadUint64(r io.Reader) (uint64, error) {
var v uint64
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadUint32 reads 4 bytes and returns them as a BigEndian uint32
func ReadUint32(r io.Reader) (uint32, error) {
var v uint32
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadUint16 reads 2 bytes and returns them as a BigEndian uint16
func ReadUint16(r io.Reader) (uint16, error) {
var v uint16
if err := binary.Read(r, binary.BigEndian, &v); err != nil {
return 0, err
}
return v, nil
}
// ReadHash reads a plumbing.Hash from r
func ReadHash(r io.Reader) (plumbing.Hash, error) {
var h plumbing.Hash
if err := binary.Read(r, binary.BigEndian, h[:]); err != nil {
return plumbing.ZeroHash, err
}
return h, nil
}
const sniffLen = 8000
// IsBinary detects if data is a binary value based on:
// http://git.kernel.org/cgit/git/git.git/tree/xdiff-interface.c?id=HEAD#n198
func IsBinary(r io.Reader) (bool, error) {
reader := bufio.NewReader(r)
c := 0
for {
if c == sniffLen {
break
}
b, err := reader.ReadByte()
if err == io.EOF {
break
}
if err != nil {
return false, err
}
if b == byte(0) {
return true, nil
}
c++
}
return false, nil
}
|
// MLAnonymousUtils.h
// MaxLeap
#ifdef EXTENSION_IOS
#import <MaxLeapExt/MLConstants.h>
#else
#import <MaxLeap/MLConstants.h>
#endif
/*!
Methods for working with Anonymously logged-in users. Anonymous users have some unique characteristics:
<ul>
<li>Anonymous users don't need a user name or password.</li>
<li>Once logged out, an anonymous user cannot be recovered.</li>
<li>When the current user is anonymous, the following methods can be used to switch to a different user or convert the
anonymous user into a regular one:
<ul>
<li>signUp converts an anonymous user to a standard user with the given username and password.
Data associated with the anonymous user is retained.</li>
<li>logIn switches users without converting the anonymous user. Data associated with the anonymous user will be lost.</li>
<li>Service logIn (e.g. Facebook, Twitter) will attempt to convert the anonymous user into a standard user by linking it to the service.
If a user already exists that is linked to the service, it will instead switch to the existing user.</li>
<li>Service linking (e.g. Facebook, Twitter) will convert the anonymous user into a standard user by linking it to the service.</li>
</ul>
</ul>
*/
@interface MLAnonymousUtils : NSObject
/*! @name Creating an Anonymous User */
/*!
Creates an anonymous user.
@param block The block to execute when anonymous user creation is complete. The block should have the following argument signature: (MLUser *user, NSError *error)
*/
+ (void)logInWithBlock:(nullable MLUserResultBlock)block;
/*! @name Determining Whether a MLUseris Anonymous */
/*!
Whether the user is logged in anonymously.
@param user User to check for anonymity. The user must be logged in on this device.
@return True if the user is anonymous. False if the user is not the current user or is not anonymous.
*/
+ (BOOL)isLinkedWithUser:(nullable MLUser *)user;
@end
|
var dude = "Dude";
var dude2 = new {
Name = "Dude", Age = 30,
};
var dude3 = new {
Name = "Dude", Age = 30, Kids = new {
Name = "LittleDude"
}
};
var dude4 = new {
Name = "Dude", Age = 30, Kids = new[] {
"LittleDude"
}
};
var dude5 = new {
Name = "Dude", Age = 30, Kids = new[] {
new {
Name = "LittleDude"
}
}
};
Action y = () => { };
Func<int, float, bool> z = (a, b) => {
var z = new {
a, b
};
return(z == null);
};
|
#include "aniGlobal.h"
#include "palApi.h"
#include "csrInsideApi.h"
#include "smeInside.h"
#include "smsDebug.h"
#include "csrSupport.h"
#include "wlan_qct_tl.h"
#include "vos_diag_core_log.h"
#include "vos_diag_core_event.h"
#include "vos_nvitem.h"
#include "vos_memory.h"
#include "wlan_qct_wda.h"
#include "vos_utils.h"
#define <API key> 100
#define <API key> 100
#define DIRECT_SSID_LEN 7
/*
* Purpose of HIDDEN_TIMER
* When we remove hidden ssid from the profile i.e., forget the SSID via GUI
* that SSID shouldn't see in the profile for above requirement we used timer
* limit, logic is explained below timer value is initialized to current time
* when it receives corresponding probe response of hidden SSID
* (The probe request is received regularly till SSID in the profile.
* Once it is removed from profile probe request is not sent.) when we receive
* probe response for broadcast probe request, during update SSID with saved
* SSID we will diff current time with saved SSID time if it is greater than
* 1 min then we are not updating with old one.
*/
#define HIDDEN_TIMER (1*60*1000)
/* Must be less than 100, represent the percentage of new RSSI */
#define <API key> 80
#define <API key> 140
#define <API key> 120
#define <API key> 30
#define <API key> 20
#define <API key>(pMac) \
( (pMac)->scan.nBssLimit <= (csrLLCount(&(pMac)->scan.scanResultList)) )
/* Reset passive scan time as per ini parameter. */
/* No rest time/Idle time if no sessions are connected. */
/* split scan if any one of the following:
* - STA session is connected and the scan is not a P2P search
* - any P2P session is connected
* Do not split scans if no concurrent infra connections are
* active and if the scan is a BG scan triggered by LFR (OR)
* any scan if LFR is in the middle of a BG scan. Splitting
* the scan is delaying the time it takes for LFR to find
* candidates and resulting in disconnects.
*/
if(<API key>(pMac) &&
!<API key>(pMac))
{
<API key> = pMac->roam.configParam.<API key>;
}
else if(<API key>(pMac))
{
<API key> = pMac->roam.configParam.<API key>;
}
if ( (<API key>(pMac) &&
#ifdef FEATURE_WLAN_LFR
(<API key>(pMac) ||
((pScanCmd->u.scanCmd.reason != eCsrScanBgScan) &&
(pMac->roam.neighborRoamInfo[sessionId].neighborRoamState !=
<API key>))) &&
#endif
(pScanCmd->u.scanCmd.u.scanRequest.p2pSearch != 1)) ||
(<API key>(pMac)) )
{
tCsrScanRequest scanReq;
tANI_U8 numChn = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels;
tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo;
tANI_U8 channelToScan[<API key>];
tANI_BOOLEAN bMemAlloc = eANI_BOOLEAN_FALSE;
if (numChn == 0)
{
numChn = pMac->scan.baseChannels.numChannels;
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(numChn);
if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
{
smsLog( pMac, LOGE, FL(" Failed to get memory for channel list ") );
return eHAL_STATUS_FAILURE;
}
bMemAlloc = eANI_BOOLEAN_TRUE;
vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList,
pMac->scan.baseChannels.channelList, numChn);
status = eHAL_STATUS_SUCCESS;
if( !HAL_STATUS_SUCCESS( status ) )
{
vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList);
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL;
smsLog( pMac, LOGE, FL(" Failed to copy memory to channel list ") );
return eHAL_STATUS_FAILURE;
}
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = numChn;
}
//Whenever we get a scan request with multiple channels we break it up into 2 requests
//First request for first channel to scan and second request to scan remaining channels
if ( numChn > <API key>)
{
vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0);
pQueueScanCmd = csrGetCommandBuffer(pMac); //optimize this to use 2 command buffer only
if (!pQueueScanCmd)
{
if (bMemAlloc)
{
vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList);
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL;
}
smsLog( pMac, LOGE, FL(" Failed to get Queue command buffer") );
return eHAL_STATUS_FAILURE;
}
pQueueScanCmd->command = pScanCmd->command;
pQueueScanCmd->sessionId = pScanCmd->sessionId;
pQueueScanCmd->u.scanCmd.callback = pScanCmd->u.scanCmd.callback;
pQueueScanCmd->u.scanCmd.pContext = pScanCmd->u.scanCmd.pContext;
pQueueScanCmd->u.scanCmd.reason = pScanCmd->u.scanCmd.reason;
pQueueScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around
/* First copy all the parameters to local variable of scan request */
csrScanCopyRequest(pMac, &scanReq, &pScanCmd->u.scanCmd.u.scanRequest);
/* Now modify the elements of local var scan request required to be modified for split scan */
if(scanReq.ChannelInfo.ChannelList != NULL)
{
vos_mem_free(scanReq.ChannelInfo.ChannelList);
scanReq.ChannelInfo.ChannelList = NULL;
}
pChnInfo->numOfChannels = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels - <API key>;
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL(" &channelToScan %p pScanCmd(%p) pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList(%p)numChn(%d)"),
&channelToScan[0], pScanCmd,
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList, numChn);
vos_mem_copy(&channelToScan[0],
&pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[
<API key>],
pChnInfo->numOfChannels * sizeof(tANI_U8));
pChnInfo->ChannelList = &channelToScan[0];
scanReq.BSSType = eCSR_BSS_TYPE_ANY;
//Use concurrency values for min/maxChnTime.
//We know <API key>(pMac) returns TRUE here
<API key>(pMac, scanReq.scanType, &scanReq);
status = csrScanCopyRequest(pMac, &pQueueScanCmd->u.scanCmd.u.scanRequest, &scanReq);
if(!HAL_STATUS_SUCCESS(status))
{
if (bMemAlloc)
{
vos_mem_free(pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList);
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL;
}
if( scanReq.pIEField != NULL)
{
vos_mem_free(scanReq.pIEField);
scanReq.pIEField = NULL;
}
smsLog( pMac, LOGE, FL(" Failed to get copy csrScanRequest = %d"), status );
return eHAL_STATUS_FAILURE;
}
/* Clean the local scan variable */
scanReq.ChannelInfo.ChannelList = NULL;
scanReq.ChannelInfo.numOfChannels = 0;
csrScanFreeRequest(pMac, &scanReq);
/* setup the command to scan 2 channels */
pSendScanCmd = pScanCmd;
pSendScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = <API key>;
pSendScanCmd->u.scanCmd.u.scanRequest.BSSType = eCSR_BSS_TYPE_ANY;
//Use concurrency values for min/maxChnTime.
//We know <API key>(pMac) returns TRUE here
<API key>(pMac, pSendScanCmd->u.scanCmd.u.scanRequest.scanType, &pSendScanCmd->u.scanCmd.u.scanRequest);
pSendScanCmd->u.scanCmd.callback = NULL;
} else {
pSendScanCmd = pScanCmd;
pSendScanCmd->u.scanCmd.u.scanRequest.BSSType = eCSR_BSS_TYPE_ANY;
//Use concurrency values for min/maxChnTime.
//We know <API key>(pMac) returns TRUE here
<API key>(pMac, pSendScanCmd->u.scanCmd.u.scanRequest.scanType, &pSendScanCmd->u.scanCmd.u.scanRequest);
}
fNoCmdPending = csrLLIsListEmpty( &pMac->scan.scanCmdPendingList, LL_ACCESS_LOCK );
//Logic Below is as follows
// If the scanCmdPendingList is empty then we directly send that command
// to smeCommandQueue else we buffer it in our scanCmdPendingList Queue
if( fNoCmdPending )
{
if (pQueueScanCmd != NULL)
{
csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pQueueScanCmd->Link, LL_ACCESS_LOCK );
}
if (pSendScanCmd != NULL)
{
return csrQueueSmeCommand(pMac, pSendScanCmd, eANI_BOOLEAN_FALSE);
}
}
else
{
if (pSendScanCmd != NULL)
{
csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pSendScanCmd->Link, LL_ACCESS_LOCK );
}
if (pQueueScanCmd != NULL)
{
csrLLInsertTail( &pMac->scan.scanCmdPendingList, &pQueueScanCmd->Link, LL_ACCESS_LOCK );
}
}
}
else
{ //No concurrency case
smsLog( pMac, LOG2, FL("Queuing scan command (reason=%d, roamState=%d"
" numOfChannels=%d)"),
pScanCmd->u.scanCmd.reason,
pMac->roam.neighborRoamInfo[sessionId].neighborRoamState,
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels);
return csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
}
return ( status );
}
#endif
/**
* csrScan2GOnyRequest() - This function will update the scan request with
* only 2.4GHz valid channel list.
* @mac_ctx: Pointer to Global MAC structure
* @scan_cmd scan cmd
* @scan_req scan req
*
* This function will update the scan request with only 2.4GHz valid channel
* list.
*
* @Return: status of operation
*/
static eHalStatus csrScan2GOnyRequest(tpAniSirGlobal mac_ctx,
tSmeCmd *scan_cmd,
tCsrScanRequest *scan_req)
{
uint8_t idx, lst_sz = 0;
VOS_ASSERT(scan_cmd && scan_req);
/* To silence the KW tool null check is added */
if ((scan_cmd == NULL) || (scan_req == NULL)) {
smsLog(mac_ctx, LOGE, FL(" Scan Cmd or Scan Request is NULL "));
return <API key>;
}
if (<API key> != scan_req->requestType)
return eHAL_STATUS_SUCCESS;
smsLog(mac_ctx, LOG1,
FL("Scanning only 2G Channels during first scan"));
/* Contsruct valid Supported 2.4 GHz Channel List */
if (NULL == scan_req->ChannelInfo.ChannelList) {
scan_req->ChannelInfo.ChannelList =
vos_mem_malloc(NUM_2_4GHZ_CHANNELS);
if (NULL == scan_req->ChannelInfo.ChannelList) {
smsLog(mac_ctx, LOGE, FL("Memory allocation failed."));
return <API key>;
}
for (idx = 1; idx <= NUM_2_4GHZ_CHANNELS; idx++) {
if (<API key>(mac_ctx, idx)) {
scan_req->ChannelInfo.ChannelList[lst_sz] = idx;
lst_sz++;
}
}
}
else {
for (idx = 0; idx < scan_req->ChannelInfo.numOfChannels; idx++) {
if (scan_req->ChannelInfo.ChannelList[idx] <= <API key>
&& <API key>(mac_ctx,
scan_req->ChannelInfo.ChannelList[idx])) {
scan_req->ChannelInfo.ChannelList[lst_sz] =
scan_req->ChannelInfo.ChannelList[idx];
lst_sz++;
}
}
}
scan_req->ChannelInfo.numOfChannels = lst_sz;
return eHAL_STATUS_SUCCESS;
}
eHalStatus csrScanRequest(tpAniSirGlobal pMac, tANI_U16 sessionId,
tCsrScanRequest *pScanRequest, tANI_U32 *pScanRequestID,
<API key> callback, void *pContext)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tSmeCmd *pScanCmd = NULL;
eCsrConnectState ConnectState;
if(pScanRequest == NULL)
{
smsLog( pMac, LOGE, FL(" pScanRequest is NULL"));
VOS_ASSERT(0);
return status;
}
/* During group formation, the P2P client scans for GO with the specific SSID.
* There will be chances of GO switching to other channels because of scan or
* to STA channel in case of STA+GO MCC scenario. So to increase the possibility
* of client to find the GO, the dwell time of scan is increased to 100ms.
*/
if(pScanRequest->p2pSearch)
{
if ((pScanRequest->SSIDs.numOfSSIDs) && (NULL != pScanRequest->SSIDs.SSIDList))
{
//If the scan request is for specific SSId the length of SSID will be
//greater than 7 as SSID for p2p search contains "DIRECT-")
if(pScanRequest->SSIDs.SSIDList->SSID.length > DIRECT_SSID_LEN)
{
smsLog( pMac, LOG1, FL("P2P: Increasing the min and max Dwell"
" time to %d for specific SSID scan %.*s"),
<API key>,
pScanRequest->SSIDs.SSIDList->SSID.length,
pScanRequest->SSIDs.SSIDList->SSID.ssId);
pScanRequest->maxChnTime = <API key>;
pScanRequest->minChnTime = <API key>;
}
}
}
do
{
if(pMac->scan.fScanEnable)
{
pScanCmd = csrGetCommandBuffer(pMac);
if(pScanCmd)
{
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pScanCmd->command = eSmeCommandScan;
pScanCmd->sessionId = sessionId;
if (pScanCmd->sessionId >= <API key>)
smsLog( pMac, LOGE, FL("Invalid Sme Session ID = %d"), sessionId);
pScanCmd->u.scanCmd.callback = callback;
pScanCmd->u.scanCmd.pContext = pContext;
if(<API key> == pScanRequest->requestType)
{
pScanCmd->u.scanCmd.reason = eCsrScan11d1;
}
else if((<API key> == pScanRequest->requestType) ||
(<API key> == pScanRequest->requestType)
#ifdef <API key>
||(<API key> == pScanRequest->requestType)
#endif
)
{
pScanCmd->u.scanCmd.reason = eCsrScanUserRequest;
}
else if(<API key> == pScanRequest->requestType)
{
pScanCmd->u.scanCmd.reason = eCsrScanBgScan;
}
else if(<API key> == pScanRequest->requestType)
{
pScanCmd->u.scanCmd.reason = eCsrScanProbeBss;
}
else if(<API key> == pScanRequest->requestType)
{
pScanCmd->u.scanCmd.reason = eCsrScanP2PFindPeer;
}
else
{
pScanCmd->u.scanCmd.reason = eCsrScanIdleScan;
}
if(pScanRequest->minChnTime == 0 && pScanRequest->maxChnTime == 0)
{
//The caller doesn't set the time correctly. Set it here
<API key>(pMac, pScanRequest->scanType,
pScanRequest);
smsLog(pMac, LOG1, FL("Setting default min %d and max %d"
" ChnTime"), pScanRequest->minChnTime,
pScanRequest->maxChnTime);
}
#ifdef <API key>
if(pScanRequest->restTime == 0)
{
/* Need to set restTime/min_Ret_time/idle_time only
* if at least one session is connected
*/
if(<API key>(pMac))
{
pScanRequest->restTime = pMac->roam.configParam.nRestTimeConc;
pScanRequest->min_rest_time = pMac->roam.configParam.min_rest_time_conc;
pScanRequest->idle_time = pMac->roam.configParam.idle_time_conc;
if(pScanRequest->scanType == eSIR_ACTIVE_SCAN)
{
pScanRequest->maxChnTime = pMac->roam.configParam.<API key>;
pScanRequest->minChnTime = pMac->roam.configParam.<API key>;
}
else
{
pScanRequest->maxChnTime = pMac->roam.configParam.<API key>;
pScanRequest->minChnTime = pMac->roam.configParam.<API key>;
}
}
}
#endif
/* Increase dwell time in case P2P Search and Miracast is not present*/
if(pScanRequest->p2pSearch &&
pScanRequest->ChannelInfo.numOfChannels == P2P_SOCIAL_CHANNELS
&& (!(pMac->sme.miracast_value))) {
pScanRequest->maxChnTime += <API key>;
}
/*For Standalone wlan : channel time will remain the same.
For BTC with A2DP up: Channel time = Channel time * 2, if station is not already associated.
This has been done to provide a larger scan window for faster connection during btc.Else Scan is seen
to take a long time.
For BTC with A2DP up: Channel time will not be doubled, if station is already associated.
*/
status = <API key>(pMac,sessionId,&ConnectState);
if (HAL_STATUS_SUCCESS(status) &&
pMac->btc.fA2DPUp &&
(<API key> != ConnectState) &&
(<API key> != ConnectState))
{
pScanRequest->maxChnTime = pScanRequest->maxChnTime << 1;
pScanRequest->minChnTime = pScanRequest->minChnTime << 1;
smsLog( pMac, LOG1, FL("BTC A2DP up, doubling max and min"
" ChnTime (Max=%d Min=%d)"),
pScanRequest->maxChnTime,
pScanRequest->minChnTime);
}
pScanRequest->maxChnTimeBtc = pMac->roam.configParam.<API key>;
pScanRequest->minChnTimeBtc = pMac->roam.configParam.<API key>;
//Need to make the following atomic
pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around
if(pScanRequestID)
{
*pScanRequestID = pScanCmd->u.scanCmd.scanID;
}
// If it is the first scan request from HDD, CSR checks if it is for 11d.
// If it is not, CSR will save the scan request in the pending cmd queue
// & issue an 11d scan request to PE.
if (((false == pMac->first_scan_done)
&& (<API key> != pScanRequest->requestType))
#ifdef <API key>
&& (<API key> != pScanRequest->requestType)
#endif
&& (eANI_BOOLEAN_FALSE == pMac->scan.fEnableBypass11d)
)
{
tSmeCmd *p11dScanCmd;
tCsrScanRequest scanReq;
tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo;
vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0);
p11dScanCmd = csrGetCommandBuffer(pMac);
if (p11dScanCmd)
{
tANI_U32 numChn = pMac->scan.baseChannels.numChannels;
vos_mem_set(&p11dScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pChnInfo->ChannelList = vos_mem_malloc(numChn);
if ( NULL == pChnInfo->ChannelList )
{
smsLog(pMac, LOGE, FL("Failed to allocate memory"));
status = eHAL_STATUS_FAILURE;
break;
}
vos_mem_copy(pChnInfo->ChannelList,
pMac->scan.baseChannels.channelList,
numChn);
pChnInfo->numOfChannels = (tANI_U8)numChn;
p11dScanCmd->command = eSmeCommandScan;
p11dScanCmd->u.scanCmd.callback = pMac->scan.callback11dScanDone;
p11dScanCmd->u.scanCmd.pContext = NULL;
p11dScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++;
scanReq.BSSType = eCSR_BSS_TYPE_ANY;
if ( csrIs11dSupported(pMac) )
{
scanReq.scanType = eSIR_PASSIVE_SCAN;
scanReq.requestType = <API key>;
p11dScanCmd->u.scanCmd.reason = eCsrScan11d1;
scanReq.maxChnTime = pMac->roam.configParam.nPassiveMaxChnTime;
scanReq.minChnTime = pMac->roam.configParam.nPassiveMinChnTime;
}
else
{
scanReq.scanType = pScanRequest->scanType;
scanReq.requestType = <API key>;
p11dScanCmd->u.scanCmd.reason = eCsrScanIdleScan;
scanReq.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime;
scanReq.minChnTime = pMac->roam.configParam.nActiveMinChnTime;
scanReq.maxChnTimeBtc = pMac->roam.configParam.<API key>;
scanReq.minChnTimeBtc = pMac->roam.configParam.<API key>;
}
if (pMac->roam.configParam.nInitialDwellTime)
{
scanReq.maxChnTime =
pMac->roam.configParam.nInitialDwellTime;
smsLog(pMac, LOG1, FL("11d scan, updating"
"dwell time for first scan %u"),
scanReq.maxChnTime);
}
status = csrScanCopyRequest(pMac, &p11dScanCmd->u.scanCmd.u.scanRequest, &scanReq);
//Free the channel list
vos_mem_free(pChnInfo->ChannelList);
pChnInfo->ChannelList = NULL;
if (HAL_STATUS_SUCCESS(status))
{
pMac->scan.scanProfile.numOfChannels =
p11dScanCmd->u.scanCmd.u.scanRequest.
ChannelInfo.numOfChannels;
//Start process the command
#ifdef <API key>
if (!pMac->fScanOffload)
status = csrQueueScanRequest(pMac, sessionId,
p11dScanCmd);
else
status = csrQueueSmeCommand(pMac, p11dScanCmd,
eANI_BOOLEAN_FALSE);
#else
status = csrQueueSmeCommand(pMac, p11dScanCmd, eANI_BOOLEAN_FALSE);
#endif
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" Failed to send message"
" status = %d"), status);
break;
}
}
else
{
smsLog(pMac, LOGE, FL("csrScanCopyRequest failed"));
break;
}
}
else
{
//error
smsLog( pMac, LOGE, FL("p11dScanCmd failed") );
break;
}
}
//Scan only 2G Channels if set in ini file
//This is mainly to reduce the First Scan duration
//Once we turn on Wifi
if(pMac->scan.<API key>
&& false == pMac->first_scan_done) {
status = csrScan2GOnyRequest(pMac, pScanCmd, pScanRequest);
if (!HAL_STATUS_SUCCESS(status)) {
smsLog(pMac, LOGE, FL("csrScan2GOnyRequest failed."));
break;
}
}
pMac->first_scan_done = true;
if (pMac->roam.configParam.nInitialDwellTime)
{
pScanRequest->maxChnTime =
pMac->roam.configParam.nInitialDwellTime;
pMac->roam.configParam.nInitialDwellTime = 0;
smsLog(pMac, LOG1,
FL("updating dwell time for first scan %u"),
pScanRequest->maxChnTime);
}
status = csrScanCopyRequest(pMac, &pScanCmd->u.scanCmd.u.scanRequest, pScanRequest);
/*
* Reset the variable after the first scan is queued after
* loading the driver. The purpose of this parameter is that
* DFS channels are skipped during the first scan after loading
* the driver. The above API builds the target scan request in
* which this variable is used.
*/
pMac->roam.configParam.<API key> = 0;
if(HAL_STATUS_SUCCESS(status))
{
tCsrScanRequest *pTempScanReq =
&pScanCmd->u.scanCmd.u.scanRequest;
pMac->scan.scanProfile.numOfChannels =
pTempScanReq->ChannelInfo.numOfChannels;
smsLog(pMac, LOG1, FL(" SId=%d scanId=%d"
" Scan reason=%u numSSIDs=%d"
" numChan=%d P2P search=%d minCT=%d maxCT=%d"
" minCBtc=%d maxCBtx=%d uIEFieldLen=%d"),
sessionId, pScanCmd->u.scanCmd.scanID,
pScanCmd->u.scanCmd.reason,
pTempScanReq->SSIDs.numOfSSIDs,
pTempScanReq->ChannelInfo.numOfChannels,
pTempScanReq->p2pSearch,
pTempScanReq->minChnTime,
pTempScanReq->maxChnTime,
pTempScanReq->minChnTimeBtc,
pTempScanReq->maxChnTimeBtc,
pTempScanReq->uIEFieldLen);
//Start process the command
#ifdef <API key>
if (!pMac->fScanOffload)
status = csrQueueScanRequest(pMac, sessionId, pScanCmd);
else
status = csrQueueSmeCommand(pMac, pScanCmd,
eANI_BOOLEAN_FALSE);
#else
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
#endif
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
}
else
{
smsLog( pMac, LOGE, FL(" fail to copy request status = %d"), status );
break;
}
}
else
{
smsLog( pMac, LOGE, FL(" pScanCmd is NULL"));
break;
}
}
else
{
smsLog( pMac, LOGE, FL("SId: %d Scanning not enabled"
" Scan type=%u, numOfSSIDs=%d P2P search=%d"),
sessionId, pScanRequest->requestType,
pScanRequest->SSIDs.numOfSSIDs,
pScanRequest->p2pSearch );
}
} while(0);
if(!HAL_STATUS_SUCCESS(status) && pScanCmd)
{
if( eCsrScanIdleScan == pScanCmd->u.scanCmd.reason )
{
//Set the flag back for restarting idle scan
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
}
smsLog( pMac, LOGE, FL(" SId: %d Failed with status=%d"
" Scan reason=%u numOfSSIDs=%d"
" P2P search=%d scanId=%d"),
sessionId, status, pScanCmd->u.scanCmd.reason,
pScanRequest->SSIDs.numOfSSIDs, pScanRequest->p2pSearch,
pScanCmd->u.scanCmd.scanID );
<API key>(pMac, pScanCmd);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pScanCmd;
if(pMac->scan.fScanEnable)
{
pScanCmd = csrGetCommandBuffer(pMac);
if(pScanCmd)
{
pScanCmd->command = eSmeCommandScan;
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pScanCmd->u.scanCmd.callback = NULL;
pScanCmd->u.scanCmd.pContext = NULL;
pScanCmd->u.scanCmd.reason = eCsrScanGetResult;
//Need to make the following atomic
pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID; //let it wrap around
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
<API key>(pMac, pScanCmd);
}
}
else
{
//log error
smsLog(pMac, LOGE, FL("can not obtain a common buffer"));
status = <API key>;
}
}
return (status);
}
#ifdef <API key>
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId,
<API key> callback, void *pContext)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pScanCmd;
if (pMac->scan.fScanEnable)
{
pScanCmd = csrGetCommandBuffer(pMac);
if (pScanCmd)
{
pScanCmd->command = eSmeCommandScan;
pScanCmd->sessionId = sessionId;
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pScanCmd->u.scanCmd.callback = callback;
pScanCmd->u.scanCmd.pContext = pContext;
pScanCmd->u.scanCmd.reason = <API key>;
//Need to make the following atomic
pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID; //let it wrap around
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_TRUE);
if ( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d\n"), status );
<API key>(pMac, pScanCmd);
}
}
else
{
//log error
smsLog(pMac, LOGE, FL("can not obtain a common buffer\n"));
status = <API key>;
}
}
return (status);
}
#endif //<API key>
eHalStatus csrScanAllChannels(tpAniSirGlobal pMac, eCsrRequestType reqType)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U32 scanId;
tCsrScanRequest scanReq;
vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0);
scanReq.BSSType = eCSR_BSS_TYPE_ANY;
scanReq.scanType = eSIR_ACTIVE_SCAN;
scanReq.requestType = reqType;
scanReq.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime;
scanReq.minChnTime = pMac->roam.configParam.nActiveMinChnTime;
scanReq.maxChnTimeBtc = pMac->roam.configParam.<API key>;
scanReq.minChnTimeBtc = pMac->roam.configParam.<API key>;
//Scan with invalid sessionId.
//This results in SME using the first available session to scan.
status = csrScanRequest(pMac, <API key>, &scanReq,
&scanId, NULL, NULL);
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId, eCsrRoamReason reason)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanResultHandle hBSSList = NULL;
<API key> *pScanFilter = NULL;
tANI_U32 roamId = 0;
tCsrRoamProfile *pProfile = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
do
{
smsLog(pMac, LOG1, " <API key> called");
if(pSession->fCancelRoaming)
{
smsLog(pMac, LOGW, " lost link roaming is canceled");
<API key>(pMac);
status = eHAL_STATUS_SUCCESS;
break;
}
//Here is the profile we need to connect to
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter)
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
break;
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
if(NULL == pSession->pCurRoamProfile)
{
pScanFilter->EncryptionType.numEntries = 1;
pScanFilter->EncryptionType.encryptionType[0] = <API key>;
}
else
{
//We have to make a copy of pCurRoamProfile because it will be free inside csrRoamIssueConnect
pProfile = vos_mem_malloc(sizeof(tCsrRoamProfile));
if ( NULL == pProfile )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
break;
vos_mem_set(pProfile, sizeof(tCsrRoamProfile), 0);
status = csrRoamCopyProfile(pMac, pProfile, pSession->pCurRoamProfile);
if(!HAL_STATUS_SUCCESS(status))
break;
status = <API key>(pMac, pProfile, pScanFilter);
}//We have a profile
roamId = GET_NEXT_ROAM_ID(&pMac->roam);
if(HAL_STATUS_SUCCESS(status))
{
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(HAL_STATUS_SUCCESS(status))
{
if(eCsrLostLink1 == reason)
{
//we want to put the last connected BSS to the very beginning, if possible
<API key>(pMac, &pSession->connectedProfile.bssid, hBSSList);
}
status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList, reason,
roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE);
if(!HAL_STATUS_SUCCESS(status))
{
csrScanResultPurge(pMac, hBSSList);
}
}//Have scan result
}
}while(0);
if(pScanFilter)
{
//we need to free memory for filter if profile exists
csrFreeScanFilter(pMac, pScanFilter);
vos_mem_free(pScanFilter);
}
if(NULL != pProfile)
{
csrReleaseProfile(pMac, pProfile);
vos_mem_free(pProfile);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U8 sessionId,
void *pContext, void *callback,
tANI_U32 scanID)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pScanCmd;
if(pMac->scan.fScanEnable)
{
pScanCmd = csrGetCommandBuffer(pMac);
if(pScanCmd)
{
pScanCmd->command = eSmeCommandScan;
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pScanCmd->u.scanCmd.callback = callback;
pScanCmd->u.scanCmd.pContext = pContext;
pScanCmd->u.scanCmd.reason = <API key>;
if (callback)
{
//use same scanID as maintained in pAdapter
pScanCmd->u.scanCmd.scanID = scanID;
}
else
{
//Need to make the following atomic
pScanCmd->u.scanCmd.scanID =
pMac->scan.nextScanID++; //let it wrap around
}
pScanCmd->sessionId = sessionId;
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
<API key>(pMac, pScanCmd);
}
}
else
{
//log error
smsLog(pMac, LOGE, FL("can not obtain a common buffer"));
status = <API key>;
}
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, "Lost link scan 1 failed");
if(pSession->fCancelRoaming)
{
<API key>(pMac);
}
else if(pSession->pCurRoamProfile)
{
//We fail lostlink1 but there may be other BSS in the cached result fit the profile. Give it a try first
if(pSession->pCurRoamProfile->SSIDs.numOfSSIDs == 0 ||
pSession->pCurRoamProfile->SSIDs.numOfSSIDs > 1)
{
/* Try lost link scan2 */
status = <API key>(pMac, sessionId);
}
else if(!pSession->pCurRoamProfile->ChannelInfo.ChannelList ||
pSession->pCurRoamProfile->ChannelInfo.ChannelList[0] == 0)
{
/* Go straight to lost link scan3 */
status = <API key>(pMac, sessionId);
}
else
{
/* We are done with lost link */
if(<API key>(pMac, sessionId, eANI_BOOLEAN_FALSE, <API key>))
{
<API key>(pMac);
}
status = eHAL_STATUS_SUCCESS;
}
}
else
{
status = <API key>(pMac, sessionId);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, "Lost link scan 2 failed");
if(pSession->fCancelRoaming)
{
<API key>(pMac);
}
else if(!pSession->pCurRoamProfile || !pSession->pCurRoamProfile->ChannelInfo.ChannelList ||
pSession->pCurRoamProfile->ChannelInfo.ChannelList[0] == 0)
{
/* Try lost link scan3 */
status = <API key>(pMac, sessionId);
}
else
{
/* We are done with lost link */
if(<API key>(pMac, sessionId, eANI_BOOLEAN_FALSE, <API key>))
{
<API key>(pMac);
}
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
smsLog(pMac, LOGW, "Lost link scan 3 failed");
if(eANI_BOOLEAN_TRUE == <API key>(pMac, sessionId, eANI_BOOLEAN_FALSE, <API key>))
{
/* We are done with lost link */
<API key>(pMac);
}
return (status);
}
//Lostlink1 scan is to actively scan the last connected profile's SSID on all matched BSS channels.
//If no roam profile (it should not), it is like lostlinkscan3
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pCommand = NULL;
tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
<API key> *pScanFilter = NULL;
tScanResultHandle hBSSList = NULL;
tCsrScanResultInfo *pScanResult = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, FL(" called"));
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->sessionId = (tANI_U8)sessionId;
pCommand->u.scanCmd.reason = eCsrScanLostLink1;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime;
pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime;
pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN;
if(pSession->connectedProfile.SSID.length)
{
pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList = vos_mem_malloc(sizeof(tCsrSSIDInfo));
if ( NULL == pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 1;
vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID,
&pSession->connectedProfile.SSID, sizeof(tSirMacSSid));
}
else
{
pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 0;
}
if(pSession->pCurRoamProfile)
{
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
status = <API key>(pMac, pSession->pCurRoamProfile, pScanFilter);
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
//Don't change variable status here because whether we can get result or not, the command goes to PE.
//The status is also used to indicate whether the command is queued. Not success meaning not queue
if(HAL_STATUS_SUCCESS((csrScanGetResult(pMac, pScanFilter, &hBSSList))) && hBSSList)
{
tANI_U8 i, nChn = 0;
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList =
vos_mem_malloc(<API key>);
if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
while(((pScanResult = <API key>(pMac, hBSSList)) != NULL) &&
nChn < <API key>)
{
for(i = 0; i < nChn; i++)
{
if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] ==
pScanResult->BssDescriptor.channelId)
{
break;
}
}
if(i == nChn)
{
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pScanResult->BssDescriptor.channelId;
}
}
//Include the last connected BSS' channel
if(<API key>(pMac, pSession->connectedProfile.operationChannel))
{
for(i = 0; i < nChn; i++)
{
if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] ==
pSession->connectedProfile.operationChannel)
{
break;
}
}
if(i == nChn)
{
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pSession->connectedProfile.operationChannel;
}
}
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = nChn;
}
else
{
if(<API key>(pMac, pSession->connectedProfile.operationChannel))
{
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(1);
if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
//just try the last connected channel
if(HAL_STATUS_SUCCESS(status))
{
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[0] = pSession->connectedProfile.operationChannel;
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 1;
}
else
{
break;
}
}
}
}
vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid));
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
} while( 0 );
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGW, " <API key> failed with status %d", status);
if(pCommand)
{
<API key>(pMac, pCommand);
}
status = <API key>( pMac, sessionId );
}
if(pScanFilter)
{
csrFreeScanFilter(pMac, pScanFilter);
vos_mem_free(pScanFilter);
}
if(hBSSList)
{
csrScanResultPurge(pMac, hBSSList);
}
return( status );
}
//Lostlink2 scan is to actively scan the all SSIDs of the last roaming profile's on all matched BSS channels.
//Since MAC doesn't support multiple SSID, we scan all SSIDs and filter them afterwards
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
<API key> *pScanFilter = NULL;
tScanResultHandle hBSSList = NULL;
tCsrScanResultInfo *pScanResult = NULL;
tSmeCmd *pCommand = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, FL(" called"));
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->sessionId = (tANI_U8)sessionId;
pCommand->u.scanCmd.reason = eCsrScanLostLink2;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime;
pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime;
pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN;
if(pSession->pCurRoamProfile)
{
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
{
break;
}
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
status = <API key>(pMac, pSession->pCurRoamProfile, pScanFilter);
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
if(hBSSList)
{
tANI_U8 i, nChn = 0;
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList =
vos_mem_malloc(<API key>);
if ( NULL == pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
{
break;
}
while(((pScanResult = <API key>(pMac, hBSSList)) != NULL) &&
nChn < <API key>)
{
for(i = 0; i < nChn; i++)
{
if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] ==
pScanResult->BssDescriptor.channelId)
{
break;
}
}
if(i == nChn)
{
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[nChn++] = pScanResult->BssDescriptor.channelId;
}
}
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = nChn;
}
}
vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid));
//Put to the head in pending queue
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_TRUE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
} while( 0 );
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGW, " <API key> failed with status %d", status);
if(pCommand)
{
<API key>(pMac, pCommand);
}
status = <API key>( pMac, sessionId );
}
if(pScanFilter)
{
csrFreeScanFilter(pMac, pScanFilter);
vos_mem_free(pScanFilter);
}
if(hBSSList)
{
csrScanResultPurge(pMac, hBSSList);
}
return( status );
}
//To actively scan all valid channels
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pCommand;
tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
smsLog(pMac, LOGW, FL(" called"));
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->sessionId = (tANI_U8)sessionId;
pCommand->u.scanCmd.reason = eCsrScanLostLink3;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
pCommand->u.scanCmd.u.scanRequest.maxChnTime = pMac->roam.configParam.nActiveMaxChnTime;
pCommand->u.scanCmd.u.scanRequest.minChnTime = pMac->roam.configParam.nActiveMinChnTime;
pCommand->u.scanCmd.u.scanRequest.maxChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.minChnTimeBtc = pMac->roam.configParam.<API key>;
pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN;
vos_mem_copy(&pCommand->u.scanCmd.u.scanRequest.bssid, bAddr, sizeof(tCsrBssid));
//Put to the head of pending queue
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_TRUE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
} while( 0 );
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGW, " <API key> failed with status %d", status);
if(<API key>(pMac, sessionId, eANI_BOOLEAN_FALSE, <API key>))
{
<API key>(pMac);
}
if(pCommand)
{
<API key>(pMac, pCommand);
}
}
return( status );
}
eHalStatus <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanResultHandle hBSSList = <API key>;
<API key> *pScanFilter = NULL;
tCsrRoamProfile *pProfile = pCommand->u.scanCmd.pToRoamProfile;
tANI_U32 sessionId = pCommand->sessionId;
do
{
#ifdef <API key>
/* If this scan is for LFR */
if (pMac->roam.neighborRoamInfo[sessionId].uOsRequestedHandoff) {
/* Notify LFR state m/c */
if (eHAL_STATUS_SUCCESS != <API key>(pMac,
sessionId,
eHAL_STATUS_SUCCESS)) {
<API key>(pMac, sessionId);
}
status = eHAL_STATUS_SUCCESS;
break;
}
#endif
//If there is roam command waiting, ignore this roam because the newer roam command is the one to execute
if(<API key>(pMac, sessionId))
{
smsLog(pMac, LOGW, FL(" aborts because roam command waiting"));
break;
}
if(pProfile == NULL)
break;
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
break;
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
status = <API key>(pMac, pProfile, pScanFilter);
if(!HAL_STATUS_SUCCESS(status))
break;
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(!HAL_STATUS_SUCCESS(status))
break;
if (pMac->roam.roamSession[sessionId].connectState ==
<API key>) {
smsLog(pMac, LOGE, FL("upper layer issued disconnetion"));
status = eHAL_STATUS_FAILURE;
break;
}
status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList, eCsrHddIssued,
pCommand->u.scanCmd.roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE);
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
}while(0);
if(!HAL_STATUS_SUCCESS(status))
{
if(<API key> != hBSSList)
{
csrScanResultPurge(pMac, hBSSList);
}
//We haven't done anything to this profile
csrRoamCallCallback(pMac, sessionId, NULL, pCommand->u.scanCmd.roamId,
<API key>, <API key>);
//In case we have nothing else to do, restart idle scan
if(<API key>(pMac, sessionId) && !<API key>(pMac))
{
status = <API key>(pMac);
}
}
if (pScanFilter)
{
csrFreeScanFilter(pMac, pScanFilter);
vos_mem_free(pScanFilter);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U32 sessionId = pCommand->sessionId;
tCsrRoamProfile *pProfile = pCommand->u.scanCmd.pToRoamProfile;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if (!pSession) {
smsLog(pMac, LOGE, FL("Session %d not found"), sessionId);
return eHAL_STATUS_FAILURE;
}
#ifdef <API key>
/* If this scan is for LFR */
if (pMac->roam.neighborRoamInfo[sessionId].uOsRequestedHandoff) {
/* Notify LFR state m/c */
if (eHAL_STATUS_SUCCESS != <API key>(pMac,
sessionId,
eHAL_STATUS_FAILURE)) {
<API key>(pMac, sessionId);
}
return eHAL_STATUS_SUCCESS;
}
#endif
#if defined(WLAN_DEBUG)
if(pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs == 1)
{
char str[36];
vos_mem_copy(str,
pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.ssId,
pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.length);
str[pCommand->u.scanCmd.u.scanRequest.SSIDs.SSIDList[0].SSID.length] = 0;
smsLog(pMac, LOGW, FL(" SSID = %s"), str);
}
#endif
//Check whether it is for start ibss. No need to do anything if it is a JOIN request
if(pProfile && CSR_IS_START_IBSS(pProfile))
{
status = csrRoamIssueConnect(pMac, sessionId, pProfile, NULL, eCsrHddIssued,
pCommand->u.scanCmd.roamId, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE);
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL("failed to issue startIBSS command with status = 0x%08X"), status);
csrRoamCallCallback(pMac, sessionId, NULL, pCommand->u.scanCmd.roamId, eCSR_ROAM_FAILED, <API key>);
}
}
else
{
eCsrRoamResult roamResult = <API key>;
if(<API key>(pMac, sessionId) &&
!<API key>(pMac, sessionId))
{
status = <API key>(pMac);
}
if((NULL == pProfile) || !csrIsBssTypeIBSS(pProfile->BSSType))
{
//Only indicate assoc_completion if we indicate assoc_start.
if(pSession->bRefAssocStartCnt > 0)
{
tCsrRoamInfo *pRoamInfo = NULL, roamInfo;
vos_mem_set(&roamInfo, sizeof(tCsrRoamInfo), 0);
pRoamInfo = &roamInfo;
if(pCommand->u.roamCmd.pRoamBssEntry)
{
tCsrScanResult *pScanResult =
GET_BASE_ADDR(pCommand->u.roamCmd.pRoamBssEntry,
tCsrScanResult, Link);
roamInfo.pBssDesc = &pScanResult->Result.BssDescriptor;
}
roamInfo.statusCode = pSession->joinFailStatusCode.statusCode;
roamInfo.reasonCode = pSession->joinFailStatusCode.reasonCode;
pSession->bRefAssocStartCnt
csrRoamCallCallback(pMac, sessionId, pRoamInfo,
pCommand->u.scanCmd.roamId,
<API key>,
<API key>);
}
else
{
csrRoamCallCallback(pMac, sessionId, NULL,
pCommand->u.scanCmd.roamId,
<API key>,
<API key>);
}
}
else
{
roamResult = <API key>;
}
csrRoamCompletion(pMac, sessionId, NULL, pCommand, roamResult, eANI_BOOLEAN_FALSE);
}
return (status);
}
//After scan for cap changes, issue a roaming command to either reconnect to the AP or pick another one to connect
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanResultHandle hBSSList = NULL;
<API key> *pScanFilter = NULL;
tANI_U32 roamId = 0;
tCsrRoamProfile *pProfile = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
do
{
//Here is the profile we need to connect to
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
break;
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
if (NULL == pSession) break;
if (NULL == pSession->pCurRoamProfile)
{
pScanFilter->EncryptionType.numEntries = 1;
pScanFilter->EncryptionType.encryptionType[0] = <API key>;
}
else
{
//We have to make a copy of pCurRoamProfile because it will be free inside csrRoamIssueConnect
pProfile = vos_mem_malloc(sizeof(tCsrRoamProfile));
if ( NULL == pProfile )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
break;
status = csrRoamCopyProfile(pMac, pProfile, pSession->pCurRoamProfile);
if(!HAL_STATUS_SUCCESS(status))
break;
status = <API key>(pMac, pProfile, pScanFilter);
}//We have a profile
roamId = GET_NEXT_ROAM_ID(&pMac->roam);
if(HAL_STATUS_SUCCESS(status))
{
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(HAL_STATUS_SUCCESS(status))
{
//we want to put the last connected BSS to the very beginning, if possible
<API key>(pMac, &pSession->connectedProfile.bssid, hBSSList);
status = csrRoamIssueConnect(pMac, sessionId, pProfile, hBSSList,
eCsrCapsChange, 0, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE);
if(!HAL_STATUS_SUCCESS(status))
{
csrScanResultPurge(pMac, hBSSList);
}
}//Have scan result
else
{
smsLog(pMac, LOGW, FL("cannot find matching BSS of "
MAC_ADDRESS_STR),
MAC_ADDR_ARRAY(pSession->connectedProfile.bssid));
//Disconnect
<API key>(pMac, sessionId, <API key>);
}
}
}while(0);
if(pScanFilter)
{
csrFreeScanFilter(pMac, pScanFilter);
vos_mem_free(pScanFilter);
}
if(NULL != pProfile)
{
csrReleaseProfile(pMac, pProfile);
vos_mem_free(pProfile);
}
return (status);
}
eHalStatus csrScanResultPurge(tpAniSirGlobal pMac, tScanResultHandle hScanList)
{
eHalStatus status = <API key>;
tScanResultList *pScanList = (tScanResultList *)hScanList;
if(pScanList)
{
status = <API key>(pMac, &pScanList->List);
csrLLClose(&pScanList->List);
vos_mem_free(pScanList);
}
return (status);
}
/**
* <API key>() - Artificially increase/decrease RSSI
* @mac_ctx: Global MAC Context pointer.
* @rssi: Actual RSSI of the AP.
* @channel_id: Channel on which the AP is parked.
* @bssid: BSSID of the AP to connect to.
*
* This routine will apply the boost and penalty parameters
* if the channel_id is of 5G band and it will also apply
* the preferred bssid score if there is a match between
* the bssid and the global preferred bssid list.
*
* Return: The modified RSSI Value
*/
static int <API key>(tpAniSirGlobal mac_ctx, int rssi,
uint8_t channel_id, tCsrBssid *bssid)
{
int modified_rssi;
int boost_factor;
int penalty_factor;
int i;
struct roam_ext_params *roam_params;
tCsrBssid local_bssid;
modified_rssi = rssi;
vos_mem_set(&local_bssid, 0, VOS_MAC_ADDR_SIZE);
if (bssid)
vos_mem_copy(&local_bssid, bssid, VOS_MAC_ADDR_SIZE);
roam_params = &mac_ctx->roam.configParam.roam_params;
/*
* If the 5G pref feature is enabled, apply the roaming
* parameters to boost or penalize the rssi.
* Boost Factor = boost_factor * (Actual RSSI - boost Threshold)
* Penalty Factor = penalty factor * (penalty threshold - Actual RSSI)
*/
if (<API key>(mac_ctx) &&
CSR_IS_CHANNEL_5GHZ(channel_id)) {
if (rssi > roam_params-><API key>) {
/* Check and boost the threshold*/
boost_factor = roam_params->raise_factor_5g *
(rssi - roam_params-><API key>);
/* Check and penalize the threshold */
modified_rssi += CSR_MIN(roam_params->max_raise_rssi_5g,
boost_factor);
} else if(rssi < roam_params->drop_rssi_thresh_5g) {
penalty_factor = roam_params->drop_factor_5g *
(roam_params->drop_rssi_thresh_5g - rssi);
modified_rssi -= CSR_MAX(roam_params->max_drop_rssi_5g,
penalty_factor);
}
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("5G BSSID("MAC_ADDRESS_STR") AR:%d, MR:%d, ch=%d"),
MAC_ADDR_ARRAY(local_bssid), rssi,
modified_rssi, channel_id);
}
/*
* Check if there are preferred bssid and then apply the
* preferred score
*/
if (roam_params->num_bssid_favored) {
for (i=0; i<roam_params->num_bssid_favored; i++) {
if (!<API key>(mac_ctx,
&roam_params->bssid_favored[i], bssid))
continue;
modified_rssi += roam_params-><API key>[i];
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("Pref: ("MAC_ADDRESS_STR") AR:%d, MR:%d, ch=%d"),
MAC_ADDR_ARRAY(local_bssid), rssi, modified_rssi,
channel_id);
}
}
return modified_rssi;
}
/**
* <API key>() - Get BSS Preference Value
* @pMac: Global MAC Context pointer.
* @rssi: Actual RSSI of the AP.
* @bssid: BSSID of the AP to connect to.
* @channel_id: Channel on which the AP is parked.
*
*
* This routine helps in determining the preference value
* of a particular BSS in the scan result which is further
* used in the sorting logic of the final candidate AP's.
*
* Return: The preference Value for a BSS.
*/
static tANI_U32 <API key>(tpAniSirGlobal pMac, int rssi,
tCsrBssid *bssid, int channel_id)
{
tANI_U32 ret = 0;
int i, modified_rssi;
/*
* The RSSI does not get modified in case the 5G
* preference or preferred BSSID is not applicable
*/
modified_rssi = <API key>(pMac, rssi, channel_id, bssid);
i = CSR_NUM_RSSI_CAT - 1;
while(i >= 0) {
if(modified_rssi >= pMac->roam.configParam.RSSICat[i]) {
ret = pMac->roam.configParam.BssPreferValue[i];
break;
}
i
};
return (ret);
}
//Return a CapValue base on the capabilities of a BSS
static tANI_U32 csrGetBssCapValue(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes)
{
tANI_U32 ret = <API key>;
#if defined (<API key>) || defined (FEATURE_WLAN_ESE) || defined(FEATURE_WLAN_LFR)
if(<API key>(pMac) || <API key>(pMac))
{
if((pBssDesc) && CSR_IS_CHANNEL_5GHZ(pBssDesc->channelId))
{
ret += <API key>;
}
}
#endif
/* if strict select 5GHz is non-zero then ignore the capability checking */
if (pIes && !<API key>(pMac))
{
//We only care about 11N capability
if (pIes->VHTCaps.present)
ret += <API key>;
else if (pIes->HTCaps.present)
ret += <API key>;
if(CSR_IS_QOS_BSS(pIes))
{
ret += <API key>;
//Give advantage to UAPSD
if(CSR_IS_UAPSD_BSS(pIes))
{
ret += <API key>;
}
}
}
return (ret);
}
/**
* csr_is_better_rssi() - Is bss1 better than bss2
* @mac_ctx: Global MAC Context pointer.
* @bss1: Pointer to the first BSS.
* @bss2: Pointer to the second BSS.
*
*
* This routine helps in determining the preference value
* of a particular BSS in the scan result which is further
* used in the sorting logic of the final candidate AP's.
*
* Return: true, if bss1 is better than bss2
* false, if bss2 is better than bss1.
*/
static bool csr_is_better_rssi(tpAniSirGlobal mac_ctx,
tCsrScanResult *bss1, tCsrScanResult *bss2)
{
bool ret;
int rssi1, rssi2;
rssi1 = bss1->Result.BssDescriptor.rssi;
rssi2 = bss2->Result.BssDescriptor.rssi;
/*
* Apply the boost and penlty logic and check
* which is the best RSSI
*/
rssi1 = <API key>(mac_ctx, rssi1,
bss1->Result.BssDescriptor.channelId,
&bss1->Result.BssDescriptor.bssId);
rssi2 = <API key>(mac_ctx, rssi2,
bss2->Result.BssDescriptor.channelId,
&bss2->Result.BssDescriptor.bssId);
if (CSR_IS_BETTER_RSSI(rssi1, rssi2))
ret = true;
else
ret = false;
return ret;
}
/* To check whether pBss1 is better than pBss2 */
static tANI_BOOLEAN csrIsBetterBss(tpAniSirGlobal mac_ctx,
tCsrScanResult *pBss1, tCsrScanResult *pBss2)
{
tANI_BOOLEAN ret;
if(<API key>(pBss1->preferValue, pBss2->preferValue))
ret = eANI_BOOLEAN_TRUE;
else if(<API key>
(pBss1->preferValue, pBss2->preferValue)) {
if(<API key>(pBss1->capValue, pBss2->capValue))
ret = eANI_BOOLEAN_TRUE;
else if (<API key>
(pBss1->capValue, pBss2->capValue)) {
if (csr_is_better_rssi(mac_ctx, pBss1, pBss2))
ret = eANI_BOOLEAN_TRUE;
else
ret = eANI_BOOLEAN_FALSE;
}
else
ret = eANI_BOOLEAN_FALSE;
}
else
ret = eANI_BOOLEAN_FALSE;
return (ret);
}
#ifdef FEATURE_WLAN_LFR
//Add the channel to the occupiedChannels array
static void <API key>(
tpAniSirGlobal pMac,
tCsrScanResult *pResult,
tANI_U8 sessionId,
tCsrChannel *pOccupiedChannels,
tDot11fBeaconIEs *pIes)
{
eHalStatus status;
tANI_U8 channel;
tANI_U8 numOccupiedChannels = pOccupiedChannels->numChannels;
tANI_U8 *<API key> = pOccupiedChannels->channelList;
channel = pResult->Result.BssDescriptor.channelId;
if (!<API key>(<API key>, numOccupiedChannels, channel)
&& <API key>(pMac, sessionId, pResult, pIes))
{
status = <API key>(<API key>, numOccupiedChannels, channel);
if(HAL_STATUS_SUCCESS(status))
{
pOccupiedChannels->numChannels++;
smsLog(pMac, LOG2, FL("Added channel %d to the list (count=%d)"),
channel, pOccupiedChannels->numChannels);
if (pOccupiedChannels->numChannels > <API key>)
pOccupiedChannels->numChannels = <API key>;
}
}
}
#endif
//Put the BSS into the scan result list
//pIes can not be NULL
static void csrScanAddResult(tpAniSirGlobal pMac, tCsrScanResult *pResult,
tDot11fBeaconIEs *pIes, tANI_U32 sessionId)
{
#ifdef FEATURE_WLAN_LFR
<API key> pNeighborRoamInfo =
&pMac->roam.neighborRoamInfo[sessionId];
#endif
tCsrBssid *bssid = &pResult->Result.BssDescriptor.bssId;
uint8_t channel_id = pResult->Result.BssDescriptor.channelId;
pResult->preferValue = <API key>(pMac,
(int)pResult->Result.BssDescriptor.rssi, bssid, channel_id);
pResult->capValue =
csrGetBssCapValue(pMac, &pResult->Result.BssDescriptor, pIes);
csrLLInsertTail( &pMac->scan.scanResultList, &pResult->Link, LL_ACCESS_LOCK );
#ifdef FEATURE_WLAN_LFR
if(0 == pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels)
{
/* Build the occupied channel list, only if "<API key>" is
NOT set in the cfg.ini file */
<API key>(pMac, pResult, sessionId,
&pMac->scan.occupiedChannels[sessionId],
pIes);
}
#endif
}
eHalStatus csrScanGetResult(tpAniSirGlobal pMac, <API key> *pFilter, tScanResultHandle *phResult)
{
eHalStatus status;
tScanResultList *pRetList;
tCsrScanResult *pResult, *pBssDesc;
tANI_U32 count = 0;
tListElem *pEntry;
tANI_U32 bssLen, allocLen;
eCsrEncryptionType uc = <API key>, mc = <API key>;
eCsrAuthType <API key>;
tDot11fBeaconIEs *pIes, *pNewIes;
tANI_BOOLEAN fMatch;
tANI_U16 i = 0;
struct roam_ext_params *roam_params = NULL;
if(phResult)
{
*phResult = <API key>;
}
if (pMac->roam.configParam.nSelect5GHzMargin ||
<API key>(pMac))
{
pMac->scan.<API key> = -128;
roam_params = &pMac->roam.configParam.roam_params;
#ifdef <API key>
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("nSelect5GHzMargin"));
#endif
csrLLLock(&pMac->scan.scanResultList);
/* For 5G preference feature, there is no
* need to check the filter match and also re-program the
* RSSI bucket categories, since we use the RSSI values
* while setting the preference value for the BSS.
* There is no need to check the match for roaming since
* it is already done.*/
if(!<API key>(pMac)) {
/* Find out the best AP Rssi going thru the scan results */
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while ( NULL != pEntry)
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
fMatch = FALSE;
if (pFilter)
for(i = 0; i < pFilter->SSIDs.numOfSSIDs; i++)
{
fMatch = csrIsSsidMatch( pMac, pFilter->SSIDs.SSIDList[i].SSID.ssId, pFilter->SSIDs.SSIDList[i].SSID.length,
pBssDesc->Result.ssId.ssId,
pBssDesc->Result.ssId.length, eANI_BOOLEAN_TRUE );
if (fMatch)
{
pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes );
//At this time, pBssDescription->Result.pvIes may be NULL
if( !pIes && (!HAL_STATUS_SUCCESS(<API key>(pMac,
&pBssDesc->Result.BssDescriptor, &pIes))) )
{
continue;
}
smsLog(pMac, LOG1, FL("SSID Matched"));
if ( pFilter->bOSENAssociation )
{
fMatch = TRUE;
}
else
{
#ifdef WLAN_FEATURE_11W
fMatch = csrIsSecurityMatch(pMac, &pFilter->authType,
&pFilter->EncryptionType,
&pFilter->mcEncryptionType,
&pFilter->MFPEnabled,
&pFilter->MFPRequired,
&pFilter->MFPCapable,
&pBssDesc->Result.BssDescriptor,
pIes, NULL, NULL, NULL );
#else
fMatch = csrIsSecurityMatch(pMac, &pFilter->authType,
&pFilter->EncryptionType,
&pFilter->mcEncryptionType,
NULL, NULL, NULL,
&pBssDesc->Result.BssDescriptor,
pIes, NULL, NULL, NULL );
#endif
}
if ((pBssDesc->Result.pvIes == NULL) && pIes)
vos_mem_free(pIes);
if (fMatch)
smsLog(pMac, LOG1, FL(" Security Matched"));
}
}
if (fMatch && (pBssDesc->Result.BssDescriptor.rssi > pMac->scan.<API key>))
{
smsLog(pMac, LOG1, FL("Best AP Rssi changed from %d to %d"),
pMac->scan.<API key>,
pBssDesc->Result.BssDescriptor.rssi);
pMac->scan.<API key> = pBssDesc->Result.BssDescriptor.rssi;
}
pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK);
}
}
if ((-128 != pMac->scan.<API key>) ||
<API key>(pMac))
{
smsLog(pMac, LOG1, FL("Best AP Rssi is %d"), pMac->scan.<API key>);
/* Modify Rssi category based on best AP Rssi */
if (-128 != pMac->scan.<API key>)
<API key>(pMac, pMac->scan.<API key>, pMac->roam.configParam.bCatRssiOffset);
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while ( NULL != pEntry)
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
/* re-assign preference value based on (modified rssi bucket (or)
* prefer 5G feature.*/
pBssDesc->preferValue = <API key>(pMac,
(int)pBssDesc->Result.BssDescriptor.rssi,
&pBssDesc->Result.BssDescriptor.bssId,
pBssDesc->Result.BssDescriptor.channelId);
smsLog(pMac, LOG2, FL("BSSID("MAC_ADDRESS_STR
") Rssi(%d) Chnl(%d) PrefVal(%u) SSID=%.*s"),
MAC_ADDR_ARRAY(pBssDesc->Result.BssDescriptor.bssId),
pBssDesc->Result.BssDescriptor.rssi,
pBssDesc->Result.BssDescriptor.channelId,
pBssDesc->preferValue,
pBssDesc->Result.ssId.length, pBssDesc->Result.ssId.ssId);
pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK);
}
}
csrLLUnlock(&pMac->scan.scanResultList);
}
pRetList = vos_mem_malloc(sizeof(tScanResultList));
if ( NULL == pRetList )
status = eHAL_STATUS_FAILURE;
else
{
status = eHAL_STATUS_SUCCESS;
vos_mem_set(pRetList, sizeof(tScanResultList), 0);
csrLLOpen(pMac->hHdd, &pRetList->List);
pRetList->pCurEntry = NULL;
csrLLLock(&pMac->scan.scanResultList);
pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_NOLOCK );
while( pEntry )
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes );
/*
* If pBssDesc->Result.pvIes is NULL, we need to free any memory
* allocated by csrMatchBSS for any error condition, otherwise,
* it will be freed later.
*/
fMatch = eANI_BOOLEAN_FALSE;
pNewIes = NULL;
if(pFilter)
{
fMatch = csrMatchBSS(pMac, &pBssDesc->Result.BssDescriptor, pFilter, &auth, &uc, &mc, &pIes);
#ifdef <API key>
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("csrMatchBSS fmatch %d"), fMatch);
#endif
if( NULL != pIes )
{
//Only save it when matching
if(fMatch)
{
if( !pBssDesc->Result.pvIes )
{
//csrMatchBSS allocates the memory. Simply pass it and it is freed later
pNewIes = pIes;
}
else
{
//The pIes is allocated by someone else. make a copy
//Only to save parsed IEs if caller provides a filter. Most likely the caller
//is using to for association, hence save the parsed IEs
pNewIes = vos_mem_malloc(sizeof(tDot11fBeaconIEs));
if ( NULL == pNewIes )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if ( HAL_STATUS_SUCCESS( status ) )
{
vos_mem_copy(pNewIes, pIes, sizeof( tDot11fBeaconIEs ));
}
else
{
smsLog(pMac, LOGE, FL(" fail to allocate memory for IEs"));
//Need to free memory allocated by csrMatchBSS
if( !pBssDesc->Result.pvIes )
{
vos_mem_free(pIes);
}
break;
}
}
}//fMatch
else if( !pBssDesc->Result.pvIes )
{
vos_mem_free(pIes);
}
}
}
if(NULL == pFilter || fMatch)
{
bssLen = pBssDesc->Result.BssDescriptor.length + sizeof(pBssDesc->Result.BssDescriptor.length);
allocLen = sizeof( tCsrScanResult ) + bssLen;
pResult = vos_mem_malloc(allocLen);
if ( NULL == pResult )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
{
smsLog(pMac, LOGE, FL(" fail to allocate memory for scan result, len=%d"), allocLen);
if(pNewIes)
{
vos_mem_free(pNewIes);
}
break;
}
vos_mem_set(pResult, allocLen, 0);
pResult->capValue = pBssDesc->capValue;
pResult->preferValue = pBssDesc->preferValue;
pResult->ucEncryptionType = uc;
pResult->mcEncryptionType = mc;
pResult->authType = auth;
pResult->Result.ssId = pBssDesc->Result.ssId;
pResult->Result.timer = pBssDesc->Result.timer;
//save the pIes for later use
pResult->Result.pvIes = pNewIes;
//save bss description
vos_mem_copy(&pResult->Result.BssDescriptor,
&pBssDesc->Result.BssDescriptor, bssLen);
//No need to lock pRetList because it is locally allocated and no outside can access it at this time
if(csrLLIsListEmpty(&pRetList->List, LL_ACCESS_NOLOCK))
{
csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_NOLOCK);
}
else
{
//To sort the list
tListElem *pTmpEntry;
tCsrScanResult *pTmpResult;
pTmpEntry = csrLLPeekHead(&pRetList->List, LL_ACCESS_NOLOCK);
while(pTmpEntry)
{
pTmpResult = GET_BASE_ADDR( pTmpEntry, tCsrScanResult, Link );
if(csrIsBetterBss(pMac, pResult, pTmpResult))
{
csrLLInsertEntry(&pRetList->List, pTmpEntry, &pResult->Link, LL_ACCESS_NOLOCK);
//To indicate we are done
pResult = NULL;
break;
}
pTmpEntry = csrLLNext(&pRetList->List, pTmpEntry, LL_ACCESS_NOLOCK);
}
if(pResult != NULL)
{
/* This one is'nt better than anyone or the first one */
csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_NOLOCK);
}
}
count++;
}
pEntry = csrLLNext( &pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK );
}//while
csrLLUnlock(&pMac->scan.scanResultList);
smsLog(pMac, LOG2, FL("return %d BSS"), csrLLCount(&pRetList->List));
if( !HAL_STATUS_SUCCESS(status) || (phResult == NULL) )
{
//Fail or No one wants the result.
csrScanResultPurge(pMac, (tScanResultHandle)pRetList);
}
else
{
if(0 == count)
{
//We are here meaning the there is no match
csrLLClose(&pRetList->List);
vos_mem_free(pRetList);
status = <API key>;
}
else if(phResult)
{
*phResult = pRetList;
}
}
}//Allocated pRetList
return (status);
}
/*
* NOTE: This routine is being added to make
* sure that scan results are not being flushed
* while roaming. If the scan results are flushed,
* we are unable to recover from
* <API key>.
* If it is needed to remove this routine,
* first ensure that we recover gracefully from
* <API key> if
* csrScanGetResult returns with a failure because
* of not being able to find the roaming BSS.
*/
tANI_U8 csrScanFlushDenied(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
switch(pMac->roam.neighborRoamInfo[sessionId].neighborRoamState) {
case <API key>:
case <API key>:
case <API key>:
case <API key>:
return (pMac->roam.neighborRoamInfo[sessionId].neighborRoamState);
default:
return 0;
}
}
eHalStatus csrScanFlushResult(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
tANI_U8 isFlushDenied = csrScanFlushDenied(pMac, sessionId);
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirMbMsg *pMsg;
tANI_U16 msgLen;
if (isFlushDenied) {
smsLog(pMac, LOGW, "%s: scan flush denied in roam state %d",
__func__, isFlushDenied);
return eHAL_STATUS_FAILURE;
}
/* prepare and send clear cached scan results msg to lim */
msgLen = (tANI_U16)(sizeof( tSirMbMsg ));
pMsg = vos_mem_malloc(msgLen);
if ( NULL != pMsg ) {
vos_mem_set((void *)pMsg, msgLen, 0);
pMsg->type = pal_cpu_to_be16((tANI_U16)<API key>);
pMsg->msgLen = pal_cpu_to_be16(msgLen);
palSendMBMessage(pMac->hHdd, pMsg);
} else {
status = <API key>;
}
<API key>( pMac, &pMac->scan.tempScanResults );
<API key>( pMac, &pMac->scan.scanResultList );
return( status );
}
eHalStatus <API key>(tpAniSirGlobal pMac, v_BOOL_t flushP2P)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tListElem *pEntry,*pFreeElem;
tCsrScanResult *pBssDesc;
tDblLinkList *pList = &pMac->scan.scanResultList;
csrLLLock(pList);
pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK );
while( pEntry != NULL)
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
if( flushP2P == vos_mem_compare( pBssDesc->Result.ssId.ssId,
"DIRECT-", 7) )
{
pFreeElem = pEntry;
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
csrLLRemoveEntry(pList, pFreeElem, LL_ACCESS_NOLOCK);
<API key>( pMac, pBssDesc );
continue;
}
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
}
csrLLUnlock(pList);
return (status);
}
void <API key>(tpAniSirGlobal pMac,
tpSmeCsaOffloadInd pCsaOffloadInd)
{
tListElem *pEntry,*pFreeElem;
tCsrScanResult *pBssDesc;
tDblLinkList *pList = &pMac->scan.scanResultList;
csrLLLock(pList);
pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK );
while( pEntry != NULL)
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
if( vos_mem_compare(pBssDesc->Result.BssDescriptor.bssId,
pCsaOffloadInd->bssId, sizeof(tSirMacAddr)) )
{
pFreeElem = pEntry;
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
csrLLRemoveEntry(pList, pFreeElem, LL_ACCESS_NOLOCK);
<API key>( pMac, pBssDesc );
smsLog( pMac, LOG1, FL("Removed BSS entry:%pM"),
pCsaOffloadInd->bssId);
continue;
}
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
}
csrLLUnlock(pList);
}
/**
* csrCheck11dChannel
*
*FUNCTION:
* This function is called from <API key> function and
* compare channel number with given channel list.
*
*LOGIC:
* Check Scan result channel number with CFG channel list
*
*ASSUMPTIONS:
*
*
*NOTE:
*
* @param channelId channel number
* @param pChannelList Pointer to channel list
* @param numChannels Number of channel in channel list
*
* @return Status
*/
eHalStatus csrCheck11dChannel(tANI_U8 channelId, tANI_U8 *pChannelList, tANI_U32 numChannels)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tANI_U8 i = 0;
for (i = 0; i < numChannels; i++)
{
if(pChannelList[ i ] == channelId)
{
status = eHAL_STATUS_SUCCESS;
break;
}
}
return status;
}
/**
* <API key>
*
*FUNCTION:
* This function is called from <API key> function and
* filter scan result based on valid channel list number.
*
*LOGIC:
* Get scan result from scan list and Check Scan result channel number
* with 11d channel list if channel number is found in 11d channel list
* then do not remove scan result entry from scan list
*
*ASSUMPTIONS:
*
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
*
* @return Status
*/
eHalStatus <API key>(tpAniSirGlobal pMac)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tListElem *pEntry,*pTempEntry;
tCsrScanResult *pBssDesc;
tANI_U32 len = sizeof(pMac->roam.validChannelList);
/* Get valid channels list from CFG */
if (!HAL_STATUS_SUCCESS(<API key>(pMac,
pMac->roam.validChannelList, &len)))
{
smsLog( pMac, LOGE, "Failed to get Channel list from CFG");
}
csrLLLock(&pMac->scan.scanResultList);
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while( pEntry )
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
pTempEntry = csrLLNext(&pMac->scan.scanResultList, pEntry,
LL_ACCESS_NOLOCK);
if(csrCheck11dChannel(pBssDesc->Result.BssDescriptor.channelId,
pMac->roam.validChannelList, len))
{
/* Remove Scan result which does not have 11d channel */
if( csrLLRemoveEntry(&pMac->scan.scanResultList, pEntry,
LL_ACCESS_NOLOCK))
{
<API key>( pMac, pBssDesc );
}
}
else
{
smsLog( pMac, LOG1, FL("%d is a Valid channel"),
pBssDesc->Result.BssDescriptor.channelId);
}
pEntry = pTempEntry;
}
csrLLUnlock(&pMac->scan.scanResultList);
csrLLLock(&pMac->scan.tempScanResults);
pEntry = csrLLPeekHead(&pMac->scan.tempScanResults, LL_ACCESS_NOLOCK);
while( pEntry )
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
pTempEntry = csrLLNext(&pMac->scan.tempScanResults, pEntry,
LL_ACCESS_NOLOCK);
if(csrCheck11dChannel(pBssDesc->Result.BssDescriptor.channelId,
pMac->roam.validChannelList, len))
{
/* Remove Scan result which does not have 11d channel */
if(csrLLRemoveEntry(&pMac->scan.tempScanResults, pEntry,
LL_ACCESS_NOLOCK))
{
<API key>( pMac, pBssDesc );
}
}
else
{
smsLog( pMac, LOG1, FL("%d is a Valid channel"),
pBssDesc->Result.BssDescriptor.channelId);
}
pEntry = pTempEntry;
}
csrLLUnlock(&pMac->scan.tempScanResults);
return status;
}
eHalStatus <API key>(tpAniSirGlobal pMac, tScanResultHandle hIn, tScanResultHandle *phResult)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tScanResultList *pRetList, *pInList = (tScanResultList *)hIn;
tCsrScanResult *pResult, *pScanResult;
tANI_U32 count = 0;
tListElem *pEntry;
tANI_U32 bssLen, allocLen;
if(phResult)
{
*phResult = <API key>;
}
pRetList = vos_mem_malloc(sizeof(tScanResultList));
if ( NULL == pRetList )
status = eHAL_STATUS_FAILURE;
else
{
vos_mem_set(pRetList, sizeof(tScanResultList), 0);
csrLLOpen(pMac->hHdd, &pRetList->List);
pRetList->pCurEntry = NULL;
csrLLLock(&pMac->scan.scanResultList);
csrLLLock(&pInList->List);
pEntry = csrLLPeekHead( &pInList->List, LL_ACCESS_NOLOCK );
while( pEntry )
{
pScanResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
bssLen = pScanResult->Result.BssDescriptor.length + sizeof(pScanResult->Result.BssDescriptor.length);
allocLen = sizeof( tCsrScanResult ) + bssLen;
pResult = vos_mem_malloc(allocLen);
if ( NULL == pResult )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
{
csrScanResultPurge(pMac, (tScanResultHandle *)pRetList);
count = 0;
break;
}
vos_mem_set(pResult, allocLen , 0);
vos_mem_copy(&pResult->Result.BssDescriptor, &pScanResult->Result.BssDescriptor, bssLen);
if( pScanResult->Result.pvIes )
{
pResult->Result.pvIes = vos_mem_malloc(sizeof( tDot11fBeaconIEs ));
if ( NULL == pResult->Result.pvIes )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (!HAL_STATUS_SUCCESS(status))
{
//Free the memory we allocate above first
vos_mem_free(pResult);
csrScanResultPurge(pMac, (tScanResultHandle *)pRetList);
count = 0;
break;
}
vos_mem_copy(pResult->Result.pvIes, pScanResult->Result.pvIes,
sizeof( tDot11fBeaconIEs ));
}
csrLLInsertTail(&pRetList->List, &pResult->Link, LL_ACCESS_LOCK);
count++;
pEntry = csrLLNext( &pInList->List, pEntry, LL_ACCESS_NOLOCK );
}//while
csrLLUnlock(&pInList->List);
csrLLUnlock(&pMac->scan.scanResultList);
if(HAL_STATUS_SUCCESS(status))
{
if(0 == count)
{
csrLLClose(&pRetList->List);
vos_mem_free(pRetList);
status = <API key>;
}
else if(phResult)
{
*phResult = pRetList;
}
}
}//Allocated pRetList
return (status);
}
eHalStatus <API key>( tpAniSirGlobal pMac, void *pMsgBuf )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirMbMsg *pMsg = (tSirMbMsg *)pMsgBuf;
if((eWNI_SME_SCAN_RSP == pMsg->type) || (<API key> == pMsg->type))
{
status = <API key>( pMac, pMsgBuf );
}
else
{
if(pMsg->type == <API key>)
{
tCsrRoamSession *pSession;
<API key> *pUpperLayerAssocCnf;
tCsrRoamInfo roamInfo;
tCsrRoamInfo *pRoamInfo = NULL;
tANI_U32 sessionId;
eHalStatus status;
smsLog( pMac, LOG1, FL("Scanning : ASSOCIATION confirmation can be given to upper layer "));
vos_mem_set(&roamInfo, sizeof(tCsrRoamInfo), 0);
pRoamInfo = &roamInfo;
pUpperLayerAssocCnf = (<API key> *)pMsgBuf;
status = <API key>( pMac, (tCsrBssid *)pUpperLayerAssocCnf->bssId, &sessionId );
pSession = CSR_GET_SESSION(pMac, sessionId);
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
pRoamInfo->statusCode = eSIR_SME_SUCCESS; //send the status code as Success
pRoamInfo->u.pConnectedProfile = &pSession->connectedProfile;
pRoamInfo->staId = (tANI_U8)pUpperLayerAssocCnf->aid;
pRoamInfo->rsnIELen = (tANI_U8)pUpperLayerAssocCnf->rsnIE.length;
pRoamInfo->prsnIE = pUpperLayerAssocCnf->rsnIE.rsnIEdata;
pRoamInfo->addIELen = (tANI_U8)pUpperLayerAssocCnf->addIE.length;
pRoamInfo->paddIE = pUpperLayerAssocCnf->addIE.addIEdata;
vos_mem_copy(pRoamInfo->peerMac, pUpperLayerAssocCnf->peerMacAddr, sizeof(tSirMacAddr));
vos_mem_copy(&pRoamInfo->bssid, pUpperLayerAssocCnf->bssId, sizeof(tCsrBssid));
pRoamInfo->wmmEnabledSta = pUpperLayerAssocCnf->wmmEnabledSta;
if(CSR_IS_INFRA_AP(pRoamInfo->u.pConnectedProfile) )
{
pMac->roam.roamSession[sessionId].connectState = <API key>;
pRoamInfo->fReassocReq = pUpperLayerAssocCnf->reassocReq;
status = csrRoamCallCallback(pMac, sessionId, pRoamInfo, 0, eCSR_ROAM_INFRA_IND, <API key>);
}
if(CSR_IS_WDS_AP( pRoamInfo->u.pConnectedProfile))
{
vos_sleep( 100 );
pMac->roam.roamSession[sessionId].connectState = <API key>;//Sta
status = csrRoamCallCallback(pMac, sessionId, pRoamInfo, 0, eCSR_ROAM_WDS_IND, <API key>);//Sta
}
}
else
{
if( <API key>( pMac ) )
{
//In case of we are connected, we need to check whether connect status changes
//because scan may also run while connected.
<API key>( pMac, ( tSirSmeRsp * )pMsgBuf );
}
else
{
smsLog( pMac, LOGW, "Message [0x%04x] received in state, when expecting Scan Response", pMsg->type );
}
}
}
return (status);
}
void csrCheckNSaveWscIe(tpAniSirGlobal pMac, tSirBssDescription *pNewBssDescr, tSirBssDescription *pOldBssDescr)
{
int idx, len;
tANI_U8 *pbIe;
//If failed to remove, assuming someone else got it.
if((pNewBssDescr->fProbeRsp != pOldBssDescr->fProbeRsp) &&
(0 == pNewBssDescr->WscIeLen))
{
idx = 0;
len = pOldBssDescr->length - sizeof(tSirBssDescription) +
sizeof(tANI_U16) + sizeof(tANI_U32) - <API key> - 2;
pbIe = (tANI_U8 *)pOldBssDescr->ieFields;
//Save WPS IE if it exists
pNewBssDescr->WscIeLen = 0;
while(idx < len)
{
if((<API key> == pbIe[0]) &&
(0x00 == pbIe[2]) && (0x50 == pbIe[3]) && (0xf2 == pbIe[4]) && (0x04 == pbIe[5]))
{
/* Found it */
if((<API key> - 2) >= pbIe[1])
{
vos_mem_copy(pNewBssDescr->WscIeProbeRsp, pbIe, pbIe[1] + 2);
pNewBssDescr->WscIeLen = pbIe[1] + 2;
}
break;
}
idx += pbIe[1] + 2;
pbIe += pbIe[1] + 2;
}
}
}
//pIes may be NULL
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDescr,
tDot11fBeaconIEs *pIes, tAniSSID *pSsid, v_TIME_t *timer, tANI_BOOLEAN fForced )
{
tListElem *pEntry;
tCsrScanResult *pBssDesc;
tANI_BOOLEAN fRC = FALSE;
// Walk through all the chained BssDescriptions. If we find a chained BssDescription that
// matches the BssID of the BssDescription passed in, then these must be duplicate scan
// results for this Bss. In that case, remove the 'old' Bss description from the linked list.
csrLLLock(&pMac->scan.scanResultList);
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while( pEntry )
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
// we have a duplicate scan results only when BSSID, SSID, Channel and NetworkType
// matches
if ( <API key>( pMac, &pBssDesc->Result.BssDescriptor,
pSirBssDescr, pIes, fForced ) )
{
int32_t rssi_new, rssi_old;
rssi_new = (int32_t) pSirBssDescr->rssi;
rssi_old = (int32_t) pBssDesc->Result.BssDescriptor.rssi;
rssi_new = ((rssi_new * <API key>) +
rssi_old * (100 - <API key>)) / 100;
pSirBssDescr->rssi = (tANI_S8) rssi_new;
rssi_new = (int32_t) pSirBssDescr->rssi_raw;
rssi_old = (int32_t) pBssDesc->Result.BssDescriptor.rssi_raw;
rssi_new = ((rssi_new * <API key>) +
rssi_old * (100 - <API key>)) / 100;
pSirBssDescr->rssi_raw = (tANI_S8) rssi_new;
// Remove the 'old' entry from the list....
if(csrLLRemoveEntry(&pMac->scan.scanResultList, pEntry,
LL_ACCESS_NOLOCK))
{
// !we need to free the memory associated with this node
//If failed to remove, assuming someone else got it.
*pSsid = pBssDesc->Result.ssId;
*timer = pBssDesc->Result.timer;
csrCheckNSaveWscIe(pMac, pSirBssDescr, &pBssDesc->Result.BssDescriptor);
<API key>( pMac, pBssDesc );
}
else
{
smsLog( pMac, LOGW, FL( " fail to remove entry" ) );
}
fRC = TRUE;
// If we found a match, we can stop looking through the list.
break;
}
pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry,
LL_ACCESS_NOLOCK);
}
csrLLUnlock(&pMac->scan.scanResultList);
return fRC;
}
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId,
tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes )
{
eHalStatus status = eHAL_STATUS_FAILURE;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, "<API key> called pMac->scan.NumPmkidCandidate = %d", pSession->NumPmkidCandidate);
if( pIes )
{
// check if this is a RSN BSS
if( pIes->RSN.present )
{
// Check if the BSS is capable of doing pre-authentication
if( pSession->NumPmkidCandidate < <API key> )
{
#ifdef <API key>
{
<API key>(secEvent, <API key>);
vos_mem_set(&secEvent, sizeof(<API key>), 0);
secEvent.eventId = <API key>;
secEvent.<API key> =
(v_U8_t)<API key>(pSession->connectedProfile.mcEncryptionType);
secEvent.<API key> =
(v_U8_t)<API key>(pSession->connectedProfile.EncryptionType);
vos_mem_copy(secEvent.bssid, pSession->connectedProfile.bssid, 6);
secEvent.authMode =
(v_U8_t)<API key>(pSession->connectedProfile.AuthType);
<API key>(&secEvent, EVENT_WLAN_SECURITY);
}
#endif//#ifdef <API key>
// if yes, then add to PMKIDCandidateList
vos_mem_copy(pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].BSSID,
pBssDesc->bssId, VOS_MAC_ADDR_SIZE);
/* Bit 0 of first byte - PreAuthentication Capability */
if ( (pIes->RSN.RSN_Cap[0] >> 0) & 0x1 )
{
pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].preAuthSupported
= eANI_BOOLEAN_TRUE;
}
else
{
pSession->PmkidCandidateInfo[pSession->NumPmkidCandidate].preAuthSupported
= eANI_BOOLEAN_FALSE;
}
pSession->NumPmkidCandidate++;
}
else
{
status = eHAL_STATUS_FAILURE;
}
}
}
return (status);
}
//This function checks whether new AP is found for the current connected profile
//If it is found, it return the sessionId, else it return invalid sessionID
eHalStatus <API key>(tpAniSirGlobal pMac,
tSirBssDescription *pBssDesc,
tDot11fBeaconIEs *pIes,
tANI_U8 sessionId)
{
tCsrRoamSession *pSession;
tDot11fBeaconIEs *pIesLocal = pIes;
eHalStatus status = eHAL_STATUS_FAILURE;
if (pIesLocal ||
HAL_STATUS_SUCCESS(<API key>(
pMac, pBssDesc, &pIesLocal))) {
if (<API key>(pMac, sessionId)) {
pSession = CSR_GET_SESSION(pMac, sessionId);
if (<API key>(pMac, sessionId) &&
(eCSR_AUTH_TYPE_RSN == pSession->connectedProfile.AuthType)) {
if (<API key>(pMac,
&pSession->connectedProfile,
pBssDesc, pIesLocal)) {
/* This new BSS fits the current profile connected */
if (!HAL_STATUS_SUCCESS(<API key>(pMac,
sessionId, pBssDesc, pIesLocal))) {
smsLog(pMac, LOGE,
FL("<API key> failed"));
} else {
status = eHAL_STATUS_SUCCESS;
}
}
}
}
if (!pIes) {
vos_mem_free(pIesLocal);
}
}
return status;
}
#ifdef FEATURE_WLAN_WAPI
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId,
tSirBssDescription *pBssDesc, tDot11fBeaconIEs *pIes )
{
eHalStatus status = eHAL_STATUS_FAILURE;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, "<API key> called pMac->scan.NumBkidCandidate = %d",
pSession->NumBkidCandidate);
if( pIes )
{
// check if this is a WAPI BSS
if( pIes->WAPI.present )
{
// Check if the BSS is capable of doing pre-authentication
if( pSession->NumBkidCandidate < <API key> )
{
// if yes, then add to BKIDCandidateList
vos_mem_copy(pSession->BkidCandidateInfo[pSession->NumBkidCandidate].BSSID,
pBssDesc->bssId, VOS_MAC_ADDR_SIZE);
if ( pIes->WAPI.preauth )
{
pSession->BkidCandidateInfo[pSession->NumBkidCandidate].preAuthSupported
= eANI_BOOLEAN_TRUE;
}
else
{
pSession->BkidCandidateInfo[pSession->NumBkidCandidate].preAuthSupported
= eANI_BOOLEAN_FALSE;
}
pSession->NumBkidCandidate++;
}
else
{
status = eHAL_STATUS_FAILURE;
}
}
}
return (status);
}
//This function checks whether new AP is found for the current connected profile
//if so add to BKIDCandidateList
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc,
tDot11fBeaconIEs *pIes)
{
tANI_BOOLEAN fRC = FALSE;
tDot11fBeaconIEs *pIesLocal = pIes;
tANI_U32 sessionId;
tCsrRoamSession *pSession;
if( pIesLocal || HAL_STATUS_SUCCESS(<API key>(pMac, pBssDesc, &pIesLocal)) )
{
for( sessionId = 0; sessionId < <API key>; sessionId++ )
{
if( <API key>( pMac, sessionId) )
{
pSession = CSR_GET_SESSION( pMac, sessionId );
if( <API key>( pMac, sessionId ) &&
eCSR_<API key> == pSession->connectedProfile.AuthType)
{
if(<API key>(pMac, &pSession->connectedProfile,pBssDesc, pIesLocal))
{
//this new BSS fits the current profile connected
if(HAL_STATUS_SUCCESS(<API key>(pMac, sessionId, pBssDesc, pIesLocal)))
{
fRC = TRUE;
}
}
}
}
}
if(!pIes)
{
vos_mem_free(pIesLocal);
}
}
return fRC;
}
#endif
static void <API key>(tpAniSirGlobal pMac,
tANI_U8 reason,
tANI_U8 sessionId)
{
tListElem *pEntry;
tCsrScanResult *pBssDescription;
tANI_BOOLEAN fDupBss;
#ifdef FEATURE_WLAN_WAPI
tANI_BOOLEAN <API key> = eANI_BOOLEAN_FALSE;
#endif /* FEATURE_WLAN_WAPI */
tDot11fBeaconIEs *pIesLocal = NULL;
tAniSSID tmpSsid;
v_TIME_t timer=0;
tmpSsid.length = 0;
// remove the BSS descriptions from temporary list
while ((pEntry = csrLLRemoveTail(&pMac->scan.tempScanResults,
LL_ACCESS_LOCK)) != NULL)
{
pBssDescription = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
smsLog( pMac, LOG2, "...Bssid= "MAC_ADDRESS_STR" chan= %d, rssi = -%d",
MAC_ADDR_ARRAY(pBssDescription->Result.BssDescriptor.bssId),
pBssDescription->Result.BssDescriptor.channelId,
pBssDescription->Result.BssDescriptor.rssi * (-1) );
//At this time, pBssDescription->Result.pvIes may be NULL
pIesLocal = (tDot11fBeaconIEs *)( pBssDescription->Result.pvIes );
if( !pIesLocal && (!HAL_STATUS_SUCCESS(<API key>(pMac, &pBssDescription->Result.BssDescriptor, &pIesLocal))) )
{
smsLog(pMac, LOGE, FL(" Cannot pared IEs"));
<API key>(pMac, pBssDescription);
continue;
}
fDupBss = <API key>( pMac, &pBssDescription->Result.BssDescriptor, pIesLocal, &tmpSsid, &timer, FALSE );
//Check whether we have reach out limit, but don't lose the LFR candidates came from FW
if( <API key>(pMac)
#ifdef <API key>
&& !( <API key> == reason )
#endif
)
{
//Limit reach
smsLog(pMac, LOGW, FL(" BSS limit reached"));
//Free the resources
if( (pBssDescription->Result.pvIes == NULL) && pIesLocal )
{
vos_mem_free(pIesLocal);
}
<API key>(pMac, pBssDescription);
//Continue because there may be duplicated BSS
continue;
}
// check for duplicate scan results
if ( !fDupBss )
{
if (HAL_STATUS_SUCCESS(<API key>(pMac,
&pBssDescription->Result.BssDescriptor,
pIesLocal, sessionId))) {
/* Found a new BSS */
csrRoamCallCallback(pMac, sessionId, NULL, 0,
<API key>, <API key>);
}
}
else
{
//Check if the new one has SSID it it, if not, use the older SSID if it exists.
if( (0 == pBssDescription->Result.ssId.length) && tmpSsid.length )
{
//New BSS has a hidden SSID and old one has the SSID. Keep the SSID only
//if diff of saved SSID time and current time is less than 1 min to avoid
//side effect of saving SSID with old one is that if AP changes its SSID while remain
//hidden, we may never see it and also to address the requirement of
//When we remove hidden ssid from the profile i.e., forget the SSID via
// GUI that SSID shouldn't see in the profile
if( (<API key>() - timer) <= HIDDEN_TIMER)
{
pBssDescription->Result.timer = timer;
pBssDescription->Result.ssId = tmpSsid;
}
}
}
//Find a good AP for 11d info
if ( csrIs11dSupported( pMac ) )
{
// check if country information element is present
if (pIesLocal->Country.present)
{
<API key>(pMac, pIesLocal->Country.country);
smsLog(pMac, LOGW, FL("11d AP Bssid " MAC_ADDRESS_STR
" chan= %d, rssi = -%d, countryCode %c%c"),
MAC_ADDR_ARRAY( pBssDescription->Result.BssDescriptor.bssId),
pBssDescription->Result.BssDescriptor.channelId,
pBssDescription->Result.BssDescriptor.rssi * (-1),
pIesLocal->Country.country[0],pIesLocal->Country.country[1] );
}
}
// append to main list
csrScanAddResult(pMac, pBssDescription, pIesLocal, sessionId);
if ( (pBssDescription->Result.pvIes == NULL) && pIesLocal )
{
vos_mem_free(pIesLocal);
}
}
pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK );
if (pEntry && 0 != pMac->scan.<API key>)
<API key>(pMac);
/* We don't need to update CC while connected to an AP
which is advertising CC already */
if (csrIs11dSupported(pMac))
{
tCsrRoamSession *pSession;
tANI_U32 i;
for (i = 0; i < <API key>; i++ )
{
if (<API key>( pMac, i ) )
{
pSession = CSR_GET_SESSION( pMac, i );
if (<API key>(pMac, i))
{
smsLog(pMac, LOGW, FL("No need for updating CC in"
"connected state"));
goto end;
}
}
}
<API key>(pMac);
<API key>( pMac, NULL, NULL, eANI_BOOLEAN_TRUE );
}
end:
//If we can find the current 11d info in any of the scan results, or
// a good enough AP with the 11d info from the scan results then no need to
// get into ambiguous state
if(pMac->scan.<API key>)
{
if((pMac->scan.<API key>))
{
pMac->scan.<API key> = eANI_BOOLEAN_FALSE;
}
}
#ifdef FEATURE_WLAN_WAPI
if(<API key>)
{
//remember it first
csrRoamCallCallback(pMac, sessionId, NULL, 0, <API key>, <API key>);
}
#endif /* FEATURE_WLAN_WAPI */
return;
}
static tCsrScanResult *
<API key>(tpAniSirGlobal pMac,
tSirBssDescription *pBSSDescription,
tDot11fBeaconIEs *pIes,
tANI_U8 sessionId)
{
tCsrScanResult *pCsrBssDescription = NULL;
tANI_U32 cbBSSDesc;
tANI_U32 cbAllocated;
tListElem *pEntry;
// figure out how big the BSS description is (the BSSDesc->length does NOT
// include the size of the length field itself).
cbBSSDesc = pBSSDescription->length + sizeof( pBSSDescription->length );
cbAllocated = sizeof( tCsrScanResult ) + cbBSSDesc;
pCsrBssDescription = vos_mem_malloc(cbAllocated);
if ( NULL != pCsrBssDescription )
{
vos_mem_set(pCsrBssDescription, cbAllocated, 0);
pCsrBssDescription->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount;
smsLog(pMac, LOGW,
FL(" Set Aging Count = %d for BSS "MAC_ADDRESS_STR" "),
pCsrBssDescription->AgingCount,
MAC_ADDR_ARRAY(pCsrBssDescription->Result.BssDescriptor.bssId));
vos_mem_copy(&pCsrBssDescription->Result.BssDescriptor, pBSSDescription, cbBSSDesc);
#if defined(VOSS_ENSBALED)
if ( NULL != pCsrBssDescription->Result.pvIes)
{
VOS_ASSERT( pCsrBssDescription->Result.pvIes == NULL );
return NULL;
}
#endif
csrScanAddResult(pMac, pCsrBssDescription, pIes, sessionId);
pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK );
if (pEntry && 0 != pMac->scan.<API key>)
<API key>(pMac);
}
return( pCsrBssDescription );
}
// Append a Bss Description...
tCsrScanResult *
<API key>(tpAniSirGlobal pMac,
tSirBssDescription *pSirBssDescription,
tDot11fBeaconIEs *pIes,
tANI_BOOLEAN fForced,
tANI_U8 sessionId)
{
tCsrScanResult *pCsrBssDescription = NULL;
tAniSSID tmpSsid;
v_TIME_t timer = 0;
int result;
tmpSsid.length = 0;
result = <API key>( pMac, pSirBssDescription, pIes, &tmpSsid, &timer, fForced );
pCsrBssDescription = <API key>(pMac, pSirBssDescription,
pIes, sessionId);
if (result && (pCsrBssDescription != NULL))
{
//Check if the new one has SSID it it, if not, use the older SSID if it exists.
if( (0 == pCsrBssDescription->Result.ssId.length) && tmpSsid.length )
{
//New BSS has a hidden SSID and old one has the SSID. Keep the SSID only
//if diff of saved SSID time and current time is less than 1 min to avoid
//side effect of saving SSID with old one is that if AP changes its SSID while remain
//hidden, we may never see it and also to address the requirement of
//When we remove hidden ssid from the profile i.e., forget the SSID via
// GUI that SSID shouldn't see in the profile
if((<API key>()-timer) <= HIDDEN_TIMER)
{
pCsrBssDescription->Result.ssId = tmpSsid;
pCsrBssDescription->Result.timer = timer;
}
}
}
return( pCsrBssDescription );
}
void <API key>( tpAniSirGlobal pMac, tDblLinkList *pChannelList )
{
<API key> *pChannelSet;
tListElem *pEntry;
csrLLLock(pChannelList);
// Remove the channel sets from the learned list and put them in the free list
while( ( pEntry = csrLLRemoveHead( pChannelList, LL_ACCESS_NOLOCK ) ) != NULL)
{
pChannelSet = GET_BASE_ADDR( pEntry, <API key>, link );
if( pChannelSet )
{
vos_mem_free(pChannelSet);
}
}
csrLLUnlock(pChannelList);
return;
}
/*
* Save the channelList into the ultimate storage as the final stage of channel
* Input: pCountryInfo -- the country code (e.g. "USI"), channel list, and power limit are all stored inside this data structure
*/
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 tableSize, tSirMacChanInfo *channelTable )
{
tANI_U32 i = tableSize / sizeof( tSirMacChanInfo );
tSirMacChanInfo *pChannelInfo;
<API key> *pChannelSet;
tANI_BOOLEAN f2GHzInfoFound = FALSE;
tANI_BOOLEAN f2GListPurged = FALSE, f5GListPurged = FALSE;
pChannelInfo = channelTable;
/* At-least 3 bytes have to be remaining -- from "countryString" */
while ( i
{
pChannelSet = vos_mem_malloc(sizeof(<API key>));
if ( NULL != pChannelSet )
{
vos_mem_set(pChannelSet, sizeof(<API key>), 0);
pChannelSet->firstChannel = pChannelInfo->firstChanNum;
pChannelSet->numChannels = pChannelInfo->numChannels;
// Now set the inter-channel offset based on the frequency band the channel set lies in
if( (<API key>(pChannelSet->firstChannel)) &&
((pChannelSet->firstChannel + (pChannelSet->numChannels - 1)) <= <API key>) )
{
pChannelSet->interChannelOffset = 1;
f2GHzInfoFound = TRUE;
}
else if ( (CSR_IS_CHANNEL_5GHZ(pChannelSet->firstChannel)) &&
((pChannelSet->firstChannel + ((pChannelSet->numChannels - 1) * 4)) <= <API key>) )
{
pChannelSet->interChannelOffset = 4;
f2GHzInfoFound = FALSE;
}
else
{
smsLog( pMac, LOGW, FL("Invalid Channel %d Present in Country IE"),
pChannelSet->firstChannel);
vos_mem_free(pChannelSet);
return eHAL_STATUS_FAILURE;
}
pChannelSet->txPower = CSR_ROAM_MIN( pChannelInfo->maxTxPower, pMac->roam.configParam.nTxPowerCap );
if( f2GHzInfoFound )
{
if( !f2GListPurged )
{
// purge previous results if found new
<API key>( pMac, &pMac->scan.<API key> );
f2GListPurged = TRUE;
}
if(<API key>(pMac))
{
// add to the list of 2.4 GHz channel sets
csrLLInsertTail( &pMac->scan.<API key>, &pChannelSet->link, LL_ACCESS_LOCK );
}
else {
smsLog( pMac, LOGW, FL("Adding 11B/G channels in 11A mode -- First Channel is %d"),
pChannelSet->firstChannel);
vos_mem_free(pChannelSet);
}
}
else
{
// 5GHz info found
if( !f5GListPurged )
{
// purge previous results if found new
<API key>( pMac, &pMac->scan.<API key> );
f5GListPurged = TRUE;
}
if(<API key>(pMac))
{
// add to the list of 5GHz channel sets
csrLLInsertTail( &pMac->scan.<API key>, &pChannelSet->link, LL_ACCESS_LOCK );
}
else {
smsLog( pMac, LOGW, FL("Adding 11A channels in B/G mode -- First Channel is %d"),
pChannelSet->firstChannel);
vos_mem_free(pChannelSet);
}
}
}
pChannelInfo++; // move to next entry
}
return eHAL_STATUS_SUCCESS;
}
static void <API key>( tpAniSirGlobal pMac )
{
tSirMbMsg *pMsg;
tANI_U16 msgLen;
msgLen = (tANI_U16)(sizeof( tSirMbMsg ));
pMsg = vos_mem_malloc(msgLen);
if ( NULL != pMsg )
{
vos_mem_set((void *)pMsg, msgLen, 0);
pMsg->type = pal_cpu_to_be16((tANI_U16)<API key>);
pMsg->msgLen = pal_cpu_to_be16(msgLen);
palSendMBMessage(pMac->hHdd, pMsg);
}
}
void <API key>( tpAniSirGlobal pMac )
{
smsLog( pMac, LOG3, FL(" Updating Cfg with power settings"));
csrSaveTxPowerToCfg( pMac, &pMac->scan.<API key>, <API key> );
csrSaveTxPowerToCfg( pMac, &pMac->scan.<API key>, <API key> );
}
void <API key>( tpAniSirGlobal pMac, tCsrChannel *pChannelList, tANI_U8 *countryCode, tANI_BOOLEAN updateRiva)
{
int i;
tANI_U8 numChannels = 0;
tANI_U8 tempNumChannels = 0;
tCsrChannel ChannelList;
if (pChannelList->numChannels)
{
tempNumChannels = CSR_MIN(pChannelList->numChannels, <API key>);
for (i = 0; i < tempNumChannels; i++)
{
ChannelList.channelList[numChannels] = pChannelList->channelList[i];
numChannels++;
}
ChannelList.numChannels = numChannels;
/* Store the channel + power info in the global place: Cfg */
<API key>(pMac);
<API key>(pMac, ChannelList.channelList, ChannelList.numChannels);
// extend scan capability
// build a scan list based on the channel list : channel# + active/passive scan
<API key>(pMac, countryCode, &ChannelList);
/*Send msg to Lim to clear DFS channel list */
<API key>(pMac);
#ifdef <API key>
if (updateRiva)
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>, FL(" Sending 11d PNO info to Riva"));
// Send HAL UpdateScanParams message
pmcUpdateScanParams(pMac, &(pMac->roam.configParam), &ChannelList, TRUE);
}
#endif // <API key>
}
else
{
smsLog( pMac, LOGE, FL(" 11D channel list is empty"));
}
<API key>(pMac, countryCode);
}
void <API key>( tpAniSirGlobal pMac, tANI_BOOLEAN fForce, tANI_BOOLEAN updateRiva )
{
if( fForce || (csrIs11dSupported( pMac ) && (!pMac->scan.f11dInfoReset)))
{
#ifdef <API key>
{
<API key> *p11dLog;
int Index;
<API key>(p11dLog, <API key>, LOG_WLAN_80211D_C);
if(p11dLog)
{
p11dLog->eventId = <API key>;
vos_mem_copy(p11dLog->countryCode, pMac->scan.countryCodeCurrent, 3);
p11dLog->numChannel = pMac->scan.base20MHzChannels.numChannels;
if(p11dLog->numChannel <= <API key>)
{
vos_mem_copy(p11dLog->Channels,
pMac->scan.base20MHzChannels.channelList,
p11dLog->numChannel);
for (Index=0; Index < pMac->scan.base20MHzChannels.numChannels; Index++)
{
p11dLog->TxPwr[Index] = CSR_ROAM_MIN( pMac->scan.defaultPowerTable[Index].pwr, pMac->roam.configParam.nTxPowerCap );
}
}
if(!pMac->roam.configParam.Is11dSupportEnabled)
{
p11dLog-><API key> = <API key>;
}
else if(pMac->roam.configParam.<API key>)
{
p11dLog-><API key> = <API key>;
}
else
{
p11dLog-><API key> = <API key>;
}
<API key>(p11dLog);
}
}
#endif //#ifdef <API key>
<API key>(pMac, &pMac->scan.baseChannels);
<API key>(pMac, &pMac->scan.base20MHzChannels);
<API key>(pMac, eANI_BOOLEAN_FALSE);
<API key>(pMac, eANI_BOOLEAN_TRUE);
// ... and apply the channel list, power settings, and the country code.
<API key>( pMac, &pMac->scan.base20MHzChannels, pMac->scan.countryCodeCurrent, updateRiva );
// clear the 11d channel list
vos_mem_set(&pMac->scan.channels11d, sizeof(pMac->scan.channels11d), 0);
pMac->scan.f11dInfoReset = eANI_BOOLEAN_TRUE;
pMac->scan.f11dInfoApplied = eANI_BOOLEAN_FALSE;
}
return;
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_BOOLEAN *pfRestartNeeded)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_BOOLEAN fRestart = eANI_BOOLEAN_FALSE;
//Use the Country code and domain from EEPROM
vos_mem_copy(pMac->scan.countryCodeCurrent, pMac->scan.countryCodeDefault,
<API key>);
<API key>(pMac, pMac->scan.domainIdCurrent, &fRestart);
if( ((eANI_BOOLEAN_FALSE == fRestart) || (pfRestartNeeded == NULL) )
&& !csrIsInfraConnected(pMac))
{
//Only reset the country info if we don't need to restart
<API key>(pMac, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE);
}
if(pfRestartNeeded)
{
*pfRestartNeeded = fRestart;
}
return (status);
}
void <API key>(tpAniSirGlobal pMac)
{
pMac->scan.countryCodeCount = 0;
vos_mem_set(pMac->scan.votes11d,
sizeof(tCsrVotes11d) * <API key>, 0);
}
void <API key>(tpAniSirGlobal pMac, tANI_U8 *pCountryCode)
{
tANI_BOOLEAN match = FALSE;
tANI_U8 i;
/* convert to UPPER here so we are assured
* the strings are always in upper case.
*/
for( i = 0; i < 3; i++ )
{
pCountryCode[ i ] = (tANI_U8)csrToUpper( pCountryCode[ i ] );
}
/* Some of the 'old' Cisco 350 series AP's advertise NA as the
* country code (for North America ??). NA is not a valid country code
* or domain so let's allow this by changing it to the proper
* country code (which is US). We've also seen some NETGEAR AP's
* that have "XX " as the country code with valid 2.4 GHz US channel
* information. If we cannot find the country code advertised in the
* 11d information element, let's default to US.
*/
if ( !HAL_STATUS_SUCCESS(<API key>( pMac,
pCountryCode, NULL,COUNTRY_QUERY ) ) )
{
pCountryCode[ 0 ] = '0';
pCountryCode[ 1 ] = '0';
}
/* We've seen some of the AP's improperly put a 0 for the
* third character of the country code. spec says valid charcters are
* 'O' (for outdoor), 'I' for Indoor, or ' ' (space; for either).
* if we see a 0 in this third character, let's change it to a ' '.
*/
if ( 0 == pCountryCode[ 2 ] )
{
pCountryCode[ 2 ] = ' ';
}
for (i = 0; i < pMac->scan.countryCodeCount; i++)
{
match = (vos_mem_compare(pMac->scan.votes11d[i].countryCode,
pCountryCode, 2));
if(match)
{
break;
}
}
if (match)
{
pMac->scan.votes11d[i].votes++;
}
else
{
vos_mem_copy( pMac->scan.votes11d[pMac->scan.countryCodeCount].countryCode,
pCountryCode, 3 );
pMac->scan.votes11d[pMac->scan.countryCodeCount].votes = 1;
pMac->scan.countryCodeCount++;
}
return;
}
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac)
{
tANI_BOOLEAN fRet = FALSE;
tANI_U8 maxVotes = 0;
tANI_U8 i, j=0;
if (!pMac->scan.countryCodeCount)
{
return fRet;
}
maxVotes = pMac->scan.votes11d[0].votes;
fRet = TRUE;
for(i = 1; i < pMac->scan.countryCodeCount; i++)
{
/* If we have a tie for max votes for 2 different country codes,
* pick random.we can put some more intelligence - TBD
*/
if (maxVotes < pMac->scan.votes11d[i].votes)
{
VOS_TRACE( VOS_MODULE_ID_SME, <API key>,
" Votes for Country %c%c : %d\n",
pMac->scan.votes11d[i].countryCode[0],
pMac->scan.votes11d[i].countryCode[1],
pMac->scan.votes11d[i].votes);
maxVotes = pMac->scan.votes11d[i].votes;
j = i;
fRet = TRUE;
}
}
if (fRet)
{
vos_mem_copy(pMac->scan.countryCodeElected,
pMac->scan.votes11d[j].countryCode, <API key>);
vos_mem_copy(pMac->scan.countryCode11d,
pMac->scan.votes11d[j].countryCode, <API key>);
VOS_TRACE( VOS_MODULE_ID_SME, <API key>,
"Selected Country is %c%c With count %d\n",
pMac->scan.votes11d[j].countryCode[0],
pMac->scan.votes11d[j].countryCode[1],
pMac->scan.votes11d[j].votes);
}
return fRet;
}
eHalStatus csrSetCountryCode(tpAniSirGlobal pMac, tANI_U8 *pCountry, tANI_BOOLEAN *pfRestartNeeded)
{
eHalStatus status = <API key>;
v_REGDOMAIN_t domainId;
if(pCountry)
{
status = <API key>(pMac, pCountry, &domainId, COUNTRY_USER);
if(HAL_STATUS_SUCCESS(status))
{
status = <API key>(pMac, domainId, pfRestartNeeded);
if(HAL_STATUS_SUCCESS(status))
{
//We don't need to check the pMac->roam.configParam.<API key> flag here,
//<API key> will fail if the country doesn't fit our domain criteria.
vos_mem_copy(pMac->scan.countryCodeCurrent, pCountry, <API key>);
if((pfRestartNeeded == NULL) || !(*pfRestartNeeded))
{
//Simply set it to cfg. If we need to restart, restart will apply it to the CFG
<API key>(pMac, pCountry);
}
}
}
}
return (status);
}
//caller allocated memory for pNumChn and pChnPowerInfo
//As input, *pNumChn has the size of the array of pChnPowerInfo
//Upon return, *pNumChn has the number of channels assigned.
void <API key>( tpAniSirGlobal pMac, tDblLinkList *pList,
tANI_U32 *pNumChn, <API key> *pChnPowerInfo)
{
tListElem *pEntry;
tANI_U32 chnIdx = 0, idx;
<API key> *pChannelSet;
//Get 2.4Ghz first
pEntry = csrLLPeekHead( pList, LL_ACCESS_LOCK );
while( pEntry && (chnIdx < *pNumChn) )
{
pChannelSet = GET_BASE_ADDR( pEntry, <API key>, link );
if ( 1 != pChannelSet->interChannelOffset )
{
for( idx = 0; (idx < pChannelSet->numChannels) && (chnIdx < *pNumChn); idx++ )
{
pChnPowerInfo[chnIdx].chanId = (tANI_U8)(pChannelSet->firstChannel + ( idx * pChannelSet->interChannelOffset ));
pChnPowerInfo[chnIdx++].pwr = pChannelSet->txPower;
}
}
else
{
for( idx = 0; (idx < pChannelSet->numChannels) && (chnIdx < *pNumChn); idx++ )
{
pChnPowerInfo[chnIdx].chanId = (tANI_U8)(pChannelSet->firstChannel + idx);
pChnPowerInfo[chnIdx++].pwr = pChannelSet->txPower;
}
}
pEntry = csrLLNext( pList, pEntry, LL_ACCESS_LOCK );
}
*pNumChn = chnIdx;
return ;
}
void <API key>( tpAniSirGlobal pMac, tANI_BOOLEAN fForce )
{
v_REGDOMAIN_t domainId;
eHalStatus status = eHAL_STATUS_SUCCESS;
do
{
if( !csrIs11dSupported( pMac ) || 0 == pMac->scan.channelOf11dInfo) break;
if( pMac->scan.<API key> )
{
/* Ambiguous info found; Restore the default domain as well */
if(HAL_STATUS_SUCCESS(<API key>(
pMac, pMac->scan.countryCodeCurrent,
&domainId, COUNTRY_QUERY)))
{
pMac->scan.domainIdCurrent = domainId;
}
else
{
smsLog(pMac, LOGE, FL(" failed to get domain from currentCountryCode %02X%02X"),
pMac->scan.countryCodeCurrent[0], pMac->scan.countryCodeCurrent[1]);
}
<API key>( pMac, eANI_BOOLEAN_FALSE, eANI_BOOLEAN_TRUE );
break;
}
if ( pMac->scan.f11dInfoApplied && !fForce ) break;
if(HAL_STATUS_SUCCESS(<API key>(
pMac, pMac->scan.countryCode11d,
&domainId, COUNTRY_QUERY)))
{
//Check whether we need to enforce default domain
if( ( !pMac->roam.configParam.<API key> ) ||
(pMac->scan.domainIdCurrent == domainId) )
{
#ifdef <API key>
{
<API key> *p11dLog;
<API key> chnPwrInfo[<API key>];
tANI_U32 nChnInfo = <API key>, nTmp;
<API key>(p11dLog, <API key>, LOG_WLAN_80211D_C);
if(p11dLog)
{
p11dLog->eventId = <API key>;
vos_mem_copy(p11dLog->countryCode, pMac->scan.countryCode11d, 3);
p11dLog->numChannel = pMac->scan.channels11d.numChannels;
if(p11dLog->numChannel <= <API key>)
{
vos_mem_copy(p11dLog->Channels,
pMac->scan.channels11d.channelList,
p11dLog->numChannel);
<API key>(pMac, &pMac->scan.<API key>,
&nChnInfo, chnPwrInfo);
nTmp = nChnInfo;
nChnInfo = <API key> - nTmp;
<API key>(pMac, &pMac->scan.<API key>,
&nChnInfo, &chnPwrInfo[nTmp]);
for(nTmp = 0; nTmp < p11dLog->numChannel; nTmp++)
{
for(nChnInfo = 0; nChnInfo < <API key>; nChnInfo++)
{
if(p11dLog->Channels[nTmp] == chnPwrInfo[nChnInfo].chanId)
{
p11dLog->TxPwr[nTmp] = chnPwrInfo[nChnInfo].pwr;
break;
}
}
}
}
if(!pMac->roam.configParam.Is11dSupportEnabled)
{
p11dLog-><API key> = <API key>;
}
else if(pMac->roam.configParam.<API key>)
{
p11dLog-><API key> = <API key>;
}
else
{
p11dLog-><API key> = <API key>;
}
<API key>(p11dLog);
}
}
#endif //#ifdef <API key>
if(pMac->scan.domainIdCurrent != domainId)
{
smsLog(pMac, LOGW, FL("Domain Changed Old %d, new %d"),
pMac->scan.domainIdCurrent, domainId);
status = WDA_SetRegDomain(pMac, domainId, eSIR_TRUE);
}
if (status != eHAL_STATUS_SUCCESS)
{
smsLog( pMac, LOGE, FL(" fail to set regId %d"), domainId );
}
pMac->scan.domainIdCurrent = domainId;
// switch to active scans using this new channel list
pMac->scan.curScanType = eSIR_ACTIVE_SCAN;
pMac->scan.f11dInfoApplied = eANI_BOOLEAN_TRUE;
pMac->scan.f11dInfoReset = eANI_BOOLEAN_FALSE;
}
}
} while( 0 );
return;
}
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tANI_U8 *pCountryCode,
tANI_BOOLEAN fForce)
{
tANI_BOOLEAN <API key> = FALSE, fUnknownCountryCode = FALSE;
tANI_U32 i;
v_REGDOMAIN_t regd;
tANI_BOOLEAN <API key> = FALSE;
// convert to UPPER here so we are assured the strings are always in upper case.
for( i = 0; i < 3; i++ )
{
pCountryCode[ i ] = (tANI_U8)csrToUpper( pCountryCode[ i ] );
}
// Some of the 'old' Cisco 350 series AP's advertise NA as the country code (for North America ??).
// NA is not a valid country code or domain so let's allow this by changing it to the proper
// country code (which is US). We've also seen some NETGEAR AP's that have "XX " as the country code
// with valid 2.4 GHz US channel information. If we cannot find the country code advertised in the
// 11d information element, let's default to US.
if ( !HAL_STATUS_SUCCESS(<API key>(pMac,
pCountryCode,
®d,
COUNTRY_QUERY) ) )
{
// Check the enforcement first
if( pMac->roam.configParam.<API key> || pMac->roam.configParam.<API key> )
{
fUnknownCountryCode = TRUE;
}
else
{
<API key> = TRUE;
}
}
//right now, even if we don't find the CC in driver we set to world. Making
//sure countryCode11d doesn't get updated with the invalid CC, instead
//reflect the world CC
else if (REGDOMAIN_WORLD == regd)
{
<API key> = TRUE;
}
/*
* We've seen some of the AP's improperly put a 0 for the third character
* of the country code. Spec says valid characters are 'O' (for outdoor),
* 'I' for Indoor, or ' ' (space; for either).
* if we see a 0 in this third character, let's change it to a ' '.
*/
if ( 0 == pCountryCode[ 2 ] )
{
pCountryCode[ 2 ] = ' ';
}
if( !fUnknownCountryCode )
{
<API key> = (!vos_mem_compare(pMac->scan.countryCode11d, pCountryCode, 2));
if(( 0 == pMac->scan.countryCode11d[ 0 ] && 0 == pMac->scan.countryCode11d[ 1 ] )
|| (fForce))
{
if (!<API key>)
{
// this is the first .11d information
vos_mem_copy(pMac->scan.countryCode11d, pCountryCode,
sizeof( pMac->scan.countryCode11d ));
}
else
{
pMac->scan.countryCode11d[0] = '0';
pMac->scan.countryCode11d[1] = '0';
}
}
}
return( <API key> );
}
void <API key>( tpAniSirGlobal pMac, tANI_BOOLEAN fPopulate5GBand )
{
tANI_U32 Index, count=0;
tSirMacChanInfo *pChanInfo;
tSirMacChanInfo *pChanInfoStart;
tANI_S32 maxChannelIndex;
maxChannelIndex = ( pMac->scan.base20MHzChannels.numChannels < <API key> ) ?
pMac->scan.base20MHzChannels.numChannels : <API key> ;
pChanInfo = vos_mem_malloc(sizeof(tSirMacChanInfo) * <API key>);
if ( NULL != pChanInfo )
{
vos_mem_set(pChanInfo, sizeof(tSirMacChanInfo) * <API key>, 0);
pChanInfoStart = pChanInfo;
for (Index=0; Index < maxChannelIndex; Index++)
{
if ((fPopulate5GBand && (CSR_IS_CHANNEL_5GHZ(pMac->scan.defaultPowerTable[Index].chanId))) ||
(!fPopulate5GBand && (<API key>(pMac->scan.defaultPowerTable[Index].chanId))) )
{
if(count >= <API key>)
{
smsLog( pMac, LOGW, FL(" <API key>, count exceeded, count = %d"), count);
break;
}
pChanInfo->firstChanNum = pMac->scan.defaultPowerTable[Index].chanId;
pChanInfo->numChannels = 1;
pChanInfo->maxTxPower = CSR_ROAM_MIN( pMac->scan.defaultPowerTable[Index].pwr, pMac->roam.configParam.nTxPowerCap );
pChanInfo++;
count++;
}
}
if(count)
{
<API key>( pMac, count * sizeof(tSirMacChanInfo), pChanInfoStart );
}
vos_mem_free(pChanInfoStart);
}
}
void <API key>( tpAniSirGlobal pMac )
{
tANI_BOOLEAN fPopulate5GBand = FALSE;
do
{
// if this is not a dual band product, then we don't need to set the opposite
// band info. We only work in one band so no need to look in the other band.
if ( !<API key>( pMac ) ) break;
// if we found channel info on the 5.0 band and...
if ( CSR_IS_CHANNEL_5GHZ( pMac->scan.channelOf11dInfo ) )
{
// and the 2.4 band is empty, then populate the 2.4 channel info
if ( !csrLLIsListEmpty( &pMac->scan.<API key>, LL_ACCESS_LOCK ) ) break;
fPopulate5GBand = FALSE;
}
else
{
// else, we found channel info in the 2.4 GHz band. If the 5.0 band is empty
// set the 5.0 band info from the 2.4 country code.
if ( !csrLLIsListEmpty( &pMac->scan.<API key>, LL_ACCESS_LOCK ) ) break;
fPopulate5GBand = TRUE;
}
<API key>( pMac, fPopulate5GBand );
} while( 0 );
}
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tANI_U8 channelId)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
tANI_U32 i;
//Make sure it is a channel that is in our supported list.
for ( i = 0; i < pMac->scan.baseChannels.numChannels; i++ )
{
if ( channelId == pMac->scan.baseChannels.channelList[i] )
{
fRet = eANI_BOOLEAN_TRUE;
break;
}
}
//If it is configured to limit a set of the channels
if( fRet && pMac->roam.configParam.fEnforce11dChannels )
{
fRet = eANI_BOOLEAN_FALSE;
for ( i = 0; i < pMac->scan.base20MHzChannels.numChannels; i++ )
{
if ( channelId == pMac->scan.base20MHzChannels.channelList[i] )
{
fRet = eANI_BOOLEAN_TRUE;
break;
}
}
}
return (fRet);
}
//bSize specify the buffer size of pChannelList
tANI_U8 <API key>( tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 bSize, <API key> *pChannelSet )
{
tANI_U8 i, j = 0, chnId;
bSize = CSR_MIN(bSize, pChannelSet->numChannels);
for( i = 0; i < bSize; i++ )
{
chnId = (tANI_U8)(pChannelSet->firstChannel + ( i * pChannelSet->interChannelOffset ));
if ( <API key>( pMac, chnId ) )
{
pChannelList[j++] = chnId;
}
}
return (j);
}
//bSize -- specify the buffer size of pChannelList
void <API key>( tpAniSirGlobal pMac, tDblLinkList *pChannelSetList,
tANI_U8 *pChannelList, tANI_U8 bSize, tANI_U8 *pNumChannels )
{
tListElem *pEntry;
<API key> *pChannelSet;
tANI_U8 numChannels;
tANI_U8 *pChannels;
if( pChannelSetList && pChannelList && pNumChannels )
{
pChannels = pChannelList;
*pNumChannels = 0;
pEntry = csrLLPeekHead( pChannelSetList, LL_ACCESS_LOCK );
while( pEntry )
{
pChannelSet = GET_BASE_ADDR( pEntry, <API key>, link );
numChannels = <API key>( pMac, pChannels, bSize, pChannelSet );
pChannels += numChannels;
*pNumChannels += numChannels;
pEntry = csrLLNext( pChannelSetList, pEntry, LL_ACCESS_LOCK );
}
}
}
/*
* 802.11D only: Gather 11d IE via beacon or Probe response and store them in pAdapter->channels11d
*/
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDesc,
tDot11fBeaconIEs *pIes, tANI_BOOLEAN fForce)
{
eHalStatus status;
tANI_U8 *<API key>;
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
v_REGDOMAIN_t domainId;
tDot11fBeaconIEs *pIesLocal = pIes;
tANI_BOOLEAN useVoting = eANI_BOOLEAN_FALSE;
if (VOS_STA_SAP_MODE == vos_get_conparam ())
return eHAL_STATUS_SUCCESS;
if ((NULL == pSirBssDesc) && (NULL == pIes))
useVoting = eANI_BOOLEAN_TRUE;
do
{
// check if .11d support is enabled
if( !csrIs11dSupported( pMac ) ) break;
if (eANI_BOOLEAN_FALSE == useVoting)
{
if( !pIesLocal &&
(!HAL_STATUS_SUCCESS(<API key>(pMac,
pSirBssDesc, &pIesLocal))))
{
break;
}
// check if country information element is present
if(!pIesLocal->Country.present)
{
//No country info
break;
}
if( HAL_STATUS_SUCCESS(<API key>
(pMac, pIesLocal->Country.country, &domainId,
COUNTRY_QUERY)) &&
( domainId == REGDOMAIN_WORLD))
{
break;
}
} //useVoting == eANI_BOOLEAN_FALSE
if (eANI_BOOLEAN_FALSE == useVoting)
<API key> = pIesLocal->Country.country;
else
<API key> = pMac->scan.countryCodeElected;
status = <API key>(pMac,
<API key>, &domainId, COUNTRY_IE);
if ( status != eHAL_STATUS_SUCCESS )
{
smsLog( pMac, LOGE, FL(" fail to get regId %d"), domainId );
fRet = eANI_BOOLEAN_FALSE;
break;
}
/* updating 11d Country Code with Country code selected. */
vos_mem_copy(pMac->scan.countryCode11d,
<API key>,
<API key>);
#ifndef <API key>
// Checking for Domain Id change
if ( domainId != pMac->scan.domainIdCurrent )
{
vos_mem_copy(pMac->scan.countryCode11d,
<API key>,
sizeof( pMac->scan.countryCode11d ) );
/* Set Current Country code and Current Regulatory domain */
status = <API key>(pMac, domainId, NULL);
if (eHAL_STATUS_SUCCESS != status)
{
smsLog(pMac, LOGE, "Set Reg Domain Fail %d", status);
fRet = eANI_BOOLEAN_FALSE;
break;
}
//<API key> will fail if the country doesn't fit our domain criteria.
vos_mem_copy(pMac->scan.countryCodeCurrent,
<API key>, <API key>);
//Simply set it to cfg.
<API key>(pMac, <API key>);
/* overwrite the defualt country code */
vos_mem_copy(pMac->scan.countryCodeDefault,
pMac->scan.countryCodeCurrent,
<API key>);
/* Set Current RegDomain */
status = WDA_SetRegDomain(pMac, domainId, eSIR_TRUE);
if ( status != eHAL_STATUS_SUCCESS )
{
smsLog( pMac, LOGE, FL(" fail to Set regId %d"), domainId );
fRet = eANI_BOOLEAN_FALSE;
break;
}
/* set to default domain ID */
pMac->scan.domainIdCurrent = domainId;
/* get the channels based on new cc */
status = csrInitGetChannels( pMac );
if ( status != eHAL_STATUS_SUCCESS )
{
smsLog( pMac, LOGE, FL(" fail to get Channels "));
fRet = eANI_BOOLEAN_FALSE;
break;
}
}
#endif
fRet = eANI_BOOLEAN_TRUE;
} while( 0 );
if( !pIes && pIesLocal )
{
//locally allocated
vos_mem_free(pIesLocal);
}
return( fRet );
}
static void csrSaveScanResults(tpAniSirGlobal pMac, tANI_U8 reason,
tANI_U8 sessionId)
{
// initialize this to FALSE. <API key>() routine
// will set this to the channel where an .11d beacon is seen
pMac->scan.channelOf11dInfo = 0;
// if we get any ambiguous .11d information then this will be set to TRUE
pMac->scan.<API key> = eANI_BOOLEAN_FALSE;
//Tush
// if we get any ambiguous .11d information, then this will be set to TRUE
// only if the applied 11d info could be found in one of the scan results
pMac->scan.<API key> = eANI_BOOLEAN_FALSE;
// move the scan results from interim list to the main scan list
<API key>(pMac, reason, sessionId);
// Now check if we gathered any domain/country specific information
// If so, we should update channel list and apply Tx power settings
if( csrIs11dSupported(pMac) )
{
<API key>( pMac, FALSE );
}
}
void csrReinitScanCmd(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
switch (pCommand->u.scanCmd.reason)
{
case <API key>:
case eCsrScanAbortBgScan:
if(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList)
{
vos_mem_free(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList);
pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList = NULL;
}
break;
case eCsrScanBGScanAbort:
case <API key>:
case <API key>:
break;
case <API key>:
default:
csrScanFreeRequest(pMac, &pCommand->u.scanCmd.u.scanRequest);
break;
}
if(pCommand->u.scanCmd.pToRoamProfile)
{
csrReleaseProfile(pMac, pCommand->u.scanCmd.pToRoamProfile);
vos_mem_free(pCommand->u.scanCmd.pToRoamProfile);
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
}
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tANI_U8 *pChannels, tANI_U8 *pcChannels )
{
tANI_U32 index11dChannels, index;
tANI_U32 <API key>;
tANI_BOOLEAN <API key>;
tANI_U32 len = sizeof(pMac->roam.validChannelList);
*pcChannels = 0;
if ( <API key>(pMac) && <API key>(pMac, pMac->scan.channelOf11dInfo) )
{
if (HAL_STATUS_SUCCESS(<API key>(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len)))
{
//Find the channel index where we found the 11d info
for(index = 0; index < len; index++)
{
if(pMac->scan.channelOf11dInfo == pMac->roam.validChannelList[index])
break;
}
//check whether we found the channel index
if(index < len)
{
// Now, look through the 11d channel list and create a list of all channels in the 11d list that are
// NOT in the current channel list. This gives us a list of the new channels that have not been
// scanned. We'll scan this new list so we have a complete set of scan results on all of the domain channels
// initially.
for ( index11dChannels = 0; index11dChannels < pMac->scan.channels11d.numChannels; index11dChannels++ )
{
<API key> = eANI_BOOLEAN_FALSE;
for( <API key> = 0; <API key> < index; <API key>++ )
{
if ( pMac->roam.validChannelList[ <API key> ] == pMac->scan.channels11d.channelList[ index11dChannels ] )
{
<API key> = eANI_BOOLEAN_TRUE;
break;
}
}
if ( !<API key> )
{
pChannels[ *pcChannels ] = pMac->scan.channels11d.channelList[ index11dChannels ];
( *pcChannels )++;
}
}
}
}//GetCFG
}
return( *pcChannels );
}
<API key> <API key>( tpAniSirGlobal pMac, tSmeCmd *pCommand, tANI_BOOLEAN fSuccess )
{
<API key> NextCommand = eCsrNextScanNothing;
switch( pCommand->u.scanCmd.reason )
{
case eCsrScan11d1:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case eCsrScan11d2:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case eCsrScan11dDone:
NextCommand = <API key>;
break;
case eCsrScanLostLink1:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case eCsrScanLostLink2:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case eCsrScanLostLink3:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case eCsrScanForSsid:
NextCommand = (fSuccess) ? <API key> : <API key>;
break;
case <API key>:
NextCommand = <API key>; //don't care success or not
break;
case eCsrScanIdleScan:
NextCommand = <API key>;
break;
default:
NextCommand = eCsrNextScanNothing;
break;
}
return( NextCommand );
}
//Return whether the pCommand is finished.
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_TRUE;
//Apply back the default setting and passively scan one more time.
<API key>(pMac, eANI_BOOLEAN_FALSE, eANI_BOOLEAN_TRUE);
pCommand->u.scanCmd.reason = eCsrScan11d2;
if(HAL_STATUS_SUCCESS(csrScanChannels(pMac, pCommand)))
{
fRet = eANI_BOOLEAN_FALSE;
}
return (fRet);
}
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_TRUE;
tANI_U8 *pChannels;
tANI_U8 cChannels;
pChannels = vos_mem_malloc(<API key>);
if ( NULL != pChannels )
{
vos_mem_set(pChannels, <API key>, 0);
if ( <API key>( pMac, pChannels, &cChannels ) )
{
pCommand->u.scanCmd.reason = eCsrScan11dDone;
if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList)
{
vos_mem_free(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList);
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL;
}
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(cChannels);
if ( NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
{
vos_mem_copy(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList,
pChannels, cChannels);
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = cChannels;
pCommand->u.scanCmd.u.scanRequest.requestType = <API key>;
pCommand->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN;
if(HAL_STATUS_SUCCESS(csrScanChannels(pMac, pCommand)))
{
//Reuse the same command buffer
fRet = eANI_BOOLEAN_FALSE;
}
}
}
vos_mem_free(pChannels);
}
return (fRet);
}
//Return whether the command should be removed
tANI_BOOLEAN csrScanComplete( tpAniSirGlobal pMac, tSirSmeScanRsp *pScanRsp )
{
<API key> NextCommand = eCsrNextScanNothing;
tListElem *pEntry;
tSmeCmd *pCommand;
tANI_BOOLEAN fRemoveCommand = eANI_BOOLEAN_TRUE;
tANI_BOOLEAN fSuccess;
if (pMac->fScanOffload)
pEntry = csrLLPeekHead(&pMac->sme.<API key>, LL_ACCESS_LOCK);
else
pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK);
if ( pEntry )
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
// If the head of the queue is Active and it is a SCAN command, remove
// and put this on the Free queue.
if ( eSmeCommandScan == pCommand->command )
{
tANI_U32 sessionId = pCommand->sessionId;
if(eSIR_SME_SUCCESS != pScanRsp->statusCode)
{
fSuccess = eANI_BOOLEAN_FALSE;
}
else
{
//pMac->scan.tempScanResults is not empty meaning the scan found something
//This check only valid here because csrSaveScanresults is not yet called
fSuccess = (!csrLLIsListEmpty(&pMac->scan.tempScanResults, LL_ACCESS_LOCK));
}
if (pCommand->u.scanCmd.<API key>)
{
/*
* Scan aborted due to band change
* The scan results need to be flushed
*/
if (pCommand->u.scanCmd.callback
!= pMac->scan.callback11dScanDone)
{
smsLog(pMac, LOG1, FL("Filtering the scan results as the "
"results may belong to wrong band"));
<API key>(pMac);
}
else
{
smsLog(pMac, LOG1, FL("11d_scan_done will flush the scan"
" results"));
}
pCommand->u.scanCmd.<API key>
= eANI_BOOLEAN_FALSE;
}
csrSaveScanResults(pMac, pCommand->u.scanCmd.reason, sessionId);
#ifdef <API key>
{
<API key> *pScanLog = NULL;
tScanResultHandle hScanResult;
tCsrScanResultInfo *pScanResult;
tDot11fBeaconIEs *pIes;
int n = 0, c = 0;
<API key>(pScanLog, <API key>, LOG_WLAN_SCAN_C);
if(pScanLog)
{
if(eCsrScanBgScan == pCommand->u.scanCmd.reason ||
eCsrScanProbeBss == pCommand->u.scanCmd.reason ||
<API key> == pCommand->u.scanCmd.reason)
{
pScanLog->eventId = <API key>;
}
else
{
if( eSIR_PASSIVE_SCAN != pMac->scan.curScanType )
{
pScanLog->eventId = <API key>;
}
else
{
pScanLog->eventId = <API key>;
}
}
if(eSIR_SME_SUCCESS == pScanRsp->statusCode)
{
if(HAL_STATUS_SUCCESS(csrScanGetResult(pMac, NULL, &hScanResult)))
{
while(((pScanResult = <API key>(pMac, hScanResult)) != NULL))
{
if( n < <API key> )
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac, &pScanResult->BssDescriptor, &pIes)))
{
smsLog(pMac, LOGE, FL(" fail to parse IEs"));
break;
}
vos_mem_copy(pScanLog->bssid[n],
pScanResult->BssDescriptor.bssId, 6);
if(pIes && pIes->SSID.present && <API key> >= pIes->SSID.num_ssid)
{
vos_mem_copy(pScanLog->ssid[n],
pIes->SSID.ssid, pIes->SSID.num_ssid);
}
vos_mem_free(pIes);
n++;
}
c++;
}
pScanLog->numSsid = (v_U8_t)n;
pScanLog->totalSsid = (v_U8_t)c;
csrScanResultPurge(pMac, hScanResult);
}
}
else
{
pScanLog->status = <API key>;
}
<API key>(pScanLog);
}
}
#endif //#ifdef <API key>
NextCommand = <API key>(pMac, pCommand, fSuccess);
//We reuse the command here instead reissue a new command
switch(NextCommand)
{
case <API key>:
case <API key>:
smsLog( pMac, LOG2, FL("11dScan1/3 produced results. Reissue Active scan..."));
// if we found country information, no need to continue scanning further, bail out
fRemoveCommand = eANI_BOOLEAN_TRUE;
NextCommand = <API key>;
break;
case <API key>:
//We are not done yet. 11d scan fail once. We will try to reset anything and do it over again
//The only meaningful thing for this retry is that we cannot find 11d information after a reset so
//we clear the "old" 11d info and give it once more chance
fRemoveCommand = <API key>(pMac, pCommand);
if(fRemoveCommand)
{
NextCommand = <API key>;
}
break;
case <API key>:
if(!HAL_STATUS_SUCCESS(<API key>(pMac, sessionId, eCsrLostLink1)))
{
<API key>(pMac, sessionId);
}
break;
case <API key>:
if(!HAL_STATUS_SUCCESS(<API key>(pMac, sessionId, eCsrLostLink2)))
{
<API key>(pMac, sessionId);
}
break;
case <API key>:
if(!HAL_STATUS_SUCCESS(<API key>(pMac, sessionId, eCsrLostLink3)))
{
<API key>(pMac, sessionId);
}
break;
case <API key>:
<API key>(pMac, sessionId);
break;
case <API key>:
<API key>(pMac, sessionId);
break;
case <API key>:
<API key>(pMac, sessionId);
break;
case <API key>:
<API key>(pMac, pCommand);
break;
case <API key>:
<API key>(pMac, pCommand);
break;
case <API key>:
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
break;
case <API key>:
<API key>(pMac, sessionId);
break;
default:
break;
}
}
else
{
smsLog( pMac, LOGW, FL("Scan Completion called but SCAN command is not ACTIVE ..."));
fRemoveCommand = eANI_BOOLEAN_FALSE;
}
}
else
{
smsLog( pMac, LOGW, FL("Scan Completion called but NO commands are ACTIVE ..."));
fRemoveCommand = eANI_BOOLEAN_FALSE;
}
return( fRemoveCommand );
}
static void <API key>( tpAniSirGlobal pMac,
tSirBssDescription *pSirBssDescr,
tDot11fBeaconIEs *pIes)
{
tListElem *pEntry;
tCsrScanResult *pCsrBssDescription;
csrLLLock(&pMac->scan.tempScanResults);
// Walk through all the chained BssDescriptions. If we find a chained BssDescription that
// matches the BssID of the BssDescription passed in, then these must be duplicate scan
// results for this Bss. In that case, remove the 'old' Bss description from the linked list.
pEntry = csrLLPeekHead(&pMac->scan.tempScanResults, LL_ACCESS_NOLOCK);
while( pEntry )
{
pCsrBssDescription = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
// we have a duplicate scan results only when BSSID, SSID, Channel and NetworkType
// matches
if ( <API key>( pMac, &pCsrBssDescription->Result.BssDescriptor,
pSirBssDescr, pIes, FALSE ) )
{
pSirBssDescr->rssi = (tANI_S8)( (((tANI_S32)pSirBssDescr->rssi * <API key> ) +
((tANI_S32)pCsrBssDescription->Result.BssDescriptor.rssi * (100 - <API key>) )) / 100 );
// Remove the 'old' entry from the list....
if(csrLLRemoveEntry(&pMac->scan.tempScanResults, pEntry,
LL_ACCESS_NOLOCK))
{
csrCheckNSaveWscIe(pMac, pSirBssDescr, &pCsrBssDescription->Result.BssDescriptor);
// we need to free the memory associated with this node
<API key>( pMac, pCsrBssDescription );
}
// If we found a match, we can stop looking through the list.
break;
}
pEntry = csrLLNext(&pMac->scan.tempScanResults, pEntry,
LL_ACCESS_NOLOCK);
}
csrLLUnlock(&pMac->scan.tempScanResults);
}
//Caller allocated memory pfNewBssForConn to return whether new candidate for
//current connection is found. Cannot be NULL
tCsrScanResult *<API key>( tpAniSirGlobal pMac,
tSirBssDescription *pBSSDescription,
tDot11fBeaconIEs *pIes)
{
tCsrScanResult *pCsrBssDescription = NULL;
tANI_U32 cbBSSDesc;
tANI_U32 cbAllocated;
// figure out how big the BSS description is (the BSSDesc->length does NOT
// include the size of the length field itself).
cbBSSDesc = pBSSDescription->length + sizeof( pBSSDescription->length );
cbAllocated = sizeof( tCsrScanResult ) + cbBSSDesc;
pCsrBssDescription = vos_mem_malloc(cbAllocated);
if ( NULL != pCsrBssDescription )
{
vos_mem_set(pCsrBssDescription, cbAllocated, 0);
pCsrBssDescription->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount;
smsLog(pMac, LOGW,
FL(" Set Aging Count = %d for BSS "MAC_ADDRESS_STR" "),
pCsrBssDescription->AgingCount,
MAC_ADDR_ARRAY(pBSSDescription->bssId));
vos_mem_copy(&pCsrBssDescription->Result.BssDescriptor, pBSSDescription, cbBSSDesc );
//Save SSID separately for later use
if( pIes->SSID.present && !csrIsNULLSSID(pIes->SSID.ssid, pIes->SSID.num_ssid) )
{
//SSID not hidden
tANI_U32 len = pIes->SSID.num_ssid;
if (len > <API key>)
{
// truncate to fit in our struct
len = <API key>;
}
pCsrBssDescription->Result.ssId.length = len;
pCsrBssDescription->Result.timer = <API key>();
vos_mem_copy(pCsrBssDescription->Result.ssId.ssId, pIes->SSID.ssid, len);
}
csrLLInsertTail( &pMac->scan.tempScanResults, &pCsrBssDescription->Link, LL_ACCESS_LOCK );
}
return( pCsrBssDescription );
}
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tSirBssDescription *pSirBssDesc1,
tSirBssDescription *pSirBssDesc2, tDot11fBeaconIEs *pIes2, tANI_BOOLEAN fForced )
{
tANI_BOOLEAN fMatch = FALSE;
<API key> *pCap1, *pCap2;
tDot11fBeaconIEs *pIes1 = NULL;
tDot11fBeaconIEs *pIesTemp = pIes2;
pCap1 = (<API key> *)&pSirBssDesc1->capabilityInfo;
pCap2 = (<API key> *)&pSirBssDesc2->capabilityInfo;
if(pCap1->ess == pCap2->ess)
{
if (pCap1->ess &&
<API key>( pMac, (tCsrBssid *)pSirBssDesc1->bssId, (tCsrBssid *)pSirBssDesc2->bssId)&&
(fForced || (vos_chan_to_band(pSirBssDesc1->channelId) == vos_chan_to_band((pSirBssDesc2->channelId)))))
{
fMatch = TRUE;
// Check for SSID match, if exists
do
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac, pSirBssDesc1, &pIes1)))
{
break;
}
if( NULL == pIesTemp )
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac, pSirBssDesc2, &pIesTemp)))
{
break;
}
}
if(pIes1->SSID.present && pIesTemp->SSID.present)
{
fMatch = csrIsSsidMatch(pMac, pIes1->SSID.ssid, pIes1->SSID.num_ssid,
pIesTemp->SSID.ssid, pIesTemp->SSID.num_ssid, eANI_BOOLEAN_TRUE);
}
}while(0);
}
else if (pCap1->ibss && (pSirBssDesc1->channelId == pSirBssDesc2->channelId))
{
do
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac, pSirBssDesc1, &pIes1)))
{
break;
}
if( NULL == pIesTemp )
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac, pSirBssDesc2, &pIesTemp)))
{
break;
}
}
//Same channel cannot have same SSID for different IBSS
if(pIes1->SSID.present && pIesTemp->SSID.present)
{
fMatch = csrIsSsidMatch(pMac, pIes1->SSID.ssid, pIes1->SSID.num_ssid,
pIesTemp->SSID.ssid, pIesTemp->SSID.num_ssid, eANI_BOOLEAN_TRUE);
}
}while(0);
}
/* In case of P2P devices, ess and ibss will be set to zero */
else if (!pCap1->ess &&
<API key>( pMac, (tCsrBssid *)pSirBssDesc1->bssId, (tCsrBssid *)pSirBssDesc2->bssId))
{
fMatch = TRUE;
}
}
if(pIes1)
{
vos_mem_free(pIes1);
}
if( (NULL == pIes2) && pIesTemp )
{
//locally allocated
vos_mem_free(pIesTemp);
}
return( fMatch );
}
tANI_BOOLEAN <API key>( tSirBssDescription *pSirBssDesc1, tSirBssDescription *pSirBssDesc2 )
{
return( pSirBssDesc1->nwType == pSirBssDesc2->nwType );
}
//to check whether the BSS matches the dot11Mode
static tANI_BOOLEAN csrScanIsBssAllowed(tpAniSirGlobal pMac, tSirBssDescription *pBssDesc,
tDot11fBeaconIEs *pIes)
{
tANI_BOOLEAN fAllowed = eANI_BOOLEAN_FALSE;
eCsrPhyMode phyMode;
if(HAL_STATUS_SUCCESS(<API key>(pMac, pBssDesc, &phyMode, pIes)))
{
switch(pMac->roam.configParam.phyMode)
{
case eCSR_DOT11_MODE_11b:
fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11a != phyMode);
break;
case eCSR_DOT11_MODE_11g:
fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11a != phyMode);
break;
case <API key>:
fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11g == phyMode);
break;
case eCSR_DOT11_MODE_11a:
fAllowed = (tANI_BOOLEAN)((eCSR_DOT11_MODE_11b != phyMode) && (eCSR_DOT11_MODE_11g != phyMode));
break;
case <API key>:
fAllowed = (tANI_BOOLEAN)((eCSR_DOT11_MODE_11n == phyMode));
break;
#ifdef WLAN_FEATURE_11AC
case <API key>:
fAllowed = (tANI_BOOLEAN)((<API key> == phyMode));
break;
#endif
case <API key>:
fAllowed = (tANI_BOOLEAN)(eCSR_DOT11_MODE_11b == phyMode);
break;
case eCSR_DOT11_MODE_11n:
#ifdef WLAN_FEATURE_11AC
case <API key>:
#endif
default:
fAllowed = eANI_BOOLEAN_TRUE;
break;
}
}
return (fAllowed);
}
//Return pIes to caller for future use when returning TRUE.
static tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tANI_U8 *pChannels,
tANI_U8 numChn, tSirBssDescription *pBssDesc,
tDot11fBeaconIEs **ppIes )
{
tANI_BOOLEAN fValidChannel = FALSE;
tDot11fBeaconIEs *pIes = NULL;
tANI_U8 index;
for( index = 0; index < numChn; index++ )
{
/*
* This check relies on the fact that a single BSS description is
* returned in each ScanRsp call, which is the way LIM implemented
* the scan req/rsp functions. We changed to this model when we ran
* with a large number of APs. If this were to change, then this check
* would have to mess with removing the bssDescription from somewhere
* in an arbitrary index in the bssDescription array.
*/
if ( pChannels[ index ] == pBssDesc->channelId )
{
fValidChannel = TRUE;
break;
}
}
*ppIes = NULL;
if(fValidChannel)
{
if( HAL_STATUS_SUCCESS( <API key>(pMac, pBssDesc, &pIes) ) )
{
fValidChannel = csrScanIsBssAllowed(pMac, pBssDesc, pIes);
if( fValidChannel )
{
*ppIes = pIes;
}
else
{
vos_mem_free(pIes);
}
}
else
{
fValidChannel = FALSE;
}
}
return( fValidChannel );
}
//Return whether last scan result is received
static tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tSmeCmd *pCommand,
tSirSmeScanRsp *pScanRsp, tANI_BOOLEAN *pfRemoveCommand )
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE, fRemoveCommand = eANI_BOOLEAN_FALSE;
tDot11fBeaconIEs *pIes = NULL;
tANI_U32 cbParsed;
tSirBssDescription *pSirBssDescription;
tANI_U32 cbBssDesc;
tANI_U32 cbScanResult = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription )
+ sizeof(tSirBssDescription); //We need at least one CB
<API key> pNeighborRoamInfo =
&pMac->roam.neighborRoamInfo[pScanRsp->sessionId];
/*
* Don't consider the scan rsp to be valid if the status code is Scan
* Failure. Scan Failure is returned when the scan could not find anything.
* So if we get scan failure return that the scan response is invalid.
* Also check the length in the scan result for valid scan BssDescriptions.
*/
do
{
if ( ( cbScanResult <= pScanRsp->length ) &&
(( eSIR_SME_SUCCESS == pScanRsp->statusCode ) ||
( <API key> == pScanRsp->statusCode ) ) )
{
tANI_U8 *pChannelList = NULL;
tANI_U8 cChannels = 0;
//Different scan type can reach this point, we need to distinguish it
#ifdef <API key>
if( <API key> == pCommand->u.scanCmd.reason )
{
pChannelList = NULL;
cChannels = 0;
}
else
#endif
if( <API key> == pCommand->u.scanCmd.reason )
{
//<API key> uses different structure
tCsrBGScanRequest *pBgScanReq = &pCommand->u.scanCmd.u.bgScanRequest;
cChannels = pBgScanReq->ChannelInfo.numOfChannels;
pChannelList = pBgScanReq->ChannelInfo.ChannelList;
}
else
{
//the rest use generic scan request
cChannels = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels;
pChannelList = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList;
}
// if the scan result is not on one of the channels in the Valid channel list, then it
// must have come from an AP on an overlapping channel (in the 2.4GHz band). In this case,
// let's drop the scan result.
// The other situation is where the scan request is for a scan on a particular channel set
// and the scan result is from a
// if the NumChannels is 0, then we are supposed to be scanning all channels. Use the full channel
// list as the 'valid' channel list. Otherwise, use the specific channel list in the scan parms
// as the valid channels.
if ( 0 == cChannels )
{
tANI_U32 len = sizeof(pMac->roam.validChannelList);
if (HAL_STATUS_SUCCESS(<API key>(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len)))
{
pChannelList = pMac->roam.validChannelList;
cChannels = (tANI_U8)len;
}
else
{
//Cannot continue
smsLog( pMac, LOGE, "CSR: Processing internal SCAN results...<API key> failed" );
break;
}
}
smsLog( pMac, LOG2, "CSR: Processing internal SCAN results..." );
cbParsed = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription );
pSirBssDescription = pScanRsp->bssDescription;
while( cbParsed < pScanRsp->length )
{
if ( <API key>( pMac, pChannelList, cChannels, pSirBssDescription, &pIes ) )
{
<API key>(pMac, pSirBssDescription, pIes);
<API key>( pMac, pSirBssDescription, pIes );
if( eSIR_PASSIVE_SCAN == pMac->scan.curScanType )
{
if( csrIs11dSupported( pMac) )
{
//Check whether the BSS is acceptable base on 11d info and our configs.
if( csrMatchCountryCode( pMac, NULL, pIes ) )
{
//Double check whether the channel is acceptable by us.
if( <API key>( pMac, pSirBssDescription->channelId ) )
{
pMac->scan.curScanType = eSIR_ACTIVE_SCAN;
}
}
}
else
{
pMac->scan.curScanType = eSIR_ACTIVE_SCAN;
}
}
//Free the resource
vos_mem_free(pIes);
}
// skip over the BSS description to the next one...
cbBssDesc = pSirBssDescription->length + sizeof( pSirBssDescription->length );
cbParsed += cbBssDesc;
pSirBssDescription = (tSirBssDescription *)((tANI_U8 *)pSirBssDescription + cbBssDesc );
} //while
}
else
{
smsLog( pMac, LOGW, " Scanrsp fail (0x%08X), length = %d (expected %d)",
pScanRsp->statusCode, pScanRsp->length, cbScanResult);
//HO bg scan/probe failed no need to try autonomously
if(eCsrScanBgScan == pCommand->u.scanCmd.reason ||
eCsrScanProbeBss == pCommand->u.scanCmd.reason ||
#ifdef <API key>
<API key> == pCommand->u.scanCmd.reason ||
#endif
<API key> == pCommand->u.scanCmd.reason)
{
fRemoveCommand = eANI_BOOLEAN_TRUE;
}
}
}while(0);
if ( <API key> != pScanRsp->statusCode )
{
smsLog(pMac, LOGE, "Found %d BSS, statusCode %d",
csrLLCount(&pMac->scan.tempScanResults),
pScanRsp->statusCode);
smsLog(pMac, LOG1, "scan reason is %d", pCommand->u.scanCmd.reason);
#ifdef <API key>
<API key>(pMac, <API key>, eSIR_SUCCESS,
eSIR_SUCCESS);
if (csrLLCount(&pMac->scan.tempScanResults) > 0)
<API key>(pMac, <API key>, eSIR_SUCCESS,
eSIR_SUCCESS);
#endif
fRemoveCommand = csrScanComplete( pMac, pScanRsp );
fRet = eANI_BOOLEAN_TRUE;
}//if ( <API key> != pScanRsp->statusCode )
if(pfRemoveCommand)
{
*pfRemoveCommand = fRemoveCommand;
}
#ifdef <API key>
if (pMac->fScanOffload)
return fRet;
if (!csrLLIsListEmpty( &pMac->scan.scanCmdPendingList, LL_ACCESS_LOCK ))
{
/* Pending scan commands in the list because the previous scan command
* was split into a scan command on one channel + a scan command for all
* remaining channels.
*
* Start timer to trigger processing of the next scan command.
* NOTE for LFR:
* Do not split scans if no concurrent infra connections are
* active and if the scan is a BG scan triggered by LFR (OR)
* any scan if LFR is in the middle of a BG scan. Splitting
* the scan is delaying the time it takes for LFR to find
* candidates and resulting in disconnects.
*/
if ((<API key>(pMac) &&
#ifdef FEATURE_WLAN_LFR
(<API key>(pMac) ||
((pCommand->u.scanCmd.reason != eCsrScanBgScan) &&
(pNeighborRoamInfo->neighborRoamState !=
<API key>))) &&
#endif
(pCommand->u.scanCmd.u.scanRequest.p2pSearch != 1)) ||
(<API key>(pMac)))
{
/* if active connected sessions present then continue to split scan
* with specified interval between consecutive scans */
<API key>(pMac, pCommand->u.scanCmd.u.scanRequest.scanType, &(pCommand->u.scanCmd.u.scanRequest));
vos_timer_start(&pMac->scan.<API key>,
pCommand->u.scanCmd.u.scanRequest.restTime);
} else {
/* if no connected sessions present then initiate next scan command immediately */
/* minimum timer granularity is 10ms */
vos_timer_start(&pMac->scan.<API key>, 10);
}
}
#endif
return (fRet);
}
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tSmeCmd *pCommand )
{
tANI_U8 bssid[VOS_MAC_ADDR_SIZE] = {0, 0, 0, 0, 0, 0};
tANI_BOOLEAN f = vos_mem_compare(pCommand->u.scanCmd.u.scanRequest.bssid,
bssid, sizeof(tCsrBssid));
//It is not a wild card scan if the bssid is not broadcast and the number of SSID is 1.
return ((tANI_BOOLEAN)( (f || (0xff == pCommand->u.scanCmd.u.scanRequest.bssid[0])) &&
(pCommand->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs != 1) ));
}
#ifdef <API key>
eHalStatus <API key>(tpAniSirGlobal pMac, tSirSmeScanRsp *pScanRsp,
tANI_U8 sessionId)
{
tSirBssDescription *pSirBssDescription;
tANI_U32 cbScanResult = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription )
+ sizeof(tSirBssDescription); //We need at least one CB
tCsrScanResult *pScanResult = NULL;
tAniSSID tmpSsid;
v_TIME_t timer;
tANI_U32 cbParsed;
tANI_U32 cbBssDesc;
tANI_U16 ieLen;
if ((cbScanResult > pScanRsp->length ) ||
(( eSIR_SME_SUCCESS != pScanRsp->statusCode ) &&
( <API key> != pScanRsp->statusCode ) ) )
return eHAL_STATUS_FAILURE;
cbParsed = GET_FIELD_OFFSET( tSirSmeScanRsp, bssDescription );
pSirBssDescription = pScanRsp->bssDescription;
while( cbParsed < pScanRsp->length )
{
// Check whether we have reach out limit
if ( <API key>(pMac) )
{
smsLog( pMac, LOGW, FL( "BSS limit reached"));
return <API key>;
}
ieLen = (pSirBssDescription->length + sizeof( pSirBssDescription->length )
- GET_FIELD_OFFSET( tSirBssDescription, ieFields ));
pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + ieLen);
if (NULL == pScanResult)
{
smsLog(pMac, LOGE, FL(" Fail to allocate memory for frame"));
return <API key>;
}
vos_mem_set(pScanResult, sizeof(tCsrScanResult) + ieLen, 0);
if (!HAL_STATUS_SUCCESS(<API key>(pMac,
pSirBssDescription, (tDot11fBeaconIEs **)&pScanResult->Result.pvIes)))
{
smsLog(pMac, LOGE, FL(" Cannot parse IEs"));
<API key>(pMac, pScanResult);
return <API key>;
}
cbBssDesc = pSirBssDescription->length +
sizeof( pSirBssDescription->length );
vos_mem_copy(&pScanResult->Result.BssDescriptor, pSirBssDescription,
cbBssDesc);
// Remove duplicate entry
<API key>( pMac, &pScanResult->Result.BssDescriptor,
(tDot11fBeaconIEs *)pScanResult->Result.pvIes,
&tmpSsid , &timer, FALSE );
//Add to scan cache
csrScanAddResult(pMac, pScanResult,
(tDot11fBeaconIEs *)pScanResult->Result.pvIes,
sessionId);
// skip over the BSS description to the next one...
cbParsed += cbBssDesc;
pSirBssDescription = (tSirBssDescription *)((tANI_U8 *)pSirBssDescription +
cbBssDesc );
}
return eHAL_STATUS_SUCCESS;
}
#endif
eHalStatus <API key>( tpAniSirGlobal pMac, void *pMsgBuf )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tListElem *pEntry;
tSmeCmd *pCommand;
eCsrScanStatus scanStatus;
tSirSmeScanRsp *pScanRsp = (tSirSmeScanRsp *)pMsgBuf;
tSmeGetScanChnRsp *pScanChnInfo;
tANI_BOOLEAN fRemoveCommand = eANI_BOOLEAN_TRUE;
eCsrScanReason reason = eCsrScanOther;
if (pMac->fScanOffload)
pEntry = csrLLPeekHead(&pMac->sme.<API key>,
LL_ACCESS_LOCK);
else
pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK);
if ( pEntry )
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
if ( eSmeCommandScan == pCommand->command )
{
scanStatus = (eSIR_SME_SUCCESS == pScanRsp->statusCode) ? eCSR_SCAN_SUCCESS : eCSR_SCAN_FAILURE;
reason = pCommand->u.scanCmd.reason;
switch(pCommand->u.scanCmd.reason)
{
case eCsrScanAbortBgScan:
case <API key>:
case eCsrScanBGScanAbort:
case <API key>:
break;
case <API key>:
pScanChnInfo = (tSmeGetScanChnRsp *)pMsgBuf;
/*
* status code not available in tSmeGetScanChnRsp, so
* by default considering it to be success
*/
scanStatus = eSIR_SME_SUCCESS;
csrScanAgeResults(pMac, pScanChnInfo);
break;
case <API key>:
<API key>( pMac, pCommand, pScanRsp, &fRemoveCommand );
break;
case eCsrScanP2PFindPeer:
scanStatus = ((eSIR_SME_SUCCESS == pScanRsp->statusCode) && (pScanRsp->length > 50)) ? <API key> : eCSR_SCAN_FAILURE;
<API key>( pMac, pCommand, pScanRsp, NULL );
break;
case <API key>:
default:
if(<API key>( pMac, pCommand, pScanRsp, &fRemoveCommand ))
{
/*
* Not to get channel info if the scan is not a
* wild card scan because it may cause scan results got
* aged out incorrectly.
*/
if( <API key>( pMac, pCommand ) && (!pCommand->u.scanCmd.u.scanRequest.p2pSearch)
#ifdef <API key>
&& (pCommand->u.scanCmd.reason != <API key>)
#endif
)
{
//Get the list of channels scanned
if( pCommand->u.scanCmd.reason != eCsrScanUserRequest)
{
<API key>(pMac, pCommand->sessionId,
NULL, NULL,
pCommand->u.scanCmd.scanID);
}
else
{
<API key>(pMac,
pCommand->sessionId,
pCommand->u.scanCmd.pContext,
pCommand->u.scanCmd.callback,
pCommand->u.scanCmd.scanID);
pCommand->u.scanCmd.callback = NULL;
}
}
}
break;
}//switch
if(fRemoveCommand)
{
<API key>(pMac, pCommand, scanStatus);
}
<API key>( pMac );
}
#ifdef <API key>
else if (pMac->pnoOffload &&
!HAL_STATUS_SUCCESS(<API key>(pMac, pScanRsp,
pScanRsp->sessionId)))
{
smsLog( pMac, LOGE, "CSR: Unable to store scan results for PNO" );
status = eHAL_STATUS_FAILURE;
}
#endif
else
{
smsLog( pMac, LOGE, "CSR: Scan Completion called but SCAN command is not ACTIVE ..." );
status = eHAL_STATUS_FAILURE;
}
}
#ifdef <API key>
else if (pMac->pnoOffload &&
!HAL_STATUS_SUCCESS(<API key>(pMac, pScanRsp,
pScanRsp->sessionId)))
{
smsLog( pMac, LOGE, "CSR: Unable to store scan results for PNO" );
status = eHAL_STATUS_FAILURE;
}
#endif
else if (pMac->pnoOffload == FALSE)
{
smsLog( pMac, LOGE, "CSR: Scan Completion called but NO commands are ACTIVE ..." );
status = eHAL_STATUS_FAILURE;
}
return (status);
}
tCsrScanResultInfo *<API key>(tpAniSirGlobal pMac, tScanResultHandle hScanResult)
{
tListElem *pEntry;
tCsrScanResult *pResult;
tCsrScanResultInfo *pRet = NULL;
tScanResultList *pResultList = (tScanResultList *)hScanResult;
if(pResultList)
{
csrLLLock(&pResultList->List);
pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK);
if(pEntry)
{
pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link);
pRet = &pResult->Result;
}
pResultList->pCurEntry = pEntry;
csrLLUnlock(&pResultList->List);
}
return pRet;
}
tCsrScanResultInfo *<API key>(tpAniSirGlobal pMac, tScanResultHandle hScanResult)
{
tListElem *pEntry = NULL;
tCsrScanResult *pResult = NULL;
tCsrScanResultInfo *pRet = NULL;
tScanResultList *pResultList = (tScanResultList *)hScanResult;
if(pResultList)
{
csrLLLock(&pResultList->List);
if(NULL == pResultList->pCurEntry)
{
pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK);
}
else
{
pEntry = csrLLNext(&pResultList->List, pResultList->pCurEntry, LL_ACCESS_NOLOCK);
}
if(pEntry)
{
pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link);
pRet = &pResult->Result;
}
pResultList->pCurEntry = pEntry;
csrLLUnlock(&pResultList->List);
}
return pRet;
}
//This function moves the first BSS that matches the bssid to the head of the result
eHalStatus <API key>(tpAniSirGlobal pMac, tCsrBssid *bssid, tScanResultHandle hScanResult)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanResultList *pResultList = (tScanResultList *)hScanResult;
tCsrScanResult *pResult = NULL;
tListElem *pEntry = NULL;
if(pResultList && bssid)
{
csrLLLock(&pResultList->List);
pEntry = csrLLPeekHead(&pResultList->List, LL_ACCESS_NOLOCK);
while(pEntry)
{
pResult = GET_BASE_ADDR(pEntry, tCsrScanResult, Link);
if (vos_mem_compare(bssid, pResult->Result.BssDescriptor.bssId, sizeof(tCsrBssid)))
{
status = eHAL_STATUS_SUCCESS;
csrLLRemoveEntry(&pResultList->List, pEntry, LL_ACCESS_NOLOCK);
csrLLInsertHead(&pResultList->List, pEntry, LL_ACCESS_NOLOCK);
break;
}
pEntry = csrLLNext(&pResultList->List, pResultList->pCurEntry, LL_ACCESS_NOLOCK);
}
csrLLUnlock(&pResultList->List);
}
return (status);
}
//Remove the BSS if possible.
//Return -- TRUE == the BSS is remove. False == Fail to remove it
//This function is called when list lock is held. Be caution what functions it can call.
tANI_BOOLEAN csrScanAgeOutBss(tpAniSirGlobal pMac, tCsrScanResult *pResult)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
tANI_U32 i;
tCsrRoamSession *pSession;
tANI_BOOLEAN isConnBssfound = eANI_BOOLEAN_FALSE;
for( i = 0; i < <API key>; i++ )
{
if( <API key>( pMac, i ) )
{
pSession = CSR_GET_SESSION( pMac, i );
//Not to remove the BSS we are connected to.
if(<API key>(pMac, i) && (NULL != pSession->pConnectBssDesc) &&
(<API key>(pMac, &pResult->Result.BssDescriptor,
pSession->pConnectBssDesc, NULL, FALSE))
)
{
isConnBssfound = eANI_BOOLEAN_TRUE;
break;
}
}
}
if( isConnBssfound )
{
/* Reset the counter so that aging out of connected BSS won't
happen too soon */
pResult->AgingCount = (tANI_S32)pMac->roam.configParam.agingCount;
smsLog(pMac, LOGW,
FL(" Connected BSS, Set Aging Count=%d for BSS "MAC_ADDRESS_STR" "),
pResult->AgingCount,
MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId));
pResult->Result.BssDescriptor.nReceivedTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
return (fRet);
}
else
{
smsLog(pMac, LOGW, "Aging out BSS "MAC_ADDRESS_STR" Channel %d",
MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId),
pResult->Result.BssDescriptor.channelId);
//No need to hold the spin lock because caller should hold the lock for pMac->scan.scanResultList
if(csrLLRemoveEntry(&pMac->scan.scanResultList, &pResult->Link,
LL_ACCESS_NOLOCK))
{
if (<API key>(pMac,
(tCsrBssid *) pResult->Result.BssDescriptor.bssId,
(tCsrBssid *) pMac->scan.currentCountryBssid))
{
smsLog(pMac, LOGW, "Aging out 11d BSS "MAC_ADDRESS_STR,
MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId));
pMac->scan.currentCountryRSSI = -128;
}
<API key>(pMac, pResult);
fRet = eANI_BOOLEAN_TRUE;
}
}
return (fRet);
}
eHalStatus csrScanAgeResults(tpAniSirGlobal pMac, tSmeGetScanChnRsp *pScanChnInfo)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tListElem *pEntry, *tmpEntry;
tCsrScanResult *pResult;
tLimScanChn *pChnInfo;
tANI_U8 i;
csrLLLock(&pMac->scan.scanResultList);
for(i = 0; i < pScanChnInfo->numChn; i++)
{
pChnInfo = &pScanChnInfo->scanChn[i];
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while( pEntry )
{
tmpEntry = csrLLNext(&pMac->scan.scanResultList,
pEntry, LL_ACCESS_NOLOCK);
pResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
if(pResult->Result.BssDescriptor.channelId == pChnInfo->channelId)
{
if(pResult->AgingCount <= 0)
{
smsLog(pMac, LOGW, " age out due to ref count");
csrScanAgeOutBss(pMac, pResult);
}
else
{
pResult->AgingCount
smsLog(pMac, LOGW,
FL("Decremented AgingCount=%d for BSS "MAC_ADDRESS_STR""),
pResult->AgingCount,
MAC_ADDR_ARRAY(pResult->Result.BssDescriptor.bssId));
}
}
pEntry = tmpEntry;
}
}
csrLLUnlock(&pMac->scan.scanResultList);
return (status);
}
eHalStatus csrSendMBScanReq( tpAniSirGlobal pMac, tANI_U16 sessionId,
tCsrScanRequest *pScanReq, tScanReqParam *pScanReqParam )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirSmeScanReq *pMsg;
tANI_U16 msgLen;
tANI_U8 bssid[VOS_MAC_ADDR_SIZE] = {0, 0, 0, 0, 0, 0};
tSirScanType scanType = pScanReq->scanType;
tANI_U32 minChnTime; //in units of milliseconds
tANI_U32 maxChnTime; //in units of milliseconds
tANI_U32 i;
tANI_U8 selfMacAddr[VOS_MAC_ADDR_SIZE];
tANI_U8 *pSelfMac = NULL;
msgLen = (tANI_U16)(sizeof( tSirSmeScanReq ) - sizeof( pMsg->channelList.channelNumber ) +
( sizeof( pMsg->channelList.channelNumber ) * pScanReq->ChannelInfo.numOfChannels )) +
( pScanReq->uIEFieldLen ) ;
pMsg = vos_mem_malloc(msgLen);
if ( NULL == pMsg )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (HAL_STATUS_SUCCESS(status))
{
do
{
vos_mem_set(pMsg, msgLen, 0);
pMsg->messageType = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_REQ);
pMsg->length = pal_cpu_to_be16(msgLen);
//ToDO: Fill in session info when we need to do scan base on session.
if ((pMac->fScanOffload) && (sessionId != <API key>))
{
pMsg->sessionId = sessionId;
}
else
{
/* if sessionId == <API key>, then send the scan
request on first available session */
pMsg->sessionId = 0;
}
if (pMsg->sessionId >= <API key>)
smsLog( pMac, LOGE, FL(" Invalid Sme Session ID = %d"), pMsg->sessionId );
pMsg->transactionId = 0;
pMsg->dot11mode = (tANI_U8) <API key>(pMac, csrFindBestPhyMode( pMac, pMac->roam.configParam.phyMode ));
pMsg->bssType = pal_cpu_to_be32(<API key>(pScanReq->BSSType));
if ( <API key>( pMac, sessionId ) )
{
pSelfMac = (tANI_U8 *)&pMac->roam.roamSession[sessionId].selfMacAddr;
}
else
{
// Since we don't have session for the scanning, we find a valid session. In case we fail to
// do so, get the WNI_CFG_STA_ID
for( i = 0; i < <API key>; i++ )
{
if( <API key>( pMac, i ) )
{
pSelfMac = (tANI_U8 *)&pMac->roam.roamSession[i].selfMacAddr;
break;
}
}
if( <API key> == i )
{
tANI_U32 len = VOS_MAC_ADDR_SIZE;
pSelfMac = selfMacAddr;
status = ccmCfgGetStr( pMac, WNI_CFG_STA_ID, pSelfMac, &len );
if( !HAL_STATUS_SUCCESS( status ) ||
( len < VOS_MAC_ADDR_SIZE ) )
{
smsLog( pMac, LOGE, FL(" Can not get self MAC address from CFG status = %d"), status );
//Force failed status
status = eHAL_STATUS_FAILURE;
break;
}
}
}
vos_mem_copy((tANI_U8 *)pMsg->selfMacAddr, pSelfMac, sizeof(tSirMacAddr));
//sirCopyMacAddr
vos_mem_copy((tANI_U8 *)pMsg->bssId, (tANI_U8 *)&pScanReq->bssid, sizeof(tSirMacAddr));
if ( vos_mem_compare(pScanReq->bssid, bssid, sizeof(tCsrBssid)))
{
vos_mem_set(pMsg->bssId, sizeof(tSirMacAddr), 0xff);
}
else
{
vos_mem_copy(pMsg->bssId, pScanReq->bssid, VOS_MAC_ADDR_SIZE);
}
minChnTime = pScanReq->minChnTime;
maxChnTime = pScanReq->maxChnTime;
//Verify the scan type first, if the scan is active scan, we need to make sure we
//are allowed to do so.
/* if 11d is enabled & we don't see any beacon around, scan type falls
back to passive. But in BT AMP STA mode we need to send out a
directed probe*/
if( (eSIR_PASSIVE_SCAN != scanType) && (<API key> != pScanReq->requestType)
&& (<API key> != pScanReq->BSSType)
&& (eANI_BOOLEAN_FALSE == pMac->scan.fEnableBypass11d))
{
scanType = pMac->scan.curScanType;
if(eSIR_PASSIVE_SCAN == pMac->scan.curScanType)
{
if(minChnTime < pMac->roam.configParam.nPassiveMinChnTime)
{
minChnTime = pMac->roam.configParam.nPassiveMinChnTime;
}
if(maxChnTime < pMac->roam.configParam.nPassiveMaxChnTime)
{
maxChnTime = pMac->roam.configParam.nPassiveMaxChnTime;
}
}
}
pMsg->scanType = pal_cpu_to_be32(scanType);
pMsg->numSsid =
(pScanReq->SSIDs.numOfSSIDs < <API key>) ?
pScanReq->SSIDs.numOfSSIDs : <API key>;
if((pScanReq->SSIDs.numOfSSIDs != 0) && ( eSIR_PASSIVE_SCAN != scanType ))
{
for (i = 0; i < pMsg->numSsid; i++)
{
vos_mem_copy(&pMsg->ssId[i],
&pScanReq->SSIDs.SSIDList[i].SSID, sizeof(tSirMacSSid));
}
}
else
{
//Otherwise we scan all SSID and let the result filter later
for (i = 0; i < <API key>; i++)
{
pMsg->ssId[i].length = 0;
}
}
pMsg->minChannelTime = pal_cpu_to_be32(minChnTime);
pMsg->maxChannelTime = pal_cpu_to_be32(maxChnTime);
pMsg->minChannelTimeBtc = pMac->roam.configParam.<API key>;
pMsg->maxChannelTimeBtc = pMac->roam.configParam.<API key>;
//hidden SSID option
pMsg->hiddenSsid = pScanReqParam->hiddenSsid;
/* maximum rest time */
pMsg->restTime = pScanReq->restTime;
/* Minimum rest time */
pMsg->min_rest_time = pScanReq->min_rest_time;
/* Idle time */
pMsg->idle_time = pScanReq->idle_time;
pMsg-><API key> = pScanReqParam-><API key>;
// All the scan results caching will be done by Roaming
// We do not want LIM to do any caching of scan results,
// so delete the LIM cache on all scan requests
pMsg->returnFreshResults = pScanReqParam->freshScan;
//Always ask for unique result
pMsg->returnUniqueResults = pScanReqParam->fUniqueResult;
pMsg->channelList.numChannels = (tANI_U8)pScanReq->ChannelInfo.numOfChannels;
if(pScanReq->ChannelInfo.numOfChannels)
{
//Assuming the channelNumber is tANI_U8 (1 byte)
vos_mem_copy(pMsg->channelList.channelNumber,
pScanReq->ChannelInfo.ChannelList,
pScanReq->ChannelInfo.numOfChannels);
}
pMsg->uIEFieldLen = (tANI_U16) pScanReq->uIEFieldLen;
pMsg->uIEFieldOffset = (tANI_U16)(sizeof( tSirSmeScanReq ) - sizeof( pMsg->channelList.channelNumber ) +
( sizeof( pMsg->channelList.channelNumber ) * pScanReq->ChannelInfo.numOfChannels )) ;
if(pScanReq->uIEFieldLen != 0)
{
vos_mem_copy((tANI_U8 *)pMsg+pMsg->uIEFieldOffset, pScanReq->pIEField,
pScanReq->uIEFieldLen);
}
pMsg->p2pSearch = pScanReq->p2pSearch;
if (pScanReq->requestType == <API key>)
{
pMsg->backgroundScanMode = eSIR_ROAMING_SCAN;
}
}while(0);
smsLog(pMac, LOG1, FL("domainIdCurrent %s (%d) scanType %s (%d)"
"bssType %s (%d), requestType %s(%d)"
"numChannels %d"),
<API key>(pMac->scan.domainIdCurrent),
pMac->scan.domainIdCurrent,
<API key>(pMsg->scanType), pMsg->scanType,
lim_BssTypetoString(pMsg->bssType), pMsg->bssType,
<API key>(pScanReq->requestType),
pScanReq->requestType,
pMsg->channelList.numChannels);
for(i = 0; i < pMsg->channelList.numChannels; i++)
{
smsLog(pMac, LOG1, FL("channelNumber[%d]= %d"), i, pMsg->channelList.channelNumber[i]);
}
if(HAL_STATUS_SUCCESS(status))
{
status = palSendMBMessage(pMac->hHdd, pMsg);
}
else
{
smsLog( pMac, LOGE, FL(" failed to send down scan req with status = %d"), status );
vos_mem_free(pMsg);
}
}//Success allocated memory
else
{
smsLog( pMac, LOGE, FL(" memory allocation failure"));
}
if(!HAL_STATUS_SUCCESS(status))
{
smsLog( pMac, LOG1, FL("Failed: SId: %d FirstMatch = %d"
" UniqueResult = %d freshScan = %d hiddenSsid = %d"),
sessionId, pScanReqParam-><API key>,
pScanReqParam->fUniqueResult, pScanReqParam->freshScan,
pScanReqParam->hiddenSsid );
smsLog( pMac, LOG1, FL("scanType = %s (%d) BSSType = %s (%d) "
"numOfSSIDs = %d numOfChannels = %d requestType = %s (%d)"
" p2pSearch = %d\n"),
<API key>(pScanReq->scanType),
pScanReq->scanType,
lim_BssTypetoString(pScanReq->BSSType),
pScanReq->BSSType,
pScanReq->SSIDs.numOfSSIDs,
pScanReq->ChannelInfo.numOfChannels,
<API key>(pScanReq->requestType),
pScanReq->requestType,
pScanReq->p2pSearch );
}
return( status );
}
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U32 sessionId, tScanReqParam *pScanReqParam )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirSmeScanReq *pMsg;
tANI_U16 msgLen;
msgLen = (tANI_U16)(sizeof( tSirSmeScanReq ));
pMsg = vos_mem_malloc(msgLen);
if ( NULL == pMsg )
status = eHAL_STATUS_FAILURE;
else
{
vos_mem_set(pMsg, msgLen, 0);
pMsg->messageType = pal_cpu_to_be16((tANI_U16)eWNI_SME_SCAN_REQ);
pMsg->length = pal_cpu_to_be16(msgLen);
pMsg->sessionId = sessionId;
pMsg->transactionId = 0;
pMsg->returnFreshResults = pScanReqParam->freshScan;
//Always ask for unique result
pMsg->returnUniqueResults = pScanReqParam->fUniqueResult;
pMsg-><API key> = pScanReqParam-><API key>;
status = palSendMBMessage(pMac->hHdd, pMsg);
if (!HAL_STATUS_SUCCESS(status))
{
smsLog( pMac, LOGE, FL(" failed to send down scan req with status = %d\n"), status );
}
}
return( status );
}
eHalStatus csrScanChannels( tpAniSirGlobal pMac, tSmeCmd *pCommand )
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanReqParam scanReq;
do
{
/*
* Don't delete cached results. Rome rssi based scan candidates
* may land up in scan cache instead of LFR cache.
* They will be deleted upon query.
*/
scanReq.freshScan = <API key>;
scanReq.fUniqueResult = TRUE;
scanReq.hiddenSsid = <API key>;
if(eCsrScanForSsid == pCommand->u.scanCmd.reason)
{
scanReq.<API key> = <API key>;
}
else
{
// Basically do scan on all channels even for 11D 1st scan case.
scanReq.<API key> = <API key>;
}
if((eCsrScanBgScan == pCommand->u.scanCmd.reason)||
(eCsrScanProbeBss == pCommand->u.scanCmd.reason))
{
scanReq.hiddenSsid = <API key>;
}
#ifdef <API key>
{
<API key> *pScanLog = NULL;
<API key>(pScanLog, <API key>, LOG_WLAN_SCAN_C);
if(pScanLog)
{
if(eCsrScanBgScan == pCommand->u.scanCmd.reason ||
eCsrScanProbeBss == pCommand->u.scanCmd.reason)
{
pScanLog->eventId = <API key>;
}
else
{
if( (eSIR_PASSIVE_SCAN != pCommand->u.scanCmd.u.scanRequest.scanType) &&
(eSIR_PASSIVE_SCAN != pMac->scan.curScanType) )
{
pScanLog->eventId = <API key>;
}
else
{
pScanLog->eventId = <API key>;
}
}
pScanLog->minChnTime = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.minChnTime;
pScanLog->maxChnTime = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.maxChnTime;
pScanLog->numChannel = (v_U8_t)pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels;
if(pScanLog->numChannel && (pScanLog->numChannel < <API key>))
{
vos_mem_copy(pScanLog->channels,
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList,
pScanLog->numChannel);
}
<API key>(pScanLog);
}
}
#endif //#ifdef <API key>
<API key>(pMac);
status = csrSendMBScanReq(pMac, pCommand->sessionId,
&pCommand->u.scanCmd.u.scanRequest, &scanReq);
}while(0);
return( status );
}
eHalStatus <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
eHalStatus status = eHAL_STATUS_FAILURE;
tScanReqParam scanReq;
do
{
#ifdef <API key>
if (<API key> == pCommand->u.scanCmd.reason)
{
//to get the LFR candidates from PE cache
scanReq.freshScan = <API key>|<API key>;
scanReq.fUniqueResult = TRUE;
scanReq.<API key> = <API key>;
}
else
#endif
{
//not a fresh scan
scanReq.freshScan = <API key>;
scanReq.fUniqueResult = TRUE;
scanReq.<API key> = <API key>;
}
status = <API key>(pMac, pCommand->sessionId, &scanReq);
}while(0);
return (status);
}
eHalStatus <API key>( tpAniSirGlobal pMac, tSmeCmd *pCommand )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tCsrChannelInfo newChannelInfo = {0, NULL};
int i, j;
tANI_U8 *pChannel = NULL;
tANI_U32 len = 0;
// Transition to Scanning state...
if (!pMac->fScanOffload)
{
for( i = 0; i < <API key>; i++ )
{
pCommand->u.scanCmd.lastRoamState[i] =
csrRoamStateChange( pMac, <API key>, i);
smsLog( pMac, LOG3, "starting SCAN command from %d state...."
" reason is %d", pCommand->u.scanCmd.lastRoamState[i],
pCommand->u.scanCmd.reason );
}
}
else
{
pCommand->u.scanCmd.lastRoamState[pCommand->sessionId] =
csrRoamStateChange(pMac, <API key>,
pCommand->sessionId);
smsLog( pMac, LOG3,
"starting SCAN command from %d state.... reason is %d",
pCommand->u.scanCmd.lastRoamState[pCommand->sessionId],
pCommand->u.scanCmd.reason );
}
switch(pCommand->u.scanCmd.reason)
{
#ifdef <API key>
case <API key>:
#endif
case eCsrScanGetResult:
case <API key>: //For cap change, LIM already save BSS description
status = <API key>(pMac, pCommand);
break;
case <API key>:
status = <API key>(pMac, pCommand);
break;
case eCsrScanBGScanAbort:
status = <API key>(pMac, 0);
break;
case <API key>:
status = <API key>(pMac, pMac->roam.configParam.bgScanInterval);
break;
case <API key>:
status = <API key>(pMac, pCommand->sessionId);
break;
case eCsrScanUserRequest:
if(pMac->roam.configParam.fScanTwice)
{
//We scan 2.4 channel twice
if(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels &&
(NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList))
{
len = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels;
/* Allocate twice the channel */
newChannelInfo.ChannelList = vos_mem_malloc(len * 2);
pChannel = pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList;
}
else
{
//get the valid channel list to scan all.
len = sizeof(pMac->roam.validChannelList);
if (HAL_STATUS_SUCCESS(<API key>(pMac, (tANI_U8 *)pMac->roam.validChannelList, &len)))
{
//allocate twice the channel
newChannelInfo.ChannelList = (tANI_U8 *)vos_mem_malloc(len * 2);
pChannel = pMac->roam.validChannelList;
}
}
if(NULL == newChannelInfo.ChannelList)
{
newChannelInfo.numOfChannels = 0;
}
else
{
j = 0;
for(i = 0; i < len; i++)
{
newChannelInfo.ChannelList[j++] = pChannel[i];
if(<API key> >= pChannel[i])
{
newChannelInfo.ChannelList[j++] = pChannel[i];
}
}
if(NULL != pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList)
{
//pChannel points to the channellist from the command, free it.
vos_mem_free(pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList);
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = NULL;
}
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = j;
pCommand->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = newChannelInfo.ChannelList;
}
} //if(pMac->roam.configParam.fScanTwice)
status = csrScanChannels(pMac, pCommand);
break;
default:
status = csrScanChannels(pMac, pCommand);
break;
}
if(!HAL_STATUS_SUCCESS(status))
{
<API key>(pMac, pCommand, eCSR_SCAN_FAILURE);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tCsrBGScanRequest *pScanReq)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pCommand = NULL;
if(pScanReq)
{
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->u.scanCmd.reason = <API key>;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
vos_mem_copy(&pCommand->u.scanCmd.u.bgScanRequest, pScanReq, sizeof(tCsrBGScanRequest));
//we have to do the follow
if(pScanReq->ChannelInfo.numOfChannels == 0)
{
pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList = NULL;
}
else
{
pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList
= vos_mem_malloc(pScanReq->ChannelInfo.numOfChannels);
if ( NULL != pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList )
{
vos_mem_copy(pCommand->u.scanCmd.u.bgScanRequest.ChannelInfo.ChannelList,
pScanReq->ChannelInfo.ChannelList,
pScanReq->ChannelInfo.numOfChannels);
}
else
{
smsLog(pMac, LOGE, FL("ran out of memory"));
<API key>(pMac, pCommand);
return eHAL_STATUS_FAILURE;
}
}
//scan req for SSID
if(pScanReq->SSID.length)
{
vos_mem_copy(pCommand->u.scanCmd.u.bgScanRequest.SSID.ssId,
pScanReq->SSID.ssId, pScanReq->SSID.length);
pCommand->u.scanCmd.u.bgScanRequest.SSID.length = pScanReq->SSID.length;
}
pCommand->u.scanCmd.u.bgScanRequest.maxChnTime= pScanReq->maxChnTime;
pCommand->u.scanCmd.u.bgScanRequest.minChnTime = pScanReq->minChnTime;
pCommand->u.scanCmd.u.bgScanRequest.scanInterval = pScanReq->scanInterval;
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
<API key>( pMac, pCommand );
break;
}
}while(0);
}
return (status);
}
eHalStatus csrScanBGScanAbort( tpAniSirGlobal pMac )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pCommand = NULL;
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->u.scanCmd.reason = eCsrScanBGScanAbort;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
<API key>( pMac, pCommand );
break;
}
}while(0);
return (status);
}
//This will enable the background scan with the non-zero interval
eHalStatus csrScanBGScanEnable(tpAniSirGlobal pMac)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSmeCmd *pCommand = NULL;
if(pMac->roam.configParam.bgScanInterval)
{
do
{
pCommand = csrGetCommandBuffer(pMac);
if(!pCommand)
{
status = <API key>;
break;
}
vos_mem_set(&pCommand->u.scanCmd, sizeof(tScanCmd), 0);
pCommand->command = eSmeCommandScan;
pCommand->u.scanCmd.reason = <API key>;
pCommand->u.scanCmd.callback = NULL;
pCommand->u.scanCmd.pContext = NULL;
status = csrQueueSmeCommand(pMac, pCommand, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
<API key>( pMac, pCommand );
break;
}
}while(0);
}
else
{
smsLog(pMac, LOGE, FL("cannot continue because the bgscan interval is 0"));
status = <API key>;
}
return (status);
}
eHalStatus csrScanCopyRequest(tpAniSirGlobal pMac, tCsrScanRequest *pDstReq, tCsrScanRequest *pSrcReq)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tANI_U32 len = sizeof(pMac->roam.validChannelList);
tANI_U32 index = 0;
tANI_U32 new_index = 0;
<API key> NVchannel_state;
bool skip_dfs_chnl = pMac->roam.configParam.<API key> ||
!pMac->scan.fEnableDFSChnlScan;
do
{
status = csrScanFreeRequest(pMac, pDstReq);
if(HAL_STATUS_SUCCESS(status))
{
vos_mem_copy(pDstReq, pSrcReq, sizeof(tCsrScanRequest));
/* Re-initialize the pointers to NULL since we did a copy */
pDstReq->pIEField = NULL;
pDstReq->ChannelInfo.ChannelList = NULL;
pDstReq->SSIDs.SSIDList = NULL;
if(pSrcReq->uIEFieldLen == 0)
{
pDstReq->pIEField = NULL;
}
else
{
pDstReq->pIEField = vos_mem_malloc(pSrcReq->uIEFieldLen);
if ( NULL == pDstReq->pIEField )
{
status = eHAL_STATUS_FAILURE;
smsLog(pMac, LOGE, FL("No memory for scanning IE fields"));
break;
}
else
{
status = eHAL_STATUS_SUCCESS;
vos_mem_copy(pDstReq->pIEField, pSrcReq->pIEField,
pSrcReq->uIEFieldLen);
pDstReq->uIEFieldLen = pSrcReq->uIEFieldLen;
}
}//Allocate memory for IE field
{
if(pSrcReq->ChannelInfo.numOfChannels == 0)
{
pDstReq->ChannelInfo.ChannelList = NULL;
pDstReq->ChannelInfo.numOfChannels = 0;
}
else
{
pDstReq->ChannelInfo.ChannelList = vos_mem_malloc(
pSrcReq->ChannelInfo.numOfChannels
* sizeof(*pDstReq->ChannelInfo.ChannelList));
if ( NULL == pDstReq->ChannelInfo.ChannelList )
{ status = eHAL_STATUS_FAILURE;
pDstReq->ChannelInfo.numOfChannels = 0;
smsLog(pMac, LOGE, FL("No memory for scanning Channel"
" List"));
break;
}
if((pSrcReq->scanType == eSIR_PASSIVE_SCAN) && (pSrcReq->requestType == <API key>))
{
for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ )
{
NVchannel_state = <API key>(
pSrcReq->ChannelInfo.ChannelList[index]);
if (pSrcReq->ChannelInfo.ChannelList[index] < MIN_11P_CHANNEL &&
((NV_CHANNEL_ENABLE == NVchannel_state) ||
((NV_CHANNEL_DFS == NVchannel_state) &&
!skip_dfs_chnl)))
{
pDstReq->ChannelInfo.ChannelList[new_index] =
pSrcReq->ChannelInfo.ChannelList[index];
new_index++;
}
}
pDstReq->ChannelInfo.numOfChannels = new_index;
}
else if(HAL_STATUS_SUCCESS(<API key>(pMac, pMac->roam.validChannelList, &len)))
{
new_index = 0;
pMac->roam.numValidChannels = len;
for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ )
{
/* Allow scan on valid channels only.
* If it is p2p scan and valid channel list doesnt contain
* social channels, enforce scan on social channels because
* that is the only way to find p2p peers.
* This can happen only if band is set to 5Ghz mode.
*/
if(pSrcReq->ChannelInfo.ChannelList[index] < MIN_11P_CHANNEL &&
((<API key>(pMac, pSrcReq->ChannelInfo.ChannelList[index])) ||
((<API key> == pSrcReq->requestType) &&
<API key>(pSrcReq->ChannelInfo.ChannelList[index]))))
{
if( ((pSrcReq-><API key> ||
skip_dfs_chnl) &&
(NV_CHANNEL_DFS == <API key>(pSrcReq->ChannelInfo.ChannelList[index])) )
#ifdef FEATURE_WLAN_LFR
/*
* If LFR is requesting a contiguous scan
* (i.e. numOfChannels > 1), then ignore
* DFS channels.
* TODO: <API key> is returning
* 120, 124 and 128 as non-DFS channels. Hence, the
* use of direct check for channels below.
*/
|| ((<API key> == pSrcReq->requestType) &&
(pSrcReq->ChannelInfo.numOfChannels > 1) &&
(CSR_IS_CHANNEL_DFS(pSrcReq->ChannelInfo.ChannelList[index])) &&
!pMac->roam.configParam.allowDFSChannelRoam )
#endif
)
{
#ifdef FEATURE_WLAN_LFR
smsLog(pMac, LOG2,
FL(" reqType= %s (%d), numOfChannels=%d,"
" ignoring DFS channel %d"),
<API key>(pSrcReq->requestType),
pSrcReq->requestType,
pSrcReq->ChannelInfo.numOfChannels,
pSrcReq->ChannelInfo.ChannelList[index]);
#endif
continue;
}
pDstReq->ChannelInfo.ChannelList[new_index] =
pSrcReq->ChannelInfo.ChannelList[index];
new_index++;
}
}
pDstReq->ChannelInfo.numOfChannels = new_index;
#ifdef FEATURE_WLAN_LFR
if ((<API key> == pSrcReq->requestType) &&
(0 == pDstReq->ChannelInfo.numOfChannels))
{
/*
* No valid channels found in the request.
* Only perform scan on the channels passed
* pSrcReq if it is a <API key>.
* Passing 0 to LIM will trigger a scan on
* all valid channels which is not desirable.
*/
smsLog(pMac, LOGE, FL(" no valid channels found"
" (request=%d)"), pSrcReq->requestType);
for ( index = 0; index < pSrcReq->ChannelInfo.numOfChannels ; index++ )
{
smsLog(pMac, LOGE, FL("pSrcReq index=%d"
" channel=%d"), index,
pSrcReq->ChannelInfo.ChannelList[index]);
}
status = eHAL_STATUS_FAILURE;
break;
}
#endif
}
else
{
smsLog(pMac, LOGE, FL("Couldn't get the valid Channel"
" List, keeping requester's list"));
new_index = 0;
for ( index = 0;
index < pSrcReq->ChannelInfo.numOfChannels;
index++ )
{
if (pSrcReq->ChannelInfo.ChannelList[index] <
MIN_11P_CHANNEL)
{
pDstReq->ChannelInfo.ChannelList[new_index] =
pSrcReq->ChannelInfo.ChannelList[index];
new_index++;
}
}
pDstReq->ChannelInfo.numOfChannels = new_index;
}
}//Allocate memory for Channel List
}
if(pSrcReq->SSIDs.numOfSSIDs == 0)
{
pDstReq->SSIDs.numOfSSIDs = 0;
pDstReq->SSIDs.SSIDList = NULL;
}
else
{
pDstReq->SSIDs.SSIDList = vos_mem_malloc(
pSrcReq->SSIDs.numOfSSIDs * sizeof(*pDstReq->SSIDs.SSIDList));
if ( NULL == pDstReq->SSIDs.SSIDList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (HAL_STATUS_SUCCESS(status))
{
pDstReq->SSIDs.numOfSSIDs = pSrcReq->SSIDs.numOfSSIDs;
vos_mem_copy(pDstReq->SSIDs.SSIDList,
pSrcReq->SSIDs.SSIDList,
pSrcReq->SSIDs.numOfSSIDs * sizeof(*pDstReq->SSIDs.SSIDList));
}
else
{
pDstReq->SSIDs.numOfSSIDs = 0;
smsLog(pMac, LOGE, FL("No memory for scanning SSID List"));
break;
}
}//Allocate memory for SSID List
pDstReq->p2pSearch = pSrcReq->p2pSearch;
pDstReq-><API key> = pSrcReq-><API key>;
}
}while(0);
if(!HAL_STATUS_SUCCESS(status))
{
csrScanFreeRequest(pMac, pDstReq);
}
return (status);
}
eHalStatus csrScanFreeRequest(tpAniSirGlobal pMac, tCsrScanRequest *pReq)
{
if(pReq->ChannelInfo.ChannelList)
{
vos_mem_free(pReq->ChannelInfo.ChannelList);
pReq->ChannelInfo.ChannelList = NULL;
}
pReq->ChannelInfo.numOfChannels = 0;
if(pReq->pIEField)
{
vos_mem_free(pReq->pIEField);
pReq->pIEField = NULL;
}
pReq->uIEFieldLen = 0;
if(pReq->SSIDs.SSIDList)
{
vos_mem_free(pReq->SSIDs.SSIDList);
pReq->SSIDs.SSIDList = NULL;
}
pReq->SSIDs.numOfSSIDs = 0;
return eHAL_STATUS_SUCCESS;
}
void csrScanCallCallback(tpAniSirGlobal pMac, tSmeCmd *pCommand, eCsrScanStatus scanStatus)
{
if(pCommand->u.scanCmd.callback)
{
pCommand->u.scanCmd.callback(pMac, pCommand->u.scanCmd.pContext,
pCommand->sessionId,
pCommand->u.scanCmd.scanID, scanStatus);
} else {
smsLog( pMac, LOG2, "%s:%d - Callback NULL!!!", __func__, __LINE__);
}
}
void csrScanStopTimers(tpAniSirGlobal pMac)
{
<API key>(pMac);
<API key>(pMac);
if(0 != pMac->scan.<API key> )
{
<API key>(pMac);
}
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
eHalStatus status;
if(pMac->scan.fScanEnable)
{
status = vos_timer_start(&pMac->scan.hTimerGetResult, <API key>/<API key>);
}
else
{
status = eHAL_STATUS_FAILURE;
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
return (vos_timer_stop(&pMac->scan.hTimerGetResult));
}
void <API key>(void *pv)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pv );
<API key>(pMac);
vos_timer_start(&pMac->scan.hTimerGetResult, <API key>/<API key>);
}
#ifdef <API key>
static void <API key>(void *pv)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pv );
tListElem *pEntry;
tSmeCmd *pScanCmd;
tANI_U32 sessionId = <API key>;
csrLLLock(&pMac->scan.scanCmdPendingList);
if ( NULL != ( pEntry = csrLLPeekHead( &pMac->scan.scanCmdPendingList, LL_ACCESS_NOLOCK) ) )
{
tCsrScanRequest scanReq;
tSmeCmd *pSendScanCmd = NULL;
tANI_U8 numChn = 0;
tANI_U8 <API key> = 0;
tANI_U8 i, j;
tCsrChannelInfo *pChnInfo = &scanReq.ChannelInfo;
tANI_U8 channelToScan[<API key>];
eHalStatus status;
pScanCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
numChn = pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels;
sessionId = pScanCmd->sessionId;
/* if any session is connected and the number of channels to scan is
* greater than 1 then split the scan into multiple scan operations
* on each individual channel else continue to perform scan on all
* specified channels */
/* split scan if number of channels to scan is greater than 1 and
* any one of the following:
* - STA session is connected and the scan is not a P2P search
* - any P2P session is connected
* Do not split scans if no concurrent infra connections are
* active and if the scan is a BG scan triggered by LFR (OR)
* any scan if LFR is in the middle of a BG scan. Splitting
* the scan is delaying the time it takes for LFR to find
* candidates and resulting in disconnects.
*/
if((<API key>(pMac) &&
!<API key>(pMac)))
{
<API key> = pMac->roam.configParam.<API key>;
}
else if(<API key>(pMac))
{
<API key> = pMac->roam.configParam.<API key>;
}
if ( (numChn > <API key>) &&
((<API key>(pMac) &&
#ifdef FEATURE_WLAN_LFR
(<API key>(pMac) ||
((pScanCmd->u.scanCmd.reason != eCsrScanBgScan) &&
(pMac->roam.neighborRoamInfo[sessionId].neighborRoamState !=
<API key>))) &&
#endif
(pScanCmd->u.scanCmd.u.scanRequest.p2pSearch != 1)) ||
(<API key>(pMac))))
{
vos_mem_set(&scanReq, sizeof(tCsrScanRequest), 0);
pSendScanCmd = csrGetCommandBuffer(pMac); //optimize this to use 2 command buffer only
if (!pSendScanCmd)
{
smsLog( pMac, LOGE, FL(" Failed to get Queue command buffer") );
csrLLUnlock(&pMac->scan.scanCmdPendingList);
return;
}
pSendScanCmd->command = pScanCmd->command;
pSendScanCmd->sessionId = pScanCmd->sessionId;
pSendScanCmd->u.scanCmd.callback = NULL;
pSendScanCmd->u.scanCmd.pContext = pScanCmd->u.scanCmd.pContext;
pSendScanCmd->u.scanCmd.reason = pScanCmd->u.scanCmd.reason;
pSendScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around
/* First copy all the parameters to local variable of scan request */
csrScanCopyRequest(pMac, &scanReq, &pScanCmd->u.scanCmd.u.scanRequest);
/* Now modify the elements of local var scan request required to be modified for split scan */
if(scanReq.ChannelInfo.ChannelList != NULL)
{
vos_mem_free(scanReq.ChannelInfo.ChannelList);
scanReq.ChannelInfo.ChannelList = NULL;
}
pChnInfo->numOfChannels = <API key>;
vos_mem_copy(&channelToScan[0],
&pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[0],
pChnInfo->numOfChannels * sizeof(tANI_U8));//just send one channel
pChnInfo->ChannelList = &channelToScan[0];
for (i = 0, j = <API key>; i < (<API key>); i++, j++)
{
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[i] =
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[j]; //Move all the channels one step
}
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = numChn - <API key>; //reduce outstanding # of channels to be scanned
scanReq.BSSType = eCSR_BSS_TYPE_ANY;
//Use concurrency values for min/maxChnTime.
<API key>(pMac, scanReq.scanType, &scanReq);
status = csrScanCopyRequest(pMac, &pSendScanCmd->u.scanCmd.u.scanRequest, &scanReq);
if(!HAL_STATUS_SUCCESS(status))
{
smsLog( pMac, LOGE, FL(" Failed to get copy csrScanRequest = %d"), status );
csrLLUnlock(&pMac->scan.scanCmdPendingList);
return;
}
/* Clean the local scan variable */
scanReq.ChannelInfo.ChannelList = NULL;
scanReq.ChannelInfo.numOfChannels = 0;
csrScanFreeRequest(pMac, &scanReq);
}
else
{
/* no active connected session present or numChn == 1
* scan all remaining channels */
pSendScanCmd = pScanCmd;
//remove this command from pending list
if (csrLLRemoveHead( &pMac->scan.scanCmdPendingList, LL_ACCESS_NOLOCK) == NULL)
{ //In case between PeekHead and here, the entry got removed by another thread.
smsLog( pMac, LOGE, FL(" Failed to remove entry from scanCmdPendingList"));
}
}
csrQueueSmeCommand(pMac, pSendScanCmd, eANI_BOOLEAN_FALSE);
}
csrLLUnlock(&pMac->scan.scanCmdPendingList);
}
#endif
eHalStatus <API key>(tpAniSirGlobal pMac)
{
eHalStatus status = eHAL_STATUS_FAILURE;
if(pMac->scan.fScanEnable)
{
status = vos_timer_start(&pMac->scan.<API key>, <API key>/<API key>);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
return (vos_timer_stop(&pMac->scan.<API key>));
}
static void <API key>(void *pv)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pv );
tListElem *pEntry, *tmpEntry;
tCsrScanResult *pResult;
tANI_TIMESTAMP ageOutTime = pMac->scan.<API key> * <API key>;
tANI_TIMESTAMP curTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
csrLLLock(&pMac->scan.scanResultList);
pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_NOLOCK );
while( pEntry )
{
tmpEntry = csrLLNext(&pMac->scan.scanResultList, pEntry,
LL_ACCESS_NOLOCK);
pResult = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
if((curTime - pResult->Result.BssDescriptor.nReceivedTime) > ageOutTime)
{
smsLog(pMac, LOGW, " age out due to time out");
csrScanAgeOutBss(pMac, pResult);
}
pEntry = tmpEntry;
}
csrLLUnlock(&pMac->scan.scanResultList);
if (pEntry)
vos_timer_start(&pMac->scan.<API key>,
<API key>/<API key>);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 interval)
{
eHalStatus status;
smsLog(pMac, LOG1, " <API key>");
if((pMac->scan.fScanEnable) && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) && interval)
{
pMac->scan.nIdleScanTimeGap += interval;
vos_timer_stop(&pMac->scan.hTimerIdleScan);
status = vos_timer_start(&pMac->scan.hTimerIdleScan, interval/<API key>);
if( !HAL_STATUS_SUCCESS(status) )
{
smsLog(pMac, LOGE, " Fail to start Idle scan timer. status = %d interval = %d", status, interval);
//This should not happen but set the flag to restart when ready
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
}
}
else
{
if( pMac->scan.fScanEnable && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) )
{
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
}
status = eHAL_STATUS_FAILURE;
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
return (vos_timer_stop(&pMac->scan.hTimerIdleScan));
}
//Stop CSR from asking for IMPS, This function doesn't disable IMPS from CSR
void csrScanSuspendIMPS( tpAniSirGlobal pMac )
{
<API key>(pMac);
}
//Start CSR from asking for IMPS. This function doesn't trigger CSR to request entering IMPS
//because IMPS maybe disabled.
void csrScanResumeIMPS( tpAniSirGlobal pMac )
{
<API key>( pMac );
}
void csrScanIMPSCallback(void *callbackContext, eHalStatus status)
{
tpAniSirGlobal pMac = PMAC_STRUCT( callbackContext );
if(eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan)
{
if(pMac->roam.configParam.IsIdleScanEnabled)
{
if(HAL_STATUS_SUCCESS(status))
{
if(<API key>(pMac) && !<API key>(pMac))
{
smsLog(pMac, LOGW, FL("starts idle mode full scan"));
csrScanAllChannels(pMac, <API key>);
}
else
{
smsLog(pMac, LOGW, FL("cannot start idle mode full scan"));
//even though we are in timer handle, calling stop timer will make sure the timer
//doesn't get to restart.
<API key>(pMac);
}
}
else
{
smsLog(pMac, LOGE, FL("sees not success status (%d)"), status);
}
}
else
{//we might need another flag to check if CSR needs to request imps at all
tANI_U32 nTime = 0;
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_FALSE;
if(!HAL_STATUS_SUCCESS(<API key>(pMac, &nTime)))
{
<API key>(pMac, nTime);
}
}
}
}
/*
* Param: pTimeInterval -- Caller allocated memory in return, if failed,
* to specify the next time interval for idle scan timer interval
* Return: Not success -- meaning it cannot start IMPS, caller needs to
* start a timer for idle scan
*/
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 *pTimeInterval)
{
eHalStatus status = <API key>;
//Do not trigger IMPS in case of concurrency
if (<API key>() &&
<API key>(pMac))
{
smsLog( pMac, LOG1, FL("Cannot request IMPS because Concurrent Sessions Running") );
return (status);
}
if(pTimeInterval)
{
*pTimeInterval = 0;
}
smsLog(pMac, LOG3, FL("called"));
if( smeCommandPending( pMac ) )
{
smsLog( pMac, LOG1, FL(" Cannot request IMPS because command pending") );
//Not to enter IMPS because more work to do
if(pTimeInterval)
{
*pTimeInterval = 0;
}
//restart when ready
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
return (status);
}
if (IsPmcImpsReqFailed (pMac))
{
if(pTimeInterval)
{
*pTimeInterval = 1000000; //usec
}
//restart when ready
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
return status;
}
if((pMac->scan.fScanEnable) &&
(eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan)) {
//Stop get result timer because idle scan gets scan result out of PE
<API key>(pMac);
if(pTimeInterval)
{
*pTimeInterval = pMac->roam.configParam.impsSleepTime;
}
//pmcRequestImps take a period in millisecond unit.
status = pmcRequestImps(pMac,
pMac->roam.configParam.impsSleepTime / <API key>,
csrScanIMPSCallback, pMac);
if(!HAL_STATUS_SUCCESS(status))
{
if(<API key> != status)
{
//Do restart the timer if CSR thinks it cannot do IMPS
if( !csrCheckPSReady( pMac ) )
{
if(pTimeInterval)
{
*pTimeInterval = 0;
}
//Set the restart flag to true because that idle scan
//can be restarted even though the timer will not be running
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
}
else
{
//For not now, we do a quicker retry
if(pTimeInterval)
{
*pTimeInterval = <API key>;
}
}
smsLog(pMac, LOGW, FL("call pmcRequestImps and it returns status code (%d)"), status);
}
else
{
smsLog(pMac, LOGW, FL("already in IMPS"));
//Since CSR is the only module to request for IMPS. If it is already in IMPS, CSR assumes
//the callback will be called in the future. Should not happen though.
status = eHAL_STATUS_SUCCESS;
pMac->scan.nIdleScanTimeGap = 0;
}
}
else
{
//requested so let's reset the value
pMac->scan.nIdleScanTimeGap = 0;
}
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac)
{
eHalStatus status = <API key>;
tANI_U32 nTime = 0;
smsLog(pMac, LOGW, FL("called"));
/*
* Idle Scan not supported with Power Save Offload
* Enabled
*/
if(pMac->psOffloadEnabled)
{
return eHAL_STATUS_SUCCESS;
}
if(pMac->roam.configParam.IsIdleScanEnabled)
{
//stop bg scan first
csrScanBGScanAbort(pMac);
//Stop get result timer because idle scan gets scan result out of PE
<API key>(pMac);
}
pMac->scan.fCancelIdleScan = eANI_BOOLEAN_FALSE;
status = <API key>(pMac, &nTime);
if(!HAL_STATUS_SUCCESS(status))
{
<API key>(pMac, nTime);
}
return (status);
}
void <API key>(tpAniSirGlobal pMac)
{
/*
* Idle Scan not supported with Power Save Offload
* Enabled
*/
if(pMac->psOffloadEnabled)
{
return;
}
if(eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan)
{
if (<API key>()) {
return;
}
smsLog(pMac, LOG1, " <API key>");
pMac->scan.fCancelIdleScan = eANI_BOOLEAN_TRUE;
/* Set the restart flag in case later on it is uncanceled */
pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE;
<API key>(pMac);
<API key>(pMac);
}
}
void <API key>(void *pv)
{
tpAniSirGlobal pMac = PMAC_STRUCT( pv );
eHalStatus status;
tANI_U32 nTime = 0;
smsLog(pMac, LOGW, " <API key> called ");
<API key> (pMac);
status = <API key>(pMac, &nTime);
if(!HAL_STATUS_SUCCESS(status) && (eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan))
{
//Check whether it is time to actually do an idle scan
if(pMac->scan.nIdleScanTimeGap >= pMac->roam.configParam.impsSleepTime)
{
pMac->scan.nIdleScanTimeGap = 0;
csrScanIMPSCallback(pMac, eHAL_STATUS_SUCCESS);
}
else
{
<API key>(pMac, nTime);
}
}
}
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
tListElem *pEntry, *pEntryTmp;
tSmeCmd *pCommand;
tDblLinkList localList;
tDblLinkList *pCmdList;
vos_mem_zero(&localList, sizeof(tDblLinkList));
if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList)))
{
smsLog(pMac, LOGE, FL(" failed to open list"));
return fRet;
}
if (!pMac->fScanOffload)
pCmdList = &pMac->sme.smeCmdPendingList;
else
pCmdList = &pMac->sme.<API key>;
csrLLLock(pCmdList);
pEntry = csrLLPeekHead(pCmdList, LL_ACCESS_NOLOCK);
while(pEntry)
{
pEntryTmp = csrLLNext(pCmdList, pEntry, LL_ACCESS_NOLOCK);
pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link);
if( eSmeCommandScan == pCommand->command )
{
switch( pCommand->u.scanCmd.reason )
{
case eCsrScanIdleScan:
if( csrLLRemoveEntry(pCmdList, pEntry, LL_ACCESS_NOLOCK) )
{
csrLLInsertTail(&localList, pEntry, LL_ACCESS_NOLOCK);
}
fRet = eANI_BOOLEAN_TRUE;
break;
default:
break;
} //switch
}
pEntry = pEntryTmp;
}
csrLLUnlock(pCmdList);
while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) )
{
pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link);
<API key>( pMac, pCommand );
}
csrLLClose(&localList);
return (fRet);
}
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
tListElem *pEntry, *pEntryTmp;
tSmeCmd *pCommand;
tDblLinkList localList;
tDblLinkList *pCmdList;
vos_mem_zero(&localList, sizeof(tDblLinkList));
if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList)))
{
smsLog(pMac, LOGE, FL(" failed to open list"));
return fRet;
}
if (!pMac->fScanOffload)
pCmdList = &pMac->sme.smeCmdPendingList;
else
pCmdList = &pMac->sme.<API key>;
csrLLLock(pCmdList);
pEntry = csrLLPeekHead(pCmdList, LL_ACCESS_NOLOCK);
while(pEntry)
{
pEntryTmp = csrLLNext(pCmdList, pEntry, LL_ACCESS_NOLOCK);
pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link);
if( (eSmeCommandScan == pCommand->command) && (sessionId == pCommand->sessionId) )
{
switch(pCommand->u.scanCmd.reason)
{
#ifdef <API key>
case <API key>:
#endif
case eCsrScanGetResult:
case <API key>:
case eCsrScanBGScanAbort:
case <API key>:
case <API key>:
break;
default:
smsLog (pMac, LOGW, "%s:
__func__, pCommand->u.scanCmd.reason);
//The rest are fresh scan requests
if( csrLLRemoveEntry(pCmdList, pEntry, LL_ACCESS_NOLOCK) )
{
csrLLInsertTail(&localList, pEntry, LL_ACCESS_NOLOCK);
}
fRet = eANI_BOOLEAN_TRUE;
break;
}
}
pEntry = pEntryTmp;
}
csrLLUnlock(pCmdList);
while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) )
{
pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link);
if (pCommand->u.scanCmd.callback)
{
/* User scan request is pending,
* send response with status eCSR_SCAN_ABORT*/
pCommand->u.scanCmd.callback(pMac,
pCommand->u.scanCmd.pContext,
sessionId,
pCommand->u.scanCmd.scanID,
eCSR_SCAN_ABORT);
}
<API key>( pMac, pCommand );
}
csrLLClose(&localList);
return (fRet);
}
void <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand, eCsrScanStatus scanStatus)
{
eCsrScanReason reason = pCommand->u.scanCmd.reason;
tANI_BOOLEAN status;
if (!pMac->fScanOffload)
{
tANI_U32 i;
for(i = 0; i < <API key>; i++)
csrRoamStateChange(pMac, pCommand->u.scanCmd.lastRoamState[i], i);
}
else
{
csrRoamStateChange(pMac,
pCommand->u.scanCmd.lastRoamState[pCommand->sessionId],
pCommand->sessionId);
}
csrScanCallCallback(pMac, pCommand, scanStatus);
smsLog(pMac, LOG3, " Remove Scan command reason = %d", reason);
if (pMac->fScanOffload)
{
status = csrLLRemoveEntry(&pMac->sme.<API key>,
&pCommand->Link, LL_ACCESS_LOCK);
}
else
{
status = csrLLRemoveEntry(&pMac->sme.smeCmdActiveList,
&pCommand->Link, LL_ACCESS_LOCK);
}
if(status)
{
<API key>( pMac, pCommand );
}
else
{
smsLog(pMac, LOGE,
" ********<API key> cannot release command reason %d",
pCommand->u.scanCmd.reason );
}
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId,
tPmkidCandidateInfo *pPmkidList, tANI_U32 *pNumItems )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, " pMac->scan.NumPmkidCandidate = %d", pSession->NumPmkidCandidate);
<API key>(pMac, sessionId);
if(<API key>(pMac, sessionId) && pSession->pCurRoamProfile)
{
<API key> *pScanFilter;
tCsrScanResultInfo *pScanResult;
tScanResultHandle hBSSList;
tANI_U32 nItems = *pNumItems;
*pNumItems = 0;
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
{
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
//Here is the profile we need to connect to
status = <API key>(pMac, pSession->pCurRoamProfile, pScanFilter);
if(HAL_STATUS_SUCCESS(status))
{
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(HAL_STATUS_SUCCESS(status))
{
while(((pScanResult = <API key>(pMac, hBSSList)) != NULL) && ( pSession->NumPmkidCandidate < nItems))
{
//NumPmkidCandidate adds up here
<API key>(pMac,
&pScanResult->BssDescriptor,
(tDot11fBeaconIEs *)(pScanResult->pvIes),
sessionId);
}
if(pSession->NumPmkidCandidate)
{
*pNumItems = pSession->NumPmkidCandidate;
vos_mem_copy(pPmkidList, pSession->PmkidCandidateInfo,
pSession->NumPmkidCandidate * sizeof(tPmkidCandidateInfo));
}
csrScanResultPurge(pMac, hBSSList);
}//Have scan result
csrFreeScanFilter(pMac, pScanFilter);
}
vos_mem_free(pScanFilter);
}
}
return (status);
}
#ifdef FEATURE_WLAN_WAPI
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId,
tBkidCandidateInfo *pBkidList, tANI_U32 *pNumItems )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
if(!pSession)
{
smsLog(pMac, LOGE, FL(" session %d not found "), sessionId);
return eHAL_STATUS_FAILURE;
}
smsLog(pMac, LOGW, " pMac->scan.NumBkidCandidate = %d", pSession->NumBkidCandidate);
<API key>(pMac, sessionId);
if(<API key>(pMac, sessionId) && pSession->pCurRoamProfile)
{
<API key> *pScanFilter;
tCsrScanResultInfo *pScanResult;
tScanResultHandle hBSSList;
tANI_U32 nItems = *pNumItems;
*pNumItems = 0;
pScanFilter = vos_mem_malloc(sizeof(<API key>));
if ( NULL == pScanFilter )
status = eHAL_STATUS_FAILURE;
else
{
vos_mem_set(pScanFilter, sizeof(<API key>), 0);
//Here is the profile we need to connect to
status = <API key>(pMac, pSession->pCurRoamProfile, pScanFilter);
if(HAL_STATUS_SUCCESS(status))
{
status = csrScanGetResult(pMac, pScanFilter, &hBSSList);
if(HAL_STATUS_SUCCESS(status))
{
while(((pScanResult = <API key>(pMac, hBSSList)) != NULL) && ( pSession->NumBkidCandidate < nItems))
{
//pMac->scan.NumBkidCandidate adds up here
<API key>(pMac, &pScanResult->BssDescriptor,
(tDot11fBeaconIEs *)( pScanResult->pvIes ));
}
if(pSession->NumBkidCandidate)
{
*pNumItems = pSession->NumBkidCandidate;
vos_mem_copy(pBkidList, pSession->BkidCandidateInfo, pSession->NumBkidCandidate * sizeof(tBkidCandidateInfo));
}
csrScanResultPurge(pMac, hBSSList);
}//Have scan result
}
vos_mem_free(pScanFilter);
}
}
return (status);
}
#endif /* FEATURE_WLAN_WAPI */
//This function is usually used for BSSs that suppresses SSID so the profile
//shall have one and only one SSID
eHalStatus csrScanForSSID(tpAniSirGlobal pMac, tANI_U32 sessionId, tCsrRoamProfile *pProfile, tANI_U32 roamId, tANI_BOOLEAN notify)
{
eHalStatus status = <API key>;
tSmeCmd *pScanCmd = NULL;
tANI_U8 bAddr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
tANI_U8 index = 0;
tANI_U32 numSsid = pProfile->SSIDs.numOfSSIDs;
<API key> pNeighborRoamInfo =
&pMac->roam.neighborRoamInfo[sessionId];
smsLog(pMac, LOG2, FL("called"));
//For WDS, we use the index 0. There must be at least one in there
if( CSR_IS_WDS_STA( pProfile ) && numSsid )
{
numSsid = 1;
}
if(pMac->scan.fScanEnable && ( numSsid == 1 ) )
{
do
{
pScanCmd = csrGetCommandBuffer(pMac);
if(!pScanCmd)
{
smsLog(pMac, LOGE, FL("failed to allocate command buffer"));
break;
}
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
pScanCmd->u.scanCmd.pToRoamProfile = vos_mem_malloc(sizeof(tCsrRoamProfile));
if ( NULL == pScanCmd->u.scanCmd.pToRoamProfile )
{
status = eHAL_STATUS_FAILURE;
}
else
{
status = csrRoamCopyProfile(pMac, pScanCmd->u.scanCmd.pToRoamProfile, pProfile);
}
if(!HAL_STATUS_SUCCESS(status))
break;
pScanCmd->u.scanCmd.roamId = roamId;
pScanCmd->command = eSmeCommandScan;
pScanCmd->sessionId = (tANI_U8)sessionId;
pScanCmd->u.scanCmd.callback = NULL;
pScanCmd->u.scanCmd.pContext = NULL;
pScanCmd->u.scanCmd.reason = eCsrScanForSsid;//Need to check: might need a new reason for SSID scan for LFR during multisession with p2p
pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around
vos_mem_set(&pScanCmd->u.scanCmd.u.scanRequest, sizeof(tCsrScanRequest), 0);
pScanCmd->u.scanCmd.u.scanRequest.scanType = eSIR_ACTIVE_SCAN;
pScanCmd->u.scanCmd.u.scanRequest.BSSType = pProfile->BSSType;
// To avoid 11b rate in probe request Set p2pSearch flag as 1 for P2P Client Mode
if(VOS_P2P_CLIENT_MODE == pProfile->csrPersona)
{
pScanCmd->u.scanCmd.u.scanRequest.p2pSearch = 1;
}
if(pProfile->pAddIEScan)
{
pScanCmd->u.scanCmd.u.scanRequest.pIEField = vos_mem_malloc(
pProfile->nAddIEScanLength);
if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.pIEField )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
vos_mem_set(pScanCmd->u.scanCmd.u.scanRequest.pIEField,
pProfile->nAddIEScanLength, 0);
if (HAL_STATUS_SUCCESS(status))
{
vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.pIEField,
pProfile->pAddIEScan, pProfile->nAddIEScanLength);
pScanCmd->u.scanCmd.u.scanRequest.uIEFieldLen = pProfile->nAddIEScanLength;
}
else
{
smsLog(pMac, LOGE, "No memory for scanning IE fields");
}
} //Allocate memory for IE field
else
{
pScanCmd->u.scanCmd.u.scanRequest.uIEFieldLen = 0;
}
/* For one channel be good enough time to receive beacon at-least */
if( 1 == pProfile->ChannelInfo.numOfChannels )
{
#if defined (<API key>)
if (pNeighborRoamInfo->handoffReqInfo.src == FASTREASSOC) {
pScanCmd->u.scanCmd.u.scanRequest.maxChnTime =
<API key>;
pScanCmd->u.scanCmd.u.scanRequest.minChnTime =
<API key>;
/* Reset this value */
pNeighborRoamInfo->handoffReqInfo.src = 0;
}
else
#endif
{
pScanCmd->u.scanCmd.u.scanRequest.maxChnTime = <API key>;
pScanCmd->u.scanCmd.u.scanRequest.minChnTime = <API key>;
}
}
else
{
pScanCmd->u.scanCmd.u.scanRequest.maxChnTime =
pMac->roam.configParam.nActiveMaxChnTime;
pScanCmd->u.scanCmd.u.scanRequest.minChnTime =
pMac->roam.configParam.nActiveMinChnTime;
}
pScanCmd->u.scanCmd.u.scanRequest.maxChnTimeBtc =
pMac->roam.configParam.<API key>;
pScanCmd->u.scanCmd.u.scanRequest.minChnTimeBtc =
pMac->roam.configParam.<API key>;
if(pProfile->BSSIDs.numOfBSSIDs == 1)
{
vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.bssid,
pProfile->BSSIDs.bssid, sizeof(tCsrBssid));
}
else
{
vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.bssid, bAddr, 6);
}
if(pProfile->ChannelInfo.numOfChannels)
{
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList = vos_mem_malloc(
sizeof(*pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList)
* pProfile->ChannelInfo.numOfChannels);
if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 0;
if(HAL_STATUS_SUCCESS(status))
{
<API key>(pMac, pProfile->ChannelInfo.ChannelList[0]);
for(index = 0; index < pProfile->ChannelInfo.numOfChannels; index++)
{
if(<API key>(pMac, pProfile->ChannelInfo.ChannelList[index]))
{
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.ChannelList[pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels]
= pProfile->ChannelInfo.ChannelList[index];
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels++;
}
else
{
smsLog(pMac, LOGW, FL("process a channel (%d) that is invalid"), pProfile->ChannelInfo.ChannelList[index]);
}
}
}
else
{
break;
}
}
else
{
pScanCmd->u.scanCmd.u.scanRequest.ChannelInfo.numOfChannels = 0;
}
if(pProfile->SSIDs.numOfSSIDs)
{
pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList = vos_mem_malloc(
pProfile->SSIDs.numOfSSIDs * sizeof(tCsrSSIDInfo));
if ( NULL == pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if(!HAL_STATUS_SUCCESS(status))
{
break;
}
pScanCmd->u.scanCmd.u.scanRequest.SSIDs.numOfSSIDs = 1;
vos_mem_copy(pScanCmd->u.scanCmd.u.scanRequest.SSIDs.SSIDList,
pProfile->SSIDs.SSIDList, sizeof(tCsrSSIDInfo));
}
//Start process the command
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
}while(0);
if(!HAL_STATUS_SUCCESS(status))
{
if(pScanCmd)
{
<API key>(pMac, pScanCmd);
//TODO:free the memory that is allocated in this function
}
if(notify)
{
csrRoamCallCallback(pMac, sessionId, NULL, roamId, eCSR_ROAM_FAILED, <API key>);
}
}
}//valid
else
{
smsLog(pMac, LOGE, FL("cannot scan because scanEnable (%d) or numSSID (%d) is invalid"),
pMac->scan.fScanEnable, pProfile->SSIDs.numOfSSIDs);
}
return (status);
}
/*
* Issue a scan based on the new capability information
* This should only happen when the associated AP changes its capability.
* After this scan is done, CSR re-roams based on the new scan results
*/
eHalStatus <API key>(tpAniSirGlobal pMac, tSirSmeApNewCaps *pNewCaps)
{
eHalStatus status = <API key>;
tSmeCmd *pScanCmd = NULL;
if(pNewCaps)
{
do
{
pScanCmd = csrGetCommandBuffer(pMac);
if(!pScanCmd)
{
smsLog(pMac, LOGE, FL("failed to allocate command buffer"));
status = <API key>;
break;
}
vos_mem_set(&pScanCmd->u.scanCmd, sizeof(tScanCmd), 0);
status = eHAL_STATUS_SUCCESS;
pScanCmd->u.scanCmd.roamId = 0;
pScanCmd->command = eSmeCommandScan;
pScanCmd->u.scanCmd.callback = NULL;
pScanCmd->u.scanCmd.pContext = NULL;
pScanCmd->u.scanCmd.reason = <API key>;
pScanCmd->u.scanCmd.scanID = pMac->scan.nextScanID++; //let it wrap around
status = csrQueueSmeCommand(pMac, pScanCmd, eANI_BOOLEAN_FALSE);
if( !HAL_STATUS_SUCCESS( status ) )
{
smsLog( pMac, LOGE, FL(" fail to send message status = %d"), status );
break;
}
}while(0);
if(!HAL_STATUS_SUCCESS(status))
{
if(pScanCmd)
{
<API key>(pMac, pScanCmd);
}
}
}
return (status);
}
void <API key>(tpAniSirGlobal pMac)
{
tANI_U32 len = CSR_MIN(sizeof(pMac->roam.validChannelList), sizeof(pMac->scan.bgScanChannelList));
vos_mem_set(pMac->scan.bgScanChannelList, len, 0);
pMac->scan.numBGScanChannel = 0;
if(HAL_STATUS_SUCCESS(<API key>(pMac, pMac->roam.validChannelList, &len)))
{
pMac->roam.numValidChannels = len;
pMac->scan.numBGScanChannel = (tANI_U8)CSR_MIN(len, <API key>);
vos_mem_copy(pMac->scan.bgScanChannelList, pMac->roam.validChannelList,
pMac->scan.numBGScanChannel);
<API key>(pMac, pMac->scan.bgScanChannelList, pMac->scan.numBGScanChannel);
}
}
//This function return TRUE if background scan channel list is adjusted.
//this function will only shrink the background scan channel list
tANI_BOOLEAN <API key>(tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 NumChannels,
tANI_U8 *pAdjustChannels, tANI_U8 *pNumAdjustChannels)
{
tANI_BOOLEAN fRet = eANI_BOOLEAN_FALSE;
tANI_U8 i, j, count = *pNumAdjustChannels;
i = 0;
while(i < count)
{
for(j = 0; j < NumChannels; j++)
{
if(pChannelList[j] == pAdjustChannels[i])
break;
}
if(j == NumChannels)
{
//This channel is not in the list, remove it
fRet = eANI_BOOLEAN_TRUE;
count
if(count - i)
{
vos_mem_copy(&pAdjustChannels[i], &pAdjustChannels[i+1], count - i);
}
else
{
//already remove the last one. Done.
break;
}
}
else
{
i++;
}
}//while(i<count)
*pNumAdjustChannels = count;
return (fRet);
}
//Get the list of the base channels to scan for passively 11d info
eHalStatus <API key>( tpAniSirGlobal pMac )
{
eHalStatus status = eHAL_STATUS_SUCCESS;
int n = <API key>;
status = <API key>( pMac->scan.baseChannels.channelList, &n, NULL, NULL );
if( HAL_STATUS_SUCCESS(status) )
{
pMac->scan.baseChannels.numChannels = (tANI_U8)n;
}
else
{
smsLog( pMac, LOGE, FL(" failed") );
pMac->scan.baseChannels.numChannels = 0;
}
return ( status );
}
//This function use the input pChannelList to validate the current saved channel list
eHalStatus <API key>( tpAniSirGlobal pMac, tANI_U8 *pAdjustChannels, tANI_U8 NumAdjustChannels)
{
tANI_U32 dataLen = sizeof( tANI_U8 ) * NumAdjustChannels;
return (ccmCfgSetStr(pMac, <API key>, pAdjustChannels, dataLen, NULL, eANI_BOOLEAN_FALSE));
}
void <API key>( tpAniSirGlobal pMac, tANI_U8 *pChannelList, tANI_U8 NumChannels )
{
tANI_U32 dataLen = sizeof( tANI_U8 ) * NumChannels;
eHalStatus status;
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"%s: dump valid channel list(NumChannels(%d))",
__func__,NumChannels);
VOS_TRACE_HEX_DUMP(VOS_MODULE_ID_SME, <API key>,
pChannelList, NumChannels);
ccmCfgSetStr(pMac, <API key>, pChannelList, dataLen, NULL, eANI_BOOLEAN_FALSE);
if (pMac->fScanOffload)
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"Scan offload is enabled, update default chan list");
/*
* disable fcc constraint since new country code
* is being set
*/
pMac->scan.fcc_constraint = false;
status = <API key>(pMac);
if (eHAL_STATUS_SUCCESS != status)
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"failed to update the supported channel list");
}
}
return;
}
/*
* The Tx power limits are saved in the cfg for future usage.
*/
void csrSaveTxPowerToCfg( tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 cfgId )
{
tListElem *pEntry;
tANI_U32 cbLen = 0, dataLen;
<API key> *pChannelSet;
tANI_U32 idx;
tSirMacChanInfo *pChannelPowerSet;
tANI_U8 *pBuf = NULL;
//allocate maximum space for all channels
dataLen = <API key> * sizeof(tSirMacChanInfo);
if ( (pBuf = vos_mem_malloc(dataLen)) != NULL )
{
vos_mem_set(pBuf, dataLen, 0);
pChannelPowerSet = (tSirMacChanInfo *)(pBuf);
pEntry = csrLLPeekHead( pList, LL_ACCESS_LOCK );
// write the tuples (startChan, numChan, txPower) for each channel found in the channel power list.
while( pEntry )
{
pChannelSet = GET_BASE_ADDR( pEntry, <API key>, link );
if ( 1 != pChannelSet->interChannelOffset )
{
/*
* we keep the 5G channel sets internally with an inter channel
* offset of 4. Expand these to the right format.
* (inter channel offset of 1 is the only option for the
* triplets that 11d advertises.
*/
if ((cbLen + (pChannelSet->numChannels * sizeof(tSirMacChanInfo))) >= dataLen)
{
// expanding this entry will overflow our allocation
smsLog(pMac, LOGE,
"%s: Buffer overflow, start %d, num %d, offset %d",
__func__,
pChannelSet->firstChannel,
pChannelSet->numChannels,
pChannelSet->interChannelOffset);
break;
}
for( idx = 0; idx < pChannelSet->numChannels; idx++ )
{
pChannelPowerSet->firstChanNum = (tSirMacChanNum)(pChannelSet->firstChannel + ( idx * pChannelSet->interChannelOffset ));
smsLog(pMac, LOG3, " Setting Channel Number %d", pChannelPowerSet->firstChanNum);
pChannelPowerSet->numChannels = 1;
pChannelPowerSet->maxTxPower = CSR_ROAM_MIN( pChannelSet->txPower, pMac->roam.configParam.nTxPowerCap );
smsLog(pMac, LOG3, " Setting Max Transmit Power %d", pChannelPowerSet->maxTxPower);
cbLen += sizeof( tSirMacChanInfo );
pChannelPowerSet++;
}
}
else
{
if (cbLen >= dataLen)
{
// this entry will overflow our allocation
smsLog(pMac, LOGE,
"%s: Buffer overflow, start %d, num %d, offset %d",
__func__,
pChannelSet->firstChannel,
pChannelSet->numChannels,
pChannelSet->interChannelOffset);
break;
}
pChannelPowerSet->firstChanNum = pChannelSet->firstChannel;
smsLog(pMac, LOG3, " Setting Channel Number %d", pChannelPowerSet->firstChanNum);
pChannelPowerSet->numChannels = pChannelSet->numChannels;
pChannelPowerSet->maxTxPower = CSR_ROAM_MIN( pChannelSet->txPower, pMac->roam.configParam.nTxPowerCap );
smsLog(pMac, LOG3, " Setting Max Transmit Power %d, nTxPower %d", pChannelPowerSet->maxTxPower,pMac->roam.configParam.nTxPowerCap );
cbLen += sizeof( tSirMacChanInfo );
pChannelPowerSet++;
}
pEntry = csrLLNext( pList, pEntry, LL_ACCESS_LOCK );
}
if(cbLen)
{
ccmCfgSetStr(pMac, cfgId, (tANI_U8 *)pBuf, cbLen, NULL, eANI_BOOLEAN_FALSE);
}
vos_mem_free(pBuf);
}//Allocate memory
}
void <API key>( tpAniSirGlobal pMac, tANI_U8 *countryCode )
{
tANI_U8 cc[<API key>];
v_REGDOMAIN_t DomainId;
smsLog( pMac, LOG3, "Setting Country Code in Cfg from <API key> %s",countryCode );
vos_mem_copy(cc, countryCode, <API key>);
// don't program the bogus country codes that we created for Korea in the MAC. if we see
// the bogus country codes, program the MAC with the right country code.
if ( ( 'K' == countryCode[ 0 ] && '1' == countryCode[ 1 ] ) ||
( 'K' == countryCode[ 0 ] && '2' == countryCode[ 1 ] ) ||
( 'K' == countryCode[ 0 ] && '3' == countryCode[ 1 ] ) ||
( 'K' == countryCode[ 0 ] && '4' == countryCode[ 1 ] ) )
{
// replace the alternate Korea country codes, 'K1', 'K2', .. with 'KR' for Korea
cc[ 1 ] = 'R';
}
ccmCfgSetStr(pMac, <API key>, cc, <API key>, NULL, eANI_BOOLEAN_FALSE);
//Need to let HALPHY know about the current domain so it can apply some
//domain-specific settings (TX filter...)
/*if(HAL_STATUS_SUCCESS(<API key>(pMac, cc, &DomainId)))
{
halPhySetRegDomain(pMac, DomainId);
}*/
}
eHalStatus csrGetCountryCode(tpAniSirGlobal pMac, tANI_U8 *pBuf, tANI_U8 *pbLen)
{
eHalStatus status = <API key>;
tANI_U32 len;
if(pBuf && pbLen && (*pbLen >= <API key>))
{
len = *pbLen;
status = ccmCfgGetStr(pMac, <API key>, pBuf, &len);
if(HAL_STATUS_SUCCESS(status))
{
*pbLen = (tANI_U8)len;
}
}
return (status);
}
void <API key>( tpAniSirGlobal pMac, tANI_U8 *countryCode, tCsrChannel *pChannelList )
{
tANI_U8 i, j;
tANI_BOOLEAN found=FALSE;
tANI_U8 *pControlList = NULL;
tANI_U32 len = <API key>;
if ( (pControlList = vos_mem_malloc(<API key>)) != NULL )
{
vos_mem_set((void *)pControlList, <API key>, 0);
if(HAL_STATUS_SUCCESS(ccmCfgGetStr(pMac, <API key>, pControlList, &len)))
{
for (i = 0; i < pChannelList->numChannels; i++)
{
for (j = 0; j < len; j += 2)
{
if (pControlList[j] == pChannelList->channelList[i])
{
found = TRUE;
break;
}
}
if (found) // insert a pair(channel#, flag)
{
pControlList[j+1] = csrGetScanType(pMac, pControlList[j]);
found = FALSE; // reset the flag
}
}
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"%s: dump scan control list",__func__);
VOS_TRACE_HEX_DUMP(VOS_MODULE_ID_SME, <API key>,
pControlList, len);
ccmCfgSetStr(pMac, <API key>, pControlList, len, NULL, eANI_BOOLEAN_FALSE);
}//Successfully getting scan control list
vos_mem_free(pControlList);
}//AllocateMemory
}
//if bgPeriod is 0, background scan is disabled. It is in millisecond units
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 bgPeriod)
{
return (ccmCfgSetInt(pMac, <API key>, bgPeriod, (tCcmCfgSetCallback) <API key>, eANI_BOOLEAN_FALSE));
}
void <API key>(tHalHandle hHal, tANI_S32 result)
{
tListElem *pEntry = NULL;
tSmeCmd *pCommand = NULL;
tpAniSirGlobal pMac = PMAC_STRUCT( hHal );
tDblLinkList *pCmdList ;
if (!pMac->fScanOffload)
pCmdList = &pMac->sme.smeCmdActiveList;
else
pCmdList = &pMac->sme.<API key>;
pEntry = csrLLPeekHead( pCmdList, LL_ACCESS_LOCK );
if ( pEntry )
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
if ( eSmeCommandScan == pCommand->command )
{
eCsrScanStatus scanStatus = (<API key>(result)) ? eCSR_SCAN_SUCCESS : eCSR_SCAN_FAILURE;
<API key>(pMac, pCommand, scanStatus);
}
else
{
smsLog( pMac, LOGW, "CSR: Scan Completion called but SCAN command is not ACTIVE ..." );
}
}
<API key>( pMac );
}
eHalStatus <API key>(tpAniSirGlobal pMac, tSmeCmd *pCommand)
{
eHalStatus status;
tCsrBGScanRequest *pScanReq = &pCommand->u.scanCmd.u.bgScanRequest;
tANI_U32 dataLen = sizeof( tANI_U8 ) * pScanReq->ChannelInfo.numOfChannels;
/* Have to make sure we don't loop back to the head of the list,
* which will happen if the entry is NOT on the list */
while (pEntry)
{
pEntryToRemove = pEntry;
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link );
if ((pCommand->command == commandType) &&
(pCommand->sessionId == sessionId))
{
/* Remove that entry only */
if (csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK))
{
csrLLInsertTail(&localList, pEntryToRemove,
LL_ACCESS_NOLOCK);
}
}
}
}
csrLLUnlock(pList);
while ((pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)))
{
pCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link);
csrAbortCommand(pMac, pCommand, eANI_BOOLEAN_FALSE);
}
csrLLClose(&localList);
}
void <API key>(tpAniSirGlobal pMac, tDblLinkList *pList,
eSmeCommandType commandType )
{
tDblLinkList localList;
tListElem *pEntry;
tSmeCmd *pCommand;
tListElem *pEntryToRemove;
vos_mem_zero(&localList, sizeof(tDblLinkList));
if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList)))
{
smsLog(pMac, LOGE, FL(" failed to open list"));
return;
}
csrLLLock(pList);
if( !csrLLIsListEmpty( pList, LL_ACCESS_NOLOCK ) )
{
pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK);
// Have to make sure we don't loop back to the head of the list, which will
// happen if the entry is NOT on the list...
while( pEntry )
{
pEntryToRemove = pEntry;
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link );
if ( pCommand->command == commandType )
{
// Remove that entry only
if(csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK))
{
csrLLInsertTail(&localList, pEntryToRemove, LL_ACCESS_NOLOCK);
}
}
}
}
csrLLUnlock(pList);
while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) )
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE);
}
csrLLClose(&localList);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirSmeScanAbortReq *pMsg;
tANI_U16 msgLen;
tListElem *pEntry;
tSmeCmd *pCommand;
if (!pMac->fScanOffload)
{
pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE;
#ifdef <API key>
<API key>( pMac, &pMac->scan.scanCmdPendingList, sessionId);
#endif
<API key>( pMac, &pMac->roam.roamCmdPendingList, sessionId);
<API key>( pMac, &pMac->sme.smeCmdPendingList, sessionId);
pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE;
pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK);
}
else
{
pMac->scan.fDropScanCmd = eANI_BOOLEAN_TRUE;
<API key>( pMac, &pMac->sme.<API key>, sessionId);
pMac->scan.fDropScanCmd = eANI_BOOLEAN_FALSE;
pEntry = csrLLPeekHead(&pMac->sme.<API key>, LL_ACCESS_LOCK);
}
if(NULL != pEntry)
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
if ( (eSmeCommandScan == pCommand->command ) &&
(sessionId == pCommand->sessionId))
{
if ( eCsrScanForSsid == pCommand->u.scanCmd.reason)
{
msgLen = (tANI_U16)(sizeof( tSirSmeScanAbortReq ));
pMsg = vos_mem_malloc(msgLen);
if ( NULL == pMsg )
{
status = eHAL_STATUS_FAILURE;
smsLog(pMac, LOGE, FL("Failed to allocate memory for SmeScanAbortReq"));
}
else
{
vos_mem_zero((void *)pMsg, msgLen);
pMsg->type = pal_cpu_to_be16((tANI_U16)<API key>);
pMsg->msgLen = pal_cpu_to_be16(msgLen);
pMsg->sessionId = sessionId;
status = palSendMBMessage(pMac->hHdd, pMsg);
}
}
}
}
return( status );
}
void <API key>(tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U32 sessionId)
{
tDblLinkList localList;
tListElem *pEntry;
tSmeCmd *pCommand;
tListElem *pEntryToRemove;
vos_mem_zero(&localList, sizeof(tDblLinkList));
if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList)))
{
smsLog(pMac, LOGE, FL(" failed to open list"));
return;
}
csrLLLock(pList);
if( !csrLLIsListEmpty( pList, LL_ACCESS_NOLOCK ) )
{
pEntry = csrLLPeekHead( pList, LL_ACCESS_NOLOCK);
// Have to make sure we don't loop back to the head of the list, which will
// happen if the entry is NOT on the list...
while( pEntry )
{
pEntryToRemove = pEntry;
pEntry = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK);
pCommand = GET_BASE_ADDR( pEntryToRemove, tSmeCmd, Link );
if ( (eSmeCommandScan == pCommand->command ) &&
(sessionId == pCommand->sessionId) )
{
if ( eCsrScanForSsid == pCommand->u.scanCmd.reason)
{
// Remove that entry only
if ( csrLLRemoveEntry( pList, pEntryToRemove, LL_ACCESS_NOLOCK))
{
csrLLInsertTail(&localList, pEntryToRemove, LL_ACCESS_NOLOCK);
}
}
}
}
}
csrLLUnlock(pList);
while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) )
{
pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link );
csrAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE);
}
csrLLClose(&localList);
}
eHalStatus <API key>(tpAniSirGlobal pMac,
tANI_U8 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
if( !<API key>( pMac ) )
{
//Only abort the scan if it is not used for other roam/connect purpose
status = csrScanAbortMacScan(pMac, sessionId, <API key>);
}
return (status);
}
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tSirMbMsg *pMsg;
tANI_U16 msgLen;
if (pMac->fScanOffload)
msgLen = (tANI_U16)(sizeof(<API key>));
else
msgLen = (tANI_U16)(sizeof(tSirMbMsg));
pMsg = vos_mem_malloc(msgLen);
if ( NULL == pMsg )
status = eHAL_STATUS_FAILURE;
else
{
vos_mem_set(pMsg, msgLen, 0);
pMsg->type = <API key>;
pMsg->msgLen = msgLen;
if (pMac->fScanOffload)
((<API key> *)pMsg)->sessionId = sessionId;
status = palSendMBMessage(pMac->hHdd, pMsg);
}
return( status );
}
tANI_BOOLEAN <API key>( tpAniSirGlobal pMac, tANI_U8 channel )
{
tANI_BOOLEAN fValid = FALSE;
tANI_U32 idxValidChannels;
tANI_U32 len = pMac->roam.numValidChannels;
for ( idxValidChannels = 0; ( idxValidChannels < len ); idxValidChannels++ )
{
if ( channel == pMac->roam.validChannelList[ idxValidChannels ] )
{
fValid = TRUE;
break;
}
}
return fValid;
}
#ifdef <API key>
eHalStatus <API key>(tpAniSirGlobal pMac,
<API key> *<API key>)
{
v_U32_t uLen = 0;
<API key> pParsedFrame;
tCsrScanResult *pScanResult = NULL;
tSirBssDescription *pBssDescr = NULL;
tANI_BOOLEAN fDupBss;
tDot11fBeaconIEs *pIesLocal = NULL;
tAniSSID tmpSsid;
v_TIME_t timer=0;
tpSirMacMgmtHdr macHeader = (tpSirMacMgmtHdr)<API key>->data;
tListElem *pEntry;
pParsedFrame =
(<API key>)vos_mem_malloc(sizeof(tSirProbeRespBeacon));
if (NULL == pParsedFrame)
{
smsLog(pMac, LOGE, FL(" fail to allocate memory for frame"));
return <API key>;
}
if ( <API key>->frameLength <= SIR_MAC_HDR_LEN_3A )
{
smsLog(pMac, LOGE,
FL("Not enough bytes in PNO indication probe resp frame! length=%d"),
<API key>->frameLength);
vos_mem_free(pParsedFrame);
return eHAL_STATUS_FAILURE;
}
if (<API key>(pMac,
&<API key>->data[SIR_MAC_HDR_LEN_3A],
<API key>->frameLength - SIR_MAC_HDR_LEN_3A,
pParsedFrame) != eSIR_SUCCESS ||
!pParsedFrame->ssidPresent)
{
smsLog(pMac, LOGE,
FL("Parse error ProbeResponse, length=%d"),
<API key>->frameLength);
vos_mem_free(pParsedFrame);
return eHAL_STATUS_FAILURE;
}
//24 byte MAC header and 12 byte to ssid IE
if (<API key>->frameLength >
(SIR_MAC_HDR_LEN_3A + <API key>))
{
uLen = <API key>->frameLength -
(SIR_MAC_HDR_LEN_3A + <API key>);
}
pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + uLen);
if ( NULL == pScanResult )
{
smsLog(pMac, LOGE, FL(" fail to allocate memory for frame"));
vos_mem_free(pParsedFrame);
return <API key>;
}
vos_mem_set(pScanResult, sizeof(tCsrScanResult) + uLen, 0);
pBssDescr = &pScanResult->Result.BssDescriptor;
/*
* Length of BSS description is without length of length itself and length
* of pointer that holds the next BSS description
*/
pBssDescr->length = (tANI_U16)(
sizeof(tSirBssDescription) - sizeof(tANI_U16) -
sizeof(tANI_U32) + uLen);
if (pParsedFrame->dsParamsPresent)
{
pBssDescr->channelId = pParsedFrame->channelNumber;
}
else if (pParsedFrame->HTInfo.present)
{
pBssDescr->channelId = pParsedFrame->HTInfo.primaryChannel;
}
else
{
pBssDescr->channelId = pParsedFrame->channelNumber;
}
if ((pBssDescr->channelId > 0) && (pBssDescr->channelId < 15))
{
int i;
// 11b or 11g packet
// 11g iff extended Rate IE is present or
// if there is an A rate in suppRate IE
for (i = 0; i < pParsedFrame->supportedRates.numRates; i++)
{
if (sirIsArate(pParsedFrame->supportedRates.rate[i] & 0x7f))
{
pBssDescr->nwType = eSIR_11G_NW_TYPE;
break;
}
}
if (pParsedFrame-><API key>)
{
pBssDescr->nwType = eSIR_11G_NW_TYPE;
}
}
else
{
// 11a packet
pBssDescr->nwType = eSIR_11A_NW_TYPE;
}
pBssDescr->sinr = 0;
pBssDescr->rssi = -1 * <API key>->rssi;
pBssDescr->beaconInterval = pParsedFrame->beaconInterval;
if (!pBssDescr->beaconInterval)
{
smsLog(pMac, LOGW,
FL("Bcn Interval is Zero , default to 100" MAC_ADDRESS_STR),
MAC_ADDR_ARRAY(pBssDescr->bssId) );
pBssDescr->beaconInterval = 100;
}
pBssDescr->timeStamp[0] = pParsedFrame->timeStamp[0];
pBssDescr->timeStamp[1] = pParsedFrame->timeStamp[1];
pBssDescr->capabilityInfo = *((tANI_U16 *)&pParsedFrame->capabilityInfo);
vos_mem_copy((tANI_U8 *) &pBssDescr->bssId, (tANI_U8 *) macHeader->bssId, sizeof(tSirMacAddr));
pBssDescr->nReceivedTime = (tANI_TIMESTAMP)palGetTickCount(pMac->hHdd);
smsLog( pMac, LOG2, "(%s):Bssid= "MAC_ADDRESS_STR
" chan= %d, rssi = %d", __func__,
MAC_ADDR_ARRAY(pBssDescr->bssId),
pBssDescr->channelId,
pBssDescr->rssi );
//IEs
if (uLen)
{
vos_mem_copy(&pBssDescr->ieFields,
<API key>->data + (SIR_MAC_HDR_LEN_3A + <API key>),
uLen);
}
pIesLocal = (tDot11fBeaconIEs *)( pScanResult->Result.pvIes );
if ( !pIesLocal &&
(!HAL_STATUS_SUCCESS(<API key>(pMac,
&pScanResult->Result.BssDescriptor, &pIesLocal))) )
{
smsLog(pMac, LOGE, FL(" Cannot parse IEs"));
<API key>(pMac, pScanResult);
vos_mem_free(pParsedFrame);
return <API key>;
}
fDupBss = <API key>( pMac,
&pScanResult->Result.BssDescriptor, pIesLocal, &tmpSsid, &timer, FALSE);
//Check whether we have reach out limit
if ( <API key>(pMac) )
{
//Limit reach
smsLog(pMac, LOGE, FL(" BSS limit reached"));
//Free the resources
if( (pScanResult->Result.pvIes == NULL) && pIesLocal )
{
vos_mem_free(pIesLocal);
}
<API key>(pMac, pScanResult);
vos_mem_free(pParsedFrame);
return <API key>;
}
if ((macHeader->fc.type == SIR_MAC_MGMT_FRAME) &&
(macHeader->fc.subType == <API key>))
{
pScanResult->Result.BssDescriptor.fProbeRsp = 1;
}
//Add to scan cache
csrScanAddResult(pMac, pScanResult, pIesLocal,
<API key>->sessionId);
pEntry = csrLLPeekHead( &pMac->scan.scanResultList, LL_ACCESS_LOCK );
if (pEntry && 0 != pMac->scan.<API key>)
<API key>(pMac);
if( (pScanResult->Result.pvIes == NULL) && pIesLocal )
{
vos_mem_free(pIesLocal);
}
vos_mem_free(pParsedFrame);
return eHAL_STATUS_SUCCESS;
}
#endif //<API key>
#ifdef FEATURE_WLAN_LFR
void <API key>(tpAniSirGlobal pMac, tANI_U8 sessionId)
{
tListElem *pEntry = NULL;
tCsrScanResult *pBssDesc = NULL;
tDot11fBeaconIEs *pIes = NULL;
<API key> pNeighborRoamInfo =
&pMac->roam.neighborRoamInfo[sessionId];
if (0 != pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels)
{
smsLog(pMac, LOG1, FL("Ini file contains neighbor scan channel list, "
"hence NO need to build occupied channel list (numChannels = %d)"),
pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels);
return;
}
if (!<API key>(pMac, sessionId))
{
smsLog(pMac, LOG2, FL("donot flush occupied list since current roam "
"profile matches previous (numChannels = %d)"),
pMac->scan.occupiedChannels[sessionId].numChannels);
return;
}
/* Empty occupied channels here */
pMac->scan.occupiedChannels[sessionId].numChannels = 0;
csrLLLock(&pMac->scan.scanResultList);
pEntry = csrLLPeekHead(&pMac->scan.scanResultList, LL_ACCESS_NOLOCK);
while( pEntry )
{
pBssDesc = GET_BASE_ADDR( pEntry, tCsrScanResult, Link );
pIes = (tDot11fBeaconIEs *)( pBssDesc->Result.pvIes );
//At this time, pBssDescription->Result.pvIes may be NULL
if( !pIes && (!HAL_STATUS_SUCCESS(<API key>(pMac,
&pBssDesc->Result.BssDescriptor, &pIes))) )
{
continue;
}
<API key>(pMac, pBssDesc, sessionId,
&pMac->scan.occupiedChannels[sessionId],
pIes);
/*
* Free the memory allocated for pIes in <API key>
*/
if( (pBssDesc->Result.pvIes == NULL) && pIes )
{
vos_mem_free(pIes);
}
pEntry = csrLLNext(&pMac->scan.scanResultList, pEntry, LL_ACCESS_NOLOCK);
}//while
csrLLUnlock(&pMac->scan.scanResultList);
}
#endif
eHalStatus <API key>(tpAniSirGlobal pMac, tANI_U32 sessionId,
tCsrBssid bssid, tANI_U8 channel)
{
eHalStatus status = eHAL_STATUS_SUCCESS;
tDot11fBeaconIEs *pNewIes = NULL;
tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId );
tSirBssDescription *pNewBssDescriptor = NULL;
tANI_U32 size = 0;
if(NULL == pSession)
{
status = eHAL_STATUS_FAILURE;
return status;
}
smsLog(pMac, LOG2, FL("<API key>: Current bssid::"
MAC_ADDRESS_STR),
MAC_ADDR_ARRAY(pSession->pConnectBssDesc->bssId));
smsLog(pMac, LOG2, FL("<API key>: My bssid::"
MAC_ADDRESS_STR" channel %d"),
MAC_ADDR_ARRAY(bssid), channel);
do
{
if(!HAL_STATUS_SUCCESS(<API key>(pMac,
pSession->pConnectBssDesc, &pNewIes)))
{
smsLog(pMac, LOGE, FL("%s: Failed to parse IEs"),
__func__);
status = eHAL_STATUS_FAILURE;
break;
}
size = pSession->pConnectBssDesc->length + sizeof(pSession->pConnectBssDesc->length);
if (size)
{
pNewBssDescriptor = vos_mem_malloc(size);
if ( NULL == pNewBssDescriptor )
status = eHAL_STATUS_FAILURE;
else
status = eHAL_STATUS_SUCCESS;
if (HAL_STATUS_SUCCESS(status))
{
vos_mem_copy(pNewBssDescriptor, pSession->pConnectBssDesc, size);
}
else
{
smsLog(pMac, LOGE, FL("%s: memory allocation failed"),
__func__);
status = eHAL_STATUS_FAILURE;
break;
}
//change the BSSID & channel as passed
vos_mem_copy(pNewBssDescriptor->bssId, bssid, sizeof(tSirMacAddr));
pNewBssDescriptor->channelId = channel;
if (NULL == <API key>(pMac, pNewBssDescriptor,
pNewIes, TRUE, sessionId)) {
smsLog(pMac, LOGE, FL("<API key> failed"));
status = eHAL_STATUS_FAILURE;
break;
}
}
else
{
smsLog(pMac, LOGE, FL("%s: length of bss descriptor is 0"),
__func__);
status = eHAL_STATUS_FAILURE;
break;
}
smsLog(pMac, LOGE, FL("%s: entry successfully added in scan cache"),
__func__);
}while(0);
if(pNewIes)
{
vos_mem_free(pNewIes);
}
if(pNewBssDescriptor)
{
vos_mem_free(pNewBssDescriptor);
}
return status;
}
#ifdef FEATURE_WLAN_ESE
// Update the TSF with the difference in system time
void UpdateCCKMTSF(tANI_U32 *timeStamp0, tANI_U32 *timeStamp1, tANI_U32 *incr)
{
tANI_U64 timeStamp64 = ((tANI_U64)*timeStamp1 << 32) | (*timeStamp0);
timeStamp64 = (tANI_U64)(timeStamp64 + (tANI_U64)*incr);
*timeStamp0 = (tANI_U32)(timeStamp64 & 0xffffffff);
*timeStamp1 = (tANI_U32)((timeStamp64 >> 32) & 0xffffffff);
}
#endif
/**
* <API key>
* This function parses the received beacon/probe response
* from the firmware as part of the roam synch indication.
* The beacon or the probe response is parsed and is also
* saved into the scan cache
*
* @param pMac Pointer to Global Mac
* @param <API key> Roam Synch Indication from
* firmware which also contains the beacon/probe
* response
* @return Status
*/
#ifdef <API key>
eHalStatus <API key>(tpAniSirGlobal pMac,
<API key> *<API key>)
{
v_U32_t uLen = 0;
tANI_BOOLEAN fDupBss;
tDot11fBeaconIEs *pIesLocal = NULL;
tAniSSID tmpSsid;
v_TIME_t timer=0;
tCsrScanResult *pScanResult = NULL;
tANI_U8 sessionId = <API key>->roamedVdevId;
uLen = <API key>-><API key> -
(SIR_MAC_HDR_LEN_3A + <API key>);
pScanResult = vos_mem_malloc(sizeof(tCsrScanResult) + uLen);
if ( pScanResult == NULL )
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
" fail to allocate memory for frame");
return <API key>;
}
vos_mem_zero(pScanResult, sizeof(tCsrScanResult) + uLen );
vos_mem_copy(&pScanResult->Result.BssDescriptor,
<API key>->pbssDescription,
(sizeof(tSirBssDescription) + uLen));
pIesLocal = (tDot11fBeaconIEs *)( pScanResult->Result.pvIes );
if ( !pIesLocal &&
(!HAL_STATUS_SUCCESS(<API key>(pMac,
&pScanResult->Result.BssDescriptor, &pIesLocal))) )
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"%s:Cannot Parse IEs", __func__);
<API key>(pMac, pScanResult);
return <API key>;
}
fDupBss = <API key>(pMac,
&pScanResult->Result.BssDescriptor,
pIesLocal, &tmpSsid, &timer, TRUE);
if ( <API key>(pMac) )
{
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
"%s:BSS Limit Exceed", __func__);
if( (pScanResult->Result.pvIes == NULL) && pIesLocal )
{
vos_mem_free(pIesLocal);
}
<API key>(pMac, pScanResult);
return <API key>;
}
csrScanAddResult(pMac, pScanResult, pIesLocal, sessionId);
return eHAL_STATUS_SUCCESS;
}
#endif
/**
* <API key>() - This function to extract
* first bss description from scan handle
* @result_handle: an object for the result.
*
* This function is written to extract first bss from scan handle.
*
* Return: first bss descriptor from the scan handle.
*/
tSirBssDescription*
<API key>(tScanResultHandle result_handle,
tSirBssDescription *bss_descr)
{
tListElem *first_element = NULL;
tCsrScanResult *scan_result = NULL;
tScanResultList *bss_list = (tScanResultList *)result_handle;
if (NULL == bss_list) {
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("Empty bss_list"));
return NULL;
}
if (csrLLIsListEmpty(&bss_list->List, LL_ACCESS_NOLOCK)) {
VOS_TRACE(VOS_MODULE_ID_SME, <API key>,
FL("bss_list->List is empty"));
vos_mem_free(bss_list);
return NULL;
}
first_element = csrLLPeekHead(&bss_list->List, LL_ACCESS_NOLOCK);
if (first_element) {
scan_result = GET_BASE_ADDR(first_element,
tCsrScanResult,
Link);
vos_mem_copy(bss_descr,
&scan_result->Result.BssDescriptor,
sizeof(tSirBssDescription));
}
return bss_descr;
}
|
#ifndef _MC68681_P_H_
#define _MC68681_P_H_
#ifdef __cplusplus
extern "C" {
#endif
/*
* Define MC68681_STATIC to nothing while debugging so the entry points
* will show up in the symbol table.
*/
#define MC68681_STATIC
/* #define MC68681_STATIC static */
/*
* mc68681 register offsets Read/Write Addresses
*/
#define MC68681_MODE_REG_1A 0 /* MR1A-MR Prior to Read */
#define MC68681_MODE_REG_2A 0 /* MR2A-MR After Read */
#define <API key> 6 /* CTU */
#define <API key> 6 /* CTU */
#define <API key> 7 /* CTL */
#define <API key> 7 /* CTL */
#define <API key> 12 /* IVR */
#define MC68681_MODE_REG_1B 8 /* MR1B-MR Prior to Read */
#define MC68681_MODE_REG_2B 8 /* MR2BA-MR After Read */
/*
* mc68681 register offsets Read Only Addresses
*/
#define <API key> 1 /* SRA */
#define <API key> 2 /* MISR */
#define <API key> 3 /* RHRA */
#define <API key> 4 /* IPCR */
#define <API key> 5 /* ISR */
#define <API key> 9 /* SRB */
#define <API key> 11 /* RHRB */
#define MC68681_INPUT_PORT 13
#define <API key> 14 /* SCC */
#define <API key> 15 /* STC */
/*
* mc68681 register offsets Write Only Addresses
*/
#define <API key> 1 /* CSRA */
#define <API key> 2 /* CRA */
#define <API key> 3 /* THRA */
#define <API key> 4 /* ACR */
#define <API key> 5 /* IMR */
#define <API key> 9 /* CSRB */
#define <API key> 10 /* CRB */
#define <API key> 11 /* THRB */
#define <API key> 13 /* OPCR */
#define <API key> 14 /* SOPBC */
#define <API key> 15 /* COPBC */
/*
* DUART Command Register Definitions:
*
* <API key>,<API key>
*/
#define <API key> 0x01
#define <API key> 0x02
#define <API key> 0x04
#define <API key> 0x08
#define <API key> 0x10
#define <API key> 0x20
#define <API key> 0x30
#define <API key> 0x40
#define <API key> 0x50
#define <API key> 0x60
#define <API key> 0x70
#define <API key> 0x80
#define <API key> 0x90
#define <API key> 0xa0
#define <API key> 0xb0
#define <API key> 0xc0
#define <API key> 0xd0
/*
* Mode Register Definitions
*
* MC68681_MODE_REG_1A
* MC68681_MODE_REG_1B
*/
#define MC68681_5BIT_CHARS 0x00
#define MC68681_6BIT_CHARS 0x01
#define MC68681_7BIT_CHARS 0x02
#define MC68681_8BIT_CHARS 0x03
#define MC68681_ODD_PARITY 0x00
#define MC68681_EVEN_PARITY 0x04
#define MC68681_WITH_PARITY 0x00
#define <API key> 0x08
#define MC68681_NO_PARITY 0x10
#define MC68681_MULTI_DROP 0x18
#define <API key> 0x00
#define <API key> 0x20
#define <API key> 0x00
#define <API key> 0x40
#define <API key> 0x00
#define MC68681_RX_RTS_CTRL 0x80
/*
* Mode Register Definitions
*
* MC68681_MODE_REG_2A
* MC68681_MODE_REG_2B
*/
#define <API key> 0x00
#define <API key> 0x01
#define <API key> 0x02
#define <API key> 0x03
#define <API key> 0x04
#define <API key> 0x05
#define <API key> 0x06
#define <API key> 0x07
#define <API key> 0x08
#define <API key> 0x09
#define <API key> 0x0a
#define <API key> 0x0b
#define <API key> 0x0c
#define <API key> 0x0d
#define <API key> 0x0e
#define <API key> 0x0f
#define <API key> 0x10
#define MC68681_TX_RTS_CTRL 0x20
#define <API key> 0x00
#define <API key> 0x40
#define <API key> 0x80
#define <API key> 0xc0
/*
* Status Register Definitions
*
* <API key>, <API key>
*/
#define MC68681_RX_READY 0x01
#define MC68681_FFULL 0x02
#define MC68681_TX_READY 0x04
#define MC68681_TX_EMPTY 0x08
#define <API key> 0x10
#define <API key> 0x20
#define <API key> 0x40
#define <API key> 0x80
#define MC68681_RX_ERRORS \
(<API key>|<API key>| \
<API key>|<API key>)
/*
* Interupt Status Register Definitions.
*
* <API key>
*/
/*
* Interupt Mask Register Definitions
*
* <API key>
*/
/* These are passed to mc68681_build_imr */
#define MC68681_IR_TX_READY 0x01
#define MC68681_IR_RX_READY 0x02
#define MC68681_IR_BREAK 0x04
#define <API key> 0x07
#define <API key> 0x00
#define <API key> 0x06
#define <API key> 0x01
#define <API key> 0x02
#define MC68681_IR_BREAK_A 0x04
#define <API key> 0x08
#define <API key> 0x10
#define <API key> 0x20
#define MC68681_IR_BREAK_B 0x40
#define <API key> 0x80
/*
* Status Register Definitions.
*
* <API key>,<API key>
*/
#define <API key> 0x01
#define <API key> 0x02
#define <API key> 0x04
#define <API key> 0x08
#define <API key> 0x10
#define <API key> 0x20
#define <API key> 0x40
#define <API key> 0x80
/*
* Definitions for the Interrupt Vector Register:
*
* <API key>
*/
#define <API key> 0x0f
/*
* Definitions for the Auxiliary Control Register
*
* <API key>
*/
#define <API key> 0x00
#define <API key> 0x80
/*
* Per chip context control
*/
typedef struct _mc68681_context
{
int mate;
unsigned char imr;
} mc68681_context;
/*
* Driver functions
*/
MC68681_STATIC void <API key>(
int minor,
mc68681_context *pmc68681Context
);
MC68681_STATIC bool mc68681_probe(int minor);
MC68681_STATIC int <API key>(
int minor,
const struct termios *t
);
MC68681_STATIC void mc68681_init(int minor);
MC68681_STATIC int mc68681_open(
int major,
int minor,
void * arg
);
MC68681_STATIC int mc68681_close(
int major,
int minor,
void * arg
);
MC68681_STATIC void <API key>(
int minor,
char cChar
);
MC68681_STATIC void <API key>(int minor);
MC68681_STATIC ssize_t <API key>(
int minor,
const char *buf,
size_t len
);
MC68681_STATIC ssize_t <API key>(
int minor,
const char *buf,
size_t len
);
MC68681_STATIC int <API key>(
int minor
);
MC68681_STATIC unsigned int mc68681_build_imr(
int minor,
int enable_flag
);
MC68681_STATIC void mc68681_process(
int minor
);
MC68681_STATIC void <API key>(
int minor,
int imr_mask
);
MC68681_STATIC rtems_isr mc68681_isr(
rtems_vector_number vector
);
#ifdef __cplusplus
}
#endif
#endif /* _MC68681_P_H_ */
|
#ifndef __DE_CLOCK_H__
#define __DE_CLOCK_H__
#include "ebios_de.h"
typedef enum
{
CLK_NONE = 0,
SYS_CLK_PLL3 = 1,
SYS_CLK_PLL7 = 2,
SYS_CLK_PLL9 = 3,
SYS_CLK_PLL10 = 4,
SYS_CLK_PLL3X2 = 5,
SYS_CLK_PLL6 = 6,
SYS_CLK_PLL6x2 = 7,
SYS_CLK_PLL7X2 = 8,
SYS_CLK_MIPIPLL = 9,
MOD_CLK_DEBE0 = 16,
MOD_CLK_DEBE1 = 17,
MOD_CLK_DEFE0 = 18,
MOD_CLK_DEFE1 = 19,
MOD_CLK_LCD0CH0 = 20,
MOD_CLK_LCD0CH1 = 21,
MOD_CLK_LCD1CH0 = 22,
MOD_CLK_LCD1CH1 = 23,
MOD_CLK_HDMI = 24,
MOD_CLK_HDMI_DDC = 25,
MOD_CLK_MIPIDSIS = 26,
MOD_CLK_MIPIDSIP = 27,
MOD_CLK_IEPDRC0 = 28,
MOD_CLK_IEPDRC1 = 29,
MOD_CLK_IEPDEU0 = 30,
MOD_CLK_IEPDEU1 = 31,
MOD_CLK_LVDS = 32,
MOD_CLK_EDP = 33,
MOD_CLK_DEBE2 = 34,
MOD_CLK_DEFE2 = 35,
MOD_CLK_SAT0 = 36,
MOD_CLK_SAT1 = 37,
MOD_CLK_SAT2 = 38,
MOD_CLK_MERGE = 39,
}__disp_clk_id_t;
typedef struct
{
__disp_clk_id_t id; /* clock id */
char *name; /* clock name */
char *src_name;
u32 freq;
struct clk *hdl;
}__disp_clk_t;
extern __disp_clk_t disp_clk_pll_tbl[3];
extern __disp_clk_t disp_clk_mod_tbl[8];
#endif //__DE_CLOCK_H__
|
-- DB Table update
ALTER TABLE `holiday_dates` CHANGE `holiday_duration` `holiday_duration` INT(10) UNSIGNED DEFAULT 0 NOT NULL;
-- Darkmoon Faire
UPDATE `game_event` SET `start_time`= '2020-01-05 00:01:00', `end_time`= '2030-01-01 06:00:00' WHERE `eventEntry`= 3;
-- Lunar Festival. Holiday ID: 327.
UPDATE `game_event` SET `start_time`='2020-01-24 00:01:00', `occurence`='525600', `length`='30240' WHERE `eventEntry`=7;
SET @HOLIDAYID := 327;
SET @DATEID := 14;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 335921152), -- 2020-01-24.
(@HOLIDAYID, @DATEID+1, 352681984), -- 2021-01-23.
(@HOLIDAYID, @DATEID+2, 369459200), -- 2022-01-23.
(@HOLIDAYID, @DATEID+3, 386236416), -- 2023-01-23.
(@HOLIDAYID, @DATEID+4, 403013632), -- 2024-01-23.
(@HOLIDAYID, @DATEID+5, 419774464); -- 2025-01-22.
UPDATE `holiday_dates` SET `holiday_duration`= 360 WHERE `id`= 327;
-- Love is in the air. Holiday ID: 423.
UPDATE `game_event` SET `start_time`='2020-02-08 00:01:00', `occurence`='525600', `length`='20160' WHERE `eventEntry`=8;
SET @HOLIDAYID := 423;
SET @DATEID := 10;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 336707584), -- 2020-02-08.
(@HOLIDAYID, @DATEID+1, 353468416), -- 2021-02-07.
(@HOLIDAYID, @DATEID+2, 370245632), -- 2022-02-07.
(@HOLIDAYID, @DATEID+3, 387022848), -- 2023-02-07.
(@HOLIDAYID, @DATEID+4, 403800064), -- 2024-02-07.
(@HOLIDAYID, @DATEID+5, 420560896); -- 2025-02-06.
-- Pilgrim's Bounty. Holiday ID: 404.
UPDATE `game_event` SET `start_time`='2020-11-23 01:00:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=26;
SET @HOLIDAYID := 404;
SET @DATEID := 11;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 346390592), -- 2020-11-23.
(@HOLIDAYID, @DATEID+1, 363167808), -- 2021-11-23.
(@HOLIDAYID, @DATEID+2, 379945024), -- 2022-11-23.
(@HOLIDAYID, @DATEID+3, 396722240), -- 2023-11-23.
(@HOLIDAYID, @DATEID+4, 413483072), -- 2024-11-22.
(@HOLIDAYID, @DATEID+5, 430260288); -- 2025-11-22.
-- Children's Week. Holiday ID: 201.
UPDATE `game_event` SET `start_time`='2020-05-01 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=10;
SET @HOLIDAYID := 201;
SET @DATEID := 16;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 339738624), -- 2020-05-01.
(@HOLIDAYID, @DATEID+1, 356515840), -- 2021-05-01.
(@HOLIDAYID, @DATEID+2, 373293056), -- 2022-05-01.
(@HOLIDAYID, @DATEID+3, 390070272), -- 2023-05-01.
(@HOLIDAYID, @DATEID+4, 406274048), -- 2024-04-30.
(@HOLIDAYID, @DATEID+5, 423051264); -- 2025-04-30.
-- Noblegarden. Holiday ID: 181.
UPDATE `game_event` SET `start_time`='2020-04-13 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=9;
SET @HOLIDAYID := 181;
SET @DATEID := 13;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 338886656), -- 2020-04-13.
(@HOLIDAYID, @DATEID+1, 355663872), -- 2021-04-13.
(@HOLIDAYID, @DATEID+2, 372441088), -- 2022-04-13.
(@HOLIDAYID, @DATEID+3, 389218304), -- 2023-04-13.
(@HOLIDAYID, @DATEID+4, 405979136), -- 2024-04-12.
(@HOLIDAYID, @DATEID+5, 422756352); -- 2025-04-12.
-- Harvest Festival. Holiday ID: 321.
UPDATE `game_event` SET `start_time`='2020-09-29 00:01:00', `occurence`='525600', `length`='10080' WHERE `eventEntry`=11;
SET @HOLIDAYID := 321;
SET @DATEID := 14;
DELETE FROM `holiday_dates` WHERE `id`=@HOLIDAYID AND `date_id` IN (@DATEID, @DATEID+1, @DATEID+2, @DATEID+3, @DATEID+4, @DATEID+5);
INSERT INTO `holiday_dates` (`id`, `date_id`, `date_value`) VALUES -- DONE.
(@HOLIDAYID, @DATEID, 344391680), -- 2020-09-29.
(@HOLIDAYID, @DATEID+1, 361168896), -- 2021-09-29.
(@HOLIDAYID, @DATEID+2, 377946112), -- 2022-09-29.
(@HOLIDAYID, @DATEID+3, 394723328), -- 2023-09-29.
(@HOLIDAYID, @DATEID+4, 411484160), -- 2024-09-28.
(@HOLIDAYID, @DATEID+5, 428261376); -- 2025-09-28.
|
Ext.define('Ext.rtl.scroll.Indicator', {
override: 'Ext.scroll.Indicator',
privates: {
translateX: function(value) {
if (this.getScroller().getRtl()) {
value = -value;
}
this.callParent([value]);
}
}
});
|
#ifndef __windll_h /* prevent multiple inclusions */
#define __windll_h
#include <windows.h>
#include <assert.h> /* required for all Windows applications */
#include <setjmp.h>
#include "../unzip.h"
#include "../windll/structs.h"
#include "../windll/decs.h"
/* Allow compilation under Borland C++ also */
#ifndef __based
# define __based(A)
#endif
#ifdef UNZIP_INTERNAL
extern jmp_buf dll_error_return;
extern HANDLE hInst; /* current instance */
int win_fprintf(zvoid *pG, FILE *file, unsigned int, char far *);
#endif
#endif /* __windll_h */
|
#include "abstract_crawler.h"
#include "this_thread.h"
#include <boost/date_time.hpp>
using namespace Mysql::Tools::Dump;
my_boost::atomic_uint64_t Abstract_crawler::next_chain_id;
Abstract_crawler::Abstract_crawler(
Mysql::I_callable<bool, const Mysql::Tools::Base::Message_data&>*
message_handler, Simple_id_generator* object_id_generator)
: <API key>(message_handler, object_id_generator)
{}
void Abstract_crawler::<API key>(I_chain_maker* new_chain_maker)
{
m_chain_makers.push_back(new_chain_maker);
}
void Abstract_crawler::process_dump_task(I_dump_task* new_dump_task)
{
<API key>.push_back(new_dump_task);
<API key>* <API key>=
this->new_task_created(new_dump_task);
this-><API key>(<API key>);
for (std::vector<I_chain_maker*>::iterator it= m_chain_makers.begin();
it != m_chain_makers.end(); ++it)
{
uint64 new_chain_id= next_chain_id++;
Chain_data* chain_data= new Chain_data(new_chain_id);
I_object_reader* chain= (*it)->create_chain(chain_data, new_dump_task);
if (chain != NULL)
{
<API key>->set_chain(chain_data);
chain->read_object(
this->new_chain_created(
chain_data, <API key>, chain));
}
else
{
delete chain_data;
}
}
this-><API key>(<API key>);
}
void Abstract_crawler::<API key>()
{
for (std::vector<I_dump_task*>::iterator it= <API key>.begin();
it != <API key>.end(); ++it)
{
while ((*it)->is_completed() == false)
my_boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}
}
bool Abstract_crawler::<API key>()
{
return true;
}
|
int f_test (int x)
{
char arr[SIZE];
return arr[x];
}
|
<?php
/**
* @file
* Contains \Drupal\quickedit\Plugin\<API key>.
*/
namespace Drupal\quickedit\Plugin;
use Drupal\Component\Plugin\<API key>;
use Drupal\Core\Field\<API key>;
/**
* Defines an interface for in-place editors plugins.
*/
interface <API key> extends <API key> {
/**
* Checks whether this in-place editor is compatible with a given field.
*
* @param \Drupal\Core\Field\<API key> $items
* The field values to be in-place edited.
*
* @return bool
* TRUE if it is compatible, FALSE otherwise.
*/
public function isCompatible(<API key> $items);
/**
* Generates metadata that is needed specifically for this editor.
*
* Will only be called by \Drupal\quickedit\<API key>::generate()
* when the passed in field instance & item values will use this editor.
*
* @param \Drupal\Core\Field\<API key> $items
* The field values to be in-place edited.
*
* @return array
* A keyed array with metadata. Each key should be prefixed with the plugin
* ID of the editor.
*/
public function getMetadata(<API key> $items);
/**
* Returns the attachments for this editor.
*
* @return array
* An array of attachments, for use with #attached.
*
* @see <API key>()
*/
public function getAttachments();
}
|
using MixERP.Net.i18n.Resources;
using MixERP.Net.WebControls.<API key>.Helpers;
using System.Web.UI.HtmlControls;
namespace MixERP.Net.WebControls.<API key>
{
public partial class FormView
{
private void AddErrorLabelBottom()
{
using (HtmlGenericControl errorLabel = new HtmlGenericControl())
{
errorLabel.TagName = "div";
errorLabel.ID = "ErrorLabel";
errorLabel.Attributes.Add("class", "big error vpad16");
this.container.Controls.Add(errorLabel);
}
}
private void AddSaveButton(HtmlGenericControl div)
{
using (HtmlInputButton button = new HtmlInputButton())
{
button.ID = "SaveButton";
button.Value = Titles.Save;
button.Attributes.Add("class", "ui small blue button");
div.Controls.Add(button);
}
}
private void <API key>(HtmlGenericControl fields)
{
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "<API key>");
label.InnerText = Titles.StatementReference;
field.Controls.Add(label);
}
using (HtmlTextArea <API key> = new HtmlTextArea())
{
<API key>.ID = "<API key>";
<API key>.Rows = 4;
field.Controls.Add(<API key>);
}
fields.Controls.Add(field);
}
}
private void <API key>(HtmlGenericControl fields)
{
if (!this.DisplaySourceStore)
{
return;
}
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "SourceStoreSelect");
label.InnerText = Titles.DeliverFrom;
field.Controls.Add(label);
}
using (HtmlSelect sourceStoreSelect = new HtmlSelect())
{
sourceStoreSelect.ID = "SourceStoreSelect";
field.Controls.Add(sourceStoreSelect);
}
fields.Controls.Add(field);
}
}
private void <API key>(HtmlGenericControl fields)
{
if (!this.DisplayShipper)
{
return;
}
using (HtmlGenericControl field = FormHelper.GetField())
{
using (HtmlGenericControl label = new HtmlGenericControl())
{
label.TagName = "label";
label.Attributes.Add("for", "<API key>");
label.InnerText = Titles.ShippingCompany;
field.Controls.Add(label);
}
using (HtmlSelect <API key> = new HtmlSelect())
{
<API key>.ID = "<API key>";
field.Controls.Add(<API key>);
}
fields.Controls.Add(field);
}
}
private void CreateBottomPanel()
{
using (HtmlGenericControl fields = FormHelper.GetFields())
{
fields.TagName = "div";
fields.Attributes.Add("class", "ui form");
fields.Attributes.Add("style", "width:290px;");
this.<API key>(fields);
this.<API key>(fields);
this.<API key>(fields);
this.AddSaveButton(fields);
this.container.Controls.Add(fields);
}
}
}
}
|
<?php
?>
<!DOCTYPE html>
<html xmlns="http:
<!-- getlocations_box -->
<head>
<title><?php print $head_title; ?></title>
<?php print $head; ?>
<?php print $styles; ?>
<?php print $scripts; ?>
<style>
/* adjust these to match your colorbox and map size */
body {
width: 500px;
margin: 0;
}
#page {
min-width: 500px;
width: 500px;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
}
#content-area {
}
</style>
</head>
<body class="<?php print $body_classes; ?>">
<div id="page"><div id="page-inner">
<div id="main"><div id="main-inner" class="clear-block">
<div id="content"><div id="content-inner">
<?php if ($title): ?>
<h2 class="title"><?php print $title; ?></h2>
<?php endif; ?>
<div id="content-area">
<?php print $content; ?>
</div>
</div></div>
</div></div>
</div></div>
<?php print $closure; ?>
</body>
</html>
|
/**
* SECTION:<API key>
* @short_description: Create, recognise and parse missing-plugins messages
*
* <refsect2>
* <para>
* Functions to create, recognise and parse missing-plugins messages for
* applications and elements.
* </para>
* <para>
* Missing-plugin messages are posted on the bus by elements like decodebin
* or playbin if they can't find an appropriate source element or decoder
* element. The application can use these messages for two things:
* <itemizedlist>
* <listitem><para>
* concise error/problem reporting to the user mentioning what exactly
* is missing, see <API key>()
* </para></listitem>
* <listitem><para>
* initiate installation of missing plugins, see
* <API key>() and
* <API key>()
* </para></listitem>
* </itemizedlist>
* </para>
* <para>
* Applications may also create missing-plugin messages themselves to install
* required elements that are missing, using the install mechanism mentioned
* above.
* </para>
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h> /* getpid on UNIX */
#endif
#ifdef HAVE_PROCESS_H
# include <process.h> /* getpid on win32 */
#endif
#include "gst/gst-i18n-plugin.h"
#include "pbutils.h"
#include "pbutils-private.h"
#include <string.h>
#define <API key> "gstreamer"
typedef enum
{
<API key> = 0,
<API key>,
<API key>,
<API key>,
<API key>,
<API key>
} GstMissingType;
static const struct
{
GstMissingType type;
const gchar type_string[12];
} <API key>[] = {
{
<API key>, "urisource"}, {
<API key>, "urisink"}, {
<API key>, "element"}, {
<API key>, "decoder"}, {
<API key>, "encoder"}
};
static GstMissingType
<API key> (const GstStructure * s)
{
const gchar *type;
guint i;
type = <API key> (s, "type");
<API key> (type != NULL, <API key>);
for (i = 0; i < G_N_ELEMENTS (<API key>); ++i) {
if (strcmp (<API key>[i].type_string, type) == 0)
return <API key>[i].type;
}
return <API key>;
}
GstCaps *
copy_and_clean_caps (const GstCaps * caps)
{
GstStructure *s;
GstCaps *ret;
ret = gst_caps_copy (caps);
/* make caps easier to interpret, remove common fields that are likely
* to be irrelevant for determining the right plugin (ie. mostly fields
* where template caps usually have the standard MIN - MAX range as value) */
s = <API key> (ret, 0);
<API key> (s, "codec_data");
<API key> (s, "palette_data");
<API key> (s, "pixel-aspect-ratio");
<API key> (s, "framerate");
<API key> (s, "leaf_size");
<API key> (s, "packet_size");
<API key> (s, "block_align");
<API key> (s, "metadata-interval"); /* icy caps */
/* decoders/encoders almost always handle the usual width/height/channel/rate
* range (and if we don't remove this then the app will have a much harder
* time blacklisting formats it has unsuccessfully tried to install before) */
<API key> (s, "width");
<API key> (s, "depth");
<API key> (s, "height");
<API key> (s, "channels");
<API key> (s, "rate");
/* rtp fields */
<API key> (s, "config");
<API key> (s, "clock-rate");
<API key> (s, "clock-base");
<API key> (s, "maxps");
<API key> (s, "seqnum-base");
<API key> (s, "npt-start");
<API key> (s, "npt-stop");
<API key> (s, "play-speed");
<API key> (s, "play-scale");
<API key> (s, "dynamic_range");
return ret;
}
/**
* <API key>:
* @element: the #GstElement posting the message
* @protocol: the URI protocol the missing source needs to implement,
* e.g. "http" or "mms"
*
* Creates a missing-plugin message for @element to notify the application
* that a source element for a particular URI protocol is missing. This
* function is mainly for use in plugins.
*
* Returns: (transfer full): a new #GstMessage, or NULL on error
*/
GstMessage *
<API key> (GstElement * element,
const gchar * protocol)
{
GstStructure *s;
gchar *description;
<API key> (element != NULL, NULL);
<API key> (GST_IS_ELEMENT (element), NULL);
<API key> (protocol != NULL, NULL);
description = <API key> (protocol);
s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING,
"urisource", "detail", G_TYPE_STRING, protocol, "name", G_TYPE_STRING,
description, NULL);
g_free (description);
return <API key> (GST_OBJECT_CAST (element), s);
}
/**
* <API key>:
* @element: the #GstElement posting the message
* @protocol: the URI protocol the missing sink needs to implement,
* e.g. "http" or "smb"
*
* Creates a missing-plugin message for @element to notify the application
* that a sink element for a particular URI protocol is missing. This
* function is mainly for use in plugins.
*
* Returns: (transfer full): a new #GstMessage, or NULL on error
*/
GstMessage *
<API key> (GstElement * element, const gchar * protocol)
{
GstStructure *s;
gchar *description;
<API key> (element != NULL, NULL);
<API key> (GST_IS_ELEMENT (element), NULL);
<API key> (protocol != NULL, NULL);
description = <API key> (protocol);
s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING,
"urisink", "detail", G_TYPE_STRING, protocol, "name", G_TYPE_STRING,
description, NULL);
g_free (description);
return <API key> (GST_OBJECT_CAST (element), s);
}
/**
* <API key>:
* @element: the #GstElement posting the message
* @factory_name: the name of the missing element (element factory),
* e.g. "videoscale" or "cdparanoiasrc"
*
* Creates a missing-plugin message for @element to notify the application
* that a certain required element is missing. This function is mainly for
* use in plugins.
*
* Returns: (transfer full): a new #GstMessage, or NULL on error
*/
GstMessage *
<API key> (GstElement * element,
const gchar * factory_name)
{
GstStructure *s;
gchar *description;
<API key> (element != NULL, NULL);
<API key> (GST_IS_ELEMENT (element), NULL);
<API key> (factory_name != NULL, NULL);
description = <API key> (factory_name);
s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING,
"element", "detail", G_TYPE_STRING, factory_name, "name", G_TYPE_STRING,
description, NULL);
g_free (description);
return <API key> (GST_OBJECT_CAST (element), s);
}
/**
* <API key>:
* @element: the #GstElement posting the message
* @decode_caps: the (fixed) caps for which a decoder element is needed
*
* Creates a missing-plugin message for @element to notify the application
* that a decoder element for a particular set of (fixed) caps is missing.
* This function is mainly for use in plugins.
*
* Returns: (transfer full): a new #GstMessage, or NULL on error
*/
GstMessage *
<API key> (GstElement * element,
const GstCaps * decode_caps)
{
GstStructure *s;
GstCaps *caps;
gchar *description;
<API key> (element != NULL, NULL);
<API key> (GST_IS_ELEMENT (element), NULL);
<API key> (decode_caps != NULL, NULL);
<API key> (GST_IS_CAPS (decode_caps), NULL);
<API key> (!gst_caps_is_any (decode_caps), NULL);
<API key> (!gst_caps_is_empty (decode_caps), NULL);
<API key> (gst_caps_is_fixed (decode_caps), NULL);
description = <API key> (decode_caps);
caps = copy_and_clean_caps (decode_caps);
s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING,
"decoder", "detail", GST_TYPE_CAPS, caps, "name", G_TYPE_STRING,
description, NULL);
gst_caps_unref (caps);
g_free (description);
return <API key> (GST_OBJECT_CAST (element), s);
}
/**
* <API key>:
* @element: the #GstElement posting the message
* @encode_caps: the (fixed) caps for which an encoder element is needed
*
* Creates a missing-plugin message for @element to notify the application
* that an encoder element for a particular set of (fixed) caps is missing.
* This function is mainly for use in plugins.
*
* Returns: (transfer full): a new #GstMessage, or NULL on error
*/
GstMessage *
<API key> (GstElement * element,
const GstCaps * encode_caps)
{
GstStructure *s;
GstCaps *caps;
gchar *description;
<API key> (element != NULL, NULL);
<API key> (GST_IS_ELEMENT (element), NULL);
<API key> (encode_caps != NULL, NULL);
<API key> (GST_IS_CAPS (encode_caps), NULL);
<API key> (!gst_caps_is_any (encode_caps), NULL);
<API key> (!gst_caps_is_empty (encode_caps), NULL);
<API key> (gst_caps_is_fixed (encode_caps), NULL);
description = <API key> (encode_caps);
caps = copy_and_clean_caps (encode_caps);
s = gst_structure_new ("missing-plugin", "type", G_TYPE_STRING,
"encoder", "detail", GST_TYPE_CAPS, caps, "name", G_TYPE_STRING,
description, NULL);
gst_caps_unref (caps);
g_free (description);
return <API key> (GST_OBJECT_CAST (element), s);
}
static gboolean
<API key> (const GstStructure * s, gchar ** p_detail)
{
const gchar *detail;
GType detail_type;
*p_detail = NULL;
detail_type = <API key> (s, "detail");
if (!g_type_is_a (detail_type, G_TYPE_STRING)) {
GST_WARNING ("expected 'detail' field to be of G_TYPE_STRING");
return FALSE;
}
detail = <API key> (s, "detail");
if (detail == NULL || *detail == '\0') {
GST_WARNING ("empty 'detail' field");
return FALSE;
}
*p_detail = g_strdup (detail);
return TRUE;
}
static gboolean
<API key> (const GstStructure * s, GstCaps ** p_caps)
{
const GstCaps *caps;
const GValue *val;
GType detail_type;
*p_caps = NULL;
detail_type = <API key> (s, "detail");
if (!g_type_is_a (detail_type, GST_TYPE_CAPS)) {
GST_WARNING ("expected 'detail' field to be of GST_TYPE_CAPS");
return FALSE;
}
val = <API key> (s, "detail");
caps = gst_value_get_caps (val);
if (gst_caps_is_empty (caps) || gst_caps_is_any (caps)) {
GST_WARNING ("EMPTY or ANY caps not allowed");
return FALSE;
}
*p_caps = gst_caps_copy (caps);
return TRUE;
}
/**
* <API key>:
* @msg: a missing-plugin #GstMessage of type #GST_MESSAGE_ELEMENT
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*/
gchar *
<API key> (GstMessage * msg)
{
GstMissingType missing_type;
const gchar *progname;
const gchar *type;
GString *str = NULL;
gchar *detail = NULL;
gchar *desc;
<API key> (<API key> (msg), NULL);
GST_LOG ("Parsing missing-plugin message: %" GST_PTR_FORMAT, msg->structure);
missing_type = <API key> (msg->structure);
if (missing_type == <API key>) {
GST_WARNING ("couldn't parse 'type' field");
goto error;
}
type = <API key> (msg->structure, "type");
g_assert (type != NULL); /* validity already checked above */
/* FIXME: use <API key>() here too */
str = g_string_new (<API key> "|");
<API key> (str, "%u.%u|", GST_VERSION_MAJOR, GST_VERSION_MINOR);
progname = (const gchar *) g_get_prgname ();
if (progname) {
<API key> (str, "%s|", progname);
} else {
<API key> (str, "pid/%lu|", (gulong) getpid ());
}
desc = <API key> (msg);
if (desc) {
g_strdelimit (desc, "|", '
<API key> (str, "%s|", desc);
g_free (desc);
} else {
g_string_append (str, "|");
}
switch (missing_type) {
case <API key>:
case <API key>:
case <API key>:
if (!<API key> (msg->structure, &detail))
goto error;
break;
case <API key>:
case <API key>:{
GstCaps *caps = NULL;
if (!<API key> (msg->structure, &caps))
goto error;
detail = gst_caps_to_string (caps);
gst_caps_unref (caps);
break;
}
default:
<API key> (NULL);
}
<API key> (str, "%s-%s", type, detail);
g_free (detail);
return g_string_free (str, FALSE);
/* ERRORS */
error:
{
GST_WARNING ("Failed to parse missing-plugin msg: %" GST_PTR_FORMAT, msg);
if (str)
g_string_free (str, TRUE);
return NULL;
}
}
/**
* <API key>:
* @msg: a missing-plugin #GstMessage of type #GST_MESSAGE_ELEMENT
*
* Returns a localised string describing the missing feature, for use in
* error dialogs and the like. Should never return NULL unless @msg is not
* a valid missing-plugin message.
*
* This function is mainly for applications that need a human-readable string
* describing a missing plugin, given a previously collected missing-plugin
* message
*
* Returns: a newly-allocated description string, or NULL on error. Free
* string with g_free() when not needed any longer.
*/
gchar *
<API key> (GstMessage * msg)
{
GstMissingType missing_type;
const gchar *desc;
gchar *ret = NULL;
<API key> (<API key> (msg), NULL);
GST_LOG ("Parsing missing-plugin message: %" GST_PTR_FORMAT, msg->structure);
desc = <API key> (msg->structure, "name");
if (desc != NULL && *desc != '\0') {
ret = g_strdup (desc);
goto done;
}
/* fallback #1 */
missing_type = <API key> (msg->structure);
switch (missing_type) {
case <API key>:
case <API key>:
case <API key>:{
gchar *detail = NULL;
if (<API key> (msg->structure, &detail)) {
if (missing_type == <API key>)
ret = <API key> (detail);
else if (missing_type == <API key>)
ret = <API key> (detail);
else
ret = <API key> (detail);
g_free (detail);
}
break;
}
case <API key>:
case <API key>:{
GstCaps *caps = NULL;
if (<API key> (msg->structure, &caps)) {
if (missing_type == <API key>)
ret = <API key> (caps);
else
ret = <API key> (caps);
gst_caps_unref (caps);
}
break;
}
default:
break;
}
if (ret)
goto done;
/* fallback #2 */
switch (missing_type) {
case <API key>:
desc = _("Unknown source element");
break;
case <API key>:
desc = _("Unknown sink element");
break;
case <API key>:
desc = _("Unknown element");
break;
case <API key>:
desc = _("Unknown decoder element");
break;
case <API key>:
desc = _("Unknown encoder element");
break;
default:
/* we should really never get here, but we better still return
* something if we do */
desc = _("Plugin or element of unknown type");
break;
}
ret = g_strdup (desc);
done:
GST_LOG ("returning '%s'", ret);
return ret;
}
/**
* <API key>:
* @msg: a #GstMessage
*
* Checks whether @msg is a missing plugins message.
*
* Returns: %TRUE if @msg is a missing-plugins message, otherwise %FALSE.
*/
gboolean
<API key> (GstMessage * msg)
{
<API key> (msg != NULL, FALSE);
<API key> (GST_IS_MESSAGE (msg), FALSE);
if (GST_MESSAGE_TYPE (msg) != GST_MESSAGE_ELEMENT || msg->structure == NULL)
return FALSE;
return <API key> (msg->structure, "missing-plugin");
}
/* takes ownership of the description */
static gchar *
<API key> (gchar * description, const gchar * type,
const gchar * detail)
{
const gchar *progname;
GString *s;
s = g_string_new (<API key> "|");
<API key> (s, "%u.%u|", GST_VERSION_MAJOR, GST_VERSION_MINOR);
progname = (const gchar *) g_get_prgname ();
if (progname) {
<API key> (s, "%s|", progname);
} else {
<API key> (s, "pid/%lu|", (gulong) getpid ());
}
if (description) {
g_strdelimit (description, "|", '
<API key> (s, "%s|", description);
g_free (description);
} else {
g_string_append (s, "|");
}
<API key> (s, "%s-%s", type, detail);
return g_string_free (s, FALSE);
}
/**
* <API key>:
* @protocol: the URI protocol the missing source needs to implement,
* e.g. "http" or "mms"
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions in
* the case where the application knows exactly what kind of plugin it is
* missing.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*
* Since: 0.10.15
*/
gchar *
<API key> (const gchar * protocol)
{
gchar *desc;
<API key> (protocol != NULL, NULL);
desc = <API key> (protocol);
return <API key> (desc, "urisource", protocol);
}
/**
* <API key>:
* @protocol: the URI protocol the missing source needs to implement,
* e.g. "http" or "mms"
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions in
* the case where the application knows exactly what kind of plugin it is
* missing.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*
* Since: 0.10.15
*/
gchar *
<API key> (const gchar * protocol)
{
gchar *desc;
<API key> (protocol != NULL, NULL);
desc = <API key> (protocol);
return <API key> (desc, "urisink", protocol);
}
/**
* <API key>:
* @factory_name: the name of the missing element (element factory),
* e.g. "videoscale" or "cdparanoiasrc"
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions in
* the case where the application knows exactly what kind of plugin it is
* missing.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*
* Since: 0.10.15
*/
gchar *
<API key> (const gchar * factory_name)
{
gchar *desc;
<API key> (factory_name != NULL, NULL);
desc = <API key> (factory_name);
return <API key> (desc, "element", factory_name);
}
/**
* <API key>:
* @decode_caps: the (fixed) caps for which a decoder element is needed
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions in
* the case where the application knows exactly what kind of plugin it is
* missing.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*
* Since: 0.10.15
*/
gchar *
<API key> (const GstCaps * decode_caps)
{
GstCaps *caps;
gchar *detail_str, *caps_str, *desc;
<API key> (decode_caps != NULL, NULL);
<API key> (GST_IS_CAPS (decode_caps), NULL);
<API key> (!gst_caps_is_any (decode_caps), NULL);
<API key> (!gst_caps_is_empty (decode_caps), NULL);
<API key> (gst_caps_is_fixed (decode_caps), NULL);
desc = <API key> (decode_caps);
caps = copy_and_clean_caps (decode_caps);
caps_str = gst_caps_to_string (caps);
detail_str = <API key> (desc, "decoder", caps_str);
g_free (caps_str);
gst_caps_unref (caps);
return detail_str;
}
/**
* <API key>:
* @encode_caps: the (fixed) caps for which an encoder element is needed
*
* Returns an opaque string containing all the details about the missing
* element to be passed to an external installer called via
* <API key>() or <API key>().
*
* This function is mainly for applications that call external plugin
* installation mechanisms using one of the two above-mentioned functions in
* the case where the application knows exactly what kind of plugin it is
* missing.
*
* Returns: a newly-allocated detail string, or NULL on error. Free string
* with g_free() when not needed any longer.
*
* Since: 0.10.15
*/
gchar *
<API key> (const GstCaps * encode_caps)
{
GstCaps *caps;
gchar *detail_str, *caps_str, *desc;
<API key> (encode_caps != NULL, NULL);
<API key> (GST_IS_CAPS (encode_caps), NULL);
<API key> (!gst_caps_is_any (encode_caps), NULL);
<API key> (!gst_caps_is_empty (encode_caps), NULL);
<API key> (gst_caps_is_fixed (encode_caps), NULL);
desc = <API key> (encode_caps);
caps = copy_and_clean_caps (encode_caps);
caps_str = gst_caps_to_string (caps);
detail_str = <API key> (desc, "encoder", caps_str);
g_free (caps_str);
gst_caps_unref (caps);
return detail_str;
}
|
/* This program is free software; you can redistribute it and/or modify */
/* (at your option) any later version. */
/* This program is distributed in the hope that it will be useful, */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See */
/* along with this program; if not, write to the Free Software Foundation, */
/* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
/* History: Porting from Crackerjack to LTP is done by */
/* Manas Kumar Nayak maknayak@in.ibm.com> */
/* Description: This tests the rt_sigaction() syscall */
/* rt_sigaction Expected EFAULT error check */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/syscall.h>
#include <string.h>
#include "test.h"
#include "<API key>.h"
#include "lapi/rt_sigaction.h"
char *TCID = "rt_sigaction02";
static int testno;
int TST_TOTAL = 1;
void cleanup(void)
{
tst_rmdir();
tst_exit();
}
void setup(void)
{
TEST_PAUSE;
tst_tmpdir();
}
static int test_flags[] =
{ SA_RESETHAND | SA_SIGINFO, SA_RESETHAND, SA_RESETHAND | SA_SIGINFO,
SA_RESETHAND | SA_SIGINFO, SA_NOMASK };
char *test_flags_list[] =
{ "SA_RESETHAND|SA_SIGINFO", "SA_RESETHAND", "SA_RESETHAND|SA_SIGINFO",
"SA_RESETHAND|SA_SIGINFO", "SA_NOMASK" };
static struct test_case_t {
int exp_errno;
char *errdesc;
} test_cases[] = {
{
EFAULT, "EFAULT"}
};
int main(int ac, char **av)
{
unsigned int flag;
int signal;
int lc;
tst_parse_opts(ac, av, NULL, NULL);
setup();
for (lc = 0; TEST_LOOPING(lc); ++lc) {
tst_count = 0;
for (testno = 0; testno < TST_TOTAL; ++testno) {
for (signal = SIGRTMIN; signal <= SIGRTMAX; signal++) {
tst_resm(TINFO, "Signal %d", signal);
for (flag = 0; flag < ARRAY_SIZE(test_flags); flag++) {
/* *
* long sys_rt_sigaction (int sig, const struct sigaction *act, *
* truct sigaction *oact, size_t sigsetsize); *
* EFAULT: *
* An invalid act or oact value was specified *
*/
TEST(ltp_rt_sigaction(signal,
INVAL_SA_PTR, NULL, SIGSETSIZE));
if ((TEST_RETURN == -1)
&& (TEST_ERRNO ==
test_cases[0].exp_errno)) {
tst_resm(TINFO,
"sa.sa_flags = %s ",
test_flags_list[flag]);
tst_resm(TPASS,
"%s failure with sig: %d as expected errno = %s : %s",
TCID, signal,
test_cases[0].errdesc,
strerror(TEST_ERRNO));
} else {
tst_resm(TFAIL,
"rt_sigaction call succeeded: result = %ld got error %d:but expected %d",
TEST_RETURN,
TEST_ERRNO,
test_cases[0].
exp_errno);
tst_resm(TINFO,
"sa.sa_flags = %s ",
test_flags_list[flag]);
}
}
}
}
}
cleanup();
tst_exit();
}
|
/*
* Following is how we use various fields and flags of underlying
* struct page(s) to form a zspage.
*
* Usage of struct page fields:
* page->first_page: points to the first component (0-order) page
* page->index (union with page->freelist): offset of the first object
* starting in this page. For the first page, this is
* always 0, so we use this field (aka freelist) to point
* to the first free object in zspage.
* page->lru: links together all component pages (except the first page)
* of a zspage
*
* For _first_ page only:
*
* page->private (union with page->first_page): refers to the
* component page after the first page
* If the page is first_page for huge object, it stores handle.
* Look at size_class->huge.
* page->freelist: points to the first free object in zspage.
* Free objects are linked together using in-place
* metadata.
* page->objects: maximum number of objects we can store in this
* zspage (class->zspage_order * PAGE_SIZE / class->size)
* page->lru: links together first pages of various zspages.
* Basically forming list of zspages in a fullness group.
* page->mapping: class index and fullness group of the zspage
*
* Usage of struct page flags:
* PG_private: identifies the first component page
* PG_private2: identifies the last component page
*
*/
#ifdef <API key>
#define DEBUG
#endif
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/bitops.h>
#include <linux/errno.h>
#include <linux/highmem.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <asm/tlbflush.h>
#include <asm/pgtable.h>
#include <linux/cpumask.h>
#include <linux/cpu.h>
#include <linux/vmalloc.h>
#include <linux/hardirq.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/debugfs.h>
#include <linux/zsmalloc.h>
#include <linux/zpool.h>
/*
* This must be power of 2 and greater than of equal to sizeof(link_free).
* These two conditions ensure that any 'struct link_free' itself doesn't
* span more than 1 page which avoids complex case of mapping 2 pages simply
* to restore link_free pointer values.
*/
#define ZS_ALIGN 8
/*
* A single 'zspage' is composed of up to 2^N discontiguous 0-order (single)
* pages. ZS_MAX_ZSPAGE_ORDER defines upper limit on N.
*/
#define ZS_MAX_ZSPAGE_ORDER 2
#define <API key> (_AC(1, UL) << ZS_MAX_ZSPAGE_ORDER)
#define ZS_HANDLE_SIZE (sizeof(unsigned long))
/*
* Object location (<PFN>, <obj_idx>) is encoded as
* as single (unsigned long) handle value.
*
* Note that object index <obj_idx> is relative to system
* page <PFN> it is stored in, so for each sub-page belonging
* to a zspage, obj_idx starts with 0.
*
* This is made more complicated by various memory models and PAE.
*/
#ifndef MAX_PHYSMEM_BITS
#ifdef CONFIG_HIGHMEM64G
#define MAX_PHYSMEM_BITS 36
#else /* !CONFIG_HIGHMEM64G */
/*
* If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
* be PAGE_SHIFT
*/
#define MAX_PHYSMEM_BITS BITS_PER_LONG
#endif
#endif
#define _PFN_BITS (MAX_PHYSMEM_BITS - PAGE_SHIFT)
/*
* Memory for allocating for handle keeps object position by
* encoding <page, obj_idx> and the encoded value has a room
* in least bit(ie, look at obj_to_location).
* We use the bit to synchronize between object access by
* user and migration.
*/
#define HANDLE_PIN_BIT 0
/*
* Head in allocated object should have OBJ_ALLOCATED_TAG
* to identify the object was allocated or not.
* It's okay to add the status bit in the least bit because
* header keeps handle which is 4byte-aligned address so we
* have room for two bit at least.
*/
#define OBJ_ALLOCATED_TAG 1
#define OBJ_TAG_BITS 1
#define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS - OBJ_TAG_BITS)
#define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
#define MAX(a, b) ((a) >= (b) ? (a) : (b))
/* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
#define ZS_MIN_ALLOC_SIZE \
MAX(32, (<API key> << PAGE_SHIFT >> OBJ_INDEX_BITS))
/* each chunk includes extra space to keep handle */
#define ZS_MAX_ALLOC_SIZE PAGE_SIZE
/*
* On systems with 4K page size, this gives 255 size classes! There is a
* trader-off here:
* - Large number of size classes is potentially wasteful as free page are
* spread across these classes
* - Small number of size classes causes large internal fragmentation
* - Probably its better to use specific size classes (empirically
* determined). NOTE: all those class sizes must be set as multiple of
* ZS_ALIGN to make sure link_free itself never has to span 2 pages.
*
* ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
* (reason above)
*/
#define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> 8)
/*
* We do not maintain any list for completely empty or full pages
*/
enum fullness_group {
ZS_ALMOST_FULL,
ZS_ALMOST_EMPTY,
<API key>,
ZS_EMPTY,
ZS_FULL
};
enum zs_stat_type {
OBJ_ALLOCATED,
OBJ_USED,
CLASS_ALMOST_FULL,
CLASS_ALMOST_EMPTY,
NR_ZS_STAT_TYPE,
};
#ifdef <API key>
static struct dentry *zs_stat_root;
struct zs_size_stat {
unsigned long objs[NR_ZS_STAT_TYPE];
};
#endif
/*
* number of size_classes
*/
static int zs_size_classes;
/*
* We assign a page to ZS_ALMOST_EMPTY fullness group when:
* n <= N / f, where
* n = number of allocated objects
* N = total number of objects zspage can store
* f = <API key>
*
* Similarly, we assign zspage to:
* ZS_ALMOST_FULL when n > N / f
* ZS_EMPTY when n == 0
* ZS_FULL when n == N
*
* (see: fix_fullness_group())
*/
static const int <API key> = 4;
struct size_class {
/*
* Size of objects stored in this class. Must be multiple
* of ZS_ALIGN.
*/
int size;
unsigned int index;
/* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
int pages_per_zspage;
/* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
bool huge;
#ifdef <API key>
struct zs_size_stat stats;
#endif
spinlock_t lock;
struct page *fullness_list[<API key>];
};
/*
* Placed within free objects to form a singly linked list.
* For every zspage, first_page->freelist gives head of this list.
*
* This must be power of 2 and less than or equal to ZS_ALIGN
*/
struct link_free {
union {
/*
* Position of next free chunk (encodes <PFN, obj_idx>)
* It's valid for non-allocated object
*/
void *next;
/*
* Handle of allocated object.
*/
unsigned long handle;
};
};
struct zs_pool {
char *name;
struct size_class **size_class;
struct kmem_cache *handle_cachep;
gfp_t flags; /* allocation flags used when growing pool */
atomic_long_t pages_allocated;
#ifdef <API key>
struct dentry *stat_dentry;
#endif
};
/*
* A zspage's class index and fullness group
* are encoded in its (first)page->mapping
*/
#define CLASS_IDX_BITS 28
#define FULLNESS_BITS 4
#define CLASS_IDX_MASK ((1 << CLASS_IDX_BITS) - 1)
#define FULLNESS_MASK ((1 << FULLNESS_BITS) - 1)
struct mapping_area {
#ifdef <API key>
struct vm_struct *vm; /* vm area for mapping object that span pages */
#else
char *vm_buf; /* copy buffer for objects that span pages */
#endif
char *vm_addr; /* address of kmap_atomic()'ed pages */
enum zs_mapmode vm_mm; /* mapping mode */
bool huge;
};
static int create_handle_cache(struct zs_pool *pool)
{
pool->handle_cachep = kmem_cache_create("zs_handle", ZS_HANDLE_SIZE,
0, 0, NULL);
return pool->handle_cachep ? 0 : 1;
}
static void <API key>(struct zs_pool *pool)
{
if (pool->handle_cachep)
kmem_cache_destroy(pool->handle_cachep);
}
static unsigned long alloc_handle(struct zs_pool *pool)
{
return (unsigned long)kmem_cache_alloc(pool->handle_cachep,
pool->flags & ~__GFP_HIGHMEM);
}
static void free_handle(struct zs_pool *pool, unsigned long handle)
{
kmem_cache_free(pool->handle_cachep, (void *)handle);
}
static void record_obj(unsigned long handle, unsigned long obj)
{
/*
* lsb of @obj represents handle lock while other bits
* represent object value the handle is pointing so
* updating shouldn't do store tearing.
*/
WRITE_ONCE(*(unsigned long *)handle, obj);
}
/* zpool driver */
#ifdef CONFIG_ZPOOL
static void *zs_zpool_create(char *name, gfp_t gfp, struct zpool_ops *zpool_ops)
{
return zs_create_pool(name, gfp);
}
static void zs_zpool_destroy(void *pool)
{
zs_destroy_pool(pool);
}
static int zs_zpool_malloc(void *pool, size_t size, gfp_t gfp,
unsigned long *handle)
{
*handle = zs_malloc(pool, size);
return *handle ? 0 : -1;
}
static void zs_zpool_free(void *pool, unsigned long handle)
{
zs_free(pool, handle);
}
static int zs_zpool_shrink(void *pool, unsigned int pages,
unsigned int *reclaimed)
{
return -EINVAL;
}
static void *zs_zpool_map(void *pool, unsigned long handle,
enum zpool_mapmode mm)
{
enum zs_mapmode zs_mm;
switch (mm) {
case ZPOOL_MM_RO:
zs_mm = ZS_MM_RO;
break;
case ZPOOL_MM_WO:
zs_mm = ZS_MM_WO;
break;
case ZPOOL_MM_RW: /* fallthru */
default:
zs_mm = ZS_MM_RW;
break;
}
return zs_map_object(pool, handle, zs_mm);
}
static void zs_zpool_unmap(void *pool, unsigned long handle)
{
zs_unmap_object(pool, handle);
}
static u64 zs_zpool_total_size(void *pool)
{
return zs_get_total_pages(pool) << PAGE_SHIFT;
}
static struct zpool_driver zs_zpool_driver = {
.type = "zsmalloc",
.owner = THIS_MODULE,
.create = zs_zpool_create,
.destroy = zs_zpool_destroy,
.malloc = zs_zpool_malloc,
.free = zs_zpool_free,
.shrink = zs_zpool_shrink,
.map = zs_zpool_map,
.unmap = zs_zpool_unmap,
.total_size = zs_zpool_total_size,
};
MODULE_ALIAS("zpool-zsmalloc");
#endif /* CONFIG_ZPOOL */
static unsigned int <API key>(int size, int pages_per_zspage)
{
return pages_per_zspage * PAGE_SIZE / size;
}
/* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
static DEFINE_PER_CPU(struct mapping_area, zs_map_area);
static int is_first_page(struct page *page)
{
return PagePrivate(page);
}
static int is_last_page(struct page *page)
{
return PagePrivate2(page);
}
static void get_zspage_mapping(struct page *page, unsigned int *class_idx,
enum fullness_group *fullness)
{
unsigned long m;
BUG_ON(!is_first_page(page));
m = (unsigned long)page->mapping;
*fullness = m & FULLNESS_MASK;
*class_idx = (m >> FULLNESS_BITS) & CLASS_IDX_MASK;
}
static void set_zspage_mapping(struct page *page, unsigned int class_idx,
enum fullness_group fullness)
{
unsigned long m;
BUG_ON(!is_first_page(page));
m = ((class_idx & CLASS_IDX_MASK) << FULLNESS_BITS) |
(fullness & FULLNESS_MASK);
page->mapping = (struct address_space *)m;
}
/*
* zsmalloc divides the pool into various size classes where each
* class maintains a list of zspages where each zspage is divided
* into equal sized chunks. Each allocation falls into one of these
* classes depending on its size. This function returns index of the
* size class which has chunk size big enough to hold the give size.
*/
static int <API key>(int size)
{
int idx = 0;
if (likely(size > ZS_MIN_ALLOC_SIZE))
idx = DIV_ROUND_UP(size - ZS_MIN_ALLOC_SIZE,
ZS_SIZE_CLASS_DELTA);
return min(zs_size_classes - 1, idx);
}
#ifdef <API key>
static inline void zs_stat_inc(struct size_class *class,
enum zs_stat_type type, unsigned long cnt)
{
class->stats.objs[type] += cnt;
}
static inline void zs_stat_dec(struct size_class *class,
enum zs_stat_type type, unsigned long cnt)
{
class->stats.objs[type] -= cnt;
}
static inline unsigned long zs_stat_get(struct size_class *class,
enum zs_stat_type type)
{
return class->stats.objs[type];
}
static int __init zs_stat_init(void)
{
if (!debugfs_initialized())
return -ENODEV;
zs_stat_root = debugfs_create_dir("zsmalloc", NULL);
if (!zs_stat_root)
return -ENOMEM;
return 0;
}
static void __exit zs_stat_exit(void)
{
<API key>(zs_stat_root);
}
static int zs_stats_size_show(struct seq_file *s, void *v)
{
int i;
struct zs_pool *pool = s->private;
struct size_class *class;
int objs_per_zspage;
unsigned long class_almost_full, class_almost_empty;
unsigned long obj_allocated, obj_used, pages_used;
unsigned long <API key> = 0, <API key> = 0;
unsigned long total_objs = 0, total_used_objs = 0, total_pages = 0;
seq_printf(s, " %5s %5s %11s %12s %13s %10s %10s %16s\n",
"class", "size", "almost_full", "almost_empty",
"obj_allocated", "obj_used", "pages_used",
"pages_per_zspage");
for (i = 0; i < zs_size_classes; i++) {
class = pool->size_class[i];
if (class->index != i)
continue;
spin_lock(&class->lock);
class_almost_full = zs_stat_get(class, CLASS_ALMOST_FULL);
class_almost_empty = zs_stat_get(class, CLASS_ALMOST_EMPTY);
obj_allocated = zs_stat_get(class, OBJ_ALLOCATED);
obj_used = zs_stat_get(class, OBJ_USED);
spin_unlock(&class->lock);
objs_per_zspage = <API key>(class->size,
class->pages_per_zspage);
pages_used = obj_allocated / objs_per_zspage *
class->pages_per_zspage;
seq_printf(s, " %5u %5u %11lu %12lu %13lu %10lu %10lu %16d\n",
i, class->size, class_almost_full, class_almost_empty,
obj_allocated, obj_used, pages_used,
class->pages_per_zspage);
<API key> += class_almost_full;
<API key> += class_almost_empty;
total_objs += obj_allocated;
total_used_objs += obj_used;
total_pages += pages_used;
}
seq_puts(s, "\n");
seq_printf(s, " %5s %5s %11lu %12lu %13lu %10lu %10lu\n",
"Total", "", <API key>,
<API key>, total_objs,
total_used_objs, total_pages);
return 0;
}
static int zs_stats_size_open(struct inode *inode, struct file *file)
{
return single_open(file, zs_stats_size_show, inode->i_private);
}
static const struct file_operations zs_stat_size_ops = {
.open = zs_stats_size_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int zs_pool_stat_create(char *name, struct zs_pool *pool)
{
struct dentry *entry;
if (!zs_stat_root)
return -ENODEV;
entry = debugfs_create_dir(name, zs_stat_root);
if (!entry) {
pr_warn("debugfs dir <%s> creation failed\n", name);
return -ENOMEM;
}
pool->stat_dentry = entry;
entry = debugfs_create_file("classes", S_IFREG | S_IRUGO,
pool->stat_dentry, pool, &zs_stat_size_ops);
if (!entry) {
pr_warn("%s: debugfs file entry <%s> creation failed\n",
name, "classes");
return -ENOMEM;
}
return 0;
}
static void <API key>(struct zs_pool *pool)
{
<API key>(pool->stat_dentry);
}
#else /* <API key> */
static inline void zs_stat_inc(struct size_class *class,
enum zs_stat_type type, unsigned long cnt)
{
}
static inline void zs_stat_dec(struct size_class *class,
enum zs_stat_type type, unsigned long cnt)
{
}
static inline unsigned long zs_stat_get(struct size_class *class,
enum zs_stat_type type)
{
return 0;
}
static int __init zs_stat_init(void)
{
return 0;
}
static void __exit zs_stat_exit(void)
{
}
static inline int zs_pool_stat_create(char *name, struct zs_pool *pool)
{
return 0;
}
static inline void <API key>(struct zs_pool *pool)
{
}
#endif
/*
* For each size class, zspages are divided into different groups
* depending on how "full" they are. This was done so that we could
* easily find empty or nearly empty zspages when we try to shrink
* the pool (not yet implemented). This function returns fullness
* status of the given page.
*/
static enum fullness_group get_fullness_group(struct page *page)
{
int inuse, max_objects;
enum fullness_group fg;
BUG_ON(!is_first_page(page));
inuse = page->inuse;
max_objects = page->objects;
if (inuse == 0)
fg = ZS_EMPTY;
else if (inuse == max_objects)
fg = ZS_FULL;
else if (inuse <= 3 * max_objects / <API key>)
fg = ZS_ALMOST_EMPTY;
else
fg = ZS_ALMOST_FULL;
return fg;
}
/*
* Each size class maintains various freelists and zspages are assigned
* to one of these freelists based on the number of live objects they
* have. This functions inserts the given zspage into the freelist
* identified by <class, fullness_group>.
*/
static void insert_zspage(struct page *page, struct size_class *class,
enum fullness_group fullness)
{
struct page **head;
BUG_ON(!is_first_page(page));
if (fullness >= <API key>)
return;
head = &class->fullness_list[fullness];
if (*head)
list_add_tail(&page->lru, &(*head)->lru);
*head = page;
zs_stat_inc(class, fullness == ZS_ALMOST_EMPTY ?
CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
}
/*
* This function removes the given zspage from the freelist identified
* by <class, fullness_group>.
*/
static void remove_zspage(struct page *page, struct size_class *class,
enum fullness_group fullness)
{
struct page **head;
BUG_ON(!is_first_page(page));
if (fullness >= <API key>)
return;
head = &class->fullness_list[fullness];
BUG_ON(!*head);
if (list_empty(&(*head)->lru))
*head = NULL;
else if (*head == page)
*head = (struct page *)list_entry((*head)->lru.next,
struct page, lru);
list_del_init(&page->lru);
zs_stat_dec(class, fullness == ZS_ALMOST_EMPTY ?
CLASS_ALMOST_EMPTY : CLASS_ALMOST_FULL, 1);
}
/*
* Each size class maintains zspages in different fullness groups depending
* on the number of live objects they contain. When allocating or freeing
* objects, the fullness status of the page can change, say, from ALMOST_FULL
* to ALMOST_EMPTY when freeing an object. This function checks if such
* a status change has occurred for the given page and accordingly moves the
* page from the freelist of the old fullness group to that of the new
* fullness group.
*/
static enum fullness_group fix_fullness_group(struct size_class *class,
struct page *page)
{
int class_idx;
enum fullness_group currfg, newfg;
BUG_ON(!is_first_page(page));
get_zspage_mapping(page, &class_idx, &currfg);
newfg = get_fullness_group(page);
if (newfg == currfg)
goto out;
remove_zspage(page, class, currfg);
insert_zspage(page, class, newfg);
set_zspage_mapping(page, class_idx, newfg);
out:
return newfg;
}
/*
* We have to decide on how many pages to link together
* to form a zspage for each size class. This is important
* to reduce wastage due to unusable space left at end of
* each zspage which is given as:
* wastage = Zp % class_size
* usage = Zp - wastage
* where Zp = zspage size = k * PAGE_SIZE where k = 1, 2, ...
*
* For example, for size class of 3/8 * PAGE_SIZE, we should
* link together 3 PAGE_SIZE sized pages to form a zspage
* since then we can perfectly fit in 8 such objects.
*/
static int <API key>(int class_size)
{
int i, max_usedpc = 0;
/* zspage order which gives maximum used size per KB */
int max_usedpc_order = 1;
for (i = 1; i <= <API key>; i++) {
int zspage_size;
int waste, usedpc;
zspage_size = i * PAGE_SIZE;
waste = zspage_size % class_size;
usedpc = (zspage_size - waste) * 100 / zspage_size;
if (usedpc > max_usedpc) {
max_usedpc = usedpc;
max_usedpc_order = i;
}
}
return max_usedpc_order;
}
/*
* A single 'zspage' is composed of many system pages which are
* linked together using fields in struct page. This function finds
* the first/head page, given any component page of a zspage.
*/
static struct page *get_first_page(struct page *page)
{
if (is_first_page(page))
return page;
else
return page->first_page;
}
static struct page *get_next_page(struct page *page)
{
struct page *next;
if (is_last_page(page))
next = NULL;
else if (is_first_page(page))
next = (struct page *)page_private(page);
else
next = list_entry(page->lru.next, struct page, lru);
return next;
}
/*
* Encode <page, obj_idx> as a single handle value.
* We use the least bit of handle for tagging.
*/
static void *location_to_obj(struct page *page, unsigned long obj_idx)
{
unsigned long obj;
if (!page) {
BUG_ON(obj_idx);
return NULL;
}
obj = page_to_pfn(page) << OBJ_INDEX_BITS;
obj |= ((obj_idx) & OBJ_INDEX_MASK);
obj <<= OBJ_TAG_BITS;
return (void *)obj;
}
/*
* Decode <page, obj_idx> pair from the given object handle. We adjust the
* decoded obj_idx back to its original value since it was adjusted in
* location_to_obj().
*/
static void obj_to_location(unsigned long obj, struct page **page,
unsigned long *obj_idx)
{
obj >>= OBJ_TAG_BITS;
*page = pfn_to_page(obj >> OBJ_INDEX_BITS);
*obj_idx = (obj & OBJ_INDEX_MASK);
}
static unsigned long handle_to_obj(unsigned long handle)
{
return *(unsigned long *)handle;
}
static unsigned long obj_to_head(struct size_class *class, struct page *page,
void *obj)
{
if (class->huge) {
VM_BUG_ON(!is_first_page(page));
return *(unsigned long *)page_private(page);
} else
return *(unsigned long *)obj;
}
static unsigned long obj_idx_to_offset(struct page *page,
unsigned long obj_idx, int class_size)
{
unsigned long off = 0;
if (!is_first_page(page))
off = page->index;
return off + obj_idx * class_size;
}
static inline int trypin_tag(unsigned long handle)
{
unsigned long *ptr = (unsigned long *)handle;
return !<API key>(HANDLE_PIN_BIT, ptr);
}
static void pin_tag(unsigned long handle)
{
while (!trypin_tag(handle));
}
static void unpin_tag(unsigned long handle)
{
unsigned long *ptr = (unsigned long *)handle;
clear_bit_unlock(HANDLE_PIN_BIT, ptr);
}
static void reset_page(struct page *page)
{
clear_bit(PG_private, &page->flags);
clear_bit(PG_private_2, &page->flags);
set_page_private(page, 0);
page->mapping = NULL;
page->freelist = NULL;
page_mapcount_reset(page);
}
static void free_zspage(struct page *first_page)
{
struct page *nextp, *tmp, *head_extra;
BUG_ON(!is_first_page(first_page));
BUG_ON(first_page->inuse);
head_extra = (struct page *)page_private(first_page);
reset_page(first_page);
__free_page(first_page);
/* zspage with only 1 system page */
if (!head_extra)
return;
<API key>(nextp, tmp, &head_extra->lru, lru) {
list_del(&nextp->lru);
reset_page(nextp);
__free_page(nextp);
}
reset_page(head_extra);
__free_page(head_extra);
}
/* Initialize a newly allocated zspage */
static void init_zspage(struct page *first_page, struct size_class *class)
{
unsigned long off = 0;
struct page *page = first_page;
BUG_ON(!is_first_page(first_page));
while (page) {
struct page *next_page;
struct link_free *link;
unsigned int i = 1;
void *vaddr;
/*
* page->index stores offset of first object starting
* in the page. For the first page, this is always 0,
* so we use first_page->index (aka ->freelist) to store
* head of corresponding zspage's freelist.
*/
if (page != first_page)
page->index = off;
vaddr = kmap_atomic(page);
link = (struct link_free *)vaddr + off / sizeof(*link);
while ((off += class->size) < PAGE_SIZE) {
link->next = location_to_obj(page, i++);
link += class->size / sizeof(*link);
}
/*
* We now come to the last (full or partial) object on this
* page, which must point to the first object on the next
* page (if present)
*/
next_page = get_next_page(page);
link->next = location_to_obj(next_page, 0);
kunmap_atomic(vaddr);
page = next_page;
off %= PAGE_SIZE;
}
}
/*
* Allocate a zspage for the given size class
*/
static struct page *alloc_zspage(struct size_class *class, gfp_t flags)
{
int i, error;
struct page *first_page = NULL, *uninitialized_var(prev_page);
/*
* Allocate individual pages and link them together as:
* 1. first page->private = first sub-page
* 2. all sub-pages are linked together using page->lru
* 3. each sub-page is linked to the first page using page->first_page
*
* For each size class, First/Head pages are linked together using
* page->lru. Also, we set PG_private to identify the first page
* (i.e. no other sub-page has this flag set) and PG_private_2 to
* identify the last page.
*/
error = -ENOMEM;
for (i = 0; i < class->pages_per_zspage; i++) {
struct page *page;
page = alloc_page(flags);
if (!page)
goto cleanup;
INIT_LIST_HEAD(&page->lru);
if (i == 0) { /* first page */
SetPagePrivate(page);
set_page_private(page, 0);
first_page = page;
first_page->inuse = 0;
}
if (i == 1)
set_page_private(first_page, (unsigned long)page);
if (i >= 1)
page->first_page = first_page;
if (i >= 2)
list_add(&page->lru, &prev_page->lru);
if (i == class->pages_per_zspage - 1) /* last page */
SetPagePrivate2(page);
prev_page = page;
}
init_zspage(first_page, class);
first_page->freelist = location_to_obj(first_page, 0);
/* Maximum number of objects we can store in this zspage */
first_page->objects = class->pages_per_zspage * PAGE_SIZE / class->size;
error = 0; /* Success */
cleanup:
if (unlikely(error) && first_page) {
free_zspage(first_page);
first_page = NULL;
}
return first_page;
}
static struct page *find_get_zspage(struct size_class *class)
{
int i;
struct page *page;
for (i = 0; i < <API key>; i++) {
page = class->fullness_list[i];
if (page)
break;
}
return page;
}
#ifdef <API key>
static inline int __zs_cpu_up(struct mapping_area *area)
{
/*
* Make sure we don't leak memory if a cpu UP notification
* and zs_init() race and both call zs_cpu_up() on the same cpu
*/
if (area->vm)
return 0;
area->vm = alloc_vm_area(PAGE_SIZE * 2, NULL);
if (!area->vm)
return -ENOMEM;
return 0;
}
static inline void __zs_cpu_down(struct mapping_area *area)
{
if (area->vm)
free_vm_area(area->vm);
area->vm = NULL;
}
static inline void *__zs_map_object(struct mapping_area *area,
struct page *pages[2], int off, int size)
{
BUG_ON(map_vm_area(area->vm, PAGE_KERNEL, pages));
area->vm_addr = area->vm->addr;
return area->vm_addr + off;
}
static inline void __zs_unmap_object(struct mapping_area *area,
struct page *pages[2], int off, int size)
{
unsigned long addr = (unsigned long)area->vm_addr;
unmap_kernel_range(addr, PAGE_SIZE * 2);
}
#else /* <API key> */
static inline int __zs_cpu_up(struct mapping_area *area)
{
/*
* Make sure we don't leak memory if a cpu UP notification
* and zs_init() race and both call zs_cpu_up() on the same cpu
*/
if (area->vm_buf)
return 0;
area->vm_buf = kmalloc(ZS_MAX_ALLOC_SIZE, GFP_KERNEL);
if (!area->vm_buf)
return -ENOMEM;
return 0;
}
static inline void __zs_cpu_down(struct mapping_area *area)
{
kfree(area->vm_buf);
area->vm_buf = NULL;
}
static void *__zs_map_object(struct mapping_area *area,
struct page *pages[2], int off, int size)
{
int sizes[2];
void *addr;
char *buf = area->vm_buf;
/* disable page faults to match kmap_atomic() return conditions */
pagefault_disable();
/* no read fastpath */
if (area->vm_mm == ZS_MM_WO)
goto out;
sizes[0] = PAGE_SIZE - off;
sizes[1] = size - sizes[0];
/* copy object to per-cpu buffer */
addr = kmap_atomic(pages[0]);
memcpy(buf, addr + off, sizes[0]);
kunmap_atomic(addr);
addr = kmap_atomic(pages[1]);
memcpy(buf + sizes[0], addr, sizes[1]);
kunmap_atomic(addr);
out:
return area->vm_buf;
}
static void __zs_unmap_object(struct mapping_area *area,
struct page *pages[2], int off, int size)
{
int sizes[2];
void *addr;
char *buf;
/* no write fastpath */
if (area->vm_mm == ZS_MM_RO)
goto out;
buf = area->vm_buf;
if (!area->huge) {
buf = buf + ZS_HANDLE_SIZE;
size -= ZS_HANDLE_SIZE;
off += ZS_HANDLE_SIZE;
}
sizes[0] = PAGE_SIZE - off;
sizes[1] = size - sizes[0];
/* copy per-cpu buffer to object */
addr = kmap_atomic(pages[0]);
memcpy(addr + off, buf, sizes[0]);
kunmap_atomic(addr);
addr = kmap_atomic(pages[1]);
memcpy(addr, buf + sizes[0], sizes[1]);
kunmap_atomic(addr);
out:
/* enable page faults to match kunmap_atomic() return conditions */
pagefault_enable();
}
#endif /* <API key> */
static int zs_cpu_notifier(struct notifier_block *nb, unsigned long action,
void *pcpu)
{
int ret, cpu = (long)pcpu;
struct mapping_area *area;
switch (action) {
case CPU_UP_PREPARE:
area = &per_cpu(zs_map_area, cpu);
ret = __zs_cpu_up(area);
if (ret)
return notifier_from_errno(ret);
break;
case CPU_DEAD:
case CPU_UP_CANCELED:
area = &per_cpu(zs_map_area, cpu);
__zs_cpu_down(area);
break;
}
return NOTIFY_OK;
}
static struct notifier_block zs_cpu_nb = {
.notifier_call = zs_cpu_notifier
};
static int <API key>(void)
{
int cpu, uninitialized_var(ret);
<API key>();
<API key>(&zs_cpu_nb);
for_each_online_cpu(cpu) {
ret = zs_cpu_notifier(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
if (notifier_to_errno(ret))
break;
}
<API key>();
return notifier_to_errno(ret);
}
static void <API key>(void)
{
int cpu;
<API key>();
for_each_online_cpu(cpu)
zs_cpu_notifier(NULL, CPU_DEAD, (void *)(long)cpu);
<API key>(&zs_cpu_nb);
<API key>();
}
static void <API key>(void)
{
int nr;
nr = (ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) / ZS_SIZE_CLASS_DELTA + 1;
if ((ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE) % ZS_SIZE_CLASS_DELTA)
nr += 1;
zs_size_classes = nr;
}
static bool can_merge(struct size_class *prev, int size, int pages_per_zspage)
{
if (prev->pages_per_zspage != pages_per_zspage)
return false;
if (<API key>(prev->size, prev->pages_per_zspage)
!= <API key>(size, pages_per_zspage))
return false;
return true;
}
static bool zspage_full(struct page *page)
{
BUG_ON(!is_first_page(page));
return page->inuse == page->objects;
}
unsigned long zs_get_total_pages(struct zs_pool *pool)
{
return atomic_long_read(&pool->pages_allocated);
}
EXPORT_SYMBOL_GPL(zs_get_total_pages);
/**
* zs_map_object - get address of allocated object from handle.
* @pool: pool from which the object was allocated
* @handle: handle returned from zs_malloc
*
* Before using an object allocated from zs_malloc, it must be mapped using
* this function. When done with the object, it must be unmapped using
* zs_unmap_object.
*
* Only one object can be mapped per cpu at a time. There is no protection
* against nested mappings.
*
* This function returns with preemption and page faults disabled.
*/
void *zs_map_object(struct zs_pool *pool, unsigned long handle,
enum zs_mapmode mm)
{
struct page *page;
unsigned long obj, obj_idx, off;
unsigned int class_idx;
enum fullness_group fg;
struct size_class *class;
struct mapping_area *area;
struct page *pages[2];
void *ret;
BUG_ON(!handle);
/*
* Because we use per-cpu mapping areas shared among the
* pools/users, we can't allow mapping in interrupt context
* because it can corrupt another users mappings.
*/
BUG_ON(in_interrupt());
/* From now on, migration cannot move the object */
pin_tag(handle);
obj = handle_to_obj(handle);
obj_to_location(obj, &page, &obj_idx);
get_zspage_mapping(get_first_page(page), &class_idx, &fg);
class = pool->size_class[class_idx];
off = obj_idx_to_offset(page, obj_idx, class->size);
area = &get_cpu_var(zs_map_area);
area->vm_mm = mm;
if (off + class->size <= PAGE_SIZE) {
/* this object is contained entirely within a page */
area->vm_addr = kmap_atomic(page);
ret = area->vm_addr + off;
goto out;
}
/* this object spans two pages */
pages[0] = page;
pages[1] = get_next_page(page);
BUG_ON(!pages[1]);
ret = __zs_map_object(area, pages, off, class->size);
out:
if (!class->huge)
ret += ZS_HANDLE_SIZE;
return ret;
}
EXPORT_SYMBOL_GPL(zs_map_object);
void zs_unmap_object(struct zs_pool *pool, unsigned long handle)
{
struct page *page;
unsigned long obj, obj_idx, off;
unsigned int class_idx;
enum fullness_group fg;
struct size_class *class;
struct mapping_area *area;
BUG_ON(!handle);
obj = handle_to_obj(handle);
obj_to_location(obj, &page, &obj_idx);
get_zspage_mapping(get_first_page(page), &class_idx, &fg);
class = pool->size_class[class_idx];
off = obj_idx_to_offset(page, obj_idx, class->size);
area = this_cpu_ptr(&zs_map_area);
if (off + class->size <= PAGE_SIZE)
kunmap_atomic(area->vm_addr);
else {
struct page *pages[2];
pages[0] = page;
pages[1] = get_next_page(page);
BUG_ON(!pages[1]);
__zs_unmap_object(area, pages, off, class->size);
}
put_cpu_var(zs_map_area);
unpin_tag(handle);
}
EXPORT_SYMBOL_GPL(zs_unmap_object);
static unsigned long obj_malloc(struct page *first_page,
struct size_class *class, unsigned long handle)
{
unsigned long obj;
struct link_free *link;
struct page *m_page;
unsigned long m_objidx, m_offset;
void *vaddr;
handle |= OBJ_ALLOCATED_TAG;
obj = (unsigned long)first_page->freelist;
obj_to_location(obj, &m_page, &m_objidx);
m_offset = obj_idx_to_offset(m_page, m_objidx, class->size);
vaddr = kmap_atomic(m_page);
link = (struct link_free *)vaddr + m_offset / sizeof(*link);
first_page->freelist = link->next;
if (!class->huge)
/* record handle in the header of allocated chunk */
link->handle = handle;
else
/* record handle in first_page->private */
set_page_private(first_page, handle);
kunmap_atomic(vaddr);
first_page->inuse++;
zs_stat_inc(class, OBJ_USED, 1);
return obj;
}
/**
* zs_malloc - Allocate block of given size from pool.
* @pool: pool to allocate from
* @size: size of block to allocate
*
* On success, handle to the allocated object is returned,
* otherwise 0.
* Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
*/
unsigned long zs_malloc(struct zs_pool *pool, size_t size)
{
unsigned long handle, obj;
struct size_class *class;
struct page *first_page;
if (unlikely(!size || size > ZS_MAX_ALLOC_SIZE))
return 0;
handle = alloc_handle(pool);
if (!handle)
return 0;
/* extra space in chunk to keep the handle */
size += ZS_HANDLE_SIZE;
class = pool->size_class[<API key>(size)];
spin_lock(&class->lock);
first_page = find_get_zspage(class);
if (!first_page) {
spin_unlock(&class->lock);
first_page = alloc_zspage(class, pool->flags);
if (unlikely(!first_page)) {
free_handle(pool, handle);
return 0;
}
set_zspage_mapping(first_page, class->index, ZS_EMPTY);
atomic_long_add(class->pages_per_zspage,
&pool->pages_allocated);
spin_lock(&class->lock);
zs_stat_inc(class, OBJ_ALLOCATED, <API key>(
class->size, class->pages_per_zspage));
}
obj = obj_malloc(first_page, class, handle);
/* Now move the zspage to another fullness group, if required */
fix_fullness_group(class, first_page);
record_obj(handle, obj);
spin_unlock(&class->lock);
return handle;
}
EXPORT_SYMBOL_GPL(zs_malloc);
static void obj_free(struct zs_pool *pool, struct size_class *class,
unsigned long obj)
{
struct link_free *link;
struct page *first_page, *f_page;
unsigned long f_objidx, f_offset;
void *vaddr;
int class_idx;
enum fullness_group fullness;
BUG_ON(!obj);
obj &= ~OBJ_ALLOCATED_TAG;
obj_to_location(obj, &f_page, &f_objidx);
first_page = get_first_page(f_page);
get_zspage_mapping(first_page, &class_idx, &fullness);
f_offset = obj_idx_to_offset(f_page, f_objidx, class->size);
vaddr = kmap_atomic(f_page);
/* Insert this object in containing zspage's freelist */
link = (struct link_free *)(vaddr + f_offset);
link->next = first_page->freelist;
if (class->huge)
set_page_private(first_page, 0);
kunmap_atomic(vaddr);
first_page->freelist = (void *)obj;
first_page->inuse
zs_stat_dec(class, OBJ_USED, 1);
}
void zs_free(struct zs_pool *pool, unsigned long handle)
{
struct page *first_page, *f_page;
unsigned long obj, f_objidx;
int class_idx;
struct size_class *class;
enum fullness_group fullness;
if (unlikely(!handle))
return;
pin_tag(handle);
obj = handle_to_obj(handle);
obj_to_location(obj, &f_page, &f_objidx);
first_page = get_first_page(f_page);
get_zspage_mapping(first_page, &class_idx, &fullness);
class = pool->size_class[class_idx];
spin_lock(&class->lock);
obj_free(pool, class, obj);
fullness = fix_fullness_group(class, first_page);
if (fullness == ZS_EMPTY) {
zs_stat_dec(class, OBJ_ALLOCATED, <API key>(
class->size, class->pages_per_zspage));
atomic_long_sub(class->pages_per_zspage,
&pool->pages_allocated);
free_zspage(first_page);
}
spin_unlock(&class->lock);
unpin_tag(handle);
free_handle(pool, handle);
}
EXPORT_SYMBOL_GPL(zs_free);
static void zs_object_copy(unsigned long src, unsigned long dst,
struct size_class *class)
{
struct page *s_page, *d_page;
unsigned long s_objidx, d_objidx;
unsigned long s_off, d_off;
void *s_addr, *d_addr;
int s_size, d_size, size;
int written = 0;
s_size = d_size = class->size;
obj_to_location(src, &s_page, &s_objidx);
obj_to_location(dst, &d_page, &d_objidx);
s_off = obj_idx_to_offset(s_page, s_objidx, class->size);
d_off = obj_idx_to_offset(d_page, d_objidx, class->size);
if (s_off + class->size > PAGE_SIZE)
s_size = PAGE_SIZE - s_off;
if (d_off + class->size > PAGE_SIZE)
d_size = PAGE_SIZE - d_off;
s_addr = kmap_atomic(s_page);
d_addr = kmap_atomic(d_page);
while (1) {
size = min(s_size, d_size);
memcpy(d_addr + d_off, s_addr + s_off, size);
written += size;
if (written == class->size)
break;
s_off += size;
s_size -= size;
d_off += size;
d_size -= size;
if (s_off >= PAGE_SIZE) {
kunmap_atomic(d_addr);
kunmap_atomic(s_addr);
s_page = get_next_page(s_page);
BUG_ON(!s_page);
s_addr = kmap_atomic(s_page);
d_addr = kmap_atomic(d_page);
s_size = class->size - written;
s_off = 0;
}
if (d_off >= PAGE_SIZE) {
kunmap_atomic(d_addr);
d_page = get_next_page(d_page);
BUG_ON(!d_page);
d_addr = kmap_atomic(d_page);
d_size = class->size - written;
d_off = 0;
}
}
kunmap_atomic(d_addr);
kunmap_atomic(s_addr);
}
/*
* Find alloced object in zspage from index object and
* return handle.
*/
static unsigned long find_alloced_obj(struct page *page, int index,
struct size_class *class)
{
unsigned long head;
int offset = 0;
unsigned long handle = 0;
void *addr = kmap_atomic(page);
if (!is_first_page(page))
offset = page->index;
offset += class->size * index;
while (offset < PAGE_SIZE) {
head = obj_to_head(class, page, addr + offset);
if (head & OBJ_ALLOCATED_TAG) {
handle = head & ~OBJ_ALLOCATED_TAG;
if (trypin_tag(handle))
break;
handle = 0;
}
offset += class->size;
index++;
}
kunmap_atomic(addr);
return handle;
}
struct zs_compact_control {
/* Source page for migration which could be a subpage of zspage. */
struct page *s_page;
/* Destination page for migration which should be a first page
* of zspage. */
struct page *d_page;
/* Starting object index within @s_page which used for live object
* in the subpage. */
int index;
/* how many of objects are migrated */
int nr_migrated;
};
static int migrate_zspage(struct zs_pool *pool, struct size_class *class,
struct zs_compact_control *cc)
{
unsigned long used_obj, free_obj;
unsigned long handle;
struct page *s_page = cc->s_page;
struct page *d_page = cc->d_page;
unsigned long index = cc->index;
int nr_migrated = 0;
int ret = 0;
while (1) {
handle = find_alloced_obj(s_page, index, class);
if (!handle) {
s_page = get_next_page(s_page);
if (!s_page)
break;
index = 0;
continue;
}
/* Stop if there is no more space */
if (zspage_full(d_page)) {
unpin_tag(handle);
ret = -ENOMEM;
break;
}
used_obj = handle_to_obj(handle);
free_obj = obj_malloc(d_page, class, handle);
zs_object_copy(used_obj, free_obj, class);
index++;
/*
* record_obj updates handle's value to free_obj and it will
* invalidate lock bit(ie, HANDLE_PIN_BIT) of handle, which
* breaks synchronization using pin_tag(e,g, zs_free) so
* let's keep the lock bit.
*/
free_obj |= BIT(HANDLE_PIN_BIT);
record_obj(handle, free_obj);
unpin_tag(handle);
obj_free(pool, class, used_obj);
nr_migrated++;
}
/* Remember last position in this iteration */
cc->s_page = s_page;
cc->index = index;
cc->nr_migrated = nr_migrated;
return ret;
}
static struct page *alloc_target_page(struct size_class *class)
{
int i;
struct page *page;
for (i = 0; i < <API key>; i++) {
page = class->fullness_list[i];
if (page) {
remove_zspage(page, class, i);
break;
}
}
return page;
}
static void putback_zspage(struct zs_pool *pool, struct size_class *class,
struct page *first_page)
{
enum fullness_group fullness;
BUG_ON(!is_first_page(first_page));
fullness = get_fullness_group(first_page);
insert_zspage(first_page, class, fullness);
set_zspage_mapping(first_page, class->index, fullness);
if (fullness == ZS_EMPTY) {
zs_stat_dec(class, OBJ_ALLOCATED, <API key>(
class->size, class->pages_per_zspage));
atomic_long_sub(class->pages_per_zspage,
&pool->pages_allocated);
free_zspage(first_page);
}
}
static struct page *isolate_source_page(struct size_class *class)
{
struct page *page;
page = class->fullness_list[ZS_ALMOST_EMPTY];
if (page)
remove_zspage(page, class, ZS_ALMOST_EMPTY);
return page;
}
static unsigned long __zs_compact(struct zs_pool *pool,
struct size_class *class)
{
int nr_to_migrate;
struct zs_compact_control cc;
struct page *src_page;
struct page *dst_page = NULL;
unsigned long nr_total_migrated = 0;
spin_lock(&class->lock);
while ((src_page = isolate_source_page(class))) {
BUG_ON(!is_first_page(src_page));
/* The goal is to migrate all live objects in source page */
nr_to_migrate = src_page->inuse;
cc.index = 0;
cc.s_page = src_page;
while ((dst_page = alloc_target_page(class))) {
cc.d_page = dst_page;
/*
* If there is no more space in dst_page, try to
* allocate another zspage.
*/
if (!migrate_zspage(pool, class, &cc))
break;
putback_zspage(pool, class, dst_page);
nr_total_migrated += cc.nr_migrated;
nr_to_migrate -= cc.nr_migrated;
}
/* Stop if we couldn't find slot */
if (dst_page == NULL)
break;
putback_zspage(pool, class, dst_page);
putback_zspage(pool, class, src_page);
spin_unlock(&class->lock);
nr_total_migrated += cc.nr_migrated;
cond_resched();
spin_lock(&class->lock);
}
if (src_page)
putback_zspage(pool, class, src_page);
spin_unlock(&class->lock);
return nr_total_migrated;
}
unsigned long zs_compact(struct zs_pool *pool)
{
int i;
unsigned long nr_migrated = 0;
struct size_class *class;
for (i = zs_size_classes - 1; i >= 0; i
class = pool->size_class[i];
if (!class)
continue;
if (class->index != i)
continue;
nr_migrated += __zs_compact(pool, class);
}
return nr_migrated;
}
EXPORT_SYMBOL_GPL(zs_compact);
/**
* zs_create_pool - Creates an allocation pool to work from.
* @flags: allocation flags used to allocate pool metadata
*
* This function must be called before anything when using
* the zsmalloc allocator.
*
* On success, a pointer to the newly created pool is returned,
* otherwise NULL.
*/
struct zs_pool *zs_create_pool(char *name, gfp_t flags)
{
int i;
struct zs_pool *pool;
struct size_class *prev_class = NULL;
pool = kzalloc(sizeof(*pool), GFP_KERNEL);
if (!pool)
return NULL;
pool->size_class = kcalloc(zs_size_classes, sizeof(struct size_class *),
GFP_KERNEL);
if (!pool->size_class) {
kfree(pool);
return NULL;
}
pool->name = kstrdup(name, GFP_KERNEL);
if (!pool->name)
goto err;
if (create_handle_cache(pool))
goto err;
/*
* Iterate reversly, because, size of size_class that we want to use
* for merging should be larger or equal to current size.
*/
for (i = zs_size_classes - 1; i >= 0; i
int size;
int pages_per_zspage;
struct size_class *class;
size = ZS_MIN_ALLOC_SIZE + i * ZS_SIZE_CLASS_DELTA;
if (size > ZS_MAX_ALLOC_SIZE)
size = ZS_MAX_ALLOC_SIZE;
pages_per_zspage = <API key>(size);
/*
* size_class is used for normal zsmalloc operation such
* as alloc/free for that size. Although it is natural that we
* have one size_class for each size, there is a chance that we
* can get more memory utilization if we use one size_class for
* many different sizes whose size_class have same
* characteristics. So, we makes size_class point to
* previous size_class if possible.
*/
if (prev_class) {
if (can_merge(prev_class, size, pages_per_zspage)) {
pool->size_class[i] = prev_class;
continue;
}
}
class = kzalloc(sizeof(struct size_class), GFP_KERNEL);
if (!class)
goto err;
class->size = size;
class->index = i;
class->pages_per_zspage = pages_per_zspage;
if (pages_per_zspage == 1 &&
<API key>(size, pages_per_zspage) == 1)
class->huge = true;
spin_lock_init(&class->lock);
pool->size_class[i] = class;
prev_class = class;
}
pool->flags = flags;
if (zs_pool_stat_create(name, pool))
goto err;
return pool;
err:
zs_destroy_pool(pool);
return NULL;
}
EXPORT_SYMBOL_GPL(zs_create_pool);
void zs_destroy_pool(struct zs_pool *pool)
{
int i;
<API key>(pool);
for (i = 0; i < zs_size_classes; i++) {
int fg;
struct size_class *class = pool->size_class[i];
if (!class)
continue;
if (class->index != i)
continue;
for (fg = 0; fg < <API key>; fg++) {
if (class->fullness_list[fg]) {
pr_info("Freeing non-empty class with size %db, fullness group %d\n",
class->size, fg);
}
}
kfree(class);
}
<API key>(pool);
kfree(pool->size_class);
kfree(pool->name);
kfree(pool);
}
EXPORT_SYMBOL_GPL(zs_destroy_pool);
static int __init zs_init(void)
{
int ret = <API key>();
if (ret)
goto notifier_fail;
<API key>();
#ifdef CONFIG_ZPOOL
<API key>(&zs_zpool_driver);
#endif
ret = zs_stat_init();
if (ret) {
pr_err("zs stat initialization failed\n");
goto stat_fail;
}
return 0;
stat_fail:
#ifdef CONFIG_ZPOOL
<API key>(&zs_zpool_driver);
#endif
notifier_fail:
<API key>();
return ret;
}
static void __exit zs_exit(void)
{
#ifdef CONFIG_ZPOOL
<API key>(&zs_zpool_driver);
#endif
<API key>();
zs_stat_exit();
}
module_init(zs_init);
module_exit(zs_exit);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
|
#include <algorithm>
#include <cinttypes>
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/logging/log.h"
#include "core/arm/skyeye_common/vfp/asm_vfp.h"
#include "core/arm/skyeye_common/vfp/vfp.h"
#include "core/arm/skyeye_common/vfp/vfp_helper.h"
static struct vfp_single <API key> = {
255, 0, <API key>,
};
static void vfp_single_dump(const char* str, struct vfp_single* s) {
LOG_TRACE(Core_ARM11, "%s: sign=%d exponent=%d significand=%08x", str, s->sign != 0,
s->exponent, s->significand);
}
static void <API key>(struct vfp_single* vs) {
int bits = 31 - fls(vs->significand);
vfp_single_dump("normalise_denormal: in", vs);
if (bits) {
vs->exponent -= bits - 1;
vs->significand <<= bits;
}
vfp_single_dump("normalise_denormal: out", vs);
}
u32 <API key>(ARMul_State* state, int sd, struct vfp_single* vs, u32 fpscr,
const char* func) {
u32 significand, incr, rmode;
int exponent, shift, underflow;
u32 exceptions = 0;
vfp_single_dump("pack: in", vs);
/*
* Infinities and NaNs are a special case.
*/
if (vs->exponent == 255 && (vs->significand == 0 || exceptions))
goto pack;
/*
* Special-case zero.
*/
if (vs->significand == 0) {
vs->exponent = 0;
goto pack;
}
exponent = vs->exponent;
significand = vs->significand;
/*
* Normalise first. Note that we shift the significand up to
* bit 31, so we have VFP_SINGLE_LOW_BITS + 1 below the least
* significant bit.
*/
shift = 32 - fls(significand);
if (shift < 32 && shift) {
exponent -= shift;
significand <<= shift;
}
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: normalised", vs);
#endif
/*
* Tiny number?
*/
underflow = exponent < 0;
if (underflow) {
significand = <API key>(significand, -exponent);
exponent = 0;
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: tiny number", vs);
#endif
if (!(significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1)))
underflow = 0;
}
/*
* Select rounding increment.
*/
incr = 0;
rmode = fpscr & FPSCR_RMODE_MASK;
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 1 << VFP_SINGLE_LOW_BITS;
if ((significand & (1 << (VFP_SINGLE_LOW_BITS + 1))) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vs->sign != 0))
incr = (1 << (VFP_SINGLE_LOW_BITS + 1)) - 1;
LOG_TRACE(Core_ARM11, "rounding increment = 0x%08x", incr);
/*
* Is our rounding going to overflow?
*/
if ((significand + incr) < significand) {
exponent += 1;
significand = (significand >> 1) | (significand & 1);
incr >>= 1;
#if 1
vs->exponent = exponent;
vs->significand = significand;
vfp_single_dump("pack: overflow", vs);
#endif
}
/*
* If any of the low bits (which will be shifted out of the
* number) are non-zero, the result is inexact.
*/
if (significand & ((1 << (VFP_SINGLE_LOW_BITS + 1)) - 1))
exceptions |= FPSCR_IXC;
/*
* Do our rounding.
*/
significand += incr;
/*
* Infinity?
*/
if (exponent >= 254) {
exceptions |= FPSCR_OFC | FPSCR_IXC;
if (incr == 0) {
vs->exponent = 253;
vs->significand = 0x7fffffff;
} else {
vs->exponent = 255; /* infinity */
vs->significand = 0;
}
} else {
if (significand >> (VFP_SINGLE_LOW_BITS + 1) == 0)
exponent = 0;
if (exponent || significand > 0x80000000)
underflow = 0;
if (underflow)
exceptions |= FPSCR_UFC;
vs->exponent = exponent;
vs->significand = significand >> 1;
}
pack:
vfp_single_dump("pack: final", vs);
{
s32 d = vfp_single_pack(vs);
LOG_TRACE(Core_ARM11, "%s: d(s%d)=%08x exceptions=%08x", func, sd, d, exceptions);
vfp_put_float(state, d, sd);
}
return exceptions;
}
/*
* Propagate the NaN, setting exceptions if it is signalling.
* 'n' is always a NaN. 'm' may be a number, NaN or infinity.
*/
static u32 vfp_propagate_nan(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm,
u32 fpscr) {
struct vfp_single* nan;
int tn, tm = 0;
tn = vfp_single_type(vsn);
if (vsm)
tm = vfp_single_type(vsm);
if (fpscr & FPSCR_DEFAULT_NAN)
/*
* Default NaN mode - always returns a quiet NaN
*/
nan = &<API key>;
else {
/*
* Contemporary mode - select the first signalling
* NAN, or if neither are signalling, the first
* quiet NAN.
*/
if (tn == VFP_SNAN || (tm != VFP_SNAN && tn == VFP_QNAN))
nan = vsn;
else
nan = vsm;
/*
* Make the NaN quiet.
*/
nan->significand |= <API key>;
}
*vsd = *nan;
/*
* If one was a signalling NAN, raise invalid operation.
*/
return tn == VFP_SNAN || tm == VFP_SNAN ? FPSCR_IOC : VFP_NAN_FLAG;
}
/*
* Extended operations
*/
static u32 vfp_single_fabs(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, <API key>(m), sd);
return 0;
}
static u32 vfp_single_fcpy(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, m, sd);
return 0;
}
static u32 vfp_single_fneg(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
vfp_put_float(state, <API key>(m), sd);
return 0;
}
static const u16 sqrt_oddadjust[] = {
0x0004, 0x0022, 0x005d, 0x00b1, 0x011d, 0x019f, 0x0236, 0x02e0,
0x039c, 0x0468, 0x0545, 0x0631, 0x072b, 0x0832, 0x0946, 0x0a67,
};
static const u16 sqrt_evenadjust[] = {
0x0a2d, 0x08af, 0x075a, 0x0629, 0x051a, 0x0429, 0x0356, 0x029e,
0x0200, 0x0179, 0x0109, 0x00af, 0x0068, 0x0034, 0x0012, 0x0002,
};
u32 <API key>(u32 exponent, u32 significand) {
int index;
u32 z, a;
if ((significand & 0xc0000000) != 0x40000000) {
LOG_TRACE(Core_ARM11, "invalid significand");
}
a = significand << 1;
index = (a >> 27) & 15;
if (exponent & 1) {
z = 0x4000 + (a >> 17) - sqrt_oddadjust[index];
z = ((a / z) << 14) + (z << 15);
a >>= 1;
} else {
z = 0x8000 + (a >> 17) - sqrt_evenadjust[index];
z = a / z + z;
z = (z >= 0x20000) ? 0xffff8000 : (z << 15);
if (z <= a)
return (s32)a >> 1;
}
{
u64 v = (u64)a << 31;
do_div(v, z);
return (u32)(v + (z >> 1));
}
}
static u32 vfp_single_fsqrt(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm, vsd, *vsp;
int ret, tm;
u32 exceptions = 0;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
tm = vfp_single_type(&vsm);
if (tm & (VFP_NAN | VFP_INFINITY)) {
vsp = &vsd;
if (tm & VFP_NAN)
ret = vfp_propagate_nan(vsp, &vsm, nullptr, fpscr);
else if (vsm.sign == 0) {
sqrt_copy:
vsp = &vsm;
ret = 0;
} else {
sqrt_invalid:
vsp = &<API key>;
ret = FPSCR_IOC;
}
vfp_put_float(state, vfp_single_pack(vsp), sd);
return ret;
}
/*
* sqrt(+/- 0) == +/- 0
*/
if (tm & VFP_ZERO)
goto sqrt_copy;
/*
* Normalise a denormalised number
*/
if (tm & VFP_DENORMAL)
<API key>(&vsm);
/*
* sqrt(<0) = invalid
*/
if (vsm.sign)
goto sqrt_invalid;
vfp_single_dump("sqrt", &vsm);
/*
* Estimate the square root.
*/
vsd.sign = 0;
vsd.exponent = ((vsm.exponent - 127) >> 1) + 127;
vsd.significand = <API key>(vsm.exponent, vsm.significand) + 2;
vfp_single_dump("sqrt estimate", &vsd);
/*
* And now adjust.
*/
if ((vsd.significand & <API key>) <= 5) {
if (vsd.significand < 2) {
vsd.significand = 0xffffffff;
} else {
u64 term;
s64 rem;
vsm.significand <<= static_cast<u32>((vsm.exponent & 1) == 0);
term = (u64)vsd.significand * vsd.significand;
rem = ((u64)vsm.significand << 32) - term;
LOG_TRACE(Core_ARM11, "term=%016" PRIx64 "rem=%016" PRIx64, term, rem);
while (rem < 0) {
vsd.significand -= 1;
rem += ((u64)vsd.significand << 1) | 1;
}
vsd.significand |= rem != 0;
}
}
vsd.significand = <API key>(vsd.significand, 1);
exceptions |= <API key>(state, sd, &vsd, fpscr, "fsqrt");
return exceptions;
}
/*
* Equal := ZC
* Less than := N
* Greater than := C
* Unordered := CV
*/
static u32 vfp_compare(ARMul_State* state, int sd, int signal_on_qnan, s32 m, u32 fpscr) {
s32 d;
u32 ret = 0;
d = vfp_get_float(state, sd);
if (<API key>(m) == 255 && <API key>(m)) {
ret |= FPSCR_CFLAG | FPSCR_VFLAG;
if (signal_on_qnan ||
!(<API key>(m) & (1 << (<API key> - 1))))
/*
* Signalling NaN, or signalling on quiet NaN
*/
ret |= FPSCR_IOC;
}
if (<API key>(d) == 255 && <API key>(d)) {
ret |= FPSCR_CFLAG | FPSCR_VFLAG;
if (signal_on_qnan ||
!(<API key>(d) & (1 << (<API key> - 1))))
/*
* Signalling NaN, or signalling on quiet NaN
*/
ret |= FPSCR_IOC;
}
if (ret == 0) {
if (d == m || <API key>(d | m) == 0) {
/*
* equal
*/
ret |= FPSCR_ZFLAG | FPSCR_CFLAG;
} else if (<API key>(d ^ m)) {
/*
* different signs
*/
if (<API key>(d))
/*
* d is negative, so d < m
*/
ret |= FPSCR_NFLAG;
else
/*
* d is positive, so d > m
*/
ret |= FPSCR_CFLAG;
} else if ((<API key>(d) != 0) ^ (d < m)) {
/*
* d < m
*/
ret |= FPSCR_NFLAG;
} else if ((<API key>(d) != 0) ^ (d > m)) {
/*
* d > m
*/
ret |= FPSCR_CFLAG;
}
}
return ret;
}
static u32 vfp_single_fcmp(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 0, m, fpscr);
}
static u32 vfp_single_fcmpe(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 1, m, fpscr);
}
static u32 vfp_single_fcmpz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 0, 0, fpscr);
}
static u32 vfp_single_fcmpez(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_compare(state, sd, 1, 0, fpscr);
}
static u32 vfp_single_fcvtd(ARMul_State* state, int dd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
struct vfp_double vdd;
int tm;
u32 exceptions = 0;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
tm = vfp_single_type(&vsm);
/*
* If we have a signalling NaN, signal invalid operation.
*/
if (tm == VFP_SNAN)
exceptions |= FPSCR_IOC;
if (tm & VFP_DENORMAL)
<API key>(&vsm);
vdd.sign = vsm.sign;
vdd.significand = (u64)vsm.significand << 32;
/*
* If we have an infinity or NaN, the exponent must be 2047.
*/
if (tm & (VFP_INFINITY | VFP_NAN)) {
vdd.exponent = 2047;
if (tm == VFP_QNAN)
vdd.significand |= <API key>;
goto pack_nan;
} else if (tm & VFP_ZERO)
vdd.exponent = 0;
else
vdd.exponent = vsm.exponent + (1023 - 127);
exceptions |= <API key>(state, dd, &vdd, fpscr, "fcvtd");
return exceptions;
pack_nan:
vfp_put_double(state, vfp_double_pack(&vdd), dd);
return exceptions;
}
static u32 vfp_single_fuito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vs;
u32 exceptions = 0;
vs.sign = 0;
vs.exponent = 127 + 31 - 1;
vs.significand = (u32)m;
exceptions |= <API key>(state, sd, &vs, fpscr, "fuito");
return exceptions;
}
static u32 vfp_single_fsito(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vs;
u32 exceptions = 0;
vs.sign = (m & 0x80000000) >> 16;
vs.exponent = 127 + 31 - 1;
vs.significand = vs.sign ? -m : m;
exceptions |= <API key>(state, sd, &vs, fpscr, "fsito");
return exceptions;
}
static u32 vfp_single_ftoui(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
u32 d, exceptions = 0;
int rmode = fpscr & FPSCR_RMODE_MASK;
int tm;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vfp_single_dump("VSM", &vsm);
/*
* Do we have a denormalised number?
*/
tm = vfp_single_type(&vsm);
if (tm & VFP_DENORMAL)
exceptions |= FPSCR_IDC;
if (tm & VFP_NAN)
vsm.sign = 1;
if (vsm.exponent >= 127 + 32) {
d = vsm.sign ? 0 : 0xffffffff;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127) {
int shift = 127 + 31 - vsm.exponent;
u32 rem, incr = 0;
/*
* 2^0 <= m < 2^32-2^8
*/
d = (vsm.significand << 1) >> shift;
if (shift > 0) {
rem = (vsm.significand << 1) << (32 - shift);
} else {
rem = 0;
}
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 0x80000000;
if ((d & 1) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) {
incr = ~0;
}
if ((rem + incr) < rem) {
if (d < 0xffffffff)
d += 1;
else
exceptions |= FPSCR_IOC;
}
if (d && vsm.sign) {
d = 0;
exceptions |= FPSCR_IOC;
} else if (rem)
exceptions |= FPSCR_IXC;
} else {
d = 0;
if (vsm.exponent | vsm.significand) {
if (rmode == FPSCR_ROUND_NEAREST) {
if (vsm.exponent >= 126) {
d = vsm.sign ? 0 : 1;
exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC;
} else {
exceptions |= FPSCR_IXC;
}
} else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) {
d = 1;
exceptions |= FPSCR_IXC;
} else if (rmode == <API key>) {
exceptions |= vsm.sign ? FPSCR_IOC : FPSCR_IXC;
} else {
exceptions |= FPSCR_IXC;
}
}
}
LOG_TRACE(Core_ARM11, "ftoui: d(s%d)=%08x exceptions=%08x", sd, d, exceptions);
vfp_put_float(state, d, sd);
return exceptions;
}
static u32 vfp_single_ftouiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_single_ftoui(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO);
}
static u32 vfp_single_ftosi(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
struct vfp_single vsm;
u32 d, exceptions = 0;
int rmode = fpscr & FPSCR_RMODE_MASK;
int tm;
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vfp_single_dump("VSM", &vsm);
/*
* Do we have a denormalised number?
*/
tm = vfp_single_type(&vsm);
if (vfp_single_type(&vsm) & VFP_DENORMAL)
exceptions |= FPSCR_IDC;
if (tm & VFP_NAN) {
d = 0;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127 + 31) {
/*
* m >= 2^31-2^7: invalid
*/
d = 0x7fffffff;
if (vsm.sign)
d = ~d;
exceptions |= FPSCR_IOC;
} else if (vsm.exponent >= 127) {
int shift = 127 + 31 - vsm.exponent;
u32 rem, incr = 0;
/* 2^0 <= m <= 2^31-2^7 */
d = (vsm.significand << 1) >> shift;
rem = (vsm.significand << 1) << (32 - shift);
if (rmode == FPSCR_ROUND_NEAREST) {
incr = 0x80000000;
if ((d & 1) == 0)
incr -= 1;
} else if (rmode == FPSCR_ROUND_TOZERO) {
incr = 0;
} else if ((rmode == FPSCR_ROUND_PLUSINF) ^ (vsm.sign != 0)) {
incr = ~0;
}
if ((rem + incr) < rem && d < 0xffffffff)
d += 1;
if (d > (0x7fffffffu + (vsm.sign != 0))) {
d = (0x7fffffffu + (vsm.sign != 0));
exceptions |= FPSCR_IOC;
} else if (rem)
exceptions |= FPSCR_IXC;
if (vsm.sign)
d = (~d + 1);
} else {
d = 0;
if (vsm.exponent | vsm.significand) {
exceptions |= FPSCR_IXC;
if (rmode == FPSCR_ROUND_NEAREST) {
if (vsm.exponent >= 126)
d = vsm.sign ? 0xffffffff : 1;
} else if (rmode == FPSCR_ROUND_PLUSINF && vsm.sign == 0) {
d = 1;
} else if (rmode == <API key> && vsm.sign) {
d = 0xffffffff;
}
}
}
LOG_TRACE(Core_ARM11, "ftosi: d(s%d)=%08x exceptions=%08x", sd, d, exceptions);
vfp_put_float(state, (s32)d, sd);
return exceptions;
}
static u32 vfp_single_ftosiz(ARMul_State* state, int sd, int unused, s32 m, u32 fpscr) {
return vfp_single_ftosi(state, sd, unused, m, (fpscr & ~FPSCR_RMODE_MASK) | FPSCR_ROUND_TOZERO);
}
static struct op fops_ext[] = {
{vfp_single_fcpy, 0}, // 0x00000000 - FEXT_FCPY
{vfp_single_fabs, 0}, // 0x00000001 - FEXT_FABS
{vfp_single_fneg, 0}, // 0x00000002 - FEXT_FNEG
{vfp_single_fsqrt, 0}, // 0x00000003 - FEXT_FSQRT
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_fcmp, OP_SCALAR}, // 0x00000008 - FEXT_FCMP
{vfp_single_fcmpe, OP_SCALAR}, // 0x00000009 - FEXT_FCMPE
{vfp_single_fcmpz, OP_SCALAR}, // 0x0000000A - FEXT_FCMPZ
{vfp_single_fcmpez, OP_SCALAR}, // 0x0000000B - FEXT_FCMPEZ
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_fcvtd, OP_SCALAR | OP_DD}, // 0x0000000F - FEXT_FCVT
{vfp_single_fuito, OP_SCALAR}, // 0x00000010 - FEXT_FUITO
{vfp_single_fsito, OP_SCALAR}, // 0x00000011 - FEXT_FSITO
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{nullptr, 0},
{vfp_single_ftoui, OP_SCALAR}, // 0x00000018 - FEXT_FTOUI
{vfp_single_ftouiz, OP_SCALAR}, // 0x00000019 - FEXT_FTOUIZ
{vfp_single_ftosi, OP_SCALAR}, // 0x0000001A - FEXT_FTOSI
{vfp_single_ftosiz, OP_SCALAR}, // 0x0000001B - FEXT_FTOSIZ
};
static u32 <API key>(struct vfp_single* vsd, struct vfp_single* vsn,
struct vfp_single* vsm, u32 fpscr) {
struct vfp_single* vsp;
u32 exceptions = 0;
int tn, tm;
tn = vfp_single_type(vsn);
tm = vfp_single_type(vsm);
if (tn & tm & VFP_INFINITY) {
/*
* Two infinities. Are they different signs?
*/
if (vsn->sign ^ vsm->sign) {
/*
* different signs -> invalid
*/
exceptions |= FPSCR_IOC;
vsp = &<API key>;
} else {
/*
* same signs -> valid
*/
vsp = vsn;
}
} else if (tn & VFP_INFINITY && tm & VFP_NUMBER) {
/*
* One infinity and one number -> infinity
*/
vsp = vsn;
} else {
/*
* 'n' is a NaN of some type
*/
return vfp_propagate_nan(vsd, vsn, vsm, fpscr);
}
*vsd = *vsp;
return exceptions;
}
static u32 vfp_single_add(struct vfp_single* vsd, struct vfp_single* vsn, struct vfp_single* vsm,
u32 fpscr) {
u32 exp_diff, m_sig;
if (vsn->significand & 0x80000000 || vsm->significand & 0x80000000) {
LOG_WARNING(Core_ARM11, "bad FP values");
vfp_single_dump("VSN", vsn);
vfp_single_dump("VSM", vsm);
}
/*
* Ensure that 'n' is the largest magnitude number. Note that
* if 'n' and 'm' have equal exponents, we do not swap them.
* This ensures that NaN propagation works correctly.
*/
if (vsn->exponent < vsm->exponent) {
std::swap(vsm, vsn);
}
/*
* Is 'n' an infinity or a NaN? Note that 'm' may be a number,
* infinity or a NaN here.
*/
if (vsn->exponent == 255)
return <API key>(vsd, vsn, vsm, fpscr);
/*
* We have two proper numbers, where 'vsn' is the larger magnitude.
*
* Copy 'n' to 'd' before doing the arithmetic.
*/
*vsd = *vsn;
/*
* Align both numbers.
*/
exp_diff = vsn->exponent - vsm->exponent;
m_sig = <API key>(vsm->significand, exp_diff);
/*
* If the signs are different, we are really subtracting.
*/
if (vsn->sign ^ vsm->sign) {
m_sig = vsn->significand - m_sig;
if ((s32)m_sig < 0) {
vsd->sign = vfp_sign_negate(vsd->sign);
m_sig = (~m_sig + 1);
} else if (m_sig == 0) {
vsd->sign = (fpscr & FPSCR_RMODE_MASK) == <API key> ? 0x8000 : 0;
}
} else {
m_sig = vsn->significand + m_sig;
}
vsd->significand = m_sig;
return 0;
}
static u32 vfp_single_multiply(struct vfp_single* vsd, struct vfp_single* vsn,
struct vfp_single* vsm, u32 fpscr) {
vfp_single_dump("VSN", vsn);
vfp_single_dump("VSM", vsm);
/*
* Ensure that 'n' is the largest magnitude number. Note that
* if 'n' and 'm' have equal exponents, we do not swap them.
* This ensures that NaN propagation works correctly.
*/
if (vsn->exponent < vsm->exponent) {
std::swap(vsm, vsn);
LOG_TRACE(Core_ARM11, "swapping M <-> N");
}
vsd->sign = vsn->sign ^ vsm->sign;
/*
* If 'n' is an infinity or NaN, handle it. 'm' may be anything.
*/
if (vsn->exponent == 255) {
if (vsn->significand || (vsm->exponent == 255 && vsm->significand))
return vfp_propagate_nan(vsd, vsn, vsm, fpscr);
if ((vsm->exponent | vsm->significand) == 0) {
*vsd = <API key>;
return FPSCR_IOC;
}
vsd->exponent = vsn->exponent;
vsd->significand = 0;
return 0;
}
/*
* If 'm' is zero, the result is always zero. In this case,
* 'n' may be zero or a number, but it doesn't matter which.
*/
if ((vsm->exponent | vsm->significand) == 0) {
vsd->exponent = 0;
vsd->significand = 0;
return 0;
}
/*
* We add 2 to the destination exponent for the same reason as
* the addition case - though this time we have +1 from each
* input operand.
*/
vsd->exponent = vsn->exponent + vsm->exponent - 127 + 2;
vsd->significand = vfp_hi64to32jamming((u64)vsn->significand * vsm->significand);
vfp_single_dump("VSD", vsd);
return 0;
}
#define NEG_MULTIPLY (1 << 0)
#define NEG_SUBTRACT (1 << 1)
static u32 <API key>(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr,
u32 negate, const char* func) {
vfp_single vsd, vsp, vsn, vsm;
u32 exceptions = 0;
s32 v;
v = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, v);
exceptions |= vfp_single_unpack(&vsn, v, fpscr);
if (vsn.exponent == 0 && vsn.significand)
<API key>(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
<API key>(&vsm);
exceptions |= vfp_single_multiply(&vsp, &vsn, &vsm, fpscr);
if (negate & NEG_MULTIPLY)
vsp.sign = vfp_sign_negate(vsp.sign);
v = vfp_get_float(state, sd);
LOG_TRACE(Core_ARM11, "s%u = %08x", sd, v);
exceptions |= vfp_single_unpack(&vsn, v, fpscr);
if (vsn.exponent == 0 && vsn.significand != 0)
<API key>(&vsn);
if (negate & NEG_SUBTRACT)
vsn.sign = vfp_sign_negate(vsn.sign);
exceptions |= vfp_single_add(&vsd, &vsn, &vsp, fpscr);
exceptions |= <API key>(state, sd, &vsd, fpscr, func);
return exceptions;
}
/*
* Standard operations
*/
/*
* sd = sd + (sn * sm)
*/
static u32 vfp_single_fmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
u32 exceptions = 0;
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
exceptions |= <API key>(state, sd, sn, m, fpscr, 0, "fmac");
return exceptions;
}
/*
* sd = sd - (sn * sm)
*/
static u32 vfp_single_fnmac(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
// TODO: this one has its arguments inverted, investigate.
LOG_TRACE(Core_ARM11, "s%u = %08x", sd, sn);
return <API key>(state, sd, sn, m, fpscr, NEG_MULTIPLY, "fnmac");
}
/*
* sd = -sd + (sn * sm)
*/
static u32 vfp_single_fmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
return <API key>(state, sd, sn, m, fpscr, NEG_SUBTRACT, "fmsc");
}
/*
* sd = -sd - (sn * sm)
*/
static u32 vfp_single_fnmsc(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
return <API key>(state, sd, sn, m, fpscr, NEG_SUBTRACT | NEG_MULTIPLY,
"fnmsc");
}
/*
* sd = sn * sm
*/
static u32 vfp_single_fmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
<API key>(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
<API key>(&vsm);
exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr);
exceptions |= <API key>(state, sd, &vsd, fpscr, "fmul");
return exceptions;
}
/*
* sd = -(sn * sm)
*/
static u32 vfp_single_fnmul(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
<API key>(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
<API key>(&vsm);
exceptions |= vfp_single_multiply(&vsd, &vsn, &vsm, fpscr);
vsd.sign = vfp_sign_negate(vsd.sign);
exceptions |= <API key>(state, sd, &vsd, fpscr, "fnmul");
return exceptions;
}
/*
* sd = sn + sm
*/
static u32 vfp_single_fadd(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
/*
* Unpack and normalise denormals.
*/
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
if (vsn.exponent == 0 && vsn.significand)
<API key>(&vsn);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
if (vsm.exponent == 0 && vsm.significand)
<API key>(&vsm);
exceptions |= vfp_single_add(&vsd, &vsn, &vsm, fpscr);
exceptions |= <API key>(state, sd, &vsd, fpscr, "fadd");
return exceptions;
}
/*
* sd = sn - sm
*/
static u32 vfp_single_fsub(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, sd);
/*
* Subtraction is addition with one sign inverted.
*/
if (m != 0x7FC00000) // Only negate if m isn't NaN.
m = <API key>(m);
return vfp_single_fadd(state, sd, sn, m, fpscr);
}
/*
* sd = sn / sm
*/
static u32 vfp_single_fdiv(ARMul_State* state, int sd, int sn, s32 m, u32 fpscr) {
struct vfp_single vsd, vsn, vsm;
u32 exceptions = 0;
s32 n = vfp_get_float(state, sn);
int tm, tn;
LOG_TRACE(Core_ARM11, "s%u = %08x", sn, n);
exceptions |= vfp_single_unpack(&vsn, n, fpscr);
exceptions |= vfp_single_unpack(&vsm, m, fpscr);
vsd.sign = vsn.sign ^ vsm.sign;
tn = vfp_single_type(&vsn);
tm = vfp_single_type(&vsm);
/*
* Is n a NAN?
*/
if (tn & VFP_NAN)
goto vsn_nan;
/*
* Is m a NAN?
*/
if (tm & VFP_NAN)
goto vsm_nan;
/*
* If n and m are infinity, the result is invalid
* If n and m are zero, the result is invalid
*/
if (tm & tn & (VFP_INFINITY | VFP_ZERO))
goto invalid;
/*
* If n is infinity, the result is infinity
*/
if (tn & VFP_INFINITY)
goto infinity;
/*
* If m is zero, raise div0 exception
*/
if (tm & VFP_ZERO)
goto divzero;
/*
* If m is infinity, or n is zero, the result is zero
*/
if (tm & VFP_INFINITY || tn & VFP_ZERO)
goto zero;
if (tn & VFP_DENORMAL)
<API key>(&vsn);
if (tm & VFP_DENORMAL)
<API key>(&vsm);
/*
* Ok, we have two numbers, we can perform division.
*/
vsd.exponent = vsn.exponent - vsm.exponent + 127 - 1;
vsm.significand <<= 1;
if (vsm.significand <= (2 * vsn.significand)) {
vsn.significand >>= 1;
vsd.exponent++;
}
{
u64 significand = (u64)vsn.significand << 32;
do_div(significand, vsm.significand);
vsd.significand = (u32)significand;
}
if ((vsd.significand & 0x3f) == 0)
vsd.significand |= ((u64)vsm.significand * vsd.significand != (u64)vsn.significand << 32);
exceptions |= <API key>(state, sd, &vsd, fpscr, "fdiv");
return exceptions;
vsn_nan:
exceptions |= vfp_propagate_nan(&vsd, &vsn, &vsm, fpscr);
pack:
vfp_put_float(state, vfp_single_pack(&vsd), sd);
return exceptions;
vsm_nan:
exceptions |= vfp_propagate_nan(&vsd, &vsm, &vsn, fpscr);
goto pack;
zero:
vsd.exponent = 0;
vsd.significand = 0;
goto pack;
divzero:
exceptions |= FPSCR_DZC;
infinity:
vsd.exponent = 255;
vsd.significand = 0;
goto pack;
invalid:
vfp_put_float(state, vfp_single_pack(&<API key>), sd);
exceptions |= FPSCR_IOC;
return exceptions;
}
static struct op fops[] = {
{vfp_single_fmac, 0}, {vfp_single_fmsc, 0}, {vfp_single_fmul, 0},
{vfp_single_fadd, 0}, {vfp_single_fnmac, 0}, {vfp_single_fnmsc, 0},
{vfp_single_fnmul, 0}, {vfp_single_fsub, 0}, {vfp_single_fdiv, 0},
};
#define FREG_BANK(x) ((x)&0x18)
#define FREG_IDX(x) ((x)&7)
u32 vfp_single_cpdo(ARMul_State* state, u32 inst, u32 fpscr) {
u32 op = inst & FOP_MASK;
u32 exceptions = 0;
unsigned int dest;
unsigned int sn = vfp_get_sn(inst);
unsigned int sm = vfp_get_sm(inst);
unsigned int vecitr, veclen, vecstride;
struct op* fop;
vecstride = 1 + ((fpscr & FPSCR_STRIDE_MASK) == FPSCR_STRIDE_MASK);
fop = (op == FOP_EXT) ? &fops_ext[FEXT_TO_IDX(inst)] : &fops[FOP_TO_IDX(op)];
/*
* fcvtsd takes a dN register number as destination, not sN.
* Technically, if bit 0 of dd is set, this is an invalid
* instruction. However, we ignore this for efficiency.
* It also only operates on scalars.
*/
if (fop->flags & OP_DD)
dest = vfp_get_dd(inst);
else
dest = vfp_get_sd(inst);
/*
* If destination bank is zero, vector length is always '1'.
* ARM DDI0100F C5.1.3, C5.3.2.
*/
if ((fop->flags & OP_SCALAR) || FREG_BANK(dest) == 0)
veclen = 0;
else
veclen = fpscr & FPSCR_LENGTH_MASK;
LOG_TRACE(Core_ARM11, "vecstride=%u veclen=%u", vecstride, (veclen >> FPSCR_LENGTH_BIT) + 1);
if (!fop->fn) {
LOG_CRITICAL(Core_ARM11, "could not find single op %d, inst=0x%x@0x%x", FEXT_TO_IDX(inst),
inst, state->Reg[15]);
Crash();
goto invalid;
}
for (vecitr = 0; vecitr <= veclen; vecitr += 1 << FPSCR_LENGTH_BIT) {
s32 m = vfp_get_float(state, sm);
u32 except;
char type;
type = (fop->flags & OP_DD) ? 'd' : 's';
if (op == FOP_EXT)
LOG_TRACE(Core_ARM11, "itr%d (%c%u) = op[%u] (s%u=%08x)", vecitr >> FPSCR_LENGTH_BIT,
type, dest, sn, sm, m);
else
LOG_TRACE(Core_ARM11, "itr%d (%c%u) = (s%u) op[%u] (s%u=%08x)",
vecitr >> FPSCR_LENGTH_BIT, type, dest, sn, FOP_TO_IDX(op), sm, m);
except = fop->fn(state, dest, sn, m, fpscr);
LOG_TRACE(Core_ARM11, "itr%d: exceptions=%08x", vecitr >> FPSCR_LENGTH_BIT, except);
exceptions |= except;
/*
* CHECK: It appears to be undefined whether we stop when
* we encounter an exception. We continue.
*/
dest = FREG_BANK(dest) + ((FREG_IDX(dest) + vecstride) & 7);
sn = FREG_BANK(sn) + ((FREG_IDX(sn) + vecstride) & 7);
if (FREG_BANK(sm) != 0)
sm = FREG_BANK(sm) + ((FREG_IDX(sm) + vecstride) & 7);
}
return exceptions;
invalid:
return (u32)-1;
}
|
#include <stddef.h> /* offsetof */
#include "hw.h"
#include "pci.h"
#include "net.h"
#include "eeprom93xx.h"
#include "sysemu.h"
#include "dma.h"
/* QEMU sends frames smaller than 60 bytes to ethernet nics.
* Such frames are rejected by real nics and their emulations.
* To avoid this behaviour, other nic emulations pad received
* frames. The following definition enables this padding for
* eepro100, too. We keep the define around in case it might
* become useful the future if the core networking is ever
* changed to pad short packets itself. */
#define <API key>
#define KiB 1024
/* Debug EEPRO100 card. */
#if 0
# define DEBUG_EEPRO100
#endif
#ifdef DEBUG_EEPRO100
#define logout(fmt, ...) fprintf(stderr, "EE100\t%-24s" fmt, __func__, ## __VA_ARGS__)
#else
#define logout(fmt, ...) ((void)0)
#endif
/* Set flags to 0 to disable debug output. */
#define INT 1 /* interrupt related actions */
#define MDI 1 /* mdi related actions */
#define OTHER 1
#define RXTX 1
#define EEPROM 1 /* eeprom related actions */
#define TRACE(flag, command) ((flag) ? (command) : (void)0)
#define missing(text) fprintf(stderr, "eepro100: feature is missing in this emulation: " text "\n")
#define MAX_ETH_FRAME_SIZE 1514
/* This driver supports several different devices which are declared here. */
#define i82550 0x82550
#define i82551 0x82551
#define i82557A 0x82557a
#define i82557B 0x82557b
#define i82557C 0x82557c
#define i82558A 0x82558a
#define i82558B 0x82558b
#define i82559A 0x82559a
#define i82559B 0x82559b
#define i82559C 0x82559c
#define i82559ER 0x82559e
#define i82562 0x82562
#define i82801 0x82801
/* Use 64 word EEPROM. TODO: could be a runtime option. */
#define EEPROM_SIZE 64
#define PCI_MEM_SIZE (4 * KiB)
#define PCI_IO_SIZE 64
#define PCI_FLASH_SIZE (128 * KiB)
#define BIT(n) (1 << (n))
#define BITS(n, m) (((0xffffffffU << (31 - n)) >> (31 - n + m)) << m)
/* The SCB accepts the following controls for the Tx and Rx units: */
#define CU_NOP 0x0000 /* No operation. */
#define CU_START 0x0010 /* CU start. */
#define CU_RESUME 0x0020 /* CU resume. */
#define CU_STATSADDR 0x0040 /* Load dump counters address. */
#define CU_SHOWSTATS 0x0050 /* Dump statistical counters. */
#define CU_CMD_BASE 0x0060 /* Load CU base address. */
#define CU_DUMPSTATS 0x0070 /* Dump and reset statistical counters. */
#define CU_SRESUME 0x00a0 /* CU static resume. */
#define RU_NOP 0x0000
#define RX_START 0x0001
#define RX_RESUME 0x0002
#define RU_ABORT 0x0004
#define RX_ADDR_LOAD 0x0006
#define RX_RESUMENR 0x0007
#define INT_MASK 0x0100
#define DRVR_INT 0x0200 /* Driver generated interrupt. */
typedef struct {
const char *name;
const char *desc;
uint16_t device_id;
uint8_t revision;
uint16_t subsystem_vendor_id;
uint16_t subsystem_id;
uint32_t device;
uint8_t stats_size;
bool <API key>;
bool power_management;
} E100PCIDeviceInfo;
/* Offsets to the various registers.
All accesses need not be longword aligned. */
typedef enum {
SCBStatus = 0, /* Status Word. */
SCBAck = 1,
SCBCmd = 2, /* Rx/Command Unit command and status. */
SCBIntmask = 3,
SCBPointer = 4, /* General purpose pointer. */
SCBPort = 8, /* Misc. commands and operands. */
SCBflash = 12, /* Flash memory control. */
SCBeeprom = 14, /* EEPROM control. */
SCBCtrlMDI = 16, /* MDI interface control. */
SCBEarlyRx = 20, /* Early receive byte count. */
SCBFlow = 24, /* Flow Control. */
SCBpmdr = 27, /* Power Management Driver. */
SCBgctrl = 28, /* General Control. */
SCBgstat = 29, /* General Status. */
} E100RegisterOffset;
/* A speedo3 transmit buffer descriptor with two buffers... */
typedef struct {
uint16_t status;
uint16_t command;
uint32_t link; /* void * */
uint32_t tbd_array_addr; /* transmit buffer descriptor array address. */
uint16_t tcb_bytes; /* transmit command block byte count (in lower 14 bits */
uint8_t tx_threshold; /* transmit threshold */
uint8_t tbd_count; /* TBD number */
#if 0
/* This constitutes two "TBD" entries: hdr and data */
uint32_t tx_buf_addr0; /* void *, header of frame to be transmitted. */
int32_t tx_buf_size0; /* Length of Tx hdr. */
uint32_t tx_buf_addr1; /* void *, data to be transmitted. */
int32_t tx_buf_size1; /* Length of Tx data. */
#endif
} eepro100_tx_t;
/* Receive frame descriptor. */
typedef struct {
int16_t status;
uint16_t command;
uint32_t link; /* struct RxFD * */
uint32_t rx_buf_addr; /* void * */
uint16_t count;
uint16_t size;
/* Ethernet frame data follows. */
} eepro100_rx_t;
typedef enum {
COMMAND_EL = BIT(15),
COMMAND_S = BIT(14),
COMMAND_I = BIT(13),
COMMAND_NC = BIT(4),
COMMAND_SF = BIT(3),
COMMAND_CMD = BITS(2, 0),
} scb_command_bit;
typedef enum {
STATUS_C = BIT(15),
STATUS_OK = BIT(13),
} scb_status_bit;
typedef struct {
uint32_t tx_good_frames, tx_max_collisions, tx_late_collisions,
tx_underruns, tx_lost_crs, tx_deferred, <API key>,
<API key>, tx_total_collisions;
uint32_t rx_good_frames, rx_crc_errors, rx_alignment_errors,
rx_resource_errors, rx_overrun_errors, rx_cdt_errors,
<API key>;
uint32_t fc_xmt_pause, fc_rcv_pause, fc_rcv_unsupported;
uint16_t xmt_tco_frames, rcv_tco_frames;
/* TODO: i82559 has six reserved statistics but a total of 24 dwords. */
uint32_t reserved[4];
} eepro100_stats_t;
typedef enum {
cu_idle = 0,
cu_suspended = 1,
cu_active = 2,
cu_lpq_active = 2,
cu_hqp_active = 3
} cu_state_t;
typedef enum {
ru_idle = 0,
ru_suspended = 1,
ru_no_resources = 2,
ru_ready = 4
} ru_state_t;
typedef struct {
PCIDevice dev;
/* Hash register (multicast mask array, multiple individual addresses). */
uint8_t mult[8];
MemoryRegion mmio_bar;
MemoryRegion io_bar;
MemoryRegion flash_bar;
NICState *nic;
NICConf conf;
uint8_t scb_stat; /* SCB stat/ack byte */
uint8_t int_stat; /* PCI interrupt status */
/* region must not be saved by nic_save. */
uint16_t mdimem[32];
eeprom_t *eeprom;
uint32_t device; /* device variant */
/* (cu_base + cu_offset) address the next command block in the command block list. */
uint32_t cu_base; /* CU base address */
uint32_t cu_offset; /* CU address offset */
/* (ru_base + ru_offset) address the RFD in the Receive Frame Area. */
uint32_t ru_base; /* RU base address */
uint32_t ru_offset; /* RU address offset */
uint32_t statsaddr; /* pointer to eepro100_stats_t */
/* Temporary status information (no need to save these values),
* used while processing CU commands. */
eepro100_tx_t tx; /* transmit buffer descriptor */
uint32_t cb_address; /* = cu_base + cu_offset */
/* Statistical counters. Also used for wake-up packet (i82559). */
eepro100_stats_t statistics;
/* Data in mem is always in the byte order of the controller (le).
* It must be dword aligned to allow direct access to 32 bit values. */
uint8_t mem[PCI_MEM_SIZE] __attribute__((aligned(8)));
/* Configuration bytes. */
uint8_t configuration[22];
/* vmstate for each particular nic */
VMStateDescription *vmstate;
/* Quasi static device properties (no need to save them). */
uint16_t stats_size;
bool <API key>;
} EEPRO100State;
/* Word indices in EEPROM. */
typedef enum {
EEPROM_CNFG_MDIX = 0x03,
EEPROM_ID = 0x05,
EEPROM_PHY_ID = 0x06,
EEPROM_VENDOR_ID = 0x0c,
EEPROM_CONFIG_ASF = 0x0d,
EEPROM_DEVICE_ID = 0x23,
EEPROM_SMBUS_ADDR = 0x90,
} EEPROMOffset;
/* Bit values for EEPROM ID word. */
typedef enum {
EEPROM_ID_MDM = BIT(0), /* Modem */
EEPROM_ID_STB = BIT(1), /* Standby Enable */
EEPROM_ID_WMR = BIT(2),
EEPROM_ID_WOL = BIT(5), /* Wake on LAN */
EEPROM_ID_DPD = BIT(6), /* Deep Power Down */
EEPROM_ID_ALT = BIT(7),
/* BITS(10, 8) device revision */
EEPROM_ID_BD = BIT(11), /* boot disable */
EEPROM_ID_ID = BIT(13), /* id bit */
/* BITS(15, 14) signature */
EEPROM_ID_VALID = BIT(14), /* signature for valid eeprom */
} eeprom_id_bit;
/* Default values for MDI (PHY) registers */
static const uint16_t <API key>[] = {
/* MDI Registers 0 - 6, 7 */
0x3000, 0x780d, 0x02a8, 0x0154, 0x05e1, 0x0000, 0x0000, 0x0000,
/* MDI Registers 8 - 15 */
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
/* MDI Registers 16 - 31 */
0x0003, 0x0000, 0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
};
/* Readonly mask for MDI (PHY) registers */
static const uint16_t eepro100_mdi_mask[] = {
0x0000, 0xffff, 0xffff, 0xffff, 0xc01f, 0xffff, 0xffff, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0fff, 0x0000, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
0xffff, 0xffff, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
};
#define POLYNOMIAL 0x04c11db6
static E100PCIDeviceInfo *eepro100_get_class(EEPRO100State *s);
/* From FreeBSD (locally modified). */
static unsigned <API key>(const uint8_t *ep)
{
uint32_t crc;
int carry, i, j;
uint8_t b;
crc = 0xffffffff;
for (i = 0; i < 6; i++) {
b = *ep++;
for (j = 0; j < 8; j++) {
carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
crc <<= 1;
b >>= 1;
if (carry) {
crc = ((crc ^ POLYNOMIAL) | carry);
}
}
}
return (crc & BITS(7, 2)) >> 2;
}
/* Read a 16 bit control/status (CSR) register. */
static uint16_t e100_read_reg2(EEPRO100State *s, E100RegisterOffset addr)
{
assert(!((uintptr_t)&s->mem[addr] & 1));
return le16_to_cpup((uint16_t *)&s->mem[addr]);
}
/* Read a 32 bit control/status (CSR) register. */
static uint32_t e100_read_reg4(EEPRO100State *s, E100RegisterOffset addr)
{
assert(!((uintptr_t)&s->mem[addr] & 3));
return le32_to_cpup((uint32_t *)&s->mem[addr]);
}
/* Write a 16 bit control/status (CSR) register. */
static void e100_write_reg2(EEPRO100State *s, E100RegisterOffset addr,
uint16_t val)
{
assert(!((uintptr_t)&s->mem[addr] & 1));
cpu_to_le16w((uint16_t *)&s->mem[addr], val);
}
/* Read a 32 bit control/status (CSR) register. */
static void e100_write_reg4(EEPRO100State *s, E100RegisterOffset addr,
uint32_t val)
{
assert(!((uintptr_t)&s->mem[addr] & 3));
cpu_to_le32w((uint32_t *)&s->mem[addr], val);
}
#if defined(DEBUG_EEPRO100)
static const char *nic_dump(const uint8_t * buf, unsigned size)
{
static char dump[3 * 16 + 1];
char *p = &dump[0];
if (size > 16) {
size = 16;
}
while (size
p += sprintf(p, " %02x", *buf++);
}
return dump;
}
#endif /* DEBUG_EEPRO100 */
enum scb_stat_ack {
stat_ack_not_ours = 0x00,
stat_ack_sw_gen = 0x04,
stat_ack_rnr = 0x10,
stat_ack_cu_idle = 0x20,
stat_ack_frame_rx = 0x40,
<API key> = 0x80,
<API key> = 0xFF,
stat_ack_rx = (stat_ack_sw_gen | stat_ack_rnr | stat_ack_frame_rx),
stat_ack_tx = (stat_ack_cu_idle | <API key>),
};
static void disable_interrupt(EEPRO100State * s)
{
if (s->int_stat) {
TRACE(INT, logout("interrupt disabled\n"));
qemu_irq_lower(s->dev.irq[0]);
s->int_stat = 0;
}
}
static void enable_interrupt(EEPRO100State * s)
{
if (!s->int_stat) {
TRACE(INT, logout("interrupt enabled\n"));
qemu_irq_raise(s->dev.irq[0]);
s->int_stat = 1;
}
}
static void <API key>(EEPRO100State * s)
{
s->scb_stat &= ~s->mem[SCBAck];
s->mem[SCBAck] = s->scb_stat;
if (s->scb_stat == 0) {
disable_interrupt(s);
}
}
static void eepro100_interrupt(EEPRO100State * s, uint8_t status)
{
uint8_t mask = ~s->mem[SCBIntmask];
s->mem[SCBAck] |= status;
status = s->scb_stat = s->mem[SCBAck];
status &= (mask | 0x0f);
#if 0
status &= (~s->mem[SCBIntmask] | 0x0xf);
#endif
if (status && (mask & 0x01)) {
/* SCB mask and SCB Bit M do not disable interrupt. */
enable_interrupt(s);
} else if (s->int_stat) {
disable_interrupt(s);
}
}
static void <API key>(EEPRO100State * s)
{
/* CU completed action command. */
/* Transmit not ok (82557 only, not in emulation). */
eepro100_interrupt(s, 0x80);
}
static void <API key>(EEPRO100State * s)
{
/* CU left the active state. */
eepro100_interrupt(s, 0x20);
}
static void <API key>(EEPRO100State * s)
{
/* RU received a complete frame. */
eepro100_interrupt(s, 0x40);
}
static void <API key>(EEPRO100State * s)
{
/* RU is not ready. */
eepro100_interrupt(s, 0x10);
}
static void <API key>(EEPRO100State * s)
{
/* MDI completed read or write cycle. */
eepro100_interrupt(s, 0x08);
}
static void <API key>(EEPRO100State * s)
{
/* Software has requested an interrupt. */
eepro100_interrupt(s, 0x04);
}
#if 0
static void <API key>(EEPRO100State * s)
{
/* Flow control pause interrupt (82558 and later). */
eepro100_interrupt(s, 0x01);
}
#endif
static void e100_pci_reset(EEPRO100State * s)
{
E100PCIDeviceInfo *info = eepro100_get_class(s);
uint32_t device = s->device;
uint8_t *pci_conf = s->dev.config;
TRACE(OTHER, logout("%p\n", s));
/* PCI Status */
pci_set_word(pci_conf + PCI_STATUS, <API key> |
<API key>);
/* PCI Latency Timer */
pci_set_byte(pci_conf + PCI_LATENCY_TIMER, 0x20); /* latency timer = 32 clocks */
/* Capability Pointer is set by PCI framework. */
/* Interrupt Line */
/* Interrupt Pin */
pci_set_byte(pci_conf + PCI_INTERRUPT_PIN, 1); /* interrupt pin A */
/* Minimum Grant */
pci_set_byte(pci_conf + PCI_MIN_GNT, 0x08);
/* Maximum Latency */
pci_set_byte(pci_conf + PCI_MAX_LAT, 0x18);
s->stats_size = info->stats_size;
s-><API key> = info-><API key>;
switch (device) {
case i82550:
case i82551:
case i82557A:
case i82557B:
case i82557C:
case i82558A:
case i82558B:
case i82559A:
case i82559B:
case i82559ER:
case i82562:
case i82801:
case i82559C:
break;
default:
logout("Device %X is undefined!\n", device);
}
/* Standard TxCB. */
s->configuration[6] |= BIT(4);
/* Standard statistical counters. */
s->configuration[6] |= BIT(5);
if (s->stats_size == 80) {
/* TODO: check TCO Statistical Counters bit. Documentation not clear. */
if (s->configuration[6] & BIT(2)) {
/* TCO statistical counters. */
assert(s->configuration[6] & BIT(5));
} else {
if (s->configuration[6] & BIT(5)) {
/* No extended statistical counters, i82557 compatible. */
s->stats_size = 64;
} else {
/* i82558 compatible. */
s->stats_size = 76;
}
}
} else {
if (s->configuration[6] & BIT(5)) {
/* No extended statistical counters. */
s->stats_size = 64;
}
}
assert(s->stats_size > 0 && s->stats_size <= sizeof(s->statistics));
if (info->power_management) {
/* Power Management Capabilities */
int cfg_offset = 0xdc;
int r = pci_add_capability(&s->dev, PCI_CAP_ID_PM,
cfg_offset, PCI_PM_SIZEOF);
assert(r >= 0);
pci_set_word(pci_conf + cfg_offset + PCI_PM_PMC, 0x7e21);
#if 0 /* TODO: replace dummy code for power management emulation. */
/* TODO: Power Management Control / Status. */
pci_set_word(pci_conf + cfg_offset + PCI_PM_CTRL, 0x0000);
/* TODO: Ethernet Power Consumption Registers (i82559 and later). */
pci_set_byte(pci_conf + cfg_offset + <API key>, 0x0000);
#endif
}
#if EEPROM_SIZE > 0
if (device == i82557C || device == i82558B || device == i82559C) {
/*
TODO: get vendor id from EEPROM for i82557C or later.
TODO: get device id from EEPROM for i82557C or later.
TODO: status bit 4 can be disabled by EEPROM for i82558, i82559.
TODO: header type is determined by EEPROM for i82559.
TODO: get subsystem id from EEPROM for i82557C or later.
TODO: get subsystem vendor id from EEPROM for i82557C or later.
TODO: exp. rom baddr depends on a bit in EEPROM for i82558 or later.
TODO: capability pointer depends on EEPROM for i82558.
*/
logout("Get device id and revision from EEPROM!!!\n");
}
#endif /* EEPROM_SIZE > 0 */
}
static void nic_selective_reset(EEPRO100State * s)
{
size_t i;
uint16_t *eeprom_contents = eeprom93xx_data(s->eeprom);
#if 0
eeprom93xx_reset(s->eeprom);
#endif
memcpy(eeprom_contents, s->conf.macaddr.a, 6);
eeprom_contents[EEPROM_ID] = EEPROM_ID_VALID;
if (s->device == i82557B || s->device == i82557C)
eeprom_contents[5] = 0x0100;
eeprom_contents[EEPROM_PHY_ID] = 1;
uint16_t sum = 0;
for (i = 0; i < EEPROM_SIZE - 1; i++) {
sum += eeprom_contents[i];
}
eeprom_contents[EEPROM_SIZE - 1] = 0xbaba - sum;
TRACE(EEPROM, logout("checksum=0x%04x\n", eeprom_contents[EEPROM_SIZE - 1]));
memset(s->mem, 0, sizeof(s->mem));
e100_write_reg4(s, SCBCtrlMDI, BIT(21));
assert(sizeof(s->mdimem) == sizeof(<API key>));
memcpy(&s->mdimem[0], &<API key>[0], sizeof(s->mdimem));
}
static void nic_reset(void *opaque)
{
EEPRO100State *s = opaque;
TRACE(OTHER, logout("%p\n", s));
/* TODO: Clearing of hash register for selective reset, too? */
memset(&s->mult[0], 0, sizeof(s->mult));
nic_selective_reset(s);
}
#if defined(DEBUG_EEPRO100)
static const char * const e100_reg[PCI_IO_SIZE / 4] = {
"Command/Status",
"General Pointer",
"Port",
"EEPROM/Flash Control",
"MDI Control",
"Receive DMA Byte Count",
"Flow Control",
"General Status/Control"
};
static char *regname(uint32_t addr)
{
static char buf[32];
if (addr < PCI_IO_SIZE) {
const char *r = e100_reg[addr / 4];
if (r != 0) {
snprintf(buf, sizeof(buf), "%s+%u", r, addr % 4);
} else {
snprintf(buf, sizeof(buf), "0x%02x", addr);
}
} else {
snprintf(buf, sizeof(buf), "??? 0x%08x", addr);
}
return buf;
}
#endif /* DEBUG_EEPRO100 */
#if 0
static uint16_t <API key>(EEPRO100State * s)
{
uint16_t val = 0xffff;
TRACE(OTHER, logout("val=0x%04x\n", val));
return val;
}
#endif
/* Commands that can be put in a command list entry. */
enum commands {
CmdNOp = 0,
CmdIASetup = 1,
CmdConfigure = 2,
CmdMulticastList = 3,
CmdTx = 4,
CmdTDR = 5, /* load microcode */
CmdDump = 6,
CmdDiagnose = 7,
/* And some extra flags: */
CmdSuspend = 0x4000, /* Suspend after completion. */
CmdIntr = 0x2000, /* Interrupt after completion. */
CmdTxFlex = 0x0008, /* Use "Flexible mode" for CmdTx command. */
};
static cu_state_t get_cu_state(EEPRO100State * s)
{
return ((s->mem[SCBStatus] & BITS(7, 6)) >> 6);
}
static void set_cu_state(EEPRO100State * s, cu_state_t state)
{
s->mem[SCBStatus] = (s->mem[SCBStatus] & ~BITS(7, 6)) + (state << 6);
}
static ru_state_t get_ru_state(EEPRO100State * s)
{
return ((s->mem[SCBStatus] & BITS(5, 2)) >> 2);
}
static void set_ru_state(EEPRO100State * s, ru_state_t state)
{
s->mem[SCBStatus] = (s->mem[SCBStatus] & ~BITS(5, 2)) + (state << 2);
}
static void dump_statistics(EEPRO100State * s)
{
/* Dump statistical data. Most data is never changed by the emulation
* and always 0, so we first just copy the whole block and then those
* values which really matter.
* Number of data should check configuration!!!
*/
pci_dma_write(&s->dev, s->statsaddr, &s->statistics, s->stats_size);
stl_le_pci_dma(&s->dev, s->statsaddr + 0,
s->statistics.tx_good_frames);
stl_le_pci_dma(&s->dev, s->statsaddr + 36,
s->statistics.rx_good_frames);
stl_le_pci_dma(&s->dev, s->statsaddr + 48,
s->statistics.rx_resource_errors);
stl_le_pci_dma(&s->dev, s->statsaddr + 60,
s->statistics.<API key>);
#if 0
stw_le_pci_dma(&s->dev, s->statsaddr + 76, s->statistics.xmt_tco_frames);
stw_le_pci_dma(&s->dev, s->statsaddr + 78, s->statistics.rcv_tco_frames);
missing("CU dump statistical counters");
#endif
}
static void read_cb(EEPRO100State *s)
{
pci_dma_read(&s->dev, s->cb_address, &s->tx, sizeof(s->tx));
s->tx.status = le16_to_cpu(s->tx.status);
s->tx.command = le16_to_cpu(s->tx.command);
s->tx.link = le32_to_cpu(s->tx.link);
s->tx.tbd_array_addr = le32_to_cpu(s->tx.tbd_array_addr);
s->tx.tcb_bytes = le16_to_cpu(s->tx.tcb_bytes);
}
static void tx_command(EEPRO100State *s)
{
uint32_t tbd_array = le32_to_cpu(s->tx.tbd_array_addr);
uint16_t tcb_bytes = (le16_to_cpu(s->tx.tcb_bytes) & 0x3fff);
/* Sends larger than MAX_ETH_FRAME_SIZE are allowed, up to 2600 bytes. */
uint8_t buf[2600];
uint16_t size = 0;
uint32_t tbd_address = s->cb_address + 0x10;
TRACE(RXTX, logout
("transmit, TBD array address 0x%08x, TCB byte count 0x%04x, TBD count %u\n",
tbd_array, tcb_bytes, s->tx.tbd_count));
if (tcb_bytes > 2600) {
logout("TCB byte count too large, using 2600\n");
tcb_bytes = 2600;
}
if (!((tcb_bytes > 0) || (tbd_array != 0xffffffff))) {
logout
("illegal values of TBD array address and TCB byte count!\n");
}
assert(tcb_bytes <= sizeof(buf));
while (size < tcb_bytes) {
uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev, tbd_address);
uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev, tbd_address + 4);
#if 0
uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev, tbd_address + 6);
#endif
tbd_address += 8;
TRACE(RXTX, logout
("TBD (simplified mode): buffer address 0x%08x, size 0x%04x\n",
tx_buffer_address, tx_buffer_size));
tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size);
pci_dma_read(&s->dev, tx_buffer_address, &buf[size], tx_buffer_size);
size += tx_buffer_size;
}
if (tbd_array == 0xffffffff) {
/* Simplified mode. Was already handled by code above. */
} else {
/* Flexible mode. */
uint8_t tbd_count = 0;
if (s-><API key> && !(s->configuration[6] & BIT(4))) {
/* Extended Flexible TCB. */
for (; tbd_count < 2; tbd_count++) {
uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev,
tbd_address);
uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev,
tbd_address + 4);
uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev,
tbd_address + 6);
tbd_address += 8;
TRACE(RXTX, logout
("TBD (extended flexible mode): buffer address 0x%08x, size 0x%04x\n",
tx_buffer_address, tx_buffer_size));
tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size);
pci_dma_read(&s->dev, tx_buffer_address,
&buf[size], tx_buffer_size);
size += tx_buffer_size;
if (tx_buffer_el & 1) {
break;
}
}
}
tbd_address = tbd_array;
for (; tbd_count < s->tx.tbd_count; tbd_count++) {
uint32_t tx_buffer_address = ldl_le_pci_dma(&s->dev, tbd_address);
uint16_t tx_buffer_size = lduw_le_pci_dma(&s->dev, tbd_address + 4);
uint16_t tx_buffer_el = lduw_le_pci_dma(&s->dev, tbd_address + 6);
tbd_address += 8;
TRACE(RXTX, logout
("TBD (flexible mode): buffer address 0x%08x, size 0x%04x\n",
tx_buffer_address, tx_buffer_size));
tx_buffer_size = MIN(tx_buffer_size, sizeof(buf) - size);
pci_dma_read(&s->dev, tx_buffer_address,
&buf[size], tx_buffer_size);
size += tx_buffer_size;
if (tx_buffer_el & 1) {
break;
}
}
}
TRACE(RXTX, logout("%p sending frame, len=%d,%s\n", s, size, nic_dump(buf, size)));
qemu_send_packet(&s->nic->nc, buf, size);
s->statistics.tx_good_frames++;
/* Transmit with bad status would raise an CX/TNO interrupt.
* (82557 only). Emulation never has bad status. */
#if 0
<API key>(s);
#endif
}
static void set_multicast_list(EEPRO100State *s)
{
uint16_t multicast_count = s->tx.tbd_array_addr & BITS(13, 0);
uint16_t i;
memset(&s->mult[0], 0, sizeof(s->mult));
TRACE(OTHER, logout("multicast list, multicast count = %u\n", multicast_count));
for (i = 0; i < multicast_count; i += 6) {
uint8_t multicast_addr[6];
pci_dma_read(&s->dev, s->cb_address + 10 + i, multicast_addr, 6);
TRACE(OTHER, logout("multicast entry %s\n", nic_dump(multicast_addr, 6)));
unsigned mcast_idx = <API key>(multicast_addr);
assert(mcast_idx < 64);
s->mult[mcast_idx >> 3] |= (1 << (mcast_idx & 7));
}
}
static void action_command(EEPRO100State *s)
{
for (;;) {
bool bit_el;
bool bit_s;
bool bit_i;
bool bit_nc;
uint16_t ok_status = STATUS_OK;
s->cb_address = s->cu_base + s->cu_offset;
read_cb(s);
bit_el = ((s->tx.command & COMMAND_EL) != 0);
bit_s = ((s->tx.command & COMMAND_S) != 0);
bit_i = ((s->tx.command & COMMAND_I) != 0);
bit_nc = ((s->tx.command & COMMAND_NC) != 0);
#if 0
bool bit_sf = ((s->tx.command & COMMAND_SF) != 0);
#endif
s->cu_offset = s->tx.link;
TRACE(OTHER,
logout("val=(cu start), status=0x%04x, command=0x%04x, link=0x%08x\n",
s->tx.status, s->tx.command, s->tx.link));
switch (s->tx.command & COMMAND_CMD) {
case CmdNOp:
/* Do nothing. */
break;
case CmdIASetup:
pci_dma_read(&s->dev, s->cb_address + 8, &s->conf.macaddr.a[0], 6);
TRACE(OTHER, logout("macaddr: %s\n", nic_dump(&s->conf.macaddr.a[0], 6)));
break;
case CmdConfigure:
pci_dma_read(&s->dev, s->cb_address + 8,
&s->configuration[0], sizeof(s->configuration));
TRACE(OTHER, logout("configuration: %s\n",
nic_dump(&s->configuration[0], 16)));
TRACE(OTHER, logout("configuration: %s\n",
nic_dump(&s->configuration[16],
ARRAY_SIZE(s->configuration) - 16)));
if (s->configuration[20] & BIT(6)) {
TRACE(OTHER, logout("Multiple IA bit\n"));
}
break;
case CmdMulticastList:
set_multicast_list(s);
break;
case CmdTx:
if (bit_nc) {
missing("CmdTx: NC = 0");
ok_status = 0;
break;
}
tx_command(s);
break;
case CmdTDR:
TRACE(OTHER, logout("load microcode\n"));
/* Starting with offset 8, the command contains
* 64 dwords microcode which we just ignore here. */
break;
case CmdDiagnose:
TRACE(OTHER, logout("diagnose\n"));
/* Make sure error flag is not set. */
s->tx.status = 0;
break;
default:
missing("undefined command");
ok_status = 0;
break;
}
/* Write new status. */
stw_le_pci_dma(&s->dev, s->cb_address,
s->tx.status | ok_status | STATUS_C);
if (bit_i) {
/* CU completed action. */
<API key>(s);
}
if (bit_el) {
/* CU becomes idle. Terminate command loop. */
set_cu_state(s, cu_idle);
<API key>(s);
break;
} else if (bit_s) {
/* CU becomes suspended. Terminate command loop. */
set_cu_state(s, cu_suspended);
<API key>(s);
break;
} else {
/* More entries in list. */
TRACE(OTHER, logout("CU list with at least one more entry\n"));
}
}
TRACE(OTHER, logout("CU list empty\n"));
/* List is empty. Now CU is idle or suspended. */
}
static void eepro100_cu_command(EEPRO100State * s, uint8_t val)
{
cu_state_t cu_state;
switch (val) {
case CU_NOP:
/* No operation. */
break;
case CU_START:
cu_state = get_cu_state(s);
if (cu_state != cu_idle && cu_state != cu_suspended) {
/* Intel documentation says that CU must be idle or suspended
* for the CU start command. */
logout("unexpected CU state is %u\n", cu_state);
}
set_cu_state(s, cu_active);
s->cu_offset = e100_read_reg4(s, SCBPointer);
action_command(s);
break;
case CU_RESUME:
if (get_cu_state(s) != cu_suspended) {
logout("bad CU resume from CU state %u\n", get_cu_state(s));
/* Workaround for bad Linux eepro100 driver which resumes
* from idle state. */
#if 0
missing("cu resume");
#endif
set_cu_state(s, cu_suspended);
}
if (get_cu_state(s) == cu_suspended) {
TRACE(OTHER, logout("CU resuming\n"));
set_cu_state(s, cu_active);
action_command(s);
}
break;
case CU_STATSADDR:
/* Load dump counters address. */
s->statsaddr = e100_read_reg4(s, SCBPointer);
TRACE(OTHER, logout("val=0x%02x (dump counters address)\n", val));
if (s->statsaddr & 3) {
/* Memory must be Dword aligned. */
logout("unaligned dump counters address\n");
/* Handling of misaligned addresses is undefined.
* Here we align the address by ignoring the lower bits. */
/* TODO: Test unaligned dump counter address on real hardware. */
s->statsaddr &= ~3;
}
break;
case CU_SHOWSTATS:
/* Dump statistical counters. */
TRACE(OTHER, logout("val=0x%02x (dump stats)\n", val));
dump_statistics(s);
stl_le_pci_dma(&s->dev, s->statsaddr + s->stats_size, 0xa005);
break;
case CU_CMD_BASE:
/* Load CU base. */
TRACE(OTHER, logout("val=0x%02x (CU base address)\n", val));
s->cu_base = e100_read_reg4(s, SCBPointer);
break;
case CU_DUMPSTATS:
/* Dump and reset statistical counters. */
TRACE(OTHER, logout("val=0x%02x (dump stats and reset)\n", val));
dump_statistics(s);
stl_le_pci_dma(&s->dev, s->statsaddr + s->stats_size, 0xa007);
memset(&s->statistics, 0, sizeof(s->statistics));
break;
case CU_SRESUME:
/* CU static resume. */
missing("CU static resume");
break;
default:
missing("Undefined CU command");
}
}
static void eepro100_ru_command(EEPRO100State * s, uint8_t val)
{
switch (val) {
case RU_NOP:
/* No operation. */
break;
case RX_START:
/* RU start. */
if (get_ru_state(s) != ru_idle) {
logout("RU state is %u, should be %u\n", get_ru_state(s), ru_idle);
#if 0
assert(!"wrong RU state");
#endif
}
set_ru_state(s, ru_ready);
s->ru_offset = e100_read_reg4(s, SCBPointer);
<API key>(&s->nic->nc);
TRACE(OTHER, logout("val=0x%02x (rx start)\n", val));
break;
case RX_RESUME:
/* Restart RU. */
if (get_ru_state(s) != ru_suspended) {
logout("RU state is %u, should be %u\n", get_ru_state(s),
ru_suspended);
#if 0
assert(!"wrong RU state");
#endif
}
set_ru_state(s, ru_ready);
break;
case RU_ABORT:
/* RU abort. */
if (get_ru_state(s) == ru_ready) {
<API key>(s);
}
set_ru_state(s, ru_idle);
break;
case RX_ADDR_LOAD:
/* Load RU base. */
TRACE(OTHER, logout("val=0x%02x (RU base address)\n", val));
s->ru_base = e100_read_reg4(s, SCBPointer);
break;
default:
logout("val=0x%02x (undefined RU command)\n", val);
missing("Undefined SU command");
}
}
static void <API key>(EEPRO100State * s, uint8_t val)
{
eepro100_ru_command(s, val & 0x0f);
eepro100_cu_command(s, val & 0xf0);
if ((val) == 0) {
TRACE(OTHER, logout("val=0x%02x\n", val));
}
/* Clear command byte after command was accepted. */
s->mem[SCBCmd] = 0;
}
#define EEPROM_CS 0x02
#define EEPROM_SK 0x01
#define EEPROM_DI 0x04
#define EEPROM_DO 0x08
static uint16_t <API key>(EEPRO100State * s)
{
uint16_t val = e100_read_reg2(s, SCBeeprom);
if (eeprom93xx_read(s->eeprom)) {
val |= EEPROM_DO;
} else {
val &= ~EEPROM_DO;
}
TRACE(EEPROM, logout("val=0x%04x\n", val));
return val;
}
static void <API key>(eeprom_t * eeprom, uint8_t val)
{
TRACE(EEPROM, logout("val=0x%02x\n", val));
/* mask unwritable bits */
#if 0
val = SET_MASKED(val, 0x31, eeprom->value);
#endif
int eecs = ((val & EEPROM_CS) != 0);
int eesk = ((val & EEPROM_SK) != 0);
int eedi = ((val & EEPROM_DI) != 0);
eeprom93xx_write(eeprom, eecs, eesk, eedi);
}
#if defined(DEBUG_EEPRO100)
static const char * const mdi_op_name[] = {
"opcode 0",
"write",
"read",
"opcode 3"
};
static const char * const mdi_reg_name[] = {
"Control",
"Status",
"PHY Identification (Word 1)",
"PHY Identification (Word 2)",
"Auto-Negotiation Advertisement",
"Auto-Negotiation Link Partner Ability",
"Auto-Negotiation Expansion"
};
static const char *reg2name(uint8_t reg)
{
static char buffer[10];
const char *p = buffer;
if (reg < ARRAY_SIZE(mdi_reg_name)) {
p = mdi_reg_name[reg];
} else {
snprintf(buffer, sizeof(buffer), "reg=0x%02x", reg);
}
return p;
}
#endif /* DEBUG_EEPRO100 */
static uint32_t eepro100_read_mdi(EEPRO100State * s)
{
uint32_t val = e100_read_reg4(s, SCBCtrlMDI);
#ifdef DEBUG_EEPRO100
uint8_t raiseint = (val & BIT(29)) >> 29;
uint8_t opcode = (val & BITS(27, 26)) >> 26;
uint8_t phy = (val & BITS(25, 21)) >> 21;
uint8_t reg = (val & BITS(20, 16)) >> 16;
uint16_t data = (val & BITS(15, 0));
#endif
/* Emulation takes no time to finish MDI transaction. */
val |= BIT(28);
TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n",
val, raiseint, mdi_op_name[opcode], phy,
reg2name(reg), data));
return val;
}
static void eepro100_write_mdi(EEPRO100State *s)
{
uint32_t val = e100_read_reg4(s, SCBCtrlMDI);
uint8_t raiseint = (val & BIT(29)) >> 29;
uint8_t opcode = (val & BITS(27, 26)) >> 26;
uint8_t phy = (val & BITS(25, 21)) >> 21;
uint8_t reg = (val & BITS(20, 16)) >> 16;
uint16_t data = (val & BITS(15, 0));
TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n",
val, raiseint, mdi_op_name[opcode], phy, reg2name(reg), data));
if (phy != 1) {
/* Unsupported PHY address. */
#if 0
logout("phy must be 1 but is %u\n", phy);
#endif
data = 0;
} else if (opcode != 1 && opcode != 2) {
/* Unsupported opcode. */
logout("opcode must be 1 or 2 but is %u\n", opcode);
data = 0;
} else if (reg > 6) {
/* Unsupported register. */
logout("register must be 0...6 but is %u\n", reg);
data = 0;
} else {
TRACE(MDI, logout("val=0x%08x (int=%u, %s, phy=%u, %s, data=0x%04x\n",
val, raiseint, mdi_op_name[opcode], phy,
reg2name(reg), data));
if (opcode == 1) {
/* MDI write */
switch (reg) {
case 0: /* Control Register */
if (data & 0x8000) {
/* Reset status and control registers to default. */
s->mdimem[0] = <API key>[0];
s->mdimem[1] = <API key>[1];
data = s->mdimem[reg];
} else {
/* Restart Auto Configuration = Normal Operation */
data &= ~0x0200;
}
break;
case 1: /* Status Register */
missing("not writable");
data = s->mdimem[reg];
break;
case 2: /* PHY Identification Register (Word 1) */
case 3: /* PHY Identification Register (Word 2) */
missing("not implemented");
break;
case 4: /* Auto-Negotiation Advertisement Register */
case 5: /* Auto-Negotiation Link Partner Ability Register */
break;
case 6: /* Auto-Negotiation Expansion Register */
default:
missing("not implemented");
}
s->mdimem[reg] = data;
} else if (opcode == 2) {
/* MDI read */
switch (reg) {
case 0: /* Control Register */
if (data & 0x8000) {
/* Reset status and control registers to default. */
s->mdimem[0] = <API key>[0];
s->mdimem[1] = <API key>[1];
}
break;
case 1: /* Status Register */
s->mdimem[reg] |= 0x0020;
break;
case 2: /* PHY Identification Register (Word 1) */
case 3: /* PHY Identification Register (Word 2) */
case 4: /* Auto-Negotiation Advertisement Register */
break;
case 5: /* Auto-Negotiation Link Partner Ability Register */
s->mdimem[reg] = 0x41fe;
break;
case 6: /* Auto-Negotiation Expansion Register */
s->mdimem[reg] = 0x0001;
break;
}
data = s->mdimem[reg];
}
/* Emulation takes no time to finish MDI transaction.
* Set MDI bit in SCB status register. */
s->mem[SCBAck] |= 0x08;
val |= BIT(28);
if (raiseint) {
<API key>(s);
}
}
val = (val & 0xffff0000) + data;
e100_write_reg4(s, SCBCtrlMDI, val);
}
#define PORT_SOFTWARE_RESET 0
#define PORT_SELFTEST 1
#define <API key> 2
#define PORT_DUMP 3
#define PORT_SELECTION_MASK 3
typedef struct {
uint32_t st_sign; /* Self Test Signature */
uint32_t st_result; /* Self Test Results */
} eepro100_selftest_t;
static uint32_t eepro100_read_port(EEPRO100State * s)
{
return 0;
}
static void eepro100_write_port(EEPRO100State *s)
{
uint32_t val = e100_read_reg4(s, SCBPort);
uint32_t address = (val & ~PORT_SELECTION_MASK);
uint8_t selection = (val & PORT_SELECTION_MASK);
switch (selection) {
case PORT_SOFTWARE_RESET:
nic_reset(s);
break;
case PORT_SELFTEST:
TRACE(OTHER, logout("selftest address=0x%08x\n", address));
eepro100_selftest_t data;
pci_dma_read(&s->dev, address, (uint8_t *) &data, sizeof(data));
data.st_sign = 0xffffffff;
data.st_result = 0;
pci_dma_write(&s->dev, address, (uint8_t *) &data, sizeof(data));
break;
case <API key>:
TRACE(OTHER, logout("selective reset, selftest address=0x%08x\n", address));
nic_selective_reset(s);
break;
default:
logout("val=0x%08x\n", val);
missing("unknown port selection");
}
}
static uint8_t eepro100_read1(EEPRO100State * s, uint32_t addr)
{
uint8_t val = 0;
if (addr <= sizeof(s->mem) - sizeof(val)) {
val = s->mem[addr];
}
switch (addr) {
case SCBStatus:
case SCBAck:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBCmd:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
#if 0
val = <API key>(s);
#endif
break;
case SCBIntmask:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBPort + 3:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBeeprom:
val = <API key>(s);
break;
case SCBCtrlMDI:
case SCBCtrlMDI + 1:
case SCBCtrlMDI + 2:
case SCBCtrlMDI + 3:
val = (uint8_t)(eepro100_read_mdi(s) >> (8 * (addr & 3)));
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBpmdr: /* Power Management Driver Register */
val = 0;
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBgctrl: /* General Control Register */
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBgstat: /* General Status Register */
/* 100 Mbps full duplex, valid link */
val = 0x07;
TRACE(OTHER, logout("addr=General Status val=%02x\n", val));
break;
default:
logout("addr=%s val=0x%02x\n", regname(addr), val);
missing("unknown byte read");
}
return val;
}
static uint16_t eepro100_read2(EEPRO100State * s, uint32_t addr)
{
uint16_t val = 0;
if (addr <= sizeof(s->mem) - sizeof(val)) {
val = e100_read_reg2(s, addr);
}
switch (addr) {
case SCBStatus:
case SCBCmd:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
case SCBeeprom:
val = <API key>(s);
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
case SCBCtrlMDI:
case SCBCtrlMDI + 2:
val = (uint16_t)(eepro100_read_mdi(s) >> (8 * (addr & 3)));
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
default:
logout("addr=%s val=0x%04x\n", regname(addr), val);
missing("unknown word read");
}
return val;
}
static uint32_t eepro100_read4(EEPRO100State * s, uint32_t addr)
{
uint32_t val = 0;
if (addr <= sizeof(s->mem) - sizeof(val)) {
val = e100_read_reg4(s, addr);
}
switch (addr) {
case SCBStatus:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
break;
case SCBPointer:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
break;
case SCBPort:
val = eepro100_read_port(s);
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
break;
case SCBflash:
val = <API key>(s);
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
break;
case SCBCtrlMDI:
val = eepro100_read_mdi(s);
break;
default:
logout("addr=%s val=0x%08x\n", regname(addr), val);
missing("unknown longword read");
}
return val;
}
static void eepro100_write1(EEPRO100State * s, uint32_t addr, uint8_t val)
{
/* SCBStatus is readonly. */
if (addr > SCBStatus && addr <= sizeof(s->mem) - sizeof(val)) {
s->mem[addr] = val;
}
switch (addr) {
case SCBStatus:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBAck:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
<API key>(s);
break;
case SCBCmd:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
<API key>(s, val);
break;
case SCBIntmask:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
if (val & BIT(1)) {
<API key>(s);
}
eepro100_interrupt(s, 0);
break;
case SCBPointer:
case SCBPointer + 1:
case SCBPointer + 2:
case SCBPointer + 3:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBPort:
case SCBPort + 1:
case SCBPort + 2:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBPort + 3:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
eepro100_write_port(s);
break;
case SCBFlow: /* does not exist on 82557 */
case SCBFlow + 1:
case SCBFlow + 2:
case SCBpmdr: /* does not exist on 82557 */
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBeeprom:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
<API key>(s->eeprom, val);
break;
case SCBCtrlMDI:
case SCBCtrlMDI + 1:
case SCBCtrlMDI + 2:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
break;
case SCBCtrlMDI + 3:
TRACE(OTHER, logout("addr=%s val=0x%02x\n", regname(addr), val));
eepro100_write_mdi(s);
break;
default:
logout("addr=%s val=0x%02x\n", regname(addr), val);
missing("unknown byte write");
}
}
static void eepro100_write2(EEPRO100State * s, uint32_t addr, uint16_t val)
{
/* SCBStatus is readonly. */
if (addr > SCBStatus && addr <= sizeof(s->mem) - sizeof(val)) {
e100_write_reg2(s, addr, val);
}
switch (addr) {
case SCBStatus:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
s->mem[SCBAck] = (val >> 8);
<API key>(s);
break;
case SCBCmd:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
<API key>(s, val);
eepro100_write1(s, SCBIntmask, val >> 8);
break;
case SCBPointer:
case SCBPointer + 2:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
case SCBPort:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
case SCBPort + 2:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
eepro100_write_port(s);
break;
case SCBeeprom:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
<API key>(s->eeprom, val);
break;
case SCBCtrlMDI:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
break;
case SCBCtrlMDI + 2:
TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));
eepro100_write_mdi(s);
break;
default:
logout("addr=%s val=0x%04x\n", regname(addr), val);
missing("unknown word write");
}
}
static void eepro100_write4(EEPRO100State * s, uint32_t addr, uint32_t val)
{
if (addr <= sizeof(s->mem) - sizeof(val)) {
e100_write_reg4(s, addr, val);
}
switch (addr) {
case SCBPointer:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
break;
case SCBPort:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
eepro100_write_port(s);
break;
case SCBflash:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
val = val >> 16;
<API key>(s->eeprom, val);
break;
case SCBCtrlMDI:
TRACE(OTHER, logout("addr=%s val=0x%08x\n", regname(addr), val));
eepro100_write_mdi(s);
break;
default:
logout("addr=%s val=0x%08x\n", regname(addr), val);
missing("unknown longword write");
}
}
static uint64_t eepro100_read(void *opaque, hwaddr addr,
unsigned size)
{
EEPRO100State *s = opaque;
switch (size) {
case 1: return eepro100_read1(s, addr);
case 2: return eepro100_read2(s, addr);
case 4: return eepro100_read4(s, addr);
default: abort();
}
}
static void eepro100_write(void *opaque, hwaddr addr,
uint64_t data, unsigned size)
{
EEPRO100State *s = opaque;
switch (size) {
case 1:
eepro100_write1(s, addr, data);
break;
case 2:
eepro100_write2(s, addr, data);
break;
case 4:
eepro100_write4(s, addr, data);
break;
default:
abort();
}
}
static const MemoryRegionOps eepro100_ops = {
.read = eepro100_read,
.write = eepro100_write,
.endianness = <API key>,
};
static int nic_can_receive(NetClientState *nc)
{
EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque;
TRACE(RXTX, logout("%p\n", s));
return get_ru_state(s) == ru_ready;
#if 0
return !<API key>(s);
#endif
}
static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size)
{
/* TODO:
* - Magic packets should set bit 30 in power management driver register.
* - Interesting packets should set bit 29 in power management driver register.
*/
EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque;
uint16_t rfd_status = 0xa000;
#if defined(<API key>)
uint8_t min_buf[60];
#endif
static const uint8_t broadcast_macaddr[6] =
{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
#if defined(<API key>)
/* Pad to minimum Ethernet frame length */
if (size < sizeof(min_buf)) {
memcpy(min_buf, buf, size);
memset(&min_buf[size], 0, sizeof(min_buf) - size);
buf = min_buf;
size = sizeof(min_buf);
}
#endif
if (s->configuration[8] & 0x80) {
/* CSMA is disabled. */
logout("%p received while CSMA is disabled\n", s);
return -1;
#if !defined(<API key>)
} else if (size < 64 && (s->configuration[7] & BIT(0))) {
/* Short frame and configuration byte 7/0 (discard short receive) set:
* Short frame is discarded */
logout("%p received short frame (%zu byte)\n", s, size);
s->statistics.<API key>++;
return -1;
#endif
} else if ((size > MAX_ETH_FRAME_SIZE + 4) && !(s->configuration[18] & BIT(3))) {
/* Long frame and configuration byte 18/3 (long receive ok) not set:
* Long frames are discarded. */
logout("%p received long frame (%zu byte), ignored\n", s, size);
return -1;
} else if (memcmp(buf, s->conf.macaddr.a, 6) == 0) {
/* Frame matches individual address. */
/* TODO: check configuration byte 15/4 (ignore U/L). */
TRACE(RXTX, logout("%p received frame for me, len=%zu\n", s, size));
} else if (memcmp(buf, broadcast_macaddr, 6) == 0) {
/* Broadcast frame. */
TRACE(RXTX, logout("%p received broadcast, len=%zu\n", s, size));
rfd_status |= 0x0002;
} else if (buf[0] & 0x01) {
/* Multicast frame. */
TRACE(RXTX, logout("%p received multicast, len=%zu,%s\n", s, size, nic_dump(buf, size)));
if (s->configuration[21] & BIT(3)) {
/* Multicast all bit is set, receive all multicast frames. */
} else {
unsigned mcast_idx = <API key>(buf);
assert(mcast_idx < 64);
if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) {
/* Multicast frame is allowed in hash table. */
} else if (s->configuration[15] & BIT(0)) {
/* Promiscuous: receive all. */
rfd_status |= 0x0004;
} else {
TRACE(RXTX, logout("%p multicast ignored\n", s));
return -1;
}
}
/* TODO: Next not for promiscuous mode? */
rfd_status |= 0x0002;
} else if (s->configuration[15] & BIT(0)) {
/* Promiscuous: receive all. */
TRACE(RXTX, logout("%p received frame in promiscuous mode, len=%zu\n", s, size));
rfd_status |= 0x0004;
} else if (s->configuration[20] & BIT(6)) {
/* Multiple IA bit set. */
unsigned mcast_idx = compute_mcast_idx(buf);
assert(mcast_idx < 64);
if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) {
TRACE(RXTX, logout("%p accepted, multiple IA bit set\n", s));
} else {
TRACE(RXTX, logout("%p frame ignored, multiple IA bit set\n", s));
return -1;
}
} else {
TRACE(RXTX, logout("%p received frame, ignored, len=%zu,%s\n", s, size,
nic_dump(buf, size)));
return size;
}
if (get_ru_state(s) != ru_ready) {
/* No resources available. */
logout("no resources, state=%u\n", get_ru_state(s));
/* TODO: RNR interrupt only at first failed frame? */
<API key>(s);
s->statistics.rx_resource_errors++;
#if 0
assert(!"no resources");
#endif
return -1;
}
eepro100_rx_t rx;
pci_dma_read(&s->dev, s->ru_base + s->ru_offset,
&rx, sizeof(eepro100_rx_t));
uint16_t rfd_command = le16_to_cpu(rx.command);
uint16_t rfd_size = le16_to_cpu(rx.size);
if (size > rfd_size) {
logout("Receive buffer (%" PRId16 " bytes) too small for data "
"(%zu bytes); data truncated\n", rfd_size, size);
size = rfd_size;
}
#if !defined(<API key>)
if (size < 64) {
rfd_status |= 0x0080;
}
#endif
TRACE(OTHER, logout("command 0x%04x, link 0x%08x, addr 0x%08x, size %u\n",
rfd_command, rx.link, rx.rx_buf_addr, rfd_size));
stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset +
offsetof(eepro100_rx_t, status), rfd_status);
stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset +
offsetof(eepro100_rx_t, count), size);
/* Early receive interrupt not supported. */
#if 0
<API key>(s);
#endif
/* Receive CRC Transfer not supported. */
if (s->configuration[18] & BIT(2)) {
missing("Receive CRC Transfer");
return -1;
}
/* TODO: check stripping enable bit. */
#if 0
assert(!(s->configuration[17] & BIT(0)));
#endif
pci_dma_write(&s->dev, s->ru_base + s->ru_offset +
sizeof(eepro100_rx_t), buf, size);
s->statistics.rx_good_frames++;
<API key>(s);
s->ru_offset = le32_to_cpu(rx.link);
if (rfd_command & COMMAND_EL) {
/* EL bit is set, so this was the last frame. */
logout("receive: Running out of frames\n");
set_ru_state(s, ru_no_resources);
<API key>(s);
}
if (rfd_command & COMMAND_S) {
/* S bit is set. */
set_ru_state(s, ru_suspended);
}
return size;
}
static const VMStateDescription vmstate_eepro100 = {
.version_id = 3,
.minimum_version_id = 2,
.<API key> = 2,
.fields = (VMStateField []) {
VMSTATE_PCI_DEVICE(dev, EEPRO100State),
VMSTATE_UNUSED(32),
VMSTATE_BUFFER(mult, EEPRO100State),
VMSTATE_BUFFER(mem, EEPRO100State),
/* Save all members of struct between scb_stat and mem. */
VMSTATE_UINT8(scb_stat, EEPRO100State),
VMSTATE_UINT8(int_stat, EEPRO100State),
VMSTATE_UNUSED(3*4),
VMSTATE_MACADDR(conf.macaddr, EEPRO100State),
VMSTATE_UNUSED(19*4),
<API key>(mdimem, EEPRO100State, 32),
/* The eeprom should be saved and restored by its own routines. */
VMSTATE_UINT32(device, EEPRO100State),
/* TODO check device. */
VMSTATE_UINT32(cu_base, EEPRO100State),
VMSTATE_UINT32(cu_offset, EEPRO100State),
VMSTATE_UINT32(ru_base, EEPRO100State),
VMSTATE_UINT32(ru_offset, EEPRO100State),
VMSTATE_UINT32(statsaddr, EEPRO100State),
/* Save eepro100_stats_t statistics. */
VMSTATE_UINT32(statistics.tx_good_frames, EEPRO100State),
VMSTATE_UINT32(statistics.tx_max_collisions, EEPRO100State),
VMSTATE_UINT32(statistics.tx_late_collisions, EEPRO100State),
VMSTATE_UINT32(statistics.tx_underruns, EEPRO100State),
VMSTATE_UINT32(statistics.tx_lost_crs, EEPRO100State),
VMSTATE_UINT32(statistics.tx_deferred, EEPRO100State),
VMSTATE_UINT32(statistics.<API key>, EEPRO100State),
VMSTATE_UINT32(statistics.<API key>, EEPRO100State),
VMSTATE_UINT32(statistics.tx_total_collisions, EEPRO100State),
VMSTATE_UINT32(statistics.rx_good_frames, EEPRO100State),
VMSTATE_UINT32(statistics.rx_crc_errors, EEPRO100State),
VMSTATE_UINT32(statistics.rx_alignment_errors, EEPRO100State),
VMSTATE_UINT32(statistics.rx_resource_errors, EEPRO100State),
VMSTATE_UINT32(statistics.rx_overrun_errors, EEPRO100State),
VMSTATE_UINT32(statistics.rx_cdt_errors, EEPRO100State),
VMSTATE_UINT32(statistics.<API key>, EEPRO100State),
VMSTATE_UINT32(statistics.fc_xmt_pause, EEPRO100State),
VMSTATE_UINT32(statistics.fc_rcv_pause, EEPRO100State),
VMSTATE_UINT32(statistics.fc_rcv_unsupported, EEPRO100State),
VMSTATE_UINT16(statistics.xmt_tco_frames, EEPRO100State),
VMSTATE_UINT16(statistics.rcv_tco_frames, EEPRO100State),
/* Configuration bytes. */
VMSTATE_BUFFER(configuration, EEPRO100State),
VMSTATE_END_OF_LIST()
}
};
static void nic_cleanup(NetClientState *nc)
{
EEPRO100State *s = DO_UPCAST(NICState, nc, nc)->opaque;
s->nic = NULL;
}
static void pci_nic_uninit(PCIDevice *pci_dev)
{
EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev);
<API key>(&s->mmio_bar);
<API key>(&s->io_bar);
<API key>(&s->flash_bar);
vmstate_unregister(&pci_dev->qdev, s->vmstate, s);
eeprom93xx_free(&pci_dev->qdev, s->eeprom);
qemu_del_net_client(&s->nic->nc);
}
static NetClientInfo net_eepro100_info = {
.type = <API key>,
.size = sizeof(NICState),
.can_receive = nic_can_receive,
.receive = nic_receive,
.cleanup = nic_cleanup,
};
static int e100_nic_init(PCIDevice *pci_dev)
{
EEPRO100State *s = DO_UPCAST(EEPRO100State, dev, pci_dev);
E100PCIDeviceInfo *info = eepro100_get_class(s);
TRACE(OTHER, logout("\n"));
s->device = info->device;
e100_pci_reset(s);
/* Add 64 * 2 EEPROM. i82557 and i82558 support a 64 word EEPROM,
* i82559 and later support 64 or 256 word EEPROM. */
s->eeprom = eeprom93xx_new(&pci_dev->qdev, EEPROM_SIZE);
/* Handler for memory-mapped I/O */
<API key>(&s->mmio_bar, &eepro100_ops, s, "eepro100-mmio",
PCI_MEM_SIZE);
pci_register_bar(&s->dev, 0, <API key>, &s->mmio_bar);
<API key>(&s->io_bar, &eepro100_ops, s, "eepro100-io",
PCI_IO_SIZE);
pci_register_bar(&s->dev, 1, <API key>, &s->io_bar);
/* FIXME: flash aliases to mmio?! */
<API key>(&s->flash_bar, &eepro100_ops, s, "eepro100-flash",
PCI_FLASH_SIZE);
pci_register_bar(&s->dev, 2, 0, &s->flash_bar);
<API key>(&s->conf.macaddr);
logout("macaddr: %s\n", nic_dump(&s->conf.macaddr.a[0], 6));
nic_reset(s);
s->nic = qemu_new_nic(&net_eepro100_info, &s->conf,
object_get_typename(OBJECT(pci_dev)), pci_dev->qdev.id, s);
<API key>(&s->nic->nc, s->conf.macaddr.a);
TRACE(OTHER, logout("%s\n", s->nic->nc.info_str));
qemu_register_reset(nic_reset, s);
s->vmstate = g_malloc(sizeof(vmstate_eepro100));
memcpy(s->vmstate, &vmstate_eepro100, sizeof(vmstate_eepro100));
s->vmstate->name = s->nic->nc.model;
vmstate_register(&pci_dev->qdev, -1, s->vmstate, s);
<API key>(s->conf.bootindex, &pci_dev->qdev, "/ethernet-phy@0");
return 0;
}
static E100PCIDeviceInfo e100_devices[] = {
{
.name = "i82550",
.desc = "Intel i82550 Ethernet",
.device = i82550,
/* TODO: check device id. */
.device_id = <API key>,
/* Revision ID: 0x0c, 0x0d, 0x0e. */
.revision = 0x0e,
/* TODO: check size of statistical counters. */
.stats_size = 80,
/* TODO: check extended tcb support. */
.<API key> = true,
.power_management = true,
},{
.name = "i82551",
.desc = "Intel i82551 Ethernet",
.device = i82551,
.device_id = <API key>,
/* Revision ID: 0x0f, 0x10. */
.revision = 0x0f,
/* TODO: check size of statistical counters. */
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
.name = "i82557a",
.desc = "Intel i82557A Ethernet",
.device = i82557A,
.device_id = <API key>,
.revision = 0x01,
.power_management = false,
},{
.name = "i82557b",
.desc = "Intel i82557B Ethernet",
.device = i82557B,
.device_id = <API key>,
.revision = 0x02,
.power_management = false,
},{
.name = "i82557c",
.desc = "Intel i82557C Ethernet",
.device = i82557C,
.device_id = <API key>,
.revision = 0x03,
.power_management = false,
},{
.name = "i82558a",
.desc = "Intel i82558A Ethernet",
.device = i82558A,
.device_id = <API key>,
.revision = 0x04,
.stats_size = 76,
.<API key> = true,
.power_management = true,
},{
.name = "i82558b",
.desc = "Intel i82558B Ethernet",
.device = i82558B,
.device_id = <API key>,
.revision = 0x05,
.stats_size = 76,
.<API key> = true,
.power_management = true,
},{
.name = "i82559a",
.desc = "Intel i82559A Ethernet",
.device = i82559A,
.device_id = <API key>,
.revision = 0x06,
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
.name = "i82559b",
.desc = "Intel i82559B Ethernet",
.device = i82559B,
.device_id = <API key>,
.revision = 0x07,
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
.name = "i82559c",
.desc = "Intel i82559C Ethernet",
.device = i82559C,
.device_id = <API key>,
#if 0
.revision = 0x08,
#endif
/* TODO: Windows wants revision id 0x0c. */
.revision = 0x0c,
#if EEPROM_SIZE > 0
.subsystem_vendor_id = PCI_VENDOR_ID_INTEL,
.subsystem_id = 0x0040,
#endif
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
.name = "i82559er",
.desc = "Intel i82559ER Ethernet",
.device = i82559ER,
.device_id = <API key>,
.revision = 0x09,
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
.name = "i82562",
.desc = "Intel i82562 Ethernet",
.device = i82562,
/* TODO: check device id. */
.device_id = <API key>,
/* TODO: wrong revision id. */
.revision = 0x0e,
.stats_size = 80,
.<API key> = true,
.power_management = true,
},{
/* Toshiba Tecra 8200. */
.name = "i82801",
.desc = "Intel i82801 Ethernet",
.device = i82801,
.device_id = 0x2449,
.revision = 0x03,
.stats_size = 80,
.<API key> = true,
.power_management = true,
}
};
static E100PCIDeviceInfo *<API key>(const char *typename)
{
E100PCIDeviceInfo *info = NULL;
int i;
/* This is admittedly awkward but also temporary. QOM allows for
* parameterized typing and for subclassing both of which would suitable
* handle what's going on here. But class_data is already being used as
* a stop-gap hack to allow incremental qdev conversion so we cannot use it
* right now. Once we merge the final QOM series, we can come back here and
* do this in a much more elegant fashion.
*/
for (i = 0; i < ARRAY_SIZE(e100_devices); i++) {
if (strcmp(e100_devices[i].name, typename) == 0) {
info = &e100_devices[i];
break;
}
}
assert(info != NULL);
return info;
}
static E100PCIDeviceInfo *eepro100_get_class(EEPRO100State *s)
{
return <API key>(object_get_typename(OBJECT(s)));
}
static Property e100_properties[] = {
<API key>(EEPRO100State, conf),
<API key>(),
};
static void eepro100_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
E100PCIDeviceInfo *info;
info = <API key>(<API key>(klass));
dc->props = e100_properties;
dc->desc = info->desc;
k->vendor_id = PCI_VENDOR_ID_INTEL;
k->class_id = <API key>;
k->romfile = "pxe-eepro100.rom";
k->init = e100_nic_init;
k->exit = pci_nic_uninit;
k->device_id = info->device_id;
k->revision = info->revision;
k->subsystem_vendor_id = info->subsystem_vendor_id;
k->subsystem_id = info->subsystem_id;
}
static void <API key>(void)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(e100_devices); i++) {
TypeInfo type_info = {};
E100PCIDeviceInfo *info = &e100_devices[i];
type_info.name = info->name;
type_info.parent = TYPE_PCI_DEVICE;
type_info.class_init = eepro100_class_init;
type_info.instance_size = sizeof(EEPRO100State);
type_register(&type_info);
}
}
type_init(<API key>)
|
#ifndef <API key>
#define <API key>
#include <wx/event.h>
#include <wx/treebase.h>
#include "<API key>.h"
class wxString;
class wxWindow;
class wxPanel;
class wxTreeCtrl;
class wxTreeEvent;
class ThreadSearch;
class ThreadSearchView;
class ThreadSearchEvent;
// MessageLog inheritance is necessary to be able to
// add logger to Messages notebook.
class <API key> : public wxEvtHandler, public <API key>
{
public:
/** Constructor. */
<API key>(ThreadSearchView& threadSearchView, ThreadSearch& threadSearchPlugin,
InsertIndexManager::eFileSorting fileSorting, wxPanel* pParent, long id);
/** Destructor. */
virtual ~<API key>();
/** Getter */
virtual eLoggerTypes GetLoggerType() {return TypeTree;}
/** Called by ThreadSearchView to process a ThreadSearchEvent
* sent by worker thread.
*/
virtual void OnThreadSearchEvent(const ThreadSearchEvent& event);
/** Removes all items from logger. */
virtual void Clear();
/** Called on search begin to prepare logger. */
virtual void OnSearchBegin(const <API key>& findData);
/** Returns the logger window. */
virtual wxWindow* GetWindow();
/** Sets focus on list window. */
virtual void SetFocus();
/** Single click event handler */
void OnLoggerTreeClick(wxTreeEvent& event);
/** Double click event handler */
void <API key>(wxTreeEvent& event);
protected:
/** <API key>
* Return the file path at index from the list control using dir and file columns.
* @param event : list control event
* @param filepath : reference that will receive the path
* @param line : reference that will receive the line index
* @return true if successful.
*/
bool <API key>(wxTreeEvent& event, wxString& filepath, long &line);
/** <API key>
* @return Return true if a result line can be found for tree item
*/
bool <API key>(wxTreeItemId treeItemId);
/** Dynamic events connection. */
virtual void ConnectEvents(wxEvtHandler* pEvtHandler);
/** Dynamic events disconnection. */
virtual void DisconnectEvents(wxEvtHandler* pEvtHandler);
/** Contextual menu event handler */
void <API key>(wxTreeEvent& event);
/** Delete item menu event handler */
void OnDeleteTreeItem(wxCommandEvent& event);
/** Delete item menu event handler */
void <API key>(wxCommandEvent& event);
/** Deletes an item from the tree */
void DeleteTreeItem(wxTreeItemId id);
/** Deletes all items from the tree */
void DeleteTreeItems();
wxTreeCtrl* m_pTreeLog;
bool <API key>; // Used to filter wxTree events and process useful ones only.
wxTreeItemId m_FilesParentId;
wxTreeItemId m_ToDeleteItemId;
};
#endif // <API key>
|
UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Assassin - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 0;
UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Chronomancer - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 1;
UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Vanquisher - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 1;
UPDATE `smart_scripts` SET `action_type` = 69, `action_param1` = 1, `action_param4` = 10, `target_type` = 19, `target_param1` = 15608, `target_param2` = 200, `comment` = "Infinite Whelp - Out of Combat - Move To Closest Creature 'Medivh'" WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 0;
UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Assassin - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 13;
UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Chronomancer - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 32;
UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Vanquisher - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 18;
UPDATE `smart_scripts` SET `event_type` = 34, `event_param1` = 8, `event_param2` = 1, `comment` = "Infinite Whelp - On Movement Inform - Cast 'Corrupt Medivh'" WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 2;
DELETE FROM `smart_scripts` WHERE `entryorguid` = 17835 AND `source_type` = 0 AND `id` = 14;
DELETE FROM `smart_scripts` WHERE `entryorguid` = 17892 AND `source_type` = 0 AND `id` = 33;
DELETE FROM `smart_scripts` WHERE `entryorguid` = 18995 AND `source_type` = 0 AND `id` = 19;
DELETE FROM `smart_scripts` WHERE `entryorguid` = 21818 AND `source_type` = 0 AND `id` = 3;
INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`event_param5`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_param4`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES
(17835,0,14,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Assassin - On Movement Inform - Set Home Position"),
(17892,0,33,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Chronomancer - On Movement Inform - Set Home Position"),
(18995,0,19,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Vanquisher - On Movement Inform - Set Home Position"),
(21818,0,3,0,34,0,100,7,8,1,0,0,0,101,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,"Infinite Whelp - On Movement Inform - Set Home Position");
DELETE FROM `smart_scripts` WHERE `entryorguid`=18994 AND `source_type`=0 AND `id` IN (6,7,8);
INSERT INTO `smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `event_param5`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_param4`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES
(18994, 0, 6, 0, 1, 0, 100, 7, 1000, 1000, 0, 0, 0, 69, 1, 0, 0, 10, 0, 0, 19, 15608, 200, 0, 0, 0, 0, 0, 0, "Infinite Executioner - Out of Combat - Move To Closest Creature 'Medivh'"),
(18994, 0, 7, 0, 34, 0, 100, 7, 8, 1, 0, 0, 0, 11, 31326, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, "Infinite Executioner - On Movement Inform - Cast 'Corrupt Medivh'"),
(18994, 0, 8, 0, 34, 0, 100, 7, 8, 1, 0, 0, 0, 101, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, "Infinite Executioner - On Movement Inform - Set Home Position");
|
--TEST
PHPT skip condition results in correct code location hint
--FILE
<?php declare(strict_types=1);
print "Nothing to see here, move along";
--SKIPIF
<?php declare(strict_types=1);
print "skip: something terrible happened\n";
--EXPECT
Nothing to see here, move along
|
if (typeof process !== "undefined") {
require("amd-loader");
require("../../test/setup_paths");
}
define(function(require, exports, module) {
var assert = require("assert");
var report = require("./linereport_base");
module.exports = {
"test parse line" : function(next) {
var results = report.parseOutput("1:2: 3");
console.log(results[0]);
assert.equal(results[0].pos.sl, 0);
assert.equal(results[0].pos.sc, 1);
assert.equal(results[0].message, "3");
next();
},
"test parse two lines" : function(next) {
var results = report.parseOutput("1:1: line 1\n1:2: line 2");
assert.equal(results.length, 2);
next();
},
"test ignore lines" : function(next) {
var results = report.parseOutput("1:1: line 1\n1:2: line 2\bmove zig");
assert.equal(results.length, 2);
next();
}
};
});
if (typeof module !== "undefined" && module === require.main) {
require("asyncjs").test.testcase(module.exports).exec();
}
|
package info.ephyra.answerselection.filters;
import info.ephyra.io.Logger;
import info.ephyra.io.MsgPrinter;
import info.ephyra.nlp.NETagger;
import info.ephyra.nlp.OpenNLP;
import info.ephyra.nlp.SnowballStemmer;
import info.ephyra.nlp.StanfordNeTagger;
import info.ephyra.nlp.indices.WordFrequencies;
import info.ephyra.querygeneration.Query;
import info.ephyra.querygeneration.generators.BagOfWordsG;
import info.ephyra.questionanalysis.AnalyzedQuestion;
import info.ephyra.questionanalysis.KeywordExtractor;
import info.ephyra.questionanalysis.QuestionNormalizer;
import info.ephyra.search.Result;
import info.ephyra.trec.TREC13To16Parser;
import info.ephyra.trec.TRECTarget;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
/**
* <p>A web reinforcement approach that ranks answer candidates for definitional
* questions. Several variations of the target of the question are generated and
* are used to retrieve relevant text snippets from the web. The frequencies of
* content words in these snippets are counted and the scores of the answers are
* adjusted to assign higher scores to candidates that cover frequent keywords.
* This approach is based on the assumption that terms that often cooccur with
* the target provide relevant information on the target that should be covered
* by the answers.</p>
*
* <p>Several instances of this web term importance filter have been implemented
* that use different sources for text snippets.</p>
*
* <p>This class extends the class <code>Filter</code>.</p>
*
* @author Guido Sautter
* @version 2008-02-15
*/
public abstract class <API key> extends Filter {
protected static final String person = "person";
protected static final String organization = "organization";
protected static final String location = "location";
protected static final String event = "event";
public static final int NO_NORMALIZATION = 0;
public static final int <API key> = 1;
public static final int <API key> = 2;
public static final int <API key> = 3;
public static final int <API key> = 4;
private final int normalizationMode;
private final int tfNormalizationMode;
private final boolean isCombined;
// protected static final String WIKIPEDIA = "wikipedia";
protected <API key>(int normalizationMode, int tfNormalizationMode, boolean isCombined) {
this.normalizationMode = normalizationMode;
this.tfNormalizationMode = tfNormalizationMode;
this.isCombined = isCombined;
}
/**
* fetch the term frequencies in the top X result snippets of a web search
* for some target
*
* @param targets an array of strings containing the targets
* @return a HashMap mapping the terms in the web serach results to their
* frequency in the snippets
*/
public abstract HashMap<String, TermCounter> getTermCounters(String[] targets);
/**
* @author sautter
*
* Mutable integer class to avoid creating new objects all the time
*/
protected class TermCounter {
private int value = 0;
/** Constructor
*/
protected TermCounter() {}
/**
* Constructor
* @param value the initial value
*/
protected TermCounter(int value) {
this.value = value;
}
/** @return the value of this TermCounter
*/
public int getValue() {
return this.value;
}
/** increment the value of this TermCounter by 1
*/
public void increment() {
this.value++;
}
/** increment the value of this TermCounter by <code>inc</code>
* @param inc
*/
public void increment(int inc) {
this.value += inc;
}
/** decrement the value of this TermCounter by 1
*/
public void decrement() {
this.value
}
/** decrement the value of this TermCounter by <code>dec</code>
* @param dec
*/
public void decrement(int dec) {
this.value -= dec;
}
/** multiply the value of this TermCounter times <code>fact</code>
* @param fact
*/
public void multiplyValue(int fact) {
this.value *= fact;
}
/** devide the value of this TermCounter times <code>denom</code>
* @param denom
*/
public void divideValue(int denom) {
this.value /= denom;
}
}
/**
* produce the target variations for a given target
*
* @param target the original traget String
* @return an array of strings containing the variations of the target
* String, including the original target
*/
public String[] getTargets(String target) {
ArrayList<String> targets = new ArrayList<String>();
targets.add(target);
boolean isPerson = false;
boolean brackets = false;
// If target starts with "the", "a", or "an", remove it.
if (target.startsWith("the ")) {
targets.add(target.substring(4, target.length()));
} else if (target.startsWith("an ")) {
targets.add(target.substring(3, target.length()));
} else if (target.startsWith("a ")) {
targets.add(target.substring(2, target.length()));
}
String targetType = this.checkType(target);
if (<API key>) {
if (targetType == null) System.out.println(" target type could not be determined");
else System.out.println(" target type is " + targetType);
}
if (person.equals(targetType)) {
// (complete) target is of type Person, no further processing is necessary
isPerson = true;
// split parts in brackets from parts not in brackets:
// "Norwegian Cruise Lines (NCL)" --> "Norwegian Cruise Lines" + "NCL"
} else if (target.contains("(") && target.contains(")")) {
int i1 = target.indexOf("(");
int i2 = target.indexOf(")");
String s1 = target.substring(0, i1 - 1);
String s2 = target.substring(i1 + 1, i2);
targets.clear();
targets.add(s1);
targets.add(s2);
// Log.println(" "+target+" contains brackest. No further processing
// necessary.", true);
brackets = true;
} else if (this.cutExtension(target, targets)) {
// do nothing, it's in the cutExtensions method
} else if (target.endsWith("University")) {
// chop off "University"
String toAdd = target.substring(0, target.length() - 11);
targets.add(toAdd);
} else if (target.endsWith("International")) {
// chop off International"
String toAdd = target.substring(0, target.length() - 14);
targets.add(toAdd);
} else if (target.endsWith("Corporation")) {
// chop off "Corporation"
String toAdd = target.substring(0, target.length() - 12);
targets.add(toAdd);
} else {
this.<API key>(targets);
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String item = iter.next();
String type = this.checkType(item);
if (person.equals(type)) {
// after removing the first NP, check again if target is
// Person (example: "philanthropist Alberto Vilar")
// Log.println(" "+item+" is Person. No further processing
// necessary.", true);
// attention, this also discarts events containing person names!!!
// maybe remove this call
//targets.clear();
targets.add(item);
}
}
}
if (isPerson) {
targets.add("\"" + target + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(target + " " + WIKIPEDIA);
// targets.add("\"" + target + "\" " + WIKIPEDIA);
} else if (!brackets) { // maybe remove condition
//targets = this.processLongTargets(targets);
this.<API key>(targets);
//targets = this.checkForEvent(targets);
// described effect done in <API key>(), uses NLP stuff we don't have
//targets = this.checkForDeterminer(targets);
// bad thing, uses to many miraculous external classen we don't have
//targets = this.removeAttachedPP(targets);
// done in <API key>()
//targets = this.<API key>(targets);
this.<API key>(targets);
//targets = this.<API key>(targets);
// done in <API key>()
// own extension: extract acronyms 'Basque ETA' --> 'ETA'
this.extractAcronyms(targets);
//targets = this.postProcess(targets);
this.postProcess(targets);
}
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String item = iter.next();
String type = this.checkType(item);
if (organization.equals(type)/* && !brackets*/) {
targets.add("the " + item);
if (!brackets)
targets.add("the " + target);
} else if (person.equals(type)) {
targets.add("\"" + item + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(item + " " + WIKIPEDIA);
// targets.add("\"" + item + "\" " + WIKIPEDIA);
}
// own extension: add determiner to acronyms
if (item.matches("([A-Z]){3,}"))
targets.add("the " + item);
else if (item.matches("([A-Z]\\.){2,}"))
targets.add("the " + item);
}
// own extension: add quoted version of title case targets like 'The Daily Show'
<API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String item = iter.next();
if (item.matches("([A-Z][a-z]++)++")) {
targets.add("\"" + item + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(item + " " + WIKIPEDIA);
// targets.add("\"" + item + "\" " + WIKIPEDIA);
}
}
// own extension: always use quoted version of original target if it has more than one word
String[] targetTokens = NETagger.tokenize(target);
if (targetTokens.length > 1) {
targets.add("\"" + target + "\"");
// // own extension: add 'wikipedia' to target
// targets.add(target + " " + WIKIPEDIA);
// targets.add("\"" + target + "\" " + WIKIPEDIA);
}
<API key> = new LinkedHashSet<String>(targets);
return <API key>.toArray(new String[<API key>.size()]);
}
/**
* find the NE type of a target
*
* @param target the target String to check
* @return the NE type of target, or null, if the type couldn't be determined
*/
private String checkType(String target) {
if (!StanfordNeTagger.isInitialized()) StanfordNeTagger.init();
HashMap<String, String[]> nesByType = StanfordNeTagger.extractNEs(target);
ArrayList<String> neTypes = new ArrayList<String>(nesByType.keySet());
for (int t = 0; t < neTypes.size(); t++) {
String type = neTypes.get(t);
String[] nes = nesByType.get(type);
for (int n = 0; n < nes.length; n++)
if (nes[n].equals(target))
return type.replace("NE", "");
}
return null;
}
/**
* cut tailing words like "University", "International", "Corporation":
* "Microsoft Corporation" --> "Microsoft" and add the non-cut part to target list
*
* @param target the target String to cut
* @param targets the target list to add the cut part to
* @return true if a cut target was added, false otherwise
*/
private boolean cutExtension(String target, ArrayList<String> targets) {
if (this.extensionList.isEmpty())
for (int i = 0; i < extensions.length; i++)
this.extensionList.add(extensions[i]);
String[] targetTokens = target.split("\\s");
String last = targetTokens[targetTokens.length - 1];
if (this.extensionList.contains(last) && (targetTokens.length > 1)) {
String cutTarget = targetTokens[0];
for (int i = 1; i < (targetTokens.length - 1); i++)
cutTarget += " " + targetTokens[i];
targets.add(cutTarget);
return true;
}
return false;
}
private HashSet<String> extensionList = new HashSet<String>();
private static final String[] extensions = {
"University",
"Corporation",
"International",
// last year's winner's list ends here
"Incorporated",
"Inc.",
"Comp.",
"Corp.",
"Co.",
"Museum",
"<to be extended>"
};
/** extract non lower case parts from the targets:
* "the film 'Star Wars'" --> "'Star Wars'"
* "1998 indictment and trial of Susan McDougal" --> "Susan McDougal"
* "Miss Universe 2000 crowned" --> "Miss Universe 2000"
* "Abraham from the bible" --> "Abraham"
* "Gobi desert" --> "Gobi"
*
* @param targets the list of targets
*/
private void <API key>(ArrayList<String> targets) {
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String target = iter.next();
String[] targetTokens = target.split("\\s");
String upperCasePart = null;
int i = 0;
while (i < targetTokens.length) {
// find start of next upper case part
while ((i < targetTokens.length) && !Character.isUpperCase(targetTokens[i].charAt(0))) i++;
// start upper case part
if (i < targetTokens.length) {
upperCasePart = targetTokens[i];
i++;
}
// collect non-lower-case part
while ((i < targetTokens.length) && !Character.isLowerCase(targetTokens[i].charAt(0))) {
upperCasePart += " " + targetTokens[i];
i++;
}
if (upperCasePart != null) {
targets.add(upperCasePart);
upperCasePart = null;
}
}
}
}
/** extract acronyms from the targets:
* "Basque ETA" --> "ETA"
*
* @param targets the list of targets
*/
private void extractAcronyms(ArrayList<String> targets) {
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String target = iter.next();
String[] targetTokens = target.split("\\s");
for (String t : targetTokens) {
if (t.matches("([A-Z]){3,}")) {
targets.add(t);
} else if (t.matches("([A-Z]\\.){2,}")) {
targets.add(t);
}
}
}
}
/** remove first NP in a sequence of NPs:
* "the film 'Star Wars'" --> "'Star Wars'"
*
* @param targets the list of targets
*/
private void <API key>(ArrayList<String> targets) {
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String target = iter.next();
// tokenize and tag sentence
String[] targetTokens = OpenNLP.tokenize(target);
String[] posTags = OpenNLP.tagPos(targetTokens);
String[] chunkTags = OpenNLP.tagChunks(targetTokens, posTags);
String np = null;
int i = 0;
// find first NP
while ((i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++;
// skip first NP
i++;
// find next NP
while (( i < targetTokens.length) && !"B-NP".equals(chunkTags[i])) i++;
// start NP
if (i < targetTokens.length) {
np = targetTokens[i];
i++;
}
// add rest of NP
while (i < targetTokens.length) {
np += " " + targetTokens[i];
i++;
}
if (np != null) targets.add(np);
}
}
/** take care of remaining brackets
*
* @param targets the list of targets
*/
private void postProcess(ArrayList<String> targets) {
HashSet<String> <API key> = new LinkedHashSet<String>(targets);
targets.clear();
for (Iterator<String> iter = <API key>.iterator(); iter.hasNext();) {
String target = iter.next().trim();
boolean add = true;
if (target.startsWith("(") && target.endsWith(")"))
target = target.substring(1, target.length() - 1).trim();
if (target.startsWith("(") != target.endsWith(")")) add = false;
// own extension: cut leading and tailing apostrophes
while (target.startsWith("'")) target = target.substring(1).trim();
while (target.endsWith("'")) target = target.substring(0, (target.length() - 1)).trim();
// own extension: cut leading singel letters, but keep determiner "a"
while (target.matches("[b-z]\\s.++")) target = target.substring(2);
// own extension: filter one-char targets
if (target.length() < 2) add = false;
if (add) targets.add(target);
}
}
/**
* Increment the score of each result snippet for each word in it according
* to the number of top-100 web search engine snippets containing this
* particular word. This favors snippets that provide information given
* frequently and thus likely to be more important with regard to the
* target.
*
* @param results array of <code>Result</code> objects
* @return extended array of <code>Result</code> objects
*/
@SuppressWarnings("unchecked")
public Result[] apply(Result[] results) {
// catch empty result
if (results.length == 0) return results;
// produce target variations
String target = results[0].getQuery().<API key>();
System.out.println("<API key>:\n processing target '" + target + "'");
HashMap<String, TermCounter> rawTermCounters = this.cacheLookup(target);
// query generation test
if (<API key>) {
String[] targets = this.getTargets(target);
System.out.println(" generated web serach Strings:");
for (String t : targets) System.out.println(" - " + t);
// query generation test only
return results;
// cache miss
} else if (rawTermCounters == null) {
String[] targets = this.getTargets(target);
System.out.println(" web serach Strings are");
for (String t : targets) System.out.println(" - " + t);
rawTermCounters = this.getTermCounters(targets);
this.cache(target, rawTermCounters);
}
// get target tokens
HashSet<String> rawTargetTerms = new HashSet<String>();
String[] targetTokens = OpenNLP.tokenize(target);
for (String tt : targetTokens)
if (Character.isLetterOrDigit(tt.charAt(0)))
rawTargetTerms.add(tt);
// stem terms, collect target terms
HashMap<String, TermCounter> termCounters = new HashMap<String, TermCounter>();//this.getTermCounters(targets);
HashSet<String> targetTerms = new HashSet<String>();
ArrayList<String> rawTerms = new ArrayList<String>(rawTermCounters.keySet());
for (String rawTerm : rawTerms) {
String stemmedTerm = SnowballStemmer.stem(rawTerm.toLowerCase());
if (!termCounters.containsKey(stemmedTerm))
termCounters.put(stemmedTerm, new TermCounter());
termCounters.get(stemmedTerm).increment(rawTermCounters.get(rawTerm).getValue());
if (rawTargetTerms.contains(rawTerm))
targetTerms.add(stemmedTerm);
}
// get overall recall (since 20070718)
int termCount = this.getCountSum(termCounters);
int termCountLog = ((termCount > 100) ? ((int) Math.log10(termCount)) : 2);
System.out.println("<API key>: termCountLog is " + termCountLog);
// score results
ArrayList<Result> resultList = new ArrayList<Result>();
boolean goOn;
do {
goOn = false;
ArrayList<Result> rawResults = new ArrayList<Result>();
// score all results
for (Result r : results) {
if (r.getScore() != Float.NEGATIVE_INFINITY) {
// tokenize sentence
String[] sentence = NETagger.tokenize(r.getAnswer());
float importance = 0;
// scan sentence for terms from web result
for (int i = 0; i < sentence.length; i++) {
String term = sentence[i];
if ((term.length() > 1)/* && !StringUtils.isSubsetKeywords(term, r.getQuery().getAnalyzedQuestion().getQuestion()) && !FunctionWords.lookup(term)*/) {
term = SnowballStemmer.stem(term.toLowerCase());
TermCounter count = termCounters.get(term);
if (count != null) {
double tf; // 20070706
if (this.tfNormalizationMode == NO_NORMALIZATION) tf = 1;
else if (this.tfNormalizationMode == <API key>) {
tf = WordFrequencies.lookup(sentence[i].toLowerCase());
if (tf > Math.E) tf = Math.log(tf);
else tf = 1;
} else if (this.tfNormalizationMode == <API key>) {
tf = WordFrequencies.lookup(sentence[i].toLowerCase());
if (tf > 10) tf = Math.log10(tf);
else tf = 1;
} else tf = 1;
importance += (count.getValue() / tf);
}
}
}
// don't throw out 0-scored results for combining approaches
if (this.isCombined || (importance > 0)) {
if (this.normalizationMode == NO_NORMALIZATION)
r.setScore(importance);
else if (this.normalizationMode == <API key>)
r.setScore(importance / sentence.length); // try normalized score
else if (this.normalizationMode == <API key>)
r.setScore(importance / ((float) Math.sqrt(sentence.length))); // try normalized score
else if (this.normalizationMode == <API key>)
r.setScore(importance / (1 + ((float) Math.log(sentence.length)))); // try normalized score
else if (this.normalizationMode == <API key>)
r.setScore(importance / (1 + ((float) Math.log10(sentence.length)))); // try normalized score
rawResults.add(r);
}
}
}
if (rawResults.size() != 0) {
// find top result
Collections.sort(rawResults);
Collections.reverse(rawResults);
Result top = rawResults.remove(0);
resultList.add(top);
// decrement scores of top result terms
String[] sentence = NETagger.tokenize(top.getAnswer());
for (int i = 0; i < sentence.length; i++) {
String term = SnowballStemmer.stem(sentence[i].toLowerCase());
TermCounter count = termCounters.get(term);
if (count != null) {
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(5);
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(3);
// if (targetTerms.contains(term)) count.divideValue(2);
// else count.divideValue(2);
// 20070718
if (targetTerms.contains(term)) count.divideValue(2);
else count.divideValue(termCountLog);
if (count.getValue() == 0) termCounters.remove(term);
}
}
// prepare remaining results for next round
results = rawResults.toArray(new Result[rawResults.size()]);
goOn = true;
}
} while (goOn);
Collections.sort(resultList);
Collections.reverse(resultList);
// set position-dependent extra score for combining approaches
if (this.isCombined) {
float eScore = 100;
for (Result r : resultList) {
r.addExtraScore((this.getClass().getName() + this.normalizationMode), eScore);
eScore *= 0.9f;
}
}
return resultList.toArray(new Result[resultList.size()]);
}
// private static String lastTarget = null;
// private static String lastCacherClassName = null;
// private static HashMap<String, TermCounter> <API key> = null;
private static class CacheEntry {
String target;
HashMap<String, TermCounter> termCounters;
public CacheEntry(String target, HashMap<String, TermCounter> termCounters) {
this.target = target;
this.termCounters = termCounters;
}
}
private static HashMap<String, CacheEntry> cache = new HashMap<String, CacheEntry>();
private void cache(String target, HashMap<String, TermCounter> termCounters) {
String className = this.getClass().getName();
System.out.println("<API key>: caching web lookup result for target '" + target + "' from class '" + className + "'");
CacheEntry ce = new CacheEntry(target, termCounters);
cache.put(className, ce);
// lastTarget = target;
// lastCacherClassName = className;
// <API key> = termCounters;
}
private HashMap<String, TermCounter> cacheLookup(String target) {
String className = this.getClass().getName();
System.out.println("<API key>: doing cache lookup result for target '" + target + "', class '" + className + "'");
CacheEntry ce = cache.get(className);
if (ce == null) {
System.out.println(" --> cache miss, no entry for '" + className + "' so far");
return null;
} else if (target.equals(ce.target)) {
System.out.println(" --> cache hit");
return ce.termCounters;
} else {
System.out.println(" --> cache miss, last target for '" + className + "' is '" + ce.target + "'");
return null;
}
}
/** add all the term counters in source to target (perform a union of the key sets, summing up the counters)
* @param source
* @param target
*/
protected void addTermCounters(HashMap<String, TermCounter> source, HashMap<String, TermCounter> target) {
for (Iterator<String> keys = source.keySet().iterator(); keys.hasNext();) {
String key = keys.next();
int count = source.get(key).getValue();
if (!target.containsKey(key))
target.put(key, new TermCounter());
target.get(key).increment(count);
}
}
/** get the maximum count out of a set of counters
* @param counters
*/
protected int getMaxCount(HashMap<String, TermCounter> counters) {
int max = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();)
max = Math.max(max, counters.get(keys.next()).getValue());
return max;
}
/** get the sum of a set of counters
* @param counters
*/
protected int getCountSum(HashMap<String, TermCounter> counters) {
int sum = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();)
sum += counters.get(keys.next()).getValue();
return sum;
}
/** get the sum of a set of counters, each one minus the count in another set of counters
* @param counters
* @param compare
*/
protected int sumDiff(HashMap<String, TermCounter> counters, HashMap<String, TermCounter> compare) {
int diffSum = 0;
for (Iterator<String> keys = counters.keySet().iterator(); keys.hasNext();) {
String key = keys.next();
int count = counters.get(key).getValue();
int comp = (compare.containsKey(key) ? compare.get(key).getValue() : 0);
diffSum += Math.max((count - comp), 0);
}
return diffSum;
}
protected static boolean <API key> = false;
public static void main(String[] args) {
<API key> = true;
MsgPrinter.enableStatusMsgs(true);
MsgPrinter.enableErrorMsgs(true);
// create tokenizer
MsgPrinter.printStatusMsg("Creating tokenizer...");
if (!OpenNLP.createTokenizer("res/nlp/tokenizer/opennlp/EnglishTok.bin.gz"))
MsgPrinter.printErrorMsg("Could not create tokenizer.");
// LingPipe.createTokenizer();
// create sentence detector
// MsgPrinter.printStatusMsg("Creating sentence detector...");
// if (!OpenNLP.<API key>("res/nlp/sentencedetector/opennlp/EnglishSD.bin.gz"))
// MsgPrinter.printErrorMsg("Could not create sentence detector.");
// LingPipe.<API key>();
// create stemmer
MsgPrinter.printStatusMsg("Creating stemmer...");
SnowballStemmer.create();
// create part of speech tagger
MsgPrinter.printStatusMsg("Creating POS tagger...");
if (!OpenNLP.createPosTagger("res/nlp/postagger/opennlp/tag.bin.gz",
"res/nlp/postagger/opennlp/tagdict"))
MsgPrinter.printErrorMsg("Could not create OpenNLP POS tagger.");
// if (!StanfordPosTagger.init("res/nlp/postagger/stanford/" +
// "train-wsj-0-18.holder"))
// MsgPrinter.printErrorMsg("Could not create Stanford POS tagger.");
// create chunker
MsgPrinter.printStatusMsg("Creating chunker...");
if (!OpenNLP.createChunker("res/nlp/phrasechunker/opennlp/" +
"EnglishChunk.bin.gz"))
MsgPrinter.printErrorMsg("Could not create chunker.");
// create named entity taggers
MsgPrinter.printStatusMsg("Creating NE taggers...");
NETagger.loadListTaggers("res/nlp/netagger/lists/");
NETagger.loadRegExTaggers("res/nlp/netagger/patterns.lst");
MsgPrinter.printStatusMsg(" ...loading models");
// if (!NETagger.loadNameFinders("res/nlp/netagger/opennlp/"))
// MsgPrinter.printErrorMsg("Could not create OpenNLP NE tagger.");
if (!StanfordNeTagger.isInitialized() && !StanfordNeTagger.init())
MsgPrinter.printErrorMsg("Could not create Stanford NE tagger.");
MsgPrinter.printStatusMsg(" ...done");
<API key> wtif = new TargetGeneratorTest(NO_NORMALIZATION);
TRECTarget[] targets = TREC13To16Parser.loadTargets(args[0]);
for (TRECTarget target : targets) {
String question = target.getTargetDesc();
// query generation
MsgPrinter.<API key>();
String qn = QuestionNormalizer.normalize(question);
MsgPrinter.printNormalization(qn); // print normalized question string
Logger.logNormalization(qn); // log normalized question string
String[] kws = KeywordExtractor.getKeywords(qn);
AnalyzedQuestion aq = new AnalyzedQuestion(question);
aq.setKeywords(kws);
aq.setFactoid(false);
Query[] queries = new BagOfWordsG().generateQueries(aq);
for (int q = 0; q < queries.length; q++)
queries[q].<API key>(question);
Result[] results = new Result[1];
results[0] = new Result("This would be the answer", queries[0]);
wtif.apply(results);
}
}
private static class TargetGeneratorTest extends <API key> {
TargetGeneratorTest(int normalizationMode) {
super(normalizationMode, normalizationMode, false);
}
public HashMap<String, TermCounter> getTermCounters(String[] targets) {
return new HashMap<String, TermCounter>();
}
}
}
|
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8"/>
<title>CSS3 Text, linebreaks: 3043 HIRAGANA LETTER SMALL I</title>
<link rel='author' title='Richard Ishida' href='mailto:ishida@w3.org'>
<meta name='flags' content=''>
<style type='text/css'>
@font-face {
font-family: 'mplus-1p-regular';
src: url('support/mplus-1p-regular.woff') format('woff');
/* filesize: 803K */
}
.test, .ref { font-size: 30px; font-family: mplus-1p-regular, sans-serif; width: 95px; padding: 0; border: 1px solid orange; line-height: 1em; }
</style>
</head>
<body>
<p class="instructions">Test passes if the two orange boxes are identical.</p>
<div class='ref'><br />ぃ</div>
<div class='ref'><br />ぃ</div>
</body>
</html>
|
require File.expand_path(File.dirname(__FILE__) + '/../helpers/<API key>')
require 'thread'
describe "account admin manage groups" do
include_context "in-process server selenium tests"
def <API key> (account, name)
f(".add_category_link").click
form = f("#add_category_form")
replace_content form.find_element(:css, "input[type=text]"), name
submit_form(form)
<API key>
category = account.group_categories.where(name: name).first
expect(category).not_to be_nil
category
end
before (:each) do
skip
#<API key>
#@admin_account = Account.default
#@admin_account.settings[:<API key>] = false
#@admin_account.save!
end
it "should show one div.group_category per category" do
group_categories = create_categories @course.account
<API key>(@course.account, group_categories[0], group_categories[1], group_categories[1], group_categories[2])
get "/accounts/#{@course.account.id}/groups"
group_divs = <API key>("div.group_category")
expect(group_divs.size).to eq 4 # three groups + blank
ids = group_divs.map { |div| div.attribute(:id) }
group_categories.each { |category| expect(ids).to include("category_#{category.id}") }
expect(ids).to include("category_template")
end
it "should show one li.category per category" do
group_categories = create_categories @admin_account
<API key>(@admin_account, group_categories[0], group_categories[1], group_categories[1], group_categories[2])
get "/accounts/#{@admin_account.id}/groups"
group_divs = driver.find_elements(:css, "li.category")
expect(group_divs.size).to eq 3
labels = group_divs.map { |div| div.find_element(:css, "a").text }
group_categories.each { |category| expect(labels).to be_include(category.name) }
end
context "single category" do
before (:each) do
@<API key> = @admin_account.group_categories.create(:name => "Existing Category")
<API key> 1
end
it "should add new categories at the end of the tabs" do
<API key> @admin_account, @<API key>
get "/accounts/#{@admin_account.id}/groups"
expect(driver.find_elements(:css, "#category_list li").size).to eq 1
# submit new category form
<API key> @admin_account, 'New Category'
expect(driver.find_elements(:css, "#category_list li").size).to eq 2
expect(driver.find_elements(:css, "#category_list li a").last.text).to eq "New Category"
end
it "should remove tab and sidebar entries for deleted category" do
get "/accounts/#{@admin_account.id}/groups"
expect(f("#category_#{@<API key>.id}")).to be_displayed
expect(f("#sidebar_category_#{@<API key>.id}")).to be_displayed
f("#category_#{@<API key>.id} .<API key>").click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
<API key>
expect(find_with_jquery("#category_#{@<API key>.id}")).to be_nil
expect(find_with_jquery("#sidebar_category_#{@<API key>.id}")).to be_nil
end
it "should populate sidebar with new category when adding a category" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @<API key>)
get "/accounts/#{Account.default.id}/groups"
expect(f("#sidebar_category_#{@<API key>.id}")).to be_displayed
expect(f("#sidebar_category_#{@<API key>.id} #sidebar_group_#{group.id}")).to be_displayed
new_category = <API key>(@admin_account, 'New Category')
# We need to refresh the page because it doesn't update the sidebar,
# This is should probably be reported as a bug
refresh_page
expect(f("#sidebar_category_#{new_category.id}")).to be_displayed
end
it "should populate sidebar with new category when adding a category and group" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @<API key>)
get "/accounts/#{Account.default.id}/groups"
expect(f("#sidebar_category_#{@<API key>.id}")).to be_displayed
expect(f("#sidebar_category_#{@<API key>.id} #sidebar_group_#{group.id}")).to be_displayed
new_category = <API key>(@admin_account, 'New Category')
group2 = <API key> new_category, "New Group Category 2"
expect(f("#sidebar_category_#{new_category.id}")).to be_displayed
expect(driver.find_element(:css, "#sidebar_category_#{new_category.id} #sidebar_group_#{group2.id}")).to be_displayed
end
it "should preserve group to category association when editing a group" do
group = @admin_account.groups.create(:name => "Group 1", :group_category => @<API key>)
get "/accounts/#{Account.default.id}/groups"
<API key>
expect(find_with_jquery("#category_#{@<API key>.id} #group_#{group.id}")).to be_displayed
# submit new category form
hover_and_click(".edit_group_link")
form = f("#edit_group_form")
replace_content form.find_element(:css, "input[type=text]"), "New Name"
submit_form(form)
expect(f("#category_#{@<API key>.id} #group_#{group.id}")).to be_displayed
end
it "should populate a group tag and check if it's there" do
get "/accounts/#{@admin_account.id}/groups"
category = <API key> @admin_account, 'New Category'
category_tabs = driver.find_elements(:css, '#category_list li')
category_tabs[1].click
category_name = f("#category_#{category.id} .category_name").text
expect(category_name).to include_text(category.name)
end
it "should add another group and see that the group is there" do
get "/accounts/#{@admin_account.id}/groups"
group = <API key> @<API key>, 'group 1'
expect(f("#group_#{group.id} .group_name").text).to eq group.name
end
it "should add multiple groups and validate they exist" do
groups = <API key> @<API key>
get "/accounts/#{Account.default.id}/groups"
category_groups = driver.find_elements(:css, ".left_side .group .name")
category_groups.each_with_index { |cg, i| expect(cg.text).to include_text(groups[i].name)}
end
it "should add multiple groups and be sure they are all deleted" do
<API key> @<API key>
get "/accounts/#{@admin_account.id}/groups"
make_full_screen
delete = f(".<API key>")
delete.click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
<API key>
expect(driver.find_elements(:css, ".left_side .group")).to be_empty
expect(@admin_account.group_categories.count).to eq 0
end
it "should edit an individual group" do
get "/accounts/#{@admin_account.id}/groups"
group = <API key> @<API key>, "group 1"
expect(group).not_to be_nil
f("#group_#{group.id}").click
<API key>
f("#group_#{group.id} .edit_group_link").click
<API key>
name = "new group 1"
f("#group_name").send_keys(name)
f("#group_#{group.id} .btn").click
<API key>
group = @admin_account.groups.where(name: name).first
expect(group).not_to be_nil
end
it "should delete an individual group" do
get "/accounts/#{@admin_account.id}/groups"
group = <API key> @<API key>, "group 1"
f("#group_#{group.id}").click
driver.find_element(:css, "#group_#{group.id} .delete_group_link").click
confirm_dialog = driver.switch_to.alert
confirm_dialog.accept
<API key>
expect(driver.find_elements(:css, ".left_side .group")).to be_empty
@admin_account.group_categories.last.groups.last.workflow_state =='deleted'
end
it "should drag a user to a group" do
student = @course.students.last
get "/accounts/#{@admin_account.id}/groups"
group = <API key> @<API key>, "group 1"
simulate_group_drag(student.id, "blank", group.id)
group_div = f("#group_#{group.id}")
expect(group_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
end
it "should drag a user to 2 different groups" do
student = @course.students.last
groups = <API key> @<API key>, 2
get "/accounts/#{@admin_account.id}/groups"
<API key>
simulate_group_drag(student.id, "blank", groups[0].id)
group1_div = f("#group_#{groups[0].id}")
expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
simulate_group_drag(student.id, groups[0].id, groups[1].id)
group2_div = f("#group_#{groups[1].id}")
expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
end
it "should drag a user to 2 different groups and back to the unassigned group" do
student = @course.students.last
groups = <API key> @<API key>, 2
get "/accounts/#{@admin_account.id}/groups"
<API key>
simulate_group_drag(student.id, "blank", groups[0].id)
group1_div = f("#group_#{groups[0].id}")
expect(group1_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
simulate_group_drag(student.id, groups[0].id, groups[1].id)
group2_div = f("#group_#{groups[1].id}")
expect(group2_div.find_element(:css, ".user_id_#{student.id}")).to be_displayed
unassigned_div = f("#category_#{@<API key>.id} .group_blank")
simulate_group_drag(student.id, groups[1].id, "blank")
expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty
get "/accounts/#{@admin_account.id}/groups"
unassigned_div =f("#category_#{@<API key>.id} .group_blank")
expect(unassigned_div.find_elements(:css, ".user_id_#{student.id}")).not_to be_empty
end
it "should create a category and should be able to edit it" do
get "/accounts/#{@admin_account.id}/groups"
expect(@admin_account.group_categories.last.name).to eq "Existing Category"
make_full_screen
f("#category_#{@<API key>.id} .edit_category_link .icon-edit").click
<API key>
form = f("#edit_category_form")
input_box = form.find_element(:css, "input[type=text]")
category_name = "New Category"
replace_content input_box, category_name
submit_form(form)
<API key>
expect(@admin_account.group_categories.last.name).to eq category_name
end
it "should not be able to check the Allow self sign-up box" do
get "/accounts/#{@admin_account.id}/groups"
expect(@admin_account.group_categories.last.name).to eq "Existing Category"
make_full_screen
f("#category_#{@<API key>.id} .edit_category_link .icon-edit").click
<API key>
form = driver.find_element(:id, "edit_category_form")
expect(ff("#<API key>", form)).to be_empty
submit_form(form)
<API key>
expect(f("#category_#{@<API key>.id} .self_signup_text")).not_to include_text "Self sign-up is enabled"
end
end
end
|
#ifndef SESSION_PLOTS_HPP
#define SESSION_PLOTS_HPP
namespace rstudio {
namespace core {
class Error;
}
}
namespace rstudio {
namespace session {
namespace modules {
namespace plots {
bool haveCairoPdf();
core::Error initialize();
} // namespace plots
} // namespace modules
} // namespace session
} // namespace rstudio
#endif // SESSION_PLOTS_HPP
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.