code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*!
* jQuery Cycle Plugin (with Transition Definitions)
* Examples and documentation at: http://jquery.malsup.com/cycle/
* Copyright (c) 2007-2013 M. Alsup
* Version: 3.0.3 (11-JUL-2013)
* Dual licensed under the MIT and GPL licenses.
* http://jquery.malsup.com/license.html
* Requires: jQuery v1.7.1 or later
*/
;(function($, undefined) {
"use strict";
var ver = '3.0.3';
function debug(s) {
if ($.fn.cycle.debug)
log(s);
}
function log() {
/*global console */
if (window.console && console.log)
console.log('[cycle] ' + Array.prototype.join.call(arguments,' '));
}
$.expr[':'].paused = function(el) {
return el.cyclePause;
};
// the options arg can be...
// a number - indicates an immediate transition should occur to the given slide index
// a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc)
// an object - properties to control the slideshow
//
// the arg2 arg can be...
// the name of an fx (only used in conjunction with a numeric value for 'options')
// the value true (only used in first arg == 'resume') and indicates
// that the resume should occur immediately (not wait for next timeout)
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };
// in 1.3+ we can fix mistakes with the ready state
if (this.length === 0 && options != 'stop') {
if (!$.isReady && o.s) {
log('DOM not ready, queuing slideshow');
$(function() {
$(o.s,o.c).cycle(options,arg2);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
// iterate the matched nodeset
return this.each(function() {
var opts = handleArguments(this, options, arg2);
if (opts === false)
return;
opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;
// stop existing slideshow for this container (if there is one)
if (this.cycleTimeout)
clearTimeout(this.cycleTimeout);
this.cycleTimeout = this.cyclePause = 0;
this.cycleStop = 0; // issue #108
var $cont = $(this);
var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
var els = $slides.get();
if (els.length < 2) {
log('terminating; too few slides: ' + els.length);
return;
}
var opts2 = buildOptions($cont, $slides, els, opts, o);
if (opts2 === false)
return;
var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards);
// if it's an auto slideshow, kick it off
if (startTime) {
startTime += (opts2.delay || 0);
if (startTime < 10)
startTime = 10;
debug('first timeout: ' + startTime);
this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime);
}
});
};
function triggerPause(cont, byHover, onPager) {
var opts = $(cont).data('cycle.opts');
if (!opts)
return;
var paused = !!cont.cyclePause;
if (paused && opts.paused)
opts.paused(cont, opts, byHover, onPager);
else if (!paused && opts.resumed)
opts.resumed(cont, opts, byHover, onPager);
}
// process the args that were passed to the plugin fn
function handleArguments(cont, options, arg2) {
if (cont.cycleStop === undefined)
cont.cycleStop = 0;
if (options === undefined || options === null)
options = {};
if (options.constructor == String) {
switch(options) {
case 'destroy':
case 'stop':
var opts = $(cont).data('cycle.opts');
if (!opts)
return false;
cont.cycleStop++; // callbacks look for change
if (cont.cycleTimeout)
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
if (opts.elements)
$(opts.elements).stop();
$(cont).removeData('cycle.opts');
if (options == 'destroy')
destroy(cont, opts);
return false;
case 'toggle':
cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1;
checkInstantResume(cont.cyclePause, arg2, cont);
triggerPause(cont);
return false;
case 'pause':
cont.cyclePause = 1;
triggerPause(cont);
return false;
case 'resume':
cont.cyclePause = 0;
checkInstantResume(false, arg2, cont);
triggerPause(cont);
return false;
case 'prev':
case 'next':
opts = $(cont).data('cycle.opts');
if (!opts) {
log('options not found, "prev/next" ignored');
return false;
}
if (typeof arg2 == 'string')
opts.oneTimeFx = arg2;
$.fn.cycle[options](opts);
return false;
default:
options = { fx: options };
}
return options;
}
else if (options.constructor == Number) {
// go to the requested slide
var num = options;
options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not advance slide');
return false;
}
if (num < 0 || num >= options.elements.length) {
log('invalid slide index: ' + num);
return false;
}
options.nextSlide = num;
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
if (typeof arg2 == 'string')
options.oneTimeFx = arg2;
go(options.elements, options, 1, num >= options.currSlide);
return false;
}
return options;
function checkInstantResume(isPaused, arg2, cont) {
if (!isPaused && arg2 === true) { // resume now!
var options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not resume');
return false;
}
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
go(options.elements, options, 1, !options.backwards);
}
}
}
function removeFilter(el, opts) {
if (!$.support.opacity && opts.cleartype && el.style.filter) {
try { el.style.removeAttribute('filter'); }
catch(smother) {} // handle old opera versions
}
}
// unbind event handlers
function destroy(cont, opts) {
if (opts.next)
$(opts.next).unbind(opts.prevNextEvent);
if (opts.prev)
$(opts.prev).unbind(opts.prevNextEvent);
if (opts.pager || opts.pagerAnchorBuilder)
$.each(opts.pagerAnchors || [], function() {
this.unbind().remove();
});
opts.pagerAnchors = null;
$(cont).unbind('mouseenter.cycle mouseleave.cycle');
if (opts.destroy) // callback
opts.destroy(opts);
}
// one-time initialization
function buildOptions($cont, $slides, els, options, o) {
var startingSlideSpecified;
// support metadata plugin (v1.0 and v2.0)
var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
if (meta)
opts = $.extend(opts, meta);
if (opts.autostop)
opts.countdown = opts.autostopCount || els.length;
var cont = $cont[0];
$cont.data('cycle.opts', opts);
opts.$cont = $cont;
opts.stopCount = cont.cycleStop;
opts.elements = els;
opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
// push some after callbacks
if (!$.support.opacity && opts.cleartype)
opts.after.push(function() { removeFilter(this, opts); });
if (opts.continuous)
opts.after.push(function() { go(els,opts,0,!opts.backwards); });
saveOriginalOpts(opts);
// clearType corrections
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($slides);
// container requires non-static position so that slides can be position within
if ($cont.css('position') == 'static')
$cont.css('position', 'relative');
if (opts.width)
$cont.width(opts.width);
if (opts.height && opts.height != 'auto')
$cont.height(opts.height);
if (opts.startingSlide !== undefined) {
opts.startingSlide = parseInt(opts.startingSlide,10);
if (opts.startingSlide >= els.length || opts.startSlide < 0)
opts.startingSlide = 0; // catch bogus input
else
startingSlideSpecified = true;
}
else if (opts.backwards)
opts.startingSlide = els.length - 1;
else
opts.startingSlide = 0;
// if random, mix up the slide array
if (opts.random) {
opts.randomMap = [];
for (var i = 0; i < els.length; i++)
opts.randomMap.push(i);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
if (startingSlideSpecified) {
// try to find the specified starting slide and if found set start slide index in the map accordingly
for ( var cnt = 0; cnt < els.length; cnt++ ) {
if ( opts.startingSlide == opts.randomMap[cnt] ) {
opts.randomIndex = cnt;
}
}
}
else {
opts.randomIndex = 1;
opts.startingSlide = opts.randomMap[1];
}
}
else if (opts.startingSlide >= els.length)
opts.startingSlide = 0; // catch bogus input
opts.currSlide = opts.startingSlide || 0;
var first = opts.startingSlide;
// set position and zIndex on all the slides
$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
var z;
if (opts.backwards)
z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i;
else
z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
$(this).css('z-index', z);
});
// make sure first slide is visible
$(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case
removeFilter(els[first], opts);
// stretch slides
if (opts.fit) {
if (!opts.aspect) {
if (opts.width)
$slides.width(opts.width);
if (opts.height && opts.height != 'auto')
$slides.height(opts.height);
} else {
$slides.each(function(){
var $slide = $(this);
var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect;
if( opts.width && $slide.width() != opts.width ) {
$slide.width( opts.width );
$slide.height( opts.width / ratio );
}
if( opts.height && $slide.height() < opts.height ) {
$slide.height( opts.height );
$slide.width( opts.height * ratio );
}
});
}
}
if (opts.center && ((!opts.fit) || opts.aspect)) {
$slides.each(function(){
var $slide = $(this);
$slide.css({
"margin-left": opts.width ?
((opts.width - $slide.width()) / 2) + "px" :
0,
"margin-top": opts.height ?
((opts.height - $slide.height()) / 2) + "px" :
0
});
});
}
if (opts.center && !opts.fit && !opts.slideResize) {
$slides.each(function(){
var $slide = $(this);
$slide.css({
"margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0,
"margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0
});
});
}
// stretch container
var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1;
if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
var maxw = 0, maxh = 0;
for(var j=0; j < els.length; j++) {
var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
if (!w) w = e.offsetWidth || e.width || $e.attr('width');
if (!h) h = e.offsetHeight || e.height || $e.attr('height');
maxw = w > maxw ? w : maxw;
maxh = h > maxh ? h : maxh;
}
if (opts.containerResize && maxw > 0 && maxh > 0)
$cont.css({width:maxw+'px',height:maxh+'px'});
if (opts.containerResizeHeight && maxh > 0)
$cont.css({height:maxh+'px'});
}
var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
if (opts.pause)
$cont.bind('mouseenter.cycle', function(){
pauseFlag = true;
this.cyclePause++;
triggerPause(cont, true);
}).bind('mouseleave.cycle', function(){
if (pauseFlag)
this.cyclePause--;
triggerPause(cont, true);
});
if (supportMultiTransitions(opts) === false)
return false;
// apparently a lot of people use image slideshows without height/width attributes on the images.
// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
var requeue = false;
options.requeueAttempts = options.requeueAttempts || 0;
$slides.each(function() {
// try to get height/width of each slide
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0);
this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0);
if ( $el.is('img') ) {
var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete);
// don't requeue for images that are still loading but have a valid size
if (loading) {
if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout);
requeue = true;
return false; // break each loop
}
else {
log('could not determine size of image: '+this.src, this.cycleW, this.cycleH);
}
}
}
return true;
});
if (requeue)
return false;
opts.cssBefore = opts.cssBefore || {};
opts.cssAfter = opts.cssAfter || {};
opts.cssFirst = opts.cssFirst || {};
opts.animIn = opts.animIn || {};
opts.animOut = opts.animOut || {};
$slides.not(':eq('+first+')').css(opts.cssBefore);
$($slides[first]).css(opts.cssFirst);
if (opts.timeout) {
opts.timeout = parseInt(opts.timeout,10);
// ensure that timeout and speed settings are sane
if (opts.speed.constructor == String)
opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10);
if (!opts.sync)
opts.speed = opts.speed / 2;
var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250;
while((opts.timeout - opts.speed) < buffer) // sanitize timeout
opts.timeout += opts.speed;
}
if (opts.easing)
opts.easeIn = opts.easeOut = opts.easing;
if (!opts.speedIn)
opts.speedIn = opts.speed;
if (!opts.speedOut)
opts.speedOut = opts.speed;
opts.slideCount = els.length;
opts.currSlide = opts.lastSlide = first;
if (opts.random) {
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.backwards)
opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1;
else
opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;
// run transition init fn
if (!opts.multiFx) {
var init = $.fn.cycle.transitions[opts.fx];
if ($.isFunction(init))
init($cont, $slides, opts);
else if (opts.fx != 'custom' && !opts.multiFx) {
log('unknown transition: ' + opts.fx,'; slideshow terminating');
return false;
}
}
// fire artificial events
var e0 = $slides[first];
if (!opts.skipInitializationCallbacks) {
if (opts.before.length)
opts.before[0].apply(e0, [e0, e0, opts, true]);
if (opts.after.length)
opts.after[0].apply(e0, [e0, e0, opts, true]);
}
if (opts.next)
$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);});
if (opts.prev)
$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);});
if (opts.pager || opts.pagerAnchorBuilder)
buildPager(els,opts);
exposeAddSlide(opts, els);
return opts;
}
// save off original opts so we can restore after clearing state
function saveOriginalOpts(opts) {
opts.original = { before: [], after: [] };
opts.original.cssBefore = $.extend({}, opts.cssBefore);
opts.original.cssAfter = $.extend({}, opts.cssAfter);
opts.original.animIn = $.extend({}, opts.animIn);
opts.original.animOut = $.extend({}, opts.animOut);
$.each(opts.before, function() { opts.original.before.push(this); });
$.each(opts.after, function() { opts.original.after.push(this); });
}
function supportMultiTransitions(opts) {
var i, tx, txs = $.fn.cycle.transitions;
// look for multiple effects
if (opts.fx.indexOf(',') > 0) {
opts.multiFx = true;
opts.fxs = opts.fx.replace(/\s*/g,'').split(',');
// discard any bogus effect names
for (i=0; i < opts.fxs.length; i++) {
var fx = opts.fxs[i];
tx = txs[fx];
if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
log('discarding unknown transition: ',fx);
opts.fxs.splice(i,1);
i--;
}
}
// if we have an empty list then we threw everything away!
if (!opts.fxs.length) {
log('No valid transitions named; slideshow terminating.');
return false;
}
}
else if (opts.fx == 'all') { // auto-gen the list of transitions
opts.multiFx = true;
opts.fxs = [];
for (var p in txs) {
if (txs.hasOwnProperty(p)) {
tx = txs[p];
if (txs.hasOwnProperty(p) && $.isFunction(tx))
opts.fxs.push(p);
}
}
}
if (opts.multiFx && opts.randomizeEffects) {
// munge the fxs array to make effect selection random
var r1 = Math.floor(Math.random() * 20) + 30;
for (i = 0; i < r1; i++) {
var r2 = Math.floor(Math.random() * opts.fxs.length);
opts.fxs.push(opts.fxs.splice(r2,1)[0]);
}
debug('randomized fx sequence: ',opts.fxs);
}
return true;
}
// provide a mechanism for adding slides after the slideshow has started
function exposeAddSlide(opts, els) {
opts.addSlide = function(newSlide, prepend) {
var $s = $(newSlide), s = $s[0];
if (!opts.autostopCount)
opts.countdown++;
els[prepend?'unshift':'push'](s);
if (opts.els)
opts.els[prepend?'unshift':'push'](s); // shuffle needs this
opts.slideCount = els.length;
// add the slide to the random map and resort
if (opts.random) {
opts.randomMap.push(opts.slideCount-1);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
}
$s.css('position','absolute');
$s[prepend?'prependTo':'appendTo'](opts.$cont);
if (prepend) {
opts.currSlide++;
opts.nextSlide++;
}
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($s);
if (opts.fit && opts.width)
$s.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$s.height(opts.height);
s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();
$s.css(opts.cssBefore);
if (opts.pager || opts.pagerAnchorBuilder)
$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
if ($.isFunction(opts.onAddSlide))
opts.onAddSlide($s);
else
$s.hide(); // default behavior
};
}
// reset internal state; we do this on every pass in order to support multiple effects
$.fn.cycle.resetState = function(opts, fx) {
fx = fx || opts.fx;
opts.before = []; opts.after = [];
opts.cssBefore = $.extend({}, opts.original.cssBefore);
opts.cssAfter = $.extend({}, opts.original.cssAfter);
opts.animIn = $.extend({}, opts.original.animIn);
opts.animOut = $.extend({}, opts.original.animOut);
opts.fxFn = null;
$.each(opts.original.before, function() { opts.before.push(this); });
$.each(opts.original.after, function() { opts.after.push(this); });
// re-init
var init = $.fn.cycle.transitions[fx];
if ($.isFunction(init))
init(opts.$cont, $(opts.elements), opts);
};
// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
function go(els, opts, manual, fwd) {
var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];
// opts.busy is true if we're in the middle of an animation
if (manual && opts.busy && opts.manualTrump) {
// let manual transitions requests trump active ones
debug('manualTrump in go(), stopping active transition');
$(els).stop(true,true);
opts.busy = 0;
clearTimeout(p.cycleTimeout);
}
// don't begin another timeout-based transition if there is one active
if (opts.busy) {
debug('transition active, ignoring new tx request');
return;
}
// stop cycling if we have an outstanding stop request
if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
return;
// check to see if we should stop cycling based on autostop options
if (!manual && !p.cyclePause && !opts.bounce &&
((opts.autostop && (--opts.countdown <= 0)) ||
(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
if (opts.end)
opts.end(opts);
return;
}
// if slideshow is paused, only transition on a manual trigger
var changed = false;
if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) {
changed = true;
var fx = opts.fx;
// keep trying to get the slide size if we don't have it yet
curr.cycleH = curr.cycleH || $(curr).height();
curr.cycleW = curr.cycleW || $(curr).width();
next.cycleH = next.cycleH || $(next).height();
next.cycleW = next.cycleW || $(next).width();
// support multiple transition types
if (opts.multiFx) {
if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length))
opts.lastFx = 0;
else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0))
opts.lastFx = opts.fxs.length - 1;
fx = opts.fxs[opts.lastFx];
}
// one-time fx overrides apply to: $('div').cycle(3,'zoom');
if (opts.oneTimeFx) {
fx = opts.oneTimeFx;
opts.oneTimeFx = null;
}
$.fn.cycle.resetState(opts, fx);
// run the before callbacks
if (opts.before.length)
$.each(opts.before, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
// stage the after callacks
var after = function() {
opts.busy = 0;
$.each(opts.after, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
if (!p.cycleStop) {
// queue next transition
queueNext();
}
};
debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide);
// get ready to perform the transition
opts.busy = 1;
if (opts.fxFn) // fx function provided?
opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
$.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else
$.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
}
else {
queueNext();
}
if (changed || opts.nextSlide == opts.currSlide) {
// calculate the next slide
var roll;
opts.lastSlide = opts.currSlide;
if (opts.random) {
opts.currSlide = opts.nextSlide;
if (++opts.randomIndex == els.length) {
opts.randomIndex = 0;
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
}
opts.nextSlide = opts.randomMap[opts.randomIndex];
if (opts.nextSlide == opts.currSlide)
opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1;
}
else if (opts.backwards) {
roll = (opts.nextSlide - 1) < 0;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = 1;
opts.currSlide = 0;
}
else {
opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1;
opts.currSlide = roll ? 0 : opts.nextSlide+1;
}
}
else { // sequence
roll = (opts.nextSlide + 1) == els.length;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = els.length-2;
opts.currSlide = els.length-1;
}
else {
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
}
}
}
if (changed && opts.pager)
opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass);
function queueNext() {
// stage the next transition
var ms = 0, timeout = opts.timeout;
if (opts.timeout && !opts.continuous) {
ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd);
if (opts.fx == 'shuffle')
ms -= opts.speedOut;
}
else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
ms = 10;
if (ms > 0)
p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms);
}
}
// invoked after transition
$.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) {
$(pager).each(function() {
$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
});
};
// calculate timeout value for current transition
function getTimeout(curr, next, opts, fwd) {
if (opts.timeoutFn) {
// call user provided calc fn
var t = opts.timeoutFn.call(curr,curr,next,opts,fwd);
while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout
t += opts.speed;
debug('calculated timeout: ' + t + '; speed: ' + opts.speed);
if (t !== false)
return t;
}
return opts.timeout;
}
// expose next/prev function, caller must pass in state
$.fn.cycle.next = function(opts) { advance(opts,1); };
$.fn.cycle.prev = function(opts) { advance(opts,0);};
// advance slide forward or back
function advance(opts, moveForward) {
var val = moveForward ? 1 : -1;
var els = opts.elements;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if (opts.random && val < 0) {
// move back to the previously display slide
opts.randomIndex--;
if (--opts.randomIndex == -2)
opts.randomIndex = els.length-2;
else if (opts.randomIndex == -1)
opts.randomIndex = els.length-1;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.random) {
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else {
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0) {
if (opts.nowrap) return false;
opts.nextSlide = els.length - 1;
}
else if (opts.nextSlide >= els.length) {
if (opts.nowrap) return false;
opts.nextSlide = 0;
}
}
var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated
if ($.isFunction(cb))
cb(val > 0, opts.nextSlide, els[opts.nextSlide]);
go(els, opts, 1, moveForward);
return false;
}
function buildPager(els, opts) {
var $p = $(opts.pager);
$.each(els, function(i,o) {
$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
});
opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);
}
$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
var a;
if ($.isFunction(opts.pagerAnchorBuilder)) {
a = opts.pagerAnchorBuilder(i,el);
debug('pagerAnchorBuilder('+i+', el) returned: ' + a);
}
else
a = '<a href="#">'+(i+1)+'</a>';
if (!a)
return;
var $a = $(a);
// don't reparent if anchor is in the dom
if ($a.parents('body').length === 0) {
var arr = [];
if ($p.length > 1) {
$p.each(function() {
var $clone = $a.clone(true);
$(this).append($clone);
arr.push($clone[0]);
});
$a = $(arr);
}
else {
$a.appendTo($p);
}
}
opts.pagerAnchors = opts.pagerAnchors || [];
opts.pagerAnchors.push($a);
var pagerFn = function(e) {
e.preventDefault();
opts.nextSlide = i;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated
if ($.isFunction(cb))
cb(opts.nextSlide, els[opts.nextSlide]);
go(els,opts,1,opts.currSlide < i); // trigger the trans
// return false; // <== allow bubble
};
if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) {
$a.hover(pagerFn, function(){/* no-op */} );
}
else {
$a.bind(opts.pagerEvent, pagerFn);
}
if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble)
$a.bind('click.cycle', function(){return false;}); // suppress click
var cont = opts.$cont[0];
var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
if (opts.pauseOnPagerHover) {
$a.hover(
function() {
pauseFlag = true;
cont.cyclePause++;
triggerPause(cont,true,true);
}, function() {
if (pauseFlag)
cont.cyclePause--;
triggerPause(cont,true,true);
}
);
}
};
// helper fn to calculate the number of slides between the current and the next
$.fn.cycle.hopsFromLast = function(opts, fwd) {
var hops, l = opts.lastSlide, c = opts.currSlide;
if (fwd)
hops = c > l ? c - l : opts.slideCount - l;
else
hops = c < l ? l - c : l + opts.slideCount - c;
return hops;
};
// fix clearType problems in ie6 by setting an explicit bg color
// (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) {
debug('applying clearType background-color hack');
function hex(s) {
s = parseInt(s,10).toString(16);
return s.length < 2 ? '0'+s : s;
}
function getBg(e) {
for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
var v = $.css(e,'background-color');
if (v && v.indexOf('rgb') >= 0 ) {
var rgb = v.match(/\d+/g);
return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}
if (v && v != 'transparent')
return v;
}
return '#ffffff';
}
$slides.each(function() { $(this).css('background-color', getBg(this)); });
}
// reset common props before the next transition
$.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) {
$(opts.elements).not(curr).hide();
if (typeof opts.cssBefore.opacity == 'undefined')
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
if (opts.slideResize && w !== false && next.cycleW > 0)
opts.cssBefore.width = next.cycleW;
if (opts.slideResize && h !== false && next.cycleH > 0)
opts.cssBefore.height = next.cycleH;
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.display = 'none';
$(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
};
// the actual fn for effecting a transition
$.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) {
var $l = $(curr), $n = $(next);
var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay;
$n.css(opts.cssBefore);
if (speedOverride) {
if (typeof speedOverride == 'number')
speedIn = speedOut = speedOverride;
else
speedIn = speedOut = 1;
easeIn = easeOut = null;
}
var fn = function() {
$n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() {
cb();
});
};
$l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() {
$l.css(opts.cssAfter);
if (!opts.sync)
fn();
});
if (opts.sync) fn();
};
// transition definitions - only fade is defined here, transition pack defines the rest
$.fn.cycle.transitions = {
fade: function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.opacity = 0;
});
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
opts.cssBefore = { top: 0, left: 0 };
}
};
$.fn.cycle.ver = function() { return ver; };
// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
activePagerClass: 'activeSlide', // class name used for the active pager link
after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling
animIn: null, // properties that define how the slide animates in
animInDelay: 0, // allows delay before next slide transitions in
animOut: null, // properties that define how the slide animates out
animOutDelay: 0, // allows delay before current slide transitions out
aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option)
autostop: 0, // true to end slideshow after X transitions (where X == slide count)
autostopCount: 0, // number of transitions (optionally used with autostop to define X)
backwards: false, // true to start slideshow at last slide and move backwards through the stack
before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options)
cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE)
cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
containerResize: 1, // resize container to fit largest slide
containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic
continuous: 0, // true to start next transition immediately after current one completes
cssAfter: null, // properties that defined the state of the slide after transitioning out
cssBefore: null, // properties that define the initial state of the slide before transitioning in
delay: 0, // additional delay (in ms) for first transition (hint: can be negative)
easeIn: null, // easing for "in" transition
easeOut: null, // easing for "out" transition
easing: null, // easing method for both in and out transitions
end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
fit: 0, // force slides to fit container
fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle')
fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well)
manualTrump: true, // causes manual transition to stop an active transition instead of being ignored
metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow
next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide
nowrap: 0, // true to prevent slideshow from wrapping
onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement)
onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement)
pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container
pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement)
pagerEvent: 'click.cycle', // name of event which drives the pager navigation
pause: 0, // true to enable "pause on hover"
pauseOnPagerHover: 0, // true to pause when hovering over pager link
prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide
prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide
random: 0, // true for random, false for sequence (not applicable to shuffle fx)
randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random
requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
requeueTimeout: 250, // ms delay for requeue
rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle)
shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 }
skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition
slideExpr: null, // expression for selecting slides (if something other than all children is required)
slideResize: 1, // force slide width/height to fixed size before every transition
speed: 1000, // speed of the transition (any valid fx speed value)
speedIn: null, // speed of the 'in' transition
speedOut: null, // speed of the 'out' transition
startingSlide: undefined,// zero-based index of the first slide to be displayed
sync: 1, // true if in/out transitions should occur simultaneously
timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance)
timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag)
updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style)
width: null // container width (if the 'fit' option is true, the slides will be set to this width as well)
};
})(jQuery);
/*!
* jQuery Cycle Plugin Transition Definitions
* This script is a plugin for the jQuery Cycle Plugin
* Examples and documentation at: http://malsup.com/jquery/cycle/
* Copyright (c) 2007-2010 M. Alsup
* Version: 2.73
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
"use strict";
//
// These functions define slide initialization and properties for the named
// transitions. To save file size feel free to remove any of these that you
// don't need.
//
$.fn.cycle.transitions.none = function($cont, $slides, opts) {
opts.fxFn = function(curr,next,opts,after){
$(next).show();
$(curr).hide();
after();
};
};
// not a cross-fade, fadeout only fades out the top slide
$.fn.cycle.transitions.fadeout = function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 });
opts.before.push(function(curr,next,opts,w,h,rev) {
$(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1));
});
opts.animIn.opacity = 1;
opts.animOut.opacity = 0;
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
opts.cssAfter.zIndex = 0;
};
// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssBefore.top = h;
opts.cssBefore.left = 0;
opts.cssFirst.top = 0;
opts.animIn.top = 0;
opts.animOut.top = -h;
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssFirst.top = 0;
opts.cssBefore.top = -h;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.top = h;
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = 0-w;
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = -w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = w;
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
$cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts, fwd) {
if (opts.rev)
fwd = !fwd;
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
});
opts.cssFirst.left = 0;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.top = 0;
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts, fwd) {
if (opts.rev)
fwd = !fwd;
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1);
opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.left = 0;
};
// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
opts.animIn.width = 'show';
opts.animOut.width = 0;
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.height = 0;
opts.animIn.height = 'show';
opts.animOut.height = 0;
};
// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
var i, w = $cont.css('overflow', 'visible').width();
$slides.css({left: 0, top: 0});
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
});
// only adjust speed once!
if (!opts.speedAdjusted) {
opts.speed = opts.speed / 2; // shuffle has 2 transitions
opts.speedAdjusted = true;
}
opts.random = 0;
opts.shuffle = opts.shuffle || {left:-w, top:15};
opts.els = [];
for (i=0; i < $slides.length; i++)
opts.els.push($slides[i]);
for (i=0; i < opts.currSlide; i++)
opts.els.push(opts.els.shift());
// custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
opts.fxFn = function(curr, next, opts, cb, fwd) {
if (opts.rev)
fwd = !fwd;
var $el = fwd ? $(curr) : $(next);
$(next).css(opts.cssBefore);
var count = opts.slideCount;
$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
var hops = $.fn.cycle.hopsFromLast(opts, fwd);
for (var k=0; k < hops; k++) {
if (fwd)
opts.els.push(opts.els.shift());
else
opts.els.unshift(opts.els.pop());
}
if (fwd) {
for (var i=0, len=opts.els.length; i < len; i++)
$(opts.els[i]).css('z-index', len-i+count);
}
else {
var z = $(curr).css('z-index');
$el.css('z-index', parseInt(z,10)+1+count);
}
$el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
$(fwd ? this : curr).hide();
if (cb) cb();
});
});
};
$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
};
// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = next.cycleH;
opts.animIn.height = next.cycleH;
opts.animOut.width = next.cycleW;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.cssBefore.height = 0;
opts.animIn.top = 0;
opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.height = 0;
opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = next.cycleW;
opts.animIn.width = next.cycleW;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
opts.animIn.left = 0;
opts.animOut.width = 0;
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
$.extend(opts.cssBefore, { top: 0, left: 0, width: 0 });
opts.animIn.left = 0;
opts.animOut.width = 0;
};
// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.cssBefore.left = next.cycleW/2;
$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
$.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 });
});
opts.cssFirst.top = 0;
opts.cssFirst.left = 0;
opts.cssBefore.width = 0;
opts.cssBefore.height = 0;
};
// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false);
opts.cssBefore.left = next.cycleW/2;
opts.cssBefore.top = next.cycleH/2;
$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
});
opts.cssBefore.width = 0;
opts.cssBefore.height = 0;
opts.animOut.opacity = 0;
};
// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = w;
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore.top = h;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.top = h;
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
var w = $cont.width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore.top = h;
opts.cssBefore.left = w;
opts.animIn.top = 0;
opts.animIn.left = 0;
opts.animOut.top = h;
opts.animOut.left = w;
};
// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = this.cycleW/2;
opts.animIn.left = 0;
opts.animIn.width = this.cycleW;
opts.animOut.left = 0;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = this.cycleH/2;
opts.animIn.top = 0;
opts.animIn.height = this.cycleH;
opts.animOut.top = 0;
});
opts.cssBefore.height = 0;
opts.cssBefore.left = 0;
};
// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true,true);
opts.cssBefore.left = next.cycleW/2;
opts.animIn.left = 0;
opts.animIn.width = this.cycleW;
opts.animOut.left = curr.cycleW/2;
opts.animOut.width = 0;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.animIn.top = 0;
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH/2;
opts.animOut.height = 0;
});
opts.cssBefore.height = 0;
opts.cssBefore.left = 0;
};
// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssAfter.display = '';
if (d == 'right')
opts.cssBefore.left = -w;
else if (d == 'up')
opts.cssBefore.top = h;
else if (d == 'down')
opts.cssBefore.top = -h;
else
opts.cssBefore.left = w;
});
opts.animIn.left = 0;
opts.animIn.top = 0;
opts.cssBefore.top = 0;
opts.cssBefore.left = 0;
};
// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
if (d == 'right')
opts.animOut.left = w;
else if (d == 'up')
opts.animOut.top = -h;
else if (d == 'down')
opts.animOut.top = h;
else
opts.animOut.left = -w;
});
opts.animIn.left = 0;
opts.animIn.top = 0;
opts.cssBefore.top = 0;
opts.cssBefore.left = 0;
};
// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
var w = $cont.css('overflow','visible').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
// provide default toss settings if animOut not provided
if (!opts.animOut.left && !opts.animOut.top)
$.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 });
else
opts.animOut.opacity = 0;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
};
// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.cssBefore = opts.cssBefore || {};
var clip;
if (opts.clip) {
if (/l2r/.test(opts.clip))
clip = 'rect(0px 0px '+h+'px 0px)';
else if (/r2l/.test(opts.clip))
clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
else if (/t2b/.test(opts.clip))
clip = 'rect(0px '+w+'px 0px 0px)';
else if (/b2t/.test(opts.clip))
clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
else if (/zoom/.test(opts.clip)) {
var top = parseInt(h/2,10);
var left = parseInt(w/2,10);
clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)';
}
}
opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';
var d = opts.cssBefore.clip.match(/(\d+)/g);
var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10);
opts.before.push(function(curr, next, opts) {
if (curr == next) return;
var $curr = $(curr), $next = $(next);
$.fn.cycle.commonReset(curr,next,opts,true,true,false);
opts.cssAfter.display = 'block';
var step = 1, count = parseInt((opts.speedIn / 13),10) - 1;
(function f() {
var tt = t ? t - parseInt(step * (t/count),10) : 0;
var ll = l ? l - parseInt(step * (l/count),10) : 0;
var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h;
var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w;
$next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
(step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
})();
});
$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
opts.animIn = { left: 0 };
opts.animOut = { left: 0 };
};
})(jQuery); | delfintrinidadIV/firstproject | wp-content/themes/simple-catch/js/jquery.cycle.all.js | JavaScript | gpl-2.0 | 52,026 |
// (C) Copyright Gennadiy Rozental 2005-2008.
// Use, modification, and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision: 49312 $
//
// Description : offline implementation of char parameter
// ***************************************************************************
#define BOOST_RT_PARAM_INLINE
#include <boost/test/utils/runtime/cla/char_parameter.ipp>
| hpl1nk/nonamegame | xray/SDK/include/boost/test/utils/runtime/cla/char_parameter.cpp | C++ | gpl-3.0 | 610 |
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="node" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var baseIndexOf = require('./baseIndexOf'),
cacheIndexOf = require('./cacheIndexOf'),
createCache = require('./createCache'),
getArray = require('./getArray'),
largeArraySize = require('./largeArraySize'),
releaseArray = require('./releaseArray'),
releaseObject = require('./releaseObject');
/**
* The base implementation of `_.uniq` without support for callback shorthands
* or `thisArg` binding.
*
* @private
* @param {Array} array The array to process.
* @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted.
* @param {Function} [callback] The function called per iteration.
* @returns {Array} Returns a duplicate-value-free array.
*/
function baseUniq(array, isSorted, callback) {
var index = -1,
indexOf = baseIndexOf,
length = array ? array.length : 0,
result = [];
var isLarge = !isSorted && length >= largeArraySize,
seen = (callback || isLarge) ? getArray() : result;
if (isLarge) {
var cache = createCache(seen);
indexOf = cacheIndexOf;
seen = cache;
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isSorted
? !index || seen[seen.length - 1] !== computed
: indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
if (isLarge) {
releaseArray(seen.array);
releaseObject(seen);
} else if (callback) {
releaseArray(seen);
}
return result;
}
module.exports = baseUniq;
| tspires/personal | zillow/node_modules/xml2js/node_modules/xmlbuilder/node_modules/lodash-node/modern/internals/baseUniq.js | JavaScript | mit | 2,014 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package service contains code for syncing cloud load balancers
// with the service registry.
package service // import "k8s.io/kubernetes/pkg/controller/service"
| humblec/external-storage | vendor/k8s.io/kubernetes/pkg/controller/service/doc.go | GO | apache-2.0 | 736 |
jQuery.extend(jQuery.fn.pickadate.defaults,{monthsFull:["janúar","febrúar","mars","apríl","maí","júní","júlí","ágúst","september","október","nóvember","desember"],monthsShort:["jan","feb","mar","apr","maí","jún","júl","ágú","sep","okt","nóv","des"],weekdaysFull:["sunnudagur","mánudagur","þriðjudagur","miðvikudagur","fimmtudagur","föstudagur","laugardagur"],weekdaysShort:["sun","mán","þri","mið","fim","fös","lau"],today:"Í dag",clear:"Hreinsa",firstDay:1,format:"dd. mmmm yyyy",formatSubmit:"yyyy/mm/dd"}),jQuery.extend(jQuery.fn.pickatime.defaults,{clear:"Hreinsa"}); | enketosurvey/mo | www/lib/pickadate.js-3.5.6/lib/compressed/translations/is_IS.js | JavaScript | apache-2.0 | 599 |
var browser_history_support = (window.history != null ? window.history.pushState : null) != null;
createTest('Nested route with the many children as a tokens, callbacks should yield historic params', {
'/a': {
'/:id': {
'/:id': function(a, b) {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''), a, b);
} else {
shared.fired.push(location.pathname, a, b);
}
}
}
}
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['/a/b/c', 'b', 'c']);
this.finish();
});
});
createTest('Nested route with the first child as a token, callback should yield a param', {
'/foo': {
'/:id': {
on: function(id) {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''), id);
} else {
shared.fired.push(location.pathname, id);
}
}
}
}
}, function() {
this.navigate('/foo/a', function() {
this.navigate('/foo/b/c', function() {
deepEqual(shared.fired, ['/foo/a', 'a']);
this.finish();
});
});
});
createTest('Nested route with the first child as a regexp, callback should yield a param', {
'/foo': {
'/(\\w+)': {
on: function(value) {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''), value);
} else {
shared.fired.push(location.pathname, value);
}
}
}
}
}, function() {
this.navigate('/foo/a', function() {
this.navigate('/foo/b/c', function() {
deepEqual(shared.fired, ['/foo/a', 'a']);
this.finish();
});
});
});
createTest('Nested route with the several regular expressions, callback should yield a param', {
'/a': {
'/(\\w+)': {
'/(\\w+)': function(a, b) {
shared.fired.push(a, b);
}
}
}
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['b', 'c']);
this.finish();
});
});
createTest('Single nested route with on member containing function value', {
'/a': {
'/b': {
on: function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}
}
}, function() {
this.navigate('/a/b', function() {
deepEqual(shared.fired, ['/a/b']);
this.finish();
});
});
createTest('Single non-nested route with on member containing function value', {
'/a/b': {
on: function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}
}, function() {
this.navigate('/a/b', function() {
deepEqual(shared.fired, ['/a/b']);
this.finish();
});
});
createTest('Single nested route with on member containing array of function values', {
'/a': {
'/b': {
on: [function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
},
function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}]
}
}
}, function() {
this.navigate('/a/b', function() {
deepEqual(shared.fired, ['/a/b', '/a/b']);
this.finish();
});
});
createTest('method should only fire once on the route.', {
'/a': {
'/b': {
once: function() {
shared.fired_count++;
}
}
}
}, function() {
this.navigate('/a/b', function() {
this.navigate('/a/b', function() {
this.navigate('/a/b', function() {
deepEqual(shared.fired_count, 1);
this.finish();
});
});
});
});
createTest('method should only fire once on the route, multiple nesting.', {
'/a': {
on: function() { shared.fired_count++; },
once: function() { shared.fired_count++; }
},
'/b': {
on: function() { shared.fired_count++; },
once: function() { shared.fired_count++; }
}
}, function() {
this.navigate('/a', function() {
this.navigate('/b', function() {
this.navigate('/a', function() {
this.navigate('/b', function() {
deepEqual(shared.fired_count, 6);
this.finish();
});
});
});
});
});
createTest('overlapping routes with tokens.', {
'/a/:b/c' : function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
},
'/a/:b/c/:d' : function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}, function() {
this.navigate('/a/b/c', function() {
this.navigate('/a/b/c/d', function() {
deepEqual(shared.fired, ['/a/b/c', '/a/b/c/d']);
this.finish();
});
});
});
// // //
// // // Recursion features
// // // ----------------------------------------------------------
createTest('Nested routes with no recursion', {
'/a': {
'/b': {
'/c': {
on: function c() {
shared.fired.push('c');
}
},
on: function b() {
shared.fired.push('b');
}
},
on: function a() {
shared.fired.push('a');
}
}
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['c']);
this.finish();
});
});
createTest('Nested routes with backward recursion', {
'/a': {
'/b': {
'/c': {
on: function c() {
shared.fired.push('c');
}
},
on: function b() {
shared.fired.push('b');
}
},
on: function a() {
shared.fired.push('a');
}
}
}, {
recurse: 'backward'
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['c', 'b', 'a']);
this.finish();
});
});
createTest('Breaking out of nested routes with backward recursion', {
'/a': {
'/:b': {
'/c': {
on: function c() {
shared.fired.push('c');
}
},
on: function b() {
shared.fired.push('b');
return false;
}
},
on: function a() {
shared.fired.push('a');
}
}
}, {
recurse: 'backward'
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['c', 'b']);
this.finish();
});
});
createTest('Nested routes with forward recursion', {
'/a': {
'/b': {
'/c': {
on: function c() {
shared.fired.push('c');
}
},
on: function b() {
shared.fired.push('b');
}
},
on: function a() {
shared.fired.push('a');
}
}
}, {
recurse: 'forward'
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['a', 'b', 'c']);
this.finish();
});
});
createTest('Nested routes with forward recursion, single route with an after event.', {
'/a': {
'/b': {
'/c': {
on: function c() {
shared.fired.push('c');
},
after: function() {
shared.fired.push('c-after');
}
},
on: function b() {
shared.fired.push('b');
}
},
on: function a() {
shared.fired.push('a');
}
}
}, {
recurse: 'forward'
}, function() {
this.navigate('/a/b/c', function() {
this.navigate('/a/b', function() {
deepEqual(shared.fired, ['a', 'b', 'c', 'c-after', 'a', 'b']);
this.finish();
});
});
});
createTest('Breaking out of nested routes with forward recursion', {
'/a': {
'/b': {
'/c': {
on: function c() {
shared.fired.push('c');
}
},
on: function b() {
shared.fired.push('b');
return false;
}
},
on: function a() {
shared.fired.push('a');
}
}
}, {
recurse: 'forward'
}, function() {
this.navigate('/a/b/c', function() {
deepEqual(shared.fired, ['a', 'b']);
this.finish();
});
});
//
// ABOVE IS WORKING
//
// //
// // Special Events
// // ----------------------------------------------------------
createTest('All global event should fire after every route', {
'/a': {
on: function a() {
shared.fired.push('a');
}
},
'/b': {
'/c': {
on: function a() {
shared.fired.push('a');
}
}
},
'/d': {
'/:e': {
on: function a() {
shared.fired.push('a');
}
}
}
}, {
after: function() {
shared.fired.push('b');
}
}, function() {
this.navigate('/a', function() {
this.navigate('/b/c', function() {
this.navigate('/d/e', function() {
deepEqual(shared.fired, ['a', 'b', 'a', 'b', 'a']);
this.finish();
});
});
});
});
createTest('Not found.', {
'/a': {
on: function a() {
shared.fired.push('a');
}
},
'/b': {
on: function a() {
shared.fired.push('b');
}
}
}, {
notfound: function() {
shared.fired.push('notfound');
}
}, function() {
this.navigate('/c', function() {
this.navigate('/d', function() {
deepEqual(shared.fired, ['notfound', 'notfound']);
this.finish();
});
});
});
createTest('On all.', {
'/a': {
on: function a() {
shared.fired.push('a');
}
},
'/b': {
on: function a() {
shared.fired.push('b');
}
}
}, {
on: function() {
shared.fired.push('c');
}
}, function() {
this.navigate('/a', function() {
this.navigate('/b', function() {
deepEqual(shared.fired, ['a', 'c', 'b', 'c']);
this.finish();
});
});
});
createTest('After all.', {
'/a': {
on: function a() {
shared.fired.push('a');
}
},
'/b': {
on: function a() {
shared.fired.push('b');
}
}
}, {
after: function() {
shared.fired.push('c');
}
}, function() {
this.navigate('/a', function() {
this.navigate('/b', function() {
deepEqual(shared.fired, ['a', 'c', 'b']);
this.finish();
});
});
});
createTest('resource object.', {
'/a': {
'/b/:c': {
on: 'f1'
},
on: 'f2'
},
'/d': {
on: ['f1', 'f2']
}
},
{
resource: {
f1: function (name){
shared.fired.push("f1-" + name);
},
f2: function (name){
shared.fired.push("f2");
}
}
}, function() {
this.navigate('/a/b/c', function() {
this.navigate('/d', function() {
deepEqual(shared.fired, ['f1-c', 'f1-undefined', 'f2']);
this.finish();
});
});
});
createTest('argument matching should be case agnostic', {
'/fooBar/:name': {
on: function(name) {
shared.fired.push("fooBar-" + name);
}
}
}, function() {
this.navigate('/fooBar/tesTing', function() {
deepEqual(shared.fired, ['fooBar-tesTing']);
this.finish();
});
});
createTest('sanity test', {
'/is/:this/:sane': {
on: function(a, b) {
shared.fired.push('yes ' + a + ' is ' + b);
}
},
'/': {
on: function() {
shared.fired.push('is there sanity?');
}
}
}, function() {
this.navigate('/is/there/sanity', function() {
deepEqual(shared.fired, ['yes there is sanity']);
this.finish();
});
});
createTest('`/` route should be navigable from the routing table', {
'/': {
on: function root() {
shared.fired.push('/');
}
},
'/:username': {
on: function afunc(username) {
shared.fired.push('/' + username);
}
}
}, function() {
this.navigate('/', function root() {
deepEqual(shared.fired, ['/']);
this.finish();
});
});
createTest('`/` route should not override a `/:token` route', {
'/': {
on: function root() {
shared.fired.push('/');
}
},
'/:username': {
on: function afunc(username) {
shared.fired.push('/' + username);
}
}
}, function() {
this.navigate('/a', function afunc() {
deepEqual(shared.fired, ['/a']);
this.finish();
});
});
createTest('should accept the root as a token.', {
'/:a': {
on: function root() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}
}, function() {
this.navigate('/a', function root() {
deepEqual(shared.fired, ['/a']);
this.finish();
});
});
createTest('routes should allow wildcards.', {
'/:a/b*d': {
on: function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}
}, function() {
this.navigate('/a/bcd', function root() {
deepEqual(shared.fired, ['/a/bcd']);
this.finish();
});
});
createTest('functions should have |this| context of the router instance.', {
'/': {
on: function root() {
shared.fired.push(!!this.routes);
}
}
}, function() {
this.navigate('/', function root() {
deepEqual(shared.fired, [true]);
this.finish();
});
});
createTest('setRoute with a single parameter should change location correctly', {
'/bonk': {
on: function() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(window.location.pathname);
}
}
}
}, function() {
var self = this;
this.router.setRoute('/bonk');
setTimeout(function() {
deepEqual(shared.fired, ['/bonk']);
self.finish();
}, 14)
});
createTest('route should accept _ and . within parameters', {
'/:a': {
on: function root() {
if (!browser_history_support) {
shared.fired.push(location.hash.replace(/^#/, ''));
} else {
shared.fired.push(location.pathname);
}
}
}
}, function() {
this.navigate('/a_complex_route.co.uk', function root() {
deepEqual(shared.fired, ['/a_complex_route.co.uk']);
this.finish();
});
});
| WAPMADRID/server | wapmadrid/node_modules/forever/node_modules/flatiron/node_modules/director/test/browser/html5-routes-test.js | JavaScript | gpl-2.0 | 14,089 |
/// <reference types="easeljs"/>
var target = new createjs.DisplayObject();
// source : http://www.createjs.com/Docs/TweenJS/modules/TweenJS.html
// Chainable modules :
target.alpha = 1;
createjs.Tween.get(target).wait(500, false).to({ alpha: 0, visible: false }, 1000).call(onComplete);
function onComplete() {
//Tween complete
} | zuzusik/DefinitelyTyped | types/tweenjs/tweenjs-tests.ts | TypeScript | mit | 337 |
#ifndef BOOST_MPL_LOWER_BOUND_HPP_INCLUDED
#define BOOST_MPL_LOWER_BOUND_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: lower_bound.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#include <boost/mpl/less.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610))
# define BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL
#endif
#if !defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL)
# include <boost/mpl/minus.hpp>
# include <boost/mpl/divides.hpp>
# include <boost/mpl/size.hpp>
# include <boost/mpl/advance.hpp>
# include <boost/mpl/begin_end.hpp>
# include <boost/mpl/long.hpp>
# include <boost/mpl/eval_if.hpp>
# include <boost/mpl/prior.hpp>
# include <boost/mpl/deref.hpp>
# include <boost/mpl/apply.hpp>
# include <boost/mpl/aux_/value_wknd.hpp>
#else
# include <boost/mpl/not.hpp>
# include <boost/mpl/find.hpp>
# include <boost/mpl/bind.hpp>
#endif
#include <boost/config.hpp>
namespace boost { namespace mpl {
#if defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL)
// agurt 23/oct/02: has a wrong complexity etc., but at least it works
// feel free to contribute a better implementation!
template<
typename BOOST_MPL_AUX_NA_PARAM(Sequence)
, typename BOOST_MPL_AUX_NA_PARAM(T)
, typename Predicate = less<>
, typename pred_ = typename lambda<Predicate>::type
>
struct lower_bound
: find_if< Sequence, bind1< not_<>, bind2<pred_,_,T> > >
{
};
#else
namespace aux {
template<
typename Distance
, typename Predicate
, typename T
, typename DeferredIterator
>
struct lower_bound_step_impl;
template<
typename Distance
, typename Predicate
, typename T
, typename DeferredIterator
>
struct lower_bound_step
{
typedef typename eval_if<
Distance
, lower_bound_step_impl<Distance,Predicate,T,DeferredIterator>
, DeferredIterator
>::type type;
};
template<
typename Distance
, typename Predicate
, typename T
, typename DeferredIterator
>
struct lower_bound_step_impl
{
typedef typename divides< Distance, long_<2> >::type offset_;
typedef typename DeferredIterator::type iter_;
typedef typename advance< iter_,offset_ >::type middle_;
typedef typename apply2<
Predicate
, typename deref<middle_>::type
, T
>::type cond_;
typedef typename prior< minus< Distance, offset_> >::type step_;
typedef lower_bound_step< offset_,Predicate,T,DeferredIterator > step_forward_;
typedef lower_bound_step< step_,Predicate,T,next<middle_> > step_backward_;
typedef typename eval_if<
cond_
, step_backward_
, step_forward_
>::type type;
};
} // namespace aux
template<
typename BOOST_MPL_AUX_NA_PARAM(Sequence)
, typename BOOST_MPL_AUX_NA_PARAM(T)
, typename Predicate = less<>
>
struct lower_bound
{
private:
typedef typename lambda<Predicate>::type pred_;
typedef typename size<Sequence>::type size_;
public:
typedef typename aux::lower_bound_step<
size_,pred_,T,begin<Sequence>
>::type type;
};
#endif // BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL
BOOST_MPL_AUX_NA_SPEC(2, lower_bound)
}}
#endif // BOOST_MPL_LOWER_BOUND_HPP_INCLUDED
| hpl1nk/nonamegame | xray/SDK/include/boost/mpl/lower_bound.hpp | C++ | gpl-3.0 | 3,713 |
/**
* @license AngularJS v1.0.6
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngResource
* @description
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* # Installation
* To use $resource make sure you have included the `angular-resource.js` that comes in Angular
* package. You can also find this file on Google CDN, bower as well as at
* {@link http://code.angularjs.org/ code.angularjs.org}.
*
* Finally load the module in your application:
*
* angular.module('app', ['ngResource']);
*
* and you are ready to get started!
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`. If you are using a URL with a port number (e.g.
* `http://example.com:8080/api`), you'll need to escape the colon character before the port
* number, like this: `$resource('http://example.com\\:8080/api')`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?},
* action2: {method:?, params:?, isArray:?},
* ...}
*
* Where:
*
* - `action` – {string} – The name of action. This name becomes the name of the method on your
* resource object.
* - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSONP`
* - `params` – {object=} – Optional set of pre-bound parameters for this action.
* - isArray – {boolean=} – If true then the returned object for this action is an array, see
* `returns` section.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
* read, update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div ng-repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction,
getter = function(obj, path) {
return $parse(path)(obj);
};
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) {
urlParams[param] = true;
}
});
this.template = template.replace(/\\:/g, ':');
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
val,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
if (angular.isDefined(val) && val !== null) {
encodedVal = encodeUriSegment(val);
url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1");
} else {
url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match,
leadingSlashes, tail) {
if (tail.charAt(0) == '/') {
return tail;
} else {
return leadingSlashes + tail;
}
});
}
});
url = url.replace(/\/?#$/, '');
var query = [];
forEach(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
query.sort();
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data, actionParams){
var ids = {};
actionParams = extend({}, paramDefaults, actionParams);
forEach(actionParams, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name) {
action.method = angular.uppercase(action.method);
var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH';
Resource[name] = function(a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
$http({
method: action.method,
url: route.url(extend({}, extractParams(data, action.params || {}), params)),
data: data
}).then(function(response) {
var data = response.data;
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
(success||noop)(value, response.headers);
}, error);
return value;
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = hasBody ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
Resource.bind = function(additionalParamDefaults){
return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
return Resource;
}
return ResourceFactory;
}]);
})(window, window.angular);
| bacardi55/b-55-log | web/jocs/components/angular-resource/angular-resource.js | JavaScript | mit | 17,163 |
/*
* CoreChip-sz SR9700 one chip USB 1.1 Ethernet Devices
*
* Author : Liu Junliang <liujunliang_ljl@163.com>
*
* Based on dm9601.c
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/stddef.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/crc32.h>
#include <linux/usb/usbnet.h>
#include "sr9700.h"
static int sr_read(struct usbnet *dev, u8 reg, u16 length, void *data)
{
int err;
err = usbnet_read_cmd(dev, SR_RD_REGS, SR_REQ_RD_REG, 0, reg, data,
length);
if ((err != length) && (err >= 0))
err = -EINVAL;
return err;
}
static int sr_write(struct usbnet *dev, u8 reg, u16 length, void *data)
{
int err;
err = usbnet_write_cmd(dev, SR_WR_REGS, SR_REQ_WR_REG, 0, reg, data,
length);
if ((err >= 0) && (err < length))
err = -EINVAL;
return err;
}
static int sr_read_reg(struct usbnet *dev, u8 reg, u8 *value)
{
return sr_read(dev, reg, 1, value);
}
static int sr_write_reg(struct usbnet *dev, u8 reg, u8 value)
{
return usbnet_write_cmd(dev, SR_WR_REGS, SR_REQ_WR_REG,
value, reg, NULL, 0);
}
static void sr_write_async(struct usbnet *dev, u8 reg, u16 length,
const void *data)
{
usbnet_write_cmd_async(dev, SR_WR_REGS, SR_REQ_WR_REG,
0, reg, data, length);
}
static void sr_write_reg_async(struct usbnet *dev, u8 reg, u8 value)
{
usbnet_write_cmd_async(dev, SR_WR_REGS, SR_REQ_WR_REG,
value, reg, NULL, 0);
}
static int wait_phy_eeprom_ready(struct usbnet *dev, int phy)
{
int i;
for (i = 0; i < SR_SHARE_TIMEOUT; i++) {
u8 tmp = 0;
int ret;
udelay(1);
ret = sr_read_reg(dev, SR_EPCR, &tmp);
if (ret < 0)
return ret;
/* ready */
if (!(tmp & EPCR_ERRE))
return 0;
}
netdev_err(dev->net, "%s write timed out!\n", phy ? "phy" : "eeprom");
return -EIO;
}
static int sr_share_read_word(struct usbnet *dev, int phy, u8 reg,
__le16 *value)
{
int ret;
mutex_lock(&dev->phy_mutex);
sr_write_reg(dev, SR_EPAR, phy ? (reg | EPAR_PHY_ADR) : reg);
sr_write_reg(dev, SR_EPCR, phy ? (EPCR_EPOS | EPCR_ERPRR) : EPCR_ERPRR);
ret = wait_phy_eeprom_ready(dev, phy);
if (ret < 0)
goto out_unlock;
sr_write_reg(dev, SR_EPCR, 0x0);
ret = sr_read(dev, SR_EPDR, 2, value);
netdev_dbg(dev->net, "read shared %d 0x%02x returned 0x%04x, %d\n",
phy, reg, *value, ret);
out_unlock:
mutex_unlock(&dev->phy_mutex);
return ret;
}
static int sr_share_write_word(struct usbnet *dev, int phy, u8 reg,
__le16 value)
{
int ret;
mutex_lock(&dev->phy_mutex);
ret = sr_write(dev, SR_EPDR, 2, &value);
if (ret < 0)
goto out_unlock;
sr_write_reg(dev, SR_EPAR, phy ? (reg | EPAR_PHY_ADR) : reg);
sr_write_reg(dev, SR_EPCR, phy ? (EPCR_WEP | EPCR_EPOS | EPCR_ERPRW) :
(EPCR_WEP | EPCR_ERPRW));
ret = wait_phy_eeprom_ready(dev, phy);
if (ret < 0)
goto out_unlock;
sr_write_reg(dev, SR_EPCR, 0x0);
out_unlock:
mutex_unlock(&dev->phy_mutex);
return ret;
}
static int sr_read_eeprom_word(struct usbnet *dev, u8 offset, void *value)
{
return sr_share_read_word(dev, 0, offset, value);
}
static int sr9700_get_eeprom_len(struct net_device *netdev)
{
return SR_EEPROM_LEN;
}
static int sr9700_get_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *data)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 *buf = (__le16 *)data;
int ret = 0;
int i;
/* access is 16bit */
if ((eeprom->offset & 0x01) || (eeprom->len & 0x01))
return -EINVAL;
for (i = 0; i < eeprom->len / 2; i++) {
ret = sr_read_eeprom_word(dev, eeprom->offset / 2 + i, buf + i);
if (ret < 0)
break;
}
return ret;
}
static int sr_mdio_read(struct net_device *netdev, int phy_id, int loc)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res;
int rc = 0;
if (phy_id) {
netdev_dbg(netdev, "Only internal phy supported\n");
return 0;
}
/* Access NSR_LINKST bit for link status instead of MII_BMSR */
if (loc == MII_BMSR) {
u8 value;
sr_read_reg(dev, SR_NSR, &value);
if (value & NSR_LINKST)
rc = 1;
}
sr_share_read_word(dev, 1, loc, &res);
if (rc == 1)
res = le16_to_cpu(res) | BMSR_LSTATUS;
else
res = le16_to_cpu(res) & ~BMSR_LSTATUS;
netdev_dbg(netdev, "sr_mdio_read() phy_id=0x%02x, loc=0x%02x, returns=0x%04x\n",
phy_id, loc, res);
return res;
}
static void sr_mdio_write(struct net_device *netdev, int phy_id, int loc,
int val)
{
struct usbnet *dev = netdev_priv(netdev);
__le16 res = cpu_to_le16(val);
if (phy_id) {
netdev_dbg(netdev, "Only internal phy supported\n");
return;
}
netdev_dbg(netdev, "sr_mdio_write() phy_id=0x%02x, loc=0x%02x, val=0x%04x\n",
phy_id, loc, val);
sr_share_write_word(dev, 1, loc, res);
}
static u32 sr9700_get_link(struct net_device *netdev)
{
struct usbnet *dev = netdev_priv(netdev);
u8 value = 0;
int rc = 0;
/* Get the Link Status directly */
sr_read_reg(dev, SR_NSR, &value);
if (value & NSR_LINKST)
rc = 1;
return rc;
}
static int sr9700_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd)
{
struct usbnet *dev = netdev_priv(netdev);
return generic_mii_ioctl(&dev->mii, if_mii(rq), cmd, NULL);
}
static const struct ethtool_ops sr9700_ethtool_ops = {
.get_drvinfo = usbnet_get_drvinfo,
.get_link = sr9700_get_link,
.get_msglevel = usbnet_get_msglevel,
.set_msglevel = usbnet_set_msglevel,
.get_eeprom_len = sr9700_get_eeprom_len,
.get_eeprom = sr9700_get_eeprom,
.nway_reset = usbnet_nway_reset,
.get_link_ksettings = usbnet_get_link_ksettings_mii,
.set_link_ksettings = usbnet_set_link_ksettings_mii,
};
static void sr9700_set_multicast(struct net_device *netdev)
{
struct usbnet *dev = netdev_priv(netdev);
/* We use the 20 byte dev->data for our 8 byte filter buffer
* to avoid allocating memory that is tricky to free later
*/
u8 *hashes = (u8 *)&dev->data;
/* rx_ctl setting : enable, disable_long, disable_crc */
u8 rx_ctl = RCR_RXEN | RCR_DIS_CRC | RCR_DIS_LONG;
memset(hashes, 0x00, SR_MCAST_SIZE);
/* broadcast address */
hashes[SR_MCAST_SIZE - 1] |= SR_MCAST_ADDR_FLAG;
if (netdev->flags & IFF_PROMISC) {
rx_ctl |= RCR_PRMSC;
} else if (netdev->flags & IFF_ALLMULTI ||
netdev_mc_count(netdev) > SR_MCAST_MAX) {
rx_ctl |= RCR_RUNT;
} else if (!netdev_mc_empty(netdev)) {
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, netdev) {
u32 crc = ether_crc(ETH_ALEN, ha->addr) >> 26;
hashes[crc >> 3] |= 1 << (crc & 0x7);
}
}
sr_write_async(dev, SR_MAR, SR_MCAST_SIZE, hashes);
sr_write_reg_async(dev, SR_RCR, rx_ctl);
}
static int sr9700_set_mac_address(struct net_device *netdev, void *p)
{
struct usbnet *dev = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data)) {
netdev_err(netdev, "not setting invalid mac address %pM\n",
addr->sa_data);
return -EINVAL;
}
eth_hw_addr_set(netdev, addr->sa_data);
sr_write_async(dev, SR_PAR, 6, netdev->dev_addr);
return 0;
}
static const struct net_device_ops sr9700_netdev_ops = {
.ndo_open = usbnet_open,
.ndo_stop = usbnet_stop,
.ndo_start_xmit = usbnet_start_xmit,
.ndo_tx_timeout = usbnet_tx_timeout,
.ndo_change_mtu = usbnet_change_mtu,
.ndo_get_stats64 = dev_get_tstats64,
.ndo_validate_addr = eth_validate_addr,
.ndo_eth_ioctl = sr9700_ioctl,
.ndo_set_rx_mode = sr9700_set_multicast,
.ndo_set_mac_address = sr9700_set_mac_address,
};
static int sr9700_bind(struct usbnet *dev, struct usb_interface *intf)
{
struct net_device *netdev;
struct mii_if_info *mii;
u8 addr[ETH_ALEN];
int ret;
ret = usbnet_get_endpoints(dev, intf);
if (ret)
goto out;
netdev = dev->net;
netdev->netdev_ops = &sr9700_netdev_ops;
netdev->ethtool_ops = &sr9700_ethtool_ops;
netdev->hard_header_len += SR_TX_OVERHEAD;
dev->hard_mtu = netdev->mtu + netdev->hard_header_len;
/* bulkin buffer is preferably not less than 3K */
dev->rx_urb_size = 3072;
mii = &dev->mii;
mii->dev = netdev;
mii->mdio_read = sr_mdio_read;
mii->mdio_write = sr_mdio_write;
mii->phy_id_mask = 0x1f;
mii->reg_num_mask = 0x1f;
sr_write_reg(dev, SR_NCR, NCR_RST);
udelay(20);
/* read MAC
* After Chip Power on, the Chip will reload the MAC from
* EEPROM automatically to PAR. In case there is no EEPROM externally,
* a default MAC address is stored in PAR for making chip work properly.
*/
if (sr_read(dev, SR_PAR, ETH_ALEN, addr) < 0) {
netdev_err(netdev, "Error reading MAC address\n");
ret = -ENODEV;
goto out;
}
eth_hw_addr_set(netdev, addr);
/* power up and reset phy */
sr_write_reg(dev, SR_PRR, PRR_PHY_RST);
/* at least 10ms, here 20ms for safe */
msleep(20);
sr_write_reg(dev, SR_PRR, 0);
/* at least 1ms, here 2ms for reading right register */
udelay(2 * 1000);
/* receive broadcast packets */
sr9700_set_multicast(netdev);
sr_mdio_write(netdev, mii->phy_id, MII_BMCR, BMCR_RESET);
sr_mdio_write(netdev, mii->phy_id, MII_ADVERTISE, ADVERTISE_ALL |
ADVERTISE_CSMA | ADVERTISE_PAUSE_CAP);
mii_nway_restart(mii);
out:
return ret;
}
static int sr9700_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
{
struct sk_buff *sr_skb;
int len;
/* skb content (packets) format :
* p0 p1 p2 ...... pm
* / \
* / \
* / \
* / \
* p0b0 p0b1 p0b2 p0b3 ...... p0b(n-4) p0b(n-3)...p0bn
*
* p0 : packet 0
* p0b0 : packet 0 byte 0
*
* b0: rx status
* b1: packet length (incl crc) low
* b2: packet length (incl crc) high
* b3..n-4: packet data
* bn-3..bn: ethernet packet crc
*/
if (unlikely(skb->len < SR_RX_OVERHEAD)) {
netdev_err(dev->net, "unexpected tiny rx frame\n");
return 0;
}
/* one skb may contains multiple packets */
while (skb->len > SR_RX_OVERHEAD) {
if (skb->data[0] != 0x40)
return 0;
/* ignore the CRC length */
len = (skb->data[1] | (skb->data[2] << 8)) - 4;
if (len > ETH_FRAME_LEN)
return 0;
/* the last packet of current skb */
if (skb->len == (len + SR_RX_OVERHEAD)) {
skb_pull(skb, 3);
skb->len = len;
skb_set_tail_pointer(skb, len);
skb->truesize = len + sizeof(struct sk_buff);
return 2;
}
/* skb_clone is used for address align */
sr_skb = skb_clone(skb, GFP_ATOMIC);
if (!sr_skb)
return 0;
sr_skb->len = len;
sr_skb->data = skb->data + 3;
skb_set_tail_pointer(sr_skb, len);
sr_skb->truesize = len + sizeof(struct sk_buff);
usbnet_skb_return(dev, sr_skb);
skb_pull(skb, len + SR_RX_OVERHEAD);
}
return 0;
}
static struct sk_buff *sr9700_tx_fixup(struct usbnet *dev, struct sk_buff *skb,
gfp_t flags)
{
int len;
/* SR9700 can only send out one ethernet packet at once.
*
* b0 b1 b2 b3 ...... b(n-4) b(n-3)...bn
*
* b0: rx status
* b1: packet length (incl crc) low
* b2: packet length (incl crc) high
* b3..n-4: packet data
* bn-3..bn: ethernet packet crc
*/
len = skb->len;
if (skb_cow_head(skb, SR_TX_OVERHEAD)) {
dev_kfree_skb_any(skb);
return NULL;
}
__skb_push(skb, SR_TX_OVERHEAD);
/* usbnet adds padding if length is a multiple of packet size
* if so, adjust length value in header
*/
if ((skb->len % dev->maxpacket) == 0)
len++;
skb->data[0] = len;
skb->data[1] = len >> 8;
return skb;
}
static void sr9700_status(struct usbnet *dev, struct urb *urb)
{
int link;
u8 *buf;
/* format:
b0: net status
b1: tx status 1
b2: tx status 2
b3: rx status
b4: rx overflow
b5: rx count
b6: tx count
b7: gpr
*/
if (urb->actual_length < 8)
return;
buf = urb->transfer_buffer;
link = !!(buf[0] & 0x40);
if (netif_carrier_ok(dev->net) != link) {
usbnet_link_change(dev, link, 1);
netdev_dbg(dev->net, "Link Status is: %d\n", link);
}
}
static int sr9700_link_reset(struct usbnet *dev)
{
struct ethtool_cmd ecmd;
mii_check_media(&dev->mii, 1, 1);
mii_ethtool_gset(&dev->mii, &ecmd);
netdev_dbg(dev->net, "link_reset() speed: %d duplex: %d\n",
ecmd.speed, ecmd.duplex);
return 0;
}
static const struct driver_info sr9700_driver_info = {
.description = "CoreChip SR9700 USB Ethernet",
.flags = FLAG_ETHER,
.bind = sr9700_bind,
.rx_fixup = sr9700_rx_fixup,
.tx_fixup = sr9700_tx_fixup,
.status = sr9700_status,
.link_reset = sr9700_link_reset,
.reset = sr9700_link_reset,
};
static const struct usb_device_id products[] = {
{
USB_DEVICE(0x0fe6, 0x9700), /* SR9700 device */
.driver_info = (unsigned long)&sr9700_driver_info,
},
{}, /* END */
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver sr9700_usb_driver = {
.name = "sr9700",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(sr9700_usb_driver);
MODULE_AUTHOR("liujl <liujunliang_ljl@163.com>");
MODULE_DESCRIPTION("SR9700 one chip USB 1.1 USB to Ethernet device from http://www.corechip-sz.com/");
MODULE_LICENSE("GPL");
| mpe/powerpc | drivers/net/usb/sr9700.c | C | gpl-2.0 | 13,255 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Allows the execution of relational queries, including those expressed in SQL using Spark.
*/
package org.apache.spark.sql.api.java;
| esi-mineset/spark | sql/core/src/main/java/org/apache/spark/sql/api/java/package-info.java | Java | apache-2.0 | 942 |
/*
* linux/arch/sh/boards/magicpanel/setup.c
*
* Copyright (C) 2007 Markus Brunner, Mark Jonas
*
* Magic Panel Release 2 board setup
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/smsc911x.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/map.h>
#include <mach/magicpanelr2.h>
#include <asm/heartbeat.h>
#include <cpu/sh7720.h>
#define LAN9115_READY (__raw_readl(0xA8000084UL) & 0x00000001UL)
/* Wait until reset finished. Timeout is 100ms. */
static int __init ethernet_reset_finished(void)
{
int i;
if (LAN9115_READY)
return 1;
for (i = 0; i < 10; ++i) {
mdelay(10);
if (LAN9115_READY)
return 1;
}
return 0;
}
static void __init reset_ethernet(void)
{
/* PMDR: LAN_RESET=on */
CLRBITS_OUTB(0x10, PORT_PMDR);
udelay(200);
/* PMDR: LAN_RESET=off */
SETBITS_OUTB(0x10, PORT_PMDR);
}
static void __init setup_chip_select(void)
{
/* CS2: LAN (0x08000000 - 0x0bffffff) */
/* no idle cycles, normal space, 8 bit data bus */
__raw_writel(0x36db0400, CS2BCR);
/* (SW:1.5 WR:3 HW:1.5), ext. wait */
__raw_writel(0x000003c0, CS2WCR);
/* CS4: CAN1 (0xb0000000 - 0xb3ffffff) */
/* no idle cycles, normal space, 8 bit data bus */
__raw_writel(0x00000200, CS4BCR);
/* (SW:1.5 WR:3 HW:1.5), ext. wait */
__raw_writel(0x00100981, CS4WCR);
/* CS5a: CAN2 (0xb4000000 - 0xb5ffffff) */
/* no idle cycles, normal space, 8 bit data bus */
__raw_writel(0x00000200, CS5ABCR);
/* (SW:1.5 WR:3 HW:1.5), ext. wait */
__raw_writel(0x00100981, CS5AWCR);
/* CS5b: CAN3 (0xb6000000 - 0xb7ffffff) */
/* no idle cycles, normal space, 8 bit data bus */
__raw_writel(0x00000200, CS5BBCR);
/* (SW:1.5 WR:3 HW:1.5), ext. wait */
__raw_writel(0x00100981, CS5BWCR);
/* CS6a: Rotary (0xb8000000 - 0xb9ffffff) */
/* no idle cycles, normal space, 8 bit data bus */
__raw_writel(0x00000200, CS6ABCR);
/* (SW:1.5 WR:3 HW:1.5), no ext. wait */
__raw_writel(0x001009C1, CS6AWCR);
}
static void __init setup_port_multiplexing(void)
{
/* A7 GPO(LED8); A6 GPO(LED7); A5 GPO(LED6); A4 GPO(LED5);
* A3 GPO(LED4); A2 GPO(LED3); A1 GPO(LED2); A0 GPO(LED1);
*/
__raw_writew(0x5555, PORT_PACR); /* 01 01 01 01 01 01 01 01 */
/* B7 GPO(RST4); B6 GPO(RST3); B5 GPO(RST2); B4 GPO(RST1);
* B3 GPO(PB3); B2 GPO(PB2); B1 GPO(PB1); B0 GPO(PB0);
*/
__raw_writew(0x5555, PORT_PBCR); /* 01 01 01 01 01 01 01 01 */
/* C7 GPO(PC7); C6 GPO(PC6); C5 GPO(PC5); C4 GPO(PC4);
* C3 LCD_DATA3; C2 LCD_DATA2; C1 LCD_DATA1; C0 LCD_DATA0;
*/
__raw_writew(0x5500, PORT_PCCR); /* 01 01 01 01 00 00 00 00 */
/* D7 GPO(PD7); D6 GPO(PD6); D5 GPO(PD5); D4 GPO(PD4);
* D3 GPO(PD3); D2 GPO(PD2); D1 GPO(PD1); D0 GPO(PD0);
*/
__raw_writew(0x5555, PORT_PDCR); /* 01 01 01 01 01 01 01 01 */
/* E7 (x); E6 GPI(nu); E5 GPI(nu); E4 LCD_M_DISP;
* E3 LCD_CL1; E2 LCD_CL2; E1 LCD_DON; E0 LCD_FLM;
*/
__raw_writew(0x3C00, PORT_PECR); /* 00 11 11 00 00 00 00 00 */
/* F7 (x); F6 DA1(VLCD); F5 DA0(nc); F4 AN3;
* F3 AN2(MID_AD); F2 AN1(EARTH_AD); F1 AN0(TEMP); F0 GPI+(nc);
*/
__raw_writew(0x0002, PORT_PFCR); /* 00 00 00 00 00 00 00 10 */
/* G7 (x); G6 IRQ5(TOUCH_BUSY); G5 IRQ4(TOUCH_IRQ); G4 GPI(KEY2);
* G3 GPI(KEY1); G2 GPO(LED11); G1 GPO(LED10); G0 GPO(LED9);
*/
__raw_writew(0x03D5, PORT_PGCR); /* 00 00 00 11 11 01 01 01 */
/* H7 (x); H6 /RAS(BRAS); H5 /CAS(BCAS); H4 CKE(BCKE);
* H3 GPO(EARTH_OFF); H2 GPO(EARTH_TEST); H1 USB2_PWR; H0 USB1_PWR;
*/
__raw_writew(0x0050, PORT_PHCR); /* 00 00 00 00 01 01 00 00 */
/* J7 (x); J6 AUDCK; J5 ASEBRKAK; J4 AUDATA3;
* J3 AUDATA2; J2 AUDATA1; J1 AUDATA0; J0 AUDSYNC;
*/
__raw_writew(0x0000, PORT_PJCR); /* 00 00 00 00 00 00 00 00 */
/* K7 (x); K6 (x); K5 (x); K4 (x);
* K3 PINT7(/PWR2); K2 PINT6(/PWR1); K1 PINT5(nu); K0 PINT4(FLASH_READY)
*/
__raw_writew(0x00FF, PORT_PKCR); /* 00 00 00 00 11 11 11 11 */
/* L7 TRST; L6 TMS; L5 TDO; L4 TDI;
* L3 TCK; L2 (x); L1 (x); L0 (x);
*/
__raw_writew(0x0000, PORT_PLCR); /* 00 00 00 00 00 00 00 00 */
/* M7 GPO(CURRENT_SINK); M6 GPO(PWR_SWITCH); M5 GPO(LAN_SPEED);
* M4 GPO(LAN_RESET); M3 GPO(BUZZER); M2 GPO(LCD_BL);
* M1 CS5B(CAN3_CS); M0 GPI+(nc);
*/
__raw_writew(0x5552, PORT_PMCR); /* 01 01 01 01 01 01 00 10 */
/* CURRENT_SINK=off, PWR_SWITCH=off, LAN_SPEED=100MBit,
* LAN_RESET=off, BUZZER=off, LCD_BL=off
*/
#if CONFIG_SH_MAGIC_PANEL_R2_VERSION == 2
__raw_writeb(0x30, PORT_PMDR);
#elif CONFIG_SH_MAGIC_PANEL_R2_VERSION == 3
__raw_writeb(0xF0, PORT_PMDR);
#else
#error Unknown revision of PLATFORM_MP_R2
#endif
/* P7 (x); P6 (x); P5 (x);
* P4 GPO(nu); P3 IRQ3(LAN_IRQ); P2 IRQ2(CAN3_IRQ);
* P1 IRQ1(CAN2_IRQ); P0 IRQ0(CAN1_IRQ)
*/
__raw_writew(0x0100, PORT_PPCR); /* 00 00 00 01 00 00 00 00 */
__raw_writeb(0x10, PORT_PPDR);
/* R7 A25; R6 A24; R5 A23; R4 A22;
* R3 A21; R2 A20; R1 A19; R0 A0;
*/
gpio_request(GPIO_FN_A25, NULL);
gpio_request(GPIO_FN_A24, NULL);
gpio_request(GPIO_FN_A23, NULL);
gpio_request(GPIO_FN_A22, NULL);
gpio_request(GPIO_FN_A21, NULL);
gpio_request(GPIO_FN_A20, NULL);
gpio_request(GPIO_FN_A19, NULL);
gpio_request(GPIO_FN_A0, NULL);
/* S7 (x); S6 (x); S5 (x); S4 GPO(EEPROM_CS2);
* S3 GPO(EEPROM_CS1); S2 SIOF0_TXD; S1 SIOF0_RXD; S0 SIOF0_SCK;
*/
__raw_writew(0x0140, PORT_PSCR); /* 00 00 00 01 01 00 00 00 */
/* T7 (x); T6 (x); T5 (x); T4 COM1_CTS;
* T3 COM1_RTS; T2 COM1_TXD; T1 COM1_RXD; T0 GPO(WDOG)
*/
__raw_writew(0x0001, PORT_PTCR); /* 00 00 00 00 00 00 00 01 */
/* U7 (x); U6 (x); U5 (x); U4 GPI+(/AC_FAULT);
* U3 GPO(TOUCH_CS); U2 TOUCH_TXD; U1 TOUCH_RXD; U0 TOUCH_SCK;
*/
__raw_writew(0x0240, PORT_PUCR); /* 00 00 00 10 01 00 00 00 */
/* V7 (x); V6 (x); V5 (x); V4 GPO(MID2);
* V3 GPO(MID1); V2 CARD_TxD; V1 CARD_RxD; V0 GPI+(/BAT_FAULT);
*/
__raw_writew(0x0142, PORT_PVCR); /* 00 00 00 01 01 00 00 10 */
}
static void __init mpr2_setup(char **cmdline_p)
{
/* set Pin Select Register A:
* /PCC_CD1, /PCC_CD2, PCC_BVD1, PCC_BVD2,
* /IOIS16, IRQ4, IRQ5, USB1d_SUSPEND
*/
__raw_writew(0xAABC, PORT_PSELA);
/* set Pin Select Register B:
* /SCIF0_RTS, /SCIF0_CTS, LCD_VCPWC,
* LCD_VEPWC, IIC_SDA, IIC_SCL, Reserved
*/
__raw_writew(0x3C00, PORT_PSELB);
/* set Pin Select Register C:
* SIOF1_SCK, SIOF1_RxD, SCIF1_RxD, SCIF1_TxD, Reserved
*/
__raw_writew(0x0000, PORT_PSELC);
/* set Pin Select Register D: Reserved, SIOF1_TxD, Reserved, SIOF1_MCLK,
* Reserved, SIOF1_SYNC, Reserved, SCIF1_SCK, Reserved
*/
__raw_writew(0x0000, PORT_PSELD);
/* set USB TxRx Control: Reserved, DRV, Reserved, USB_TRANS, USB_SEL */
__raw_writew(0x0101, PORT_UTRCTL);
/* set USB Clock Control: USSCS, USSTB, Reserved (HighByte always A5) */
__raw_writew(0xA5C0, PORT_UCLKCR_W);
setup_chip_select();
setup_port_multiplexing();
reset_ethernet();
printk(KERN_INFO "Magic Panel Release 2 A.%i\n",
CONFIG_SH_MAGIC_PANEL_R2_VERSION);
if (ethernet_reset_finished() == 0)
printk(KERN_WARNING "Ethernet not ready\n");
}
static struct resource smsc911x_resources[] = {
[0] = {
.start = 0xa8000000,
.end = 0xabffffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 35,
.end = 35,
.flags = IORESOURCE_IRQ,
},
};
static struct smsc911x_platform_config smsc911x_config = {
.phy_interface = PHY_INTERFACE_MODE_MII,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = SMSC911X_USE_32BIT,
};
static struct platform_device smsc911x_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smsc911x_resources),
.resource = smsc911x_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
static struct resource heartbeat_resources[] = {
[0] = {
.start = PA_LED,
.end = PA_LED,
.flags = IORESOURCE_MEM,
},
};
static struct heartbeat_data heartbeat_data = {
.flags = HEARTBEAT_INVERTED,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.dev = {
.platform_data = &heartbeat_data,
},
.num_resources = ARRAY_SIZE(heartbeat_resources),
.resource = heartbeat_resources,
};
static struct mtd_partition mpr2_partitions[] = {
/* Reserved for bootloader, read-only */
{
.name = "Bootloader",
.offset = 0x00000000UL,
.size = MPR2_MTD_BOOTLOADER_SIZE,
.mask_flags = MTD_WRITEABLE,
},
/* Reserved for kernel image */
{
.name = "Kernel",
.offset = MTDPART_OFS_NXTBLK,
.size = MPR2_MTD_KERNEL_SIZE,
},
/* Rest is used for Flash FS */
{
.name = "Flash_FS",
.offset = MTDPART_OFS_NXTBLK,
.size = MTDPART_SIZ_FULL,
}
};
static struct physmap_flash_data flash_data = {
.parts = mpr2_partitions,
.nr_parts = ARRAY_SIZE(mpr2_partitions),
.width = 2,
};
static struct resource flash_resource = {
.start = 0x00000000,
.end = 0x2000000UL,
.flags = IORESOURCE_MEM,
};
static struct platform_device flash_device = {
.name = "physmap-flash",
.id = -1,
.resource = &flash_resource,
.num_resources = 1,
.dev = {
.platform_data = &flash_data,
},
};
/*
* Add all resources to the platform_device
*/
static struct platform_device *mpr2_devices[] __initdata = {
&heartbeat_device,
&smsc911x_device,
&flash_device,
};
static int __init mpr2_devices_setup(void)
{
return platform_add_devices(mpr2_devices, ARRAY_SIZE(mpr2_devices));
}
device_initcall(mpr2_devices_setup);
/*
* Initialize IRQ setting
*/
static void __init init_mpr2_IRQ(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ); /* install handlers for IRQ0-5 */
irq_set_irq_type(32, IRQ_TYPE_LEVEL_LOW); /* IRQ0 CAN1 */
irq_set_irq_type(33, IRQ_TYPE_LEVEL_LOW); /* IRQ1 CAN2 */
irq_set_irq_type(34, IRQ_TYPE_LEVEL_LOW); /* IRQ2 CAN3 */
irq_set_irq_type(35, IRQ_TYPE_LEVEL_LOW); /* IRQ3 SMSC9115 */
irq_set_irq_type(36, IRQ_TYPE_EDGE_RISING); /* IRQ4 touchscreen */
irq_set_irq_type(37, IRQ_TYPE_EDGE_FALLING); /* IRQ5 touchscreen */
intc_set_priority(32, 13); /* IRQ0 CAN1 */
intc_set_priority(33, 13); /* IRQ0 CAN2 */
intc_set_priority(34, 13); /* IRQ0 CAN3 */
intc_set_priority(35, 6); /* IRQ3 SMSC9115 */
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_mpr2 __initmv = {
.mv_name = "mpr2",
.mv_setup = mpr2_setup,
.mv_init_irq = init_mpr2_IRQ,
};
| talnoah/android_kernel_htc_dlx | virt/arch/sh/boards/board-magicpanelr2.c | C | gpl-2.0 | 10,719 |
import { Duration, isDuration } from './constructor';
import toInt from '../utils/to-int';
import hasOwnProp from '../utils/has-own-prop';
import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants';
import { cloneWithOffset } from '../units/offset';
import { createLocal } from '../create/local';
// ASP.NET json date format regex
var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/;
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;
export function createDuration (input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms : input._milliseconds,
d : input._days,
M : input._months
};
} else if (typeof input === 'number') {
duration = {};
if (key) {
duration[key] = input;
} else {
duration.milliseconds = input;
}
} else if (!!(match = aspNetRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : 0,
d : toInt(match[DATE]) * sign,
h : toInt(match[HOUR]) * sign,
m : toInt(match[MINUTE]) * sign,
s : toInt(match[SECOND]) * sign,
ms : toInt(match[MILLISECOND]) * sign
};
} else if (!!(match = isoRegex.exec(input))) {
sign = (match[1] === '-') ? -1 : 1;
duration = {
y : parseIso(match[2], sign),
M : parseIso(match[3], sign),
w : parseIso(match[4], sign),
d : parseIso(match[5], sign),
h : parseIso(match[6], sign),
m : parseIso(match[7], sign),
s : parseIso(match[8], sign)
};
} else if (duration == null) {// checks for null or undefined
duration = {};
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, '_locale')) {
ret._locale = input._locale;
}
return ret;
}
createDuration.fn = Duration.prototype;
function parseIso (inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {milliseconds: 0, months: 0};
res.months = other.month() - base.month() +
(other.year() - base.year()) * 12;
if (base.clone().add(res.months, 'M').isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return {milliseconds: 0, months: 0};
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
| krasnyuk/e-liquid-MS | wwwroot/assets/js/moment/src/lib/duration/create.js | JavaScript | mit | 3,948 |
// { dg-do assemble }
template <class T> void foo(); // { dg-message "" } candidate
void (*bar)() = foo<void>;
void (*baz)() = foo; // { dg-error "" } can't deduce T
| selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/g++.old-deja/g++.pt/overload5.C | C++ | gpl-3.0 | 169 |
<?php
namespace Illuminate\Validation;
use Exception;
class ValidationException extends Exception
{
/**
* The validator instance.
*
* @var \Illuminate\Validation\Validator
*/
public $validator;
/**
* The recommended response to send to the client.
*
* @var \Illuminate\Http\Response|null
*/
public $response;
/**
* Create a new exception instance.
*
* @param \Illuminate\Validation\Validator $validator
* @param \Illuminate\Http\Response $response
* @return void
*/
public function __construct($validator, $response = null)
{
parent::__construct('The given data failed to pass validation.');
$this->response = $response;
$this->validator = $validator;
}
/**
* Get the underlying response instance.
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getResponse()
{
return $this->response;
}
}
| goldenscarab/scriba | vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php | PHP | mit | 997 |
DELETE FROM `achievement_criteria_data` WHERE `criteria_id` IN (6343, 6344, 6345, 6346, 6347);
INSERT INTO `achievement_criteria_data` (`criteria_id`, `type`, `value1`, `value2`, `ScriptName`) VALUES
(6343,6,4197,0,''), -- Wintergrasp
(6343,1,16111,0,''), -- target Love Fool
(6344,6,2177,0,''), -- Battle Ring
(6344,1,16111,0,''), -- target Love Fool
(6345,6,3421,0,''), -- Blacksmith
(6345,1,16111,0,''), -- target Love Fool
(6346,6,4100,0,''), -- The Culling of Stratholme
(6346,1,16111,0,''), -- target Love Fool
(6347,6,3456,0,''), -- Naxxramas
(6347,1,16111,0,''); -- target Love Fool
| heros/multi_realm_cell | sql/sql_cata/old/3.3.5a/2012_02_08_06_world_achievement_criteria_data.sql | SQL | gpl-2.0 | 591 |
/*
* Linux Guest Relocation (LGR) detection
*
* Copyright IBM Corp. 2012
* Author(s): Michael Holzheu <holzheu@linux.vnet.ibm.com>
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <asm/facility.h>
#include <asm/sysinfo.h>
#include <asm/ebcdic.h>
#include <asm/debug.h>
#include <asm/ipl.h>
#define LGR_TIMER_INTERVAL_SECS (30 * 60)
#define VM_LEVEL_MAX 2 /* Maximum is 8, but we only record two levels */
/*
* LGR info: Contains stfle and stsi data
*/
struct lgr_info {
/* Bit field with facility information: 4 DWORDs are stored */
u64 stfle_fac_list[4];
/* Level of system (1 = CEC, 2 = LPAR, 3 = z/VM */
u32 level;
/* Level 1: CEC info (stsi 1.1.1) */
char manufacturer[16];
char type[4];
char sequence[16];
char plant[4];
char model[16];
/* Level 2: LPAR info (stsi 2.2.2) */
u16 lpar_number;
char name[8];
/* Level 3: VM info (stsi 3.2.2) */
u8 vm_count;
struct {
char name[8];
char cpi[16];
} vm[VM_LEVEL_MAX];
} __packed __aligned(8);
/*
* LGR globals
*/
static char lgr_page[PAGE_SIZE] __aligned(PAGE_SIZE);
static struct lgr_info lgr_info_last;
static struct lgr_info lgr_info_cur;
static struct debug_info *lgr_dbf;
/*
* Copy buffer and then convert it to ASCII
*/
static void cpascii(char *dst, char *src, int size)
{
memcpy(dst, src, size);
EBCASC(dst, size);
}
/*
* Fill LGR info with 1.1.1 stsi data
*/
static void lgr_stsi_1_1_1(struct lgr_info *lgr_info)
{
struct sysinfo_1_1_1 *si = (void *) lgr_page;
if (stsi(si, 1, 1, 1))
return;
cpascii(lgr_info->manufacturer, si->manufacturer,
sizeof(si->manufacturer));
cpascii(lgr_info->type, si->type, sizeof(si->type));
cpascii(lgr_info->model, si->model, sizeof(si->model));
cpascii(lgr_info->sequence, si->sequence, sizeof(si->sequence));
cpascii(lgr_info->plant, si->plant, sizeof(si->plant));
}
/*
* Fill LGR info with 2.2.2 stsi data
*/
static void lgr_stsi_2_2_2(struct lgr_info *lgr_info)
{
struct sysinfo_2_2_2 *si = (void *) lgr_page;
if (stsi(si, 2, 2, 2))
return;
cpascii(lgr_info->name, si->name, sizeof(si->name));
memcpy(&lgr_info->lpar_number, &si->lpar_number,
sizeof(lgr_info->lpar_number));
}
/*
* Fill LGR info with 3.2.2 stsi data
*/
static void lgr_stsi_3_2_2(struct lgr_info *lgr_info)
{
struct sysinfo_3_2_2 *si = (void *) lgr_page;
int i;
if (stsi(si, 3, 2, 2))
return;
for (i = 0; i < min_t(u8, si->count, VM_LEVEL_MAX); i++) {
cpascii(lgr_info->vm[i].name, si->vm[i].name,
sizeof(si->vm[i].name));
cpascii(lgr_info->vm[i].cpi, si->vm[i].cpi,
sizeof(si->vm[i].cpi));
}
lgr_info->vm_count = si->count;
}
/*
* Fill LGR info with current data
*/
static void lgr_info_get(struct lgr_info *lgr_info)
{
int level;
memset(lgr_info, 0, sizeof(*lgr_info));
stfle(lgr_info->stfle_fac_list, ARRAY_SIZE(lgr_info->stfle_fac_list));
level = stsi(NULL, 0, 0, 0);
lgr_info->level = level;
if (level >= 1)
lgr_stsi_1_1_1(lgr_info);
if (level >= 2)
lgr_stsi_2_2_2(lgr_info);
if (level >= 3)
lgr_stsi_3_2_2(lgr_info);
}
/*
* Check if LGR info has changed and if yes log new LGR info to s390dbf
*/
void lgr_info_log(void)
{
static DEFINE_SPINLOCK(lgr_info_lock);
unsigned long flags;
if (!spin_trylock_irqsave(&lgr_info_lock, flags))
return;
lgr_info_get(&lgr_info_cur);
if (memcmp(&lgr_info_last, &lgr_info_cur, sizeof(lgr_info_cur)) != 0) {
debug_event(lgr_dbf, 1, &lgr_info_cur, sizeof(lgr_info_cur));
lgr_info_last = lgr_info_cur;
}
spin_unlock_irqrestore(&lgr_info_lock, flags);
}
EXPORT_SYMBOL_GPL(lgr_info_log);
static void lgr_timer_set(void);
/*
* LGR timer callback
*/
static void lgr_timer_fn(unsigned long ignored)
{
lgr_info_log();
lgr_timer_set();
}
static struct timer_list lgr_timer =
TIMER_DEFERRED_INITIALIZER(lgr_timer_fn, 0, 0);
/*
* Setup next LGR timer
*/
static void lgr_timer_set(void)
{
mod_timer(&lgr_timer, jiffies + LGR_TIMER_INTERVAL_SECS * HZ);
}
/*
* Initialize LGR: Add s390dbf, write initial lgr_info and setup timer
*/
static int __init lgr_init(void)
{
lgr_dbf = debug_register("lgr", 1, 1, sizeof(struct lgr_info));
if (!lgr_dbf)
return -ENOMEM;
debug_register_view(lgr_dbf, &debug_hex_ascii_view);
lgr_info_get(&lgr_info_last);
debug_event(lgr_dbf, 1, &lgr_info_last, sizeof(lgr_info_last));
lgr_timer_set();
return 0;
}
device_initcall(lgr_init);
| eabatalov/au-linux-kernel-autumn-2017 | linux/arch/s390/kernel/lgr.c | C | gpl-3.0 | 4,365 |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_xml_validation_relaxng_InterleavePattern__
#define __gnu_xml_validation_relaxng_InterleavePattern__
#pragma interface
#include <gnu/xml/validation/relaxng/Pattern.h>
extern "Java"
{
namespace gnu
{
namespace xml
{
namespace validation
{
namespace relaxng
{
class InterleavePattern;
class Pattern;
}
}
}
}
}
class gnu::xml::validation::relaxng::InterleavePattern : public ::gnu::xml::validation::relaxng::Pattern
{
public: // actually package-private
InterleavePattern();
::gnu::xml::validation::relaxng::Pattern * __attribute__((aligned(__alignof__( ::gnu::xml::validation::relaxng::Pattern)))) pattern1;
::gnu::xml::validation::relaxng::Pattern * pattern2;
public:
static ::java::lang::Class class$;
};
#endif // __gnu_xml_validation_relaxng_InterleavePattern__
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/gnu/xml/validation/relaxng/InterleavePattern.h | C | gpl-2.0 | 939 |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __javax_swing_plaf_metal_MetalBorders$RolloverMarginBorder__
#define __javax_swing_plaf_metal_MetalBorders$RolloverMarginBorder__
#pragma interface
#include <javax/swing/border/AbstractBorder.h>
extern "Java"
{
namespace java
{
namespace awt
{
class Component;
class Insets;
}
}
namespace javax
{
namespace swing
{
namespace plaf
{
namespace metal
{
class MetalBorders$RolloverMarginBorder;
}
}
}
}
}
class javax::swing::plaf::metal::MetalBorders$RolloverMarginBorder : public ::javax::swing::border::AbstractBorder
{
public:
MetalBorders$RolloverMarginBorder();
virtual ::java::awt::Insets * getBorderInsets(::java::awt::Component *);
virtual ::java::awt::Insets * getBorderInsets(::java::awt::Component *, ::java::awt::Insets *);
public: // actually protected
static ::java::awt::Insets * borderInsets;
public:
static ::java::lang::Class class$;
};
#endif // __javax_swing_plaf_metal_MetalBorders$RolloverMarginBorder__
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/javax/swing/plaf/metal/MetalBorders$RolloverMarginBorder.h | C | gpl-2.0 | 1,116 |
/*
* Copyright (C) 2004 IBM Corporation
*
* Author: Serge Hallyn <serue@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/export.h>
#include <linux/uts.h>
#include <linux/utsname.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/cred.h>
#include <linux/user_namespace.h>
#include <linux/proc_ns.h>
#include <linux/sched/task.h>
static struct ucounts *inc_uts_namespaces(struct user_namespace *ns)
{
return inc_ucount(ns, current_euid(), UCOUNT_UTS_NAMESPACES);
}
static void dec_uts_namespaces(struct ucounts *ucounts)
{
dec_ucount(ucounts, UCOUNT_UTS_NAMESPACES);
}
static struct uts_namespace *create_uts_ns(void)
{
struct uts_namespace *uts_ns;
uts_ns = kmalloc(sizeof(struct uts_namespace), GFP_KERNEL);
if (uts_ns)
kref_init(&uts_ns->kref);
return uts_ns;
}
/*
* Clone a new ns copying an original utsname, setting refcount to 1
* @old_ns: namespace to clone
* Return ERR_PTR(-ENOMEM) on error (failure to kmalloc), new ns otherwise
*/
static struct uts_namespace *clone_uts_ns(struct user_namespace *user_ns,
struct uts_namespace *old_ns)
{
struct uts_namespace *ns;
struct ucounts *ucounts;
int err;
err = -ENOSPC;
ucounts = inc_uts_namespaces(user_ns);
if (!ucounts)
goto fail;
err = -ENOMEM;
ns = create_uts_ns();
if (!ns)
goto fail_dec;
err = ns_alloc_inum(&ns->ns);
if (err)
goto fail_free;
ns->ucounts = ucounts;
ns->ns.ops = &utsns_operations;
down_read(&uts_sem);
memcpy(&ns->name, &old_ns->name, sizeof(ns->name));
ns->user_ns = get_user_ns(user_ns);
up_read(&uts_sem);
return ns;
fail_free:
kfree(ns);
fail_dec:
dec_uts_namespaces(ucounts);
fail:
return ERR_PTR(err);
}
/*
* Copy task tsk's utsname namespace, or clone it if flags
* specifies CLONE_NEWUTS. In latter case, changes to the
* utsname of this process won't be seen by parent, and vice
* versa.
*/
struct uts_namespace *copy_utsname(unsigned long flags,
struct user_namespace *user_ns, struct uts_namespace *old_ns)
{
struct uts_namespace *new_ns;
BUG_ON(!old_ns);
get_uts_ns(old_ns);
if (!(flags & CLONE_NEWUTS))
return old_ns;
new_ns = clone_uts_ns(user_ns, old_ns);
put_uts_ns(old_ns);
return new_ns;
}
void free_uts_ns(struct kref *kref)
{
struct uts_namespace *ns;
ns = container_of(kref, struct uts_namespace, kref);
dec_uts_namespaces(ns->ucounts);
put_user_ns(ns->user_ns);
ns_free_inum(&ns->ns);
kfree(ns);
}
static inline struct uts_namespace *to_uts_ns(struct ns_common *ns)
{
return container_of(ns, struct uts_namespace, ns);
}
static struct ns_common *utsns_get(struct task_struct *task)
{
struct uts_namespace *ns = NULL;
struct nsproxy *nsproxy;
task_lock(task);
nsproxy = task->nsproxy;
if (nsproxy) {
ns = nsproxy->uts_ns;
get_uts_ns(ns);
}
task_unlock(task);
return ns ? &ns->ns : NULL;
}
static void utsns_put(struct ns_common *ns)
{
put_uts_ns(to_uts_ns(ns));
}
static int utsns_install(struct nsproxy *nsproxy, struct ns_common *new)
{
struct uts_namespace *ns = to_uts_ns(new);
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN) ||
!ns_capable(current_user_ns(), CAP_SYS_ADMIN))
return -EPERM;
get_uts_ns(ns);
put_uts_ns(nsproxy->uts_ns);
nsproxy->uts_ns = ns;
return 0;
}
static struct user_namespace *utsns_owner(struct ns_common *ns)
{
return to_uts_ns(ns)->user_ns;
}
const struct proc_ns_operations utsns_operations = {
.name = "uts",
.type = CLONE_NEWUTS,
.get = utsns_get,
.put = utsns_put,
.install = utsns_install,
.owner = utsns_owner,
};
| mkvdv/au-linux-kernel-autumn-2017 | linux/kernel/utsname.c | C | gpl-3.0 | 3,695 |
/* jshint -W100 */
/* jslint maxlen: 86 */
define(function () {
// Farsi (Persian)
return {
errorLoading: function () {
return 'امکان بارگذاری نتایج وجود ندارد.';
},
inputTooLong: function (args) {
var overChars = args.input.length - args.maximum;
var message = 'لطفاً ' + overChars + ' کاراکتر را حذف نمایید';
return message;
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
var message = 'لطفاً تعداد ' + remainingChars + ' کاراکتر یا بیشتر وارد نمایید';
return message;
},
loadingMore: function () {
return 'در حال بارگذاری نتایج بیشتر...';
},
maximumSelected: function (args) {
var message = 'شما تنها میتوانید ' + args.maximum + ' آیتم را انتخاب نمایید';
return message;
},
noResults: function () {
return 'هیچ نتیجهای یافت نشد';
},
searching: function () {
return 'در حال جستجو...';
}
};
});
| krasnyuk/e-liquid-MS | wwwroot/assets/js/select2/src/js/select2/i18n/fa.js | JavaScript | mit | 1,152 |
/*
* Support for IDE interfaces on Celleb platform
*
* (C) Copyright 2006 TOSHIBA CORPORATION
*
* This code is based on drivers/ide/pci/siimage.c:
* Copyright (C) 2001-2002 Andre Hedrick <andre@linux-ide.org>
* Copyright (C) 2003 Red Hat
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#define PCI_DEVICE_ID_TOSHIBA_SCC_ATA 0x01b4
#define SCC_PATA_NAME "scc IDE"
#define TDVHSEL_MASTER 0x00000001
#define TDVHSEL_SLAVE 0x00000004
#define MODE_JCUSFEN 0x00000080
#define CCKCTRL_ATARESET 0x00040000
#define CCKCTRL_BUFCNT 0x00020000
#define CCKCTRL_CRST 0x00010000
#define CCKCTRL_OCLKEN 0x00000100
#define CCKCTRL_ATACLKOEN 0x00000002
#define CCKCTRL_LCLKEN 0x00000001
#define QCHCD_IOS_SS 0x00000001
#define QCHSD_STPDIAG 0x00020000
#define INTMASK_MSK 0xD1000012
#define INTSTS_SERROR 0x80000000
#define INTSTS_PRERR 0x40000000
#define INTSTS_RERR 0x10000000
#define INTSTS_ICERR 0x01000000
#define INTSTS_BMSINT 0x00000010
#define INTSTS_BMHE 0x00000008
#define INTSTS_IOIRQS 0x00000004
#define INTSTS_INTRQ 0x00000002
#define INTSTS_ACTEINT 0x00000001
#define ECMODE_VALUE 0x01
static struct scc_ports {
unsigned long ctl, dma;
struct ide_host *host; /* for removing port from system */
} scc_ports[MAX_HWIFS];
/* PIO transfer mode table */
/* JCHST */
static unsigned long JCHSTtbl[2][7] = {
{0x0E, 0x05, 0x02, 0x03, 0x02, 0x00, 0x00}, /* 100MHz */
{0x13, 0x07, 0x04, 0x04, 0x03, 0x00, 0x00} /* 133MHz */
};
/* JCHHT */
static unsigned long JCHHTtbl[2][7] = {
{0x0E, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00}, /* 100MHz */
{0x13, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00} /* 133MHz */
};
/* JCHCT */
static unsigned long JCHCTtbl[2][7] = {
{0x1D, 0x1D, 0x1C, 0x0B, 0x06, 0x00, 0x00}, /* 100MHz */
{0x27, 0x26, 0x26, 0x0E, 0x09, 0x00, 0x00} /* 133MHz */
};
/* DMA transfer mode table */
/* JCHDCTM/JCHDCTS */
static unsigned long JCHDCTxtbl[2][7] = {
{0x0A, 0x06, 0x04, 0x03, 0x01, 0x00, 0x00}, /* 100MHz */
{0x0E, 0x09, 0x06, 0x04, 0x02, 0x01, 0x00} /* 133MHz */
};
/* JCSTWTM/JCSTWTS */
static unsigned long JCSTWTxtbl[2][7] = {
{0x06, 0x04, 0x03, 0x02, 0x02, 0x02, 0x00}, /* 100MHz */
{0x09, 0x06, 0x04, 0x02, 0x02, 0x02, 0x02} /* 133MHz */
};
/* JCTSS */
static unsigned long JCTSStbl[2][7] = {
{0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x00}, /* 100MHz */
{0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05} /* 133MHz */
};
/* JCENVT */
static unsigned long JCENVTtbl[2][7] = {
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00}, /* 100MHz */
{0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02} /* 133MHz */
};
/* JCACTSELS/JCACTSELM */
static unsigned long JCACTSELtbl[2][7] = {
{0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00}, /* 100MHz */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01} /* 133MHz */
};
static u8 scc_ide_inb(unsigned long port)
{
u32 data = in_be32((void*)port);
return (u8)data;
}
static void scc_exec_command(ide_hwif_t *hwif, u8 cmd)
{
out_be32((void *)hwif->io_ports.command_addr, cmd);
eieio();
in_be32((void *)(hwif->dma_base + 0x01c));
eieio();
}
static u8 scc_read_status(ide_hwif_t *hwif)
{
return (u8)in_be32((void *)hwif->io_ports.status_addr);
}
static u8 scc_read_altstatus(ide_hwif_t *hwif)
{
return (u8)in_be32((void *)hwif->io_ports.ctl_addr);
}
static u8 scc_dma_sff_read_status(ide_hwif_t *hwif)
{
return (u8)in_be32((void *)(hwif->dma_base + 4));
}
static void scc_write_devctl(ide_hwif_t *hwif, u8 ctl)
{
out_be32((void *)hwif->io_ports.ctl_addr, ctl);
eieio();
in_be32((void *)(hwif->dma_base + 0x01c));
eieio();
}
static void scc_ide_insw(unsigned long port, void *addr, u32 count)
{
u16 *ptr = (u16 *)addr;
while (count--) {
*ptr++ = le16_to_cpu(in_be32((void*)port));
}
}
static void scc_ide_insl(unsigned long port, void *addr, u32 count)
{
u16 *ptr = (u16 *)addr;
while (count--) {
*ptr++ = le16_to_cpu(in_be32((void*)port));
*ptr++ = le16_to_cpu(in_be32((void*)port));
}
}
static void scc_ide_outb(u8 addr, unsigned long port)
{
out_be32((void*)port, addr);
}
static void
scc_ide_outsw(unsigned long port, void *addr, u32 count)
{
u16 *ptr = (u16 *)addr;
while (count--) {
out_be32((void*)port, cpu_to_le16(*ptr++));
}
}
static void
scc_ide_outsl(unsigned long port, void *addr, u32 count)
{
u16 *ptr = (u16 *)addr;
while (count--) {
out_be32((void*)port, cpu_to_le16(*ptr++));
out_be32((void*)port, cpu_to_le16(*ptr++));
}
}
/**
* scc_set_pio_mode - set host controller for PIO mode
* @hwif: port
* @drive: drive
*
* Load the timing settings for this device mode into the
* controller.
*/
static void scc_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct scc_ports *ports = ide_get_hwifdata(hwif);
unsigned long ctl_base = ports->ctl;
unsigned long cckctrl_port = ctl_base + 0xff0;
unsigned long piosht_port = ctl_base + 0x000;
unsigned long pioct_port = ctl_base + 0x004;
unsigned long reg;
int offset;
const u8 pio = drive->pio_mode - XFER_PIO_0;
reg = in_be32((void __iomem *)cckctrl_port);
if (reg & CCKCTRL_ATACLKOEN) {
offset = 1; /* 133MHz */
} else {
offset = 0; /* 100MHz */
}
reg = JCHSTtbl[offset][pio] << 16 | JCHHTtbl[offset][pio];
out_be32((void __iomem *)piosht_port, reg);
reg = JCHCTtbl[offset][pio];
out_be32((void __iomem *)pioct_port, reg);
}
/**
* scc_set_dma_mode - set host controller for DMA mode
* @hwif: port
* @drive: drive
*
* Load the timing settings for this device mode into the
* controller.
*/
static void scc_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct scc_ports *ports = ide_get_hwifdata(hwif);
unsigned long ctl_base = ports->ctl;
unsigned long cckctrl_port = ctl_base + 0xff0;
unsigned long mdmact_port = ctl_base + 0x008;
unsigned long mcrcst_port = ctl_base + 0x00c;
unsigned long sdmact_port = ctl_base + 0x010;
unsigned long scrcst_port = ctl_base + 0x014;
unsigned long udenvt_port = ctl_base + 0x018;
unsigned long tdvhsel_port = ctl_base + 0x020;
int is_slave = drive->dn & 1;
int offset, idx;
unsigned long reg;
unsigned long jcactsel;
const u8 speed = drive->dma_mode;
reg = in_be32((void __iomem *)cckctrl_port);
if (reg & CCKCTRL_ATACLKOEN) {
offset = 1; /* 133MHz */
} else {
offset = 0; /* 100MHz */
}
idx = speed - XFER_UDMA_0;
jcactsel = JCACTSELtbl[offset][idx];
if (is_slave) {
out_be32((void __iomem *)sdmact_port, JCHDCTxtbl[offset][idx]);
out_be32((void __iomem *)scrcst_port, JCSTWTxtbl[offset][idx]);
jcactsel = jcactsel << 2;
out_be32((void __iomem *)tdvhsel_port, (in_be32((void __iomem *)tdvhsel_port) & ~TDVHSEL_SLAVE) | jcactsel);
} else {
out_be32((void __iomem *)mdmact_port, JCHDCTxtbl[offset][idx]);
out_be32((void __iomem *)mcrcst_port, JCSTWTxtbl[offset][idx]);
out_be32((void __iomem *)tdvhsel_port, (in_be32((void __iomem *)tdvhsel_port) & ~TDVHSEL_MASTER) | jcactsel);
}
reg = JCTSStbl[offset][idx] << 16 | JCENVTtbl[offset][idx];
out_be32((void __iomem *)udenvt_port, reg);
}
static void scc_dma_host_set(ide_drive_t *drive, int on)
{
ide_hwif_t *hwif = drive->hwif;
u8 unit = drive->dn & 1;
u8 dma_stat = scc_dma_sff_read_status(hwif);
if (on)
dma_stat |= (1 << (5 + unit));
else
dma_stat &= ~(1 << (5 + unit));
scc_ide_outb(dma_stat, hwif->dma_base + 4);
}
/**
* scc_dma_setup - begin a DMA phase
* @drive: target device
* @cmd: command
*
* Build an IDE DMA PRD (IDE speak for scatter gather table)
* and then set up the DMA transfer registers.
*
* Returns 0 on success. If a PIO fallback is required then 1
* is returned.
*/
static int scc_dma_setup(ide_drive_t *drive, struct ide_cmd *cmd)
{
ide_hwif_t *hwif = drive->hwif;
u32 rw = (cmd->tf_flags & IDE_TFLAG_WRITE) ? 0 : ATA_DMA_WR;
u8 dma_stat;
/* fall back to pio! */
if (ide_build_dmatable(drive, cmd) == 0)
return 1;
/* PRD table */
out_be32((void __iomem *)(hwif->dma_base + 8), hwif->dmatable_dma);
/* specify r/w */
out_be32((void __iomem *)hwif->dma_base, rw);
/* read DMA status for INTR & ERROR flags */
dma_stat = scc_dma_sff_read_status(hwif);
/* clear INTR & ERROR flags */
out_be32((void __iomem *)(hwif->dma_base + 4), dma_stat | 6);
return 0;
}
static void scc_dma_start(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u8 dma_cmd = scc_ide_inb(hwif->dma_base);
/* start DMA */
scc_ide_outb(dma_cmd | 1, hwif->dma_base);
}
static int __scc_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u8 dma_stat, dma_cmd;
/* get DMA command mode */
dma_cmd = scc_ide_inb(hwif->dma_base);
/* stop DMA */
scc_ide_outb(dma_cmd & ~1, hwif->dma_base);
/* get DMA status */
dma_stat = scc_dma_sff_read_status(hwif);
/* clear the INTR & ERROR bits */
scc_ide_outb(dma_stat | 6, hwif->dma_base + 4);
/* verify good DMA status */
return (dma_stat & 7) != 4 ? (0x10 | dma_stat) : 0;
}
/**
* scc_dma_end - Stop DMA
* @drive: IDE drive
*
* Check and clear INT Status register.
* Then call __scc_dma_end().
*/
static int scc_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
void __iomem *dma_base = (void __iomem *)hwif->dma_base;
unsigned long intsts_port = hwif->dma_base + 0x014;
u32 reg;
int dma_stat, data_loss = 0;
static int retry = 0;
/* errata A308 workaround: Step5 (check data loss) */
/* We don't check non ide_disk because it is limited to UDMA4 */
if (!(in_be32((void __iomem *)hwif->io_ports.ctl_addr)
& ATA_ERR) &&
drive->media == ide_disk && drive->current_speed > XFER_UDMA_4) {
reg = in_be32((void __iomem *)intsts_port);
if (!(reg & INTSTS_ACTEINT)) {
printk(KERN_WARNING "%s: operation failed (transfer data loss)\n",
drive->name);
data_loss = 1;
if (retry++) {
struct request *rq = hwif->rq;
ide_drive_t *drive;
int i;
/* ERROR_RESET and drive->crc_count are needed
* to reduce DMA transfer mode in retry process.
*/
if (rq)
rq->errors |= ERROR_RESET;
ide_port_for_each_dev(i, drive, hwif)
drive->crc_count++;
}
}
}
while (1) {
reg = in_be32((void __iomem *)intsts_port);
if (reg & INTSTS_SERROR) {
printk(KERN_WARNING "%s: SERROR\n", SCC_PATA_NAME);
out_be32((void __iomem *)intsts_port, INTSTS_SERROR|INTSTS_BMSINT);
out_be32(dma_base, in_be32(dma_base) & ~QCHCD_IOS_SS);
continue;
}
if (reg & INTSTS_PRERR) {
u32 maea0, maec0;
unsigned long ctl_base = hwif->config_data;
maea0 = in_be32((void __iomem *)(ctl_base + 0xF50));
maec0 = in_be32((void __iomem *)(ctl_base + 0xF54));
printk(KERN_WARNING "%s: PRERR [addr:%x cmd:%x]\n", SCC_PATA_NAME, maea0, maec0);
out_be32((void __iomem *)intsts_port, INTSTS_PRERR|INTSTS_BMSINT);
out_be32(dma_base, in_be32(dma_base) & ~QCHCD_IOS_SS);
continue;
}
if (reg & INTSTS_RERR) {
printk(KERN_WARNING "%s: Response Error\n", SCC_PATA_NAME);
out_be32((void __iomem *)intsts_port, INTSTS_RERR|INTSTS_BMSINT);
out_be32(dma_base, in_be32(dma_base) & ~QCHCD_IOS_SS);
continue;
}
if (reg & INTSTS_ICERR) {
out_be32(dma_base, in_be32(dma_base) & ~QCHCD_IOS_SS);
printk(KERN_WARNING "%s: Illegal Configuration\n", SCC_PATA_NAME);
out_be32((void __iomem *)intsts_port, INTSTS_ICERR|INTSTS_BMSINT);
continue;
}
if (reg & INTSTS_BMSINT) {
printk(KERN_WARNING "%s: Internal Bus Error\n", SCC_PATA_NAME);
out_be32((void __iomem *)intsts_port, INTSTS_BMSINT);
ide_do_reset(drive);
continue;
}
if (reg & INTSTS_BMHE) {
out_be32((void __iomem *)intsts_port, INTSTS_BMHE);
continue;
}
if (reg & INTSTS_ACTEINT) {
out_be32((void __iomem *)intsts_port, INTSTS_ACTEINT);
continue;
}
if (reg & INTSTS_IOIRQS) {
out_be32((void __iomem *)intsts_port, INTSTS_IOIRQS);
continue;
}
break;
}
dma_stat = __scc_dma_end(drive);
if (data_loss)
dma_stat |= 2; /* emulate DMA error (to retry command) */
return dma_stat;
}
/* returns 1 if dma irq issued, 0 otherwise */
static int scc_dma_test_irq(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u32 int_stat = in_be32((void __iomem *)hwif->dma_base + 0x014);
/* SCC errata A252,A308 workaround: Step4 */
if ((in_be32((void __iomem *)hwif->io_ports.ctl_addr)
& ATA_ERR) &&
(int_stat & INTSTS_INTRQ))
return 1;
/* SCC errata A308 workaround: Step5 (polling IOIRQS) */
if (int_stat & INTSTS_IOIRQS)
return 1;
return 0;
}
static u8 scc_udma_filter(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u8 mask = hwif->ultra_mask;
/* errata A308 workaround: limit non ide_disk drive to UDMA4 */
if ((drive->media != ide_disk) && (mask & 0xE0)) {
printk(KERN_INFO "%s: limit %s to UDMA4\n",
SCC_PATA_NAME, drive->name);
mask = ATA_UDMA4;
}
return mask;
}
/**
* setup_mmio_scc - map CTRL/BMID region
* @dev: PCI device we are configuring
* @name: device name
*
*/
static int setup_mmio_scc (struct pci_dev *dev, const char *name)
{
void __iomem *ctl_addr;
void __iomem *dma_addr;
int i, ret;
for (i = 0; i < MAX_HWIFS; i++) {
if (scc_ports[i].ctl == 0)
break;
}
if (i >= MAX_HWIFS)
return -ENOMEM;
ret = pci_request_selected_regions(dev, (1 << 2) - 1, name);
if (ret < 0) {
printk(KERN_ERR "%s: can't reserve resources\n", name);
return ret;
}
ctl_addr = pci_ioremap_bar(dev, 0);
if (!ctl_addr)
goto fail_0;
dma_addr = pci_ioremap_bar(dev, 1);
if (!dma_addr)
goto fail_1;
pci_set_master(dev);
scc_ports[i].ctl = (unsigned long)ctl_addr;
scc_ports[i].dma = (unsigned long)dma_addr;
pci_set_drvdata(dev, (void *) &scc_ports[i]);
return 1;
fail_1:
iounmap(ctl_addr);
fail_0:
return -ENOMEM;
}
static int scc_ide_setup_pci_device(struct pci_dev *dev,
const struct ide_port_info *d)
{
struct scc_ports *ports = pci_get_drvdata(dev);
struct ide_host *host;
struct ide_hw hw, *hws[] = { &hw };
int i, rc;
memset(&hw, 0, sizeof(hw));
for (i = 0; i <= 8; i++)
hw.io_ports_array[i] = ports->dma + 0x20 + i * 4;
hw.irq = dev->irq;
hw.dev = &dev->dev;
rc = ide_host_add(d, hws, 1, &host);
if (rc)
return rc;
ports->host = host;
return 0;
}
/**
* init_setup_scc - set up an SCC PATA Controller
* @dev: PCI device
* @d: IDE port info
*
* Perform the initial set up for this device.
*/
static int init_setup_scc(struct pci_dev *dev, const struct ide_port_info *d)
{
unsigned long ctl_base;
unsigned long dma_base;
unsigned long cckctrl_port;
unsigned long intmask_port;
unsigned long mode_port;
unsigned long ecmode_port;
u32 reg = 0;
struct scc_ports *ports;
int rc;
rc = pci_enable_device(dev);
if (rc)
goto end;
rc = setup_mmio_scc(dev, d->name);
if (rc < 0)
goto end;
ports = pci_get_drvdata(dev);
ctl_base = ports->ctl;
dma_base = ports->dma;
cckctrl_port = ctl_base + 0xff0;
intmask_port = dma_base + 0x010;
mode_port = ctl_base + 0x024;
ecmode_port = ctl_base + 0xf00;
/* controller initialization */
reg = 0;
out_be32((void*)cckctrl_port, reg);
reg |= CCKCTRL_ATACLKOEN;
out_be32((void*)cckctrl_port, reg);
reg |= CCKCTRL_LCLKEN | CCKCTRL_OCLKEN;
out_be32((void*)cckctrl_port, reg);
reg |= CCKCTRL_CRST;
out_be32((void*)cckctrl_port, reg);
for (;;) {
reg = in_be32((void*)cckctrl_port);
if (reg & CCKCTRL_CRST)
break;
udelay(5000);
}
reg |= CCKCTRL_ATARESET;
out_be32((void*)cckctrl_port, reg);
out_be32((void*)ecmode_port, ECMODE_VALUE);
out_be32((void*)mode_port, MODE_JCUSFEN);
out_be32((void*)intmask_port, INTMASK_MSK);
rc = scc_ide_setup_pci_device(dev, d);
end:
return rc;
}
static void scc_tf_load(ide_drive_t *drive, struct ide_taskfile *tf, u8 valid)
{
struct ide_io_ports *io_ports = &drive->hwif->io_ports;
if (valid & IDE_VALID_FEATURE)
scc_ide_outb(tf->feature, io_ports->feature_addr);
if (valid & IDE_VALID_NSECT)
scc_ide_outb(tf->nsect, io_ports->nsect_addr);
if (valid & IDE_VALID_LBAL)
scc_ide_outb(tf->lbal, io_ports->lbal_addr);
if (valid & IDE_VALID_LBAM)
scc_ide_outb(tf->lbam, io_ports->lbam_addr);
if (valid & IDE_VALID_LBAH)
scc_ide_outb(tf->lbah, io_ports->lbah_addr);
if (valid & IDE_VALID_DEVICE)
scc_ide_outb(tf->device, io_ports->device_addr);
}
static void scc_tf_read(ide_drive_t *drive, struct ide_taskfile *tf, u8 valid)
{
struct ide_io_ports *io_ports = &drive->hwif->io_ports;
if (valid & IDE_VALID_ERROR)
tf->error = scc_ide_inb(io_ports->feature_addr);
if (valid & IDE_VALID_NSECT)
tf->nsect = scc_ide_inb(io_ports->nsect_addr);
if (valid & IDE_VALID_LBAL)
tf->lbal = scc_ide_inb(io_ports->lbal_addr);
if (valid & IDE_VALID_LBAM)
tf->lbam = scc_ide_inb(io_ports->lbam_addr);
if (valid & IDE_VALID_LBAH)
tf->lbah = scc_ide_inb(io_ports->lbah_addr);
if (valid & IDE_VALID_DEVICE)
tf->device = scc_ide_inb(io_ports->device_addr);
}
static void scc_input_data(ide_drive_t *drive, struct ide_cmd *cmd,
void *buf, unsigned int len)
{
unsigned long data_addr = drive->hwif->io_ports.data_addr;
len++;
if (drive->io_32bit) {
scc_ide_insl(data_addr, buf, len / 4);
if ((len & 3) >= 2)
scc_ide_insw(data_addr, (u8 *)buf + (len & ~3), 1);
} else
scc_ide_insw(data_addr, buf, len / 2);
}
static void scc_output_data(ide_drive_t *drive, struct ide_cmd *cmd,
void *buf, unsigned int len)
{
unsigned long data_addr = drive->hwif->io_ports.data_addr;
len++;
if (drive->io_32bit) {
scc_ide_outsl(data_addr, buf, len / 4);
if ((len & 3) >= 2)
scc_ide_outsw(data_addr, (u8 *)buf + (len & ~3), 1);
} else
scc_ide_outsw(data_addr, buf, len / 2);
}
/**
* init_mmio_iops_scc - set up the iops for MMIO
* @hwif: interface to set up
*
*/
static void init_mmio_iops_scc(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct scc_ports *ports = pci_get_drvdata(dev);
unsigned long dma_base = ports->dma;
ide_set_hwifdata(hwif, ports);
hwif->dma_base = dma_base;
hwif->config_data = ports->ctl;
}
/**
* init_iops_scc - set up iops
* @hwif: interface to set up
*
* Do the basic setup for the SCC hardware interface
* and then do the MMIO setup.
*/
static void init_iops_scc(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
hwif->hwif_data = NULL;
if (pci_get_drvdata(dev) == NULL)
return;
init_mmio_iops_scc(hwif);
}
static int scc_init_dma(ide_hwif_t *hwif, const struct ide_port_info *d)
{
return ide_allocate_dma_engine(hwif);
}
static u8 scc_cable_detect(ide_hwif_t *hwif)
{
return ATA_CBL_PATA80;
}
/**
* init_hwif_scc - set up hwif
* @hwif: interface to set up
*
* We do the basic set up of the interface structure. The SCC
* requires several custom handlers so we override the default
* ide DMA handlers appropriately.
*/
static void init_hwif_scc(ide_hwif_t *hwif)
{
/* PTERADD */
out_be32((void __iomem *)(hwif->dma_base + 0x018), hwif->dmatable_dma);
if (in_be32((void __iomem *)(hwif->config_data + 0xff0)) & CCKCTRL_ATACLKOEN)
hwif->ultra_mask = ATA_UDMA6; /* 133MHz */
else
hwif->ultra_mask = ATA_UDMA5; /* 100MHz */
}
static const struct ide_tp_ops scc_tp_ops = {
.exec_command = scc_exec_command,
.read_status = scc_read_status,
.read_altstatus = scc_read_altstatus,
.write_devctl = scc_write_devctl,
.dev_select = ide_dev_select,
.tf_load = scc_tf_load,
.tf_read = scc_tf_read,
.input_data = scc_input_data,
.output_data = scc_output_data,
};
static const struct ide_port_ops scc_port_ops = {
.set_pio_mode = scc_set_pio_mode,
.set_dma_mode = scc_set_dma_mode,
.udma_filter = scc_udma_filter,
.cable_detect = scc_cable_detect,
};
static const struct ide_dma_ops scc_dma_ops = {
.dma_host_set = scc_dma_host_set,
.dma_setup = scc_dma_setup,
.dma_start = scc_dma_start,
.dma_end = scc_dma_end,
.dma_test_irq = scc_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = scc_dma_sff_read_status,
};
static const struct ide_port_info scc_chipset = {
.name = "sccIDE",
.init_iops = init_iops_scc,
.init_dma = scc_init_dma,
.init_hwif = init_hwif_scc,
.tp_ops = &scc_tp_ops,
.port_ops = &scc_port_ops,
.dma_ops = &scc_dma_ops,
.host_flags = IDE_HFLAG_SINGLE,
.irq_flags = IRQF_SHARED,
.pio_mask = ATA_PIO4,
.chipset = ide_pci,
};
/**
* scc_init_one - pci layer discovery entry
* @dev: PCI device
* @id: ident table entry
*
* Called by the PCI code when it finds an SCC PATA controller.
* We then use the IDE PCI generic helper to do most of the work.
*/
static int scc_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
return init_setup_scc(dev, &scc_chipset);
}
/**
* scc_remove - pci layer remove entry
* @dev: PCI device
*
* Called by the PCI code when it removes an SCC PATA controller.
*/
static void scc_remove(struct pci_dev *dev)
{
struct scc_ports *ports = pci_get_drvdata(dev);
struct ide_host *host = ports->host;
ide_host_remove(host);
iounmap((void*)ports->dma);
iounmap((void*)ports->ctl);
pci_release_selected_regions(dev, (1 << 2) - 1);
memset(ports, 0, sizeof(*ports));
}
static const struct pci_device_id scc_pci_tbl[] = {
{ PCI_VDEVICE(TOSHIBA_2, PCI_DEVICE_ID_TOSHIBA_SCC_ATA), 0 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, scc_pci_tbl);
static struct pci_driver scc_pci_driver = {
.name = "SCC IDE",
.id_table = scc_pci_tbl,
.probe = scc_init_one,
.remove = scc_remove,
};
static int __init scc_ide_init(void)
{
return ide_pci_register_driver(&scc_pci_driver);
}
static void __exit scc_ide_exit(void)
{
pci_unregister_driver(&scc_pci_driver);
}
module_init(scc_ide_init);
module_exit(scc_ide_exit);
MODULE_DESCRIPTION("PCI driver module for Toshiba SCC IDE");
MODULE_LICENSE("GPL");
| mericon/Xp_Kernel_LGH850 | virt/drivers/ide/scc_pata.c | C | gpl-2.0 | 22,450 |
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "DirectoryNodeAlbumCompilations.h"
#include "QueryParams.h"
#include "music/MusicDatabase.h"
using namespace XFILE::MUSICDATABASEDIRECTORY;
CDirectoryNodeAlbumCompilations::CDirectoryNodeAlbumCompilations(const std::string& strName, CDirectoryNode* pParent)
: CDirectoryNode(NODE_TYPE_ALBUM_COMPILATIONS, strName, pParent)
{
}
NODE_TYPE CDirectoryNodeAlbumCompilations::GetChildType() const
{
if (GetName()=="-1")
return NODE_TYPE_ALBUM_COMPILATIONS_SONGS;
return NODE_TYPE_SONG;
}
std::string CDirectoryNodeAlbumCompilations::GetLocalizedName() const
{
if (GetID() == -1)
return g_localizeStrings.Get(15102); // All Albums
CMusicDatabase db;
if (db.Open())
return db.GetAlbumById(GetID());
return "";
}
bool CDirectoryNodeAlbumCompilations::GetContent(CFileItemList& items) const
{
CMusicDatabase musicdatabase;
if (!musicdatabase.Open())
return false;
CQueryParams params;
CollectQueryParams(params);
bool bSuccess=musicdatabase.GetCompilationAlbums(BuildPath(), items);
musicdatabase.Close();
return bSuccess;
}
| joethefox/xbmc | xbmc/filesystem/MusicDatabaseDirectory/DirectoryNodeAlbumCompilations.cpp | C++ | gpl-2.0 | 1,817 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.oncrpc;
/**
* Represent an RPC message as defined in RFC 1831.
*/
public abstract class RpcMessage {
/** Message type */
public static enum Type {
// the order of the values below are significant.
RPC_CALL,
RPC_REPLY;
public int getValue() {
return ordinal();
}
public static Type fromValue(int value) {
if (value < 0 || value >= values().length) {
return null;
}
return values()[value];
}
}
protected final int xid;
protected final Type messageType;
RpcMessage(int xid, Type messageType) {
if (messageType != Type.RPC_CALL && messageType != Type.RPC_REPLY) {
throw new IllegalArgumentException("Invalid message type " + messageType);
}
this.xid = xid;
this.messageType = messageType;
}
public abstract XDR write(XDR xdr);
public int getXid() {
return xid;
}
public Type getMessageType() {
return messageType;
}
protected void validateMessageType(Type expected) {
if (expected != messageType) {
throw new IllegalArgumentException("Message type is expected to be "
+ expected + " but got " + messageType);
}
}
}
| tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/oncrpc/RpcMessage.java | Java | apache-2.0 | 2,009 |
<?php
/**
* Locale data for 'kcg'.
*
* This file is automatically generated by yiic cldr command.
*
* Copyright © 1991-2007 Unicode, Inc. All rights reserved.
* Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
*
* @copyright 2008-2013 Yii Software LLC (http://www.yiiframework.com/license/)
*/
return array (
'version' => '5798',
'numberSymbols' =>
array (
'alias' => '',
'decimal' => '.',
'group' => ',',
'list' => ';',
'percentSign' => '%',
'plusSign' => '+',
'minusSign' => '-',
'exponential' => 'E',
'perMille' => '‰',
'infinity' => '∞',
'nan' => 'NaN',
),
'decimalFormat' => '#,##0.###',
'scientificFormat' => '#E0',
'percentFormat' => '#,##0%',
'currencyFormat' => '¤ #,##0.00',
'currencySymbols' =>
array (
'AUD' => 'AU$',
'BRL' => 'R$',
'CAD' => 'CA$',
'CNY' => 'CN¥',
'EUR' => '€',
'GBP' => '£',
'HKD' => 'HK$',
'ILS' => '₪',
'INR' => '₹',
'JPY' => 'JP¥',
'KRW' => '₩',
'MXN' => 'MX$',
'NZD' => 'NZ$',
'THB' => '฿',
'TWD' => 'NT$',
'USD' => 'US$',
'VND' => '₫',
'XAF' => 'FCFA',
'XCD' => 'EC$',
'XOF' => 'CFA',
'XPF' => 'CFPF',
'NGN' => '₦',
),
'monthNames' =>
array (
'wide' =>
array (
1 => 'Zwat Juwung',
2 => 'Zwat Swiyang',
3 => 'Zwat Tsat',
4 => 'Zwat Nyai',
5 => 'Zwat Tswon',
6 => 'Zwat Ataah',
7 => 'Zwat Anatat',
8 => 'Zwat Arinai',
9 => 'Zwat Akubunyung',
10 => 'Zwat Swag',
11 => 'Zwat Mangjuwang',
12 => 'Zwat Swag-Ma-Suyang',
),
'abbreviated' =>
array (
1 => 'Juw',
2 => 'Swi',
3 => 'Tsa',
4 => 'Nya',
5 => 'Tsw',
6 => 'Ata',
7 => 'Ana',
8 => 'Ari',
9 => 'Aku',
10 => 'Swa',
11 => 'Man',
12 => 'Mas',
),
),
'monthNamesSA' =>
array (
'narrow' =>
array (
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => '10',
11 => '11',
12 => '12',
),
),
'weekDayNames' =>
array (
'wide' =>
array (
0 => 'Ladi',
1 => 'Tanii',
2 => 'Talata',
3 => 'Larba',
4 => 'Lamit',
5 => 'Juma',
6 => 'Asabat',
),
'abbreviated' =>
array (
0 => 'Lad',
1 => 'Tan',
2 => 'Tal',
3 => 'Lar',
4 => 'Lam',
5 => 'Jum',
6 => 'Asa',
),
),
'weekDayNamesSA' =>
array (
'narrow' =>
array (
0 => '1',
1 => '2',
2 => '3',
3 => '4',
4 => '5',
5 => '6',
6 => '7',
),
),
'eraNames' =>
array (
'abbreviated' =>
array (
0 => 'GM',
1 => 'M',
),
'wide' =>
array (
0 => 'Gabanin Miladi',
1 => 'Miladi',
),
'narrow' =>
array (
0 => 'GM',
1 => 'M',
),
),
'dateFormats' =>
array (
'full' => 'EEEE, y MMMM dd',
'long' => 'y MMMM d',
'medium' => 'y MMM d',
'short' => 'yy/MM/dd',
),
'timeFormats' =>
array (
'full' => 'HH:mm:ss zzzz',
'long' => 'HH:mm:ss z',
'medium' => 'HH:mm:ss',
'short' => 'HH:mm',
),
'dateTimeFormat' => '{1} {0}',
'amName' => 'AM',
'pmName' => 'PM',
'orientation' => 'ltr',
'pluralRules' =>
array (
0 => 'n==1',
1 => 'true',
),
);
| Wyden971/IpMotors | yiiframework/i18n/data/kcg.php | PHP | unlicense | 3,480 |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __javax_swing_JRadioButton__
#define __javax_swing_JRadioButton__
#pragma interface
#include <javax/swing/JToggleButton.h>
extern "Java"
{
namespace javax
{
namespace accessibility
{
class AccessibleContext;
}
namespace swing
{
class Action;
class Icon;
class JRadioButton;
}
}
}
class javax::swing::JRadioButton : public ::javax::swing::JToggleButton
{
public:
JRadioButton();
JRadioButton(::javax::swing::Action *);
JRadioButton(::javax::swing::Icon *);
JRadioButton(::javax::swing::Icon *, jboolean);
JRadioButton(::java::lang::String *);
JRadioButton(::java::lang::String *, jboolean);
JRadioButton(::java::lang::String *, ::javax::swing::Icon *);
JRadioButton(::java::lang::String *, ::javax::swing::Icon *, jboolean);
virtual ::javax::accessibility::AccessibleContext * getAccessibleContext();
virtual ::java::lang::String * getUIClassID();
public: // actually protected
virtual ::java::lang::String * paramString();
public:
virtual void updateUI();
private:
static const jlong serialVersionUID = 7751949583255506856LL;
public:
static ::java::lang::Class class$;
};
#endif // __javax_swing_JRadioButton__
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/javax/swing/JRadioButton.h | C | gpl-2.0 | 1,279 |
/* SPDX-License-Identifier: MIT */
/*
* Copyright © 2019 Intel Corporation
*/
#ifndef __I915_SUSPEND_H__
#define __I915_SUSPEND_H__
struct drm_i915_private;
int i915_save_state(struct drm_i915_private *i915);
int i915_restore_state(struct drm_i915_private *i915);
#endif /* __I915_SUSPEND_H__ */
| CSE3320/kernel-code | linux-5.8/drivers/gpu/drm/i915/i915_suspend.h | C | gpl-2.0 | 303 |
/* This file is part of the program psim.
Copyright (C) 1994-1996, Andrew Cagney <cagney@highland.com.au>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _HW_PAL_C_
#define _HW_PAL_C_
#ifndef STATIC_INLINE_HW_PAL
#define STATIC_INLINE_HW_PAL STATIC_INLINE
#endif
#include "device_table.h"
#include "cpu.h"
#ifdef HAVE_STRING_H
#include <string.h>
#else
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
/* DEVICE
pal - glue logic device containing assorted junk
DESCRIPTION
Typical hardware dependant hack. This device allows the firmware
to gain access to all the things the firmware needs (but the OS
doesn't).
The pal contains the following registers. Except for the interrupt
level register, each of the below is 8 bytes in size and must be
accessed using correct alignment. For 16 and 32 bit accesses the
bytes not directed to the register are ignored:
|0 reset register (write)
|4 processor id register (read)
|8 interrupt port (write)
|9 interrupt level (write)
|12 processor count register (read)
|16 tty input fifo register (read)
|20 tty input status register (read)
|24 tty output fifo register (write)
|28 tty output status register (read)
Reset register (write) halts the simulator exiting with the
value written.
Processor id register (read) returns the processor number (0
.. N-1) of the processor performing the read.
The interrupt registers should be accessed as a pair (using a 16 or
32 bit store). The low byte specifies the interrupt port while the
high byte specifies the level to drive that port at. By
convention, the pal's interrupt ports (int0, int1, ...) are wired
up to the corresponding processor's level sensative external
interrupt pin. Eg: A two byte write to address 8 of 0x0102
(big-endian) will result in processor 2's external interrupt pin to
be asserted.
Processor count register (read) returns the total number of
processors active in the current simulation.
TTY input fifo register (read), if the TTY input status register
indicates a character is available by being nonzero, returns the
next available character from the pal's tty input port.
Similarly, the TTY output fifo register (write), if the TTY output
status register indicates the output fifo is not full by being
nonzero, outputs the character written to the tty's output port.
PROPERTIES
reg = <address> <size> (required)
Specify the address (within the parent bus) that this device is to
live.
*/
enum {
hw_pal_reset_register = 0x0,
hw_pal_cpu_nr_register = 0x4,
hw_pal_int_register = 0x8,
hw_pal_nr_cpu_register = 0xa,
hw_pal_read_fifo = 0x10,
hw_pal_read_status = 0x14,
hw_pal_write_fifo = 0x18,
hw_pal_write_status = 0x1a,
hw_pal_address_mask = 0x1f,
};
typedef struct _hw_pal_console_buffer {
char buffer;
int status;
} hw_pal_console_buffer;
typedef struct _hw_pal_device {
hw_pal_console_buffer input;
hw_pal_console_buffer output;
device *disk;
} hw_pal_device;
/* check the console for an available character */
static void
scan_hw_pal(hw_pal_device *hw_pal)
{
char c;
int count;
count = sim_io_read_stdin(&c, sizeof(c));
switch (count) {
case sim_io_not_ready:
case sim_io_eof:
hw_pal->input.buffer = 0;
hw_pal->input.status = 0;
break;
default:
hw_pal->input.buffer = c;
hw_pal->input.status = 1;
}
}
/* write the character to the hw_pal */
static void
write_hw_pal(hw_pal_device *hw_pal,
char val)
{
sim_io_write_stdout(&val, 1);
hw_pal->output.buffer = val;
hw_pal->output.status = 1;
}
static unsigned
hw_pal_io_read_buffer_callback(device *me,
void *dest,
int space,
unsigned_word addr,
unsigned nr_bytes,
cpu *processor,
unsigned_word cia)
{
hw_pal_device *hw_pal = (hw_pal_device*)device_data(me);
unsigned_1 val;
switch (addr & hw_pal_address_mask) {
case hw_pal_cpu_nr_register:
val = cpu_nr(processor);
DTRACE(pal, ("read - cpu-nr %d\n", val));
break;
case hw_pal_nr_cpu_register:
val = tree_find_integer_property(me, "/openprom/options/smp");
DTRACE(pal, ("read - nr-cpu %d\n", val));
break;
case hw_pal_read_fifo:
val = hw_pal->input.buffer;
DTRACE(pal, ("read - input-fifo %d\n", val));
break;
case hw_pal_read_status:
scan_hw_pal(hw_pal);
val = hw_pal->input.status;
DTRACE(pal, ("read - input-status %d\n", val));
break;
case hw_pal_write_fifo:
val = hw_pal->output.buffer;
DTRACE(pal, ("read - output-fifo %d\n", val));
break;
case hw_pal_write_status:
val = hw_pal->output.status;
DTRACE(pal, ("read - output-status %d\n", val));
break;
default:
val = 0;
DTRACE(pal, ("read - ???\n"));
}
memset(dest, 0, nr_bytes);
*(unsigned_1*)dest = val;
return nr_bytes;
}
static unsigned
hw_pal_io_write_buffer_callback(device *me,
const void *source,
int space,
unsigned_word addr,
unsigned nr_bytes,
cpu *processor,
unsigned_word cia)
{
hw_pal_device *hw_pal = (hw_pal_device*)device_data(me);
unsigned_1 *byte = (unsigned_1*)source;
switch (addr & hw_pal_address_mask) {
case hw_pal_reset_register:
cpu_halt(processor, cia, was_exited, byte[0]);
break;
case hw_pal_int_register:
device_interrupt_event(me,
byte[0], /*port*/
(nr_bytes > 1 ? byte[1] : 0), /* val */
processor, cia);
break;
case hw_pal_read_fifo:
hw_pal->input.buffer = byte[0];
DTRACE(pal, ("write - input-fifo %d\n", byte[0]));
break;
case hw_pal_read_status:
hw_pal->input.status = byte[0];
DTRACE(pal, ("write - input-status %d\n", byte[0]));
break;
case hw_pal_write_fifo:
write_hw_pal(hw_pal, byte[0]);
DTRACE(pal, ("write - output-fifo %d\n", byte[0]));
break;
case hw_pal_write_status:
hw_pal->output.status = byte[0];
DTRACE(pal, ("write - output-status %d\n", byte[0]));
break;
}
return nr_bytes;
}
/* instances of the hw_pal device */
static void
hw_pal_instance_delete_callback(device_instance *instance)
{
/* nothing to delete, the hw_pal is attached to the device */
return;
}
static int
hw_pal_instance_read_callback(device_instance *instance,
void *buf,
unsigned_word len)
{
DITRACE(pal, ("read - %s (%ld)", (const char*)buf, (long int)len));
return sim_io_read_stdin(buf, len);
}
static int
hw_pal_instance_write_callback(device_instance *instance,
const void *buf,
unsigned_word len)
{
int i;
const char *chp = buf;
hw_pal_device *hw_pal = device_instance_data(instance);
DITRACE(pal, ("write - %s (%ld)", (const char*)buf, (long int)len));
for (i = 0; i < len; i++)
write_hw_pal(hw_pal, chp[i]);
sim_io_flush_stdoutput();
return i;
}
static const device_instance_callbacks hw_pal_instance_callbacks = {
hw_pal_instance_delete_callback,
hw_pal_instance_read_callback,
hw_pal_instance_write_callback,
};
static device_instance *
hw_pal_create_instance(device *me,
const char *path,
const char *args)
{
return device_create_instance_from(me, NULL,
device_data(me),
path, args,
&hw_pal_instance_callbacks);
}
static const device_interrupt_port_descriptor hw_pal_interrupt_ports[] = {
{ "int", 0, MAX_NR_PROCESSORS },
{ NULL }
};
static void
hw_pal_attach_address(device *me,
attach_type attach,
int space,
unsigned_word addr,
unsigned nr_bytes,
access_type access,
device *client)
{
hw_pal_device *pal = (hw_pal_device*)device_data(me);
pal->disk = client;
}
static device_callbacks const hw_pal_callbacks = {
{ generic_device_init_address, },
{ hw_pal_attach_address, }, /* address */
{ hw_pal_io_read_buffer_callback,
hw_pal_io_write_buffer_callback, },
{ NULL, }, /* DMA */
{ NULL, NULL, hw_pal_interrupt_ports }, /* interrupt */
{ generic_device_unit_decode,
generic_device_unit_encode,
generic_device_address_to_attach_address,
generic_device_size_to_attach_size },
hw_pal_create_instance,
};
static void *
hw_pal_create(const char *name,
const device_unit *unit_address,
const char *args)
{
/* create the descriptor */
hw_pal_device *hw_pal = ZALLOC(hw_pal_device);
hw_pal->output.status = 1;
hw_pal->output.buffer = '\0';
hw_pal->input.status = 0;
hw_pal->input.buffer = '\0';
return hw_pal;
}
const device_descriptor hw_pal_device_descriptor[] = {
{ "pal", hw_pal_create, &hw_pal_callbacks },
{ NULL },
};
#endif /* _HW_PAL_C_ */
| zxombie/aarch64-freebsd-binutils | sim/ppc/hw_pal.c | C | gpl-2.0 | 9,416 |
/******************************************************************************
*
* Name: acresrc.h - Resource Manager function prototypes
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#ifndef __ACRESRC_H__
#define __ACRESRC_H__
/* Need the AML resource descriptor structs */
#include "amlresrc.h"
/*
* If possible, pack the following structures to byte alignment, since we
* don't care about performance for debug output. Two cases where we cannot
* pack the structures:
*
* 1) Hardware does not support misaligned memory transfers
* 2) Compiler does not support pointers within packed structures
*/
#if (!defined(ACPI_MISALIGNMENT_NOT_SUPPORTED) && !defined(ACPI_PACKED_POINTERS_NOT_SUPPORTED))
#pragma pack(1)
#endif
/*
* Individual entry for the resource conversion tables
*/
typedef const struct acpi_rsconvert_info {
u8 opcode;
u8 resource_offset;
u8 aml_offset;
u8 value;
} acpi_rsconvert_info;
/* Resource conversion opcodes */
#define ACPI_RSC_INITGET 0
#define ACPI_RSC_INITSET 1
#define ACPI_RSC_FLAGINIT 2
#define ACPI_RSC_1BITFLAG 3
#define ACPI_RSC_2BITFLAG 4
#define ACPI_RSC_COUNT 5
#define ACPI_RSC_COUNT16 6
#define ACPI_RSC_LENGTH 7
#define ACPI_RSC_MOVE8 8
#define ACPI_RSC_MOVE16 9
#define ACPI_RSC_MOVE32 10
#define ACPI_RSC_MOVE64 11
#define ACPI_RSC_SET8 12
#define ACPI_RSC_DATA8 13
#define ACPI_RSC_ADDRESS 14
#define ACPI_RSC_SOURCE 15
#define ACPI_RSC_SOURCEX 16
#define ACPI_RSC_BITMASK 17
#define ACPI_RSC_BITMASK16 18
#define ACPI_RSC_EXIT_NE 19
#define ACPI_RSC_EXIT_LE 20
#define ACPI_RSC_EXIT_EQ 21
/* Resource Conversion sub-opcodes */
#define ACPI_RSC_COMPARE_AML_LENGTH 0
#define ACPI_RSC_COMPARE_VALUE 1
#define ACPI_RSC_TABLE_SIZE(d) (sizeof (d) / sizeof (struct acpi_rsconvert_info))
#define ACPI_RS_OFFSET(f) (u8) ACPI_OFFSET (struct acpi_resource,f)
#define AML_OFFSET(f) (u8) ACPI_OFFSET (union aml_resource,f)
typedef const struct acpi_rsdump_info {
u8 opcode;
u8 offset;
char *name;
const char **pointer;
} acpi_rsdump_info;
/* Values for the Opcode field above */
#define ACPI_RSD_TITLE 0
#define ACPI_RSD_LITERAL 1
#define ACPI_RSD_STRING 2
#define ACPI_RSD_UINT8 3
#define ACPI_RSD_UINT16 4
#define ACPI_RSD_UINT32 5
#define ACPI_RSD_UINT64 6
#define ACPI_RSD_1BITFLAG 7
#define ACPI_RSD_2BITFLAG 8
#define ACPI_RSD_SHORTLIST 9
#define ACPI_RSD_LONGLIST 10
#define ACPI_RSD_DWORDLIST 11
#define ACPI_RSD_ADDRESS 12
#define ACPI_RSD_SOURCE 13
/* restore default alignment */
#pragma pack()
/* Resource tables indexed by internal resource type */
extern const u8 acpi_gbl_aml_resource_sizes[];
extern struct acpi_rsconvert_info *acpi_gbl_set_resource_dispatch[];
/* Resource tables indexed by raw AML resource descriptor type */
extern const u8 acpi_gbl_resource_struct_sizes[];
extern struct acpi_rsconvert_info *acpi_gbl_get_resource_dispatch[];
struct acpi_vendor_walk_info {
struct acpi_vendor_uuid *uuid;
struct acpi_buffer *buffer;
acpi_status status;
};
/*
* rscreate
*/
acpi_status
acpi_rs_create_resource_list(union acpi_operand_object *aml_buffer,
struct acpi_buffer *output_buffer);
acpi_status
acpi_rs_create_aml_resources(struct acpi_resource *linked_list_buffer,
struct acpi_buffer *output_buffer);
acpi_status
acpi_rs_create_pci_routing_table(union acpi_operand_object *package_object,
struct acpi_buffer *output_buffer);
/*
* rsutils
*/
acpi_status
acpi_rs_get_prt_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer);
acpi_status
acpi_rs_get_crs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer);
acpi_status
acpi_rs_get_prs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer);
acpi_status
acpi_rs_get_method_data(acpi_handle handle,
char *path, struct acpi_buffer *ret_buffer);
acpi_status
acpi_rs_set_srs_method_data(struct acpi_namespace_node *node,
struct acpi_buffer *ret_buffer);
/*
* rscalc
*/
acpi_status
acpi_rs_get_list_length(u8 * aml_buffer,
u32 aml_buffer_length, acpi_size * size_needed);
acpi_status
acpi_rs_get_aml_length(struct acpi_resource *linked_list_buffer,
acpi_size * size_needed);
acpi_status
acpi_rs_get_pci_routing_table_length(union acpi_operand_object *package_object,
acpi_size * buffer_size_needed);
acpi_status
acpi_rs_convert_aml_to_resources(u8 * aml,
u32 length,
u32 offset, u8 resource_index, void **context);
acpi_status
acpi_rs_convert_resources_to_aml(struct acpi_resource *resource,
acpi_size aml_size_needed, u8 * output_buffer);
/*
* rsaddr
*/
void
acpi_rs_set_address_common(union aml_resource *aml,
struct acpi_resource *resource);
u8
acpi_rs_get_address_common(struct acpi_resource *resource,
union aml_resource *aml);
/*
* rsmisc
*/
acpi_status
acpi_rs_convert_aml_to_resource(struct acpi_resource *resource,
union aml_resource *aml,
struct acpi_rsconvert_info *info);
acpi_status
acpi_rs_convert_resource_to_aml(struct acpi_resource *resource,
union aml_resource *aml,
struct acpi_rsconvert_info *info);
/*
* rsutils
*/
void
acpi_rs_move_data(void *destination,
void *source, u16 item_count, u8 move_type);
u8 acpi_rs_decode_bitmask(u16 mask, u8 * list);
u16 acpi_rs_encode_bitmask(u8 * list, u8 count);
acpi_rs_length
acpi_rs_get_resource_source(acpi_rs_length resource_length,
acpi_rs_length minimum_length,
struct acpi_resource_source *resource_source,
union aml_resource *aml, char *string_ptr);
acpi_rsdesc_size
acpi_rs_set_resource_source(union aml_resource *aml,
acpi_rs_length minimum_length,
struct acpi_resource_source *resource_source);
void
acpi_rs_set_resource_header(u8 descriptor_type,
acpi_rsdesc_size total_length,
union aml_resource *aml);
void
acpi_rs_set_resource_length(acpi_rsdesc_size total_length,
union aml_resource *aml);
/*
* rsdump
*/
void acpi_rs_dump_resource_list(struct acpi_resource *resource);
void acpi_rs_dump_irq_list(u8 * route_table);
/*
* Resource conversion tables
*/
extern struct acpi_rsconvert_info acpi_rs_convert_dma[];
extern struct acpi_rsconvert_info acpi_rs_convert_end_dpf[];
extern struct acpi_rsconvert_info acpi_rs_convert_io[];
extern struct acpi_rsconvert_info acpi_rs_convert_fixed_io[];
extern struct acpi_rsconvert_info acpi_rs_convert_end_tag[];
extern struct acpi_rsconvert_info acpi_rs_convert_memory24[];
extern struct acpi_rsconvert_info acpi_rs_convert_generic_reg[];
extern struct acpi_rsconvert_info acpi_rs_convert_memory32[];
extern struct acpi_rsconvert_info acpi_rs_convert_fixed_memory32[];
extern struct acpi_rsconvert_info acpi_rs_convert_address32[];
extern struct acpi_rsconvert_info acpi_rs_convert_address16[];
extern struct acpi_rsconvert_info acpi_rs_convert_ext_irq[];
extern struct acpi_rsconvert_info acpi_rs_convert_address64[];
extern struct acpi_rsconvert_info acpi_rs_convert_ext_address64[];
/* These resources require separate get/set tables */
extern struct acpi_rsconvert_info acpi_rs_get_irq[];
extern struct acpi_rsconvert_info acpi_rs_get_start_dpf[];
extern struct acpi_rsconvert_info acpi_rs_get_vendor_small[];
extern struct acpi_rsconvert_info acpi_rs_get_vendor_large[];
extern struct acpi_rsconvert_info acpi_rs_set_irq[];
extern struct acpi_rsconvert_info acpi_rs_set_start_dpf[];
extern struct acpi_rsconvert_info acpi_rs_set_vendor[];
#if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER)
/*
* rsinfo
*/
extern struct acpi_rsdump_info *acpi_gbl_dump_resource_dispatch[];
/*
* rsdump
*/
extern struct acpi_rsdump_info acpi_rs_dump_irq[];
extern struct acpi_rsdump_info acpi_rs_dump_dma[];
extern struct acpi_rsdump_info acpi_rs_dump_start_dpf[];
extern struct acpi_rsdump_info acpi_rs_dump_end_dpf[];
extern struct acpi_rsdump_info acpi_rs_dump_io[];
extern struct acpi_rsdump_info acpi_rs_dump_fixed_io[];
extern struct acpi_rsdump_info acpi_rs_dump_vendor[];
extern struct acpi_rsdump_info acpi_rs_dump_end_tag[];
extern struct acpi_rsdump_info acpi_rs_dump_memory24[];
extern struct acpi_rsdump_info acpi_rs_dump_memory32[];
extern struct acpi_rsdump_info acpi_rs_dump_fixed_memory32[];
extern struct acpi_rsdump_info acpi_rs_dump_address16[];
extern struct acpi_rsdump_info acpi_rs_dump_address32[];
extern struct acpi_rsdump_info acpi_rs_dump_address64[];
extern struct acpi_rsdump_info acpi_rs_dump_ext_address64[];
extern struct acpi_rsdump_info acpi_rs_dump_ext_irq[];
extern struct acpi_rsdump_info acpi_rs_dump_generic_reg[];
#endif
#endif /* __ACRESRC_H__ */
| JijonHyuni/HyperKernel-JB | virt/drivers/acpi/acpica/acresrc.h | C | gpl-2.0 | 11,064 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
namespace System.Threading.Tasks
{
internal static class ExceptionDispatchHelper
{
internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext)
{
if (exception == null)
return;
// TODO - decide how to cleanly do it so it lights up if TA is defined
//if (exception is ThreadAbortException)
// return;
ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception);
if (targetContext != null)
{
try
{
targetContext.Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
}
catch
{
// Something went wrong in the Post; let's try using the thread pool instead:
ThrowAsync(exception, null);
}
return;
}
bool scheduled = true;
try
{
new SynchronizationContext().Post((edi) => ((ExceptionDispatchInfo)edi).Throw(), exceptionDispatchInfo);
}
catch
{
// Something went wrong when scheduling the thrower; we do our best by throwing the exception here:
scheduled = false;
}
if (!scheduled)
exceptionDispatchInfo.Throw();
}
} // ExceptionDispatchHelper
} // namespace
// ExceptionDispatchHelper.cs
| krytarowski/corefx | src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/ExceptionDispatchHelper.cs | C# | mit | 1,835 |
/* Copyright (C) 1996 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#define DATABASE_NAME publickey
#define DEFAULT_CONFIG "nis nisplus"
#include "XXX-lookup.c"
| GarethNelson/Zoidberg | userland/newlib/newlib/libc/sys/linux/net/key-lookup.c | C | gpl-2.0 | 1,006 |
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require_once(dirname(__FILE__).'/../../bootstrap/unit.php');
class FormFormatterStub extends sfWidgetFormSchemaFormatter
{
public function __construct() {}
public function translate($subject, $parameters = array())
{
return sprintf('translation[%s]', $subject);
}
}
$t = new lime_test(13);
$dom = new DomDocument('1.0', 'utf-8');
$dom->validateOnParse = true;
// ->render()
$t->diag('->render()');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => 'bar', 'foobar' => 'foo'), 'separator' => ''));
$output = '<ul class="checkbox_list">'.
'<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" /> <label for="foo_foo">bar</label></li>'.
'<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" /> <label for="foo_foobar">foo</label></li>'.
'</ul>';
$t->is($w->render('foo', array('foobar')), $output, '->render() renders a checkbox tag with the value checked');
// attributes
$onChange = '<ul class="checkbox_list">'.
'<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" onChange="alert(42)" />'.
' <label for="foo_foo">bar</label></li>'.
'<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" onChange="alert(42)" />'.
' <label for="foo_foobar">foo</label></li>'.
'</ul>';
$t->is($w->render('foo', array('foobar'), array('onChange' => 'alert(42)')), $onChange, '->render() renders a checkbox tag using extra attributes');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('0' => 'bar', '1' => 'foo')));
$output = <<< EOF
<ul class="checkbox_list"><li><input name="myname[]" type="checkbox" value="0" id="myname_0" checked="checked" /> <label for="myname_0">bar</label></li>
<li><input name="myname[]" type="checkbox" value="1" id="myname_1" /> <label for="myname_1">foo</label></li></ul>
EOF;
$t->is($w->render('myname', array(false)), fix_linebreaks($output), '->render() considers false to be an integer 0');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('0' => 'bar', '1' => 'foo')));
$output = <<< EOF
<ul class="checkbox_list"><li><input name="myname[]" type="checkbox" value="0" id="myname_0" /> <label for="myname_0">bar</label></li>
<li><input name="myname[]" type="checkbox" value="1" id="myname_1" checked="checked" /> <label for="myname_1">foo</label></li></ul>
EOF;
$t->is($w->render('myname', array(true)), fix_linebreaks($output), '->render() considers true to be an integer 1');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array()));
$t->is($w->render('myname', array()), '', '->render() returns an empty HTML string if no choices');
// group support
$t->diag('group support');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => array('foo' => 'bar', 'bar' => 'foo'), 'bar' => array('foobar' => 'barfoo'))));
$output = <<<EOF
foo <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" checked="checked" /> <label for="foo_foo">bar</label></li>
<li><input name="foo[]" type="checkbox" value="bar" id="foo_bar" /> <label for="foo_bar">foo</label></li></ul>
bar <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" checked="checked" /> <label for="foo_foobar">barfoo</label></li></ul>
EOF;
$t->is($w->render('foo', array('foo', 'foobar')), fix_linebreaks($output), '->render() has support for groups');
$w->setOption('choices', array('foo' => array('foo' => 'bar', 'bar' => 'foo')));
$output = <<<EOF
foo <ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" /> <label for="foo_foo">bar</label></li>
<li><input name="foo[]" type="checkbox" value="bar" id="foo_bar" checked="checked" /> <label for="foo_bar">foo</label></li></ul>
EOF;
$t->is($w->render('foo', array('bar')), fix_linebreaks($output), '->render() accepts a single group');
try
{
$w = new sfWidgetFormSelectCheckbox();
$t->fail('__construct() throws an RuntimeException if you don\'t pass a choices option');
}
catch (RuntimeException $e)
{
$t->pass('__construct() throws an RuntimeException if you don\'t pass a choices option');
}
// choices as a callable
$t->diag('choices as a callable');
function choice_callable()
{
return array(1, 2, 3);
}
$w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable('choice_callable')));
$dom->loadHTML($w->render('foo'));
$css = new sfDomCssSelector($dom);
$t->is(count($css->matchAll('input[type="checkbox"]')->getNodes()), 3, '->render() accepts a sfCallable as a choices option');
// choices are translated
$t->diag('choices are translated');
$ws = new sfWidgetFormSchema();
$ws->addFormFormatter('stub', new FormFormatterStub());
$ws->setFormFormatterName('stub');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('foo' => 'bar', 'foobar' => 'foo'), 'separator' => ''));
$w->setParent($ws);
$output = '<ul class="checkbox_list">'.
'<li><input name="foo[]" type="checkbox" value="foo" id="foo_foo" /> <label for="foo_foo">translation[bar]</label></li>'.
'<li><input name="foo[]" type="checkbox" value="foobar" id="foo_foobar" /> <label for="foo_foobar">translation[foo]</label></li>'.
'</ul>';
$t->is($w->render('foo'), $output, '->render() translates the options');
// choices are escaped
$t->diag('choices are escaped');
$w = new sfWidgetFormSelectCheckbox(array('choices' => array('<b>Hello world</b>')));
$t->is($w->render('foo'), '<ul class="checkbox_list"><li><input name="foo[]" type="checkbox" value="0" id="foo_0" /> <label for="foo_0"><b>Hello world</b></label></li></ul>', '->render() escapes the choices');
// __clone()
$t->diag('__clone()');
$w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable(array($w, 'foo'))));
$w1 = clone $w;
$callable = $w1->getOption('choices')->getCallable();
$t->is(spl_object_hash($callable[0]), spl_object_hash($w1), '__clone() changes the choices is a callable and the object is an instance of the current object');
$w = new sfWidgetFormSelectCheckbox(array('choices' => new sfCallable(array($a = new stdClass(), 'foo'))));
$w1 = clone $w;
$callable = $w1->getOption('choices')->getCallable();
$t->is(spl_object_hash($callable[0]), spl_object_hash($a), '__clone() changes nothing if the choices is a callable and the object is not an instance of the current object');
| voota/voota | www/lib/vendor/symfony/test/unit/widget/sfWidgetFormSelectCheckboxTest.php | PHP | mit | 6,638 |
/*
* linux/arch/arm/mm/dma-mapping.c
*
* Copyright (C) 2000-2004 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* DMA uncached mapping support.
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/gfp.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/dma-contiguous.h>
#include <linux/highmem.h>
#include <linux/memblock.h>
#include <linux/slab.h>
#include <linux/iommu.h>
#include <linux/vmalloc.h>
#include <asm/memory.h>
#include <asm/highmem.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/sizes.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/system_info.h>
#include <asm/dma-contiguous.h>
#include <asm/dma-iommu.h>
#include "mm.h"
/*
* The DMA API is built upon the notion of "buffer ownership". A buffer
* is either exclusively owned by the CPU (and therefore may be accessed
* by it) or exclusively owned by the DMA device. These helper functions
* represent the transitions between these two ownership states.
*
* Note, however, that on later ARMs, this notion does not work due to
* speculative prefetches. We model our approach on the assumption that
* the CPU does do speculative prefetches, which means we clean caches
* before transfers and delay cache invalidation until transfer completion.
*
*/
static void __dma_page_cpu_to_dev(struct page *, unsigned long,
size_t, enum dma_data_direction);
static void __dma_page_dev_to_cpu(struct page *, unsigned long,
size_t, enum dma_data_direction);
/**
* arm_dma_map_page - map a portion of a page for streaming DMA
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @page: page that buffer resides in
* @offset: offset into page for start of buffer
* @size: size of buffer to map
* @dir: DMA transfer direction
*
* Ensure that any data held in the cache is appropriately discarded
* or written back.
*
* The device owns this memory once this call has completed. The CPU
* can regain ownership by calling dma_unmap_page().
*/
static dma_addr_t arm_dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
return pfn_to_dma(dev, page_to_pfn(page)) + offset;
}
/**
* arm_dma_unmap_page - unmap a buffer previously mapped through dma_map_page()
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @handle: DMA address of buffer
* @size: size of buffer (same as passed to dma_map_page)
* @dir: DMA transfer direction (same as passed to dma_map_page)
*
* Unmap a page streaming mode DMA translation. The handle and size
* must match what was provided in the previous dma_map_page() call.
* All other usages are undefined.
*
* After this call, reads by the CPU to the buffer are guaranteed to see
* whatever the device wrote there.
*/
static void arm_dma_unmap_page(struct device *dev, dma_addr_t handle,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
if (!arch_is_coherent())
__dma_page_dev_to_cpu(pfn_to_page(dma_to_pfn(dev, handle)),
handle & ~PAGE_MASK, size, dir);
}
static void arm_dma_sync_single_for_cpu(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
unsigned int offset = handle & (PAGE_SIZE - 1);
struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
}
static void arm_dma_sync_single_for_device(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
unsigned int offset = handle & (PAGE_SIZE - 1);
struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
}
static int arm_dma_set_mask(struct device *dev, u64 dma_mask);
struct dma_map_ops arm_dma_ops = {
.alloc = arm_dma_alloc,
.free = arm_dma_free,
.mmap = arm_dma_mmap,
.map_page = arm_dma_map_page,
.unmap_page = arm_dma_unmap_page,
.map_sg = arm_dma_map_sg,
.unmap_sg = arm_dma_unmap_sg,
.sync_single_for_cpu = arm_dma_sync_single_for_cpu,
.sync_single_for_device = arm_dma_sync_single_for_device,
.sync_sg_for_cpu = arm_dma_sync_sg_for_cpu,
.sync_sg_for_device = arm_dma_sync_sg_for_device,
.set_dma_mask = arm_dma_set_mask,
};
EXPORT_SYMBOL(arm_dma_ops);
static u64 get_coherent_dma_mask(struct device *dev)
{
u64 mask = (u64)arm_dma_limit;
if (dev) {
mask = dev->coherent_dma_mask;
/*
* Sanity check the DMA mask - it must be non-zero, and
* must be able to be satisfied by a DMA allocation.
*/
if (mask == 0) {
dev_warn(dev, "coherent DMA mask is unset\n");
return 0;
}
if ((~mask) & (u64)arm_dma_limit) {
dev_warn(dev, "coherent DMA mask %#llx is smaller "
"than system GFP_DMA mask %#llx\n",
mask, (u64)arm_dma_limit);
return 0;
}
}
return mask;
}
static void __dma_clear_buffer(struct page *page, size_t size)
{
/*
* Ensure that the allocated pages are zeroed, and that any data
* lurking in the kernel direct-mapped region is invalidated.
*/
if (!PageHighMem(page)) {
void *ptr = page_address(page);
if (ptr) {
memset(ptr, 0, size);
dmac_flush_range(ptr, ptr + size);
outer_flush_range(__pa(ptr), __pa(ptr) + size);
}
} else {
phys_addr_t base = __pfn_to_phys(page_to_pfn(page));
phys_addr_t end = base + size;
while (size > 0) {
void *ptr = kmap_atomic(page);
memset(ptr, 0, PAGE_SIZE);
dmac_flush_range(ptr, ptr + PAGE_SIZE);
kunmap_atomic(ptr);
page++;
size -= PAGE_SIZE;
}
outer_flush_range(base, end);
}
}
/*
* Allocate a DMA buffer for 'dev' of size 'size' using the
* specified gfp mask. Note that 'size' must be page aligned.
*/
static struct page *__dma_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
{
unsigned long order = get_order(size);
struct page *page, *p, *e;
page = alloc_pages(gfp, order);
if (!page)
return NULL;
/*
* Now split the huge page and free the excess pages
*/
split_page(page, order);
for (p = page + (size >> PAGE_SHIFT), e = page + (1 << order); p < e; p++)
__free_page(p);
__dma_clear_buffer(page, size);
return page;
}
/*
* Free a DMA buffer. 'size' must be page aligned.
*/
static void __dma_free_buffer(struct page *page, size_t size)
{
struct page *e = page + (size >> PAGE_SHIFT);
while (page < e) {
__free_page(page);
page++;
}
}
#ifdef CONFIG_MMU
#define CONSISTENT_OFFSET(x) (((unsigned long)(x) - consistent_base) >> PAGE_SHIFT)
#define CONSISTENT_PTE_INDEX(x) (((unsigned long)(x) - consistent_base) >> PMD_SHIFT)
/*
* These are the page tables (2MB each) covering uncached, DMA consistent allocations
*/
static pte_t **consistent_pte;
#define DEFAULT_CONSISTENT_DMA_SIZE (7*SZ_2M)
static unsigned long consistent_base = CONSISTENT_END - DEFAULT_CONSISTENT_DMA_SIZE;
void __init init_consistent_dma_size(unsigned long size)
{
unsigned long base = CONSISTENT_END - ALIGN(size, SZ_2M);
BUG_ON(consistent_pte); /* Check we're called before DMA region init */
BUG_ON(base < VMALLOC_END);
/* Grow region to accommodate specified size */
if (base < consistent_base)
consistent_base = base;
}
#include "vmregion.h"
static struct arm_vmregion_head consistent_head = {
.vm_lock = __SPIN_LOCK_UNLOCKED(&consistent_head.vm_lock),
.vm_list = LIST_HEAD_INIT(consistent_head.vm_list),
.vm_end = CONSISTENT_END,
};
#ifdef CONFIG_HUGETLB_PAGE
#error ARM Coherent DMA allocator does not (yet) support huge TLB
#endif
/*
* Initialise the consistent memory allocation.
*/
static int __init consistent_init(void)
{
int ret = 0;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int i = 0;
unsigned long base = consistent_base;
unsigned long num_ptes = (CONSISTENT_END - base) >> PMD_SHIFT;
if (IS_ENABLED(CONFIG_CMA) && !IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU))
return 0;
consistent_pte = kmalloc(num_ptes * sizeof(pte_t), GFP_KERNEL);
if (!consistent_pte) {
pr_err("%s: no memory\n", __func__);
return -ENOMEM;
}
pr_debug("DMA memory: 0x%08lx - 0x%08lx:\n", base, CONSISTENT_END);
consistent_head.vm_start = base;
do {
pgd = pgd_offset(&init_mm, base);
pud = pud_alloc(&init_mm, pgd, base);
if (!pud) {
pr_err("%s: no pud tables\n", __func__);
ret = -ENOMEM;
break;
}
pmd = pmd_alloc(&init_mm, pud, base);
if (!pmd) {
pr_err("%s: no pmd tables\n", __func__);
ret = -ENOMEM;
break;
}
WARN_ON(!pmd_none(*pmd));
pte = pte_alloc_kernel(pmd, base);
if (!pte) {
pr_err("%s: no pte tables\n", __func__);
ret = -ENOMEM;
break;
}
consistent_pte[i++] = pte;
base += PMD_SIZE;
} while (base < CONSISTENT_END);
return ret;
}
core_initcall(consistent_init);
static void *__alloc_from_contiguous(struct device *dev, size_t size,
pgprot_t prot, struct page **ret_page,
bool no_kernel_mapping, const void *caller);
static struct arm_vmregion_head coherent_head = {
.vm_lock = __SPIN_LOCK_UNLOCKED(&coherent_head.vm_lock),
.vm_list = LIST_HEAD_INIT(coherent_head.vm_list),
};
static size_t coherent_pool_size = DEFAULT_CONSISTENT_DMA_SIZE / 8;
static int __init early_coherent_pool(char *p)
{
coherent_pool_size = memparse(p, &p);
return 0;
}
early_param("coherent_pool", early_coherent_pool);
/*
* Initialise the coherent pool for atomic allocations.
*/
static int __init coherent_init(void)
{
pgprot_t prot = pgprot_dmacoherent(pgprot_kernel);
size_t size = coherent_pool_size;
struct page *page;
void *ptr;
if (!IS_ENABLED(CONFIG_CMA))
return 0;
ptr = __alloc_from_contiguous(NULL, size, prot, &page, false,
coherent_init);
if (ptr) {
coherent_head.vm_start = (unsigned long) ptr;
coherent_head.vm_end = (unsigned long) ptr + size;
printk(KERN_INFO "DMA: preallocated %u KiB pool for atomic coherent allocations\n",
(unsigned)size / 1024);
return 0;
}
printk(KERN_ERR "DMA: failed to allocate %u KiB pool for atomic coherent allocation\n",
(unsigned)size / 1024);
return -ENOMEM;
}
/*
* CMA is activated by core_initcall, so we must be called after it.
*/
postcore_initcall(coherent_init);
struct dma_contig_early_reserve {
phys_addr_t base;
unsigned long size;
};
static struct dma_contig_early_reserve dma_mmu_remap[MAX_CMA_AREAS] __initdata;
static int dma_mmu_remap_num __initdata;
void __init dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
{
dma_mmu_remap[dma_mmu_remap_num].base = base;
dma_mmu_remap[dma_mmu_remap_num].size = size;
dma_mmu_remap_num++;
}
void __init dma_contiguous_remap(void)
{
int i;
for (i = 0; i < dma_mmu_remap_num; i++) {
phys_addr_t start = dma_mmu_remap[i].base;
phys_addr_t end = start + dma_mmu_remap[i].size;
struct map_desc map;
unsigned long addr;
if (end > arm_lowmem_limit)
end = arm_lowmem_limit;
if (start >= end)
continue;
map.pfn = __phys_to_pfn(start);
map.virtual = __phys_to_virt(start);
map.length = end - start;
map.type = MT_MEMORY_DMA_READY;
/*
* Clear previous low-memory mapping
*/
for (addr = __phys_to_virt(start); addr < __phys_to_virt(end);
addr += PMD_SIZE)
pmd_clear(pmd_off_k(addr));
iotable_init(&map, 1);
}
}
static void *
__dma_alloc_remap(struct page *page, size_t size, gfp_t gfp, pgprot_t prot,
const void *caller)
{
struct arm_vmregion *c;
size_t align;
int bit;
if (!consistent_pte) {
pr_err("%s: not initialised\n", __func__);
dump_stack();
return NULL;
}
/*
* Align the virtual region allocation - maximum alignment is
* a section size, minimum is a page size. This helps reduce
* fragmentation of the DMA space, and also prevents allocations
* smaller than a section from crossing a section boundary.
*/
bit = fls(size - 1);
if (bit > SECTION_SHIFT)
bit = SECTION_SHIFT;
align = 1 << bit;
/*
* Allocate a virtual address in the consistent mapping region.
*/
c = arm_vmregion_alloc(&consistent_head, align, size,
gfp & ~(__GFP_DMA | __GFP_HIGHMEM), caller);
if (c) {
pte_t *pte;
int idx = CONSISTENT_PTE_INDEX(c->vm_start);
u32 off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
pte = consistent_pte[idx] + off;
c->priv = page;
do {
BUG_ON(!pte_none(*pte));
set_pte_ext(pte, mk_pte(page, prot), 0);
page++;
pte++;
off++;
if (off >= PTRS_PER_PTE) {
off = 0;
pte = consistent_pte[++idx];
}
} while (size -= PAGE_SIZE);
dsb();
return (void *)c->vm_start;
}
return NULL;
}
static void __dma_free_remap(void *cpu_addr, size_t size, bool no_warn)
{
struct arm_vmregion *c;
unsigned long addr;
pte_t *ptep;
int idx;
u32 off;
c = arm_vmregion_find_remove(&consistent_head, (unsigned long)cpu_addr);
if (!c) {
if (!no_warn) {
pr_err("%s: trying to free invalid coherent area: %p\n",
__func__, cpu_addr);
dump_stack();
}
return;
}
if ((c->vm_end - c->vm_start) != size) {
pr_err("%s: freeing wrong coherent size (%ld != %d)\n",
__func__, c->vm_end - c->vm_start, size);
dump_stack();
size = c->vm_end - c->vm_start;
}
idx = CONSISTENT_PTE_INDEX(c->vm_start);
off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
ptep = consistent_pte[idx] + off;
addr = c->vm_start;
do {
pte_t pte = ptep_get_and_clear(&init_mm, addr, ptep);
ptep++;
addr += PAGE_SIZE;
off++;
if (off >= PTRS_PER_PTE) {
off = 0;
ptep = consistent_pte[++idx];
}
if (pte_none(pte) || !pte_present(pte))
pr_crit("%s: bad page in kernel page table\n",
__func__);
} while (size -= PAGE_SIZE);
flush_tlb_kernel_range(c->vm_start, c->vm_end);
arm_vmregion_free(&consistent_head, c);
}
static int __dma_update_pte(pte_t *pte, pgtable_t token, unsigned long addr,
void *data)
{
struct page *page = virt_to_page(addr);
pgprot_t prot = *(pgprot_t *)data;
set_pte_ext(pte, mk_pte(page, prot), 0);
return 0;
}
static int __dma_clear_pte(pte_t *pte, pgtable_t token, unsigned long addr,
void *data)
{
pte_clear(&init_mm, addr, pte);
return 0;
}
static void __dma_remap(struct page *page, size_t size, pgprot_t prot,
bool no_kernel_map)
{
unsigned long start = (unsigned long) page_address(page);
unsigned end = start + size;
int (*func)(pte_t *pte, pgtable_t token, unsigned long addr,
void *data);
if (no_kernel_map)
func = __dma_clear_pte;
else
func = __dma_update_pte;
apply_to_page_range(&init_mm, start, size, func, &prot);
dsb();
flush_tlb_kernel_range(start, end);
}
static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
pgprot_t prot, struct page **ret_page,
const void *caller)
{
struct page *page;
void *ptr;
page = __dma_alloc_buffer(dev, size, gfp);
if (!page)
return NULL;
ptr = __dma_alloc_remap(page, size, gfp, prot, caller);
if (!ptr) {
__dma_free_buffer(page, size);
return NULL;
}
*ret_page = page;
return ptr;
}
static void *__alloc_from_pool(struct device *dev, size_t size,
struct page **ret_page, const void *caller)
{
struct arm_vmregion *c;
size_t align;
if (!coherent_head.vm_start) {
printk(KERN_ERR "%s: coherent pool not initialised!\n",
__func__);
dump_stack();
return NULL;
}
/*
* Align the region allocation - allocations from pool are rather
* small, so align them to their order in pages, minimum is a page
* size. This helps reduce fragmentation of the DMA space.
*/
align = PAGE_SIZE << get_order(size);
c = arm_vmregion_alloc(&coherent_head, align, size, 0, caller);
if (c) {
void *ptr = (void *)c->vm_start;
struct page *page = virt_to_page(ptr);
*ret_page = page;
return ptr;
}
return NULL;
}
static int __free_from_pool(void *cpu_addr, size_t size)
{
unsigned long start = (unsigned long)cpu_addr;
unsigned long end = start + size;
struct arm_vmregion *c;
if (start < coherent_head.vm_start || end > coherent_head.vm_end)
return 0;
c = arm_vmregion_find_remove(&coherent_head, (unsigned long)start);
if ((c->vm_end - c->vm_start) != size) {
printk(KERN_ERR "%s: freeing wrong coherent size (%ld != %d)\n",
__func__, c->vm_end - c->vm_start, size);
dump_stack();
size = c->vm_end - c->vm_start;
}
arm_vmregion_free(&coherent_head, c);
return 1;
}
#define NO_KERNEL_MAPPING_DUMMY 0x2222
static void *__alloc_from_contiguous(struct device *dev, size_t size,
pgprot_t prot, struct page **ret_page,
bool no_kernel_mapping,
const void *caller)
{
unsigned long order = get_order(size);
size_t count = size >> PAGE_SHIFT;
struct page *page;
void *ptr;
page = dma_alloc_from_contiguous(dev, count, order);
if (!page)
return NULL;
__dma_clear_buffer(page, size);
if (!PageHighMem(page)) {
__dma_remap(page, size, prot, no_kernel_mapping);
ptr = page_address(page);
} else {
if (no_kernel_mapping) {
/*
* Something non-NULL needs to be returned here. Give
* back a dummy address that is unmapped to catch
* clients trying to use the address incorrectly
*/
ptr = (void *)NO_KERNEL_MAPPING_DUMMY;
} else {
ptr = __dma_alloc_remap(page, size, GFP_KERNEL, prot,
caller);
if (!ptr) {
dma_release_from_contiguous(dev, page, count);
return NULL;
}
}
}
*ret_page = page;
return ptr;
}
static void __free_from_contiguous(struct device *dev, struct page *page,
void *cpu_addr, size_t size)
{
if (!PageHighMem(page))
__dma_remap(page, size, pgprot_kernel, false);
else
__dma_free_remap(cpu_addr, size, true);
dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT);
}
static inline pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot)
{
if (dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs))
prot = pgprot_writecombine(prot);
else if (dma_get_attr(DMA_ATTR_STRONGLY_ORDERED, attrs))
prot = pgprot_stronglyordered(prot);
/* if non-consistent just pass back what was given */
else if (!dma_get_attr(DMA_ATTR_NON_CONSISTENT, attrs))
prot = pgprot_dmacoherent(prot);
return prot;
}
#define nommu() 0
#else /* !CONFIG_MMU */
#define nommu() 1
#define __alloc_remap_buffer(dev, size, gfp, prot, ret, c) NULL
#define __alloc_from_pool(dev, size, ret_page, c) NULL
#define __alloc_from_contiguous(dev, size, prot, ret, w) NULL
#define __free_from_pool(cpu_addr, size) 0
#define __free_from_contiguous(dev, page, size) do { } while (0)
#define __dma_free_remap(cpu_addr, size) do { } while (0)
#define __get_dma_pgprot(attrs, prot) __pgprot(0)
#endif /* CONFIG_MMU */
static void *__alloc_simple_buffer(struct device *dev, size_t size, gfp_t gfp,
struct page **ret_page)
{
struct page *page;
page = __dma_alloc_buffer(dev, size, gfp);
if (!page)
return NULL;
*ret_page = page;
return page_address(page);
}
static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, pgprot_t prot, const void *caller,
bool no_kernel_mapping)
{
u64 mask = get_coherent_dma_mask(dev);
struct page *page;
void *addr;
#ifdef CONFIG_DMA_API_DEBUG
u64 limit = (mask + 1) & ~mask;
if (limit && size >= limit) {
dev_warn(dev, "coherent allocation too big (requested %#x mask %#llx)\n",
size, mask);
return NULL;
}
#endif
if (!mask)
return NULL;
if (mask < 0xffffffffULL)
gfp |= GFP_DMA;
/*
* Following is a work-around (a.k.a. hack) to prevent pages
* with __GFP_COMP being passed to split_page() which cannot
* handle them. The real problem is that this flag probably
* should be 0 on ARM as it is not supported on this
* platform; see CONFIG_HUGETLBFS.
*/
gfp &= ~(__GFP_COMP);
*handle = DMA_ERROR_CODE;
size = PAGE_ALIGN(size);
if (arch_is_coherent() || nommu())
addr = __alloc_simple_buffer(dev, size, gfp, &page);
else if (!IS_ENABLED(CONFIG_CMA))
addr = __alloc_remap_buffer(dev, size, gfp, prot, &page, caller);
else if (gfp & GFP_ATOMIC)
addr = __alloc_from_pool(dev, size, &page, caller);
else
addr = __alloc_from_contiguous(dev, size, prot, &page,
no_kernel_mapping, caller);
if (addr)
*handle = pfn_to_dma(dev, page_to_pfn(page));
return addr;
}
/*
* Allocate DMA-coherent memory space and return both the kernel remapped
* virtual and bus address for that space.
*/
void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
void *memory;
bool no_kernel_mapping = dma_get_attr(DMA_ATTR_NO_KERNEL_MAPPING,
attrs);
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot,
__builtin_return_address(0), no_kernel_mapping);
}
/*
* Create userspace mapping for the DMA-coherent memory.
*/
int arm_dma_mmap(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
int ret = -ENXIO;
#ifdef CONFIG_MMU
unsigned long pfn = dma_to_pfn(dev, dma_addr);
vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret))
return ret;
ret = remap_pfn_range(vma, vma->vm_start,
pfn + vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
#endif /* CONFIG_MMU */
return ret;
}
/*
* Free a buffer as defined by the above mapping.
*/
void arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t handle, struct dma_attrs *attrs)
{
struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
if (dma_release_from_coherent(dev, get_order(size), cpu_addr))
return;
size = PAGE_ALIGN(size);
if (arch_is_coherent() || nommu()) {
__dma_free_buffer(page, size);
} else if (!IS_ENABLED(CONFIG_CMA)) {
__dma_free_remap(cpu_addr, size, false);
__dma_free_buffer(page, size);
} else {
if (__free_from_pool(cpu_addr, size))
return;
/*
* Non-atomic allocations cannot be freed with IRQs disabled
*/
WARN_ON(irqs_disabled());
__free_from_contiguous(dev, page, cpu_addr, size);
}
}
static void dma_cache_maint_page(struct page *page, unsigned long offset,
size_t size, enum dma_data_direction dir,
void (*op)(const void *, size_t, int))
{
/*
* A single sg entry may refer to multiple physically contiguous
* pages. But we still need to process highmem pages individually.
* If highmem is not configured then the bulk of this loop gets
* optimized out.
*/
size_t left = size;
do {
size_t len = left;
void *vaddr;
if (PageHighMem(page)) {
if (len + offset > PAGE_SIZE) {
if (offset >= PAGE_SIZE) {
page += offset / PAGE_SIZE;
offset %= PAGE_SIZE;
}
len = PAGE_SIZE - offset;
}
if (cache_is_vipt_nonaliasing()) {
vaddr = kmap_atomic(page);
op(vaddr + offset, len, dir);
kunmap_atomic(vaddr);
} else {
vaddr = kmap_high_get(page);
if (vaddr) {
op(vaddr + offset, len, dir);
kunmap_high(page);
}
}
} else {
vaddr = page_address(page) + offset;
op(vaddr, len, dir);
}
offset = 0;
page++;
left -= len;
} while (left);
}
/*
* Make an area consistent for devices.
* Note: Drivers should NOT use this function directly, as it will break
* platforms with CONFIG_DMABOUNCE.
* Use the driver DMA support - see dma-mapping.h (dma_sync_*)
*/
static void __dma_page_cpu_to_dev(struct page *page, unsigned long off,
size_t size, enum dma_data_direction dir)
{
unsigned long paddr;
dma_cache_maint_page(page, off, size, dir, dmac_map_area);
paddr = page_to_phys(page) + off;
if (dir == DMA_FROM_DEVICE) {
outer_inv_range(paddr, paddr + size);
} else {
outer_clean_range(paddr, paddr + size);
}
/* FIXME: non-speculating: flush on bidirectional mappings? */
}
static void __dma_page_dev_to_cpu(struct page *page, unsigned long off,
size_t size, enum dma_data_direction dir)
{
unsigned long paddr = page_to_phys(page) + off;
/* FIXME: non-speculating: not required */
/* don't bother invalidating if DMA to device */
if (dir != DMA_TO_DEVICE)
outer_inv_range(paddr, paddr + size);
dma_cache_maint_page(page, off, size, dir, dmac_unmap_area);
/*
* Mark the D-cache clean for this page to avoid extra flushing.
*/
if (dir != DMA_TO_DEVICE && off == 0 && size >= PAGE_SIZE)
set_bit(PG_dcache_clean, &page->flags);
}
/**
* arm_dma_map_sg - map a set of SG buffers for streaming mode DMA
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map
* @dir: DMA transfer direction
*
* Map a set of buffers described by scatterlist in streaming mode for DMA.
* This is the scatter-gather version of the dma_map_single interface.
* Here the scatter gather list elements are each tagged with the
* appropriate dma address and length. They are obtained via
* sg_dma_{address,length}.
*
* Device ownership issues as mentioned for dma_map_single are the same
* here.
*/
int arm_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i, j;
for_each_sg(sg, s, nents, i) {
#ifdef CONFIG_NEED_SG_DMA_LENGTH
s->dma_length = s->length;
#endif
s->dma_address = ops->map_page(dev, sg_page(s), s->offset,
s->length, dir, attrs);
if (dma_mapping_error(dev, s->dma_address))
goto bad_mapping;
}
return nents;
bad_mapping:
for_each_sg(sg, s, i, j)
ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
return 0;
}
/**
* arm_dma_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to unmap (same as was passed to dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*
* Unmap a set of streaming mode DMA translations. Again, CPU access
* rules concerning calls here are the same as for dma_unmap_single().
*/
void arm_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
}
/**
* arm_dma_sync_sg_for_cpu
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->sync_single_for_cpu(dev, sg_dma_address(s), s->length,
dir);
}
/**
* arm_dma_sync_sg_for_device
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->sync_single_for_device(dev, sg_dma_address(s), s->length,
dir);
}
/*
* Return whether the given device DMA address mask can be supported
* properly. For example, if your device can only drive the low 24-bits
* during bus mastering, then you would pass 0x00ffffff as the mask
* to this function.
*/
int dma_supported(struct device *dev, u64 mask)
{
if (mask < (u64)arm_dma_limit)
return 0;
return 1;
}
EXPORT_SYMBOL(dma_supported);
static int arm_dma_set_mask(struct device *dev, u64 dma_mask)
{
if (!dev->dma_mask || !dma_supported(dev, dma_mask))
return -EIO;
*dev->dma_mask = dma_mask;
return 0;
}
#define PREALLOC_DMA_DEBUG_ENTRIES 4096
static int __init dma_debug_do_init(void)
{
#ifdef CONFIG_MMU
arm_vmregion_create_proc("dma-mappings", &consistent_head);
#endif
dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
return 0;
}
fs_initcall(dma_debug_do_init);
#ifdef CONFIG_ARM_DMA_USE_IOMMU
/* IOMMU */
static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
size_t size)
{
unsigned int order = get_order(size);
unsigned int align = 0;
unsigned int count, start;
unsigned long flags;
count = ((PAGE_ALIGN(size) >> PAGE_SHIFT) +
(1 << mapping->order) - 1) >> mapping->order;
if (order > mapping->order)
align = (1 << (order - mapping->order)) - 1;
spin_lock_irqsave(&mapping->lock, flags);
start = bitmap_find_next_zero_area(mapping->bitmap, mapping->bits, 0,
count, align);
if (start > mapping->bits) {
spin_unlock_irqrestore(&mapping->lock, flags);
return DMA_ERROR_CODE;
}
bitmap_set(mapping->bitmap, start, count);
spin_unlock_irqrestore(&mapping->lock, flags);
return mapping->base + (start << (mapping->order + PAGE_SHIFT));
}
static inline void __free_iova(struct dma_iommu_mapping *mapping,
dma_addr_t addr, size_t size)
{
unsigned int start = (addr - mapping->base) >>
(mapping->order + PAGE_SHIFT);
unsigned int count = ((size >> PAGE_SHIFT) +
(1 << mapping->order) - 1) >> mapping->order;
unsigned long flags;
spin_lock_irqsave(&mapping->lock, flags);
bitmap_clear(mapping->bitmap, start, count);
spin_unlock_irqrestore(&mapping->lock, flags);
}
static struct page **__iommu_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
{
struct page **pages;
int count = size >> PAGE_SHIFT;
int array_size = count * sizeof(struct page *);
int i = 0;
if (array_size <= PAGE_SIZE)
pages = kzalloc(array_size, gfp);
else
pages = vzalloc(array_size);
if (!pages)
return NULL;
while (count) {
int j, order = __fls(count);
pages[i] = alloc_pages(gfp | __GFP_NOWARN, order);
while (!pages[i] && order)
pages[i] = alloc_pages(gfp | __GFP_NOWARN, --order);
if (!pages[i])
goto error;
if (order)
split_page(pages[i], order);
j = 1 << order;
while (--j)
pages[i + j] = pages[i] + j;
__dma_clear_buffer(pages[i], PAGE_SIZE << order);
i += 1 << order;
count -= 1 << order;
}
return pages;
error:
while (--i)
if (pages[i])
__free_pages(pages[i], 0);
if (array_size < PAGE_SIZE)
kfree(pages);
else
vfree(pages);
return NULL;
}
static int __iommu_free_buffer(struct device *dev, struct page **pages, size_t size)
{
int count = size >> PAGE_SHIFT;
int array_size = count * sizeof(struct page *);
int i;
for (i = 0; i < count; i++)
if (pages[i])
__free_pages(pages[i], 0);
if (array_size < PAGE_SIZE)
kfree(pages);
else
vfree(pages);
return 0;
}
/*
* Create a CPU mapping for a specified pages
*/
static void *
__iommu_alloc_remap(struct page **pages, size_t size, gfp_t gfp, pgprot_t prot)
{
struct arm_vmregion *c;
size_t align;
size_t count = size >> PAGE_SHIFT;
int bit;
if (!consistent_pte[0]) {
pr_err("%s: not initialised\n", __func__);
dump_stack();
return NULL;
}
/*
* Align the virtual region allocation - maximum alignment is
* a section size, minimum is a page size. This helps reduce
* fragmentation of the DMA space, and also prevents allocations
* smaller than a section from crossing a section boundary.
*/
bit = fls(size - 1);
if (bit > SECTION_SHIFT)
bit = SECTION_SHIFT;
align = 1 << bit;
/*
* Allocate a virtual address in the consistent mapping region.
*/
c = arm_vmregion_alloc(&consistent_head, align, size,
gfp & ~(__GFP_DMA | __GFP_HIGHMEM), NULL);
if (c) {
pte_t *pte;
int idx = CONSISTENT_PTE_INDEX(c->vm_start);
int i = 0;
u32 off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
pte = consistent_pte[idx] + off;
c->priv = pages;
do {
BUG_ON(!pte_none(*pte));
set_pte_ext(pte, mk_pte(pages[i], prot), 0);
pte++;
off++;
i++;
if (off >= PTRS_PER_PTE) {
off = 0;
pte = consistent_pte[++idx];
}
} while (i < count);
dsb();
return (void *)c->vm_start;
}
return NULL;
}
/*
* Create a mapping in device IO address space for specified pages
*/
static dma_addr_t
__iommu_create_mapping(struct device *dev, struct page **pages, size_t size)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
dma_addr_t dma_addr, iova;
int i, ret = DMA_ERROR_CODE;
dma_addr = __alloc_iova(mapping, size);
if (dma_addr == DMA_ERROR_CODE)
return dma_addr;
iova = dma_addr;
for (i = 0; i < count; ) {
unsigned int next_pfn = page_to_pfn(pages[i]) + 1;
phys_addr_t phys = page_to_phys(pages[i]);
unsigned int len, j;
for (j = i + 1; j < count; j++, next_pfn++)
if (page_to_pfn(pages[j]) != next_pfn)
break;
len = (j - i) << PAGE_SHIFT;
ret = iommu_map(mapping->domain, iova, phys, len, 0);
if (ret < 0)
goto fail;
iova += len;
i = j;
}
return dma_addr;
fail:
iommu_unmap(mapping->domain, dma_addr, iova-dma_addr);
__free_iova(mapping, dma_addr, size);
return DMA_ERROR_CODE;
}
static int __iommu_remove_mapping(struct device *dev, dma_addr_t iova, size_t size)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
/*
* add optional in-page offset from iova to size and align
* result to page size
*/
size = PAGE_ALIGN((iova & ~PAGE_MASK) + size);
iova &= PAGE_MASK;
iommu_unmap(mapping->domain, iova, size);
__free_iova(mapping, iova, size);
return 0;
}
static void *arm_iommu_alloc_attrs(struct device *dev, size_t size,
dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
struct page **pages;
void *addr = NULL;
*handle = DMA_ERROR_CODE;
size = PAGE_ALIGN(size);
pages = __iommu_alloc_buffer(dev, size, gfp);
if (!pages)
return NULL;
*handle = __iommu_create_mapping(dev, pages, size);
if (*handle == DMA_ERROR_CODE)
goto err_buffer;
addr = __iommu_alloc_remap(pages, size, gfp, prot);
if (!addr)
goto err_mapping;
return addr;
err_mapping:
__iommu_remove_mapping(dev, *handle, size);
err_buffer:
__iommu_free_buffer(dev, pages, size);
return NULL;
}
static int arm_iommu_mmap_attrs(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
struct arm_vmregion *c;
vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
c = arm_vmregion_find(&consistent_head, (unsigned long)cpu_addr);
if (c) {
struct page **pages = c->priv;
unsigned long uaddr = vma->vm_start;
unsigned long usize = vma->vm_end - vma->vm_start;
int i = 0;
do {
int ret;
ret = vm_insert_page(vma, uaddr, pages[i++]);
if (ret) {
pr_err("Remapping memory, error: %d\n", ret);
return ret;
}
uaddr += PAGE_SIZE;
usize -= PAGE_SIZE;
} while (usize > 0);
}
return 0;
}
/*
* free a page as defined by the above mapping.
* Must not be called with IRQs disabled.
*/
void arm_iommu_free_attrs(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t handle, struct dma_attrs *attrs)
{
struct arm_vmregion *c;
size = PAGE_ALIGN(size);
c = arm_vmregion_find(&consistent_head, (unsigned long)cpu_addr);
if (c) {
struct page **pages = c->priv;
__dma_free_remap(cpu_addr, size, false);
__iommu_remove_mapping(dev, handle, size);
__iommu_free_buffer(dev, pages, size);
}
}
/*
* Map a part of the scatter-gather list into contiguous io address space
*/
static int __map_sg_chunk(struct device *dev, struct scatterlist *sg,
size_t size, dma_addr_t *handle,
enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova, iova_base;
int ret = 0;
unsigned int count;
struct scatterlist *s;
size = PAGE_ALIGN(size);
*handle = DMA_ERROR_CODE;
iova_base = iova = __alloc_iova(mapping, size);
if (iova == DMA_ERROR_CODE)
return -ENOMEM;
for (count = 0, s = sg; count < (size >> PAGE_SHIFT); s = sg_next(s)) {
phys_addr_t phys = page_to_phys(sg_page(s));
unsigned int len = PAGE_ALIGN(s->offset + s->length);
if (!arch_is_coherent())
__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
ret = iommu_map(mapping->domain, iova, phys, len, 0);
if (ret < 0)
goto fail;
count += len >> PAGE_SHIFT;
iova += len;
}
*handle = iova_base;
return 0;
fail:
iommu_unmap(mapping->domain, iova_base, count * PAGE_SIZE);
__free_iova(mapping, iova_base, size);
return ret;
}
/**
* arm_iommu_map_sg - map a set of SG buffers for streaming mode DMA
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map
* @dir: DMA transfer direction
*
* Map a set of buffers described by scatterlist in streaming mode for DMA.
* The scatter gather list elements are merged together (if possible) and
* tagged with the appropriate dma address and length. They are obtained via
* sg_dma_{address,length}.
*/
int arm_iommu_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s = sg, *dma = sg, *start = sg;
int i, count = 0;
unsigned int offset = s->offset;
unsigned int size = s->offset + s->length;
unsigned int max = dma_get_max_seg_size(dev);
for (i = 1; i < nents; i++) {
s = sg_next(s);
s->dma_address = DMA_ERROR_CODE;
s->dma_length = 0;
if (s->offset || (size & ~PAGE_MASK) || size + s->length > max) {
if (__map_sg_chunk(dev, start, size, &dma->dma_address,
dir) < 0)
goto bad_mapping;
dma->dma_address += offset;
dma->dma_length = size - offset;
size = offset = s->offset;
start = s;
dma = sg_next(dma);
count += 1;
}
size += s->length;
}
if (__map_sg_chunk(dev, start, size, &dma->dma_address, dir) < 0)
goto bad_mapping;
dma->dma_address += offset;
dma->dma_length = size - offset;
return count+1;
bad_mapping:
for_each_sg(sg, s, count, i)
__iommu_remove_mapping(dev, sg_dma_address(s), sg_dma_len(s));
return 0;
}
/**
* arm_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to unmap (same as was passed to dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*
* Unmap a set of streaming mode DMA translations. Again, CPU access
* rules concerning calls here are the same as for dma_unmap_single().
*/
void arm_iommu_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i) {
if (sg_dma_len(s))
__iommu_remove_mapping(dev, sg_dma_address(s),
sg_dma_len(s));
if (!arch_is_coherent())
__dma_page_dev_to_cpu(sg_page(s), s->offset,
s->length, dir);
}
}
/**
* arm_iommu_sync_sg_for_cpu
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_iommu_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
if (!arch_is_coherent())
__dma_page_dev_to_cpu(sg_page(s), s->offset, s->length, dir);
}
/**
* arm_iommu_sync_sg_for_device
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_iommu_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
if (!arch_is_coherent())
__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
}
/**
* arm_iommu_map_page
* @dev: valid struct device pointer
* @page: page that buffer resides in
* @offset: offset into page for start of buffer
* @size: size of buffer to map
* @dir: DMA transfer direction
*
* IOMMU aware version of arm_dma_map_page()
*/
static dma_addr_t arm_iommu_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t dma_addr;
int ret, len = PAGE_ALIGN(size + offset);
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
dma_addr = __alloc_iova(mapping, len);
if (dma_addr == DMA_ERROR_CODE)
return dma_addr;
ret = iommu_map(mapping->domain, dma_addr, page_to_phys(page), len, 0);
if (ret < 0)
goto fail;
return dma_addr + offset;
fail:
__free_iova(mapping, dma_addr, len);
return DMA_ERROR_CODE;
}
/**
* arm_iommu_unmap_page
* @dev: valid struct device pointer
* @handle: DMA address of buffer
* @size: size of buffer (same as passed to dma_map_page)
* @dir: DMA transfer direction (same as passed to dma_map_page)
*
* IOMMU aware version of arm_dma_unmap_page()
*/
static void arm_iommu_unmap_page(struct device *dev, dma_addr_t handle,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
int offset = handle & ~PAGE_MASK;
int len = PAGE_ALIGN(size + offset);
if (!iova)
return;
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
iommu_unmap(mapping->domain, iova, len);
__free_iova(mapping, iova, len);
}
static void arm_iommu_sync_single_for_cpu(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
unsigned int offset = handle & ~PAGE_MASK;
if (!iova)
return;
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
}
static void arm_iommu_sync_single_for_device(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
unsigned int offset = handle & ~PAGE_MASK;
if (!iova)
return;
__dma_page_cpu_to_dev(page, offset, size, dir);
}
struct dma_map_ops iommu_ops = {
.alloc = arm_iommu_alloc_attrs,
.free = arm_iommu_free_attrs,
.mmap = arm_iommu_mmap_attrs,
.map_page = arm_iommu_map_page,
.unmap_page = arm_iommu_unmap_page,
.sync_single_for_cpu = arm_iommu_sync_single_for_cpu,
.sync_single_for_device = arm_iommu_sync_single_for_device,
.map_sg = arm_iommu_map_sg,
.unmap_sg = arm_iommu_unmap_sg,
.sync_sg_for_cpu = arm_iommu_sync_sg_for_cpu,
.sync_sg_for_device = arm_iommu_sync_sg_for_device,
};
/**
* arm_iommu_create_mapping
* @bus: pointer to the bus holding the client device (for IOMMU calls)
* @base: start address of the valid IO address space
* @size: size of the valid IO address space
* @order: accuracy of the IO addresses allocations
*
* Creates a mapping structure which holds information about used/unused
* IO address ranges, which is required to perform memory allocation and
* mapping with IOMMU aware functions.
*
* The client device need to be attached to the mapping with
* arm_iommu_attach_device function.
*/
struct dma_iommu_mapping *
arm_iommu_create_mapping(struct bus_type *bus, dma_addr_t base, size_t size,
int order)
{
unsigned int count = size >> (PAGE_SHIFT + order);
unsigned int bitmap_size = BITS_TO_LONGS(count) * sizeof(long);
struct dma_iommu_mapping *mapping;
int err = -ENOMEM;
if (!count)
return ERR_PTR(-EINVAL);
mapping = kzalloc(sizeof(struct dma_iommu_mapping), GFP_KERNEL);
if (!mapping)
goto err;
mapping->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
if (!mapping->bitmap)
goto err2;
mapping->base = base;
mapping->bits = BITS_PER_BYTE * bitmap_size;
mapping->order = order;
spin_lock_init(&mapping->lock);
mapping->domain = iommu_domain_alloc(bus);
if (!mapping->domain)
goto err3;
kref_init(&mapping->kref);
return mapping;
err3:
kfree(mapping->bitmap);
err2:
kfree(mapping);
err:
return ERR_PTR(err);
}
static void release_iommu_mapping(struct kref *kref)
{
struct dma_iommu_mapping *mapping =
container_of(kref, struct dma_iommu_mapping, kref);
iommu_domain_free(mapping->domain);
kfree(mapping->bitmap);
kfree(mapping);
}
void arm_iommu_release_mapping(struct dma_iommu_mapping *mapping)
{
if (mapping)
kref_put(&mapping->kref, release_iommu_mapping);
}
/**
* arm_iommu_attach_device
* @dev: valid struct device pointer
* @mapping: io address space mapping structure (returned from
* arm_iommu_create_mapping)
*
* Attaches specified io address space mapping to the provided device,
* this replaces the dma operations (dma_map_ops pointer) with the
* IOMMU aware version. More than one client might be attached to
* the same io address space mapping.
*/
int arm_iommu_attach_device(struct device *dev,
struct dma_iommu_mapping *mapping)
{
int err;
err = iommu_attach_device(mapping->domain, dev);
if (err)
return err;
kref_get(&mapping->kref);
dev->archdata.mapping = mapping;
set_dma_ops(dev, &iommu_ops);
pr_info("Attached IOMMU controller to %s device.\n", dev_name(dev));
return 0;
}
#endif
| keeeener/nicki | kernel/arch/arm/mm/dma-mapping.c | C | gpl-2.0 | 46,012 |
/*
* Author(s)......: Horst Hummel <Horst.Hummel@de.ibm.com>
* Holger Smolinski <Holger.Smolinski@de.ibm.com>
* Bugreports.to..: <Linux390@de.ibm.com>
* Copyright IBM Corp. 2000, 2001
*
*/
#define KMSG_COMPONENT "dasd-eckd"
#include <linux/timer.h>
#include <asm/idals.h>
#define PRINTK_HEADER "dasd_erp(3990): "
#include "dasd_int.h"
#include "dasd_eckd.h"
struct DCTL_data {
unsigned char subcommand; /* e.g Inhibit Write, Enable Write,... */
unsigned char modifier; /* Subcommand modifier */
unsigned short res; /* reserved */
} __attribute__ ((packed));
/*
*****************************************************************************
* SECTION ERP HANDLING
*****************************************************************************
*/
/*
*****************************************************************************
* 24 and 32 byte sense ERP functions
*****************************************************************************
*/
/*
* DASD_3990_ERP_CLEANUP
*
* DESCRIPTION
* Removes the already build but not necessary ERP request and sets
* the status of the original cqr / erp to the given (final) status
*
* PARAMETER
* erp request to be blocked
* final_status either DASD_CQR_DONE or DASD_CQR_FAILED
*
* RETURN VALUES
* cqr original cqr
*/
static struct dasd_ccw_req *
dasd_3990_erp_cleanup(struct dasd_ccw_req * erp, char final_status)
{
struct dasd_ccw_req *cqr = erp->refers;
dasd_free_erp_request(erp, erp->memdev);
cqr->status = final_status;
return cqr;
} /* end dasd_3990_erp_cleanup */
/*
* DASD_3990_ERP_BLOCK_QUEUE
*
* DESCRIPTION
* Block the given device request queue to prevent from further
* processing until the started timer has expired or an related
* interrupt was received.
*/
static void dasd_3990_erp_block_queue(struct dasd_ccw_req *erp, int expires)
{
struct dasd_device *device = erp->startdev;
unsigned long flags;
DBF_DEV_EVENT(DBF_INFO, device,
"blocking request queue for %is", expires/HZ);
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
dasd_device_set_stop_bits(device, DASD_STOPPED_PENDING);
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
erp->status = DASD_CQR_FILLED;
if (erp->block)
dasd_block_set_timer(erp->block, expires);
else
dasd_device_set_timer(device, expires);
}
/*
* DASD_3990_ERP_INT_REQ
*
* DESCRIPTION
* Handles 'Intervention Required' error.
* This means either device offline or not installed.
*
* PARAMETER
* erp current erp
* RETURN VALUES
* erp modified erp
*/
static struct dasd_ccw_req *
dasd_3990_erp_int_req(struct dasd_ccw_req * erp)
{
struct dasd_device *device = erp->startdev;
/* first time set initial retry counter and erp_function */
/* and retry once without blocking queue */
/* (this enables easier enqueing of the cqr) */
if (erp->function != dasd_3990_erp_int_req) {
erp->retries = 256;
erp->function = dasd_3990_erp_int_req;
} else {
/* issue a message and wait for 'device ready' interrupt */
dev_err(&device->cdev->dev,
"is offline or not installed - "
"INTERVENTION REQUIRED!!\n");
dasd_3990_erp_block_queue(erp, 60*HZ);
}
return erp;
} /* end dasd_3990_erp_int_req */
/*
* DASD_3990_ERP_ALTERNATE_PATH
*
* DESCRIPTION
* Repeat the operation on a different channel path.
* If all alternate paths have been tried, the request is posted with a
* permanent error.
*
* PARAMETER
* erp pointer to the current ERP
*
* RETURN VALUES
* erp modified pointer to the ERP
*/
static void
dasd_3990_erp_alternate_path(struct dasd_ccw_req * erp)
{
struct dasd_device *device = erp->startdev;
__u8 opm;
unsigned long flags;
/* try alternate valid path */
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
opm = ccw_device_get_path_mask(device->cdev);
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
if (erp->lpm == 0)
erp->lpm = device->path_data.opm &
~(erp->irb.esw.esw0.sublog.lpum);
else
erp->lpm &= ~(erp->irb.esw.esw0.sublog.lpum);
if ((erp->lpm & opm) != 0x00) {
DBF_DEV_EVENT(DBF_WARNING, device,
"try alternate lpm=%x (lpum=%x / opm=%x)",
erp->lpm, erp->irb.esw.esw0.sublog.lpum, opm);
/* reset status to submit the request again... */
erp->status = DASD_CQR_FILLED;
erp->retries = 10;
} else {
dev_err(&device->cdev->dev,
"The DASD cannot be reached on any path (lpum=%x"
"/opm=%x)\n", erp->irb.esw.esw0.sublog.lpum, opm);
/* post request with permanent error */
erp->status = DASD_CQR_FAILED;
}
} /* end dasd_3990_erp_alternate_path */
/*
* DASD_3990_ERP_DCTL
*
* DESCRIPTION
* Setup cqr to do the Diagnostic Control (DCTL) command with an
* Inhibit Write subcommand (0x20) and the given modifier.
*
* PARAMETER
* erp pointer to the current (failed) ERP
* modifier subcommand modifier
*
* RETURN VALUES
* dctl_cqr pointer to NEW dctl_cqr
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_DCTL(struct dasd_ccw_req * erp, char modifier)
{
struct dasd_device *device = erp->startdev;
struct DCTL_data *DCTL_data;
struct ccw1 *ccw;
struct dasd_ccw_req *dctl_cqr;
dctl_cqr = dasd_alloc_erp_request((char *) &erp->magic, 1,
sizeof(struct DCTL_data),
device);
if (IS_ERR(dctl_cqr)) {
dev_err(&device->cdev->dev,
"Unable to allocate DCTL-CQR\n");
erp->status = DASD_CQR_FAILED;
return erp;
}
DCTL_data = dctl_cqr->data;
DCTL_data->subcommand = 0x02; /* Inhibit Write */
DCTL_data->modifier = modifier;
ccw = dctl_cqr->cpaddr;
memset(ccw, 0, sizeof(struct ccw1));
ccw->cmd_code = CCW_CMD_DCTL;
ccw->count = 4;
ccw->cda = (__u32)(addr_t) DCTL_data;
dctl_cqr->flags = erp->flags;
dctl_cqr->function = dasd_3990_erp_DCTL;
dctl_cqr->refers = erp;
dctl_cqr->startdev = device;
dctl_cqr->memdev = device;
dctl_cqr->magic = erp->magic;
dctl_cqr->expires = 5 * 60 * HZ;
dctl_cqr->retries = 2;
dctl_cqr->buildclk = get_tod_clock();
dctl_cqr->status = DASD_CQR_FILLED;
return dctl_cqr;
} /* end dasd_3990_erp_DCTL */
/*
* DASD_3990_ERP_ACTION_1
*
* DESCRIPTION
* Setup ERP to do the ERP action 1 (see Reference manual).
* Repeat the operation on a different channel path.
* As deviation from the recommended recovery action, we reset the path mask
* after we have tried each path and go through all paths a second time.
* This will cover situations where only one path at a time is actually down,
* but all paths fail and recover just with the same sequence and timing as
* we try to use them (flapping links).
* If all alternate paths have been tried twice, the request is posted with
* a permanent error.
*
* PARAMETER
* erp pointer to the current ERP
*
* RETURN VALUES
* erp pointer to the ERP
*
*/
static struct dasd_ccw_req *dasd_3990_erp_action_1_sec(struct dasd_ccw_req *erp)
{
erp->function = dasd_3990_erp_action_1_sec;
dasd_3990_erp_alternate_path(erp);
return erp;
}
static struct dasd_ccw_req *dasd_3990_erp_action_1(struct dasd_ccw_req *erp)
{
erp->function = dasd_3990_erp_action_1;
dasd_3990_erp_alternate_path(erp);
if (erp->status == DASD_CQR_FAILED &&
!test_bit(DASD_CQR_VERIFY_PATH, &erp->flags)) {
erp->status = DASD_CQR_FILLED;
erp->retries = 10;
erp->lpm = erp->startdev->path_data.opm;
erp->function = dasd_3990_erp_action_1_sec;
}
return erp;
} /* end dasd_3990_erp_action_1(b) */
/*
* DASD_3990_ERP_ACTION_4
*
* DESCRIPTION
* Setup ERP to do the ERP action 4 (see Reference manual).
* Set the current request to PENDING to block the CQR queue for that device
* until the state change interrupt appears.
* Use a timer (20 seconds) to retry the cqr if the interrupt is still
* missing.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the current ERP
*
* RETURN VALUES
* erp pointer to the ERP
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_action_4(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
/* first time set initial retry counter and erp_function */
/* and retry once without waiting for state change pending */
/* interrupt (this enables easier enqueing of the cqr) */
if (erp->function != dasd_3990_erp_action_4) {
DBF_DEV_EVENT(DBF_INFO, device, "%s",
"dasd_3990_erp_action_4: first time retry");
erp->retries = 256;
erp->function = dasd_3990_erp_action_4;
} else {
if (sense && (sense[25] == 0x1D)) { /* state change pending */
DBF_DEV_EVENT(DBF_INFO, device,
"waiting for state change pending "
"interrupt, %d retries left",
erp->retries);
dasd_3990_erp_block_queue(erp, 30*HZ);
} else if (sense && (sense[25] == 0x1E)) { /* busy */
DBF_DEV_EVENT(DBF_INFO, device,
"busy - redriving request later, "
"%d retries left",
erp->retries);
dasd_3990_erp_block_queue(erp, HZ);
} else {
/* no state change pending - retry */
DBF_DEV_EVENT(DBF_INFO, device,
"redriving request immediately, "
"%d retries left",
erp->retries);
erp->status = DASD_CQR_FILLED;
}
}
return erp;
} /* end dasd_3990_erp_action_4 */
/*
*****************************************************************************
* 24 byte sense ERP functions (only)
*****************************************************************************
*/
/*
* DASD_3990_ERP_ACTION_5
*
* DESCRIPTION
* Setup ERP to do the ERP action 5 (see Reference manual).
* NOTE: Further handling is done in xxx_further_erp after the retries.
*
* PARAMETER
* erp pointer to the current ERP
*
* RETURN VALUES
* erp pointer to the ERP
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_action_5(struct dasd_ccw_req * erp)
{
/* first of all retry */
erp->retries = 10;
erp->function = dasd_3990_erp_action_5;
return erp;
} /* end dasd_3990_erp_action_5 */
/*
* DASD_3990_HANDLE_ENV_DATA
*
* DESCRIPTION
* Handles 24 byte 'Environmental data present'.
* Does a analysis of the sense data (message Format)
* and prints the error messages.
*
* PARAMETER
* sense current sense data
*
* RETURN VALUES
* void
*/
static void
dasd_3990_handle_env_data(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
char msg_format = (sense[7] & 0xF0);
char msg_no = (sense[7] & 0x0F);
char errorstring[ERRORLENGTH];
switch (msg_format) {
case 0x00: /* Format 0 - Program or System Checks */
if (sense[1] & 0x10) { /* check message to operator bit */
switch (msg_no) {
case 0x00: /* No Message */
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Invalid Command\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Invalid Command "
"Sequence\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 0 - CCW Count less than "
"required\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Invalid Parameter\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Diagnostic of Special"
" Command Violates File Mask\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Channel Returned with "
"Incorrect retry CCW\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Reset Notification\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Storage Path Restart\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Channel requested "
"... %02x\n", sense[8]);
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Invalid Defective/"
"Alternate Track Pointer\n");
break;
case 0x0C:
dev_warn(&device->cdev->dev,
"FORMAT 0 - DPS Installation "
"Check\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Command Invalid on "
"Secondary Address\n");
break;
case 0x0F:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Status Not As "
"Required: reason %02x\n",
sense[8]);
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Reserved\n");
}
} else {
switch (msg_no) {
case 0x00: /* No Message */
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Device Error "
"Source\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Reserved\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Device Fenced - "
"device = %02x\n", sense[4]);
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Data Pinned for "
"Device\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 0 - Reserved\n");
}
}
break;
case 0x10: /* Format 1 - Device Equipment Checks */
switch (msg_no) {
case 0x00: /* No Message */
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Device Status 1 not as "
"expected\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Index missing\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Interruption cannot be "
"reset\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Device did not respond to "
"selection\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Device check-2 error or Set "
"Sector is not complete\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Head address does not "
"compare\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Device status 1 not valid\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Device not ready\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Track physical address did "
"not compare\n");
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Missing device address bit\n");
break;
case 0x0C:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Drive motor switch is off\n");
break;
case 0x0D:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Seek incomplete\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Cylinder address did not "
"compare\n");
break;
case 0x0F:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Offset active cannot be "
"reset\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 1 - Reserved\n");
}
break;
case 0x20: /* Format 2 - 3990 Equipment Checks */
switch (msg_no) {
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 2 - 3990 check-2 error\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT 2 - Support facility errors\n");
break;
case 0x0F:
dev_warn(&device->cdev->dev,
"FORMAT 2 - Microcode detected error "
"%02x\n",
sense[8]);
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 2 - Reserved\n");
}
break;
case 0x30: /* Format 3 - 3990 Control Checks */
switch (msg_no) {
case 0x0F:
dev_warn(&device->cdev->dev,
"FORMAT 3 - Allegiance terminated\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 3 - Reserved\n");
}
break;
case 0x40: /* Format 4 - Data Checks */
switch (msg_no) {
case 0x00:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Home address area error\n");
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Count area error\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Key area error\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Data area error\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in home address "
"area\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in count address "
"area\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in key area\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in data area\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Home address area error; "
"offset active\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Count area error; offset "
"active\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Key area error; offset "
"active\n");
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Data area error; "
"offset active\n");
break;
case 0x0C:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in home "
"address area; offset active\n");
break;
case 0x0D:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No syn byte in count "
"address area; offset active\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No sync byte in key area; "
"offset active\n");
break;
case 0x0F:
dev_warn(&device->cdev->dev,
"FORMAT 4 - No syn byte in data area; "
"offset active\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 4 - Reserved\n");
}
break;
case 0x50: /* Format 5 - Data Check with displacement information */
switch (msg_no) {
case 0x00:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the "
"home address area\n");
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the count "
"area\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the key area\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the data "
"area\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the "
"home address area; offset active\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the count area; "
"offset active\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the key area; "
"offset active\n");
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Data Check in the data area; "
"offset active\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 5 - Reserved\n");
}
break;
case 0x60: /* Format 6 - Usage Statistics/Overrun Errors */
switch (msg_no) {
case 0x00:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel A\n");
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel B\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel C\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel D\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel E\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel F\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel G\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Overrun on channel H\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 6 - Reserved\n");
}
break;
case 0x70: /* Format 7 - Device Connection Control Checks */
switch (msg_no) {
case 0x00:
dev_warn(&device->cdev->dev,
"FORMAT 7 - RCC initiated by a connection "
"check alert\n");
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 7 - RCC 1 sequence not "
"successful\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT 7 - RCC 1 and RCC 2 sequences not "
"successful\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Invalid tag-in during "
"selection sequence\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 7 - extra RCC required\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Invalid DCC selection "
"response or timeout\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Missing end operation; device "
"transfer complete\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Missing end operation; device "
"transfer incomplete\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Invalid tag-in for an "
"immediate command sequence\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Invalid tag-in for an "
"extended command sequence\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 7 - 3990 microcode time out when "
"stopping selection\n");
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT 7 - No response to selection "
"after a poll interruption\n");
break;
case 0x0C:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Permanent path error (DASD "
"controller not available)\n");
break;
case 0x0D:
dev_warn(&device->cdev->dev,
"FORMAT 7 - DASD controller not available"
" on disconnected command chain\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 7 - Reserved\n");
}
break;
case 0x80: /* Format 8 - Additional Device Equipment Checks */
switch (msg_no) {
case 0x00: /* No Message */
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT 8 - Error correction code "
"hardware fault\n");
break;
case 0x03:
dev_warn(&device->cdev->dev,
"FORMAT 8 - Unexpected end operation "
"response code\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT 8 - End operation with transfer "
"count not zero\n");
break;
case 0x05:
dev_warn(&device->cdev->dev,
"FORMAT 8 - End operation with transfer "
"count zero\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 8 - DPS checks after a system "
"reset or selective reset\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 8 - DPS cannot be filled\n");
break;
case 0x08:
dev_warn(&device->cdev->dev,
"FORMAT 8 - Short busy time-out during "
"device selection\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT 8 - DASD controller failed to "
"set or reset the long busy latch\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 8 - No interruption from device "
"during a command chain\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 8 - Reserved\n");
}
break;
case 0x90: /* Format 9 - Device Read, Write, and Seek Checks */
switch (msg_no) {
case 0x00:
break; /* No Message */
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT 9 - Device check-2 error\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT 9 - Head address did not "
"compare\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT 9 - Track physical address did "
"not compare while oriented\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT 9 - Cylinder address did not "
"compare\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT 9 - Reserved\n");
}
break;
case 0xF0: /* Format F - Cache Storage Checks */
switch (msg_no) {
case 0x00:
dev_warn(&device->cdev->dev,
"FORMAT F - Operation Terminated\n");
break;
case 0x01:
dev_warn(&device->cdev->dev,
"FORMAT F - Subsystem Processing Error\n");
break;
case 0x02:
dev_warn(&device->cdev->dev,
"FORMAT F - Cache or nonvolatile storage "
"equipment failure\n");
break;
case 0x04:
dev_warn(&device->cdev->dev,
"FORMAT F - Caching terminated\n");
break;
case 0x06:
dev_warn(&device->cdev->dev,
"FORMAT F - Cache fast write access not "
"authorized\n");
break;
case 0x07:
dev_warn(&device->cdev->dev,
"FORMAT F - Track format incorrect\n");
break;
case 0x09:
dev_warn(&device->cdev->dev,
"FORMAT F - Caching reinitiated\n");
break;
case 0x0A:
dev_warn(&device->cdev->dev,
"FORMAT F - Nonvolatile storage "
"terminated\n");
break;
case 0x0B:
dev_warn(&device->cdev->dev,
"FORMAT F - Volume is suspended duplex\n");
/* call extended error reporting (EER) */
dasd_eer_write(device, erp->refers,
DASD_EER_PPRCSUSPEND);
break;
case 0x0C:
dev_warn(&device->cdev->dev,
"FORMAT F - Subsystem status cannot be "
"determined\n");
break;
case 0x0D:
dev_warn(&device->cdev->dev,
"FORMAT F - Caching status reset to "
"default\n");
break;
case 0x0E:
dev_warn(&device->cdev->dev,
"FORMAT F - DASD Fast Write inhibited\n");
break;
default:
dev_warn(&device->cdev->dev,
"FORMAT D - Reserved\n");
}
break;
default: /* unknown message format - should not happen
internal error 03 - unknown message format */
snprintf(errorstring, ERRORLENGTH, "03 %x02", msg_format);
dev_err(&device->cdev->dev,
"An error occurred in the DASD device driver, "
"reason=%s\n", errorstring);
break;
} /* end switch message format */
} /* end dasd_3990_handle_env_data */
/*
* DASD_3990_ERP_COM_REJ
*
* DESCRIPTION
* Handles 24 byte 'Command Reject' error.
*
* PARAMETER
* erp current erp_head
* sense current sense data
*
* RETURN VALUES
* erp 'new' erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_com_rej(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_com_rej;
/* env data present (ACTION 10 - retry should work) */
if (sense[2] & SNS2_ENV_DATA_PRESENT) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Command Reject - environmental data present");
dasd_3990_handle_env_data(erp, sense);
erp->retries = 5;
} else if (sense[1] & SNS1_WRITE_INHIBITED) {
dev_err(&device->cdev->dev, "An I/O request was rejected"
" because writing is inhibited\n");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
} else {
/* fatal error - set status to FAILED
internal error 09 - Command Reject */
dev_err(&device->cdev->dev, "An error occurred in the DASD "
"device driver, reason=%s\n", "09");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
}
return erp;
} /* end dasd_3990_erp_com_rej */
/*
* DASD_3990_ERP_BUS_OUT
*
* DESCRIPTION
* Handles 24 byte 'Bus Out Parity Check' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_bus_out(struct dasd_ccw_req * erp)
{
struct dasd_device *device = erp->startdev;
/* first time set initial retry counter and erp_function */
/* and retry once without blocking queue */
/* (this enables easier enqueing of the cqr) */
if (erp->function != dasd_3990_erp_bus_out) {
erp->retries = 256;
erp->function = dasd_3990_erp_bus_out;
} else {
/* issue a message and wait for 'device ready' interrupt */
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"bus out parity error or BOPC requested by "
"channel");
dasd_3990_erp_block_queue(erp, 60*HZ);
}
return erp;
} /* end dasd_3990_erp_bus_out */
/*
* DASD_3990_ERP_EQUIP_CHECK
*
* DESCRIPTION
* Handles 24 byte 'Equipment Check' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_equip_check(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_equip_check;
if (sense[1] & SNS1_WRITE_INHIBITED) {
dev_info(&device->cdev->dev,
"Write inhibited path encountered\n");
/* vary path offline
internal error 04 - Path should be varied off-line.*/
dev_err(&device->cdev->dev, "An error occurred in the DASD "
"device driver, reason=%s\n", "04");
erp = dasd_3990_erp_action_1(erp);
} else if (sense[2] & SNS2_ENV_DATA_PRESENT) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Equipment Check - " "environmental data present");
dasd_3990_handle_env_data(erp, sense);
erp = dasd_3990_erp_action_4(erp, sense);
} else if (sense[1] & SNS1_PERM_ERR) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Equipment Check - retry exhausted or "
"undesirable");
erp = dasd_3990_erp_action_1(erp);
} else {
/* all other equipment checks - Action 5 */
/* rest is done when retries == 0 */
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Equipment check or processing error");
erp = dasd_3990_erp_action_5(erp);
}
return erp;
} /* end dasd_3990_erp_equip_check */
/*
* DASD_3990_ERP_DATA_CHECK
*
* DESCRIPTION
* Handles 24 byte 'Data Check' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_data_check(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_data_check;
if (sense[2] & SNS2_CORRECTABLE) { /* correctable data check */
/* issue message that the data has been corrected */
dev_emerg(&device->cdev->dev,
"Data recovered during retry with PCI "
"fetch mode active\n");
/* not possible to handle this situation in Linux */
panic("No way to inform application about the possibly "
"incorrect data");
} else if (sense[2] & SNS2_ENV_DATA_PRESENT) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Uncorrectable data check recovered secondary "
"addr of duplex pair");
erp = dasd_3990_erp_action_4(erp, sense);
} else if (sense[1] & SNS1_PERM_ERR) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Uncorrectable data check with internal "
"retry exhausted");
erp = dasd_3990_erp_action_1(erp);
} else {
/* all other data checks */
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Uncorrectable data check with retry count "
"exhausted...");
erp = dasd_3990_erp_action_5(erp);
}
return erp;
} /* end dasd_3990_erp_data_check */
/*
* DASD_3990_ERP_OVERRUN
*
* DESCRIPTION
* Handles 24 byte 'Overrun' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_overrun(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_overrun;
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Overrun - service overrun or overrun"
" error requested by channel");
erp = dasd_3990_erp_action_5(erp);
return erp;
} /* end dasd_3990_erp_overrun */
/*
* DASD_3990_ERP_INV_FORMAT
*
* DESCRIPTION
* Handles 24 byte 'Invalid Track Format' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_inv_format(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_inv_format;
if (sense[2] & SNS2_ENV_DATA_PRESENT) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Track format error when destaging or "
"staging data");
dasd_3990_handle_env_data(erp, sense);
erp = dasd_3990_erp_action_4(erp, sense);
} else {
/* internal error 06 - The track format is not valid*/
dev_err(&device->cdev->dev,
"An error occurred in the DASD device driver, "
"reason=%s\n", "06");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
}
return erp;
} /* end dasd_3990_erp_inv_format */
/*
* DASD_3990_ERP_EOC
*
* DESCRIPTION
* Handles 24 byte 'End-of-Cylinder' error.
*
* PARAMETER
* erp already added default erp
* RETURN VALUES
* erp pointer to original (failed) cqr.
*/
static struct dasd_ccw_req *
dasd_3990_erp_EOC(struct dasd_ccw_req * default_erp, char *sense)
{
struct dasd_device *device = default_erp->startdev;
dev_err(&device->cdev->dev,
"The cylinder data for accessing the DASD is inconsistent\n");
/* implement action 7 - BUG */
return dasd_3990_erp_cleanup(default_erp, DASD_CQR_FAILED);
} /* end dasd_3990_erp_EOC */
/*
* DASD_3990_ERP_ENV_DATA
*
* DESCRIPTION
* Handles 24 byte 'Environmental-Data Present' error.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_env_data(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_env_data;
DBF_DEV_EVENT(DBF_WARNING, device, "%s", "Environmental data present");
dasd_3990_handle_env_data(erp, sense);
/* don't retry on disabled interface */
if (sense[7] != 0x0F) {
erp = dasd_3990_erp_action_4(erp, sense);
} else {
erp->status = DASD_CQR_FILLED;
}
return erp;
} /* end dasd_3990_erp_env_data */
/*
* DASD_3990_ERP_NO_REC
*
* DESCRIPTION
* Handles 24 byte 'No Record Found' error.
*
* PARAMETER
* erp already added default ERP
*
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_no_rec(struct dasd_ccw_req * default_erp, char *sense)
{
struct dasd_device *device = default_erp->startdev;
/*
* In some cases the 'No Record Found' error might be expected and
* log messages shouldn't be written then.
* Check if the according suppress bit is set.
*/
if (!test_bit(DASD_CQR_SUPPRESS_NRF, &default_erp->flags))
dev_err(&device->cdev->dev,
"The specified record was not found\n");
return dasd_3990_erp_cleanup(default_erp, DASD_CQR_FAILED);
} /* end dasd_3990_erp_no_rec */
/*
* DASD_3990_ERP_FILE_PROT
*
* DESCRIPTION
* Handles 24 byte 'File Protected' error.
* Note: Seek related recovery is not implemented because
* wee don't use the seek command yet.
*
* PARAMETER
* erp current erp_head
* RETURN VALUES
* erp new erp_head - pointer to new ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_file_prot(struct dasd_ccw_req * erp)
{
struct dasd_device *device = erp->startdev;
/*
* In some cases the 'File Protected' error might be expected and
* log messages shouldn't be written then.
* Check if the according suppress bit is set.
*/
if (!test_bit(DASD_CQR_SUPPRESS_FP, &erp->flags))
dev_err(&device->cdev->dev,
"Accessing the DASD failed because of a hardware error\n");
return dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
} /* end dasd_3990_erp_file_prot */
/*
* DASD_3990_ERP_INSPECT_ALIAS
*
* DESCRIPTION
* Checks if the original request was started on an alias device.
* If yes, it modifies the original and the erp request so that
* the erp request can be started on a base device.
*
* PARAMETER
* erp pointer to the currently created default ERP
*
* RETURN VALUES
* erp pointer to the modified ERP, or NULL
*/
static struct dasd_ccw_req *dasd_3990_erp_inspect_alias(
struct dasd_ccw_req *erp)
{
struct dasd_ccw_req *cqr = erp->refers;
char *sense;
if (cqr->block &&
(cqr->block->base != cqr->startdev)) {
sense = dasd_get_sense(&erp->refers->irb);
/*
* dynamic pav may have changed base alias mapping
*/
if (!test_bit(DASD_FLAG_OFFLINE, &cqr->startdev->flags) && sense
&& (sense[0] == 0x10) && (sense[7] == 0x0F)
&& (sense[8] == 0x67)) {
/*
* remove device from alias handling to prevent new
* requests from being scheduled on the
* wrong alias device
*/
dasd_alias_remove_device(cqr->startdev);
/* schedule worker to reload device */
dasd_reload_device(cqr->startdev);
}
if (cqr->startdev->features & DASD_FEATURE_ERPLOG) {
DBF_DEV_EVENT(DBF_ERR, cqr->startdev,
"ERP on alias device for request %p,"
" recover on base device %s", cqr,
dev_name(&cqr->block->base->cdev->dev));
}
dasd_eckd_reset_ccw_to_base_io(cqr);
erp->startdev = cqr->block->base;
erp->function = dasd_3990_erp_inspect_alias;
return erp;
} else
return NULL;
}
/*
* DASD_3990_ERP_INSPECT_24
*
* DESCRIPTION
* Does a detailed inspection of the 24 byte sense data
* and sets up a related error recovery action.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created default ERP
*
* RETURN VALUES
* erp pointer to the (addtitional) ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_inspect_24(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_ccw_req *erp_filled = NULL;
/* Check sense for .... */
/* 'Command Reject' */
if ((erp_filled == NULL) && (sense[0] & SNS0_CMD_REJECT)) {
erp_filled = dasd_3990_erp_com_rej(erp, sense);
}
/* 'Intervention Required' */
if ((erp_filled == NULL) && (sense[0] & SNS0_INTERVENTION_REQ)) {
erp_filled = dasd_3990_erp_int_req(erp);
}
/* 'Bus Out Parity Check' */
if ((erp_filled == NULL) && (sense[0] & SNS0_BUS_OUT_CHECK)) {
erp_filled = dasd_3990_erp_bus_out(erp);
}
/* 'Equipment Check' */
if ((erp_filled == NULL) && (sense[0] & SNS0_EQUIPMENT_CHECK)) {
erp_filled = dasd_3990_erp_equip_check(erp, sense);
}
/* 'Data Check' */
if ((erp_filled == NULL) && (sense[0] & SNS0_DATA_CHECK)) {
erp_filled = dasd_3990_erp_data_check(erp, sense);
}
/* 'Overrun' */
if ((erp_filled == NULL) && (sense[0] & SNS0_OVERRUN)) {
erp_filled = dasd_3990_erp_overrun(erp, sense);
}
/* 'Invalid Track Format' */
if ((erp_filled == NULL) && (sense[1] & SNS1_INV_TRACK_FORMAT)) {
erp_filled = dasd_3990_erp_inv_format(erp, sense);
}
/* 'End-of-Cylinder' */
if ((erp_filled == NULL) && (sense[1] & SNS1_EOC)) {
erp_filled = dasd_3990_erp_EOC(erp, sense);
}
/* 'Environmental Data' */
if ((erp_filled == NULL) && (sense[2] & SNS2_ENV_DATA_PRESENT)) {
erp_filled = dasd_3990_erp_env_data(erp, sense);
}
/* 'No Record Found' */
if ((erp_filled == NULL) && (sense[1] & SNS1_NO_REC_FOUND)) {
erp_filled = dasd_3990_erp_no_rec(erp, sense);
}
/* 'File Protected' */
if ((erp_filled == NULL) && (sense[1] & SNS1_FILE_PROTECTED)) {
erp_filled = dasd_3990_erp_file_prot(erp);
}
/* other (unknown) error - do default ERP */
if (erp_filled == NULL) {
erp_filled = erp;
}
return erp_filled;
} /* END dasd_3990_erp_inspect_24 */
/*
*****************************************************************************
* 32 byte sense ERP functions (only)
*****************************************************************************
*/
/*
* DASD_3990_ERPACTION_10_32
*
* DESCRIPTION
* Handles 32 byte 'Action 10' of Single Program Action Codes.
* Just retry and if retry doesn't work, return with error.
*
* PARAMETER
* erp current erp_head
* sense current sense data
* RETURN VALUES
* erp modified erp_head
*/
static struct dasd_ccw_req *
dasd_3990_erp_action_10_32(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->retries = 256;
erp->function = dasd_3990_erp_action_10_32;
DBF_DEV_EVENT(DBF_WARNING, device, "%s", "Perform logging requested");
return erp;
} /* end dasd_3990_erp_action_10_32 */
/*
* DASD_3990_ERP_ACTION_1B_32
*
* DESCRIPTION
* Handles 32 byte 'Action 1B' of Single Program Action Codes.
* A write operation could not be finished because of an unexpected
* condition.
* The already created 'default erp' is used to get the link to
* the erp chain, but it can not be used for this recovery
* action because it contains no DE/LO data space.
*
* PARAMETER
* default_erp already added default erp.
* sense current sense data
*
* RETURN VALUES
* erp new erp or
* default_erp in case of imprecise ending or error
*/
static struct dasd_ccw_req *
dasd_3990_erp_action_1B_32(struct dasd_ccw_req * default_erp, char *sense)
{
struct dasd_device *device = default_erp->startdev;
__u32 cpa = 0;
struct dasd_ccw_req *cqr;
struct dasd_ccw_req *erp;
struct DE_eckd_data *DE_data;
struct PFX_eckd_data *PFX_data;
char *LO_data; /* LO_eckd_data_t */
struct ccw1 *ccw, *oldccw;
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Write not finished because of unexpected condition");
default_erp->function = dasd_3990_erp_action_1B_32;
/* determine the original cqr */
cqr = default_erp;
while (cqr->refers != NULL) {
cqr = cqr->refers;
}
if (scsw_is_tm(&cqr->irb.scsw)) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"32 bit sense, action 1B is not defined"
" in transport mode - just retry");
return default_erp;
}
/* for imprecise ending just do default erp */
if (sense[1] & 0x01) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Imprecise ending is set - just retry");
return default_erp;
}
/* determine the address of the CCW to be restarted */
/* Imprecise ending is not set -> addr from IRB-SCSW */
cpa = default_erp->refers->irb.scsw.cmd.cpa;
if (cpa == 0) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Unable to determine address of the CCW "
"to be restarted");
return dasd_3990_erp_cleanup(default_erp, DASD_CQR_FAILED);
}
/* Build new ERP request including DE/LO */
erp = dasd_alloc_erp_request((char *) &cqr->magic,
2 + 1,/* DE/LO + TIC */
sizeof(struct DE_eckd_data) +
sizeof(struct LO_eckd_data), device);
if (IS_ERR(erp)) {
/* internal error 01 - Unable to allocate ERP */
dev_err(&device->cdev->dev, "An error occurred in the DASD "
"device driver, reason=%s\n", "01");
return dasd_3990_erp_cleanup(default_erp, DASD_CQR_FAILED);
}
/* use original DE */
DE_data = erp->data;
oldccw = cqr->cpaddr;
if (oldccw->cmd_code == DASD_ECKD_CCW_PFX) {
PFX_data = cqr->data;
memcpy(DE_data, &PFX_data->define_extent,
sizeof(struct DE_eckd_data));
} else
memcpy(DE_data, cqr->data, sizeof(struct DE_eckd_data));
/* create LO */
LO_data = erp->data + sizeof(struct DE_eckd_data);
if ((sense[3] == 0x01) && (LO_data[1] & 0x01)) {
/* should not */
return dasd_3990_erp_cleanup(default_erp, DASD_CQR_FAILED);
}
if ((sense[7] & 0x3F) == 0x01) {
/* operation code is WRITE DATA -> data area orientation */
LO_data[0] = 0x81;
} else if ((sense[7] & 0x3F) == 0x03) {
/* operation code is FORMAT WRITE -> index orientation */
LO_data[0] = 0xC3;
} else {
LO_data[0] = sense[7]; /* operation */
}
LO_data[1] = sense[8]; /* auxiliary */
LO_data[2] = sense[9];
LO_data[3] = sense[3]; /* count */
LO_data[4] = sense[29]; /* seek_addr.cyl */
LO_data[5] = sense[30]; /* seek_addr.cyl 2nd byte */
LO_data[7] = sense[31]; /* seek_addr.head 2nd byte */
memcpy(&(LO_data[8]), &(sense[11]), 8);
/* create DE ccw */
ccw = erp->cpaddr;
memset(ccw, 0, sizeof(struct ccw1));
ccw->cmd_code = DASD_ECKD_CCW_DEFINE_EXTENT;
ccw->flags = CCW_FLAG_CC;
ccw->count = 16;
ccw->cda = (__u32)(addr_t) DE_data;
/* create LO ccw */
ccw++;
memset(ccw, 0, sizeof(struct ccw1));
ccw->cmd_code = DASD_ECKD_CCW_LOCATE_RECORD;
ccw->flags = CCW_FLAG_CC;
ccw->count = 16;
ccw->cda = (__u32)(addr_t) LO_data;
/* TIC to the failed ccw */
ccw++;
ccw->cmd_code = CCW_CMD_TIC;
ccw->cda = cpa;
/* fill erp related fields */
erp->flags = default_erp->flags;
erp->function = dasd_3990_erp_action_1B_32;
erp->refers = default_erp->refers;
erp->startdev = device;
erp->memdev = device;
erp->magic = default_erp->magic;
erp->expires = default_erp->expires;
erp->retries = 256;
erp->buildclk = get_tod_clock();
erp->status = DASD_CQR_FILLED;
/* remove the default erp */
dasd_free_erp_request(default_erp, device);
return erp;
} /* end dasd_3990_erp_action_1B_32 */
/*
* DASD_3990_UPDATE_1B
*
* DESCRIPTION
* Handles the update to the 32 byte 'Action 1B' of Single Program
* Action Codes in case the first action was not successful.
* The already created 'previous_erp' is the currently not successful
* ERP.
*
* PARAMETER
* previous_erp already created previous erp.
* sense current sense data
* RETURN VALUES
* erp modified erp
*/
static struct dasd_ccw_req *
dasd_3990_update_1B(struct dasd_ccw_req * previous_erp, char *sense)
{
struct dasd_device *device = previous_erp->startdev;
__u32 cpa = 0;
struct dasd_ccw_req *cqr;
struct dasd_ccw_req *erp;
char *LO_data; /* struct LO_eckd_data */
struct ccw1 *ccw;
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Write not finished because of unexpected condition"
" - follow on");
/* determine the original cqr */
cqr = previous_erp;
while (cqr->refers != NULL) {
cqr = cqr->refers;
}
if (scsw_is_tm(&cqr->irb.scsw)) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"32 bit sense, action 1B, update,"
" in transport mode - just retry");
return previous_erp;
}
/* for imprecise ending just do default erp */
if (sense[1] & 0x01) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Imprecise ending is set - just retry");
previous_erp->status = DASD_CQR_FILLED;
return previous_erp;
}
/* determine the address of the CCW to be restarted */
/* Imprecise ending is not set -> addr from IRB-SCSW */
cpa = previous_erp->irb.scsw.cmd.cpa;
if (cpa == 0) {
/* internal error 02 -
Unable to determine address of the CCW to be restarted */
dev_err(&device->cdev->dev, "An error occurred in the DASD "
"device driver, reason=%s\n", "02");
previous_erp->status = DASD_CQR_FAILED;
return previous_erp;
}
erp = previous_erp;
/* update the LO with the new returned sense data */
LO_data = erp->data + sizeof(struct DE_eckd_data);
if ((sense[3] == 0x01) && (LO_data[1] & 0x01)) {
/* should not happen */
previous_erp->status = DASD_CQR_FAILED;
return previous_erp;
}
if ((sense[7] & 0x3F) == 0x01) {
/* operation code is WRITE DATA -> data area orientation */
LO_data[0] = 0x81;
} else if ((sense[7] & 0x3F) == 0x03) {
/* operation code is FORMAT WRITE -> index orientation */
LO_data[0] = 0xC3;
} else {
LO_data[0] = sense[7]; /* operation */
}
LO_data[1] = sense[8]; /* auxiliary */
LO_data[2] = sense[9];
LO_data[3] = sense[3]; /* count */
LO_data[4] = sense[29]; /* seek_addr.cyl */
LO_data[5] = sense[30]; /* seek_addr.cyl 2nd byte */
LO_data[7] = sense[31]; /* seek_addr.head 2nd byte */
memcpy(&(LO_data[8]), &(sense[11]), 8);
/* TIC to the failed ccw */
ccw = erp->cpaddr; /* addr of DE ccw */
ccw++; /* addr of LE ccw */
ccw++; /* addr of TIC ccw */
ccw->cda = cpa;
erp->status = DASD_CQR_FILLED;
return erp;
} /* end dasd_3990_update_1B */
/*
* DASD_3990_ERP_COMPOUND_RETRY
*
* DESCRIPTION
* Handles the compound ERP action retry code.
* NOTE: At least one retry is done even if zero is specified
* by the sense data. This makes enqueueing of the request
* easier.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created ERP
*
* RETURN VALUES
* erp modified ERP pointer
*
*/
static void
dasd_3990_erp_compound_retry(struct dasd_ccw_req * erp, char *sense)
{
switch (sense[25] & 0x03) {
case 0x00: /* no not retry */
erp->retries = 1;
break;
case 0x01: /* retry 2 times */
erp->retries = 2;
break;
case 0x02: /* retry 10 times */
erp->retries = 10;
break;
case 0x03: /* retry 256 times */
erp->retries = 256;
break;
default:
BUG();
}
erp->function = dasd_3990_erp_compound_retry;
} /* end dasd_3990_erp_compound_retry */
/*
* DASD_3990_ERP_COMPOUND_PATH
*
* DESCRIPTION
* Handles the compound ERP action for retry on alternate
* channel path.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created ERP
*
* RETURN VALUES
* erp modified ERP pointer
*
*/
static void
dasd_3990_erp_compound_path(struct dasd_ccw_req * erp, char *sense)
{
if (sense[25] & DASD_SENSE_BIT_3) {
dasd_3990_erp_alternate_path(erp);
if (erp->status == DASD_CQR_FAILED &&
!test_bit(DASD_CQR_VERIFY_PATH, &erp->flags)) {
/* reset the lpm and the status to be able to
* try further actions. */
erp->lpm = erp->startdev->path_data.opm;
erp->status = DASD_CQR_NEED_ERP;
}
}
erp->function = dasd_3990_erp_compound_path;
} /* end dasd_3990_erp_compound_path */
/*
* DASD_3990_ERP_COMPOUND_CODE
*
* DESCRIPTION
* Handles the compound ERP action for retry code.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created ERP
*
* RETURN VALUES
* erp NEW ERP pointer
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_compound_code(struct dasd_ccw_req * erp, char *sense)
{
if (sense[25] & DASD_SENSE_BIT_2) {
switch (sense[28]) {
case 0x17:
/* issue a Diagnostic Control command with an
* Inhibit Write subcommand and controller modifier */
erp = dasd_3990_erp_DCTL(erp, 0x20);
break;
case 0x25:
/* wait for 5 seconds and retry again */
erp->retries = 1;
dasd_3990_erp_block_queue (erp, 5*HZ);
break;
default:
/* should not happen - continue */
break;
}
}
erp->function = dasd_3990_erp_compound_code;
return erp;
} /* end dasd_3990_erp_compound_code */
/*
* DASD_3990_ERP_COMPOUND_CONFIG
*
* DESCRIPTION
* Handles the compound ERP action for configruation
* dependent error.
* Note: duplex handling is not implemented (yet).
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created ERP
*
* RETURN VALUES
* erp modified ERP pointer
*
*/
static void
dasd_3990_erp_compound_config(struct dasd_ccw_req * erp, char *sense)
{
if ((sense[25] & DASD_SENSE_BIT_1) && (sense[26] & DASD_SENSE_BIT_2)) {
/* set to suspended duplex state then restart
internal error 05 - Set device to suspended duplex state
should be done */
struct dasd_device *device = erp->startdev;
dev_err(&device->cdev->dev,
"An error occurred in the DASD device driver, "
"reason=%s\n", "05");
}
erp->function = dasd_3990_erp_compound_config;
} /* end dasd_3990_erp_compound_config */
/*
* DASD_3990_ERP_COMPOUND
*
* DESCRIPTION
* Does the further compound program action if
* compound retry was not successful.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the current (failed) ERP
*
* RETURN VALUES
* erp (additional) ERP pointer
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_compound(struct dasd_ccw_req * erp, char *sense)
{
if ((erp->function == dasd_3990_erp_compound_retry) &&
(erp->status == DASD_CQR_NEED_ERP)) {
dasd_3990_erp_compound_path(erp, sense);
}
if ((erp->function == dasd_3990_erp_compound_path) &&
(erp->status == DASD_CQR_NEED_ERP)) {
erp = dasd_3990_erp_compound_code(erp, sense);
}
if ((erp->function == dasd_3990_erp_compound_code) &&
(erp->status == DASD_CQR_NEED_ERP)) {
dasd_3990_erp_compound_config(erp, sense);
}
/* if no compound action ERP specified, the request failed */
if (erp->status == DASD_CQR_NEED_ERP)
erp->status = DASD_CQR_FAILED;
return erp;
} /* end dasd_3990_erp_compound */
/*
*DASD_3990_ERP_HANDLE_SIM
*
*DESCRIPTION
* inspects the SIM SENSE data and starts an appropriate action
*
* PARAMETER
* sense sense data of the actual error
*
* RETURN VALUES
* none
*/
void
dasd_3990_erp_handle_sim(struct dasd_device *device, char *sense)
{
/* print message according to log or message to operator mode */
if ((sense[24] & DASD_SIM_MSG_TO_OP) || (sense[1] & 0x10)) {
/* print SIM SRC from RefCode */
dev_err(&device->cdev->dev, "SIM - SRC: "
"%02x%02x%02x%02x\n", sense[22],
sense[23], sense[11], sense[12]);
} else if (sense[24] & DASD_SIM_LOG) {
/* print SIM SRC Refcode */
dev_warn(&device->cdev->dev, "log SIM - SRC: "
"%02x%02x%02x%02x\n", sense[22],
sense[23], sense[11], sense[12]);
}
}
/*
* DASD_3990_ERP_INSPECT_32
*
* DESCRIPTION
* Does a detailed inspection of the 32 byte sense data
* and sets up a related error recovery action.
*
* PARAMETER
* sense sense data of the actual error
* erp pointer to the currently created default ERP
*
* RETURN VALUES
* erp_filled pointer to the ERP
*
*/
static struct dasd_ccw_req *
dasd_3990_erp_inspect_32(struct dasd_ccw_req * erp, char *sense)
{
struct dasd_device *device = erp->startdev;
erp->function = dasd_3990_erp_inspect_32;
/* check for SIM sense data */
if ((sense[6] & DASD_SIM_SENSE) == DASD_SIM_SENSE)
dasd_3990_erp_handle_sim(device, sense);
if (sense[25] & DASD_SENSE_BIT_0) {
/* compound program action codes (byte25 bit 0 == '1') */
dasd_3990_erp_compound_retry(erp, sense);
} else {
/* single program action codes (byte25 bit 0 == '0') */
switch (sense[25]) {
case 0x00: /* success - use default ERP for retries */
DBF_DEV_EVENT(DBF_DEBUG, device, "%s",
"ERP called for successful request"
" - just retry");
break;
case 0x01: /* fatal error */
dev_err(&device->cdev->dev,
"ERP failed for the DASD\n");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
break;
case 0x02: /* intervention required */
case 0x03: /* intervention required during dual copy */
erp = dasd_3990_erp_int_req(erp);
break;
case 0x0F: /* length mismatch during update write command
internal error 08 - update write command error*/
dev_err(&device->cdev->dev, "An error occurred in the "
"DASD device driver, reason=%s\n", "08");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
break;
case 0x10: /* logging required for other channel program */
erp = dasd_3990_erp_action_10_32(erp, sense);
break;
case 0x15: /* next track outside defined extend
internal error 07 - The next track is not
within the defined storage extent */
dev_err(&device->cdev->dev,
"An error occurred in the DASD device driver, "
"reason=%s\n", "07");
erp = dasd_3990_erp_cleanup(erp, DASD_CQR_FAILED);
break;
case 0x1B: /* unexpected condition during write */
erp = dasd_3990_erp_action_1B_32(erp, sense);
break;
case 0x1C: /* invalid data */
dev_emerg(&device->cdev->dev,
"Data recovered during retry with PCI "
"fetch mode active\n");
/* not possible to handle this situation in Linux */
panic
("Invalid data - No way to inform application "
"about the possibly incorrect data");
break;
case 0x1D: /* state-change pending */
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"A State change pending condition exists "
"for the subsystem or device");
erp = dasd_3990_erp_action_4(erp, sense);
break;
case 0x1E: /* busy */
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"Busy condition exists "
"for the subsystem or device");
erp = dasd_3990_erp_action_4(erp, sense);
break;
default: /* all others errors - default erp */
break;
}
}
return erp;
} /* end dasd_3990_erp_inspect_32 */
/*
*****************************************************************************
* main ERP control functions (24 and 32 byte sense)
*****************************************************************************
*/
/*
* DASD_3990_ERP_CONTROL_CHECK
*
* DESCRIPTION
* Does a generic inspection if a control check occurred and sets up
* the related error recovery procedure
*
* PARAMETER
* erp pointer to the currently created default ERP
*
* RETURN VALUES
* erp_filled pointer to the erp
*/
static struct dasd_ccw_req *
dasd_3990_erp_control_check(struct dasd_ccw_req *erp)
{
struct dasd_device *device = erp->startdev;
if (scsw_cstat(&erp->refers->irb.scsw) & (SCHN_STAT_INTF_CTRL_CHK
| SCHN_STAT_CHN_CTRL_CHK)) {
DBF_DEV_EVENT(DBF_WARNING, device, "%s",
"channel or interface control check");
erp = dasd_3990_erp_action_4(erp, NULL);
}
return erp;
}
/*
* DASD_3990_ERP_INSPECT
*
* DESCRIPTION
* Does a detailed inspection for sense data by calling either
* the 24-byte or the 32-byte inspection routine.
*
* PARAMETER
* erp pointer to the currently created default ERP
* RETURN VALUES
* erp_new contens was possibly modified
*/
static struct dasd_ccw_req *
dasd_3990_erp_inspect(struct dasd_ccw_req *erp)
{
struct dasd_ccw_req *erp_new = NULL;
char *sense;
/* if this problem occurred on an alias retry on base */
erp_new = dasd_3990_erp_inspect_alias(erp);
if (erp_new)
return erp_new;
/* sense data are located in the refers record of the
* already set up new ERP !
* check if concurrent sens is available
*/
sense = dasd_get_sense(&erp->refers->irb);
if (!sense)
erp_new = dasd_3990_erp_control_check(erp);
/* distinguish between 24 and 32 byte sense data */
else if (sense[27] & DASD_SENSE_BIT_0) {
/* inspect the 24 byte sense data */
erp_new = dasd_3990_erp_inspect_24(erp, sense);
} else {
/* inspect the 32 byte sense data */
erp_new = dasd_3990_erp_inspect_32(erp, sense);
} /* end distinguish between 24 and 32 byte sense data */
return erp_new;
}
/*
* DASD_3990_ERP_ADD_ERP
*
* DESCRIPTION
* This function adds an additional request block (ERP) to the head of
* the given cqr (or erp).
* For a command mode cqr the erp is initialized as an default erp
* (retry TIC).
* For transport mode we make a copy of the original TCW (points to
* the original TCCB, TIDALs, etc.) but give it a fresh
* TSB so the original sense data will not be changed.
*
* PARAMETER
* cqr head of the current ERP-chain (or single cqr if
* first error)
* RETURN VALUES
* erp pointer to new ERP-chain head
*/
static struct dasd_ccw_req *dasd_3990_erp_add_erp(struct dasd_ccw_req *cqr)
{
struct dasd_device *device = cqr->startdev;
struct ccw1 *ccw;
struct dasd_ccw_req *erp;
int cplength, datasize;
struct tcw *tcw;
struct tsb *tsb;
if (cqr->cpmode == 1) {
cplength = 0;
/* TCW needs to be 64 byte aligned, so leave enough room */
datasize = 64 + sizeof(struct tcw) + sizeof(struct tsb);
} else {
cplength = 2;
datasize = 0;
}
/* allocate additional request block */
erp = dasd_alloc_erp_request((char *) &cqr->magic,
cplength, datasize, device);
if (IS_ERR(erp)) {
if (cqr->retries <= 0) {
DBF_DEV_EVENT(DBF_ERR, device, "%s",
"Unable to allocate ERP request");
cqr->status = DASD_CQR_FAILED;
cqr->stopclk = get_tod_clock();
} else {
DBF_DEV_EVENT(DBF_ERR, device,
"Unable to allocate ERP request "
"(%i retries left)",
cqr->retries);
dasd_block_set_timer(device->block, (HZ << 3));
}
return erp;
}
ccw = cqr->cpaddr;
if (cqr->cpmode == 1) {
/* make a shallow copy of the original tcw but set new tsb */
erp->cpmode = 1;
erp->cpaddr = PTR_ALIGN(erp->data, 64);
tcw = erp->cpaddr;
tsb = (struct tsb *) &tcw[1];
*tcw = *((struct tcw *)cqr->cpaddr);
tcw->tsb = (long)tsb;
} else if (ccw->cmd_code == DASD_ECKD_CCW_PSF) {
/* PSF cannot be chained from NOOP/TIC */
erp->cpaddr = cqr->cpaddr;
} else {
/* initialize request with default TIC to current ERP/CQR */
ccw = erp->cpaddr;
ccw->cmd_code = CCW_CMD_NOOP;
ccw->flags = CCW_FLAG_CC;
ccw++;
ccw->cmd_code = CCW_CMD_TIC;
ccw->cda = (long)(cqr->cpaddr);
}
erp->flags = cqr->flags;
erp->function = dasd_3990_erp_add_erp;
erp->refers = cqr;
erp->startdev = device;
erp->memdev = device;
erp->block = cqr->block;
erp->magic = cqr->magic;
erp->expires = cqr->expires;
erp->retries = 256;
erp->buildclk = get_tod_clock();
erp->status = DASD_CQR_FILLED;
return erp;
}
/*
* DASD_3990_ERP_ADDITIONAL_ERP
*
* DESCRIPTION
* An additional ERP is needed to handle the current error.
* Add ERP to the head of the ERP-chain containing the ERP processing
* determined based on the sense data.
*
* PARAMETER
* cqr head of the current ERP-chain (or single cqr if
* first error)
*
* RETURN VALUES
* erp pointer to new ERP-chain head
*/
static struct dasd_ccw_req *
dasd_3990_erp_additional_erp(struct dasd_ccw_req * cqr)
{
struct dasd_ccw_req *erp = NULL;
/* add erp and initialize with default TIC */
erp = dasd_3990_erp_add_erp(cqr);
if (IS_ERR(erp))
return erp;
/* inspect sense, determine specific ERP if possible */
if (erp != cqr) {
erp = dasd_3990_erp_inspect(erp);
}
return erp;
} /* end dasd_3990_erp_additional_erp */
/*
* DASD_3990_ERP_ERROR_MATCH
*
* DESCRIPTION
* Check if the device status of the given cqr is the same.
* This means that the failed CCW and the relevant sense data
* must match.
* I don't distinguish between 24 and 32 byte sense because in case of
* 24 byte sense byte 25 and 27 is set as well.
*
* PARAMETER
* cqr1 first cqr, which will be compared with the
* cqr2 second cqr.
*
* RETURN VALUES
* match 'boolean' for match found
* returns 1 if match found, otherwise 0.
*/
static int dasd_3990_erp_error_match(struct dasd_ccw_req *cqr1,
struct dasd_ccw_req *cqr2)
{
char *sense1, *sense2;
if (cqr1->startdev != cqr2->startdev)
return 0;
sense1 = dasd_get_sense(&cqr1->irb);
sense2 = dasd_get_sense(&cqr2->irb);
/* one request has sense data, the other not -> no match, return 0 */
if (!sense1 != !sense2)
return 0;
/* no sense data in both cases -> check cstat for IFCC */
if (!sense1 && !sense2) {
if ((scsw_cstat(&cqr1->irb.scsw) & (SCHN_STAT_INTF_CTRL_CHK |
SCHN_STAT_CHN_CTRL_CHK)) ==
(scsw_cstat(&cqr2->irb.scsw) & (SCHN_STAT_INTF_CTRL_CHK |
SCHN_STAT_CHN_CTRL_CHK)))
return 1; /* match with ifcc*/
}
/* check sense data; byte 0-2,25,27 */
if (!(sense1 && sense2 &&
(memcmp(sense1, sense2, 3) == 0) &&
(sense1[27] == sense2[27]) &&
(sense1[25] == sense2[25]))) {
return 0; /* sense doesn't match */
}
return 1; /* match */
} /* end dasd_3990_erp_error_match */
/*
* DASD_3990_ERP_IN_ERP
*
* DESCRIPTION
* check if the current error already happened before.
* quick exit if current cqr is not an ERP (cqr->refers=NULL)
*
* PARAMETER
* cqr failed cqr (either original cqr or already an erp)
*
* RETURN VALUES
* erp erp-pointer to the already defined error
* recovery procedure OR
* NULL if a 'new' error occurred.
*/
static struct dasd_ccw_req *
dasd_3990_erp_in_erp(struct dasd_ccw_req *cqr)
{
struct dasd_ccw_req *erp_head = cqr, /* save erp chain head */
*erp_match = NULL; /* save erp chain head */
int match = 0; /* 'boolean' for matching error found */
if (cqr->refers == NULL) { /* return if not in erp */
return NULL;
}
/* check the erp/cqr chain for current error */
do {
match = dasd_3990_erp_error_match(erp_head, cqr->refers);
erp_match = cqr; /* save possible matching erp */
cqr = cqr->refers; /* check next erp/cqr in queue */
} while ((cqr->refers != NULL) && (!match));
if (!match) {
return NULL; /* no match was found */
}
return erp_match; /* return address of matching erp */
} /* END dasd_3990_erp_in_erp */
/*
* DASD_3990_ERP_FURTHER_ERP (24 & 32 byte sense)
*
* DESCRIPTION
* No retry is left for the current ERP. Check what has to be done
* with the ERP.
* - do further defined ERP action or
* - wait for interrupt or
* - exit with permanent error
*
* PARAMETER
* erp ERP which is in progress with no retry left
*
* RETURN VALUES
* erp modified/additional ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_further_erp(struct dasd_ccw_req *erp)
{
struct dasd_device *device = erp->startdev;
char *sense = dasd_get_sense(&erp->irb);
/* check for 24 byte sense ERP */
if ((erp->function == dasd_3990_erp_bus_out) ||
(erp->function == dasd_3990_erp_action_1) ||
(erp->function == dasd_3990_erp_action_4)) {
erp = dasd_3990_erp_action_1(erp);
} else if (erp->function == dasd_3990_erp_action_1_sec) {
erp = dasd_3990_erp_action_1_sec(erp);
} else if (erp->function == dasd_3990_erp_action_5) {
/* retries have not been successful */
/* prepare erp for retry on different channel path */
erp = dasd_3990_erp_action_1(erp);
if (sense && !(sense[2] & DASD_SENSE_BIT_0)) {
/* issue a Diagnostic Control command with an
* Inhibit Write subcommand */
switch (sense[25]) {
case 0x17:
case 0x57:{ /* controller */
erp = dasd_3990_erp_DCTL(erp, 0x20);
break;
}
case 0x18:
case 0x58:{ /* channel path */
erp = dasd_3990_erp_DCTL(erp, 0x40);
break;
}
case 0x19:
case 0x59:{ /* storage director */
erp = dasd_3990_erp_DCTL(erp, 0x80);
break;
}
default:
DBF_DEV_EVENT(DBF_WARNING, device,
"invalid subcommand modifier 0x%x "
"for Diagnostic Control Command",
sense[25]);
}
}
/* check for 32 byte sense ERP */
} else if (sense &&
((erp->function == dasd_3990_erp_compound_retry) ||
(erp->function == dasd_3990_erp_compound_path) ||
(erp->function == dasd_3990_erp_compound_code) ||
(erp->function == dasd_3990_erp_compound_config))) {
erp = dasd_3990_erp_compound(erp, sense);
} else {
/*
* No retry left and no additional special handling
* necessary
*/
dev_err(&device->cdev->dev,
"ERP %p has run out of retries and failed\n", erp);
erp->status = DASD_CQR_FAILED;
}
return erp;
} /* end dasd_3990_erp_further_erp */
/*
* DASD_3990_ERP_HANDLE_MATCH_ERP
*
* DESCRIPTION
* An error occurred again and an ERP has been detected which is already
* used to handle this error (e.g. retries).
* All prior ERP's are asumed to be successful and therefore removed
* from queue.
* If retry counter of matching erp is already 0, it is checked if further
* action is needed (besides retry) or if the ERP has failed.
*
* PARAMETER
* erp_head first ERP in ERP-chain
* erp ERP that handles the actual error.
* (matching erp)
*
* RETURN VALUES
* erp modified/additional ERP
*/
static struct dasd_ccw_req *
dasd_3990_erp_handle_match_erp(struct dasd_ccw_req *erp_head,
struct dasd_ccw_req *erp)
{
struct dasd_device *device = erp_head->startdev;
struct dasd_ccw_req *erp_done = erp_head; /* finished req */
struct dasd_ccw_req *erp_free = NULL; /* req to be freed */
/* loop over successful ERPs and remove them from chanq */
while (erp_done != erp) {
if (erp_done == NULL) /* end of chain reached */
panic(PRINTK_HEADER "Programming error in ERP! The "
"original request was lost\n");
/* remove the request from the device queue */
list_del(&erp_done->blocklist);
erp_free = erp_done;
erp_done = erp_done->refers;
/* free the finished erp request */
dasd_free_erp_request(erp_free, erp_free->memdev);
} /* end while */
if (erp->retries > 0) {
char *sense = dasd_get_sense(&erp->refers->irb);
/* check for special retries */
if (sense && erp->function == dasd_3990_erp_action_4) {
erp = dasd_3990_erp_action_4(erp, sense);
} else if (sense &&
erp->function == dasd_3990_erp_action_1B_32) {
erp = dasd_3990_update_1B(erp, sense);
} else if (sense && erp->function == dasd_3990_erp_int_req) {
erp = dasd_3990_erp_int_req(erp);
} else {
/* simple retry */
DBF_DEV_EVENT(DBF_DEBUG, device,
"%i retries left for erp %p",
erp->retries, erp);
/* handle the request again... */
erp->status = DASD_CQR_FILLED;
}
} else {
/* no retry left - check for further necessary action */
/* if no further actions, handle rest as permanent error */
erp = dasd_3990_erp_further_erp(erp);
}
return erp;
} /* end dasd_3990_erp_handle_match_erp */
/*
* DASD_3990_ERP_ACTION
*
* DESCRIPTION
* control routine for 3990 erp actions.
* Has to be called with the queue lock (namely the s390_irq_lock) acquired.
*
* PARAMETER
* cqr failed cqr (either original cqr or already an erp)
*
* RETURN VALUES
* erp erp-pointer to the head of the ERP action chain.
* This means:
* - either a ptr to an additional ERP cqr or
* - the original given cqr (which's status might
* be modified)
*/
struct dasd_ccw_req *
dasd_3990_erp_action(struct dasd_ccw_req * cqr)
{
struct dasd_ccw_req *erp = NULL;
struct dasd_device *device = cqr->startdev;
struct dasd_ccw_req *temp_erp = NULL;
if (device->features & DASD_FEATURE_ERPLOG) {
/* print current erp_chain */
dev_err(&device->cdev->dev,
"ERP chain at BEGINNING of ERP-ACTION\n");
for (temp_erp = cqr;
temp_erp != NULL; temp_erp = temp_erp->refers) {
dev_err(&device->cdev->dev,
"ERP %p (%02x) refers to %p\n",
temp_erp, temp_erp->status,
temp_erp->refers);
}
}
/* double-check if current erp/cqr was successful */
if ((scsw_cstat(&cqr->irb.scsw) == 0x00) &&
(scsw_dstat(&cqr->irb.scsw) ==
(DEV_STAT_CHN_END | DEV_STAT_DEV_END))) {
DBF_DEV_EVENT(DBF_DEBUG, device,
"ERP called for successful request %p"
" - NO ERP necessary", cqr);
cqr->status = DASD_CQR_DONE;
return cqr;
}
/* check if error happened before */
erp = dasd_3990_erp_in_erp(cqr);
if (erp == NULL) {
/* no matching erp found - set up erp */
erp = dasd_3990_erp_additional_erp(cqr);
if (IS_ERR(erp))
return erp;
} else {
/* matching erp found - set all leading erp's to DONE */
erp = dasd_3990_erp_handle_match_erp(cqr, erp);
}
if (device->features & DASD_FEATURE_ERPLOG) {
/* print current erp_chain */
dev_err(&device->cdev->dev,
"ERP chain at END of ERP-ACTION\n");
for (temp_erp = erp;
temp_erp != NULL; temp_erp = temp_erp->refers) {
dev_err(&device->cdev->dev,
"ERP %p (%02x) refers to %p\n",
temp_erp, temp_erp->status,
temp_erp->refers);
}
}
/* enqueue ERP request if it's a new one */
if (list_empty(&erp->blocklist)) {
cqr->status = DASD_CQR_IN_ERP;
/* add erp request before the cqr */
list_add_tail(&erp->blocklist, &cqr->blocklist);
}
return erp;
} /* end dasd_3990_erp_action */
| geminy/aidear | oss/linux/linux-4.7/drivers/s390/block/dasd_3990_erp.c | C | gpl-3.0 | 70,793 |
/*
* Copyright (C) 2001 Matthew Wilcox <willy at parisc-linux.org>
* Copyright (C) 2003 Carlos O'Donell <carlos at parisc-linux.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _PARISC64_KERNEL_SIGNAL32_H
#define _PARISC64_KERNEL_SIGNAL32_H
#include <linux/compat.h>
typedef compat_uptr_t compat_sighandler_t;
typedef struct compat_sigaltstack {
compat_uptr_t ss_sp;
compat_int_t ss_flags;
compat_size_t ss_size;
} compat_stack_t;
/* Most things should be clean enough to redefine this at will, if care
is taken to make libc match. */
struct compat_sigaction {
compat_sighandler_t sa_handler;
compat_uint_t sa_flags;
compat_sigset_t sa_mask; /* mask last for extensibility */
};
/* 32-bit ucontext as seen from an 64-bit kernel */
struct compat_ucontext {
compat_uint_t uc_flags;
compat_uptr_t uc_link;
compat_stack_t uc_stack; /* struct compat_sigaltstack (12 bytes)*/
/* FIXME: Pad out to get uc_mcontext to start at an 8-byte aligned boundary */
compat_uint_t pad[1];
struct compat_sigcontext uc_mcontext;
compat_sigset_t uc_sigmask; /* mask last for extensibility */
};
/* ELF32 signal handling */
struct k_sigaction32 {
struct compat_sigaction sa;
};
typedef struct compat_siginfo {
int si_signo;
int si_errno;
int si_code;
union {
int _pad[((128/sizeof(int)) - 3)];
/* kill() */
struct {
unsigned int _pid; /* sender's pid */
unsigned int _uid; /* sender's uid */
} _kill;
/* POSIX.1b timers */
struct {
compat_timer_t _tid; /* timer id */
int _overrun; /* overrun count */
char _pad[sizeof(unsigned int) - sizeof(int)];
compat_sigval_t _sigval; /* same as below */
int _sys_private; /* not to be passed to user */
} _timer;
/* POSIX.1b signals */
struct {
unsigned int _pid; /* sender's pid */
unsigned int _uid; /* sender's uid */
compat_sigval_t _sigval;
} _rt;
/* SIGCHLD */
struct {
unsigned int _pid; /* which child */
unsigned int _uid; /* sender's uid */
int _status; /* exit code */
compat_clock_t _utime;
compat_clock_t _stime;
} _sigchld;
/* SIGILL, SIGFPE, SIGSEGV, SIGBUS */
struct {
unsigned int _addr; /* faulting insn/memory ref. */
} _sigfault;
/* SIGPOLL */
struct {
int _band; /* POLL_IN, POLL_OUT, POLL_MSG */
int _fd;
} _sigpoll;
} _sifields;
} compat_siginfo_t;
int copy_siginfo_to_user32 (compat_siginfo_t __user *to, siginfo_t *from);
int copy_siginfo_from_user32 (siginfo_t *to, compat_siginfo_t __user *from);
/* In a deft move of uber-hackery, we decide to carry the top half of all
* 64-bit registers in a non-portable, non-ABI, hidden structure.
* Userspace can read the hidden structure if it *wants* but is never
* guaranteed to be in the same place. In fact the uc_sigmask from the
* ucontext_t structure may push the hidden register file downards
*/
struct compat_regfile {
/* Upper half of all the 64-bit registers that were truncated
on a copy to a 32-bit userspace */
compat_int_t rf_gr[32];
compat_int_t rf_iasq[2];
compat_int_t rf_iaoq[2];
compat_int_t rf_sar;
};
#define COMPAT_SIGRETURN_TRAMP 4
#define COMPAT_SIGRESTARTBLOCK_TRAMP 5
#define COMPAT_TRAMP_SIZE (COMPAT_SIGRETURN_TRAMP + \
COMPAT_SIGRESTARTBLOCK_TRAMP)
struct compat_rt_sigframe {
/* XXX: Must match trampoline size in arch/parisc/kernel/signal.c
Secondary to that it must protect the ERESTART_RESTARTBLOCK
trampoline we left on the stack (we were bad and didn't
change sp so we could run really fast.) */
compat_uint_t tramp[COMPAT_TRAMP_SIZE];
compat_siginfo_t info;
struct compat_ucontext uc;
/* Hidden location of truncated registers, *must* be last. */
struct compat_regfile regs;
};
/*
* The 32-bit ABI wants at least 48 bytes for a function call frame:
* 16 bytes for arg0-arg3, and 32 bytes for magic (the only part of
* which Linux/parisc uses is sp-20 for the saved return pointer...)
* Then, the stack pointer must be rounded to a cache line (64 bytes).
*/
#define SIGFRAME32 64
#define FUNCTIONCALLFRAME32 48
#define PARISC_RT_SIGFRAME_SIZE32 (((sizeof(struct compat_rt_sigframe) + FUNCTIONCALLFRAME32) + SIGFRAME32) & -SIGFRAME32)
void sigset_32to64(sigset_t *s64, compat_sigset_t *s32);
void sigset_64to32(compat_sigset_t *s32, sigset_t *s64);
int do_sigaltstack32 (const compat_stack_t __user *uss32,
compat_stack_t __user *uoss32, unsigned long sp);
long restore_sigcontext32(struct compat_sigcontext __user *sc,
struct compat_regfile __user *rf,
struct pt_regs *regs);
long setup_sigcontext32(struct compat_sigcontext __user *sc,
struct compat_regfile __user *rf,
struct pt_regs *regs, int in_syscall);
#endif
| talnoah/android_kernel_htc_dlx | virt/arch/parisc/kernel/signal32.h | C | gpl-2.0 | 6,372 |
#import "GPUImage.h"
#import <UIKit/UIKit.h>
@interface RawDataTestAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| shahen94/react-native-video-processing | ios/GPUImage/examples/iOS/RawDataTest/RawDataTest/RawDataTestAppDelegate.h | C | mit | 173 |
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// EnvVarApplyConfiguration represents an declarative configuration of the EnvVar type for use
// with apply.
type EnvVarApplyConfiguration struct {
Name *string `json:"name,omitempty"`
Value *string `json:"value,omitempty"`
ValueFrom *EnvVarSourceApplyConfiguration `json:"valueFrom,omitempty"`
}
// EnvVarApplyConfiguration constructs an declarative configuration of the EnvVar type for use with
// apply.
func EnvVar() *EnvVarApplyConfiguration {
return &EnvVarApplyConfiguration{}
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *EnvVarApplyConfiguration) WithName(value string) *EnvVarApplyConfiguration {
b.Name = &value
return b
}
// WithValue sets the Value field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Value field is set to the value of the last call.
func (b *EnvVarApplyConfiguration) WithValue(value string) *EnvVarApplyConfiguration {
b.Value = &value
return b
}
// WithValueFrom sets the ValueFrom field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ValueFrom field is set to the value of the last call.
func (b *EnvVarApplyConfiguration) WithValueFrom(value *EnvVarSourceApplyConfiguration) *EnvVarApplyConfiguration {
b.ValueFrom = value
return b
}
| knative-sandbox/net-gateway-api | vendor/k8s.io/client-go/applyconfigurations/core/v1/envvar.go | GO | apache-2.0 | 2,383 |
//------------------------------------------------------------------------------
// <copyright file="bmi.c" company="Atheros">
// Copyright (c) 2004-2010 Atheros Corporation. All rights reserved.
//
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
//
//------------------------------------------------------------------------------
//==============================================================================
//
// Author(s): ="Atheros"
//==============================================================================
#ifdef THREAD_X
#include <string.h>
#endif
#include "hif.h"
#include "bmi.h"
#include "htc_api.h"
#include "bmi_internal.h"
#ifdef ATH_DEBUG_MODULE
static ATH_DEBUG_MASK_DESCRIPTION bmi_debug_desc[] = {
{ ATH_DEBUG_BMI , "BMI Tracing"},
};
ATH_DEBUG_INSTANTIATE_MODULE_VAR(bmi,
"bmi",
"Boot Manager Interface",
ATH_DEBUG_MASK_DEFAULTS,
ATH_DEBUG_DESCRIPTION_COUNT(bmi_debug_desc),
bmi_debug_desc);
#endif
/*
Although we had envisioned BMI to run on top of HTC, this is not how the
final implementation ended up. On the Target side, BMI is a part of the BSP
and does not use the HTC protocol nor even DMA -- it is intentionally kept
very simple.
*/
static A_BOOL pendingEventsFuncCheck = FALSE;
static A_UINT32 *pBMICmdCredits;
static A_UCHAR *pBMICmdBuf;
#define MAX_BMI_CMDBUF_SZ (BMI_DATASZ_MAX + \
sizeof(A_UINT32) /* cmd */ + \
sizeof(A_UINT32) /* addr */ + \
sizeof(A_UINT32))/* length */
#define BMI_COMMAND_FITS(sz) ((sz) <= MAX_BMI_CMDBUF_SZ)
/* APIs visible to the driver */
void
BMIInit(void)
{
bmiDone = FALSE;
pendingEventsFuncCheck = FALSE;
/*
* On some platforms, it's not possible to DMA to a static variable
* in a device driver (e.g. Linux loadable driver module).
* So we need to A_MALLOC space for "command credits" and for commands.
*
* Note: implicitly relies on A_MALLOC to provide a buffer that is
* suitable for DMA (or PIO). This buffer will be passed down the
* bus stack.
*/
if (!pBMICmdCredits) {
pBMICmdCredits = (A_UINT32 *)A_MALLOC_NOWAIT(4);
A_ASSERT(pBMICmdCredits);
}
if (!pBMICmdBuf) {
pBMICmdBuf = (A_UCHAR *)A_MALLOC_NOWAIT(MAX_BMI_CMDBUF_SZ);
A_ASSERT(pBMICmdBuf);
}
A_REGISTER_MODULE_DEBUG_INFO(bmi);
}
void
BMICleanup(void)
{
if (pBMICmdCredits) {
A_FREE(pBMICmdCredits);
pBMICmdCredits = NULL;
}
if (pBMICmdBuf) {
A_FREE(pBMICmdBuf);
pBMICmdBuf = NULL;
}
}
A_STATUS
BMIDone(HIF_DEVICE *device)
{
A_STATUS status;
A_UINT32 cid;
if (bmiDone) {
AR_DEBUG_PRINTF (ATH_DEBUG_BMI, ("BMIDone skipped\n"));
return A_OK;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Done: Enter (device: 0x%p)\n", device));
bmiDone = TRUE;
cid = BMI_DONE;
status = bmiBufferSend(device, (A_UCHAR *)&cid, sizeof(cid));
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
if (pBMICmdCredits) {
A_FREE(pBMICmdCredits);
pBMICmdCredits = NULL;
}
if (pBMICmdBuf) {
A_FREE(pBMICmdBuf);
pBMICmdBuf = NULL;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Done: Exit\n"));
return A_OK;
}
A_STATUS
BMIGetTargetInfo(HIF_DEVICE *device, struct bmi_target_info *targ_info)
{
A_STATUS status;
A_UINT32 cid;
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Get Target Info: Enter (device: 0x%p)\n", device));
cid = BMI_GET_TARGET_INFO;
status = bmiBufferSend(device, (A_UCHAR *)&cid, sizeof(cid));
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
status = bmiBufferReceive(device, (A_UCHAR *)&targ_info->target_ver,
sizeof(targ_info->target_ver), TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read Target Version from the device\n"));
return A_ERROR;
}
if (targ_info->target_ver == TARGET_VERSION_SENTINAL) {
/* Determine how many bytes are in the Target's targ_info */
status = bmiBufferReceive(device, (A_UCHAR *)&targ_info->target_info_byte_count,
sizeof(targ_info->target_info_byte_count), TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read Target Info Byte Count from the device\n"));
return A_ERROR;
}
/*
* The Target's targ_info doesn't match the Host's targ_info.
* We need to do some backwards compatibility work to make this OK.
*/
A_ASSERT(targ_info->target_info_byte_count == sizeof(*targ_info));
/* Read the remainder of the targ_info */
status = bmiBufferReceive(device,
((A_UCHAR *)targ_info)+sizeof(targ_info->target_info_byte_count),
sizeof(*targ_info)-sizeof(targ_info->target_info_byte_count), TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read Target Info (%d bytes) from the device\n",
targ_info->target_info_byte_count));
return A_ERROR;
}
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Get Target Info: Exit (ver: 0x%x type: 0x%x)\n",
targ_info->target_ver, targ_info->target_type));
return A_OK;
}
A_STATUS
BMIReadMemory(HIF_DEVICE *device,
A_UINT32 address,
A_UCHAR *buffer,
A_UINT32 length)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_UINT32 remaining, rxlen;
A_ASSERT(BMI_COMMAND_FITS(BMI_DATASZ_MAX + sizeof(cid) + sizeof(address) + sizeof(length)));
memset (pBMICmdBuf, 0, BMI_DATASZ_MAX + sizeof(cid) + sizeof(address) + sizeof(length));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Read Memory: Enter (device: 0x%p, address: 0x%x, length: %d)\n",
device, address, length));
cid = BMI_READ_MEMORY;
remaining = length;
while (remaining)
{
rxlen = (remaining < BMI_DATASZ_MAX) ? remaining : BMI_DATASZ_MAX;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
A_MEMCPY(&(pBMICmdBuf[offset]), &rxlen, sizeof(rxlen));
offset += sizeof(length);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
status = bmiBufferReceive(device, pBMICmdBuf, rxlen, TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read from the device\n"));
return A_ERROR;
}
A_MEMCPY(&buffer[length - remaining], pBMICmdBuf, rxlen);
remaining -= rxlen; address += rxlen;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Read Memory: Exit\n"));
return A_OK;
}
A_STATUS
BMIWriteMemory(HIF_DEVICE *device,
A_UINT32 address,
A_UCHAR *buffer,
A_UINT32 length)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_UINT32 remaining, txlen;
const A_UINT32 header = sizeof(cid) + sizeof(address) + sizeof(length);
A_UCHAR alignedBuffer[BMI_DATASZ_MAX];
A_UCHAR *src;
A_ASSERT(BMI_COMMAND_FITS(BMI_DATASZ_MAX + header));
memset (pBMICmdBuf, 0, BMI_DATASZ_MAX + header);
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Write Memory: Enter (device: 0x%p, address: 0x%x, length: %d)\n",
device, address, length));
cid = BMI_WRITE_MEMORY;
remaining = length;
while (remaining)
{
src = &buffer[length - remaining];
if (remaining < (BMI_DATASZ_MAX - header)) {
if (remaining & 3) {
/* align it with 4 bytes */
remaining = remaining + (4 - (remaining & 3));
memcpy(alignedBuffer, src, remaining);
src = alignedBuffer;
}
txlen = remaining;
} else {
txlen = (BMI_DATASZ_MAX - header);
}
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
A_MEMCPY(&(pBMICmdBuf[offset]), &txlen, sizeof(txlen));
offset += sizeof(txlen);
A_MEMCPY(&(pBMICmdBuf[offset]), src, txlen);
offset += txlen;
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
remaining -= txlen; address += txlen;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Write Memory: Exit\n"));
return A_OK;
}
A_STATUS
BMIExecute(HIF_DEVICE *device,
A_UINT32 address,
A_UINT32 *param)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(address) + sizeof(param)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(address) + sizeof(param));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Execute: Enter (device: 0x%p, address: 0x%x, param: %d)\n",
device, address, *param));
cid = BMI_EXECUTE;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
A_MEMCPY(&(pBMICmdBuf[offset]), param, sizeof(*param));
offset += sizeof(*param);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
status = bmiBufferReceive(device, pBMICmdBuf, sizeof(*param), FALSE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read from the device\n"));
return A_ERROR;
}
A_MEMCPY(param, pBMICmdBuf, sizeof(*param));
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Execute: Exit (param: %d)\n", *param));
return A_OK;
}
A_STATUS
BMISetAppStart(HIF_DEVICE *device,
A_UINT32 address)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(address)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(address));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Set App Start: Enter (device: 0x%p, address: 0x%x)\n",
device, address));
cid = BMI_SET_APP_START;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Set App Start: Exit\n"));
return A_OK;
}
A_STATUS
BMIReadSOCRegister(HIF_DEVICE *device,
A_UINT32 address,
A_UINT32 *param)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(address)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(address));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Read SOC Register: Enter (device: 0x%p, address: 0x%x)\n",
device, address));
cid = BMI_READ_SOC_REGISTER;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
status = bmiBufferReceive(device, pBMICmdBuf, sizeof(*param), TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read from the device\n"));
return A_ERROR;
}
A_MEMCPY(param, pBMICmdBuf, sizeof(*param));
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Read SOC Register: Exit (value: %d)\n", *param));
return A_OK;
}
A_STATUS
BMIWriteSOCRegister(HIF_DEVICE *device,
A_UINT32 address,
A_UINT32 param)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(address) + sizeof(param)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(address) + sizeof(param));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Write SOC Register: Enter (device: 0x%p, address: 0x%x, param: %d)\n",
device, address, param));
cid = BMI_WRITE_SOC_REGISTER;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
A_MEMCPY(&(pBMICmdBuf[offset]), ¶m, sizeof(param));
offset += sizeof(param);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Read SOC Register: Exit\n"));
return A_OK;
}
A_STATUS
BMIrompatchInstall(HIF_DEVICE *device,
A_UINT32 ROM_addr,
A_UINT32 RAM_addr,
A_UINT32 nbytes,
A_UINT32 do_activate,
A_UINT32 *rompatch_id)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(ROM_addr) + sizeof(RAM_addr) +
sizeof(nbytes) + sizeof(do_activate)));
memset(pBMICmdBuf, 0, sizeof(cid) + sizeof(ROM_addr) + sizeof(RAM_addr) +
sizeof(nbytes) + sizeof(do_activate));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI rompatch Install: Enter (device: 0x%p, ROMaddr: 0x%x, RAMaddr: 0x%x length: %d activate: %d)\n",
device, ROM_addr, RAM_addr, nbytes, do_activate));
cid = BMI_ROMPATCH_INSTALL;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &ROM_addr, sizeof(ROM_addr));
offset += sizeof(ROM_addr);
A_MEMCPY(&(pBMICmdBuf[offset]), &RAM_addr, sizeof(RAM_addr));
offset += sizeof(RAM_addr);
A_MEMCPY(&(pBMICmdBuf[offset]), &nbytes, sizeof(nbytes));
offset += sizeof(nbytes);
A_MEMCPY(&(pBMICmdBuf[offset]), &do_activate, sizeof(do_activate));
offset += sizeof(do_activate);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
status = bmiBufferReceive(device, pBMICmdBuf, sizeof(*rompatch_id), TRUE);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read from the device\n"));
return A_ERROR;
}
A_MEMCPY(rompatch_id, pBMICmdBuf, sizeof(*rompatch_id));
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI rompatch Install: (rompatch_id=%d)\n", *rompatch_id));
return A_OK;
}
A_STATUS
BMIrompatchUninstall(HIF_DEVICE *device,
A_UINT32 rompatch_id)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(rompatch_id)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(rompatch_id));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI rompatch Uninstall: Enter (device: 0x%p, rompatch_id: %d)\n",
device, rompatch_id));
cid = BMI_ROMPATCH_UNINSTALL;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &rompatch_id, sizeof(rompatch_id));
offset += sizeof(rompatch_id);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI rompatch UNinstall: (rompatch_id=0x%x)\n", rompatch_id));
return A_OK;
}
static A_STATUS
_BMIrompatchChangeActivation(HIF_DEVICE *device,
A_UINT32 rompatch_count,
A_UINT32 *rompatch_list,
A_UINT32 do_activate)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_UINT32 length;
A_ASSERT(BMI_COMMAND_FITS(BMI_DATASZ_MAX + sizeof(cid) + sizeof(rompatch_count)));
memset(pBMICmdBuf, 0, BMI_DATASZ_MAX + sizeof(cid) + sizeof(rompatch_count));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Change rompatch Activation: Enter (device: 0x%p, count: %d)\n",
device, rompatch_count));
cid = do_activate ? BMI_ROMPATCH_ACTIVATE : BMI_ROMPATCH_DEACTIVATE;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &rompatch_count, sizeof(rompatch_count));
offset += sizeof(rompatch_count);
length = rompatch_count * sizeof(*rompatch_list);
A_MEMCPY(&(pBMICmdBuf[offset]), rompatch_list, length);
offset += length;
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI Change rompatch Activation: Exit\n"));
return A_OK;
}
A_STATUS
BMIrompatchActivate(HIF_DEVICE *device,
A_UINT32 rompatch_count,
A_UINT32 *rompatch_list)
{
return _BMIrompatchChangeActivation(device, rompatch_count, rompatch_list, 1);
}
A_STATUS
BMIrompatchDeactivate(HIF_DEVICE *device,
A_UINT32 rompatch_count,
A_UINT32 *rompatch_list)
{
return _BMIrompatchChangeActivation(device, rompatch_count, rompatch_list, 0);
}
A_STATUS
BMILZData(HIF_DEVICE *device,
A_UCHAR *buffer,
A_UINT32 length)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_UINT32 remaining, txlen;
const A_UINT32 header = sizeof(cid) + sizeof(length);
A_ASSERT(BMI_COMMAND_FITS(BMI_DATASZ_MAX+header));
memset (pBMICmdBuf, 0, BMI_DATASZ_MAX+header);
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI Send LZ Data: Enter (device: 0x%p, length: %d)\n",
device, length));
cid = BMI_LZ_DATA;
remaining = length;
while (remaining)
{
txlen = (remaining < (BMI_DATASZ_MAX - header)) ?
remaining : (BMI_DATASZ_MAX - header);
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &txlen, sizeof(txlen));
offset += sizeof(txlen);
A_MEMCPY(&(pBMICmdBuf[offset]), &buffer[length - remaining], txlen);
offset += txlen;
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to write to the device\n"));
return A_ERROR;
}
remaining -= txlen;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI LZ Data: Exit\n"));
return A_OK;
}
A_STATUS
BMILZStreamStart(HIF_DEVICE *device,
A_UINT32 address)
{
A_UINT32 cid;
A_STATUS status;
A_UINT32 offset;
A_ASSERT(BMI_COMMAND_FITS(sizeof(cid) + sizeof(address)));
memset (pBMICmdBuf, 0, sizeof(cid) + sizeof(address));
if (bmiDone) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Command disallowed\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI,
("BMI LZ Stream Start: Enter (device: 0x%p, address: 0x%x)\n",
device, address));
cid = BMI_LZ_STREAM_START;
offset = 0;
A_MEMCPY(&(pBMICmdBuf[offset]), &cid, sizeof(cid));
offset += sizeof(cid);
A_MEMCPY(&(pBMICmdBuf[offset]), &address, sizeof(address));
offset += sizeof(address);
status = bmiBufferSend(device, pBMICmdBuf, offset);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to Start LZ Stream to the device\n"));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_BMI, ("BMI LZ Stream Start: Exit\n"));
return A_OK;
}
/* BMI Access routines */
A_STATUS
bmiBufferSend(HIF_DEVICE *device,
A_UCHAR *buffer,
A_UINT32 length)
{
A_STATUS status;
A_UINT32 timeout;
A_UINT32 address;
A_UINT32 mboxAddress[HTC_MAILBOX_NUM_MAX];
HIFConfigureDevice(device, HIF_DEVICE_GET_MBOX_ADDR,
&mboxAddress[0], sizeof(mboxAddress));
*pBMICmdCredits = 0;
timeout = BMI_COMMUNICATION_TIMEOUT;
while(timeout-- && !(*pBMICmdCredits)) {
/* Read the counter register to get the command credits */
address = COUNT_DEC_ADDRESS + (HTC_MAILBOX_NUM_MAX + ENDPOINT1) * 4;
/* hit the credit counter with a 4-byte access, the first byte read will hit the counter and cause
* a decrement, while the remaining 3 bytes has no effect. The rationale behind this is to
* make all HIF accesses 4-byte aligned */
status = HIFReadWrite(device, address, (A_UINT8 *)pBMICmdCredits, 4,
HIF_RD_SYNC_BYTE_INC, NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to decrement the command credit count register\n"));
return A_ERROR;
}
/* the counter is only 8=bits, ignore anything in the upper 3 bytes */
(*pBMICmdCredits) &= 0xFF;
}
if (*pBMICmdCredits) {
address = mboxAddress[ENDPOINT1];
status = HIFReadWrite(device, address, buffer, length,
HIF_WR_SYNC_BYTE_INC, NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to send the BMI data to the device\n"));
return A_ERROR;
}
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI Communication timeout - bmiBufferSend\n"));
return A_ERROR;
}
return status;
}
A_STATUS
bmiBufferReceive(HIF_DEVICE *device,
A_UCHAR *buffer,
A_UINT32 length,
A_BOOL want_timeout)
{
A_STATUS status;
A_UINT32 address;
A_UINT32 mboxAddress[HTC_MAILBOX_NUM_MAX];
HIF_PENDING_EVENTS_INFO hifPendingEvents;
static HIF_PENDING_EVENTS_FUNC getPendingEventsFunc = NULL;
if (!pendingEventsFuncCheck) {
/* see if the HIF layer implements an alternative function to get pending events
* do this only once! */
HIFConfigureDevice(device,
HIF_DEVICE_GET_PENDING_EVENTS_FUNC,
&getPendingEventsFunc,
sizeof(getPendingEventsFunc));
pendingEventsFuncCheck = TRUE;
}
HIFConfigureDevice(device, HIF_DEVICE_GET_MBOX_ADDR,
&mboxAddress[0], sizeof(mboxAddress));
/*
* During normal bootup, small reads may be required.
* Rather than issue an HIF Read and then wait as the Target
* adds successive bytes to the FIFO, we wait here until
* we know that response data is available.
*
* This allows us to cleanly timeout on an unexpected
* Target failure rather than risk problems at the HIF level. In
* particular, this avoids SDIO timeouts and possibly garbage
* data on some host controllers. And on an interconnect
* such as Compact Flash (as well as some SDIO masters) which
* does not provide any indication on data timeout, it avoids
* a potential hang or garbage response.
*
* Synchronization is more difficult for reads larger than the
* size of the MBOX FIFO (128B), because the Target is unable
* to push the 129th byte of data until AFTER the Host posts an
* HIF Read and removes some FIFO data. So for large reads the
* Host proceeds to post an HIF Read BEFORE all the data is
* actually available to read. Fortunately, large BMI reads do
* not occur in practice -- they're supported for debug/development.
*
* So Host/Target BMI synchronization is divided into these cases:
* CASE 1: length < 4
* Should not happen
*
* CASE 2: 4 <= length <= 128
* Wait for first 4 bytes to be in FIFO
* If CONSERVATIVE_BMI_READ is enabled, also wait for
* a BMI command credit, which indicates that the ENTIRE
* response is available in the the FIFO
*
* CASE 3: length > 128
* Wait for the first 4 bytes to be in FIFO
*
* For most uses, a small timeout should be sufficient and we will
* usually see a response quickly; but there may be some unusual
* (debug) cases of BMI_EXECUTE where we want an larger timeout.
* For now, we use an unbounded busy loop while waiting for
* BMI_EXECUTE.
*
* If BMI_EXECUTE ever needs to support longer-latency execution,
* especially in production, this code needs to be enhanced to sleep
* and yield. Also note that BMI_COMMUNICATION_TIMEOUT is currently
* a function of Host processor speed.
*/
if (length >= 4) { /* NB: Currently, always true */
/*
* NB: word_available is declared static for esoteric reasons
* having to do with protection on some OSes.
*/
static A_UINT32 word_available;
A_UINT32 timeout;
word_available = 0;
timeout = BMI_COMMUNICATION_TIMEOUT;
while((!want_timeout || timeout--) && !word_available) {
if (getPendingEventsFunc != NULL) {
status = getPendingEventsFunc(device,
&hifPendingEvents,
NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("BMI: Failed to get pending events \n"));
break;
}
if (hifPendingEvents.AvailableRecvBytes >= sizeof(A_UINT32)) {
word_available = 1;
}
continue;
}
status = HIFReadWrite(device, RX_LOOKAHEAD_VALID_ADDRESS, (A_UINT8 *)&word_available,
sizeof(word_available), HIF_RD_SYNC_BYTE_INC, NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read RX_LOOKAHEAD_VALID register\n"));
return A_ERROR;
}
/* We did a 4-byte read to the same register; all we really want is one bit */
word_available &= (1 << ENDPOINT1);
}
if (!word_available) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI Communication timeout - bmiBufferReceive FIFO empty\n"));
return A_ERROR;
}
}
#define CONSERVATIVE_BMI_READ 0
#if CONSERVATIVE_BMI_READ
/*
* This is an extra-conservative CREDIT check. It guarantees
* that ALL data is available in the FIFO before we start to
* read from the interconnect.
*
* This credit check is useless when firmware chooses to
* allow multiple outstanding BMI Command Credits, since the next
* credit will already be present. To restrict the Target to one
* BMI Command Credit, see HI_OPTION_BMI_CRED_LIMIT.
*
* And for large reads (when HI_OPTION_BMI_CRED_LIMIT is set)
* we cannot wait for the next credit because the Target's FIFO
* will not hold the entire response. So we need the Host to
* start to empty the FIFO sooner. (And again, large reads are
* not used in practice; they are for debug/development only.)
*
* For a more conservative Host implementation (which would be
* safer for a Compact Flash interconnect):
* Set CONSERVATIVE_BMI_READ (above) to 1
* Set HI_OPTION_BMI_CRED_LIMIT and
* reduce BMI_DATASZ_MAX to 32 or 64
*/
if ((length > 4) && (length < 128)) { /* check against MBOX FIFO size */
A_UINT32 timeout;
*pBMICmdCredits = 0;
timeout = BMI_COMMUNICATION_TIMEOUT;
while((!want_timeout || timeout--) && !(*pBMICmdCredits) {
/* Read the counter register to get the command credits */
address = COUNT_ADDRESS + (HTC_MAILBOX_NUM_MAX + ENDPOINT1) * 1;
/* read the counter using a 4-byte read. Since the counter is NOT auto-decrementing,
* we can read this counter multiple times using a non-incrementing address mode.
* The rationale here is to make all HIF accesses a multiple of 4 bytes */
status = HIFReadWrite(device, address, (A_UINT8 *)pBMICmdCredits, sizeof(*pBMICmdCredits),
HIF_RD_SYNC_BYTE_FIX, NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read the command credit count register\n"));
return A_ERROR;
}
/* we did a 4-byte read to the same count register so mask off upper bytes */
(*pBMICmdCredits) &= 0xFF;
}
if (!(*pBMICmdCredits)) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("BMI Communication timeout- bmiBufferReceive no credit\n"));
return A_ERROR;
}
}
#endif
address = mboxAddress[ENDPOINT1];
status = HIFReadWrite(device, address, buffer, length, HIF_RD_SYNC_BYTE_INC, NULL);
if (status != A_OK) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("Unable to read the BMI data from the device\n"));
return A_ERROR;
}
return A_OK;
}
A_STATUS
BMIFastDownload(HIF_DEVICE *device, A_UINT32 address, A_UCHAR *buffer, A_UINT32 length)
{
A_STATUS status = A_ERROR;
A_UINT32 lastWord = 0;
A_UINT32 lastWordOffset = length & ~0x3;
A_UINT32 unalignedBytes = length & 0x3;
status = BMILZStreamStart (device, address);
if (A_FAILED(status)) {
return A_ERROR;
}
if (unalignedBytes) {
/* copy the last word into a zero padded buffer */
A_MEMCPY(&lastWord, &buffer[lastWordOffset], unalignedBytes);
}
status = BMILZData(device, buffer, lastWordOffset);
if (A_FAILED(status)) {
return A_ERROR;
}
if (unalignedBytes) {
status = BMILZData(device, (A_UINT8 *)&lastWord, 4);
}
if (A_SUCCESS(status)) {
//
// Close compressed stream and open a new (fake) one. This serves mainly to flush Target caches.
//
status = BMILZStreamStart (device, 0x00);
if (A_FAILED(status)) {
return A_ERROR;
}
}
return status;
}
A_STATUS
BMIRawWrite(HIF_DEVICE *device, A_UCHAR *buffer, A_UINT32 length)
{
return bmiBufferSend(device, buffer, length);
}
A_STATUS
BMIRawRead(HIF_DEVICE *device, A_UCHAR *buffer, A_UINT32 length, A_BOOL want_timeout)
{
return bmiBufferReceive(device, buffer, length, want_timeout);
}
| sktjdgns1189/android_kernel_samsung_SHW-M340S | drivers/stagings/ath6kl/bmi/src/bmi.c | C | gpl-2.0 | 33,537 |
/*
* Copyright (c) 2010-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "htc.h"
MODULE_AUTHOR("Atheros Communications");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION("Atheros driver 802.11n HTC based wireless devices");
static unsigned int ath9k_debug = ATH_DBG_DEFAULT;
module_param_named(debug, ath9k_debug, uint, 0);
MODULE_PARM_DESC(debug, "Debugging mask");
int htc_modparam_nohwcrypt;
module_param_named(nohwcrypt, htc_modparam_nohwcrypt, int, 0444);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption");
static int ath9k_htc_btcoex_enable;
module_param_named(btcoex_enable, ath9k_htc_btcoex_enable, int, 0444);
MODULE_PARM_DESC(btcoex_enable, "Enable wifi-BT coexistence");
#define CHAN2G(_freq, _idx) { \
.center_freq = (_freq), \
.hw_value = (_idx), \
.max_power = 20, \
}
#define CHAN5G(_freq, _idx) { \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = (_freq), \
.hw_value = (_idx), \
.max_power = 20, \
}
static struct ieee80211_channel ath9k_2ghz_channels[] = {
CHAN2G(2412, 0), /* Channel 1 */
CHAN2G(2417, 1), /* Channel 2 */
CHAN2G(2422, 2), /* Channel 3 */
CHAN2G(2427, 3), /* Channel 4 */
CHAN2G(2432, 4), /* Channel 5 */
CHAN2G(2437, 5), /* Channel 6 */
CHAN2G(2442, 6), /* Channel 7 */
CHAN2G(2447, 7), /* Channel 8 */
CHAN2G(2452, 8), /* Channel 9 */
CHAN2G(2457, 9), /* Channel 10 */
CHAN2G(2462, 10), /* Channel 11 */
CHAN2G(2467, 11), /* Channel 12 */
CHAN2G(2472, 12), /* Channel 13 */
CHAN2G(2484, 13), /* Channel 14 */
};
static struct ieee80211_channel ath9k_5ghz_channels[] = {
/* _We_ call this UNII 1 */
CHAN5G(5180, 14), /* Channel 36 */
CHAN5G(5200, 15), /* Channel 40 */
CHAN5G(5220, 16), /* Channel 44 */
CHAN5G(5240, 17), /* Channel 48 */
/* _We_ call this UNII 2 */
CHAN5G(5260, 18), /* Channel 52 */
CHAN5G(5280, 19), /* Channel 56 */
CHAN5G(5300, 20), /* Channel 60 */
CHAN5G(5320, 21), /* Channel 64 */
/* _We_ call this "Middle band" */
CHAN5G(5500, 22), /* Channel 100 */
CHAN5G(5520, 23), /* Channel 104 */
CHAN5G(5540, 24), /* Channel 108 */
CHAN5G(5560, 25), /* Channel 112 */
CHAN5G(5580, 26), /* Channel 116 */
CHAN5G(5600, 27), /* Channel 120 */
CHAN5G(5620, 28), /* Channel 124 */
CHAN5G(5640, 29), /* Channel 128 */
CHAN5G(5660, 30), /* Channel 132 */
CHAN5G(5680, 31), /* Channel 136 */
CHAN5G(5700, 32), /* Channel 140 */
/* _We_ call this UNII 3 */
CHAN5G(5745, 33), /* Channel 149 */
CHAN5G(5765, 34), /* Channel 153 */
CHAN5G(5785, 35), /* Channel 157 */
CHAN5G(5805, 36), /* Channel 161 */
CHAN5G(5825, 37), /* Channel 165 */
};
/* Atheros hardware rate code addition for short premble */
#define SHPCHECK(__hw_rate, __flags) \
((__flags & IEEE80211_RATE_SHORT_PREAMBLE) ? (__hw_rate | 0x04) : 0)
#define RATE(_bitrate, _hw_rate, _flags) { \
.bitrate = (_bitrate), \
.flags = (_flags), \
.hw_value = (_hw_rate), \
.hw_value_short = (SHPCHECK(_hw_rate, _flags)) \
}
static struct ieee80211_rate ath9k_legacy_rates[] = {
RATE(10, 0x1b, 0),
RATE(20, 0x1a, IEEE80211_RATE_SHORT_PREAMBLE), /* shortp : 0x1e */
RATE(55, 0x19, IEEE80211_RATE_SHORT_PREAMBLE), /* shortp: 0x1d */
RATE(110, 0x18, IEEE80211_RATE_SHORT_PREAMBLE), /* short: 0x1c */
RATE(60, 0x0b, 0),
RATE(90, 0x0f, 0),
RATE(120, 0x0a, 0),
RATE(180, 0x0e, 0),
RATE(240, 0x09, 0),
RATE(360, 0x0d, 0),
RATE(480, 0x08, 0),
RATE(540, 0x0c, 0),
};
#ifdef CONFIG_MAC80211_LEDS
static const struct ieee80211_tpt_blink ath9k_htc_tpt_blink[] = {
{ .throughput = 0 * 1024, .blink_time = 334 },
{ .throughput = 1 * 1024, .blink_time = 260 },
{ .throughput = 5 * 1024, .blink_time = 220 },
{ .throughput = 10 * 1024, .blink_time = 190 },
{ .throughput = 20 * 1024, .blink_time = 170 },
{ .throughput = 50 * 1024, .blink_time = 150 },
{ .throughput = 70 * 1024, .blink_time = 130 },
{ .throughput = 100 * 1024, .blink_time = 110 },
{ .throughput = 200 * 1024, .blink_time = 80 },
{ .throughput = 300 * 1024, .blink_time = 50 },
};
#endif
static int ath9k_htc_wait_for_target(struct ath9k_htc_priv *priv)
{
int time_left;
if (atomic_read(&priv->htc->tgt_ready) > 0) {
atomic_dec(&priv->htc->tgt_ready);
return 0;
}
/* Firmware can take up to 50ms to get ready, to be safe use 1 second */
time_left = wait_for_completion_timeout(&priv->htc->target_wait, HZ);
if (!time_left) {
dev_err(priv->dev, "ath9k_htc: Target is unresponsive\n");
return -ETIMEDOUT;
}
atomic_dec(&priv->htc->tgt_ready);
return 0;
}
static void ath9k_deinit_priv(struct ath9k_htc_priv *priv)
{
ath9k_hw_deinit(priv->ah);
kfree(priv->ah);
priv->ah = NULL;
}
static void ath9k_deinit_device(struct ath9k_htc_priv *priv)
{
struct ieee80211_hw *hw = priv->hw;
wiphy_rfkill_stop_polling(hw->wiphy);
ath9k_deinit_leds(priv);
ieee80211_unregister_hw(hw);
ath9k_rx_cleanup(priv);
ath9k_tx_cleanup(priv);
ath9k_deinit_priv(priv);
}
static inline int ath9k_htc_connect_svc(struct ath9k_htc_priv *priv,
u16 service_id,
void (*tx) (void *,
struct sk_buff *,
enum htc_endpoint_id,
bool txok),
enum htc_endpoint_id *ep_id)
{
struct htc_service_connreq req;
memset(&req, 0, sizeof(struct htc_service_connreq));
req.service_id = service_id;
req.ep_callbacks.priv = priv;
req.ep_callbacks.rx = ath9k_htc_rxep;
req.ep_callbacks.tx = tx;
return htc_connect_service(priv->htc, &req, ep_id);
}
static int ath9k_init_htc_services(struct ath9k_htc_priv *priv, u16 devid,
u32 drv_info)
{
int ret;
/* WMI CMD*/
ret = ath9k_wmi_connect(priv->htc, priv->wmi, &priv->wmi_cmd_ep);
if (ret)
goto err;
/* Beacon */
ret = ath9k_htc_connect_svc(priv, WMI_BEACON_SVC, ath9k_htc_beaconep,
&priv->beacon_ep);
if (ret)
goto err;
/* CAB */
ret = ath9k_htc_connect_svc(priv, WMI_CAB_SVC, ath9k_htc_txep,
&priv->cab_ep);
if (ret)
goto err;
/* UAPSD */
ret = ath9k_htc_connect_svc(priv, WMI_UAPSD_SVC, ath9k_htc_txep,
&priv->uapsd_ep);
if (ret)
goto err;
/* MGMT */
ret = ath9k_htc_connect_svc(priv, WMI_MGMT_SVC, ath9k_htc_txep,
&priv->mgmt_ep);
if (ret)
goto err;
/* DATA BE */
ret = ath9k_htc_connect_svc(priv, WMI_DATA_BE_SVC, ath9k_htc_txep,
&priv->data_be_ep);
if (ret)
goto err;
/* DATA BK */
ret = ath9k_htc_connect_svc(priv, WMI_DATA_BK_SVC, ath9k_htc_txep,
&priv->data_bk_ep);
if (ret)
goto err;
/* DATA VI */
ret = ath9k_htc_connect_svc(priv, WMI_DATA_VI_SVC, ath9k_htc_txep,
&priv->data_vi_ep);
if (ret)
goto err;
/* DATA VO */
ret = ath9k_htc_connect_svc(priv, WMI_DATA_VO_SVC, ath9k_htc_txep,
&priv->data_vo_ep);
if (ret)
goto err;
/*
* Setup required credits before initializing HTC.
* This is a bit hacky, but, since queuing is done in
* the HIF layer, shouldn't matter much.
*/
if (IS_AR7010_DEVICE(drv_info))
priv->htc->credits = 45;
else
priv->htc->credits = 33;
ret = htc_init(priv->htc);
if (ret)
goto err;
dev_info(priv->dev, "ath9k_htc: HTC initialized with %d credits\n",
priv->htc->credits);
return 0;
err:
dev_err(priv->dev, "ath9k_htc: Unable to initialize HTC services\n");
return ret;
}
static void ath9k_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *request)
{
struct ieee80211_hw *hw = wiphy_to_ieee80211_hw(wiphy);
struct ath9k_htc_priv *priv = hw->priv;
ath_reg_notifier_apply(wiphy, request,
ath9k_hw_regulatory(priv->ah));
}
static unsigned int ath9k_regread(void *hw_priv, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
__be32 val, reg = cpu_to_be32(reg_offset);
int r;
r = ath9k_wmi_cmd(priv->wmi, WMI_REG_READ_CMDID,
(u8 *) ®, sizeof(reg),
(u8 *) &val, sizeof(val),
100);
if (unlikely(r)) {
ath_dbg(common, WMI, "REGISTER READ FAILED: (0x%04x, %d)\n",
reg_offset, r);
return -EIO;
}
return be32_to_cpu(val);
}
static void ath9k_multi_regread(void *hw_priv, u32 *addr,
u32 *val, u16 count)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
__be32 tmpaddr[8];
__be32 tmpval[8];
int i, ret;
for (i = 0; i < count; i++) {
tmpaddr[i] = cpu_to_be32(addr[i]);
}
ret = ath9k_wmi_cmd(priv->wmi, WMI_REG_READ_CMDID,
(u8 *)tmpaddr , sizeof(u32) * count,
(u8 *)tmpval, sizeof(u32) * count,
100);
if (unlikely(ret)) {
ath_dbg(common, WMI,
"Multiple REGISTER READ FAILED (count: %d)\n", count);
}
for (i = 0; i < count; i++) {
val[i] = be32_to_cpu(tmpval[i]);
}
}
static void ath9k_regwrite_single(void *hw_priv, u32 val, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
const __be32 buf[2] = {
cpu_to_be32(reg_offset),
cpu_to_be32(val),
};
int r;
r = ath9k_wmi_cmd(priv->wmi, WMI_REG_WRITE_CMDID,
(u8 *) &buf, sizeof(buf),
(u8 *) &val, sizeof(val),
100);
if (unlikely(r)) {
ath_dbg(common, WMI, "REGISTER WRITE FAILED:(0x%04x, %d)\n",
reg_offset, r);
}
}
static void ath9k_regwrite_buffer(void *hw_priv, u32 val, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
u32 rsp_status;
int r;
mutex_lock(&priv->wmi->multi_write_mutex);
/* Store the register/value */
priv->wmi->multi_write[priv->wmi->multi_write_idx].reg =
cpu_to_be32(reg_offset);
priv->wmi->multi_write[priv->wmi->multi_write_idx].val =
cpu_to_be32(val);
priv->wmi->multi_write_idx++;
/* If the buffer is full, send it out. */
if (priv->wmi->multi_write_idx == MAX_CMD_NUMBER) {
r = ath9k_wmi_cmd(priv->wmi, WMI_REG_WRITE_CMDID,
(u8 *) &priv->wmi->multi_write,
sizeof(struct register_write) * priv->wmi->multi_write_idx,
(u8 *) &rsp_status, sizeof(rsp_status),
100);
if (unlikely(r)) {
ath_dbg(common, WMI,
"REGISTER WRITE FAILED, multi len: %d\n",
priv->wmi->multi_write_idx);
}
priv->wmi->multi_write_idx = 0;
}
mutex_unlock(&priv->wmi->multi_write_mutex);
}
static void ath9k_regwrite(void *hw_priv, u32 val, u32 reg_offset)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
if (atomic_read(&priv->wmi->mwrite_cnt))
ath9k_regwrite_buffer(hw_priv, val, reg_offset);
else
ath9k_regwrite_single(hw_priv, val, reg_offset);
}
static void ath9k_enable_regwrite_buffer(void *hw_priv)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
atomic_inc(&priv->wmi->mwrite_cnt);
}
static void ath9k_regwrite_flush(void *hw_priv)
{
struct ath_hw *ah = (struct ath_hw *) hw_priv;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
u32 rsp_status;
int r;
atomic_dec(&priv->wmi->mwrite_cnt);
mutex_lock(&priv->wmi->multi_write_mutex);
if (priv->wmi->multi_write_idx) {
r = ath9k_wmi_cmd(priv->wmi, WMI_REG_WRITE_CMDID,
(u8 *) &priv->wmi->multi_write,
sizeof(struct register_write) * priv->wmi->multi_write_idx,
(u8 *) &rsp_status, sizeof(rsp_status),
100);
if (unlikely(r)) {
ath_dbg(common, WMI,
"REGISTER WRITE FAILED, multi len: %d\n",
priv->wmi->multi_write_idx);
}
priv->wmi->multi_write_idx = 0;
}
mutex_unlock(&priv->wmi->multi_write_mutex);
}
static u32 ath9k_reg_rmw(void *hw_priv, u32 reg_offset, u32 set, u32 clr)
{
u32 val;
val = ath9k_regread(hw_priv, reg_offset);
val &= ~clr;
val |= set;
ath9k_regwrite(hw_priv, val, reg_offset);
return val;
}
static void ath_usb_read_cachesize(struct ath_common *common, int *csz)
{
*csz = L1_CACHE_BYTES >> 2;
}
static bool ath_usb_eeprom_read(struct ath_common *common, u32 off, u16 *data)
{
struct ath_hw *ah = (struct ath_hw *) common->ah;
(void)REG_READ(ah, AR5416_EEPROM_OFFSET + (off << AR5416_EEPROM_S));
if (!ath9k_hw_wait(ah,
AR_EEPROM_STATUS_DATA,
AR_EEPROM_STATUS_DATA_BUSY |
AR_EEPROM_STATUS_DATA_PROT_ACCESS, 0,
AH_WAIT_TIMEOUT))
return false;
*data = MS(REG_READ(ah, AR_EEPROM_STATUS_DATA),
AR_EEPROM_STATUS_DATA_VAL);
return true;
}
static const struct ath_bus_ops ath9k_usb_bus_ops = {
.ath_bus_type = ATH_USB,
.read_cachesize = ath_usb_read_cachesize,
.eeprom_read = ath_usb_eeprom_read,
};
static void setup_ht_cap(struct ath9k_htc_priv *priv,
struct ieee80211_sta_ht_cap *ht_info)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
u8 tx_streams, rx_streams;
int i;
ht_info->ht_supported = true;
ht_info->cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 |
IEEE80211_HT_CAP_SM_PS |
IEEE80211_HT_CAP_SGI_40 |
IEEE80211_HT_CAP_DSSSCCK40;
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_SGI_20)
ht_info->cap |= IEEE80211_HT_CAP_SGI_20;
ht_info->cap |= (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT);
ht_info->ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
ht_info->ampdu_density = IEEE80211_HT_MPDU_DENSITY_8;
memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
/* ath9k_htc supports only 1 or 2 stream devices */
tx_streams = ath9k_cmn_count_streams(priv->ah->txchainmask, 2);
rx_streams = ath9k_cmn_count_streams(priv->ah->rxchainmask, 2);
ath_dbg(common, CONFIG, "TX streams %d, RX streams: %d\n",
tx_streams, rx_streams);
if (tx_streams != rx_streams) {
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_RX_DIFF;
ht_info->mcs.tx_params |= ((tx_streams - 1) <<
IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT);
}
for (i = 0; i < rx_streams; i++)
ht_info->mcs.rx_mask[i] = 0xff;
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_DEFINED;
}
static int ath9k_init_queues(struct ath9k_htc_priv *priv)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
int i;
for (i = 0; i < ARRAY_SIZE(priv->hwq_map); i++)
priv->hwq_map[i] = -1;
priv->beaconq = ath9k_hw_beaconq_setup(priv->ah);
if (priv->beaconq == -1) {
ath_err(common, "Unable to setup BEACON xmit queue\n");
goto err;
}
priv->cabq = ath9k_htc_cabq_setup(priv);
if (priv->cabq == -1) {
ath_err(common, "Unable to setup CAB xmit queue\n");
goto err;
}
if (!ath9k_htc_txq_setup(priv, IEEE80211_AC_BE)) {
ath_err(common, "Unable to setup xmit queue for BE traffic\n");
goto err;
}
if (!ath9k_htc_txq_setup(priv, IEEE80211_AC_BK)) {
ath_err(common, "Unable to setup xmit queue for BK traffic\n");
goto err;
}
if (!ath9k_htc_txq_setup(priv, IEEE80211_AC_VI)) {
ath_err(common, "Unable to setup xmit queue for VI traffic\n");
goto err;
}
if (!ath9k_htc_txq_setup(priv, IEEE80211_AC_VO)) {
ath_err(common, "Unable to setup xmit queue for VO traffic\n");
goto err;
}
return 0;
err:
return -EINVAL;
}
static void ath9k_init_channels_rates(struct ath9k_htc_priv *priv)
{
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ) {
priv->sbands[IEEE80211_BAND_2GHZ].channels =
ath9k_2ghz_channels;
priv->sbands[IEEE80211_BAND_2GHZ].band = IEEE80211_BAND_2GHZ;
priv->sbands[IEEE80211_BAND_2GHZ].n_channels =
ARRAY_SIZE(ath9k_2ghz_channels);
priv->sbands[IEEE80211_BAND_2GHZ].bitrates = ath9k_legacy_rates;
priv->sbands[IEEE80211_BAND_2GHZ].n_bitrates =
ARRAY_SIZE(ath9k_legacy_rates);
}
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ) {
priv->sbands[IEEE80211_BAND_5GHZ].channels = ath9k_5ghz_channels;
priv->sbands[IEEE80211_BAND_5GHZ].band = IEEE80211_BAND_5GHZ;
priv->sbands[IEEE80211_BAND_5GHZ].n_channels =
ARRAY_SIZE(ath9k_5ghz_channels);
priv->sbands[IEEE80211_BAND_5GHZ].bitrates =
ath9k_legacy_rates + 4;
priv->sbands[IEEE80211_BAND_5GHZ].n_bitrates =
ARRAY_SIZE(ath9k_legacy_rates) - 4;
}
}
static void ath9k_init_misc(struct ath9k_htc_priv *priv)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
memcpy(common->bssidmask, ath_bcast_mac, ETH_ALEN);
priv->ah->opmode = NL80211_IFTYPE_STATION;
}
static int ath9k_init_priv(struct ath9k_htc_priv *priv,
u16 devid, char *product,
u32 drv_info)
{
struct ath_hw *ah = NULL;
struct ath_common *common;
int i, ret = 0, csz = 0;
set_bit(OP_INVALID, &priv->op_flags);
ah = kzalloc(sizeof(struct ath_hw), GFP_KERNEL);
if (!ah)
return -ENOMEM;
ah->hw_version.devid = devid;
ah->hw_version.usbdev = drv_info;
ah->ah_flags |= AH_USE_EEPROM;
ah->reg_ops.read = ath9k_regread;
ah->reg_ops.multi_read = ath9k_multi_regread;
ah->reg_ops.write = ath9k_regwrite;
ah->reg_ops.enable_write_buffer = ath9k_enable_regwrite_buffer;
ah->reg_ops.write_flush = ath9k_regwrite_flush;
ah->reg_ops.rmw = ath9k_reg_rmw;
priv->ah = ah;
common = ath9k_hw_common(ah);
common->ops = &ah->reg_ops;
common->bus_ops = &ath9k_usb_bus_ops;
common->ah = ah;
common->hw = priv->hw;
common->priv = priv;
common->debug_mask = ath9k_debug;
common->btcoex_enabled = ath9k_htc_btcoex_enable == 1;
spin_lock_init(&priv->beacon_lock);
spin_lock_init(&priv->tx.tx_lock);
mutex_init(&priv->mutex);
mutex_init(&priv->htc_pm_lock);
tasklet_init(&priv->rx_tasklet, ath9k_rx_tasklet,
(unsigned long)priv);
tasklet_init(&priv->tx_failed_tasklet, ath9k_tx_failed_tasklet,
(unsigned long)priv);
INIT_DELAYED_WORK(&priv->ani_work, ath9k_htc_ani_work);
INIT_WORK(&priv->ps_work, ath9k_ps_work);
INIT_WORK(&priv->fatal_work, ath9k_fatal_work);
setup_timer(&priv->tx.cleanup_timer, ath9k_htc_tx_cleanup_timer,
(unsigned long)priv);
/*
* Cache line size is used to size and align various
* structures used to communicate with the hardware.
*/
ath_read_cachesize(common, &csz);
common->cachelsz = csz << 2; /* convert to bytes */
ret = ath9k_hw_init(ah);
if (ret) {
ath_err(common,
"Unable to initialize hardware; initialization status: %d\n",
ret);
goto err_hw;
}
ret = ath9k_init_queues(priv);
if (ret)
goto err_queues;
for (i = 0; i < ATH9K_HTC_MAX_BCN_VIF; i++)
priv->cur_beacon_conf.bslot[i] = NULL;
ath9k_cmn_init_crypto(ah);
ath9k_init_channels_rates(priv);
ath9k_init_misc(priv);
ath9k_htc_init_btcoex(priv, product);
return 0;
err_queues:
ath9k_hw_deinit(ah);
err_hw:
kfree(ah);
priv->ah = NULL;
return ret;
}
static const struct ieee80211_iface_limit if_limits[] = {
{ .max = 2, .types = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_P2P_CLIENT) },
{ .max = 2, .types = BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_GO) },
};
static const struct ieee80211_iface_combination if_comb = {
.limits = if_limits,
.n_limits = ARRAY_SIZE(if_limits),
.max_interfaces = 2,
.num_different_channels = 1,
};
static void ath9k_set_hw_capab(struct ath9k_htc_priv *priv,
struct ieee80211_hw *hw)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
hw->flags = IEEE80211_HW_SIGNAL_DBM |
IEEE80211_HW_AMPDU_AGGREGATION |
IEEE80211_HW_SPECTRUM_MGMT |
IEEE80211_HW_HAS_RATE_CONTROL |
IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_PS_NULLFUNC_STACK |
IEEE80211_HW_REPORTS_TX_ACK_STATUS |
IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING;
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_CLIENT);
hw->wiphy->iface_combinations = &if_comb;
hw->wiphy->n_iface_combinations = 1;
hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN |
WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
hw->queues = 4;
hw->channel_change_time = 5000;
hw->max_listen_interval = 1;
hw->vif_data_size = sizeof(struct ath9k_htc_vif);
hw->sta_data_size = sizeof(struct ath9k_htc_sta);
/* tx_frame_hdr is larger than tx_mgmt_hdr anyway */
hw->extra_tx_headroom = sizeof(struct tx_frame_hdr) +
sizeof(struct htc_frame_hdr) + 4;
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
&priv->sbands[IEEE80211_BAND_2GHZ];
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
&priv->sbands[IEEE80211_BAND_5GHZ];
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_HT) {
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_2GHZ)
setup_ht_cap(priv,
&priv->sbands[IEEE80211_BAND_2GHZ].ht_cap);
if (priv->ah->caps.hw_caps & ATH9K_HW_CAP_5GHZ)
setup_ht_cap(priv,
&priv->sbands[IEEE80211_BAND_5GHZ].ht_cap);
}
SET_IEEE80211_PERM_ADDR(hw, common->macaddr);
}
static int ath9k_init_firmware_version(struct ath9k_htc_priv *priv)
{
struct ieee80211_hw *hw = priv->hw;
struct wmi_fw_version cmd_rsp;
int ret;
memset(&cmd_rsp, 0, sizeof(cmd_rsp));
WMI_CMD(WMI_GET_FW_VERSION);
if (ret)
return -EINVAL;
priv->fw_version_major = be16_to_cpu(cmd_rsp.major);
priv->fw_version_minor = be16_to_cpu(cmd_rsp.minor);
snprintf(hw->wiphy->fw_version, sizeof(hw->wiphy->fw_version), "%d.%d",
priv->fw_version_major,
priv->fw_version_minor);
dev_info(priv->dev, "ath9k_htc: FW Version: %d.%d\n",
priv->fw_version_major,
priv->fw_version_minor);
/*
* Check if the available FW matches the driver's
* required version.
*/
if (priv->fw_version_major != MAJOR_VERSION_REQ ||
priv->fw_version_minor < MINOR_VERSION_REQ) {
dev_err(priv->dev, "ath9k_htc: Please upgrade to FW version %d.%d\n",
MAJOR_VERSION_REQ, MINOR_VERSION_REQ);
return -EINVAL;
}
return 0;
}
static int ath9k_init_device(struct ath9k_htc_priv *priv,
u16 devid, char *product, u32 drv_info)
{
struct ieee80211_hw *hw = priv->hw;
struct ath_common *common;
struct ath_hw *ah;
int error = 0;
struct ath_regulatory *reg;
char hw_name[64];
/* Bring up device */
error = ath9k_init_priv(priv, devid, product, drv_info);
if (error != 0)
goto err_init;
ah = priv->ah;
common = ath9k_hw_common(ah);
ath9k_set_hw_capab(priv, hw);
error = ath9k_init_firmware_version(priv);
if (error != 0)
goto err_fw;
/* Initialize regulatory */
error = ath_regd_init(&common->regulatory, priv->hw->wiphy,
ath9k_reg_notifier);
if (error)
goto err_regd;
reg = &common->regulatory;
/* Setup TX */
error = ath9k_tx_init(priv);
if (error != 0)
goto err_tx;
/* Setup RX */
error = ath9k_rx_init(priv);
if (error != 0)
goto err_rx;
ath9k_hw_disable(priv->ah);
#ifdef CONFIG_MAC80211_LEDS
/* must be initialized before ieee80211_register_hw */
priv->led_cdev.default_trigger = ieee80211_create_tpt_led_trigger(priv->hw,
IEEE80211_TPT_LEDTRIG_FL_RADIO, ath9k_htc_tpt_blink,
ARRAY_SIZE(ath9k_htc_tpt_blink));
#endif
/* Register with mac80211 */
error = ieee80211_register_hw(hw);
if (error)
goto err_register;
/* Handle world regulatory */
if (!ath_is_world_regd(reg)) {
error = regulatory_hint(hw->wiphy, reg->alpha2);
if (error)
goto err_world;
}
error = ath9k_htc_init_debug(priv->ah);
if (error) {
ath_err(common, "Unable to create debugfs files\n");
goto err_world;
}
ath_dbg(common, CONFIG,
"WMI:%d, BCN:%d, CAB:%d, UAPSD:%d, MGMT:%d, BE:%d, BK:%d, VI:%d, VO:%d\n",
priv->wmi_cmd_ep,
priv->beacon_ep,
priv->cab_ep,
priv->uapsd_ep,
priv->mgmt_ep,
priv->data_be_ep,
priv->data_bk_ep,
priv->data_vi_ep,
priv->data_vo_ep);
ath9k_hw_name(priv->ah, hw_name, sizeof(hw_name));
wiphy_info(hw->wiphy, "%s\n", hw_name);
ath9k_init_leds(priv);
ath9k_start_rfkill_poll(priv);
return 0;
err_world:
ieee80211_unregister_hw(hw);
err_register:
ath9k_rx_cleanup(priv);
err_rx:
ath9k_tx_cleanup(priv);
err_tx:
/* Nothing */
err_regd:
/* Nothing */
err_fw:
ath9k_deinit_priv(priv);
err_init:
return error;
}
int ath9k_htc_probe_device(struct htc_target *htc_handle, struct device *dev,
u16 devid, char *product, u32 drv_info)
{
struct ieee80211_hw *hw;
struct ath9k_htc_priv *priv;
int ret;
hw = ieee80211_alloc_hw(sizeof(struct ath9k_htc_priv), &ath9k_htc_ops);
if (!hw)
return -ENOMEM;
priv = hw->priv;
priv->hw = hw;
priv->htc = htc_handle;
priv->dev = dev;
htc_handle->drv_priv = priv;
SET_IEEE80211_DEV(hw, priv->dev);
ret = ath9k_htc_wait_for_target(priv);
if (ret)
goto err_free;
priv->wmi = ath9k_init_wmi(priv);
if (!priv->wmi) {
ret = -EINVAL;
goto err_free;
}
ret = ath9k_init_htc_services(priv, devid, drv_info);
if (ret)
goto err_init;
ret = ath9k_init_device(priv, devid, product, drv_info);
if (ret)
goto err_init;
return 0;
err_init:
ath9k_deinit_wmi(priv);
err_free:
ieee80211_free_hw(hw);
return ret;
}
void ath9k_htc_disconnect_device(struct htc_target *htc_handle, bool hotunplug)
{
if (htc_handle->drv_priv) {
/* Check if the device has been yanked out. */
if (hotunplug)
htc_handle->drv_priv->ah->ah_flags |= AH_UNPLUGGED;
ath9k_deinit_device(htc_handle->drv_priv);
ath9k_deinit_wmi(htc_handle->drv_priv);
ieee80211_free_hw(htc_handle->drv_priv->hw);
}
}
#ifdef CONFIG_PM
void ath9k_htc_suspend(struct htc_target *htc_handle)
{
ath9k_htc_setpower(htc_handle->drv_priv, ATH9K_PM_FULL_SLEEP);
}
int ath9k_htc_resume(struct htc_target *htc_handle)
{
struct ath9k_htc_priv *priv = htc_handle->drv_priv;
int ret;
ret = ath9k_htc_wait_for_target(priv);
if (ret)
return ret;
ret = ath9k_init_htc_services(priv, priv->ah->hw_version.devid,
priv->ah->hw_version.usbdev);
return ret;
}
#endif
static int __init ath9k_htc_init(void)
{
if (ath9k_hif_usb_init() < 0) {
pr_err("No USB devices found, driver not installed\n");
return -ENODEV;
}
return 0;
}
module_init(ath9k_htc_init);
static void __exit ath9k_htc_exit(void)
{
ath9k_hif_usb_exit();
pr_info("Driver unloaded\n");
}
module_exit(ath9k_htc_exit);
| prasidh09/cse506 | unionfs-3.10.y/drivers/net/wireless/ath/ath9k/htc_drv_init.c | C | gpl-2.0 | 26,608 |
.leaflet-cluster-anim .leaflet-marker-icon, .leaflet-cluster-anim .leaflet-marker-shadow {
-webkit-transition: -webkit-transform 0.2s ease-out, opacity 0.2s ease-in;
-moz-transition: -moz-transform 0.2s ease-out, opacity 0.2s ease-in;
-o-transition: -o-transform 0.2s ease-out, opacity 0.2s ease-in;
transition: transform 0.2s ease-out, opacity 0.2s ease-in;
}
| aksswami/aks-bitmap | www/css/MarkerCluster.css | CSS | apache-2.0 | 366 |
-- Dragonblight Pathing - Moa'ki Harbor + Azure Dragonshrine
-- 1. rndmmovement
UPDATE `creature` SET `spawndist`=20 WHERE `guid` IN (106644, 106699, 106698, 106714, 106736, 131071, 106695, 106720);
-- 2. emotes
DELETE FROM `creature_addon` WHERE `guid` IN (109020, 109041);
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(109020,0,0,0,1,51, ''),
(109041,0,0,0,1,51, '');
-- 3.
SET @NPC := 106347;
SET @PATH := @NPC * 10;
UPDATE `creature` SET `spawndist`=0,`MovementType`=2,`position_x`=3328.549,`position_y`=35.32029,`position_z`=68.77303 WHERE `guid`=@NPC;
DELETE FROM `creature_addon` WHERE `guid`=@NPC;
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES (@NPC,@PATH,0,0,1,0, '');
DELETE FROM `waypoint_data` WHERE `id`=@PATH;
INSERT INTO `waypoint_data` (`id`,`point`,`position_x`,`position_y`,`position_z`,`orientation`,`delay`,`move_type`,`action`,`action_chance`,`wpguid`) VALUES
(@PATH,1,3328.549,35.32029,68.77303,0,0,0,0,100,0),
(@PATH,2,3328.281,35.21631,68.51276,0,0,0,0,100,0),
(@PATH,3,3328.231,35.3801,68.81226,0,0,0,0,100,0),
(@PATH,4,3326.481,39.1301,69.56226,0,0,0,0,100,0),
(@PATH,5,3324.981,42.3801,70.06226,0,0,0,0,100,0),
(@PATH,6,3323.481,44.8801,70.56226,0,0,0,0,100,0),
(@PATH,7,3323.24,45.35506,70.7541,0,0,0,0,100,0),
(@PATH,8,3322.99,45.85506,70.7541,0,0,0,0,100,0),
(@PATH,9,3321.24,48.35506,71.2541,0,0,0,0,100,0),
(@PATH,10,3321.963,47.37666,71.00128,0,0,0,0,100,0),
(@PATH,11,3322.048,47.26694,71.02554,0,0,0,0,100,0),
(@PATH,12,3323.298,45.51694,70.77554,0,0,0,0,100,0),
(@PATH,13,3324.798,42.01694,70.02554,0,0,0,0,100,0),
(@PATH,14,3326.298,39.51694,69.52554,0,0,0,0,100,0);
-- 4. foxus warlock emotes
DELETE FROM `creature_addon` WHERE `guid` IN (114036, 114035, 114040, 114039, 114041, 114002, 114005, 114003, 113973, 113995, 114000, 113996, 113998, 114038, 113999);
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(114036,0,0,0,1,69, ''),
(114035,0,0,0,1,69, ''),
(114040,0,0,0,1,69, ''),
(114039,0,0,0,1,69, ''),
(114041,0,0,0,1,69, ''),
(114002,0,0,0,1,69, ''),
(114005,0,0,0,1,69, ''),
(114003,0,0,0,1,69, ''),
(113973,0,0,0,1,69, ''),
(113995,0,0,0,1,69, ''),
(114000,0,0,0,1,69, ''),
(113996,0,0,0,1,69, ''),
(113998,0,0,0,1,69, ''),
(114038,0,0,0,1,69, ''),
(113999,0,0,0,1,69, '');
-- 5. mage hunter emotes
DELETE FROM `creature_addon` WHERE `guid` IN (111759, 111757, 111756, 111758, 111760, 111761, 111802, 111801, 111800);
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(111759,0,0,0,1,27, ''),
(111757,0,0,0,1,27, ''),
(111756,0,0,0,1,27, ''),
(111758,0,0,0,1,27, ''),
(111760,0,0,0,1,27, ''),
(111761,0,0,0,1,27, ''),
(111802,0,0,0,1,27, ''),
(111801,0,0,0,1,27, ''),
(111800,0,0,0,1,27, '');
-- 6. Beefwps
SET @NPC := 111043;
SET @PATH := @NPC * 10;
UPDATE `creature` SET `spawndist`=0,`MovementType`=2,`position_x`=3357.819,`position_y`=518.5552,`position_z`=78.31688 WHERE `guid`=@NPC;
UPDATE `creature` SET `spawndist`=0,`MovementType`=0,`position_x`=3357.819,`position_y`=518.5552,`position_z`=78.31688 WHERE `guid`=111211;
DELETE FROM `creature_addon` WHERE `guid`=@NPC;
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES (@NPC,@PATH,0,0,1,0, '');
DELETE FROM `waypoint_data` WHERE `id`=@PATH;
INSERT INTO `waypoint_data` (`id`,`point`,`position_x`,`position_y`,`position_z`,`orientation`,`delay`,`move_type`,`action`,`action_chance`,`wpguid`) VALUES
(@PATH,1,3357.819,518.5552,78.31688,0,0,0,0,100,0),
(@PATH,2,3364.319,524.5552,78.81688,0,0,0,0,100,0),
(@PATH,3,3368.569,528.3052,79.31688,0,0,0,0,100,0),
(@PATH,4,3375.445,534.399,79.33154,0,0,0,0,100,0),
(@PATH,5,3391.695,551.649,78.83154,0,0,0,0,100,0),
(@PATH,6,3395.945,555.899,78.08154,0,0,0,0,100,0),
(@PATH,7,3406.195,566.649,77.58154,0,0,0,0,100,0),
(@PATH,8,3407.308,568.47,77.32245,0,0,0,0,100,0),
(@PATH,9,3395.808,585.72,78.07245,0,0,0,0,100,0),
(@PATH,10,3393.808,588.97,78.32245,0,0,0,0,100,0),
(@PATH,11,3388.808,596.47,79.07245,0,0,0,0,100,0),
(@PATH,12,3384.558,603.22,79.57245,0,0,0,0,100,0),
(@PATH,13,3384.328,603.3331,79.72012,0,0,0,0,100,0),
(@PATH,14,3383.578,604.5831,79.97012,0,0,0,0,100,0),
(@PATH,15,3372.078,617.0831,80.47012,0,0,0,0,100,0),
(@PATH,16,3369.578,619.8331,80.97012,0,0,0,0,100,0),
(@PATH,17,3354.531,636.454,81.09949,0,0,0,0,100,0),
(@PATH,18,3352.031,648.204,81.84949,0,0,0,0,100,0),
(@PATH,19,3351.031,654.954,82.09949,0,0,0,0,100,0),
(@PATH,20,3347.781,671.454,82.84949,0,0,0,0,100,0),
(@PATH,21,3347.66,671.6125,82.84419,0,0,0,0,100,0),
(@PATH,22,3348.41,668.6125,82.09419,0,0,0,0,100,0),
(@PATH,23,3350.16,658.8625,82.59419,0,0,0,0,100,0),
(@PATH,24,3351.16,653.1125,82.09419,0,0,0,0,100,0),
(@PATH,25,3352.91,644.3625,81.59419,0,0,0,0,100,0),
(@PATH,26,3354.698,636.1382,80.88446,0,0,0,0,100,0),
(@PATH,27,3371.948,617.3882,80.38446,0,0,0,0,100,0),
(@PATH,28,3374.698,614.3882,79.88446,0,0,0,0,100,0),
(@PATH,29,3383.664,604.2737,79.74067,0,0,0,0,100,0),
(@PATH,30,3387.164,599.2737,79.24067,0,0,0,0,100,0),
(@PATH,31,3393.164,590.0237,78.49067,0,0,0,0,100,0),
(@PATH,32,3395.664,586.0237,77.99067,0,0,0,0,100,0),
(@PATH,33,3398.414,582.0237,77.49067,0,0,0,0,100,0),
(@PATH,34,3407.336,568.2035,77.34898,0,0,0,0,100,0),
(@PATH,35,3404.086,564.4535,78.09898,0,0,0,0,100,0),
(@PATH,36,3394.336,554.4535,78.59898,0,0,0,0,100,0),
(@PATH,37,3389.836,549.4535,79.09898,0,0,0,0,100,0),
(@PATH,38,3375.294,534.2694,79.25139,0,0,0,0,100,0),
(@PATH,39,3365.794,525.7694,78.75139,0,0,0,0,100,0),
(@PATH,40,3361.294,521.7694,78.25139,0,0,0,0,100,0),
(@PATH,41,3357.338,518.4061,78.19955,0,0,0,0,100,0),
(@PATH,42,3353.588,514.9061,78.94955,0,0,0,0,100,0),
(@PATH,43,3349.838,511.6561,79.44955,0,0,0,0,100,0),
(@PATH,44,3346.088,508.4061,80.19955,0,0,0,0,100,0),
(@PATH,45,3343.338,505.9061,80.69955,0,0,0,0,100,0),
(@PATH,46,3336.588,500.1561,81.19955,0,0,0,0,100,0),
(@PATH,47,3331.361,495.4106,81.15448,0,0,0,0,100,0),
(@PATH,48,3311.611,470.6606,80.40448,0,0,0,0,100,0),
(@PATH,49,3308.507,466.9263,79.84391,0,0,0,0,100,0),
(@PATH,50,3307.007,463.1763,79.34391,0,0,0,0,100,0),
(@PATH,51,3304.757,457.6763,78.59391,0,0,0,0,100,0),
(@PATH,52,3303.257,453.4263,78.09391,0,0,0,0,100,0),
(@PATH,53,3300.507,446.9263,77.59391,0,0,0,0,100,0),
(@PATH,54,3298.613,441.5379,76.93367,0,0,0,0,100,0),
(@PATH,55,3303.113,424.2879,77.43367,0,0,0,0,100,0),
(@PATH,56,3306.613,411.0379,76.93367,0,0,0,0,100,0),
(@PATH,57,3307.363,408.0379,76.18367,0,0,0,0,100,0),
(@PATH,58,3308.363,404.2879,75.93367,0,0,0,0,100,0),
(@PATH,59,3307.172,408.4494,76.61504,0,0,0,0,100,0),
(@PATH,60,3306.172,412.1994,77.36504,0,0,0,0,100,0),
(@PATH,61,3298.596,441.697,77.28619,0,0,0,0,100,0),
(@PATH,62,3301.596,449.197,77.78619,0,0,0,0,100,0),
(@PATH,63,3303.596,454.447,78.28619,0,0,0,0,100,0),
(@PATH,64,3305.346,459.197,78.78619,0,0,0,0,100,0),
(@PATH,65,3307.346,463.947,79.53619,0,0,0,0,100,0),
(@PATH,66,3308.805,467.3031,80.26054,0,0,0,0,100,0),
(@PATH,67,3312.055,471.0531,80.76054,0,0,0,0,100,0),
(@PATH,68,3318.305,479.0531,81.26054,0,0,0,0,100,0);
DELETE FROM `creature_formations` WHERE `leaderGUID`=111043;
INSERT INTO `creature_formations` (`leaderGUID`, `memberGUID`, `dist`, `angle`, `groupAI`, `point_1`, `point_2`) VALUES
(111043, 111043, 0, 0, 2, 0, 0),
(111043, 111211, 7, 0, 0, 0, 0);
-- 7. casting emotes gnomes
DELETE FROM `creature_addon` WHERE `guid` IN (109040, 109039);
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(109040,0,0,0,1,51, ''),
(109039,0,0,0,1,51, '');
-- 8. Attackemotes for hunter + warlocks (all 3 caves)
DELETE FROM `creature_addon` WHERE `guid` IN (111789, 111827, 114030, 111796, 111811, 111813, 114029, 111834, 114069, 111812, 114049, 111750, 113966, 111768, 111766, 114010, 111770, 114008, 111769, 111767, 114009, 111734, 111779, 114020, 111776, 111774, 111775, 111747, 111754, 111755, 111753, 113951, 113968, 113969, 113964, 111717, 113967, 111735, 113970, 111728, 113940, 113965, 114006, 111727, 111743, 111763, 111764);
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES
(111789, 0,0,0,1,27, ''),
(111827, 0,0,0,1,27, ''),
(114030, 0,0,0,1,27, ''),
(111796, 0,0,0,1,27, ''),
(111811, 0,0,0,1,27, ''),
(111813, 0,0,0,1,27, ''),
(114029, 0,0,0,1,27, ''),
(111834, 0,0,0,1,27, ''),
(114069, 0,0,0,1,27, ''),
(111812, 0,0,0,1,27, ''),
(114049, 0,0,0,1,27, ''),
(111750, 0,0,0,1,27, ''),
(113966, 0,0,0,1,27, ''),
(111768, 0,0,0,1,27, ''),
(111766, 0,0,0,1,27, ''),
(114010, 0,0,0,1,27, ''),
(111770, 0,0,0,1,27, ''),
(114008, 0,0,0,1,27, ''),
(111769, 0,0,0,1,27, ''),
(111767, 0,0,0,1,27, ''),
(114009, 0,0,0,1,27, ''),
(111734, 0,0,0,1,27, ''),
(111779, 0,0,0,1,27, ''),
(114020, 0,0,0,1,27, ''),
(111776, 0,0,0,1,27, ''),
(111774, 0,0,0,1,27, ''),
(111775, 0,0,0,1,27, ''),
(111747, 0,0,0,1,27, ''),
(111754, 0,0,0,1,27, ''),
(111755, 0,0,0,1,27, ''),
(111753, 0,0,0,1,27, ''),
(113951, 0,0,0,1,27, ''),
(113968, 0,0,0,1,27, ''),
(113969, 0,0,0,1,27, ''),
(113964, 0,0,0,1,27, ''),
(111717, 0,0,0,1,27, ''),
(113967, 0,0,0,1,27, ''),
(111735, 0,0,0,1,27, ''),
(113970, 0,0,0,1,27, ''),
(111728, 0,0,0,1,27, ''),
(113940, 0,0,0,1,27, ''),
(113965, 0,0,0,1,27, ''),
(114006, 0,0,0,1,27, ''),
(111727, 0,0,0,1,27, ''),
(111743, 0,0,0,1,27, ''),
(111763, 0,0,0,1,27, ''),
(111764,0,0,0,1,27, '');
-- 9. Moa'ki Warrior
SET @NPC := 99801;
SET @PATH := @NPC * 10;
UPDATE `creature` SET `spawndist`=0,`MovementType`=2,`position_x`=2942.45,`position_y`=874.4968,`position_z`=35.30196 WHERE `guid`=@NPC;
UPDATE `creature` SET `spawndist`=0,`MovementType`=0,`position_x`=2942.45,`position_y`=874.4968,`position_z`=35.30196 WHERE `guid`=99802;
DELETE FROM `creature_addon` WHERE `guid`=@NPC;
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES (@NPC,@PATH,0,0,1,0, '');
DELETE FROM `waypoint_data` WHERE `id`=@PATH;
INSERT INTO `waypoint_data` (`id`,`point`,`position_x`,`position_y`,`position_z`,`orientation`,`delay`,`move_type`,`action`,`action_chance`,`wpguid`) VALUES
(@PATH,1,2942.45,874.4968,35.30196,0,0,0,0,100,0),
(@PATH,2,2940.95,874.7468,35.05196,0,0,0,0,100,0),
(@PATH,3,2938.95,874.4968,34.55196,0,0,0,0,100,0),
(@PATH,4,2935.95,873.9968,33.55196,0,0,0,0,100,0),
(@PATH,5,2934.2,873.7468,33.05196,0,0,0,0,100,0),
(@PATH,6,2932.45,873.4968,32.55196,0,0,0,0,100,0),
(@PATH,7,2929.45,873.2468,31.80196,0,0,0,0,100,0),
(@PATH,8,2926.45,872.9968,31.05196,0,0,0,0,100,0),
(@PATH,9,2923.45,872.4968,30.05196,0,0,0,0,100,0),
(@PATH,10,2923.197,872.4724,29.89659,0,0,0,0,100,0),
(@PATH,11,2921.197,872.2224,29.39659,0,0,0,0,100,0),
(@PATH,12,2919.197,871.7224,28.89659,0,0,0,0,100,0),
(@PATH,13,2916.447,870.9724,28.14659,0,0,0,0,100,0),
(@PATH,14,2914.447,870.4724,27.39659,0,0,0,0,100,0),
(@PATH,15,2910.697,869.9724,26.89659,0,0,0,0,100,0),
(@PATH,16,2907.697,869.2224,26.14659,0,0,0,0,100,0),
(@PATH,17,2904.947,868.4724,25.64659,0,0,0,0,100,0),
(@PATH,18,2902.995,868.2098,24.81467,0,0,0,0,100,0),
(@PATH,19,2899.995,868.9598,24.31467,0,0,0,0,100,0),
(@PATH,20,2896.245,869.9598,23.56467,0,0,0,0,100,0),
(@PATH,21,2893.495,870.7098,23.06467,0,0,0,0,100,0),
(@PATH,22,2890.495,871.4598,22.56467,0,0,0,0,100,0),
(@PATH,23,2885.745,872.7098,21.81467,0,0,0,0,100,0),
(@PATH,24,2885.609,872.7776,21.46217,0,0,0,0,100,0),
(@PATH,25,2884.109,873.2776,21.21217,0,0,0,0,100,0),
(@PATH,26,2880.109,873.2776,20.71217,0,0,0,0,100,0),
(@PATH,27,2873.359,873.2776,20.21217,0,0,0,0,100,0),
(@PATH,28,2868.175,873.5178,19.47064,0,0,0,0,100,0),
(@PATH,29,2860.175,880.7678,18.97064,0,0,0,0,100,0),
(@PATH,30,2857.271,883.4542,18.24871,0,0,0,0,100,0),
(@PATH,31,2851.021,886.2042,17.74871,0,0,0,0,100,0),
(@PATH,32,2843.771,889.4542,17.24871,0,0,0,0,100,0),
(@PATH,33,2843.393,889.6986,17.05721,0,0,0,0,100,0),
(@PATH,34,2842.643,889.9486,17.05721,0,0,0,0,100,0),
(@PATH,35,2836.893,892.1986,16.30721,0,0,0,0,100,0),
(@PATH,36,2829.259,895.6682,16.03611,0,0,0,0,100,0),
(@PATH,37,2826.259,899.6682,16.78611,0,0,0,0,100,0),
(@PATH,38,2824.759,901.9182,17.28611,0,0,0,0,100,0),
(@PATH,39,2823.009,904.1682,18.03611,0,0,0,0,100,0),
(@PATH,40,2820.759,907.4182,18.78611,0,0,0,0,100,0),
(@PATH,41,2818.548,910.2606,19.6723,0,0,0,0,100,0),
(@PATH,42,2815.048,912.5106,20.1723,0,0,0,0,100,0),
(@PATH,43,2811.798,914.5106,20.4223,0,0,0,0,100,0),
(@PATH,44,2807.798,917.0106,21.1723,0,0,0,0,100,0),
(@PATH,45,2804.548,919.2606,21.9223,0,0,0,0,100,0),
(@PATH,46,2804.113,919.4464,22.19062,0,0,0,0,100,0),
(@PATH,47,2802.863,920.4464,22.19062,0,0,0,0,100,0),
(@PATH,48,2802.113,936.1964,22.69062,0,0,0,0,100,0),
(@PATH,49,2801.614,942.2058,22.90605,0,0,0,0,100,0),
(@PATH,50,2794.46,955.9167,22.82833,0,0,0,0,100,0),
(@PATH,51,2789.868,969.0771,22.71787,0,0,0,0,100,0),
(@PATH,52,2789.86,968.7522,22.44791,0,0,0,0,100,0),
(@PATH,53,2790.052,968.7579,22.57249,0,0,0,0,100,0),
(@PATH,54,2794.692,955.4985,22.95527,0,0,0,0,100,0),
(@PATH,55,2801.604,942.0818,22.84189,0,0,0,0,100,0),
(@PATH,56,2802.354,929.3318,22.34189,0,0,0,0,100,0),
(@PATH,57,2803.029,920.1268,22.10619,0,0,0,0,100,0),
(@PATH,58,2807.279,917.3768,21.60619,0,0,0,0,100,0),
(@PATH,59,2809.779,916.1268,20.85619,0,0,0,0,100,0),
(@PATH,60,2813.779,913.3768,20.35619,0,0,0,0,100,0),
(@PATH,61,2817.029,911.3768,19.85619,0,0,0,0,100,0),
(@PATH,62,2817.245,910.9927,19.40564,0,0,0,0,100,0),
(@PATH,63,2818.745,909.9927,19.40564,0,0,0,0,100,0),
(@PATH,64,2820.995,906.7427,18.40564,0,0,0,0,100,0),
(@PATH,65,2823.245,903.7427,17.65564,0,0,0,0,100,0),
(@PATH,66,2825.495,900.7427,17.15564,0,0,0,0,100,0),
(@PATH,67,2827.245,898.2427,16.65564,0,0,0,0,100,0),
(@PATH,68,2827.63,897.9916,16.59999,0,0,0,0,100,0),
(@PATH,69,2829.38,895.2416,16.09999,0,0,0,0,100,0),
(@PATH,70,2839.38,891.2416,16.59999,0,0,0,0,100,0),
(@PATH,71,2842.658,889.7286,17.27651,0,0,0,0,100,0),
(@PATH,72,2849.908,886.7286,17.52651,0,0,0,0,100,0),
(@PATH,73,2855.408,884.2286,18.27651,0,0,0,0,100,0),
(@PATH,74,2857.304,883.3358,18.64834,0,0,0,0,100,0),
(@PATH,75,2861.054,879.8358,18.89834,0,0,0,0,100,0),
(@PATH,76,2868.077,873.4034,19.59505,0,0,0,0,100,0),
(@PATH,77,2874.077,873.4034,20.09505,0,0,0,0,100,0),
(@PATH,78,2879.827,873.4034,20.59505,0,0,0,0,100,0),
(@PATH,79,2884.046,873.29,21.49246,0,0,0,0,100,0),
(@PATH,80,2888.046,872.04,22.24246,0,0,0,0,100,0),
(@PATH,81,2892.546,870.79,22.74246,0,0,0,0,100,0),
(@PATH,82,2895.546,870.29,23.24246,0,0,0,0,100,0),
(@PATH,83,2898.296,869.54,23.99246,0,0,0,0,100,0),
(@PATH,84,2901.296,868.54,24.49246,0,0,0,0,100,0),
(@PATH,85,2901.368,868.5389,24.78852,0,0,0,0,100,0),
(@PATH,86,2903.118,868.0389,25.03852,0,0,0,0,100,0),
(@PATH,87,2906.118,868.7889,25.53852,0,0,0,0,100,0),
(@PATH,88,2908.868,869.5389,26.28852,0,0,0,0,100,0),
(@PATH,89,2911.618,870.2889,26.78852,0,0,0,0,100,0),
(@PATH,90,2915.618,870.7889,27.53852,0,0,0,0,100,0),
(@PATH,91,2917.618,871.2889,28.28852,0,0,0,0,100,0),
(@PATH,92,2920.368,872.0389,29.03852,0,0,0,0,100,0),
(@PATH,93,2920.589,872.1874,29.30408,0,0,0,0,100,0),
(@PATH,94,2921.339,872.4374,29.55408,0,0,0,0,100,0),
(@PATH,95,2924.339,872.6874,30.55408,0,0,0,0,100,0),
(@PATH,96,2927.339,873.1874,31.30408,0,0,0,0,100,0),
(@PATH,97,2930.089,873.1874,31.80408,0,0,0,0,100,0),
(@PATH,98,2933.089,873.6874,32.80408,0,0,0,0,100,0),
(@PATH,99,2935.089,873.9374,33.30408,0,0,0,0,100,0),
(@PATH,100,2937.089,874.1874,34.05408,0,0,0,0,100,0),
(@PATH,101,2940.089,874.6874,34.80408,0,0,0,0,100,0),
(@PATH,102,2940.357,874.6572,35.2282,0,0,0,0,100,0),
(@PATH,103,2941.357,874.6572,35.4782,0,0,0,0,100,0),
(@PATH,104,2944.357,874.4072,36.2282,0,0,0,0,100,0),
(@PATH,105,2947.357,874.1572,36.7282,0,0,0,0,100,0),
(@PATH,106,2949.107,873.9072,37.4782,0,0,0,0,100,0),
(@PATH,107,2953.107,873.9072,38.2282,0,0,0,0,100,0),
(@PATH,108,2955.857,873.6572,38.9782,0,0,0,0,100,0),
(@PATH,109,2953.459,873.7681,38.4597,0,0,0,0,100,0);
DELETE FROM `creature_formations` WHERE `leaderGUID`=99801;
INSERT INTO `creature_formations` (`leaderGUID`, `memberGUID`, `dist`, `angle`, `groupAI`, `point_1`, `point_2`) VALUES
(99801, 99801, 0, 0, 2, 0, 0),
(99801, 99802, 3, 90, 2, 0, 0);
UPDATE `smart_scripts` SET `action_param1`=1 WHERE `entryorguid`=27178 AND `source_type`=0 AND `id`=0 AND `link`=1;
-- 10. Moa'ki Warrior
SET @NPC := 99815;
SET @PATH := @NPC * 10;
UPDATE `creature` SET `spawndist`=0,`MovementType`=2,`position_x`=2734.04,`position_y`=908.0725,`position_z`=3.249194 WHERE `guid`=@NPC;
UPDATE `creature` SET `spawndist`=0,`MovementType`=0,`position_x`=2734.04,`position_y`=908.0725,`position_z`=3.249194 WHERE `guid`=99814;
DELETE FROM `creature_addon` WHERE `guid`=@NPC;
INSERT INTO `creature_addon` (`guid`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES (@NPC,@PATH,0,0,1,0, '');
DELETE FROM `waypoint_data` WHERE `id`=@PATH;
INSERT INTO `waypoint_data` (`id`,`point`,`position_x`,`position_y`,`position_z`,`orientation`,`delay`,`move_type`,`action`,`action_chance`,`wpguid`) VALUES
(@PATH,1,2734.04,908.0725,3.249194,0,0,0,0,100,0),
(@PATH,2,2736.54,905.0725,3.749194,0,0,0,0,100,0),
(@PATH,3,2739.04,901.8225,4.249194,0,0,0,0,100,0),
(@PATH,4,2740.54,899.8225,4.749194,0,0,0,0,100,0),
(@PATH,5,2743.79,895.8225,5.249194,0,0,0,0,100,0),
(@PATH,6,2746.789,892.0921,5.316426,0,0,0,0,100,0),
(@PATH,7,2765.288,879.248,5.514341,0,0,0,0,100,0),
(@PATH,8,2788.071,876.0192,5.926539,0,0,0,0,100,0),
(@PATH,9,2796.821,876.0192,6.676539,0,0,0,0,100,0),
(@PATH,10,2802.821,876.0192,6.926539,0,0,0,0,100,0),
(@PATH,11,2806.821,875.7692,7.676539,0,0,0,0,100,0),
(@PATH,12,2806.909,875.7591,7.908364,0,0,0,0,100,0),
(@PATH,13,2807.659,875.7591,8.158364,0,0,0,0,100,0),
(@PATH,14,2810.159,877.7591,8.658364,0,0,0,0,100,0),
(@PATH,15,2812.159,879.5091,9.158364,0,0,0,0,100,0),
(@PATH,16,2813.909,880.5091,9.908364,0,0,0,0,100,0),
(@PATH,17,2816.159,882.2591,10.65836,0,0,0,0,100,0),
(@PATH,18,2817.659,883.5091,11.40836,0,0,0,0,100,0),
(@PATH,19,2816.375,882.6917,10.97033,0,0,0,0,100,0),
(@PATH,20,2818.125,883.9417,11.72033,0,0,0,0,100,0),
(@PATH,21,2818.875,884.6917,11.72033,0,0,0,0,100,0),
(@PATH,22,2820.375,885.9417,12.72033,0,0,0,0,100,0),
(@PATH,23,2821.375,887.4417,12.97033,0,0,0,0,100,0),
(@PATH,24,2822.875,888.6917,13.72033,0,0,0,0,100,0),
(@PATH,25,2824.125,890.1917,14.47033,0,0,0,0,100,0),
(@PATH,26,2825.375,891.6917,15.22033,0,0,0,0,100,0),
(@PATH,27,2824.66,890.6411,14.79578,0,0,0,0,100,0),
(@PATH,28,2823.16,889.3911,14.04578,0,0,0,0,100,0),
(@PATH,29,2821.41,887.3911,13.29578,0,0,0,0,100,0),
(@PATH,30,2818.638,884.2707,11.69823,0,0,0,0,100,0),
(@PATH,31,2816.388,882.5207,10.69823,0,0,0,0,100,0),
(@PATH,32,2813.888,880.7707,9.948226,0,0,0,0,100,0),
(@PATH,33,2812.638,879.5207,9.448226,0,0,0,0,100,0),
(@PATH,34,2810.388,877.7707,8.698226,0,0,0,0,100,0),
(@PATH,35,2807.556,875.8849,7.826558,0,0,0,0,100,0),
(@PATH,36,2803.556,876.1349,7.076558,0,0,0,0,100,0),
(@PATH,37,2798.556,876.1349,6.826558,0,0,0,0,100,0),
(@PATH,38,2790.806,876.3849,6.076558,0,0,0,0,100,0),
(@PATH,39,2790.671,876.3419,5.86481,0,0,0,0,100,0),
(@PATH,40,2787.671,876.3419,5.86481,0,0,0,0,100,0),
(@PATH,41,2764.954,879.5082,5.60566,0,0,0,0,100,0),
(@PATH,42,2746.52,892.532,5.507929,0,0,0,0,100,0),
(@PATH,43,2741.77,898.782,4.757929,0,0,0,0,100,0),
(@PATH,44,2739.27,901.532,4.257929,0,0,0,0,100,0),
(@PATH,45,2736.77,904.782,3.757929,0,0,0,0,100,0),
(@PATH,46,2734.27,907.782,3.257929,0,0,0,0,100,0),
(@PATH,47,2733.933,908.0688,3.006025,0,0,0,0,100,0),
(@PATH,48,2733.683,908.3188,3.006025,0,0,0,0,100,0),
(@PATH,49,2732.933,911.3188,2.256025,0,0,0,0,100,0),
(@PATH,50,2732.183,914.3188,1.756025,0,0,0,0,100,0),
(@PATH,51,2731.183,918.8188,1.256025,0,0,0,0,100,0),
(@PATH,52,2728.75,928.4617,0.6681505,0,0,0,0,100,0),
(@PATH,53,2731.75,918.9617,1.418151,0,0,0,0,100,0),
(@PATH,54,2732.5,915.2117,1.668151,0,0,0,0,100,0);
DELETE FROM `creature_formations` WHERE `leaderGUID`=99815;
INSERT INTO `creature_formations` (`leaderGUID`, `memberGUID`, `dist`, `angle`, `groupAI`, `point_1`, `point_2`) VALUES
(99815, 99815, 0, 0, 2, 0, 0),
(99815, 99814, 3, 90, 2, 0, 0);
| amsjunior1/TrinityCore | sql/updates/world/2015_07_19_01_world_2015_07_15_01.sql | SQL | gpl-2.0 | 20,040 |
// MESSAGE RADIO_STATUS PACKING
#define MAVLINK_MSG_ID_RADIO_STATUS 109
typedef struct __mavlink_radio_status_t
{
uint16_t rxerrors; ///< Receive errors
uint16_t fixed; ///< Count of error corrected packets
uint8_t rssi; ///< Local signal strength
uint8_t remrssi; ///< Remote signal strength
uint8_t txbuf; ///< Remaining free buffer space in percent.
uint8_t noise; ///< Background noise level
uint8_t remnoise; ///< Remote background noise level
} mavlink_radio_status_t;
#define MAVLINK_MSG_ID_RADIO_STATUS_LEN 9
#define MAVLINK_MSG_ID_109_LEN 9
#define MAVLINK_MSG_ID_RADIO_STATUS_CRC 185
#define MAVLINK_MSG_ID_109_CRC 185
#define MAVLINK_MESSAGE_INFO_RADIO_STATUS { \
"RADIO_STATUS", \
7, \
{ { "rxerrors", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_radio_status_t, rxerrors) }, \
{ "fixed", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_radio_status_t, fixed) }, \
{ "rssi", NULL, MAVLINK_TYPE_UINT8_T, 0, 4, offsetof(mavlink_radio_status_t, rssi) }, \
{ "remrssi", NULL, MAVLINK_TYPE_UINT8_T, 0, 5, offsetof(mavlink_radio_status_t, remrssi) }, \
{ "txbuf", NULL, MAVLINK_TYPE_UINT8_T, 0, 6, offsetof(mavlink_radio_status_t, txbuf) }, \
{ "noise", NULL, MAVLINK_TYPE_UINT8_T, 0, 7, offsetof(mavlink_radio_status_t, noise) }, \
{ "remnoise", NULL, MAVLINK_TYPE_UINT8_T, 0, 8, offsetof(mavlink_radio_status_t, remnoise) }, \
} \
}
/**
* @brief Pack a radio_status message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param rssi Local signal strength
* @param remrssi Remote signal strength
* @param txbuf Remaining free buffer space in percent.
* @param noise Background noise level
* @param remnoise Remote background noise level
* @param rxerrors Receive errors
* @param fixed Count of error corrected packets
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_radio_status_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint8_t rssi, uint8_t remrssi, uint8_t txbuf, uint8_t noise, uint8_t remnoise, uint16_t rxerrors, uint16_t fixed)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_RADIO_STATUS_LEN];
_mav_put_uint16_t(buf, 0, rxerrors);
_mav_put_uint16_t(buf, 2, fixed);
_mav_put_uint8_t(buf, 4, rssi);
_mav_put_uint8_t(buf, 5, remrssi);
_mav_put_uint8_t(buf, 6, txbuf);
_mav_put_uint8_t(buf, 7, noise);
_mav_put_uint8_t(buf, 8, remnoise);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#else
mavlink_radio_status_t packet;
packet.rxerrors = rxerrors;
packet.fixed = fixed;
packet.rssi = rssi;
packet.remrssi = remrssi;
packet.txbuf = txbuf;
packet.noise = noise;
packet.remnoise = remnoise;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_RADIO_STATUS;
#if MAVLINK_CRC_EXTRA
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
}
/**
* @brief Pack a radio_status message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param rssi Local signal strength
* @param remrssi Remote signal strength
* @param txbuf Remaining free buffer space in percent.
* @param noise Background noise level
* @param remnoise Remote background noise level
* @param rxerrors Receive errors
* @param fixed Count of error corrected packets
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_radio_status_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint8_t rssi,uint8_t remrssi,uint8_t txbuf,uint8_t noise,uint8_t remnoise,uint16_t rxerrors,uint16_t fixed)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_RADIO_STATUS_LEN];
_mav_put_uint16_t(buf, 0, rxerrors);
_mav_put_uint16_t(buf, 2, fixed);
_mav_put_uint8_t(buf, 4, rssi);
_mav_put_uint8_t(buf, 5, remrssi);
_mav_put_uint8_t(buf, 6, txbuf);
_mav_put_uint8_t(buf, 7, noise);
_mav_put_uint8_t(buf, 8, remnoise);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#else
mavlink_radio_status_t packet;
packet.rxerrors = rxerrors;
packet.fixed = fixed;
packet.rssi = rssi;
packet.remrssi = remrssi;
packet.txbuf = txbuf;
packet.noise = noise;
packet.remnoise = remnoise;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_RADIO_STATUS;
#if MAVLINK_CRC_EXTRA
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
}
/**
* @brief Encode a radio_status struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param radio_status C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_radio_status_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_radio_status_t* radio_status)
{
return mavlink_msg_radio_status_pack(system_id, component_id, msg, radio_status->rssi, radio_status->remrssi, radio_status->txbuf, radio_status->noise, radio_status->remnoise, radio_status->rxerrors, radio_status->fixed);
}
/**
* @brief Encode a radio_status struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param radio_status C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_radio_status_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_radio_status_t* radio_status)
{
return mavlink_msg_radio_status_pack_chan(system_id, component_id, chan, msg, radio_status->rssi, radio_status->remrssi, radio_status->txbuf, radio_status->noise, radio_status->remnoise, radio_status->rxerrors, radio_status->fixed);
}
/**
* @brief Send a radio_status message
* @param chan MAVLink channel to send the message
*
* @param rssi Local signal strength
* @param remrssi Remote signal strength
* @param txbuf Remaining free buffer space in percent.
* @param noise Background noise level
* @param remnoise Remote background noise level
* @param rxerrors Receive errors
* @param fixed Count of error corrected packets
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_radio_status_send(mavlink_channel_t chan, uint8_t rssi, uint8_t remrssi, uint8_t txbuf, uint8_t noise, uint8_t remnoise, uint16_t rxerrors, uint16_t fixed)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_RADIO_STATUS_LEN];
_mav_put_uint16_t(buf, 0, rxerrors);
_mav_put_uint16_t(buf, 2, fixed);
_mav_put_uint8_t(buf, 4, rssi);
_mav_put_uint8_t(buf, 5, remrssi);
_mav_put_uint8_t(buf, 6, txbuf);
_mav_put_uint8_t(buf, 7, noise);
_mav_put_uint8_t(buf, 8, remnoise);
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
#else
mavlink_radio_status_t packet;
packet.rxerrors = rxerrors;
packet.fixed = fixed;
packet.rssi = rssi;
packet.remrssi = remrssi;
packet.txbuf = txbuf;
packet.noise = noise;
packet.remnoise = remnoise;
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, (const char *)&packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, (const char *)&packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
#endif
}
#if MAVLINK_MSG_ID_RADIO_STATUS_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_radio_status_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint8_t rssi, uint8_t remrssi, uint8_t txbuf, uint8_t noise, uint8_t remnoise, uint16_t rxerrors, uint16_t fixed)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint16_t(buf, 0, rxerrors);
_mav_put_uint16_t(buf, 2, fixed);
_mav_put_uint8_t(buf, 4, rssi);
_mav_put_uint8_t(buf, 5, remrssi);
_mav_put_uint8_t(buf, 6, txbuf);
_mav_put_uint8_t(buf, 7, noise);
_mav_put_uint8_t(buf, 8, remnoise);
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, buf, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
#else
mavlink_radio_status_t *packet = (mavlink_radio_status_t *)msgbuf;
packet->rxerrors = rxerrors;
packet->fixed = fixed;
packet->rssi = rssi;
packet->remrssi = remrssi;
packet->txbuf = txbuf;
packet->noise = noise;
packet->remnoise = remnoise;
#if MAVLINK_CRC_EXTRA
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, (const char *)packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN, MAVLINK_MSG_ID_RADIO_STATUS_CRC);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_RADIO_STATUS, (const char *)packet, MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
#endif
}
#endif
#endif
// MESSAGE RADIO_STATUS UNPACKING
/**
* @brief Get field rssi from radio_status message
*
* @return Local signal strength
*/
static inline uint8_t mavlink_msg_radio_status_get_rssi(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 4);
}
/**
* @brief Get field remrssi from radio_status message
*
* @return Remote signal strength
*/
static inline uint8_t mavlink_msg_radio_status_get_remrssi(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 5);
}
/**
* @brief Get field txbuf from radio_status message
*
* @return Remaining free buffer space in percent.
*/
static inline uint8_t mavlink_msg_radio_status_get_txbuf(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 6);
}
/**
* @brief Get field noise from radio_status message
*
* @return Background noise level
*/
static inline uint8_t mavlink_msg_radio_status_get_noise(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 7);
}
/**
* @brief Get field remnoise from radio_status message
*
* @return Remote background noise level
*/
static inline uint8_t mavlink_msg_radio_status_get_remnoise(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 8);
}
/**
* @brief Get field rxerrors from radio_status message
*
* @return Receive errors
*/
static inline uint16_t mavlink_msg_radio_status_get_rxerrors(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 0);
}
/**
* @brief Get field fixed from radio_status message
*
* @return Count of error corrected packets
*/
static inline uint16_t mavlink_msg_radio_status_get_fixed(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 2);
}
/**
* @brief Decode a radio_status message into a struct
*
* @param msg The message to decode
* @param radio_status C-struct to decode the message contents into
*/
static inline void mavlink_msg_radio_status_decode(const mavlink_message_t* msg, mavlink_radio_status_t* radio_status)
{
#if MAVLINK_NEED_BYTE_SWAP
radio_status->rxerrors = mavlink_msg_radio_status_get_rxerrors(msg);
radio_status->fixed = mavlink_msg_radio_status_get_fixed(msg);
radio_status->rssi = mavlink_msg_radio_status_get_rssi(msg);
radio_status->remrssi = mavlink_msg_radio_status_get_remrssi(msg);
radio_status->txbuf = mavlink_msg_radio_status_get_txbuf(msg);
radio_status->noise = mavlink_msg_radio_status_get_noise(msg);
radio_status->remnoise = mavlink_msg_radio_status_get_remnoise(msg);
#else
memcpy(radio_status, _MAV_PAYLOAD(msg), MAVLINK_MSG_ID_RADIO_STATUS_LEN);
#endif
}
| CPB9/mcc | thirdparty/mavlink/mavlink/common/mavlink_msg_radio_status.h | C | mpl-2.0 | 12,984 |
/*
TwoWire.cpp - TWI/I2C library for Wiring & Arduino
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
*/
extern "C" {
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "twi.h"
}
#include "Wire.h"
// Initialize Class Variables //////////////////////////////////////////////////
uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;
uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;
uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);
// Constructors ////////////////////////////////////////////////////////////////
TwoWire::TwoWire()
{
}
// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
rxBufferIndex = 0;
rxBufferLength = 0;
txBufferIndex = 0;
txBufferLength = 0;
twi_init();
}
void TwoWire::begin(uint8_t address)
{
twi_setAddress(address);
twi_attachSlaveTxEvent(onRequestService);
twi_attachSlaveRxEvent(onReceiveService);
begin();
}
void TwoWire::begin(int address)
{
begin((uint8_t)address);
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, uint8_t sendStop)
{
// clamp to buffer length
if(quantity > BUFFER_LENGTH){
quantity = BUFFER_LENGTH;
}
// perform blocking read into buffer
uint8_t read = twi_readFrom(address, rxBuffer, quantity, sendStop);
// set rx buffer iterator vars
rxBufferIndex = 0;
rxBufferLength = read;
return read;
}
uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)true);
}
uint8_t TwoWire::requestFrom(int address, int quantity, int sendStop)
{
return requestFrom((uint8_t)address, (uint8_t)quantity, (uint8_t)sendStop);
}
void TwoWire::beginTransmission(uint8_t address)
{
// indicate that we are transmitting
transmitting = 1;
// set address of targeted slave
txAddress = address;
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
}
void TwoWire::beginTransmission(int address)
{
beginTransmission((uint8_t)address);
}
//
// Originally, 'endTransmission' was an f(void) function.
// It has been modified to take one parameter indicating
// whether or not a STOP should be performed on the bus.
// Calling endTransmission(false) allows a sketch to
// perform a repeated start.
//
// WARNING: Nothing in the library keeps track of whether
// the bus tenure has been properly ended with a STOP. It
// is very possible to leave the bus in a hung state if
// no call to endTransmission(true) is made. Some I2C
// devices will behave oddly if they do not see a STOP.
//
uint8_t TwoWire::endTransmission(uint8_t sendStop)
{
// transmit buffer (blocking)
int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1, sendStop);
// reset tx buffer iterator vars
txBufferIndex = 0;
txBufferLength = 0;
// indicate that we are done transmitting
transmitting = 0;
return ret;
}
// This provides backwards compatibility with the original
// definition, and expected behaviour, of endTransmission
//
uint8_t TwoWire::endTransmission(void)
{
return endTransmission(true);
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(uint8_t data)
{
if(transmitting){
// in master transmitter mode
// don't bother if buffer is full
if(txBufferLength >= BUFFER_LENGTH){
setWriteError();
return 0;
}
// put byte in tx buffer
txBuffer[txBufferIndex] = data;
++txBufferIndex;
// update amount in buffer
txBufferLength = txBufferIndex;
}else{
// in slave send mode
// reply to master
twi_transmit(&data, 1);
}
return 1;
}
// must be called in:
// slave tx event callback
// or after beginTransmission(address)
size_t TwoWire::write(const uint8_t *data, size_t quantity)
{
if(transmitting){
// in master transmitter mode
for(size_t i = 0; i < quantity; ++i){
write(data[i]);
}
}else{
// in slave send mode
// reply to master
twi_transmit(data, quantity);
}
return quantity;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::available(void)
{
return rxBufferLength - rxBufferIndex;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::read(void)
{
int value = -1;
// get each successive byte on each call
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
++rxBufferIndex;
}
return value;
}
// must be called in:
// slave rx event callback
// or after requestFrom(address, numBytes)
int TwoWire::peek(void)
{
int value = -1;
if(rxBufferIndex < rxBufferLength){
value = rxBuffer[rxBufferIndex];
}
return value;
}
void TwoWire::flush(void)
{
// XXX: to be implemented.
}
// behind the scenes function that is called when data is received
void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
{
// don't bother if user hasn't registered a callback
if(!user_onReceive){
return;
}
// don't bother if rx buffer is in use by a master requestFrom() op
// i know this drops data, but it allows for slight stupidity
// meaning, they may not have read all the master requestFrom() data yet
if(rxBufferIndex < rxBufferLength){
return;
}
// copy twi rx buffer into local read buffer
// this enables new reads to happen in parallel
for(uint8_t i = 0; i < numBytes; ++i){
rxBuffer[i] = inBytes[i];
}
// set rx iterator vars
rxBufferIndex = 0;
rxBufferLength = numBytes;
// alert user program
user_onReceive(numBytes);
}
// behind the scenes function that is called when data is requested
void TwoWire::onRequestService(void)
{
// don't bother if user hasn't registered a callback
if(!user_onRequest){
return;
}
// reset tx buffer iterator vars
// !!! this will kill any pending pre-master sendTo() activity
txBufferIndex = 0;
txBufferLength = 0;
// alert user program
user_onRequest();
}
// sets function called on slave write
void TwoWire::onReceive( void (*function)(int) )
{
user_onReceive = function;
}
// sets function called on slave read
void TwoWire::onRequest( void (*function)(void) )
{
user_onRequest = function;
}
// Preinstantiate Objects //////////////////////////////////////////////////////
TwoWire Wire = TwoWire();
| chcbaram/FPGA | zap-2.3.0-windows/papilio-zap-ide/hardware/arduino/avr/libraries/Wire/Wire.cpp | C++ | mit | 7,532 |
//! moment.js locale configuration
//! locale : belarusian (be)
//! author : Dmitry Demidov : https://github.com/demidov91
//! author: Praleska: http://praleska.pro/
//! Author : Menelion Elensúle : https://github.com/Oire
import moment from '../moment';
function plural(word, num) {
var forms = word.split('_');
return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]);
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
var format = {
'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',
'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',
'dd': 'дзень_дні_дзён',
'MM': 'месяц_месяцы_месяцаў',
'yy': 'год_гады_гадоў'
};
if (key === 'm') {
return withoutSuffix ? 'хвіліна' : 'хвіліну';
}
else if (key === 'h') {
return withoutSuffix ? 'гадзіна' : 'гадзіну';
}
else {
return number + ' ' + plural(format[key], +number);
}
}
function monthsCaseReplace(m, format) {
var months = {
'nominative': 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_'),
'accusative': 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_')
},
nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ?
'accusative' :
'nominative';
return months[nounCase][m.month()];
}
function weekdaysCaseReplace(m, format) {
var weekdays = {
'nominative': 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'),
'accusative': 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_')
},
nounCase = (/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/).test(format) ?
'accusative' :
'nominative';
return weekdays[nounCase][m.day()];
}
export default moment.defineLocale('be', {
months : monthsCaseReplace,
monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),
weekdays : weekdaysCaseReplace,
weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D MMMM YYYY г.',
LLL : 'D MMMM YYYY г., HH:mm',
LLLL : 'dddd, D MMMM YYYY г., HH:mm'
},
calendar : {
sameDay: '[Сёння ў] LT',
nextDay: '[Заўтра ў] LT',
lastDay: '[Учора ў] LT',
nextWeek: function () {
return '[У] dddd [ў] LT';
},
lastWeek: function () {
switch (this.day()) {
case 0:
case 3:
case 5:
case 6:
return '[У мінулую] dddd [ў] LT';
case 1:
case 2:
case 4:
return '[У мінулы] dddd [ў] LT';
}
},
sameElse: 'L'
},
relativeTime : {
future : 'праз %s',
past : '%s таму',
s : 'некалькі секунд',
m : relativeTimeWithPlural,
mm : relativeTimeWithPlural,
h : relativeTimeWithPlural,
hh : relativeTimeWithPlural,
d : 'дзень',
dd : relativeTimeWithPlural,
M : 'месяц',
MM : relativeTimeWithPlural,
y : 'год',
yy : relativeTimeWithPlural
},
meridiemParse: /ночы|раніцы|дня|вечара/,
isPM : function (input) {
return /^(дня|вечара)$/.test(input);
},
meridiem : function (hour, minute, isLower) {
if (hour < 4) {
return 'ночы';
} else if (hour < 12) {
return 'раніцы';
} else if (hour < 17) {
return 'дня';
} else {
return 'вечара';
}
},
ordinalParse: /\d{1,2}-(і|ы|га)/,
ordinal: function (number, period) {
switch (period) {
case 'M':
case 'd':
case 'DDD':
case 'w':
case 'W':
return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы';
case 'D':
return number + '-га';
default:
return number;
}
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
});
| LilShy/test | 新建文件夹/material_admin_v-1.5-2/Template/jquery/vendors/bower_components/moment/src/locale/be.js | JavaScript | apache-2.0 | 5,171 |
#ifndef __ARCH_MACH_COMMON_H
#define __ARCH_MACH_COMMON_H
extern struct sys_timer shmobile_timer;
extern void shmobile_setup_console(void);
struct clk;
extern int clk_init(void);
extern void sh7367_init_irq(void);
extern void sh7367_add_early_devices(void);
extern void sh7367_add_standard_devices(void);
extern void sh7367_clock_init(void);
extern void sh7367_pinmux_init(void);
extern struct clk sh7367_extalb1_clk;
extern struct clk sh7367_extal2_clk;
extern void sh7377_init_irq(void);
extern void sh7377_add_early_devices(void);
extern void sh7377_add_standard_devices(void);
extern void sh7377_clock_init(void);
extern void sh7377_pinmux_init(void);
extern struct clk sh7377_extalc1_clk;
extern struct clk sh7377_extal2_clk;
extern void sh7372_init_irq(void);
extern void sh7372_add_early_devices(void);
extern void sh7372_add_standard_devices(void);
extern void sh7372_clock_init(void);
extern void sh7372_pinmux_init(void);
extern struct clk sh7372_extal1_clk;
extern struct clk sh7372_extal2_clk;
#endif /* __ARCH_MACH_COMMON_H */
| wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/arch/arm/mach-shmobile/include/mach/common.h | C | gpl-2.0 | 1,045 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>amCharts Data Loader Example</title>
<script src="http://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="http://www.amcharts.com/lib/3/pie.js"></script>
<script src="../dataloader.min.js"></script>
<style>
body, html {
font-family: Verdana;
font-size: 12px;
}
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<script>
AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataLoader": {
"url": "data/pie.csv",
"format": "csv",
"delimiter": ",",
"useColumnNames": true
},
"titleField": "country",
"valueField": "litres",
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"innerRadius": "30%",
"legend": {
"align": "center",
"markerType": "circle"
},
"responsive": {
"enabled": true,
"addDefaultRules": true,
"rules": [
{
"minWidth": 500,
"overrides": {
"innerRadius": "50%",
}
}
]
}
});
</script>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html> | liushuishang/YayCrawler | yaycrawler.admin/src/main/resources/static/assets/global/plugins/amcharts/amstockcharts/plugins/dataloader/examples/pie_csv.html | HTML | lgpl-3.0 | 1,448 |
#ifndef __NET_TC_MIR_H
#define __NET_TC_MIR_H
#include <net/act_api.h>
struct tcf_mirred {
struct tcf_common common;
int tcfm_eaction;
int tcfm_ifindex;
int tcfm_ok_push;
struct net_device *tcfm_dev;
struct list_head tcfm_list;
};
#define to_mirred(pc) \
container_of(pc, struct tcf_mirred, common)
#endif /* __NET_TC_MIR_H */
| talnoah/android_kernel_htc_dlx | virt/include/net/tc_act/tc_mirred.h | C | gpl-2.0 | 343 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path"
"runtime"
"strings"
)
func isGoFile(dir os.FileInfo) bool {
return !dir.IsDir() &&
!strings.HasPrefix(dir.Name(), ".") && // ignore .files
path.Ext(dir.Name()) == ".go"
}
func isPkgFile(dir os.FileInfo) bool {
return isGoFile(dir) &&
!strings.HasSuffix(dir.Name(), "_test.go") // ignore test files
}
func pkgName(filename string) string {
file, err := parser.ParseFile(token.NewFileSet(), filename, nil, parser.PackageClauseOnly)
if err != nil || file == nil {
return ""
}
return file.Name.Name
}
func parseDir(dirpath string) map[string]*ast.Package {
// the package name is the directory name within its parent.
// (use dirname instead of path because dirname is clean; it
// has no trailing '/')
_, pkgname := path.Split(dirpath)
// filter function to select the desired .go files
filter := func(d os.FileInfo) bool {
if isPkgFile(d) {
// Some directories contain main packages: Only accept
// files that belong to the expected package so that
// parser.ParsePackage doesn't return "multiple packages
// found" errors.
// Additionally, accept the special package name
// fakePkgName if we are looking at cmd documentation.
name := pkgName(dirpath + "/" + d.Name())
return name == pkgname
}
return false
}
// get package AST
pkgs, err := parser.ParseDir(token.NewFileSet(), dirpath, filter, parser.ParseComments)
if err != nil {
println("parse", dirpath, err.Error())
panic("go ParseDir fail: " + err.Error())
}
return pkgs
}
func stressParseGo() {
pkgroot := runtime.GOROOT() + "/src/"
for {
m := make(map[string]map[string]*ast.Package)
for _, pkg := range packages {
m[pkg] = parseDir(pkgroot + pkg)
Println("parsed go package", pkg)
}
}
}
// find . -type d -not -path "./exp" -not -path "./exp/*" -printf "\t\"%p\",\n" | sort | sed "s/\.\///" | grep -v testdata
var packages = []string{
"archive",
"archive/tar",
"archive/zip",
"bufio",
"builtin",
"bytes",
"compress",
"compress/bzip2",
"compress/flate",
"compress/gzip",
"compress/lzw",
"compress/zlib",
"container",
"container/heap",
"container/list",
"container/ring",
"crypto",
"crypto/aes",
"crypto/cipher",
"crypto/des",
"crypto/dsa",
"crypto/ecdsa",
"crypto/elliptic",
"crypto/hmac",
"crypto/md5",
"crypto/rand",
"crypto/rc4",
"crypto/rsa",
"crypto/sha1",
"crypto/sha256",
"crypto/sha512",
"crypto/subtle",
"crypto/tls",
"crypto/x509",
"crypto/x509/pkix",
"database",
"database/sql",
"database/sql/driver",
"debug",
"debug/dwarf",
"debug/elf",
"debug/gosym",
"debug/macho",
"debug/pe",
"encoding",
"encoding/ascii85",
"encoding/asn1",
"encoding/base32",
"encoding/base64",
"encoding/binary",
"encoding/csv",
"encoding/gob",
"encoding/hex",
"encoding/json",
"encoding/pem",
"encoding/xml",
"errors",
"expvar",
"flag",
"fmt",
"go",
"go/ast",
"go/build",
"go/doc",
"go/format",
"go/parser",
"go/printer",
"go/scanner",
"go/token",
"hash",
"hash/adler32",
"hash/crc32",
"hash/crc64",
"hash/fnv",
"html",
"html/template",
"image",
"image/color",
"image/draw",
"image/gif",
"image/jpeg",
"image/png",
"index",
"index/suffixarray",
"io",
"io/ioutil",
"log",
"log/syslog",
"math",
"math/big",
"math/cmplx",
"math/rand",
"mime",
"mime/multipart",
"net",
"net/http",
"net/http/cgi",
"net/http/cookiejar",
"net/http/fcgi",
"net/http/httptest",
"net/http/httputil",
"net/http/pprof",
"net/mail",
"net/rpc",
"net/rpc/jsonrpc",
"net/smtp",
"net/textproto",
"net/url",
"os",
"os/exec",
"os/signal",
"os/user",
"path",
"path/filepath",
"reflect",
"regexp",
"regexp/syntax",
"runtime",
"runtime/cgo",
"runtime/debug",
"runtime/pprof",
"runtime/race",
"sort",
"strconv",
"strings",
"sync",
"sync/atomic",
"syscall",
"testing",
"testing/iotest",
"testing/quick",
"text",
"text/scanner",
"text/tabwriter",
"text/template",
"text/template/parse",
"time",
"unicode",
"unicode/utf16",
"unicode/utf8",
"unsafe",
}
| shishkander/go | test/stress/parsego.go | GO | bsd-3-clause | 4,212 |
<?php
/**
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
/**
* Messages Component Messages Model
*
* @package Joomla.Administrator
* @subpackage com_messages
* @since 1.6
*/
class MessagesModelMessages extends JModelList
{
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'message_id', 'a.id',
'subject', 'a.subject',
'state', 'a.state',
'user_id_from', 'a.user_id_from',
'user_id_to', 'a.user_id_to',
'date_time', 'a.date_time',
'priority', 'a.priority',
);
}
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication('administrator');
// Load the filter state.
$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
$this->setState('filter.search', $search);
$state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string');
$this->setState('filter.state', $state);
// List state information.
parent::populateState('a.date_time', 'desc');
}
/**
* Method to get a store id based on model configuration state.
*
* This is necessary because the model is used by the component and
* different modules that might need different sets of data or different
* ordering requirements.
*
* @param string A prefix for the store id.
*
* @return string A store id.
*/
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':'.$this->getState('filter.search');
$id .= ':'.$this->getState('filter.state');
return parent::getStoreId($id);
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$user = JFactory::getUser();
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.*, '.
'u.name AS user_from'
)
);
$query->from('#__messages AS a');
// Join over the users for message owner.
$query->join('INNER', '#__users AS u ON u.id = a.user_id_from');
$query->where('a.user_id_to = '.(int) $user->get('id'));
// Filter by published state.
$state = $this->getState('filter.state');
if (is_numeric($state)) {
$query->where('a.state = '.(int) $state);
}
elseif ($state === '') {
$query->where('(a.state IN (0, 1))');
}
// Filter by search in subject or message.
$search = $this->getState('filter.search');
if (!empty($search)) {
$search = $db->Quote('%'.$db->escape($search, true).'%', false);
$query->where('a.subject LIKE '.$search.' OR a.message LIKE '.$search);
}
// Add the list ordering clause.
$query->order($db->escape($this->getState('list.ordering', 'a.date_time')).' '.$db->escape($this->getState('list.direction', 'DESC')));
//echo nl2br(str_replace('#__','jos_',$query));
return $query;
}
}
| baxri/cvote | tmp/install_54bd2998c811f/administrator/components/com_messages/models/messages.php | PHP | gpl-2.0 | 3,562 |
#!/usr/bin/env node
require("./bin/npm-cli.js")
| nikste/visualizationDemo | zeppelin-web/node/npm/cli.js | JavaScript | apache-2.0 | 48 |
package client
import (
"bufio"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/tlsconfig"
"github.com/docker/go-connections/sockets"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
// tlsClientCon holds tls information and a dialed connection.
type tlsClientCon struct {
*tls.Conn
rawConn net.Conn
}
func (c *tlsClientCon) CloseWrite() error {
// Go standard tls.Conn doesn't provide the CloseWrite() method so we do it
// on its underlying connection.
if conn, ok := c.rawConn.(types.CloseWriter); ok {
return conn.CloseWrite()
}
return nil
}
// postHijacked sends a POST request and hijacks the connection.
func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) {
bodyEncoded, err := encodeData(body)
if err != nil {
return types.HijackedResponse{}, err
}
apiPath := cli.getAPIPath(path, query)
req, err := http.NewRequest("POST", apiPath, bodyEncoded)
if err != nil {
return types.HijackedResponse{}, err
}
req = cli.addHeaders(req, headers)
conn, err := cli.setupHijackConn(req, "tcp")
if err != nil {
return types.HijackedResponse{}, err
}
return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err
}
func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) {
return tlsDialWithDialer(new(net.Dialer), network, addr, config)
}
// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in
// order to return our custom tlsClientCon struct which holds both the tls.Conn
// object _and_ its underlying raw connection. The rationale for this is that
// we need to be able to close the write end of the connection when attaching,
// which tls.Conn does not provide.
func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {
// We want the Timeout and Deadline values from dialer to cover the
// whole process: TCP connection and TLS handshake. This means that we
// also need to start our own timers now.
timeout := dialer.Timeout
if !dialer.Deadline.IsZero() {
deadlineTimeout := dialer.Deadline.Sub(time.Now())
if timeout == 0 || deadlineTimeout < timeout {
timeout = deadlineTimeout
}
}
var errChannel chan error
if timeout != 0 {
errChannel = make(chan error, 2)
time.AfterFunc(timeout, func() {
errChannel <- errors.New("")
})
}
proxyDialer, err := sockets.DialerFromEnvironment(dialer)
if err != nil {
return nil, err
}
rawConn, err := proxyDialer.Dial(network, addr)
if err != nil {
return nil, err
}
// When we set up a TCP connection for hijack, there could be long periods
// of inactivity (a long running command with no output) that in certain
// network setups may cause ECONNTIMEOUT, leaving the client in an unknown
// state. Setting TCP KeepAlive on the socket connection will prohibit
// ECONNTIMEOUT unless the socket connection truly is broken
if tcpConn, ok := rawConn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
}
colonPos := strings.LastIndex(addr, ":")
if colonPos == -1 {
colonPos = len(addr)
}
hostname := addr[:colonPos]
// If no ServerName is set, infer the ServerName
// from the hostname we're connecting to.
if config.ServerName == "" {
// Make a copy to avoid polluting argument or default.
config = tlsconfig.Clone(config)
config.ServerName = hostname
}
conn := tls.Client(rawConn, config)
if timeout == 0 {
err = conn.Handshake()
} else {
go func() {
errChannel <- conn.Handshake()
}()
err = <-errChannel
}
if err != nil {
rawConn.Close()
return nil, err
}
// This is Docker difference with standard's crypto/tls package: returned a
// wrapper which holds both the TLS and raw connections.
return &tlsClientCon{conn, rawConn}, nil
}
func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) {
if tlsConfig != nil && proto != "unix" && proto != "npipe" {
// Notice this isn't Go standard's tls.Dial function
return tlsDial(proto, addr, tlsConfig)
}
if proto == "npipe" {
return sockets.DialPipe(addr, 32*time.Second)
}
return net.Dial(proto, addr)
}
func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, error) {
req.Host = cli.addr
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", proto)
conn, err := dial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport))
if err != nil {
return nil, errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?")
}
// When we set up a TCP connection for hijack, there could be long periods
// of inactivity (a long running command with no output) that in certain
// network setups may cause ECONNTIMEOUT, leaving the client in an unknown
// state. Setting TCP KeepAlive on the socket connection will prohibit
// ECONNTIMEOUT unless the socket connection truly is broken
if tcpConn, ok := conn.(*net.TCPConn); ok {
tcpConn.SetKeepAlive(true)
tcpConn.SetKeepAlivePeriod(30 * time.Second)
}
clientconn := httputil.NewClientConn(conn, nil)
defer clientconn.Close()
// Server hijacks the connection, error 'connection closed' expected
resp, err := clientconn.Do(req)
if err != httputil.ErrPersistEOF {
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols {
resp.Body.Close()
return nil, fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode)
}
}
c, br := clientconn.Hijack()
if br.Buffered() > 0 {
// If there is buffered content, wrap the connection
c = &hijackedConn{c, br}
} else {
br.Reset(nil)
}
return c, nil
}
type hijackedConn struct {
net.Conn
r *bufio.Reader
}
func (c *hijackedConn) Read(b []byte) (int, error) {
return c.r.Read(b)
}
| aleksandra-malinowska/autoscaler | vertical-pod-autoscaler/vendor/github.com/docker/docker/client/hijack.go | GO | apache-2.0 | 5,955 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Filter;
use Traversable;
class StringToUpper extends AbstractUnicode
{
/**
* @var array
*/
protected $options = array(
'encoding' => null,
);
/**
* Constructor
*
* @param string|array|Traversable $encodingOrOptions OPTIONAL
*/
public function __construct($encodingOrOptions = null)
{
if ($encodingOrOptions !== null) {
if (!static::isOptions($encodingOrOptions)) {
$this->setEncoding($encodingOrOptions);
} else {
$this->setOptions($encodingOrOptions);
}
}
}
/**
* Defined by Zend\Filter\FilterInterface
*
* Returns the string $value, converting characters to uppercase as necessary
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (!is_scalar($value)) {
return $value;
}
$value = (string) $value;
if ($this->options['encoding'] !== null) {
return mb_strtoupper($value, $this->options['encoding']);
}
return strtoupper($value);
}
}
| JorikVartanov/zf2 | zf2_project/vendor/zendframework/zendframework/library/Zend/Filter/StringToUpper.php | PHP | bsd-3-clause | 1,560 |
<?php
/**
* @package Joomla.Site
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
jimport('joomla.application.categories');
/**
* Build the route for the com_contact component
*
* @param array An array of URL arguments
*
* @return array The URL arguments to use to assemble the subsequent URL.
*/
function ContactBuildRoute(&$query){
$segments = array();
// get a menu item based on Itemid or currently active
$app = JFactory::getApplication();
$menu = $app->getMenu();
$params = JComponentHelper::getParams('com_contact');
$advanced = $params->get('sef_advanced_link', 0);
if (empty($query['Itemid'])) {
$menuItem = $menu->getActive();
} else {
$menuItem = $menu->getItem($query['Itemid']);
}
$mView = (empty($menuItem->query['view'])) ? null : $menuItem->query['view'];
$mCatid = (empty($menuItem->query['catid'])) ? null : $menuItem->query['catid'];
$mId = (empty($menuItem->query['id'])) ? null : $menuItem->query['id'];
if (isset($query['view']))
{
$view = $query['view'];
if (empty($query['Itemid'])) {
$segments[] = $query['view'];
}
unset($query['view']);
};
// are we dealing with a contact that is attached to a menu item?
if (isset($view) && ($mView == $view) and (isset($query['id'])) and ($mId == intval($query['id']))) {
unset($query['view']);
unset($query['catid']);
unset($query['id']);
return $segments;
}
if (isset($view) and ($view == 'category' or $view == 'contact')) {
if ($mId != intval($query['id']) || $mView != $view) {
if($view == 'contact' && isset($query['catid']))
{
$catid = $query['catid'];
} elseif(isset($query['id'])) {
$catid = $query['id'];
}
$menuCatid = $mId;
$categories = JCategories::getInstance('Contact');
$category = $categories->get($catid);
if($category)
{
//TODO Throw error that the category either not exists or is unpublished
$path = array_reverse($category->getPath());
$array = array();
foreach($path as $id)
{
if((int) $id == (int)$menuCatid)
{
break;
}
if($advanced)
{
list($tmp, $id) = explode(':', $id, 2);
}
$array[] = $id;
}
$segments = array_merge($segments, array_reverse($array));
}
if($view == 'contact')
{
if($advanced)
{
list($tmp, $id) = explode(':', $query['id'], 2);
} else {
$id = $query['id'];
}
$segments[] = $id;
}
}
unset($query['id']);
unset($query['catid']);
}
if (isset($query['layout']))
{
if (!empty($query['Itemid']) && isset($menuItem->query['layout']))
{
if ($query['layout'] == $menuItem->query['layout']) {
unset($query['layout']);
}
}
else
{
if ($query['layout'] == 'default') {
unset($query['layout']);
}
}
};
return $segments;
}
/**
* Parse the segments of a URL.
*
* @param array The segments of the URL to parse.
*
* @return array The URL attributes to be used by the application.
*/
function ContactParseRoute($segments)
{
$vars = array();
//Get the active menu item.
$app = JFactory::getApplication();
$menu = $app->getMenu();
$item = $menu->getActive();
$params = JComponentHelper::getParams('com_contact');
$advanced = $params->get('sef_advanced_link', 0);
// Count route segments
$count = count($segments);
// Standard routing for newsfeeds.
if (!isset($item))
{
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
return $vars;
}
// From the categories view, we can only jump to a category.
$id = (isset($item->query['id']) && $item->query['id'] > 1) ? $item->query['id'] : 'root';
$contactCategory = JCategories::getInstance('Contact')->get($id);
$categories = ($contactCategory) ? $contactCategory->getChildren() : array();
$vars['catid'] = $id;
$vars['id'] = $id;
$found = 0;
foreach($segments as $segment)
{
$segment = $advanced ? str_replace(':', '-', $segment) : $segment;
foreach($categories as $category)
{
if ($category->slug == $segment || $category->alias == $segment)
{
$vars['id'] = $category->id;
$vars['catid'] = $category->id;
$vars['view'] = 'category';
$categories = $category->getChildren();
$found = 1;
break;
}
}
if ($found == 0)
{
if($advanced)
{
$db = JFactory::getDBO();
$query = 'SELECT id FROM #__contact_details WHERE catid = '.$vars['catid'].' AND alias = '.$db->Quote($segment);
$db->setQuery($query);
$nid = $db->loadResult();
} else {
$nid = $segment;
}
$vars['id'] = $nid;
$vars['view'] = 'contact';
}
$found = 0;
}
return $vars;
}
| baxri/cvote | tmp/install_54bd2998c811f/components/com_contact/router.php | PHP | gpl-2.0 | 4,706 |
var vows = require("vows"),
_ = require("../../"),
load = require("../load"),
assert = require("../assert");
var suite = vows.describe("d3.max");
suite.addBatch({
"max": {
topic: load("arrays/max").expression("d3.max"),
"returns the greatest numeric value for numbers": function(max) {
assert.equal(max([1]), 1);
assert.equal(max([5, 1, 2, 3, 4]), 5);
assert.equal(max([20, 3]), 20);
assert.equal(max([3, 20]), 20);
},
"returns the greatest lexicographic value for strings": function(max) {
assert.equal(max(["c", "a", "b"]), "c");
assert.equal(max(["20", "3"]), "3");
assert.equal(max(["3", "20"]), "3");
},
"ignores null, undefined and NaN": function(max) {
var o = {valueOf: function() { return NaN; }};
assert.equal(max([NaN, 1, 2, 3, 4, 5]), 5);
assert.equal(max([o, 1, 2, 3, 4, 5]), 5);
assert.equal(max([1, 2, 3, 4, 5, NaN]), 5);
assert.equal(max([1, 2, 3, 4, 5, o]), 5);
assert.equal(max([10, null, 3, undefined, 5, NaN]), 10);
assert.equal(max([-1, null, -3, undefined, -5, NaN]), -1);
},
"compares heterogenous types as numbers": function(max) {
assert.strictEqual(max([20, "3"]), 20);
assert.strictEqual(max(["20", 3]), "20");
assert.strictEqual(max([3, "20"]), "20");
assert.strictEqual(max(["3", 20]), 20);
},
"returns undefined for empty array": function(max) {
assert.isUndefined(max([]));
assert.isUndefined(max([null]));
assert.isUndefined(max([undefined]));
assert.isUndefined(max([NaN]));
assert.isUndefined(max([NaN, NaN]));
},
"applies the optional accessor function": function(max) {
assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2);
assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4);
}
}
});
suite.export(module);
| MoonApps/barelyalive | www/js/vendor/d3-master/test/arrays/max-test.js | JavaScript | gpl-2.0 | 1,919 |
/*
* Copyright(c) 2006, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef _ADMA_H
#define _ADMA_H
#include <linux/types.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/hardware/iop_adma.h>
#define ADMA_ACCR(chan) (chan->mmr_base + 0x0)
#define ADMA_ACSR(chan) (chan->mmr_base + 0x4)
#define ADMA_ADAR(chan) (chan->mmr_base + 0x8)
#define ADMA_IIPCR(chan) (chan->mmr_base + 0x18)
#define ADMA_IIPAR(chan) (chan->mmr_base + 0x1c)
#define ADMA_IIPUAR(chan) (chan->mmr_base + 0x20)
#define ADMA_ANDAR(chan) (chan->mmr_base + 0x24)
#define ADMA_ADCR(chan) (chan->mmr_base + 0x28)
#define ADMA_CARMD(chan) (chan->mmr_base + 0x2c)
#define ADMA_ABCR(chan) (chan->mmr_base + 0x30)
#define ADMA_DLADR(chan) (chan->mmr_base + 0x34)
#define ADMA_DUADR(chan) (chan->mmr_base + 0x38)
#define ADMA_SLAR(src, chan) (chan->mmr_base + (0x3c + (src << 3)))
#define ADMA_SUAR(src, chan) (chan->mmr_base + (0x40 + (src << 3)))
struct iop13xx_adma_src {
u32 src_addr;
union {
u32 upper_src_addr;
struct {
unsigned int pq_upper_src_addr:24;
unsigned int pq_dmlt:8;
};
};
};
struct iop13xx_adma_desc_ctrl {
unsigned int int_en:1;
unsigned int xfer_dir:2;
unsigned int src_select:4;
unsigned int zero_result:1;
unsigned int block_fill_en:1;
unsigned int crc_gen_en:1;
unsigned int crc_xfer_dis:1;
unsigned int crc_seed_fetch_dis:1;
unsigned int status_write_back_en:1;
unsigned int endian_swap_en:1;
unsigned int reserved0:2;
unsigned int pq_update_xfer_en:1;
unsigned int dual_xor_en:1;
unsigned int pq_xfer_en:1;
unsigned int p_xfer_dis:1;
unsigned int reserved1:10;
unsigned int relax_order_en:1;
unsigned int no_snoop_en:1;
};
struct iop13xx_adma_byte_count {
unsigned int byte_count:24;
unsigned int host_if:3;
unsigned int reserved:2;
unsigned int zero_result_err_q:1;
unsigned int zero_result_err:1;
unsigned int tx_complete:1;
};
struct iop13xx_adma_desc_hw {
u32 next_desc;
union {
u32 desc_ctrl;
struct iop13xx_adma_desc_ctrl desc_ctrl_field;
};
union {
u32 crc_addr;
u32 block_fill_data;
u32 q_dest_addr;
};
union {
u32 byte_count;
struct iop13xx_adma_byte_count byte_count_field;
};
union {
u32 dest_addr;
u32 p_dest_addr;
};
union {
u32 upper_dest_addr;
u32 pq_upper_dest_addr;
};
struct iop13xx_adma_src src[1];
};
struct iop13xx_adma_desc_dual_xor {
u32 next_desc;
u32 desc_ctrl;
u32 reserved;
u32 byte_count;
u32 h_dest_addr;
u32 h_upper_dest_addr;
u32 src0_addr;
u32 upper_src0_addr;
u32 src1_addr;
u32 upper_src1_addr;
u32 h_src_addr;
u32 h_upper_src_addr;
u32 d_src_addr;
u32 d_upper_src_addr;
u32 d_dest_addr;
u32 d_upper_dest_addr;
};
struct iop13xx_adma_desc_pq_update {
u32 next_desc;
u32 desc_ctrl;
u32 reserved;
u32 byte_count;
u32 p_dest_addr;
u32 p_upper_dest_addr;
u32 src0_addr;
u32 upper_src0_addr;
u32 src1_addr;
u32 upper_src1_addr;
u32 p_src_addr;
u32 p_upper_src_addr;
u32 q_src_addr;
struct {
unsigned int q_upper_src_addr:24;
unsigned int q_dmlt:8;
};
u32 q_dest_addr;
u32 q_upper_dest_addr;
};
static inline int iop_adma_get_max_xor(void)
{
return 16;
}
#define iop_adma_get_max_pq iop_adma_get_max_xor
static inline u32 iop_chan_get_current_descriptor(struct iop_adma_chan *chan)
{
return __raw_readl(ADMA_ADAR(chan));
}
static inline void iop_chan_set_next_descriptor(struct iop_adma_chan *chan,
u32 next_desc_addr)
{
__raw_writel(next_desc_addr, ADMA_ANDAR(chan));
}
#define ADMA_STATUS_BUSY (1 << 13)
static inline char iop_chan_is_busy(struct iop_adma_chan *chan)
{
if (__raw_readl(ADMA_ACSR(chan)) &
ADMA_STATUS_BUSY)
return 1;
else
return 0;
}
static inline int
iop_chan_get_desc_align(struct iop_adma_chan *chan, int num_slots)
{
return 1;
}
#define iop_desc_is_aligned(x, y) 1
static inline int
iop_chan_memcpy_slot_count(size_t len, int *slots_per_op)
{
*slots_per_op = 1;
return 1;
}
#define iop_chan_interrupt_slot_count(s, c) iop_chan_memcpy_slot_count(0, s)
static inline int
iop_chan_memset_slot_count(size_t len, int *slots_per_op)
{
*slots_per_op = 1;
return 1;
}
static inline int
iop_chan_xor_slot_count(size_t len, int src_cnt, int *slots_per_op)
{
static const char slot_count_table[] = { 1, 2, 2, 2,
2, 3, 3, 3,
3, 4, 4, 4,
4, 5, 5, 5,
};
*slots_per_op = slot_count_table[src_cnt - 1];
return *slots_per_op;
}
#define ADMA_MAX_BYTE_COUNT (16 * 1024 * 1024)
#define IOP_ADMA_MAX_BYTE_COUNT ADMA_MAX_BYTE_COUNT
#define IOP_ADMA_ZERO_SUM_MAX_BYTE_COUNT ADMA_MAX_BYTE_COUNT
#define IOP_ADMA_XOR_MAX_BYTE_COUNT ADMA_MAX_BYTE_COUNT
#define IOP_ADMA_PQ_MAX_BYTE_COUNT ADMA_MAX_BYTE_COUNT
#define iop_chan_zero_sum_slot_count(l, s, o) iop_chan_xor_slot_count(l, s, o)
#define iop_chan_pq_slot_count iop_chan_xor_slot_count
#define iop_chan_pq_zero_sum_slot_count iop_chan_xor_slot_count
static inline u32 iop_desc_get_dest_addr(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->dest_addr;
}
static inline u32 iop_desc_get_qdest_addr(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->q_dest_addr;
}
static inline u32 iop_desc_get_byte_count(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->byte_count_field.byte_count;
}
static inline u32 iop_desc_get_src_addr(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan,
int src_idx)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->src[src_idx].src_addr;
}
static inline u32 iop_desc_get_src_count(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->desc_ctrl_field.src_select + 1;
}
static inline void
iop_desc_init_memcpy(struct iop_adma_desc_slot *desc, unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
hw_desc->crc_addr = 0;
}
static inline void
iop_desc_init_memset(struct iop_adma_desc_slot *desc, unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.block_fill_en = 1;
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
hw_desc->crc_addr = 0;
}
/* to do: support buffers larger than ADMA_MAX_BYTE_COUNT */
static inline void
iop_desc_init_xor(struct iop_adma_desc_slot *desc, int src_cnt,
unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.src_select = src_cnt - 1;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
hw_desc->crc_addr = 0;
}
#define iop_desc_init_null_xor(d, s, i) iop_desc_init_xor(d, s, i)
/* to do: support buffers larger than ADMA_MAX_BYTE_COUNT */
static inline int
iop_desc_init_zero_sum(struct iop_adma_desc_slot *desc, int src_cnt,
unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.src_select = src_cnt - 1;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.zero_result = 1;
u_desc_ctrl.field.status_write_back_en = 1;
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
hw_desc->crc_addr = 0;
return 1;
}
static inline void
iop_desc_init_pq(struct iop_adma_desc_slot *desc, int src_cnt,
unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.src_select = src_cnt - 1;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.pq_xfer_en = 1;
u_desc_ctrl.field.p_xfer_dis = !!(flags & DMA_PREP_PQ_DISABLE_P);
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
}
static inline int iop_desc_is_pq(struct iop_adma_desc_slot *desc)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = hw_desc->desc_ctrl;
return u_desc_ctrl.field.pq_xfer_en;
}
static inline void
iop_desc_init_pq_zero_sum(struct iop_adma_desc_slot *desc, int src_cnt,
unsigned long flags)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
union {
u32 value;
struct iop13xx_adma_desc_ctrl field;
} u_desc_ctrl;
u_desc_ctrl.value = 0;
u_desc_ctrl.field.src_select = src_cnt - 1;
u_desc_ctrl.field.xfer_dir = 3; /* local to internal bus */
u_desc_ctrl.field.zero_result = 1;
u_desc_ctrl.field.status_write_back_en = 1;
u_desc_ctrl.field.pq_xfer_en = 1;
u_desc_ctrl.field.p_xfer_dis = !!(flags & DMA_PREP_PQ_DISABLE_P);
u_desc_ctrl.field.int_en = flags & DMA_PREP_INTERRUPT;
hw_desc->desc_ctrl = u_desc_ctrl.value;
}
static inline void iop_desc_set_byte_count(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan,
u32 byte_count)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->byte_count = byte_count;
}
static inline void
iop_desc_set_zero_sum_byte_count(struct iop_adma_desc_slot *desc, u32 len)
{
int slots_per_op = desc->slots_per_op;
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc, *iter;
int i = 0;
if (len <= IOP_ADMA_ZERO_SUM_MAX_BYTE_COUNT) {
hw_desc->byte_count = len;
} else {
do {
iter = iop_hw_desc_slot_idx(hw_desc, i);
iter->byte_count = IOP_ADMA_ZERO_SUM_MAX_BYTE_COUNT;
len -= IOP_ADMA_ZERO_SUM_MAX_BYTE_COUNT;
i += slots_per_op;
} while (len > IOP_ADMA_ZERO_SUM_MAX_BYTE_COUNT);
if (len) {
iter = iop_hw_desc_slot_idx(hw_desc, i);
iter->byte_count = len;
}
}
}
#define iop_desc_set_pq_zero_sum_byte_count iop_desc_set_zero_sum_byte_count
static inline void iop_desc_set_dest_addr(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan,
dma_addr_t addr)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->dest_addr = addr;
hw_desc->upper_dest_addr = 0;
}
static inline void
iop_desc_set_pq_addr(struct iop_adma_desc_slot *desc, dma_addr_t *addr)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->dest_addr = addr[0];
hw_desc->q_dest_addr = addr[1];
hw_desc->upper_dest_addr = 0;
}
static inline void iop_desc_set_memcpy_src_addr(struct iop_adma_desc_slot *desc,
dma_addr_t addr)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->src[0].src_addr = addr;
hw_desc->src[0].upper_src_addr = 0;
}
static inline void iop_desc_set_xor_src_addr(struct iop_adma_desc_slot *desc,
int src_idx, dma_addr_t addr)
{
int slot_cnt = desc->slot_cnt, slots_per_op = desc->slots_per_op;
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc, *iter;
int i = 0;
do {
iter = iop_hw_desc_slot_idx(hw_desc, i);
iter->src[src_idx].src_addr = addr;
iter->src[src_idx].upper_src_addr = 0;
slot_cnt -= slots_per_op;
if (slot_cnt) {
i += slots_per_op;
addr += IOP_ADMA_XOR_MAX_BYTE_COUNT;
}
} while (slot_cnt);
}
static inline void
iop_desc_set_pq_src_addr(struct iop_adma_desc_slot *desc, int src_idx,
dma_addr_t addr, unsigned char coef)
{
int slot_cnt = desc->slot_cnt, slots_per_op = desc->slots_per_op;
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc, *iter;
struct iop13xx_adma_src *src;
int i = 0;
do {
iter = iop_hw_desc_slot_idx(hw_desc, i);
src = &iter->src[src_idx];
src->src_addr = addr;
src->pq_upper_src_addr = 0;
src->pq_dmlt = coef;
slot_cnt -= slots_per_op;
if (slot_cnt) {
i += slots_per_op;
addr += IOP_ADMA_PQ_MAX_BYTE_COUNT;
}
} while (slot_cnt);
}
static inline void
iop_desc_init_interrupt(struct iop_adma_desc_slot *desc,
struct iop_adma_chan *chan)
{
iop_desc_init_memcpy(desc, 1);
iop_desc_set_byte_count(desc, chan, 0);
iop_desc_set_dest_addr(desc, chan, 0);
iop_desc_set_memcpy_src_addr(desc, 0);
}
#define iop_desc_set_zero_sum_src_addr iop_desc_set_xor_src_addr
#define iop_desc_set_pq_zero_sum_src_addr iop_desc_set_pq_src_addr
static inline void
iop_desc_set_pq_zero_sum_addr(struct iop_adma_desc_slot *desc, int pq_idx,
dma_addr_t *src)
{
iop_desc_set_xor_src_addr(desc, pq_idx, src[pq_idx]);
iop_desc_set_xor_src_addr(desc, pq_idx+1, src[pq_idx+1]);
}
static inline void iop_desc_set_next_desc(struct iop_adma_desc_slot *desc,
u32 next_desc_addr)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
iop_paranoia(hw_desc->next_desc);
hw_desc->next_desc = next_desc_addr;
}
static inline u32 iop_desc_get_next_desc(struct iop_adma_desc_slot *desc)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
return hw_desc->next_desc;
}
static inline void iop_desc_clear_next_desc(struct iop_adma_desc_slot *desc)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->next_desc = 0;
}
static inline void iop_desc_set_block_fill_val(struct iop_adma_desc_slot *desc,
u32 val)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
hw_desc->block_fill_data = val;
}
static inline enum sum_check_flags
iop_desc_get_zero_result(struct iop_adma_desc_slot *desc)
{
struct iop13xx_adma_desc_hw *hw_desc = desc->hw_desc;
struct iop13xx_adma_desc_ctrl desc_ctrl = hw_desc->desc_ctrl_field;
struct iop13xx_adma_byte_count byte_count = hw_desc->byte_count_field;
enum sum_check_flags flags;
BUG_ON(!(byte_count.tx_complete && desc_ctrl.zero_result));
flags = byte_count.zero_result_err_q << SUM_CHECK_Q;
flags |= byte_count.zero_result_err << SUM_CHECK_P;
return flags;
}
static inline void iop_chan_append(struct iop_adma_chan *chan)
{
u32 adma_accr;
adma_accr = __raw_readl(ADMA_ACCR(chan));
adma_accr |= 0x2;
__raw_writel(adma_accr, ADMA_ACCR(chan));
}
static inline u32 iop_chan_get_status(struct iop_adma_chan *chan)
{
return __raw_readl(ADMA_ACSR(chan));
}
static inline void iop_chan_disable(struct iop_adma_chan *chan)
{
u32 adma_chan_ctrl = __raw_readl(ADMA_ACCR(chan));
adma_chan_ctrl &= ~0x1;
__raw_writel(adma_chan_ctrl, ADMA_ACCR(chan));
}
static inline void iop_chan_enable(struct iop_adma_chan *chan)
{
u32 adma_chan_ctrl;
adma_chan_ctrl = __raw_readl(ADMA_ACCR(chan));
adma_chan_ctrl |= 0x1;
__raw_writel(adma_chan_ctrl, ADMA_ACCR(chan));
}
static inline void iop_adma_device_clear_eot_status(struct iop_adma_chan *chan)
{
u32 status = __raw_readl(ADMA_ACSR(chan));
status &= (1 << 12);
__raw_writel(status, ADMA_ACSR(chan));
}
static inline void iop_adma_device_clear_eoc_status(struct iop_adma_chan *chan)
{
u32 status = __raw_readl(ADMA_ACSR(chan));
status &= (1 << 11);
__raw_writel(status, ADMA_ACSR(chan));
}
static inline void iop_adma_device_clear_err_status(struct iop_adma_chan *chan)
{
u32 status = __raw_readl(ADMA_ACSR(chan));
status &= (1 << 9) | (1 << 5) | (1 << 4) | (1 << 3);
__raw_writel(status, ADMA_ACSR(chan));
}
static inline int
iop_is_err_int_parity(unsigned long status, struct iop_adma_chan *chan)
{
return test_bit(9, &status);
}
static inline int
iop_is_err_mcu_abort(unsigned long status, struct iop_adma_chan *chan)
{
return test_bit(5, &status);
}
static inline int
iop_is_err_int_tabort(unsigned long status, struct iop_adma_chan *chan)
{
return test_bit(4, &status);
}
static inline int
iop_is_err_int_mabort(unsigned long status, struct iop_adma_chan *chan)
{
return test_bit(3, &status);
}
static inline int
iop_is_err_pci_tabort(unsigned long status, struct iop_adma_chan *chan)
{
return 0;
}
static inline int
iop_is_err_pci_mabort(unsigned long status, struct iop_adma_chan *chan)
{
return 0;
}
static inline int
iop_is_err_split_tx(unsigned long status, struct iop_adma_chan *chan)
{
return 0;
}
#endif /* _ADMA_H */
| talnoah/android_kernel_htc_dlx | virt/arch/arm/mach-iop13xx/include/mach/adma.h | C | gpl-2.0 | 17,035 |
/* SPDX-License-Identifier: GPL-2.0+ */
/*
* Copyright 2016-2017 Google, Inc
*
* Fairchild FUSB302 Type-C Chip Driver
*/
#ifndef FUSB302_REG_H
#define FUSB302_REG_H
#define FUSB_REG_DEVICE_ID 0x01
#define FUSB_REG_SWITCHES0 0x02
#define FUSB_REG_SWITCHES0_CC2_PU_EN BIT(7)
#define FUSB_REG_SWITCHES0_CC1_PU_EN BIT(6)
#define FUSB_REG_SWITCHES0_VCONN_CC2 BIT(5)
#define FUSB_REG_SWITCHES0_VCONN_CC1 BIT(4)
#define FUSB_REG_SWITCHES0_MEAS_CC2 BIT(3)
#define FUSB_REG_SWITCHES0_MEAS_CC1 BIT(2)
#define FUSB_REG_SWITCHES0_CC2_PD_EN BIT(1)
#define FUSB_REG_SWITCHES0_CC1_PD_EN BIT(0)
#define FUSB_REG_SWITCHES1 0x03
#define FUSB_REG_SWITCHES1_POWERROLE BIT(7)
#define FUSB_REG_SWITCHES1_SPECREV1 BIT(6)
#define FUSB_REG_SWITCHES1_SPECREV0 BIT(5)
#define FUSB_REG_SWITCHES1_DATAROLE BIT(4)
#define FUSB_REG_SWITCHES1_AUTO_GCRC BIT(2)
#define FUSB_REG_SWITCHES1_TXCC2_EN BIT(1)
#define FUSB_REG_SWITCHES1_TXCC1_EN BIT(0)
#define FUSB_REG_MEASURE 0x04
#define FUSB_REG_MEASURE_MDAC5 BIT(7)
#define FUSB_REG_MEASURE_MDAC4 BIT(6)
#define FUSB_REG_MEASURE_MDAC3 BIT(5)
#define FUSB_REG_MEASURE_MDAC2 BIT(4)
#define FUSB_REG_MEASURE_MDAC1 BIT(3)
#define FUSB_REG_MEASURE_MDAC0 BIT(2)
#define FUSB_REG_MEASURE_VBUS BIT(1)
#define FUSB_REG_MEASURE_XXXX5 BIT(0)
#define FUSB_REG_CONTROL0 0x06
#define FUSB_REG_CONTROL0_TX_FLUSH BIT(6)
#define FUSB_REG_CONTROL0_INT_MASK BIT(5)
#define FUSB_REG_CONTROL0_HOST_CUR_MASK (0xC)
#define FUSB_REG_CONTROL0_HOST_CUR_HIGH (0xC)
#define FUSB_REG_CONTROL0_HOST_CUR_MED (0x8)
#define FUSB_REG_CONTROL0_HOST_CUR_DEF (0x4)
#define FUSB_REG_CONTROL0_TX_START BIT(0)
#define FUSB_REG_CONTROL1 0x07
#define FUSB_REG_CONTROL1_ENSOP2DB BIT(6)
#define FUSB_REG_CONTROL1_ENSOP1DB BIT(5)
#define FUSB_REG_CONTROL1_BIST_MODE2 BIT(4)
#define FUSB_REG_CONTROL1_RX_FLUSH BIT(2)
#define FUSB_REG_CONTROL1_ENSOP2 BIT(1)
#define FUSB_REG_CONTROL1_ENSOP1 BIT(0)
#define FUSB_REG_CONTROL2 0x08
#define FUSB_REG_CONTROL2_MODE BIT(1)
#define FUSB_REG_CONTROL2_MODE_MASK (0x6)
#define FUSB_REG_CONTROL2_MODE_DFP (0x6)
#define FUSB_REG_CONTROL2_MODE_UFP (0x4)
#define FUSB_REG_CONTROL2_MODE_DRP (0x2)
#define FUSB_REG_CONTROL2_MODE_NONE (0x0)
#define FUSB_REG_CONTROL2_TOGGLE BIT(0)
#define FUSB_REG_CONTROL3 0x09
#define FUSB_REG_CONTROL3_SEND_HARDRESET BIT(6)
#define FUSB_REG_CONTROL3_BIST_TMODE BIT(5) /* 302B Only */
#define FUSB_REG_CONTROL3_AUTO_HARDRESET BIT(4)
#define FUSB_REG_CONTROL3_AUTO_SOFTRESET BIT(3)
#define FUSB_REG_CONTROL3_N_RETRIES BIT(1)
#define FUSB_REG_CONTROL3_N_RETRIES_MASK (0x6)
#define FUSB_REG_CONTROL3_N_RETRIES_3 (0x6)
#define FUSB_REG_CONTROL3_N_RETRIES_2 (0x4)
#define FUSB_REG_CONTROL3_N_RETRIES_1 (0x2)
#define FUSB_REG_CONTROL3_AUTO_RETRY BIT(0)
#define FUSB_REG_MASK 0x0A
#define FUSB_REG_MASK_VBUSOK BIT(7)
#define FUSB_REG_MASK_ACTIVITY BIT(6)
#define FUSB_REG_MASK_COMP_CHNG BIT(5)
#define FUSB_REG_MASK_CRC_CHK BIT(4)
#define FUSB_REG_MASK_ALERT BIT(3)
#define FUSB_REG_MASK_WAKE BIT(2)
#define FUSB_REG_MASK_COLLISION BIT(1)
#define FUSB_REG_MASK_BC_LVL BIT(0)
#define FUSB_REG_POWER 0x0B
#define FUSB_REG_POWER_PWR BIT(0)
#define FUSB_REG_POWER_PWR_LOW 0x1
#define FUSB_REG_POWER_PWR_MEDIUM 0x3
#define FUSB_REG_POWER_PWR_HIGH 0x7
#define FUSB_REG_POWER_PWR_ALL 0xF
#define FUSB_REG_RESET 0x0C
#define FUSB_REG_RESET_PD_RESET BIT(1)
#define FUSB_REG_RESET_SW_RESET BIT(0)
#define FUSB_REG_MASKA 0x0E
#define FUSB_REG_MASKA_OCP_TEMP BIT(7)
#define FUSB_REG_MASKA_TOGDONE BIT(6)
#define FUSB_REG_MASKA_SOFTFAIL BIT(5)
#define FUSB_REG_MASKA_RETRYFAIL BIT(4)
#define FUSB_REG_MASKA_HARDSENT BIT(3)
#define FUSB_REG_MASKA_TX_SUCCESS BIT(2)
#define FUSB_REG_MASKA_SOFTRESET BIT(1)
#define FUSB_REG_MASKA_HARDRESET BIT(0)
#define FUSB_REG_MASKB 0x0F
#define FUSB_REG_MASKB_GCRCSENT BIT(0)
#define FUSB_REG_STATUS0A 0x3C
#define FUSB_REG_STATUS0A_SOFTFAIL BIT(5)
#define FUSB_REG_STATUS0A_RETRYFAIL BIT(4)
#define FUSB_REG_STATUS0A_POWER BIT(2)
#define FUSB_REG_STATUS0A_RX_SOFT_RESET BIT(1)
#define FUSB_REG_STATUS0A_RX_HARD_RESET BIT(0)
#define FUSB_REG_STATUS1A 0x3D
#define FUSB_REG_STATUS1A_TOGSS BIT(3)
#define FUSB_REG_STATUS1A_TOGSS_RUNNING 0x0
#define FUSB_REG_STATUS1A_TOGSS_SRC1 0x1
#define FUSB_REG_STATUS1A_TOGSS_SRC2 0x2
#define FUSB_REG_STATUS1A_TOGSS_SNK1 0x5
#define FUSB_REG_STATUS1A_TOGSS_SNK2 0x6
#define FUSB_REG_STATUS1A_TOGSS_AA 0x7
#define FUSB_REG_STATUS1A_TOGSS_POS (3)
#define FUSB_REG_STATUS1A_TOGSS_MASK (0x7)
#define FUSB_REG_STATUS1A_RXSOP2DB BIT(2)
#define FUSB_REG_STATUS1A_RXSOP1DB BIT(1)
#define FUSB_REG_STATUS1A_RXSOP BIT(0)
#define FUSB_REG_INTERRUPTA 0x3E
#define FUSB_REG_INTERRUPTA_OCP_TEMP BIT(7)
#define FUSB_REG_INTERRUPTA_TOGDONE BIT(6)
#define FUSB_REG_INTERRUPTA_SOFTFAIL BIT(5)
#define FUSB_REG_INTERRUPTA_RETRYFAIL BIT(4)
#define FUSB_REG_INTERRUPTA_HARDSENT BIT(3)
#define FUSB_REG_INTERRUPTA_TX_SUCCESS BIT(2)
#define FUSB_REG_INTERRUPTA_SOFTRESET BIT(1)
#define FUSB_REG_INTERRUPTA_HARDRESET BIT(0)
#define FUSB_REG_INTERRUPTB 0x3F
#define FUSB_REG_INTERRUPTB_GCRCSENT BIT(0)
#define FUSB_REG_STATUS0 0x40
#define FUSB_REG_STATUS0_VBUSOK BIT(7)
#define FUSB_REG_STATUS0_ACTIVITY BIT(6)
#define FUSB_REG_STATUS0_COMP BIT(5)
#define FUSB_REG_STATUS0_CRC_CHK BIT(4)
#define FUSB_REG_STATUS0_ALERT BIT(3)
#define FUSB_REG_STATUS0_WAKE BIT(2)
#define FUSB_REG_STATUS0_BC_LVL_MASK 0x03
#define FUSB_REG_STATUS0_BC_LVL_0_200 0x0
#define FUSB_REG_STATUS0_BC_LVL_200_600 0x1
#define FUSB_REG_STATUS0_BC_LVL_600_1230 0x2
#define FUSB_REG_STATUS0_BC_LVL_1230_MAX 0x3
#define FUSB_REG_STATUS0_BC_LVL1 BIT(1)
#define FUSB_REG_STATUS0_BC_LVL0 BIT(0)
#define FUSB_REG_STATUS1 0x41
#define FUSB_REG_STATUS1_RXSOP2 BIT(7)
#define FUSB_REG_STATUS1_RXSOP1 BIT(6)
#define FUSB_REG_STATUS1_RX_EMPTY BIT(5)
#define FUSB_REG_STATUS1_RX_FULL BIT(4)
#define FUSB_REG_STATUS1_TX_EMPTY BIT(3)
#define FUSB_REG_STATUS1_TX_FULL BIT(2)
#define FUSB_REG_INTERRUPT 0x42
#define FUSB_REG_INTERRUPT_VBUSOK BIT(7)
#define FUSB_REG_INTERRUPT_ACTIVITY BIT(6)
#define FUSB_REG_INTERRUPT_COMP_CHNG BIT(5)
#define FUSB_REG_INTERRUPT_CRC_CHK BIT(4)
#define FUSB_REG_INTERRUPT_ALERT BIT(3)
#define FUSB_REG_INTERRUPT_WAKE BIT(2)
#define FUSB_REG_INTERRUPT_COLLISION BIT(1)
#define FUSB_REG_INTERRUPT_BC_LVL BIT(0)
#define FUSB_REG_FIFOS 0x43
/* Tokens defined for the FUSB302 TX FIFO */
enum fusb302_txfifo_tokens {
FUSB302_TKN_TXON = 0xA1,
FUSB302_TKN_SYNC1 = 0x12,
FUSB302_TKN_SYNC2 = 0x13,
FUSB302_TKN_SYNC3 = 0x1B,
FUSB302_TKN_RST1 = 0x15,
FUSB302_TKN_RST2 = 0x16,
FUSB302_TKN_PACKSYM = 0x80,
FUSB302_TKN_JAMCRC = 0xFF,
FUSB302_TKN_EOP = 0x14,
FUSB302_TKN_TXOFF = 0xFE,
};
#endif
| CSE3320/kernel-code | linux-5.8/drivers/usb/typec/tcpm/fusb302_reg.h | C | gpl-2.0 | 6,760 |
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// Must not be included from any .h files to avoid polluting the namespace
// with macros.
#ifndef STORAGE_LEVELDB_UTIL_LOGGING_H_
#define STORAGE_LEVELDB_UTIL_LOGGING_H_
#include <stdio.h>
#include <stdint.h>
#include <string>
#include "port/port.h"
namespace leveldb {
class Slice;
class WritableFile;
// Append a human-readable printout of "num" to *str
extern void AppendNumberTo(std::string* str, uint64_t num);
// Append a human-readable printout of "value" to *str.
// Escapes any non-printable characters found in "value".
extern void AppendEscapedStringTo(std::string* str, const Slice& value);
// Return a human-readable printout of "num"
extern std::string NumberToString(uint64_t num);
// Return a human-readable version of "value".
// Escapes any non-printable characters found in "value".
extern std::string EscapeString(const Slice& value);
// If *in starts with "c", advances *in past the first character and
// returns true. Otherwise, returns false.
extern bool ConsumeChar(Slice* in, char c);
// Parse a human-readable number from "*in" into *value. On success,
// advances "*in" past the consumed number and sets "*val" to the
// numeric value. Otherwise, returns false and leaves *in in an
// unspecified state.
extern bool ConsumeDecimalNumber(Slice* in, uint64_t* val);
} // namespace leveldb
#endif // STORAGE_LEVELDB_UTIL_LOGGING_H_
| Noah-Huppert/Website-2013 | vhosts/www.noahhuppert.com/htdocs/trex/deps/leveldb/util/logging.h | C | mit | 1,594 |
This file has moved to [https://github.com/kubernetes/community/blob/master/contributors/design-proposals/federation-lite.md](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/federation-lite.md)
| aweiteka/cri-o | vendor/k8s.io/kubernetes/docs/proposals/federation-lite.md | Markdown | apache-2.0 | 228 |
require "openssl"
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
module Integrations #:nodoc:
module Dwolla
module Common
def verify_signature(checkoutId, amount, notification_signature, secret)
if secret.nil?
raise ArgumentError, "You need to provide the Application secret as the option :credential3 to verify that the notification originated from Dwolla"
end
expected_signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, "%s&%.2f" % [checkoutId, amount])
if notification_signature != expected_signature
raise StandardError, "Dwolla signature verification failed."
end
end
end
end
end
end
end
| jinutm/silvfinal | vendor/bundle/ruby/2.1.0/gems/activemerchant-1.42.4/lib/active_merchant/billing/integrations/dwolla/common.rb | Ruby | mit | 772 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.analysis;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.payloads.*;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.assistedinject.Assisted;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
/**
*
*/
public class DelimitedPayloadTokenFilterFactory extends AbstractTokenFilterFactory {
public static final char DEFAULT_DELIMITER = '|';
public static final PayloadEncoder DEFAULT_ENCODER = new FloatEncoder();
static final String ENCODING = "encoding";
static final String DELIMITER = "delimiter";
char delimiter;
PayloadEncoder encoder;
@Inject
public DelimitedPayloadTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name,
@Assisted Settings settings) {
super(index, indexSettings, name, settings);
String delimiterConf = settings.get(DELIMITER);
if (delimiterConf != null) {
delimiter = delimiterConf.charAt(0);
} else {
delimiter = DEFAULT_DELIMITER;
}
if (settings.get(ENCODING) != null) {
if (settings.get(ENCODING).equals("float")) {
encoder = new FloatEncoder();
} else if (settings.get(ENCODING).equals("int")) {
encoder = new IntegerEncoder();
} else if (settings.get(ENCODING).equals("identity")) {
encoder = new IdentityEncoder();
}
} else {
encoder = DEFAULT_ENCODER;
}
}
@Override
public TokenStream create(TokenStream tokenStream) {
DelimitedPayloadTokenFilter filter = new DelimitedPayloadTokenFilter(tokenStream, delimiter, encoder);
return filter;
}
}
| mkis-/elasticsearch | src/main/java/org/elasticsearch/index/analysis/DelimitedPayloadTokenFilterFactory.java | Java | apache-2.0 | 2,762 |
var name;
switch (name) {
case "Kamol":
doSomething();
default:
doSomethingElse();
}
switch (name) {
default:
doSomethingElse();
break;
case "Kamol":
doSomething();
} | bryantaylor/Epic | wp-content/themes/epic/node_modules/grunt-contrib-jshint/node_modules/jshint/tests/stable/unit/fixtures/switchDefaultFirst.js | JavaScript | gpl-2.0 | 173 |
require "language/java"
class JavaRequirement < Requirement
fatal true
cask "java"
download "http://www.oracle.com/technetwork/java/javase/downloads/index.html"
satisfy :build_env => false do
args = %w[--failfast]
args << "--version" << "#{@version}" if @version
@java_home = Utils.popen_read("/usr/libexec/java_home", *args).chomp
$?.success?
end
env do
java_home = Pathname.new(@java_home)
ENV["JAVA_HOME"] = java_home
ENV.prepend_path "PATH", java_home/"bin"
if (java_home/"include").exist? # Oracle JVM
ENV.append_to_cflags "-I#{java_home}/include"
ENV.append_to_cflags "-I#{java_home}/include/darwin"
else # Apple JVM
ENV.append_to_cflags "-I/System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/"
end
end
def initialize(tags)
@version = tags.shift if /(\d\.)+\d/ === tags.first
super
end
def message
version_string = " #{@version}" if @version
s = "Java#{version_string} is required to install this formula."
s += super
s
end
def inspect
"#<#{self.class.name}: #{name.inspect} #{tags.inspect} version=#{@version.inspect}>"
end
end
| rokn/Count_Words_2015 | fetched_code/ruby/java_requirement.rb | Ruby | mit | 1,171 |
/*
* linux/drivers/i2c/chips/twl4030-power.c
*
* Handle TWL4030 Power initialization
*
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2006 Texas Instruments, Inc
*
* Written by Kalle Jokiniemi
* Peter De Schrijver <peter.de-schrijver@nokia.com>
* Several fixes by Amit Kucheria <amit.kucheria@verdurent.com>
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file "COPYING" in the main directory of this
* archive for more details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/pm.h>
#include <linux/i2c/twl.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <asm/mach-types.h>
static u8 twl4030_start_script_address = 0x2b;
/* Register bits for P1, P2 and P3_SW_EVENTS */
#define PWR_STOPON_PRWON BIT(6)
#define PWR_STOPON_SYSEN BIT(5)
#define PWR_ENABLE_WARMRESET BIT(4)
#define PWR_LVL_WAKEUP BIT(3)
#define PWR_DEVACT BIT(2)
#define PWR_DEVSLP BIT(1)
#define PWR_DEVOFF BIT(0)
/* Register bits for CFG_P1_TRANSITION (also for P2 and P3) */
#define STARTON_SWBUG BIT(7) /* Start on watchdog */
#define STARTON_VBUS BIT(5) /* Start on VBUS */
#define STARTON_VBAT BIT(4) /* Start on battery insert */
#define STARTON_RTC BIT(3) /* Start on RTC */
#define STARTON_USB BIT(2) /* Start on USB host */
#define STARTON_CHG BIT(1) /* Start on charger */
#define STARTON_PWON BIT(0) /* Start on PWRON button */
#define SEQ_OFFSYNC (1 << 0)
#define PHY_TO_OFF_PM_MASTER(p) (p - 0x36)
#define PHY_TO_OFF_PM_RECEIVER(p) (p - 0x5b)
/* resource - hfclk */
#define R_HFCLKOUT_DEV_GRP PHY_TO_OFF_PM_RECEIVER(0xe6)
/* PM events */
#define R_P1_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x46)
#define R_P2_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x47)
#define R_P3_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x48)
#define R_CFG_P1_TRANSITION PHY_TO_OFF_PM_MASTER(0x36)
#define R_CFG_P2_TRANSITION PHY_TO_OFF_PM_MASTER(0x37)
#define R_CFG_P3_TRANSITION PHY_TO_OFF_PM_MASTER(0x38)
#define END_OF_SCRIPT 0x3f
#define R_SEQ_ADD_A2S PHY_TO_OFF_PM_MASTER(0x55)
#define R_SEQ_ADD_S2A12 PHY_TO_OFF_PM_MASTER(0x56)
#define R_SEQ_ADD_S2A3 PHY_TO_OFF_PM_MASTER(0x57)
#define R_SEQ_ADD_WARM PHY_TO_OFF_PM_MASTER(0x58)
#define R_MEMORY_ADDRESS PHY_TO_OFF_PM_MASTER(0x59)
#define R_MEMORY_DATA PHY_TO_OFF_PM_MASTER(0x5a)
/* resource configuration registers
<RESOURCE>_DEV_GRP at address 'n+0'
<RESOURCE>_TYPE at address 'n+1'
<RESOURCE>_REMAP at address 'n+2'
<RESOURCE>_DEDICATED at address 'n+3'
*/
#define DEV_GRP_OFFSET 0
#define TYPE_OFFSET 1
#define REMAP_OFFSET 2
#define DEDICATED_OFFSET 3
/* Bit positions in the registers */
/* <RESOURCE>_DEV_GRP */
#define DEV_GRP_SHIFT 5
#define DEV_GRP_MASK (7 << DEV_GRP_SHIFT)
/* <RESOURCE>_TYPE */
#define TYPE_SHIFT 0
#define TYPE_MASK (7 << TYPE_SHIFT)
#define TYPE2_SHIFT 3
#define TYPE2_MASK (3 << TYPE2_SHIFT)
/* <RESOURCE>_REMAP */
#define SLEEP_STATE_SHIFT 0
#define SLEEP_STATE_MASK (0xf << SLEEP_STATE_SHIFT)
#define OFF_STATE_SHIFT 4
#define OFF_STATE_MASK (0xf << OFF_STATE_SHIFT)
static u8 res_config_addrs[] = {
[RES_VAUX1] = 0x17,
[RES_VAUX2] = 0x1b,
[RES_VAUX3] = 0x1f,
[RES_VAUX4] = 0x23,
[RES_VMMC1] = 0x27,
[RES_VMMC2] = 0x2b,
[RES_VPLL1] = 0x2f,
[RES_VPLL2] = 0x33,
[RES_VSIM] = 0x37,
[RES_VDAC] = 0x3b,
[RES_VINTANA1] = 0x3f,
[RES_VINTANA2] = 0x43,
[RES_VINTDIG] = 0x47,
[RES_VIO] = 0x4b,
[RES_VDD1] = 0x55,
[RES_VDD2] = 0x63,
[RES_VUSB_1V5] = 0x71,
[RES_VUSB_1V8] = 0x74,
[RES_VUSB_3V1] = 0x77,
[RES_VUSBCP] = 0x7a,
[RES_REGEN] = 0x7f,
[RES_NRES_PWRON] = 0x82,
[RES_CLKEN] = 0x85,
[RES_SYSEN] = 0x88,
[RES_HFCLKOUT] = 0x8b,
[RES_32KCLKOUT] = 0x8e,
[RES_RESET] = 0x91,
[RES_MAIN_REF] = 0x94,
};
/*
* Usable values for .remap_sleep and .remap_off
* Based on table "5.3.3 Resource Operating modes"
*/
enum {
TWL_REMAP_OFF = 0,
TWL_REMAP_SLEEP = 8,
TWL_REMAP_ACTIVE = 9,
};
/*
* Macros to configure the PM register states for various resources.
* Note that we can make MSG_SINGULAR etc private to this driver once
* omap3 has been made DT only.
*/
#define TWL_DFLT_DELAY 2 /* typically 2 32 KiHz cycles */
#define TWL_DEV_GRP_P123 (DEV_GRP_P1 | DEV_GRP_P2 | DEV_GRP_P3)
#define TWL_RESOURCE_SET(res, state) \
{ MSG_SINGULAR(DEV_GRP_NULL, (res), (state)), TWL_DFLT_DELAY }
#define TWL_RESOURCE_ON(res) TWL_RESOURCE_SET(res, RES_STATE_ACTIVE)
#define TWL_RESOURCE_OFF(res) TWL_RESOURCE_SET(res, RES_STATE_OFF)
#define TWL_RESOURCE_RESET(res) TWL_RESOURCE_SET(res, RES_STATE_WRST)
/*
* It seems that type1 and type2 is just the resource init order
* number for the type1 and type2 group.
*/
#define TWL_RESOURCE_SET_ACTIVE(res, state) \
{ MSG_SINGULAR(DEV_GRP_NULL, (res), RES_STATE_ACTIVE), (state) }
#define TWL_RESOURCE_GROUP_RESET(group, type1, type2) \
{ MSG_BROADCAST(DEV_GRP_NULL, (group), (type1), (type2), \
RES_STATE_WRST), TWL_DFLT_DELAY }
#define TWL_RESOURCE_GROUP_SLEEP(group, type, type2) \
{ MSG_BROADCAST(DEV_GRP_NULL, (group), (type), (type2), \
RES_STATE_SLEEP), TWL_DFLT_DELAY }
#define TWL_RESOURCE_GROUP_ACTIVE(group, type, type2) \
{ MSG_BROADCAST(DEV_GRP_NULL, (group), (type), (type2), \
RES_STATE_ACTIVE), TWL_DFLT_DELAY }
#define TWL_REMAP_SLEEP(res, devgrp, typ, typ2) \
{ .resource = (res), .devgroup = (devgrp), \
.type = (typ), .type2 = (typ2), \
.remap_off = TWL_REMAP_OFF, \
.remap_sleep = TWL_REMAP_SLEEP, }
#define TWL_REMAP_OFF(res, devgrp, typ, typ2) \
{ .resource = (res), .devgroup = (devgrp), \
.type = (typ), .type2 = (typ2), \
.remap_off = TWL_REMAP_OFF, .remap_sleep = TWL_REMAP_OFF, }
static int twl4030_write_script_byte(u8 address, u8 byte)
{
int err;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, address, R_MEMORY_ADDRESS);
if (err)
goto out;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, byte, R_MEMORY_DATA);
out:
return err;
}
static int twl4030_write_script_ins(u8 address, u16 pmb_message,
u8 delay, u8 next)
{
int err;
address *= 4;
err = twl4030_write_script_byte(address++, pmb_message >> 8);
if (err)
goto out;
err = twl4030_write_script_byte(address++, pmb_message & 0xff);
if (err)
goto out;
err = twl4030_write_script_byte(address++, delay);
if (err)
goto out;
err = twl4030_write_script_byte(address++, next);
out:
return err;
}
static int twl4030_write_script(u8 address, struct twl4030_ins *script,
int len)
{
int err = -EINVAL;
for (; len; len--, address++, script++) {
if (len == 1) {
err = twl4030_write_script_ins(address,
script->pmb_message,
script->delay,
END_OF_SCRIPT);
if (err)
break;
} else {
err = twl4030_write_script_ins(address,
script->pmb_message,
script->delay,
address + 1);
if (err)
break;
}
}
return err;
}
static int twl4030_config_wakeup3_sequence(u8 address)
{
int err;
u8 data;
/* Set SLEEP to ACTIVE SEQ address for P3 */
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, address, R_SEQ_ADD_S2A3);
if (err)
goto out;
/* P3 LVL_WAKEUP should be on LEVEL */
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &data, R_P3_SW_EVENTS);
if (err)
goto out;
data |= PWR_LVL_WAKEUP;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, data, R_P3_SW_EVENTS);
out:
if (err)
pr_err("TWL4030 wakeup sequence for P3 config error\n");
return err;
}
static int twl4030_config_wakeup12_sequence(u8 address)
{
int err = 0;
u8 data;
/* Set SLEEP to ACTIVE SEQ address for P1 and P2 */
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, address, R_SEQ_ADD_S2A12);
if (err)
goto out;
/* P1/P2 LVL_WAKEUP should be on LEVEL */
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &data, R_P1_SW_EVENTS);
if (err)
goto out;
data |= PWR_LVL_WAKEUP;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, data, R_P1_SW_EVENTS);
if (err)
goto out;
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &data, R_P2_SW_EVENTS);
if (err)
goto out;
data |= PWR_LVL_WAKEUP;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, data, R_P2_SW_EVENTS);
if (err)
goto out;
if (machine_is_omap_3430sdp() || machine_is_omap_ldp()) {
/* Disabling AC charger effect on sleep-active transitions */
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &data,
R_CFG_P1_TRANSITION);
if (err)
goto out;
data &= ~(1<<1);
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, data,
R_CFG_P1_TRANSITION);
if (err)
goto out;
}
out:
if (err)
pr_err("TWL4030 wakeup sequence for P1 and P2" \
"config error\n");
return err;
}
static int twl4030_config_sleep_sequence(u8 address)
{
int err;
/* Set ACTIVE to SLEEP SEQ address in T2 memory*/
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, address, R_SEQ_ADD_A2S);
if (err)
pr_err("TWL4030 sleep sequence config error\n");
return err;
}
static int twl4030_config_warmreset_sequence(u8 address)
{
int err;
u8 rd_data;
/* Set WARM RESET SEQ address for P1 */
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, address, R_SEQ_ADD_WARM);
if (err)
goto out;
/* P1/P2/P3 enable WARMRESET */
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &rd_data, R_P1_SW_EVENTS);
if (err)
goto out;
rd_data |= PWR_ENABLE_WARMRESET;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, rd_data, R_P1_SW_EVENTS);
if (err)
goto out;
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &rd_data, R_P2_SW_EVENTS);
if (err)
goto out;
rd_data |= PWR_ENABLE_WARMRESET;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, rd_data, R_P2_SW_EVENTS);
if (err)
goto out;
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &rd_data, R_P3_SW_EVENTS);
if (err)
goto out;
rd_data |= PWR_ENABLE_WARMRESET;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, rd_data, R_P3_SW_EVENTS);
out:
if (err)
pr_err("TWL4030 warmreset seq config error\n");
return err;
}
static int twl4030_configure_resource(struct twl4030_resconfig *rconfig)
{
int rconfig_addr;
int err;
u8 type;
u8 grp;
u8 remap;
if (rconfig->resource > TOTAL_RESOURCES) {
pr_err("TWL4030 Resource %d does not exist\n",
rconfig->resource);
return -EINVAL;
}
rconfig_addr = res_config_addrs[rconfig->resource];
/* Set resource group */
err = twl_i2c_read_u8(TWL_MODULE_PM_RECEIVER, &grp,
rconfig_addr + DEV_GRP_OFFSET);
if (err) {
pr_err("TWL4030 Resource %d group could not be read\n",
rconfig->resource);
return err;
}
if (rconfig->devgroup != TWL4030_RESCONFIG_UNDEF) {
grp &= ~DEV_GRP_MASK;
grp |= rconfig->devgroup << DEV_GRP_SHIFT;
err = twl_i2c_write_u8(TWL_MODULE_PM_RECEIVER,
grp, rconfig_addr + DEV_GRP_OFFSET);
if (err < 0) {
pr_err("TWL4030 failed to program devgroup\n");
return err;
}
}
/* Set resource types */
err = twl_i2c_read_u8(TWL_MODULE_PM_RECEIVER, &type,
rconfig_addr + TYPE_OFFSET);
if (err < 0) {
pr_err("TWL4030 Resource %d type could not be read\n",
rconfig->resource);
return err;
}
if (rconfig->type != TWL4030_RESCONFIG_UNDEF) {
type &= ~TYPE_MASK;
type |= rconfig->type << TYPE_SHIFT;
}
if (rconfig->type2 != TWL4030_RESCONFIG_UNDEF) {
type &= ~TYPE2_MASK;
type |= rconfig->type2 << TYPE2_SHIFT;
}
err = twl_i2c_write_u8(TWL_MODULE_PM_RECEIVER,
type, rconfig_addr + TYPE_OFFSET);
if (err < 0) {
pr_err("TWL4030 failed to program resource type\n");
return err;
}
/* Set remap states */
err = twl_i2c_read_u8(TWL_MODULE_PM_RECEIVER, &remap,
rconfig_addr + REMAP_OFFSET);
if (err < 0) {
pr_err("TWL4030 Resource %d remap could not be read\n",
rconfig->resource);
return err;
}
if (rconfig->remap_off != TWL4030_RESCONFIG_UNDEF) {
remap &= ~OFF_STATE_MASK;
remap |= rconfig->remap_off << OFF_STATE_SHIFT;
}
if (rconfig->remap_sleep != TWL4030_RESCONFIG_UNDEF) {
remap &= ~SLEEP_STATE_MASK;
remap |= rconfig->remap_sleep << SLEEP_STATE_SHIFT;
}
err = twl_i2c_write_u8(TWL_MODULE_PM_RECEIVER,
remap,
rconfig_addr + REMAP_OFFSET);
if (err < 0) {
pr_err("TWL4030 failed to program remap\n");
return err;
}
return 0;
}
static int load_twl4030_script(struct twl4030_script *tscript,
u8 address)
{
int err;
static int order;
/* Make sure the script isn't going beyond last valid address (0x3f) */
if ((address + tscript->size) > END_OF_SCRIPT) {
pr_err("TWL4030 scripts too big error\n");
return -EINVAL;
}
err = twl4030_write_script(address, tscript->script, tscript->size);
if (err)
goto out;
if (tscript->flags & TWL4030_WRST_SCRIPT) {
err = twl4030_config_warmreset_sequence(address);
if (err)
goto out;
}
if (tscript->flags & TWL4030_WAKEUP12_SCRIPT) {
/* Reset any existing sleep script to avoid hangs on reboot */
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, END_OF_SCRIPT,
R_SEQ_ADD_A2S);
if (err)
goto out;
err = twl4030_config_wakeup12_sequence(address);
if (err)
goto out;
order = 1;
}
if (tscript->flags & TWL4030_WAKEUP3_SCRIPT) {
err = twl4030_config_wakeup3_sequence(address);
if (err)
goto out;
}
if (tscript->flags & TWL4030_SLEEP_SCRIPT) {
if (!order)
pr_warning("TWL4030: Bad order of scripts (sleep "\
"script before wakeup) Leads to boot"\
"failure on some boards\n");
err = twl4030_config_sleep_sequence(address);
}
out:
return err;
}
int twl4030_remove_script(u8 flags)
{
int err = 0;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, TWL4030_PM_MASTER_KEY_CFG1,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err) {
pr_err("twl4030: unable to unlock PROTECT_KEY\n");
return err;
}
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, TWL4030_PM_MASTER_KEY_CFG2,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err) {
pr_err("twl4030: unable to unlock PROTECT_KEY\n");
return err;
}
if (flags & TWL4030_WRST_SCRIPT) {
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, END_OF_SCRIPT,
R_SEQ_ADD_WARM);
if (err)
return err;
}
if (flags & TWL4030_WAKEUP12_SCRIPT) {
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, END_OF_SCRIPT,
R_SEQ_ADD_S2A12);
if (err)
return err;
}
if (flags & TWL4030_WAKEUP3_SCRIPT) {
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, END_OF_SCRIPT,
R_SEQ_ADD_S2A3);
if (err)
return err;
}
if (flags & TWL4030_SLEEP_SCRIPT) {
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, END_OF_SCRIPT,
R_SEQ_ADD_A2S);
if (err)
return err;
}
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, 0,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err)
pr_err("TWL4030 Unable to relock registers\n");
return err;
}
static int
twl4030_power_configure_scripts(const struct twl4030_power_data *pdata)
{
int err;
int i;
u8 address = twl4030_start_script_address;
for (i = 0; i < pdata->num; i++) {
err = load_twl4030_script(pdata->scripts[i], address);
if (err)
return err;
address += pdata->scripts[i]->size;
}
return 0;
}
static void twl4030_patch_rconfig(struct twl4030_resconfig *common,
struct twl4030_resconfig *board)
{
while (common->resource) {
struct twl4030_resconfig *b = board;
while (b->resource) {
if (b->resource == common->resource) {
*common = *b;
break;
}
b++;
}
common++;
}
}
static int
twl4030_power_configure_resources(const struct twl4030_power_data *pdata)
{
struct twl4030_resconfig *resconfig = pdata->resource_config;
struct twl4030_resconfig *boardconf = pdata->board_config;
int err;
if (resconfig) {
if (boardconf)
twl4030_patch_rconfig(resconfig, boardconf);
while (resconfig->resource) {
err = twl4030_configure_resource(resconfig);
if (err)
return err;
resconfig++;
}
}
return 0;
}
static int twl4030_starton_mask_and_set(u8 bitmask, u8 bitvalues)
{
u8 regs[3] = { TWL4030_PM_MASTER_CFG_P1_TRANSITION,
TWL4030_PM_MASTER_CFG_P2_TRANSITION,
TWL4030_PM_MASTER_CFG_P3_TRANSITION, };
u8 val;
int i, err;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, TWL4030_PM_MASTER_KEY_CFG1,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err)
goto relock;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER,
TWL4030_PM_MASTER_KEY_CFG2,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err)
goto relock;
for (i = 0; i < sizeof(regs); i++) {
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER,
&val, regs[i]);
if (err)
break;
val = (~bitmask & val) | (bitmask & bitvalues);
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER,
val, regs[i]);
if (err)
break;
}
if (err)
pr_err("TWL4030 Register access failed: %i\n", err);
relock:
return twl_i2c_write_u8(TWL_MODULE_PM_MASTER, 0,
TWL4030_PM_MASTER_PROTECT_KEY);
}
/*
* In master mode, start the power off sequence.
* After a successful execution, TWL shuts down the power to the SoC
* and all peripherals connected to it.
*/
void twl4030_power_off(void)
{
int err;
/* Disable start on charger or VBUS as it can break poweroff */
err = twl4030_starton_mask_and_set(STARTON_VBUS | STARTON_CHG, 0);
if (err)
pr_err("TWL4030 Unable to configure start-up\n");
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, PWR_DEVOFF,
TWL4030_PM_MASTER_P1_SW_EVENTS);
if (err)
pr_err("TWL4030 Unable to power off\n");
}
static bool twl4030_power_use_poweroff(const struct twl4030_power_data *pdata,
struct device_node *node)
{
if (pdata && pdata->use_poweroff)
return true;
if (of_property_read_bool(node, "ti,system-power-controller"))
return true;
if (of_property_read_bool(node, "ti,use_poweroff"))
return true;
return false;
}
#ifdef CONFIG_OF
/* Generic warm reset configuration for omap3 */
static struct twl4030_ins omap3_wrst_seq[] = {
TWL_RESOURCE_OFF(RES_NRES_PWRON),
TWL_RESOURCE_OFF(RES_RESET),
TWL_RESOURCE_RESET(RES_MAIN_REF),
TWL_RESOURCE_GROUP_RESET(RES_GRP_ALL, RES_TYPE_R0, RES_TYPE2_R2),
TWL_RESOURCE_RESET(RES_VUSB_3V1),
TWL_RESOURCE_GROUP_RESET(RES_GRP_ALL, RES_TYPE_R0, RES_TYPE2_R1),
TWL_RESOURCE_GROUP_RESET(RES_GRP_RC, RES_TYPE_ALL, RES_TYPE2_R0),
TWL_RESOURCE_ON(RES_RESET),
TWL_RESOURCE_ON(RES_NRES_PWRON),
};
static struct twl4030_script omap3_wrst_script = {
.script = omap3_wrst_seq,
.size = ARRAY_SIZE(omap3_wrst_seq),
.flags = TWL4030_WRST_SCRIPT,
};
static struct twl4030_script *omap3_reset_scripts[] = {
&omap3_wrst_script,
};
static struct twl4030_resconfig omap3_rconfig[] = {
TWL_REMAP_SLEEP(RES_HFCLKOUT, DEV_GRP_P3, -1, -1),
TWL_REMAP_SLEEP(RES_VDD1, DEV_GRP_P1, -1, -1),
TWL_REMAP_SLEEP(RES_VDD2, DEV_GRP_P1, -1, -1),
{ 0, 0 },
};
static struct twl4030_power_data omap3_reset = {
.scripts = omap3_reset_scripts,
.num = ARRAY_SIZE(omap3_reset_scripts),
.resource_config = omap3_rconfig,
};
/* Recommended generic default idle configuration for off-idle */
/* Broadcast message to put res to sleep */
static struct twl4030_ins omap3_idle_sleep_on_seq[] = {
TWL_RESOURCE_GROUP_SLEEP(RES_GRP_ALL, RES_TYPE_ALL, 0),
};
static struct twl4030_script omap3_idle_sleep_on_script = {
.script = omap3_idle_sleep_on_seq,
.size = ARRAY_SIZE(omap3_idle_sleep_on_seq),
.flags = TWL4030_SLEEP_SCRIPT,
};
/* Broadcast message to put res to active */
static struct twl4030_ins omap3_idle_wakeup_p12_seq[] = {
TWL_RESOURCE_GROUP_ACTIVE(RES_GRP_ALL, RES_TYPE_ALL, 0),
};
static struct twl4030_script omap3_idle_wakeup_p12_script = {
.script = omap3_idle_wakeup_p12_seq,
.size = ARRAY_SIZE(omap3_idle_wakeup_p12_seq),
.flags = TWL4030_WAKEUP12_SCRIPT,
};
/* Broadcast message to put res to active */
static struct twl4030_ins omap3_idle_wakeup_p3_seq[] = {
TWL_RESOURCE_SET_ACTIVE(RES_CLKEN, 0x37),
TWL_RESOURCE_GROUP_ACTIVE(RES_GRP_ALL, RES_TYPE_ALL, 0),
};
static struct twl4030_script omap3_idle_wakeup_p3_script = {
.script = omap3_idle_wakeup_p3_seq,
.size = ARRAY_SIZE(omap3_idle_wakeup_p3_seq),
.flags = TWL4030_WAKEUP3_SCRIPT,
};
static struct twl4030_script *omap3_idle_scripts[] = {
&omap3_idle_wakeup_p12_script,
&omap3_idle_wakeup_p3_script,
&omap3_wrst_script,
&omap3_idle_sleep_on_script,
};
/*
* Recommended configuration based on "Recommended Sleep
* Sequences for the Zoom Platform":
* http://omappedia.com/wiki/File:Recommended_Sleep_Sequences_Zoom.pdf
* Note that the type1 and type2 seem to be just the init order number
* for type1 and type2 groups as specified in the document mentioned
* above.
*/
static struct twl4030_resconfig omap3_idle_rconfig[] = {
TWL_REMAP_SLEEP(RES_VAUX1, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VAUX2, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VAUX3, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VAUX4, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VMMC1, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VMMC2, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_OFF(RES_VPLL1, DEV_GRP_P1, 3, 1),
TWL_REMAP_SLEEP(RES_VPLL2, DEV_GRP_P1, 0, 0),
TWL_REMAP_SLEEP(RES_VSIM, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VDAC, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VINTANA1, TWL_DEV_GRP_P123, 1, 2),
TWL_REMAP_SLEEP(RES_VINTANA2, TWL_DEV_GRP_P123, 0, 2),
TWL_REMAP_SLEEP(RES_VINTDIG, TWL_DEV_GRP_P123, 1, 2),
TWL_REMAP_SLEEP(RES_VIO, TWL_DEV_GRP_P123, 2, 2),
TWL_REMAP_OFF(RES_VDD1, DEV_GRP_P1, 4, 1),
TWL_REMAP_OFF(RES_VDD2, DEV_GRP_P1, 3, 1),
TWL_REMAP_SLEEP(RES_VUSB_1V5, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VUSB_1V8, TWL4030_RESCONFIG_UNDEF, 0, 0),
TWL_REMAP_SLEEP(RES_VUSB_3V1, TWL_DEV_GRP_P123, 0, 0),
/* Resource #20 USB charge pump skipped */
TWL_REMAP_SLEEP(RES_REGEN, TWL_DEV_GRP_P123, 2, 1),
TWL_REMAP_SLEEP(RES_NRES_PWRON, TWL_DEV_GRP_P123, 0, 1),
TWL_REMAP_SLEEP(RES_CLKEN, TWL_DEV_GRP_P123, 3, 2),
TWL_REMAP_SLEEP(RES_SYSEN, TWL_DEV_GRP_P123, 6, 1),
TWL_REMAP_SLEEP(RES_HFCLKOUT, DEV_GRP_P3, 0, 2),
TWL_REMAP_SLEEP(RES_32KCLKOUT, TWL_DEV_GRP_P123, 0, 0),
TWL_REMAP_SLEEP(RES_RESET, TWL_DEV_GRP_P123, 6, 0),
TWL_REMAP_SLEEP(RES_MAIN_REF, TWL_DEV_GRP_P123, 0, 0),
{ /* Terminator */ },
};
static struct twl4030_power_data omap3_idle = {
.scripts = omap3_idle_scripts,
.num = ARRAY_SIZE(omap3_idle_scripts),
.resource_config = omap3_idle_rconfig,
};
/* Disable 32 KiHz oscillator during idle */
static struct twl4030_resconfig osc_off_rconfig[] = {
TWL_REMAP_OFF(RES_CLKEN, DEV_GRP_P1 | DEV_GRP_P3, 3, 2),
{ /* Terminator */ },
};
static struct twl4030_power_data osc_off_idle = {
.scripts = omap3_idle_scripts,
.num = ARRAY_SIZE(omap3_idle_scripts),
.resource_config = omap3_idle_rconfig,
.board_config = osc_off_rconfig,
};
static struct of_device_id twl4030_power_of_match[] = {
{
.compatible = "ti,twl4030-power",
},
{
.compatible = "ti,twl4030-power-reset",
.data = &omap3_reset,
},
{
.compatible = "ti,twl4030-power-idle",
.data = &omap3_idle,
},
{
.compatible = "ti,twl4030-power-idle-osc-off",
.data = &osc_off_idle,
},
{ },
};
MODULE_DEVICE_TABLE(of, twl4030_power_of_match);
#endif /* CONFIG_OF */
static int twl4030_power_probe(struct platform_device *pdev)
{
const struct twl4030_power_data *pdata = dev_get_platdata(&pdev->dev);
struct device_node *node = pdev->dev.of_node;
const struct of_device_id *match;
int err = 0;
int err2 = 0;
u8 val;
if (!pdata && !node) {
dev_err(&pdev->dev, "Platform data is missing\n");
return -EINVAL;
}
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, TWL4030_PM_MASTER_KEY_CFG1,
TWL4030_PM_MASTER_PROTECT_KEY);
err |= twl_i2c_write_u8(TWL_MODULE_PM_MASTER,
TWL4030_PM_MASTER_KEY_CFG2,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err) {
pr_err("TWL4030 Unable to unlock registers\n");
return err;
}
match = of_match_device(of_match_ptr(twl4030_power_of_match),
&pdev->dev);
if (match && match->data)
pdata = match->data;
if (pdata) {
err = twl4030_power_configure_scripts(pdata);
if (err) {
pr_err("TWL4030 failed to load scripts\n");
goto relock;
}
err = twl4030_power_configure_resources(pdata);
if (err) {
pr_err("TWL4030 failed to configure resource\n");
goto relock;
}
}
/* Board has to be wired properly to use this feature */
if (twl4030_power_use_poweroff(pdata, node) && !pm_power_off) {
/* Default for SEQ_OFFSYNC is set, lets ensure this */
err = twl_i2c_read_u8(TWL_MODULE_PM_MASTER, &val,
TWL4030_PM_MASTER_CFG_P123_TRANSITION);
if (err) {
pr_warning("TWL4030 Unable to read registers\n");
} else if (!(val & SEQ_OFFSYNC)) {
val |= SEQ_OFFSYNC;
err = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, val,
TWL4030_PM_MASTER_CFG_P123_TRANSITION);
if (err) {
pr_err("TWL4030 Unable to setup SEQ_OFFSYNC\n");
goto relock;
}
}
pm_power_off = twl4030_power_off;
}
relock:
err2 = twl_i2c_write_u8(TWL_MODULE_PM_MASTER, 0,
TWL4030_PM_MASTER_PROTECT_KEY);
if (err2) {
pr_err("TWL4030 Unable to relock registers\n");
return err2;
}
return err;
}
static int twl4030_power_remove(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver twl4030_power_driver = {
.driver = {
.name = "twl4030_power",
.of_match_table = of_match_ptr(twl4030_power_of_match),
},
.probe = twl4030_power_probe,
.remove = twl4030_power_remove,
};
module_platform_driver(twl4030_power_driver);
MODULE_AUTHOR("Nokia Corporation");
MODULE_AUTHOR("Texas Instruments, Inc.");
MODULE_DESCRIPTION("Power management for TWL4030");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:twl4030_power");
| systemdaemon/systemd | src/linux/drivers/mfd/twl4030-power.c | C | gpl-2.0 | 25,688 |
// { dg-do assemble }
// Copyright (C) 2000 Free Software Foundation
// by Alexandre Oliva <aoliva@cygnus.com>
// distilled from libg++'s Fix.cc
struct Integer {
~Integer () {}
};
void foo (const Integer& y);
Integer bar (const Integer& x);
void show (const Integer& x) {
foo (bar (x));
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.oliva/stkalign.C | C++ | gpl-2.0 | 299 |
/* SPDX-License-Identifier: GPL-2.0 or BSD-3-Clause */
/* Authors: Bernard Metzler <bmt@zurich.ibm.com> */
/* Copyright (c) 2008-2019, IBM Corporation */
#ifndef _SIW_MEM_H
#define _SIW_MEM_H
struct siw_umem *siw_umem_get(u64 start, u64 len, bool writable);
void siw_umem_release(struct siw_umem *umem, bool dirty);
struct siw_pbl *siw_pbl_alloc(u32 num_buf);
dma_addr_t siw_pbl_get_buffer(struct siw_pbl *pbl, u64 off, int *len, int *idx);
struct siw_mem *siw_mem_id2obj(struct siw_device *sdev, int stag_index);
int siw_mem_add(struct siw_device *sdev, struct siw_mem *m);
int siw_invalidate_stag(struct ib_pd *pd, u32 stag);
int siw_check_mem(struct ib_pd *pd, struct siw_mem *mem, u64 addr,
enum ib_access_flags perms, int len);
int siw_check_sge(struct ib_pd *pd, struct siw_sge *sge,
struct siw_mem *mem[], enum ib_access_flags perms,
u32 off, int len);
void siw_wqe_put_mem(struct siw_wqe *wqe, enum siw_opcode op);
int siw_mr_add_mem(struct siw_mr *mr, struct ib_pd *pd, void *mem_obj,
u64 start, u64 len, int rights);
void siw_mr_drop_mem(struct siw_mr *mr);
void siw_free_mem(struct kref *ref);
static inline void siw_mem_put(struct siw_mem *mem)
{
kref_put(&mem->ref, siw_free_mem);
}
static inline struct siw_mr *siw_mem2mr(struct siw_mem *m)
{
return container_of(m, struct siw_mr, mem);
}
static inline void siw_unref_mem_sgl(struct siw_mem **mem, unsigned int num_sge)
{
while (num_sge) {
if (*mem == NULL)
break;
siw_mem_put(*mem);
*mem = NULL;
mem++;
num_sge--;
}
}
#define CHUNK_SHIFT 9 /* sets number of pages per chunk */
#define PAGES_PER_CHUNK (_AC(1, UL) << CHUNK_SHIFT)
#define CHUNK_MASK (~(PAGES_PER_CHUNK - 1))
#define PAGE_CHUNK_SIZE (PAGES_PER_CHUNK * sizeof(struct page *))
/*
* siw_get_upage()
*
* Get page pointer for address on given umem.
*
* @umem: two dimensional list of page pointers
* @addr: user virtual address
*/
static inline struct page *siw_get_upage(struct siw_umem *umem, u64 addr)
{
unsigned int page_idx = (addr - umem->fp_addr) >> PAGE_SHIFT,
chunk_idx = page_idx >> CHUNK_SHIFT,
page_in_chunk = page_idx & ~CHUNK_MASK;
if (likely(page_idx < umem->num_pages))
return umem->page_chunk[chunk_idx].plist[page_in_chunk];
return NULL;
}
#endif
| CSE3320/kernel-code | linux-5.8/drivers/infiniband/sw/siw/siw_mem.h | C | gpl-2.0 | 2,260 |
// { dg-do assemble }
// GROUPS passed patches
// patches file
// From: david.binderman@pmsr.philips.co.uk
// Date: Wed, 6 Oct 93 17:05:54 BST
// Subject: Reno 1.2 bug fix
// Message-ID: <9310061605.AA04160@pmsr.philips.co.uk>
int type(float) { return 1; }
int type(double) { return 2; }
int type(long double) { return 3; }
extern "C" int printf( const char *, ...);
int main()
{
int i = 0;
if (type(0.0) != 2)
++i;
if (i > 0)
{ printf ("FAIL\n"); return 1; }
else
printf ("PASS\n");
}
| SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.law/patches1.C | C++ | gpl-2.0 | 546 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the class for restore of this submission plugin
*
* @package assignsubmission_file
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Restore subplugin class.
*
* Provides the necessary information
* needed to restore one assign_submission subplugin.
*
* @package assignsubmission_file
* @copyright 2012 NetSpot {@link http://www.netspot.com.au}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_assignsubmission_file_subplugin extends restore_subplugin {
/**
* Returns the paths to be handled by the subplugin at workshop level
* @return array
*/
protected function define_submission_subplugin_structure() {
$paths = array();
$elename = $this->get_namefor('submission');
$elepath = $this->get_pathfor('/submission_file');
// We used get_recommended_name() so this works.
$paths[] = new restore_path_element($elename, $elepath);
return $paths;
}
/**
* Processes one submission_file element
* @param mixed $data
* @return void
*/
public function process_assignsubmission_file_submission($data) {
global $DB;
$data = (object)$data;
$data->assignment = $this->get_new_parentid('assign');
$oldsubmissionid = $data->submission;
// The mapping is set in the restore for the core assign activity
// when a submission node is processed.
$data->submission = $this->get_mappingid('submission', $data->submission);
$DB->insert_record('assignsubmission_file', $data);
$this->add_related_files('assignsubmission_file',
'submission_files',
'submission',
null,
$oldsubmissionid);
}
}
| ernestovi/ups | moodle/mod/assign/submission/file/backup/moodle2/restore_assignsubmission_file_subplugin.class.php | PHP | gpl-3.0 | 2,645 |
<?php
/*
* This file is part of the Assetic package, an OpenSky project.
*
* (c) 2010-2013 OpenSky Project Inc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Assetic\Factory\Resource;
/**
* A resource is something formulae can be loaded from.
*
* @author Kris Wallsmith <kris.wallsmith@gmail.com>
*/
interface IteratorResourceInterface extends ResourceInterface, \IteratorAggregate
{
}
| nickopris/musicapp | www/core/vendor/kriswallsmith/assetic/src/Assetic/Factory/Resource/IteratorResourceInterface.php | PHP | apache-2.0 | 493 |
/*
* Driver for ESS Solo-1 (ES1938, ES1946, ES1969) soundcard
* Copyright (c) by Jaromir Koutek <miri@punknet.cz>,
* Jaroslav Kysela <perex@perex.cz>,
* Thomas Sailer <sailer@ife.ee.ethz.ch>,
* Abramo Bagnara <abramo@alsa-project.org>,
* Markus Gruber <gruber@eikon.tum.de>
*
* Rewritten from sonicvibes.c source.
*
* TODO:
* Rewrite better spinlocks
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
NOTES:
- Capture data is written unaligned starting from dma_base + 1 so I need to
disable mmap and to add a copy callback.
- After several cycle of the following:
while : ; do arecord -d1 -f cd -t raw | aplay -f cd ; done
a "playback write error (DMA or IRQ trouble?)" may happen.
This is due to playback interrupts not generated.
I suspect a timing issue.
- Sometimes the interrupt handler is invoked wrongly during playback.
This generates some harmless "Unexpected hw_pointer: wrong interrupt
acknowledge".
I've seen that using small period sizes.
Reproducible with:
mpg123 test.mp3 &
hdparm -t -T /dev/hda
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/opl3.h>
#include <sound/mpu401.h>
#include <sound/initval.h>
#include <sound/tlv.h>
MODULE_AUTHOR("Jaromir Koutek <miri@punknet.cz>");
MODULE_DESCRIPTION("ESS Solo-1");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ESS,ES1938},"
"{ESS,ES1946},"
"{ESS,ES1969},"
"{TerraTec,128i PCI}}");
#if defined(CONFIG_GAMEPORT) || (defined(MODULE) && defined(CONFIG_GAMEPORT_MODULE))
#define SUPPORT_JOYSTICK 1
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for ESS Solo-1 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for ESS Solo-1 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable ESS Solo-1 soundcard.");
#define SLIO_REG(chip, x) ((chip)->io_port + ESSIO_REG_##x)
#define SLDM_REG(chip, x) ((chip)->ddma_port + ESSDM_REG_##x)
#define SLSB_REG(chip, x) ((chip)->sb_port + ESSSB_REG_##x)
#define SL_PCI_LEGACYCONTROL 0x40
#define SL_PCI_CONFIG 0x50
#define SL_PCI_DDMACONTROL 0x60
#define ESSIO_REG_AUDIO2DMAADDR 0
#define ESSIO_REG_AUDIO2DMACOUNT 4
#define ESSIO_REG_AUDIO2MODE 6
#define ESSIO_REG_IRQCONTROL 7
#define ESSDM_REG_DMAADDR 0x00
#define ESSDM_REG_DMACOUNT 0x04
#define ESSDM_REG_DMACOMMAND 0x08
#define ESSDM_REG_DMASTATUS 0x08
#define ESSDM_REG_DMAMODE 0x0b
#define ESSDM_REG_DMACLEAR 0x0d
#define ESSDM_REG_DMAMASK 0x0f
#define ESSSB_REG_FMLOWADDR 0x00
#define ESSSB_REG_FMHIGHADDR 0x02
#define ESSSB_REG_MIXERADDR 0x04
#define ESSSB_REG_MIXERDATA 0x05
#define ESSSB_IREG_AUDIO1 0x14
#define ESSSB_IREG_MICMIX 0x1a
#define ESSSB_IREG_RECSRC 0x1c
#define ESSSB_IREG_MASTER 0x32
#define ESSSB_IREG_FM 0x36
#define ESSSB_IREG_AUXACD 0x38
#define ESSSB_IREG_AUXB 0x3a
#define ESSSB_IREG_PCSPEAKER 0x3c
#define ESSSB_IREG_LINE 0x3e
#define ESSSB_IREG_SPATCONTROL 0x50
#define ESSSB_IREG_SPATLEVEL 0x52
#define ESSSB_IREG_MASTER_LEFT 0x60
#define ESSSB_IREG_MASTER_RIGHT 0x62
#define ESSSB_IREG_MPU401CONTROL 0x64
#define ESSSB_IREG_MICMIXRECORD 0x68
#define ESSSB_IREG_AUDIO2RECORD 0x69
#define ESSSB_IREG_AUXACDRECORD 0x6a
#define ESSSB_IREG_FMRECORD 0x6b
#define ESSSB_IREG_AUXBRECORD 0x6c
#define ESSSB_IREG_MONO 0x6d
#define ESSSB_IREG_LINERECORD 0x6e
#define ESSSB_IREG_MONORECORD 0x6f
#define ESSSB_IREG_AUDIO2SAMPLE 0x70
#define ESSSB_IREG_AUDIO2MODE 0x71
#define ESSSB_IREG_AUDIO2FILTER 0x72
#define ESSSB_IREG_AUDIO2TCOUNTL 0x74
#define ESSSB_IREG_AUDIO2TCOUNTH 0x76
#define ESSSB_IREG_AUDIO2CONTROL1 0x78
#define ESSSB_IREG_AUDIO2CONTROL2 0x7a
#define ESSSB_IREG_AUDIO2 0x7c
#define ESSSB_REG_RESET 0x06
#define ESSSB_REG_READDATA 0x0a
#define ESSSB_REG_WRITEDATA 0x0c
#define ESSSB_REG_READSTATUS 0x0c
#define ESSSB_REG_STATUS 0x0e
#define ESS_CMD_EXTSAMPLERATE 0xa1
#define ESS_CMD_FILTERDIV 0xa2
#define ESS_CMD_DMACNTRELOADL 0xa4
#define ESS_CMD_DMACNTRELOADH 0xa5
#define ESS_CMD_ANALOGCONTROL 0xa8
#define ESS_CMD_IRQCONTROL 0xb1
#define ESS_CMD_DRQCONTROL 0xb2
#define ESS_CMD_RECLEVEL 0xb4
#define ESS_CMD_SETFORMAT 0xb6
#define ESS_CMD_SETFORMAT2 0xb7
#define ESS_CMD_DMACONTROL 0xb8
#define ESS_CMD_DMATYPE 0xb9
#define ESS_CMD_OFFSETLEFT 0xba
#define ESS_CMD_OFFSETRIGHT 0xbb
#define ESS_CMD_READREG 0xc0
#define ESS_CMD_ENABLEEXT 0xc6
#define ESS_CMD_PAUSEDMA 0xd0
#define ESS_CMD_ENABLEAUDIO1 0xd1
#define ESS_CMD_STOPAUDIO1 0xd3
#define ESS_CMD_AUDIO1STATUS 0xd8
#define ESS_CMD_CONTDMA 0xd4
#define ESS_CMD_TESTIRQ 0xf2
#define ESS_RECSRC_MIC 0
#define ESS_RECSRC_AUXACD 2
#define ESS_RECSRC_AUXB 5
#define ESS_RECSRC_LINE 6
#define ESS_RECSRC_NONE 7
#define DAC1 0x01
#define ADC1 0x02
#define DAC2 0x04
/*
*/
#define SAVED_REG_SIZE 32 /* max. number of registers to save */
struct es1938 {
int irq;
unsigned long io_port;
unsigned long sb_port;
unsigned long vc_port;
unsigned long mpu_port;
unsigned long game_port;
unsigned long ddma_port;
unsigned char irqmask;
unsigned char revision;
struct snd_kcontrol *hw_volume;
struct snd_kcontrol *hw_switch;
struct snd_kcontrol *master_volume;
struct snd_kcontrol *master_switch;
struct pci_dev *pci;
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *capture_substream;
struct snd_pcm_substream *playback1_substream;
struct snd_pcm_substream *playback2_substream;
struct snd_rawmidi *rmidi;
unsigned int dma1_size;
unsigned int dma2_size;
unsigned int dma1_start;
unsigned int dma2_start;
unsigned int dma1_shift;
unsigned int dma2_shift;
unsigned int last_capture_dmaaddr;
unsigned int active;
spinlock_t reg_lock;
spinlock_t mixer_lock;
struct snd_info_entry *proc_entry;
#ifdef SUPPORT_JOYSTICK
struct gameport *gameport;
#endif
#ifdef CONFIG_PM_SLEEP
unsigned char saved_regs[SAVED_REG_SIZE];
#endif
};
static irqreturn_t snd_es1938_interrupt(int irq, void *dev_id);
static const struct pci_device_id snd_es1938_ids[] = {
{ PCI_VDEVICE(ESS, 0x1969), 0, }, /* Solo-1 */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_es1938_ids);
#define RESET_LOOP_TIMEOUT 0x10000
#define WRITE_LOOP_TIMEOUT 0x10000
#define GET_LOOP_TIMEOUT 0x01000
/* -----------------------------------------------------------------
* Write to a mixer register
* -----------------------------------------------------------------*/
static void snd_es1938_mixer_write(struct es1938 *chip, unsigned char reg, unsigned char val)
{
unsigned long flags;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, SLSB_REG(chip, MIXERADDR));
outb(val, SLSB_REG(chip, MIXERDATA));
spin_unlock_irqrestore(&chip->mixer_lock, flags);
dev_dbg(chip->card->dev, "Mixer reg %02x set to %02x\n", reg, val);
}
/* -----------------------------------------------------------------
* Read from a mixer register
* -----------------------------------------------------------------*/
static int snd_es1938_mixer_read(struct es1938 *chip, unsigned char reg)
{
int data;
unsigned long flags;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, SLSB_REG(chip, MIXERADDR));
data = inb(SLSB_REG(chip, MIXERDATA));
spin_unlock_irqrestore(&chip->mixer_lock, flags);
dev_dbg(chip->card->dev, "Mixer reg %02x now is %02x\n", reg, data);
return data;
}
/* -----------------------------------------------------------------
* Write to some bits of a mixer register (return old value)
* -----------------------------------------------------------------*/
static int snd_es1938_mixer_bits(struct es1938 *chip, unsigned char reg,
unsigned char mask, unsigned char val)
{
unsigned long flags;
unsigned char old, new, oval;
spin_lock_irqsave(&chip->mixer_lock, flags);
outb(reg, SLSB_REG(chip, MIXERADDR));
old = inb(SLSB_REG(chip, MIXERDATA));
oval = old & mask;
if (val != oval) {
new = (old & ~mask) | (val & mask);
outb(new, SLSB_REG(chip, MIXERDATA));
dev_dbg(chip->card->dev,
"Mixer reg %02x was %02x, set to %02x\n",
reg, old, new);
}
spin_unlock_irqrestore(&chip->mixer_lock, flags);
return oval;
}
/* -----------------------------------------------------------------
* Write command to Controller Registers
* -----------------------------------------------------------------*/
static void snd_es1938_write_cmd(struct es1938 *chip, unsigned char cmd)
{
int i;
unsigned char v;
for (i = 0; i < WRITE_LOOP_TIMEOUT; i++) {
if (!(v = inb(SLSB_REG(chip, READSTATUS)) & 0x80)) {
outb(cmd, SLSB_REG(chip, WRITEDATA));
return;
}
}
dev_err(chip->card->dev,
"snd_es1938_write_cmd timeout (0x02%x/0x02%x)\n", cmd, v);
}
/* -----------------------------------------------------------------
* Read the Read Data Buffer
* -----------------------------------------------------------------*/
static int snd_es1938_get_byte(struct es1938 *chip)
{
int i;
unsigned char v;
for (i = GET_LOOP_TIMEOUT; i; i--)
if ((v = inb(SLSB_REG(chip, STATUS))) & 0x80)
return inb(SLSB_REG(chip, READDATA));
dev_err(chip->card->dev, "get_byte timeout: status 0x02%x\n", v);
return -ENODEV;
}
/* -----------------------------------------------------------------
* Write value cmd register
* -----------------------------------------------------------------*/
static void snd_es1938_write(struct es1938 *chip, unsigned char reg, unsigned char val)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
snd_es1938_write_cmd(chip, reg);
snd_es1938_write_cmd(chip, val);
spin_unlock_irqrestore(&chip->reg_lock, flags);
dev_dbg(chip->card->dev, "Reg %02x set to %02x\n", reg, val);
}
/* -----------------------------------------------------------------
* Read data from cmd register and return it
* -----------------------------------------------------------------*/
static unsigned char snd_es1938_read(struct es1938 *chip, unsigned char reg)
{
unsigned char val;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
snd_es1938_write_cmd(chip, ESS_CMD_READREG);
snd_es1938_write_cmd(chip, reg);
val = snd_es1938_get_byte(chip);
spin_unlock_irqrestore(&chip->reg_lock, flags);
dev_dbg(chip->card->dev, "Reg %02x now is %02x\n", reg, val);
return val;
}
/* -----------------------------------------------------------------
* Write data to cmd register and return old value
* -----------------------------------------------------------------*/
static int snd_es1938_bits(struct es1938 *chip, unsigned char reg, unsigned char mask,
unsigned char val)
{
unsigned long flags;
unsigned char old, new, oval;
spin_lock_irqsave(&chip->reg_lock, flags);
snd_es1938_write_cmd(chip, ESS_CMD_READREG);
snd_es1938_write_cmd(chip, reg);
old = snd_es1938_get_byte(chip);
oval = old & mask;
if (val != oval) {
snd_es1938_write_cmd(chip, reg);
new = (old & ~mask) | (val & mask);
snd_es1938_write_cmd(chip, new);
dev_dbg(chip->card->dev, "Reg %02x was %02x, set to %02x\n",
reg, old, new);
}
spin_unlock_irqrestore(&chip->reg_lock, flags);
return oval;
}
/* --------------------------------------------------------------------
* Reset the chip
* --------------------------------------------------------------------*/
static void snd_es1938_reset(struct es1938 *chip)
{
int i;
outb(3, SLSB_REG(chip, RESET));
inb(SLSB_REG(chip, RESET));
outb(0, SLSB_REG(chip, RESET));
for (i = 0; i < RESET_LOOP_TIMEOUT; i++) {
if (inb(SLSB_REG(chip, STATUS)) & 0x80) {
if (inb(SLSB_REG(chip, READDATA)) == 0xaa)
goto __next;
}
}
dev_err(chip->card->dev, "ESS Solo-1 reset failed\n");
__next:
snd_es1938_write_cmd(chip, ESS_CMD_ENABLEEXT);
/* Demand transfer DMA: 4 bytes per DMA request */
snd_es1938_write(chip, ESS_CMD_DMATYPE, 2);
/* Change behaviour of register A1
4x oversampling
2nd channel DAC asynchronous */
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2MODE, 0x32);
/* enable/select DMA channel and IRQ channel */
snd_es1938_bits(chip, ESS_CMD_IRQCONTROL, 0xf0, 0x50);
snd_es1938_bits(chip, ESS_CMD_DRQCONTROL, 0xf0, 0x50);
snd_es1938_write_cmd(chip, ESS_CMD_ENABLEAUDIO1);
/* Set spatializer parameters to recommended values */
snd_es1938_mixer_write(chip, 0x54, 0x8f);
snd_es1938_mixer_write(chip, 0x56, 0x95);
snd_es1938_mixer_write(chip, 0x58, 0x94);
snd_es1938_mixer_write(chip, 0x5a, 0x80);
}
/* --------------------------------------------------------------------
* Reset the FIFOs
* --------------------------------------------------------------------*/
static void snd_es1938_reset_fifo(struct es1938 *chip)
{
outb(2, SLSB_REG(chip, RESET));
outb(0, SLSB_REG(chip, RESET));
}
static struct snd_ratnum clocks[2] = {
{
.num = 793800,
.den_min = 1,
.den_max = 128,
.den_step = 1,
},
{
.num = 768000,
.den_min = 1,
.den_max = 128,
.den_step = 1,
}
};
static struct snd_pcm_hw_constraint_ratnums hw_constraints_clocks = {
.nrats = 2,
.rats = clocks,
};
static void snd_es1938_rate_set(struct es1938 *chip,
struct snd_pcm_substream *substream,
int mode)
{
unsigned int bits, div0;
struct snd_pcm_runtime *runtime = substream->runtime;
if (runtime->rate_num == clocks[0].num)
bits = 128 - runtime->rate_den;
else
bits = 256 - runtime->rate_den;
/* set filter register */
div0 = 256 - 7160000*20/(8*82*runtime->rate);
if (mode == DAC2) {
snd_es1938_mixer_write(chip, 0x70, bits);
snd_es1938_mixer_write(chip, 0x72, div0);
} else {
snd_es1938_write(chip, 0xA1, bits);
snd_es1938_write(chip, 0xA2, div0);
}
}
/* --------------------------------------------------------------------
* Configure Solo1 builtin DMA Controller
* --------------------------------------------------------------------*/
static void snd_es1938_playback1_setdma(struct es1938 *chip)
{
outb(0x00, SLIO_REG(chip, AUDIO2MODE));
outl(chip->dma2_start, SLIO_REG(chip, AUDIO2DMAADDR));
outw(0, SLIO_REG(chip, AUDIO2DMACOUNT));
outw(chip->dma2_size, SLIO_REG(chip, AUDIO2DMACOUNT));
}
static void snd_es1938_playback2_setdma(struct es1938 *chip)
{
/* Enable DMA controller */
outb(0xc4, SLDM_REG(chip, DMACOMMAND));
/* 1. Master reset */
outb(0, SLDM_REG(chip, DMACLEAR));
/* 2. Mask DMA */
outb(1, SLDM_REG(chip, DMAMASK));
outb(0x18, SLDM_REG(chip, DMAMODE));
outl(chip->dma1_start, SLDM_REG(chip, DMAADDR));
outw(chip->dma1_size - 1, SLDM_REG(chip, DMACOUNT));
/* 3. Unmask DMA */
outb(0, SLDM_REG(chip, DMAMASK));
}
static void snd_es1938_capture_setdma(struct es1938 *chip)
{
/* Enable DMA controller */
outb(0xc4, SLDM_REG(chip, DMACOMMAND));
/* 1. Master reset */
outb(0, SLDM_REG(chip, DMACLEAR));
/* 2. Mask DMA */
outb(1, SLDM_REG(chip, DMAMASK));
outb(0x14, SLDM_REG(chip, DMAMODE));
outl(chip->dma1_start, SLDM_REG(chip, DMAADDR));
chip->last_capture_dmaaddr = chip->dma1_start;
outw(chip->dma1_size - 1, SLDM_REG(chip, DMACOUNT));
/* 3. Unmask DMA */
outb(0, SLDM_REG(chip, DMAMASK));
}
/* ----------------------------------------------------------------------
*
* *** PCM part ***
*/
static int snd_es1938_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
int val;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
val = 0x0f;
chip->active |= ADC1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
val = 0x00;
chip->active &= ~ADC1;
break;
default:
return -EINVAL;
}
snd_es1938_write(chip, ESS_CMD_DMACONTROL, val);
return 0;
}
static int snd_es1938_playback1_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
/* According to the documentation this should be:
0x13 but that value may randomly swap stereo channels */
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2CONTROL1, 0x92);
udelay(10);
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2CONTROL1, 0x93);
/* This two stage init gives the FIFO -> DAC connection time to
* settle before first data from DMA flows in. This should ensure
* no swapping of stereo channels. Report a bug if otherwise :-) */
outb(0x0a, SLIO_REG(chip, AUDIO2MODE));
chip->active |= DAC2;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
outb(0, SLIO_REG(chip, AUDIO2MODE));
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2CONTROL1, 0);
chip->active &= ~DAC2;
break;
default:
return -EINVAL;
}
return 0;
}
static int snd_es1938_playback2_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
int val;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
val = 5;
chip->active |= DAC1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
val = 0;
chip->active &= ~DAC1;
break;
default:
return -EINVAL;
}
snd_es1938_write(chip, ESS_CMD_DMACONTROL, val);
return 0;
}
static int snd_es1938_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
switch (substream->number) {
case 0:
return snd_es1938_playback1_trigger(substream, cmd);
case 1:
return snd_es1938_playback2_trigger(substream, cmd);
}
snd_BUG();
return -EINVAL;
}
/* --------------------------------------------------------------------
* First channel for Extended Mode Audio 1 ADC Operation
* --------------------------------------------------------------------*/
static int snd_es1938_capture_prepare(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int u, is8, mono;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
chip->dma1_size = size;
chip->dma1_start = runtime->dma_addr;
mono = (runtime->channels > 1) ? 0 : 1;
is8 = snd_pcm_format_width(runtime->format) == 16 ? 0 : 1;
u = snd_pcm_format_unsigned(runtime->format);
chip->dma1_shift = 2 - mono - is8;
snd_es1938_reset_fifo(chip);
/* program type */
snd_es1938_bits(chip, ESS_CMD_ANALOGCONTROL, 0x03, (mono ? 2 : 1));
/* set clock and counters */
snd_es1938_rate_set(chip, substream, ADC1);
count = 0x10000 - count;
snd_es1938_write(chip, ESS_CMD_DMACNTRELOADL, count & 0xff);
snd_es1938_write(chip, ESS_CMD_DMACNTRELOADH, count >> 8);
/* initialize and configure ADC */
snd_es1938_write(chip, ESS_CMD_SETFORMAT2, u ? 0x51 : 0x71);
snd_es1938_write(chip, ESS_CMD_SETFORMAT2, 0x90 |
(u ? 0x00 : 0x20) |
(is8 ? 0x00 : 0x04) |
(mono ? 0x40 : 0x08));
// snd_es1938_reset_fifo(chip);
/* 11. configure system interrupt controller and DMA controller */
snd_es1938_capture_setdma(chip);
return 0;
}
/* ------------------------------------------------------------------------------
* Second Audio channel DAC Operation
* ------------------------------------------------------------------------------*/
static int snd_es1938_playback1_prepare(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int u, is8, mono;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
chip->dma2_size = size;
chip->dma2_start = runtime->dma_addr;
mono = (runtime->channels > 1) ? 0 : 1;
is8 = snd_pcm_format_width(runtime->format) == 16 ? 0 : 1;
u = snd_pcm_format_unsigned(runtime->format);
chip->dma2_shift = 2 - mono - is8;
snd_es1938_reset_fifo(chip);
/* set clock and counters */
snd_es1938_rate_set(chip, substream, DAC2);
count >>= 1;
count = 0x10000 - count;
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2TCOUNTL, count & 0xff);
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2TCOUNTH, count >> 8);
/* initialize and configure Audio 2 DAC */
snd_es1938_mixer_write(chip, ESSSB_IREG_AUDIO2CONTROL2, 0x40 | (u ? 0 : 4) |
(mono ? 0 : 2) | (is8 ? 0 : 1));
/* program DMA */
snd_es1938_playback1_setdma(chip);
return 0;
}
static int snd_es1938_playback2_prepare(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int u, is8, mono;
unsigned int size = snd_pcm_lib_buffer_bytes(substream);
unsigned int count = snd_pcm_lib_period_bytes(substream);
chip->dma1_size = size;
chip->dma1_start = runtime->dma_addr;
mono = (runtime->channels > 1) ? 0 : 1;
is8 = snd_pcm_format_width(runtime->format) == 16 ? 0 : 1;
u = snd_pcm_format_unsigned(runtime->format);
chip->dma1_shift = 2 - mono - is8;
count = 0x10000 - count;
/* reset */
snd_es1938_reset_fifo(chip);
snd_es1938_bits(chip, ESS_CMD_ANALOGCONTROL, 0x03, (mono ? 2 : 1));
/* set clock and counters */
snd_es1938_rate_set(chip, substream, DAC1);
snd_es1938_write(chip, ESS_CMD_DMACNTRELOADL, count & 0xff);
snd_es1938_write(chip, ESS_CMD_DMACNTRELOADH, count >> 8);
/* initialized and configure DAC */
snd_es1938_write(chip, ESS_CMD_SETFORMAT, u ? 0x80 : 0x00);
snd_es1938_write(chip, ESS_CMD_SETFORMAT, u ? 0x51 : 0x71);
snd_es1938_write(chip, ESS_CMD_SETFORMAT2,
0x90 | (mono ? 0x40 : 0x08) |
(is8 ? 0x00 : 0x04) | (u ? 0x00 : 0x20));
/* program DMA */
snd_es1938_playback2_setdma(chip);
return 0;
}
static int snd_es1938_playback_prepare(struct snd_pcm_substream *substream)
{
switch (substream->number) {
case 0:
return snd_es1938_playback1_prepare(substream);
case 1:
return snd_es1938_playback2_prepare(substream);
}
snd_BUG();
return -EINVAL;
}
/* during the incrementing of dma counters the DMA register reads sometimes
returns garbage. To ensure a valid hw pointer, the following checks which
should be very unlikely to fail are used:
- is the current DMA address in the valid DMA range ?
- is the sum of DMA address and DMA counter pointing to the last DMA byte ?
One can argue this could differ by one byte depending on which register is
updated first, so the implementation below allows for that.
*/
static snd_pcm_uframes_t snd_es1938_capture_pointer(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
size_t ptr;
#if 0
size_t old, new;
/* This stuff is *needed*, don't ask why - AB */
old = inw(SLDM_REG(chip, DMACOUNT));
while ((new = inw(SLDM_REG(chip, DMACOUNT))) != old)
old = new;
ptr = chip->dma1_size - 1 - new;
#else
size_t count;
unsigned int diff;
ptr = inl(SLDM_REG(chip, DMAADDR));
count = inw(SLDM_REG(chip, DMACOUNT));
diff = chip->dma1_start + chip->dma1_size - ptr - count;
if (diff > 3 || ptr < chip->dma1_start
|| ptr >= chip->dma1_start+chip->dma1_size)
ptr = chip->last_capture_dmaaddr; /* bad, use last saved */
else
chip->last_capture_dmaaddr = ptr; /* good, remember it */
ptr -= chip->dma1_start;
#endif
return ptr >> chip->dma1_shift;
}
static snd_pcm_uframes_t snd_es1938_playback1_pointer(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
size_t ptr;
#if 1
ptr = chip->dma2_size - inw(SLIO_REG(chip, AUDIO2DMACOUNT));
#else
ptr = inl(SLIO_REG(chip, AUDIO2DMAADDR)) - chip->dma2_start;
#endif
return ptr >> chip->dma2_shift;
}
static snd_pcm_uframes_t snd_es1938_playback2_pointer(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
size_t ptr;
size_t old, new;
#if 1
/* This stuff is *needed*, don't ask why - AB */
old = inw(SLDM_REG(chip, DMACOUNT));
while ((new = inw(SLDM_REG(chip, DMACOUNT))) != old)
old = new;
ptr = chip->dma1_size - 1 - new;
#else
ptr = inl(SLDM_REG(chip, DMAADDR)) - chip->dma1_start;
#endif
return ptr >> chip->dma1_shift;
}
static snd_pcm_uframes_t snd_es1938_playback_pointer(struct snd_pcm_substream *substream)
{
switch (substream->number) {
case 0:
return snd_es1938_playback1_pointer(substream);
case 1:
return snd_es1938_playback2_pointer(substream);
}
snd_BUG();
return -EINVAL;
}
static int snd_es1938_capture_copy(struct snd_pcm_substream *substream,
int channel,
snd_pcm_uframes_t pos,
void __user *dst,
snd_pcm_uframes_t count)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct es1938 *chip = snd_pcm_substream_chip(substream);
pos <<= chip->dma1_shift;
count <<= chip->dma1_shift;
if (snd_BUG_ON(pos + count > chip->dma1_size))
return -EINVAL;
if (pos + count < chip->dma1_size) {
if (copy_to_user(dst, runtime->dma_area + pos + 1, count))
return -EFAULT;
} else {
if (copy_to_user(dst, runtime->dma_area + pos + 1, count - 1))
return -EFAULT;
if (put_user(runtime->dma_area[0], ((unsigned char __user *)dst) + count - 1))
return -EFAULT;
}
return 0;
}
/*
* buffer management
*/
static int snd_es1938_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
int err;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
return 0;
}
static int snd_es1938_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
/* ----------------------------------------------------------------------
* Audio1 Capture (ADC)
* ----------------------------------------------------------------------*/
static struct snd_pcm_hardware snd_es1938_capture =
{
.info = (SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U16_LE),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 6000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 0x8000, /* DMA controller screws on higher values */
.period_bytes_min = 64,
.period_bytes_max = 0x8000,
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 256,
};
/* -----------------------------------------------------------------------
* Audio2 Playback (DAC)
* -----------------------------------------------------------------------*/
static struct snd_pcm_hardware snd_es1938_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_U16_LE),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 6000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 0x8000, /* DMA controller screws on higher values */
.period_bytes_min = 64,
.period_bytes_max = 0x8000,
.periods_min = 1,
.periods_max = 1024,
.fifo_size = 256,
};
static int snd_es1938_capture_open(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
if (chip->playback2_substream)
return -EAGAIN;
chip->capture_substream = substream;
runtime->hw = snd_es1938_capture;
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraints_clocks);
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 0, 0xff00);
return 0;
}
static int snd_es1938_playback_open(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
switch (substream->number) {
case 0:
chip->playback1_substream = substream;
break;
case 1:
if (chip->capture_substream)
return -EAGAIN;
chip->playback2_substream = substream;
break;
default:
snd_BUG();
return -EINVAL;
}
runtime->hw = snd_es1938_playback;
snd_pcm_hw_constraint_ratnums(runtime, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraints_clocks);
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 0, 0xff00);
return 0;
}
static int snd_es1938_capture_close(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
chip->capture_substream = NULL;
return 0;
}
static int snd_es1938_playback_close(struct snd_pcm_substream *substream)
{
struct es1938 *chip = snd_pcm_substream_chip(substream);
switch (substream->number) {
case 0:
chip->playback1_substream = NULL;
break;
case 1:
chip->playback2_substream = NULL;
break;
default:
snd_BUG();
return -EINVAL;
}
return 0;
}
static struct snd_pcm_ops snd_es1938_playback_ops = {
.open = snd_es1938_playback_open,
.close = snd_es1938_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_es1938_pcm_hw_params,
.hw_free = snd_es1938_pcm_hw_free,
.prepare = snd_es1938_playback_prepare,
.trigger = snd_es1938_playback_trigger,
.pointer = snd_es1938_playback_pointer,
};
static struct snd_pcm_ops snd_es1938_capture_ops = {
.open = snd_es1938_capture_open,
.close = snd_es1938_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_es1938_pcm_hw_params,
.hw_free = snd_es1938_pcm_hw_free,
.prepare = snd_es1938_capture_prepare,
.trigger = snd_es1938_capture_trigger,
.pointer = snd_es1938_capture_pointer,
.copy = snd_es1938_capture_copy,
};
static int snd_es1938_new_pcm(struct es1938 *chip, int device)
{
struct snd_pcm *pcm;
int err;
if ((err = snd_pcm_new(chip->card, "es-1938-1946", device, 2, 1, &pcm)) < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_es1938_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_es1938_capture_ops);
pcm->private_data = chip;
pcm->info_flags = 0;
strcpy(pcm->name, "ESS Solo-1");
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 64*1024);
chip->pcm = pcm;
return 0;
}
/* -------------------------------------------------------------------
*
* *** Mixer part ***
*/
static int snd_es1938_info_mux(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char * const texts[8] = {
"Mic", "Mic Master", "CD", "AOUT",
"Mic1", "Mix", "Line", "Master"
};
return snd_ctl_enum_info(uinfo, 1, 8, texts);
}
static int snd_es1938_get_mux(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = snd_es1938_mixer_read(chip, 0x1c) & 0x07;
return 0;
}
static int snd_es1938_put_mux(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
unsigned char val = ucontrol->value.enumerated.item[0];
if (val > 7)
return -EINVAL;
return snd_es1938_mixer_bits(chip, 0x1c, 0x07, val) != val;
}
#define snd_es1938_info_spatializer_enable snd_ctl_boolean_mono_info
static int snd_es1938_get_spatializer_enable(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
unsigned char val = snd_es1938_mixer_read(chip, 0x50);
ucontrol->value.integer.value[0] = !!(val & 8);
return 0;
}
static int snd_es1938_put_spatializer_enable(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
unsigned char oval, nval;
int change;
nval = ucontrol->value.integer.value[0] ? 0x0c : 0x04;
oval = snd_es1938_mixer_read(chip, 0x50) & 0x0c;
change = nval != oval;
if (change) {
snd_es1938_mixer_write(chip, 0x50, nval & ~0x04);
snd_es1938_mixer_write(chip, 0x50, nval);
}
return change;
}
static int snd_es1938_info_hw_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 63;
return 0;
}
static int snd_es1938_get_hw_volume(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = snd_es1938_mixer_read(chip, 0x61) & 0x3f;
ucontrol->value.integer.value[1] = snd_es1938_mixer_read(chip, 0x63) & 0x3f;
return 0;
}
#define snd_es1938_info_hw_switch snd_ctl_boolean_stereo_info
static int snd_es1938_get_hw_switch(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = !(snd_es1938_mixer_read(chip, 0x61) & 0x40);
ucontrol->value.integer.value[1] = !(snd_es1938_mixer_read(chip, 0x63) & 0x40);
return 0;
}
static void snd_es1938_hwv_free(struct snd_kcontrol *kcontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
chip->master_volume = NULL;
chip->master_switch = NULL;
chip->hw_volume = NULL;
chip->hw_switch = NULL;
}
static int snd_es1938_reg_bits(struct es1938 *chip, unsigned char reg,
unsigned char mask, unsigned char val)
{
if (reg < 0xa0)
return snd_es1938_mixer_bits(chip, reg, mask, val);
else
return snd_es1938_bits(chip, reg, mask, val);
}
static int snd_es1938_reg_read(struct es1938 *chip, unsigned char reg)
{
if (reg < 0xa0)
return snd_es1938_mixer_read(chip, reg);
else
return snd_es1938_read(chip, reg);
}
#define ES1938_SINGLE_TLV(xname, xindex, reg, shift, mask, invert, xtlv) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ,\
.name = xname, .index = xindex, \
.info = snd_es1938_info_single, \
.get = snd_es1938_get_single, .put = snd_es1938_put_single, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24), \
.tlv = { .p = xtlv } }
#define ES1938_SINGLE(xname, xindex, reg, shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_es1938_info_single, \
.get = snd_es1938_get_single, .put = snd_es1938_put_single, \
.private_value = reg | (shift << 8) | (mask << 16) | (invert << 24) }
static int snd_es1938_info_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 16) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_es1938_get_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int val;
val = snd_es1938_reg_read(chip, reg);
ucontrol->value.integer.value[0] = (val >> shift) & mask;
if (invert)
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
return 0;
}
static int snd_es1938_put_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
unsigned char val;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
mask <<= shift;
val <<= shift;
return snd_es1938_reg_bits(chip, reg, mask, val) != val;
}
#define ES1938_DOUBLE_TLV(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert, xtlv) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ,\
.name = xname, .index = xindex, \
.info = snd_es1938_info_double, \
.get = snd_es1938_get_double, .put = snd_es1938_put_double, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22), \
.tlv = { .p = xtlv } }
#define ES1938_DOUBLE(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_es1938_info_double, \
.get = snd_es1938_get_double, .put = snd_es1938_put_double, \
.private_value = left_reg | (right_reg << 8) | (shift_left << 16) | (shift_right << 19) | (mask << 24) | (invert << 22) }
static int snd_es1938_info_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 24) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_es1938_get_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
unsigned char left, right;
left = snd_es1938_reg_read(chip, left_reg);
if (left_reg != right_reg)
right = snd_es1938_reg_read(chip, right_reg);
else
right = left;
ucontrol->value.integer.value[0] = (left >> shift_left) & mask;
ucontrol->value.integer.value[1] = (right >> shift_right) & mask;
if (invert) {
ucontrol->value.integer.value[0] = mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] = mask - ucontrol->value.integer.value[1];
}
return 0;
}
static int snd_es1938_put_double(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct es1938 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change;
unsigned char val1, val2, mask1, mask2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
mask1 = mask << shift_left;
mask2 = mask << shift_right;
if (left_reg != right_reg) {
change = 0;
if (snd_es1938_reg_bits(chip, left_reg, mask1, val1) != val1)
change = 1;
if (snd_es1938_reg_bits(chip, right_reg, mask2, val2) != val2)
change = 1;
} else {
change = (snd_es1938_reg_bits(chip, left_reg, mask1 | mask2,
val1 | val2) != (val1 | val2));
}
return change;
}
static const DECLARE_TLV_DB_RANGE(db_scale_master,
0, 54, TLV_DB_SCALE_ITEM(-3600, 50, 1),
54, 63, TLV_DB_SCALE_ITEM(-900, 100, 0),
);
static const DECLARE_TLV_DB_RANGE(db_scale_audio1,
0, 8, TLV_DB_SCALE_ITEM(-3300, 300, 1),
8, 15, TLV_DB_SCALE_ITEM(-900, 150, 0),
);
static const DECLARE_TLV_DB_RANGE(db_scale_audio2,
0, 8, TLV_DB_SCALE_ITEM(-3450, 300, 1),
8, 15, TLV_DB_SCALE_ITEM(-1050, 150, 0),
);
static const DECLARE_TLV_DB_RANGE(db_scale_mic,
0, 8, TLV_DB_SCALE_ITEM(-2400, 300, 1),
8, 15, TLV_DB_SCALE_ITEM(0, 150, 0),
);
static const DECLARE_TLV_DB_RANGE(db_scale_line,
0, 8, TLV_DB_SCALE_ITEM(-3150, 300, 1),
8, 15, TLV_DB_SCALE_ITEM(-750, 150, 0),
);
static const DECLARE_TLV_DB_SCALE(db_scale_capture, 0, 150, 0);
static struct snd_kcontrol_new snd_es1938_controls[] = {
ES1938_DOUBLE_TLV("Master Playback Volume", 0, 0x60, 0x62, 0, 0, 63, 0,
db_scale_master),
ES1938_DOUBLE("Master Playback Switch", 0, 0x60, 0x62, 6, 6, 1, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Hardware Master Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = snd_es1938_info_hw_volume,
.get = snd_es1938_get_hw_volume,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READ |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Hardware Master Playback Switch",
.info = snd_es1938_info_hw_switch,
.get = snd_es1938_get_hw_switch,
.tlv = { .p = db_scale_master },
},
ES1938_SINGLE("Hardware Volume Split", 0, 0x64, 7, 1, 0),
ES1938_DOUBLE_TLV("Line Playback Volume", 0, 0x3e, 0x3e, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE("CD Playback Volume", 0, 0x38, 0x38, 4, 0, 15, 0),
ES1938_DOUBLE_TLV("FM Playback Volume", 0, 0x36, 0x36, 4, 0, 15, 0,
db_scale_mic),
ES1938_DOUBLE_TLV("Mono Playback Volume", 0, 0x6d, 0x6d, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("Mic Playback Volume", 0, 0x1a, 0x1a, 4, 0, 15, 0,
db_scale_mic),
ES1938_DOUBLE_TLV("Aux Playback Volume", 0, 0x3a, 0x3a, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("Capture Volume", 0, 0xb4, 0xb4, 4, 0, 15, 0,
db_scale_capture),
ES1938_SINGLE("Beep Volume", 0, 0x3c, 0, 7, 0),
ES1938_SINGLE("Record Monitor", 0, 0xa8, 3, 1, 0),
ES1938_SINGLE("Capture Switch", 0, 0x1c, 4, 1, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = snd_es1938_info_mux,
.get = snd_es1938_get_mux,
.put = snd_es1938_put_mux,
},
ES1938_DOUBLE_TLV("Mono Input Playback Volume", 0, 0x6d, 0x6d, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("PCM Capture Volume", 0, 0x69, 0x69, 4, 0, 15, 0,
db_scale_audio2),
ES1938_DOUBLE_TLV("Mic Capture Volume", 0, 0x68, 0x68, 4, 0, 15, 0,
db_scale_mic),
ES1938_DOUBLE_TLV("Line Capture Volume", 0, 0x6e, 0x6e, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("FM Capture Volume", 0, 0x6b, 0x6b, 4, 0, 15, 0,
db_scale_mic),
ES1938_DOUBLE_TLV("Mono Capture Volume", 0, 0x6f, 0x6f, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("CD Capture Volume", 0, 0x6a, 0x6a, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("Aux Capture Volume", 0, 0x6c, 0x6c, 4, 0, 15, 0,
db_scale_line),
ES1938_DOUBLE_TLV("PCM Playback Volume", 0, 0x7c, 0x7c, 4, 0, 15, 0,
db_scale_audio2),
ES1938_DOUBLE_TLV("PCM Playback Volume", 1, 0x14, 0x14, 4, 0, 15, 0,
db_scale_audio1),
ES1938_SINGLE("3D Control - Level", 0, 0x52, 0, 63, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "3D Control - Switch",
.info = snd_es1938_info_spatializer_enable,
.get = snd_es1938_get_spatializer_enable,
.put = snd_es1938_put_spatializer_enable,
},
ES1938_SINGLE("Mic Boost (+26dB)", 0, 0x7d, 3, 1, 0)
};
/* ---------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------- */
/*
* initialize the chip - used by resume callback, too
*/
static void snd_es1938_chip_init(struct es1938 *chip)
{
/* reset chip */
snd_es1938_reset(chip);
/* configure native mode */
/* enable bus master */
pci_set_master(chip->pci);
/* disable legacy audio */
pci_write_config_word(chip->pci, SL_PCI_LEGACYCONTROL, 0x805f);
/* set DDMA base */
pci_write_config_word(chip->pci, SL_PCI_DDMACONTROL, chip->ddma_port | 1);
/* set DMA/IRQ policy */
pci_write_config_dword(chip->pci, SL_PCI_CONFIG, 0);
/* enable Audio 1, Audio 2, MPU401 IRQ and HW volume IRQ*/
outb(0xf0, SLIO_REG(chip, IRQCONTROL));
/* reset DMA */
outb(0, SLDM_REG(chip, DMACLEAR));
}
#ifdef CONFIG_PM_SLEEP
/*
* PM support
*/
static unsigned char saved_regs[SAVED_REG_SIZE+1] = {
0x14, 0x1a, 0x1c, 0x3a, 0x3c, 0x3e, 0x36, 0x38,
0x50, 0x52, 0x60, 0x61, 0x62, 0x63, 0x64, 0x68,
0x69, 0x6a, 0x6b, 0x6d, 0x6e, 0x6f, 0x7c, 0x7d,
0xa8, 0xb4,
};
static int es1938_suspend(struct device *dev)
{
struct snd_card *card = dev_get_drvdata(dev);
struct es1938 *chip = card->private_data;
unsigned char *s, *d;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
/* save mixer-related registers */
for (s = saved_regs, d = chip->saved_regs; *s; s++, d++)
*d = snd_es1938_reg_read(chip, *s);
outb(0x00, SLIO_REG(chip, IRQCONTROL)); /* disable irqs */
if (chip->irq >= 0) {
free_irq(chip->irq, chip);
chip->irq = -1;
}
return 0;
}
static int es1938_resume(struct device *dev)
{
struct pci_dev *pci = to_pci_dev(dev);
struct snd_card *card = dev_get_drvdata(dev);
struct es1938 *chip = card->private_data;
unsigned char *s, *d;
if (request_irq(pci->irq, snd_es1938_interrupt,
IRQF_SHARED, KBUILD_MODNAME, chip)) {
dev_err(dev, "unable to grab IRQ %d, disabling device\n",
pci->irq);
snd_card_disconnect(card);
return -EIO;
}
chip->irq = pci->irq;
snd_es1938_chip_init(chip);
/* restore mixer-related registers */
for (s = saved_regs, d = chip->saved_regs; *s; s++, d++) {
if (*s < 0xa0)
snd_es1938_mixer_write(chip, *s, *d);
else
snd_es1938_write(chip, *s, *d);
}
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
static SIMPLE_DEV_PM_OPS(es1938_pm, es1938_suspend, es1938_resume);
#define ES1938_PM_OPS &es1938_pm
#else
#define ES1938_PM_OPS NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef SUPPORT_JOYSTICK
static int snd_es1938_create_gameport(struct es1938 *chip)
{
struct gameport *gp;
chip->gameport = gp = gameport_allocate_port();
if (!gp) {
dev_err(chip->card->dev,
"cannot allocate memory for gameport\n");
return -ENOMEM;
}
gameport_set_name(gp, "ES1938");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci));
gameport_set_dev_parent(gp, &chip->pci->dev);
gp->io = chip->game_port;
gameport_register_port(gp);
return 0;
}
static void snd_es1938_free_gameport(struct es1938 *chip)
{
if (chip->gameport) {
gameport_unregister_port(chip->gameport);
chip->gameport = NULL;
}
}
#else
static inline int snd_es1938_create_gameport(struct es1938 *chip) { return -ENOSYS; }
static inline void snd_es1938_free_gameport(struct es1938 *chip) { }
#endif /* SUPPORT_JOYSTICK */
static int snd_es1938_free(struct es1938 *chip)
{
/* disable irqs */
outb(0x00, SLIO_REG(chip, IRQCONTROL));
if (chip->rmidi)
snd_es1938_mixer_bits(chip, ESSSB_IREG_MPU401CONTROL, 0x40, 0);
snd_es1938_free_gameport(chip);
if (chip->irq >= 0)
free_irq(chip->irq, chip);
pci_release_regions(chip->pci);
pci_disable_device(chip->pci);
kfree(chip);
return 0;
}
static int snd_es1938_dev_free(struct snd_device *device)
{
struct es1938 *chip = device->device_data;
return snd_es1938_free(chip);
}
static int snd_es1938_create(struct snd_card *card,
struct pci_dev *pci,
struct es1938 **rchip)
{
struct es1938 *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_es1938_dev_free,
};
*rchip = NULL;
/* enable PCI device */
if ((err = pci_enable_device(pci)) < 0)
return err;
/* check, if we can restrict PCI DMA transfers to 24 bits */
if (dma_set_mask(&pci->dev, DMA_BIT_MASK(24)) < 0 ||
dma_set_coherent_mask(&pci->dev, DMA_BIT_MASK(24)) < 0) {
dev_err(card->dev,
"architecture does not support 24bit PCI busmaster DMA\n");
pci_disable_device(pci);
return -ENXIO;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
spin_lock_init(&chip->reg_lock);
spin_lock_init(&chip->mixer_lock);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
if ((err = pci_request_regions(pci, "ESS Solo-1")) < 0) {
kfree(chip);
pci_disable_device(pci);
return err;
}
chip->io_port = pci_resource_start(pci, 0);
chip->sb_port = pci_resource_start(pci, 1);
chip->vc_port = pci_resource_start(pci, 2);
chip->mpu_port = pci_resource_start(pci, 3);
chip->game_port = pci_resource_start(pci, 4);
if (request_irq(pci->irq, snd_es1938_interrupt, IRQF_SHARED,
KBUILD_MODNAME, chip)) {
dev_err(card->dev, "unable to grab IRQ %d\n", pci->irq);
snd_es1938_free(chip);
return -EBUSY;
}
chip->irq = pci->irq;
dev_dbg(card->dev,
"create: io: 0x%lx, sb: 0x%lx, vc: 0x%lx, mpu: 0x%lx, game: 0x%lx\n",
chip->io_port, chip->sb_port, chip->vc_port, chip->mpu_port, chip->game_port);
chip->ddma_port = chip->vc_port + 0x00; /* fix from Thomas Sailer */
snd_es1938_chip_init(chip);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_es1938_free(chip);
return err;
}
*rchip = chip;
return 0;
}
/* --------------------------------------------------------------------
* Interrupt handler
* -------------------------------------------------------------------- */
static irqreturn_t snd_es1938_interrupt(int irq, void *dev_id)
{
struct es1938 *chip = dev_id;
unsigned char status, audiostatus;
int handled = 0;
status = inb(SLIO_REG(chip, IRQCONTROL));
#if 0
dev_dbg(chip->card->dev,
"Es1938debug - interrupt status: =0x%x\n", status);
#endif
/* AUDIO 1 */
if (status & 0x10) {
#if 0
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 1 interrupt\n");
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 1 DMAC DMA count: %u\n",
inw(SLDM_REG(chip, DMACOUNT)));
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 1 DMAC DMA base: %u\n",
inl(SLDM_REG(chip, DMAADDR)));
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 1 DMAC DMA status: 0x%x\n",
inl(SLDM_REG(chip, DMASTATUS)));
#endif
/* clear irq */
handled = 1;
audiostatus = inb(SLSB_REG(chip, STATUS));
if (chip->active & ADC1)
snd_pcm_period_elapsed(chip->capture_substream);
else if (chip->active & DAC1)
snd_pcm_period_elapsed(chip->playback2_substream);
}
/* AUDIO 2 */
if (status & 0x20) {
#if 0
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 2 interrupt\n");
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 2 DMAC DMA count: %u\n",
inw(SLIO_REG(chip, AUDIO2DMACOUNT)));
dev_dbg(chip->card->dev,
"Es1938debug - AUDIO channel 2 DMAC DMA base: %u\n",
inl(SLIO_REG(chip, AUDIO2DMAADDR)));
#endif
/* clear irq */
handled = 1;
snd_es1938_mixer_bits(chip, ESSSB_IREG_AUDIO2CONTROL2, 0x80, 0);
if (chip->active & DAC2)
snd_pcm_period_elapsed(chip->playback1_substream);
}
/* Hardware volume */
if (status & 0x40) {
int split = snd_es1938_mixer_read(chip, 0x64) & 0x80;
handled = 1;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->hw_switch->id);
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &chip->hw_volume->id);
if (!split) {
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_switch->id);
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->master_volume->id);
}
/* ack interrupt */
snd_es1938_mixer_write(chip, 0x66, 0x00);
}
/* MPU401 */
if (status & 0x80) {
// the following line is evil! It switches off MIDI interrupt handling after the first interrupt received.
// replacing the last 0 by 0x40 works for ESS-Solo1, but just doing nothing works as well!
// andreas@flying-snail.de
// snd_es1938_mixer_bits(chip, ESSSB_IREG_MPU401CONTROL, 0x40, 0); /* ack? */
if (chip->rmidi) {
handled = 1;
snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data);
}
}
return IRQ_RETVAL(handled);
}
#define ES1938_DMA_SIZE 64
static int snd_es1938_mixer(struct es1938 *chip)
{
struct snd_card *card;
unsigned int idx;
int err;
card = chip->card;
strcpy(card->mixername, "ESS Solo-1");
for (idx = 0; idx < ARRAY_SIZE(snd_es1938_controls); idx++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_new1(&snd_es1938_controls[idx], chip);
switch (idx) {
case 0:
chip->master_volume = kctl;
kctl->private_free = snd_es1938_hwv_free;
break;
case 1:
chip->master_switch = kctl;
kctl->private_free = snd_es1938_hwv_free;
break;
case 2:
chip->hw_volume = kctl;
kctl->private_free = snd_es1938_hwv_free;
break;
case 3:
chip->hw_switch = kctl;
kctl->private_free = snd_es1938_hwv_free;
break;
}
if ((err = snd_ctl_add(card, kctl)) < 0)
return err;
}
return 0;
}
static int snd_es1938_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct es1938 *chip;
struct snd_opl3 *opl3;
int idx, err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
0, &card);
if (err < 0)
return err;
for (idx = 0; idx < 5; idx++) {
if (pci_resource_start(pci, idx) == 0 ||
!(pci_resource_flags(pci, idx) & IORESOURCE_IO)) {
snd_card_free(card);
return -ENODEV;
}
}
if ((err = snd_es1938_create(card, pci, &chip)) < 0) {
snd_card_free(card);
return err;
}
card->private_data = chip;
strcpy(card->driver, "ES1938");
strcpy(card->shortname, "ESS ES1938 (Solo-1)");
sprintf(card->longname, "%s rev %i, irq %i",
card->shortname,
chip->revision,
chip->irq);
if ((err = snd_es1938_new_pcm(chip, 0)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_es1938_mixer(chip)) < 0) {
snd_card_free(card);
return err;
}
if (snd_opl3_create(card,
SLSB_REG(chip, FMLOWADDR),
SLSB_REG(chip, FMHIGHADDR),
OPL3_HW_OPL3, 1, &opl3) < 0) {
dev_err(card->dev, "OPL3 not detected at 0x%lx\n",
SLSB_REG(chip, FMLOWADDR));
} else {
if ((err = snd_opl3_timer_new(opl3, 0, 1)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
snd_card_free(card);
return err;
}
}
if (snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401,
chip->mpu_port,
MPU401_INFO_INTEGRATED | MPU401_INFO_IRQ_HOOK,
-1, &chip->rmidi) < 0) {
dev_err(card->dev, "unable to initialize MPU-401\n");
} else {
// this line is vital for MIDI interrupt handling on ess-solo1
// andreas@flying-snail.de
snd_es1938_mixer_bits(chip, ESSSB_IREG_MPU401CONTROL, 0x40, 0x40);
}
snd_es1938_create_gameport(chip);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void snd_es1938_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
}
static struct pci_driver es1938_driver = {
.name = KBUILD_MODNAME,
.id_table = snd_es1938_ids,
.probe = snd_es1938_probe,
.remove = snd_es1938_remove,
.driver = {
.pm = ES1938_PM_OPS,
},
};
module_pci_driver(es1938_driver);
| AiJiaZone/linux-4.0 | virt/sound/pci/es1938.c | C | gpl-2.0 | 55,936 |
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/log_writer.h"
#include <stdint.h>
#include "leveldb/env.h"
#include "util/coding.h"
#include "util/crc32c.h"
namespace leveldb {
namespace log {
Writer::Writer(WritableFile* dest)
: dest_(dest),
block_offset_(0) {
for (int i = 0; i <= kMaxRecordType; i++) {
char t = static_cast<char>(i);
type_crc_[i] = crc32c::Value(&t, 1);
}
}
Writer::~Writer() {
}
Status Writer::AddRecord(const Slice& slice) {
const char* ptr = slice.data();
size_t left = slice.size();
// Fragment the record if necessary and emit it. Note that if slice
// is empty, we still want to iterate once to emit a single
// zero-length record
Status s;
bool begin = true;
do {
const int leftover = kBlockSize - block_offset_;
assert(leftover >= 0);
if (leftover < kHeaderSize) {
// Switch to a new block
if (leftover > 0) {
// Fill the trailer (literal below relies on kHeaderSize being 7)
assert(kHeaderSize == 7);
dest_->Append(Slice("\x00\x00\x00\x00\x00\x00", leftover));
}
block_offset_ = 0;
}
// Invariant: we never leave < kHeaderSize bytes in a block.
assert(kBlockSize - block_offset_ - kHeaderSize >= 0);
const size_t avail = kBlockSize - block_offset_ - kHeaderSize;
const size_t fragment_length = (left < avail) ? left : avail;
RecordType type;
const bool end = (left == fragment_length);
if (begin && end) {
type = kFullType;
} else if (begin) {
type = kFirstType;
} else if (end) {
type = kLastType;
} else {
type = kMiddleType;
}
s = EmitPhysicalRecord(type, ptr, fragment_length);
ptr += fragment_length;
left -= fragment_length;
begin = false;
} while (s.ok() && left > 0);
return s;
}
Status Writer::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n) {
assert(n <= 0xffff); // Must fit in two bytes
assert(block_offset_ + kHeaderSize + n <= kBlockSize);
// Format the header
char buf[kHeaderSize];
buf[4] = static_cast<char>(n & 0xff);
buf[5] = static_cast<char>(n >> 8);
buf[6] = static_cast<char>(t);
// Compute the crc of the record type and the payload.
uint32_t crc = crc32c::Extend(type_crc_[t], ptr, n);
crc = crc32c::Mask(crc); // Adjust for storage
EncodeFixed32(buf, crc);
// Write the header and the payload
Status s = dest_->Append(Slice(buf, kHeaderSize));
if (s.ok()) {
s = dest_->Append(Slice(ptr, n));
if (s.ok()) {
s = dest_->Flush();
}
}
block_offset_ += kHeaderSize + n;
return s;
}
} // namespace log
} // namespace leveldb
| february29/Learning | web/vue/AccountBook-Express/node_modules/.staging/leveldown-d5bd0bf6/deps/leveldb/leveldb-1.18.0/db/log_writer.cc | C++ | mit | 2,844 |
/* $Id: cache.h,v 1.6 2004/03/11 18:08:05 lethal Exp $
*
* include/asm-sh/cache.h
*
* Copyright 1999 (C) Niibe Yutaka
* Copyright 2002, 2003 (C) Paul Mundt
*/
#ifndef __ASM_SH_CACHE_H
#define __ASM_SH_CACHE_H
#ifdef __KERNEL__
#include <linux/init.h>
#include <cpu/cache.h>
#define L1_CACHE_BYTES (1 << L1_CACHE_SHIFT)
#define __read_mostly __attribute__((__section__(".data..read_mostly")))
#ifndef __ASSEMBLY__
struct cache_info {
unsigned int ways; /* Number of cache ways */
unsigned int sets; /* Number of cache sets */
unsigned int linesz; /* Cache line size (bytes) */
unsigned int way_size; /* sets * line size */
/*
* way_incr is the address offset for accessing the next way
* in memory mapped cache array ops.
*/
unsigned int way_incr;
unsigned int entry_shift;
unsigned int entry_mask;
/*
* Compute a mask which selects the address bits which overlap between
* 1. those used to select the cache set during indexing
* 2. those in the physical page number.
*/
unsigned int alias_mask;
unsigned int n_aliases; /* Number of aliases */
unsigned long flags;
};
#endif /* __ASSEMBLY__ */
#endif /* __KERNEL__ */
#endif /* __ASM_SH_CACHE_H */
| talnoah/android_kernel_htc_dlx | virt/arch/sh/include/asm/cache.h | C | gpl-2.0 | 1,193 |
-- Vazruden the herald
DELETE FROM `creature_text` WHERE `entry`=17307;
INSERT INTO `creature_text`(`entry`,`groupid`,`id`,`type`,`probability`,`sound`,`comment`,`text`) VALUES
(17307,0,0,14,100,10292,"vazruden the herald SAY_INTRO","You have faced many challenges, pity they were all in vain. Soon your people will kneel to my lord!");
-- Nazan
DELETE FROM `creature_text` WHERE `entry`=17536;
INSERT INTO `creature_text`(`entry`,`groupid`,`id`,`type`,`probability`,`comment`,`text`) VALUE
(17536,0,0,41,100,"nazan EMOTE","%s descends from the sky");
-- Vazruden
DELETE FROM `creature_text` WHERE `entry`=17537;
INSERT INTO `creature_text`(`entry`,`groupid`,`id`,`type`,`probability`,`sound`,`comment`,`text`) VALUES
(17537,0,0,14,100,10293,"vazruden SAY_WIPE","Is there no one left to test me?"),
(17537,1,0,14,100,10294,"vazruden SAY_AGGRO_1","Your time is running out!"),
(17537,1,1,14,100,10295,"vazruden SAY_AGGRO_2","You are nothing, I answer a higher call!"),
(17537,1,2,14,100,10296,"vazruden SAY_AGGRO_3","The Dark Lord laughs at you!"),
(17537,2,0,14,100,10297,"vazruden SAY_KILL_1","It is over. Finished!"),
(17537,2,1,14,100,10298,"vazruden SAY_KILL_2","Your days are done!"),
(17537,3,0,14,100,10299,"vazruden SAY_DIE","My lord will be the end you all...");
-- Talbot aka Prince Valanar (There's an UpdateEntry() call in the script which I did not see)
UPDATE `creature_text` SET `entry`=28189 WHERE `entry`=25301;
-- Darion Mograine
UPDATE `creature_text` SET `entry`=29228 WHERE `entry`=29173 AND `groupid`=74;
-- Core rager
UPDATE `creature_text` SET `entry`=11672 WHERE `entry`=11988;
DELETE FROM `creature_text` WHERE `entry` IN (15550,16151);
INSERT INTO `creature_text`(`entry`,`groupid`,`id`,`type`,`probability`,`sound`,`comment`,`text`) VALUES
-- Attumen
(15550,0,0,14,100,9169,"attumen SAY_KILL1","It was... inevitable."),
(15550,0,1,14,100,9300,"attumen SAY_KILL2","Another trophy to add to my collection!"),
(15550,1,0,14,100,9166,"attumen SAY_DISARMED","Weapons are merely a convenience for a warrior of my skill!"),
(15550,2,0,14,100,9165,"attumen SAY_DEATH","I always knew... someday I would become... the hunted."),
(15550,3,0,14,100,9170,"attumen SAY_RANDOM1","Such easy sport."),
(15550,3,1,14,100,9304,"attumen SAY_RANDOM2","Amateurs! Do not think you can best me! I kill for a living."),
-- Midnight
(16151,0,0,14,100,9173,"attumen SAY_MIDNIGHT_KILL","Well done Midnight!"),
(16151,1,0,14,100,9167,"attumen SAY_APPEAR1","Cowards! Wretches!"),
(16151,1,1,14,100,9298,"attumen SAY_APPEAR2","Who dares attack the steed of the Huntsman?"),
(16151,1,2,14,100,9299,"attumen SAY_APPEAR3","Perhaps you would rather test yourselves against a more formidable opponent?!"),
(16151,2,0,14,100,9168,"attumen SAY_MOUNT","Come, Midnight, let\'s disperse this petty rabble!");
-- Creature text preparation for rajaxx
DELETE FROM `creature_text` WHERE `entry` IN (15471,15341);
INSERT INTO `creature_text`(`entry`,`groupid`,`sound`,`type`,`probability`,`comment`,`text`) VALUES
(15471,0,0,14,100,"andorov SAY_ANDOROV_INTRO","They come now. Try not to get yourself killed, young blood."),
(15471,1,0,14,100,"andorov SAY_ANDOROV_ATTACK","Remember, Rajaxx, when I said I\'d kill you last? I lied..."),
(15341,0,8612,14,100,"rajaxx SAY_WAVE3","The time of our retribution is at hand! Let darkness reign in the hearts of our enemies!"),
(15341,1,8610,14,100,"rajaxx SAY_WAVE4","No longer will we wait behind barred doors and walls of stone! No longer will our vengeance be denied! The dragons themselves will tremble before our wrath!"),
(15341,2,8608,14,100,"rajaxx SAY_WAVE5","Fear is for the enemy! Fear and death!"),
(15341,3,8611,14,100,"rajaxx SAY_WAVE6","Staghelm will whimper and beg for his life, just as his whelp of a son did! One thousand years of injustice will end this day!"),
(15341,4,8607,14,100,"rajaxx SAY_WAVE7","Fandral! Your time has come! Go and hide in the Emerald Dream and pray we never find you!"),
(15341,5,8609,14,100,"rajaxx SAY_INTRO","Impudent fool! I will kill you myself!"),
(15341,6,8603,14,100,"rajaxx SAY_UNK1","Attack and make them pay dearly!"),
(15341,7,8605,14,100,"rajaxx SAY_UNK2","Crush them! Drive them out!"),
(15341,8,8606,14,100,"rajaxx SAY_UNK3","Do not hesitate! Destroy them!"),
(15341,9,8613,14,100,"rajaxx SAY_UNK4","Warriors! Captains! Continue the fight!"),
(15341,10,8614,14,100,"rajaxx SAY_DEAGGRO","You are not worth my time $N!"),
(15341,11,8604,14,100,"rajaxx SAY_KILLS_ANDOROV","Breath your last!"),
(15341,12,0,14,100,"rajaxx SAY_COMPLETE_QUEST","Soon you will know the price of your meddling, mortals... The master is nearly whole... And when he rises, your world will be cease!");
-- moam
DELETE FROM `creature_text` WHERE `entry`=15340;
INSERT INTO `creature_text`(`entry`,`groupid`,`type`,`probability`,`comment`,`text`) VALUES
(15340,0,16,100,"moam EMOTE_AGGRO","%s senses your fear."),
(15340,1,16,100,"moan EMOTE_MANA_FULL","%s bristles with energy!");
-- buru
DELETE FROM `creature_text` WHERE `entry`=15370;
INSERT INTO `creature_text`(`entry`,`groupid`,`type`,`probability`,`comment`,`text`) VALUES
(15370,0,16,100,"buru EMOTE_TARGET","%s sets eyes on $N!");
| ralph93/ShuriCore | sql/updates/worldacc/2012_12_18_01_world_creature_text.sql | SQL | gpl-2.0 | 5,153 |
/* Getopt for GNU.
NOTE: getopt is now part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
before changing it!
Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97
Free Software Foundation, Inc.
This file is part of the GNU C Library. Its master source is NOT part of
the C library, however. The master source lives in /gd/gnu/lib.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
Floor, Boston, MA 02110-1301 USA. */
/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
Ditto for AIX 3.2 and <stdlib.h>. */
#ifndef _NO_PROTO
#define _NO_PROTO
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#if !defined (__STDC__) || !__STDC__
/* This is a separate conditional since some stdc systems
reject `defined (const)'. */
#ifndef const
#define const
#endif
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined (_LIBC) && defined (__GLIBC__) && __GLIBC__ >= 2
#include <gnu-versions.h>
#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
#define ELIDE_CODE
#endif
#endif
#ifndef ELIDE_CODE
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
#include <stdlib.h>
#include <unistd.h>
#endif /* GNU C library. */
#ifdef VMS
#include <unixlib.h>
#if HAVE_STRING_H - 0
#include <string.h>
#ifdef STRNCASECMP_IN_STRINGS_H
# include <strings.h>
#endif
#endif
#endif
#if defined (WIN32) && !defined (__CYGWIN32__) || defined(UNDER_CE)
/* It's not Unix, really. See? Capital letters. */
#include <windows.h>
#define getpid() GetCurrentProcessId()
#endif
#ifndef _
/* This is for other GNU distributions with internationalized messages.
When compiling libc, the _ macro is predefined. */
#ifdef HAVE_LIBINTL_H
#include <libintl.h>
#define _(msgid) gettext (msgid)
#else
#define _(msgid) (msgid)
#endif
#endif
/* This version of `getopt' appears to the caller like standard Unix `getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
Setting the environment variable POSIXLY_CORRECT disables permutation.
Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "getopt.h"
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg = NULL;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
int optind = 1;
/* Formerly, initialization of getopt depended on optind==0, which
causes problems with re-calling getopt as programs generally don't
know that. */
int __getopt_initialized = 0;
/* The next char to be scanned in the option-element
in which the last option character we returned was found.
This allows us to pick up the scan where we left off.
If this is zero, or a null string, it means resume the scan
by advancing to the next ARGV-element. */
static char *nextchar;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
int opterr = 1;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
int optopt = '?';
/* Describe how to deal with options that follow non-option ARGV-elements.
If the caller did not specify anything,
the default is REQUIRE_ORDER if the environment variable
POSIXLY_CORRECT is defined, PERMUTE otherwise.
REQUIRE_ORDER means don't recognize them as options;
stop option processing when the first non-option is seen.
This is what Unix does.
This mode of operation is selected by either setting the environment
variable POSIXLY_CORRECT, or using `+' as the first character
of the list of option characters.
PERMUTE is the default. We permute the contents of ARGV as we scan,
so that eventually all the non-options are at the end. This allows options
to be given in any order, even with programs that were not written to
expect this.
RETURN_IN_ORDER is an option available to programs that were written
to expect options and other ARGV-elements in any order and that care about
the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1.
Using `-' as the first character of the list of option characters
selects this mode of operation.
The special argument `--' forces an end of option-scanning regardless
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `optind' != ARGC. */
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
}
ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
#ifdef __GNU_LIBRARY__
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
#include <string.h>
#define my_index strchr
#else
/* Avoid depending on library functions or files
whose names are inconsistent. */
char *getenv();
static char *
my_index(str, chr)
const char *str;
int chr;
{
while (*str)
{
if (*str == chr)
return (char *) str;
str++;
}
return 0;
}
/* If using GCC, we can safely declare strlen this way.
If not using GCC, it is ok not to declare it. */
#ifdef __GNUC__
/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
That was relevant to code that was here before. */
#if !defined (__STDC__) || !__STDC__
/* gcc with -traditional declares the built-in strlen to return int,
and has done so at least since version 2.4.5. -- rms. */
extern int strlen(const char *);
#endif /* not __STDC__ */
#endif /* __GNUC__ */
#endif /* not __GNU_LIBRARY__ */
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
been skipped. `first_nonopt' is the index in ARGV of the first of them;
`last_nonopt' is the index after the last of them. */
static int first_nonopt;
static int last_nonopt;
#ifdef _LIBC
/* Bash 2.0 gives us an environment variable containing flags
indicating ARGV elements that should not be considered arguments. */
static const char *nonoption_flags;
static int nonoption_flags_len;
static int original_argc;
static char *const *original_argv;
/* Make sure the environment variable bash 2.0 puts in the environment
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void store_args(int argc, char *const *argv) __attribute__((unused));
static void
store_args(int argc, char *const *argv)
{
/* XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
original_argc = argc;
original_argv = argv;
}
text_set_element(__libc_subinit, store_args);
#endif
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
#if defined (__STDC__) && __STDC__
static void exchange(char **);
#endif
static void
exchange(argv)
char **argv;
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
/* Initialize the internal data when the first call is made. */
#if defined (__STDC__) && __STDC__
static const char *_getopt_initialize(int, char *const *, const char *);
#endif
static const char *
_getopt_initialize(argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind = 1;
nextchar = NULL;
posixly_correct = getenv("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
#ifdef _LIBC
if (posixly_correct == NULL
&& argc == original_argc && argv == original_argv)
{
/* Bash 2.0 puts a special variable in the environment for each
command it runs, specifying which ARGV elements are the results of
file name wildcard expansion and therefore should not be
considered as options. */
char var[100];
sprintf(var, "_%d_GNU_nonoption_argv_flags_", getpid());
nonoption_flags = getenv(var);
if (nonoption_flags == NULL)
nonoption_flags_len = 0;
else
nonoption_flags_len = strlen(nonoption_flags);
}
else
nonoption_flags_len = 0;
#endif
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `optarg', otherwise `optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
The elements of ARGV aren't really const, because we permute them.
But we pretend they're const in the prototype to be compatible
with other systems.
LONGOPTS is a vector of `struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
int
_getopt_internal(argc, argv, optstring, longopts, longind, long_only)
int argc;
char *const *argv;
const char *optstring;
const struct option *longopts;
int *longind;
int long_only;
{
optarg = NULL;
if (!__getopt_initialized || optind == 0)
{
optstring = _getopt_initialize(argc, argv, optstring);
optind = 1; /* Don't scan ARGV[0], the program name. */
__getopt_initialized = 1;
}
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#ifdef _LIBC
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
|| (optind < nonoption_flags_len \
&& nonoption_flags[optind] == '1'))
#else
#define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp(argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !my_index(optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen(p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf(stderr, _("%s: option `%s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen(nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
{
if (argv[optind - 1][1] == '-')
/* --option */
fprintf(stderr,
_("%s: option `--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
else
/* +option or -option */
fprintf(stderr,
_("%s: option `%c%s' doesn't allow an argument\n"),
argv[0], argv[optind - 1][0], pfound->name);
}
nextchar += strlen(nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf(stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen(nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen(nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| my_index(optstring, *nextchar) == NULL)
{
if (opterr)
{
if (argv[optind][1] == '-')
/* --option */
fprintf(stderr, _("%s: unrecognized option `--%s'\n"),
argv[0], nextchar);
else
/* +option or -option */
fprintf(stderr, _("%s: unrecognized option `%c%s'\n"),
argv[0], argv[optind][0], nextchar);
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = my_index(optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (opterr)
{
if (posixly_correct)
/* 1003.2 specifies the format of this message. */
fprintf(stderr, _("%s: illegal option -- %c\n"),
argv[0], c);
else
fprintf(stderr, _("%s: invalid option -- %c\n"),
argv[0], c);
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf(stderr, _("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen(p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf(stderr, _("%s: option `-W %s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen(nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
fprintf(stderr, _("\
%s: option `-W %s' doesn't allow an argument\n"),
argv[0], pfound->name);
nextchar += strlen(nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf(stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen(nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen(nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf(stderr,
_("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
int
getopt(argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
return _getopt_internal(argc, argv, optstring,
(const struct option *) 0,
(int *) 0,
0);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
the above definition of `getopt'. */
int
main(argc, argv)
int argc;
char **argv;
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
c = getopt(argc, argv, "abc:d:0123456789");
if (c == -1)
break;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(0);
}
#endif /* TEST */
| freedesktop-unofficial-mirror/gstreamer-sdk__libdvdnav | msvc/contrib/getopt.c | C | gpl-2.0 | 28,567 |
(function() {
"use strict";
var WORD = /[\w$]+/, RANGE = 500;
CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
var word = options && options.word || WORD;
var range = options && options.range || RANGE;
var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
var start = cur.ch, end = start;
while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
while (start && word.test(curLine.charAt(start - 1))) --start;
var curWord = start != end && curLine.slice(start, end);
var list = [], seen = {};
var re = new RegExp(word.source, "g");
for (var dir = -1; dir <= 1; dir += 2) {
var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
for (; line != end; line += dir) {
var text = editor.getLine(line), m;
while (m = re.exec(text)) {
if (line == cur.line && m[0] === curWord) continue;
if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
seen[m[0]] = true;
list.push(m[0]);
}
}
}
}
return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
});
})();
| zoyoe/ectool | zoyoeec/static/CodeMirror/addon/hint/anyword-hint.js | JavaScript | gpl-2.0 | 1,296 |
DROP TABLE IF EXISTS `character_tutorial`;
CREATE TABLE `character_tutorial` (
`account` bigint(20) unsigned NOT NULL auto_increment COMMENT 'Account Identifier',
`realmid` int(11) unsigned NOT NULL default '0' COMMENT 'Realm Identifier',
`tut0` int(11) unsigned NOT NULL default '0',
`tut1` int(11) unsigned NOT NULL default '0',
`tut2` int(11) unsigned NOT NULL default '0',
`tut3` int(11) unsigned NOT NULL default '0',
`tut4` int(11) unsigned NOT NULL default '0',
`tut5` int(11) unsigned NOT NULL default '0',
`tut6` int(11) unsigned NOT NULL default '0',
`tut7` int(11) unsigned NOT NULL default '0',
PRIMARY KEY (`account`,`realmid`),
KEY acc_key (`account`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Player System';
| M-X/mangos | sql/updates/6698_characters_character_tutorial.sql | SQL | gpl-2.0 | 772 |
/*
'aes_xcbc.c' Obfuscated by COBF (Version 1.06 2006-01-07 by BB) at Fri Oct 12 22:15:16 2012
*/
#include"cobf.h"
#ifdef _WIN32
#if defined( UNDER_CE) && defined( bb337) || ! defined( bb329)
#define bb355 1
#define bb332 1
#else
#define bb351 bb343
#define bb333 1
#define bb331 1
#endif
#define bb348 1
#include"uncobf.h"
#include<ndis.h>
#include"cobf.h"
#ifdef UNDER_CE
#include"uncobf.h"
#include<ndiswan.h>
#include"cobf.h"
#endif
#include"uncobf.h"
#include<stdio.h>
#include<basetsd.h>
#include"cobf.h"
bba bbs bbl bbf, *bb1;bba bbs bbe bbq, *bb93;bba bb135 bb124, *bb334;
bba bbs bbl bb40, *bb72;bba bbs bb135 bbk, *bb59;bba bbe bbu, *bb133;
bba bbh bbf*bb89;
#ifdef bb311
bba bbd bb60, *bb122;
#endif
#else
#include"uncobf.h"
#include<linux/module.h>
#include<linux/ctype.h>
#include<linux/time.h>
#include<linux/slab.h>
#include"cobf.h"
#ifndef bb116
#define bb116
#ifdef _WIN32
#include"uncobf.h"
#include<wtypes.h>
#include"cobf.h"
#else
#ifdef bb120
#include"uncobf.h"
#include<linux/types.h>
#include"cobf.h"
#else
#include"uncobf.h"
#include<stddef.h>
#include<sys/types.h>
#include"cobf.h"
#endif
#endif
#ifdef _WIN32
bba bb119 bb215;
#else
bba bbe bbu, *bb133, *bb246;
#define bb201 1
#define bb202 0
bba bb251 bb205, *bb240, *bb208;bba bbe bb285, *bb283, *bb262;bba bbs
bbq, *bb93, *bb270;bba bb6 bb238, *bb216;bba bbs bb6 bb263, *bb250;
bba bb6 bb111, *bb222;bba bbs bb6 bb63, *bb289;bba bb63 bb264, *bb207
;bba bb63 bb219, *bb254;bba bb111 bb119, *bb226;bba bb243 bb247;bba
bb279 bb124;bba bb230 bb83;bba bb118 bb112;bba bb118 bb253;
#ifdef bb211
bba bb282 bb40, *bb72;bba bb258 bbk, *bb59;bba bb232 bbd, *bb28;bba
bb256 bb56, *bb113;
#else
bba bb271 bb40, *bb72;bba bb229 bbk, *bb59;bba bb233 bbd, *bb28;bba
bb277 bb56, *bb113;
#endif
bba bb40 bbf, *bb1, *bb214;bba bbk bb237, *bb245, *bb224;bba bbk bb255
, *bb220, *bb248;bba bbd bb60, *bb122, *bb206;bba bb83 bb37, *bb274, *
bb252;bba bbd bb290, *bb275, *bb210;bba bb112 bb265, *bb291, *bb269;
bba bb56 bb227, *bb261, *bb223;
#define bb140 bbb
bba bbb*bb221, *bb77;bba bbh bbb*bb225;bba bbl bb287;bba bbl*bb276;
bba bbh bbl*bb82;
#if defined( bb120)
bba bbe bb115;
#endif
bba bb115 bb20;bba bb20*bb218;bba bbh bb20*bb187;
#if defined( bb213) || defined( bb266)
bba bb20 bb36;bba bb20 bb114;
#else
bba bbl bb36;bba bbs bbl bb114;
#endif
bba bbh bb36*bb257;bba bb36*bb244;bba bb60 bb212, *bb239;bba bbb*
bb106;bba bb106*bb241;
#define bb281( bb34) bbi bb34##__ { bbe bb228; }; bba bbi bb34##__ * \
bb34
bba bbi{bb37 bb188,bb242,bb231,bb260;}bb286, *bb234, *bb278;bba bbi{
bb37 bb8,bb193;}bb280, *bb235, *bb259;bba bbi{bb37 bb267,bb249;}bb236
, *bb217, *bb284;
#endif
bba bbh bbf*bb89;
#endif
bba bbf bb100;
#define IN
#define OUT
#ifdef _DEBUG
#define bb139( bbc) bb31( bbc)
#else
#define bb139( bbc) ( bbb)( bbc)
#endif
bba bbe bb161, *bb173;
#define bb209 0
#define bb314 1
#define bb298 2
#define bb324 3
#define bb346 4
bba bbe bb349;bba bbb*bb121;
#endif
#ifdef _WIN32
#ifndef UNDER_CE
#define bb30 bb344
#define bb43 bb335
bba bbs bb6 bb30;bba bb6 bb43;
#endif
#else
#endif
#ifdef _WIN32
bbb*bb128(bb30 bb47);bbb bb105(bbb* );bbb*bb137(bb30 bb159,bb30 bb47);
#else
#define bb128( bbc) bb146(1, bbc, bb142)
#define bb105( bbc) bb342( bbc)
#define bb137( bbc, bbn) bb146( bbc, bbn, bb142)
#endif
#ifdef _WIN32
#define bb31( bbc) bb358( bbc)
#else
#ifdef _DEBUG
bbe bb145(bbh bbl*bb95,bbh bbl*bb25,bbs bb272);
#define bb31( bbc) ( bbb)(( bbc) || ( bb145(# bbc, __FILE__, __LINE__ \
)))
#else
#define bb31( bbc) (( bbb)0)
#endif
#endif
bb43 bb301(bb43*bb320);
#ifndef _WIN32
bbe bb328(bbh bbl*bbg);bbe bb322(bbh bbl*bb19,...);
#endif
#ifdef _WIN32
bba bb353 bb96;
#define bb141( bbc) bb356( bbc)
#define bb144( bbc) bb345( bbc)
#define bb134( bbc) bb350( bbc)
#define bb132( bbc) bb339( bbc)
#else
bba bb347 bb96;
#define bb141( bbc) ( bbb)( * bbc = bb330( bbc))
#define bb144( bbc) (( bbb)0)
#define bb134( bbc) bb352( bbc)
#define bb132( bbc) bb354( bbc)
#endif
#ifdef __cplusplus
bbr"\x43"{
#endif
#ifdef __cplusplus
bbr"\x43"{
#endif
bba bbi{bbq bb456;bbd bb417[4 * (14 +1 )];}bb363;bbb bb1098(bb363*bbj,
bbh bbb*bb71,bbq bb143);bbb bb1736(bb363*bbj,bbh bbb*bb71,bbq bb143);
bbb bb1034(bb363*bbj,bbb*bb14,bbh bbb*bb5);bbb bb1779(bb363*bbj,bbb*
bb14,bbh bbb*bb5);
#ifdef __cplusplus
}
#endif
bba bbi{bb363 bb2116;bbq bb10;bbf bb101[16 ];bbf bb1927[16 ];bbf bb1926
[16 ];bbf bb1842[16 ];}bb944;bbb bb2041(bb944*bbj,bbh bbb*bb71,bbq bb143
);bbb bb2092(bb944*bbj,bbh bbb*bb5,bbq bb10);bbb bb2102(bb944*bbj,bbb
*bb14);
#ifdef __cplusplus
}
#endif
bbb bb2041(bb944*bbj,bbh bbb*bb71,bbq bb143){bb363 bb2148;bbf bb2179[
16 ];bbj->bb10=0 ;bb31(bb143==16 );bb1098(&bb2148,bb71,bb143);bb996(bbj
->bb1842,0 ,16 );bb996(bb2179,1 ,16 );bb1034(&bb2148,bb2179,bb2179);bb996
(bbj->bb1927,2 ,16 );bb1034(&bb2148,bbj->bb1927,bbj->bb1927);bb996(bbj
->bb1926,3 ,16 );bb1034(&bb2148,bbj->bb1926,bbj->bb1926);bb1098(&bbj->
bb2116,bb2179,bb143);}bb41 bbb bb1252(bb944*bbj,bbh bbf*bb5){bbq bbz;
bb90(bbz=0 ;bbz<16 ;bbz++)bbj->bb1842[bbz]^=bb5[bbz];bb1034(&bbj->
bb2116,bbj->bb1842,bbj->bb1842);}bbb bb2092(bb944*bbj,bbh bbb*bb498,
bbq bb10){bbh bbf*bb5=(bbh bbf* )bb498;bbq bb384=bbj->bb10?(bbj->bb10
-1 )%16 +1 :0 ;bbj->bb10+=bb10;bbm(bb384){bbq bb11=16 -bb384;bb81(bbj->
bb101+bb384,bb5,((bb10)<(bb11)?(bb10):(bb11)));bbm(bb10<=bb11)bb2;bb5
+=bb11;bb10-=bb11;bb1252(bbj,bbj->bb101);}bb90(;bb10>16 ;bb10-=16 ,bb5
+=16 )bb1252(bbj,bb5);bb81(bbj->bb101,bb5,bb10);}bbb bb2102(bb944*bbj,
bbb*bb14){bb1 bb3;bbq bbz,bb384=bbj->bb10?(bbj->bb10-1 )%16 +1 :0 ;bbm(
bb384<16 ){bbj->bb101[bb384++]=0x80 ;bb996(bbj->bb101+bb384,0 ,16 -bb384);
bb3=bbj->bb1926;}bb54 bb3=bbj->bb1927;bb90(bbz=0 ;bbz<16 ;bbz++)bbj->
bb101[bbz]^=bb3[bbz];bb1252(bbj,bbj->bb101);bb81(bb14,bbj->bb1842,16 );
}
| sktjdgns1189/android_kernel_samsung_SHV-E110S | drivers/net/wirelessa/ipsecdrvtl/ac.c | C | gpl-2.0 | 5,737 |
import { addFormatToken } from '../format/format';
import { addUnitAlias } from './aliases';
import { addUnitPriority } from './priorities';
import { addRegexToken, match1to2, matchWord, regexEscape } from '../parse/regex';
import { addWeekParseToken } from '../parse/token';
import toInt from '../utils/to-int';
import isArray from '../utils/is-array';
import indexOf from '../utils/index-of';
import hasOwnProp from '../utils/has-own-prop';
import { createUTC } from '../create/utc';
import getParsingFlags from '../create/parsing-flags';
// FORMATTING
addFormatToken('d', 0, 'do', 'day');
addFormatToken('dd', 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken('ddd', 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken('dddd', 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken('e', 0, 0, 'weekday');
addFormatToken('E', 0, 0, 'isoWeekday');
// ALIASES
addUnitAlias('day', 'd');
addUnitAlias('weekday', 'e');
addUnitAlias('isoWeekday', 'E');
// PRIORITY
addUnitPriority('day', 11);
addUnitPriority('weekday', 11);
addUnitPriority('isoWeekday', 11);
// PARSING
addRegexToken('d', match1to2);
addRegexToken('e', match1to2);
addRegexToken('E', match1to2);
addRegexToken('dd', function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken('ddd', function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken('dddd', function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
});
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== 'string') {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === 'number') {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === 'string') {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
export var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
export function localeWeekdays (m, format) {
return isArray(this._weekdays) ? this._weekdays[m.day()] :
this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
}
export var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
export function localeWeekdaysShort (m) {
return this._weekdaysShort[m.day()];
}
export var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
export function localeWeekdaysMin (m) {
return this._weekdaysMin[m.day()];
}
function handleStrictParse(weekdayName, format, strict) {
var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
}
}
if (strict) {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === 'dddd') {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === 'ddd') {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
export function localeWeekdaysParse (weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
}
if (!this._weekdaysParse[i]) {
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
}
// test the regex
if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
export function getSetDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, 'd');
} else {
return day;
}
}
export function getSetLocaleDayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, 'd');
}
export function getSetISODayOfWeek (input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
var defaultWeekdaysRegex = matchWord;
export function weekdaysRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysRegex')) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict ?
this._weekdaysStrictRegex : this._weekdaysRegex;
}
}
var defaultWeekdaysShortRegex = matchWord;
export function weekdaysShortRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysShortRegex')) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict ?
this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
}
}
var defaultWeekdaysMinRegex = matchWord;
export function weekdaysMinRegex (isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, '_weekdaysRegex')) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, '_weekdaysMinRegex')) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict ?
this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
}
}
function computeWeekdaysParse () {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
i, mom, minp, shortp, longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = this.weekdaysMin(mom, '');
shortp = this.weekdaysShort(mom, '');
longp = this.weekdays(mom, '');
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 7; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
}
| Nucleo-235/roupa-livre-ionic | www/lib/moment/src/lib/units/day-of-week.js | JavaScript | gpl-3.0 | 11,793 |
DELETE FROM `script_texts` WHERE `entry` IN (-1000472,-1000473);
INSERT INTO `script_texts` (`npc_entry`,`entry`,`content_default`,`content_loc1`,`content_loc2`,`content_loc3`,`content_loc4`,`content_loc5`,`content_loc6`,`content_loc7`,`content_loc8`,`sound`,`type`,`language`,`emote`,`comment`) VALUES
(23864,-1000472,'This land was mine long before your wretched kind set foot here.',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0,1,0,0,''),
(23864,-1000473,'All who venture here belong to me, including you!',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0,1,0,0,'');
| milleniumcore/CactusEMU | sql/updates/TrinityCore_old/3.2.2a_old/7054_world_script_texts.sql | SQL | gpl-2.0 | 566 |
//! moment.js locale configuration
//! locale : Chinese (Hong Kong) [zh-hk]
//! author : Ben : https://github.com/ben-lin
//! author : Chris Lam : https://github.com/hehachris
//! author : Konstantin : https://github.com/skfd
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
var zhHk = moment.defineLocale('zh-hk', {
months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'),
weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'YYYY年MMMD日',
LL : 'YYYY年MMMD日',
LLL : 'YYYY年MMMD日 HH:mm',
LLLL : 'YYYY年MMMD日dddd HH:mm',
l : 'YYYY年MMMD日',
ll : 'YYYY年MMMD日',
lll : 'YYYY年MMMD日 HH:mm',
llll : 'YYYY年MMMD日dddd HH:mm'
},
meridiemParse: /凌晨|早上|上午|中午|下午|晚上/,
meridiemHour : function (hour, meridiem) {
if (hour === 12) {
hour = 0;
}
if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') {
return hour;
} else if (meridiem === '中午') {
return hour >= 11 ? hour : hour + 12;
} else if (meridiem === '下午' || meridiem === '晚上') {
return hour + 12;
}
},
meridiem : function (hour, minute, isLower) {
var hm = hour * 100 + minute;
if (hm < 600) {
return '凌晨';
} else if (hm < 900) {
return '早上';
} else if (hm < 1130) {
return '上午';
} else if (hm < 1230) {
return '中午';
} else if (hm < 1800) {
return '下午';
} else {
return '晚上';
}
},
calendar : {
sameDay : '[今天]LT',
nextDay : '[明天]LT',
nextWeek : '[下]ddddLT',
lastDay : '[昨天]LT',
lastWeek : '[上]ddddLT',
sameElse : 'L'
},
dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/,
ordinal : function (number, period) {
switch (period) {
case 'd' :
case 'D' :
case 'DDD' :
return number + '日';
case 'M' :
return number + '月';
case 'w' :
case 'W' :
return number + '週';
default :
return number;
}
},
relativeTime : {
future : '%s內',
past : '%s前',
s : '幾秒',
m : '1 分鐘',
mm : '%d 分鐘',
h : '1 小時',
hh : '%d 小時',
d : '1 天',
dd : '%d 天',
M : '1 個月',
MM : '%d 個月',
y : '1 年',
yy : '%d 年'
}
});
return zhHk;
})));
| stevemoore113/ch_web_- | 資源/CCEI/handsontable/dist/moment/locale/zh-hk.js | JavaScript | mit | 3,363 |
var assert = require('assert');
var cookie = require('..');
suite('parse');
test('basic', function() {
assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar'));
assert.deepEqual({ foo: '123' }, cookie.parse('foo=123'));
});
test('ignore spaces', function() {
assert.deepEqual({ FOO: 'bar', baz: 'raz' },
cookie.parse('FOO = bar; baz = raz'));
});
test('escaping', function() {
assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' },
cookie.parse('foo="bar=123456789&name=Magic+Mouse"'));
assert.deepEqual({ email: ' ",;/' },
cookie.parse('email=%20%22%2c%3b%2f'));
});
test('ignore escaping error and return original value', function() {
assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar'));
});
| BrowenChen/classroomDashboard | zzishwebsite/node_modules/express/node_modules/connect/node_modules/cookie/test/parse.js | JavaScript | mit | 800 |
/* drivers/misc/fm34_we395.c - fm34_we395 voice processor driver
*
* Copyright (C) 2012 Samsung Corporation.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/miscdevice.h>
#include <linux/gpio.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/workqueue.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/i2c/fm34_we395.h>
#include "2mic/fm34_we395.h"
#define MODULE_NAME "[FM34_WE395] :"
#define DEBUG 0
static struct i2c_client *this_client;
static struct fm34_platform_data *pdata;
#if defined(CONFIG_MACH_C1_KOR_LGT) || defined(CONFIG_MACH_BAFFIN_KOR_LGT)
unsigned char bypass_cmd[] = {
/*0xC0,*/
0xFC, 0xF3, 0x3B, 0x22, 0xC0, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xC1, 0x00, 0x01,
0xFC, 0xF3, 0x3B, 0x22, 0xC2, 0x00, 0x02,
0xFC, 0xF3, 0x3B, 0x22, 0xC3, 0x00, 0x02,
0xFC, 0xF3, 0x3B, 0x22, 0xC6, 0x00, 0x7D,
0xFC, 0xF3, 0x3B, 0x22, 0xC7, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xC8, 0x00, 0x18,
0xFC, 0xF3, 0x3B, 0x22, 0xD2, 0x82, 0x94,
0xFC, 0xF3, 0x3B, 0x22, 0xEE, 0x00, 0x01,
0xFC, 0xF3, 0x3B, 0x22, 0xF5, 0x00, 0x03,
0xFC, 0xF3, 0x3B, 0x22, 0xF6, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xF8, 0x80, 0x01,
0xFC, 0xF3, 0x3B, 0x22, 0xF9, 0x08, 0x7F,
0xFC, 0xF3, 0x3B, 0x22, 0xFA, 0x24, 0x8B,
0xFC, 0xF3, 0x3B, 0x23, 0x07, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x23, 0x0A, 0x1A, 0x00,
0xFC, 0xF3, 0x3B, 0x23, 0x0C, 0x00, 0xB8,
0xFC, 0xF3, 0x3B, 0x23, 0x0D, 0x02, 0x00,
0xFC, 0xF3, 0x3B, 0x23, 0x65, 0x08, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xFB, 0x00, 0x00
};
#else
unsigned char bypass_cmd[] = {
/*0xC0,*/
0xFC, 0xF3, 0x3B, 0x22, 0xF5, 0x00, 0x03,
0xFC, 0xF3, 0x3B, 0x22, 0xF8, 0x80, 0x03,
0xFC, 0xF3, 0x3B, 0x22, 0xC6, 0x00, 0x7D,
0xFC, 0xF3, 0x3B, 0x22, 0xC7, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xC8, 0x00, 0x18,
0xFC, 0xF3, 0x3B, 0x23, 0x0A, 0x1A, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xFA, 0x24, 0x8B,
0xFC, 0xF3, 0x3B, 0x22, 0xF9, 0x00, 0x7F,
0xFC, 0xF3, 0x3B, 0x22, 0xF6, 0x00, 0x00,
0xFC, 0xF3, 0x3B, 0x22, 0xD2, 0x82, 0x94,
0xFC, 0xF3, 0x3B, 0x22, 0xEE, 0x00, 0x01,
0xFC, 0xF3, 0x3B, 0x22, 0xFB, 0x00, 0x00,
};
#endif
static int fm34_i2c_read(char *rxData, int length)
{
int rc;
struct i2c_msg msgs[] = {
{
.addr = this_client->addr,
.flags = I2C_M_RD,
.len = length,
.buf = rxData,
},
};
rc = i2c_transfer(this_client->adapter, msgs, 1);
if (rc < 0) {
pr_err("%s: transfer error %d\n", __func__, rc);
return rc;
}
return 0;
}
static int fm34_i2c_write(char *txData, int length)
{
int rc;
struct i2c_msg msg[] = {
{
.addr = this_client->addr,
.flags = 0,
.len = length,
.buf = txData,
},
};
rc = i2c_transfer(this_client->adapter, msg, 1);
if (rc < 0) {
pr_err("%s: transfer error %d\n", __func__, rc);
return rc;
}
return 0;
}
#if defined(CONFIG_MACH_C1_KOR_LGT) || defined(CONFIG_MACH_BAFFIN_KOR_LGT)
void fm34_parameter_reset(void)
{
pr_info(MODULE_NAME "%s\n", __func__);
if (pdata->gpio_rst) {
gpio_set_value(pdata->gpio_rst, 0);
usleep_range(5000, 5000);
gpio_set_value(pdata->gpio_rst, 1);
}
usleep_range(5000, 5000);
}
int fm34_set_bypass_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
pr_info(MODULE_NAME "%s\n", __func__);
fm34_parameter_reset();
i2c_cmds = bypass_cmd;
size = sizeof(bypass_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_hw_bypass_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
pr_info(MODULE_NAME "%s\n", __func__);
usleep_range(20000, 20000);
gpio_set_value(pdata->gpio_pwdn, 0);
return rc;
}
int fm34_set_loopback_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = loopback_cmd;
size = sizeof(loopback_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_HS_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_cmd;
size = sizeof(HS_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_SPK_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HF_cmd;
size = sizeof(HF_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_HS_NS_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_NS_cmd;
size = sizeof(HS_NS_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_HS_ExtraVol_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_ExtraVol_cmd;
size = sizeof(HS_ExtraVol_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_SPK_ExtraVol_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HF_ExtraVol_cmd;
size = sizeof(HF_ExtraVol_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_ExtraVol_NS_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_ExtraVol_NS_cmd;
size = sizeof(HS_ExtraVol_NS_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_EP_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = EP_cmd;
size = sizeof(EP_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_BTSCO_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = BT_SCO_cmd;
size = sizeof(BT_SCO_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_factory_rcv_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_FACTORY_RCV_cmd;
size = sizeof(HS_FACTORY_RCV_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_factory_spk_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
int val = gpio_get_value(pdata->gpio_pwdn);
pr_info(MODULE_NAME "%s\n", __func__);
if (val == 0)
gpio_set_value(pdata->gpio_pwdn, 1);
fm34_parameter_reset();
i2c_cmds = HS_FACTORY_SPK_cmd;
size = sizeof(HS_FACTORY_SPK_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0)
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
return rc;
}
int fm34_set_mode(int mode)
{
int ret = 0;
pr_info(MODULE_NAME "%s : fm34_set_mode mode[%d]\n", __func__, mode);
if (mode == 0)
ret = fm34_set_bypass_mode(); /* OFF,Bypass */
else if (mode == 1)
ret = fm34_set_HS_mode(); /* Receiver */
else if (mode == 2)
ret = fm34_set_bypass_mode(); /* S/W Bypass */
else if (mode == 3)
ret = fm34_set_SPK_mode(); /* Speaker */
else if (mode == 4)
ret = fm34_set_hw_bypass_mode(); /* PwrDn H/W Bypass */
else if (mode == 5)
ret = fm34_set_HS_NS_mode(); /* Receiver+NS */
else if (mode == 6)
ret = fm34_set_HS_ExtraVol_mode(); /* Receiver+ExtraVol */
else if (mode == 7)
ret = fm34_set_SPK_ExtraVol_mode(); /* Speaker+ExtraVol */
else if (mode == 8)
ret = fm34_set_EP_mode(); /* Headset */
else if (mode == 9)
ret = fm34_set_BTSCO_mode(); /* BT SCO */
else if (mode == 11)
ret = fm34_set_factory_rcv_mode(); /* Factory Mode RCV */
else if (mode == 12)
ret = fm34_set_factory_spk_mode(); /* Factory Mode SPK */
else if (mode == 13)
ret = fm34_set_ExtraVol_NS_mode(); /* Receiver+ExtraVol+NS */
else
pr_err(MODULE_NAME"fm34_set_mode : INVALID mode[%d]\n", mode);
return ret;
}
EXPORT_SYMBOL_GPL(fm34_set_mode);
#else
int fm34_set_bypass_mode(void)
{
int i = 0, rc = 0, size = 0;
unsigned char *i2c_cmds;
pr_info(MODULE_NAME "%s\n", __func__);
i2c_cmds = bypass_cmd;
size = sizeof(bypass_cmd);
#if DEBUG
for (i = 0; i < size; i += 1)
pr_info(MODULE_NAME "%s : i2c_cmds[%d/%d] = 0x%x\n",
__func__, i, size, i2c_cmds[i]);
#endif
rc = fm34_i2c_write(i2c_cmds, size);
if (rc < 0) {
pr_err(MODULE_NAME "%s failed return %d\n", __func__, rc);
} else if (pdata->gpio_pwdn) {
msleep(20);
gpio_set_value(pdata->gpio_pwdn, 0);
}
return rc;
}
#endif
static struct miscdevice fm34_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "fm34_we395",
};
static void fm34_gpio_init(void)
{
if (pdata->gpio_rst) {
gpio_request(pdata->gpio_rst, "FM34_RESET");
gpio_direction_output(pdata->gpio_rst, 1);
gpio_free(pdata->gpio_rst);
gpio_set_value(pdata->gpio_rst, 0);
}
usleep_range(10000, 10000);
if (pdata->gpio_pwdn) {
gpio_request(pdata->gpio_pwdn, "FM34_PWDN");
gpio_direction_output(pdata->gpio_pwdn, 1);
gpio_free(pdata->gpio_pwdn);
gpio_set_value(pdata->gpio_pwdn, 1);
}
if (pdata->gpio_bp) {
gpio_request(pdata->gpio_bp, "FM34_BYPASS");
gpio_direction_output(pdata->gpio_bp, 1);
gpio_free(pdata->gpio_bp);
gpio_set_value(pdata->gpio_bp, 1);
}
}
static void fm34_bootup_init(void)
{
if (pdata->set_mclk != NULL)
pdata->set_mclk(true, false);
msleep(20);
if (pdata->gpio_rst) {
gpio_set_value(pdata->gpio_rst, 0);
msleep(20);
gpio_set_value(pdata->gpio_rst, 1);
}
msleep(50);
}
static int fm34_probe(
struct i2c_client *client, const struct i2c_device_id *id)
{
int rc = 0;
pdata = client->dev.platform_data;
pr_info(MODULE_NAME "%s : start\n", __func__);
if (pdata == NULL) {
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (pdata == NULL) {
rc = -ENOMEM;
pr_err(MODULE_NAME "%s: platform data is NULL\n",
__func__);
}
}
this_client = client;
fm34_gpio_init();
fm34_bootup_init();
if (fm34_set_bypass_mode() < 0)
pr_err(MODULE_NAME "bypass setting failed %d\n", rc);
pr_info(MODULE_NAME "%s : finish\n", __func__);
return rc;
}
static int fm34_remove(struct i2c_client *client)
{
struct fm34_platform_data *pfm34data = i2c_get_clientdata(client);
kfree(pfm34data);
return 0;
}
static int fm34_suspend(struct i2c_client *client, pm_message_t mesg)
{
return 0;
}
static int fm34_resume(struct i2c_client *client)
{
return 0;
}
static const struct i2c_device_id fm34_id[] = {
{ "fm34_we395", 0 },
{ }
};
static struct i2c_driver fm34_driver = {
.probe = fm34_probe,
.remove = fm34_remove,
.suspend = fm34_suspend,
.resume = fm34_resume,
.id_table = fm34_id,
.driver = {
.name = "fm34_we395",
},
};
static int __init fm34_init(void)
{
pr_info("%s\n", __func__);
return i2c_add_driver(&fm34_driver);
}
static void __exit fm34_exit(void)
{
i2c_del_driver(&fm34_driver);
}
module_init(fm34_init);
module_exit(fm34_exit);
MODULE_DESCRIPTION("fm34 voice processor driver");
MODULE_LICENSE("GPL");
| vet-note/android_kernel_samsung_smdk4210 | drivers/misc/fm34_we395.c | C | gpl-2.0 | 14,942 |
package reflectwalk
//go:generate stringer -type=Location location.go
type Location uint
const (
None Location = iota
Map
MapKey
MapValue
Slice
SliceElem
Struct
StructField
WalkLoc
)
| bakins/terraform-provider-etcd | vendor/src/github.com/mitchellh/reflectwalk/location.go | GO | mpl-2.0 | 195 |
#
# arch/score/boot/Makefile
#
# This file is subject to the terms and conditions of the GNU General Public
# License. See the file "COPYING" in the main directory of this archive
# for more details.
#
targets := vmlinux.bin
$(obj)/vmlinux.bin: vmlinux FORCE
$(call if_changed,objcopy)
@echo 'Kernel: $@ is ready' ' (#'`cat .version`')'
clean-files += vmlinux.bin
| AiJiaZone/linux-4.0 | virt/arch/score/boot/Makefile | Makefile | gpl-2.0 | 370 |
<?php
/*
* $Id: TarTask.php 220 2007-08-21 00:03:13Z hans $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/tasks/system/MatchingTask.php';
include_once 'phing/util/SourceFileScanner.php';
include_once 'phing/mappers/MergeMapper.php';
include_once 'phing/util/StringHelper.php';
/**
* Creates a tar archive using PEAR Archive_Tar.
*
* @author Hans Lellelid <hans@xmpl.org> (Phing)
* @author Stefano Mazzocchi <stefano@apache.org> (Ant)
* @author Stefan Bodewig <stefan.bodewig@epost.de> (Ant)
* @author Magesh Umasankar
* @version $Revision: 1.10 $
* @package phing.tasks.ext
*/
class TarTask extends MatchingTask {
const TAR_NAMELEN = 100;
const WARN = "warn";
const FAIL = "fail";
const OMIT = "omit";
private $tarFile;
private $baseDir;
private $includeEmpty = true; // Whether to include empty dirs in the TAR
private $longFileMode = "warn";
private $filesets = array();
private $fileSetFiles = array();
/**
* Indicates whether the user has been warned about long files already.
*/
private $longWarningGiven = false;
/**
* Compression mode. Available options "gzip", "bzip2", "none" (null).
*/
private $compression = null;
/**
* Ensures that PEAR lib exists.
*/
public function init() {
include_once 'Archive/Tar.php';
if (!class_exists('Archive_Tar')) {
throw new BuildException("You must have installed the PEAR Archive_Tar class in order to use TarTask.");
}
}
/**
* Add a new fileset
* @return FileSet
*/
public function createTarFileSet() {
$this->fileset = new TarFileSet();
$this->filesets[] = $this->fileset;
return $this->fileset;
}
/**
* Add a new fileset. Alias to createTarFileSet() for backwards compatibility.
* @return FileSet
* @see createTarFileSet()
*/
public function createFileSet() {
$this->fileset = new TarFileSet();
$this->filesets[] = $this->fileset;
return $this->fileset;
}
/**
* Set is the name/location of where to create the tar file.
* @param PhingFile $destFile The output of the tar
*/
public function setDestFile(PhingFile $destFile) {
$this->tarFile = $destFile;
}
/**
* This is the base directory to look in for things to tar.
* @param PhingFile $baseDir
*/
public function setBasedir(PhingFile $baseDir) {
$this->baseDir = $baseDir;
}
/**
* Set the include empty dirs flag.
* @param boolean Flag if empty dirs should be tarred too
* @return void
* @access public
*/
function setIncludeEmptyDirs($bool) {
$this->includeEmpty = (boolean) $bool;
}
/**
* Set how to handle long files, those with a path>100 chars.
* Optional, default=warn.
* <p>
* Allowable values are
* <ul>
* <li> truncate - paths are truncated to the maximum length
* <li> fail - paths greater than the maximim cause a build exception
* <li> warn - paths greater than the maximum cause a warning and GNU is used
* <li> gnu - GNU extensions are used for any paths greater than the maximum.
* <li> omit - paths greater than the maximum are omitted from the archive
* </ul>
*/
public function setLongfile($mode) {
$this->longFileMode = $mode;
}
/**
* Set compression method.
* Allowable values are
* <ul>
* <li> none - no compression
* <li> gzip - Gzip compression
* <li> bzip2 - Bzip2 compression
* </ul>
*/
public function setCompression($mode) {
switch($mode) {
case "gzip":
$this->compression = "gz";
break;
case "bzip2":
$this->compression = "bz2";
break;
case "none":
$this->compression = null;
break;
default:
$this->log("Ignoring unknown compression mode: ".$mode, Project::MSG_WARN);
$this->compression = null;
}
}
/**
* do the work
* @throws BuildException
*/
public function main() {
if ($this->tarFile === null) {
throw new BuildException("tarfile attribute must be set!", $this->getLocation());
}
if ($this->tarFile->exists() && $this->tarFile->isDirectory()) {
throw new BuildException("tarfile is a directory!", $this->getLocation());
}
if ($this->tarFile->exists() && !$this->tarFile->canWrite()) {
throw new BuildException("Can not write to the specified tarfile!", $this->getLocation());
}
// shouldn't need to clone, since the entries in filesets
// themselves won't be modified -- only elements will be added
$savedFileSets = $this->filesets;
try {
if ($this->baseDir !== null) {
if (!$this->baseDir->exists()) {
throw new BuildException("basedir does not exist!", $this->getLocation());
}
if (empty($this->filesets)) { // if there weren't any explicit filesets specivied, then
// create a default, all-inclusive fileset using the specified basedir.
$mainFileSet = new TarFileSet($this->fileset);
$mainFileSet->setDir($this->baseDir);
$this->filesets[] = $mainFileSet;
}
}
if (empty($this->filesets)) {
throw new BuildException("You must supply either a basedir "
. "attribute or some nested filesets.",
$this->getLocation());
}
// check if tar is out of date with respect to each fileset
if($this->tarFile->exists()) {
$upToDate = true;
foreach($this->filesets as $fs) {
$files = $fs->getFiles($this->project, $this->includeEmpty);
if (!$this->archiveIsUpToDate($files, $fs->getDir($this->project))) {
$upToDate = false;
}
for ($i=0, $fcount=count($files); $i < $fcount; $i++) {
if ($this->tarFile->equals(new PhingFile($fs->getDir($this->project), $files[$i]))) {
throw new BuildException("A tar file cannot include itself", $this->getLocation());
}
}
}
if ($upToDate) {
$this->log("Nothing to do: " . $this->tarFile->__toString() . " is up to date.", Project::MSG_INFO);
return;
}
}
$this->log("Building tar: " . $this->tarFile->__toString(), Project::MSG_INFO);
$tar = new Archive_Tar($this->tarFile->getAbsolutePath(), $this->compression);
// print errors
$tar->setErrorHandling(PEAR_ERROR_PRINT);
foreach($this->filesets as $fs) {
$files = $fs->getFiles($this->project, $this->includeEmpty);
if (count($files) > 1 && strlen($fs->getFullpath()) > 0) {
throw new BuildException("fullpath attribute may only "
. "be specified for "
. "filesets that specify a "
. "single file.");
}
$fsBasedir = $fs->getDir($this->project);
$filesToTar = array();
for ($i=0, $fcount=count($files); $i < $fcount; $i++) {
$f = new PhingFile($fsBasedir, $files[$i]);
$filesToTar[] = $f->getAbsolutePath();
$this->log("Adding file " . $f->getPath() . " to archive.", Project::MSG_VERBOSE);
}
$tar->addModify($filesToTar, '', $fsBasedir->getAbsolutePath());
}
} catch (IOException $ioe) {
$msg = "Problem creating TAR: " . $ioe->getMessage();
$this->filesets = $savedFileSets;
throw new BuildException($msg, $ioe, $this->getLocation());
}
$this->filesets = $savedFileSets;
}
/**
* @param array $files array of filenames
* @param PhingFile $dir
* @return boolean
*/
protected function archiveIsUpToDate($files, $dir) {
$sfs = new SourceFileScanner($this);
$mm = new MergeMapper();
$mm->setTo($this->tarFile->getAbsolutePath());
return count($sfs->restrict($files, $dir, null, $mm)) == 0;
}
}
/**
* This is a FileSet with the option to specify permissions.
*
* Permissions are currently not implemented by PEAR Archive_Tar,
* but hopefully they will be in the future.
*
*/
class TarFileSet extends FileSet {
private $files = null;
private $mode = 0100644;
private $userName = "";
private $groupName = "";
private $prefix = "";
private $fullpath = "";
private $preserveLeadingSlashes = false;
/**
* Get a list of files and directories specified in the fileset.
* @return array a list of file and directory names, relative to
* the baseDir for the project.
*/
public function getFiles(Project $p, $includeEmpty = true) {
if ($this->files === null) {
$ds = $this->getDirectoryScanner($p);
$this->files = $ds->getIncludedFiles();
if ($includeEmpty) {
// first any empty directories that will not be implicitly added by any of the files
$implicitDirs = array();
foreach($this->files as $file) {
$implicitDirs[] = dirname($file);
}
$incDirs = $ds->getIncludedDirectories();
// we'll need to add to that list of implicit dirs any directories
// that contain other *directories* (and not files), since otherwise
// we get duplicate directories in the resulting tar
foreach($incDirs as $dir) {
foreach($incDirs as $dircheck) {
if (!empty($dir) && $dir == dirname($dircheck)) {
$implicitDirs[] = $dir;
}
}
}
$implicitDirs = array_unique($implicitDirs);
// Now add any empty dirs (dirs not covered by the implicit dirs)
// to the files array.
foreach($incDirs as $dir) { // we cannot simply use array_diff() since we want to disregard empty/. dirs
if ($dir != "" && $dir != "." && !in_array($dir, $implicitDirs)) {
// it's an empty dir, so we'll add it.
$this->files[] = $dir;
}
}
} // if $includeEmpty
} // if ($this->files===null)
return $this->files;
}
/**
* A 3 digit octal string, specify the user, group and
* other modes in the standard Unix fashion;
* optional, default=0644
* @param string $octalString
*/
public function setMode($octalString) {
$octal = (int) $octalString;
$this->mode = 0100000 | $octal;
}
public function getMode() {
return $this->mode;
}
/**
* The username for the tar entry
* This is not the same as the UID, which is
* not currently set by the task.
*/
public function setUserName($userName) {
$this->userName = $userName;
}
public function getUserName() {
return $this->userName;
}
/**
* The groupname for the tar entry; optional, default=""
* This is not the same as the GID, which is
* not currently set by the task.
*/
public function setGroup($groupName) {
$this->groupName = $groupName;
}
public function getGroup() {
return $this->groupName;
}
/**
* If the prefix attribute is set, all files in the fileset
* are prefixed with that path in the archive.
* optional.
*/
public function setPrefix($prefix) {
$this->prefix = $prefix;
}
public function getPrefix() {
return $this->prefix;
}
/**
* If the fullpath attribute is set, the file in the fileset
* is written with that path in the archive. The prefix attribute,
* if specified, is ignored. It is an error to have more than one file specified in
* such a fileset.
*/
public function setFullpath($fullpath) {
$this->fullpath = $fullpath;
}
public function getFullpath() {
return $this->fullpath;
}
/**
* Flag to indicates whether leading `/'s should
* be preserved in the file names.
* Optional, default is <code>false</code>.
* @return void
*/
public function setPreserveLeadingSlashes($b) {
$this->preserveLeadingSlashes = (boolean) $b;
}
public function getPreserveLeadingSlashes() {
return $this->preserveLeadingSlashes;
}
}
| voota/voota | www/lib/vendor/symfony/lib/plugins/sfPropelPlugin/lib/vendor/phing/tasks/ext/TarTask.php | PHP | mit | 14,247 |
/*
* watchdog_core.c
*
* (c) Copyright 2008-2011 Alan Cox <alan@lxorguk.ukuu.org.uk>,
* All Rights Reserved.
*
* (c) Copyright 2008-2011 Wim Van Sebroeck <wim@iguana.be>.
*
* This source code is part of the generic code that can be used
* by all the watchdog timer drivers.
*
* Based on source code of the following authors:
* Matt Domsch <Matt_Domsch@dell.com>,
* Rob Radez <rob@osinvestor.com>,
* Rusty Lynch <rusty@linux.co.intel.com>
* Satyam Sharma <satyam@infradead.org>
* Randy Dunlap <randy.dunlap@oracle.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Neither Alan Cox, CymruNet Ltd., Wim Van Sebroeck nor Iguana vzw.
* admit liability nor provide warranty for any of this software.
* This material is provided "AS-IS" and at no charge.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h> /* For EXPORT_SYMBOL/module stuff/... */
#include <linux/types.h> /* For standard types */
#include <linux/errno.h> /* For the -ENODEV/... values */
#include <linux/kernel.h> /* For printk/panic/... */
#include <linux/watchdog.h> /* For watchdog specific items */
#include <linux/init.h> /* For __init/__exit/... */
#include <linux/idr.h> /* For ida_* macros */
#include <linux/err.h> /* For IS_ERR macros */
#include "watchdog_core.h" /* For watchdog_dev_register/... */
static DEFINE_IDA(watchdog_ida);
static struct class *watchdog_class;
/**
* watchdog_register_device() - register a watchdog device
* @wdd: watchdog device
*
* Register a watchdog device with the kernel so that the
* watchdog timer can be accessed from userspace.
*
* A zero is returned on success and a negative errno code for
* failure.
*/
int watchdog_register_device(struct watchdog_device *wdd)
{
int ret, id, devno;
if (wdd == NULL || wdd->info == NULL || wdd->ops == NULL)
return -EINVAL;
/* Mandatory operations need to be supported */
if (wdd->ops->start == NULL || wdd->ops->stop == NULL)
return -EINVAL;
/*
* Check that we have valid min and max timeout values, if
* not reset them both to 0 (=not used or unknown)
*/
if (wdd->min_timeout > wdd->max_timeout) {
pr_info("Invalid min and max timeout values, resetting to 0!\n");
wdd->min_timeout = 0;
wdd->max_timeout = 0;
}
/*
* Note: now that all watchdog_device data has been verified, we
* will not check this anymore in other functions. If data gets
* corrupted in a later stage then we expect a kernel panic!
*/
mutex_init(&wdd->lock);
id = ida_simple_get(&watchdog_ida, 0, MAX_DOGS, GFP_KERNEL);
if (id < 0)
return id;
wdd->id = id;
ret = watchdog_dev_register(wdd);
if (ret) {
ida_simple_remove(&watchdog_ida, id);
if (!(id == 0 && ret == -EBUSY))
return ret;
/* Retry in case a legacy watchdog module exists */
id = ida_simple_get(&watchdog_ida, 1, MAX_DOGS, GFP_KERNEL);
if (id < 0)
return id;
wdd->id = id;
ret = watchdog_dev_register(wdd);
if (ret) {
ida_simple_remove(&watchdog_ida, id);
return ret;
}
}
devno = wdd->cdev.dev;
wdd->dev = device_create(watchdog_class, wdd->parent, devno,
NULL, "watchdog%d", wdd->id);
if (IS_ERR(wdd->dev)) {
watchdog_dev_unregister(wdd);
ida_simple_remove(&watchdog_ida, id);
ret = PTR_ERR(wdd->dev);
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(watchdog_register_device);
/**
* watchdog_unregister_device() - unregister a watchdog device
* @wdd: watchdog device to unregister
*
* Unregister a watchdog device that was previously successfully
* registered with watchdog_register_device().
*/
void watchdog_unregister_device(struct watchdog_device *wdd)
{
int ret;
int devno;
if (wdd == NULL)
return;
devno = wdd->cdev.dev;
ret = watchdog_dev_unregister(wdd);
if (ret)
pr_err("error unregistering /dev/watchdog (err=%d)\n", ret);
device_destroy(watchdog_class, devno);
ida_simple_remove(&watchdog_ida, wdd->id);
wdd->dev = NULL;
}
EXPORT_SYMBOL_GPL(watchdog_unregister_device);
static int __init watchdog_init(void)
{
int err;
watchdog_class = class_create(THIS_MODULE, "watchdog");
if (IS_ERR(watchdog_class)) {
pr_err("couldn't create class\n");
return PTR_ERR(watchdog_class);
}
err = watchdog_dev_init();
if (err < 0) {
class_destroy(watchdog_class);
return err;
}
return 0;
}
static void __exit watchdog_exit(void)
{
watchdog_dev_exit();
class_destroy(watchdog_class);
ida_destroy(&watchdog_ida);
}
subsys_initcall(watchdog_init);
module_exit(watchdog_exit);
MODULE_AUTHOR("Alan Cox <alan@lxorguk.ukuu.org.uk>");
MODULE_AUTHOR("Wim Van Sebroeck <wim@iguana.be>");
MODULE_DESCRIPTION("WatchDog Timer Driver Core");
MODULE_LICENSE("GPL");
| SanDisk-Open-Source/SSD_Dashboard | uefi/linux-source-3.8.0/drivers/watchdog/watchdog_core.c | C | gpl-2.0 | 4,853 |
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright 2016 IBM Corporation.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/irq.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/cpu.h>
#include <linux/of.h>
#include <asm/smp.h>
#include <asm/irq.h>
#include <asm/errno.h>
#include <asm/xics.h>
#include <asm/io.h>
#include <asm/opal.h>
#include <asm/kvm_ppc.h>
static void icp_opal_teardown_cpu(void)
{
int hw_cpu = hard_smp_processor_id();
/* Clear any pending IPI */
opal_int_set_mfrr(hw_cpu, 0xff);
}
static void icp_opal_flush_ipi(void)
{
/*
* We take the ipi irq but and never return so we need to EOI the IPI,
* but want to leave our priority 0.
*
* Should we check all the other interrupts too?
* Should we be flagging idle loop instead?
* Or creating some task to be scheduled?
*/
if (opal_int_eoi((0x00 << 24) | XICS_IPI) > 0)
force_external_irq_replay();
}
static unsigned int icp_opal_get_xirr(void)
{
unsigned int kvm_xirr;
__be32 hw_xirr;
int64_t rc;
/* Handle an interrupt latched by KVM first */
kvm_xirr = kvmppc_get_xics_latch();
if (kvm_xirr)
return kvm_xirr;
/* Then ask OPAL */
rc = opal_int_get_xirr(&hw_xirr, false);
if (rc < 0)
return 0;
return be32_to_cpu(hw_xirr);
}
static unsigned int icp_opal_get_irq(void)
{
unsigned int xirr;
unsigned int vec;
unsigned int irq;
xirr = icp_opal_get_xirr();
vec = xirr & 0x00ffffff;
if (vec == XICS_IRQ_SPURIOUS)
return 0;
irq = irq_find_mapping(xics_host, vec);
if (likely(irq)) {
xics_push_cppr(vec);
return irq;
}
/* We don't have a linux mapping, so have rtas mask it. */
xics_mask_unknown_vec(vec);
/* We might learn about it later, so EOI it */
if (opal_int_eoi(xirr) > 0)
force_external_irq_replay();
return 0;
}
static void icp_opal_set_cpu_priority(unsigned char cppr)
{
/*
* Here be dragons. The caller has asked to allow only IPI's and not
* external interrupts. But OPAL XIVE doesn't support that. So instead
* of allowing no interrupts allow all. That's still not right, but
* currently the only caller who does this is xics_migrate_irqs_away()
* and it works in that case.
*/
if (cppr >= DEFAULT_PRIORITY)
cppr = LOWEST_PRIORITY;
xics_set_base_cppr(cppr);
opal_int_set_cppr(cppr);
iosync();
}
static void icp_opal_eoi(struct irq_data *d)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
int64_t rc;
iosync();
rc = opal_int_eoi((xics_pop_cppr() << 24) | hw_irq);
/*
* EOI tells us whether there are more interrupts to fetch.
*
* Some HW implementations might not be able to send us another
* external interrupt in that case, so we force a replay.
*/
if (rc > 0)
force_external_irq_replay();
}
#ifdef CONFIG_SMP
static void icp_opal_cause_ipi(int cpu)
{
int hw_cpu = get_hard_smp_processor_id(cpu);
kvmppc_set_host_ipi(cpu);
opal_int_set_mfrr(hw_cpu, IPI_PRIORITY);
}
static irqreturn_t icp_opal_ipi_action(int irq, void *dev_id)
{
int cpu = smp_processor_id();
kvmppc_clear_host_ipi(cpu);
opal_int_set_mfrr(get_hard_smp_processor_id(cpu), 0xff);
return smp_ipi_demux();
}
/*
* Called when an interrupt is received on an off-line CPU to
* clear the interrupt, so that the CPU can go back to nap mode.
*/
void icp_opal_flush_interrupt(void)
{
unsigned int xirr;
unsigned int vec;
do {
xirr = icp_opal_get_xirr();
vec = xirr & 0x00ffffff;
if (vec == XICS_IRQ_SPURIOUS)
break;
if (vec == XICS_IPI) {
/* Clear pending IPI */
int cpu = smp_processor_id();
kvmppc_clear_host_ipi(cpu);
opal_int_set_mfrr(get_hard_smp_processor_id(cpu), 0xff);
} else {
pr_err("XICS: hw interrupt 0x%x to offline cpu, "
"disabling\n", vec);
xics_mask_unknown_vec(vec);
}
/* EOI the interrupt */
} while (opal_int_eoi(xirr) > 0);
}
#endif /* CONFIG_SMP */
static const struct icp_ops icp_opal_ops = {
.get_irq = icp_opal_get_irq,
.eoi = icp_opal_eoi,
.set_priority = icp_opal_set_cpu_priority,
.teardown_cpu = icp_opal_teardown_cpu,
.flush_ipi = icp_opal_flush_ipi,
#ifdef CONFIG_SMP
.ipi_action = icp_opal_ipi_action,
.cause_ipi = icp_opal_cause_ipi,
#endif
};
int icp_opal_init(void)
{
struct device_node *np;
np = of_find_compatible_node(NULL, NULL, "ibm,opal-intc");
if (!np)
return -ENODEV;
icp_ops = &icp_opal_ops;
printk("XICS: Using OPAL ICP fallbacks\n");
return 0;
}
| CSE3320/kernel-code | linux-5.8/arch/powerpc/sysdev/xics/icp-opal.c | C | gpl-2.0 | 4,387 |
0.0.2 / 2014-02-20
==================
* fix infinite loop
0.0.1 / 2014-01-15
==================
* fix error bubbling
0.0.0 / 2014-01-13
==================
* initial release
| kressentolm/jensite | wp-content/themes/eddiemachado-bones-652abb9/node_modules/grunt-contrib-imagemin/node_modules/image-min/node_modules/multipipe/History.md | Markdown | gpl-2.0 | 181 |
// Boost.Assign library
//
// Copyright Thorsten Ottosen 2003-2004. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/assign/
//
#ifndef BOOST_ASSIGN_STD_MAP_HPP
#define BOOST_ASSIGN_STD_MAP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <boost/assign/list_inserter.hpp>
#include <boost/config.hpp>
#include <map>
namespace boost
{
namespace assign
{
template< class K, class V, class C, class A, class P >
inline list_inserter< assign_detail::call_insert< std::map<K,V,C,A> >, P >
operator+=( std::map<K,V,C,A>& m, const P& p )
{
return insert( m )( p );
}
template< class K, class V, class C, class A, class P >
inline list_inserter< assign_detail::call_insert< std::multimap<K,V,C,A> >, P >
operator+=( std::multimap<K,V,C,A>& m, const P& p )
{
return insert( m )( p );
}
}
}
#endif
| hpl1nk/nonamegame | xray/SDK/include/boost/assign/std/map.hpp | C++ | gpl-3.0 | 1,085 |
/*
* Copyright 2007 Robert Schwebel <r.schwebel@pengutronix.de>, Pengutronix
* Copyright (C) 2009 Sascha Hauer (kernel@pengutronix.de)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/dma-mapping.h>
#include <linux/spi/spi.h>
#include <linux/spi/eeprom.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/usb/ulpi.h>
#include <asm/mach/arch.h>
#include <asm/mach-types.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx27.h>
#include <asm/mach/time.h>
#include <mach/audmux.h>
#include <mach/irqs.h>
#include <mach/ulpi.h>
#include "devices-imx27.h"
#define OTG_PHY_CS_GPIO (GPIO_PORTB + 23)
#define USBH2_PHY_CS_GPIO (GPIO_PORTB + 24)
#define SPI1_SS0 (GPIO_PORTD + 28)
#define SPI1_SS1 (GPIO_PORTD + 27)
#define SD2_CD (GPIO_PORTC + 29)
static const int pca100_pins[] __initconst = {
/* UART1 */
PE12_PF_UART1_TXD,
PE13_PF_UART1_RXD,
PE14_PF_UART1_CTS,
PE15_PF_UART1_RTS,
/* SDHC */
PB4_PF_SD2_D0,
PB5_PF_SD2_D1,
PB6_PF_SD2_D2,
PB7_PF_SD2_D3,
PB8_PF_SD2_CMD,
PB9_PF_SD2_CLK,
SD2_CD | GPIO_GPIO | GPIO_IN,
/* FEC */
PD0_AIN_FEC_TXD0,
PD1_AIN_FEC_TXD1,
PD2_AIN_FEC_TXD2,
PD3_AIN_FEC_TXD3,
PD4_AOUT_FEC_RX_ER,
PD5_AOUT_FEC_RXD1,
PD6_AOUT_FEC_RXD2,
PD7_AOUT_FEC_RXD3,
PD8_AF_FEC_MDIO,
PD9_AIN_FEC_MDC,
PD10_AOUT_FEC_CRS,
PD11_AOUT_FEC_TX_CLK,
PD12_AOUT_FEC_RXD0,
PD13_AOUT_FEC_RX_DV,
PD14_AOUT_FEC_RX_CLK,
PD15_AOUT_FEC_COL,
PD16_AIN_FEC_TX_ER,
PF23_AIN_FEC_TX_EN,
/* SSI1 */
PC20_PF_SSI1_FS,
PC21_PF_SSI1_RXD,
PC22_PF_SSI1_TXD,
PC23_PF_SSI1_CLK,
/* onboard I2C */
PC5_PF_I2C2_SDA,
PC6_PF_I2C2_SCL,
/* external I2C */
PD17_PF_I2C_DATA,
PD18_PF_I2C_CLK,
/* SPI1 */
PD25_PF_CSPI1_RDY,
PD29_PF_CSPI1_SCLK,
PD30_PF_CSPI1_MISO,
PD31_PF_CSPI1_MOSI,
/* OTG */
OTG_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PC7_PF_USBOTG_DATA5,
PC8_PF_USBOTG_DATA6,
PC9_PF_USBOTG_DATA0,
PC10_PF_USBOTG_DATA2,
PC11_PF_USBOTG_DATA1,
PC12_PF_USBOTG_DATA4,
PC13_PF_USBOTG_DATA3,
PE0_PF_USBOTG_NXT,
PE1_PF_USBOTG_STP,
PE2_PF_USBOTG_DIR,
PE24_PF_USBOTG_CLK,
PE25_PF_USBOTG_DATA7,
/* USBH2 */
USBH2_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PA0_PF_USBH2_CLK,
PA1_PF_USBH2_DIR,
PA2_PF_USBH2_DATA7,
PA3_PF_USBH2_NXT,
PA4_PF_USBH2_STP,
PD19_AF_USBH2_DATA4,
PD20_AF_USBH2_DATA3,
PD21_AF_USBH2_DATA6,
PD22_AF_USBH2_DATA0,
PD23_AF_USBH2_DATA2,
PD24_AF_USBH2_DATA1,
PD26_AF_USBH2_DATA5,
/* display */
PA5_PF_LSCLK,
PA6_PF_LD0,
PA7_PF_LD1,
PA8_PF_LD2,
PA9_PF_LD3,
PA10_PF_LD4,
PA11_PF_LD5,
PA12_PF_LD6,
PA13_PF_LD7,
PA14_PF_LD8,
PA15_PF_LD9,
PA16_PF_LD10,
PA17_PF_LD11,
PA18_PF_LD12,
PA19_PF_LD13,
PA20_PF_LD14,
PA21_PF_LD15,
PA22_PF_LD16,
PA23_PF_LD17,
PA26_PF_PS,
PA28_PF_HSYNC,
PA29_PF_VSYNC,
PA31_PF_OE_ACD,
/* free GPIO */
GPIO_PORTC | 31 | GPIO_GPIO | GPIO_IN, /* GPIO0_IRQ */
GPIO_PORTC | 25 | GPIO_GPIO | GPIO_IN, /* GPIO1_IRQ */
GPIO_PORTE | 5 | GPIO_GPIO | GPIO_IN, /* GPIO2_IRQ */
};
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static const struct mxc_nand_platform_data
pca100_nand_board_info __initconst = {
.width = 1,
.hw_ecc = 1,
};
static const struct imxi2c_platform_data pca100_i2c1_data __initconst = {
.bitrate = 100000,
};
static struct at24_platform_data board_eeprom = {
.byte_len = 4096,
.page_size = 32,
.flags = AT24_FLAG_ADDR16,
};
static struct i2c_board_info pca100_i2c_devices[] = {
{
I2C_BOARD_INFO("at24", 0x52), /* E0=0, E1=1, E2=0 */
.platform_data = &board_eeprom,
}, {
I2C_BOARD_INFO("pcf8563", 0x51),
}, {
I2C_BOARD_INFO("lm75", 0x4a),
}
};
static struct spi_eeprom at25320 = {
.name = "at25320an",
.byte_len = 4096,
.page_size = 32,
.flags = EE_ADDR2,
};
static struct spi_board_info pca100_spi_board_info[] __initdata = {
{
.modalias = "at25",
.max_speed_hz = 30000,
.bus_num = 0,
.chip_select = 1,
.platform_data = &at25320,
},
};
static int pca100_spi_cs[] = {SPI1_SS0, SPI1_SS1};
static const struct spi_imx_master pca100_spi0_data __initconst = {
.chipselect = pca100_spi_cs,
.num_chipselect = ARRAY_SIZE(pca100_spi_cs),
};
static void pca100_ac97_warm_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT);
gpio_set_value(GPIO_PORTC + 20, 1);
udelay(2);
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(PC20_PF_SSI1_FS);
msleep(2);
}
static void pca100_ac97_cold_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT); /* FS */
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(GPIO_PORTC | 22 | GPIO_GPIO | GPIO_OUT); /* TX */
gpio_set_value(GPIO_PORTC + 22, 0);
mxc_gpio_mode(GPIO_PORTC | 28 | GPIO_GPIO | GPIO_OUT); /* reset */
gpio_set_value(GPIO_PORTC + 28, 0);
udelay(10);
gpio_set_value(GPIO_PORTC + 28, 1);
mxc_gpio_mode(PC20_PF_SSI1_FS);
mxc_gpio_mode(PC22_PF_SSI1_TXD);
msleep(2);
}
static const struct imx_ssi_platform_data pca100_ssi_pdata __initconst = {
.ac97_reset = pca100_ac97_cold_reset,
.ac97_warm_reset = pca100_ac97_warm_reset,
.flags = IMX_SSI_USE_AC97,
};
static int pca100_sdhc2_init(struct device *dev, irq_handler_t detect_irq,
void *data)
{
int ret;
ret = request_irq(IRQ_GPIOC(29), detect_irq,
IRQF_DISABLED | IRQF_TRIGGER_FALLING,
"imx-mmc-detect", data);
if (ret)
printk(KERN_ERR
"pca100: Failed to reuest irq for sd/mmc detection\n");
return ret;
}
static void pca100_sdhc2_exit(struct device *dev, void *data)
{
free_irq(IRQ_GPIOC(29), data);
}
static const struct imxmmc_platform_data sdhc_pdata __initconst = {
.init = pca100_sdhc2_init,
.exit = pca100_sdhc2_exit,
};
static int otg_phy_init(struct platform_device *pdev)
{
gpio_set_value(OTG_PHY_CS_GPIO, 0);
mdelay(10);
return mx27_initialize_usb_hw(pdev->id, MXC_EHCI_INTERFACE_DIFF_UNI);
}
static struct mxc_usbh_platform_data otg_pdata __initdata = {
.init = otg_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
};
static int usbh2_phy_init(struct platform_device *pdev)
{
gpio_set_value(USBH2_PHY_CS_GPIO, 0);
mdelay(10);
return mx27_initialize_usb_hw(pdev->id, MXC_EHCI_INTERFACE_DIFF_UNI);
}
static struct mxc_usbh_platform_data usbh2_pdata __initdata = {
.init = usbh2_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
};
static const struct fsl_usb2_platform_data otg_device_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_ULPI,
};
static int otg_mode_host;
static int __init pca100_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", pca100_otg_mode);
/* framebuffer info */
static struct imx_fb_videomode pca100_fb_modes[] = {
{
.mode = {
.name = "EMERGING-ETV570G0DHU",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 39722, /* in ps (25.175 MHz) */
.hsync_len = 30,
.left_margin = 114,
.right_margin = 16,
.vsync_len = 3,
.upper_margin = 32,
.lower_margin = 0,
},
/*
* TFT
* Pixel pol active high
* HSYNC active low
* VSYNC active low
* use HSYNC for ACD count
* line clock disable while idle
* always enable line clock even if no data
*/
.pcr = 0xf0c08080,
.bpp = 16,
},
};
static const struct imx_fb_platform_data pca100_fb_data __initconst = {
.mode = pca100_fb_modes,
.num_modes = ARRAY_SIZE(pca100_fb_modes),
.pwmr = 0x00A903FF,
.lscr1 = 0x00120300,
.dmacr = 0x00020010,
};
static void __init pca100_init(void)
{
int ret;
/* SSI unit */
mxc_audmux_v1_configure_port(MX27_AUDMUX_HPCR1_SSI0,
MXC_AUDMUX_V1_PCR_SYN | /* 4wire mode */
MXC_AUDMUX_V1_PCR_TFCSEL(3) |
MXC_AUDMUX_V1_PCR_TCLKDIR | /* clock is output */
MXC_AUDMUX_V1_PCR_RXDSEL(3));
mxc_audmux_v1_configure_port(3,
MXC_AUDMUX_V1_PCR_SYN | /* 4wire mode */
MXC_AUDMUX_V1_PCR_TFCSEL(0) |
MXC_AUDMUX_V1_PCR_TFSDIR |
MXC_AUDMUX_V1_PCR_RXDSEL(0));
ret = mxc_gpio_setup_multiple_pins(pca100_pins,
ARRAY_SIZE(pca100_pins), "PCA100");
if (ret)
printk(KERN_ERR "pca100: Failed to setup pins (%d)\n", ret);
imx27_add_imx_ssi(0, &pca100_ssi_pdata);
imx27_add_imx_uart0(&uart_pdata);
imx27_add_mxc_mmc(1, &sdhc_pdata);
imx27_add_mxc_nand(&pca100_nand_board_info);
/* only the i2c master 1 is used on this CPU card */
i2c_register_board_info(1, pca100_i2c_devices,
ARRAY_SIZE(pca100_i2c_devices));
imx27_add_imx_i2c(1, &pca100_i2c1_data);
mxc_gpio_mode(GPIO_PORTD | 28 | GPIO_GPIO | GPIO_IN);
mxc_gpio_mode(GPIO_PORTD | 27 | GPIO_GPIO | GPIO_IN);
spi_register_board_info(pca100_spi_board_info,
ARRAY_SIZE(pca100_spi_board_info));
imx27_add_spi_imx0(&pca100_spi0_data);
gpio_request(OTG_PHY_CS_GPIO, "usb-otg-cs");
gpio_direction_output(OTG_PHY_CS_GPIO, 1);
gpio_request(USBH2_PHY_CS_GPIO, "usb-host2-cs");
gpio_direction_output(USBH2_PHY_CS_GPIO, 1);
if (otg_mode_host) {
otg_pdata.otg = imx_otg_ulpi_create(ULPI_OTG_DRVVBUS |
ULPI_OTG_DRVVBUS_EXT);
if (otg_pdata.otg)
imx27_add_mxc_ehci_otg(&otg_pdata);
} else {
gpio_set_value(OTG_PHY_CS_GPIO, 0);
imx27_add_fsl_usb2_udc(&otg_device_pdata);
}
usbh2_pdata.otg = otg_ulpi_create(&mxc_ulpi_access_ops,
ULPI_OTG_DRVVBUS | ULPI_OTG_DRVVBUS_EXT);
if (usbh2_pdata.otg)
imx27_add_mxc_ehci_hs(2, &usbh2_pdata);
imx27_add_imx_fb(&pca100_fb_data);
imx27_add_fec(NULL);
imx27_add_imx2_wdt(NULL);
imx27_add_mxc_w1(NULL);
}
static void __init pca100_timer_init(void)
{
mx27_clocks_init(26000000);
}
static struct sys_timer pca100_timer = {
.init = pca100_timer_init,
};
MACHINE_START(PCA100, "phyCARD-i.MX27")
.boot_params = MX27_PHYS_OFFSET + 0x100,
.map_io = mx27_map_io,
.init_early = imx27_init_early,
.init_irq = mx27_init_irq,
.init_machine = pca100_init,
.timer = &pca100_timer,
MACHINE_END
| JijonHyuni/HyperKernel-JB | virt/arch/arm/mach-imx/mach-pca100.c | C | gpl-2.0 | 10,691 |
Bitcoin-Qt version 0.8.2 is now available from:
http://sourceforge.net/projects/bitcoin/files/Bitcoin/bitcoin-0.8.2/
This is a maintenance release that fixes many bugs and includes
a few small new features.
Please report bugs using the issue tracker at github:
https://github.com/bitcoin/bitcoin/issues
How to Upgrade
If you are running an older version, shut it down. Wait
until it has completely shut down (which might take a few minutes for older
versions), then run the installer (on Windows) or just copy over
/Applications/Bitcoin-Qt (on Mac) or bitcoind/bitcoin-qt (on Linux).
If you are upgrading from version 0.7.2 or earlier, the first time you
run 0.8.2 your blockchain files will be re-indexed, which will take
anywhere from 30 minutes to several hours, depending on the speed of
your machine.
0.8.2 Release notes
Fee Policy changes
The default fee for low-priority transactions is lowered from 0.0005 BTC
(for each 1,000 bytes in the transaction; an average transaction is
about 500 bytes) to 0.0001 BTC.
Payments (transaction outputs) of 0.543 times the minimum relay fee
(0.00005430 BTC) are now considered 'non-standard', because storing them
costs the network more than they are worth and spending them will usually
cost their owner more in transaction fees than they are worth.
Non-standard transactions are not relayed across the network, are not included
in blocks by most miners, and will not show up in your wallet until they are
included in a block.
The default fee policy can be overridden using the -mintxfee and -minrelaytxfee
command-line options, but note that we intend to replace the hard-coded fees
with code that automatically calculates and suggests appropriate fees in the
0.9 release and note that if you set a fee policy significantly different from
the rest of the network your transactions may never confirm.
Bitcoin-Qt changes
* New icon and splash screen
* Improve reporting of synchronization process
* Remove hardcoded fee recommendations
* Improve metadata of executable on MacOSX and Windows
* Move export button to individual tabs instead of toolbar
* Add "send coins" command to context menu in address book
* Add "copy txid" command to copy transaction IDs from transaction overview
* Save & restore window size and position when showing & hiding window
* New translations: Arabic (ar), Bosnian (bs), Catalan (ca), Welsh (cy),
Esperanto (eo), Interlingua (la), Latvian (lv) and many improvements
to current translations
MacOSX:
* OSX support for click-to-pay (bitcoin:) links
* Fix GUI disappearing problem on MacOSX (issue #1522)
Linux/Unix:
* Copy addresses to middle-mouse-button clipboard
Command-line options
* -walletnotify will call a command on receiving transactions that affect the wallet.
* -alertnotify will call a command on receiving an alert from the network.
* -par now takes a negative number, to leave a certain amount of cores free.
JSON-RPC API changes
* fixed a getblocktemplate bug that caused excessive CPU creating blocks.
* listunspent now lists account and address information.
* getinfo now also returns the time adjustment estimated from your peers.
* getpeerinfo now returns bytessent, bytesrecv and syncnode.
* gettxoutsetinfo returns statistics about the unspent transaction output database.
* gettxout returns information about a specific unspent transaction output.
Networking changes
* Significant changes to the networking code, reducing latency and memory consumption.
* Avoid initial block download stalling.
* Remove IRC seeding support.
* Performance tweaks.
* Added testnet DNS seeds.
Wallet compatibility/rescuing
* Cases where wallets cannot be opened in another version/installation should be reduced.
* -salvagewallet now works for encrypted wallets.
Known Bugs
* Entering the 'getblocktemplate' or 'getwork' RPC commands into the Bitcoin-Qt debug
console will cause Bitcoin-Qt to crash. Run Bitcoin-Qt with the -server command-line
option to workaround.
Thanks to everybody who contributed to the 0.8.2 release!
APerson241
Andrew Poelstra
Calvin Owens
Chuck LeDuc Díaz
Colin Dean
David Griffith
David Serrano
Eric Lombrozo
Gavin Andresen
Gregory Maxwell
Jeff Garzik
Jonas Schnelli
Larry Gilbert
Luke Dashjr
Matt Corallo
Michael Ford
Mike Hearn
Patrick Brown
Peter Todd
Philip Kaufmann
Pieter Wuille
Richard Schwab
Roman Mindalev
Scott Howard
Tariq Bashir
Warren Togami
Wladimir J. van der Laan
freewil
gladoscc
kjj2
mb300sd
super3
| projectinterzone/ITZ | src/doc/release-notes/bitcoin/release-notes-0.8.2.md | Markdown | mit | 4,464 |
/*
* Driver for the Conexant CX23885 PCIe bridge
*
* Copyright (c) 2007 Steven Toth <stoth@linuxtv.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kmod.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <asm/div64.h>
#include "cx23885.h"
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include "cx23885-ioctl.h"
#include "tuner-xc2028.h"
MODULE_DESCRIPTION("v4l2 driver module for cx23885 based TV cards");
MODULE_AUTHOR("Steven Toth <stoth@linuxtv.org>");
MODULE_LICENSE("GPL");
/* ------------------------------------------------------------------ */
static unsigned int video_nr[] = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
static unsigned int vbi_nr[] = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
static unsigned int radio_nr[] = {[0 ... (CX23885_MAXBOARDS - 1)] = UNSET };
module_param_array(video_nr, int, NULL, 0444);
module_param_array(vbi_nr, int, NULL, 0444);
module_param_array(radio_nr, int, NULL, 0444);
MODULE_PARM_DESC(video_nr, "video device numbers");
MODULE_PARM_DESC(vbi_nr, "vbi device numbers");
MODULE_PARM_DESC(radio_nr, "radio device numbers");
static unsigned int video_debug;
module_param(video_debug, int, 0644);
MODULE_PARM_DESC(video_debug, "enable debug messages [video]");
static unsigned int irq_debug;
module_param(irq_debug, int, 0644);
MODULE_PARM_DESC(irq_debug, "enable debug messages [IRQ handler]");
static unsigned int vid_limit = 16;
module_param(vid_limit, int, 0644);
MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
#define dprintk(level, fmt, arg...)\
do { if (video_debug >= level)\
printk(KERN_DEBUG "%s/0: " fmt, dev->name, ## arg);\
} while (0)
/* ------------------------------------------------------------------- */
/* static data */
#define FORMAT_FLAGS_PACKED 0x01
static struct cx23885_fmt formats[] = {
{
.name = "8 bpp, gray",
.fourcc = V4L2_PIX_FMT_GREY,
.depth = 8,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "15 bpp RGB, le",
.fourcc = V4L2_PIX_FMT_RGB555,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "15 bpp RGB, be",
.fourcc = V4L2_PIX_FMT_RGB555X,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "16 bpp RGB, le",
.fourcc = V4L2_PIX_FMT_RGB565,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "16 bpp RGB, be",
.fourcc = V4L2_PIX_FMT_RGB565X,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "24 bpp RGB, le",
.fourcc = V4L2_PIX_FMT_BGR24,
.depth = 24,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "32 bpp RGB, le",
.fourcc = V4L2_PIX_FMT_BGR32,
.depth = 32,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "32 bpp RGB, be",
.fourcc = V4L2_PIX_FMT_RGB32,
.depth = 32,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "4:2:2, packed, YUYV",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
}, {
.name = "4:2:2, packed, UYVY",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = 16,
.flags = FORMAT_FLAGS_PACKED,
},
};
static struct cx23885_fmt *format_by_fourcc(unsigned int fourcc)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(formats); i++)
if (formats[i].fourcc == fourcc)
return formats+i;
printk(KERN_ERR "%s(0x%08x) NOT FOUND\n", __func__, fourcc);
return NULL;
}
/* ------------------------------------------------------------------- */
static const struct v4l2_queryctrl no_ctl = {
.name = "42",
.flags = V4L2_CTRL_FLAG_DISABLED,
};
static struct cx23885_ctrl cx23885_ctls[] = {
/* --- video --- */
{
.v = {
.id = V4L2_CID_BRIGHTNESS,
.name = "Brightness",
.minimum = 0x00,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f,
.type = V4L2_CTRL_TYPE_INTEGER,
},
.off = 128,
.reg = LUMA_CTRL,
.mask = 0x00ff,
.shift = 0,
}, {
.v = {
.id = V4L2_CID_CONTRAST,
.name = "Contrast",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x3f,
.type = V4L2_CTRL_TYPE_INTEGER,
},
.off = 0,
.reg = LUMA_CTRL,
.mask = 0xff00,
.shift = 8,
}, {
.v = {
.id = V4L2_CID_HUE,
.name = "Hue",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f,
.type = V4L2_CTRL_TYPE_INTEGER,
},
.off = 128,
.reg = CHROMA_CTRL,
.mask = 0xff0000,
.shift = 16,
}, {
/* strictly, this only describes only U saturation.
* V saturation is handled specially through code.
*/
.v = {
.id = V4L2_CID_SATURATION,
.name = "Saturation",
.minimum = 0,
.maximum = 0xff,
.step = 1,
.default_value = 0x7f,
.type = V4L2_CTRL_TYPE_INTEGER,
},
.off = 0,
.reg = CHROMA_CTRL,
.mask = 0x00ff,
.shift = 0,
}, {
/* --- audio --- */
.v = {
.id = V4L2_CID_AUDIO_MUTE,
.name = "Mute",
.minimum = 0,
.maximum = 1,
.default_value = 1,
.type = V4L2_CTRL_TYPE_BOOLEAN,
},
.reg = PATH1_CTL1,
.mask = (0x1f << 24),
.shift = 24,
}, {
.v = {
.id = V4L2_CID_AUDIO_VOLUME,
.name = "Volume",
.minimum = 0,
.maximum = 0x3f,
.step = 1,
.default_value = 0x3f,
.type = V4L2_CTRL_TYPE_INTEGER,
},
.reg = PATH1_VOL_CTL,
.mask = 0xff,
.shift = 0,
}
};
static const int CX23885_CTLS = ARRAY_SIZE(cx23885_ctls);
/* Must be sorted from low to high control ID! */
static const u32 cx23885_user_ctrls[] = {
V4L2_CID_USER_CLASS,
V4L2_CID_BRIGHTNESS,
V4L2_CID_CONTRAST,
V4L2_CID_SATURATION,
V4L2_CID_HUE,
V4L2_CID_AUDIO_VOLUME,
V4L2_CID_AUDIO_MUTE,
0
};
static const u32 *ctrl_classes[] = {
cx23885_user_ctrls,
NULL
};
static void cx23885_video_wakeup(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q, u32 count)
{
struct cx23885_buffer *buf;
int bc;
for (bc = 0;; bc++) {
if (list_empty(&q->active))
break;
buf = list_entry(q->active.next,
struct cx23885_buffer, vb.queue);
/* count comes from the hw and is is 16bit wide --
* this trick handles wrap-arounds correctly for
* up to 32767 buffers in flight... */
if ((s16) (count - buf->count) < 0)
break;
do_gettimeofday(&buf->vb.ts);
dprintk(2, "[%p/%d] wakeup reg=%d buf=%d\n", buf, buf->vb.i,
count, buf->count);
buf->vb.state = VIDEOBUF_DONE;
list_del(&buf->vb.queue);
wake_up(&buf->vb.done);
}
if (list_empty(&q->active))
del_timer(&q->timeout);
else
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
if (bc != 1)
printk(KERN_ERR "%s: %d buffers handled (should be 1)\n",
__func__, bc);
}
static int cx23885_set_tvnorm(struct cx23885_dev *dev, v4l2_std_id norm)
{
dprintk(1, "%s(norm = 0x%08x) name: [%s]\n",
__func__,
(unsigned int)norm,
v4l2_norm_to_name(norm));
dev->tvnorm = norm;
call_all(dev, core, s_std, norm);
return 0;
}
static struct video_device *cx23885_vdev_init(struct cx23885_dev *dev,
struct pci_dev *pci,
struct video_device *template,
char *type)
{
struct video_device *vfd;
dprintk(1, "%s()\n", __func__);
vfd = video_device_alloc();
if (NULL == vfd)
return NULL;
*vfd = *template;
vfd->v4l2_dev = &dev->v4l2_dev;
vfd->release = video_device_release;
snprintf(vfd->name, sizeof(vfd->name), "%s %s (%s)",
dev->name, type, cx23885_boards[dev->board].name);
video_set_drvdata(vfd, dev);
return vfd;
}
static int cx23885_ctrl_query(struct v4l2_queryctrl *qctrl)
{
int i;
if (qctrl->id < V4L2_CID_BASE ||
qctrl->id >= V4L2_CID_LASTP1)
return -EINVAL;
for (i = 0; i < CX23885_CTLS; i++)
if (cx23885_ctls[i].v.id == qctrl->id)
break;
if (i == CX23885_CTLS) {
*qctrl = no_ctl;
return 0;
}
*qctrl = cx23885_ctls[i].v;
return 0;
}
/* ------------------------------------------------------------------- */
/* resource management */
static int res_get(struct cx23885_dev *dev, struct cx23885_fh *fh,
unsigned int bit)
{
dprintk(1, "%s()\n", __func__);
if (fh->resources & bit)
/* have it already allocated */
return 1;
/* is it free? */
mutex_lock(&dev->lock);
if (dev->resources & bit) {
/* no, someone else uses it */
mutex_unlock(&dev->lock);
return 0;
}
/* it's free, grab it */
fh->resources |= bit;
dev->resources |= bit;
dprintk(1, "res: get %d\n", bit);
mutex_unlock(&dev->lock);
return 1;
}
static int res_check(struct cx23885_fh *fh, unsigned int bit)
{
return fh->resources & bit;
}
static int res_locked(struct cx23885_dev *dev, unsigned int bit)
{
return dev->resources & bit;
}
static void res_free(struct cx23885_dev *dev, struct cx23885_fh *fh,
unsigned int bits)
{
BUG_ON((fh->resources & bits) != bits);
dprintk(1, "%s()\n", __func__);
mutex_lock(&dev->lock);
fh->resources &= ~bits;
dev->resources &= ~bits;
dprintk(1, "res: put %d\n", bits);
mutex_unlock(&dev->lock);
}
static int cx23885_video_mux(struct cx23885_dev *dev, unsigned int input)
{
dprintk(1, "%s() video_mux: %d [vmux=%d, gpio=0x%x,0x%x,0x%x,0x%x]\n",
__func__,
input, INPUT(input)->vmux,
INPUT(input)->gpio0, INPUT(input)->gpio1,
INPUT(input)->gpio2, INPUT(input)->gpio3);
dev->input = input;
if (dev->board == CX23885_BOARD_MYGICA_X8506 ||
dev->board == CX23885_BOARD_MAGICPRO_PROHDTVE2) {
/* Select Analog TV */
if (INPUT(input)->type == CX23885_VMUX_TELEVISION)
cx23885_gpio_clear(dev, GPIO_0);
}
/* Tell the internal A/V decoder */
v4l2_subdev_call(dev->sd_cx25840, video, s_routing,
INPUT(input)->vmux, 0, 0);
return 0;
}
/* ------------------------------------------------------------------ */
static int cx23885_set_scale(struct cx23885_dev *dev, unsigned int width,
unsigned int height, enum v4l2_field field)
{
dprintk(1, "%s()\n", __func__);
return 0;
}
static int cx23885_start_video_dma(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q,
struct cx23885_buffer *buf)
{
dprintk(1, "%s()\n", __func__);
/* setup fifo + format */
cx23885_sram_channel_setup(dev, &dev->sram_channels[SRAM_CH01],
buf->bpl, buf->risc.dma);
cx23885_set_scale(dev, buf->vb.width, buf->vb.height, buf->vb.field);
/* reset counter */
cx_write(VID_A_GPCNT_CTL, 3);
q->count = 1;
/* enable irq */
cx23885_irq_add_enable(dev, 0x01);
cx_set(VID_A_INT_MSK, 0x000011);
/* start dma */
cx_set(DEV_CNTRL2, (1<<5));
cx_set(VID_A_DMA_CTL, 0x11); /* FIFO and RISC enable */
return 0;
}
static int cx23885_restart_video_queue(struct cx23885_dev *dev,
struct cx23885_dmaqueue *q)
{
struct cx23885_buffer *buf, *prev;
struct list_head *item;
dprintk(1, "%s()\n", __func__);
if (!list_empty(&q->active)) {
buf = list_entry(q->active.next, struct cx23885_buffer,
vb.queue);
dprintk(2, "restart_queue [%p/%d]: restart dma\n",
buf, buf->vb.i);
cx23885_start_video_dma(dev, q, buf);
list_for_each(item, &q->active) {
buf = list_entry(item, struct cx23885_buffer,
vb.queue);
buf->count = q->count++;
}
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
return 0;
}
prev = NULL;
for (;;) {
if (list_empty(&q->queued))
return 0;
buf = list_entry(q->queued.next, struct cx23885_buffer,
vb.queue);
if (NULL == prev) {
list_move_tail(&buf->vb.queue, &q->active);
cx23885_start_video_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2, "[%p/%d] restart_queue - first active\n",
buf, buf->vb.i);
} else if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_move_tail(&buf->vb.queue, &q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
prev->risc.jmp[2] = cpu_to_le32(0); /* Bits 63 - 32 */
dprintk(2, "[%p/%d] restart_queue - move to active\n",
buf, buf->vb.i);
} else {
return 0;
}
prev = buf;
}
}
static int buffer_setup(struct videobuf_queue *q, unsigned int *count,
unsigned int *size)
{
struct cx23885_fh *fh = q->priv_data;
*size = fh->fmt->depth*fh->width*fh->height >> 3;
if (0 == *count)
*count = 32;
if (*size * *count > vid_limit * 1024 * 1024)
*count = (vid_limit * 1024 * 1024) / *size;
return 0;
}
static int buffer_prepare(struct videobuf_queue *q, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct cx23885_fh *fh = q->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_buffer *buf =
container_of(vb, struct cx23885_buffer, vb);
int rc, init_buffer = 0;
u32 line0_offset, line1_offset;
struct videobuf_dmabuf *dma = videobuf_to_dma(&buf->vb);
BUG_ON(NULL == fh->fmt);
if (fh->width < 48 || fh->width > norm_maxw(dev->tvnorm) ||
fh->height < 32 || fh->height > norm_maxh(dev->tvnorm))
return -EINVAL;
buf->vb.size = (fh->width * fh->height * fh->fmt->depth) >> 3;
if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
return -EINVAL;
if (buf->fmt != fh->fmt ||
buf->vb.width != fh->width ||
buf->vb.height != fh->height ||
buf->vb.field != field) {
buf->fmt = fh->fmt;
buf->vb.width = fh->width;
buf->vb.height = fh->height;
buf->vb.field = field;
init_buffer = 1;
}
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
init_buffer = 1;
rc = videobuf_iolock(q, &buf->vb, NULL);
if (0 != rc)
goto fail;
}
if (init_buffer) {
buf->bpl = buf->vb.width * buf->fmt->depth >> 3;
switch (buf->vb.field) {
case V4L2_FIELD_TOP:
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist, 0, UNSET,
buf->bpl, 0, buf->vb.height);
break;
case V4L2_FIELD_BOTTOM:
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist, UNSET, 0,
buf->bpl, 0, buf->vb.height);
break;
case V4L2_FIELD_INTERLACED:
if (dev->tvnorm & V4L2_STD_NTSC) {
/* cx25840 transmits NTSC bottom field first */
dprintk(1, "%s() Creating NTSC risc\n",
__func__);
line0_offset = buf->bpl;
line1_offset = 0;
} else {
/* All other formats are top field first */
dprintk(1, "%s() Creating PAL/SECAM risc\n",
__func__);
line0_offset = 0;
line1_offset = buf->bpl;
}
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist, line0_offset,
line1_offset,
buf->bpl, buf->bpl,
buf->vb.height >> 1);
break;
case V4L2_FIELD_SEQ_TB:
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist,
0, buf->bpl * (buf->vb.height >> 1),
buf->bpl, 0,
buf->vb.height >> 1);
break;
case V4L2_FIELD_SEQ_BT:
cx23885_risc_buffer(dev->pci, &buf->risc,
dma->sglist,
buf->bpl * (buf->vb.height >> 1), 0,
buf->bpl, 0,
buf->vb.height >> 1);
break;
default:
BUG();
}
}
dprintk(2, "[%p/%d] buffer_prep - %dx%d %dbpp \"%s\" - dma=0x%08lx\n",
buf, buf->vb.i,
fh->width, fh->height, fh->fmt->depth, fh->fmt->name,
(unsigned long)buf->risc.dma);
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
cx23885_free_buffer(q, buf);
return rc;
}
static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf = container_of(vb,
struct cx23885_buffer, vb);
struct cx23885_buffer *prev;
struct cx23885_fh *fh = vq->priv_data;
struct cx23885_dev *dev = fh->dev;
struct cx23885_dmaqueue *q = &dev->vidq;
/* add jump to stopper */
buf->risc.jmp[0] = cpu_to_le32(RISC_JUMP | RISC_IRQ1 | RISC_CNT_INC);
buf->risc.jmp[1] = cpu_to_le32(q->stopper.dma);
buf->risc.jmp[2] = cpu_to_le32(0); /* bits 63-32 */
if (!list_empty(&q->queued)) {
list_add_tail(&buf->vb.queue, &q->queued);
buf->vb.state = VIDEOBUF_QUEUED;
dprintk(2, "[%p/%d] buffer_queue - append to queued\n",
buf, buf->vb.i);
} else if (list_empty(&q->active)) {
list_add_tail(&buf->vb.queue, &q->active);
cx23885_start_video_dma(dev, q, buf);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
mod_timer(&q->timeout, jiffies+BUFFER_TIMEOUT);
dprintk(2, "[%p/%d] buffer_queue - first active\n",
buf, buf->vb.i);
} else {
prev = list_entry(q->active.prev, struct cx23885_buffer,
vb.queue);
if (prev->vb.width == buf->vb.width &&
prev->vb.height == buf->vb.height &&
prev->fmt == buf->fmt) {
list_add_tail(&buf->vb.queue, &q->active);
buf->vb.state = VIDEOBUF_ACTIVE;
buf->count = q->count++;
prev->risc.jmp[1] = cpu_to_le32(buf->risc.dma);
/* 64 bit bits 63-32 */
prev->risc.jmp[2] = cpu_to_le32(0);
dprintk(2, "[%p/%d] buffer_queue - append to active\n",
buf, buf->vb.i);
} else {
list_add_tail(&buf->vb.queue, &q->queued);
buf->vb.state = VIDEOBUF_QUEUED;
dprintk(2, "[%p/%d] buffer_queue - first queued\n",
buf, buf->vb.i);
}
}
}
static void buffer_release(struct videobuf_queue *q,
struct videobuf_buffer *vb)
{
struct cx23885_buffer *buf = container_of(vb,
struct cx23885_buffer, vb);
cx23885_free_buffer(q, buf);
}
static struct videobuf_queue_ops cx23885_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
static struct videobuf_queue *get_queue(struct cx23885_fh *fh)
{
switch (fh->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
return &fh->vidq;
case V4L2_BUF_TYPE_VBI_CAPTURE:
return &fh->vbiq;
default:
BUG();
return NULL;
}
}
static int get_resource(struct cx23885_fh *fh)
{
switch (fh->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
return RESOURCE_VIDEO;
case V4L2_BUF_TYPE_VBI_CAPTURE:
return RESOURCE_VBI;
default:
BUG();
return 0;
}
}
static int video_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct cx23885_dev *dev = video_drvdata(file);
struct cx23885_fh *fh;
enum v4l2_buf_type type = 0;
int radio = 0;
switch (vdev->vfl_type) {
case VFL_TYPE_GRABBER:
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
break;
case VFL_TYPE_VBI:
type = V4L2_BUF_TYPE_VBI_CAPTURE;
break;
case VFL_TYPE_RADIO:
radio = 1;
break;
}
dprintk(1, "open dev=%s radio=%d type=%s\n",
video_device_node_name(vdev), radio, v4l2_type_names[type]);
/* allocate + initialize per filehandle data */
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (NULL == fh)
return -ENOMEM;
file->private_data = fh;
fh->dev = dev;
fh->radio = radio;
fh->type = type;
fh->width = 320;
fh->height = 240;
fh->fmt = format_by_fourcc(V4L2_PIX_FMT_BGR24);
videobuf_queue_sg_init(&fh->vidq, &cx23885_video_qops,
&dev->pci->dev, &dev->slock,
V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_INTERLACED,
sizeof(struct cx23885_buffer),
fh, NULL);
dprintk(1, "post videobuf_queue_init()\n");
return 0;
}
static ssize_t video_read(struct file *file, char __user *data,
size_t count, loff_t *ppos)
{
struct cx23885_fh *fh = file->private_data;
switch (fh->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
if (res_locked(fh->dev, RESOURCE_VIDEO))
return -EBUSY;
return videobuf_read_one(&fh->vidq, data, count, ppos,
file->f_flags & O_NONBLOCK);
case V4L2_BUF_TYPE_VBI_CAPTURE:
if (!res_get(fh->dev, fh, RESOURCE_VBI))
return -EBUSY;
return videobuf_read_stream(&fh->vbiq, data, count, ppos, 1,
file->f_flags & O_NONBLOCK);
default:
BUG();
return 0;
}
}
static unsigned int video_poll(struct file *file,
struct poll_table_struct *wait)
{
struct cx23885_fh *fh = file->private_data;
struct cx23885_buffer *buf;
unsigned int rc = POLLERR;
if (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type) {
if (!res_get(fh->dev, fh, RESOURCE_VBI))
return POLLERR;
return videobuf_poll_stream(file, &fh->vbiq, wait);
}
mutex_lock(&fh->vidq.vb_lock);
if (res_check(fh, RESOURCE_VIDEO)) {
/* streaming capture */
if (list_empty(&fh->vidq.stream))
goto done;
buf = list_entry(fh->vidq.stream.next,
struct cx23885_buffer, vb.stream);
} else {
/* read() capture */
buf = (struct cx23885_buffer *)fh->vidq.read_buf;
if (NULL == buf)
goto done;
}
poll_wait(file, &buf->vb.done, wait);
if (buf->vb.state == VIDEOBUF_DONE ||
buf->vb.state == VIDEOBUF_ERROR)
rc = POLLIN|POLLRDNORM;
else
rc = 0;
done:
mutex_unlock(&fh->vidq.vb_lock);
return rc;
}
static int video_release(struct file *file)
{
struct cx23885_fh *fh = file->private_data;
struct cx23885_dev *dev = fh->dev;
/* turn off overlay */
if (res_check(fh, RESOURCE_OVERLAY)) {
/* FIXME */
res_free(dev, fh, RESOURCE_OVERLAY);
}
/* stop video capture */
if (res_check(fh, RESOURCE_VIDEO)) {
videobuf_queue_cancel(&fh->vidq);
res_free(dev, fh, RESOURCE_VIDEO);
}
if (fh->vidq.read_buf) {
buffer_release(&fh->vidq, fh->vidq.read_buf);
kfree(fh->vidq.read_buf);
}
/* stop vbi capture */
if (res_check(fh, RESOURCE_VBI)) {
if (fh->vbiq.streaming)
videobuf_streamoff(&fh->vbiq);
if (fh->vbiq.reading)
videobuf_read_stop(&fh->vbiq);
res_free(dev, fh, RESOURCE_VBI);
}
videobuf_mmap_free(&fh->vidq);
file->private_data = NULL;
kfree(fh);
/* We are not putting the tuner to sleep here on exit, because
* we want to use the mpeg encoder in another session to capture
* tuner video. Closing this will result in no video to the encoder.
*/
return 0;
}
static int video_mmap(struct file *file, struct vm_area_struct *vma)
{
struct cx23885_fh *fh = file->private_data;
return videobuf_mmap_mapper(get_queue(fh), vma);
}
/* ------------------------------------------------------------------ */
/* VIDEO CTRL IOCTLS */
static int cx23885_get_control(struct cx23885_dev *dev,
struct v4l2_control *ctl)
{
dprintk(1, "%s() calling cx25840(VIDIOC_G_CTRL)\n", __func__);
call_all(dev, core, g_ctrl, ctl);
return 0;
}
static int cx23885_set_control(struct cx23885_dev *dev,
struct v4l2_control *ctl)
{
dprintk(1, "%s() calling cx25840(VIDIOC_S_CTRL)"
" (disabled - no action)\n", __func__);
return 0;
}
static void init_controls(struct cx23885_dev *dev)
{
struct v4l2_control ctrl;
int i;
for (i = 0; i < CX23885_CTLS; i++) {
ctrl.id = cx23885_ctls[i].v.id;
ctrl.value = cx23885_ctls[i].v.default_value;
cx23885_set_control(dev, &ctrl);
}
}
/* ------------------------------------------------------------------ */
/* VIDEO IOCTLS */
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx23885_fh *fh = priv;
f->fmt.pix.width = fh->width;
f->fmt.pix.height = fh->height;
f->fmt.pix.field = fh->vidq.field;
f->fmt.pix.pixelformat = fh->fmt->fourcc;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fh->fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return 0;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
struct cx23885_fmt *fmt;
enum v4l2_field field;
unsigned int maxw, maxh;
fmt = format_by_fourcc(f->fmt.pix.pixelformat);
if (NULL == fmt)
return -EINVAL;
field = f->fmt.pix.field;
maxw = norm_maxw(dev->tvnorm);
maxh = norm_maxh(dev->tvnorm);
if (V4L2_FIELD_ANY == field) {
field = (f->fmt.pix.height > maxh/2)
? V4L2_FIELD_INTERLACED
: V4L2_FIELD_BOTTOM;
}
switch (field) {
case V4L2_FIELD_TOP:
case V4L2_FIELD_BOTTOM:
maxh = maxh / 2;
break;
case V4L2_FIELD_INTERLACED:
break;
default:
return -EINVAL;
}
f->fmt.pix.field = field;
v4l_bound_align_image(&f->fmt.pix.width, 48, maxw, 2,
&f->fmt.pix.height, 32, maxh, 0, 0);
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return 0;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
struct v4l2_mbus_framefmt mbus_fmt;
int err;
dprintk(2, "%s()\n", __func__);
err = vidioc_try_fmt_vid_cap(file, priv, f);
if (0 != err)
return err;
fh->fmt = format_by_fourcc(f->fmt.pix.pixelformat);
fh->width = f->fmt.pix.width;
fh->height = f->fmt.pix.height;
fh->vidq.field = f->fmt.pix.field;
dprintk(2, "%s() width=%d height=%d field=%d\n", __func__,
fh->width, fh->height, fh->vidq.field);
v4l2_fill_mbus_format(&mbus_fmt, &f->fmt.pix, V4L2_MBUS_FMT_FIXED);
call_all(dev, video, s_mbus_fmt, &mbus_fmt);
v4l2_fill_pix_format(&f->fmt.pix, &mbus_fmt);
return 0;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
strcpy(cap->driver, "cx23885");
strlcpy(cap->card, cx23885_boards[dev->board].name,
sizeof(cap->card));
sprintf(cap->bus_info, "PCIe:%s", pci_name(dev->pci));
cap->version = CX23885_VERSION_CODE;
cap->capabilities =
V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING |
V4L2_CAP_VBI_CAPTURE;
if (UNSET != dev->tuner_type)
cap->capabilities |= V4L2_CAP_TUNER;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
if (unlikely(f->index >= ARRAY_SIZE(formats)))
return -EINVAL;
strlcpy(f->description, formats[f->index].name,
sizeof(f->description));
f->pixelformat = formats[f->index].fourcc;
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct cx23885_fh *fh = priv;
return videobuf_reqbufs(get_queue(fh), p);
}
static int vidioc_querybuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct cx23885_fh *fh = priv;
return videobuf_querybuf(get_queue(fh), p);
}
static int vidioc_qbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct cx23885_fh *fh = priv;
return videobuf_qbuf(get_queue(fh), p);
}
static int vidioc_dqbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct cx23885_fh *fh = priv;
return videobuf_dqbuf(get_queue(fh), p,
file->f_flags & O_NONBLOCK);
}
static int vidioc_streamon(struct file *file, void *priv,
enum v4l2_buf_type i)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
dprintk(1, "%s()\n", __func__);
if (unlikely(fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE))
return -EINVAL;
if (unlikely(i != fh->type))
return -EINVAL;
if (unlikely(!res_get(dev, fh, get_resource(fh))))
return -EBUSY;
return videobuf_streamon(get_queue(fh));
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
int err, res;
dprintk(1, "%s()\n", __func__);
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (i != fh->type)
return -EINVAL;
res = get_resource(fh);
err = videobuf_streamoff(get_queue(fh));
if (err < 0)
return err;
res_free(dev, fh, res);
return 0;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *tvnorms)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
dprintk(1, "%s()\n", __func__);
mutex_lock(&dev->lock);
cx23885_set_tvnorm(dev, *tvnorms);
mutex_unlock(&dev->lock);
return 0;
}
static int cx23885_enum_input(struct cx23885_dev *dev, struct v4l2_input *i)
{
static const char *iname[] = {
[CX23885_VMUX_COMPOSITE1] = "Composite1",
[CX23885_VMUX_COMPOSITE2] = "Composite2",
[CX23885_VMUX_COMPOSITE3] = "Composite3",
[CX23885_VMUX_COMPOSITE4] = "Composite4",
[CX23885_VMUX_SVIDEO] = "S-Video",
[CX23885_VMUX_COMPONENT] = "Component",
[CX23885_VMUX_TELEVISION] = "Television",
[CX23885_VMUX_CABLE] = "Cable TV",
[CX23885_VMUX_DVB] = "DVB",
[CX23885_VMUX_DEBUG] = "for debug only",
};
unsigned int n;
dprintk(1, "%s()\n", __func__);
n = i->index;
if (n >= 4)
return -EINVAL;
if (0 == INPUT(n)->type)
return -EINVAL;
i->index = n;
i->type = V4L2_INPUT_TYPE_CAMERA;
strcpy(i->name, iname[INPUT(n)->type]);
if ((CX23885_VMUX_TELEVISION == INPUT(n)->type) ||
(CX23885_VMUX_CABLE == INPUT(n)->type)) {
i->type = V4L2_INPUT_TYPE_TUNER;
i->std = CX23885_NORMS;
}
return 0;
}
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *i)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
dprintk(1, "%s()\n", __func__);
return cx23885_enum_input(dev, i);
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
*i = dev->input;
dprintk(1, "%s() returns %d\n", __func__, *i);
return 0;
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
dprintk(1, "%s(%d)\n", __func__, i);
if (i >= 4) {
dprintk(1, "%s() -EINVAL\n", __func__);
return -EINVAL;
}
mutex_lock(&dev->lock);
cx23885_video_mux(dev, i);
mutex_unlock(&dev->lock);
return 0;
}
static int vidioc_log_status(struct file *file, void *priv)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
printk(KERN_INFO
"%s/0: ============ START LOG STATUS ============\n",
dev->name);
call_all(dev, core, log_status);
printk(KERN_INFO
"%s/0: ============= END LOG STATUS =============\n",
dev->name);
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qctrl)
{
qctrl->id = v4l2_ctrl_next(ctrl_classes, qctrl->id);
if (unlikely(qctrl->id == 0))
return -EINVAL;
return cx23885_ctrl_query(qctrl);
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctl)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
return cx23885_get_control(dev, ctl);
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctl)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
return cx23885_set_control(dev, ctl);
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
if (0 != t->index)
return -EINVAL;
strcpy(t->name, "Television");
t->type = V4L2_TUNER_ANALOG_TV;
t->capability = V4L2_TUNER_CAP_NORM;
t->rangehigh = 0xffffffffUL;
t->signal = 0xffff ; /* LOCKED */
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *t)
{
struct cx23885_dev *dev = ((struct cx23885_fh *)priv)->dev;
if (UNSET == dev->tuner_type)
return -EINVAL;
if (0 != t->index)
return -EINVAL;
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
/* f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; */
f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
f->frequency = dev->freq;
call_all(dev, tuner, g_frequency, f);
return 0;
}
static int cx23885_set_freq(struct cx23885_dev *dev, struct v4l2_frequency *f)
{
if (unlikely(UNSET == dev->tuner_type))
return -EINVAL;
if (unlikely(f->tuner != 0))
return -EINVAL;
mutex_lock(&dev->lock);
dev->freq = f->frequency;
call_all(dev, tuner, s_frequency, f);
/* When changing channels it is required to reset TVAUDIO */
msleep(10);
mutex_unlock(&dev->lock);
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct cx23885_fh *fh = priv;
struct cx23885_dev *dev = fh->dev;
if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV))
return -EINVAL;
if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO))
return -EINVAL;
return
cx23885_set_freq(dev, f);
}
/* ----------------------------------------------------------- */
static void cx23885_vid_timeout(unsigned long data)
{
struct cx23885_dev *dev = (struct cx23885_dev *)data;
struct cx23885_dmaqueue *q = &dev->vidq;
struct cx23885_buffer *buf;
unsigned long flags;
cx23885_sram_channel_dump(dev, &dev->sram_channels[SRAM_CH01]);
cx_clear(VID_A_DMA_CTL, 0x11);
spin_lock_irqsave(&dev->slock, flags);
while (!list_empty(&q->active)) {
buf = list_entry(q->active.next,
struct cx23885_buffer, vb.queue);
list_del(&buf->vb.queue);
buf->vb.state = VIDEOBUF_ERROR;
wake_up(&buf->vb.done);
printk(KERN_ERR "%s/0: [%p/%d] timeout - dma=0x%08lx\n",
dev->name, buf, buf->vb.i,
(unsigned long)buf->risc.dma);
}
cx23885_restart_video_queue(dev, q);
spin_unlock_irqrestore(&dev->slock, flags);
}
int cx23885_video_irq(struct cx23885_dev *dev, u32 status)
{
u32 mask, count;
int handled = 0;
mask = cx_read(VID_A_INT_MSK);
if (0 == (status & mask))
return handled;
cx_write(VID_A_INT_STAT, status);
dprintk(2, "%s() status = 0x%08x\n", __func__, status);
/* risc op code error */
if (status & (1 << 16)) {
printk(KERN_WARNING "%s/0: video risc op code error\n",
dev->name);
cx_clear(VID_A_DMA_CTL, 0x11);
cx23885_sram_channel_dump(dev, &dev->sram_channels[SRAM_CH01]);
}
/* risc1 y */
if (status & 0x01) {
spin_lock(&dev->slock);
count = cx_read(VID_A_GPCNT);
cx23885_video_wakeup(dev, &dev->vidq, count);
spin_unlock(&dev->slock);
handled++;
}
/* risc2 y */
if (status & 0x10) {
dprintk(2, "stopper video\n");
spin_lock(&dev->slock);
cx23885_restart_video_queue(dev, &dev->vidq);
spin_unlock(&dev->slock);
handled++;
}
return handled;
}
/* ----------------------------------------------------------- */
/* exported stuff */
static const struct v4l2_file_operations video_fops = {
.owner = THIS_MODULE,
.open = video_open,
.release = video_release,
.read = video_read,
.poll = video_poll,
.mmap = video_mmap,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops video_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_g_fmt_vbi_cap = cx23885_vbi_fmt,
.vidioc_try_fmt_vbi_cap = cx23885_vbi_fmt,
.vidioc_s_fmt_vbi_cap = cx23885_vbi_fmt,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_log_status = vidioc_log_status,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_g_chip_ident = cx23885_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = cx23885_g_register,
.vidioc_s_register = cx23885_s_register,
#endif
};
static struct video_device cx23885_vbi_template;
static struct video_device cx23885_video_template = {
.name = "cx23885-video",
.fops = &video_fops,
.ioctl_ops = &video_ioctl_ops,
.tvnorms = CX23885_NORMS,
.current_norm = V4L2_STD_NTSC_M,
};
static const struct v4l2_file_operations radio_fops = {
.owner = THIS_MODULE,
.open = video_open,
.release = video_release,
.ioctl = video_ioctl2,
};
void cx23885_video_unregister(struct cx23885_dev *dev)
{
dprintk(1, "%s()\n", __func__);
cx23885_irq_remove(dev, 0x01);
if (dev->video_dev) {
if (video_is_registered(dev->video_dev))
video_unregister_device(dev->video_dev);
else
video_device_release(dev->video_dev);
dev->video_dev = NULL;
btcx_riscmem_free(dev->pci, &dev->vidq.stopper);
}
}
int cx23885_video_register(struct cx23885_dev *dev)
{
int err;
dprintk(1, "%s()\n", __func__);
spin_lock_init(&dev->slock);
/* Initialize VBI template */
memcpy(&cx23885_vbi_template, &cx23885_video_template,
sizeof(cx23885_vbi_template));
strcpy(cx23885_vbi_template.name, "cx23885-vbi");
dev->tvnorm = cx23885_video_template.current_norm;
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
INIT_LIST_HEAD(&dev->vidq.queued);
dev->vidq.timeout.function = cx23885_vid_timeout;
dev->vidq.timeout.data = (unsigned long)dev;
init_timer(&dev->vidq.timeout);
cx23885_risc_stopper(dev->pci, &dev->vidq.stopper,
VID_A_DMA_CTL, 0x11, 0x00);
/* Don't enable VBI yet */
cx23885_irq_add_enable(dev, 0x01);
if ((TUNER_ABSENT != dev->tuner_type) &&
((dev->tuner_bus == 0) || (dev->tuner_bus == 1))) {
struct v4l2_subdev *sd = NULL;
if (dev->tuner_addr)
sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
&dev->i2c_bus[dev->tuner_bus].i2c_adap,
"tuner", dev->tuner_addr, NULL);
else
sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
&dev->i2c_bus[dev->tuner_bus].i2c_adap,
"tuner", 0, v4l2_i2c_tuner_addrs(ADDRS_TV));
if (sd) {
struct tuner_setup tun_setup;
memset(&tun_setup, 0, sizeof(tun_setup));
tun_setup.mode_mask = T_ANALOG_TV;
tun_setup.type = dev->tuner_type;
tun_setup.addr = v4l2_i2c_subdev_addr(sd);
tun_setup.tuner_callback = cx23885_tuner_callback;
v4l2_subdev_call(sd, tuner, s_type_addr, &tun_setup);
if (dev->board == CX23885_BOARD_LEADTEK_WINFAST_PXTV1200) {
struct xc2028_ctrl ctrl = {
.fname = XC2028_DEFAULT_FIRMWARE,
.max_len = 64
};
struct v4l2_priv_tun_config cfg = {
.tuner = dev->tuner_type,
.priv = &ctrl
};
v4l2_subdev_call(sd, tuner, s_config, &cfg);
}
}
}
/* register v4l devices */
dev->video_dev = cx23885_vdev_init(dev, dev->pci,
&cx23885_video_template, "video");
err = video_register_device(dev->video_dev, VFL_TYPE_GRABBER,
video_nr[dev->nr]);
if (err < 0) {
printk(KERN_INFO "%s: can't register video device\n",
dev->name);
goto fail_unreg;
}
printk(KERN_INFO "%s/0: registered device %s [v4l2]\n",
dev->name, video_device_node_name(dev->video_dev));
/* initial device configuration */
mutex_lock(&dev->lock);
cx23885_set_tvnorm(dev, dev->tvnorm);
init_controls(dev);
cx23885_video_mux(dev, 0);
mutex_unlock(&dev->lock);
return 0;
fail_unreg:
cx23885_video_unregister(dev);
return err;
}
| JijonHyuni/HyperKernel-JB | virt/drivers/media/video/cx23885/cx23885-video.c | C | gpl-2.0 | 40,135 |
/*
* Copyright (C) 2015 Cavium, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*/
#ifndef THUNDER_BGX_H
#define THUNDER_BGX_H
#define MAX_BGX_THUNDER 8 /* Max 4 nodes, 2 per node */
#define MAX_BGX_PER_CN88XX 2
#define MAX_LMAC_PER_BGX 4
#define MAX_BGX_CHANS_PER_LMAC 16
#define MAX_DMAC_PER_LMAC 8
#define MAX_FRAME_SIZE 9216
#define MAX_DMAC_PER_LMAC_TNS_BYPASS_MODE 2
#define MAX_LMAC (MAX_BGX_PER_CN88XX * MAX_LMAC_PER_BGX)
/* Registers */
#define BGX_CMRX_CFG 0x00
#define CMR_PKT_TX_EN BIT_ULL(13)
#define CMR_PKT_RX_EN BIT_ULL(14)
#define CMR_EN BIT_ULL(15)
#define BGX_CMR_GLOBAL_CFG 0x08
#define CMR_GLOBAL_CFG_FCS_STRIP BIT_ULL(6)
#define BGX_CMRX_RX_ID_MAP 0x60
#define BGX_CMRX_RX_STAT0 0x70
#define BGX_CMRX_RX_STAT1 0x78
#define BGX_CMRX_RX_STAT2 0x80
#define BGX_CMRX_RX_STAT3 0x88
#define BGX_CMRX_RX_STAT4 0x90
#define BGX_CMRX_RX_STAT5 0x98
#define BGX_CMRX_RX_STAT6 0xA0
#define BGX_CMRX_RX_STAT7 0xA8
#define BGX_CMRX_RX_STAT8 0xB0
#define BGX_CMRX_RX_STAT9 0xB8
#define BGX_CMRX_RX_STAT10 0xC0
#define BGX_CMRX_RX_BP_DROP 0xC8
#define BGX_CMRX_RX_DMAC_CTL 0x0E8
#define BGX_CMR_RX_DMACX_CAM 0x200
#define RX_DMACX_CAM_EN BIT_ULL(48)
#define RX_DMACX_CAM_LMACID(x) (x << 49)
#define RX_DMAC_COUNT 32
#define BGX_CMR_RX_STREERING 0x300
#define RX_TRAFFIC_STEER_RULE_COUNT 8
#define BGX_CMR_CHAN_MSK_AND 0x450
#define BGX_CMR_BIST_STATUS 0x460
#define BGX_CMR_RX_LMACS 0x468
#define BGX_CMRX_TX_STAT0 0x600
#define BGX_CMRX_TX_STAT1 0x608
#define BGX_CMRX_TX_STAT2 0x610
#define BGX_CMRX_TX_STAT3 0x618
#define BGX_CMRX_TX_STAT4 0x620
#define BGX_CMRX_TX_STAT5 0x628
#define BGX_CMRX_TX_STAT6 0x630
#define BGX_CMRX_TX_STAT7 0x638
#define BGX_CMRX_TX_STAT8 0x640
#define BGX_CMRX_TX_STAT9 0x648
#define BGX_CMRX_TX_STAT10 0x650
#define BGX_CMRX_TX_STAT11 0x658
#define BGX_CMRX_TX_STAT12 0x660
#define BGX_CMRX_TX_STAT13 0x668
#define BGX_CMRX_TX_STAT14 0x670
#define BGX_CMRX_TX_STAT15 0x678
#define BGX_CMRX_TX_STAT16 0x680
#define BGX_CMRX_TX_STAT17 0x688
#define BGX_CMR_TX_LMACS 0x1000
#define BGX_SPUX_CONTROL1 0x10000
#define SPU_CTL_LOW_POWER BIT_ULL(11)
#define SPU_CTL_LOOPBACK BIT_ULL(14)
#define SPU_CTL_RESET BIT_ULL(15)
#define BGX_SPUX_STATUS1 0x10008
#define SPU_STATUS1_RCV_LNK BIT_ULL(2)
#define BGX_SPUX_STATUS2 0x10020
#define SPU_STATUS2_RCVFLT BIT_ULL(10)
#define BGX_SPUX_BX_STATUS 0x10028
#define SPU_BX_STATUS_RX_ALIGN BIT_ULL(12)
#define BGX_SPUX_BR_STATUS1 0x10030
#define SPU_BR_STATUS_BLK_LOCK BIT_ULL(0)
#define SPU_BR_STATUS_RCV_LNK BIT_ULL(12)
#define BGX_SPUX_BR_PMD_CRTL 0x10068
#define SPU_PMD_CRTL_TRAIN_EN BIT_ULL(1)
#define BGX_SPUX_BR_PMD_LP_CUP 0x10078
#define BGX_SPUX_BR_PMD_LD_CUP 0x10088
#define BGX_SPUX_BR_PMD_LD_REP 0x10090
#define BGX_SPUX_FEC_CONTROL 0x100A0
#define SPU_FEC_CTL_FEC_EN BIT_ULL(0)
#define SPU_FEC_CTL_ERR_EN BIT_ULL(1)
#define BGX_SPUX_AN_CONTROL 0x100C8
#define SPU_AN_CTL_AN_EN BIT_ULL(12)
#define SPU_AN_CTL_XNP_EN BIT_ULL(13)
#define BGX_SPUX_AN_ADV 0x100D8
#define BGX_SPUX_MISC_CONTROL 0x10218
#define SPU_MISC_CTL_INTLV_RDISP BIT_ULL(10)
#define SPU_MISC_CTL_RX_DIS BIT_ULL(12)
#define BGX_SPUX_INT 0x10220 /* +(0..3) << 20 */
#define BGX_SPUX_INT_W1S 0x10228
#define BGX_SPUX_INT_ENA_W1C 0x10230
#define BGX_SPUX_INT_ENA_W1S 0x10238
#define BGX_SPU_DBG_CONTROL 0x10300
#define SPU_DBG_CTL_AN_ARB_LINK_CHK_EN BIT_ULL(18)
#define SPU_DBG_CTL_AN_NONCE_MCT_DIS BIT_ULL(29)
#define BGX_SMUX_RX_INT 0x20000
#define BGX_SMUX_RX_JABBER 0x20030
#define BGX_SMUX_RX_CTL 0x20048
#define SMU_RX_CTL_STATUS (3ull << 0)
#define BGX_SMUX_TX_APPEND 0x20100
#define SMU_TX_APPEND_FCS_D BIT_ULL(2)
#define BGX_SMUX_TX_MIN_PKT 0x20118
#define BGX_SMUX_TX_INT 0x20140
#define BGX_SMUX_TX_CTL 0x20178
#define SMU_TX_CTL_DIC_EN BIT_ULL(0)
#define SMU_TX_CTL_UNI_EN BIT_ULL(1)
#define SMU_TX_CTL_LNK_STATUS (3ull << 4)
#define BGX_SMUX_TX_THRESH 0x20180
#define BGX_SMUX_CTL 0x20200
#define SMU_CTL_RX_IDLE BIT_ULL(0)
#define SMU_CTL_TX_IDLE BIT_ULL(1)
#define BGX_GMP_PCS_MRX_CTL 0x30000
#define PCS_MRX_CTL_RST_AN BIT_ULL(9)
#define PCS_MRX_CTL_PWR_DN BIT_ULL(11)
#define PCS_MRX_CTL_AN_EN BIT_ULL(12)
#define PCS_MRX_CTL_LOOPBACK1 BIT_ULL(14)
#define PCS_MRX_CTL_RESET BIT_ULL(15)
#define BGX_GMP_PCS_MRX_STATUS 0x30008
#define PCS_MRX_STATUS_AN_CPT BIT_ULL(5)
#define BGX_GMP_PCS_ANX_AN_RESULTS 0x30020
#define BGX_GMP_PCS_SGM_AN_ADV 0x30068
#define BGX_GMP_PCS_MISCX_CTL 0x30078
#define PCS_MISC_CTL_GMX_ENO BIT_ULL(11)
#define PCS_MISC_CTL_SAMP_PT_MASK 0x7Full
#define BGX_GMP_GMI_PRTX_CFG 0x38020
#define GMI_PORT_CFG_SPEED BIT_ULL(1)
#define GMI_PORT_CFG_DUPLEX BIT_ULL(2)
#define GMI_PORT_CFG_SLOT_TIME BIT_ULL(3)
#define GMI_PORT_CFG_SPEED_MSB BIT_ULL(8)
#define BGX_GMP_GMI_RXX_JABBER 0x38038
#define BGX_GMP_GMI_TXX_THRESH 0x38210
#define BGX_GMP_GMI_TXX_APPEND 0x38218
#define BGX_GMP_GMI_TXX_SLOT 0x38220
#define BGX_GMP_GMI_TXX_BURST 0x38228
#define BGX_GMP_GMI_TXX_MIN_PKT 0x38240
#define BGX_GMP_GMI_TXX_SGMII_CTL 0x38300
#define BGX_MSIX_VEC_0_29_ADDR 0x400000 /* +(0..29) << 4 */
#define BGX_MSIX_VEC_0_29_CTL 0x400008
#define BGX_MSIX_PBA_0 0x4F0000
/* MSI-X interrupts */
#define BGX_MSIX_VECTORS 30
#define BGX_LMAC_VEC_OFFSET 7
#define BGX_MSIX_VEC_SHIFT 4
#define CMRX_INT 0
#define SPUX_INT 1
#define SMUX_RX_INT 2
#define SMUX_TX_INT 3
#define GMPX_PCS_INT 4
#define GMPX_GMI_RX_INT 5
#define GMPX_GMI_TX_INT 6
#define CMR_MEM_INT 28
#define SPU_MEM_INT 29
#define LMAC_INTR_LINK_UP BIT(0)
#define LMAC_INTR_LINK_DOWN BIT(1)
/* RX_DMAC_CTL configuration*/
enum MCAST_MODE {
MCAST_MODE_REJECT,
MCAST_MODE_ACCEPT,
MCAST_MODE_CAM_FILTER,
RSVD
};
#define BCAST_ACCEPT 1
#define CAM_ACCEPT 1
void bgx_add_dmac_addr(u64 dmac, int node, int bgx_idx, int lmac);
unsigned bgx_get_map(int node);
int bgx_get_lmac_count(int node, int bgx);
const u8 *bgx_get_lmac_mac(int node, int bgx_idx, int lmacid);
void bgx_set_lmac_mac(int node, int bgx_idx, int lmacid, const u8 *mac);
void bgx_get_lmac_link_state(int node, int bgx_idx, int lmacid, void *status);
void bgx_lmac_internal_loopback(int node, int bgx_idx,
int lmac_idx, bool enable);
u64 bgx_get_rx_stats(int node, int bgx_idx, int lmac, int idx);
u64 bgx_get_tx_stats(int node, int bgx_idx, int lmac, int idx);
#define BGX_RX_STATS_COUNT 11
#define BGX_TX_STATS_COUNT 18
struct bgx_stats {
u64 rx_stats[BGX_RX_STATS_COUNT];
u64 tx_stats[BGX_TX_STATS_COUNT];
};
enum LMAC_TYPE {
BGX_MODE_SGMII = 0, /* 1 lane, 1.250 Gbaud */
BGX_MODE_XAUI = 1, /* 4 lanes, 3.125 Gbaud */
BGX_MODE_DXAUI = 1, /* 4 lanes, 6.250 Gbaud */
BGX_MODE_RXAUI = 2, /* 2 lanes, 6.250 Gbaud */
BGX_MODE_XFI = 3, /* 1 lane, 10.3125 Gbaud */
BGX_MODE_XLAUI = 4, /* 4 lanes, 10.3125 Gbaud */
BGX_MODE_10G_KR = 3,/* 1 lane, 10.3125 Gbaud */
BGX_MODE_40G_KR = 4,/* 4 lanes, 10.3125 Gbaud */
};
enum qlm_mode {
QLM_MODE_SGMII, /* SGMII, each lane independent */
QLM_MODE_XAUI_1X4, /* 1 XAUI or DXAUI, 4 lanes */
QLM_MODE_RXAUI_2X2, /* 2 RXAUI, 2 lanes each */
QLM_MODE_XFI_4X1, /* 4 XFI, 1 lane each */
QLM_MODE_XLAUI_1X4, /* 1 XLAUI, 4 lanes each */
QLM_MODE_10G_KR_4X1, /* 4 10GBASE-KR, 1 lane each */
QLM_MODE_40G_KR4_1X4, /* 1 40GBASE-KR4, 4 lanes each */
};
#endif /* THUNDER_BGX_H */
| publicloudapp/csrutil | linux-4.3/drivers/net/ethernet/cavium/thunder/thunder_bgx.h | C | mit | 7,595 |
/*
* Copyright (c) International Business Machines Corp., 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Artem Bityutskiy (Битюцкий Артём)
*/
#include "ubi.h"
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/module.h>
/**
* ubi_dump_flash - dump a region of flash.
* @ubi: UBI device description object
* @pnum: the physical eraseblock number to dump
* @offset: the starting offset within the physical eraseblock to dump
* @len: the length of the region to dump
*/
void ubi_dump_flash(struct ubi_device *ubi, int pnum, int offset, int len)
{
int err;
size_t read;
void *buf;
loff_t addr = (loff_t)pnum * ubi->peb_size + offset;
buf = vmalloc(len);
if (!buf)
return;
err = mtd_read(ubi->mtd, addr, len, &read, buf);
if (err && err != -EUCLEAN) {
ubi_err(ubi, "err %d while reading %d bytes from PEB %d:%d, read %zd bytes",
err, len, pnum, offset, read);
goto out;
}
ubi_msg(ubi, "dumping %d bytes of data from PEB %d, offset %d",
len, pnum, offset);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1, buf, len, 1);
out:
vfree(buf);
return;
}
/**
* ubi_dump_ec_hdr - dump an erase counter header.
* @ec_hdr: the erase counter header to dump
*/
void ubi_dump_ec_hdr(const struct ubi_ec_hdr *ec_hdr)
{
pr_err("Erase counter header dump:\n");
pr_err("\tmagic %#08x\n", be32_to_cpu(ec_hdr->magic));
pr_err("\tversion %d\n", (int)ec_hdr->version);
pr_err("\tec %llu\n", (long long)be64_to_cpu(ec_hdr->ec));
pr_err("\tvid_hdr_offset %d\n", be32_to_cpu(ec_hdr->vid_hdr_offset));
pr_err("\tdata_offset %d\n", be32_to_cpu(ec_hdr->data_offset));
pr_err("\timage_seq %d\n", be32_to_cpu(ec_hdr->image_seq));
pr_err("\thdr_crc %#08x\n", be32_to_cpu(ec_hdr->hdr_crc));
pr_err("erase counter header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
ec_hdr, UBI_EC_HDR_SIZE, 1);
}
/**
* ubi_dump_vid_hdr - dump a volume identifier header.
* @vid_hdr: the volume identifier header to dump
*/
void ubi_dump_vid_hdr(const struct ubi_vid_hdr *vid_hdr)
{
pr_err("Volume identifier header dump:\n");
pr_err("\tmagic %08x\n", be32_to_cpu(vid_hdr->magic));
pr_err("\tversion %d\n", (int)vid_hdr->version);
pr_err("\tvol_type %d\n", (int)vid_hdr->vol_type);
pr_err("\tcopy_flag %d\n", (int)vid_hdr->copy_flag);
pr_err("\tcompat %d\n", (int)vid_hdr->compat);
pr_err("\tvol_id %d\n", be32_to_cpu(vid_hdr->vol_id));
pr_err("\tlnum %d\n", be32_to_cpu(vid_hdr->lnum));
pr_err("\tdata_size %d\n", be32_to_cpu(vid_hdr->data_size));
pr_err("\tused_ebs %d\n", be32_to_cpu(vid_hdr->used_ebs));
pr_err("\tdata_pad %d\n", be32_to_cpu(vid_hdr->data_pad));
pr_err("\tsqnum %llu\n",
(unsigned long long)be64_to_cpu(vid_hdr->sqnum));
pr_err("\thdr_crc %08x\n", be32_to_cpu(vid_hdr->hdr_crc));
pr_err("Volume identifier header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
vid_hdr, UBI_VID_HDR_SIZE, 1);
}
/**
* ubi_dump_vol_info - dump volume information.
* @vol: UBI volume description object
*/
void ubi_dump_vol_info(const struct ubi_volume *vol)
{
pr_err("Volume information dump:\n");
pr_err("\tvol_id %d\n", vol->vol_id);
pr_err("\treserved_pebs %d\n", vol->reserved_pebs);
pr_err("\talignment %d\n", vol->alignment);
pr_err("\tdata_pad %d\n", vol->data_pad);
pr_err("\tvol_type %d\n", vol->vol_type);
pr_err("\tname_len %d\n", vol->name_len);
pr_err("\tusable_leb_size %d\n", vol->usable_leb_size);
pr_err("\tused_ebs %d\n", vol->used_ebs);
pr_err("\tused_bytes %lld\n", vol->used_bytes);
pr_err("\tlast_eb_bytes %d\n", vol->last_eb_bytes);
pr_err("\tcorrupted %d\n", vol->corrupted);
pr_err("\tupd_marker %d\n", vol->upd_marker);
if (vol->name_len <= UBI_VOL_NAME_MAX &&
strnlen(vol->name, vol->name_len + 1) == vol->name_len) {
pr_err("\tname %s\n", vol->name);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
vol->name[0], vol->name[1], vol->name[2],
vol->name[3], vol->name[4]);
}
}
/**
* ubi_dump_vtbl_record - dump a &struct ubi_vtbl_record object.
* @r: the object to dump
* @idx: volume table index
*/
void ubi_dump_vtbl_record(const struct ubi_vtbl_record *r, int idx)
{
int name_len = be16_to_cpu(r->name_len);
pr_err("Volume table record %d dump:\n", idx);
pr_err("\treserved_pebs %d\n", be32_to_cpu(r->reserved_pebs));
pr_err("\talignment %d\n", be32_to_cpu(r->alignment));
pr_err("\tdata_pad %d\n", be32_to_cpu(r->data_pad));
pr_err("\tvol_type %d\n", (int)r->vol_type);
pr_err("\tupd_marker %d\n", (int)r->upd_marker);
pr_err("\tname_len %d\n", name_len);
if (r->name[0] == '\0') {
pr_err("\tname NULL\n");
return;
}
if (name_len <= UBI_VOL_NAME_MAX &&
strnlen(&r->name[0], name_len + 1) == name_len) {
pr_err("\tname %s\n", &r->name[0]);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
r->name[0], r->name[1], r->name[2], r->name[3],
r->name[4]);
}
pr_err("\tcrc %#08x\n", be32_to_cpu(r->crc));
}
/**
* ubi_dump_av - dump a &struct ubi_ainf_volume object.
* @av: the object to dump
*/
void ubi_dump_av(const struct ubi_ainf_volume *av)
{
pr_err("Volume attaching information dump:\n");
pr_err("\tvol_id %d\n", av->vol_id);
pr_err("\thighest_lnum %d\n", av->highest_lnum);
pr_err("\tleb_count %d\n", av->leb_count);
pr_err("\tcompat %d\n", av->compat);
pr_err("\tvol_type %d\n", av->vol_type);
pr_err("\tused_ebs %d\n", av->used_ebs);
pr_err("\tlast_data_size %d\n", av->last_data_size);
pr_err("\tdata_pad %d\n", av->data_pad);
}
/**
* ubi_dump_aeb - dump a &struct ubi_ainf_peb object.
* @aeb: the object to dump
* @type: object type: 0 - not corrupted, 1 - corrupted
*/
void ubi_dump_aeb(const struct ubi_ainf_peb *aeb, int type)
{
pr_err("eraseblock attaching information dump:\n");
pr_err("\tec %d\n", aeb->ec);
pr_err("\tpnum %d\n", aeb->pnum);
if (type == 0) {
pr_err("\tlnum %d\n", aeb->lnum);
pr_err("\tscrub %d\n", aeb->scrub);
pr_err("\tsqnum %llu\n", aeb->sqnum);
}
}
/**
* ubi_dump_mkvol_req - dump a &struct ubi_mkvol_req object.
* @req: the object to dump
*/
void ubi_dump_mkvol_req(const struct ubi_mkvol_req *req)
{
char nm[17];
pr_err("Volume creation request dump:\n");
pr_err("\tvol_id %d\n", req->vol_id);
pr_err("\talignment %d\n", req->alignment);
pr_err("\tbytes %lld\n", (long long)req->bytes);
pr_err("\tvol_type %d\n", req->vol_type);
pr_err("\tname_len %d\n", req->name_len);
memcpy(nm, req->name, 16);
nm[16] = 0;
pr_err("\t1st 16 characters of name: %s\n", nm);
}
/*
* Root directory for UBI stuff in debugfs. Contains sub-directories which
* contain the stuff specific to particular UBI devices.
*/
static struct dentry *dfs_rootdir;
/**
* ubi_debugfs_init - create UBI debugfs directory.
*
* Create UBI debugfs directory. Returns zero in case of success and a negative
* error code in case of failure.
*/
int ubi_debugfs_init(void)
{
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
dfs_rootdir = debugfs_create_dir("ubi", NULL);
if (IS_ERR_OR_NULL(dfs_rootdir)) {
int err = dfs_rootdir ? PTR_ERR(dfs_rootdir) : -ENODEV;
pr_err("UBI error: cannot create \"ubi\" debugfs directory, error %d\n",
err);
return err;
}
return 0;
}
/**
* ubi_debugfs_exit - remove UBI debugfs directory.
*/
void ubi_debugfs_exit(void)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove(dfs_rootdir);
}
/* Read an UBI debugfs file */
static ssize_t dfs_file_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
char buf[8];
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
if (dent == d->dfs_chk_gen)
val = d->chk_gen;
else if (dent == d->dfs_chk_io)
val = d->chk_io;
else if (dent == d->dfs_chk_fastmap)
val = d->chk_fastmap;
else if (dent == d->dfs_disable_bgt)
val = d->disable_bgt;
else if (dent == d->dfs_emulate_bitflips)
val = d->emulate_bitflips;
else if (dent == d->dfs_emulate_io_failures)
val = d->emulate_io_failures;
else if (dent == d->dfs_emulate_power_cut) {
snprintf(buf, sizeof(buf), "%u\n", d->emulate_power_cut);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
} else if (dent == d->dfs_power_cut_min) {
snprintf(buf, sizeof(buf), "%u\n", d->power_cut_min);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
} else if (dent == d->dfs_power_cut_max) {
snprintf(buf, sizeof(buf), "%u\n", d->power_cut_max);
count = simple_read_from_buffer(user_buf, count, ppos,
buf, strlen(buf));
goto out;
}
else {
count = -EINVAL;
goto out;
}
if (val)
buf[0] = '1';
else
buf[0] = '0';
buf[1] = '\n';
buf[2] = 0x00;
count = simple_read_from_buffer(user_buf, count, ppos, buf, 2);
out:
ubi_put_device(ubi);
return count;
}
/* Write an UBI debugfs file */
static ssize_t dfs_file_write(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
size_t buf_size;
char buf[8] = {0};
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
buf_size = min_t(size_t, count, (sizeof(buf) - 1));
if (copy_from_user(buf, user_buf, buf_size)) {
count = -EFAULT;
goto out;
}
if (dent == d->dfs_power_cut_min) {
if (kstrtouint(buf, 0, &d->power_cut_min) != 0)
count = -EINVAL;
goto out;
} else if (dent == d->dfs_power_cut_max) {
if (kstrtouint(buf, 0, &d->power_cut_max) != 0)
count = -EINVAL;
goto out;
} else if (dent == d->dfs_emulate_power_cut) {
if (kstrtoint(buf, 0, &val) != 0)
count = -EINVAL;
else
d->emulate_power_cut = val;
goto out;
}
if (buf[0] == '1')
val = 1;
else if (buf[0] == '0')
val = 0;
else {
count = -EINVAL;
goto out;
}
if (dent == d->dfs_chk_gen)
d->chk_gen = val;
else if (dent == d->dfs_chk_io)
d->chk_io = val;
else if (dent == d->dfs_chk_fastmap)
d->chk_fastmap = val;
else if (dent == d->dfs_disable_bgt)
d->disable_bgt = val;
else if (dent == d->dfs_emulate_bitflips)
d->emulate_bitflips = val;
else if (dent == d->dfs_emulate_io_failures)
d->emulate_io_failures = val;
else
count = -EINVAL;
out:
ubi_put_device(ubi);
return count;
}
/* File operations for all UBI debugfs files */
static const struct file_operations dfs_fops = {
.read = dfs_file_read,
.write = dfs_file_write,
.open = simple_open,
.llseek = no_llseek,
.owner = THIS_MODULE,
};
/**
* ubi_debugfs_init_dev - initialize debugfs for an UBI device.
* @ubi: UBI device description object
*
* This function creates all debugfs files for UBI device @ubi. Returns zero in
* case of success and a negative error code in case of failure.
*/
int ubi_debugfs_init_dev(struct ubi_device *ubi)
{
int err, n;
unsigned long ubi_num = ubi->ubi_num;
const char *fname;
struct dentry *dent;
struct ubi_debug_info *d = &ubi->dbg;
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
n = snprintf(d->dfs_dir_name, UBI_DFS_DIR_LEN + 1, UBI_DFS_DIR_NAME,
ubi->ubi_num);
if (n == UBI_DFS_DIR_LEN) {
/* The array size is too small */
fname = UBI_DFS_DIR_NAME;
dent = ERR_PTR(-EINVAL);
goto out;
}
fname = d->dfs_dir_name;
dent = debugfs_create_dir(fname, dfs_rootdir);
if (IS_ERR_OR_NULL(dent))
goto out;
d->dfs_dir = dent;
fname = "chk_gen";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_gen = dent;
fname = "chk_io";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_io = dent;
fname = "chk_fastmap";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_fastmap = dent;
fname = "tst_disable_bgt";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_disable_bgt = dent;
fname = "tst_emulate_bitflips";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_bitflips = dent;
fname = "tst_emulate_io_failures";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_io_failures = dent;
fname = "tst_emulate_power_cut";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_power_cut = dent;
fname = "tst_emulate_power_cut_min";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_power_cut_min = dent;
fname = "tst_emulate_power_cut_max";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_power_cut_max = dent;
return 0;
out_remove:
debugfs_remove_recursive(d->dfs_dir);
out:
err = dent ? PTR_ERR(dent) : -ENODEV;
ubi_err(ubi, "cannot create \"%s\" debugfs file or directory, error %d\n",
fname, err);
return err;
}
/**
* dbg_debug_exit_dev - free all debugfs files corresponding to device @ubi
* @ubi: UBI device description object
*/
void ubi_debugfs_exit_dev(struct ubi_device *ubi)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove_recursive(ubi->dbg.dfs_dir);
}
/**
* ubi_dbg_power_cut - emulate a power cut if it is time to do so
* @ubi: UBI device description object
* @caller: Flags set to indicate from where the function is being called
*
* Returns non-zero if a power cut was emulated, zero if not.
*/
int ubi_dbg_power_cut(struct ubi_device *ubi, int caller)
{
unsigned int range;
if ((ubi->dbg.emulate_power_cut & caller) == 0)
return 0;
if (ubi->dbg.power_cut_counter == 0) {
ubi->dbg.power_cut_counter = ubi->dbg.power_cut_min;
if (ubi->dbg.power_cut_max > ubi->dbg.power_cut_min) {
range = ubi->dbg.power_cut_max - ubi->dbg.power_cut_min;
ubi->dbg.power_cut_counter += prandom_u32() % range;
}
return 0;
}
ubi->dbg.power_cut_counter--;
if (ubi->dbg.power_cut_counter)
return 0;
ubi_msg(ubi, "XXXXXXXXXXXXXXX emulating a power cut XXXXXXXXXXXXXXXX");
ubi_ro_mode(ubi);
return 1;
}
| geminy/aidear | oss/linux/linux-4.7/drivers/mtd/ubi/debug.c | C | gpl-3.0 | 15,674 |
-- Delete redundant data first
DELETE FROM `spelldifficulty_dbc` WHERE `id` IN (3042,3043,3044,3045,3046,3047,3048,3053,3055,3056,3057,3058,3059,3060,3061,3063,3073,3074,3075,3076,3077,3078,3079,3080,3081,3082,3083,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095);
INSERT INTO `spelldifficulty_dbc` (`id`, `spellid0`, `spellid1`, `spellid2`, `spellid3`) VALUES
-- Razorscale spells
(3042, 62796, 63815, 0, 0), -- SPELL_FIREBALL_10 / SPELL_FIREBALL_25
(3043, 64709, 64734, 0, 0), -- SPELL_FLAME_GROUND_10 / SPELL_FLAME_GROUND_25
(3044, 63317, 64021, 0, 0), -- SPELL_FLAMEBREATH_10 / SPELL_FLAMEBREATH_25
-- Ignis spells
(3045, 62680, 63472, 0, 0), -- SPELL_FLAME_JETS_10 / SPELL_FLAME_JETS_25
(3046, 62546, 63474, 0, 0), -- SPELL_SCORCH_10 / SPELL_SCORCH_25
(3047, 62717, 63477, 0, 0), -- SPELL_SLAG_POT_10 / SPELL_SLAG_POT_25
(3048, 62836, 63536, 0, 0), -- SPELL_SLAG_IMBUED_10 / SPELL_SLAG_IMBUED_25
(3053, 62548, 63476, 0, 0); -- SPELL_GROUND_10 / SPELL_GROUND_25
| BuloZB/SkyFireEMU | sql/updates/world/40_world_spelldifficulty_dbc.sql | SQL | gpl-3.0 | 978 |
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', './util'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('./util'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.Util);
global.modal = mod.exports;
}
})(this, function (exports, module, _util) {
'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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Util = _interopRequireDefault(_util);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 300;
var BACKDROP_TRANSITION_DURATION = 150;
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
RESIZE: 'resize' + EVENT_KEY,
CLICK_DISMISS: 'click.dismiss' + EVENT_KEY,
KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY,
MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY,
MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
IN: 'in'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.navbar-fixed-top, .navbar-fixed-bottom, .is-fixed'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Modal = (function () {
function Modal(element, config) {
_classCallCheck(this, Modal);
this._config = this._getConfig(config);
this._element = element;
this._dialog = $(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._originalBodyPadding = 0;
this._scrollbarWidth = 0;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Modal, [{
key: 'toggle',
// public
value: function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
}
}, {
key: 'show',
value: function show(relatedTarget) {
var _this = this;
var showEvent = $.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
$(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, $.proxy(this.hide, this));
$(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$(_this._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($(event.target).is(_this._element)) {
that._ignoreBackdropClick = true;
}
});
});
this._showBackdrop($.proxy(this._showElement, this, relatedTarget));
}
}, {
key: 'hide',
value: function hide(event) {
if (event) {
event.preventDefault();
}
var hideEvent = $.Event(Event.HIDE);
$(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
this._setEscapeEvent();
this._setResizeEvent();
$(document).off(Event.FOCUSIN);
$(this._element).removeClass(ClassName.IN);
$(this._element).off(Event.CLICK_DISMISS);
$(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (_Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._element).one(_Util['default'].TRANSITION_END, $.proxy(this._hideModal, this)).emulateTransitionEnd(TRANSITION_DURATION);
} else {
this._hideModal();
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
$(window).off(EVENT_KEY);
$(document).off(EVENT_KEY);
$(this._element).off(EVENT_KEY);
$(this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._originalBodyPadding = null;
this._scrollbarWidth = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
_Util['default'].typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_showElement',
value: function _showElement(relatedTarget) {
var _this2 = this;
var transition = _Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// don't move modals dom position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.scrollTop = 0;
if (transition) {
_Util['default'].reflow(this._element);
}
$(this._element).addClass(ClassName.IN);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this2._config.focus) {
_this2._element.focus();
}
$(_this2._element).trigger(shownEvent);
};
if (transition) {
$(this._dialog).one(_Util['default'].TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
transitionComplete();
}
}
}, {
key: '_enforceFocus',
value: function _enforceFocus() {
var _this3 = this;
$(document).off(Event.FOCUSIN) // guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (_this3._element !== event.target && !$(_this3._element).has(event.target).length) {
_this3._element.focus();
}
});
}
}, {
key: '_setEscapeEvent',
value: function _setEscapeEvent() {
var _this4 = this;
if (this._isShown && this._config.keyboard) {
$(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === 27) {
_this4.hide();
}
});
} else if (!this._isShown) {
$(this._element).off(Event.KEYDOWN_DISMISS);
}
}
}, {
key: '_setResizeEvent',
value: function _setResizeEvent() {
if (this._isShown) {
$(window).on(Event.RESIZE, $.proxy(this._handleUpdate, this));
} else {
$(window).off(Event.RESIZE);
}
}
}, {
key: '_hideModal',
value: function _hideModal() {
var _this5 = this;
this._element.style.display = 'none';
this._showBackdrop(function () {
$(document.body).removeClass(ClassName.OPEN);
_this5._resetAdjustments();
_this5._resetScrollbar();
$(_this5._element).trigger(Event.HIDDEN);
});
}
}, {
key: '_removeBackdrop',
value: function _removeBackdrop() {
if (this._backdrop) {
$(this._backdrop).remove();
this._backdrop = null;
}
}
}, {
key: '_showBackdrop',
value: function _showBackdrop(callback) {
var _this6 = this;
var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
var doAnimate = _Util['default'].supportsTransitionEnd() && animate;
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$(this._backdrop).addClass(animate);
}
$(this._backdrop).appendTo(document.body);
$(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this6._ignoreBackdropClick) {
_this6._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this6._config.backdrop === 'static') {
_this6._element.focus();
} else {
_this6.hide();
}
});
if (doAnimate) {
_Util['default'].reflow(this._backdrop);
}
$(this._backdrop).addClass(ClassName.IN);
if (!callback) {
return;
}
if (!doAnimate) {
callback();
return;
}
$(this._backdrop).one(_Util['default'].TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else if (!this._isShown && this._backdrop) {
$(this._backdrop).removeClass(ClassName.IN);
var callbackRemove = function callbackRemove() {
_this6._removeBackdrop();
if (callback) {
callback();
}
};
if (_Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._backdrop).one(_Util['default'].TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
}
// ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
}, {
key: '_handleUpdate',
value: function _handleUpdate() {
this._adjustDialog();
}
}, {
key: '_adjustDialog',
value: function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + 'px';
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + 'px~';
}
}
}, {
key: '_resetAdjustments',
value: function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
}
}, {
key: '_checkScrollbar',
value: function _checkScrollbar() {
var fullWindowWidth = window.innerWidth;
if (!fullWindowWidth) {
// workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect();
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
this._isBodyOverflowing = document.body.clientWidth < fullWindowWidth;
this._scrollbarWidth = this._getScrollbarWidth();
}
}, {
key: '_setScrollbar',
value: function _setScrollbar() {
var bodyPadding = parseInt($(Selector.FIXED_CONTENT).css('padding-right') || 0, 10);
this._originalBodyPadding = document.body.style.paddingRight || '';
if (this._isBodyOverflowing) {
document.body.style.paddingRight = bodyPadding + (this._scrollbarWidth + 'px');
}
}
}, {
key: '_resetScrollbar',
value: function _resetScrollbar() {
document.body.style.paddingRight = this._originalBodyPadding;
}
}, {
key: '_getScrollbarWidth',
value: function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Modal.Default, $(this).data(), typeof config === 'object' && config);
if (!data) {
data = new Modal(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Modal;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this7 = this;
var target = undefined;
var selector = _Util['default'].getSelectorFromElement(this);
if (selector) {
target = $(selector)[0];
}
var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data());
if (this.tagName === 'A') {
event.preventDefault();
}
var $target = $(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($(_this7).is(':visible')) {
_this7.focus();
}
});
});
Modal._jQueryInterface.call($(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
})(jQuery);
module.exports = Modal;
});
| davygxyz/neundorfer | wp-content/themes/neundorfer/sass/bootstrap/docs/dist/js/umd/modal.js | JavaScript | gpl-2.0 | 17,699 |
/*=============================================================================
Copyright (c) 2001 Doug Gregor
Copyright (c) 1999-2003 Jaakko Jarvi
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_IGNORE_07192005_0329)
#define FUSION_IGNORE_07192005_0329
#include <boost/fusion/support/config.hpp>
namespace boost { namespace fusion
{
// Swallows any assignment (by Doug Gregor)
namespace detail
{
struct swallow_assign
{
template<typename T>
BOOST_FUSION_CONSTEXPR_THIS BOOST_FUSION_GPU_ENABLED
swallow_assign const&
operator=(const T&) const
{
return *this;
}
};
}
// "ignore" allows tuple positions to be ignored when using "tie".
BOOST_CONSTEXPR_OR_CONST detail::swallow_assign ignore = detail::swallow_assign();
}}
#endif
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/boost/fusion/container/generation/ignore.hpp | C++ | gpl-3.0 | 1,129 |
<?php
namespace Drupal\system\Controller;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface;
use Drupal\Core\Render\BareHtmlPageRendererInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Update\UpdateRegistry;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* Controller routines for database update routes.
*/
class DbUpdateController extends ControllerBase {
/**
* The keyvalue expirable factory.
*
* @var \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface
*/
protected $keyValueExpirableFactory;
/**
* A cache backend interface.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cache;
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The bare HTML page renderer.
*
* @var \Drupal\Core\Render\BareHtmlPageRendererInterface
*/
protected $bareHtmlPageRenderer;
/**
* The app root.
*
* @var string
*/
protected $root;
/**
* The post update registry.
*
* @var \Drupal\Core\Update\UpdateRegistry
*/
protected $postUpdateRegistry;
/**
* Constructs a new UpdateController.
*
* @param string $root
* The app root.
* @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expirable_factory
* The keyvalue expirable factory.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* A cache backend interface.
* @param \Drupal\Core\State\StateInterface $state
* The state service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Session\AccountInterface $account
* The current user.
* @param \Drupal\Core\Render\BareHtmlPageRendererInterface $bare_html_page_renderer
* The bare HTML page renderer.
* @param \Drupal\Core\Update\UpdateRegistry $post_update_registry
* The post update registry.
*/
public function __construct($root, KeyValueExpirableFactoryInterface $key_value_expirable_factory, CacheBackendInterface $cache, StateInterface $state, ModuleHandlerInterface $module_handler, AccountInterface $account, BareHtmlPageRendererInterface $bare_html_page_renderer, UpdateRegistry $post_update_registry) {
$this->root = $root;
$this->keyValueExpirableFactory = $key_value_expirable_factory;
$this->cache = $cache;
$this->state = $state;
$this->moduleHandler = $module_handler;
$this->account = $account;
$this->bareHtmlPageRenderer = $bare_html_page_renderer;
$this->postUpdateRegistry = $post_update_registry;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('app.root'),
$container->get('keyvalue.expirable'),
$container->get('cache.default'),
$container->get('state'),
$container->get('module_handler'),
$container->get('current_user'),
$container->get('bare_html_page_renderer'),
$container->get('update.post_update_registry')
);
}
/**
* Returns a database update page.
*
* @param string $op
* The update operation to perform. Can be any of the below:
* - info
* - selection
* - run
* - results
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*
* @return \Symfony\Component\HttpFoundation\Response
* A response object object.
*/
public function handle($op, Request $request) {
require_once $this->root . '/core/includes/install.inc';
require_once $this->root . '/core/includes/update.inc';
drupal_load_updates();
update_fix_compatibility();
if ($request->query->get('continue')) {
$_SESSION['update_ignore_warnings'] = TRUE;
}
$regions = array();
$requirements = update_check_requirements();
$severity = drupal_requirements_severity($requirements);
if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($_SESSION['update_ignore_warnings']))) {
$regions['sidebar_first'] = $this->updateTasksList('requirements');
$output = $this->requirements($severity, $requirements, $request);
}
else {
switch ($op) {
case 'selection':
$regions['sidebar_first'] = $this->updateTasksList('selection');
$output = $this->selection($request);
break;
case 'run':
$regions['sidebar_first'] = $this->updateTasksList('run');
$output = $this->triggerBatch($request);
break;
case 'info':
$regions['sidebar_first'] = $this->updateTasksList('info');
$output = $this->info($request);
break;
case 'results':
$regions['sidebar_first'] = $this->updateTasksList('results');
$output = $this->results($request);
break;
// Regular batch ops : defer to batch processing API.
default:
require_once $this->root . '/core/includes/batch.inc';
$regions['sidebar_first'] = $this->updateTasksList('run');
$output = _batch_page($request);
break;
}
}
if ($output instanceof Response) {
return $output;
}
$title = isset($output['#title']) ? $output['#title'] : $this->t('Drupal database update');
return $this->bareHtmlPageRenderer->renderBarePage($output, $title, 'maintenance_page', $regions);
}
/**
* Returns the info database update page.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return array
* A render array.
*/
protected function info(Request $request) {
// Change query-strings on css/js files to enforce reload for all users.
_drupal_flush_css_js();
// Flush the cache of all data for the update status module.
$this->keyValueExpirableFactory->get('update')->deleteAll();
$this->keyValueExpirableFactory->get('update_available_release')->deleteAll();
$build['info_header'] = array(
'#markup' => '<p>' . $this->t('Use this utility to update your database whenever a new release of Drupal or a module is installed.') . '</p><p>' . $this->t('For more detailed information, see the <a href="https://www.drupal.org/upgrade">upgrading handbook</a>. If you are unsure what these terms mean you should probably contact your hosting provider.') . '</p>',
);
$info[] = $this->t("<strong>Back up your code</strong>. Hint: when backing up module code, do not leave that backup in the 'modules' or 'sites/*/modules' directories as this may confuse Drupal's auto-discovery mechanism.");
$info[] = $this->t('Put your site into <a href=":url">maintenance mode</a>.', array(
':url' => Url::fromRoute('system.site_maintenance_mode')->toString(TRUE)->getGeneratedUrl(),
));
$info[] = $this->t('<strong>Back up your database</strong>. This process will change your database values and in case of emergency you may need to revert to a backup.');
$info[] = $this->t('Install your new files in the appropriate location, as described in the handbook.');
$build['info'] = array(
'#theme' => 'item_list',
'#list_type' => 'ol',
'#items' => $info,
);
$build['info_footer'] = array(
'#markup' => '<p>' . $this->t('When you have performed the steps above, you may proceed.') . '</p>',
);
$build['link'] = array(
'#type' => 'link',
'#title' => $this->t('Continue'),
'#attributes' => array('class' => array('button', 'button--primary')),
// @todo Revisit once https://www.drupal.org/node/2548095 is in.
'#url' => Url::fromUri('base://selection'),
);
return $build;
}
/**
* Renders a list of available database updates.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return array
* A render array.
*/
protected function selection(Request $request) {
// Make sure there is no stale theme registry.
$this->cache->deleteAll();
$count = 0;
$incompatible_count = 0;
$build['start'] = array(
'#tree' => TRUE,
'#type' => 'details',
);
// Ensure system.module's updates appear first.
$build['start']['system'] = array();
$starting_updates = array();
$incompatible_updates_exist = FALSE;
$updates_per_module = [];
foreach (['update', 'post_update'] as $update_type) {
switch ($update_type) {
case 'update':
$updates = update_get_update_list();
break;
case 'post_update':
$updates = $this->postUpdateRegistry->getPendingUpdateInformation();
break;
}
foreach ($updates as $module => $update) {
if (!isset($update['start'])) {
$build['start'][$module] = array(
'#type' => 'item',
'#title' => $module . ' module',
'#markup' => $update['warning'],
'#prefix' => '<div class="messages messages--warning">',
'#suffix' => '</div>',
);
$incompatible_updates_exist = TRUE;
continue;
}
if (!empty($update['pending'])) {
$updates_per_module += [$module => []];
$updates_per_module[$module] = array_merge($updates_per_module[$module], $update['pending']);
$build['start'][$module] = array(
'#type' => 'hidden',
'#value' => $update['start'],
);
// Store the previous items in order to merge normal updates and
// post_update functions together.
$build['start'][$module] = array(
'#theme' => 'item_list',
'#items' => $updates_per_module[$module],
'#title' => $module . ' module',
);
if ($update_type === 'update') {
$starting_updates[$module] = $update['start'];
}
}
if (isset($update['pending'])) {
$count = $count + count($update['pending']);
}
}
}
// Find and label any incompatible updates.
foreach (update_resolve_dependencies($starting_updates) as $data) {
if (!$data['allowed']) {
$incompatible_updates_exist = TRUE;
$incompatible_count++;
$module_update_key = $data['module'] . '_updates';
if (isset($build['start'][$module_update_key]['#items'][$data['number']])) {
if ($data['missing_dependencies']) {
$text = $this->t('This update will been skipped due to the following missing dependencies:') . '<em>' . implode(', ', $data['missing_dependencies']) . '</em>';
}
else {
$text = $this->t("This update will be skipped due to an error in the module's code.");
}
$build['start'][$module_update_key]['#items'][$data['number']] .= '<div class="warning">' . $text . '</div>';
}
// Move the module containing this update to the top of the list.
$build['start'] = array($module_update_key => $build['start'][$module_update_key]) + $build['start'];
}
}
// Warn the user if any updates were incompatible.
if ($incompatible_updates_exist) {
drupal_set_message($this->t('Some of the pending updates cannot be applied because their dependencies were not met.'), 'warning');
}
if (empty($count)) {
drupal_set_message($this->t('No pending updates.'));
unset($build);
$build['links'] = array(
'#theme' => 'links',
'#links' => $this->helpfulLinks($request),
);
// No updates to run, so caches won't get flushed later. Clear them now.
drupal_flush_all_caches();
}
else {
$build['help'] = array(
'#markup' => '<p>' . $this->t('The version of Drupal you are updating from has been automatically detected.') . '</p>',
'#weight' => -5,
);
if ($incompatible_count) {
$build['start']['#title'] = $this->formatPlural(
$count,
'1 pending update (@number_applied to be applied, @number_incompatible skipped)',
'@count pending updates (@number_applied to be applied, @number_incompatible skipped)',
array('@number_applied' => $count - $incompatible_count, '@number_incompatible' => $incompatible_count)
);
}
else {
$build['start']['#title'] = $this->formatPlural($count, '1 pending update', '@count pending updates');
}
// @todo Simplify with https://www.drupal.org/node/2548095
$base_url = str_replace('/update.php', '', $request->getBaseUrl());
$url = (new Url('system.db_update', array('op' => 'run')))->setOption('base_url', $base_url);
$build['link'] = array(
'#type' => 'link',
'#title' => $this->t('Apply pending updates'),
'#attributes' => array('class' => array('button', 'button--primary')),
'#weight' => 5,
'#url' => $url,
'#access' => $url->access($this->currentUser()),
);
}
return $build;
}
/**
* Displays results of the update script with any accompanying errors.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return array
* A render array.
*/
protected function results(Request $request) {
// @todo Simplify with https://www.drupal.org/node/2548095
$base_url = str_replace('/update.php', '', $request->getBaseUrl());
// Report end result.
$dblog_exists = $this->moduleHandler->moduleExists('dblog');
if ($dblog_exists && $this->account->hasPermission('access site reports')) {
$log_message = $this->t('All errors have been <a href=":url">logged</a>.', array(
':url' => Url::fromRoute('dblog.overview')->setOption('base_url', $base_url)->toString(TRUE)->getGeneratedUrl(),
));
}
else {
$log_message = $this->t('All errors have been logged.');
}
if (!empty($_SESSION['update_success'])) {
$message = '<p>' . $this->t('Updates were attempted. If you see no failures below, you may proceed happily back to your <a href=":url">site</a>. Otherwise, you may need to update your database manually.', array(':url' => Url::fromRoute('<front>')->setOption('base_url', $base_url)->toString(TRUE)->getGeneratedUrl())) . ' ' . $log_message . '</p>';
}
else {
$last = reset($_SESSION['updates_remaining']);
list($module, $version) = array_pop($last);
$message = '<p class="error">' . $this->t('The update process was aborted prematurely while running <strong>update #@version in @module.module</strong>.', array(
'@version' => $version,
'@module' => $module,
)) . ' ' . $log_message;
if ($dblog_exists) {
$message .= ' ' . $this->t('You may need to check the <code>watchdog</code> database table manually.');
}
$message .= '</p>';
}
if (Settings::get('update_free_access')) {
$message .= '<p>' . $this->t("<strong>Reminder: don't forget to set the <code>\$settings['update_free_access']</code> value in your <code>settings.php</code> file back to <code>FALSE</code>.</strong>") . '</p>';
}
$build['message'] = array(
'#markup' => $message,
);
$build['links'] = array(
'#theme' => 'links',
'#links' => $this->helpfulLinks($request),
);
// Output a list of info messages.
if (!empty($_SESSION['update_results'])) {
$all_messages = array();
foreach ($_SESSION['update_results'] as $module => $updates) {
if ($module != '#abort') {
$module_has_message = FALSE;
$info_messages = array();
foreach ($updates as $name => $queries) {
$messages = array();
foreach ($queries as $query) {
// If there is no message for this update, don't show anything.
if (empty($query['query'])) {
continue;
}
if ($query['success']) {
$messages[] = array(
'#wrapper_attributes' => array('class' => array('success')),
'#markup' => $query['query'],
);
}
else {
$messages[] = array(
'#wrapper_attributes' => array('class' => array('failure')),
'#markup' => '<strong>' . $this->t('Failed:') . '</strong> ' . $query['query'],
);
}
}
if ($messages) {
$module_has_message = TRUE;
if (is_numeric($name)) {
$title = $this->t('Update #@count', ['@count' => $name]);
}
else {
$title = $this->t('Update @name', ['@name' => trim($name, '_')]);
}
$info_messages[] = array(
'#theme' => 'item_list',
'#items' => $messages,
'#title' => $title,
);
}
}
// If there were any messages then prefix them with the module name
// and add it to the global message list.
if ($module_has_message) {
$all_messages[] = array(
'#type' => 'container',
'#prefix' => '<h3>' . $this->t('@module module', array('@module' => $module)) . '</h3>',
'#children' => $info_messages,
);
}
}
}
if ($all_messages) {
$build['query_messages'] = array(
'#type' => 'container',
'#children' => $all_messages,
'#attributes' => array('class' => array('update-results')),
'#prefix' => '<h2>' . $this->t('The following updates returned messages:') . '</h2>',
);
}
}
unset($_SESSION['update_results']);
unset($_SESSION['update_success']);
unset($_SESSION['update_ignore_warnings']);
return $build;
}
/**
* Renders a list of requirement errors or warnings.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return array
* A render array.
*/
public function requirements($severity, array $requirements, Request $request) {
$options = $severity == REQUIREMENT_WARNING ? array('continue' => 1) : array();
// @todo Revisit once https://www.drupal.org/node/2548095 is in. Something
// like Url::fromRoute('system.db_update')->setOptions() should then be
// possible.
$try_again_url = Url::fromUri($request->getUriForPath(''))->setOptions(['query' => $options])->toString(TRUE)->getGeneratedUrl();
$build['status_report'] = array(
'#theme' => 'status_report',
'#requirements' => $requirements,
'#suffix' => $this->t('Check the messages and <a href=":url">try again</a>.', array(':url' => $try_again_url))
);
$build['#title'] = $this->t('Requirements problem');
return $build;
}
/**
* Provides the update task list render array.
*
* @param string $active
* The active task.
* Can be one of 'requirements', 'info', 'selection', 'run', 'results'.
*
* @return array
* A render array.
*/
protected function updateTasksList($active = NULL) {
// Default list of tasks.
$tasks = array(
'requirements' => $this->t('Verify requirements'),
'info' => $this->t('Overview'),
'selection' => $this->t('Review updates'),
'run' => $this->t('Run updates'),
'results' => $this->t('Review log'),
);
$task_list = array(
'#theme' => 'maintenance_task_list',
'#items' => $tasks,
'#active' => $active,
);
return $task_list;
}
/**
* Starts the database update batch process.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request object.
*/
protected function triggerBatch(Request $request) {
$maintenance_mode = $this->state->get('system.maintenance_mode', FALSE);
// Store the current maintenance mode status in the session so that it can
// be restored at the end of the batch.
$_SESSION['maintenance_mode'] = $maintenance_mode;
// During the update, always put the site into maintenance mode so that
// in-progress schema changes do not affect visiting users.
if (empty($maintenance_mode)) {
$this->state->set('system.maintenance_mode', TRUE);
}
$operations = array();
// Resolve any update dependencies to determine the actual updates that will
// be run and the order they will be run in.
$start = $this->getModuleUpdates();
$updates = update_resolve_dependencies($start);
// Store the dependencies for each update function in an array which the
// batch API can pass in to the batch operation each time it is called. (We
// do not store the entire update dependency array here because it is
// potentially very large.)
$dependency_map = array();
foreach ($updates as $function => $update) {
$dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
}
// Determine updates to be performed.
foreach ($updates as $function => $update) {
if ($update['allowed']) {
// Set the installed version of each module so updates will start at the
// correct place. (The updates are already sorted, so we can simply base
// this on the first one we come across in the above foreach loop.)
if (isset($start[$update['module']])) {
drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
unset($start[$update['module']]);
}
$operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
}
}
$post_updates = $this->postUpdateRegistry->getPendingUpdateFunctions();
if ($post_updates) {
// Now we rebuild all caches and after that execute the hook_post_update()
// functions.
$operations[] = ['drupal_flush_all_caches', []];
foreach ($post_updates as $function) {
$operations[] = ['update_invoke_post_update', [$function]];
}
}
$batch['operations'] = $operations;
$batch += array(
'title' => $this->t('Updating'),
'init_message' => $this->t('Starting updates'),
'error_message' => $this->t('An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.'),
'finished' => array('\Drupal\system\Controller\DbUpdateController', 'batchFinished'),
);
batch_set($batch);
// @todo Revisit once https://www.drupal.org/node/2548095 is in.
return batch_process(Url::fromUri('base://results'), Url::fromUri('base://start'));
}
/**
* Finishes the update process and stores the results for eventual display.
*
* After the updates run, all caches are flushed. The update results are
* stored into the session (for example, to be displayed on the update results
* page in update.php). Additionally, if the site was off-line, now that the
* update process is completed, the site is set back online.
*
* @param $success
* Indicate that the batch API tasks were all completed successfully.
* @param array $results
* An array of all the results that were updated in update_do_one().
* @param array $operations
* A list of all the operations that had not been completed by the batch API.
*/
public static function batchFinished($success, $results, $operations) {
// No updates to run, so caches won't get flushed later. Clear them now.
drupal_flush_all_caches();
$_SESSION['update_results'] = $results;
$_SESSION['update_success'] = $success;
$_SESSION['updates_remaining'] = $operations;
// Now that the update is done, we can put the site back online if it was
// previously not in maintenance mode.
if (empty($_SESSION['maintenance_mode'])) {
\Drupal::state()->set('system.maintenance_mode', FALSE);
}
unset($_SESSION['maintenance_mode']);
}
/**
* Provides links to the homepage and administration pages.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current request.
*
* @return array
* An array of links.
*/
protected function helpfulLinks(Request $request) {
// @todo Simplify with https://www.drupal.org/node/2548095
$base_url = str_replace('/update.php', '', $request->getBaseUrl());
$links['front'] = array(
'title' => $this->t('Front page'),
'url' => Url::fromRoute('<front>')->setOption('base_url', $base_url),
);
if ($this->account->hasPermission('access administration pages')) {
$links['admin-pages'] = array(
'title' => $this->t('Administration pages'),
'url' => Url::fromRoute('system.admin')->setOption('base_url', $base_url),
);
}
return $links;
}
/**
* Retrieves module updates.
*
* @return array
* The module updates that can be performed.
*/
protected function getModuleUpdates() {
$return = array();
$updates = update_get_update_list();
foreach ($updates as $module => $update) {
$return[$module] = $update['start'];
}
return $return;
}
}
| windtrader/drupalvm-d8 | web/core/modules/system/src/Controller/DbUpdateController.php | PHP | gpl-2.0 | 25,829 |
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* dlmconvert.h
*
* Copyright (C) 2004 Oracle. All rights reserved.
*/
#ifndef DLMCONVERT_H
#define DLMCONVERT_H
enum dlm_status dlmconvert_master(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock, int flags, int type);
enum dlm_status dlmconvert_remote(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_lock *lock, int flags, int type);
#endif
| CSE3320/kernel-code | linux-5.8/fs/ocfs2/dlm/dlmconvert.h | C | gpl-2.0 | 542 |
<h1
| akumar21NCSU/servo | tests/unit/net/parsable_mime/text/html/text_html_h1_20_u.html | HTML | mpl-2.0 | 9 |
"use strict";
exports.__esModule = true;
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.explode = explode;
exports.verify = verify;
exports.merge = merge;
var _virtualTypes = require("./path/lib/virtual-types");
var virtualTypes = _interopRequireWildcard(_virtualTypes);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _clone = require("lodash/clone");
var _clone2 = _interopRequireDefault(_clone);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function explode(visitor) {
if (visitor._exploded) return visitor;
visitor._exploded = true;
for (var nodeType in visitor) {
if (shouldIgnoreKey(nodeType)) continue;
var parts = nodeType.split("|");
if (parts.length === 1) continue;
var fns = visitor[nodeType];
delete visitor[nodeType];
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var part = _ref;
visitor[part] = fns;
}
}
verify(visitor);
delete visitor.__esModule;
ensureEntranceObjects(visitor);
ensureCallbackArrays(visitor);
for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var _nodeType3 = _ref2;
if (shouldIgnoreKey(_nodeType3)) continue;
var wrapper = virtualTypes[_nodeType3];
if (!wrapper) continue;
var _fns2 = visitor[_nodeType3];
for (var type in _fns2) {
_fns2[type] = wrapCheck(wrapper, _fns2[type]);
}
delete visitor[_nodeType3];
if (wrapper.types) {
for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var _type = _ref4;
if (visitor[_type]) {
mergePair(visitor[_type], _fns2);
} else {
visitor[_type] = _fns2;
}
}
} else {
mergePair(visitor, _fns2);
}
}
for (var _nodeType in visitor) {
if (shouldIgnoreKey(_nodeType)) continue;
var _fns = visitor[_nodeType];
var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType];
var deprecratedKey = t.DEPRECATED_KEYS[_nodeType];
if (deprecratedKey) {
console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey);
aliases = [deprecratedKey];
}
if (!aliases) continue;
delete visitor[_nodeType];
for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var alias = _ref3;
var existing = visitor[alias];
if (existing) {
mergePair(existing, _fns);
} else {
visitor[alias] = (0, _clone2.default)(_fns);
}
}
}
for (var _nodeType2 in visitor) {
if (shouldIgnoreKey(_nodeType2)) continue;
ensureCallbackArrays(visitor[_nodeType2]);
}
return visitor;
}
function verify(visitor) {
if (visitor._verified) return;
if (typeof visitor === "function") {
throw new Error(messages.get("traverseVerifyRootFunction"));
}
for (var nodeType in visitor) {
if (nodeType === "enter" || nodeType === "exit") {
validateVisitorMethods(nodeType, visitor[nodeType]);
}
if (shouldIgnoreKey(nodeType)) continue;
if (t.TYPES.indexOf(nodeType) < 0) {
throw new Error(messages.get("traverseVerifyNodeType", nodeType));
}
var visitors = visitor[nodeType];
if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") {
for (var visitorKey in visitors) {
if (visitorKey === "enter" || visitorKey === "exit") {
validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]);
} else {
throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey));
}
}
}
}
visitor._verified = true;
}
function validateVisitorMethods(path, val) {
var fns = [].concat(val);
for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var fn = _ref5;
if (typeof fn !== "function") {
throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn)));
}
}
}
function merge(visitors) {
var states = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
var wrapper = arguments[2];
var rootVisitor = {};
for (var i = 0; i < visitors.length; i++) {
var visitor = visitors[i];
var state = states[i];
explode(visitor);
for (var type in visitor) {
var visitorType = visitor[type];
if (state || wrapper) {
visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper);
}
var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {};
mergePair(nodeVisitor, visitorType);
}
}
return rootVisitor;
}
function wrapWithStateOrWrapper(oldVisitor, state, wrapper) {
var newVisitor = {};
var _loop = function _loop(key) {
var fns = oldVisitor[key];
if (!Array.isArray(fns)) return "continue";
fns = fns.map(function (fn) {
var newFn = fn;
if (state) {
newFn = function newFn(path) {
return fn.call(state, path, state);
};
}
if (wrapper) {
newFn = wrapper(state.key, key, newFn);
}
return newFn;
});
newVisitor[key] = fns;
};
for (var key in oldVisitor) {
var _ret = _loop(key);
if (_ret === "continue") continue;
}
return newVisitor;
}
function ensureEntranceObjects(obj) {
for (var key in obj) {
if (shouldIgnoreKey(key)) continue;
var fns = obj[key];
if (typeof fns === "function") {
obj[key] = { enter: fns };
}
}
}
function ensureCallbackArrays(obj) {
if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter];
if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit];
}
function wrapCheck(wrapper, fn) {
var newFn = function newFn(path) {
if (wrapper.checkPath(path)) {
return fn.apply(this, arguments);
}
};
newFn.toString = function () {
return fn.toString();
};
return newFn;
}
function shouldIgnoreKey(key) {
if (key[0] === "_") return true;
if (key === "enter" || key === "exit" || key === "shouldSkip") return true;
if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true;
return false;
}
function mergePair(dest, src) {
for (var key in src) {
dest[key] = [].concat(dest[key] || [], src[key]);
}
} | jintoppy/react-training | step8-unittest/node_modules/babel-plugin-transform-decorators/node_modules/babel-traverse/lib/visitors.js | JavaScript | mit | 8,665 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.