{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n"},"repo_name":{"kind":"string","value":"UK992/servo"},"path":{"kind":"string","value":"tests/wpt/web-platform-tests/accname/name_test_case_740-manual.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"mpl-2.0"},"size":{"kind":"number","value":1849,"string":"1,849"}}},{"rowIdx":115086508,"cells":{"code":{"kind":"string","value":"'use strict';\n\nvar fs = require('fs');\nvar path = require('path');\nvar readdirp = require('readdirp');\nvar handlebars = require('handlebars');\nvar async = require('./async');\n\n/**\n * Regex pattern for layout directive. {{!< layout }}\n */\nvar layoutPattern = /{{!<\\s+([A-Za-z0-9\\._\\-\\/]+)\\s*}}/;\n\n\n/**\n * Constructor\n */\nvar ExpressHbs = function() {\n this.handlebars = handlebars.create();\n this.SafeString = this.handlebars.SafeString;\n this.Utils = this.handlebars.Utils;\n this.beautify = null;\n this.beautifyrc = null;\n};\n\n\n/**\n * Defines a block into which content is inserted via `content`.\n *\n * @example\n * In layout.hbs\n *\n * {{{block \"pageStylesheets\"}}}\n */\nExpressHbs.prototype.block = function(name) {\n var val = (this.blocks[name] || []).join('\\n');\n // free mem\n this.blocks[name] = null;\n return val;\n};\n\n/**\n * Defines content for a named block declared in layout.\n *\n * @example\n *\n * {{#contentFor \"pageStylesheets\"}}\n * \n * {{/contentFor}}\n */\nExpressHbs.prototype.content = function(name, options, context) {\n var block = this.blocks[name] || (this.blocks[name] = []);\n block.push(options.fn(context));\n};\n\n/**\n * Returns the layout filepath given the template filename and layout used.\n * Backward compatible with specifying layouts in locals like 'layouts/foo',\n * but if you have specified a layoutsDir you can specify layouts in locals with just the layout name.\n *\n * @param {String} filename Path to template file.\n * @param {String} layout Layout path.\n */\nExpressHbs.prototype.layoutPath = function(filename, layout) {\n var layoutPath;\n if (layout[0] === '.') {\n layoutPath = path.resolve(path.dirname(filename), layout);\n } else if (this.layoutsDir) {\n layoutPath = path.resolve(this.layoutsDir, layout);\n } else {\n layoutPath = path.resolve(this.viewsDir, layout);\n }\n return layoutPath;\n}\n\n/**\n * Find the path of the declared layout in `str`, if any\n *\n * @param {String} str The template string to parse\n * @param {String} filename Path to template\n * @returns {String|undefined} Returns the path to layout.\n */\nExpressHbs.prototype.declaredLayoutFile = function(str, filename) {\n var matches = str.match(layoutPattern);\n if (matches) {\n var layout = matches[1];\n // behave like `require`, if '.' then relative, else look in\n // usual location (layoutsDir)\n if (this.layoutsDir && layout[0] !== '.') {\n layout = path.resolve(this.layoutsDir, layout);\n }\n return path.resolve(path.dirname(filename), layout);\n }\n};\n\n/**\n * Compiles a layout file.\n *\n * The function checks whether the layout file declares a parent layout.\n * If it does, the parent layout is loaded recursively and checked as well\n * for a parent layout, and so on, until the top layout is reached.\n * All layouts are then returned as a stack to the caller via the callback.\n *\n * @param {String} layoutFile The path to the layout file to compile\n * @param {Boolean} useCache Cache the compiled layout?\n * @param {Function} cb Callback called with layouts stack\n */\nExpressHbs.prototype.cacheLayout = function(layoutFile, useCache, cb) {\n var self = this;\n\n // assume hbs extension\n if (path.extname(layoutFile) === '') layoutFile += this._options.extname;\n\n // path is relative in directive, make it absolute\n var layoutTemplates = this.cache[layoutFile];\n if (layoutTemplates) return cb(null, layoutTemplates);\n\n fs.readFile(layoutFile, 'utf8', function(err, str) {\n if (err) return cb(err);\n\n // File path of eventual declared parent layout\n var parentLayoutFile = self.declaredLayoutFile(str, layoutFile);\n\n // This function returns the current layout stack to the caller\n var _returnLayouts = function(layouts) {\n var currentLayout;\n layouts = layouts.slice(0);\n currentLayout = self.compile(str, layoutFile);\n layouts.push(currentLayout);\n if (useCache) {\n self.cache[layoutFile] = layouts.slice(0);\n }\n cb(null, layouts);\n };\n\n if (parentLayoutFile) {\n // Recursively compile/cache parent layouts\n self.cacheLayout(parentLayoutFile, useCache, function(err, parentLayouts) {\n if (err) return cb(err);\n _returnLayouts(parentLayouts);\n });\n } else {\n // No parent layout: return current layout with an empty stack\n _returnLayouts([]);\n }\n });\n};\n\n\n/**\n * Cache partial templates found under directories configure in partialsDir.\n */\nExpressHbs.prototype.cachePartials = function(cb) {\n var self = this;\n\n if (!(this.partialsDir instanceof Array)) {\n this.partialsDir = [this.partialsDir];\n }\n\n // Use to iterate all folder in series\n var count = 0;\n\n function readNext() {\n readdirp({ root: self.partialsDir[count], fileFilter: '*.*' })\n .on('warn', function(err) {\n console.warn('Non-fatal error in express-hbs cachePartials.', err);\n })\n .on('error', function(err) {\n console.error('Fatal error in express-hbs cachePartials', err);\n return cb(err);\n })\n .on('data', function(entry) {\n if (!entry) return;\n var source = fs.readFileSync(entry.fullPath, 'utf8');\n var dirname = path.dirname(entry.path);\n dirname = dirname === '.' ? '' : dirname + '/';\n\n var name = dirname + path.basename(entry.name, path.extname(entry.name));\n self.registerPartial(name, source);\n })\n .on('end', function() {\n count += 1;\n\n // If all directories aren't read, read the next directory\n if (count < self.partialsDir.length) {\n readNext()\n } else {\n self.isPartialCachingComplete = true;\n cb && cb(null, true);\n }\n });\n }\n\n readNext();\n};\n\n\n/**\n * Express 3.x template engine compliance.\n *\n * @param {Object} options = {\n * handlebars: \"override handlebars\",\n * defaultLayout: \"path to default layout\",\n * partialsDir: \"absolute path to partials (one path or an array of paths)\",\n * layoutsDir: \"absolute path to the layouts\",\n * extname: \"extension to use\",\n * contentHelperName: \"contentFor\",\n * blockHelperName: \"block\",\n * beautify: \"{Boolean} whether to pretty print HTML\"\n * }\n *\n */\nExpressHbs.prototype.express3 = function(options) {\n var self = this;\n\n // Set defaults\n if (!options) options = {};\n if (!options.extname) options.extname = '.hbs';\n if (!options.contentHelperName) options.contentHelperName = 'contentFor';\n if (!options.blockHelperName) options.blockHelperName = 'block';\n if (!options.templateOptions) options.templateOptions = {};\n if (options.handlebars) this.handlebars = options.handlebars;\n\n this._options = options;\n if (this._options.handlebars) this.handlebars = this._options.handlebars;\n\n if (options.i18n) {\n var i18n = options.i18n;\n this.handlebars.registerHelper('__', function() {\n return i18n.__.apply(this, arguments);\n });\n this.handlebars.registerHelper('__n', function() {\n return i18n.__n.apply(this, arguments);\n });\n }\n\n this.handlebars.registerHelper(this._options.blockHelperName, function(name, options) {\n var val = self.block(name);\n if (val == '' && (typeof options.fn === 'function')) {\n val = options.fn(this);\n }\n // blocks may have async helpers\n if (val.indexOf('__aSyNcId_') >= 0) {\n if (self.asyncValues) {\n Object.keys(self.asyncValues).forEach(function (id) {\n val = val.replace(id, self.asyncValues[id]);\n val = val.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(self.asyncValues[id]));\n });\n }\n }\n return val;\n });\n\n\n\n // Pass 'this' as context of helper function to don't lose context call of helpers.\n this.handlebars.registerHelper(this._options.contentHelperName, function(name, options) {\n return self.content(name, options, this);\n });\n\n // Absolute path to partials directory.\n this.partialsDir = this._options.partialsDir;\n\n // Absolute path to the layouts directory\n this.layoutsDir = this._options.layoutsDir;\n\n // express passes this through _express3 func, gulp pass in an option\n this.viewsDir = null\n this.viewsDirOpt = this._options.viewsDir;\n\n // Cache for templates, express 3.x doesn't do this for us\n this.cache = {};\n\n // Blocks for layouts. Is this safe? What happens if the same block is used on multiple connections?\n // Isn't there a chance block and content are not in sync. The template and layout are processed asynchronously.\n this.blocks = {};\n\n // Holds the default compiled layout if specified in options configuration.\n this.defaultLayoutTemplates = null;\n\n // Keep track of if partials have been cached already or not.\n this.isPartialCachingComplete = false;\n\n return _express3.bind(this);\n};\n\n\n/**\n * Tries to load the default layout.\n *\n * @param {Boolean} useCache Whether to cache.\n */\nExpressHbs.prototype.loadDefaultLayout = function(useCache, cb) {\n var self = this;\n if (!this._options.defaultLayout) return cb();\n if (useCache && this.defaultLayoutTemplates) return cb(null, this.defaultLayoutTemplates);\n\n this.cacheLayout(this._options.defaultLayout, useCache, function(err, templates) {\n if (err) return cb(err);\n self.defaultLayoutTemplates = templates.slice(0);\n return cb(null, templates);\n });\n};\n\n\n/**\n * express 3.x template engine compliance\n *\n * @param {String} filename Full path to template.\n * @param {Object} options Is the context or locals for templates. {\n * {Object} settings - subset of Express settings, `settings.views` is\n * the views directory\n * }\n * @param {Function} cb The callback expecting the rendered template as a string.\n *\n * @example\n *\n * Example options from express\n *\n * {\n * settings: {\n * 'x-powered-by': true,\n * env: 'production',\n * views: '/home/coder/barc/code/express-hbs/example/views',\n * 'jsonp callback name': 'callback',\n * 'view cache': true,\n * 'view engine': 'hbs'\n * },\n * cache: true,\n *\n * // the rest are app-defined locals\n * title: 'My favorite veggies',\n * layout: 'layout/veggie'\n * }\n */\nfunction _express3(filename, source, options, cb) {\n // console.log('filename', filename);\n // console.log('options', options);\n\n // support running as a gulp/grunt filter outside of express\n if (arguments.length === 3) {\n cb = options;\n options = source;\n source = null;\n }\n\n this.viewsDir = options.settings.views || this.viewsDirOpt;\n var self = this;\n\n /**\n * Allow a layout to be declared as a handlebars comment to remain spec\n * compatible with handlebars.\n *\n * Valid directives\n *\n * {{!< foo}} # foo.hbs in same directory as template\n * {{!< ../layouts/default}} # default.hbs in parent layout directory\n * {{!< ../layouts/default.html}} # default.html in parent layout directory\n */\n function parseLayout(str, filename, cb) {\n var layoutFile = self.declaredLayoutFile(str, filename);\n if (layoutFile) {\n self.cacheLayout(layoutFile, options.cache, cb);\n } else {\n cb(null, null);\n }\n }\n\n /**\n * Renders `template` with given `locals` and calls `cb` with the\n * resulting HTML string.\n *\n * @param template\n * @param locals\n * @param cb\n */\n function renderTemplate(template, locals, cb) {\n var res;\n\n try {\n res = template(locals, self._options.templateOptions);\n } catch (err) {\n if (err.message) {\n err.message = '[' + template.__filename + '] ' + err.message;\n } else if (typeof err === 'string') {\n err = '[' + template.__filename + '] ' + err;\n }\n return cb(err, null);\n }\n\n // Wait for async helpers\n async.done(function (values) {\n // Save for layout. Block helpers are called within layout, not in the\n // current template.\n self.asyncValues = values;\n\n Object.keys(values).forEach(function (id) {\n res = res.replace(id, values[id]);\n res = res.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(values[id]));\n });\n cb(null, res);\n });\n }\n\n\n /**\n * Renders `template` with an optional set of nested `layoutTemplates` using\n * data in `locals`.\n */\n function render(template, locals, layoutTemplates, cb) {\n if (layoutTemplates == undefined) layoutTemplates = [];\n\n // We'll render templates from bottom to top of the stack, each template\n // being passed the rendered string of the previous ones as `body`\n var i = layoutTemplates.length - 1;\n\n var _stackRenderer = function(err, htmlStr) {\n if (err) return cb(err);\n\n if (i >= 0) {\n locals.body = htmlStr;\n renderTemplate(layoutTemplates[i--], locals, _stackRenderer);\n } else {\n cb(null, htmlStr);\n }\n };\n\n // Start the rendering with the innermost page template\n renderTemplate(template, locals, _stackRenderer);\n }\n\n\n /**\n * Lazy loads js-beautify, which shouldn't be used in production env.\n */\n function loadBeautify() {\n if (!self.beautify) {\n self.beautify = require('js-beautify').html;\n var rc = path.join(process.cwd(), '.jsbeautifyrc');\n if (fs.existsSync(rc)) {\n self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8'));\n }\n }\n }\n\n\n /**\n * Compiles a file into a template and a layoutTemplate, then renders it above.\n */\n function compileFile(locals, cb) {\n var source, info, template;\n\n if (options.cache) {\n info = self.cache[filename];\n if (info) {\n source = info.source;\n template = info.template;\n }\n }\n\n if (!info) {\n source = fs.readFileSync(filename, 'utf8');\n template = self.compile(source, filename);\n if (options.cache) {\n self.cache[filename] = { source: source, template: template };\n }\n }\n\n // Try to get the layout\n parseLayout(source, filename, function (err, layoutTemplates) {\n if (err) return cb(err);\n\n function renderIt(layoutTemplates) {\n if (self._options.beautify) {\n return render(template, locals, layoutTemplates, function(err, html) {\n if (err) return cb(err);\n loadBeautify();\n return cb(null, self.beautify(html, self.beautifyrc));\n });\n } else {\n return render(template, locals, layoutTemplates, cb);\n }\n }\n\n // Determine which layout to use\n // If options.layout is falsy, behave as if no layout should be used - suppress defaults\n if ((typeof (options.layout) !== 'undefined') && !options.layout) {\n renderIt(null);\n } else {\n // 1. Layout specified in template\n if (layoutTemplates) {\n renderIt(layoutTemplates);\n }\n\n // 2. Layout specified by options from render\n else if ((typeof (options.layout) !== 'undefined') && options.layout) {\n var layoutFile = self.layoutPath(filename, options.layout);\n self.cacheLayout(layoutFile, options.cache, function (err, layoutTemplates) {\n if (err) return cb(err);\n renderIt(layoutTemplates);\n });\n }\n\n // 3. Default layout specified when middleware was configured.\n else if (self.defaultLayoutTemplates) {\n renderIt(self.defaultLayoutTemplates);\n }\n\n // render without a template\n else renderIt(null);\n }\n });\n }\n\n // kick it off by loading default template (if any)\n this.loadDefaultLayout(options.cache, function(err) {\n if (err) return cb(err);\n\n // Force reloading of all partials if caching is not used. Inefficient but there\n // is no loading partial event.\n if (self.partialsDir && (!options.cache || !self.isPartialCachingComplete)) {\n return self.cachePartials(function(err) {\n if (err) return cb(err);\n return compileFile(options, cb);\n });\n }\n\n return compileFile(options, cb);\n });\n}\n\n/**\n * Expose useful methods.\n */\nExpressHbs.prototype.registerHelper = function(name, fn) {\n this.handlebars.registerHelper(name, fn);\n};\n\n\n/**\n * Registers a partial.\n *\n * @param {String} name The name of the partial as used in a template.\n * @param {String} source String source of the partial.\n */\nExpressHbs.prototype.registerPartial = function(name, source) {\n this.handlebars.registerPartial(name, this.compile(source));\n};\n\n\n/**\n * Compiles a string.\n *\n * @param {String} source The source to compile.\n * @param {String} filename The path used to embed into __filename for errors.\n */\nExpressHbs.prototype.compile = function(source, filename) {\n // Handlebars has a bug with comment only partial causes errors. This must\n // be a string so the block below can add a space.\n if (typeof source !== 'string') {\n throw new Error('registerPartial must be a string for empty comment workaround');\n }\n if (source.indexOf('}}') === source.length - 2) {\n source += ' ';\n }\n var compiled = this.handlebars.compile(source);\n if (filename) {\n // track for error message\n compiled.__filename = path.relative(this.viewsDir, filename).replace(path.sep, '/');\n }\n return compiled;\n}\n\n/**\n * Registers an asynchronous helper.\n *\n * @param {String} name The name of the partial as used in a template.\n * @param {String} fn The `function(options, cb)`\n */\nExpressHbs.prototype.registerAsyncHelper = function(name, fn) {\n this.handlebars.registerHelper(name, function(context) {\n return async.resolve(fn.bind(this), context);\n });\n};\n\nExpressHbs.prototype.updateTemplateOptions = function(templateOptions) {\n this._options.templateOptions = templateOptions;\n};\n\n/**\n * Creates a new instance of ExpressHbs.\n */\nExpressHbs.prototype.create = function() {\n return new ExpressHbs();\n};\n\nmodule.exports = new ExpressHbs();\n"},"repo_name":{"kind":"string","value":"vietpn/ghost-nodejs"},"path":{"kind":"string","value":"node_modules/express-hbs/lib/hbs.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":17800,"string":"17,800"}}},{"rowIdx":115086509,"cells":{"code":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.IO;\n\nnamespace System.Net\n{\n /// \n /// The FtpWebResponse class contains the result of the FTP request.\n /// \n public class FtpWebResponse : WebResponse, IDisposable\n {\n internal Stream _responseStream;\n private long _contentLength;\n private Uri _responseUri;\n private FtpStatusCode _statusCode;\n private string _statusLine;\n private WebHeaderCollection _ftpRequestHeaders;\n private DateTime _lastModified;\n private string _bannerMessage;\n private string _welcomeMessage;\n private string _exitMessage;\n\n internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage)\n {\n if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine);\n\n _responseStream = responseStream;\n if (responseStream == null && contentLength < 0)\n {\n contentLength = 0;\n }\n _contentLength = contentLength;\n _responseUri = responseUri;\n _statusCode = statusCode;\n _statusLine = statusLine;\n _lastModified = lastModified;\n _bannerMessage = bannerMessage;\n _welcomeMessage = welcomeMessage;\n _exitMessage = exitMessage;\n }\n\n internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage)\n {\n _statusCode = statusCode;\n _statusLine = statusLine;\n _exitMessage = exitMessage;\n }\n\n public override Stream GetResponseStream()\n {\n Stream responseStream = null;\n\n if (_responseStream != null)\n {\n responseStream = _responseStream;\n }\n else\n {\n responseStream = _responseStream = new EmptyStream();\n }\n return responseStream;\n }\n\n internal sealed class EmptyStream : MemoryStream\n {\n internal EmptyStream() : base(Array.Empty(), false)\n {\n }\n }\n\n internal void SetResponseStream(Stream stream)\n {\n if (stream == null || stream == Stream.Null || stream is EmptyStream)\n return;\n _responseStream = stream;\n }\n\n /// \n /// Closes the underlying FTP response stream, but does not close control connection\n /// \n public override void Close()\n {\n if (NetEventSource.IsEnabled) NetEventSource.Enter(this);\n _responseStream?.Close();\n if (NetEventSource.IsEnabled) NetEventSource.Exit(this);\n }\n\n /// \n /// Queries the length of the response\n /// \n public override long ContentLength\n {\n get\n {\n return _contentLength;\n }\n }\n\n internal void SetContentLength(long value)\n {\n _contentLength = value;\n }\n\n public override WebHeaderCollection Headers\n {\n get\n {\n if (_ftpRequestHeaders == null)\n {\n lock (this)\n {\n if (_ftpRequestHeaders == null)\n {\n _ftpRequestHeaders = new WebHeaderCollection();\n }\n }\n }\n return _ftpRequestHeaders;\n }\n }\n\n public override bool SupportsHeaders\n {\n get\n {\n return true;\n }\n }\n\n /// \n /// Shows the final Uri that the FTP request ended up on\n /// \n public override Uri ResponseUri\n {\n get\n {\n return _responseUri;\n }\n }\n\n /// \n /// Last status code retrived\n /// \n public FtpStatusCode StatusCode\n {\n get\n {\n return _statusCode;\n }\n }\n\n /// \n /// Last status line retrived\n /// \n public string StatusDescription\n {\n get\n {\n return _statusLine;\n }\n }\n\n /// \n /// Returns last modified date time for given file (null if not relavant/avail)\n /// \n public DateTime LastModified\n {\n get\n {\n return _lastModified;\n }\n }\n\n /// \n /// Returns the server message sent before user credentials are sent\n /// \n public string BannerMessage\n {\n get\n {\n return _bannerMessage;\n }\n }\n\n /// \n /// Returns the server message sent after user credentials are sent\n /// \n public string WelcomeMessage\n {\n get\n {\n return _welcomeMessage;\n }\n }\n\n /// \n /// Returns the exit sent message on shutdown\n /// \n public string ExitMessage\n {\n get\n {\n return _exitMessage;\n }\n }\n }\n}\n\n"},"repo_name":{"kind":"string","value":"krk/corefx"},"path":{"kind":"string","value":"src/System.Net.Requests/src/System/Net/FtpWebResponse.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5923,"string":"5,923"}}},{"rowIdx":115086510,"cells":{"code":{"kind":"string","value":"WebMock.disable_net_connect!(allow: 'coveralls.io')\n\n# iTunes Lookup API\nRSpec.configure do |config|\n config.before(:each) do\n # iTunes Lookup API by Apple ID\n [\"invalid\", \"\", 0, '284882215', ['338986109', 'FR']].each do |current|\n if current.kind_of? Array\n id = current[0]\n country = current[1]\n url = \"https://itunes.apple.com/lookup?id=#{id}&country=#{country}\"\n body_file = \"spec/responses/itunesLookup-#{id}_#{country}.json\"\n else\n id = current\n url = \"https://itunes.apple.com/lookup?id=#{id}\"\n body_file = \"spec/responses/itunesLookup-#{id}.json\"\n end\n stub_request(:get, url).\n with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).\n to_return(status: 200, body: File.read(body_file), headers: {})\n end\n\n # iTunes Lookup API by App Identifier\n stub_request(:get, \"https://itunes.apple.com/lookup?bundleId=com.facebook.Facebook\").\n with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).\n to_return(status: 200, body: File.read(\"spec/responses/itunesLookup-com.facebook.Facebook.json\"), headers: {})\n\n stub_request(:get, \"https://itunes.apple.com/lookup?bundleId=net.sunapps.invalid\").\n with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).\n to_return(status: 200, body: File.read(\"spec/responses/itunesLookup-net.sunapps.invalid.json\"), headers: {})\n end\nend\n\ndescribe FastlaneCore do\n describe FastlaneCore::ItunesSearchApi do\n it \"returns nil when it could not be found\" do\n expect(FastlaneCore::ItunesSearchApi.fetch(\"invalid\")).to eq(nil)\n expect(FastlaneCore::ItunesSearchApi.fetch(\"\")).to eq(nil)\n expect(FastlaneCore::ItunesSearchApi.fetch(0)).to eq(nil)\n end\n\n it \"returns the actual object if it could be found\" do\n response = FastlaneCore::ItunesSearchApi.fetch(\"284882215\")\n expect(response['kind']).to eq('software')\n expect(response['supportedDevices'].count).to be > 8\n\n expect(FastlaneCore::ItunesSearchApi.fetch_bundle_identifier(\"284882215\")).to eq('com.facebook.Facebook')\n end\n\n it \"returns the actual object if it could be found\" do\n response = FastlaneCore::ItunesSearchApi.fetch_by_identifier(\"com.facebook.Facebook\")\n expect(response['kind']).to eq('software')\n expect(response['supportedDevices'].count).to be > 8\n expect(response['trackId']).to eq(284_882_215)\n end\n\n it \"can find country specific object\" do\n response = FastlaneCore::ItunesSearchApi.fetch(338_986_109, 'FR')\n expect(response['kind']).to eq('software')\n expect(response['supportedDevices'].count).to be > 8\n expect(response['trackId']).to eq(338_986_109)\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"mathiasAichinger/fastlane_core"},"path":{"kind":"string","value":"spec/itunes_search_api_spec.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2907,"string":"2,907"}}},{"rowIdx":115086511,"cells":{"code":{"kind":"string","value":"/* shmbutil.h -- utility functions for multibyte characters. */\n\n/* Copyright (C) 2002-2004 Free Software Foundation, Inc.\n\n This file is part of GNU Bash, the Bourne Again SHell.\n\n Bash is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Bash is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with Bash. If not, see .\n*/\n \n#if !defined (_SH_MBUTIL_H_)\n#define _SH_MBUTIL_H_\n\n#include \"stdc.h\"\n\n/* Include config.h for HANDLE_MULTIBYTE */\n#include \n\n#if defined (HANDLE_MULTIBYTE)\n#include \"shmbchar.h\"\n\nextern size_t xmbsrtowcs __P((wchar_t *, const char **, size_t, mbstate_t *));\nextern size_t xdupmbstowcs __P((wchar_t **, char ***, const char *));\n\nextern size_t mbstrlen __P((const char *));\n\nextern char *xstrchr __P((const char *, int));\n\n#ifndef MB_INVALIDCH\n#define MB_INVALIDCH(x)\t\t((x) == (size_t)-1 || (x) == (size_t)-2)\n#define MB_NULLWCH(x)\t\t((x) == 0)\n#endif\n\n#define MBSLEN(s)\t(((s) && (s)[0]) ? ((s)[1] ? mbstrlen (s) : 1) : 0)\n#define MB_STRLEN(s)\t((MB_CUR_MAX > 1) ? MBSLEN (s) : STRLEN (s))\n\n#define MBLEN(s, n)\t((MB_CUR_MAX > 1) ? mblen ((s), (n)) : 1)\n#define MBRLEN(s, n, p)\t((MB_CUR_MAX > 1) ? mbrlen ((s), (n), (p)) : 1)\n\n#else /* !HANDLE_MULTIBYTE */\n\n#undef MB_LEN_MAX\n#undef MB_CUR_MAX\n\n#define MB_LEN_MAX\t1\n#define MB_CUR_MAX\t1\n\n#undef xstrchr\n#define xstrchr(s, c)\tstrchr(s, c)\n\n#ifndef MB_INVALIDCH\n#define MB_INVALIDCH(x)\t\t(0)\n#define MB_NULLWCH(x)\t\t(0)\n#endif\n\n#define MB_STRLEN(s)\t\t(STRLEN(s))\n\n#define MBLEN(s, n)\t\t1\n#define MBRLEN(s, n, p)\t\t1\n\n#ifndef wchar_t\n# define wchar_t\tint\n#endif\n\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Declare and initialize a multibyte state. Call must be terminated\n with `;'. */\n#if defined (HANDLE_MULTIBYTE)\n# define DECLARE_MBSTATE \\\n\tmbstate_t state; \\\n\tmemset (&state, '\\0', sizeof (mbstate_t))\n#else\n# define DECLARE_MBSTATE\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Initialize or reinitialize a multibyte state named `state'. Call must be\n terminated with `;'. */\n#if defined (HANDLE_MULTIBYTE)\n# define INITIALIZE_MBSTATE memset (&state, '\\0', sizeof (mbstate_t))\n#else\n# define INITIALIZE_MBSTATE\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Advance one (possibly multi-byte) character in string _STR of length\n _STRSIZE, starting at index _I. STATE must have already been declared. */\n#if defined (HANDLE_MULTIBYTE)\n# define ADVANCE_CHAR(_str, _strsize, _i) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _f; \\\n\\\n\t _f = is_basic ((_str)[_i]); \\\n\t if (_f) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t state_bak = state; \\\n\t mblength = mbrlen ((_str) + (_i), (_strsize) - (_i), &state); \\\n\t } \\\n\\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\t(_i)++; \\\n\t } \\\n\t else if (mblength == 0) \\\n\t (_i)++; \\\n\t else \\\n\t (_i) += mblength; \\\n\t } \\\n\telse \\\n\t (_i)++; \\\n } \\\n while (0)\n#else\n# define ADVANCE_CHAR(_str, _strsize, _i)\t(_i)++\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Advance one (possibly multibyte) character in the string _STR of length\n _STRSIZE.\n SPECIAL: assume that _STR will be incremented by 1 after this call. */\n#if defined (HANDLE_MULTIBYTE)\n# define ADVANCE_CHAR_P(_str, _strsize) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _f; \\\n\\\n\t _f = is_basic (*(_str)); \\\n\t if (_f) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_str), (_strsize), &state); \\\n\t } \\\n\\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t else \\\n\t (_str) += (mblength < 1) ? 0 : (mblength - 1); \\\n\t } \\\n } \\\n while (0)\n#else\n# define ADVANCE_CHAR_P(_str, _strsize)\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Back up one (possibly multi-byte) character in string _STR of length\n _STRSIZE, starting at index _I. STATE must have already been declared. */\n#if defined (HANDLE_MULTIBYTE)\n# define BACKUP_CHAR(_str, _strsize, _i) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _x, _p; /* _x == temp index into string, _p == prev index */ \\\n\\\n\t _x = _p = 0; \\\n\t while (_x < (_i)) \\\n\t { \\\n\t state_bak = state; \\\n\t mblength = mbrlen ((_str) + (_x), (_strsize) - (_x), &state); \\\n\\\n\t\tif (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t\t { \\\n\t\t state = state_bak; \\\n\t\t _x++; \\\n\t\t } \\\n\t\telse if (mblength == 0) \\\n\t\t _x++; \\\n\t\telse \\\n\t\t { \\\n\t\t _p = _x; /* _p == start of prev mbchar */ \\\n\t\t _x += mblength; \\\n\t\t } \\\n\t } \\\n\t (_i) = _p; \\\n\t } \\\n\telse \\\n\t (_i)--; \\\n } \\\n while (0)\n#else\n# define BACKUP_CHAR(_str, _strsize, _i)\t(_i)--\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Back up one (possibly multibyte) character in the string _BASE of length\n _STRSIZE starting at _STR (_BASE <= _STR <= (_BASE + _STRSIZE) ).\n SPECIAL: DO NOT assume that _STR will be decremented by 1 after this call. */\n#if defined (HANDLE_MULTIBYTE)\n# define BACKUP_CHAR_P(_base, _strsize, _str) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t char *_x, _p; /* _x == temp pointer into string, _p == prev pointer */ \\\n\\\n\t _x = _p = _base; \\\n\t while (_x < (_str)) \\\n\t { \\\n\t state_bak = state; \\\n\t mblength = mbrlen (_x, (_strsize) - _x, &state); \\\n\\\n\t\tif (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t\t { \\\n\t\t state = state_bak; \\\n\t\t _x++; \\\n\t\t } \\\n\t\telse if (mblength == 0) \\\n\t\t _x++; \\\n\t\telse \\\n\t\t { \\\n\t\t _p = _x; /* _p == start of prev mbchar */ \\\n\t\t _x += mblength; \\\n\t\t } \\\n\t } \\\n\t (_str) = _p; \\\n\t } \\\n\telse \\\n\t (_str)--; \\\n } \\\n while (0)\n#else\n# define BACKUP_CHAR_P(_base, _strsize, _str) (_str)--\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Copy a single character from the string _SRC to the string _DST.\n _SRCEND is a pointer to the end of _SRC. */\n#if defined (HANDLE_MULTIBYTE)\n# define COPY_CHAR_P(_dst, _src, _srcend) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _k; \\\n\\\n\t _k = is_basic (*(_src)); \\\n\t if (_k) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src), (_srcend) - (_src), &state); \\\n\t } \\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t else \\\n\t mblength = (mblength < 1) ? 1 : mblength; \\\n\\\n\t for (_k = 0; _k < mblength; _k++) \\\n\t *(_dst)++ = *(_src)++; \\\n\t } \\\n\telse \\\n\t *(_dst)++ = *(_src)++; \\\n } \\\n while (0)\n#else\n# define COPY_CHAR_P(_dst, _src, _srcend)\t*(_dst)++ = *(_src)++\n#endif /* !HANDLE_MULTIBYTE */\n\n/* Copy a single character from the string _SRC at index _SI to the string\n _DST at index _DI. _SRCEND is a pointer to the end of _SRC. */\n#if defined (HANDLE_MULTIBYTE)\n# define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _k; \\\n\\\n\t _k = is_basic (*((_src) + (_si))); \\\n\t if (_k) \\\n\t mblength = 1; \\\n\t else \\\n\t {\\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src) + (_si), (_srcend) - ((_src)+(_si)), &state); \\\n\t } \\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t else \\\n\t mblength = (mblength < 1) ? 1 : mblength; \\\n\\\n\t for (_k = 0; _k < mblength; _k++) \\\n\t _dst[_di++] = _src[_si++]; \\\n\t } \\\n\telse \\\n\t _dst[_di++] = _src[_si++]; \\\n } \\\n while (0)\n#else\n# define COPY_CHAR_I(_dst, _di, _src, _srcend, _si)\t_dst[_di++] = _src[_si++]\n#endif /* !HANDLE_MULTIBYTE */\n\n/****************************************************************\n *\t\t\t\t\t\t\t\t*\n * The following are only guaranteed to work in subst.c\t\t*\n *\t\t\t\t\t\t\t\t*\n ****************************************************************/\n\n#if defined (HANDLE_MULTIBYTE)\n# define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _i; \\\n\\\n\t _i = is_basic (*((_src) + (_si))); \\\n\t if (_i) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src) + (_si), (_slen) - (_si), &state); \\\n\t } \\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t else \\\n\t mblength = (mblength < 1) ? 1 : mblength; \\\n\\\n\t temp = xmalloc (mblength + 2); \\\n\t temp[0] = _escchar; \\\n\t for (_i = 0; _i < mblength; _i++) \\\n\t temp[_i + 1] = _src[_si++]; \\\n\t temp[mblength + 1] = '\\0'; \\\n\\\n\t goto add_string; \\\n\t } \\\n\telse \\\n\t { \\\n\t _dst[0] = _escchar; \\\n\t _dst[1] = _sc; \\\n\t } \\\n } \\\n while (0)\n#else\n# define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \\\n _dst[0] = _escchar; \\\n _dst[1] = _sc\n#endif /* !HANDLE_MULTIBYTE */\n\n#if defined (HANDLE_MULTIBYTE)\n# define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\t int _i; \\\n\\\n\t _i = is_basic (*((_src) + (_si))); \\\n\t if (_i) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src) + (_si), (_srcend) - ((_src) + (_si)), &state); \\\n\t } \\\n\t if (mblength == (size_t)-2 || mblength == (size_t)-1) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t else \\\n\t mblength = (mblength < 1) ? 1 : mblength; \\\n\\\n\t FASTCOPY(((_src) + (_si)), (_dst), mblength); \\\n\\\n\t (_dst) += mblength; \\\n\t (_si) += mblength; \\\n\t } \\\n\telse \\\n\t { \\\n\t *(_dst)++ = _src[(_si)]; \\\n\t (_si)++; \\\n\t } \\\n } \\\n while (0)\n#else\n# define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \\\n\t*(_dst)++ = _src[(_si)]; \\\n\t(_si)++\n#endif /* !HANDLE_MULTIBYTE */\n\n#if HANDLE_MULTIBYTE\n# define SADD_MBCHAR(_dst, _src, _si, _srcsize) \\\n do \\\n { \\\n\tif (MB_CUR_MAX > 1) \\\n\t { \\\n\t int i; \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\\\n\t i = is_basic (*((_src) + (_si))); \\\n\t if (i) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \\\n\t } \\\n\t if (mblength == (size_t)-1 || mblength == (size_t)-2) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t if (mblength < 1) \\\n\t mblength = 1; \\\n\\\n\t _dst = (char *)xmalloc (mblength + 1); \\\n\t for (i = 0; i < mblength; i++) \\\n\t (_dst)[i] = (_src)[(_si)++]; \\\n\t (_dst)[mblength] = '\\0'; \\\n\\\n\t goto add_string; \\\n\t } \\\n } \\\n while (0)\n\n#else\n# define SADD_MBCHAR(_dst, _src, _si, _srcsize)\n#endif\n\n/* Watch out when using this -- it's just straight textual subsitution */\n#if defined (HANDLE_MULTIBYTE)\n# define SADD_MBQCHAR_BODY(_dst, _src, _si, _srcsize) \\\n\\\n\t int i; \\\n\t mbstate_t state_bak; \\\n\t size_t mblength; \\\n\\\n\t i = is_basic (*((_src) + (_si))); \\\n\t if (i) \\\n\t mblength = 1; \\\n\t else \\\n\t { \\\n\t\tstate_bak = state; \\\n\t\tmblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \\\n\t } \\\n\t if (mblength == (size_t)-1 || mblength == (size_t)-2) \\\n\t { \\\n\t\tstate = state_bak; \\\n\t\tmblength = 1; \\\n\t } \\\n\t if (mblength < 1) \\\n\t mblength = 1; \\\n\\\n\t (_dst) = (char *)xmalloc (mblength + 2); \\\n\t (_dst)[0] = CTLESC; \\\n\t for (i = 0; i < mblength; i++) \\\n\t (_dst)[i+1] = (_src)[(_si)++]; \\\n\t (_dst)[mblength+1] = '\\0'; \\\n\\\n\t goto add_string\n\n#endif /* HANDLE_MULTIBYTE */\n#endif /* _SH_MBUTIL_H_ */\n"},"repo_name":{"kind":"string","value":"tavaresdong/courses-notes"},"path":{"kind":"string","value":"uw_cse333/hw/projdocs/test_tree/bash-4.2/include/shmbutil.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":12303,"string":"12,303"}}},{"rowIdx":115086512,"cells":{"code":{"kind":"string","value":"var baz = \"baz\";\n\nexport default baz;\n"},"repo_name":{"kind":"string","value":"EliteScientist/webpack"},"path":{"kind":"string","value":"test/statsCases/import-context-filter/templates/baz.noimport.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":38,"string":"38"}}},{"rowIdx":115086513,"cells":{"code":{"kind":"string","value":"/* $NoKeywords:$ */\n/**\n * @file\n *\n * ma.h\n *\n * ARDK common header file\n *\n * @xrefitem bom \"File Content Label\" \"Release Content\"\n * @e project: AGESA\n * @e sub-project: (Mem)\n * @e \\$Revision: 84150 $ @e \\$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $\n *\n **/\n/*****************************************************************************\n*\n * Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of Advanced Micro Devices, Inc. nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n* ***************************************************************************\n*\n*/\n\n#ifndef _MA_H_\n#define _MA_H_\n\n/*----------------------------------------------------------------------------\n * Mixed (DEFINITIONS AND MACROS / TYPEDEFS, STRUCTURES, ENUMS)\n *\n *----------------------------------------------------------------------------\n */\n\n/*-----------------------------------------------------------------------------\n * DEFINITIONS AND MACROS\n *\n *-----------------------------------------------------------------------------\n */\n\n\n#define MAX_CS_PER_CHANNEL 8 ///< Max CS per channel\n/*----------------------------------------------------------------------------\n * TYPEDEFS, STRUCTURES, ENUMS\n *\n *----------------------------------------------------------------------------\n */\n\n/** MARDK Structure*/\ntypedef struct {\n UINT16 Speed; ///< Dram speed in MHz\n UINT8 Loads; ///< Number of Data Loads\n UINT32 AddrTmg; ///< Address Timing value\n UINT32 Odc; ///< Output Driver Compensation Value\n} PSCFG_ENTRY;\n\n/** MARDK Structure*/\ntypedef struct {\n UINT16 Speed; ///< Dram speed in MHz\n UINT8 Loads; ///< Number of Data Loads\n UINT32 AddrTmg; ///< Address Timing value\n UINT32 Odc; ///< Output Driver Compensation Value\n UINT8 Dimms; ///< Number of Dimms\n} ADV_PSCFG_ENTRY;\n\n/** MARDK Structure for RDIMMs*/\ntypedef struct {\n UINT16 Speed; ///< Dram speed in MHz\n UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3\n UINT32 AddrTmg; ///< Address Timing value\n UINT16 RC2RC8; ///< RC2 and RC8 value //High byte: 1st pair value, Low byte: 2nd pair value\n UINT8 Dimms; ///< Number of Dimms\n} ADV_R_PSCFG_ENTRY;\n\n/** MARDK Structure*/\ntypedef struct {\n UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3\n UINT32 PhyRODTCSLow; ///< Fn2_9C 180\n UINT32 PhyRODTCSHigh; ///< Fn2_9C 181\n UINT32 PhyWODTCSLow; ///< Fn2_9C 182\n UINT32 PhyWODTCSHigh; ///< Fn2_9C 183\n UINT8 Dimms; ///< Number of Dimms\n} ADV_PSCFG_ODT_ENTRY;\n\n/** MARDK Structure for Write Levelization ODT*/\ntypedef struct {\n UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3\n UINT8 PhyWrLvOdt[MAX_CS_PER_CHANNEL / 2]; ///< WrLvOdt (Fn2_9C_0x08[11:8]) Value for each Dimm\n UINT8 Dimms; ///< Number of Dimms\n} ADV_R_PSCFG_WL_ODT_ENTRY;\n\n/*----------------------------------------------------------------------------\n * FUNCTIONS PROTOTYPE\n *\n *----------------------------------------------------------------------------\n */\n\nAGESA_STATUS\nMemAGetPsCfgDef (\n IN OUT MEM_DATA_STRUCT *MemData,\n IN UINT8 SocketID,\n IN OUT CH_DEF_STRUCT *CurrentChannel\n );\n\nUINT16\nMemAGetPsRankType (\n IN CH_DEF_STRUCT *CurrentChannel\n );\n\nAGESA_STATUS\nMemRecNGetPsCfgDef (\n IN OUT MEM_DATA_STRUCT *MemData,\n IN UINT8 SocketID,\n IN OUT CH_DEF_STRUCT *CurrentChannel\n );\n\nUINT16\nMemRecNGetPsRankType (\n IN CH_DEF_STRUCT *CurrentChannel\n );\n\nAGESA_STATUS\nMemRecNGetPsCfgUDIMM3Nb (\n IN OUT MEM_DATA_STRUCT *MemData,\n IN UINT8 SocketID,\n IN OUT CH_DEF_STRUCT *CurrentChannel\n );\n\nAGESA_STATUS\nMemRecNGetPsCfgSODIMM3Nb (\n IN OUT MEM_DATA_STRUCT *MemData,\n IN UINT8 SocketID,\n IN OUT CH_DEF_STRUCT *CurrentChannel\n );\n\nAGESA_STATUS\nMemRecNGetPsCfgRDIMM3Nb (\n IN OUT MEM_DATA_STRUCT *MemData,\n IN UINT8 SocketID,\n IN OUT CH_DEF_STRUCT *CurrentChannel\n );\n\n#endif /* _MA_H_ */\n"},"repo_name":{"kind":"string","value":"BTDC/coreboot"},"path":{"kind":"string","value":"src/vendorcode/amd/agesa/f16kb/Proc/Mem/ma.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":6015,"string":"6,015"}}},{"rowIdx":115086514,"cells":{"code":{"kind":"string","value":"/* $NoKeywords:$ */\n/**\n * @file\n *\n * PCIe training library\n *\n *\n *\n * @xrefitem bom \"File Content Label\" \"Release Content\"\n * @e project: AGESA\n * @e sub-project: GNB\n * @e \\$Revision: 84150 $ @e \\$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $\n *\n */\n/*\n*****************************************************************************\n*\n * Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of Advanced Micro Devices, Inc. nor the names of\n * its contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n* ***************************************************************************\n*\n*/\n#ifndef _GNBPCIETRAININGV2_H_\n#define _GNBPCIETRAININGV2_H_\n\n#include \"PcieTrainingV2.h\"\n#include \"PcieWorkaroundsV2.h\"\n\n#endif\n"},"repo_name":{"kind":"string","value":"BTDC/coreboot"},"path":{"kind":"string","value":"src/vendorcode/amd/agesa/f16kb/Proc/GNB/Modules/GnbPcieTrainingV2/GnbPcieTrainingV2.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":2173,"string":"2,173"}}},{"rowIdx":115086515,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (C) 2002 Roman Zippel \n * Released under the terms of the GNU GPL v2.0.\n */\n\n#include \n#include \n\n#define LKC_DIRECT_LINK\n#include \"lkc.h\"\n\nstruct menu rootmenu;\nstatic struct menu **last_entry_ptr;\n\nstruct file *file_list;\nstruct file *current_file;\n\nstatic void menu_warn(struct menu *menu, const char *fmt, ...)\n{\n\tva_list ap;\n\tva_start(ap, fmt);\n\tfprintf(stderr, \"%s:%d:warning: \", menu->file->name, menu->lineno);\n\tvfprintf(stderr, fmt, ap);\n\tfprintf(stderr, \"\\n\");\n\tva_end(ap);\n}\n\nstatic void prop_warn(struct property *prop, const char *fmt, ...)\n{\n\tva_list ap;\n\tva_start(ap, fmt);\n\tfprintf(stderr, \"%s:%d:warning: \", prop->file->name, prop->lineno);\n\tvfprintf(stderr, fmt, ap);\n\tfprintf(stderr, \"\\n\");\n\tva_end(ap);\n}\n\nvoid menu_init(void)\n{\n\tcurrent_entry = current_menu = &rootmenu;\n\tlast_entry_ptr = &rootmenu.list;\n}\n\nvoid menu_add_entry(struct symbol *sym)\n{\n\tstruct menu *menu;\n\n\tmenu = malloc(sizeof(*menu));\n\tmemset(menu, 0, sizeof(*menu));\n\tmenu->sym = sym;\n\tmenu->parent = current_menu;\n\tmenu->file = current_file;\n\tmenu->lineno = zconf_lineno();\n\n\t*last_entry_ptr = menu;\n\tlast_entry_ptr = &menu->next;\n\tcurrent_entry = menu;\n}\n\nvoid menu_end_entry(void)\n{\n}\n\nstruct menu *menu_add_menu(void)\n{\n\tmenu_end_entry();\n\tlast_entry_ptr = &current_entry->list;\n\treturn current_menu = current_entry;\n}\n\nvoid menu_end_menu(void)\n{\n\tlast_entry_ptr = &current_menu->next;\n\tcurrent_menu = current_menu->parent;\n}\n\nstruct expr *menu_check_dep(struct expr *e)\n{\n\tif (!e)\n\t\treturn e;\n\n\tswitch (e->type) {\n\tcase E_NOT:\n\t\te->left.expr = menu_check_dep(e->left.expr);\n\t\tbreak;\n\tcase E_OR:\n\tcase E_AND:\n\t\te->left.expr = menu_check_dep(e->left.expr);\n\t\te->right.expr = menu_check_dep(e->right.expr);\n\t\tbreak;\n\tcase E_SYMBOL:\n\t\t/* change 'm' into 'm' && MODULES */\n\t\tif (e->left.sym == &symbol_mod)\n\t\t\treturn expr_alloc_and(e, expr_alloc_symbol(modules_sym));\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn e;\n}\n\nvoid menu_add_dep(struct expr *dep)\n{\n\tcurrent_entry->dep = expr_alloc_and(current_entry->dep, menu_check_dep(dep));\n}\n\nvoid menu_set_type(int type)\n{\n\tstruct symbol *sym = current_entry->sym;\n\n\tif (sym->type == type)\n\t\treturn;\n\tif (sym->type == S_UNKNOWN) {\n\t\tsym->type = type;\n\t\treturn;\n\t}\n\tmenu_warn(current_entry, \"type of '%s' redefined from '%s' to '%s'\",\n\t sym->name ? sym->name : \"\",\n\t sym_type_name(sym->type), sym_type_name(type));\n}\n\nstruct property *menu_add_prop(enum prop_type type, char *prompt, struct expr *expr, struct expr *dep)\n{\n\tstruct property *prop = prop_alloc(type, current_entry->sym);\n\n\tprop->menu = current_entry;\n\tprop->expr = expr;\n\tprop->visible.expr = menu_check_dep(dep);\n\n\tif (prompt) {\n\t\tif (isspace(*prompt)) {\n\t\t\tprop_warn(prop, \"leading whitespace ignored\");\n\t\t\twhile (isspace(*prompt))\n\t\t\t\tprompt++;\n\t\t}\n\t\tif (current_entry->prompt)\n\t\t\tprop_warn(prop, \"prompt redefined\");\n\t\tcurrent_entry->prompt = prop;\n\t}\n\tprop->text = prompt;\n\n\treturn prop;\n}\n\nstruct property *menu_add_prompt(enum prop_type type, char *prompt, struct expr *dep)\n{\n\treturn menu_add_prop(type, prompt, NULL, dep);\n}\n\nvoid menu_add_expr(enum prop_type type, struct expr *expr, struct expr *dep)\n{\n\tmenu_add_prop(type, NULL, expr, dep);\n}\n\nvoid menu_add_symbol(enum prop_type type, struct symbol *sym, struct expr *dep)\n{\n\tmenu_add_prop(type, NULL, expr_alloc_symbol(sym), dep);\n}\n\nvoid menu_add_option(int token, char *arg)\n{\n\tstruct property *prop;\n\n\tswitch (token) {\n\tcase T_OPT_MODULES:\n\t\tprop = prop_alloc(P_DEFAULT, modules_sym);\n\t\tprop->expr = expr_alloc_symbol(current_entry->sym);\n\t\tbreak;\n\tcase T_OPT_DEFCONFIG_LIST:\n\t\tif (!sym_defconfig_list)\n\t\t\tsym_defconfig_list = current_entry->sym;\n\t\telse if (sym_defconfig_list != current_entry->sym)\n\t\t\tzconf_error(\"trying to redefine defconfig symbol\");\n\t\tbreak;\n\t}\n}\n\nstatic int menu_range_valid_sym(struct symbol *sym, struct symbol *sym2)\n{\n\treturn sym2->type == S_INT || sym2->type == S_HEX ||\n\t (sym2->type == S_UNKNOWN && sym_string_valid(sym, sym2->name));\n}\n\nvoid sym_check_prop(struct symbol *sym)\n{\n\tstruct property *prop;\n\tstruct symbol *sym2;\n\tfor (prop = sym->prop; prop; prop = prop->next) {\n\t\tswitch (prop->type) {\n\t\tcase P_DEFAULT:\n\t\t\tif ((sym->type == S_STRING || sym->type == S_INT || sym->type == S_HEX) &&\n\t\t\t prop->expr->type != E_SYMBOL)\n\t\t\t\tprop_warn(prop,\n\t\t\t\t \"default for config symbol '%'\"\n\t\t\t\t \" must be a single symbol\", sym->name);\n\t\t\tbreak;\n\t\tcase P_SELECT:\n\t\t\tsym2 = prop_get_symbol(prop);\n\t\t\tif (sym->type != S_BOOLEAN && sym->type != S_TRISTATE)\n\t\t\t\tprop_warn(prop,\n\t\t\t\t \"config symbol '%s' uses select, but is \"\n\t\t\t\t \"not boolean or tristate\", sym->name);\n\t\t\telse if (sym2->type == S_UNKNOWN)\n\t\t\t\tprop_warn(prop,\n\t\t\t\t \"'select' used by config symbol '%s' \"\n\t\t\t\t \"refers to undefined symbol '%s'\",\n\t\t\t\t sym->name, sym2->name);\n\t\t\telse if (sym2->type != S_BOOLEAN && sym2->type != S_TRISTATE)\n\t\t\t\tprop_warn(prop,\n\t\t\t\t \"'%s' has wrong type. 'select' only \"\n\t\t\t\t \"accept arguments of boolean and \"\n\t\t\t\t \"tristate type\", sym2->name);\n\t\t\tbreak;\n\t\tcase P_RANGE:\n\t\t\tif (sym->type != S_INT && sym->type != S_HEX)\n\t\t\t\tprop_warn(prop, \"range is only allowed \"\n\t\t\t\t \"for int or hex symbols\");\n\t\t\tif (!menu_range_valid_sym(sym, prop->expr->left.sym) ||\n\t\t\t !menu_range_valid_sym(sym, prop->expr->right.sym))\n\t\t\t\tprop_warn(prop, \"range is invalid\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t;\n\t\t}\n\t}\n}\n\nvoid menu_finalize(struct menu *parent)\n{\n\tstruct menu *menu, *last_menu;\n\tstruct symbol *sym;\n\tstruct property *prop;\n\tstruct expr *parentdep, *basedep, *dep, *dep2, **ep;\n\n\tsym = parent->sym;\n\tif (parent->list) {\n\t\tif (sym && sym_is_choice(sym)) {\n\t\t\t/* find the first choice value and find out choice type */\n\t\t\tfor (menu = parent->list; menu; menu = menu->next) {\n\t\t\t\tif (menu->sym) {\n\t\t\t\t\tcurrent_entry = parent;\n\t\t\t\t\tmenu_set_type(menu->sym->type);\n\t\t\t\t\tcurrent_entry = menu;\n\t\t\t\t\tmenu_set_type(sym->type);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tparentdep = expr_alloc_symbol(sym);\n\t\t} else if (parent->prompt)\n\t\t\tparentdep = parent->prompt->visible.expr;\n\t\telse\n\t\t\tparentdep = parent->dep;\n\n\t\tfor (menu = parent->list; menu; menu = menu->next) {\n\t\t\tbasedep = expr_transform(menu->dep);\n\t\t\tbasedep = expr_alloc_and(expr_copy(parentdep), basedep);\n\t\t\tbasedep = expr_eliminate_dups(basedep);\n\t\t\tmenu->dep = basedep;\n\t\t\tif (menu->sym)\n\t\t\t\tprop = menu->sym->prop;\n\t\t\telse\n\t\t\t\tprop = menu->prompt;\n\t\t\tfor (; prop; prop = prop->next) {\n\t\t\t\tif (prop->menu != menu)\n\t\t\t\t\tcontinue;\n\t\t\t\tdep = expr_transform(prop->visible.expr);\n\t\t\t\tdep = expr_alloc_and(expr_copy(basedep), dep);\n\t\t\t\tdep = expr_eliminate_dups(dep);\n\t\t\t\tif (menu->sym && menu->sym->type != S_TRISTATE)\n\t\t\t\t\tdep = expr_trans_bool(dep);\n\t\t\t\tprop->visible.expr = dep;\n\t\t\t\tif (prop->type == P_SELECT) {\n\t\t\t\t\tstruct symbol *es = prop_get_symbol(prop);\n\t\t\t\t\tes->rev_dep.expr = expr_alloc_or(es->rev_dep.expr,\n\t\t\t\t\t\t\texpr_alloc_and(expr_alloc_symbol(menu->sym), expr_copy(dep)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (menu = parent->list; menu; menu = menu->next)\n\t\t\tmenu_finalize(menu);\n\t} else if (sym) {\n\t\tbasedep = parent->prompt ? parent->prompt->visible.expr : NULL;\n\t\tbasedep = expr_trans_compare(basedep, E_UNEQUAL, &symbol_no);\n\t\tbasedep = expr_eliminate_dups(expr_transform(basedep));\n\t\tlast_menu = NULL;\n\t\tfor (menu = parent->next; menu; menu = menu->next) {\n\t\t\tdep = menu->prompt ? menu->prompt->visible.expr : menu->dep;\n\t\t\tif (!expr_contains_symbol(dep, sym))\n\t\t\t\tbreak;\n\t\t\tif (expr_depends_symbol(dep, sym))\n\t\t\t\tgoto next;\n\t\t\tdep = expr_trans_compare(dep, E_UNEQUAL, &symbol_no);\n\t\t\tdep = expr_eliminate_dups(expr_transform(dep));\n\t\t\tdep2 = expr_copy(basedep);\n\t\t\texpr_eliminate_eq(&dep, &dep2);\n\t\t\texpr_free(dep);\n\t\t\tif (!expr_is_yes(dep2)) {\n\t\t\t\texpr_free(dep2);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\texpr_free(dep2);\n\t\tnext:\n\t\t\tmenu_finalize(menu);\n\t\t\tmenu->parent = parent;\n\t\t\tlast_menu = menu;\n\t\t}\n\t\tif (last_menu) {\n\t\t\tparent->list = parent->next;\n\t\t\tparent->next = last_menu->next;\n\t\t\tlast_menu->next = NULL;\n\t\t}\n\t}\n\tfor (menu = parent->list; menu; menu = menu->next) {\n\t\tif (sym && sym_is_choice(sym) && menu->sym) {\n\t\t\tmenu->sym->flags |= SYMBOL_CHOICEVAL;\n\t\t\tif (!menu->prompt)\n\t\t\t\tmenu_warn(menu, \"choice value must have a prompt\");\n\t\t\tfor (prop = menu->sym->prop; prop; prop = prop->next) {\n\t\t\t\tif (prop->type == P_PROMPT && prop->menu != menu) {\n\t\t\t\t\tprop_warn(prop, \"choice values \"\n\t\t\t\t\t \"currently only support a \"\n\t\t\t\t\t \"single prompt\");\n\t\t\t\t}\n\t\t\t\tif (prop->type == P_DEFAULT)\n\t\t\t\t\tprop_warn(prop, \"defaults for choice \"\n\t\t\t\t\t \"values not supported\");\n\t\t\t}\n\t\t\tcurrent_entry = menu;\n\t\t\tmenu_set_type(sym->type);\n\t\t\tmenu_add_symbol(P_CHOICE, sym, NULL);\n\t\t\tprop = sym_get_choice_prop(sym);\n\t\t\tfor (ep = &prop->expr; *ep; ep = &(*ep)->left.expr)\n\t\t\t\t;\n\t\t\t*ep = expr_alloc_one(E_CHOICE, NULL);\n\t\t\t(*ep)->right.sym = menu->sym;\n\t\t}\n\t\tif (menu->list && (!menu->prompt || !menu->prompt->text)) {\n\t\t\tfor (last_menu = menu->list; ; last_menu = last_menu->next) {\n\t\t\t\tlast_menu->parent = parent;\n\t\t\t\tif (!last_menu->next)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlast_menu->next = menu->next;\n\t\t\tmenu->next = menu->list;\n\t\t\tmenu->list = NULL;\n\t\t}\n\t}\n\n\tif (sym && !(sym->flags & SYMBOL_WARNED)) {\n\t\tif (sym->type == S_UNKNOWN)\n\t\t\tmenu_warn(parent, \"config symbol defined without type\");\n\n\t\tif (sym_is_choice(sym) && !parent->prompt)\n\t\t\tmenu_warn(parent, \"choice must have a prompt\");\n\n\t\t/* Check properties connected to this symbol */\n\t\tsym_check_prop(sym);\n\t\tsym->flags |= SYMBOL_WARNED;\n\t}\n\n\tif (sym && !sym_is_optional(sym) && parent->prompt) {\n\t\tsym->rev_dep.expr = expr_alloc_or(sym->rev_dep.expr,\n\t\t\t\texpr_alloc_and(parent->prompt->visible.expr,\n\t\t\t\t\texpr_alloc_symbol(&symbol_mod)));\n\t}\n}\n\nbool menu_is_visible(struct menu *menu)\n{\n\tstruct menu *child;\n\tstruct symbol *sym;\n\ttristate visible;\n\n\tif (!menu->prompt)\n\t\treturn false;\n\tsym = menu->sym;\n\tif (sym) {\n\t\tsym_calc_value(sym);\n\t\tvisible = menu->prompt->visible.tri;\n\t} else\n\t\tvisible = menu->prompt->visible.tri = expr_calc_value(menu->prompt->visible.expr);\n\n\tif (visible != no)\n\t\treturn true;\n\tif (!sym || sym_get_tristate_value(menu->sym) == no)\n\t\treturn false;\n\n\tfor (child = menu->list; child; child = child->next)\n\t\tif (menu_is_visible(child))\n\t\t\treturn true;\n\treturn false;\n}\n\nconst char *menu_get_prompt(struct menu *menu)\n{\n\tif (menu->prompt)\n\t\treturn _(menu->prompt->text);\n\telse if (menu->sym)\n\t\treturn _(menu->sym->name);\n\treturn NULL;\n}\n\nstruct menu *menu_get_root_menu(struct menu *menu)\n{\n\treturn &rootmenu;\n}\n\nstruct menu *menu_get_parent_menu(struct menu *menu)\n{\n\tenum prop_type type;\n\n\tfor (; menu != &rootmenu; menu = menu->parent) {\n\t\ttype = menu->prompt ? menu->prompt->type : 0;\n\t\tif (type == P_MENU)\n\t\t\tbreak;\n\t}\n\treturn menu;\n}\n\n"},"repo_name":{"kind":"string","value":"janrinze/loox7xxport.loox2-6-22"},"path":{"kind":"string","value":"scripts/kconfig/menu.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":10632,"string":"10,632"}}},{"rowIdx":115086516,"cells":{"code":{"kind":"string","value":"/*\n\t$License:\n\tCopyright (C) 2011 InvenSense Corporation, All Rights Reserved.\n\n\tThis program is free software; you can redistribute it and/or modify\n\tit under the terms of the GNU General Public License version 2 as\n\tpublished by the Free Software Foundation.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with this program. If not, see .\n\t$\n */\n\n/**\n * @addtogroup ACCELDL\n * @brief Provides the interface to setup and handle an accelerometer.\n *\n * @{\n * @file mma8450.c\n * @brief Accelerometer setup and handling methods for Freescale MMA8450.\n */\n\n/* -------------------------------------------------------------------------- */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mpu-dev.h\"\n\n#include \n#include \n#include \"mlsl.h\"\n#include \"mldl_cfg.h\"\n#undef MPL_LOG_TAG\n#define MPL_LOG_TAG \"MPL-acc\"\n\n/* full scale setting - register & mask */\n#define ACCEL_MMA8450_XYZ_DATA_CFG\t(0x16)\n\n#define ACCEL_MMA8450_CTRL_REG1\t\t(0x38)\n#define ACCEL_MMA8450_CTRL_REG2 (0x39)\n#define ACCEL_MMA8450_CTRL_REG4\t\t(0x3B)\n#define ACCEL_MMA8450_CTRL_REG5\t\t(0x3C)\n\n#define ACCEL_MMA8450_CTRL_REG\t\t(0x38)\n#define ACCEL_MMA8450_CTRL_MASK\t\t(0x03)\n\n#define ACCEL_MMA8450_SLEEP_MASK\t(0x03)\n\n/* -------------------------------------------------------------------------- */\n\nstruct mma8450_config {\n\tunsigned int odr;\n\tunsigned int fsr;\t/** < full scale range mg */\n\tunsigned int ths;\t/** < Motion no-motion thseshold mg */\n\tunsigned int dur;\t/** < Motion no-motion duration ms */\n\tunsigned char reg_ths;\n\tunsigned char reg_dur;\n\tunsigned char ctrl_reg1;\n\tunsigned char irq_type;\n\tunsigned char mot_int1_cfg;\n};\n\nstruct mma8450_private_data {\n\tstruct mma8450_config suspend;\n\tstruct mma8450_config resume;\n};\n\n\n/* -------------------------------------------------------------------------- */\n\nstatic int mma8450_set_ths(void *mlsl_handle,\n\t\t\tstruct ext_slave_platform_data *pdata,\n\t\t\tstruct mma8450_config *config,\n\t\t\tint apply,\n\t\t\tlong ths)\n{\n\treturn INV_ERROR_FEATURE_NOT_IMPLEMENTED;\n}\n\nstatic int mma8450_set_dur(void *mlsl_handle,\n\t\t\tstruct ext_slave_platform_data *pdata,\n\t\t\tstruct mma8450_config *config,\n\t\t\tint apply,\n\t\t\tlong dur)\n{\n\treturn INV_ERROR_FEATURE_NOT_IMPLEMENTED;\n}\n\n/**\n * @brief Sets the IRQ to fire when one of the IRQ events occur.\n * Threshold and duration will not be used unless the type is MOT or\n * NMOT.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param pdata\n * a pointer to the slave platform data.\n * @param config\n * configuration to apply to, suspend or resume\n * @param apply\n * whether to apply immediately or save the settings to be applied\n * at the next resume.\n * @param irq_type\n * the type of IRQ. Valid values are\n * - MPU_SLAVE_IRQ_TYPE_NONE\n * - MPU_SLAVE_IRQ_TYPE_MOTION\n * - MPU_SLAVE_IRQ_TYPE_DATA_READY\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_set_irq(void *mlsl_handle,\n\t\tstruct ext_slave_platform_data *pdata,\n\t\tstruct mma8450_config *config,\n\t\tint apply,\n\t\tlong irq_type)\n{\n\tint result = INV_SUCCESS;\n\tunsigned char reg1;\n\tunsigned char reg2;\n\tunsigned char reg3;\n\n\tconfig->irq_type = (unsigned char)irq_type;\n\tif (irq_type == MPU_SLAVE_IRQ_TYPE_DATA_READY) {\n\t\treg1 = 0x01;\n\t\treg2 = 0x01;\n\t\treg3 = 0x07;\n\t} else if (irq_type == MPU_SLAVE_IRQ_TYPE_NONE) {\n\t\treg1 = 0x00;\n\t\treg2 = 0x00;\n\t\treg3 = 0x00;\n\t} else {\n\t\treturn INV_ERROR_FEATURE_NOT_IMPLEMENTED;\n\t}\n\n\tif (apply) {\n\t\t/* XYZ_DATA_CFG: event flag enabled on Z axis */\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\t\tACCEL_MMA8450_XYZ_DATA_CFG, reg3);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\t\tACCEL_MMA8450_CTRL_REG4, reg1);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\t\tACCEL_MMA8450_CTRL_REG5, reg2);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * @brief Set the output data rate for the particular configuration.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param pdata\n * a pointer to the slave platform data.\n * @param config\n * Config to modify with new ODR.\n * @param apply\n * whether to apply immediately or save the settings to be applied\n * at the next resume.\n * @param odr\n * Output data rate in units of 1/1000Hz (mHz).\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_set_odr(void *mlsl_handle,\n\t\tstruct ext_slave_platform_data *pdata,\n\t\tstruct mma8450_config *config,\n\t\tint apply,\n\t\tlong odr)\n{\n\tunsigned char bits;\n\tint result = INV_SUCCESS;\n\n\tif (odr > 200000) {\n\t\tconfig->odr = 400000;\n\t\tbits = 0x00;\n\t} else if (odr > 100000) {\n\t\tconfig->odr = 200000;\n\t\tbits = 0x04;\n\t} else if (odr > 50000) {\n\t\tconfig->odr = 100000;\n\t\tbits = 0x08;\n\t} else if (odr > 25000) {\n\t\tconfig->odr = 50000;\n\t\tbits = 0x0C;\n\t} else if (odr > 12500) {\n\t\tconfig->odr = 25000;\n\t\tbits = 0x40; /* Sleep -> Auto wake mode */\n\t} else if (odr > 1563) {\n\t\tconfig->odr = 12500;\n\t\tbits = 0x10;\n\t} else if (odr > 0) {\n\t\tconfig->odr = 1563;\n\t\tbits = 0x14;\n\t} else {\n\t\tconfig->ctrl_reg1 = 0; /* Set FS1.FS2 to Standby */\n\t\tconfig->odr = 0;\n\t\tbits = 0;\n\t}\n\n\tconfig->ctrl_reg1 = bits | (config->ctrl_reg1 & 0x3);\n\tif (apply) {\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\tACCEL_MMA8450_CTRL_REG1, 0);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\tACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t\tMPL_LOGV(\"ODR: %d mHz, 0x%02x\\n\",\n\t\t\tconfig->odr, (int)config->ctrl_reg1);\n\t}\n\treturn result;\n}\n\n/**\n * @brief Set the full scale range of the accels\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param pdata\n * a pointer to the slave platform data.\n * @param config\n * pointer to configuration.\n * @param apply\n * whether to apply immediately or save the settings to be applied\n * at the next resume.\n * @param fsr\n * requested full scale range.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_set_fsr(void *mlsl_handle,\n\t\tstruct ext_slave_platform_data *pdata,\n\t\tstruct mma8450_config *config,\n\t\tint apply,\n\t\tlong fsr)\n{\n\tunsigned char bits;\n\tint result = INV_SUCCESS;\n\n\tif (fsr <= 2000) {\n\t\tbits = 0x01;\n\t\tconfig->fsr = 2000;\n\t} else if (fsr <= 4000) {\n\t\tbits = 0x02;\n\t\tconfig->fsr = 4000;\n\t} else {\n\t\tbits = 0x03;\n\t\tconfig->fsr = 8000;\n\t}\n\n\tconfig->ctrl_reg1 = bits | (config->ctrl_reg1 & 0xFC);\n\tif (apply) {\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\tACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t\tMPL_LOGV(\"FSR: %d mg\\n\", config->fsr);\n\t}\n\treturn result;\n}\n\n/**\n * @brief suspends the device to put it in its lowest power mode.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_suspend(void *mlsl_handle,\n\t\t struct ext_slave_descr *slave,\n\t\t struct ext_slave_platform_data *pdata)\n{\n\tint result;\n\tstruct mma8450_private_data *private_data = pdata->private_data;\n\n\tif (private_data->suspend.fsr == 4000)\n\t\tslave->range.mantissa = 4;\n\telse if (private_data->suspend.fsr == 8000)\n\t\tslave->range.mantissa = 8;\n\telse\n\t\tslave->range.mantissa = 2;\n\tslave->range.fraction = 0;\n\n\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\tACCEL_MMA8450_CTRL_REG1, 0);\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\tif (private_data->suspend.ctrl_reg1) {\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\tACCEL_MMA8450_CTRL_REG1,\n\t\t\t\tprivate_data->suspend.ctrl_reg1);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tresult = mma8450_set_irq(mlsl_handle, pdata,\n\t\t\t\t&private_data->suspend,\n\t\t\t\ttrue, private_data->suspend.irq_type);\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\treturn result;\n}\n\n/**\n * @brief resume the device in the proper power state given the configuration\n * chosen.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_resume(void *mlsl_handle,\n\t\t struct ext_slave_descr *slave,\n\t\t struct ext_slave_platform_data *pdata)\n{\n\tint result = INV_SUCCESS;\n\tstruct mma8450_private_data *private_data = pdata->private_data;\n\n\t/* Full Scale */\n\tif (private_data->resume.fsr == 4000)\n\t\tslave->range.mantissa = 4;\n\telse if (private_data->resume.fsr == 8000)\n\t\tslave->range.mantissa = 8;\n\telse\n\t\tslave->range.mantissa = 2;\n\tslave->range.fraction = 0;\n\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\tACCEL_MMA8450_CTRL_REG1, 0);\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\tif (private_data->resume.ctrl_reg1) {\n\t\tresult = inv_serial_single_write(mlsl_handle, pdata->address,\n\t\t\t\tACCEL_MMA8450_CTRL_REG1,\n\t\t\t\tprivate_data->resume.ctrl_reg1);\n\t\tif (result) {\n\t\t\tLOG_RESULT_LOCATION(result);\n\t\t\treturn result;\n\t\t}\n\t}\n\tresult = mma8450_set_irq(mlsl_handle, pdata,\n\t\t\t&private_data->resume,\n\t\t\ttrue, private_data->resume.irq_type);\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\n\treturn result;\n}\n\n/**\n * @brief read the sensor data from the device.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n * @param data\n * a buffer to store the data read.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_read(void *mlsl_handle,\n\t\t struct ext_slave_descr *slave,\n\t\t struct ext_slave_platform_data *pdata, unsigned char *data)\n{\n\tint result;\n\tunsigned char local_data[4];\t/* Status register + 3 bytes data */\n\tresult = inv_serial_read(mlsl_handle, pdata->address,\n\t\t\t\t0x00, sizeof(local_data), local_data);\n\tif (result) {\n\t\tLOG_RESULT_LOCATION(result);\n\t\treturn result;\n\t}\n\tmemcpy(data, &local_data[1], (slave->read_len) - 1);\n\n\tMPL_LOGV(\"Data Not Ready: %02x %02x %02x %02x\\n\",\n\t\t local_data[0], local_data[1],\n\t\t local_data[2], local_data[3]);\n\n\treturn result;\n}\n\n/**\n * @brief one-time device driver initialization function.\n * If the driver is built as a kernel module, this function will be\n * called when the module is loaded in the kernel.\n * If the driver is built-in in the kernel, this function will be\n * called at boot time.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_init(void *mlsl_handle,\n\t\t\t struct ext_slave_descr *slave,\n\t\t\t struct ext_slave_platform_data *pdata)\n{\n\tstruct mma8450_private_data *private_data;\n\tprivate_data = (struct mma8450_private_data *)\n\t kzalloc(sizeof(struct mma8450_private_data), GFP_KERNEL);\n\n\tif (!private_data)\n\t\treturn INV_ERROR_MEMORY_EXAUSTED;\n\n\tpdata->private_data = private_data;\n\n\tmma8450_set_odr(mlsl_handle, pdata, &private_data->suspend,\n\t\t\tfalse, 0);\n\tmma8450_set_odr(mlsl_handle, pdata, &private_data->resume,\n\t\t\tfalse, 200000);\n\tmma8450_set_fsr(mlsl_handle, pdata, &private_data->suspend,\n\t\t\tfalse, 2000);\n\tmma8450_set_fsr(mlsl_handle, pdata, &private_data->resume,\n\t\t\tfalse, 2000);\n\tmma8450_set_irq(mlsl_handle, pdata, &private_data->suspend,\n\t\t\tfalse,\n\t\t\tMPU_SLAVE_IRQ_TYPE_NONE);\n\tmma8450_set_irq(mlsl_handle, pdata, &private_data->resume,\n\t\t\tfalse,\n\t\t\tMPU_SLAVE_IRQ_TYPE_NONE);\n\treturn INV_SUCCESS;\n}\n\n/**\n * @brief one-time device driver exit function.\n * If the driver is built as a kernel module, this function will be\n * called when the module is removed from the kernel.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_exit(void *mlsl_handle,\n\t\t\t struct ext_slave_descr *slave,\n\t\t\t struct ext_slave_platform_data *pdata)\n{\n\tkfree(pdata->private_data);\n\treturn INV_SUCCESS;\n}\n\n/**\n * @brief device configuration facility.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n * @param data\n * a pointer to the configuration data structure.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_config(void *mlsl_handle,\n\t\t\tstruct ext_slave_descr *slave,\n\t\t\tstruct ext_slave_platform_data *pdata,\n\t\t\tstruct ext_slave_config *data)\n{\n\tstruct mma8450_private_data *private_data = pdata->private_data;\n\tif (!data->data)\n\t\treturn INV_ERROR_INVALID_PARAMETER;\n\n\tswitch (data->key) {\n\tcase MPU_SLAVE_CONFIG_ODR_SUSPEND:\n\t\treturn mma8450_set_odr(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->suspend,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_ODR_RESUME:\n\t\treturn mma8450_set_odr(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->resume,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_FSR_SUSPEND:\n\t\treturn mma8450_set_fsr(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->suspend,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_FSR_RESUME:\n\t\treturn mma8450_set_fsr(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->resume,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_MOT_THS:\n\t\treturn mma8450_set_ths(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->suspend,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_NMOT_THS:\n\t\treturn mma8450_set_ths(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->resume,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_MOT_DUR:\n\t\treturn mma8450_set_dur(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->suspend,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_NMOT_DUR:\n\t\treturn mma8450_set_dur(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->resume,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_IRQ_SUSPEND:\n\t\treturn mma8450_set_irq(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->suspend,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tcase MPU_SLAVE_CONFIG_IRQ_RESUME:\n\t\treturn mma8450_set_irq(mlsl_handle, pdata,\n\t\t\t\t\t&private_data->resume,\n\t\t\t\t\tdata->apply,\n\t\t\t\t\t*((long *)data->data));\n\tdefault:\n\t\tLOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED);\n\t\treturn INV_ERROR_FEATURE_NOT_IMPLEMENTED;\n\t};\n\n\treturn INV_SUCCESS;\n}\n\n/**\n * @brief facility to retrieve the device configuration.\n *\n * @param mlsl_handle\n * the handle to the serial channel the device is connected to.\n * @param slave\n * a pointer to the slave descriptor data structure.\n * @param pdata\n * a pointer to the slave platform data.\n * @param data\n * a pointer to store the returned configuration data structure.\n *\n * @return INV_SUCCESS if successful or a non-zero error code.\n */\nstatic int mma8450_get_config(void *mlsl_handle,\n\t\t\t\tstruct ext_slave_descr *slave,\n\t\t\t\tstruct ext_slave_platform_data *pdata,\n\t\t\t\tstruct ext_slave_config *data)\n{\n\tstruct mma8450_private_data *private_data = pdata->private_data;\n\tif (!data->data)\n\t\treturn INV_ERROR_INVALID_PARAMETER;\n\n\tswitch (data->key) {\n\tcase MPU_SLAVE_CONFIG_ODR_SUSPEND:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->suspend.odr;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_ODR_RESUME:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->resume.odr;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_FSR_SUSPEND:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->suspend.fsr;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_FSR_RESUME:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->resume.fsr;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_MOT_THS:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->suspend.ths;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_NMOT_THS:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->resume.ths;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_MOT_DUR:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->suspend.dur;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_NMOT_DUR:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->resume.dur;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_IRQ_SUSPEND:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->suspend.irq_type;\n\t\tbreak;\n\tcase MPU_SLAVE_CONFIG_IRQ_RESUME:\n\t\t(*(unsigned long *)data->data) =\n\t\t\t(unsigned long) private_data->resume.irq_type;\n\t\tbreak;\n\tdefault:\n\t\tLOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED);\n\t\treturn INV_ERROR_FEATURE_NOT_IMPLEMENTED;\n\t};\n\n\treturn INV_SUCCESS;\n}\n\nstatic struct ext_slave_descr mma8450_descr = {\n\t.init = mma8450_init,\n\t.exit = mma8450_exit,\n\t.suspend = mma8450_suspend,\n\t.resume = mma8450_resume,\n\t.read = mma8450_read,\n\t.config = mma8450_config,\n\t.get_config = mma8450_get_config,\n\t.name = \"mma8450\",\n\t.type = EXT_SLAVE_TYPE_ACCEL,\n\t.id = ACCEL_ID_MMA8450,\n\t.read_reg = 0x00,\n\t.read_len = 4,\n\t.endian = EXT_SLAVE_FS8_BIG_ENDIAN,\n\t.range = {2, 0},\n\t.trigger = NULL,\n};\n\nstatic\nstruct ext_slave_descr *mma8450_get_slave_descr(void)\n{\n\treturn &mma8450_descr;\n}\n\n/* -------------------------------------------------------------------------- */\nstruct mma8450_mod_private_data {\n\tstruct i2c_client *client;\n\tstruct ext_slave_platform_data *pdata;\n};\n\nstatic unsigned short normal_i2c[] = { I2C_CLIENT_END };\n\nstatic int mma8450_mod_probe(struct i2c_client *client,\n\t\t\t const struct i2c_device_id *devid)\n{\n\tstruct ext_slave_platform_data *pdata;\n\tstruct mma8450_mod_private_data *private_data;\n\tint result = 0;\n\n\tdev_info(&client->adapter->dev, \"%s: %s\\n\", __func__, devid->name);\n\n\tif (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {\n\t\tresult = -ENODEV;\n\t\tgoto out_no_free;\n\t}\n\n\tpdata = client->dev.platform_data;\n\tif (!pdata) {\n\t\tdev_err(&client->adapter->dev,\n\t\t\t\"Missing platform data for slave %s\\n\", devid->name);\n\t\tresult = -EFAULT;\n\t\tgoto out_no_free;\n\t}\n\n\tprivate_data = kzalloc(sizeof(*private_data), GFP_KERNEL);\n\tif (!private_data) {\n\t\tresult = -ENOMEM;\n\t\tgoto out_no_free;\n\t}\n\n\ti2c_set_clientdata(client, private_data);\n\tprivate_data->client = client;\n\tprivate_data->pdata = pdata;\n\n\tresult = inv_mpu_register_slave(THIS_MODULE, client, pdata,\n\t\t\t\t\tmma8450_get_slave_descr);\n\tif (result) {\n\t\tdev_err(&client->adapter->dev,\n\t\t\t\"Slave registration failed: %s, %d\\n\",\n\t\t\tdevid->name, result);\n\t\tgoto out_free_memory;\n\t}\n\n\treturn result;\n\nout_free_memory:\n\tkfree(private_data);\nout_no_free:\n\tdev_err(&client->adapter->dev, \"%s failed %d\\n\", __func__, result);\n\treturn result;\n\n}\n\nstatic int mma8450_mod_remove(struct i2c_client *client)\n{\n\tstruct mma8450_mod_private_data *private_data =\n\t\ti2c_get_clientdata(client);\n\n\tdev_dbg(&client->adapter->dev, \"%s\\n\", __func__);\n\n\tinv_mpu_unregister_slave(client, private_data->pdata,\n\t\t\t\tmma8450_get_slave_descr);\n\n\tkfree(private_data);\n\treturn 0;\n}\n\nstatic const struct i2c_device_id mma8450_mod_id[] = {\n\t{ \"mma8450\", ACCEL_ID_MMA8450 },\n\t{}\n};\n\nMODULE_DEVICE_TABLE(i2c, mma8450_mod_id);\n\nstatic struct i2c_driver mma8450_mod_driver = {\n\t.class = I2C_CLASS_HWMON,\n\t.probe = mma8450_mod_probe,\n\t.remove = mma8450_mod_remove,\n\t.id_table = mma8450_mod_id,\n\t.driver = {\n\t\t .owner = THIS_MODULE,\n\t\t .name = \"mma8450_mod\",\n\t\t },\n\t.address_list = normal_i2c,\n};\n\nstatic int __init mma8450_mod_init(void)\n{\n\tint res = i2c_add_driver(&mma8450_mod_driver);\n\tpr_info(\"%s: Probe name %s\\n\", __func__, \"mma8450_mod\");\n\tif (res)\n\t\tpr_err(\"%s failed\\n\", __func__);\n\treturn res;\n}\n\nstatic void __exit mma8450_mod_exit(void)\n{\n\tpr_info(\"%s\\n\", __func__);\n\ti2c_del_driver(&mma8450_mod_driver);\n}\n\nmodule_init(mma8450_mod_init);\nmodule_exit(mma8450_mod_exit);\n\nMODULE_AUTHOR(\"Invensense Corporation\");\nMODULE_DESCRIPTION(\"Driver to integrate MMA8450 sensor with the MPU\");\nMODULE_LICENSE(\"GPL\");\nMODULE_ALIAS(\"mma8450_mod\");\n\n/**\n * @}\n */\n"},"repo_name":{"kind":"string","value":"akw28888/caf2"},"path":{"kind":"string","value":"drivers/misc/inv_mpu/accel/mma8450.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":21949,"string":"21,949"}}},{"rowIdx":115086517,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n/*\n * This file was created in part using the configuration script provided with\n * the libpng sources. However it was missing some symbols which caused the\n * linker to fail so those were added manually by scanning the library looking\n * for exported symbols missing the skia_ prefix and adding them to the end of\n * this file.\n *\n * ./third_party/externals/libpng/configure --with-libpng-prefix=skia_\n */\n\n#define png_sRGB_table skia_png_sRGB_table\n#define png_sRGB_base skia_png_sRGB_base\n#define png_sRGB_delta skia_png_sRGB_delta\n#define png_zstream_error skia_png_zstream_error\n#define png_free_buffer_list skia_png_free_buffer_list\n#define png_fixed skia_png_fixed\n#define png_user_version_check skia_png_user_version_check\n#define png_malloc_base skia_png_malloc_base\n#define png_malloc_array skia_png_malloc_array\n#define png_realloc_array skia_png_realloc_array\n#define png_create_png_struct skia_png_create_png_struct\n#define png_destroy_png_struct skia_png_destroy_png_struct\n#define png_free_jmpbuf skia_png_free_jmpbuf\n#define png_zalloc skia_png_zalloc\n#define png_zfree skia_png_zfree\n#define png_default_read_data skia_png_default_read_data\n#define png_push_fill_buffer skia_png_push_fill_buffer\n#define png_default_write_data skia_png_default_write_data\n#define png_default_flush skia_png_default_flush\n#define png_reset_crc skia_png_reset_crc\n#define png_write_data skia_png_write_data\n#define png_read_sig skia_png_read_sig\n#define png_read_chunk_header skia_png_read_chunk_header\n#define png_read_data skia_png_read_data\n#define png_crc_read skia_png_crc_read\n#define png_crc_finish skia_png_crc_finish\n#define png_crc_error skia_png_crc_error\n#define png_calculate_crc skia_png_calculate_crc\n#define png_flush skia_png_flush\n#define png_write_IHDR skia_png_write_IHDR\n#define png_write_PLTE skia_png_write_PLTE\n#define png_compress_IDAT skia_png_compress_IDAT\n#define png_write_IEND skia_png_write_IEND\n#define png_write_gAMA_fixed skia_png_write_gAMA_fixed\n#define png_write_sBIT skia_png_write_sBIT\n#define png_write_cHRM_fixed skia_png_write_cHRM_fixed\n#define png_write_sRGB skia_png_write_sRGB\n#define png_write_iCCP skia_png_write_iCCP\n#define png_write_sPLT skia_png_write_sPLT\n#define png_write_tRNS skia_png_write_tRNS\n#define png_write_bKGD skia_png_write_bKGD\n#define png_write_hIST skia_png_write_hIST\n#define png_write_tEXt skia_png_write_tEXt\n#define png_write_zTXt skia_png_write_zTXt\n#define png_write_iTXt skia_png_write_iTXt\n#define png_set_text_2 skia_png_set_text_2\n#define png_write_oFFs skia_png_write_oFFs\n#define png_write_pCAL skia_png_write_pCAL\n#define png_write_pHYs skia_png_write_pHYs\n#define png_write_tIME skia_png_write_tIME\n#define png_write_sCAL_s skia_png_write_sCAL_s\n#define png_write_finish_row skia_png_write_finish_row\n#define png_write_start_row skia_png_write_start_row\n#define png_combine_row skia_png_combine_row\n#define png_do_read_interlace skia_png_do_read_interlace\n#define png_do_write_interlace skia_png_do_write_interlace\n#define png_read_filter_row skia_png_read_filter_row\n#define png_read_filter_row_up_neon skia_png_read_filter_row_up_neon\n#define png_read_filter_row_sub3_neon skia_png_read_filter_row_sub3_neon\n#define png_read_filter_row_sub4_neon skia_png_read_filter_row_sub4_neon\n#define png_read_filter_row_avg3_neon skia_png_read_filter_row_avg3_neon\n#define png_read_filter_row_avg4_neon skia_png_read_filter_row_avg4_neon\n#define png_read_filter_row_paeth3_neon skia_png_read_filter_row_paeth3_neon\n#define png_read_filter_row_paeth4_neon skia_png_read_filter_row_paeth4_neon\n#define png_write_find_filter skia_png_write_find_filter\n#define png_read_IDAT_data skia_png_read_IDAT_data\n#define png_read_finish_IDAT skia_png_read_finish_IDAT\n#define png_read_finish_row skia_png_read_finish_row\n#define png_read_start_row skia_png_read_start_row\n#define png_read_transform_info skia_png_read_transform_info\n#define png_do_read_filler skia_png_do_read_filler\n#define png_do_read_swap_alpha skia_png_do_read_swap_alpha\n#define png_do_write_swap_alpha skia_png_do_write_swap_alpha\n#define png_do_read_invert_alpha skia_png_do_read_invert_alpha\n#define png_do_write_invert_alpha skia_png_do_write_invert_alpha\n#define png_do_strip_channel skia_png_do_strip_channel\n#define png_do_swap skia_png_do_swap\n#define png_do_packswap skia_png_do_packswap\n#define png_do_rgb_to_gray skia_png_do_rgb_to_gray\n#define png_do_gray_to_rgb skia_png_do_gray_to_rgb\n#define png_do_unpack skia_png_do_unpack\n#define png_do_unshift skia_png_do_unshift\n#define png_do_invert skia_png_do_invert\n#define png_do_scale_16_to_8 skia_png_do_scale_16_to_8\n#define png_do_chop skia_png_do_chop\n#define png_do_quantize skia_png_do_quantize\n#define png_do_bgr skia_png_do_bgr\n#define png_do_pack skia_png_do_pack\n#define png_do_shift skia_png_do_shift\n#define png_do_compose skia_png_do_compose\n#define png_do_gamma skia_png_do_gamma\n#define png_do_encode_alpha skia_png_do_encode_alpha\n#define png_do_expand_palette skia_png_do_expand_palette\n#define png_do_expand skia_png_do_expand\n#define png_do_expand_16 skia_png_do_expand_16\n#define png_handle_IHDR skia_png_handle_IHDR\n#define png_handle_PLTE skia_png_handle_PLTE\n#define png_handle_IEND skia_png_handle_IEND\n#define png_handle_bKGD skia_png_handle_bKGD\n#define png_handle_cHRM skia_png_handle_cHRM\n#define png_handle_gAMA skia_png_handle_gAMA\n#define png_handle_hIST skia_png_handle_hIST\n#define png_handle_iCCP skia_png_handle_iCCP\n#define png_handle_iTXt skia_png_handle_iTXt\n#define png_handle_oFFs skia_png_handle_oFFs\n#define png_handle_pCAL skia_png_handle_pCAL\n#define png_handle_pHYs skia_png_handle_pHYs\n#define png_handle_sBIT skia_png_handle_sBIT\n#define png_handle_sCAL skia_png_handle_sCAL\n#define png_handle_sPLT skia_png_handle_sPLT\n#define png_handle_sRGB skia_png_handle_sRGB\n#define png_handle_tEXt skia_png_handle_tEXt\n#define png_handle_tIME skia_png_handle_tIME\n#define png_handle_tRNS skia_png_handle_tRNS\n#define png_handle_zTXt skia_png_handle_zTXt\n#define png_check_chunk_name skia_png_check_chunk_name\n#define png_handle_unknown skia_png_handle_unknown\n#define png_chunk_unknown_handling skia_png_chunk_unknown_handling\n#define png_do_read_transformations skia_png_do_read_transformations\n#define png_do_write_transformations skia_png_do_write_transformations\n#define png_init_read_transformations skia_png_init_read_transformations\n#define png_push_read_chunk skia_png_push_read_chunk\n#define png_push_read_sig skia_png_push_read_sig\n#define png_push_check_crc skia_png_push_check_crc\n#define png_push_crc_skip skia_png_push_crc_skip\n#define png_push_crc_finish skia_png_push_crc_finish\n#define png_push_save_buffer skia_png_push_save_buffer\n#define png_push_restore_buffer skia_png_push_restore_buffer\n#define png_push_read_IDAT skia_png_push_read_IDAT\n#define png_process_IDAT_data skia_png_process_IDAT_data\n#define png_push_process_row skia_png_push_process_row\n#define png_push_handle_unknown skia_png_push_handle_unknown\n#define png_push_have_info skia_png_push_have_info\n#define png_push_have_end skia_png_push_have_end\n#define png_push_have_row skia_png_push_have_row\n#define png_push_read_end skia_png_push_read_end\n#define png_process_some_data skia_png_process_some_data\n#define png_read_push_finish_row skia_png_read_push_finish_row\n#define png_push_handle_tEXt skia_png_push_handle_tEXt\n#define png_push_read_tEXt skia_png_push_read_tEXt\n#define png_push_handle_zTXt skia_png_push_handle_zTXt\n#define png_push_read_zTXt skia_png_push_read_zTXt\n#define png_push_handle_iTXt skia_png_push_handle_iTXt\n#define png_push_read_iTXt skia_png_push_read_iTXt\n#define png_do_read_intrapixel skia_png_do_read_intrapixel\n#define png_do_write_intrapixel skia_png_do_write_intrapixel\n#define png_colorspace_set_gamma skia_png_colorspace_set_gamma\n#define png_colorspace_sync_info skia_png_colorspace_sync_info\n#define png_colorspace_sync skia_png_colorspace_sync\n#define png_colorspace_set_chromaticities skia_png_colorspace_set_chromaticities\n#define png_colorspace_set_endpoints skia_png_colorspace_set_endpoints\n#define png_colorspace_set_sRGB skia_png_colorspace_set_sRGB\n#define png_colorspace_set_ICC skia_png_colorspace_set_ICC\n#define png_icc_check_length skia_png_icc_check_length\n#define png_icc_check_header skia_png_icc_check_header\n#define png_icc_check_tag_table skia_png_icc_check_tag_table\n#define png_icc_set_sRGB skia_png_icc_set_sRGB\n#define png_colorspace_set_rgb_coefficients skia_png_colorspace_set_rgb_coefficients\n#define png_check_IHDR skia_png_check_IHDR\n#define png_do_check_palette_indexes skia_png_do_check_palette_indexes\n#define png_fixed_error skia_png_fixed_error\n#define png_safecat skia_png_safecat\n#define png_format_number skia_png_format_number\n#define png_warning_parameter skia_png_warning_parameter\n#define png_warning_parameter_unsigned skia_png_warning_parameter_unsigned\n#define png_warning_parameter_signed skia_png_warning_parameter_signed\n#define png_formatted_warning skia_png_formatted_warning\n#define png_app_warning skia_png_app_warning\n#define png_app_error skia_png_app_error\n#define png_chunk_report skia_png_chunk_report\n#define png_ascii_from_fp skia_png_ascii_from_fp\n#define png_ascii_from_fixed skia_png_ascii_from_fixed\n#define png_check_fp_number skia_png_check_fp_number\n#define png_check_fp_string skia_png_check_fp_string\n#define png_muldiv skia_png_muldiv\n#define png_muldiv_warn skia_png_muldiv_warn\n#define png_reciprocal skia_png_reciprocal\n#define png_reciprocal2 skia_png_reciprocal2\n#define png_gamma_significant skia_png_gamma_significant\n#define png_gamma_correct skia_png_gamma_correct\n#define png_gamma_16bit_correct skia_png_gamma_16bit_correct\n#define png_gamma_8bit_correct skia_png_gamma_8bit_correct\n#define png_destroy_gamma_table skia_png_destroy_gamma_table\n#define png_build_gamma_table skia_png_build_gamma_table\n#define png_safe_error skia_png_safe_error\n#define png_safe_warning skia_png_safe_warning\n#define png_safe_execute skia_png_safe_execute\n#define png_image_error skia_png_image_error\n\n#define png_access_version_number skia_png_access_version_number\n#define png_build_grayscale_palette skia_png_build_grayscale_palette\n#define png_convert_to_rfc1123 skia_png_convert_to_rfc1123\n#define png_convert_to_rfc1123_buffer skia_png_convert_to_rfc1123_buffer\n#define png_create_info_struct skia_png_create_info_struct\n#define png_data_freer skia_png_data_freer\n#define png_destroy_info_struct skia_png_destroy_info_struct\n#define png_free_data skia_png_free_data\n#define png_get_copyright skia_png_get_copyright\n#define png_get_header_ver skia_png_get_header_ver\n#define png_get_header_version skia_png_get_header_version\n#define png_get_io_ptr skia_png_get_io_ptr\n#define png_get_libpng_ver skia_png_get_libpng_ver\n#define png_handle_as_unknown skia_png_handle_as_unknown\n#define png_image_free skia_png_image_free\n#define png_info_init_3 skia_png_info_init_3\n#define png_init_io skia_png_init_io\n#define png_reset_zstream skia_png_reset_zstream\n#define png_save_int_32 skia_png_save_int_32\n#define png_set_option skia_png_set_option\n#define png_set_sig_bytes skia_png_set_sig_bytes\n#define png_sig_cmp skia_png_sig_cmp\n#define png_benign_error skia_png_benign_error\n#define png_chunk_benign_error skia_png_chunk_benign_error\n#define png_chunk_error skia_png_chunk_error\n#define png_chunk_warning skia_png_chunk_warning\n#define png_error skia_png_error\n#define png_get_error_ptr skia_png_get_error_ptr\n#define png_longjmp skia_png_longjmp\n#define png_set_error_fn skia_png_set_error_fn\n#define png_set_longjmp_fn skia_png_set_longjmp_fn\n#define png_warning skia_png_warning\n#define png_get_bit_depth skia_png_get_bit_depth\n#define png_get_bKGD skia_png_get_bKGD\n#define png_get_channels skia_png_get_channels\n#define png_get_cHRM skia_png_get_cHRM\n#define png_get_cHRM_fixed skia_png_get_cHRM_fixed\n#define png_get_cHRM_XYZ skia_png_get_cHRM_XYZ\n#define png_get_cHRM_XYZ_fixed skia_png_get_cHRM_XYZ_fixed\n#define png_get_chunk_cache_max skia_png_get_chunk_cache_max\n#define png_get_chunk_malloc_max skia_png_get_chunk_malloc_max\n#define png_get_color_type skia_png_get_color_type\n#define png_get_compression_buffer_size skia_png_get_compression_buffer_size\n#define png_get_compression_type skia_png_get_compression_type\n#define png_get_filter_type skia_png_get_filter_type\n#define png_get_gAMA skia_png_get_gAMA\n#define png_get_gAMA_fixed skia_png_get_gAMA_fixed\n#define png_get_hIST skia_png_get_hIST\n#define png_get_iCCP skia_png_get_iCCP\n#define png_get_IHDR skia_png_get_IHDR\n#define png_get_image_height skia_png_get_image_height\n#define png_get_image_width skia_png_get_image_width\n#define png_get_interlace_type skia_png_get_interlace_type\n#define png_get_io_chunk_type skia_png_get_io_chunk_type\n#define png_get_io_state skia_png_get_io_state\n#define png_get_oFFs skia_png_get_oFFs\n#define png_get_palette_max skia_png_get_palette_max\n#define png_get_pCAL skia_png_get_pCAL\n#define png_get_pHYs skia_png_get_pHYs\n#define png_get_pHYs_dpi skia_png_get_pHYs_dpi\n#define png_get_pixel_aspect_ratio skia_png_get_pixel_aspect_ratio\n#define png_get_pixel_aspect_ratio_fixed skia_png_get_pixel_aspect_ratio_fixed\n#define png_get_pixels_per_inch skia_png_get_pixels_per_inch\n#define png_get_pixels_per_meter skia_png_get_pixels_per_meter\n#define png_get_PLTE skia_png_get_PLTE\n#define png_get_rgb_to_gray_status skia_png_get_rgb_to_gray_status\n#define png_get_rowbytes skia_png_get_rowbytes\n#define png_get_rows skia_png_get_rows\n#define png_get_sBIT skia_png_get_sBIT\n#define png_get_sCAL skia_png_get_sCAL\n#define png_get_sCAL_fixed skia_png_get_sCAL_fixed\n#define png_get_sCAL_s skia_png_get_sCAL_s\n#define png_get_signature skia_png_get_signature\n#define png_get_sPLT skia_png_get_sPLT\n#define png_get_sRGB skia_png_get_sRGB\n#define png_get_text skia_png_get_text\n#define png_get_tIME skia_png_get_tIME\n#define png_get_tRNS skia_png_get_tRNS\n#define png_get_unknown_chunks skia_png_get_unknown_chunks\n#define png_get_user_chunk_ptr skia_png_get_user_chunk_ptr\n#define png_get_user_height_max skia_png_get_user_height_max\n#define png_get_user_width_max skia_png_get_user_width_max\n#define png_get_valid skia_png_get_valid\n#define png_get_x_offset_inches skia_png_get_x_offset_inches\n#define png_get_x_offset_inches_fixed skia_png_get_x_offset_inches_fixed\n#define png_get_x_offset_microns skia_png_get_x_offset_microns\n#define png_get_x_offset_pixels skia_png_get_x_offset_pixels\n#define png_get_x_pixels_per_inch skia_png_get_x_pixels_per_inch\n#define png_get_x_pixels_per_meter skia_png_get_x_pixels_per_meter\n#define png_get_y_offset_inches skia_png_get_y_offset_inches\n#define png_get_y_offset_inches_fixed skia_png_get_y_offset_inches_fixed\n#define png_get_y_offset_microns skia_png_get_y_offset_microns\n#define png_get_y_offset_pixels skia_png_get_y_offset_pixels\n#define png_get_y_pixels_per_inch skia_png_get_y_pixels_per_inch\n#define png_get_y_pixels_per_meter skia_png_get_y_pixels_per_meter\n#define png_calloc skia_png_calloc\n#define png_free skia_png_free\n#define png_free_default skia_png_free_default\n#define png_get_mem_ptr skia_png_get_mem_ptr\n#define png_malloc skia_png_malloc\n#define png_malloc_default skia_png_malloc_default\n#define png_malloc_warn skia_png_malloc_warn\n#define png_set_mem_fn skia_png_set_mem_fn\n#define png_get_progressive_ptr skia_png_get_progressive_ptr\n#define png_process_data skia_png_process_data\n#define png_process_data_pause skia_png_process_data_pause\n#define png_process_data_skip skia_png_process_data_skip\n#define png_progressive_combine_row skia_png_progressive_combine_row\n#define png_set_progressive_read_fn skia_png_set_progressive_read_fn\n#define png_create_read_struct skia_png_create_read_struct\n#define png_create_read_struct_2 skia_png_create_read_struct_2\n#define png_destroy_read_struct skia_png_destroy_read_struct\n#define png_image_begin_read_from_file skia_png_image_begin_read_from_file\n#define png_image_begin_read_from_memory skia_png_image_begin_read_from_memory\n#define png_image_begin_read_from_stdio skia_png_image_begin_read_from_stdio\n#define png_image_finish_read skia_png_image_finish_read\n#define png_read_end skia_png_read_end\n#define png_read_image skia_png_read_image\n#define png_read_info skia_png_read_info\n#define png_read_png skia_png_read_png\n#define png_read_row skia_png_read_row\n#define png_read_rows skia_png_read_rows\n#define png_read_update_info skia_png_read_update_info\n#define png_set_read_status_fn skia_png_set_read_status_fn\n#define png_start_read_image skia_png_start_read_image\n#define png_set_read_fn skia_png_set_read_fn\n#define png_set_alpha_mode skia_png_set_alpha_mode\n#define png_set_alpha_mode_fixed skia_png_set_alpha_mode_fixed\n#define png_set_background skia_png_set_background\n#define png_set_background_fixed skia_png_set_background_fixed\n#define png_set_crc_action skia_png_set_crc_action\n#define png_set_expand skia_png_set_expand\n#define png_set_expand_16 skia_png_set_expand_16\n#define png_set_expand_gray_1_2_4_to_8 skia_png_set_expand_gray_1_2_4_to_8\n#define png_set_gamma skia_png_set_gamma\n#define png_set_gamma_fixed skia_png_set_gamma_fixed\n#define png_set_gray_to_rgb skia_png_set_gray_to_rgb\n#define png_set_palette_to_rgb skia_png_set_palette_to_rgb\n#define png_set_quantize skia_png_set_quantize\n#define png_set_read_user_transform_fn skia_png_set_read_user_transform_fn\n#define png_set_rgb_to_gray skia_png_set_rgb_to_gray\n#define png_set_rgb_to_gray_fixed skia_png_set_rgb_to_gray_fixed\n#define png_set_scale_16 skia_png_set_scale_16\n#define png_set_strip_16 skia_png_set_strip_16\n#define png_set_strip_alpha skia_png_set_strip_alpha\n#define png_set_tRNS_to_alpha skia_png_set_tRNS_to_alpha\n#define png_get_int_32 skia_png_get_int_32\n#define png_get_uint_16 skia_png_get_uint_16\n#define png_get_uint_31 skia_png_get_uint_31\n#define png_get_uint_32 skia_png_get_uint_32\n#define png_permit_mng_features skia_png_permit_mng_features\n#define png_set_benign_errors skia_png_set_benign_errors\n#define png_set_bKGD skia_png_set_bKGD\n#define png_set_check_for_invalid_index skia_png_set_check_for_invalid_index\n#define png_set_cHRM skia_png_set_cHRM\n#define png_set_cHRM_fixed skia_png_set_cHRM_fixed\n#define png_set_cHRM_XYZ skia_png_set_cHRM_XYZ\n#define png_set_cHRM_XYZ_fixed skia_png_set_cHRM_XYZ_fixed\n#define png_set_chunk_cache_max skia_png_set_chunk_cache_max\n#define png_set_chunk_malloc_max skia_png_set_chunk_malloc_max\n#define png_set_compression_buffer_size skia_png_set_compression_buffer_size\n#define png_set_gAMA skia_png_set_gAMA\n#define png_set_gAMA_fixed skia_png_set_gAMA_fixed\n#define png_set_hIST skia_png_set_hIST\n#define png_set_iCCP skia_png_set_iCCP\n#define png_set_IHDR skia_png_set_IHDR\n#define png_set_invalid skia_png_set_invalid\n#define png_set_keep_unknown_chunks skia_png_set_keep_unknown_chunks\n#define png_set_oFFs skia_png_set_oFFs\n#define png_set_pCAL skia_png_set_pCAL\n#define png_set_pHYs skia_png_set_pHYs\n#define png_set_PLTE skia_png_set_PLTE\n#define png_set_read_user_chunk_fn skia_png_set_read_user_chunk_fn\n#define png_set_rows skia_png_set_rows\n#define png_set_sBIT skia_png_set_sBIT\n#define png_set_sCAL skia_png_set_sCAL\n#define png_set_sCAL_fixed skia_png_set_sCAL_fixed\n#define png_set_sCAL_s skia_png_set_sCAL_s\n#define png_set_sPLT skia_png_set_sPLT\n#define png_set_sRGB skia_png_set_sRGB\n#define png_set_sRGB_gAMA_and_cHRM skia_png_set_sRGB_gAMA_and_cHRM\n#define png_set_text skia_png_set_text\n#define png_set_tIME skia_png_set_tIME\n#define png_set_tRNS skia_png_set_tRNS\n#define png_set_unknown_chunk_location skia_png_set_unknown_chunk_location\n#define png_set_unknown_chunks skia_png_set_unknown_chunks\n#define png_set_user_limits skia_png_set_user_limits\n#define png_get_current_pass_number skia_png_get_current_pass_number\n#define png_get_current_row_number skia_png_get_current_row_number\n#define png_get_user_transform_ptr skia_png_get_user_transform_ptr\n#define png_set_add_alpha skia_png_set_add_alpha\n#define png_set_bgr skia_png_set_bgr\n#define png_set_filler skia_png_set_filler\n#define png_set_interlace_handling skia_png_set_interlace_handling\n#define png_set_invert_alpha skia_png_set_invert_alpha\n#define png_set_invert_mono skia_png_set_invert_mono\n#define png_set_packing skia_png_set_packing\n#define png_set_packswap skia_png_set_packswap\n#define png_set_shift skia_png_set_shift\n#define png_set_swap skia_png_set_swap\n#define png_set_swap_alpha skia_png_set_swap_alpha\n#define png_set_user_transform_info skia_png_set_user_transform_info\n#define png_set_write_fn skia_png_set_write_fn\n#define png_convert_from_struct_tm skia_png_convert_from_struct_tm\n#define png_convert_from_time_t skia_png_convert_from_time_t\n#define png_create_write_struct skia_png_create_write_struct\n#define png_create_write_struct_2 skia_png_create_write_struct_2\n#define png_destroy_write_struct skia_png_destroy_write_struct\n#define png_image_write_to_file skia_png_image_write_to_file\n#define png_image_write_to_stdio skia_png_image_write_to_stdio\n#define png_set_compression_level skia_png_set_compression_level\n#define png_set_compression_mem_level skia_png_set_compression_mem_level\n#define png_set_compression_method skia_png_set_compression_method\n#define png_set_compression_strategy skia_png_set_compression_strategy\n#define png_set_compression_window_bits skia_png_set_compression_window_bits\n#define png_set_filter skia_png_set_filter\n#define png_set_filter_heuristics skia_png_set_filter_heuristics\n#define png_set_filter_heuristics_fixed skia_png_set_filter_heuristics_fixed\n#define png_set_flush skia_png_set_flush\n#define png_set_text_compression_level skia_png_set_text_compression_level\n#define png_set_text_compression_mem_level skia_png_set_text_compression_mem_level\n#define png_set_text_compression_method skia_png_set_text_compression_method\n#define png_set_text_compression_strategy skia_png_set_text_compression_strategy\n#define png_set_text_compression_window_bits skia_png_set_text_compression_window_bits\n#define png_set_write_status_fn skia_png_set_write_status_fn\n#define png_set_write_user_transform_fn skia_png_set_write_user_transform_fn\n#define png_write_end skia_png_write_end\n#define png_write_flush skia_png_write_flush\n#define png_write_image skia_png_write_image\n#define png_write_info skia_png_write_info\n#define png_write_info_before_PLTE skia_png_write_info_before_PLTE\n#define png_write_png skia_png_write_png\n#define png_write_row skia_png_write_row\n#define png_write_rows skia_png_write_rows\n#define png_save_uint_16 skia_png_save_uint_16\n#define png_save_uint_32 skia_png_save_uint_32\n#define png_write_chunk skia_png_write_chunk\n#define png_write_chunk_data skia_png_write_chunk_data\n#define png_write_chunk_start skia_png_write_chunk_start\n#define png_write_chunk_end skia_png_write_chunk_end\n#define png_write_sig skia_png_write_sig\n"},"repo_name":{"kind":"string","value":"zero-ui/miniblink49"},"path":{"kind":"string","value":"third_party/skia/third_party/libpng/pngprefix.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":22924,"string":"22,924"}}},{"rowIdx":115086518,"cells":{"code":{"kind":"string","value":"define(\n [\n \"js/views/baseview\", \"underscore\", \"js/models/metadata\", \"js/views/abstract_editor\",\n \"js/models/uploads\", \"js/views/uploads\",\n \"js/models/license\", \"js/views/license\",\n \"js/views/video/transcripts/metadata_videolist\",\n \"js/views/video/translations_editor\"\n ],\nfunction(BaseView, _, MetadataModel, AbstractEditor, FileUpload, UploadDialog,\n LicenseModel, LicenseView, VideoList, VideoTranslations) {\n var Metadata = {};\n\n Metadata.Editor = BaseView.extend({\n\n // Model is CMS.Models.MetadataCollection,\n initialize : function() {\n var self = this,\n counter = 0,\n locator = self.$el.closest('[data-locator]').data('locator'),\n courseKey = self.$el.closest('[data-course-key]').data('course-key');\n\n this.template = this.loadTemplate('metadata-editor');\n this.$el.html(this.template({numEntries: this.collection.length}));\n\n this.collection.each(\n function (model) {\n var data = {\n el: self.$el.find('.metadata_entry')[counter++],\n courseKey: courseKey,\n locator: locator,\n model: model\n },\n conversions = {\n 'Select': 'Option',\n 'Float': 'Number',\n 'Integer': 'Number'\n },\n type = model.getType();\n\n if (conversions[type]) {\n type = conversions[type];\n }\n\n if (_.isFunction(Metadata[type])) {\n new Metadata[type](data);\n } else {\n // Everything else is treated as GENERIC_TYPE, which uses String editor.\n new Metadata.String(data);\n }\n });\n },\n\n /**\n * Returns just the modified metadata values, in the format used to persist to the server.\n */\n getModifiedMetadataValues: function () {\n var modified_values = {};\n this.collection.each(\n function (model) {\n if (model.isModified()) {\n modified_values[model.getFieldName()] = model.getValue();\n }\n }\n );\n return modified_values;\n },\n\n /**\n * Returns a display name for the component related to this metadata. This method looks to see\n * if there is a metadata entry called 'display_name', and if so, it returns its value. If there\n * is no such entry, or if display_name does not have a value set, it returns an empty string.\n */\n getDisplayName: function () {\n var displayName = '';\n this.collection.each(\n function (model) {\n if (model.get('field_name') === 'display_name') {\n var displayNameValue = model.get('value');\n // It is possible that there is no display name value set. In that case, return empty string.\n displayName = displayNameValue ? displayNameValue : '';\n }\n }\n );\n return displayName;\n }\n });\n\n Metadata.VideoList = VideoList;\n Metadata.VideoTranslations = VideoTranslations;\n\n Metadata.String = AbstractEditor.extend({\n\n events : {\n \"change input\" : \"updateModel\",\n \"keypress .setting-input\" : \"showClearButton\",\n \"click .setting-clear\" : \"clear\"\n },\n\n templateName: \"metadata-string-entry\",\n\n render: function () {\n AbstractEditor.prototype.render.apply(this);\n\n // If the model has property `non editable` equals `true`,\n // the field is disabled, but user is able to clear it.\n if (this.model.get('non_editable')) {\n this.$el.find('#' + this.uniqueId)\n .prop('readonly', true)\n .addClass('is-disabled')\n .attr('aria-disabled', true);\n }\n },\n\n getValueFromEditor : function () {\n return this.$el.find('#' + this.uniqueId).val();\n },\n\n setValueInEditor : function (value) {\n this.$el.find('input').val(value);\n }\n });\n\n Metadata.Number = AbstractEditor.extend({\n\n events : {\n \"change input\" : \"updateModel\",\n \"keypress .setting-input\" : \"keyPressed\",\n \"change .setting-input\" : \"changed\",\n \"click .setting-clear\" : \"clear\"\n },\n\n render: function () {\n AbstractEditor.prototype.render.apply(this);\n if (!this.initialized) {\n var numToString = function (val) {\n return val.toFixed(4);\n };\n var min = \"min\";\n var max = \"max\";\n var step = \"step\";\n var options = this.model.getOptions();\n if (options.hasOwnProperty(min)) {\n this.min = Number(options[min]);\n this.$el.find('input').attr(min, numToString(this.min));\n }\n if (options.hasOwnProperty(max)) {\n this.max = Number(options[max]);\n this.$el.find('input').attr(max, numToString(this.max));\n }\n var stepValue = undefined;\n if (options.hasOwnProperty(step)) {\n // Parse step and convert to String. Polyfill doesn't like float values like \".1\" (expects \"0.1\").\n stepValue = numToString(Number(options[step]));\n }\n else if (this.isIntegerField()) {\n stepValue = \"1\";\n }\n if (stepValue !== undefined) {\n this.$el.find('input').attr(step, stepValue);\n }\n\n // Manually runs polyfill for input number types to correct for Firefox non-support.\n // inputNumber will be undefined when unit test is running.\n if ($.fn.inputNumber) {\n this.$el.find('.setting-input-number').inputNumber();\n }\n\n this.initialized = true;\n }\n\n return this;\n },\n\n templateName: \"metadata-number-entry\",\n\n getValueFromEditor : function () {\n return this.$el.find('#' + this.uniqueId).val();\n },\n\n setValueInEditor : function (value) {\n this.$el.find('input').val(value);\n },\n\n /**\n * Returns true if this view is restricted to integers, as opposed to floating points values.\n */\n isIntegerField : function () {\n return this.model.getType() === 'Integer';\n },\n\n keyPressed: function (e) {\n this.showClearButton();\n // This first filtering if statement is take from polyfill to prevent\n // non-numeric input (for browsers that don't use polyfill because they DO have a number input type).\n var _ref, _ref1;\n if (((_ref = e.keyCode) !== 8 && _ref !== 9 && _ref !== 35 && _ref !== 36 && _ref !== 37 && _ref !== 39) &&\n ((_ref1 = e.which) !== 45 && _ref1 !== 46 && _ref1 !== 48 && _ref1 !== 49 && _ref1 !== 50 && _ref1 !== 51\n && _ref1 !== 52 && _ref1 !== 53 && _ref1 !== 54 && _ref1 !== 55 && _ref1 !== 56 && _ref1 !== 57)) {\n e.preventDefault();\n }\n // For integers, prevent decimal points.\n if (this.isIntegerField() && e.keyCode === 46) {\n e.preventDefault();\n }\n },\n\n changed: function () {\n // Limit value to the range specified by min and max (necessary for browsers that aren't using polyfill).\n // Prevent integer/float fields value to be empty (set them to their defaults)\n var value = this.getValueFromEditor();\n if (value) {\n if ((this.max !== undefined) && value > this.max) {\n value = this.max;\n } else if ((this.min != undefined) && value < this.min) {\n value = this.min;\n }\n this.setValueInEditor(value);\n this.updateModel();\n } else {\n this.clear();\n }\n }\n\n });\n\n Metadata.Option = AbstractEditor.extend({\n\n events : {\n \"change select\" : \"updateModel\",\n \"click .setting-clear\" : \"clear\"\n },\n\n templateName: \"metadata-option-entry\",\n\n getValueFromEditor : function () {\n var selectedText = this.$el.find('#' + this.uniqueId).find(\":selected\").text();\n var selectedValue;\n _.each(this.model.getOptions(), function (modelValue) {\n if (modelValue === selectedText) {\n selectedValue = modelValue;\n }\n else if (modelValue['display_name'] === selectedText) {\n selectedValue = modelValue['value'];\n }\n });\n return selectedValue;\n },\n\n setValueInEditor : function (value) {\n // Value here is the json value as used by the field. The choice may instead be showing display names.\n // Find the display name matching the value passed in.\n _.each(this.model.getOptions(), function (modelValue) {\n if (modelValue['value'] === value) {\n value = modelValue['display_name'];\n }\n });\n this.$el.find('#' + this.uniqueId + \" option\").filter(function() {\n return $(this).text() === value;\n }).prop('selected', true);\n }\n });\n\n Metadata.List = AbstractEditor.extend({\n\n events : {\n \"click .setting-clear\" : \"clear\",\n \"keypress .setting-input\" : \"showClearButton\",\n \"change input\" : \"updateModel\",\n \"input input\" : \"enableAdd\",\n \"click .create-setting\" : \"addEntry\",\n \"click .remove-setting\" : \"removeEntry\"\n },\n\n templateName: \"metadata-list-entry\",\n\n getValueFromEditor: function () {\n return _.map(\n this.$el.find('li input'),\n function (ele) { return ele.value.trim(); }\n ).filter(_.identity);\n },\n\n setValueInEditor: function (value) {\n var list = this.$el.find('ol');\n\n list.empty();\n _.each(value, function(ele, index) {\n var template = _.template(\n '
  • ' +\n '\">' +\n '\">Remove' +\n '
  • '\n );\n list.append($(template({'ele': ele, 'index': index})));\n });\n },\n\n addEntry: function(event) {\n event.preventDefault();\n // We don't call updateModel here since it's bound to the\n // change event\n var list = this.model.get('value') || [];\n this.setValueInEditor(list.concat(['']));\n this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true);\n },\n\n removeEntry: function(event) {\n event.preventDefault();\n var entry = $(event.currentTarget).siblings().val();\n this.setValueInEditor(_.without(this.model.get('value'), entry));\n this.updateModel();\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n },\n\n enableAdd: function() {\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n },\n\n clear: function() {\n AbstractEditor.prototype.clear.apply(this, arguments);\n if (_.isNull(this.model.getValue())) {\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n }\n }\n });\n\n Metadata.RelativeTime = AbstractEditor.extend({\n\n defaultValue: '00:00:00',\n // By default max value of RelativeTime field on Backend is 23:59:59,\n // that is 86399 seconds.\n maxTimeInSeconds: 86399,\n\n events: {\n \"focus input\" : \"addSelection\",\n \"mouseup input\" : \"mouseUpHandler\",\n \"change input\" : \"updateModel\",\n \"keypress .setting-input\" : \"showClearButton\" ,\n \"click .setting-clear\" : \"clear\"\n },\n\n templateName: \"metadata-string-entry\",\n\n getValueFromEditor: function () {\n var $input = this.$el.find('#' + this.uniqueId);\n\n return $input.val();\n },\n\n updateModel: function () {\n var value = this.getValueFromEditor(),\n time = this.parseRelativeTime(value);\n\n this.model.setValue(time);\n\n // Sometimes, `parseRelativeTime` method returns the same value for\n // the different inputs. In this case, model will not be\n // updated (it already has the same value) and we should\n // call `render` method manually.\n // Examples:\n // value => 23:59:59; parseRelativeTime => 23:59:59\n // value => 44:59:59; parseRelativeTime => 23:59:59\n if (value !== time && !this.model.hasChanged('value')) {\n this.render();\n }\n },\n\n parseRelativeTime: function (value) {\n // This function ensure you have two-digits\n var pad = function (number) {\n return (number < 10) ? \"0\" + number : number;\n },\n // Removes all white-spaces and splits by `:`.\n list = value.replace(/\\s+/g, '').split(':'),\n seconds, date;\n\n list = _.map(list, function(num) {\n return Math.max(0, parseInt(num, 10) || 0);\n }).reverse();\n\n seconds = _.reduce(list, function(memo, num, index) {\n return memo + num * Math.pow(60, index);\n }, 0);\n\n // multiply by 1000 because Date() requires milliseconds\n date = new Date(Math.min(seconds, this.maxTimeInSeconds) * 1000);\n\n return [\n pad(date.getUTCHours()),\n pad(date.getUTCMinutes()),\n pad(date.getUTCSeconds())\n ].join(':');\n },\n\n setValueInEditor: function (value) {\n if (!value) {\n value = this.defaultValue;\n }\n\n this.$el.find('input').val(value);\n },\n\n addSelection: function (event) {\n $(event.currentTarget).select();\n },\n\n mouseUpHandler: function (event) {\n // Prevents default behavior to make works selection in WebKit\n // browsers\n event.preventDefault();\n }\n });\n\n Metadata.Dict = AbstractEditor.extend({\n\n events: {\n \"click .setting-clear\" : \"clear\",\n \"keypress .setting-input\" : \"showClearButton\",\n \"change input\" : \"updateModel\",\n \"input input\" : \"enableAdd\",\n \"click .create-setting\" : \"addEntry\",\n \"click .remove-setting\" : \"removeEntry\"\n },\n\n templateName: \"metadata-dict-entry\",\n\n getValueFromEditor: function () {\n var dict = {};\n\n _.each(this.$el.find('li'), function(li, index) {\n var key = $(li).find('.input-key').val().trim(),\n value = $(li).find('.input-value').val().trim();\n\n // Keys should be unique, so if our keys are duplicated and\n // second key is empty or key and value are empty just do\n // nothing. Otherwise, it'll be overwritten by the new value.\n if (value === '') {\n if (key === '' || key in dict) {\n return false;\n }\n }\n\n dict[key] = value;\n });\n\n return dict;\n },\n\n setValueInEditor: function (value) {\n var list = this.$el.find('ol'),\n frag = document.createDocumentFragment();\n\n _.each(value, function(value, key) {\n var template = _.template(\n '
  • ' +\n '\">' +\n '\">' +\n '\">Remove' +\n '
  • '\n );\n\n frag.appendChild($(template({'key': key, 'value': value}))[0]);\n });\n\n list.html([frag]);\n },\n\n addEntry: function(event) {\n event.preventDefault();\n // We don't call updateModel here since it's bound to the\n // change event\n var dict = $.extend(true, {}, this.model.get('value')) || {};\n dict[''] = '';\n this.setValueInEditor(dict);\n this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true);\n },\n\n removeEntry: function(event) {\n event.preventDefault();\n var entry = $(event.currentTarget).siblings('.input-key').val();\n this.setValueInEditor(_.omit(this.model.get('value'), entry));\n this.updateModel();\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n },\n\n enableAdd: function() {\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n },\n\n clear: function() {\n AbstractEditor.prototype.clear.apply(this, arguments);\n if (_.isNull(this.model.getValue())) {\n this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);\n }\n }\n });\n\n\n /**\n * Provides convenient way to upload/download files in component edit.\n * The editor uploads files directly to course assets and stores link\n * to uploaded file.\n */\n Metadata.FileUploader = AbstractEditor.extend({\n\n events : {\n \"click .upload-setting\" : \"upload\",\n \"click .setting-clear\" : \"clear\"\n },\n\n templateName: \"metadata-file-uploader-entry\",\n templateButtonsName: \"metadata-file-uploader-item\",\n\n initialize: function () {\n this.buttonTemplate = this.loadTemplate(this.templateButtonsName);\n AbstractEditor.prototype.initialize.apply(this);\n },\n\n getValueFromEditor: function () {\n return this.$('#' + this.uniqueId).val();\n },\n\n setValueInEditor: function (value) {\n var html = this.buttonTemplate({\n model: this.model,\n uniqueId: this.uniqueId\n });\n\n this.$('#' + this.uniqueId).val(value);\n this.$('.wrapper-uploader-actions').html(html);\n },\n\n upload: function (event) {\n var self = this,\n target = $(event.currentTarget),\n url = '/assets/' + this.options.courseKey + '/',\n model = new FileUpload({\n title: gettext('Upload File'),\n }),\n view = new UploadDialog({\n model: model,\n url: url,\n parentElement: target.closest('.xblock-editor'),\n onSuccess: function (response) {\n if (response['asset'] && response['asset']['url']) {\n self.model.setValue(response['asset']['url']);\n }\n }\n }).show();\n\n event.preventDefault();\n }\n });\n\n Metadata.License = AbstractEditor.extend({\n\n initialize: function(options) {\n this.licenseModel = new LicenseModel({\"asString\": this.model.getValue()});\n this.licenseView = new LicenseView({model: this.licenseModel});\n\n // Rerender when the license model changes\n this.listenTo(this.licenseModel, 'change', this.setLicense);\n this.render();\n },\n\n render: function() {\n this.licenseView.render().$el.css(\"display\", \"inline\");\n this.licenseView.undelegateEvents();\n this.$el.empty().append(this.licenseView.el);\n // restore event bindings\n this.licenseView.delegateEvents();\n return this;\n },\n\n setLicense: function() {\n this.model.setValue(this.licenseModel.toString());\n this.render()\n }\n\n });\n\n return Metadata;\n});\n"},"repo_name":{"kind":"string","value":"MakeHer/edx-platform"},"path":{"kind":"string","value":"cms/static/js/views/metadata.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"agpl-3.0"},"size":{"kind":"number","value":21517,"string":"21,517"}}},{"rowIdx":115086519,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (c) 2013 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n */\n#ifndef VP9_COMMON_VP9_CONVOLVE_H_\n#define VP9_COMMON_VP9_CONVOLVE_H_\n\n#include \"./vpx_config.h\"\n#include \"vpx/vpx_integer.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef void (*convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride,\n uint8_t *dst, ptrdiff_t dst_stride,\n const int16_t *filter_x, int x_step_q4,\n const int16_t *filter_y, int y_step_q4,\n int w, int h);\n\n#if CONFIG_VP9_HIGHBITDEPTH\ntypedef void (*highbd_convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride,\n uint8_t *dst, ptrdiff_t dst_stride,\n const int16_t *filter_x, int x_step_q4,\n const int16_t *filter_y, int y_step_q4,\n int w, int h, int bd);\n#endif\n\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n#endif // VP9_COMMON_VP9_CONVOLVE_H_\n"},"repo_name":{"kind":"string","value":"jacklicn/webm.libvpx"},"path":{"kind":"string","value":"vp9/common/vp9_convolve.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":1386,"string":"1,386"}}},{"rowIdx":115086520,"cells":{"code":{"kind":"string","value":"\nflexbox | visibility: collapse and line wrapping\n\n\n\n
    \n\t

    filler

    \n\t

    filler

    \n\t

    filler

    \n\t

    filler

    \n
    \n"},"repo_name":{"kind":"string","value":"scheib/chromium"},"path":{"kind":"string","value":"third_party/blink/web_tests/external/wpt/css/css-flexbox/flexbox_visibility-collapse-line-wrapping-ref.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":463,"string":"463"}}},{"rowIdx":115086521,"cells":{"code":{"kind":"string","value":"\n */\n\n#ifndef __ASM_MACH_JZ4740_JZ4740_FB_H__\n#define __ASM_MACH_JZ4740_JZ4740_FB_H__\n\n#include \n\nenum jz4740_fb_lcd_type {\n\tJZ_LCD_TYPE_GENERIC_16_BIT = 0,\n\tJZ_LCD_TYPE_GENERIC_18_BIT = 0 | (1 << 4),\n\tJZ_LCD_TYPE_SPECIAL_TFT_1 = 1,\n\tJZ_LCD_TYPE_SPECIAL_TFT_2 = 2,\n\tJZ_LCD_TYPE_SPECIAL_TFT_3 = 3,\n\tJZ_LCD_TYPE_NON_INTERLACED_CCIR656 = 5,\n\tJZ_LCD_TYPE_INTERLACED_CCIR656 = 7,\n\tJZ_LCD_TYPE_SINGLE_COLOR_STN = 8,\n\tJZ_LCD_TYPE_SINGLE_MONOCHROME_STN = 9,\n\tJZ_LCD_TYPE_DUAL_COLOR_STN = 10,\n\tJZ_LCD_TYPE_DUAL_MONOCHROME_STN = 11,\n\tJZ_LCD_TYPE_8BIT_SERIAL = 12,\n};\n\n#define JZ4740_FB_SPECIAL_TFT_CONFIG(start, stop) (((start) << 16) | (stop))\n\n/*\n* width: width of the lcd display in mm\n* height: height of the lcd display in mm\n* num_modes: size of modes\n* modes: list of valid video modes\n* bpp: bits per pixel for the lcd\n* lcd_type: lcd type\n*/\n\nstruct jz4740_fb_platform_data {\n\tunsigned int width;\n\tunsigned int height;\n\n\tsize_t num_modes;\n\tstruct fb_videomode *modes;\n\n\tunsigned int bpp;\n\tenum jz4740_fb_lcd_type lcd_type;\n\n\tstruct {\n\t\tuint32_t spl;\n\t\tuint32_t cls;\n\t\tuint32_t ps;\n\t\tuint32_t rev;\n\t} special_tft_config;\n\n\tunsigned pixclk_falling_edge:1;\n\tunsigned date_enable_active_low:1;\n};\n\n#endif\n"},"repo_name":{"kind":"string","value":"koct9i/linux"},"path":{"kind":"string","value":"arch/mips/include/asm/mach-jz4740/jz4740_fb.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":1323,"string":"1,323"}}},{"rowIdx":115086524,"cells":{"code":{"kind":"string","value":"/* Copyright 2020 Alexander Tulloh\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\n#pragma once\n\n/*\n * Keyboard Matrix Assignments\n *\n * Change this to how you wired your keyboard\n * COLS: AVR pins used for columns, left to right\n * ROWS: AVR pins used for rows, top to bottom\n * DIODE_DIRECTION: COL2ROW = COL = Anode (+), ROW = Cathode (-, marked on diode)\n * ROW2COL = ROW = Anode (+), COL = Cathode (-, marked on diode)\n *\n */\n#define MATRIX_ROW_PINS { F6, B5, B6, F7 }\n#define MATRIX_COL_PINS { D6, D7, B4, D3, C6, C7 }\n#define UNUSED_PINS { B7, D4, D5, E6, F0, F1, F4, F5 }\n"},"repo_name":{"kind":"string","value":"kmtoki/qmk_firmware"},"path":{"kind":"string","value":"keyboards/oddball/v1/config.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":1203,"string":"1,203"}}},{"rowIdx":115086525,"cells":{"code":{"kind":"string","value":"\n\n\n \n \n Bulk Transfers\n \n \n \n \n \n \n \n
    \n \n \n \n \n \n \n \n \n \n
    Bulk Transfers
    Prev Chapter 5. Additional Features 
    \n
    \n
    \n
    \n
    \n
    \n
    \n

    Bulk Transfers

    \n
    \n
    \n
    \n

    \n By default, messages are sent from the master to replicas as they are generated.\n This can degrade replication performance because the various participating\n environments must handle a fair amount of network I/O activity.\n

    \n

    \n You can alleviate this problem by configuring your master environment for bulk\n transfers. Bulk transfers simply cause replication messages to accumulate in a\n buffer until a triggering event occurs. When this event occurs, the entire\n contents of the buffer is sent to the replica, thereby eliminating excessive\n network I/O.\n

    \n

    \n Note that if you are using replica to replica transfers, then you might want any\n replica that can service replication requests to also be configured for bulk\n transfers.\n

    \n

    \n The events that result in a bulk transfer of replication messages to a replica\n will differ depending on if the transmitting environment is a master or a\n replica.\n

    \n

    \n If the servicing environment is a master environment, then bulk transfer\n occurs when:\n

    \n
    \n
      \n
    1. \n

      \n Bulk transfers are configured for the master environment, and\n

      \n
    2. \n
    3. \n

      \n the message buffer is full or\n

      \n
    4. \n
    5. \n

      \n a permanent record (for example, a transaction commit or a\n checkpoint record) is placed in the buffer for the replica.\n

      \n
    6. \n
    \n
    \n

    \n If the servicing environment is a replica environment (that is, replica to replica\n transfers are in use), then a bulk transfer occurs when:\n

    \n
    \n
      \n
    1. \n

      \n Bulk transfers are configured for the transmitting replica, and\n

      \n
    2. \n
    3. \n

      \n the message buffer is full or\n

      \n
    4. \n
    5. \n

      \n the replica servicing the request is able to completely satisfy\n the request with the contents of the message buffer. \n

      \n
    6. \n
    \n
    \n

    \n To configure bulk transfers, specify\n\n \n DB_REP_CONF_BULK to\n \n DbEnv::rep_set_config()\n and then specify 1 to the onoff\n parameter. (Specify 0 to turn the feature off.)\n \n \n

    \n
    \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n \n
    Prev \n Up\n  
    Client to Client Transfer \n Home\n  
    \n
    \n \n\n"},"repo_name":{"kind":"string","value":"joglomedia/masedi.net"},"path":{"kind":"string","value":"work/berkeley-db/docs/gsg_db_rep/CXX/bulk.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":5739,"string":"5,739"}}},{"rowIdx":115086526,"cells":{"code":{"kind":"string","value":"/*\n * kexec-mips.c - kexec for mips\n * Copyright (C) 2007 Francesco Chiechi, Alessandro Rubini\n * Copyright (C) 2007 Tvblob s.r.l.\n *\n * derived from ../ppc/kexec-mips.c\n * Copyright (C) 2004, 2005 Albert Herranz\n *\n * This source code is licensed under the GNU General Public License,\n * Version 2. See the file COPYING for more details.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"../../kexec.h\"\n#include \"../../kexec-syscall.h\"\n#include \"kexec-mips.h\"\n#include \n\nstatic struct memory_range memory_range[MAX_MEMORY_RANGES];\n\n/* Return a sorted list of memory ranges. */\nint get_memory_ranges(struct memory_range **range, int *ranges,\n\t\t unsigned long UNUSED(kexec_flags))\n{\n\tint memory_ranges = 0;\n\n\tconst char iomem[] = \"/proc/iomem\";\n\tchar line[MAX_LINE];\n\tFILE *fp;\n\tunsigned long long start, end;\n\tchar *str;\n\tint type, consumed, count;\n\n\tfp = fopen(iomem, \"r\");\n\tif (!fp) {\n\t\tfprintf(stderr, \"Cannot open %s: %s\\n\", iomem, strerror(errno));\n\t\treturn -1;\n\t}\n\twhile (fgets(line, sizeof(line), fp) != 0) {\n\t\tif (memory_ranges >= MAX_MEMORY_RANGES)\n\t\t\tbreak;\n\t\tcount = sscanf(line, \"%Lx-%Lx : %n\", &start, &end, &consumed);\n\t\tif (count != 2)\n\t\t\tcontinue;\n\t\tstr = line + consumed;\n\t\tend = end + 1;\n\t\tif (memcmp(str, \"System RAM\\n\", 11) == 0) {\n\t\t\ttype = RANGE_RAM;\n\t\t} else if (memcmp(str, \"reserved\\n\", 9) == 0) {\n\t\t\ttype = RANGE_RESERVED;\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\t\tmemory_range[memory_ranges].start = start;\n\t\tmemory_range[memory_ranges].end = end;\n\t\tmemory_range[memory_ranges].type = type;\n\t\tmemory_ranges++;\n\t}\n\tfclose(fp);\n\t*range = memory_range;\n\t*ranges = memory_ranges;\n\treturn 0;\n}\n\nstruct file_type file_type[] = {\n\t{\"elf-mips\", elf_mips_probe, elf_mips_load, elf_mips_usage},\n};\nint file_types = sizeof(file_type) / sizeof(file_type[0]);\n\nvoid arch_usage(void)\n{\n#ifdef __mips64\n\tfprintf(stderr, \" --elf32-core-headers Prepare core headers in \"\n\t\t\t\"ELF32 format\\n\");\n#endif\n}\n\n#ifdef __mips64\nstruct arch_options_t arch_options = {\n\t.core_header_type = CORE_TYPE_ELF64\n};\n#endif\n\nint arch_process_options(int argc, char **argv)\n{\n\treturn 0;\n}\n\nconst struct arch_map_entry arches[] = {\n\t/* For compatibility with older patches\n\t * use KEXEC_ARCH_DEFAULT instead of KEXEC_ARCH_MIPS here.\n\t */\n\t{ \"mips\", KEXEC_ARCH_MIPS },\n\t{ \"mips64\", KEXEC_ARCH_MIPS },\n\t{ NULL, 0 },\n};\n\nint arch_compat_trampoline(struct kexec_info *UNUSED(info))\n{\n\n\treturn 0;\n}\n\nvoid arch_update_purgatory(struct kexec_info *UNUSED(info))\n{\n}\n\nunsigned long virt_to_phys(unsigned long addr)\n{\n\treturn addr & 0x7fffffff;\n}\n\n/*\n * add_segment() should convert base to a physical address on mips,\n * while the default is just to work with base as is */\nvoid add_segment(struct kexec_info *info, const void *buf, size_t bufsz,\n\t\t unsigned long base, size_t memsz)\n{\n\tadd_segment_phys_virt(info, buf, bufsz, virt_to_phys(base), memsz, 1);\n}\n\n/*\n * add_buffer() should convert base to a physical address on mips,\n * while the default is just to work with base as is */\nunsigned long add_buffer(struct kexec_info *info, const void *buf,\n\t\t\t unsigned long bufsz, unsigned long memsz,\n\t\t\t unsigned long buf_align, unsigned long buf_min,\n\t\t\t unsigned long buf_max, int buf_end)\n{\n\treturn add_buffer_phys_virt(info, buf, bufsz, memsz, buf_align,\n\t\t\t\t buf_min, buf_max, buf_end, 1);\n}\n\n"},"repo_name":{"kind":"string","value":"wanghao-xznu/vte"},"path":{"kind":"string","value":"testcases/third_party_suite/kexec/kexec-tools-2.0.2/kexec/arch/mips/kexec-mips.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":3379,"string":"3,379"}}},{"rowIdx":115086527,"cells":{"code":{"kind":"string","value":"// RUN: %clang_cc1 %s -emit-llvm -o - -fblocks -triple x86_64-apple-darwin10 | FileCheck %s\n// rdar://10033986\n\ntypedef void (^BLOCK)(void);\nint main ()\n{\n _Complex double c;\n BLOCK b = ^() {\n _Complex double z;\n z = z + c;\n };\n b();\n}\n\n// CHECK-LABEL: define internal void @__main_block_invoke\n// CHECK: [[C1:%.*]] = alloca { double, double }, align 8\n// CHECK: [[RP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 0\n// CHECK-NEXT: [[R:%.*]] = load double, double* [[RP]]\n// CHECK-NEXT: [[IP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 1\n// CHECK-NEXT: [[I:%.*]] = load double, double* [[IP]]\n"},"repo_name":{"kind":"string","value":"cd80/UtilizedLLVM"},"path":{"kind":"string","value":"tools/clang/test/CodeGen/capture-complex-expr-in-block.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"unlicense"},"size":{"kind":"number","value":710,"string":"710"}}},{"rowIdx":115086528,"cells":{"code":{"kind":"string","value":"\n\n \n \n or-tools/src/constraint_solver/: Class Members - Doxy\n \n \n \n \n \n\n \n \n \n\n \n \n \n \n \n\n \n \n \n \n\n \n \n \n \n \n\n \n \n \n \n
    \n \n Generated on: Thu Mar 29 07:46:58 PDT 2012\n for custom file set\n \n
    \n \n \n \n \n \n
    \n \"Doxy\"\n
    \n
    \n\n \n
    \n \n \n \n \n
    //\n doxy/\n or-tools/\n src/\n constraint_solver/\n \n
    \n
    \n
    \n \n \n\n
    \n \n \n
    \n \n
    \n
    \n \n
    \n
    \n
    \nHere is a list of all file members with links to the files they belong to:\n

    \n

    - l -

    \n
    \n\n \n \n \n \n \n \n \n \n
    \n\n













    \n













    \n













    \n













    \n













    \n













    \n













    \n













    \n













    \n













    \n

    \n\n \n \n\n"},"repo_name":{"kind":"string","value":"capturePointer/or-tools"},"path":{"kind":"string","value":"documentation/reference_manual/or-tools/src/constraint_solver/globals_0x6c.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":8677,"string":"8,677"}}},{"rowIdx":115086529,"cells":{"code":{"kind":"string","value":"\n * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)\n * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence\n * @link http://pear.php.net/package/PHP_CodeSniffer\n */\n\n/**\n * Unit test class for the MultiLineAssignment sniff.\n *\n * A sniff unit test checks a .inc file for expected violations of a single\n * coding standard. Expected errors and warnings are stored in this class.\n *\n * @category PHP\n * @package PHP_CodeSniffer\n * @author Greg Sherwood \n * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)\n * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence\n * @version Release: @package_version@\n * @link http://pear.php.net/package/PHP_CodeSniffer\n */\nclass PEAR_Tests_Formatting_MultiLineAssignmentUnitTest extends AbstractSniffUnitTest\n{\n\n\n /**\n * Returns the lines where errors should occur.\n *\n * The key of the array should represent the line number and the value\n * should represent the number of errors that should occur on that line.\n *\n * @return array\n */\n public function getErrorList()\n {\n return array(\n 3 => 1,\n 6 => 1,\n 8 => 1,\n );\n\n }//end getErrorList()\n\n\n /**\n * Returns the lines where warnings should occur.\n *\n * The key of the array should represent the line number and the value\n * should represent the number of warnings that should occur on that line.\n *\n * @return array\n */\n public function getWarningList()\n {\n return array();\n\n }//end getWarningList()\n\n\n}//end class\n\n?>\n"},"repo_name":{"kind":"string","value":"danalec/dotfiles"},"path":{"kind":"string","value":"sublime/.config/sublime-text-3/Packages/anaconda_php/plugin/handlers_php/linting/phpcs/CodeSniffer/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1893,"string":"1,893"}}},{"rowIdx":115086530,"cells":{"code":{"kind":"string","value":"/*\n * (C) Copyright 2003\n * Wolfgang Denk, DENX Software Engineering, wd@denx.de.\n *\n * See file CREDITS for list of people who contributed to this\n * project.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nDECLARE_GLOBAL_DATA_PTR;\n\n#define\tLINUX_MAX_ENVS\t\t256\n#define\tLINUX_MAX_ARGS\t\t256\n\nstatic int linux_argc;\nstatic char **linux_argv;\n\nstatic char **linux_env;\nstatic char *linux_env_p;\nstatic int linux_env_idx;\n\nstatic void linux_params_init(ulong start, char *commandline);\nstatic void linux_env_set(char *env_name, char *env_val);\n\nstatic void boot_prep_linux(bootm_headers_t *images)\n{\n\tchar *commandline = getenv(\"bootargs\");\n\tchar env_buf[12];\n\tchar *cp;\n\n\tlinux_params_init(UNCACHED_SDRAM(gd->bd->bi_boot_params), commandline);\n\n#ifdef CONFIG_MEMSIZE_IN_BYTES\n\tsprintf(env_buf, \"%lu\", (ulong)gd->ram_size);\n\tdebug(\"## Giving linux memsize in bytes, %lu\\n\", (ulong)gd->ram_size);\n#else\n\tsprintf(env_buf, \"%lu\", (ulong)(gd->ram_size >> 20));\n\tdebug(\"## Giving linux memsize in MB, %lu\\n\",\n\t\t(ulong)(gd->ram_size >> 20));\n#endif /* CONFIG_MEMSIZE_IN_BYTES */\n\n\tlinux_env_set(\"memsize\", env_buf);\n\n\tsprintf(env_buf, \"0x%08X\", (uint) UNCACHED_SDRAM(images->rd_start));\n\tlinux_env_set(\"initrd_start\", env_buf);\n\n\tsprintf(env_buf, \"0x%X\", (uint) (images->rd_end - images->rd_start));\n\tlinux_env_set(\"initrd_size\", env_buf);\n\n\tsprintf(env_buf, \"0x%08X\", (uint) (gd->bd->bi_flashstart));\n\tlinux_env_set(\"flash_start\", env_buf);\n\n\tsprintf(env_buf, \"0x%X\", (uint) (gd->bd->bi_flashsize));\n\tlinux_env_set(\"flash_size\", env_buf);\n\n\tcp = getenv(\"ethaddr\");\n\tif (cp)\n\t\tlinux_env_set(\"ethaddr\", cp);\n\n\tcp = getenv(\"eth1addr\");\n\tif (cp)\n\t\tlinux_env_set(\"eth1addr\", cp);\n}\n\nstatic void boot_jump_linux(bootm_headers_t *images)\n{\n\tvoid (*theKernel) (int, char **, char **, int *);\n\n\t/* find kernel entry point */\n\ttheKernel = (void (*)(int, char **, char **, int *))images->ep;\n\n\tdebug(\"## Transferring control to Linux (at address %08lx) ...\\n\",\n\t\t(ulong) theKernel);\n\n\tbootstage_mark(BOOTSTAGE_ID_RUN_OS);\n\n\t/* we assume that the kernel is in place */\n\tprintf(\"\\nStarting kernel ...\\n\\n\");\n\n\ttheKernel(linux_argc, linux_argv, linux_env, 0);\n}\n\nint do_bootm_linux(int flag, int argc, char * const argv[],\n\t\t\tbootm_headers_t *images)\n{\n\t/* No need for those on MIPS */\n\tif (flag & BOOTM_STATE_OS_BD_T || flag & BOOTM_STATE_OS_CMDLINE)\n\t\treturn -1;\n\n\tif (flag & BOOTM_STATE_OS_PREP) {\n\t\tboot_prep_linux(images);\n\t\treturn 0;\n\t}\n\n\tif (flag & BOOTM_STATE_OS_GO) {\n\t\tboot_jump_linux(images);\n\t\treturn 0;\n\t}\n\n\tboot_prep_linux(images);\n\tboot_jump_linux(images);\n\n\t/* does not return */\n\treturn 1;\n}\n\nstatic void linux_params_init(ulong start, char *line)\n{\n\tchar *next, *quote, *argp;\n\n\tlinux_argc = 1;\n\tlinux_argv = (char **) start;\n\tlinux_argv[0] = 0;\n\targp = (char *) (linux_argv + LINUX_MAX_ARGS);\n\n\tnext = line;\n\n\twhile (line && *line && linux_argc < LINUX_MAX_ARGS) {\n\t\tquote = strchr(line, '\"');\n\t\tnext = strchr(line, ' ');\n\n\t\twhile (next && quote && quote < next) {\n\t\t\t/* we found a left quote before the next blank\n\t\t\t * now we have to find the matching right quote\n\t\t\t */\n\t\t\tnext = strchr(quote + 1, '\"');\n\t\t\tif (next) {\n\t\t\t\tquote = strchr(next + 1, '\"');\n\t\t\t\tnext = strchr(next + 1, ' ');\n\t\t\t}\n\t\t}\n\n\t\tif (!next)\n\t\t\tnext = line + strlen(line);\n\n\t\tlinux_argv[linux_argc] = argp;\n\t\tmemcpy(argp, line, next - line);\n\t\targp[next - line] = 0;\n\n\t\targp += next - line + 1;\n\t\tlinux_argc++;\n\n\t\tif (*next)\n\t\t\tnext++;\n\n\t\tline = next;\n\t}\n\n\tlinux_env = (char **) (((ulong) argp + 15) & ~15);\n\tlinux_env[0] = 0;\n\tlinux_env_p = (char *) (linux_env + LINUX_MAX_ENVS);\n\tlinux_env_idx = 0;\n}\n\nstatic void linux_env_set(char *env_name, char *env_val)\n{\n\tif (linux_env_idx < LINUX_MAX_ENVS - 1) {\n\t\tlinux_env[linux_env_idx] = linux_env_p;\n\n\t\tstrcpy(linux_env_p, env_name);\n\t\tlinux_env_p += strlen(env_name);\n\n\t\tstrcpy(linux_env_p, \"=\");\n\t\tlinux_env_p += 1;\n\n\t\tstrcpy(linux_env_p, env_val);\n\t\tlinux_env_p += strlen(env_val);\n\n\t\tlinux_env_p++;\n\t\tlinux_env[++linux_env_idx] = 0;\n\t}\n}\n"},"repo_name":{"kind":"string","value":"lxl1140989/dmsdk"},"path":{"kind":"string","value":"uboot/u-boot-dm6291/arch/mips/lib/bootm.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":4774,"string":"4,774"}}},{"rowIdx":115086531,"cells":{"code":{"kind":"string","value":"enforce();\n\nif(!$yarpp->enabled() && !$yarpp->activate()) {\n echo '
    '.__('The YARPP database has an error which could not be fixed.','yarpp').'
    ';\n}\n\n/* Check to see that templates are in the right place */\nif (!$yarpp->diagnostic_custom_templates()) {\n\n $template_option = yarpp_get_option('template');\n if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('template', false);\n\n $template_option = yarpp_get_option('rss_template');\n if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('rss_template', false);\n}\n\n/**\n * @since 3.3 Move version checking here, in PHP.\n */\nif (current_user_can('update_plugins')) {\n $yarpp_version_info = $yarpp->version_info();\n\n /*\n * These strings are not localizable, as long as the plugin data on wordpress.org cannot be.\n */\n $slug = 'yet-another-related-posts-plugin';\n $plugin_name = 'Yet Another Related Posts Plugin';\n $file = basename(YARPP_DIR).'/yarpp.php';\n if ($yarpp_version_info['result'] === 'new') {\n\n /* Make sure the update system is aware of this version. */\n $current = get_site_transient('update_plugins');\n if (!isset($current->response[$file])) {\n delete_site_transient('update_plugins');\n wp_update_plugins();\n }\n\n echo '

    ';\n $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin='.$slug.'&TB_iframe=true&width=600&height=800');\n printf(\n __(\n 'There is a new version of %1$s available.'.\n 'View version %4$s details'.\n 'or update automatically.', 'yarpp'),\n $plugin_name,\n esc_url($details_url),\n esc_attr($plugin_name),\n $yarpp_version_info['current']['version'],\n wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_'.$file)\n );\n echo '

    ';\n\n } else if ($yarpp_version_info['result'] === 'newbeta') {\n\n echo '

    ';\n printf(\n __(\n \"There is a new beta (%s) of Yet Another Related Posts Plugin. \".\n \"You can download it here at your own risk.\", \"yarpp\"),\n $yarpp_version_info['beta']['version'],\n $yarpp_version_info['beta']['url']\n );\n echo '

    ';\n\n }\n}\n\n/* MyISAM Check */\ninclude 'yarpp_myisam_notice.php';\n\n/* This is not a yarpp pluging update, it is an yarpp option update */\nif (isset($_POST['update_yarpp'])) {\n $new_options = array();\n foreach ($yarpp->default_options as $option => $default) {\n if ( is_bool($default) )\n $new_options[$option] = isset($_POST[$option]);\n if ( (is_string($default) || is_int($default)) &&\n isset($_POST[$option]) && is_string($_POST[$option]) )\n $new_options[$option] = stripslashes($_POST[$option]);\n }\n\n if ( isset($_POST['weight']) ) {\n $new_options['weight'] = array();\n $new_options['require_tax'] = array();\n foreach ( (array) $_POST['weight'] as $key => $value) {\n if ( $value == 'consider' )\n $new_options['weight'][$key] = 1;\n if ( $value == 'consider_extra' )\n $new_options['weight'][$key] = YARPP_EXTRA_WEIGHT;\n }\n foreach ( (array) $_POST['weight']['tax'] as $tax => $value) {\n if ( $value == 'consider' )\n $new_options['weight']['tax'][$tax] = 1;\n if ( $value == 'consider_extra' )\n $new_options['weight']['tax'][$tax] = YARPP_EXTRA_WEIGHT;\n if ( $value == 'require_one' ) {\n $new_options['weight']['tax'][$tax] = 1;\n $new_options['require_tax'][$tax] = 1;\n }\n if ( $value == 'require_more' ) {\n $new_options['weight']['tax'][$tax] = 1;\n $new_options['require_tax'][$tax] = 2;\n }\n }\n }\n\n if ( isset( $_POST['auto_display_post_types'] ) ) {\n $new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] );\n } else {\n $new_options['auto_display_post_types'] = array();\n }\n\n $new_options['recent'] = isset($_POST['recent_only']) ?\n $_POST['recent_number'] . ' ' . $_POST['recent_units'] : false;\n\n if ( isset($_POST['exclude']) )\n $new_options['exclude'] = implode(',',array_keys($_POST['exclude']));\n else\n $new_options['exclude'] = '';\n\n $new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] :\n ( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false );\n $new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] :\n ( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false );\n\n $new_options = apply_filters( 'yarpp_settings_save', $new_options );\n yarpp_set_option($new_options);\n\n echo '

    '.__('Options saved!','yarpp').'

    ';\n}\n\nwp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);\nwp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);\nwp_nonce_field('yarpp_display_demo', 'yarpp_display_demo-nonce', false);\nwp_nonce_field('yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false);\nwp_nonce_field('yarpp_optin_data', 'yarpp_optin_data-nonce', false);\nwp_nonce_field('yarpp_set_display_code', 'yarpp_set_display_code-nonce', false);\n\nif (!count($yarpp->admin->get_templates()) && $yarpp->admin->can_copy_templates()) {\n wp_nonce_field('yarpp_copy_templates', 'yarpp_copy_templates-nonce', false);\n}\n\ninclude(YARPP_DIR.'/includes/phtmls/yarpp_options.phtml');"},"repo_name":{"kind":"string","value":"sarahkpeck/it-starts-with"},"path":{"kind":"string","value":"wp-content/plugins/yet-another-related-posts-plugin/includes/yarpp_options.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":5985,"string":"5,985"}}},{"rowIdx":115086532,"cells":{"code":{"kind":"string","value":"#\n# Copyright (C) 2010-2013 ARM Limited. All rights reserved.\n# \n# This program is free software and is provided to you under the terms of the GNU General Public License version 2\n# as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.\n# \n# A copy of the licence is included with the program, and can also be obtained from Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\nUSE_UMPV2=0\nUSING_PROFILING ?= 1\nUSING_INTERNAL_PROFILING ?= 0\nMALI_DMA_BUF_MAP_ON_ATTACH ?= 1\n\n# The Makefile sets up \"arch\" based on the CONFIG, creates the version info\n# string and the __malidrv_build_info.c file, and then call the Linux build\n# system to actually build the driver. After that point the Kbuild file takes\n# over.\n\n# set up defaults if not defined by the user\nARCH ?= arm\n\nOSKOS=linux\nFILES_PREFIX=\n\ncheck_cc2 = \\\n\t$(shell if $(1) -S -o /dev/null -xc /dev/null > /dev/null 2>&1; \\\n\tthen \\\n\t\techo \"$(2)\"; \\\n\telse \\\n\t\techo \"$(3)\"; \\\n\tfi ;)\n\n# This conditional makefile exports the global definition ARM_INTERNAL_BUILD. Customer releases will not include arm_internal.mak\n-include ../../../arm_internal.mak\n\n# Give warning of old config parameters are used\nifneq ($(CONFIG),)\n$(warning \"You have specified the CONFIG variable which is no longer in used. Use TARGET_PLATFORM instead.\")\nendif\n\nifneq ($(CPU),)\n$(warning \"You have specified the CPU variable which is no longer in used. Use TARGET_PLATFORM instead.\")\nendif\n\n# Include the mapping between TARGET_PLATFORM and KDIR + MALI_PLATFORM\n-include MALI_CONFIGURATION\nexport KDIR ?= $(KDIR-$(TARGET_PLATFORM))\nexport MALI_PLATFORM ?= $(MALI_PLATFORM-$(TARGET_PLATFORM))\n\nifneq ($(TARGET_PLATFORM),)\nifeq ($(MALI_PLATFORM),)\n$(error \"Invalid TARGET_PLATFORM: $(TARGET_PLATFORM)\")\nendif\nendif\n\n# validate lookup result\nifeq ($(KDIR),)\n$(error No KDIR found for platform $(TARGET_PLATFORM))\nendif\n\n\nifeq ($(USING_UMP),1)\nexport CONFIG_MALI400_UMP=y\nexport EXTRA_DEFINES += -DCONFIG_MALI400_UMP=1\nifeq ($(USE_UMPV2),1)\nUMP_SYMVERS_FILE ?= ../umpv2/Module.symvers\nelse\nUMP_SYMVERS_FILE ?= ../ump/Module.symvers\nendif\nKBUILD_EXTRA_SYMBOLS = $(realpath $(UMP_SYMVERS_FILE))\n$(warning $(KBUILD_EXTRA_SYMBOLS))\nendif\n\n# Define host system directory\nKDIR-$(shell uname -m):=/lib/modules/$(shell uname -r)/build\n\ninclude $(KDIR)/.config\n\nifeq ($(ARCH), arm)\n# when compiling for ARM we're cross compiling\nexport CROSS_COMPILE ?= $(call check_cc2, arm-linux-gnueabi-gcc, arm-linux-gnueabi-, arm-none-linux-gnueabi-)\nendif\n\n# report detected/selected settings\nifdef ARM_INTERNAL_BUILD\n$(warning TARGET_PLATFORM $(TARGET_PLATFORM))\n$(warning KDIR $(KDIR))\n$(warning MALI_PLATFORM $(MALI_PLATFORM))\nendif\n\n# Set up build config\nexport CONFIG_MALI400=m\n\nifneq ($(MALI_PLATFORM),)\nexport EXTRA_DEFINES += -DMALI_FAKE_PLATFORM_DEVICE=1\nexport MALI_PLATFORM_FILES = $(wildcard platform/$(MALI_PLATFORM)/*.c)\nendif\n\nifeq ($(USING_PROFILING),1)\nifeq ($(CONFIG_TRACEPOINTS),)\n$(warning CONFIG_TRACEPOINTS reqired for profiling)\nelse\nexport CONFIG_MALI400_PROFILING=y\nexport EXTRA_DEFINES += -DCONFIG_MALI400_PROFILING=1\nifeq ($(USING_INTERNAL_PROFILING),1)\nexport CONFIG_MALI400_INTERNAL_PROFILING=y\nexport EXTRA_DEFINES += -DCONFIG_MALI400_INTERNAL_PROFILING=1\nendif\nendif\nendif\n\nifeq ($(MALI_DMA_BUF_MAP_ON_ATTACH),1)\nexport CONFIG_MALI_DMA_BUF_MAP_ON_ATTACH=y\nexport EXTRA_DEFINES += -DCONFIG_MALI_DMA_BUF_MAP_ON_ATTACH\nendif\n\nifeq ($(MALI_SHARED_INTERRUPTS),1)\nexport CONFIG_MALI_SHARED_INTERRUPTS=y\nexport EXTRA_DEFINES += -DCONFIG_MALI_SHARED_INTERRUPTS\nendif\n\nifneq ($(BUILD),release)\nexport CONFIG_MALI400_DEBUG=y\nendif\n\nall: $(UMP_SYMVERS_FILE)\n\t$(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) modules\n\t@rm $(FILES_PREFIX)__malidrv_build_info.c $(FILES_PREFIX)__malidrv_build_info.o\n\nclean:\n\t$(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) clean\n\nkernelrelease:\n\t$(MAKE) ARCH=$(ARCH) -C $(KDIR) kernelrelease\n\nexport CONFIG KBUILD_EXTRA_SYMBOLS\n"},"repo_name":{"kind":"string","value":"gh1026/linux-3.4"},"path":{"kind":"string","value":"modules/mali/DX910-SW-99002-r3p2-01rel3/driver/src/devicedrv/mali/Makefile"},"language":{"kind":"string","value":"Makefile"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":3987,"string":"3,987"}}},{"rowIdx":115086533,"cells":{"code":{"kind":"string","value":"/* SPDX-License-Identifier: GPL-2.0+ */\n/* Copyright (c) 2016-2017 Hisilicon Limited. */\n\n#ifndef __HCLGEVF_CMD_H\n#define __HCLGEVF_CMD_H\n#include \n#include \n#include \"hnae3.h\"\n\n#define HCLGEVF_CMDQ_TX_TIMEOUT\t\t30000\n#define HCLGEVF_CMDQ_RX_INVLD_B\t\t0\n#define HCLGEVF_CMDQ_RX_OUTVLD_B\t1\n\nstruct hclgevf_hw;\nstruct hclgevf_dev;\n\nstruct hclgevf_desc {\n\t__le16 opcode;\n\t__le16 flag;\n\t__le16 retval;\n\t__le16 rsv;\n\t__le32 data[6];\n};\n\nstruct hclgevf_desc_cb {\n\tdma_addr_t dma;\n\tvoid *va;\n\tu32 length;\n};\n\nstruct hclgevf_cmq_ring {\n\tdma_addr_t desc_dma_addr;\n\tstruct hclgevf_desc *desc;\n\tstruct hclgevf_desc_cb *desc_cb;\n\tstruct hclgevf_dev *dev;\n\tu32 head;\n\tu32 tail;\n\n\tu16 buf_size;\n\tu16 desc_num;\n\tint next_to_use;\n\tint next_to_clean;\n\tu8 flag;\n\tspinlock_t lock; /* Command queue lock */\n};\n\nenum hclgevf_cmd_return_status {\n\tHCLGEVF_CMD_EXEC_SUCCESS\t= 0,\n\tHCLGEVF_CMD_NO_AUTH\t= 1,\n\tHCLGEVF_CMD_NOT_EXEC\t= 2,\n\tHCLGEVF_CMD_QUEUE_FULL\t= 3,\n};\n\nenum hclgevf_cmd_status {\n\tHCLGEVF_STATUS_SUCCESS\t= 0,\n\tHCLGEVF_ERR_CSQ_FULL\t= -1,\n\tHCLGEVF_ERR_CSQ_TIMEOUT\t= -2,\n\tHCLGEVF_ERR_CSQ_ERROR\t= -3\n};\n\nstruct hclgevf_cmq {\n\tstruct hclgevf_cmq_ring csq;\n\tstruct hclgevf_cmq_ring crq;\n\tu16 tx_timeout; /* Tx timeout */\n\tenum hclgevf_cmd_status last_status;\n};\n\n#define HCLGEVF_CMD_FLAG_IN_VALID_SHIFT\t\t0\n#define HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT\t1\n#define HCLGEVF_CMD_FLAG_NEXT_SHIFT\t\t2\n#define HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT\t\t3\n#define HCLGEVF_CMD_FLAG_NO_INTR_SHIFT\t\t4\n#define HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT\t\t5\n\n#define HCLGEVF_CMD_FLAG_IN\t\tBIT(HCLGEVF_CMD_FLAG_IN_VALID_SHIFT)\n#define HCLGEVF_CMD_FLAG_OUT\t\tBIT(HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT)\n#define HCLGEVF_CMD_FLAG_NEXT\t\tBIT(HCLGEVF_CMD_FLAG_NEXT_SHIFT)\n#define HCLGEVF_CMD_FLAG_WR\t\tBIT(HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT)\n#define HCLGEVF_CMD_FLAG_NO_INTR\tBIT(HCLGEVF_CMD_FLAG_NO_INTR_SHIFT)\n#define HCLGEVF_CMD_FLAG_ERR_INTR\tBIT(HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT)\n\nenum hclgevf_opcode_type {\n\t/* Generic command */\n\tHCLGEVF_OPC_QUERY_FW_VER\t= 0x0001,\n\t/* TQP command */\n\tHCLGEVF_OPC_QUERY_TX_STATUS\t= 0x0B03,\n\tHCLGEVF_OPC_QUERY_RX_STATUS\t= 0x0B13,\n\tHCLGEVF_OPC_CFG_COM_TQP_QUEUE\t= 0x0B20,\n\t/* RSS cmd */\n\tHCLGEVF_OPC_RSS_GENERIC_CONFIG\t= 0x0D01,\n\tHCLGEVF_OPC_RSS_INDIR_TABLE\t= 0x0D07,\n\tHCLGEVF_OPC_RSS_TC_MODE\t\t= 0x0D08,\n\t/* Mailbox cmd */\n\tHCLGEVF_OPC_MBX_VF_TO_PF\t= 0x2001,\n};\n\n#define HCLGEVF_TQP_REG_OFFSET\t\t0x80000\n#define HCLGEVF_TQP_REG_SIZE\t\t0x200\n\nstruct hclgevf_tqp_map {\n\t__le16 tqp_id;\t/* Absolute tqp id for in this pf */\n\tu8 tqp_vf; /* VF id */\n#define HCLGEVF_TQP_MAP_TYPE_PF\t\t0\n#define HCLGEVF_TQP_MAP_TYPE_VF\t\t1\n#define HCLGEVF_TQP_MAP_TYPE_B\t\t0\n#define HCLGEVF_TQP_MAP_EN_B\t\t1\n\tu8 tqp_flag;\t/* Indicate it's pf or vf tqp */\n\t__le16 tqp_vid; /* Virtual id in this pf/vf */\n\tu8 rsv[18];\n};\n\n#define HCLGEVF_VECTOR_ELEMENTS_PER_CMD\t10\n\nenum hclgevf_int_type {\n\tHCLGEVF_INT_TX = 0,\n\tHCLGEVF_INT_RX,\n\tHCLGEVF_INT_EVENT,\n};\n\nstruct hclgevf_ctrl_vector_chain {\n\tu8 int_vector_id;\n\tu8 int_cause_num;\n#define HCLGEVF_INT_TYPE_S\t0\n#define HCLGEVF_INT_TYPE_M\t0x3\n#define HCLGEVF_TQP_ID_S\t2\n#define HCLGEVF_TQP_ID_M\t(0x3fff << HCLGEVF_TQP_ID_S)\n\t__le16 tqp_type_and_id[HCLGEVF_VECTOR_ELEMENTS_PER_CMD];\n\tu8 vfid;\n\tu8 resv;\n};\n\nstruct hclgevf_query_version_cmd {\n\t__le32 firmware;\n\t__le32 firmware_rsv[5];\n};\n\n#define HCLGEVF_RSS_HASH_KEY_OFFSET\t4\n#define HCLGEVF_RSS_HASH_KEY_NUM\t16\nstruct hclgevf_rss_config_cmd {\n\tu8 hash_config;\n\tu8 rsv[7];\n\tu8 hash_key[HCLGEVF_RSS_HASH_KEY_NUM];\n};\n\nstruct hclgevf_rss_input_tuple_cmd {\n\tu8 ipv4_tcp_en;\n\tu8 ipv4_udp_en;\n\tu8 ipv4_stcp_en;\n\tu8 ipv4_fragment_en;\n\tu8 ipv6_tcp_en;\n\tu8 ipv6_udp_en;\n\tu8 ipv6_stcp_en;\n\tu8 ipv6_fragment_en;\n\tu8 rsv[16];\n};\n\n#define HCLGEVF_RSS_CFG_TBL_SIZE\t16\n\nstruct hclgevf_rss_indirection_table_cmd {\n\tu16 start_table_index;\n\tu16 rss_set_bitmap;\n\tu8 rsv[4];\n\tu8 rss_result[HCLGEVF_RSS_CFG_TBL_SIZE];\n};\n\n#define HCLGEVF_RSS_TC_OFFSET_S\t\t0\n#define HCLGEVF_RSS_TC_OFFSET_M\t\t(0x3ff << HCLGEVF_RSS_TC_OFFSET_S)\n#define HCLGEVF_RSS_TC_SIZE_S\t\t12\n#define HCLGEVF_RSS_TC_SIZE_M\t\t(0x7 << HCLGEVF_RSS_TC_SIZE_S)\n#define HCLGEVF_RSS_TC_VALID_B\t\t15\n#define HCLGEVF_MAX_TC_NUM\t\t8\nstruct hclgevf_rss_tc_mode_cmd {\n\tu16 rss_tc_mode[HCLGEVF_MAX_TC_NUM];\n\tu8 rsv[8];\n};\n\n#define HCLGEVF_LINK_STS_B\t0\n#define HCLGEVF_LINK_STATUS\tBIT(HCLGEVF_LINK_STS_B)\nstruct hclgevf_link_status_cmd {\n\tu8 status;\n\tu8 rsv[23];\n};\n\n#define HCLGEVF_RING_ID_MASK\t0x3ff\n#define HCLGEVF_TQP_ENABLE_B\t0\n\nstruct hclgevf_cfg_com_tqp_queue_cmd {\n\t__le16 tqp_id;\n\t__le16 stream_id;\n\tu8 enable;\n\tu8 rsv[19];\n};\n\nstruct hclgevf_cfg_tx_queue_pointer_cmd {\n\t__le16 tqp_id;\n\t__le16 tx_tail;\n\t__le16 tx_head;\n\t__le16 fbd_num;\n\t__le16 ring_offset;\n\tu8 rsv[14];\n};\n\n#define HCLGEVF_TYPE_CRQ\t\t0\n#define HCLGEVF_TYPE_CSQ\t\t1\n#define HCLGEVF_NIC_CSQ_BASEADDR_L_REG\t0x27000\n#define HCLGEVF_NIC_CSQ_BASEADDR_H_REG\t0x27004\n#define HCLGEVF_NIC_CSQ_DEPTH_REG\t0x27008\n#define HCLGEVF_NIC_CSQ_TAIL_REG\t0x27010\n#define HCLGEVF_NIC_CSQ_HEAD_REG\t0x27014\n#define HCLGEVF_NIC_CRQ_BASEADDR_L_REG\t0x27018\n#define HCLGEVF_NIC_CRQ_BASEADDR_H_REG\t0x2701c\n#define HCLGEVF_NIC_CRQ_DEPTH_REG\t0x27020\n#define HCLGEVF_NIC_CRQ_TAIL_REG\t0x27024\n#define HCLGEVF_NIC_CRQ_HEAD_REG\t0x27028\n#define HCLGEVF_NIC_CMQ_EN_B\t\t16\n#define HCLGEVF_NIC_CMQ_ENABLE\t\tBIT(HCLGEVF_NIC_CMQ_EN_B)\n#define HCLGEVF_NIC_CMQ_DESC_NUM\t1024\n#define HCLGEVF_NIC_CMQ_DESC_NUM_S\t3\n#define HCLGEVF_NIC_CMDQ_INT_SRC_REG\t0x27100\n\nstatic inline void hclgevf_write_reg(void __iomem *base, u32 reg, u32 value)\n{\n\twritel(value, base + reg);\n}\n\nstatic inline u32 hclgevf_read_reg(u8 __iomem *base, u32 reg)\n{\n\tu8 __iomem *reg_addr = READ_ONCE(base);\n\n\treturn readl(reg_addr + reg);\n}\n\n#define hclgevf_write_dev(a, reg, value) \\\n\thclgevf_write_reg((a)->io_base, (reg), (value))\n#define hclgevf_read_dev(a, reg) \\\n\thclgevf_read_reg((a)->io_base, (reg))\n\n#define HCLGEVF_SEND_SYNC(flag) \\\n\t((flag) & HCLGEVF_CMD_FLAG_NO_INTR)\n\nint hclgevf_cmd_init(struct hclgevf_dev *hdev);\nvoid hclgevf_cmd_uninit(struct hclgevf_dev *hdev);\n\nint hclgevf_cmd_send(struct hclgevf_hw *hw, struct hclgevf_desc *desc, int num);\nvoid hclgevf_cmd_setup_basic_desc(struct hclgevf_desc *desc,\n\t\t\t\t enum hclgevf_opcode_type opcode,\n\t\t\t\t bool is_read);\n#endif\n"},"repo_name":{"kind":"string","value":"raumfeld/linux-am33xx"},"path":{"kind":"string","value":"drivers/net/ethernet/hisilicon/hns3/hns3vf/hclgevf_cmd.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":6156,"string":"6,156"}}},{"rowIdx":115086534,"cells":{"code":{"kind":"string","value":"/* Test the `vmaxQs32' ARM Neon intrinsic. */\n/* This file was autogenerated by neon-testgen. */\n\n/* { dg-do assemble } */\n/* { dg-require-effective-target arm_neon_ok } */\n/* { dg-options \"-save-temps -O0\" } */\n/* { dg-add-options arm_neon } */\n\n#include \"arm_neon.h\"\n\nvoid test_vmaxQs32 (void)\n{\n int32x4_t out_int32x4_t;\n int32x4_t arg0_int32x4_t;\n int32x4_t arg1_int32x4_t;\n\n out_int32x4_t = vmaxq_s32 (arg0_int32x4_t, arg1_int32x4_t);\n}\n\n/* { dg-final { scan-assembler \"vmax\\.s32\\[ \t\\]+\\[qQ\\]\\[0-9\\]+, \\[qQ\\]\\[0-9\\]+, \\[qQ\\]\\[0-9\\]+!?\\(\\[ \t\\]+@\\[a-zA-Z0-9 \\]+\\)?\\n\" } } */\n"},"repo_name":{"kind":"string","value":"selmentdev/selment-toolchain"},"path":{"kind":"string","value":"source/gcc-latest/gcc/testsuite/gcc.target/arm/neon/vmaxQs32.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":584,"string":"584"}}},{"rowIdx":115086535,"cells":{"code":{"kind":"string","value":"\"\"\"\n report test results in JUnit-XML format,\n for use with Jenkins and build integration servers.\n\n\nBased on initial code from Ross Lawley.\n\nOutput conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/\nsrc/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport functools\nimport py\nimport os\nimport re\nimport sys\nimport time\nimport pytest\nfrom _pytest import nodes\nfrom _pytest.config import filename_arg\n\n# Python 2.X and 3.X compatibility\nif sys.version_info[0] < 3:\n from codecs import open\nelse:\n unichr = chr\n unicode = str\n long = int\n\n\nclass Junit(py.xml.Namespace):\n pass\n\n\n# We need to get the subset of the invalid unicode ranges according to\n# XML 1.0 which are valid in this python build. Hence we calculate\n# this dynamically instead of hardcoding it. The spec range of valid\n# chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]\n# | [#x10000-#x10FFFF]\n_legal_chars = (0x09, 0x0A, 0x0d)\n_legal_ranges = (\n (0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF),\n)\n_legal_xml_re = [\n unicode(\"%s-%s\") % (unichr(low), unichr(high))\n for (low, high) in _legal_ranges if low < sys.maxunicode\n]\n_legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re\nillegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re))\ndel _legal_chars\ndel _legal_ranges\ndel _legal_xml_re\n\n_py_ext_re = re.compile(r\"\\.py$\")\n\n\ndef bin_xml_escape(arg):\n def repl(matchobj):\n i = ord(matchobj.group())\n if i <= 0xFF:\n return unicode('#x%02X') % i\n else:\n return unicode('#x%04X') % i\n\n return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))\n\n\nclass _NodeReporter(object):\n def __init__(self, nodeid, xml):\n\n self.id = nodeid\n self.xml = xml\n self.add_stats = self.xml.add_stats\n self.duration = 0\n self.properties = []\n self.nodes = []\n self.testcase = None\n self.attrs = {}\n\n def append(self, node):\n self.xml.add_stats(type(node).__name__)\n self.nodes.append(node)\n\n def add_property(self, name, value):\n self.properties.append((str(name), bin_xml_escape(value)))\n\n def make_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.properties:\n return Junit.properties([\n Junit.property(name=name, value=value)\n for name, value in self.properties\n ])\n return ''\n\n def record_testreport(self, testreport):\n assert not self.testcase\n names = mangle_test_address(testreport.nodeid)\n classnames = names[:-1]\n if self.xml.prefix:\n classnames.insert(0, self.xml.prefix)\n attrs = {\n \"classname\": \".\".join(classnames),\n \"name\": bin_xml_escape(names[-1]),\n \"file\": testreport.location[0],\n }\n if testreport.location[1] is not None:\n attrs[\"line\"] = testreport.location[1]\n if hasattr(testreport, \"url\"):\n attrs[\"url\"] = testreport.url\n self.attrs = attrs\n\n def to_xml(self):\n testcase = Junit.testcase(time=self.duration, **self.attrs)\n testcase.append(self.make_properties_node())\n for node in self.nodes:\n testcase.append(node)\n return testcase\n\n def _add_simple(self, kind, message, data=None):\n data = bin_xml_escape(data)\n node = kind(data, message=message)\n self.append(node)\n\n def write_captured_output(self, report):\n for capname in ('out', 'err'):\n content = getattr(report, 'capstd' + capname)\n if content:\n tag = getattr(Junit, 'system-' + capname)\n self.append(tag(bin_xml_escape(content)))\n\n def append_pass(self, report):\n self.add_stats('passed')\n\n def append_failure(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n if hasattr(report, \"wasxfail\"):\n self._add_simple(\n Junit.skipped,\n \"xfail-marked test passes unexpectedly\")\n else:\n if hasattr(report.longrepr, \"reprcrash\"):\n message = report.longrepr.reprcrash.message\n elif isinstance(report.longrepr, (unicode, str)):\n message = report.longrepr\n else:\n message = str(report.longrepr)\n message = bin_xml_escape(message)\n fail = Junit.failure(message=message)\n fail.append(bin_xml_escape(report.longrepr))\n self.append(fail)\n\n def append_collect_error(self, report):\n # msg = str(report.longrepr.reprtraceback.extraline)\n self.append(Junit.error(bin_xml_escape(report.longrepr),\n message=\"collection failure\"))\n\n def append_collect_skipped(self, report):\n self._add_simple(\n Junit.skipped, \"collection skipped\", report.longrepr)\n\n def append_error(self, report):\n if getattr(report, 'when', None) == 'teardown':\n msg = \"test teardown failure\"\n else:\n msg = \"test setup failure\"\n self._add_simple(\n Junit.error, msg, report.longrepr)\n\n def append_skipped(self, report):\n if hasattr(report, \"wasxfail\"):\n self._add_simple(\n Junit.skipped, \"expected test failure\", report.wasxfail\n )\n else:\n filename, lineno, skipreason = report.longrepr\n if skipreason.startswith(\"Skipped: \"):\n skipreason = bin_xml_escape(skipreason[9:])\n self.append(\n Junit.skipped(\"%s:%s: %s\" % (filename, lineno, skipreason),\n type=\"pytest.skip\",\n message=skipreason))\n self.write_captured_output(report)\n\n def finalize(self):\n data = self.to_xml().unicode(indent=0)\n self.__dict__.clear()\n self.to_xml = lambda: py.xml.raw(data)\n\n\n@pytest.fixture\ndef record_xml_property(request):\n \"\"\"Add extra xml properties to the tag for the calling test.\n The fixture is callable with ``(name, value)``, with value being automatically\n xml-encoded.\n \"\"\"\n request.node.warn(\n code='C3',\n message='record_xml_property is an experimental feature',\n )\n xml = getattr(request.config, \"_xml\", None)\n if xml is not None:\n node_reporter = xml.node_reporter(request.node.nodeid)\n return node_reporter.add_property\n else:\n def add_property_noop(name, value):\n pass\n\n return add_property_noop\n\n\ndef pytest_addoption(parser):\n group = parser.getgroup(\"terminal reporting\")\n group.addoption(\n '--junitxml', '--junit-xml',\n action=\"store\",\n dest=\"xmlpath\",\n metavar=\"path\",\n type=functools.partial(filename_arg, optname=\"--junitxml\"),\n default=None,\n help=\"create junit-xml style report file at given path.\")\n group.addoption(\n '--junitprefix', '--junit-prefix',\n action=\"store\",\n metavar=\"str\",\n default=None,\n help=\"prepend prefix to classnames in junit-xml output\")\n parser.addini(\"junit_suite_name\", \"Test suite name for JUnit report\", default=\"pytest\")\n\n\ndef pytest_configure(config):\n xmlpath = config.option.xmlpath\n # prevent opening xmllog on slave nodes (xdist)\n if xmlpath and not hasattr(config, 'slaveinput'):\n config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini(\"junit_suite_name\"))\n config.pluginmanager.register(config._xml)\n\n\ndef pytest_unconfigure(config):\n xml = getattr(config, '_xml', None)\n if xml:\n del config._xml\n config.pluginmanager.unregister(xml)\n\n\ndef mangle_test_address(address):\n path, possible_open_bracket, params = address.partition('[')\n names = path.split(\"::\")\n try:\n names.remove('()')\n except ValueError:\n pass\n # convert file path to dotted path\n names[0] = names[0].replace(nodes.SEP, '.')\n names[0] = _py_ext_re.sub(\"\", names[0])\n # put any params back\n names[-1] += possible_open_bracket + params\n return names\n\n\nclass LogXML(object):\n def __init__(self, logfile, prefix, suite_name=\"pytest\"):\n logfile = os.path.expanduser(os.path.expandvars(logfile))\n self.logfile = os.path.normpath(os.path.abspath(logfile))\n self.prefix = prefix\n self.suite_name = suite_name\n self.stats = dict.fromkeys([\n 'error',\n 'passed',\n 'failure',\n 'skipped',\n ], 0)\n self.node_reporters = {} # nodeid -> _NodeReporter\n self.node_reporters_ordered = []\n self.global_properties = []\n # List of reports that failed on call but teardown is pending.\n self.open_reports = []\n self.cnt_double_fail_tests = 0\n\n def finalize(self, report):\n nodeid = getattr(report, 'nodeid', report)\n # local hack to handle xdist report order\n slavenode = getattr(report, 'node', None)\n reporter = self.node_reporters.pop((nodeid, slavenode))\n if reporter is not None:\n reporter.finalize()\n\n def node_reporter(self, report):\n nodeid = getattr(report, 'nodeid', report)\n # local hack to handle xdist report order\n slavenode = getattr(report, 'node', None)\n\n key = nodeid, slavenode\n\n if key in self.node_reporters:\n # TODO: breasks for --dist=each\n return self.node_reporters[key]\n\n reporter = _NodeReporter(nodeid, self)\n\n self.node_reporters[key] = reporter\n self.node_reporters_ordered.append(reporter)\n\n return reporter\n\n def add_stats(self, key):\n if key in self.stats:\n self.stats[key] += 1\n\n def _opentestcase(self, report):\n reporter = self.node_reporter(report)\n reporter.record_testreport(report)\n return reporter\n\n def pytest_runtest_logreport(self, report):\n \"\"\"handle a setup/call/teardown report, generating the appropriate\n xml tags as necessary.\n\n note: due to plugins like xdist, this hook may be called in interlaced\n order with reports from other nodes. for example:\n\n usual call order:\n -> setup node1\n -> call node1\n -> teardown node1\n -> setup node2\n -> call node2\n -> teardown node2\n\n possible call order in xdist:\n -> setup node1\n -> call node1\n -> setup node2\n -> call node2\n -> teardown node2\n -> teardown node1\n \"\"\"\n close_report = None\n if report.passed:\n if report.when == \"call\": # ignore setup/teardown\n reporter = self._opentestcase(report)\n reporter.append_pass(report)\n elif report.failed:\n if report.when == \"teardown\":\n # The following vars are needed when xdist plugin is used\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (rep for rep in self.open_reports\n if (rep.nodeid == report.nodeid and\n getattr(rep, \"item_index\", None) == report_ii and\n getattr(rep, \"worker_id\", None) == report_wid\n )\n ), None)\n if close_report:\n # We need to open new testcase in case we have failure in\n # call and error in teardown in order to follow junit\n # schema\n self.finalize(close_report)\n self.cnt_double_fail_tests += 1\n reporter = self._opentestcase(report)\n if report.when == \"call\":\n reporter.append_failure(report)\n self.open_reports.append(report)\n else:\n reporter.append_error(report)\n elif report.skipped:\n reporter = self._opentestcase(report)\n reporter.append_skipped(report)\n self.update_testcase_duration(report)\n if report.when == \"teardown\":\n reporter = self._opentestcase(report)\n reporter.write_captured_output(report)\n self.finalize(report)\n report_wid = getattr(report, \"worker_id\", None)\n report_ii = getattr(report, \"item_index\", None)\n close_report = next(\n (rep for rep in self.open_reports\n if (rep.nodeid == report.nodeid and\n getattr(rep, \"item_index\", None) == report_ii and\n getattr(rep, \"worker_id\", None) == report_wid\n )\n ), None)\n if close_report:\n self.open_reports.remove(close_report)\n\n def update_testcase_duration(self, report):\n \"\"\"accumulates total duration for nodeid from given report and updates\n the Junit.testcase with the new total if already created.\n \"\"\"\n reporter = self.node_reporter(report)\n reporter.duration += getattr(report, 'duration', 0.0)\n\n def pytest_collectreport(self, report):\n if not report.passed:\n reporter = self._opentestcase(report)\n if report.failed:\n reporter.append_collect_error(report)\n else:\n reporter.append_collect_skipped(report)\n\n def pytest_internalerror(self, excrepr):\n reporter = self.node_reporter('internal')\n reporter.attrs.update(classname=\"pytest\", name='internal')\n reporter._add_simple(Junit.error, 'internal error', excrepr)\n\n def pytest_sessionstart(self):\n self.suite_start_time = time.time()\n\n def pytest_sessionfinish(self):\n dirname = os.path.dirname(os.path.abspath(self.logfile))\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n logfile = open(self.logfile, 'w', encoding='utf-8')\n suite_stop_time = time.time()\n suite_time_delta = suite_stop_time - self.suite_start_time\n\n numtests = (self.stats['passed'] + self.stats['failure'] +\n self.stats['skipped'] + self.stats['error'] -\n self.cnt_double_fail_tests)\n logfile.write('')\n\n logfile.write(Junit.testsuite(\n self._get_global_properties_node(),\n [x.to_xml() for x in self.node_reporters_ordered],\n name=self.suite_name,\n errors=self.stats['error'],\n failures=self.stats['failure'],\n skips=self.stats['skipped'],\n tests=numtests,\n time=\"%.3f\" % suite_time_delta, ).unicode(indent=0))\n logfile.close()\n\n def pytest_terminal_summary(self, terminalreporter):\n terminalreporter.write_sep(\"-\",\n \"generated xml file: %s\" % (self.logfile))\n\n def add_global_property(self, name, value):\n self.global_properties.append((str(name), bin_xml_escape(value)))\n\n def _get_global_properties_node(self):\n \"\"\"Return a Junit node containing custom properties, if any.\n \"\"\"\n if self.global_properties:\n return Junit.properties(\n [\n Junit.property(name=name, value=value)\n for name, value in self.global_properties\n ]\n )\n return ''\n"},"repo_name":{"kind":"string","value":"anthgur/servo"},"path":{"kind":"string","value":"tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/junitxml.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"mpl-2.0"},"size":{"kind":"number","value":15681,"string":"15,681"}}},{"rowIdx":115086536,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\n\n\n\n
    \n\n\n"},"repo_name":{"kind":"string","value":"js0701/chromium-crosswalk"},"path":{"kind":"string","value":"third_party/WebKit/LayoutTests/http/tests/security/cookies/base-about-blank.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":842,"string":"842"}}},{"rowIdx":115086537,"cells":{"code":{"kind":"string","value":"/**\r\n * Copyright (c) 2016 hustcc\r\n * License: MIT\r\n * https://github.com/hustcc/timeago.js\r\n**/\r\n/* jshint expr: true */\r\n!function (root, factory) {\r\n if (typeof module === 'object' && module.exports)\r\n module.exports = factory(root);\r\n else\r\n root.timeago = factory(root);\r\n}(typeof window !== 'undefined' ? window : this, \r\nfunction () {\r\n var cnt = 0, // the timer counter, for timer key\r\n indexMapEn = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'],\r\n indexMapZh = ['秒', '分钟', '小时', '天', '周', '月', '年'],\r\n // build-in locales: en & zh_CN\r\n locales = {\r\n 'en': function(number, index) {\r\n if (index === 0) return ['just now', 'a while'];\r\n else {\r\n var unit = indexMapEn[parseInt(index / 2)];\r\n if (number > 1) unit += 's';\r\n return [number + ' ' + unit + ' ago', 'in ' + number + ' ' + unit];\r\n }\r\n },\r\n 'zh_CN': function(number, index) {\r\n if (index === 0) return ['刚刚', '片刻后'];\r\n else {\r\n var unit = indexMapZh[parseInt(index / 2)];\r\n return [number + unit + '前', number + unit + '后'];\r\n }\r\n }\r\n },\r\n // second, minute, hour, day, week, month, year(365 days)\r\n SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12],\r\n SEC_ARRAY_LEN = 6,\r\n ATTR_DATETIME = 'datetime';\r\n \r\n /**\r\n * timeago: the function to get `timeago` instance.\r\n * - nowDate: the relative date, default is new Date().\r\n * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you.\r\n *\r\n * How to use it?\r\n * var timeagoLib = require('timeago.js');\r\n * var timeago = timeagoLib(); // all use default.\r\n * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.\r\n * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`.\r\n * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前.\r\n **/\r\n function timeago(nowDate, defaultLocale) {\r\n var timers = {}; // real-time render timers\r\n // if do not set the defaultLocale, set it with `en`\r\n if (! defaultLocale) defaultLocale = 'en'; // use default build-in locale\r\n // calculate the diff second between date to be formated an now date.\r\n function diffSec(date) {\r\n var now = new Date();\r\n if (nowDate) now = toDate(nowDate);\r\n return (now - toDate(date)) / 1000;\r\n }\r\n // format the diff second to *** time ago, with setting locale\r\n function formatDiff(diff, locale) {\r\n if (! locales[locale]) locale = defaultLocale;\r\n var i = 0;\r\n agoin = diff < 0 ? 1 : 0, // timein or timeago\r\n diff = Math.abs(diff);\r\n\r\n for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {\r\n diff /= SEC_ARRAY[i];\r\n }\r\n diff = toInt(diff);\r\n i *= 2;\r\n\r\n if (diff > (i === 0 ? 9 : 1)) i += 1;\r\n return locales[locale](diff, i)[agoin].replace('%s', diff);\r\n }\r\n /**\r\n * format: format the date to *** time ago, with setting or default locale\r\n * - date: the date / string / timestamp to be formated\r\n * - locale: the formated string's locale name, e.g. en / zh_CN\r\n *\r\n * How to use it?\r\n * var timeago = require('timeago.js')();\r\n * timeago.format(new Date(), 'pl'); // Date instance\r\n * timeago.format('2016-09-10', 'fr'); // formated date string\r\n * timeago.format(1473473400269); // timestamp with ms\r\n **/\r\n this.format = function(date, locale) {\r\n return formatDiff(diffSec(date), locale);\r\n };\r\n // format Date / string / timestamp to Date instance.\r\n function toDate(input) {\r\n if (input instanceof Date) {\r\n return input;\r\n } else if (!isNaN(input)) {\r\n return new Date(toInt(input));\r\n } else if (/^\\d+$/.test(input)) {\r\n return new Date(toInt(input, 10));\r\n } else {\r\n var s = (input || '').trim();\r\n s = s.replace(/\\.\\d+/, '') // remove milliseconds\r\n .replace(/-/, '/').replace(/-/, '/')\r\n .replace(/T/, ' ').replace(/Z/, ' UTC')\r\n .replace(/([\\+\\-]\\d\\d)\\:?(\\d\\d)/, ' $1$2'); // -04:00 -> -0400\r\n return new Date(s);\r\n }\r\n }\r\n // change f into int, remove Decimal. just for code compression\r\n function toInt(f) {\r\n return parseInt(f);\r\n }\r\n // function leftSec(diff, unit) {\r\n // diff = diff % unit;\r\n // diff = diff ? unit - diff : unit;\r\n // return Math.ceil(diff);\r\n // }\r\n /**\r\n * nextInterval: calculate the next interval time.\r\n * - diff: the diff sec between now and date to be formated.\r\n *\r\n * What's the meaning?\r\n * diff = 61 then return 59\r\n * diff = 3601 (an hour + 1 second), then return 3599\r\n * make the interval with high performace.\r\n **/\r\n // this.nextInterval = function(diff) { // for dev test\r\n function nextInterval(diff) {\r\n var rst = 1, i = 0, d = diff;\r\n for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {\r\n diff /= SEC_ARRAY[i];\r\n rst *= SEC_ARRAY[i];\r\n }\r\n // return leftSec(d, rst);\r\n d = d % rst;\r\n d = d ? rst - d : rst;\r\n return Math.ceil(d);\r\n // }; // for dev test\r\n }\r\n // what the timer will do\r\n function doRender(node, date, locale, cnt) {\r\n var diff = diffSec(date);\r\n node.innerHTML = formatDiff(diff, locale);\r\n // waiting %s seconds, do the next render\r\n timers['k' + cnt] = setTimeout(function() {\r\n doRender(node, date, locale, cnt);\r\n }, nextInterval(diff) * 1000);\r\n }\r\n // get the datetime attribute, jQuery and DOM\r\n function getDateAttr(node) {\r\n if (node.getAttribute) return node.getAttribute(ATTR_DATETIME);\r\n if(node.attr) return node.attr(ATTR_DATETIME);\r\n }\r\n /**\r\n * render: render the DOM real-time.\r\n * - nodes: which nodes will be rendered.\r\n * - locale: the locale name used to format date.\r\n *\r\n * How to use it?\r\n * var timeago = new require('timeago.js')();\r\n * // 1. javascript selector\r\n * timeago.render(document.querySelectorAll('.need_to_be_rendered'));\r\n * // 2. use jQuery selector\r\n * timeago.render($('.need_to_be_rendered'), 'pl');\r\n *\r\n * Notice: please be sure the dom has attribute `datetime`.\r\n **/\r\n this.render = function(nodes, locale) {\r\n if (nodes.length === undefined) nodes = [nodes];\r\n for (var i = 0; i < nodes.length; i++) {\r\n doRender(nodes[i], getDateAttr(nodes[i]), locale, ++ cnt); // render item\r\n }\r\n };\r\n /**\r\n * cancel: cancel all the timers which are doing real-time render.\r\n *\r\n * How to use it?\r\n * var timeago = new require('timeago.js')();\r\n * timeago.render(document.querySelectorAll('.need_to_be_rendered'));\r\n * timeago.cancel(); // will stop all the timer, stop render in real time.\r\n **/\r\n this.cancel = function() {\r\n for (var key in timers) {\r\n clearTimeout(timers[key]);\r\n }\r\n timers = {};\r\n };\r\n /**\r\n * setLocale: set the default locale name.\r\n *\r\n * How to use it?\r\n * var timeago = require('timeago.js');\r\n * timeago = new timeago();\r\n * timeago.setLocale('fr');\r\n **/\r\n this.setLocale = function(locale) {\r\n defaultLocale = locale;\r\n };\r\n return this;\r\n }\r\n /**\r\n * timeago: the function to get `timeago` instance.\r\n * - nowDate: the relative date, default is new Date().\r\n * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you.\r\n *\r\n * How to use it?\r\n * var timeagoLib = require('timeago.js');\r\n * var timeago = timeagoLib(); // all use default.\r\n * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.\r\n * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`.\r\n * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前.\r\n **/\r\n function timeagoFactory(nowDate, defaultLocale) {\r\n return new timeago(nowDate, defaultLocale);\r\n }\r\n /**\r\n * register: register a new language locale\r\n * - locale: locale name, e.g. en / zh_CN, notice the standard.\r\n * - localeFunc: the locale process function\r\n *\r\n * How to use it?\r\n * var timeagoLib = require('timeago.js');\r\n *\r\n * timeagoLib.register('the locale name', the_locale_func);\r\n * // or\r\n * timeagoLib.register('pl', require('timeago.js/locales/pl'));\r\n **/\r\n timeagoFactory.register = function(locale, localeFunc) {\r\n locales[locale] = localeFunc;\r\n };\r\n\r\n return timeagoFactory;\r\n});"},"repo_name":{"kind":"string","value":"froala/cdnjs"},"path":{"kind":"string","value":"ajax/libs/timeago.js/2.0.0/timeago.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":8824,"string":"8,824"}}},{"rowIdx":115086538,"cells":{"code":{"kind":"string","value":"/*\n * drivers/net/ethernet/mellanox/mlxsw/cmd.h\n * Copyright (c) 2015 Mellanox Technologies. All rights reserved.\n * Copyright (c) 2015 Jiri Pirko \n * Copyright (c) 2015 Ido Schimmel \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the names of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * Alternatively, this software may be distributed under the terms of the\n * GNU General Public License (\"GPL\") version 2 as published by the Free\n * Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef _MLXSW_CMD_H\n#define _MLXSW_CMD_H\n\n#include \"item.h\"\n\n#define MLXSW_CMD_MBOX_SIZE\t4096\n\nstatic inline char *mlxsw_cmd_mbox_alloc(void)\n{\n\treturn kzalloc(MLXSW_CMD_MBOX_SIZE, GFP_KERNEL);\n}\n\nstatic inline void mlxsw_cmd_mbox_free(char *mbox)\n{\n\tkfree(mbox);\n}\n\nstatic inline void mlxsw_cmd_mbox_zero(char *mbox)\n{\n\tmemset(mbox, 0, MLXSW_CMD_MBOX_SIZE);\n}\n\nstruct mlxsw_core;\n\nint mlxsw_cmd_exec(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod,\n\t\t u32 in_mod, bool out_mbox_direct,\n\t\t char *in_mbox, size_t in_mbox_size,\n\t\t char *out_mbox, size_t out_mbox_size);\n\nstatic inline int mlxsw_cmd_exec_in(struct mlxsw_core *mlxsw_core, u16 opcode,\n\t\t\t\t u8 opcode_mod, u32 in_mod, char *in_mbox,\n\t\t\t\t size_t in_mbox_size)\n{\n\treturn mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false,\n\t\t\t in_mbox, in_mbox_size, NULL, 0);\n}\n\nstatic inline int mlxsw_cmd_exec_out(struct mlxsw_core *mlxsw_core, u16 opcode,\n\t\t\t\t u8 opcode_mod, u32 in_mod,\n\t\t\t\t bool out_mbox_direct,\n\t\t\t\t char *out_mbox, size_t out_mbox_size)\n{\n\treturn mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod,\n\t\t\t out_mbox_direct, NULL, 0,\n\t\t\t out_mbox, out_mbox_size);\n}\n\nstatic inline int mlxsw_cmd_exec_none(struct mlxsw_core *mlxsw_core, u16 opcode,\n\t\t\t\t u8 opcode_mod, u32 in_mod)\n{\n\treturn mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false,\n\t\t\t NULL, 0, NULL, 0);\n}\n\nenum mlxsw_cmd_opcode {\n\tMLXSW_CMD_OPCODE_QUERY_FW\t\t= 0x004,\n\tMLXSW_CMD_OPCODE_QUERY_BOARDINFO\t= 0x006,\n\tMLXSW_CMD_OPCODE_QUERY_AQ_CAP\t\t= 0x003,\n\tMLXSW_CMD_OPCODE_MAP_FA\t\t\t= 0xFFF,\n\tMLXSW_CMD_OPCODE_UNMAP_FA\t\t= 0xFFE,\n\tMLXSW_CMD_OPCODE_CONFIG_PROFILE\t\t= 0x100,\n\tMLXSW_CMD_OPCODE_ACCESS_REG\t\t= 0x040,\n\tMLXSW_CMD_OPCODE_SW2HW_DQ\t\t= 0x201,\n\tMLXSW_CMD_OPCODE_HW2SW_DQ\t\t= 0x202,\n\tMLXSW_CMD_OPCODE_2ERR_DQ\t\t= 0x01E,\n\tMLXSW_CMD_OPCODE_QUERY_DQ\t\t= 0x022,\n\tMLXSW_CMD_OPCODE_SW2HW_CQ\t\t= 0x016,\n\tMLXSW_CMD_OPCODE_HW2SW_CQ\t\t= 0x017,\n\tMLXSW_CMD_OPCODE_QUERY_CQ\t\t= 0x018,\n\tMLXSW_CMD_OPCODE_SW2HW_EQ\t\t= 0x013,\n\tMLXSW_CMD_OPCODE_HW2SW_EQ\t\t= 0x014,\n\tMLXSW_CMD_OPCODE_QUERY_EQ\t\t= 0x015,\n\tMLXSW_CMD_OPCODE_QUERY_RESOURCES\t= 0x101,\n};\n\nstatic inline const char *mlxsw_cmd_opcode_str(u16 opcode)\n{\n\tswitch (opcode) {\n\tcase MLXSW_CMD_OPCODE_QUERY_FW:\n\t\treturn \"QUERY_FW\";\n\tcase MLXSW_CMD_OPCODE_QUERY_BOARDINFO:\n\t\treturn \"QUERY_BOARDINFO\";\n\tcase MLXSW_CMD_OPCODE_QUERY_AQ_CAP:\n\t\treturn \"QUERY_AQ_CAP\";\n\tcase MLXSW_CMD_OPCODE_MAP_FA:\n\t\treturn \"MAP_FA\";\n\tcase MLXSW_CMD_OPCODE_UNMAP_FA:\n\t\treturn \"UNMAP_FA\";\n\tcase MLXSW_CMD_OPCODE_CONFIG_PROFILE:\n\t\treturn \"CONFIG_PROFILE\";\n\tcase MLXSW_CMD_OPCODE_ACCESS_REG:\n\t\treturn \"ACCESS_REG\";\n\tcase MLXSW_CMD_OPCODE_SW2HW_DQ:\n\t\treturn \"SW2HW_DQ\";\n\tcase MLXSW_CMD_OPCODE_HW2SW_DQ:\n\t\treturn \"HW2SW_DQ\";\n\tcase MLXSW_CMD_OPCODE_2ERR_DQ:\n\t\treturn \"2ERR_DQ\";\n\tcase MLXSW_CMD_OPCODE_QUERY_DQ:\n\t\treturn \"QUERY_DQ\";\n\tcase MLXSW_CMD_OPCODE_SW2HW_CQ:\n\t\treturn \"SW2HW_CQ\";\n\tcase MLXSW_CMD_OPCODE_HW2SW_CQ:\n\t\treturn \"HW2SW_CQ\";\n\tcase MLXSW_CMD_OPCODE_QUERY_CQ:\n\t\treturn \"QUERY_CQ\";\n\tcase MLXSW_CMD_OPCODE_SW2HW_EQ:\n\t\treturn \"SW2HW_EQ\";\n\tcase MLXSW_CMD_OPCODE_HW2SW_EQ:\n\t\treturn \"HW2SW_EQ\";\n\tcase MLXSW_CMD_OPCODE_QUERY_EQ:\n\t\treturn \"QUERY_EQ\";\n\tcase MLXSW_CMD_OPCODE_QUERY_RESOURCES:\n\t\treturn \"QUERY_RESOURCES\";\n\tdefault:\n\t\treturn \"*UNKNOWN*\";\n\t}\n}\n\nenum mlxsw_cmd_status {\n\t/* Command execution succeeded. */\n\tMLXSW_CMD_STATUS_OK\t\t= 0x00,\n\t/* Internal error (e.g. bus error) occurred while processing command. */\n\tMLXSW_CMD_STATUS_INTERNAL_ERR\t= 0x01,\n\t/* Operation/command not supported or opcode modifier not supported. */\n\tMLXSW_CMD_STATUS_BAD_OP\t\t= 0x02,\n\t/* Parameter not supported, parameter out of range. */\n\tMLXSW_CMD_STATUS_BAD_PARAM\t= 0x03,\n\t/* System was not enabled or bad system state. */\n\tMLXSW_CMD_STATUS_BAD_SYS_STATE\t= 0x04,\n\t/* Attempt to access reserved or unallocated resource, or resource in\n\t * inappropriate ownership.\n\t */\n\tMLXSW_CMD_STATUS_BAD_RESOURCE\t= 0x05,\n\t/* Requested resource is currently executing a command. */\n\tMLXSW_CMD_STATUS_RESOURCE_BUSY\t= 0x06,\n\t/* Required capability exceeds device limits. */\n\tMLXSW_CMD_STATUS_EXCEED_LIM\t= 0x08,\n\t/* Resource is not in the appropriate state or ownership. */\n\tMLXSW_CMD_STATUS_BAD_RES_STATE\t= 0x09,\n\t/* Index out of range (might be beyond table size or attempt to\n\t * access a reserved resource).\n\t */\n\tMLXSW_CMD_STATUS_BAD_INDEX\t= 0x0A,\n\t/* NVMEM checksum/CRC failed. */\n\tMLXSW_CMD_STATUS_BAD_NVMEM\t= 0x0B,\n\t/* Bad management packet (silently discarded). */\n\tMLXSW_CMD_STATUS_BAD_PKT\t= 0x30,\n};\n\nstatic inline const char *mlxsw_cmd_status_str(u8 status)\n{\n\tswitch (status) {\n\tcase MLXSW_CMD_STATUS_OK:\n\t\treturn \"OK\";\n\tcase MLXSW_CMD_STATUS_INTERNAL_ERR:\n\t\treturn \"INTERNAL_ERR\";\n\tcase MLXSW_CMD_STATUS_BAD_OP:\n\t\treturn \"BAD_OP\";\n\tcase MLXSW_CMD_STATUS_BAD_PARAM:\n\t\treturn \"BAD_PARAM\";\n\tcase MLXSW_CMD_STATUS_BAD_SYS_STATE:\n\t\treturn \"BAD_SYS_STATE\";\n\tcase MLXSW_CMD_STATUS_BAD_RESOURCE:\n\t\treturn \"BAD_RESOURCE\";\n\tcase MLXSW_CMD_STATUS_RESOURCE_BUSY:\n\t\treturn \"RESOURCE_BUSY\";\n\tcase MLXSW_CMD_STATUS_EXCEED_LIM:\n\t\treturn \"EXCEED_LIM\";\n\tcase MLXSW_CMD_STATUS_BAD_RES_STATE:\n\t\treturn \"BAD_RES_STATE\";\n\tcase MLXSW_CMD_STATUS_BAD_INDEX:\n\t\treturn \"BAD_INDEX\";\n\tcase MLXSW_CMD_STATUS_BAD_NVMEM:\n\t\treturn \"BAD_NVMEM\";\n\tcase MLXSW_CMD_STATUS_BAD_PKT:\n\t\treturn \"BAD_PKT\";\n\tdefault:\n\t\treturn \"*UNKNOWN*\";\n\t}\n}\n\n/* QUERY_FW - Query Firmware\n * -------------------------\n * OpMod == 0, INMmod == 0\n * -----------------------\n * The QUERY_FW command retrieves information related to firmware, command\n * interface version and the amount of resources that should be allocated to\n * the firmware.\n */\n\nstatic inline int mlxsw_cmd_query_fw(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_FW,\n\t\t\t\t 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_query_fw_fw_pages\n * Amount of physical memory to be allocatedfor firmware usage in 4KB pages.\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_pages, 0x00, 16, 16);\n\n/* cmd_mbox_query_fw_fw_rev_major\n * Firmware Revision - Major\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_major, 0x00, 0, 16);\n\n/* cmd_mbox_query_fw_fw_rev_subminor\n * Firmware Sub-minor version (Patch level)\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_subminor, 0x04, 16, 16);\n\n/* cmd_mbox_query_fw_fw_rev_minor\n * Firmware Revision - Minor\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_minor, 0x04, 0, 16);\n\n/* cmd_mbox_query_fw_core_clk\n * Internal Clock Frequency (in MHz)\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, core_clk, 0x08, 16, 16);\n\n/* cmd_mbox_query_fw_cmd_interface_rev\n * Command Interface Interpreter Revision ID. This number is bumped up\n * every time a non-backward-compatible change is done for the command\n * interface. The current cmd_interface_rev is 1.\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, cmd_interface_rev, 0x08, 0, 16);\n\n/* cmd_mbox_query_fw_dt\n * If set, Debug Trace is supported\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, dt, 0x0C, 31, 1);\n\n/* cmd_mbox_query_fw_api_version\n * Indicates the version of the API, to enable software querying\n * for compatibility. The current api_version is 1.\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, api_version, 0x0C, 0, 16);\n\n/* cmd_mbox_query_fw_fw_hour\n * Firmware timestamp - hour\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_hour, 0x10, 24, 8);\n\n/* cmd_mbox_query_fw_fw_minutes\n * Firmware timestamp - minutes\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_minutes, 0x10, 16, 8);\n\n/* cmd_mbox_query_fw_fw_seconds\n * Firmware timestamp - seconds\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_seconds, 0x10, 8, 8);\n\n/* cmd_mbox_query_fw_fw_year\n * Firmware timestamp - year\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_year, 0x14, 16, 16);\n\n/* cmd_mbox_query_fw_fw_month\n * Firmware timestamp - month\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_month, 0x14, 8, 8);\n\n/* cmd_mbox_query_fw_fw_day\n * Firmware timestamp - day\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, fw_day, 0x14, 0, 8);\n\n/* cmd_mbox_query_fw_clr_int_base_offset\n * Clear Interrupt register's offset from clr_int_bar register\n * in PCI address space.\n */\nMLXSW_ITEM64(cmd_mbox, query_fw, clr_int_base_offset, 0x20, 0, 64);\n\n/* cmd_mbox_query_fw_clr_int_bar\n * PCI base address register (BAR) where clr_int register is located.\n * 00 - BAR 0-1 (64 bit BAR)\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, clr_int_bar, 0x28, 30, 2);\n\n/* cmd_mbox_query_fw_error_buf_offset\n * Read Only buffer for internal error reports of offset\n * from error_buf_bar register in PCI address space).\n */\nMLXSW_ITEM64(cmd_mbox, query_fw, error_buf_offset, 0x30, 0, 64);\n\n/* cmd_mbox_query_fw_error_buf_size\n * Internal error buffer size in DWORDs\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, error_buf_size, 0x38, 0, 32);\n\n/* cmd_mbox_query_fw_error_int_bar\n * PCI base address register (BAR) where error buffer\n * register is located.\n * 00 - BAR 0-1 (64 bit BAR)\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, error_int_bar, 0x3C, 30, 2);\n\n/* cmd_mbox_query_fw_doorbell_page_offset\n * Offset of the doorbell page\n */\nMLXSW_ITEM64(cmd_mbox, query_fw, doorbell_page_offset, 0x40, 0, 64);\n\n/* cmd_mbox_query_fw_doorbell_page_bar\n * PCI base address register (BAR) of the doorbell page\n * 00 - BAR 0-1 (64 bit BAR)\n */\nMLXSW_ITEM32(cmd_mbox, query_fw, doorbell_page_bar, 0x48, 30, 2);\n\n/* QUERY_BOARDINFO - Query Board Information\n * -----------------------------------------\n * OpMod == 0 (N/A), INMmod == 0 (N/A)\n * -----------------------------------\n * The QUERY_BOARDINFO command retrieves adapter specific parameters.\n */\n\nstatic inline int mlxsw_cmd_boardinfo(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_BOARDINFO,\n\t\t\t\t 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_boardinfo_intapin\n * When PCIe interrupt messages are being used, this value is used for clearing\n * an interrupt. When using MSI-X, this register is not used.\n */\nMLXSW_ITEM32(cmd_mbox, boardinfo, intapin, 0x10, 24, 8);\n\n/* cmd_mbox_boardinfo_vsd_vendor_id\n * PCISIG Vendor ID (www.pcisig.com/membership/vid_search) of the vendor\n * specifying/formatting the VSD. The vsd_vendor_id identifies the management\n * domain of the VSD/PSID data. Different vendors may choose different VSD/PSID\n * format and encoding as long as they use their assigned vsd_vendor_id.\n */\nMLXSW_ITEM32(cmd_mbox, boardinfo, vsd_vendor_id, 0x1C, 0, 16);\n\n/* cmd_mbox_boardinfo_vsd\n * Vendor Specific Data. The VSD string that is burnt to the Flash\n * with the firmware.\n */\n#define MLXSW_CMD_BOARDINFO_VSD_LEN 208\nMLXSW_ITEM_BUF(cmd_mbox, boardinfo, vsd, 0x20, MLXSW_CMD_BOARDINFO_VSD_LEN);\n\n/* cmd_mbox_boardinfo_psid\n * The PSID field is a 16-ascii (byte) character string which acts as\n * the board ID. The PSID format is used in conjunction with\n * Mellanox vsd_vendor_id (15B3h).\n */\n#define MLXSW_CMD_BOARDINFO_PSID_LEN 16\nMLXSW_ITEM_BUF(cmd_mbox, boardinfo, psid, 0xF0, MLXSW_CMD_BOARDINFO_PSID_LEN);\n\n/* QUERY_AQ_CAP - Query Asynchronous Queues Capabilities\n * -----------------------------------------------------\n * OpMod == 0 (N/A), INMmod == 0 (N/A)\n * -----------------------------------\n * The QUERY_AQ_CAP command returns the device asynchronous queues\n * capabilities supported.\n */\n\nstatic inline int mlxsw_cmd_query_aq_cap(struct mlxsw_core *mlxsw_core,\n\t\t\t\t\t char *out_mbox)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_AQ_CAP,\n\t\t\t\t 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_query_aq_cap_log_max_sdq_sz\n * Log (base 2) of max WQEs allowed on SDQ.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_sdq_sz, 0x00, 24, 8);\n\n/* cmd_mbox_query_aq_cap_max_num_sdqs\n * Maximum number of SDQs.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_sdqs, 0x00, 0, 8);\n\n/* cmd_mbox_query_aq_cap_log_max_rdq_sz\n * Log (base 2) of max WQEs allowed on RDQ.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_rdq_sz, 0x04, 24, 8);\n\n/* cmd_mbox_query_aq_cap_max_num_rdqs\n * Maximum number of RDQs.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_rdqs, 0x04, 0, 8);\n\n/* cmd_mbox_query_aq_cap_log_max_cq_sz\n * Log (base 2) of max CQEs allowed on CQ.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_cq_sz, 0x08, 24, 8);\n\n/* cmd_mbox_query_aq_cap_max_num_cqs\n * Maximum number of CQs.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_cqs, 0x08, 0, 8);\n\n/* cmd_mbox_query_aq_cap_log_max_eq_sz\n * Log (base 2) of max EQEs allowed on EQ.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_eq_sz, 0x0C, 24, 8);\n\n/* cmd_mbox_query_aq_cap_max_num_eqs\n * Maximum number of EQs.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_eqs, 0x0C, 0, 8);\n\n/* cmd_mbox_query_aq_cap_max_sg_sq\n * The maximum S/G list elements in an DSQ. DSQ must not contain\n * more S/G entries than indicated here.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_sq, 0x10, 8, 8);\n\n/* cmd_mbox_query_aq_cap_\n * The maximum S/G list elements in an DRQ. DRQ must not contain\n * more S/G entries than indicated here.\n */\nMLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_rq, 0x10, 0, 8);\n\n/* MAP_FA - Map Firmware Area\n * --------------------------\n * OpMod == 0 (N/A), INMmod == Number of VPM entries\n * -------------------------------------------------\n * The MAP_FA command passes physical pages to the switch. These pages\n * are used to store the device firmware. MAP_FA can be executed multiple\n * times until all the firmware area is mapped (the size that should be\n * mapped is retrieved through the QUERY_FW command). All required pages\n * must be mapped to finish the initialization phase. Physical memory\n * passed in this command must be pinned.\n */\n\n#define MLXSW_CMD_MAP_FA_VPM_ENTRIES_MAX 32\n\nstatic inline int mlxsw_cmd_map_fa(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 vpm_entries_count)\n{\n\treturn mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_MAP_FA,\n\t\t\t\t 0, vpm_entries_count,\n\t\t\t\t in_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_map_fa_pa\n * Physical Address.\n */\nMLXSW_ITEM64_INDEXED(cmd_mbox, map_fa, pa, 0x00, 12, 52, 0x08, 0x00, true);\n\n/* cmd_mbox_map_fa_log2size\n * Log (base 2) of the size in 4KB pages of the physical and contiguous memory\n * that starts at PA_L/H.\n */\nMLXSW_ITEM32_INDEXED(cmd_mbox, map_fa, log2size, 0x00, 0, 5, 0x08, 0x04, false);\n\n/* UNMAP_FA - Unmap Firmware Area\n * ------------------------------\n * OpMod == 0 (N/A), INMmod == 0 (N/A)\n * -----------------------------------\n * The UNMAP_FA command unload the firmware and unmaps all the\n * firmware area. After this command is completed the device will not access\n * the pages that were mapped to the firmware area. After executing UNMAP_FA\n * command, software reset must be done prior to execution of MAP_FW command.\n */\n\nstatic inline int mlxsw_cmd_unmap_fa(struct mlxsw_core *mlxsw_core)\n{\n\treturn mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_UNMAP_FA, 0, 0);\n}\n\n/* QUERY_RESOURCES - Query chip resources\n * --------------------------------------\n * OpMod == 0 (N/A) , INMmod is index\n * ----------------------------------\n * The QUERY_RESOURCES command retrieves information related to chip resources\n * by resource ID. Every command returns 32 entries. INmod is being use as base.\n * for example, index 1 will return entries 32-63. When the tables end and there\n * are no more sources in the table, will return resource id 0xFFF to indicate\n * it.\n */\n\n#define MLXSW_CMD_QUERY_RESOURCES_TABLE_END_ID 0xffff\n#define MLXSW_CMD_QUERY_RESOURCES_MAX_QUERIES 100\n#define MLXSW_CMD_QUERY_RESOURCES_PER_QUERY 32\n\nstatic inline int mlxsw_cmd_query_resources(struct mlxsw_core *mlxsw_core,\n\t\t\t\t\t char *out_mbox, int index)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_RESOURCES,\n\t\t\t\t 0, index, false, out_mbox,\n\t\t\t\t MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_query_resource_id\n * The resource id. 0xFFFF indicates table's end.\n */\nMLXSW_ITEM32_INDEXED(cmd_mbox, query_resource, id, 0x00, 16, 16, 0x8, 0, false);\n\n/* cmd_mbox_query_resource_data\n * The resource\n */\nMLXSW_ITEM64_INDEXED(cmd_mbox, query_resource, data,\n\t\t 0x00, 0, 40, 0x8, 0, false);\n\n/* CONFIG_PROFILE (Set) - Configure Switch Profile\n * ------------------------------\n * OpMod == 1 (Set), INMmod == 0 (N/A)\n * -----------------------------------\n * The CONFIG_PROFILE command sets the switch profile. The command can be\n * executed on the device only once at startup in order to allocate and\n * configure all switch resources and prepare it for operational mode.\n * It is not possible to change the device profile after the chip is\n * in operational mode.\n * Failure of the CONFIG_PROFILE command leaves the hardware in an indeterminate\n * state therefore it is required to perform software reset to the device\n * following an unsuccessful completion of the command. It is required\n * to perform software reset to the device to change an existing profile.\n */\n\nstatic inline int mlxsw_cmd_config_profile_set(struct mlxsw_core *mlxsw_core,\n\t\t\t\t\t char *in_mbox)\n{\n\treturn mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_CONFIG_PROFILE,\n\t\t\t\t 1, 0, in_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_config_profile_set_max_vepa_channels\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_vepa_channels, 0x0C, 0, 1);\n\n/* cmd_mbox_config_profile_set_max_lag\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_lag, 0x0C, 1, 1);\n\n/* cmd_mbox_config_profile_set_max_port_per_lag\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_port_per_lag, 0x0C, 2, 1);\n\n/* cmd_mbox_config_profile_set_max_mid\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_mid, 0x0C, 3, 1);\n\n/* cmd_mbox_config_profile_set_max_pgt\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_pgt, 0x0C, 4, 1);\n\n/* cmd_mbox_config_profile_set_max_system_port\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_system_port, 0x0C, 5, 1);\n\n/* cmd_mbox_config_profile_set_max_vlan_groups\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_vlan_groups, 0x0C, 6, 1);\n\n/* cmd_mbox_config_profile_set_max_regions\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_regions, 0x0C, 7, 1);\n\n/* cmd_mbox_config_profile_set_flood_mode\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_flood_mode, 0x0C, 8, 1);\n\n/* cmd_mbox_config_profile_set_max_flood_tables\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_flood_tables, 0x0C, 9, 1);\n\n/* cmd_mbox_config_profile_set_max_ib_mc\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_ib_mc, 0x0C, 12, 1);\n\n/* cmd_mbox_config_profile_set_max_pkey\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_max_pkey, 0x0C, 13, 1);\n\n/* cmd_mbox_config_profile_set_adaptive_routing_group_cap\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile,\n\t set_adaptive_routing_group_cap, 0x0C, 14, 1);\n\n/* cmd_mbox_config_profile_set_ar_sec\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_ar_sec, 0x0C, 15, 1);\n\n/* cmd_mbox_config_set_kvd_linear_size\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_linear_size, 0x0C, 24, 1);\n\n/* cmd_mbox_config_set_kvd_hash_single_size\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_single_size, 0x0C, 25, 1);\n\n/* cmd_mbox_config_set_kvd_hash_double_size\n * Capability bit. Setting a bit to 1 configures the profile\n * according to the mailbox contents.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_double_size, 0x0C, 26, 1);\n\n/* cmd_mbox_config_profile_max_vepa_channels\n * Maximum number of VEPA channels per port (0 through 16)\n * 0 - multi-channel VEPA is disabled\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_vepa_channels, 0x10, 0, 8);\n\n/* cmd_mbox_config_profile_max_lag\n * Maximum number of LAG IDs requested.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_lag, 0x14, 0, 16);\n\n/* cmd_mbox_config_profile_max_port_per_lag\n * Maximum number of ports per LAG requested.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_port_per_lag, 0x18, 0, 16);\n\n/* cmd_mbox_config_profile_max_mid\n * Maximum Multicast IDs.\n * Multicast IDs are allocated from 0 to max_mid-1\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_mid, 0x1C, 0, 16);\n\n/* cmd_mbox_config_profile_max_pgt\n * Maximum records in the Port Group Table per Switch Partition.\n * Port Group Table indexes are from 0 to max_pgt-1\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_pgt, 0x20, 0, 16);\n\n/* cmd_mbox_config_profile_max_system_port\n * The maximum number of system ports that can be allocated.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_system_port, 0x24, 0, 16);\n\n/* cmd_mbox_config_profile_max_vlan_groups\n * Maximum number VLAN Groups for VLAN binding.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_vlan_groups, 0x28, 0, 12);\n\n/* cmd_mbox_config_profile_max_regions\n * Maximum number of TCAM Regions.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_regions, 0x2C, 0, 16);\n\n/* cmd_mbox_config_profile_max_flood_tables\n * Maximum number of single-entry flooding tables. Different flooding tables\n * can be associated with different packet types.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_flood_tables, 0x30, 16, 4);\n\n/* cmd_mbox_config_profile_max_vid_flood_tables\n * Maximum number of per-vid flooding tables. Flooding tables are associated\n * to the different packet types for the different switch partitions.\n * Table size is 4K entries covering all VID space.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_vid_flood_tables, 0x30, 8, 4);\n\n/* cmd_mbox_config_profile_flood_mode\n * Flooding mode to use.\n * 0-2 - Backward compatible modes for SwitchX devices.\n * 3 - Mixed mode, where:\n * max_flood_tables indicates the number of single-entry tables.\n * max_vid_flood_tables indicates the number of per-VID tables.\n * max_fid_offset_flood_tables indicates the number of FID-offset tables.\n * max_fid_flood_tables indicates the number of per-FID tables.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, flood_mode, 0x30, 0, 2);\n\n/* cmd_mbox_config_profile_max_fid_offset_flood_tables\n * Maximum number of FID-offset flooding tables.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile,\n\t max_fid_offset_flood_tables, 0x34, 24, 4);\n\n/* cmd_mbox_config_profile_fid_offset_flood_table_size\n * The size (number of entries) of each FID-offset flood table.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile,\n\t fid_offset_flood_table_size, 0x34, 0, 16);\n\n/* cmd_mbox_config_profile_max_fid_flood_tables\n * Maximum number of per-FID flooding tables.\n *\n * Note: This flooding tables cover special FIDs only (vFIDs), starting at\n * FID value 4K and higher.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_fid_flood_tables, 0x38, 24, 4);\n\n/* cmd_mbox_config_profile_fid_flood_table_size\n * The size (number of entries) of each per-FID table.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, fid_flood_table_size, 0x38, 0, 16);\n\n/* cmd_mbox_config_profile_max_ib_mc\n * Maximum number of multicast FDB records for InfiniBand\n * FDB (in 512 chunks) per InfiniBand switch partition.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_ib_mc, 0x40, 0, 15);\n\n/* cmd_mbox_config_profile_max_pkey\n * Maximum per port PKEY table size (for PKEY enforcement)\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, max_pkey, 0x44, 0, 15);\n\n/* cmd_mbox_config_profile_ar_sec\n * Primary/secondary capability\n * Describes the number of adaptive routing sub-groups\n * 0 - disable primary/secondary (single group)\n * 1 - enable primary/secondary (2 sub-groups)\n * 2 - 3 sub-groups: Not supported in SwitchX, SwitchX-2\n * 3 - 4 sub-groups: Not supported in SwitchX, SwitchX-2\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, ar_sec, 0x4C, 24, 2);\n\n/* cmd_mbox_config_profile_adaptive_routing_group_cap\n * Adaptive Routing Group Capability. Indicates the number of AR groups\n * supported. Note that when Primary/secondary is enabled, each\n * primary/secondary couple consumes 2 adaptive routing entries.\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, adaptive_routing_group_cap, 0x4C, 0, 16);\n\n/* cmd_mbox_config_profile_arn\n * Adaptive Routing Notification Enable\n * Not supported in SwitchX, SwitchX-2\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, arn, 0x50, 31, 1);\n\n/* cmd_mbox_config_kvd_linear_size\n * KVD Linear Size\n * Valid for Spectrum only\n * Allowed values are 128*N where N=0 or higher\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, kvd_linear_size, 0x54, 0, 24);\n\n/* cmd_mbox_config_kvd_hash_single_size\n * KVD Hash single-entries size\n * Valid for Spectrum only\n * Allowed values are 128*N where N=0 or higher\n * Must be greater or equal to cap_min_kvd_hash_single_size\n * Must be smaller or equal to cap_kvd_size - kvd_linear_size\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_single_size, 0x58, 0, 24);\n\n/* cmd_mbox_config_kvd_hash_double_size\n * KVD Hash double-entries size (units of single-size entries)\n * Valid for Spectrum only\n * Allowed values are 128*N where N=0 or higher\n * Must be either 0 or greater or equal to cap_min_kvd_hash_double_size\n * Must be smaller or equal to cap_kvd_size - kvd_linear_size\n */\nMLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_double_size, 0x5C, 0, 24);\n\n/* cmd_mbox_config_profile_swid_config_mask\n * Modify Switch Partition Configuration mask. When set, the configu-\n * ration value for the Switch Partition are taken from the mailbox.\n * When clear, the current configuration values are used.\n * Bit 0 - set type\n * Bit 1 - properties\n * Other - reserved\n */\nMLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_mask,\n\t\t 0x60, 24, 8, 0x08, 0x00, false);\n\n/* cmd_mbox_config_profile_swid_config_type\n * Switch Partition type.\n * 0000 - disabled (Switch Partition does not exist)\n * 0001 - InfiniBand\n * 0010 - Ethernet\n * 1000 - router port (SwitchX-2 only)\n * Other - reserved\n */\nMLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_type,\n\t\t 0x60, 20, 4, 0x08, 0x00, false);\n\n/* cmd_mbox_config_profile_swid_config_properties\n * Switch Partition properties.\n */\nMLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_properties,\n\t\t 0x60, 0, 8, 0x08, 0x00, false);\n\n/* ACCESS_REG - Access EMAD Supported Register\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == 0 (N/A)\n * -------------------------------------\n * The ACCESS_REG command supports accessing device registers. This access\n * is mainly used for bootstrapping.\n */\n\nstatic inline int mlxsw_cmd_access_reg(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, char *out_mbox)\n{\n\treturn mlxsw_cmd_exec(mlxsw_core, MLXSW_CMD_OPCODE_ACCESS_REG,\n\t\t\t 0, 0, false, in_mbox, MLXSW_CMD_MBOX_SIZE,\n\t\t\t out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* SW2HW_DQ - Software to Hardware DQ\n * ----------------------------------\n * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)\n * INMmod == DQ number\n * ----------------------------------------------\n * The SW2HW_DQ command transitions a descriptor queue from software to\n * hardware ownership. The command enables posting WQEs and ringing DoorBells\n * on the descriptor queue.\n */\n\nstatic inline int __mlxsw_cmd_sw2hw_dq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 dq_number,\n\t\t\t\t u8 opcode_mod)\n{\n\treturn mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_DQ,\n\t\t\t\t opcode_mod, dq_number,\n\t\t\t\t in_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\nenum {\n\tMLXSW_CMD_OPCODE_MOD_SDQ = 0,\n\tMLXSW_CMD_OPCODE_MOD_RDQ = 1,\n};\n\nstatic inline int mlxsw_cmd_sw2hw_sdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 dq_number)\n{\n\treturn __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_SDQ);\n}\n\nstatic inline int mlxsw_cmd_sw2hw_rdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 dq_number)\n{\n\treturn __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_RDQ);\n}\n\n/* cmd_mbox_sw2hw_dq_cq\n * Number of the CQ that this Descriptor Queue reports completions to.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_dq, cq, 0x00, 24, 8);\n\n/* cmd_mbox_sw2hw_dq_sdq_tclass\n * SDQ: CPU Egress TClass\n * RDQ: Reserved\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_dq, sdq_tclass, 0x00, 16, 6);\n\n/* cmd_mbox_sw2hw_dq_log2_dq_sz\n * Log (base 2) of the Descriptor Queue size in 4KB pages.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_dq, log2_dq_sz, 0x00, 0, 6);\n\n/* cmd_mbox_sw2hw_dq_pa\n * Physical Address.\n */\nMLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_dq, pa, 0x10, 12, 52, 0x08, 0x00, true);\n\n/* HW2SW_DQ - Hardware to Software DQ\n * ----------------------------------\n * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)\n * INMmod == DQ number\n * ----------------------------------------------\n * The HW2SW_DQ command transitions a descriptor queue from hardware to\n * software ownership. Incoming packets on the DQ are silently discarded,\n * SW should not post descriptors on nonoperational DQs.\n */\n\nstatic inline int __mlxsw_cmd_hw2sw_dq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number, u8 opcode_mod)\n{\n\treturn mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_DQ,\n\t\t\t\t opcode_mod, dq_number);\n}\n\nstatic inline int mlxsw_cmd_hw2sw_sdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number)\n{\n\treturn __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_SDQ);\n}\n\nstatic inline int mlxsw_cmd_hw2sw_rdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number)\n{\n\treturn __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_RDQ);\n}\n\n/* 2ERR_DQ - To Error DQ\n * ---------------------\n * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)\n * INMmod == DQ number\n * ----------------------------------------------\n * The 2ERR_DQ command transitions the DQ into the error state from the state\n * in which it has been. While the command is executed, some in-process\n * descriptors may complete. Once the DQ transitions into the error state,\n * if there are posted descriptors on the RDQ/SDQ, the hardware writes\n * a completion with error (flushed) for all descriptors posted in the RDQ/SDQ.\n * When the command is completed successfully, the DQ is already in\n * the error state.\n */\n\nstatic inline int __mlxsw_cmd_2err_dq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number, u8 opcode_mod)\n{\n\treturn mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ,\n\t\t\t\t opcode_mod, dq_number);\n}\n\nstatic inline int mlxsw_cmd_2err_sdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number)\n{\n\treturn __mlxsw_cmd_2err_dq(mlxsw_core, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_SDQ);\n}\n\nstatic inline int mlxsw_cmd_2err_rdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 dq_number)\n{\n\treturn __mlxsw_cmd_2err_dq(mlxsw_core, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_RDQ);\n}\n\n/* QUERY_DQ - Query DQ\n * ---------------------\n * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)\n * INMmod == DQ number\n * ----------------------------------------------\n * The QUERY_DQ command retrieves a snapshot of DQ parameters from the hardware.\n *\n * Note: Output mailbox has the same format as SW2HW_DQ.\n */\n\nstatic inline int __mlxsw_cmd_query_dq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox, u32 dq_number,\n\t\t\t\t u8 opcode_mod)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ,\n\t\t\t\t opcode_mod, dq_number, false,\n\t\t\t\t out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\nstatic inline int mlxsw_cmd_query_sdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox, u32 dq_number)\n{\n\treturn __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_SDQ);\n}\n\nstatic inline int mlxsw_cmd_query_rdq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox, u32 dq_number)\n{\n\treturn __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number,\n\t\t\t\t MLXSW_CMD_OPCODE_MOD_RDQ);\n}\n\n/* SW2HW_CQ - Software to Hardware CQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == CQ number\n * -------------------------------------\n * The SW2HW_CQ command transfers ownership of a CQ context entry from software\n * to hardware. The command takes the CQ context entry from the input mailbox\n * and stores it in the CQC in the ownership of the hardware. The command fails\n * if the requested CQC entry is already in the ownership of the hardware.\n */\n\nstatic inline int mlxsw_cmd_sw2hw_cq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 cq_number)\n{\n\treturn mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_CQ,\n\t\t\t\t 0, cq_number, in_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_sw2hw_cq_cv\n * CQE Version.\n * 0 - CQE Version 0, 1 - CQE Version 1\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, cv, 0x00, 28, 4);\n\n/* cmd_mbox_sw2hw_cq_c_eqn\n * Event Queue this CQ reports completion events to.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, c_eqn, 0x00, 24, 1);\n\n/* cmd_mbox_sw2hw_cq_oi\n * When set, overrun ignore is enabled. When set, updates of\n * CQ consumer counter (poll for completion) or Request completion\n * notifications (Arm CQ) DoorBells should not be rung on that CQ.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, oi, 0x00, 12, 1);\n\n/* cmd_mbox_sw2hw_cq_st\n * Event delivery state machine\n * 0x0 - FIRED\n * 0x1 - ARMED (Request for Notification)\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, st, 0x00, 8, 1);\n\n/* cmd_mbox_sw2hw_cq_log_cq_size\n * Log (base 2) of the CQ size (in entries).\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, log_cq_size, 0x00, 0, 4);\n\n/* cmd_mbox_sw2hw_cq_producer_counter\n * Producer Counter. The counter is incremented for each CQE that is\n * written by the HW to the CQ.\n * Maintained by HW (valid for the QUERY_CQ command only)\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_cq, producer_counter, 0x04, 0, 16);\n\n/* cmd_mbox_sw2hw_cq_pa\n * Physical Address.\n */\nMLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_cq, pa, 0x10, 11, 53, 0x08, 0x00, true);\n\n/* HW2SW_CQ - Hardware to Software CQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == CQ number\n * -------------------------------------\n * The HW2SW_CQ command transfers ownership of a CQ context entry from hardware\n * to software. The CQC entry is invalidated as a result of this command.\n */\n\nstatic inline int mlxsw_cmd_hw2sw_cq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 cq_number)\n{\n\treturn mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_CQ,\n\t\t\t\t 0, cq_number);\n}\n\n/* QUERY_CQ - Query CQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == CQ number\n * -------------------------------------\n * The QUERY_CQ command retrieves a snapshot of the current CQ context entry.\n * The command stores the snapshot in the output mailbox in the software format.\n * Note that the CQ context state and values are not affected by the QUERY_CQ\n * command. The QUERY_CQ command is for debug purposes only.\n *\n * Note: Output mailbox has the same format as SW2HW_CQ.\n */\n\nstatic inline int mlxsw_cmd_query_cq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox, u32 cq_number)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_CQ,\n\t\t\t\t 0, cq_number, false,\n\t\t\t\t out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* SW2HW_EQ - Software to Hardware EQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == EQ number\n * -------------------------------------\n * The SW2HW_EQ command transfers ownership of an EQ context entry from software\n * to hardware. The command takes the EQ context entry from the input mailbox\n * and stores it in the EQC in the ownership of the hardware. The command fails\n * if the requested EQC entry is already in the ownership of the hardware.\n */\n\nstatic inline int mlxsw_cmd_sw2hw_eq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *in_mbox, u32 eq_number)\n{\n\treturn mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_EQ,\n\t\t\t\t 0, eq_number, in_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n/* cmd_mbox_sw2hw_eq_int_msix\n * When set, MSI-X cycles will be generated by this EQ.\n * When cleared, an interrupt will be generated by this EQ.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_eq, int_msix, 0x00, 24, 1);\n\n/* cmd_mbox_sw2hw_eq_int_oi\n * When set, overrun ignore is enabled.\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_eq, oi, 0x00, 12, 1);\n\n/* cmd_mbox_sw2hw_eq_int_st\n * Event delivery state machine\n * 0x0 - FIRED\n * 0x1 - ARMED (Request for Notification)\n * 0x11 - Always ARMED\n * other - reserved\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_eq, st, 0x00, 8, 2);\n\n/* cmd_mbox_sw2hw_eq_int_log_eq_size\n * Log (base 2) of the EQ size (in entries).\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_eq, log_eq_size, 0x00, 0, 4);\n\n/* cmd_mbox_sw2hw_eq_int_producer_counter\n * Producer Counter. The counter is incremented for each EQE that is written\n * by the HW to the EQ.\n * Maintained by HW (valid for the QUERY_EQ command only)\n */\nMLXSW_ITEM32(cmd_mbox, sw2hw_eq, producer_counter, 0x04, 0, 16);\n\n/* cmd_mbox_sw2hw_eq_int_pa\n * Physical Address.\n */\nMLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_eq, pa, 0x10, 11, 53, 0x08, 0x00, true);\n\n/* HW2SW_EQ - Hardware to Software EQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == EQ number\n * -------------------------------------\n */\n\nstatic inline int mlxsw_cmd_hw2sw_eq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t u32 eq_number)\n{\n\treturn mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_EQ,\n\t\t\t\t 0, eq_number);\n}\n\n/* QUERY_EQ - Query EQ\n * ----------------------------------\n * OpMod == 0 (N/A), INMmod == EQ number\n * -------------------------------------\n *\n * Note: Output mailbox has the same format as SW2HW_EQ.\n */\n\nstatic inline int mlxsw_cmd_query_eq(struct mlxsw_core *mlxsw_core,\n\t\t\t\t char *out_mbox, u32 eq_number)\n{\n\treturn mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_EQ,\n\t\t\t\t 0, eq_number, false,\n\t\t\t\t out_mbox, MLXSW_CMD_MBOX_SIZE);\n}\n\n#endif\n"},"repo_name":{"kind":"string","value":"bas-t/linux_media"},"path":{"kind":"string","value":"drivers/net/ethernet/mellanox/mlxsw/cmd.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":40398,"string":"40,398"}}},{"rowIdx":115086539,"cells":{"code":{"kind":"string","value":"/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 and\n * only version 2 as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"msm.h\"\n#include \"msm_csid.h\"\n#include \"msm_csic.h\"\n#include \"msm_csiphy.h\"\n#include \"msm_ispif.h\"\n#include \"msm_sensor.h\"\n\n#ifdef CONFIG_MSM_CAMERA_DEBUG\n#define D(fmt, args...) pr_debug(\"msm_mctl: \" fmt, ##args)\n#else\n#define D(fmt, args...) do {} while (0)\n#endif\n\n#define MSM_V4L2_SWFI_LATENCY 3\n\n/* VFE required buffer number for streaming */\nstatic struct msm_isp_color_fmt msm_isp_formats[] = {\n\t{\n\t.name\t = \"NV12YUV\",\n\t.depth\t = 12,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV12,\n\t.pxlcode\t= V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV21YUV\",\n\t.depth\t = 12,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV21,\n\t.pxlcode\t= V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV12BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV12,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV21BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV21,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV16BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV16,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV61BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV61,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"NV21BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_NV21,\n\t.pxlcode\t= V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"YU12BAYER\",\n\t.depth\t = 8,\n\t.bitsperpxl = 8,\n\t.fourcc\t = V4L2_PIX_FMT_YUV420M,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"RAWBAYER\",\n\t.depth\t = 10,\n\t.bitsperpxl = 10,\n\t.fourcc\t = V4L2_PIX_FMT_SBGGR10,\n\t.pxlcode\t= V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\t{\n\t.name\t = \"RAWBAYER\",\n\t.depth\t = 10,\n\t.bitsperpxl = 10,\n\t.fourcc\t = V4L2_PIX_FMT_SBGGR10,\n\t.pxlcode\t= V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */\n\t.colorspace = V4L2_COLORSPACE_JPEG,\n\t},\n\n};\n\n/*\n * V4l2 subdevice operations\n */\nstatic\tint mctl_subdev_log_status(struct v4l2_subdev *sd)\n{\n\treturn -EINVAL;\n}\n\nstatic long mctl_subdev_ioctl(struct v4l2_subdev *sd,\n\t\t\t\t unsigned int cmd, void *arg)\n{\n\tstruct msm_cam_media_controller *pmctl = NULL;\n\tif (!sd) {\n\t\tpr_err(\"%s: param is NULL\", __func__);\n\t\treturn -EINVAL;\n\t} else\n\t\tpmctl = (struct msm_cam_media_controller *)\n\t\tv4l2_get_subdevdata(sd);\n\n\n\treturn -EINVAL;\n}\n\n\nstatic int mctl_subdev_g_mbus_fmt(struct v4l2_subdev *sd,\n\t\t\t\t\t struct v4l2_mbus_framefmt *mf)\n{\n\treturn -EINVAL;\n}\n\nstatic struct v4l2_subdev_core_ops mctl_subdev_core_ops = {\n\t.log_status = mctl_subdev_log_status,\n\t.ioctl = mctl_subdev_ioctl,\n};\n\nstatic struct v4l2_subdev_video_ops mctl_subdev_video_ops = {\n\t.g_mbus_fmt = mctl_subdev_g_mbus_fmt,\n};\n\nstatic struct v4l2_subdev_ops mctl_subdev_ops = {\n\t.core = &mctl_subdev_core_ops,\n\t.video = &mctl_subdev_video_ops,\n};\n\nstatic int msm_get_sensor_info(struct msm_sync *sync,\n\t\t\t\tvoid __user *arg)\n{\n\tint rc = 0;\n\tstruct msm_camsensor_info info;\n\tstruct msm_camera_sensor_info *sdata;\n\n\tif (copy_from_user(&info,\n\t\t\targ,\n\t\t\tsizeof(struct msm_camsensor_info))) {\n\t\tERR_COPY_FROM_USER();\n\t\treturn -EFAULT;\n\t}\n\n\tsdata = sync->sdata;\n\tD(\"%s: sensor_name %s\\n\", __func__, sdata->sensor_name);\n\n\tmemcpy(&info.name[0], sdata->sensor_name, MAX_SENSOR_NAME);\n\tinfo.flash_enabled = sdata->flash_data->flash_type !=\n\t\t\t\t\tMSM_CAMERA_FLASH_NONE;\n\n\t/* copy back to user space */\n\tif (copy_to_user((void *)arg,\n\t\t\t\t&info,\n\t\t\t\tsizeof(struct msm_camsensor_info))) {\n\t\tERR_COPY_TO_USER();\n\t\trc = -EFAULT;\n\t}\n\n\treturn rc;\n}\n\n/* called by other subdev to notify any changes*/\n\nstatic int msm_mctl_notify(struct msm_cam_media_controller *p_mctl,\n\tunsigned int notification, void *arg)\n{\n\tint rc = -EINVAL;\n\tstruct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);\n\tstruct msm_camera_sensor_info *sinfo =\n\t\t(struct msm_camera_sensor_info *) s_ctrl->sensordata;\n\tstruct msm_camera_device_platform_data *camdev = sinfo->pdata;\n\tuint8_t csid_core = camdev->csid_core;\n\tswitch (notification) {\n\tcase NOTIFY_CID_CHANGE:\n\t\t/* reconfig the ISPIF*/\n\t\tif (p_mctl->ispif_sdev) {\n\t\t\tstruct msm_ispif_params_list ispif_params;\n\t\t\tispif_params.len = 1;\n\t\t\tispif_params.params[0].intftype = PIX0;\n\t\t\tispif_params.params[0].cid_mask = 0x0001;\n\t\t\tispif_params.params[0].csid = csid_core;\n\n\t\t\trc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,\n\t\t\t\tVIDIOC_MSM_ISPIF_CFG, &ispif_params);\n\t\t\tif (rc < 0)\n\t\t\t\treturn rc;\n\t\t}\n\t\tbreak;\n\tcase NOTIFY_ISPIF_STREAM:\n\t\t/* call ISPIF stream on/off */\n\t\trc = v4l2_subdev_call(p_mctl->ispif_sdev, video,\n\t\t\t\ts_stream, (int)arg);\n\t\tif (rc < 0)\n\t\t\treturn rc;\n\n\t\tbreak;\n\tcase NOTIFY_ISP_MSG_EVT:\n\tcase NOTIFY_VFE_MSG_OUT:\n\tcase NOTIFY_VFE_MSG_STATS:\n\tcase NOTIFY_VFE_MSG_COMP_STATS:\n\tcase NOTIFY_VFE_BUF_EVT:\n\tcase NOTIFY_VFE_BUF_FREE_EVT:\n\t\tif (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) {\n\t\t\trc = p_mctl->isp_sdev->isp_notify(\n\t\t\t\tp_mctl->isp_sdev->sd, notification, arg);\n\t\t}\n\t\tbreak;\n\tcase NOTIFY_VPE_MSG_EVT:\n\t\tif (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) {\n\t\t\trc = p_mctl->isp_sdev->isp_notify(\n\t\t\t\tp_mctl->isp_sdev->sd_vpe, notification, arg);\n\t\t}\n\t\tbreak;\n\tcase NOTIFY_PCLK_CHANGE:\n\t\trc = v4l2_subdev_call(p_mctl->isp_sdev->sd, video,\n\t\t\ts_crystal_freq, *(uint32_t *)arg, 0);\n\t\tbreak;\n\tcase NOTIFY_CSIPHY_CFG:\n\t\trc = v4l2_subdev_call(p_mctl->csiphy_sdev,\n\t\t\tcore, ioctl, VIDIOC_MSM_CSIPHY_CFG, arg);\n\t\tbreak;\n\tcase NOTIFY_CSID_CFG:\n\t\trc = v4l2_subdev_call(p_mctl->csid_sdev,\n\t\t\tcore, ioctl, VIDIOC_MSM_CSID_CFG, arg);\n\t\tbreak;\n\tcase NOTIFY_CSIC_CFG:\n\t\trc = v4l2_subdev_call(p_mctl->csic_sdev,\n\t\t\tcore, ioctl, VIDIOC_MSM_CSIC_CFG, arg);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn rc;\n}\n\nstatic int msm_mctl_set_vfe_output_mode(struct msm_cam_media_controller\n\t\t\t\t\t*p_mctl, void __user *arg)\n{\n\tint rc = 0;\n\tif (copy_from_user(&p_mctl->vfe_output_mode,\n\t\t(void __user *)arg, sizeof(p_mctl->vfe_output_mode))) {\n\t\tpr_err(\"%s Copy from user failed \", __func__);\n\t\trc = -EFAULT;\n\t} else {\n\t\tpr_info(\"%s: mctl=0x%p, vfe output mode =0x%x\",\n\t\t __func__, p_mctl, p_mctl->vfe_output_mode);\n\t}\n\treturn rc;\n}\n\n/* called by the server or the config nodes to handle user space\n\tcommands*/\nstatic int msm_mctl_cmd(struct msm_cam_media_controller *p_mctl,\n\t\t\tunsigned int cmd, unsigned long arg)\n{\n\tint rc = -EINVAL;\n\tvoid __user *argp = (void __user *)arg;\n\tif (!p_mctl) {\n\t\tpr_err(\"%s: param is NULL\", __func__);\n\t\treturn -EINVAL;\n\t}\n\tD(\"%s:%d: cmd %d\\n\", __func__, __LINE__, cmd);\n\n\t/* ... call sensor, ISPIF or VEF subdev*/\n\tswitch (cmd) {\n\t\t/* sensor config*/\n\tcase MSM_CAM_IOCTL_GET_SENSOR_INFO:\n\t\t\trc = msm_get_sensor_info(&p_mctl->sync, argp);\n\t\t\tbreak;\n\n\tcase MSM_CAM_IOCTL_SENSOR_IO_CFG:\n\t\tprintk(KERN_DEBUG \"MSM_CAM_IOCTL_SENSOR_IO_CFG\\n\");\n\t\trc = v4l2_subdev_call(p_mctl->sensor_sdev,\n\t\t\tcore, ioctl, VIDIOC_MSM_SENSOR_CFG, argp);\n\t\t\tbreak;\n\n\tcase MSM_CAM_IOCTL_SENSOR_V4l2_S_CTRL: {\n\t\t\tstruct v4l2_control v4l2_ctrl;\n\t\t\tCDBG(\"subdev call\\n\");\n\t\t\tif (copy_from_user(&v4l2_ctrl,\n\t\t\t\t(void *)argp,\n\t\t\t\tsizeof(struct v4l2_control))) {\n\t\t\t\tCDBG(\"copy fail\\n\");\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\tCDBG(\"subdev call ok\\n\");\n\t\t\trc = v4l2_subdev_call(p_mctl->sensor_sdev,\n\t\t\t\tcore, s_ctrl, &v4l2_ctrl);\n\t\t\tbreak;\n\t}\n\n\tcase MSM_CAM_IOCTL_SENSOR_V4l2_QUERY_CTRL: {\n\t\t\tstruct v4l2_queryctrl v4l2_qctrl;\n\t\t\tCDBG(\"query called\\n\");\n\t\t\tif (copy_from_user(&v4l2_qctrl,\n\t\t\t\t(void *)argp,\n\t\t\t\tsizeof(struct v4l2_queryctrl))) {\n\t\t\t\tCDBG(\"copy fail\\n\");\n\t\t\t\trc = -EFAULT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trc = v4l2_subdev_call(p_mctl->sensor_sdev,\n\t\t\t\tcore, queryctrl, &v4l2_qctrl);\n\t\t\tif (rc < 0) {\n\t\t\t\trc = -EFAULT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (copy_to_user((void *)argp,\n\t\t\t\t\t &v4l2_qctrl,\n\t\t\t\t\t sizeof(struct v4l2_queryctrl))) {\n\t\t\t\trc = -EFAULT;\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\tcase MSM_CAM_IOCTL_ACTUATOR_IO_CFG: {\n\t\tstruct msm_actuator_cfg_data act_data;\n\t\tif (p_mctl->sync.actctrl.a_config) {\n\t\t\trc = p_mctl->sync.actctrl.a_config(argp);\n\t\t} else {\n\t\t\trc = copy_from_user(\n\t\t\t\t&act_data,\n\t\t\t\t(void *)argp,\n\t\t\t\tsizeof(struct msm_actuator_cfg_data));\n\t\t\tif (rc != 0) {\n\t\t\t\trc = -EFAULT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tact_data.is_af_supported = 0;\n\t\t\trc = copy_to_user((void *)argp,\n\t\t\t\t\t &act_data,\n\t\t\t\t\t sizeof(struct msm_actuator_cfg_data));\n\t\t\tif (rc != 0) {\n\t\t\t\trc = -EFAULT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase MSM_CAM_IOCTL_GET_KERNEL_SYSTEM_TIME: {\n\t\tstruct timeval timestamp;\n\t\tif (copy_from_user(&timestamp, argp, sizeof(timestamp))) {\n\t\t\tERR_COPY_FROM_USER();\n\t\t\trc = -EFAULT;\n\t\t} else {\n\t\t\tmsm_mctl_gettimeofday(&timestamp);\n\t\t\trc = copy_to_user((void *)argp,\n\t\t\t\t &timestamp, sizeof(timestamp));\n\t\t}\n\t\tbreak;\n\t}\n\n\tcase MSM_CAM_IOCTL_FLASH_CTRL: {\n\t\tstruct flash_ctrl_data flash_info;\n\t\tif (copy_from_user(&flash_info, argp, sizeof(flash_info))) {\n\t\t\tERR_COPY_FROM_USER();\n\t\t\trc = -EFAULT;\n\t\t} else {\n\t\t\trc = msm_flash_ctrl(p_mctl->sync.sdata, &flash_info);\n\t\t}\n\t\tbreak;\n\t}\n\tcase MSM_CAM_IOCTL_PICT_PP:\n\t\trc = msm_mctl_set_pp_key(p_mctl, (void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_PICT_PP_DIVERT_DONE:\n\t\trc = msm_mctl_pp_divert_done(p_mctl, (void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_PICT_PP_DONE:\n\t\trc = msm_mctl_pp_done(p_mctl, (void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_MCTL_POST_PROC:\n\t\trc = msm_mctl_pp_ioctl(p_mctl, cmd, arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_RESERVE_FREE_FRAME:\n\t\trc = msm_mctl_pp_reserve_free_frame(p_mctl,\n\t\t\t(void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_RELEASE_FREE_FRAME:\n\t\trc = msm_mctl_pp_release_free_frame(p_mctl,\n\t\t\t(void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_SET_VFE_OUTPUT_TYPE:\n\t\trc = msm_mctl_set_vfe_output_mode(p_mctl,\n\t\t (void __user *)arg);\n\t\tbreak;\n\tcase MSM_CAM_IOCTL_MCTL_DIVERT_DONE:\n\t\trc = msm_mctl_pp_mctl_divert_done(p_mctl,\n\t\t\t(void __user *)arg);\n\t\tbreak;\n\t\t\t/* ISFIF config*/\n\tdefault:\n\t\t/* ISP config*/\n\t\tD(\"%s:%d: go to default. Calling msm_isp_config\\n\",\n\t\t\t__func__, __LINE__);\n\t\trc = p_mctl->isp_sdev->isp_config(p_mctl, cmd, arg);\n\t\tbreak;\n\t}\n\tD(\"%s: !!! cmd = %d, rc = %d\\n\",\n\t\t__func__, _IOC_NR(cmd), rc);\n\treturn rc;\n}\n\nstatic int msm_mctl_subdev_match_core(struct device *dev, void *data)\n{\n\tint core_index = (int)data;\n\tstruct platform_device *pdev = to_platform_device(dev);\n\n\tif (pdev->id == core_index)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nstatic int msm_mctl_register_subdevs(struct msm_cam_media_controller *p_mctl,\n\tint core_index)\n{\n\tstruct device_driver *driver;\n\tstruct device *dev;\n\tint rc = -ENODEV;\n\n\tstruct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);\n\tstruct msm_camera_sensor_info *sinfo =\n\t\t(struct msm_camera_sensor_info *) s_ctrl->sensordata;\n\tstruct msm_camera_device_platform_data *pdata = sinfo->pdata;\n\n\tif (pdata->is_csiphy) {\n\t\t/* register csiphy subdev */\n\t\tdriver = driver_find(MSM_CSIPHY_DRV_NAME, &platform_bus_type);\n\t\tif (!driver)\n\t\t\tgoto out;\n\n\t\tdev = driver_find_device(driver, NULL, (void *)core_index,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\t\tif (!dev)\n\t\t\tgoto out_put_driver;\n\n\t\tp_mctl->csiphy_sdev = dev_get_drvdata(dev);\n//\t\tput_driver(driver);\n\t}\n\n/*\tif (pdata->is_csic) {\n\t\t/ * register csic subdev * /\n\t\tdriver = driver_find(MSM_CSIC_DRV_NAME, &platform_bus_type);\n\t\tif (!driver)\n\t\t\tgoto out;\n\n\t\tdev = driver_find_device(driver, NULL, (void *)core_index,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\t\tif (!dev)\n\t\t\tgoto out_put_driver;\n\n\t\tp_mctl->csic_sdev = dev_get_drvdata(dev);\n//\t\tput_driver(driver);\n\t}\n*/\n\n\tif (pdata->is_csid) {\n\t\t/* register csid subdev */\n\t\tdriver = driver_find(MSM_CSID_DRV_NAME, &platform_bus_type);\n\t\tif (!driver)\n\t\t\tgoto out;\n\n\t\tdev = driver_find_device(driver, NULL, (void *)core_index,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\t\tif (!dev)\n\t\t\tgoto out_put_driver;\n\n\t\tp_mctl->csid_sdev = dev_get_drvdata(dev);\n//\t\tput_driver(driver);\n\t}\n\n\tif (pdata->is_ispif) {\n\t\t/* register ispif subdev */\n\t\tdriver = driver_find(MSM_ISPIF_DRV_NAME, &platform_bus_type);\n\t\tif (!driver)\n\t\t\tgoto out;\n\n\t\tdev = driver_find_device(driver, NULL, 0,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\t\tif (!dev)\n\t\t\tgoto out_put_driver;\n\n\t\tp_mctl->ispif_sdev = dev_get_drvdata(dev);\n//\t\tput_driver(driver);\n\t}\n\n\t/* register vfe subdev */\n\tdriver = driver_find(MSM_VFE_DRV_NAME, &platform_bus_type);\n\tif (!driver)\n\t\tgoto out;\n\n\tdev = driver_find_device(driver, NULL, 0,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\tif (!dev)\n\t\tgoto out_put_driver;\n\n\tp_mctl->isp_sdev->sd = dev_get_drvdata(dev);\n//\tput_driver(driver);\n\n\tif (pdata->is_vpe) {\n\t\t/* register vfe subdev */\n\t\tdriver = driver_find(MSM_VPE_DRV_NAME, &platform_bus_type);\n\t\tif (!driver)\n\t\t\tgoto out;\n\n\t\tdev = driver_find_device(driver, NULL, 0,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\t\tif (!dev)\n\t\t\tgoto out_put_driver;\n\n\t\tp_mctl->isp_sdev->sd_vpe = dev_get_drvdata(dev);\n//\t\tput_driver(driver);\n\t}\n\n\trc = 0;\n\n\n\t/* register gemini subdev */\n\tdriver = driver_find(MSM_GEMINI_DRV_NAME, &platform_bus_type);\n\tif (!driver) {\n\t\tpr_err(\"%s:%d:Gemini: Failure: goto out\\n\",\n\t\t\t__func__, __LINE__);\n\t\tgoto out;\n\t}\n\tpr_debug(\"%s:%d:Gemini: driver_find_device Gemini driver 0x%x\\n\",\n\t\t__func__, __LINE__, (uint32_t)driver);\n\tdev = driver_find_device(driver, NULL, NULL,\n\t\t\t\tmsm_mctl_subdev_match_core);\n\tif (!dev) {\n\t\tpr_err(\"%s:%d:Gemini: Failure goto out_put_driver\\n\",\n\t\t\t__func__, __LINE__);\n\t\tgoto out_put_driver;\n\t}\n\tp_mctl->gemini_sdev = dev_get_drvdata(dev);\n\tpr_debug(\"%s:%d:Gemini: After dev_get_drvdata gemini_sdev=0x%x\\n\",\n\t\t__func__, __LINE__, (uint32_t)p_mctl->gemini_sdev);\n\n\tif (p_mctl->gemini_sdev == NULL) {\n\t\tpr_err(\"%s:%d:Gemini: Failure gemini_sdev is null\\n\",\n\t\t\t__func__, __LINE__);\n\t\tgoto out_put_driver;\n\t}\n\trc = 0;\n\treturn rc;\nout_put_driver:\n\t//put_driver(driver);\nout:\n\treturn rc;\n}\n\nstatic int msm_mctl_open(struct msm_cam_media_controller *p_mctl,\n\t\t\t\t const char *const apps_id)\n{\n\tint rc = 0;\n\tstruct msm_sync *sync = NULL;\n\tstruct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);\n\tstruct msm_camera_sensor_info *sinfo =\n\t\t(struct msm_camera_sensor_info *) s_ctrl->sensordata;\n\tstruct msm_camera_device_platform_data *camdev = sinfo->pdata;\n\tuint8_t csid_core;\n\tD(\"%s\\n\", __func__);\n\tif (!p_mctl) {\n\t\tpr_err(\"%s: param is NULL\", __func__);\n\t\treturn -EINVAL;\n\t}\n\n\t/* msm_sync_init() muct be called before*/\n\tsync = &(p_mctl->sync);\n\n\tmutex_lock(&sync->lock);\n\t/* open sub devices - once only*/\n\tif (!sync->opencnt) {\n\t\tuint32_t csid_version;\n\t\twake_lock(&sync->wake_lock);\n\n\t\tcsid_core = camdev->csid_core;\n\t\trc = msm_mctl_register_subdevs(p_mctl, csid_core);\n\t\tif (rc < 0) {\n\t\t\tpr_err(\"%s: msm_mctl_register_subdevs failed:%d\\n\",\n\t\t\t\t__func__, rc);\n\t\t\tgoto register_sdev_failed;\n\t\t}\n\n\t\t/* then sensor - move sub dev later*/\n\t\trc = v4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 1);\n\n\t\tif (rc < 0) {\n\t\t\tpr_err(\"%s: isp init failed: %d\\n\", __func__, rc);\n\t\t\tgoto msm_open_done;\n\t\t}\n\t\tif (sync->actctrl.a_power_up)\n\t\t\trc = sync->actctrl.a_power_up(\n\t\t\t\tsync->sdata->actuator_info);\n\n\t\tif (rc < 0) {\n\t\t\tpr_err(\"%s: act power failed:%d\\n\", __func__, rc);\n\t\t\tgoto msm_open_done;\n\t\t}\n\n\t\tif (camdev->is_csiphy) {\n\t\t\trc = v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,\n\t\t\t\tVIDIOC_MSM_CSIPHY_INIT, NULL);\n\t\t\tif (rc < 0) {\n\t\t\t\tpr_err(\"%s: csiphy initialization failed %d\\n\",\n\t\t\t\t\t__func__, rc);\n\t\t\t\tgoto csiphy_init_failed;\n\t\t\t}\n\t\t}\n\n\t\tif (camdev->is_csid) {\n\t\t\trc = v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,\n\t\t\t\tVIDIOC_MSM_CSID_INIT, &csid_version);\n\t\t\tif (rc < 0) {\n\t\t\t\tpr_err(\"%s: csid initialization failed %d\\n\",\n\t\t\t\t\t__func__, rc);\n\t\t\t\tgoto csid_init_failed;\n\t\t\t}\n\t\t}\n/*\t\tif (camdev->is_csic) {\n\t\t\trc = v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,\n\t\t\t\tVIDIOC_MSM_CSIC_INIT, &csid_version);\n\t\t\tif (rc < 0) {\n\t\t\t\tpr_err(\"%s: csic initialization failed %d\\n\",\n\t\t\t\t\t__func__, rc);\n\t\t\t\tgoto csic_init_failed;\n\t\t\t}\n\t\t}\n*/\n\n\t\t/* ISP first*/\n\t\tif (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_open)\n\t\t\trc = p_mctl->isp_sdev->isp_open(\n\t\t\t\tp_mctl->isp_sdev->sd,\n\t\t\t\tp_mctl->isp_sdev->sd_vpe,\n\t\t\t\tp_mctl->gemini_sdev,\n\t\t\t\tsync);\n\t\tif (rc < 0) {\n\t\t\tpr_err(\"%s: isp init failed: %d\\n\", __func__, rc);\n\t\t\tgoto isp_open_failed;\n\t\t}\n\n\t\tif (camdev->is_ispif) {\n\t\t\trc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,\n\t\t\t\tVIDIOC_MSM_ISPIF_INIT, &csid_version);\n\t\t\tif (rc < 0) {\n\t\t\t\tpr_err(\"%s: ispif initialization failed %d\\n\",\n\t\t\t\t\t__func__, rc);\n\t\t\t\tgoto ispif_init_failed;\n\t\t\t}\n\t\t}\n\n\t\tif (camdev->is_ispif) {\n\t\t\tpm_qos_add_request(p_mctl->pm_qos_req_list,\n\t\t\t\t\tPM_QOS_CPU_DMA_LATENCY,\n\t\t\t\t\tPM_QOS_DEFAULT_VALUE);\n\t\t\tpm_qos_update_request(p_mctl->pm_qos_req_list,\n\t\t\t\t\tMSM_V4L2_SWFI_LATENCY);\n\t\t}\n\t\tsync->apps_id = apps_id;\n\t\tsync->opencnt++;\n\t} else {\n\t\tD(\"%s: camera is already open\", __func__);\n\t}\n\n\tmutex_unlock(&sync->lock);\n\treturn rc;\n\nispif_init_failed:\n\tif (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release)\n\t\tp_mctl->isp_sdev->isp_release(&p_mctl->sync,\n\t\t\t\tp_mctl->gemini_sdev);\nisp_open_failed:\n/*\tif (camdev->is_csic)\n\t\tif (v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSIC_RELEASE, NULL) < 0)\n\t\t\tpr_err(\"%s: csic release failed %d\\n\", __func__, rc);\ncsic_init_failed:*/\n\tif (camdev->is_csid)\n\t\tif (v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSID_RELEASE, NULL) < 0)\n\t\t\tpr_err(\"%s: csid release failed %d\\n\", __func__, rc);\ncsid_init_failed:\n\tif (camdev->is_csiphy)\n\t\tif (v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSIPHY_RELEASE, NULL) < 0)\n\t\t\tpr_err(\"%s: csiphy release failed %d\\n\", __func__, rc);\ncsiphy_init_failed:\n\tif (p_mctl->sync.actctrl.a_power_down)\n\t\tp_mctl->sync.actctrl.a_power_down(\n\t\t\tp_mctl->sync.sdata->actuator_info);\nregister_sdev_failed:\nmsm_open_done:\n\twake_unlock(&p_mctl->sync.wake_lock);\n\tmutex_unlock(&sync->lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_release(struct msm_cam_media_controller *p_mctl)\n{\n\tint rc = 0;\n\tstruct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);\n\tstruct msm_camera_sensor_info *sinfo =\n\t\t(struct msm_camera_sensor_info *) s_ctrl->sensordata;\n\tstruct msm_camera_device_platform_data *camdev = sinfo->pdata;\n\n\tv4l2_subdev_call(p_mctl->sensor_sdev, core, ioctl,\n\t\tVIDIOC_MSM_SENSOR_RELEASE, NULL);\n\n\tif (camdev->is_ispif) {\n\t\tv4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_ISPIF_RELEASE, NULL);\n\t}\n\n/*\tif (camdev->is_csic) {\n\t\tv4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSIC_RELEASE, NULL);\n\t}\n*/\n\n\tif (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release)\n\t\tp_mctl->isp_sdev->isp_release(&p_mctl->sync,\n\t\t\t\tp_mctl->gemini_sdev);\n\n\tif (camdev->is_csid) {\n\t\tv4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSID_RELEASE, NULL);\n\t}\n\n\tif (camdev->is_csiphy) {\n\t\tv4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,\n\t\t\tVIDIOC_MSM_CSIPHY_RELEASE, NULL);\n\t}\n\n\tif (camdev->is_ispif) {\n\t\tpm_qos_update_request(p_mctl->pm_qos_req_list,\n\t\t\t\tPM_QOS_DEFAULT_VALUE);\n\t\tpm_qos_remove_request(p_mctl->pm_qos_req_list);\n\t}\n\tif (p_mctl->sync.actctrl.a_power_down)\n\t\tp_mctl->sync.actctrl.a_power_down(\n\t\t\tp_mctl->sync.sdata->actuator_info);\n\n\tv4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 0);\n\n\twake_unlock(&p_mctl->sync.wake_lock);\n\treturn rc;\n}\n\nint msm_mctl_init_user_formats(struct msm_cam_v4l2_device *pcam)\n{\n\tstruct v4l2_subdev *sd = pcam->mctl.sensor_sdev;\n\tenum v4l2_mbus_pixelcode pxlcode;\n\tint numfmt_sensor = 0;\n\tint numfmt = 0;\n\tint rc = 0;\n\tint i, j;\n\n\tD(\"%s\\n\", __func__);\n\twhile (!v4l2_subdev_call(sd, video, enum_mbus_fmt, numfmt_sensor,\n\t\t\t\t\t\t\t\t&pxlcode))\n\t\tnumfmt_sensor++;\n\n\tD(\"%s, numfmt_sensor = %d\\n\", __func__, numfmt_sensor);\n\tif (!numfmt_sensor)\n\t\treturn -ENXIO;\n\n\tpcam->usr_fmts = vmalloc(numfmt_sensor * ARRAY_SIZE(msm_isp_formats) *\n\t\t\t\tsizeof(struct msm_isp_color_fmt));\n\tif (!pcam->usr_fmts)\n\t\treturn -ENOMEM;\n\n\t/* from sensor to ISP.. fill the data structure */\n\tfor (i = 0; i < numfmt_sensor; i++) {\n\t\trc = v4l2_subdev_call(sd, video, enum_mbus_fmt, i, &pxlcode);\n\t\tD(\"rc is %d\\n\", rc);\n\t\tif (rc < 0) {\n\t\t\tvfree(pcam->usr_fmts);\n\t\t\treturn rc;\n\t\t}\n\n\t\tfor (j = 0; j < ARRAY_SIZE(msm_isp_formats); j++) {\n\t\t\t/* find the corresponding format */\n\t\t\tif (pxlcode == msm_isp_formats[j].pxlcode) {\n\t\t\t\tpcam->usr_fmts[numfmt] = msm_isp_formats[j];\n\t\t\t\tD(\"pcam->usr_fmts=0x%x\\n\", (u32)pcam->usr_fmts);\n\t\t\t\tD(\"format pxlcode 0x%x (0x%x) found\\n\",\n\t\t\t\t\t pcam->usr_fmts[numfmt].pxlcode,\n\t\t\t\t\t pcam->usr_fmts[numfmt].fourcc);\n\t\t\t\tnumfmt++;\n\t\t\t}\n\t\t}\n\t}\n\n\tpcam->num_fmts = numfmt;\n\n\tif (numfmt == 0) {\n\t\tpr_err(\"%s: No supported formats.\\n\", __func__);\n\t\tvfree(pcam->usr_fmts);\n\t\treturn -EINVAL;\n\t}\n\n\tD(\"Found %d supported formats.\\n\", pcam->num_fmts);\n\t/* set the default pxlcode, in any case, it will be set through\n\t * setfmt */\n\treturn 0;\n}\n\n/* this function plug in the implementation of a v4l2_subdev */\nint msm_mctl_init_module(struct msm_cam_v4l2_device *pcam)\n{\n\tstruct msm_cam_media_controller *pmctl = NULL;\n\tD(\"%s\\n\", __func__);\n\tif (!pcam) {\n\t\tpr_err(\"%s: param is NULL\", __func__);\n\t\treturn -EINVAL;\n\t} else\n\t\tpmctl = &pcam->mctl;\n\n\tpmctl->sync.opencnt = 0;\n\n\t/* init module operations*/\n\tpmctl->mctl_open = msm_mctl_open;\n\tpmctl->mctl_cmd = msm_mctl_cmd;\n\tpmctl->mctl_notify = msm_mctl_notify;\n\tpmctl->mctl_release = msm_mctl_release;\n\t/* init mctl buf */\n\tmsm_mctl_buf_init(pcam);\n\tmemset(&pmctl->pp_info, 0, sizeof(pmctl->pp_info));\n\tpmctl->vfe_output_mode = 0;\n\tspin_lock_init(&pmctl->pp_info.lock);\n\t/* init sub device*/\n\tv4l2_subdev_init(&(pmctl->mctl_sdev), &mctl_subdev_ops);\n\tv4l2_set_subdevdata(&(pmctl->mctl_sdev), pmctl);\n\n\treturn 0;\n}\n\n\n/* mctl node v4l2_file_operations */\nstatic int msm_mctl_dev_open(struct file *f)\n{\n\tint rc = -EINVAL, i;\n\t/* get the video device */\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpr_err(\"%s : E \", __func__);\n\n\tif (!pcam) {\n\t\tpr_err(\"%s NULL pointer passed in!\\n\", __func__);\n\t\treturn rc;\n\t}\n\n\tmutex_lock(&pcam->mctl_node.dev_lock);\n\tfor (i = 0; i < MSM_DEV_INST_MAX; i++) {\n\t\tif (pcam->mctl_node.dev_inst[i] == NULL)\n\t\t\tbreak;\n\t}\n\t/* if no instance is available, return error */\n\tif (i == MSM_DEV_INST_MAX) {\n\t\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\t\treturn rc;\n\t}\n\tpcam_inst = kzalloc(sizeof(struct msm_cam_v4l2_dev_inst), GFP_KERNEL);\n\tif (!pcam_inst) {\n\t\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\t\treturn rc;\n\t}\n\n\tpcam_inst->sensor_pxlcode = pcam->usr_fmts[0].pxlcode;\n\tpcam_inst->my_index = i;\n\tpcam_inst->pcam = pcam;\n\tpcam->mctl_node.dev_inst[i] = pcam_inst;\n\n\tD(\"%s pcam_inst %p my_index = %d\\n\", __func__,\n\t\tpcam_inst, pcam_inst->my_index);\n\tD(\"%s for %s\\n\", __func__, pcam->pdev->name);\n\trc = msm_setup_v4l2_event_queue(&pcam_inst->eventHandle,\n\t\t\t\t\tpcam->mctl_node.pvdev);\n\tif (rc < 0) {\n\t\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\t\treturn rc;\n\t}\n\tpcam_inst->vbqueue_initialized = 0;\n\tkref_get(&pcam->mctl.refcount);\n\tf->private_data = &pcam_inst->eventHandle;\n\n\tD(\"f->private_data = 0x%x, pcam = 0x%x\\n\",\n\t\t(u32)f->private_data, (u32)pcam_inst);\n\n\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\tD(\"%s : X \", __func__);\n\treturn rc;\n}\n\nstatic unsigned int msm_mctl_dev_poll(struct file *f,\n\t\t\t\tstruct poll_table_struct *wait)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_device *pcam;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\tpcam = pcam_inst->pcam;\n\n\tD(\"%s : E pcam_inst = %p\", __func__, pcam_inst);\n\tif (!pcam) {\n\t\tpr_err(\"%s NULL pointer of camera device!\\n\", __func__);\n\t\treturn -EINVAL;\n\t}\n\n\tpoll_wait(f, &(pcam_inst->eventHandle.wait), wait);\n\tif (v4l2_event_pending(&pcam_inst->eventHandle)) {\n\t\trc |= POLLPRI;\n\t\tD(\"%s Event available on mctl node \", __func__);\n\t}\n\n\tD(\"%s poll on vb2\\n\", __func__);\n\tif (!pcam_inst->vid_bufq.streaming) {\n\t\tD(\"%s vid_bufq.streaming is off, inst=0x%x\\n\",\n\t\t\t\t__func__, (u32)pcam_inst);\n\t\treturn rc;\n\t}\n\trc |= vb2_poll(&pcam_inst->vid_bufq, f, wait);\n\n\tD(\"%s : X \", __func__);\n\treturn rc;\n}\n\nstatic int msm_mctl_dev_close(struct file *f)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_device *pcam;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\tpcam = pcam_inst->pcam;\n\n\tpr_err(\"%s : E \", __func__);\n\tif (!pcam) {\n\t\tpr_err(\"%s NULL pointer of camera device!\\n\", __func__);\n\t\treturn -EINVAL;\n\t}\n\n\tmutex_lock(&pcam->mctl_node.dev_lock);\n\tpcam_inst->streamon = 0;\n\tpcam->mctl_node.dev_inst_map[pcam_inst->image_mode] = NULL;\n\tif (pcam_inst->vbqueue_initialized)\n\t\tvb2_queue_release(&pcam_inst->vid_bufq);\n\tD(\"%s Closing down instance %p \", __func__, pcam_inst);\n\tpcam->mctl_node.dev_inst[pcam_inst->my_index] = NULL;\n\tv4l2_fh_del(&pcam_inst->eventHandle);\n\tv4l2_fh_exit(&pcam_inst->eventHandle);\n\n\tkfree(pcam_inst);\n\tkref_put(&pcam->mctl.refcount, msm_release_ion_client);\n\tf->private_data = NULL;\n\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\tD(\"%s : X \", __func__);\n\treturn rc;\n}\n\nstatic struct v4l2_file_operations g_msm_mctl_fops = {\n\t.owner = THIS_MODULE,\n\t.open\t= msm_mctl_dev_open,\n\t.poll\t= msm_mctl_dev_poll,\n\t.release = msm_mctl_dev_close,\n\t.unlocked_ioctl = video_ioctl2,\n};\n\n/*\n *\n * implementation of mctl node v4l2_ioctl_ops\n *\n */\nstatic int msm_mctl_v4l2_querycap(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_capability *pcaps)\n{\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\tstrlcpy(pcaps->driver, pcam->pdev->name, sizeof(pcaps->driver));\n\tpcaps->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;\n\treturn 0;\n}\n\nstatic int msm_mctl_v4l2_queryctrl(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_queryctrl *pqctrl)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_g_ctrl(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_control *c)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_s_ctrl(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_control *ctrl)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s\\n\", __func__);\n\n\tWARN_ON(pctx != f->private_data);\n\tmutex_lock(&pcam->mctl_node.dev_lock);\n\tif (ctrl->id == MSM_V4L2_PID_PP_PLANE_INFO) {\n\t\tif (copy_from_user(&pcam_inst->plane_info,\n\t\t\t\t\t(void *)ctrl->value,\n\t\t\t\t\tsizeof(struct img_plane_info))) {\n\t\t\tpr_err(\"%s inst %p Copying plane_info failed \",\n\t\t\t\t\t__func__, pcam_inst);\n\t\t\trc = -EFAULT;\n\t\t}\n\t\tD(\"%s inst %p got plane info: num_planes = %d,\"\n\t\t\t\t\"plane size = %ld %ld \", __func__, pcam_inst,\n\t\t\t\tpcam_inst->plane_info.num_planes,\n\t\t\t\tpcam_inst->plane_info.plane[0].size,\n\t\t\t\tpcam_inst->plane_info.plane[1].size);\n\t} else\n\t\tpr_err(\"%s Unsupported S_CTRL Value \", __func__);\n\n\tmutex_unlock(&pcam->mctl_node.dev_lock);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_reqbufs(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_requestbuffers *pb)\n{\n\tint rc = 0, i, j;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\trc = vb2_reqbufs(&pcam_inst->vid_bufq, pb);\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tif (rc < 0) {\n\t\tpr_err(\"%s reqbufs failed %d \", __func__, rc);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\treturn rc;\n\t}\n\tif (!pb->count) {\n\t\t/* Deallocation. free buf_offset array */\n\t\tD(\"%s Inst %p freeing buffer offsets array\",\n\t\t\t__func__, pcam_inst);\n\t\tfor (j = 0 ; j < pcam_inst->buf_count ; j++)\n\t\t\tkfree(pcam_inst->buf_offset[j]);\n\t\tkfree(pcam_inst->buf_offset);\n\t\tpcam_inst->buf_offset = NULL;\n\t\t/* If the userspace has deallocated all the\n\t\t * buffers, then release the vb2 queue */\n\t\tif (pcam_inst->vbqueue_initialized) {\n\t\t\tvb2_queue_release(&pcam_inst->vid_bufq);\n\t\t\tpcam_inst->vbqueue_initialized = 0;\n\t\t}\n\t} else {\n\t\tD(\"%s Inst %p Allocating buf_offset array\",\n\t\t\t__func__, pcam_inst);\n\t\t/* Allocation. allocate buf_offset array */\n\t\tpcam_inst->buf_offset = (struct msm_cam_buf_offset **)\n\t\t\tkzalloc(pb->count * sizeof(struct msm_cam_buf_offset *),\n\t\t\t\t\t\t\tGFP_KERNEL);\n\t\tif (!pcam_inst->buf_offset) {\n\t\t\tpr_err(\"%s out of memory \", __func__);\n\t\t\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tfor (i = 0; i < pb->count; i++) {\n\t\t\tpcam_inst->buf_offset[i] =\n\t\t\t\tkzalloc(sizeof(struct msm_cam_buf_offset) *\n\t\t\t\tpcam_inst->plane_info.num_planes, GFP_KERNEL);\n\t\t\tif (!pcam_inst->buf_offset[i]) {\n\t\t\t\tpr_err(\"%s out of memory \", __func__);\n\t\t\t\tfor (j = i-1 ; j >= 0; j--)\n\t\t\t\t\tkfree(pcam_inst->buf_offset[j]);\n\t\t\t\tkfree(pcam_inst->buf_offset);\n\t\t\t\tpcam_inst->buf_offset = NULL;\n\t\t\t\tmutex_unlock(\n\t\t\t\t\t&pcam_inst->pcam->mctl_node.dev_lock);\n\t\t\t\treturn -ENOMEM;\n\t\t\t}\n\t\t}\n\t}\n\tpcam_inst->buf_count = pb->count;\n\tD(\"%s inst %p, buf count %d \", __func__,\n\t\tpcam_inst, pcam_inst->buf_count);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_querybuf(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_buffer *pb)\n{\n\t/* get the video device */\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\treturn vb2_querybuf(&pcam_inst->vid_bufq, pb);\n}\n\nstatic int msm_mctl_v4l2_qbuf(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_buffer *pb)\n{\n\tint rc = 0, i = 0;\n\t/* get the camera device */\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s Inst = %p\\n\", __func__, pcam_inst);\n\tWARN_ON(pctx != f->private_data);\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tif (!pcam_inst->buf_offset) {\n\t\tpr_err(\"%s Buffer is already released. Returning. \", __func__);\n\t\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\treturn -EINVAL;\n\t}\n\n\tif (pb->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {\n\t\t/* Reject the buffer if planes array was not allocated */\n\t\tif (pb->m.planes == NULL) {\n\t\t\tpr_err(\"%s Planes array is null \", __func__);\n\t\t\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tfor (i = 0; i < pcam_inst->plane_info.num_planes; i++) {\n\t\t\tD(\"%s stored offsets for plane %d as\"\n\t\t\t\t\"addr offset %d, data offset %d\",\n\t\t\t\t__func__, i, pb->m.planes[i].reserved[0],\n\t\t\t\tpb->m.planes[i].data_offset);\n\t\t\tpcam_inst->buf_offset[pb->index][i].data_offset =\n\t\t\t\tpb->m.planes[i].data_offset;\n\t\t\tpcam_inst->buf_offset[pb->index][i].addr_offset =\n\t\t\t\tpb->m.planes[i].reserved[0];\n\t\t}\n\t} else {\n\t\tD(\"%s stored reserved info %d\", __func__, pb->reserved);\n\t\tpcam_inst->buf_offset[pb->index][0].addr_offset = pb->reserved;\n\t}\n\n\trc = vb2_qbuf(&pcam_inst->vid_bufq, pb);\n\tD(\"%s, videobuf_qbuf returns %d\\n\", __func__, rc);\n\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_dqbuf(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_buffer *pb)\n{\n\tint rc = 0;\n\t/* get the camera device */\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\trc = vb2_dqbuf(&pcam_inst->vid_bufq, pb, f->f_flags & O_NONBLOCK);\n\tD(\"%s, videobuf_dqbuf returns %d\\n\", __func__, rc);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_streamon(struct file *f, void *pctx,\n\t\t\t\t\tenum v4l2_buf_type buf_type)\n{\n\tint rc = 0;\n\t/* get the camera device */\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s Inst %p\\n\", __func__, pcam_inst);\n\tWARN_ON(pctx != f->private_data);\n\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tif ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&\n\t\t(buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) {\n\t\tpr_err(\"%s Invalid buffer type \", __func__);\n\t\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\treturn -EINVAL;\n\t}\n\n\tD(\"%s Calling videobuf_streamon\", __func__);\n\t/* if HW streaming on is successful, start buffer streaming */\n\trc = vb2_streamon(&pcam_inst->vid_bufq, buf_type);\n\tD(\"%s, videobuf_streamon returns %d\\n\", __func__, rc);\n\t/* turn HW (VFE/sensor) streaming */\n\tpcam_inst->streamon = 1;\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tD(\"%s rc = %d\\n\", __func__, rc);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_streamoff(struct file *f, void *pctx,\n\t\t\t\t\tenum v4l2_buf_type buf_type)\n{\n\tint rc = 0;\n\t/* get the camera device */\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s Inst %p\\n\", __func__, pcam_inst);\n\tWARN_ON(pctx != f->private_data);\n\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tif ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&\n\t\t(buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) {\n\t\tpr_err(\"%s Invalid buffer type \", __func__);\n\t\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\t\treturn -EINVAL;\n\t}\n\n\t/* first turn of HW (VFE/sensor) streaming so that buffers are\n\t\tnot in use when we free the buffers */\n\tpcam_inst->streamon = 0;\n\t/* stop buffer streaming */\n\trc = vb2_streamoff(&pcam_inst->vid_bufq, buf_type);\n\tD(\"%s, videobuf_streamoff returns %d\\n\", __func__, rc);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_enum_fmt_cap(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_fmtdesc *pfmtdesc)\n{\n\t/* get the video device */\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\tconst struct msm_isp_color_fmt *isp_fmt;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\tif ((pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&\n\t\t(pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE))\n\t\treturn -EINVAL;\n\n\tif (pfmtdesc->index >= pcam->num_fmts)\n\t\treturn -EINVAL;\n\n\tisp_fmt = &pcam->usr_fmts[pfmtdesc->index];\n\n\tif (isp_fmt->name)\n\t\tstrlcpy(pfmtdesc->description, isp_fmt->name,\n\t\t\t\t\t\tsizeof(pfmtdesc->description));\n\n\tpfmtdesc->pixelformat = isp_fmt->fourcc;\n\n\tD(\"%s: [%d] 0x%x, %s\\n\", __func__, pfmtdesc->index,\n\t\tisp_fmt->fourcc, isp_fmt->name);\n\treturn 0;\n}\n\nstatic int msm_mctl_v4l2_g_fmt_cap(struct file *f,\n\t\tvoid *pctx, struct v4l2_format *pfmt)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\tif (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)\n\t\treturn -EINVAL;\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_g_fmt_cap_mplane(struct file *f,\n\t\tvoid *pctx, struct v4l2_format *pfmt)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\tif (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)\n\t\treturn -EINVAL;\n\n\treturn rc;\n}\n\n/* This function will readjust the format parameters based in HW\n capabilities. Called by s_fmt_cap\n*/\nstatic int msm_mctl_v4l2_try_fmt_cap(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_format *pfmt)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_try_fmt_cap_mplane(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_format *pfmt)\n{\n\tint rc = 0;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\n/* This function will reconfig the v4l2 driver and HW device, it should be\n called after the streaming is stopped.\n*/\nstatic int msm_mctl_v4l2_s_fmt_cap(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_format *pfmt)\n{\n\tint rc = 0;\n\t/* get the video device */\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s\\n\", __func__);\n\tD(\"%s, inst=0x%x,idx=%d,priv = 0x%p\\n\",\n\t\t__func__, (u32)pcam_inst, pcam_inst->my_index,\n\t\t(void *)pfmt->fmt.pix.priv);\n\tWARN_ON(pctx != f->private_data);\n\n\tif (!pcam_inst->vbqueue_initialized) {\n\t\tpcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq,\n\t\t\t\t\tV4L2_BUF_TYPE_VIDEO_CAPTURE);\n\t\tpcam_inst->vbqueue_initialized = 1;\n\t}\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_s_fmt_cap_mplane(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_format *pfmt)\n{\n\tint rc = 0, i;\n\tstruct msm_cam_v4l2_device *pcam = video_drvdata(f);\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s Inst %p vbqueue %d\\n\", __func__,\n\t\tpcam_inst, pcam_inst->vbqueue_initialized);\n\tWARN_ON(pctx != f->private_data);\n\n\tif (!pcam_inst->vbqueue_initialized) {\n\t\tpcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq,\n\t\t\t\t\tV4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);\n\t\tpcam_inst->vbqueue_initialized = 1;\n\t}\n\tfor (i = 0; i < pcam->num_fmts; i++)\n\t\tif (pcam->usr_fmts[i].fourcc == pfmt->fmt.pix_mp.pixelformat)\n\t\t\tbreak;\n\tif (i == pcam->num_fmts) {\n\t\tpr_err(\"%s: User requested pixelformat %x not supported\\n\",\n\t\t\t__func__, pfmt->fmt.pix_mp.pixelformat);\n\t\treturn -EINVAL;\n\t}\n\tpcam_inst->vid_fmt = *pfmt;\n\tpcam_inst->sensor_pxlcode =\n\t\tpcam->usr_fmts[i].pxlcode;\n\tD(\"%s: inst=%p, width=%d, heigth=%d\\n\",\n\t\t__func__, pcam_inst,\n\t\tpcam_inst->vid_fmt.fmt.pix_mp.width,\n\t\tpcam_inst->vid_fmt.fmt.pix_mp.height);\n\treturn rc;\n}\nstatic int msm_mctl_v4l2_g_jpegcomp(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_jpegcompression *pcomp)\n{\n\tint rc = -EINVAL;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_s_jpegcomp(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_jpegcompression *pcomp)\n{\n\tint rc = -EINVAL;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\n\nstatic int msm_mctl_v4l2_g_crop(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_crop *crop)\n{\n\tint rc = -EINVAL;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_s_crop(struct file *f, void *pctx,\n\t\t\t\t\tstruct v4l2_crop *a)\n{\n\tint rc = -EINVAL;\n\n\tD(\"%s\\n\", __func__);\n\tWARN_ON(pctx != f->private_data);\n\n\treturn rc;\n}\n\n/* Stream type-dependent parameter ioctls */\nstatic int msm_mctl_v4l2_g_parm(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_streamparm *a)\n{\n\tint rc = -EINVAL;\n\treturn rc;\n}\n\nstatic int msm_mctl_vidbuf_get_path(u32 extendedmode)\n{\n\tswitch (extendedmode) {\n\tcase MSM_V4L2_EXT_CAPTURE_MODE_THUMBNAIL:\n\t\treturn OUTPUT_TYPE_T;\n\tcase MSM_V4L2_EXT_CAPTURE_MODE_MAIN:\n\t\treturn OUTPUT_TYPE_S;\n\tcase MSM_V4L2_EXT_CAPTURE_MODE_VIDEO:\n\t\treturn OUTPUT_TYPE_V;\n\tcase MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT:\n\tcase MSM_V4L2_EXT_CAPTURE_MODE_PREVIEW:\n\tdefault:\n\t\treturn OUTPUT_TYPE_P;\n\t}\n}\n\nstatic int msm_mctl_v4l2_s_parm(struct file *f, void *pctx,\n\t\t\t\tstruct v4l2_streamparm *a)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst = container_of(f->private_data,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\tpcam_inst->image_mode = a->parm.capture.extendedmode;\n\tmutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);\n\tif (pcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode]) {\n\t\tpr_err(\"%s Stream type %d already used.\",\n\t\t\t__func__, pcam_inst->image_mode);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn -EBUSY;\n\t}\n\tpcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode] =\n\t\tpcam_inst;\n\tpcam_inst->path = msm_mctl_vidbuf_get_path(pcam_inst->image_mode);\n\tD(\"%s path=%d, image mode = %d rc=%d\\n\", __func__,\n\t\tpcam_inst->path, pcam_inst->image_mode, rc);\n\tmutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_subscribe_event(struct v4l2_fh *fh,\n\t\t\tstruct v4l2_event_subscription *sub)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst =\n\t\t(struct msm_cam_v4l2_dev_inst *)container_of(fh,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s:fh = 0x%x, type = 0x%x\\n\", __func__, (u32)fh, sub->type);\n\n\tif (sub->type == V4L2_EVENT_ALL)\n\t\tsub->type = V4L2_EVENT_PRIVATE_START+MSM_CAM_APP_NOTIFY_EVENT;\n\trc = v4l2_event_subscribe(fh, sub, 30);\n\tif (rc < 0)\n\t\tpr_err(\"%s: failed for evtType = 0x%x, rc = %d\\n\",\n\t\t\t\t\t\t__func__, sub->type, rc);\n\treturn rc;\n}\n\nstatic int msm_mctl_v4l2_unsubscribe_event(struct v4l2_fh *fh,\n\t\t\tstruct v4l2_event_subscription *sub)\n{\n\tint rc = 0;\n\tstruct msm_cam_v4l2_dev_inst *pcam_inst;\n\tpcam_inst =\n\t\t(struct msm_cam_v4l2_dev_inst *)container_of(fh,\n\t\tstruct msm_cam_v4l2_dev_inst, eventHandle);\n\n\tD(\"%s: fh = 0x%x\\n\", __func__, (u32)fh);\n\n\trc = v4l2_event_unsubscribe(fh, sub);\n\tD(\"%s: rc = %d\\n\", __func__, rc);\n\treturn rc;\n}\n\n/* mctl node v4l2_ioctl_ops */\nstatic const struct v4l2_ioctl_ops g_msm_mctl_ioctl_ops = {\n\t.vidioc_querycap = msm_mctl_v4l2_querycap,\n\n\t.vidioc_s_crop = msm_mctl_v4l2_s_crop,\n\t.vidioc_g_crop = msm_mctl_v4l2_g_crop,\n\n\t.vidioc_queryctrl = msm_mctl_v4l2_queryctrl,\n\t.vidioc_g_ctrl = msm_mctl_v4l2_g_ctrl,\n\t.vidioc_s_ctrl = msm_mctl_v4l2_s_ctrl,\n\n\t.vidioc_reqbufs = msm_mctl_v4l2_reqbufs,\n\t.vidioc_querybuf = msm_mctl_v4l2_querybuf,\n\t.vidioc_qbuf = msm_mctl_v4l2_qbuf,\n\t.vidioc_dqbuf = msm_mctl_v4l2_dqbuf,\n\n\t.vidioc_streamon = msm_mctl_v4l2_streamon,\n\t.vidioc_streamoff = msm_mctl_v4l2_streamoff,\n\n\t/* format ioctls */\n\t.vidioc_enum_fmt_vid_cap = msm_mctl_v4l2_enum_fmt_cap,\n\t.vidioc_enum_fmt_vid_cap_mplane = msm_mctl_v4l2_enum_fmt_cap,\n\t.vidioc_try_fmt_vid_cap = msm_mctl_v4l2_try_fmt_cap,\n\t.vidioc_try_fmt_vid_cap_mplane = msm_mctl_v4l2_try_fmt_cap_mplane,\n\t.vidioc_g_fmt_vid_cap = msm_mctl_v4l2_g_fmt_cap,\n\t.vidioc_g_fmt_vid_cap_mplane = msm_mctl_v4l2_g_fmt_cap_mplane,\n\t.vidioc_s_fmt_vid_cap = msm_mctl_v4l2_s_fmt_cap,\n\t.vidioc_s_fmt_vid_cap_mplane = msm_mctl_v4l2_s_fmt_cap_mplane,\n\n\t.vidioc_g_jpegcomp = msm_mctl_v4l2_g_jpegcomp,\n\t.vidioc_s_jpegcomp = msm_mctl_v4l2_s_jpegcomp,\n\n\t/* Stream type-dependent parameter ioctls */\n\t.vidioc_g_parm = msm_mctl_v4l2_g_parm,\n\t.vidioc_s_parm = msm_mctl_v4l2_s_parm,\n\n\t/* event subscribe/unsubscribe */\n\t.vidioc_subscribe_event = msm_mctl_v4l2_subscribe_event,\n\t.vidioc_unsubscribe_event = msm_mctl_v4l2_unsubscribe_event,\n};\n\nint msm_setup_mctl_node(struct msm_cam_v4l2_device *pcam)\n{\n\tint rc = -EINVAL;\n\tstruct video_device *pvdev = NULL;\n\tstruct i2c_client *client = v4l2_get_subdevdata(pcam->mctl.sensor_sdev);\n\n\tD(\"%s\\n\", __func__);\n\n\t/* first register the v4l2 device */\n\tpcam->mctl_node.v4l2_dev.dev = &client->dev;\n\trc = v4l2_device_register(pcam->mctl_node.v4l2_dev.dev,\n\t\t\t\t&pcam->mctl_node.v4l2_dev);\n\tif (rc < 0)\n\t\treturn -EINVAL;\n\t/*\telse\n\t\t\tpcam->v4l2_dev.notify = msm_cam_v4l2_subdev_notify; */\n\n\t/* now setup video device */\n\tpvdev = video_device_alloc();\n\tif (pvdev == NULL) {\n\t\tpr_err(\"%s: video_device_alloc failed\\n\", __func__);\n\t\treturn rc;\n\t}\n\n\t/* init video device's driver interface */\n\tD(\"sensor name = %s, sizeof(pvdev->name)=%d\\n\",\n\t\t\tpcam->mctl.sensor_sdev->name, sizeof(pvdev->name));\n\n\t/* device info - strlcpy is safer than strncpy but\n\t only if architecture supports*/\n\tstrlcpy(pvdev->name, pcam->mctl.sensor_sdev->name,\n\t\t\tsizeof(pvdev->name));\n\n\tpvdev->release = video_device_release;\n\tpvdev->fops\t = &g_msm_mctl_fops;\n\tpvdev->ioctl_ops = &g_msm_mctl_ioctl_ops;\n\tpvdev->minor\t = -1;\n\tpvdev->vfl_type = 1;\n\n\t/* register v4l2 video device to kernel as /dev/videoXX */\n\tD(\"%s video_register_device\\n\", __func__);\n\trc = video_register_device(pvdev,\n\t\t\tVFL_TYPE_GRABBER,\n\t\t\t-1);\n\tif (rc) {\n\t\tpr_err(\"%s: video_register_device failed\\n\", __func__);\n\t\tgoto reg_fail;\n\t}\n\tD(\"%s: video device registered as /dev/video%d\\n\",\n\t\t\t__func__, pvdev->num);\n\n\t/* connect pcam and mctl video dev to each other */\n\tpcam->mctl_node.pvdev\t= pvdev;\n\tvideo_set_drvdata(pcam->mctl_node.pvdev, pcam);\n\n\treturn rc ;\n\nreg_fail:\n\tvideo_device_release(pvdev);\n\tv4l2_device_unregister(&pcam->mctl_node.v4l2_dev);\n\tpcam->mctl_node.v4l2_dev.dev = NULL;\n\treturn rc;\n}\n"},"repo_name":{"kind":"string","value":"imoseyon/leanKernel-d2vzw"},"path":{"kind":"string","value":"drivers/media/video/msm_apexq/msm_mctl.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":44450,"string":"44,450"}}},{"rowIdx":115086540,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2000-2014 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.usages.impl;\n\nimport com.intellij.openapi.application.ApplicationManager;\nimport com.intellij.openapi.util.text.StringUtil;\nimport com.intellij.pom.Navigatable;\nimport com.intellij.usages.Usage;\nimport com.intellij.usages.UsageGroup;\nimport com.intellij.usages.UsageView;\nimport com.intellij.usages.rules.MergeableUsage;\nimport com.intellij.util.Consumer;\nimport com.intellij.util.SmartList;\nimport gnu.trove.THashMap;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\n\nimport javax.swing.tree.DefaultMutableTreeNode;\nimport javax.swing.tree.MutableTreeNode;\nimport javax.swing.tree.TreeNode;\nimport java.util.*;\n\n/**\n * @author max\n */\npublic class GroupNode extends Node implements Navigatable, Comparable {\n private static final NodeComparator COMPARATOR = new NodeComparator();\n private final Object lock = new Object();\n private final UsageGroup myGroup;\n private final int myRuleIndex;\n private final Map mySubgroupNodes = new THashMap();\n private final List myUsageNodes = new SmartList();\n @NotNull private final UsageViewTreeModelBuilder myUsageTreeModel;\n private volatile int myRecursiveUsageCount = 0;\n\n public GroupNode(@Nullable UsageGroup group, int ruleIndex, @NotNull UsageViewTreeModelBuilder treeModel) {\n super(treeModel);\n myUsageTreeModel = treeModel;\n setUserObject(group);\n myGroup = group;\n myRuleIndex = ruleIndex;\n }\n\n @Override\n protected void updateNotify() {\n if (myGroup != null) {\n myGroup.update();\n }\n }\n\n public String toString() {\n String result = \"\";\n if (myGroup != null) result = myGroup.getText(null);\n if (children == null) {\n return result;\n }\n return result + children.subList(0, Math.min(10, children.size())).toString();\n }\n\n public GroupNode addGroup(@NotNull UsageGroup group, int ruleIndex, @NotNull Consumer edtQueue) {\n synchronized (lock) {\n GroupNode node = mySubgroupNodes.get(group);\n if (node == null) {\n final GroupNode node1 = node = new GroupNode(group, ruleIndex, getBuilder());\n mySubgroupNodes.put(group, node);\n\n addNode(node1, edtQueue);\n }\n return node;\n }\n }\n\n void addNode(@NotNull final DefaultMutableTreeNode node, @NotNull Consumer edtQueue) {\n if (!getBuilder().isDetachedMode()) {\n edtQueue.consume(new Runnable() {\n @Override\n public void run() {\n myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node));\n }\n });\n }\n }\n\n private UsageViewTreeModelBuilder getBuilder() {\n return (UsageViewTreeModelBuilder)myTreeModel;\n }\n\n @Override\n public void removeAllChildren() {\n synchronized (lock) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n super.removeAllChildren();\n mySubgroupNodes.clear();\n myRecursiveUsageCount = 0;\n myUsageNodes.clear();\n }\n myTreeModel.reload(this);\n }\n\n @Nullable UsageNode tryMerge(@NotNull Usage usage) {\n if (!(usage instanceof MergeableUsage)) return null;\n MergeableUsage mergeableUsage = (MergeableUsage)usage;\n for (UsageNode node : myUsageNodes) {\n Usage original = node.getUsage();\n if (original == mergeableUsage) {\n // search returned duplicate usage, ignore\n return node;\n }\n if (original instanceof MergeableUsage) {\n if (((MergeableUsage)original).merge(mergeableUsage)) return node;\n }\n }\n\n return null;\n }\n\n public boolean removeUsage(@NotNull UsageNode usage) {\n ApplicationManager.getApplication().assertIsDispatchThread();\n final Collection groupNodes = mySubgroupNodes.values();\n for(Iterator iterator = groupNodes.iterator();iterator.hasNext();) {\n final GroupNode groupNode = iterator.next();\n\n if(groupNode.removeUsage(usage)) {\n doUpdate();\n\n if (groupNode.getRecursiveUsageCount() == 0) {\n myTreeModel.removeNodeFromParent(groupNode);\n iterator.remove();\n }\n return true;\n }\n }\n\n boolean removed;\n synchronized (lock) {\n removed = myUsageNodes.remove(usage);\n }\n if (removed) {\n doUpdate();\n return true;\n }\n\n return false;\n }\n\n public boolean removeUsagesBulk(@NotNull Set usages) {\n boolean removed;\n synchronized (lock) {\n removed = myUsageNodes.removeAll(usages);\n }\n\n Collection groupNodes = mySubgroupNodes.values();\n\n for (Iterator iterator = groupNodes.iterator(); iterator.hasNext(); ) {\n GroupNode groupNode = iterator.next();\n\n if (groupNode.removeUsagesBulk(usages)) {\n if (groupNode.getRecursiveUsageCount() == 0) {\n MutableTreeNode parent = (MutableTreeNode)groupNode.getParent();\n int childIndex = parent.getIndex(groupNode);\n if (childIndex != -1) {\n parent.remove(childIndex);\n }\n iterator.remove();\n }\n removed = true;\n }\n }\n if (removed) {\n --myRecursiveUsageCount;\n }\n return removed;\n }\n\n private void doUpdate() {\n ApplicationManager.getApplication().assertIsDispatchThread();\n --myRecursiveUsageCount;\n myTreeModel.nodeChanged(this);\n }\n\n public UsageNode addUsage(@NotNull Usage usage, @NotNull Consumer edtQueue) {\n final UsageNode node;\n synchronized (lock) {\n if (myUsageTreeModel.isFilterDuplicatedLine()) {\n UsageNode mergedWith = tryMerge(usage);\n if (mergedWith != null) {\n return mergedWith;\n }\n }\n node = new UsageNode(usage, getBuilder());\n myUsageNodes.add(node);\n }\n\n if (!getBuilder().isDetachedMode()) {\n edtQueue.consume(new Runnable() {\n @Override\n public void run() {\n myTreeModel.insertNodeInto(node, GroupNode.this, getNodeIndex(node));\n incrementUsageCount();\n }\n });\n }\n return node;\n }\n\n private int getNodeIndex(@NotNull UsageNode node) {\n int index = indexedBinarySearch(node);\n return index >= 0 ? index : -index-1;\n }\n\n private int indexedBinarySearch(@NotNull UsageNode key) {\n int low = 0;\n int high = getChildCount() - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n TreeNode treeNode = getChildAt(mid);\n int cmp;\n if (treeNode instanceof UsageNode) {\n UsageNode midVal = (UsageNode)treeNode;\n cmp = midVal.compareTo(key);\n }\n else {\n cmp = -1;\n }\n if (cmp < 0) {\n low = mid + 1;\n }\n else if (cmp > 0) {\n high = mid - 1;\n }\n else {\n return mid; // key found\n }\n }\n return -(low + 1); // key not found\n }\n\n\n private void incrementUsageCount() {\n GroupNode groupNode = this;\n while (true) {\n groupNode.myRecursiveUsageCount++;\n final GroupNode node = groupNode;\n myTreeModel.nodeChanged(node);\n TreeNode parent = groupNode.getParent();\n if (!(parent instanceof GroupNode)) return;\n groupNode = (GroupNode)parent;\n }\n }\n\n @Override\n public String tree2string(int indent, String lineSeparator) {\n StringBuffer result = new StringBuffer();\n StringUtil.repeatSymbol(result, ' ', indent);\n\n if (myGroup != null) result.append(myGroup.toString());\n result.append(\"[\");\n result.append(lineSeparator);\n\n Enumeration enumeration = children();\n while (enumeration.hasMoreElements()) {\n Node node = (Node)enumeration.nextElement();\n result.append(node.tree2string(indent + 4, lineSeparator));\n result.append(lineSeparator);\n }\n\n StringUtil.repeatSymbol(result, ' ', indent);\n result.append(\"]\");\n result.append(lineSeparator);\n\n return result.toString();\n }\n\n @Override\n protected boolean isDataValid() {\n return myGroup == null || myGroup.isValid();\n }\n\n @Override\n protected boolean isDataReadOnly() {\n Enumeration enumeration = children();\n while (enumeration.hasMoreElements()) {\n Object element = enumeration.nextElement();\n if (element instanceof Node && ((Node)element).isReadOnly()) return true;\n }\n return false;\n }\n\n private int getNodeInsertionIndex(@NotNull DefaultMutableTreeNode node) {\n Enumeration children = children();\n int idx = 0;\n while (children.hasMoreElements()) {\n DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();\n if (COMPARATOR.compare(child, node) >= 0) break;\n idx++;\n }\n return idx;\n }\n\n private static class NodeComparator implements Comparator {\n private static int getClassIndex(DefaultMutableTreeNode node) {\n if (node instanceof UsageNode) return 3;\n if (node instanceof GroupNode) return 2;\n if (node instanceof UsageTargetNode) return 1;\n return 0;\n }\n\n @Override\n public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) {\n int classIdx1 = getClassIndex(n1);\n int classIdx2 = getClassIndex(n2);\n if (classIdx1 != classIdx2) return classIdx1 - classIdx2;\n if (classIdx1 == 2) return ((GroupNode)n1).compareTo((GroupNode)n2);\n\n return 0;\n }\n }\n\n @Override\n public int compareTo(@NotNull GroupNode groupNode) {\n if (myRuleIndex == groupNode.myRuleIndex) {\n return myGroup.compareTo(groupNode.myGroup);\n }\n\n return myRuleIndex - groupNode.myRuleIndex;\n }\n\n public UsageGroup getGroup() {\n return myGroup;\n }\n\n public int getRecursiveUsageCount() {\n return myRecursiveUsageCount;\n }\n\n @Override\n public void navigate(boolean requestFocus) {\n if (myGroup != null) {\n myGroup.navigate(requestFocus);\n }\n }\n\n @Override\n public boolean canNavigate() {\n return myGroup != null && myGroup.canNavigate();\n }\n\n @Override\n public boolean canNavigateToSource() {\n return myGroup != null && myGroup.canNavigateToSource();\n }\n\n\n @Override\n protected boolean isDataExcluded() {\n Enumeration enumeration = children();\n while (enumeration.hasMoreElements()) {\n Node node = (Node)enumeration.nextElement();\n if (!node.isExcluded()) return false;\n }\n return true;\n }\n\n @Override\n protected String getText(@NotNull UsageView view) {\n return myGroup.getText(view);\n }\n\n @NotNull\n public Collection getSubGroups() {\n return mySubgroupNodes.values();\n }\n\n @NotNull\n public Collection getUsageNodes() {\n return myUsageNodes;\n }\n}\n"},"repo_name":{"kind":"string","value":"akosyakov/intellij-community"},"path":{"kind":"string","value":"platform/usageView/src/com/intellij/usages/impl/GroupNode.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":11143,"string":"11,143"}}},{"rowIdx":115086541,"cells":{"code":{"kind":"string","value":"package testclient\n\nimport (\n\tktestclient \"k8s.io/kubernetes/pkg/client/testclient\"\n\t\"k8s.io/kubernetes/pkg/fields\"\n\t\"k8s.io/kubernetes/pkg/labels\"\n\t\"k8s.io/kubernetes/pkg/watch\"\n\n\ttemplateapi \"github.com/openshift/origin/pkg/template/api\"\n)\n\n// FakeTemplates implements TemplateInterface. Meant to be embedded into a struct to get a default\n// implementation. This makes faking out just the methods you want to test easier.\ntype FakeTemplates struct {\n\tFake *Fake\n\tNamespace string\n}\n\nfunc (c *FakeTemplates) Get(name string) (*templateapi.Template, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewGetAction(\"templates\", c.Namespace, name), &templateapi.Template{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*templateapi.Template), err\n}\n\nfunc (c *FakeTemplates) List(label labels.Selector, field fields.Selector) (*templateapi.TemplateList, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewListAction(\"templates\", c.Namespace, label, field), &templateapi.TemplateList{})\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*templateapi.TemplateList), err\n}\n\nfunc (c *FakeTemplates) Create(inObj *templateapi.Template) (*templateapi.Template, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewCreateAction(\"templates\", c.Namespace, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*templateapi.Template), err\n}\n\nfunc (c *FakeTemplates) Update(inObj *templateapi.Template) (*templateapi.Template, error) {\n\tobj, err := c.Fake.Invokes(ktestclient.NewUpdateAction(\"templates\", c.Namespace, inObj), inObj)\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\n\treturn obj.(*templateapi.Template), err\n}\n\nfunc (c *FakeTemplates) Delete(name string) error {\n\t_, err := c.Fake.Invokes(ktestclient.NewDeleteAction(\"templates\", c.Namespace, name), &templateapi.Template{})\n\treturn err\n}\n\nfunc (c *FakeTemplates) Watch(label labels.Selector, field fields.Selector, resourceVersion string) (watch.Interface, error) {\n\tc.Fake.Invokes(ktestclient.NewWatchAction(\"templates\", c.Namespace, label, field, resourceVersion), nil)\n\treturn c.Fake.Watch, nil\n}\n"},"repo_name":{"kind":"string","value":"domenicbove/origin"},"path":{"kind":"string","value":"pkg/client/testclient/fake_templates.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":2068,"string":"2,068"}}},{"rowIdx":115086542,"cells":{"code":{"kind":"string","value":"package im.actor.model.api.rpc;\n/*\n * Generated by the Actor API Scheme generator. DO NOT EDIT!\n */\n\nimport im.actor.model.droidkit.bser.Bser;\nimport im.actor.model.droidkit.bser.BserParser;\nimport im.actor.model.droidkit.bser.BserObject;\nimport im.actor.model.droidkit.bser.BserValues;\nimport im.actor.model.droidkit.bser.BserWriter;\nimport im.actor.model.droidkit.bser.DataInput;\nimport im.actor.model.droidkit.bser.DataOutput;\nimport im.actor.model.droidkit.bser.util.SparseArray;\nimport org.jetbrains.annotations.Nullable;\nimport org.jetbrains.annotations.NotNull;\nimport com.google.j2objc.annotations.ObjectiveCName;\nimport static im.actor.model.droidkit.bser.Utils.*;\nimport java.io.IOException;\nimport im.actor.model.network.parser.*;\nimport java.util.List;\nimport java.util.ArrayList;\nimport im.actor.model.api.*;\n\npublic class RequestSendMessage extends Request {\n\n public static final int HEADER = 0x5c;\n public static RequestSendMessage fromBytes(byte[] data) throws IOException {\n return Bser.parse(new RequestSendMessage(), data);\n }\n\n private OutPeer peer;\n private long rid;\n private Message message;\n\n public RequestSendMessage(@NotNull OutPeer peer, long rid, @NotNull Message message) {\n this.peer = peer;\n this.rid = rid;\n this.message = message;\n }\n\n public RequestSendMessage() {\n\n }\n\n @NotNull\n public OutPeer getPeer() {\n return this.peer;\n }\n\n public long getRid() {\n return this.rid;\n }\n\n @NotNull\n public Message getMessage() {\n return this.message;\n }\n\n @Override\n public void parse(BserValues values) throws IOException {\n this.peer = values.getObj(1, new OutPeer());\n this.rid = values.getLong(3);\n this.message = Message.fromBytes(values.getBytes(4));\n }\n\n @Override\n public void serialize(BserWriter writer) throws IOException {\n if (this.peer == null) {\n throw new IOException();\n }\n writer.writeObject(1, this.peer);\n writer.writeLong(3, this.rid);\n if (this.message == null) {\n throw new IOException();\n }\n\n writer.writeBytes(4, this.message.buildContainer());\n }\n\n @Override\n public String toString() {\n String res = \"rpc SendMessage{\";\n res += \"peer=\" + this.peer;\n res += \", rid=\" + this.rid;\n res += \", message=\" + this.message;\n res += \"}\";\n return res;\n }\n\n @Override\n public int getHeaderKey() {\n return HEADER;\n }\n}\n"},"repo_name":{"kind":"string","value":"Rogerlin2013/actor-platform"},"path":{"kind":"string","value":"actor-apps/core/src/main/java/im/actor/model/api/rpc/RequestSendMessage.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2557,"string":"2,557"}}},{"rowIdx":115086543,"cells":{"code":{"kind":"string","value":"require \"spec_helper\"\n\ndescribe Mongoid::Relations::Referenced::In do\n\n let(:person) do\n Person.create\n end\n\n describe \"#=\" do\n\n context \"when the relation is named target\" do\n\n let(:target) do\n User.new\n end\n\n context \"when the relation is referenced from an embeds many\" do\n\n context \"when setting via create\" do\n\n let(:service) do\n person.services.create(target: target)\n end\n\n it \"sets the target relation\" do\n service.target.should eq(target)\n end\n end\n end\n end\n\n context \"when the inverse relation has no reference defined\" do\n\n let(:agent) do\n Agent.new(title: \"007\")\n end\n\n let(:game) do\n Game.new(name: \"Donkey Kong\")\n end\n\n before do\n agent.game = game\n end\n\n it \"sets the relation\" do\n agent.game.should eq(game)\n end\n\n it \"sets the foreign_key\" do\n agent.game_id.should eq(game.id)\n end\n end\n\n context \"when referencing a document from an embedded document\" do\n\n let(:person) do\n Person.create\n end\n\n let(:address) do\n person.addresses.create(street: \"Wienerstr\")\n end\n\n let(:account) do\n Account.create(name: \"1\", number: 1000000)\n end\n\n before do\n address.account = account\n end\n\n it \"sets the relation\" do\n address.account.should eq(account)\n end\n\n it \"does not erase the metadata\" do\n address.metadata.should_not be_nil\n end\n\n it \"allows saving of the embedded document\" do\n address.save.should be_true\n end\n end\n\n context \"when the parent is a references one\" do\n\n context \"when the relation is not polymorphic\" do\n\n context \"when the child is a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:game) do\n Game.new\n end\n\n before do\n game.person = person\n end\n\n it \"sets the target of the relation\" do\n game.person.target.should eq(person)\n end\n\n it \"sets the foreign key on the relation\" do\n game.person_id.should eq(person.id)\n end\n\n it \"sets the base on the inverse relation\" do\n person.game.should eq(game)\n end\n\n it \"sets the same instance on the inverse relation\" do\n person.game.should eql(game)\n end\n\n it \"does not save the target\" do\n person.should_not be_persisted\n end\n end\n\n context \"when the child is not a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:game) do\n Game.create\n end\n\n before do\n game.person = person\n end\n\n it \"sets the target of the relation\" do\n game.person.target.should eq(person)\n end\n\n it \"sets the foreign key of the relation\" do\n game.person_id.should eq(person.id)\n end\n\n it \"sets the base on the inverse relation\" do\n person.game.should eq(game)\n end\n\n it \"sets the same instance on the inverse relation\" do\n person.game.should eql(game)\n end\n\n it \"does not saves the target\" do\n person.should_not be_persisted\n end\n end\n end\n\n context \"when the relation is not polymorphic\" do\n\n context \"when the child is a new record\" do\n\n let(:bar) do\n Bar.new\n end\n\n let(:rating) do\n Rating.new\n end\n\n before do\n rating.ratable = bar\n end\n\n it \"sets the target of the relation\" do\n rating.ratable.target.should eq(bar)\n end\n\n it \"sets the foreign key on the relation\" do\n rating.ratable_id.should eq(bar.id)\n end\n\n it \"sets the base on the inverse relation\" do\n bar.rating.should eq(rating)\n end\n\n it \"sets the same instance on the inverse relation\" do\n bar.rating.should eql(rating)\n end\n\n it \"does not save the target\" do\n bar.should_not be_persisted\n end\n end\n\n context \"when the child is not a new record\" do\n\n let(:bar) do\n Bar.new\n end\n\n let(:rating) do\n Rating.create\n end\n\n before do\n rating.ratable = bar\n end\n\n it \"sets the target of the relation\" do\n rating.ratable.target.should eq(bar)\n end\n\n it \"sets the foreign key of the relation\" do\n rating.ratable_id.should eq(bar.id)\n end\n\n it \"sets the base on the inverse relation\" do\n bar.rating.should eq(rating)\n end\n\n it \"sets the same instance on the inverse relation\" do\n bar.rating.should eql(rating)\n end\n\n it \"does not saves the target\" do\n bar.should_not be_persisted\n end\n end\n end\n end\n\n context \"when the parent is a references many\" do\n\n context \"when the relation is not polymorphic\" do\n\n context \"when the child is a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:post) do\n Post.new\n end\n\n before do\n post.person = person\n end\n\n it \"sets the target of the relation\" do\n post.person.target.should eq(person)\n end\n\n it \"sets the foreign key on the relation\" do\n post.person_id.should eq(person.id)\n end\n\n it \"does not save the target\" do\n person.should_not be_persisted\n end\n end\n\n context \"when the child is not a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:post) do\n Post.create\n end\n\n before do\n post.person = person\n end\n\n it \"sets the target of the relation\" do\n post.person.target.should eq(person)\n end\n\n it \"sets the foreign key of the relation\" do\n post.person_id.should eq(person.id)\n end\n\n it \"does not saves the target\" do\n person.should_not be_persisted\n end\n end\n end\n\n context \"when the relation is polymorphic\" do\n\n context \"when multiple relations against the same class exist\" do\n\n let(:face) do\n Face.new\n end\n\n let(:eye) do\n Eye.new\n end\n\n it \"raises an error\" do\n expect {\n eye.eyeable = face\n }.to raise_error(Mongoid::Errors::InvalidSetPolymorphicRelation)\n end\n end\n\n context \"when one relation against the same class exists\" do\n\n context \"when the child is a new record\" do\n\n let(:movie) do\n Movie.new\n end\n\n let(:rating) do\n Rating.new\n end\n\n before do\n rating.ratable = movie\n end\n\n it \"sets the target of the relation\" do\n rating.ratable.target.should eq(movie)\n end\n\n it \"sets the foreign key on the relation\" do\n rating.ratable_id.should eq(movie.id)\n end\n\n it \"does not save the target\" do\n movie.should_not be_persisted\n end\n end\n\n context \"when the child is not a new record\" do\n\n let(:movie) do\n Movie.new\n end\n\n let(:rating) do\n Rating.create\n end\n\n before do\n rating.ratable = movie\n end\n\n it \"sets the target of the relation\" do\n rating.ratable.target.should eq(movie)\n end\n\n it \"sets the foreign key of the relation\" do\n rating.ratable_id.should eq(movie.id)\n end\n\n it \"does not saves the target\" do\n movie.should_not be_persisted\n end\n end\n end\n end\n end\n end\n\n describe \"#= nil\" do\n\n context \"when dependent is destroy\" do\n\n let(:account) do\n Account.create\n end\n\n let(:drug) do\n Drug.create\n end\n\n let(:person) do\n Person.create\n end\n\n context \"when relation is has_one\" do\n\n before do\n Account.belongs_to :person, dependent: :destroy\n Person.has_one :account\n person.account = account\n person.save\n end\n\n after :all do\n Account.belongs_to :person, dependent: :nullify\n Person.has_one :account, validate: false\n end\n\n context \"when parent exists\" do\n\n context \"when child is destroyed\" do\n\n before do\n account.delete\n end\n\n it \"deletes child\" do\n account.should be_destroyed\n end\n\n it \"deletes parent\" do\n person.should be_destroyed\n end\n end\n end\n end\n\n context \"when relation is has_many\" do\n\n before do\n Drug.belongs_to :person, dependent: :destroy\n Person.has_many :drugs\n person.drugs = [drug]\n person.save\n end\n\n after :all do\n Drug.belongs_to :person, dependent: :nullify\n Person.has_many :drugs, validate: false\n end\n\n context \"when parent exists\" do\n\n context \"when child is destroyed\" do\n\n before do\n drug.delete\n end\n\n it \"deletes child\" do\n drug.should be_destroyed\n end\n\n it \"deletes parent\" do\n person.should be_destroyed\n end\n end\n end\n end\n end\n\n context \"when dependent is delete\" do\n\n let(:account) do\n Account.create\n end\n\n let(:drug) do\n Drug.create\n end\n\n let(:person) do\n Person.create\n end\n\n context \"when relation is has_one\" do\n\n before do\n Account.belongs_to :person, dependent: :delete\n Person.has_one :account\n person.account = account\n person.save\n end\n\n after :all do\n Account.belongs_to :person, dependent: :nullify\n Person.has_one :account, validate: false\n end\n\n context \"when parent is persisted\" do\n\n context \"when child is deleted\" do\n\n before do\n account.delete\n end\n\n it \"deletes child\" do\n account.should be_destroyed\n end\n\n it \"deletes parent\" do\n person.should be_destroyed\n end\n end\n end\n end\n\n context \"when relation is has_many\" do\n\n before do\n Drug.belongs_to :person, dependent: :delete\n Person.has_many :drugs\n person.drugs = [drug]\n person.save\n end\n\n after :all do\n Drug.belongs_to :person, dependent: :nullify\n Person.has_many :drugs, validate: false\n end\n\n context \"when parent exists\" do\n\n context \"when child is destroyed\" do\n\n before do\n drug.delete\n end\n\n it \"deletes child\" do\n drug.should be_destroyed\n end\n\n it \"deletes parent\" do\n person.should be_destroyed\n end\n end\n end\n end\n end\n\n context \"when dependent is nullify\" do\n\n let(:account) do\n Account.create\n end\n\n let(:drug) do\n Drug.create\n end\n\n let(:person) do\n Person.create\n end\n\n context \"when relation is has_one\" do\n\n before do\n Account.belongs_to :person, dependent: :nullify\n Person.has_one :account\n person.account = account\n person.save\n end\n\n context \"when parent is persisted\" do\n\n context \"when child is deleted\" do\n\n before do\n account.delete\n end\n\n it \"deletes child\" do\n account.should be_destroyed\n end\n\n it \"doesn't delete parent\" do\n person.should_not be_destroyed\n end\n\n it \"removes the link\" do\n person.account.should be_nil\n end\n end\n end\n end\n\n context \"when relation is has_many\" do\n\n before do\n Drug.belongs_to :person, dependent: :nullify\n Person.has_many :drugs\n person.drugs = [drug]\n person.save\n end\n\n context \"when parent exists\" do\n\n context \"when child is destroyed\" do\n\n before do\n drug.delete\n end\n\n it \"deletes child\" do\n drug.should be_destroyed\n end\n\n it \"doesn't deletes parent\" do\n person.should_not be_destroyed\n end\n\n it \"removes the link\" do\n person.drugs.should eq([])\n end\n end\n end\n end\n end\n\n context \"when the inverse relation has no reference defined\" do\n\n let(:agent) do\n Agent.new(title: \"007\")\n end\n\n let(:game) do\n Game.new(name: \"Donkey Kong\")\n end\n\n before do\n agent.game = game\n agent.game = nil\n end\n\n it \"removes the relation\" do\n agent.game.should be_nil\n end\n\n it \"removes the foreign_key\" do\n agent.game_id.should be_nil\n end\n end\n\n context \"when the parent is a references one\" do\n\n context \"when the relation is not polymorphic\" do\n\n context \"when the parent is a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:game) do\n Game.new\n end\n\n before do\n game.person = person\n game.person = nil\n end\n\n it \"sets the relation to nil\" do\n game.person.should be_nil\n end\n\n it \"removed the inverse relation\" do\n person.game.should be_nil\n end\n\n it \"removes the foreign key value\" do\n game.person_id.should be_nil\n end\n end\n\n context \"when the parent is not a new record\" do\n\n let(:person) do\n Person.create\n end\n\n let(:game) do\n Game.create\n end\n\n before do\n game.person = person\n game.person = nil\n end\n\n it \"sets the relation to nil\" do\n game.person.should be_nil\n end\n\n it \"removed the inverse relation\" do\n person.game.should be_nil\n end\n\n it \"removes the foreign key value\" do\n game.person_id.should be_nil\n end\n\n it \"does not delete the child\" do\n game.should_not be_destroyed\n end\n end\n end\n\n context \"when the relation is polymorphic\" do\n\n context \"when multiple relations against the same class exist\" do\n\n context \"when the parent is a new record\" do\n\n let(:face) do\n Face.new\n end\n\n let(:eye) do\n Eye.new\n end\n\n before do\n face.left_eye = eye\n eye.eyeable = nil\n end\n\n it \"sets the relation to nil\" do\n eye.eyeable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n face.left_eye.should be_nil\n end\n\n it \"removes the foreign key value\" do\n eye.eyeable_id.should be_nil\n end\n end\n\n context \"when the parent is not a new record\" do\n\n let(:face) do\n Face.new\n end\n\n let(:eye) do\n Eye.create\n end\n\n before do\n face.left_eye = eye\n eye.eyeable = nil\n end\n\n it \"sets the relation to nil\" do\n eye.eyeable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n face.left_eye.should be_nil\n end\n\n it \"removes the foreign key value\" do\n eye.eyeable_id.should be_nil\n end\n end\n end\n\n context \"when one relation against the same class exists\" do\n\n context \"when the parent is a new record\" do\n\n let(:bar) do\n Bar.new\n end\n\n let(:rating) do\n Rating.new\n end\n\n before do\n rating.ratable = bar\n rating.ratable = nil\n end\n\n it \"sets the relation to nil\" do\n rating.ratable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n bar.rating.should be_nil\n end\n\n it \"removes the foreign key value\" do\n rating.ratable_id.should be_nil\n end\n end\n\n context \"when the parent is not a new record\" do\n\n let(:bar) do\n Bar.new\n end\n\n let(:rating) do\n Rating.create\n end\n\n before do\n rating.ratable = bar\n rating.ratable = nil\n end\n\n it \"sets the relation to nil\" do\n rating.ratable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n bar.rating.should be_nil\n end\n\n it \"removes the foreign key value\" do\n rating.ratable_id.should be_nil\n end\n end\n end\n end\n end\n\n context \"when the parent is a references many\" do\n\n context \"when the relation is not polymorphic\" do\n\n context \"when the parent is a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:post) do\n Post.new\n end\n\n before do\n post.person = person\n post.person = nil\n end\n\n it \"sets the relation to nil\" do\n post.person.should be_nil\n end\n\n it \"removed the inverse relation\" do\n person.posts.should be_empty\n end\n\n it \"removes the foreign key value\" do\n post.person_id.should be_nil\n end\n end\n\n context \"when the parent is not a new record\" do\n\n let(:person) do\n Person.new\n end\n\n let(:post) do\n Post.create\n end\n\n before do\n post.person = person\n post.person = nil\n end\n\n it \"sets the relation to nil\" do\n post.person.should be_nil\n end\n\n it \"removed the inverse relation\" do\n person.posts.should be_empty\n end\n\n it \"removes the foreign key value\" do\n post.person_id.should be_nil\n end\n end\n end\n\n context \"when the relation is polymorphic\" do\n\n context \"when the parent is a new record\" do\n\n let(:movie) do\n Movie.new\n end\n\n let(:rating) do\n Rating.new\n end\n\n before do\n rating.ratable = movie\n rating.ratable = nil\n end\n\n it \"sets the relation to nil\" do\n rating.ratable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n movie.ratings.should be_empty\n end\n\n it \"removes the foreign key value\" do\n rating.ratable_id.should be_nil\n end\n end\n\n context \"when the parent is not a new record\" do\n\n let(:movie) do\n Movie.new\n end\n\n let(:rating) do\n Rating.create\n end\n\n before do\n rating.ratable = movie\n rating.ratable = nil\n end\n\n it \"sets the relation to nil\" do\n rating.ratable.should be_nil\n end\n\n it \"removed the inverse relation\" do\n movie.ratings.should be_empty\n end\n\n it \"removes the foreign key value\" do\n rating.ratable_id.should be_nil\n end\n end\n end\n end\n end\n\n describe \".builder\" do\n\n let(:builder_klass) do\n Mongoid::Relations::Builders::Referenced::In\n end\n\n let(:document) do\n stub\n end\n\n let(:metadata) do\n stub(extension?: false)\n end\n\n it \"returns the embedded in builder\" do\n described_class.builder(nil, metadata, document).should\n be_a_kind_of(builder_klass)\n end\n end\n\n describe \".eager_load\" do\n\n before do\n Mongoid.identity_map_enabled = true\n end\n\n after do\n Mongoid.identity_map_enabled = false\n end\n\n context \"when the relation is not polymorphic\" do\n\n let!(:person) do\n Person.create\n end\n\n let!(:post) do\n person.posts.create(title: \"testing\")\n end\n\n let(:metadata) do\n Post.relations[\"person\"]\n end\n\n let(:eager) do\n described_class.eager_load(metadata, Post.all)\n end\n\n let!(:map) do\n Mongoid::IdentityMap.get(Person, person.id)\n end\n\n it \"puts the document in the identity map\" do\n map.should eq(person)\n end\n end\n\n context \"when the relation is polymorphic\" do\n\n let(:metadata) do\n Rating.relations[\"ratable\"]\n end\n\n it \"raises an error\" do\n expect {\n described_class.eager_load(metadata, Rating.all)\n }.to raise_error(Mongoid::Errors::EagerLoad)\n end\n end\n\n context \"when the ids has been duplicated\" do\n\n let!(:person) do\n Person.create\n end\n\n let!(:posts) do\n 2.times {|i| person.posts.create(title: \"testing#{i}\") }\n person.posts\n end\n\n let(:metadata) do\n Post.relations[\"person\"]\n end\n\n let(:eager) do\n described_class.eager_load(metadata, posts.map(&:person_id))\n end\n\n it \"duplication should be removed\" do\n eager.count.should eq(1)\n end\n end\n end\n\n describe \".embedded?\" do\n\n it \"returns false\" do\n described_class.should_not be_embedded\n end\n end\n\n describe \".foreign_key_suffix\" do\n\n it \"returns _id\" do\n described_class.foreign_key_suffix.should eq(\"_id\")\n end\n end\n\n describe \".macro\" do\n\n it \"returns belongs_to\" do\n described_class.macro.should eq(:belongs_to)\n end\n end\n\n describe \"#respond_to?\" do\n\n let(:person) do\n Person.new\n end\n\n let(:game) do\n person.build_game(name: \"Tron\")\n end\n\n let(:document) do\n game.person\n end\n\n Mongoid::Document.public_instance_methods(true).each do |method|\n\n context \"when checking #{method}\" do\n\n it \"returns true\" do\n document.respond_to?(method).should be_true\n end\n end\n end\n end\n\n describe \".stores_foreign_key?\" do\n\n it \"returns true\" do\n described_class.stores_foreign_key?.should be_true\n end\n end\n\n describe \".valid_options\" do\n\n it \"returns the valid options\" do\n described_class.valid_options.should eq(\n [ :autobuild, :autosave, :dependent, :foreign_key, :index, :polymorphic, :touch ]\n )\n end\n end\n\n describe \".validation_default\" do\n\n it \"returns false\" do\n described_class.validation_default.should be_false\n end\n end\n\n context \"when the relation is self referencing\" do\n\n let(:game_one) do\n Game.new(name: \"Diablo\")\n end\n\n let(:game_two) do\n Game.new(name: \"Warcraft\")\n end\n\n context \"when setting the parent\" do\n\n before do\n game_one.parent = game_two\n end\n\n it \"sets the parent\" do\n game_one.parent.should eq(game_two)\n end\n\n it \"does not set the parent recursively\" do\n game_two.parent.should be_nil\n end\n end\n end\n\n context \"when the relation belongs to a has many and has one\" do\n\n before(:all) do\n class A\n include Mongoid::Document\n has_many :bs, inverse_of: :a\n end\n\n class B\n include Mongoid::Document\n belongs_to :a, inverse_of: :bs\n belongs_to :c, inverse_of: :b\n end\n\n class C\n include Mongoid::Document\n has_one :b, inverse_of: :c\n end\n end\n\n after(:all) do\n Object.send(:remove_const, :A)\n Object.send(:remove_const, :B)\n Object.send(:remove_const, :C)\n end\n\n context \"when setting the has one\" do\n\n let(:a) do\n A.new\n end\n\n let(:b) do\n B.new\n end\n\n let(:c) do\n C.new\n end\n\n before do\n b.c = c\n end\n\n context \"when subsequently setting the has many\" do\n\n before do\n b.a = a\n end\n\n context \"when setting the has one again\" do\n\n before do\n b.c = c\n end\n\n it \"allows the reset of the has one\" do\n b.c.should eq(c)\n end\n end\n end\n end\n end\n\n context \"when replacing the relation with another\" do\n\n let!(:person) do\n Person.create\n end\n\n let!(:post) do\n Post.create(title: \"test\")\n end\n\n let!(:game) do\n person.create_game(name: \"Tron\")\n end\n\n before do\n post.person = game.person\n post.save\n end\n\n it \"clones the relation\" do\n post.person.should eq(person)\n end\n\n it \"sets the foreign key\" do\n post.person_id.should eq(person.id)\n end\n\n it \"does not remove the previous relation\" do\n game.person.should eq(person)\n end\n\n it \"does not remove the previous foreign key\" do\n game.person_id.should eq(person.id)\n end\n\n context \"when reloading\" do\n\n before do\n post.reload\n game.reload\n end\n\n it \"persists the relation\" do\n post.reload.person.should eq(person)\n end\n\n it \"persists the foreign key\" do\n post.reload.person_id.should eq(game.person_id)\n end\n\n it \"does not remove the previous relation\" do\n game.person.should eq(person)\n end\n\n it \"does not remove the previous foreign key\" do\n game.person_id.should eq(person.id)\n end\n end\n end\n\n context \"when the document belongs to a has one and has many\" do\n\n let(:movie) do\n Movie.create(name: \"Infernal Affairs\")\n end\n\n let(:account) do\n Account.create(name: \"Leung\")\n end\n\n context \"when creating the document\" do\n\n let(:comment) do\n Comment.create(movie: movie, account: account)\n end\n\n it \"sets the correct has one\" do\n comment.account.should eq(account)\n end\n\n it \"sets the correct has many\" do\n comment.movie.should eq(movie)\n end\n end\n end\n\n context \"when reloading the relation\" do\n\n let!(:person_one) do\n Person.create\n end\n\n let!(:person_two) do\n Person.create(title: \"Sir\")\n end\n\n let!(:game) do\n Game.create(name: \"Starcraft 2\")\n end\n\n before do\n game.person = person_one\n game.save\n end\n\n context \"when the relation references the same document\" do\n\n before do\n Person.collection.find({ _id: person_one.id }).\n update({ \"$set\" => { title: \"Madam\" }})\n end\n\n let(:reloaded) do\n game.person(true)\n end\n\n it \"reloads the document from the database\" do\n reloaded.title.should eq(\"Madam\")\n end\n\n it \"sets a new document instance\" do\n reloaded.should_not equal(person_one)\n end\n end\n\n context \"when the relation references a different document\" do\n\n before do\n game.person_id = person_two.id\n game.save\n end\n\n let(:reloaded) do\n game.person(true)\n end\n\n it \"reloads the new document from the database\" do\n reloaded.title.should eq(\"Sir\")\n end\n\n it \"sets a new document instance\" do\n reloaded.should_not equal(person_one)\n end\n end\n end\n\n context \"when the parent and child are persisted\" do\n\n context \"when the identity map is enabled\" do\n\n before do\n Mongoid.identity_map_enabled = true\n end\n\n after do\n Mongoid.identity_map_enabled = false\n end\n\n let(:series) do\n Series.create\n end\n\n let!(:book_one) do\n series.books.create\n end\n\n let!(:book_two) do\n series.books.create\n end\n\n let(:id) do\n Book.first.id\n end\n\n context \"when asking for the inverse multiple times\" do\n\n before do\n Book.find(id).series.books.to_a\n end\n\n it \"does not append and save duplicate docs\" do\n Book.find(id).series.books.to_a.length.should eq(2)\n end\n\n it \"returns the same documents from the map\" do\n Book.find(id).should equal(Book.find(id))\n end\n end\n end\n end\n\n context \"when creating with a reference to an integer id parent\" do\n\n let!(:jar) do\n Jar.create do |doc|\n doc._id = 1\n end\n end\n\n let(:cookie) do\n Cookie.create(jar_id: \"1\")\n end\n\n it \"allows strings to be passed as the id\" do\n cookie.jar.should eq(jar)\n end\n\n it \"persists the relation\" do\n cookie.reload.jar.should eq(jar)\n end\n end\n\n context \"when setting the relation via the foreign key\" do\n\n context \"when the relation exists\" do\n\n let!(:person_one) do\n Person.create\n end\n\n let!(:person_two) do\n Person.create\n end\n\n let!(:game) do\n Game.create(person: person_one)\n end\n\n before do\n game.person_id = person_two.id\n end\n\n it \"sets the new document on the relation\" do\n game.person.should eq(person_two)\n end\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"peterwillcn/mongoid"},"path":{"kind":"string","value":"spec/mongoid/relations/referenced/in_spec.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":30037,"string":"30,037"}}},{"rowIdx":115086544,"cells":{"code":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing Microsoft.Win32.SafeHandles;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Security.Cryptography.X509Certificates;\n\nnamespace System.Net.Security\n{\n internal static class CertificateValidation\n {\n private static readonly IdnMapping s_idnMapping = new IdnMapping();\n\n internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName)\n {\n SslPolicyErrors errors = chain.Build(remoteCertificate) ?\n SslPolicyErrors.None :\n SslPolicyErrors.RemoteCertificateChainErrors;\n\n if (!checkCertName)\n {\n return errors;\n }\n\n if (string.IsNullOrEmpty(hostName))\n {\n return errors | SslPolicyErrors.RemoteCertificateNameMismatch;\n }\n\n int hostNameMatch;\n using (SafeX509Handle certHandle = Interop.Crypto.X509UpRef(remoteCertificate.Handle))\n {\n IPAddress hostnameAsIp;\n if (IPAddress.TryParse(hostName, out hostnameAsIp))\n {\n byte[] addressBytes = hostnameAsIp.GetAddressBytes();\n hostNameMatch = Interop.Crypto.CheckX509IpAddress(certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length);\n }\n else\n {\n // The IdnMapping converts Unicode input into the IDNA punycode sequence.\n // It also does host case normalization. The bypass logic would be something\n // like \"all characters being within [a-z0-9.-]+\"\n string matchName = s_idnMapping.GetAscii(hostName);\n hostNameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length);\n }\n }\n\n Debug.Assert(hostNameMatch == 0 || hostNameMatch == 1, $\"Expected 0 or 1 from CheckX509Hostname, got {hostNameMatch}\");\n return hostNameMatch == 1 ?\n errors :\n errors | SslPolicyErrors.RemoteCertificateNameMismatch;\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"ptoonen/corefx"},"path":{"kind":"string","value":"src/Common/src/System/Net/Security/CertificateValidation.Unix.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2411,"string":"2,411"}}},{"rowIdx":115086545,"cells":{"code":{"kind":"string","value":"// SPDX-License-Identifier: GPL-2.0-only\n/*\n * Copyright 2013-2015 Analog Devices Inc.\n * Author: Lars-Peter Clausen \n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * For DMA buffers the storage is sub-divided into so called blocks. Each block\n * has its own memory buffer. The size of the block is the granularity at which\n * memory is exchanged between the hardware and the application. Increasing the\n * basic unit of data exchange from one sample to one block decreases the\n * management overhead that is associated with each sample. E.g. if we say the\n * management overhead for one exchange is x and the unit of exchange is one\n * sample the overhead will be x for each sample. Whereas when using a block\n * which contains n samples the overhead per sample is reduced to x/n. This\n * allows to achieve much higher samplerates than what can be sustained with\n * the one sample approach.\n *\n * Blocks are exchanged between the DMA controller and the application via the\n * means of two queues. The incoming queue and the outgoing queue. Blocks on the\n * incoming queue are waiting for the DMA controller to pick them up and fill\n * them with data. Block on the outgoing queue have been filled with data and\n * are waiting for the application to dequeue them and read the data.\n *\n * A block can be in one of the following states:\n * * Owned by the application. In this state the application can read data from\n * the block.\n * * On the incoming list: Blocks on the incoming list are queued up to be\n * processed by the DMA controller.\n * * Owned by the DMA controller: The DMA controller is processing the block\n * and filling it with data.\n * * On the outgoing list: Blocks on the outgoing list have been successfully\n * processed by the DMA controller and contain data. They can be dequeued by\n * the application.\n * * Dead: A block that is dead has been marked as to be freed. It might still\n * be owned by either the application or the DMA controller at the moment.\n * But once they are done processing it instead of going to either the\n * incoming or outgoing queue the block will be freed.\n *\n * In addition to this blocks are reference counted and the memory associated\n * with both the block structure as well as the storage memory for the block\n * will be freed when the last reference to the block is dropped. This means a\n * block must not be accessed without holding a reference.\n *\n * The iio_dma_buffer implementation provides a generic infrastructure for\n * managing the blocks.\n *\n * A driver for a specific piece of hardware that has DMA capabilities need to\n * implement the submit() callback from the iio_dma_buffer_ops structure. This\n * callback is supposed to initiate the DMA transfer copying data from the\n * converter to the memory region of the block. Once the DMA transfer has been\n * completed the driver must call iio_dma_buffer_block_done() for the completed\n * block.\n *\n * Prior to this it must set the bytes_used field of the block contains\n * the actual number of bytes in the buffer. Typically this will be equal to the\n * size of the block, but if the DMA hardware has certain alignment requirements\n * for the transfer length it might choose to use less than the full size. In\n * either case it is expected that bytes_used is a multiple of the bytes per\n * datum, i.e. the block must not contain partial samples.\n *\n * The driver must call iio_dma_buffer_block_done() for each block it has\n * received through its submit_block() callback, even if it does not actually\n * perform a DMA transfer for the block, e.g. because the buffer was disabled\n * before the block transfer was started. In this case it should set bytes_used\n * to 0.\n *\n * In addition it is recommended that a driver implements the abort() callback.\n * It will be called when the buffer is disabled and can be used to cancel\n * pending and stop active transfers.\n *\n * The specific driver implementation should use the default callback\n * implementations provided by this module for the iio_buffer_access_funcs\n * struct. It may overload some callbacks with custom variants if the hardware\n * has special requirements that are not handled by the generic functions. If a\n * driver chooses to overload a callback it has to ensure that the generic\n * callback is called from within the custom callback.\n */\n\nstatic void iio_buffer_block_release(struct kref *kref)\n{\n\tstruct iio_dma_buffer_block *block = container_of(kref,\n\t\tstruct iio_dma_buffer_block, kref);\n\n\tWARN_ON(block->state != IIO_BLOCK_STATE_DEAD);\n\n\tdma_free_coherent(block->queue->dev, PAGE_ALIGN(block->size),\n\t\t\t\t\tblock->vaddr, block->phys_addr);\n\n\tiio_buffer_put(&block->queue->buffer);\n\tkfree(block);\n}\n\nstatic void iio_buffer_block_get(struct iio_dma_buffer_block *block)\n{\n\tkref_get(&block->kref);\n}\n\nstatic void iio_buffer_block_put(struct iio_dma_buffer_block *block)\n{\n\tkref_put(&block->kref, iio_buffer_block_release);\n}\n\n/*\n * dma_free_coherent can sleep, hence we need to take some special care to be\n * able to drop a reference from an atomic context.\n */\nstatic LIST_HEAD(iio_dma_buffer_dead_blocks);\nstatic DEFINE_SPINLOCK(iio_dma_buffer_dead_blocks_lock);\n\nstatic void iio_dma_buffer_cleanup_worker(struct work_struct *work)\n{\n\tstruct iio_dma_buffer_block *block, *_block;\n\tLIST_HEAD(block_list);\n\n\tspin_lock_irq(&iio_dma_buffer_dead_blocks_lock);\n\tlist_splice_tail_init(&iio_dma_buffer_dead_blocks, &block_list);\n\tspin_unlock_irq(&iio_dma_buffer_dead_blocks_lock);\n\n\tlist_for_each_entry_safe(block, _block, &block_list, head)\n\t\tiio_buffer_block_release(&block->kref);\n}\nstatic DECLARE_WORK(iio_dma_buffer_cleanup_work, iio_dma_buffer_cleanup_worker);\n\nstatic void iio_buffer_block_release_atomic(struct kref *kref)\n{\n\tstruct iio_dma_buffer_block *block;\n\tunsigned long flags;\n\n\tblock = container_of(kref, struct iio_dma_buffer_block, kref);\n\n\tspin_lock_irqsave(&iio_dma_buffer_dead_blocks_lock, flags);\n\tlist_add_tail(&block->head, &iio_dma_buffer_dead_blocks);\n\tspin_unlock_irqrestore(&iio_dma_buffer_dead_blocks_lock, flags);\n\n\tschedule_work(&iio_dma_buffer_cleanup_work);\n}\n\n/*\n * Version of iio_buffer_block_put() that can be called from atomic context\n */\nstatic void iio_buffer_block_put_atomic(struct iio_dma_buffer_block *block)\n{\n\tkref_put(&block->kref, iio_buffer_block_release_atomic);\n}\n\nstatic struct iio_dma_buffer_queue *iio_buffer_to_queue(struct iio_buffer *buf)\n{\n\treturn container_of(buf, struct iio_dma_buffer_queue, buffer);\n}\n\nstatic struct iio_dma_buffer_block *iio_dma_buffer_alloc_block(\n\tstruct iio_dma_buffer_queue *queue, size_t size)\n{\n\tstruct iio_dma_buffer_block *block;\n\n\tblock = kzalloc(sizeof(*block), GFP_KERNEL);\n\tif (!block)\n\t\treturn NULL;\n\n\tblock->vaddr = dma_alloc_coherent(queue->dev, PAGE_ALIGN(size),\n\t\t&block->phys_addr, GFP_KERNEL);\n\tif (!block->vaddr) {\n\t\tkfree(block);\n\t\treturn NULL;\n\t}\n\n\tblock->size = size;\n\tblock->state = IIO_BLOCK_STATE_DEQUEUED;\n\tblock->queue = queue;\n\tINIT_LIST_HEAD(&block->head);\n\tkref_init(&block->kref);\n\n\tiio_buffer_get(&queue->buffer);\n\n\treturn block;\n}\n\nstatic void _iio_dma_buffer_block_done(struct iio_dma_buffer_block *block)\n{\n\tstruct iio_dma_buffer_queue *queue = block->queue;\n\n\t/*\n\t * The buffer has already been freed by the application, just drop the\n\t * reference.\n\t */\n\tif (block->state != IIO_BLOCK_STATE_DEAD) {\n\t\tblock->state = IIO_BLOCK_STATE_DONE;\n\t\tlist_add_tail(&block->head, &queue->outgoing);\n\t}\n}\n\n/**\n * iio_dma_buffer_block_done() - Indicate that a block has been completed\n * @block: The completed block\n *\n * Should be called when the DMA controller has finished handling the block to\n * pass back ownership of the block to the queue.\n */\nvoid iio_dma_buffer_block_done(struct iio_dma_buffer_block *block)\n{\n\tstruct iio_dma_buffer_queue *queue = block->queue;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&queue->list_lock, flags);\n\t_iio_dma_buffer_block_done(block);\n\tspin_unlock_irqrestore(&queue->list_lock, flags);\n\n\tiio_buffer_block_put_atomic(block);\n\twake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM);\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_block_done);\n\n/**\n * iio_dma_buffer_block_list_abort() - Indicate that a list block has been\n * aborted\n * @queue: Queue for which to complete blocks.\n * @list: List of aborted blocks. All blocks in this list must be from @queue.\n *\n * Typically called from the abort() callback after the DMA controller has been\n * stopped. This will set bytes_used to 0 for each block in the list and then\n * hand the blocks back to the queue.\n */\nvoid iio_dma_buffer_block_list_abort(struct iio_dma_buffer_queue *queue,\n\tstruct list_head *list)\n{\n\tstruct iio_dma_buffer_block *block, *_block;\n\tunsigned long flags;\n\n\tspin_lock_irqsave(&queue->list_lock, flags);\n\tlist_for_each_entry_safe(block, _block, list, head) {\n\t\tlist_del(&block->head);\n\t\tblock->bytes_used = 0;\n\t\t_iio_dma_buffer_block_done(block);\n\t\tiio_buffer_block_put_atomic(block);\n\t}\n\tspin_unlock_irqrestore(&queue->list_lock, flags);\n\n\twake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM);\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_block_list_abort);\n\nstatic bool iio_dma_block_reusable(struct iio_dma_buffer_block *block)\n{\n\t/*\n\t * If the core owns the block it can be re-used. This should be the\n\t * default case when enabling the buffer, unless the DMA controller does\n\t * not support abort and has not given back the block yet.\n\t */\n\tswitch (block->state) {\n\tcase IIO_BLOCK_STATE_DEQUEUED:\n\tcase IIO_BLOCK_STATE_QUEUED:\n\tcase IIO_BLOCK_STATE_DONE:\n\t\treturn true;\n\tdefault:\n\t\treturn false;\n\t}\n}\n\n/**\n * iio_dma_buffer_request_update() - DMA buffer request_update callback\n * @buffer: The buffer which to request an update\n *\n * Should be used as the iio_dma_buffer_request_update() callback for\n * iio_buffer_access_ops struct for DMA buffers.\n */\nint iio_dma_buffer_request_update(struct iio_buffer *buffer)\n{\n\tstruct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);\n\tstruct iio_dma_buffer_block *block;\n\tbool try_reuse = false;\n\tsize_t size;\n\tint ret = 0;\n\tint i;\n\n\t/*\n\t * Split the buffer into two even parts. This is used as a double\n\t * buffering scheme with usually one block at a time being used by the\n\t * DMA and the other one by the application.\n\t */\n\tsize = DIV_ROUND_UP(queue->buffer.bytes_per_datum *\n\t\tqueue->buffer.length, 2);\n\n\tmutex_lock(&queue->lock);\n\n\t/* Allocations are page aligned */\n\tif (PAGE_ALIGN(queue->fileio.block_size) == PAGE_ALIGN(size))\n\t\ttry_reuse = true;\n\n\tqueue->fileio.block_size = size;\n\tqueue->fileio.active_block = NULL;\n\n\tspin_lock_irq(&queue->list_lock);\n\tfor (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {\n\t\tblock = queue->fileio.blocks[i];\n\n\t\t/* If we can't re-use it free it */\n\t\tif (block && (!iio_dma_block_reusable(block) || !try_reuse))\n\t\t\tblock->state = IIO_BLOCK_STATE_DEAD;\n\t}\n\n\t/*\n\t * At this point all blocks are either owned by the core or marked as\n\t * dead. This means we can reset the lists without having to fear\n\t * corrution.\n\t */\n\tINIT_LIST_HEAD(&queue->outgoing);\n\tspin_unlock_irq(&queue->list_lock);\n\n\tINIT_LIST_HEAD(&queue->incoming);\n\n\tfor (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {\n\t\tif (queue->fileio.blocks[i]) {\n\t\t\tblock = queue->fileio.blocks[i];\n\t\t\tif (block->state == IIO_BLOCK_STATE_DEAD) {\n\t\t\t\t/* Could not reuse it */\n\t\t\t\tiio_buffer_block_put(block);\n\t\t\t\tblock = NULL;\n\t\t\t} else {\n\t\t\t\tblock->size = size;\n\t\t\t}\n\t\t} else {\n\t\t\tblock = NULL;\n\t\t}\n\n\t\tif (!block) {\n\t\t\tblock = iio_dma_buffer_alloc_block(queue, size);\n\t\t\tif (!block) {\n\t\t\t\tret = -ENOMEM;\n\t\t\t\tgoto out_unlock;\n\t\t\t}\n\t\t\tqueue->fileio.blocks[i] = block;\n\t\t}\n\n\t\tblock->state = IIO_BLOCK_STATE_QUEUED;\n\t\tlist_add_tail(&block->head, &queue->incoming);\n\t}\n\nout_unlock:\n\tmutex_unlock(&queue->lock);\n\n\treturn ret;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_request_update);\n\nstatic void iio_dma_buffer_submit_block(struct iio_dma_buffer_queue *queue,\n\tstruct iio_dma_buffer_block *block)\n{\n\tint ret;\n\n\t/*\n\t * If the hardware has already been removed we put the block into\n\t * limbo. It will neither be on the incoming nor outgoing list, nor will\n\t * it ever complete. It will just wait to be freed eventually.\n\t */\n\tif (!queue->ops)\n\t\treturn;\n\n\tblock->state = IIO_BLOCK_STATE_ACTIVE;\n\tiio_buffer_block_get(block);\n\tret = queue->ops->submit(queue, block);\n\tif (ret) {\n\t\t/*\n\t\t * This is a bit of a problem and there is not much we can do\n\t\t * other then wait for the buffer to be disabled and re-enabled\n\t\t * and try again. But it should not really happen unless we run\n\t\t * out of memory or something similar.\n\t\t *\n\t\t * TODO: Implement support in the IIO core to allow buffers to\n\t\t * notify consumers that something went wrong and the buffer\n\t\t * should be disabled.\n\t\t */\n\t\tiio_buffer_block_put(block);\n\t}\n}\n\n/**\n * iio_dma_buffer_enable() - Enable DMA buffer\n * @buffer: IIO buffer to enable\n * @indio_dev: IIO device the buffer is attached to\n *\n * Needs to be called when the device that the buffer is attached to starts\n * sampling. Typically should be the iio_buffer_access_ops enable callback.\n *\n * This will allocate the DMA buffers and start the DMA transfers.\n */\nint iio_dma_buffer_enable(struct iio_buffer *buffer,\n\tstruct iio_dev *indio_dev)\n{\n\tstruct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);\n\tstruct iio_dma_buffer_block *block, *_block;\n\n\tmutex_lock(&queue->lock);\n\tqueue->active = true;\n\tlist_for_each_entry_safe(block, _block, &queue->incoming, head) {\n\t\tlist_del(&block->head);\n\t\tiio_dma_buffer_submit_block(queue, block);\n\t}\n\tmutex_unlock(&queue->lock);\n\n\treturn 0;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_enable);\n\n/**\n * iio_dma_buffer_disable() - Disable DMA buffer\n * @buffer: IIO DMA buffer to disable\n * @indio_dev: IIO device the buffer is attached to\n *\n * Needs to be called when the device that the buffer is attached to stops\n * sampling. Typically should be the iio_buffer_access_ops disable callback.\n */\nint iio_dma_buffer_disable(struct iio_buffer *buffer,\n\tstruct iio_dev *indio_dev)\n{\n\tstruct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);\n\n\tmutex_lock(&queue->lock);\n\tqueue->active = false;\n\n\tif (queue->ops && queue->ops->abort)\n\t\tqueue->ops->abort(queue);\n\tmutex_unlock(&queue->lock);\n\n\treturn 0;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_disable);\n\nstatic void iio_dma_buffer_enqueue(struct iio_dma_buffer_queue *queue,\n\tstruct iio_dma_buffer_block *block)\n{\n\tif (block->state == IIO_BLOCK_STATE_DEAD) {\n\t\tiio_buffer_block_put(block);\n\t} else if (queue->active) {\n\t\tiio_dma_buffer_submit_block(queue, block);\n\t} else {\n\t\tblock->state = IIO_BLOCK_STATE_QUEUED;\n\t\tlist_add_tail(&block->head, &queue->incoming);\n\t}\n}\n\nstatic struct iio_dma_buffer_block *iio_dma_buffer_dequeue(\n\tstruct iio_dma_buffer_queue *queue)\n{\n\tstruct iio_dma_buffer_block *block;\n\n\tspin_lock_irq(&queue->list_lock);\n\tblock = list_first_entry_or_null(&queue->outgoing, struct\n\t\tiio_dma_buffer_block, head);\n\tif (block != NULL) {\n\t\tlist_del(&block->head);\n\t\tblock->state = IIO_BLOCK_STATE_DEQUEUED;\n\t}\n\tspin_unlock_irq(&queue->list_lock);\n\n\treturn block;\n}\n\n/**\n * iio_dma_buffer_read() - DMA buffer read callback\n * @buffer: Buffer to read form\n * @n: Number of bytes to read\n * @user_buffer: Userspace buffer to copy the data to\n *\n * Should be used as the read callback for iio_buffer_access_ops\n * struct for DMA buffers.\n */\nint iio_dma_buffer_read(struct iio_buffer *buffer, size_t n,\n\tchar __user *user_buffer)\n{\n\tstruct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);\n\tstruct iio_dma_buffer_block *block;\n\tint ret;\n\n\tif (n < buffer->bytes_per_datum)\n\t\treturn -EINVAL;\n\n\tmutex_lock(&queue->lock);\n\n\tif (!queue->fileio.active_block) {\n\t\tblock = iio_dma_buffer_dequeue(queue);\n\t\tif (block == NULL) {\n\t\t\tret = 0;\n\t\t\tgoto out_unlock;\n\t\t}\n\t\tqueue->fileio.pos = 0;\n\t\tqueue->fileio.active_block = block;\n\t} else {\n\t\tblock = queue->fileio.active_block;\n\t}\n\n\tn = rounddown(n, buffer->bytes_per_datum);\n\tif (n > block->bytes_used - queue->fileio.pos)\n\t\tn = block->bytes_used - queue->fileio.pos;\n\n\tif (copy_to_user(user_buffer, block->vaddr + queue->fileio.pos, n)) {\n\t\tret = -EFAULT;\n\t\tgoto out_unlock;\n\t}\n\n\tqueue->fileio.pos += n;\n\n\tif (queue->fileio.pos == block->bytes_used) {\n\t\tqueue->fileio.active_block = NULL;\n\t\tiio_dma_buffer_enqueue(queue, block);\n\t}\n\n\tret = n;\n\nout_unlock:\n\tmutex_unlock(&queue->lock);\n\n\treturn ret;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_read);\n\n/**\n * iio_dma_buffer_data_available() - DMA buffer data_available callback\n * @buf: Buffer to check for data availability\n *\n * Should be used as the data_available callback for iio_buffer_access_ops\n * struct for DMA buffers.\n */\nsize_t iio_dma_buffer_data_available(struct iio_buffer *buf)\n{\n\tstruct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buf);\n\tstruct iio_dma_buffer_block *block;\n\tsize_t data_available = 0;\n\n\t/*\n\t * For counting the available bytes we'll use the size of the block not\n\t * the number of actual bytes available in the block. Otherwise it is\n\t * possible that we end up with a value that is lower than the watermark\n\t * but won't increase since all blocks are in use.\n\t */\n\n\tmutex_lock(&queue->lock);\n\tif (queue->fileio.active_block)\n\t\tdata_available += queue->fileio.active_block->size;\n\n\tspin_lock_irq(&queue->list_lock);\n\tlist_for_each_entry(block, &queue->outgoing, head)\n\t\tdata_available += block->size;\n\tspin_unlock_irq(&queue->list_lock);\n\tmutex_unlock(&queue->lock);\n\n\treturn data_available;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_data_available);\n\n/**\n * iio_dma_buffer_set_bytes_per_datum() - DMA buffer set_bytes_per_datum callback\n * @buffer: Buffer to set the bytes-per-datum for\n * @bpd: The new bytes-per-datum value\n *\n * Should be used as the set_bytes_per_datum callback for iio_buffer_access_ops\n * struct for DMA buffers.\n */\nint iio_dma_buffer_set_bytes_per_datum(struct iio_buffer *buffer, size_t bpd)\n{\n\tbuffer->bytes_per_datum = bpd;\n\n\treturn 0;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_set_bytes_per_datum);\n\n/**\n * iio_dma_buffer_set_length - DMA buffer set_length callback\n * @buffer: Buffer to set the length for\n * @length: The new buffer length\n *\n * Should be used as the set_length callback for iio_buffer_access_ops\n * struct for DMA buffers.\n */\nint iio_dma_buffer_set_length(struct iio_buffer *buffer, unsigned int length)\n{\n\t/* Avoid an invalid state */\n\tif (length < 2)\n\t\tlength = 2;\n\tbuffer->length = length;\n\tbuffer->watermark = length / 2;\n\n\treturn 0;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_set_length);\n\n/**\n * iio_dma_buffer_init() - Initialize DMA buffer queue\n * @queue: Buffer to initialize\n * @dev: DMA device\n * @ops: DMA buffer queue callback operations\n *\n * The DMA device will be used by the queue to do DMA memory allocations. So it\n * should refer to the device that will perform the DMA to ensure that\n * allocations are done from a memory region that can be accessed by the device.\n */\nint iio_dma_buffer_init(struct iio_dma_buffer_queue *queue,\n\tstruct device *dev, const struct iio_dma_buffer_ops *ops)\n{\n\tiio_buffer_init(&queue->buffer);\n\tqueue->buffer.length = PAGE_SIZE;\n\tqueue->buffer.watermark = queue->buffer.length / 2;\n\tqueue->dev = dev;\n\tqueue->ops = ops;\n\n\tINIT_LIST_HEAD(&queue->incoming);\n\tINIT_LIST_HEAD(&queue->outgoing);\n\n\tmutex_init(&queue->lock);\n\tspin_lock_init(&queue->list_lock);\n\n\treturn 0;\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_init);\n\n/**\n * iio_dma_buffer_exit() - Cleanup DMA buffer queue\n * @queue: Buffer to cleanup\n *\n * After this function has completed it is safe to free any resources that are\n * associated with the buffer and are accessed inside the callback operations.\n */\nvoid iio_dma_buffer_exit(struct iio_dma_buffer_queue *queue)\n{\n\tunsigned int i;\n\n\tmutex_lock(&queue->lock);\n\n\tspin_lock_irq(&queue->list_lock);\n\tfor (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {\n\t\tif (!queue->fileio.blocks[i])\n\t\t\tcontinue;\n\t\tqueue->fileio.blocks[i]->state = IIO_BLOCK_STATE_DEAD;\n\t}\n\tINIT_LIST_HEAD(&queue->outgoing);\n\tspin_unlock_irq(&queue->list_lock);\n\n\tINIT_LIST_HEAD(&queue->incoming);\n\n\tfor (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {\n\t\tif (!queue->fileio.blocks[i])\n\t\t\tcontinue;\n\t\tiio_buffer_block_put(queue->fileio.blocks[i]);\n\t\tqueue->fileio.blocks[i] = NULL;\n\t}\n\tqueue->fileio.active_block = NULL;\n\tqueue->ops = NULL;\n\n\tmutex_unlock(&queue->lock);\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_exit);\n\n/**\n * iio_dma_buffer_release() - Release final buffer resources\n * @queue: Buffer to release\n *\n * Frees resources that can't yet be freed in iio_dma_buffer_exit(). Should be\n * called in the buffers release callback implementation right before freeing\n * the memory associated with the buffer.\n */\nvoid iio_dma_buffer_release(struct iio_dma_buffer_queue *queue)\n{\n\tmutex_destroy(&queue->lock);\n}\nEXPORT_SYMBOL_GPL(iio_dma_buffer_release);\n\nMODULE_AUTHOR(\"Lars-Peter Clausen \");\nMODULE_DESCRIPTION(\"DMA buffer for the IIO framework\");\nMODULE_LICENSE(\"GPL v2\");\n"},"repo_name":{"kind":"string","value":"c0d3z3r0/linux-rockchip"},"path":{"kind":"string","value":"drivers/iio/buffer/industrialio-buffer-dma.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":21128,"string":"21,128"}}},{"rowIdx":115086546,"cells":{"code":{"kind":"string","value":"/* ------------------------------------------------------------------\n * Copyright (C) 1998-2009 PacketVideo\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the License for the specific language governing permissions\n * and limitations under the License.\n * -------------------------------------------------------------------\n */\n/****************************************************************************************\nPortions of this file are derived from the following 3GPP standard:\n\n 3GPP TS 26.173\n ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec\n Available from http://www.3gpp.org\n\n(C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)\nPermission to distribute, modify and use this file under the standard license\nterms listed above has been obtained from the copyright holder.\n****************************************************************************************/\n#include \"qisf_ns.h\"\n\n\n/*\n * Tables for function q_gain2()\n *\n * g_pitch(Q14), g_code(Q11)\n *\n * pitch gain are ordered in table to reduce complexity\n * during quantization of gains.\n */\n\n\n\n\nconst int16 t_qua_gain6b[NB_QUA_GAIN6B*2] =\n{\n 1566, 1332,\n 1577, 3557,\n 3071, 6490,\n 4193, 10163,\n 4496, 2534,\n 5019, 4488,\n 5586, 15614,\n 5725, 1422,\n 6453, 580,\n 6724, 6831,\n 7657, 3527,\n 8072, 2099,\n 8232, 5319,\n 8827, 8775,\n 9740, 2868,\n 9856, 1465,\n 10087, 12488,\n 10241, 4453,\n 10859, 6618,\n 11321, 3587,\n 11417, 1800,\n 11643, 2428,\n 11718, 988,\n 12312, 5093,\n 12523, 8413,\n 12574, 26214,\n 12601, 3396,\n 13172, 1623,\n 13285, 2423,\n 13418, 6087,\n 13459, 12810,\n 13656, 3607,\n 14111, 4521,\n 14144, 1229,\n 14425, 1871,\n 14431, 7234,\n 14445, 2834,\n 14628, 10036,\n 14860, 17496,\n 15161, 3629,\n 15209, 5819,\n 15299, 2256,\n 15518, 4722,\n 15663, 1060,\n 15759, 7972,\n 15939, 11964,\n 16020, 2996,\n 16086, 1707,\n 16521, 4254,\n 16576, 6224,\n 16894, 2380,\n 16906, 681,\n 17213, 8406,\n 17610, 3418,\n 17895, 5269,\n 18168, 11748,\n 18230, 1575,\n 18607, 32767,\n 18728, 21684,\n 19137, 2543,\n 19422, 6577,\n 19446, 4097,\n 19450, 9056,\n 20371, 14885\n};\n\nconst int16 t_qua_gain7b[NB_QUA_GAIN7B*2] =\n{\n 204, 441,\n 464, 1977,\n 869, 1077,\n 1072, 3062,\n 1281, 4759,\n 1647, 1539,\n 1845, 7020,\n 1853, 634,\n 1995, 2336,\n 2351, 15400,\n 2661, 1165,\n 2702, 3900,\n 2710, 10133,\n 3195, 1752,\n 3498, 2624,\n 3663, 849,\n 3984, 5697,\n 4214, 3399,\n 4415, 1304,\n 4695, 2056,\n 5376, 4558,\n 5386, 676,\n 5518, 23554,\n 5567, 7794,\n 5644, 3061,\n 5672, 1513,\n 5957, 2338,\n 6533, 1060,\n 6804, 5998,\n 6820, 1767,\n 6937, 3837,\n 7277, 414,\n 7305, 2665,\n 7466, 11304,\n 7942, 794,\n 8007, 1982,\n 8007, 1366,\n 8326, 3105,\n 8336, 4810,\n 8708, 7954,\n 8989, 2279,\n 9031, 1055,\n 9247, 3568,\n 9283, 1631,\n 9654, 6311,\n 9811, 2605,\n 10120, 683,\n 10143, 4179,\n 10245, 1946,\n 10335, 1218,\n 10468, 9960,\n 10651, 3000,\n 10951, 1530,\n 10969, 5290,\n 11203, 2305,\n 11325, 3562,\n 11771, 6754,\n 11839, 1849,\n 11941, 4495,\n 11954, 1298,\n 11975, 15223,\n 11977, 883,\n 11986, 2842,\n 12438, 2141,\n 12593, 3665,\n 12636, 8367,\n 12658, 1594,\n 12886, 2628,\n 12984, 4942,\n 13146, 1115,\n 13224, 524,\n 13341, 3163,\n 13399, 1923,\n 13549, 5961,\n 13606, 1401,\n 13655, 2399,\n 13782, 3909,\n 13868, 10923,\n 14226, 1723,\n 14232, 2939,\n 14278, 7528,\n 14439, 4598,\n 14451, 984,\n 14458, 2265,\n 14792, 1403,\n 14818, 3445,\n 14899, 5709,\n 15017, 15362,\n 15048, 1946,\n 15069, 2655,\n 15405, 9591,\n 15405, 4079,\n 15570, 7183,\n 15687, 2286,\n 15691, 1624,\n 15699, 3068,\n 15772, 5149,\n 15868, 1205,\n 15970, 696,\n 16249, 3584,\n 16338, 1917,\n 16424, 2560,\n 16483, 4438,\n 16529, 6410,\n 16620, 11966,\n 16839, 8780,\n 17030, 3050,\n 17033, 18325,\n 17092, 1568,\n 17123, 5197,\n 17351, 2113,\n 17374, 980,\n 17566, 26214,\n 17609, 3912,\n 17639, 32767,\n 18151, 7871,\n 18197, 2516,\n 18202, 5649,\n 18679, 3283,\n 18930, 1370,\n 19271, 13757,\n 19317, 4120,\n 19460, 1973,\n 19654, 10018,\n 19764, 6792,\n 19912, 5135,\n 20040, 2841,\n 21234, 19833\n};\n\n\n"},"repo_name":{"kind":"string","value":"raj-bhatia/grooveip-ios-public"},"path":{"kind":"string","value":"submodules/externals/opencore-amr/opencore/codecs_v2/audio/gsm_amr/amr_wb/dec/src/q_gain2_tab.cpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":5030,"string":"5,030"}}},{"rowIdx":115086547,"cells":{"code":{"kind":"string","value":"// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * PowerPC version \n * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org)\n *\n * Derived from \"arch/i386/kernel/signal.c\"\n * Copyright (C) 1991, 1992 Linus Torvalds\n * 1997-11-28 Modified for POSIX.1b signals by Richard Henderson\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"signal.h\"\n\n\n#define GP_REGS_SIZE\tmin(sizeof(elf_gregset_t), sizeof(struct pt_regs))\n#define FP_REGS_SIZE\tsizeof(elf_fpregset_t)\n\n#define TRAMP_TRACEBACK\t4\n#define TRAMP_SIZE\t7\n\n/*\n * When we have signals to deliver, we set up on the user stack,\n * going down from the original stack pointer:\n *\t1) a rt_sigframe struct which contains the ucontext\t\n *\t2) a gap of __SIGNAL_FRAMESIZE bytes which acts as a dummy caller\n *\t frame for the signal handler.\n */\n\nstruct rt_sigframe {\n\t/* sys_rt_sigreturn requires the ucontext be the first field */\n\tstruct ucontext uc;\n#ifdef CONFIG_PPC_TRANSACTIONAL_MEM\n\tstruct ucontext uc_transact;\n#endif\n\tunsigned long _unused[2];\n\tunsigned int tramp[TRAMP_SIZE];\n\tstruct siginfo __user *pinfo;\n\tvoid __user *puc;\n\tstruct siginfo info;\n\t/* New 64 bit little-endian ABI allows redzone of 512 bytes below sp */\n\tchar abigap[USER_REDZONE_SIZE];\n} __attribute__ ((aligned (16)));\n\n/*\n * This computes a quad word aligned pointer inside the vmx_reserve array\n * element. For historical reasons sigcontext might not be quad word aligned,\n * but the location we write the VMX regs to must be. See the comment in\n * sigcontext for more detail.\n */\n#ifdef CONFIG_ALTIVEC\nstatic elf_vrreg_t __user *sigcontext_vmx_regs(struct sigcontext __user *sc)\n{\n\treturn (elf_vrreg_t __user *) (((unsigned long)sc->vmx_reserve + 15) & ~0xful);\n}\n#endif\n\nstatic void prepare_setup_sigcontext(struct task_struct *tsk)\n{\n#ifdef CONFIG_ALTIVEC\n\t/* save altivec registers */\n\tif (tsk->thread.used_vr)\n\t\tflush_altivec_to_thread(tsk);\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\ttsk->thread.vrsave = mfspr(SPRN_VRSAVE);\n#endif /* CONFIG_ALTIVEC */\n\n\tflush_fp_to_thread(tsk);\n\n#ifdef CONFIG_VSX\n\tif (tsk->thread.used_vsr)\n\t\tflush_vsx_to_thread(tsk);\n#endif /* CONFIG_VSX */\n}\n\n/*\n * Set up the sigcontext for the signal frame.\n */\n\n#define unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region, label)\\\ndo {\t\t\t\t\t\t\t\t\t\t\t\\\n\tif (__unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region))\\\n\t\tgoto label;\t\t\t\t\t\t\t\t\\\n} while (0)\nstatic long notrace __unsafe_setup_sigcontext(struct sigcontext __user *sc,\n\t\t\t\t\tstruct task_struct *tsk, int signr, sigset_t *set,\n\t\t\t\t\tunsigned long handler, int ctx_has_vsx_region)\n{\n\t/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the\n\t * process never used altivec yet (MSR_VEC is zero in pt_regs of\n\t * the context). This is very important because we must ensure we\n\t * don't lose the VRSAVE content that may have been set prior to\n\t * the process doing its first vector operation\n\t * Userland shall check AT_HWCAP to know whether it can rely on the\n\t * v_regs pointer or not\n\t */\n#ifdef CONFIG_ALTIVEC\n\telf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);\n#endif\n\tstruct pt_regs *regs = tsk->thread.regs;\n\tunsigned long msr = regs->msr;\n\t/* Force usr to alway see softe as 1 (interrupts enabled) */\n\tunsigned long softe = 0x1;\n\n\tBUG_ON(tsk != current);\n\n#ifdef CONFIG_ALTIVEC\n\tunsafe_put_user(v_regs, &sc->v_regs, efault_out);\n\n\t/* save altivec registers */\n\tif (tsk->thread.used_vr) {\n\t\t/* Copy 33 vec registers (vr0..31 and vscr) to the stack */\n\t\tunsafe_copy_to_user(v_regs, &tsk->thread.vr_state,\n\t\t\t\t 33 * sizeof(vector128), efault_out);\n\t\t/* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg)\n\t\t * contains valid data.\n\t\t */\n\t\tmsr |= MSR_VEC;\n\t}\n\t/* We always copy to/from vrsave, it's 0 if we don't have or don't\n\t * use altivec.\n\t */\n\tunsafe_put_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out);\n#else /* CONFIG_ALTIVEC */\n\tunsafe_put_user(0, &sc->v_regs, efault_out);\n#endif /* CONFIG_ALTIVEC */\n\t/* copy fpr regs and fpscr */\n\tunsafe_copy_fpr_to_user(&sc->fp_regs, tsk, efault_out);\n\n\t/*\n\t * Clear the MSR VSX bit to indicate there is no valid state attached\n\t * to this context, except in the specific case below where we set it.\n\t */\n\tmsr &= ~MSR_VSX;\n#ifdef CONFIG_VSX\n\t/*\n\t * Copy VSX low doubleword to local buffer for formatting,\n\t * then out to userspace. Update v_regs to point after the\n\t * VMX data.\n\t */\n\tif (tsk->thread.used_vsr && ctx_has_vsx_region) {\n\t\tv_regs += ELF_NVRREG;\n\t\tunsafe_copy_vsx_to_user(v_regs, tsk, efault_out);\n\t\t/* set MSR_VSX in the MSR value in the frame to\n\t\t * indicate that sc->vs_reg) contains valid data.\n\t\t */\n\t\tmsr |= MSR_VSX;\n\t}\n#endif /* CONFIG_VSX */\n\tunsafe_put_user(&sc->gp_regs, &sc->regs, efault_out);\n\tunsafe_copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE, efault_out);\n\tunsafe_put_user(msr, &sc->gp_regs[PT_MSR], efault_out);\n\tunsafe_put_user(softe, &sc->gp_regs[PT_SOFTE], efault_out);\n\tunsafe_put_user(signr, &sc->signal, efault_out);\n\tunsafe_put_user(handler, &sc->handler, efault_out);\n\tif (set != NULL)\n\t\tunsafe_put_user(set->sig[0], &sc->oldmask, efault_out);\n\n\treturn 0;\n\nefault_out:\n\treturn -EFAULT;\n}\n\n#ifdef CONFIG_PPC_TRANSACTIONAL_MEM\n/*\n * As above, but Transactional Memory is in use, so deliver sigcontexts\n * containing checkpointed and transactional register states.\n *\n * To do this, we treclaim (done before entering here) to gather both sets of\n * registers and set up the 'normal' sigcontext registers with rolled-back\n * register values such that a simple signal handler sees a correct\n * checkpointed register state. If interested, a TM-aware sighandler can\n * examine the transactional registers in the 2nd sigcontext to determine the\n * real origin of the signal.\n */\nstatic long setup_tm_sigcontexts(struct sigcontext __user *sc,\n\t\t\t\t struct sigcontext __user *tm_sc,\n\t\t\t\t struct task_struct *tsk,\n\t\t\t\t int signr, sigset_t *set, unsigned long handler,\n\t\t\t\t unsigned long msr)\n{\n\t/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the\n\t * process never used altivec yet (MSR_VEC is zero in pt_regs of\n\t * the context). This is very important because we must ensure we\n\t * don't lose the VRSAVE content that may have been set prior to\n\t * the process doing its first vector operation\n\t * Userland shall check AT_HWCAP to know wether it can rely on the\n\t * v_regs pointer or not.\n\t */\n#ifdef CONFIG_ALTIVEC\n\telf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);\n\telf_vrreg_t __user *tm_v_regs = sigcontext_vmx_regs(tm_sc);\n#endif\n\tstruct pt_regs *regs = tsk->thread.regs;\n\tlong err = 0;\n\n\tBUG_ON(tsk != current);\n\n\tBUG_ON(!MSR_TM_ACTIVE(msr));\n\n\tWARN_ON(tm_suspend_disabled);\n\n\t/* Restore checkpointed FP, VEC, and VSX bits from ckpt_regs as\n\t * it contains the correct FP, VEC, VSX state after we treclaimed\n\t * the transaction and giveup_all() was called on reclaiming.\n\t */\n\tmsr |= tsk->thread.ckpt_regs.msr & (MSR_FP | MSR_VEC | MSR_VSX);\n\n#ifdef CONFIG_ALTIVEC\n\terr |= __put_user(v_regs, &sc->v_regs);\n\terr |= __put_user(tm_v_regs, &tm_sc->v_regs);\n\n\t/* save altivec registers */\n\tif (tsk->thread.used_vr) {\n\t\t/* Copy 33 vec registers (vr0..31 and vscr) to the stack */\n\t\terr |= __copy_to_user(v_regs, &tsk->thread.ckvr_state,\n\t\t\t\t 33 * sizeof(vector128));\n\t\t/* If VEC was enabled there are transactional VRs valid too,\n\t\t * else they're a copy of the checkpointed VRs.\n\t\t */\n\t\tif (msr & MSR_VEC)\n\t\t\terr |= __copy_to_user(tm_v_regs,\n\t\t\t\t\t &tsk->thread.vr_state,\n\t\t\t\t\t 33 * sizeof(vector128));\n\t\telse\n\t\t\terr |= __copy_to_user(tm_v_regs,\n\t\t\t\t\t &tsk->thread.ckvr_state,\n\t\t\t\t\t 33 * sizeof(vector128));\n\n\t\t/* set MSR_VEC in the MSR value in the frame to indicate\n\t\t * that sc->v_reg contains valid data.\n\t\t */\n\t\tmsr |= MSR_VEC;\n\t}\n\t/* We always copy to/from vrsave, it's 0 if we don't have or don't\n\t * use altivec.\n\t */\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\ttsk->thread.ckvrsave = mfspr(SPRN_VRSAVE);\n\terr |= __put_user(tsk->thread.ckvrsave, (u32 __user *)&v_regs[33]);\n\tif (msr & MSR_VEC)\n\t\terr |= __put_user(tsk->thread.vrsave,\n\t\t\t\t (u32 __user *)&tm_v_regs[33]);\n\telse\n\t\terr |= __put_user(tsk->thread.ckvrsave,\n\t\t\t\t (u32 __user *)&tm_v_regs[33]);\n\n#else /* CONFIG_ALTIVEC */\n\terr |= __put_user(0, &sc->v_regs);\n\terr |= __put_user(0, &tm_sc->v_regs);\n#endif /* CONFIG_ALTIVEC */\n\n\t/* copy fpr regs and fpscr */\n\terr |= copy_ckfpr_to_user(&sc->fp_regs, tsk);\n\tif (msr & MSR_FP)\n\t\terr |= copy_fpr_to_user(&tm_sc->fp_regs, tsk);\n\telse\n\t\terr |= copy_ckfpr_to_user(&tm_sc->fp_regs, tsk);\n\n#ifdef CONFIG_VSX\n\t/*\n\t * Copy VSX low doubleword to local buffer for formatting,\n\t * then out to userspace. Update v_regs to point after the\n\t * VMX data.\n\t */\n\tif (tsk->thread.used_vsr) {\n\t\tv_regs += ELF_NVRREG;\n\t\ttm_v_regs += ELF_NVRREG;\n\n\t\terr |= copy_ckvsx_to_user(v_regs, tsk);\n\n\t\tif (msr & MSR_VSX)\n\t\t\terr |= copy_vsx_to_user(tm_v_regs, tsk);\n\t\telse\n\t\t\terr |= copy_ckvsx_to_user(tm_v_regs, tsk);\n\n\t\t/* set MSR_VSX in the MSR value in the frame to\n\t\t * indicate that sc->vs_reg) contains valid data.\n\t\t */\n\t\tmsr |= MSR_VSX;\n\t}\n#endif /* CONFIG_VSX */\n\n\terr |= __put_user(&sc->gp_regs, &sc->regs);\n\terr |= __put_user(&tm_sc->gp_regs, &tm_sc->regs);\n\terr |= __copy_to_user(&tm_sc->gp_regs, regs, GP_REGS_SIZE);\n\terr |= __copy_to_user(&sc->gp_regs,\n\t\t\t &tsk->thread.ckpt_regs, GP_REGS_SIZE);\n\terr |= __put_user(msr, &tm_sc->gp_regs[PT_MSR]);\n\terr |= __put_user(msr, &sc->gp_regs[PT_MSR]);\n\terr |= __put_user(signr, &sc->signal);\n\terr |= __put_user(handler, &sc->handler);\n\tif (set != NULL)\n\t\terr |= __put_user(set->sig[0], &sc->oldmask);\n\n\treturn err;\n}\n#endif\n\n/*\n * Restore the sigcontext from the signal frame.\n */\n#define unsafe_restore_sigcontext(tsk, set, sig, sc, label) do {\t\\\n\tif (__unsafe_restore_sigcontext(tsk, set, sig, sc))\t\t\\\n\t\tgoto label;\t\t\t\t\t\t\\\n} while (0)\nstatic long notrace __unsafe_restore_sigcontext(struct task_struct *tsk, sigset_t *set,\n\t\t\t\t\t\tint sig, struct sigcontext __user *sc)\n{\n#ifdef CONFIG_ALTIVEC\n\telf_vrreg_t __user *v_regs;\n#endif\n\tunsigned long save_r13 = 0;\n\tunsigned long msr;\n\tstruct pt_regs *regs = tsk->thread.regs;\n#ifdef CONFIG_VSX\n\tint i;\n#endif\n\n\tBUG_ON(tsk != current);\n\n\t/* If this is not a signal return, we preserve the TLS in r13 */\n\tif (!sig)\n\t\tsave_r13 = regs->gpr[13];\n\n\t/* copy the GPRs */\n\tunsafe_copy_from_user(regs->gpr, sc->gp_regs, sizeof(regs->gpr), efault_out);\n\tunsafe_get_user(regs->nip, &sc->gp_regs[PT_NIP], efault_out);\n\t/* get MSR separately, transfer the LE bit if doing signal return */\n\tunsafe_get_user(msr, &sc->gp_regs[PT_MSR], efault_out);\n\tif (sig)\n\t\tregs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE));\n\tunsafe_get_user(regs->orig_gpr3, &sc->gp_regs[PT_ORIG_R3], efault_out);\n\tunsafe_get_user(regs->ctr, &sc->gp_regs[PT_CTR], efault_out);\n\tunsafe_get_user(regs->link, &sc->gp_regs[PT_LNK], efault_out);\n\tunsafe_get_user(regs->xer, &sc->gp_regs[PT_XER], efault_out);\n\tunsafe_get_user(regs->ccr, &sc->gp_regs[PT_CCR], efault_out);\n\t/* Don't allow userspace to set SOFTE */\n\tset_trap_norestart(regs);\n\tunsafe_get_user(regs->dar, &sc->gp_regs[PT_DAR], efault_out);\n\tunsafe_get_user(regs->dsisr, &sc->gp_regs[PT_DSISR], efault_out);\n\tunsafe_get_user(regs->result, &sc->gp_regs[PT_RESULT], efault_out);\n\n\tif (!sig)\n\t\tregs->gpr[13] = save_r13;\n\tif (set != NULL)\n\t\tunsafe_get_user(set->sig[0], &sc->oldmask, efault_out);\n\n\t/*\n\t * Force reload of FP/VEC.\n\t * This has to be done before copying stuff into tsk->thread.fpr/vr\n\t * for the reasons explained in the previous comment.\n\t */\n\tregs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX));\n\n#ifdef CONFIG_ALTIVEC\n\tunsafe_get_user(v_regs, &sc->v_regs, efault_out);\n\tif (v_regs && !access_ok(v_regs, 34 * sizeof(vector128)))\n\t\treturn -EFAULT;\n\t/* Copy 33 vec registers (vr0..31 and vscr) from the stack */\n\tif (v_regs != NULL && (msr & MSR_VEC) != 0) {\n\t\tunsafe_copy_from_user(&tsk->thread.vr_state, v_regs,\n\t\t\t\t 33 * sizeof(vector128), efault_out);\n\t\ttsk->thread.used_vr = true;\n\t} else if (tsk->thread.used_vr) {\n\t\tmemset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128));\n\t}\n\t/* Always get VRSAVE back */\n\tif (v_regs != NULL)\n\t\tunsafe_get_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out);\n\telse\n\t\ttsk->thread.vrsave = 0;\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\tmtspr(SPRN_VRSAVE, tsk->thread.vrsave);\n#endif /* CONFIG_ALTIVEC */\n\t/* restore floating point */\n\tunsafe_copy_fpr_from_user(tsk, &sc->fp_regs, efault_out);\n#ifdef CONFIG_VSX\n\t/*\n\t * Get additional VSX data. Update v_regs to point after the\n\t * VMX data. Copy VSX low doubleword from userspace to local\n\t * buffer for formatting, then into the taskstruct.\n\t */\n\tv_regs += ELF_NVRREG;\n\tif ((msr & MSR_VSX) != 0) {\n\t\tunsafe_copy_vsx_from_user(tsk, v_regs, efault_out);\n\t\ttsk->thread.used_vsr = true;\n\t} else {\n\t\tfor (i = 0; i < 32 ; i++)\n\t\t\ttsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t}\n#endif\n\treturn 0;\n\nefault_out:\n\treturn -EFAULT;\n}\n\n#ifdef CONFIG_PPC_TRANSACTIONAL_MEM\n/*\n * Restore the two sigcontexts from the frame of a transactional processes.\n */\n\nstatic long restore_tm_sigcontexts(struct task_struct *tsk,\n\t\t\t\t struct sigcontext __user *sc,\n\t\t\t\t struct sigcontext __user *tm_sc)\n{\n#ifdef CONFIG_ALTIVEC\n\telf_vrreg_t __user *v_regs, *tm_v_regs;\n#endif\n\tunsigned long err = 0;\n\tunsigned long msr;\n\tstruct pt_regs *regs = tsk->thread.regs;\n#ifdef CONFIG_VSX\n\tint i;\n#endif\n\n\tBUG_ON(tsk != current);\n\n\tif (tm_suspend_disabled)\n\t\treturn -EINVAL;\n\n\t/* copy the GPRs */\n\terr |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));\n\terr |= __copy_from_user(&tsk->thread.ckpt_regs, sc->gp_regs,\n\t\t\t\tsizeof(regs->gpr));\n\n\t/*\n\t * TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.\n\t * TEXASR was set by the signal delivery reclaim, as was TFIAR.\n\t * Users doing anything abhorrent like thread-switching w/ signals for\n\t * TM-Suspended code will have to back TEXASR/TFIAR up themselves.\n\t * For the case of getting a signal and simply returning from it,\n\t * we don't need to re-copy them here.\n\t */\n\terr |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);\n\terr |= __get_user(tsk->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);\n\n\t/* get MSR separately, transfer the LE bit if doing signal return */\n\terr |= __get_user(msr, &sc->gp_regs[PT_MSR]);\n\t/* Don't allow reserved mode. */\n\tif (MSR_TM_RESV(msr))\n\t\treturn -EINVAL;\n\n\t/* pull in MSR LE from user context */\n\tregs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE));\n\n\t/* The following non-GPR non-FPR non-VR state is also checkpointed: */\n\terr |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);\n\terr |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);\n\terr |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);\n\terr |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);\n\terr |= __get_user(tsk->thread.ckpt_regs.ctr,\n\t\t\t &sc->gp_regs[PT_CTR]);\n\terr |= __get_user(tsk->thread.ckpt_regs.link,\n\t\t\t &sc->gp_regs[PT_LNK]);\n\terr |= __get_user(tsk->thread.ckpt_regs.xer,\n\t\t\t &sc->gp_regs[PT_XER]);\n\terr |= __get_user(tsk->thread.ckpt_regs.ccr,\n\t\t\t &sc->gp_regs[PT_CCR]);\n\t/* Don't allow userspace to set SOFTE */\n\tset_trap_norestart(regs);\n\t/* These regs are not checkpointed; they can go in 'regs'. */\n\terr |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);\n\terr |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);\n\terr |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);\n\n\t/*\n\t * Force reload of FP/VEC.\n\t * This has to be done before copying stuff into tsk->thread.fpr/vr\n\t * for the reasons explained in the previous comment.\n\t */\n\tregs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX));\n\n#ifdef CONFIG_ALTIVEC\n\terr |= __get_user(v_regs, &sc->v_regs);\n\terr |= __get_user(tm_v_regs, &tm_sc->v_regs);\n\tif (err)\n\t\treturn err;\n\tif (v_regs && !access_ok(v_regs, 34 * sizeof(vector128)))\n\t\treturn -EFAULT;\n\tif (tm_v_regs && !access_ok(tm_v_regs, 34 * sizeof(vector128)))\n\t\treturn -EFAULT;\n\t/* Copy 33 vec registers (vr0..31 and vscr) from the stack */\n\tif (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {\n\t\terr |= __copy_from_user(&tsk->thread.ckvr_state, v_regs,\n\t\t\t\t\t33 * sizeof(vector128));\n\t\terr |= __copy_from_user(&tsk->thread.vr_state, tm_v_regs,\n\t\t\t\t\t33 * sizeof(vector128));\n\t\tcurrent->thread.used_vr = true;\n\t}\n\telse if (tsk->thread.used_vr) {\n\t\tmemset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128));\n\t\tmemset(&tsk->thread.ckvr_state, 0, 33 * sizeof(vector128));\n\t}\n\t/* Always get VRSAVE back */\n\tif (v_regs != NULL && tm_v_regs != NULL) {\n\t\terr |= __get_user(tsk->thread.ckvrsave,\n\t\t\t\t (u32 __user *)&v_regs[33]);\n\t\terr |= __get_user(tsk->thread.vrsave,\n\t\t\t\t (u32 __user *)&tm_v_regs[33]);\n\t}\n\telse {\n\t\ttsk->thread.vrsave = 0;\n\t\ttsk->thread.ckvrsave = 0;\n\t}\n\tif (cpu_has_feature(CPU_FTR_ALTIVEC))\n\t\tmtspr(SPRN_VRSAVE, tsk->thread.vrsave);\n#endif /* CONFIG_ALTIVEC */\n\t/* restore floating point */\n\terr |= copy_fpr_from_user(tsk, &tm_sc->fp_regs);\n\terr |= copy_ckfpr_from_user(tsk, &sc->fp_regs);\n#ifdef CONFIG_VSX\n\t/*\n\t * Get additional VSX data. Update v_regs to point after the\n\t * VMX data. Copy VSX low doubleword from userspace to local\n\t * buffer for formatting, then into the taskstruct.\n\t */\n\tif (v_regs && ((msr & MSR_VSX) != 0)) {\n\t\tv_regs += ELF_NVRREG;\n\t\ttm_v_regs += ELF_NVRREG;\n\t\terr |= copy_vsx_from_user(tsk, tm_v_regs);\n\t\terr |= copy_ckvsx_from_user(tsk, v_regs);\n\t\ttsk->thread.used_vsr = true;\n\t} else {\n\t\tfor (i = 0; i < 32 ; i++) {\n\t\t\ttsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t\ttsk->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET] = 0;\n\t\t}\n\t}\n#endif\n\ttm_enable();\n\t/* Make sure the transaction is marked as failed */\n\ttsk->thread.tm_texasr |= TEXASR_FS;\n\n\t/*\n\t * Disabling preemption, since it is unsafe to be preempted\n\t * with MSR[TS] set without recheckpointing.\n\t */\n\tpreempt_disable();\n\n\t/* pull in MSR TS bits from user context */\n\tregs_set_return_msr(regs, regs->msr | (msr & MSR_TS_MASK));\n\n\t/*\n\t * Ensure that TM is enabled in regs->msr before we leave the signal\n\t * handler. It could be the case that (a) user disabled the TM bit\n\t * through the manipulation of the MSR bits in uc_mcontext or (b) the\n\t * TM bit was disabled because a sufficient number of context switches\n\t * happened whilst in the signal handler and load_tm overflowed,\n\t * disabling the TM bit. In either case we can end up with an illegal\n\t * TM state leading to a TM Bad Thing when we return to userspace.\n\t *\n\t * CAUTION:\n\t * After regs->MSR[TS] being updated, make sure that get_user(),\n\t * put_user() or similar functions are *not* called. These\n\t * functions can generate page faults which will cause the process\n\t * to be de-scheduled with MSR[TS] set but without calling\n\t * tm_recheckpoint(). This can cause a bug.\n\t */\n\tregs_set_return_msr(regs, regs->msr | MSR_TM);\n\n\t/* This loads the checkpointed FP/VEC state, if used */\n\ttm_recheckpoint(&tsk->thread);\n\n\tmsr_check_and_set(msr & (MSR_FP | MSR_VEC));\n\tif (msr & MSR_FP) {\n\t\tload_fp_state(&tsk->thread.fp_state);\n\t\tregs_set_return_msr(regs, regs->msr | (MSR_FP | tsk->thread.fpexc_mode));\n\t}\n\tif (msr & MSR_VEC) {\n\t\tload_vr_state(&tsk->thread.vr_state);\n\t\tregs_set_return_msr(regs, regs->msr | MSR_VEC);\n\t}\n\n\tpreempt_enable();\n\n\treturn err;\n}\n#else /* !CONFIG_PPC_TRANSACTIONAL_MEM */\nstatic long restore_tm_sigcontexts(struct task_struct *tsk, struct sigcontext __user *sc,\n\t\t\t\t struct sigcontext __user *tm_sc)\n{\n\treturn -EINVAL;\n}\n#endif\n\n/*\n * Setup the trampoline code on the stack\n */\nstatic long setup_trampoline(unsigned int syscall, unsigned int __user *tramp)\n{\n\tint i;\n\tlong err = 0;\n\n\t/* Call the handler and pop the dummy stackframe*/\n\terr |= __put_user(PPC_RAW_BCTRL(), &tramp[0]);\n\terr |= __put_user(PPC_RAW_ADDI(_R1, _R1, __SIGNAL_FRAMESIZE), &tramp[1]);\n\n\terr |= __put_user(PPC_RAW_LI(_R0, syscall), &tramp[2]);\n\terr |= __put_user(PPC_RAW_SC(), &tramp[3]);\n\n\t/* Minimal traceback info */\n\tfor (i=TRAMP_TRACEBACK; i < TRAMP_SIZE ;i++)\n\t\terr |= __put_user(0, &tramp[i]);\n\n\tif (!err)\n\t\tflush_icache_range((unsigned long) &tramp[0],\n\t\t\t (unsigned long) &tramp[TRAMP_SIZE]);\n\n\treturn err;\n}\n\n/*\n * Userspace code may pass a ucontext which doesn't include VSX added\n * at the end. We need to check for this case.\n */\n#define UCONTEXTSIZEWITHOUTVSX \\\n\t\t(sizeof(struct ucontext) - 32*sizeof(long))\n\n/*\n * Handle {get,set,swap}_context operations\n */\nSYSCALL_DEFINE3(swapcontext, struct ucontext __user *, old_ctx,\n\t\tstruct ucontext __user *, new_ctx, long, ctx_size)\n{\n\tsigset_t set;\n\tunsigned long new_msr = 0;\n\tint ctx_has_vsx_region = 0;\n\n\tif (new_ctx &&\n\t get_user(new_msr, &new_ctx->uc_mcontext.gp_regs[PT_MSR]))\n\t\treturn -EFAULT;\n\t/*\n\t * Check that the context is not smaller than the original\n\t * size (with VMX but without VSX)\n\t */\n\tif (ctx_size < UCONTEXTSIZEWITHOUTVSX)\n\t\treturn -EINVAL;\n\t/*\n\t * If the new context state sets the MSR VSX bits but\n\t * it doesn't provide VSX state.\n\t */\n\tif ((ctx_size < sizeof(struct ucontext)) &&\n\t (new_msr & MSR_VSX))\n\t\treturn -EINVAL;\n\t/* Does the context have enough room to store VSX data? */\n\tif (ctx_size >= sizeof(struct ucontext))\n\t\tctx_has_vsx_region = 1;\n\n\tif (old_ctx != NULL) {\n\t\tprepare_setup_sigcontext(current);\n\t\tif (!user_write_access_begin(old_ctx, ctx_size))\n\t\t\treturn -EFAULT;\n\n\t\tunsafe_setup_sigcontext(&old_ctx->uc_mcontext, current, 0, NULL,\n\t\t\t\t\t0, ctx_has_vsx_region, efault_out);\n\t\tunsafe_copy_to_user(&old_ctx->uc_sigmask, &current->blocked,\n\t\t\t\t sizeof(sigset_t), efault_out);\n\n\t\tuser_write_access_end();\n\t}\n\tif (new_ctx == NULL)\n\t\treturn 0;\n\tif (!access_ok(new_ctx, ctx_size) ||\n\t fault_in_pages_readable((u8 __user *)new_ctx, ctx_size))\n\t\treturn -EFAULT;\n\n\t/*\n\t * If we get a fault copying the context into the kernel's\n\t * image of the user's registers, we can't just return -EFAULT\n\t * because the user's registers will be corrupted. For instance\n\t * the NIP value may have been updated but not some of the\n\t * other registers. Given that we have done the access_ok\n\t * and successfully read the first and last bytes of the region\n\t * above, this should only happen in an out-of-memory situation\n\t * or if another thread unmaps the region containing the context.\n\t * We kill the task with a SIGSEGV in this situation.\n\t */\n\n\tif (__get_user_sigset(&set, &new_ctx->uc_sigmask))\n\t\tdo_exit(SIGSEGV);\n\tset_current_blocked(&set);\n\n\tif (!user_read_access_begin(new_ctx, ctx_size))\n\t\treturn -EFAULT;\n\tif (__unsafe_restore_sigcontext(current, NULL, 0, &new_ctx->uc_mcontext)) {\n\t\tuser_read_access_end();\n\t\tdo_exit(SIGSEGV);\n\t}\n\tuser_read_access_end();\n\n\t/* This returns like rt_sigreturn */\n\tset_thread_flag(TIF_RESTOREALL);\n\n\treturn 0;\n\nefault_out:\n\tuser_write_access_end();\n\treturn -EFAULT;\n}\n\n\n/*\n * Do a signal return; undo the signal stack.\n */\n\nSYSCALL_DEFINE0(rt_sigreturn)\n{\n\tstruct pt_regs *regs = current_pt_regs();\n\tstruct ucontext __user *uc = (struct ucontext __user *)regs->gpr[1];\n\tsigset_t set;\n\tunsigned long msr;\n\n\t/* Always make any pending restarted system calls return -EINTR */\n\tcurrent->restart_block.fn = do_no_restart_syscall;\n\n\tif (!access_ok(uc, sizeof(*uc)))\n\t\tgoto badframe;\n\n\tif (__get_user_sigset(&set, &uc->uc_sigmask))\n\t\tgoto badframe;\n\tset_current_blocked(&set);\n\n\tif (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM)) {\n\t\t/*\n\t\t * If there is a transactional state then throw it away.\n\t\t * The purpose of a sigreturn is to destroy all traces of the\n\t\t * signal frame, this includes any transactional state created\n\t\t * within in. We only check for suspended as we can never be\n\t\t * active in the kernel, we are active, there is nothing better to\n\t\t * do than go ahead and Bad Thing later.\n\t\t * The cause is not important as there will never be a\n\t\t * recheckpoint so it's not user visible.\n\t\t */\n\t\tif (MSR_TM_SUSPENDED(mfmsr()))\n\t\t\ttm_reclaim_current(0);\n\n\t\t/*\n\t\t * Disable MSR[TS] bit also, so, if there is an exception in the\n\t\t * code below (as a page fault in copy_ckvsx_to_user()), it does\n\t\t * not recheckpoint this task if there was a context switch inside\n\t\t * the exception.\n\t\t *\n\t\t * A major page fault can indirectly call schedule(). A reschedule\n\t\t * process in the middle of an exception can have a side effect\n\t\t * (Changing the CPU MSR[TS] state), since schedule() is called\n\t\t * with the CPU MSR[TS] disable and returns with MSR[TS]=Suspended\n\t\t * (switch_to() calls tm_recheckpoint() for the 'new' process). In\n\t\t * this case, the process continues to be the same in the CPU, but\n\t\t * the CPU state just changed.\n\t\t *\n\t\t * This can cause a TM Bad Thing, since the MSR in the stack will\n\t\t * have the MSR[TS]=0, and this is what will be used to RFID.\n\t\t *\n\t\t * Clearing MSR[TS] state here will avoid a recheckpoint if there\n\t\t * is any process reschedule in kernel space. The MSR[TS] state\n\t\t * does not need to be saved also, since it will be replaced with\n\t\t * the MSR[TS] that came from user context later, at\n\t\t * restore_tm_sigcontexts.\n\t\t */\n\t\tregs_set_return_msr(regs, regs->msr & ~MSR_TS_MASK);\n\n\t\tif (__get_user(msr, &uc->uc_mcontext.gp_regs[PT_MSR]))\n\t\t\tgoto badframe;\n\t}\n\n\tif (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM) && MSR_TM_ACTIVE(msr)) {\n\t\t/* We recheckpoint on return. */\n\t\tstruct ucontext __user *uc_transact;\n\n\t\t/* Trying to start TM on non TM system */\n\t\tif (!cpu_has_feature(CPU_FTR_TM))\n\t\t\tgoto badframe;\n\n\t\tif (__get_user(uc_transact, &uc->uc_link))\n\t\t\tgoto badframe;\n\t\tif (restore_tm_sigcontexts(current, &uc->uc_mcontext,\n\t\t\t\t\t &uc_transact->uc_mcontext))\n\t\t\tgoto badframe;\n\t} else {\n\t\t/*\n\t\t * Fall through, for non-TM restore\n\t\t *\n\t\t * Unset MSR[TS] on the thread regs since MSR from user\n\t\t * context does not have MSR active, and recheckpoint was\n\t\t * not called since restore_tm_sigcontexts() was not called\n\t\t * also.\n\t\t *\n\t\t * If not unsetting it, the code can RFID to userspace with\n\t\t * MSR[TS] set, but without CPU in the proper state,\n\t\t * causing a TM bad thing.\n\t\t */\n\t\tregs_set_return_msr(current->thread.regs,\n\t\t\t\tcurrent->thread.regs->msr & ~MSR_TS_MASK);\n\t\tif (!user_read_access_begin(&uc->uc_mcontext, sizeof(uc->uc_mcontext)))\n\t\t\tgoto badframe;\n\n\t\tunsafe_restore_sigcontext(current, NULL, 1, &uc->uc_mcontext,\n\t\t\t\t\t badframe_block);\n\n\t\tuser_read_access_end();\n\t}\n\n\tif (restore_altstack(&uc->uc_stack))\n\t\tgoto badframe;\n\n\tset_thread_flag(TIF_RESTOREALL);\n\n\treturn 0;\n\nbadframe_block:\n\tuser_read_access_end();\nbadframe:\n\tsignal_fault(current, regs, \"rt_sigreturn\", uc);\n\n\tforce_sig(SIGSEGV);\n\treturn 0;\n}\n\nint handle_rt_signal64(struct ksignal *ksig, sigset_t *set,\n\t\tstruct task_struct *tsk)\n{\n\tstruct rt_sigframe __user *frame;\n\tunsigned long newsp = 0;\n\tlong err = 0;\n\tstruct pt_regs *regs = tsk->thread.regs;\n\t/* Save the thread's msr before get_tm_stackpointer() changes it */\n\tunsigned long msr = regs->msr;\n\n\tframe = get_sigframe(ksig, tsk, sizeof(*frame), 0);\n\n\t/*\n\t * This only applies when calling unsafe_setup_sigcontext() and must be\n\t * called before opening the uaccess window.\n\t */\n\tif (!MSR_TM_ACTIVE(msr))\n\t\tprepare_setup_sigcontext(tsk);\n\n\tif (!user_write_access_begin(frame, sizeof(*frame)))\n\t\tgoto badframe;\n\n\tunsafe_put_user(&frame->info, &frame->pinfo, badframe_block);\n\tunsafe_put_user(&frame->uc, &frame->puc, badframe_block);\n\n\t/* Create the ucontext. */\n\tunsafe_put_user(0, &frame->uc.uc_flags, badframe_block);\n\tunsafe_save_altstack(&frame->uc.uc_stack, regs->gpr[1], badframe_block);\n\n\tif (MSR_TM_ACTIVE(msr)) {\n#ifdef CONFIG_PPC_TRANSACTIONAL_MEM\n\t\t/* The ucontext_t passed to userland points to the second\n\t\t * ucontext_t (for transactional state) with its uc_link ptr.\n\t\t */\n\t\tunsafe_put_user(&frame->uc_transact, &frame->uc.uc_link, badframe_block);\n\n\t\tuser_write_access_end();\n\n\t\terr |= setup_tm_sigcontexts(&frame->uc.uc_mcontext,\n\t\t\t\t\t &frame->uc_transact.uc_mcontext,\n\t\t\t\t\t tsk, ksig->sig, NULL,\n\t\t\t\t\t (unsigned long)ksig->ka.sa.sa_handler,\n\t\t\t\t\t msr);\n\n\t\tif (!user_write_access_begin(&frame->uc.uc_sigmask,\n\t\t\t\t\t sizeof(frame->uc.uc_sigmask)))\n\t\t\tgoto badframe;\n\n#endif\n\t} else {\n\t\tunsafe_put_user(0, &frame->uc.uc_link, badframe_block);\n\t\tunsafe_setup_sigcontext(&frame->uc.uc_mcontext, tsk, ksig->sig,\n\t\t\t\t\tNULL, (unsigned long)ksig->ka.sa.sa_handler,\n\t\t\t\t\t1, badframe_block);\n\t}\n\n\tunsafe_copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set), badframe_block);\n\tuser_write_access_end();\n\n\t/* Save the siginfo outside of the unsafe block. */\n\tif (copy_siginfo_to_user(&frame->info, &ksig->info))\n\t\tgoto badframe;\n\n\t/* Make sure signal handler doesn't get spurious FP exceptions */\n\ttsk->thread.fp_state.fpscr = 0;\n\n\t/* Set up to return from userspace. */\n\tif (tsk->mm->context.vdso) {\n\t\tregs_set_return_ip(regs, VDSO64_SYMBOL(tsk->mm->context.vdso, sigtramp_rt64));\n\t} else {\n\t\terr |= setup_trampoline(__NR_rt_sigreturn, &frame->tramp[0]);\n\t\tif (err)\n\t\t\tgoto badframe;\n\t\tregs_set_return_ip(regs, (unsigned long) &frame->tramp[0]);\n\t}\n\n\t/* Allocate a dummy caller frame for the signal handler. */\n\tnewsp = ((unsigned long)frame) - __SIGNAL_FRAMESIZE;\n\terr |= put_user(regs->gpr[1], (unsigned long __user *)newsp);\n\n\t/* Set up \"regs\" so we \"return\" to the signal handler. */\n\tif (is_elf2_task()) {\n\t\tregs->ctr = (unsigned long) ksig->ka.sa.sa_handler;\n\t\tregs->gpr[12] = regs->ctr;\n\t} else {\n\t\t/* Handler is *really* a pointer to the function descriptor for\n\t\t * the signal routine. The first entry in the function\n\t\t * descriptor is the entry address of signal and the second\n\t\t * entry is the TOC value we need to use.\n\t\t */\n\t\tfunc_descr_t __user *funct_desc_ptr =\n\t\t\t(func_descr_t __user *) ksig->ka.sa.sa_handler;\n\n\t\terr |= get_user(regs->ctr, &funct_desc_ptr->entry);\n\t\terr |= get_user(regs->gpr[2], &funct_desc_ptr->toc);\n\t}\n\n\t/* enter the signal handler in native-endian mode */\n\tregs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (MSR_KERNEL & MSR_LE));\n\tregs->gpr[1] = newsp;\n\tregs->gpr[3] = ksig->sig;\n\tregs->result = 0;\n\tif (ksig->ka.sa.sa_flags & SA_SIGINFO) {\n\t\tregs->gpr[4] = (unsigned long)&frame->info;\n\t\tregs->gpr[5] = (unsigned long)&frame->uc;\n\t\tregs->gpr[6] = (unsigned long) frame;\n\t} else {\n\t\tregs->gpr[4] = (unsigned long)&frame->uc.uc_mcontext;\n\t}\n\tif (err)\n\t\tgoto badframe;\n\n\treturn 0;\n\nbadframe_block:\n\tuser_write_access_end();\nbadframe:\n\tsignal_fault(current, regs, \"handle_rt_signal64\", frame);\n\n\treturn 1;\n}\n"},"repo_name":{"kind":"string","value":"tprrt/linux-stable"},"path":{"kind":"string","value":"arch/powerpc/kernel/signal_64.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":30604,"string":"30,604"}}},{"rowIdx":115086548,"cells":{"code":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\nuse dom::attr::AttrValue;\nuse dom::bindings::codegen::Bindings::HTMLAreaElementBinding;\nuse dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;\nuse dom::bindings::inheritance::Castable;\nuse dom::bindings::js::{JS, MutNullableHeap, Root};\nuse dom::bindings::reflector::Reflectable;\nuse dom::document::Document;\nuse dom::domtokenlist::DOMTokenList;\nuse dom::htmlelement::HTMLElement;\nuse dom::node::Node;\nuse dom::virtualmethods::VirtualMethods;\nuse std::default::Default;\nuse string_cache::Atom;\nuse util::str::DOMString;\n\n#[dom_struct]\npub struct HTMLAreaElement {\n htmlelement: HTMLElement,\n rel_list: MutNullableHeap>,\n}\n\nimpl HTMLAreaElement {\n fn new_inherited(localName: Atom, prefix: Option, document: &Document) -> HTMLAreaElement {\n HTMLAreaElement {\n htmlelement: HTMLElement::new_inherited(localName, prefix, document),\n rel_list: Default::default(),\n }\n }\n\n #[allow(unrooted_must_root)]\n pub fn new(localName: Atom,\n prefix: Option,\n document: &Document) -> Root {\n let element = HTMLAreaElement::new_inherited(localName, prefix, document);\n Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)\n }\n}\n\nimpl VirtualMethods for HTMLAreaElement {\n fn super_type(&self) -> Option<&VirtualMethods> {\n Some(self.upcast::() as &VirtualMethods)\n }\n\n fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {\n match name {\n &atom!(\"rel\") => AttrValue::from_serialized_tokenlist(value),\n _ => self.super_type().unwrap().parse_plain_attribute(name, value),\n }\n }\n}\n\nimpl HTMLAreaElementMethods for HTMLAreaElement {\n // https://html.spec.whatwg.org/multipage/#dom-area-rellist\n fn RelList(&self) -> Root {\n self.rel_list.or_init(|| {\n DOMTokenList::new(self.upcast(), &atom!(\"rel\"))\n })\n }\n}\n"},"repo_name":{"kind":"string","value":"rohlandm/servo"},"path":{"kind":"string","value":"components/script/dom/htmlareaelement.rs"},"language":{"kind":"string","value":"Rust"},"license":{"kind":"string","value":"mpl-2.0"},"size":{"kind":"number","value":2237,"string":"2,237"}}},{"rowIdx":115086549,"cells":{"code":{"kind":"string","value":"require 'will_paginate/core_ext'\n\nmodule WillPaginate\n # A mixin for ActiveRecord::Base. Provides +per_page+ class method\n # and hooks things up to provide paginating finders.\n #\n # Find out more in WillPaginate::Finder::ClassMethods\n #\n module Finder\n def self.included(base)\n base.extend ClassMethods\n class << base\n alias_method_chain :method_missing, :paginate\n # alias_method_chain :find_every, :paginate\n define_method(:per_page) { 30 } unless respond_to?(:per_page)\n end\n end\n\n # = Paginating finders for ActiveRecord models\n # \n # WillPaginate adds +paginate+, +per_page+ and other methods to\n # ActiveRecord::Base class methods and associations. It also hooks into\n # +method_missing+ to intercept pagination calls to dynamic finders such as\n # +paginate_by_user_id+ and translate them to ordinary finders\n # (+find_all_by_user_id+ in this case).\n # \n # In short, paginating finders are equivalent to ActiveRecord finders; the\n # only difference is that we start with \"paginate\" instead of \"find\" and\n # that :page is required parameter:\n #\n # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'\n # \n # In paginating finders, \"all\" is implicit. There is no sense in paginating\n # a single record, right? So, you can drop the :all argument:\n # \n # Post.paginate(...) => Post.find :all\n # Post.paginate_all_by_something => Post.find_all_by_something\n # Post.paginate_by_something => Post.find_all_by_something\n #\n # == The importance of the :order parameter\n #\n # In ActiveRecord finders, :order parameter specifies columns for\n # the ORDER BY clause in SQL. It is important to have it, since\n # pagination only makes sense with ordered sets. Without the ORDER\n # BY clause, databases aren't required to do consistent ordering when\n # performing SELECT queries; this is especially true for\n # PostgreSQL.\n #\n # Therefore, make sure you are doing ordering on a column that makes the\n # most sense in the current context. Make that obvious to the user, also.\n # For perfomance reasons you will also want to add an index to that column.\n module ClassMethods\n # This is the main paginating finder.\n #\n # == Special parameters for paginating finders\n # * :page -- REQUIRED, but defaults to 1 if false or nil\n # * :per_page -- defaults to CurrentModel.per_page (which is 30 if not overridden)\n # * :total_entries -- use only if you manually count total entries\n # * :count -- additional options that are passed on to +count+\n # * :finder -- name of the ActiveRecord finder used (default: \"find\")\n #\n # All other options (+conditions+, +order+, ...) are forwarded to +find+\n # and +count+ calls.\n def paginate(*args, &block)\n options = args.pop\n page, per_page, total_entries = wp_parse_options(options)\n finder = (options[:finder] || 'find').to_s\n\n if finder == 'find'\n # an array of IDs may have been given:\n total_entries ||= (Array === args.first and args.first.size)\n # :all is implicit\n args.unshift(:all) if args.empty?\n end\n\n WillPaginate::Collection.create(page, per_page, total_entries) do |pager|\n count_options = options.except :page, :per_page, :total_entries, :finder\n find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) \n \n args << find_options\n # @options_from_last_find = nil\n pager.replace send(finder, *args, &block)\n \n # magic counting for user convenience:\n pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries\n end\n end\n\n # Iterates through all records by loading one page at a time. This is useful\n # for migrations or any other use case where you don't want to load all the\n # records in memory at once.\n #\n # It uses +paginate+ internally; therefore it accepts all of its options.\n # You can specify a starting page with :page (default is 1). Default\n # :order is \"id\", override if necessary.\n #\n # See http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord where\n # Jamis Buck describes this and also uses a more efficient way for MySQL.\n def paginated_each(options = {}, &block)\n options = { :order => 'id', :page => 1 }.merge options\n options[:page] = options[:page].to_i\n options[:total_entries] = 0 # skip the individual count queries\n total = 0\n \n begin \n collection = paginate(options)\n total += collection.each(&block).size\n options[:page] += 1\n end until collection.size < collection.per_page\n \n total\n end\n \n # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string\n # based on the params otherwise used by paginating finds: +page+ and\n # +per_page+.\n #\n # Example:\n # \n # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],\n # :page => params[:page], :per_page => 3\n #\n # A query for counting rows will automatically be generated if you don't\n # supply :total_entries. If you experience problems with this\n # generated SQL, you might want to perform the count manually in your\n # application.\n # \n def paginate_by_sql(sql, options)\n WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|\n query = sanitize_sql(sql)\n original_query = query.dup\n # add limit, offset\n add_limit! query, :offset => pager.offset, :limit => pager.per_page\n # perfom the find\n pager.replace find_by_sql(query)\n \n unless pager.total_entries\n count_query = original_query.sub /\\bORDER\\s+BY\\s+[\\w`,\\s]+$/mi, ''\n count_query = \"SELECT COUNT(*) FROM (#{count_query})\"\n \n unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase)\n count_query << ' AS count_table'\n end\n # perform the count query\n pager.total_entries = count_by_sql(count_query)\n end\n end\n end\n\n def respond_to?(method, include_priv = false) #:nodoc:\n case method.to_sym\n when :paginate, :paginate_by_sql\n true\n else\n super(method.to_s.sub(/^paginate/, 'find'), include_priv)\n end\n end\n\n protected\n \n def method_missing_with_paginate(method, *args, &block) #:nodoc:\n # did somebody tried to paginate? if not, let them be\n unless method.to_s.index('paginate') == 0\n return method_missing_without_paginate(method, *args, &block) \n end\n \n # paginate finders are really just find_* with limit and offset\n finder = method.to_s.sub('paginate', 'find')\n finder.sub!('find', 'find_all') if finder.index('find_by_') == 0\n \n options = args.pop\n raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys\n options = options.dup\n options[:finder] = finder\n args << options\n \n paginate(*args, &block)\n end\n\n # Does the not-so-trivial job of finding out the total number of entries\n # in the database. It relies on the ActiveRecord +count+ method.\n def wp_count(options, args, finder)\n excludees = [:count, :order, :limit, :offset, :readonly]\n unless options[:select] and options[:select] =~ /^\\s*DISTINCT\\b/i\n excludees << :select # only exclude the select param if it doesn't begin with DISTINCT\n end\n\n # count expects (almost) the same options as find\n count_options = options.except *excludees\n\n # merge the hash found in :count\n # this allows you to specify :select, :order, or anything else just for the count query\n count_options.update options[:count] if options[:count]\n \n # we may be in a model or an association proxy\n klass = (@owner and @reflection) ? @reflection.klass : self\n \n # forget about includes if they are irrelevant (Rails 2.1)\n if count_options[:include] and\n klass.private_methods.include?('references_eager_loaded_tables?') and\n !klass.send(:references_eager_loaded_tables?, count_options)\n count_options.delete :include\n end\n\n # we may have to scope ...\n counter = Proc.new { count(count_options) }\n\n count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with'))\n # scope_out adds a 'with_finder' method which acts like with_scope, if it's present\n # then execute the count with the scoping provided by the with_finder\n send(scoper, &counter)\n elsif match = /^find_(all_by|by)_([_a-zA-Z]\\w*)$/.match(finder)\n # extract conditions from calls like \"paginate_by_foo_and_bar\"\n attribute_names = extract_attribute_names_from_match(match)\n conditions = construct_attributes_from_arguments(attribute_names, args)\n with_scope(:find => { :conditions => conditions }, &counter)\n else\n counter.call\n end\n\n count.respond_to?(:length) ? count.length : count\n end\n\n def wp_parse_options(options) #:nodoc:\n raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys\n options = options.symbolize_keys\n raise ArgumentError, ':page parameter required' unless options.key? :page\n \n if options[:count] and options[:total_entries]\n raise ArgumentError, ':count and :total_entries are mutually exclusive'\n end\n\n page = options[:page] || 1\n per_page = options[:per_page] || self.per_page\n total = options[:total_entries]\n [page, per_page, total]\n end\n\n private\n\n # def find_every_with_paginate(options)\n # @options_from_last_find = options\n # find_every_without_paginate(options)\n # end\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"gkneighb/insoshi"},"path":{"kind":"string","value":"vendor/plugins/will_paginate/lib/will_paginate/finder.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"agpl-3.0"},"size":{"kind":"number","value":10582,"string":"10,582"}}},{"rowIdx":115086550,"cells":{"code":{"kind":"string","value":"//\n// basic_serial_port.hpp\n// ~~~~~~~~~~~~~~~~~~~~~\n//\n// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com)\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef ASIO_BASIC_SERIAL_PORT_HPP\n#define ASIO_BASIC_SERIAL_PORT_HPP\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1200)\n# pragma once\n#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)\n\n#include \"asio/detail/config.hpp\"\n\n#if defined(ASIO_HAS_SERIAL_PORT) \\\n || defined(GENERATING_DOCUMENTATION)\n\n#include \n#include \"asio/basic_io_object.hpp\"\n#include \"asio/detail/handler_type_requirements.hpp\"\n#include \"asio/detail/throw_error.hpp\"\n#include \"asio/error.hpp\"\n#include \"asio/serial_port_base.hpp\"\n#include \"asio/serial_port_service.hpp\"\n\n#include \"asio/detail/push_options.hpp\"\n\nnamespace asio {\n\n/// Provides serial port functionality.\n/**\n * The basic_serial_port class template provides functionality that is common\n * to all serial ports.\n *\n * @par Thread Safety\n * @e Distinct @e objects: Safe.@n\n * @e Shared @e objects: Unsafe.\n */\ntemplate \nclass basic_serial_port\n : public basic_io_object,\n public serial_port_base\n{\npublic:\n /// (Deprecated: Use native_handle_type.) The native representation of a\n /// serial port.\n typedef typename SerialPortService::native_handle_type native_type;\n\n /// The native representation of a serial port.\n typedef typename SerialPortService::native_handle_type native_handle_type;\n\n /// A basic_serial_port is always the lowest layer.\n typedef basic_serial_port lowest_layer_type;\n\n /// Construct a basic_serial_port without opening it.\n /**\n * This constructor creates a serial port without opening it.\n *\n * @param io_service The io_service object that the serial port will use to\n * dispatch handlers for any asynchronous operations performed on the port.\n */\n explicit basic_serial_port(asio::io_service& io_service)\n : basic_io_object(io_service)\n {\n }\n\n /// Construct and open a basic_serial_port.\n /**\n * This constructor creates and opens a serial port for the specified device\n * name.\n *\n * @param io_service The io_service object that the serial port will use to\n * dispatch handlers for any asynchronous operations performed on the port.\n *\n * @param device The platform-specific device name for this serial\n * port.\n */\n explicit basic_serial_port(asio::io_service& io_service,\n const char* device)\n : basic_io_object(io_service)\n {\n asio::error_code ec;\n this->get_service().open(this->get_implementation(), device, ec);\n asio::detail::throw_error(ec, \"open\");\n }\n\n /// Construct and open a basic_serial_port.\n /**\n * This constructor creates and opens a serial port for the specified device\n * name.\n *\n * @param io_service The io_service object that the serial port will use to\n * dispatch handlers for any asynchronous operations performed on the port.\n *\n * @param device The platform-specific device name for this serial\n * port.\n */\n explicit basic_serial_port(asio::io_service& io_service,\n const std::string& device)\n : basic_io_object(io_service)\n {\n asio::error_code ec;\n this->get_service().open(this->get_implementation(), device, ec);\n asio::detail::throw_error(ec, \"open\");\n }\n\n /// Construct a basic_serial_port on an existing native serial port.\n /**\n * This constructor creates a serial port object to hold an existing native\n * serial port.\n *\n * @param io_service The io_service object that the serial port will use to\n * dispatch handlers for any asynchronous operations performed on the port.\n *\n * @param native_serial_port A native serial port.\n *\n * @throws asio::system_error Thrown on failure.\n */\n basic_serial_port(asio::io_service& io_service,\n const native_handle_type& native_serial_port)\n : basic_io_object(io_service)\n {\n asio::error_code ec;\n this->get_service().assign(this->get_implementation(),\n native_serial_port, ec);\n asio::detail::throw_error(ec, \"assign\");\n }\n\n#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)\n /// Move-construct a basic_serial_port from another.\n /**\n * This constructor moves a serial port from one object to another.\n *\n * @param other The other basic_serial_port object from which the move will\n * occur.\n *\n * @note Following the move, the moved-from object is in the same state as if\n * constructed using the @c basic_serial_port(io_service&) constructor.\n */\n basic_serial_port(basic_serial_port&& other)\n : basic_io_object(\n ASIO_MOVE_CAST(basic_serial_port)(other))\n {\n }\n\n /// Move-assign a basic_serial_port from another.\n /**\n * This assignment operator moves a serial port from one object to another.\n *\n * @param other The other basic_serial_port object from which the move will\n * occur.\n *\n * @note Following the move, the moved-from object is in the same state as if\n * constructed using the @c basic_serial_port(io_service&) constructor.\n */\n basic_serial_port& operator=(basic_serial_port&& other)\n {\n basic_io_object::operator=(\n ASIO_MOVE_CAST(basic_serial_port)(other));\n return *this;\n }\n#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)\n\n /// Get a reference to the lowest layer.\n /**\n * This function returns a reference to the lowest layer in a stack of\n * layers. Since a basic_serial_port cannot contain any further layers, it\n * simply returns a reference to itself.\n *\n * @return A reference to the lowest layer in the stack of layers. Ownership\n * is not transferred to the caller.\n */\n lowest_layer_type& lowest_layer()\n {\n return *this;\n }\n\n /// Get a const reference to the lowest layer.\n /**\n * This function returns a const reference to the lowest layer in a stack of\n * layers. Since a basic_serial_port cannot contain any further layers, it\n * simply returns a reference to itself.\n *\n * @return A const reference to the lowest layer in the stack of layers.\n * Ownership is not transferred to the caller.\n */\n const lowest_layer_type& lowest_layer() const\n {\n return *this;\n }\n\n /// Open the serial port using the specified device name.\n /**\n * This function opens the serial port for the specified device name.\n *\n * @param device The platform-specific device name.\n *\n * @throws asio::system_error Thrown on failure.\n */\n void open(const std::string& device)\n {\n asio::error_code ec;\n this->get_service().open(this->get_implementation(), device, ec);\n asio::detail::throw_error(ec, \"open\");\n }\n\n /// Open the serial port using the specified device name.\n /**\n * This function opens the serial port using the given platform-specific\n * device name.\n *\n * @param device The platform-specific device name.\n *\n * @param ec Set the indicate what error occurred, if any.\n */\n asio::error_code open(const std::string& device,\n asio::error_code& ec)\n {\n return this->get_service().open(this->get_implementation(), device, ec);\n }\n\n /// Assign an existing native serial port to the serial port.\n /*\n * This function opens the serial port to hold an existing native serial port.\n *\n * @param native_serial_port A native serial port.\n *\n * @throws asio::system_error Thrown on failure.\n */\n void assign(const native_handle_type& native_serial_port)\n {\n asio::error_code ec;\n this->get_service().assign(this->get_implementation(),\n native_serial_port, ec);\n asio::detail::throw_error(ec, \"assign\");\n }\n\n /// Assign an existing native serial port to the serial port.\n /*\n * This function opens the serial port to hold an existing native serial port.\n *\n * @param native_serial_port A native serial port.\n *\n * @param ec Set to indicate what error occurred, if any.\n */\n asio::error_code assign(const native_handle_type& native_serial_port,\n asio::error_code& ec)\n {\n return this->get_service().assign(this->get_implementation(),\n native_serial_port, ec);\n }\n\n /// Determine whether the serial port is open.\n bool is_open() const\n {\n return this->get_service().is_open(this->get_implementation());\n }\n\n /// Close the serial port.\n /**\n * This function is used to close the serial port. Any asynchronous read or\n * write operations will be cancelled immediately, and will complete with the\n * asio::error::operation_aborted error.\n *\n * @throws asio::system_error Thrown on failure.\n */\n void close()\n {\n asio::error_code ec;\n this->get_service().close(this->get_implementation(), ec);\n asio::detail::throw_error(ec, \"close\");\n }\n\n /// Close the serial port.\n /**\n * This function is used to close the serial port. Any asynchronous read or\n * write operations will be cancelled immediately, and will complete with the\n * asio::error::operation_aborted error.\n *\n * @param ec Set to indicate what error occurred, if any.\n */\n asio::error_code close(asio::error_code& ec)\n {\n return this->get_service().close(this->get_implementation(), ec);\n }\n\n /// (Deprecated: Use native_handle().) Get the native serial port\n /// representation.\n /**\n * This function may be used to obtain the underlying representation of the\n * serial port. This is intended to allow access to native serial port\n * functionality that is not otherwise provided.\n */\n native_type native()\n {\n return this->get_service().native_handle(this->get_implementation());\n }\n\n /// Get the native serial port representation.\n /**\n * This function may be used to obtain the underlying representation of the\n * serial port. This is intended to allow access to native serial port\n * functionality that is not otherwise provided.\n */\n native_handle_type native_handle()\n {\n return this->get_service().native_handle(this->get_implementation());\n }\n\n /// Cancel all asynchronous operations associated with the serial port.\n /**\n * This function causes all outstanding asynchronous read or write operations\n * to finish immediately, and the handlers for cancelled operations will be\n * passed the asio::error::operation_aborted error.\n *\n * @throws asio::system_error Thrown on failure.\n */\n void cancel()\n {\n asio::error_code ec;\n this->get_service().cancel(this->get_implementation(), ec);\n asio::detail::throw_error(ec, \"cancel\");\n }\n\n /// Cancel all asynchronous operations associated with the serial port.\n /**\n * This function causes all outstanding asynchronous read or write operations\n * to finish immediately, and the handlers for cancelled operations will be\n * passed the asio::error::operation_aborted error.\n *\n * @param ec Set to indicate what error occurred, if any.\n */\n asio::error_code cancel(asio::error_code& ec)\n {\n return this->get_service().cancel(this->get_implementation(), ec);\n }\n\n /// Send a break sequence to the serial port.\n /**\n * This function causes a break sequence of platform-specific duration to be\n * sent out the serial port.\n *\n * @throws asio::system_error Thrown on failure.\n */\n void send_break()\n {\n asio::error_code ec;\n this->get_service().send_break(this->get_implementation(), ec);\n asio::detail::throw_error(ec, \"send_break\");\n }\n\n /// Send a break sequence to the serial port.\n /**\n * This function causes a break sequence of platform-specific duration to be\n * sent out the serial port.\n *\n * @param ec Set to indicate what error occurred, if any.\n */\n asio::error_code send_break(asio::error_code& ec)\n {\n return this->get_service().send_break(this->get_implementation(), ec);\n }\n\n /// Set an option on the serial port.\n /**\n * This function is used to set an option on the serial port.\n *\n * @param option The option value to be set on the serial port.\n *\n * @throws asio::system_error Thrown on failure.\n *\n * @sa SettableSerialPortOption @n\n * asio::serial_port_base::baud_rate @n\n * asio::serial_port_base::flow_control @n\n * asio::serial_port_base::parity @n\n * asio::serial_port_base::stop_bits @n\n * asio::serial_port_base::character_size\n */\n template \n void set_option(const SettableSerialPortOption& option)\n {\n asio::error_code ec;\n this->get_service().set_option(this->get_implementation(), option, ec);\n asio::detail::throw_error(ec, \"set_option\");\n }\n\n /// Set an option on the serial port.\n /**\n * This function is used to set an option on the serial port.\n *\n * @param option The option value to be set on the serial port.\n *\n * @param ec Set to indicate what error occurred, if any.\n *\n * @sa SettableSerialPortOption @n\n * asio::serial_port_base::baud_rate @n\n * asio::serial_port_base::flow_control @n\n * asio::serial_port_base::parity @n\n * asio::serial_port_base::stop_bits @n\n * asio::serial_port_base::character_size\n */\n template \n asio::error_code set_option(const SettableSerialPortOption& option,\n asio::error_code& ec)\n {\n return this->get_service().set_option(\n this->get_implementation(), option, ec);\n }\n\n /// Get an option from the serial port.\n /**\n * This function is used to get the current value of an option on the serial\n * port.\n *\n * @param option The option value to be obtained from the serial port.\n *\n * @throws asio::system_error Thrown on failure.\n *\n * @sa GettableSerialPortOption @n\n * asio::serial_port_base::baud_rate @n\n * asio::serial_port_base::flow_control @n\n * asio::serial_port_base::parity @n\n * asio::serial_port_base::stop_bits @n\n * asio::serial_port_base::character_size\n */\n template \n void get_option(GettableSerialPortOption& option)\n {\n asio::error_code ec;\n this->get_service().get_option(this->get_implementation(), option, ec);\n asio::detail::throw_error(ec, \"get_option\");\n }\n\n /// Get an option from the serial port.\n /**\n * This function is used to get the current value of an option on the serial\n * port.\n *\n * @param option The option value to be obtained from the serial port.\n *\n * @param ec Set to indicate what error occured, if any.\n *\n * @sa GettableSerialPortOption @n\n * asio::serial_port_base::baud_rate @n\n * asio::serial_port_base::flow_control @n\n * asio::serial_port_base::parity @n\n * asio::serial_port_base::stop_bits @n\n * asio::serial_port_base::character_size\n */\n template \n asio::error_code get_option(GettableSerialPortOption& option,\n asio::error_code& ec)\n {\n return this->get_service().get_option(\n this->get_implementation(), option, ec);\n }\n\n /// Write some data to the serial port.\n /**\n * This function is used to write data to the serial port. The function call\n * will block until one or more bytes of the data has been written\n * successfully, or until an error occurs.\n *\n * @param buffers One or more data buffers to be written to the serial port.\n *\n * @returns The number of bytes written.\n *\n * @throws asio::system_error Thrown on failure. An error code of\n * asio::error::eof indicates that the connection was closed by the\n * peer.\n *\n * @note The write_some operation may not transmit all of the data to the\n * peer. Consider using the @ref write function if you need to ensure that\n * all data is written before the blocking operation completes.\n *\n * @par Example\n * To write a single data buffer use the @ref buffer function as follows:\n * @code\n * serial_port.write_some(asio::buffer(data, size));\n * @endcode\n * See the @ref buffer documentation for information on writing multiple\n * buffers in one go, and how to use it with arrays, boost::array or\n * std::vector.\n */\n template \n std::size_t write_some(const ConstBufferSequence& buffers)\n {\n asio::error_code ec;\n std::size_t s = this->get_service().write_some(\n this->get_implementation(), buffers, ec);\n asio::detail::throw_error(ec, \"write_some\");\n return s;\n }\n\n /// Write some data to the serial port.\n /**\n * This function is used to write data to the serial port. The function call\n * will block until one or more bytes of the data has been written\n * successfully, or until an error occurs.\n *\n * @param buffers One or more data buffers to be written to the serial port.\n *\n * @param ec Set to indicate what error occurred, if any.\n *\n * @returns The number of bytes written. Returns 0 if an error occurred.\n *\n * @note The write_some operation may not transmit all of the data to the\n * peer. Consider using the @ref write function if you need to ensure that\n * all data is written before the blocking operation completes.\n */\n template \n std::size_t write_some(const ConstBufferSequence& buffers,\n asio::error_code& ec)\n {\n return this->get_service().write_some(\n this->get_implementation(), buffers, ec);\n }\n\n /// Start an asynchronous write.\n /**\n * This function is used to asynchronously write data to the serial port.\n * The function call always returns immediately.\n *\n * @param buffers One or more data buffers to be written to the serial port.\n * Although the buffers object may be copied as necessary, ownership of the\n * underlying memory blocks is retained by the caller, which must guarantee\n * that they remain valid until the handler is called.\n *\n * @param handler The handler to be called when the write operation completes.\n * Copies will be made of the handler as required. The function signature of\n * the handler must be:\n * @code void handler(\n * const asio::error_code& error, // Result of operation.\n * std::size_t bytes_transferred // Number of bytes written.\n * ); @endcode\n * Regardless of whether the asynchronous operation completes immediately or\n * not, the handler will not be invoked from within this function. Invocation\n * of the handler will be performed in a manner equivalent to using\n * asio::io_service::post().\n *\n * @note The write operation may not transmit all of the data to the peer.\n * Consider using the @ref async_write function if you need to ensure that all\n * data is written before the asynchronous operation completes.\n *\n * @par Example\n * To write a single data buffer use the @ref buffer function as follows:\n * @code\n * serial_port.async_write_some(asio::buffer(data, size), handler);\n * @endcode\n * See the @ref buffer documentation for information on writing multiple\n * buffers in one go, and how to use it with arrays, boost::array or\n * std::vector.\n */\n template \n ASIO_INITFN_RESULT_TYPE(WriteHandler,\n void (asio::error_code, std::size_t))\n async_write_some(const ConstBufferSequence& buffers,\n ASIO_MOVE_ARG(WriteHandler) handler)\n {\n // If you get an error on the following line it means that your handler does\n // not meet the documented type requirements for a WriteHandler.\n ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;\n\n return this->get_service().async_write_some(this->get_implementation(),\n buffers, ASIO_MOVE_CAST(WriteHandler)(handler));\n }\n\n /// Read some data from the serial port.\n /**\n * This function is used to read data from the serial port. The function\n * call will block until one or more bytes of data has been read successfully,\n * or until an error occurs.\n *\n * @param buffers One or more buffers into which the data will be read.\n *\n * @returns The number of bytes read.\n *\n * @throws asio::system_error Thrown on failure. An error code of\n * asio::error::eof indicates that the connection was closed by the\n * peer.\n *\n * @note The read_some operation may not read all of the requested number of\n * bytes. Consider using the @ref read function if you need to ensure that\n * the requested amount of data is read before the blocking operation\n * completes.\n *\n * @par Example\n * To read into a single data buffer use the @ref buffer function as follows:\n * @code\n * serial_port.read_some(asio::buffer(data, size));\n * @endcode\n * See the @ref buffer documentation for information on reading into multiple\n * buffers in one go, and how to use it with arrays, boost::array or\n * std::vector.\n */\n template \n std::size_t read_some(const MutableBufferSequence& buffers)\n {\n asio::error_code ec;\n std::size_t s = this->get_service().read_some(\n this->get_implementation(), buffers, ec);\n asio::detail::throw_error(ec, \"read_some\");\n return s;\n }\n\n /// Read some data from the serial port.\n /**\n * This function is used to read data from the serial port. The function\n * call will block until one or more bytes of data has been read successfully,\n * or until an error occurs.\n *\n * @param buffers One or more buffers into which the data will be read.\n *\n * @param ec Set to indicate what error occurred, if any.\n *\n * @returns The number of bytes read. Returns 0 if an error occurred.\n *\n * @note The read_some operation may not read all of the requested number of\n * bytes. Consider using the @ref read function if you need to ensure that\n * the requested amount of data is read before the blocking operation\n * completes.\n */\n template \n std::size_t read_some(const MutableBufferSequence& buffers,\n asio::error_code& ec)\n {\n return this->get_service().read_some(\n this->get_implementation(), buffers, ec);\n }\n\n /// Start an asynchronous read.\n /**\n * This function is used to asynchronously read data from the serial port.\n * The function call always returns immediately.\n *\n * @param buffers One or more buffers into which the data will be read.\n * Although the buffers object may be copied as necessary, ownership of the\n * underlying memory blocks is retained by the caller, which must guarantee\n * that they remain valid until the handler is called.\n *\n * @param handler The handler to be called when the read operation completes.\n * Copies will be made of the handler as required. The function signature of\n * the handler must be:\n * @code void handler(\n * const asio::error_code& error, // Result of operation.\n * std::size_t bytes_transferred // Number of bytes read.\n * ); @endcode\n * Regardless of whether the asynchronous operation completes immediately or\n * not, the handler will not be invoked from within this function. Invocation\n * of the handler will be performed in a manner equivalent to using\n * asio::io_service::post().\n *\n * @note The read operation may not read all of the requested number of bytes.\n * Consider using the @ref async_read function if you need to ensure that the\n * requested amount of data is read before the asynchronous operation\n * completes.\n *\n * @par Example\n * To read into a single data buffer use the @ref buffer function as follows:\n * @code\n * serial_port.async_read_some(asio::buffer(data, size), handler);\n * @endcode\n * See the @ref buffer documentation for information on reading into multiple\n * buffers in one go, and how to use it with arrays, boost::array or\n * std::vector.\n */\n template \n ASIO_INITFN_RESULT_TYPE(ReadHandler,\n void (asio::error_code, std::size_t))\n async_read_some(const MutableBufferSequence& buffers,\n ASIO_MOVE_ARG(ReadHandler) handler)\n {\n // If you get an error on the following line it means that your handler does\n // not meet the documented type requirements for a ReadHandler.\n ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;\n\n return this->get_service().async_read_some(this->get_implementation(),\n buffers, ASIO_MOVE_CAST(ReadHandler)(handler));\n }\n};\n\n} // namespace asio\n\n#include \"asio/detail/pop_options.hpp\"\n\n#endif // defined(ASIO_HAS_SERIAL_PORT)\n // || defined(GENERATING_DOCUMENTATION)\n\n#endif // ASIO_BASIC_SERIAL_PORT_HPP\n"},"repo_name":{"kind":"string","value":"julien3/vertxbuspp"},"path":{"kind":"string","value":"vertxbuspp/asio/include/asio/basic_serial_port.hpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":24579,"string":"24,579"}}},{"rowIdx":115086551,"cells":{"code":{"kind":"string","value":"/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.camel.test.spring;\n\nimport org.apache.camel.management.JmxSystemPropertyKeys;\nimport org.apache.camel.spring.SpringCamelContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.support.BeanDefinitionRegistry;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.ConfigurableApplicationContext;\nimport org.springframework.context.annotation.AnnotationConfigUtils;\nimport org.springframework.test.context.MergedContextConfiguration;\nimport org.springframework.test.context.support.DelegatingSmartContextLoader;\n\n/**\n * CamelSpringDelegatingTestContextLoader which fixes issues in Camel's JavaConfigContextLoader. (adds support for Camel's test annotations)\n *
    \n * This loader can handle either classes or locations for configuring the context.\n *
    \n * NOTE: This TestContextLoader doesn't support the annotation of ExcludeRoutes now.\n */\npublic class CamelSpringDelegatingTestContextLoader extends DelegatingSmartContextLoader {\n\n protected final Logger logger = LoggerFactory.getLogger(getClass());\n\n @Override\n public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {\n \n Class testClass = getTestClass();\n \n if (logger.isDebugEnabled()) {\n logger.debug(\"Loading ApplicationContext for merged context configuration [{}].\", mergedConfig);\n }\n \n // Pre CamelContext(s) instantiation setup\n CamelAnnotationsHandler.handleDisableJmx(null, testClass);\n\n try {\n SpringCamelContext.setNoStart(true);\n System.setProperty(\"skipStartingCamelContext\", \"true\");\n ConfigurableApplicationContext context = (ConfigurableApplicationContext) super.loadContext(mergedConfig);\n SpringCamelContext.setNoStart(false);\n System.clearProperty(\"skipStartingCamelContext\");\n return loadContext(context, testClass);\n } finally {\n cleanup(testClass);\n }\n }\n\n /**\n * Performs the bulk of the Spring application context loading/customization.\n *\n * @param context the partially configured context. The context should have the bean definitions loaded, but nothing else.\n * @param testClass the test class being executed\n * @return the initialized (refreshed) Spring application context\n *\n * @throws Exception if there is an error during initialization/customization\n */\n public ApplicationContext loadContext(ConfigurableApplicationContext context, Class testClass)\n throws Exception {\n \n AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) context);\n\n // Post CamelContext(s) instantiation but pre CamelContext(s) start setup\n CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass);\n CamelAnnotationsHandler.handleShutdownTimeout(context, testClass);\n CamelAnnotationsHandler.handleMockEndpoints(context, testClass);\n CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass);\n CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass);\n \n // CamelContext(s) startup\n CamelAnnotationsHandler.handleCamelContextStartup(context, testClass);\n \n return context;\n }\n \n /**\n * Cleanup/restore global state to defaults / pre-test values after the test setup\n * is complete. \n * \n * @param testClass the test class being executed\n */\n protected void cleanup(Class testClass) {\n SpringCamelContext.setNoStart(false);\n \n if (testClass.isAnnotationPresent(DisableJmx.class)) {\n if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) {\n System.clearProperty(JmxSystemPropertyKeys.DISABLED);\n } else {\n System.setProperty(JmxSystemPropertyKeys.DISABLED,\n CamelSpringTestHelper.getOriginalJmxDisabled());\n }\n }\n }\n\n /**\n * Returns the class under test in order to enable inspection of annotations while the\n * Spring context is being created.\n * \n * @return the test class that is being executed\n * @see CamelSpringTestHelper\n */\n protected Class getTestClass() {\n return CamelSpringTestHelper.getTestClass();\n }\n\n}"},"repo_name":{"kind":"string","value":"jmandawg/camel"},"path":{"kind":"string","value":"components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":5252,"string":"5,252"}}},{"rowIdx":115086552,"cells":{"code":{"kind":"string","value":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See the LICENSE file in builder/azure for license information.\n\npackage arm\n\nimport (\n\t\"golang.org/x/crypto/ssh\"\n\t\"testing\"\n)\n\nfunc TestFart(t *testing.T) {\n\n}\n\nfunc TestAuthorizedKeyShouldParse(t *testing.T) {\n\ttestSubject, err := NewOpenSshKeyPairWithSize(512)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new OpenSSH key pair, err=%s.\", err)\n\t}\n\n\tauthorizedKey := testSubject.AuthorizedKey()\n\n\t_, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to parse the authorized key, err=%s\", err)\n\t}\n}\n\nfunc TestPrivateKeyShouldParse(t *testing.T) {\n\ttestSubject, err := NewOpenSshKeyPairWithSize(512)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create a new OpenSSH key pair, err=%s.\", err)\n\t}\n\n\t_, err = ssh.ParsePrivateKey([]byte(testSubject.PrivateKey()))\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to parse the private key, err=%s\\n\", err)\n\t}\n}\n"},"repo_name":{"kind":"string","value":"stardog-union/stardog-graviton"},"path":{"kind":"string","value":"vendor/github.com/mitchellh/packer/builder/azure/arm/openssh_key_pair_test.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":980,"string":"980"}}},{"rowIdx":115086553,"cells":{"code":{"kind":"string","value":"#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script performs disaster recovery of etcd from the backup data.\n# Assumptions:\n# - backup was done using etcdctl command:\n# a) in case of etcd2\n# $ etcdctl backup --data-dir=\n# produced .snap and .wal files\n# b) in case of etcd3\n# $ etcdctl --endpoints=
    snapshot save\n# produced .db file\n# - version.txt file is in the current directory (if it isn't it will be\n# defaulted to \"3.0.17/etcd3\"). Based on this file, the script will\n# decide to which version we are restoring (procedures are different\n# for etcd2 and etcd3).\n# - in case of etcd2 - *.snap and *.wal files are in current directory\n# - in case of etcd3 - *.db file is in the current directory\n# - the script is run as root\n# - for event etcd, we only support clearing it - to do it, you need to\n# set RESET_EVENT_ETCD=true env var.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Version file contains information about current version in the format:\n# / (e.g. \"3.0.12/etcd3\").\n#\n# If the file doesn't exist we assume \"3.0.17/etcd3\" configuration is\n# the current one and create a file with such configuration.\n# The restore procedure is chosen based on this information.\nVERSION_FILE=\"version.txt\"\n\n# Make it possible to overwrite version file (or default version)\n# with VERSION_CONTENTS env var.\nif [ -n \"${VERSION_CONTENTS:-}\" ]; then\n echo \"${VERSION_CONTENTS}\" > \"${VERSION_FILE}\"\nfi\nif [ ! -f \"${VERSION_FILE}\" ]; then\n echo \"3.0.17/etcd3\" > \"${VERSION_FILE}\"\nfi\nVERSION_CONTENTS=\"$(cat ${VERSION_FILE})\"\nETCD_VERSION=\"$(echo \"$VERSION_CONTENTS\" | cut -d '/' -f 1)\"\nETCD_API=\"$(echo \"$VERSION_CONTENTS\" | cut -d '/' -f 2)\"\n\n# Name is used only in case of etcd3 mode, to appropriate set the metadata\n# for the etcd data.\n# NOTE: NAME HAS TO BE EQUAL TO WHAT WE USE IN --name flag when starting etcd.\nNAME=\"${NAME:-etcd-$(hostname)}\"\n\nINITIAL_CLUSTER=\"${INITIAL_CLUSTER:-${NAME}=http://localhost:2380}\"\nINITIAL_ADVERTISE_PEER_URLS=\"${INITIAL_ADVERTISE_PEER_URLS:-http://localhost:2380}\"\n\n# Port on which etcd is exposed.\netcd_port=2379\nevent_etcd_port=4002\n\n# Wait until both etcd instances are up\nwait_for_etcd_up() {\n port=$1\n # TODO: As of 3.0.x etcd versions, all 2.* and 3.* versions return\n # {\"health\": \"true\"} on /health endpoint in healthy case.\n # However, we should come with a regex for it to avoid future break.\n health_ok=\"{\\\"health\\\": \\\"true\\\"}\"\n for _ in $(seq 120); do\n # TODO: Is it enough to look into /health endpoint?\n health=$(curl --silent \"http://127.0.0.1:${port}/health\")\n if [ \"${health}\" == \"${health_ok}\" ]; then\n return 0\n fi\n sleep 1\n done\n return 1\n}\n\n# Wait until apiserver is up.\nwait_for_cluster_healthy() {\n for _ in $(seq 120); do\n cs_status=$(kubectl get componentstatuses -o template --template='{{range .items}}{{with index .conditions 0}}{{.type}}:{{.status}}{{end}}{{\"\\n\"}}{{end}}') || true\n componentstatuses=$(echo \"${cs_status}\" | grep -c 'Healthy:') || true\n healthy=$(echo \"${cs_status}\" | grep -c 'Healthy:True') || true\n if [ \"${componentstatuses}\" -eq \"${healthy}\" ]; then\n return 0\n fi\n sleep 1\n done\n return 1\n}\n\n# Wait until etcd and apiserver pods are down.\nwait_for_etcd_and_apiserver_down() {\n for _ in $(seq 120); do\n etcd=$(docker ps | grep -c etcd-server)\n apiserver=$(docker ps | grep -c apiserver)\n # TODO: Theoretically it is possible, that apiserver and or etcd\n # are currently down, but Kubelet is now restarting them and they\n # will reappear again. We should avoid it.\n if [ \"${etcd}\" -eq \"0\" ] && [ \"${apiserver}\" -eq \"0\" ]; then\n return 0\n fi\n sleep 1\n done\n return 1\n}\n\n# Move the manifest files to stop etcd and kube-apiserver\n# while we swap the data out from under them.\nMANIFEST_DIR=\"/etc/kubernetes/manifests\"\nMANIFEST_BACKUP_DIR=\"/etc/kubernetes/manifests-backups\"\nmkdir -p \"${MANIFEST_BACKUP_DIR}\"\necho \"Moving etcd(s) & apiserver manifest files to ${MANIFEST_BACKUP_DIR}\"\n# If those files were already moved (e.g. during previous\n# try of backup) don't fail on it.\nmv \"${MANIFEST_DIR}/kube-apiserver.manifest\" \"${MANIFEST_BACKUP_DIR}\" || true\nmv \"${MANIFEST_DIR}/etcd.manifest\" \"${MANIFEST_BACKUP_DIR}\" || true\nmv \"${MANIFEST_DIR}/etcd-events.manifest\" \"${MANIFEST_BACKUP_DIR}\" || true\n\n# Wait for the pods to be stopped\necho \"Waiting for etcd and kube-apiserver to be down\"\nif ! wait_for_etcd_and_apiserver_down; then\n # Couldn't kill etcd and apiserver.\n echo \"Downing etcd and apiserver failed\"\n exit 1\nfi\n\nread -rsp $'Press enter when all etcd instances are down...\\n'\n\n# Create the sort of directory structure that etcd expects.\n# If this directory already exists, remove it.\nBACKUP_DIR=\"/var/tmp/backup\"\nrm -rf \"${BACKUP_DIR}\"\nif [ \"${ETCD_API}\" == \"etcd2\" ]; then\n echo \"Preparing etcd backup data for restore\"\n # In v2 mode, we simply copy both snap and wal files to a newly created\n # directory. After that, we start etcd with --force-new-cluster option\n # that (according to the etcd documentation) is required to recover from\n # a backup.\n echo \"Copying data to ${BACKUP_DIR} and restoring there\"\n mkdir -p \"${BACKUP_DIR}/member/snap\"\n mkdir -p \"${BACKUP_DIR}/member/wal\"\n # If the cluster is relatively new, there can be no .snap file.\n mv ./*.snap \"${BACKUP_DIR}/member/snap/\" || true\n mv ./*.wal \"${BACKUP_DIR}/member/wal/\"\n\n # TODO(jsz): This won't work with HA setups (e.g. do we need to set --name flag)?\n echo \"Starting etcd ${ETCD_VERSION} to restore data\"\n if ! image=$(docker run -d -v ${BACKUP_DIR}:/var/etcd/data \\\n --net=host -p ${etcd_port}:${etcd_port} \\\n \"k8s.gcr.io/etcd:${ETCD_VERSION}\" /bin/sh -c \\\n \"/usr/local/bin/etcd --data-dir /var/etcd/data --force-new-cluster\"); then\n echo \"Docker container didn't started correctly\"\n exit 1\n fi\n echo \"Container ${image} created, waiting for etcd to report as healthy\"\n\n if ! wait_for_etcd_up \"${etcd_port}\"; then\n echo \"Etcd didn't come back correctly\"\n exit 1\n fi\n\n # Kill that etcd instance.\n echo \"Etcd healthy - killing ${image} container\"\n docker kill \"${image}\"\nelif [ \"${ETCD_API}\" == \"etcd3\" ]; then\n echo \"Preparing etcd snapshot for restore\"\n mkdir -p \"${BACKUP_DIR}\"\n echo \"Copying data to ${BACKUP_DIR} and restoring there\"\n number_files=$(find . -maxdepth 1 -type f -name \"*.db\" | wc -l)\n if [ \"${number_files}\" -ne \"1\" ]; then\n echo \"Incorrect number of *.db files - expected 1\"\n exit 1\n fi\n mv ./*.db \"${BACKUP_DIR}/\"\n snapshot=\"$(ls ${BACKUP_DIR})\"\n\n # Run etcdctl snapshot restore command and wait until it is finished.\n # setting with --name in the etcd manifest file and then it seems to work.\n if ! docker run -v ${BACKUP_DIR}:/var/tmp/backup --env ETCDCTL_API=3 \\\n \"k8s.gcr.io/etcd:${ETCD_VERSION}\" /bin/sh -c \\\n \"/usr/local/bin/etcdctl snapshot restore ${BACKUP_DIR}/${snapshot} --name ${NAME} --initial-cluster ${INITIAL_CLUSTER} --initial-advertise-peer-urls ${INITIAL_ADVERTISE_PEER_URLS}; mv /${NAME}.etcd/member /var/tmp/backup/\"; then\n echo \"Docker container didn't started correctly\"\n exit 1\n fi\n\n rm -f \"${BACKUP_DIR}/${snapshot}\"\nfi\n# Also copy version.txt file.\ncp \"${VERSION_FILE}\" \"${BACKUP_DIR}\"\n\nexport MNT_DISK=\"/mnt/disks/master-pd\"\n\n# Save the corrupted data (clean directory if it is already non-empty).\nrm -rf \"${MNT_DISK}/var/etcd-corrupted\"\nmkdir -p \"${MNT_DISK}/var/etcd-corrupted\"\necho \"Saving corrupted data to ${MNT_DISK}/var/etcd-corrupted\"\nmv /var/etcd/data \"${MNT_DISK}/var/etcd-corrupted\"\n\n# Replace the corrupted data dir with the restored data.\necho \"Copying restored data to /var/etcd/data\"\nmv \"${BACKUP_DIR}\" /var/etcd/data\n\nif [ \"${RESET_EVENT_ETCD:-}\" == \"true\" ]; then\n echo \"Removing event-etcd corrupted data\"\n EVENTS_CORRUPTED_DIR=\"${MNT_DISK}/var/etcd-events-corrupted\"\n # Save the corrupted data (clean directory if it is already non-empty).\n rm -rf \"${EVENTS_CORRUPTED_DIR}\"\n mkdir -p \"${EVENTS_CORRUPTED_DIR}\"\n mv /var/etcd/data-events \"${EVENTS_CORRUPTED_DIR}\"\nfi\n\n# Start etcd and kube-apiserver again.\necho \"Restarting etcd and apiserver from restored snapshot\"\nmv \"${MANIFEST_BACKUP_DIR}\"/* \"${MANIFEST_DIR}/\"\nrm -rf \"${MANIFEST_BACKUP_DIR}\"\n\n# Verify that etcd is back.\necho \"Waiting for etcd to come back\"\nif ! wait_for_etcd_up \"${etcd_port}\"; then\n echo \"Etcd didn't come back correctly\"\n exit 1\nfi\n\n# Verify that event etcd is back.\necho \"Waiting for event etcd to come back\"\nif ! wait_for_etcd_up \"${event_etcd_port}\"; then\n echo \"Event etcd didn't come back correctly\"\n exit 1\nfi\n\n# Verify that kube-apiserver is back and cluster is healthy.\necho \"Waiting for apiserver to come back\"\nif ! wait_for_cluster_healthy; then\n echo \"Apiserver didn't come back correctly\"\n exit 1\nfi\n\necho \"Cluster successfully restored!\"\n"},"repo_name":{"kind":"string","value":"mkumatag/origin"},"path":{"kind":"string","value":"vendor/k8s.io/kubernetes/cluster/restore-from-backup.sh"},"language":{"kind":"string","value":"Shell"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":9389,"string":"9,389"}}},{"rowIdx":115086554,"cells":{"code":{"kind":"string","value":"import {isPresent, RegExpWrapper, StringWrapper} from 'angular2/src/core/facade/lang';\nimport {MapWrapper} from 'angular2/src/core/facade/collection';\n\nimport {Parser} from 'angular2/src/core/change_detection/change_detection';\n\nimport {CompileStep} from './compile_step';\nimport {CompileElement} from './compile_element';\nimport {CompileControl} from './compile_control';\n\nimport {dashCaseToCamelCase} from '../util';\n\n// Group 1 = \"bind-\"\n// Group 2 = \"var-\" or \"#\"\n// Group 3 = \"on-\"\n// Group 4 = \"bindon-\"\n// Group 5 = the identifier after \"bind-\", \"var-/#\", or \"on-\"\n// Group 6 = identifier inside [()]\n// Group 7 = identifier inside []\n// Group 8 = identifier inside ()\nvar BIND_NAME_REGEXP =\n /^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\\[\\(([^\\)]+)\\)\\]|\\[([^\\]]+)\\]|\\(([^\\)]+)\\))$/g;\n/**\n * Parses the property bindings on a single element.\n */\nexport class PropertyBindingParser implements CompileStep {\n constructor(private _parser: Parser) {}\n\n processStyle(style: string): string { return style; }\n\n processElement(parent: CompileElement, current: CompileElement, control: CompileControl) {\n var attrs = current.attrs();\n var newAttrs = new Map();\n\n MapWrapper.forEach(attrs, (attrValue, attrName) => {\n\n attrName = this._normalizeAttributeName(attrName);\n\n var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName);\n if (isPresent(bindParts)) {\n if (isPresent(bindParts[1])) { // match: bind-prop\n this._bindProperty(bindParts[5], attrValue, current, newAttrs);\n\n } else if (isPresent(\n bindParts[2])) { // match: var-name / var-name=\"iden\" / #name / #name=\"iden\"\n var identifier = bindParts[5];\n var value = attrValue == '' ? '\\$implicit' : attrValue;\n this._bindVariable(identifier, value, current, newAttrs);\n\n } else if (isPresent(bindParts[3])) { // match: on-event\n this._bindEvent(bindParts[5], attrValue, current, newAttrs);\n\n } else if (isPresent(bindParts[4])) { // match: bindon-prop\n this._bindProperty(bindParts[5], attrValue, current, newAttrs);\n this._bindAssignmentEvent(bindParts[5], attrValue, current, newAttrs);\n\n } else if (isPresent(bindParts[6])) { // match: [(expr)]\n this._bindProperty(bindParts[6], attrValue, current, newAttrs);\n this._bindAssignmentEvent(bindParts[6], attrValue, current, newAttrs);\n\n } else if (isPresent(bindParts[7])) { // match: [expr]\n this._bindProperty(bindParts[7], attrValue, current, newAttrs);\n\n } else if (isPresent(bindParts[8])) { // match: (event)\n this._bindEvent(bindParts[8], attrValue, current, newAttrs);\n }\n } else {\n var expr = this._parser.parseInterpolation(attrValue, current.elementDescription);\n if (isPresent(expr)) {\n this._bindPropertyAst(attrName, expr, current, newAttrs);\n }\n }\n });\n\n MapWrapper.forEach(newAttrs, (attrValue, attrName) => { attrs.set(attrName, attrValue); });\n }\n\n _normalizeAttributeName(attrName: string): string {\n return StringWrapper.startsWith(attrName, 'data-') ? StringWrapper.substring(attrName, 5) :\n attrName;\n }\n\n _bindVariable(identifier, value, current: CompileElement, newAttrs: Map) {\n current.bindElement().bindVariable(dashCaseToCamelCase(identifier), value);\n newAttrs.set(identifier, value);\n }\n\n _bindProperty(name, expression, current: CompileElement, newAttrs) {\n this._bindPropertyAst(name, this._parser.parseBinding(expression, current.elementDescription),\n current, newAttrs);\n }\n\n _bindPropertyAst(name, ast, current: CompileElement, newAttrs: Map) {\n var binder = current.bindElement();\n binder.bindProperty(dashCaseToCamelCase(name), ast);\n newAttrs.set(name, ast.source);\n }\n\n _bindAssignmentEvent(name, expression, current: CompileElement, newAttrs) {\n this._bindEvent(name, `${expression}=$event`, current, newAttrs);\n }\n\n _bindEvent(name, expression, current: CompileElement, newAttrs) {\n current.bindElement().bindEvent(\n dashCaseToCamelCase(name),\n this._parser.parseAction(expression, current.elementDescription));\n // Don't detect directives for event names for now,\n // so don't add the event name to the CompileElement.attrs\n }\n}\n"},"repo_name":{"kind":"string","value":"shahata/angular"},"path":{"kind":"string","value":"modules/angular2/src/core/render/dom/compiler/property_binding_parser.ts"},"language":{"kind":"string","value":"TypeScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":4415,"string":"4,415"}}},{"rowIdx":115086555,"cells":{"code":{"kind":"string","value":"public class Test {\n void fooBarGoo() {\n try {}\n finally {}\n fbg\n }\n}"},"repo_name":{"kind":"string","value":"smmribeiro/intellij-community"},"path":{"kind":"string","value":"java/java-tests/testData/codeInsight/completion/normal/MethodCallAfterFinally.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":87,"string":"87"}}},{"rowIdx":115086556,"cells":{"code":{"kind":"string","value":"\n\n\n \n \n \n \n\n

    Test transform change on reflected elements. Left and right side should be symmetrical.

    \n
    \n
    \n 1\n
    \n
    \n\n\n"},"repo_name":{"kind":"string","value":"js0701/chromium-crosswalk"},"path":{"kind":"string","value":"third_party/WebKit/LayoutTests/compositing/reflections/nested-reflection-transformed.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":959,"string":"959"}}},{"rowIdx":115086557,"cells":{"code":{"kind":"string","value":"# rank 1\nclass CandidateTest\n def test4\n end\n\n def test5\n end\nend\n"},"repo_name":{"kind":"string","value":"phstc/sshp"},"path":{"kind":"string","value":"vendor/ruby/1.9.1/gems/pry-0.9.12.2/spec/fixtures/candidate_helper2.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":70,"string":"70"}}},{"rowIdx":115086558,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2004, Instant802 Networks, Inc.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \"ieee80211_i.h\"\n#include \"wme.h\"\n\n/* Default mapping in classifier to work with default\n * queue setup.\n */\nconst int ieee802_1d_to_ac[8] = { 2, 3, 3, 2, 1, 1, 0, 0 };\n\nstatic int wme_downgrade_ac(struct sk_buff *skb)\n{\n\tswitch (skb->priority) {\n\tcase 6:\n\tcase 7:\n\t\tskb->priority = 5; /* VO -> VI */\n\t\treturn 0;\n\tcase 4:\n\tcase 5:\n\t\tskb->priority = 3; /* VI -> BE */\n\t\treturn 0;\n\tcase 0:\n\tcase 3:\n\t\tskb->priority = 2; /* BE -> BK */\n\t\treturn 0;\n\tdefault:\n\t\treturn -1;\n\t}\n}\n\n\n/* Indicate which queue to use. */\nu16 ieee80211_select_queue(struct ieee80211_sub_if_data *sdata,\n\t\t\t struct sk_buff *skb)\n{\n\tstruct ieee80211_local *local = sdata->local;\n\tstruct sta_info *sta = NULL;\n\tu32 sta_flags = 0;\n\tconst u8 *ra = NULL;\n\tbool qos = false;\n\n\tif (local->hw.queues < 4 || skb->len < 6) {\n\t\tskb->priority = 0; /* required for correct WPA/11i MIC */\n\t\treturn min_t(u16, local->hw.queues - 1,\n\t\t\t ieee802_1d_to_ac[skb->priority]);\n\t}\n\n\trcu_read_lock();\n\tswitch (sdata->vif.type) {\n\tcase NL80211_IFTYPE_AP_VLAN:\n\t\trcu_read_lock();\n\t\tsta = rcu_dereference(sdata->u.vlan.sta);\n\t\tif (sta)\n\t\t\tsta_flags = get_sta_flags(sta);\n\t\trcu_read_unlock();\n\t\tif (sta)\n\t\t\tbreak;\n\tcase NL80211_IFTYPE_AP:\n\t\tra = skb->data;\n\t\tbreak;\n\tcase NL80211_IFTYPE_WDS:\n\t\tra = sdata->u.wds.remote_addr;\n\t\tbreak;\n#ifdef CONFIG_MAC80211_MESH\n\tcase NL80211_IFTYPE_MESH_POINT:\n\t\tbreak;\n#endif\n\tcase NL80211_IFTYPE_STATION:\n\t\tra = sdata->u.mgd.bssid;\n\t\tbreak;\n\tcase NL80211_IFTYPE_ADHOC:\n\t\tra = skb->data;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (!sta && ra && !is_multicast_ether_addr(ra)) {\n\t\tsta = sta_info_get(sdata, ra);\n\t\tif (sta)\n\t\t\tsta_flags = get_sta_flags(sta);\n\t}\n\n\tif (sta_flags & WLAN_STA_WME)\n\t\tqos = true;\n\n\trcu_read_unlock();\n\n\tif (!qos) {\n\t\tskb->priority = 0; /* required for correct WPA/11i MIC */\n\t\treturn ieee802_1d_to_ac[skb->priority];\n\t}\n\n\t/* use the data classifier to determine what 802.1d tag the\n\t * data frame has */\n\tskb->priority = cfg80211_classify8021d(skb);\n\n\treturn ieee80211_downgrade_queue(local, skb);\n}\n\nu16 ieee80211_downgrade_queue(struct ieee80211_local *local,\n\t\t\t struct sk_buff *skb)\n{\n\t/* in case we are a client verify acm is not set for this ac */\n\twhile (unlikely(local->wmm_acm & BIT(skb->priority))) {\n\t\tif (wme_downgrade_ac(skb)) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* look up which queue to use for frames with this 1d tag */\n\treturn ieee802_1d_to_ac[skb->priority];\n}\n\nvoid ieee80211_set_qos_hdr(struct ieee80211_local *local, struct sk_buff *skb)\n{\n\tstruct ieee80211_hdr *hdr = (void *)skb->data;\n\n\t/* Fill in the QoS header if there is one. */\n\tif (ieee80211_is_data_qos(hdr->frame_control)) {\n\t\tu8 *p = ieee80211_get_qos_ctl(hdr);\n\t\tu8 ack_policy = 0, tid;\n\n\t\ttid = skb->priority & IEEE80211_QOS_CTL_TAG1D_MASK;\n\n\t\tif (unlikely(local->wifi_wme_noack_test))\n\t\t\tack_policy |= QOS_CONTROL_ACK_POLICY_NOACK <<\n\t\t\t\t\tQOS_CONTROL_ACK_POLICY_SHIFT;\n\t\t/* qos header is 2 bytes, second reserved */\n\t\t*p++ = ack_policy | tid;\n\t\t*p = 0;\n\t}\n}\n"},"repo_name":{"kind":"string","value":"sigma-random/asuswrt-merlin"},"path":{"kind":"string","value":"release/src-rt-7.x.main/src/linux/linux-2.6.36/net/mac80211/wme.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":3394,"string":"3,394"}}},{"rowIdx":115086559,"cells":{"code":{"kind":"string","value":"/* tuner-xc2028\n *\n * Copyright (c) 2007-2008 Mauro Carvalho Chehab (mchehab@infradead.org)\n * This code is placed under the terms of the GNU General Public License v2\n */\n\n#ifndef __TUNER_XC2028_H__\n#define __TUNER_XC2028_H__\n\n#include \"dvb_frontend.h\"\n\n#define XC2028_DEFAULT_FIRMWARE \"xc3028-v27.fw\"\n#define XC3028L_DEFAULT_FIRMWARE \"xc3028L-v36.fw\"\n\n/* Dmoduler\t\tIF (kHz) */\n#define\tXC3028_FE_DEFAULT\t0\t\t/* Don't load SCODE */\n#define XC3028_FE_LG60\t\t6000\n#define\tXC3028_FE_ATI638\t6380\n#define\tXC3028_FE_OREN538\t5380\n#define\tXC3028_FE_OREN36\t3600\n#define\tXC3028_FE_TOYOTA388\t3880\n#define\tXC3028_FE_TOYOTA794\t7940\n#define\tXC3028_FE_DIBCOM52\t5200\n#define\tXC3028_FE_ZARLINK456\t4560\n#define\tXC3028_FE_CHINA\t\t5200\n\nenum firmware_type {\n\tXC2028_AUTO = 0, /* By default, auto-detects */\n\tXC2028_D2633,\n\tXC2028_D2620,\n};\n\nstruct xc2028_ctrl {\n\tchar\t\t\t*fname;\n\tint\t\t\tmax_len;\n\tint\t\t\tmsleep;\n\tunsigned int\t\tscode_table;\n\tunsigned int\t\tmts :1;\n\tunsigned int\t\tinput1:1;\n\tunsigned int\t\tvhfbw7:1;\n\tunsigned int\t\tuhfbw8:1;\n\tunsigned int\t\tdisable_power_mgmt:1;\n\tunsigned int read_not_reliable:1;\n\tunsigned int\t\tdemod;\n\tenum firmware_type\ttype:2;\n};\n\nstruct xc2028_config {\n\tstruct i2c_adapter *i2c_adap;\n\tu8 \t\t i2c_addr;\n\tstruct xc2028_ctrl *ctrl;\n};\n\n/* xc2028 commands for callback */\n#define XC2028_TUNER_RESET\t0\n#define XC2028_RESET_CLK\t1\n\n#if defined(CONFIG_MEDIA_TUNER_XC2028) || (defined(CONFIG_MEDIA_TUNER_XC2028_MODULE) && \\\n\tdefined(MODULE))\nextern struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,\n\t\t\t\t\t struct xc2028_config *cfg);\n#else\nstatic inline struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,\n\t\t\t\t\t\t struct xc2028_config *cfg)\n{\n\tprintk(KERN_INFO \"%s: not probed - driver disabled by Kconfig\\n\",\n\t __func__);\n\treturn NULL;\n}\n#endif\n\n#endif /* __TUNER_XC2028_H__ */\n"},"repo_name":{"kind":"string","value":"wkritzinger/asuswrt-merlin"},"path":{"kind":"string","value":"release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/media/common/tuners/tuner-xc2028.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":1827,"string":"1,827"}}},{"rowIdx":115086560,"cells":{"code":{"kind":"string","value":"#define PRISM2_PCCARD\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"hostap_wlan.h\"\n\n\nstatic char *dev_info = \"hostap_cs\";\n\nMODULE_AUTHOR(\"Jouni Malinen\");\nMODULE_DESCRIPTION(\"Support for Intersil Prism2-based 802.11 wireless LAN \"\n\t\t \"cards (PC Card).\");\nMODULE_SUPPORTED_DEVICE(\"Intersil Prism2-based WLAN cards (PC Card)\");\nMODULE_LICENSE(\"GPL\");\n\n\nstatic int ignore_cis_vcc;\nmodule_param(ignore_cis_vcc, int, 0444);\nMODULE_PARM_DESC(ignore_cis_vcc, \"Ignore broken CIS VCC entry\");\n\n\n/* struct local_info::hw_priv */\nstruct hostap_cs_priv {\n\tstruct pcmcia_device *link;\n\tint sandisk_connectplus;\n};\n\n\n#ifdef PRISM2_IO_DEBUG\n\nstatic inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v);\n\toutb(v, dev->base_addr + a);\n\tspin_unlock_irqrestore(&local->lock, flags);\n}\n\nstatic inline u8 hfa384x_inb_debug(struct net_device *dev, int a)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\tu8 v;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tv = inb(dev->base_addr + a);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v);\n\tspin_unlock_irqrestore(&local->lock, flags);\n\treturn v;\n}\n\nstatic inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v);\n\toutw(v, dev->base_addr + a);\n\tspin_unlock_irqrestore(&local->lock, flags);\n}\n\nstatic inline u16 hfa384x_inw_debug(struct net_device *dev, int a)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\tu16 v;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tv = inw(dev->base_addr + a);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v);\n\tspin_unlock_irqrestore(&local->lock, flags);\n\treturn v;\n}\n\nstatic inline void hfa384x_outsw_debug(struct net_device *dev, int a,\n\t\t\t\t u8 *buf, int wc)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc);\n\toutsw(dev->base_addr + a, buf, wc);\n\tspin_unlock_irqrestore(&local->lock, flags);\n}\n\nstatic inline void hfa384x_insw_debug(struct net_device *dev, int a,\n\t\t\t\t u8 *buf, int wc)\n{\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tunsigned long flags;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tspin_lock_irqsave(&local->lock, flags);\n\tprism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc);\n\tinsw(dev->base_addr + a, buf, wc);\n\tspin_unlock_irqrestore(&local->lock, flags);\n}\n\n#define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v))\n#define HFA384X_INB(a) hfa384x_inb_debug(dev, (a))\n#define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v))\n#define HFA384X_INW(a) hfa384x_inw_debug(dev, (a))\n#define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc))\n#define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc))\n\n#else /* PRISM2_IO_DEBUG */\n\n#define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a))\n#define HFA384X_INB(a) inb(dev->base_addr + (a))\n#define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a))\n#define HFA384X_INW(a) inw(dev->base_addr + (a))\n#define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc)\n#define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc)\n\n#endif /* PRISM2_IO_DEBUG */\n\n\nstatic int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf,\n\t\t\t int len)\n{\n\tu16 d_off;\n\tu16 *pos;\n\n\td_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;\n\tpos = (u16 *) buf;\n\n\tif (len / 2)\n\t\tHFA384X_INSW(d_off, buf, len / 2);\n\tpos += len / 2;\n\n\tif (len & 1)\n\t\t*((char *) pos) = HFA384X_INB(d_off);\n\n\treturn 0;\n}\n\n\nstatic int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len)\n{\n\tu16 d_off;\n\tu16 *pos;\n\n\td_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;\n\tpos = (u16 *) buf;\n\n\tif (len / 2)\n\t\tHFA384X_OUTSW(d_off, buf, len / 2);\n\tpos += len / 2;\n\n\tif (len & 1)\n\t\tHFA384X_OUTB(*((char *) pos), d_off);\n\n\treturn 0;\n}\n\n\n/* FIX: This might change at some point.. */\n#include \"hostap_hw.c\"\n\n\n\nstatic void prism2_detach(struct pcmcia_device *p_dev);\nstatic void prism2_release(u_long arg);\nstatic int prism2_config(struct pcmcia_device *link);\n\n\nstatic int prism2_pccard_card_present(local_info_t *local)\n{\n\tstruct hostap_cs_priv *hw_priv = local->hw_priv;\n\tif (hw_priv != NULL && hw_priv->link != NULL && pcmcia_dev_present(hw_priv->link))\n\t\treturn 1;\n\treturn 0;\n}\n\n\n/*\n * SanDisk CompactFlash WLAN Flashcard - Product Manual v1.0\n * Document No. 20-10-00058, January 2004\n * http://www.sandisk.com/pdf/industrial/ProdManualCFWLANv1.0.pdf\n */\n#define SANDISK_WLAN_ACTIVATION_OFF 0x40\n#define SANDISK_HCR_OFF 0x42\n\n\nstatic void sandisk_set_iobase(local_info_t *local)\n{\n\tint res;\n\tstruct hostap_cs_priv *hw_priv = local->hw_priv;\n\n\tres = pcmcia_write_config_byte(hw_priv->link, 0x10,\n\t\t\t\thw_priv->link->resource[0]->start & 0x00ff);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"Prism3 SanDisk - failed to set I/O base 0 -\"\n\t\t \" res=%d\\n\", res);\n\t}\n\tudelay(10);\n\n\tres = pcmcia_write_config_byte(hw_priv->link, 0x12,\n\t\t\t\t(hw_priv->link->resource[0]->start >> 8) & 0x00ff);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"Prism3 SanDisk - failed to set I/O base 1 -\"\n\t\t \" res=%d\\n\", res);\n\t}\n}\n\n\nstatic void sandisk_write_hcr(local_info_t *local, int hcr)\n{\n\tstruct net_device *dev = local->dev;\n\tint i;\n\n\tHFA384X_OUTB(0x80, SANDISK_WLAN_ACTIVATION_OFF);\n\tudelay(50);\n\tfor (i = 0; i < 10; i++) {\n\t\tHFA384X_OUTB(hcr, SANDISK_HCR_OFF);\n\t}\n\tudelay(55);\n\tHFA384X_OUTB(0x45, SANDISK_WLAN_ACTIVATION_OFF);\n}\n\n\nstatic int sandisk_enable_wireless(struct net_device *dev)\n{\n\tint res, ret = 0;\n\tstruct hostap_interface *iface = netdev_priv(dev);\n\tlocal_info_t *local = iface->local;\n\tstruct hostap_cs_priv *hw_priv = local->hw_priv;\n\n\tif (resource_size(hw_priv->link->resource[0]) < 0x42) {\n\t\t/* Not enough ports to be SanDisk multi-function card */\n\t\tret = -ENODEV;\n\t\tgoto done;\n\t}\n\n\tif (hw_priv->link->manf_id != 0xd601 || hw_priv->link->card_id != 0x0101) {\n\t\t/* No SanDisk manfid found */\n\t\tret = -ENODEV;\n\t\tgoto done;\n\t}\n\n\tif (hw_priv->link->socket->functions < 2) {\n\t\t/* No multi-function links found */\n\t\tret = -ENODEV;\n\t\tgoto done;\n\t}\n\n\tprintk(KERN_DEBUG \"%s: Multi-function SanDisk ConnectPlus detected\"\n\t \" - using vendor-specific initialization\\n\", dev->name);\n\thw_priv->sandisk_connectplus = 1;\n\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,\n\t\t\t\tCOR_SOFT_RESET);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"%s: SanDisk - COR sreset failed (%d)\\n\",\n\t\t dev->name, res);\n\t\tgoto done;\n\t}\n\tmdelay(5);\n\n\t/*\n\t * Do not enable interrupts here to avoid some bogus events. Interrupts\n\t * will be enabled during the first cor_sreset call.\n\t */\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,\n\t\t\t\t(COR_LEVEL_REQ | 0x8 | COR_ADDR_DECODE |\n\t\t\t\t\tCOR_FUNC_ENA));\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"%s: SanDisk - COR sreset failed (%d)\\n\",\n\t\t dev->name, res);\n\t\tgoto done;\n\t}\n\tmdelay(5);\n\n\tsandisk_set_iobase(local);\n\n\tHFA384X_OUTB(0xc5, SANDISK_WLAN_ACTIVATION_OFF);\n\tudelay(10);\n\tHFA384X_OUTB(0x4b, SANDISK_WLAN_ACTIVATION_OFF);\n\tudelay(10);\n\ndone:\n\treturn ret;\n}\n\n\nstatic void prism2_pccard_cor_sreset(local_info_t *local)\n{\n\tint res;\n\tu8 val;\n\tstruct hostap_cs_priv *hw_priv = local->hw_priv;\n\n\tif (!prism2_pccard_card_present(local))\n\t return;\n\n\tres = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &val);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_cor_sreset failed 1 (%d)\\n\",\n\t\t res);\n\t\treturn;\n\t}\n\tprintk(KERN_DEBUG \"prism2_pccard_cor_sreset: original COR %02x\\n\",\n\t\tval);\n\n\tval |= COR_SOFT_RESET;\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_cor_sreset failed 2 (%d)\\n\",\n\t\t res);\n\t\treturn;\n\t}\n\n\tmdelay(hw_priv->sandisk_connectplus ? 5 : 2);\n\n\tval &= ~COR_SOFT_RESET;\n\tif (hw_priv->sandisk_connectplus)\n\t\tval |= COR_IREQ_ENA;\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_cor_sreset failed 3 (%d)\\n\",\n\t\t res);\n\t\treturn;\n\t}\n\n\tmdelay(hw_priv->sandisk_connectplus ? 5 : 2);\n\n\tif (hw_priv->sandisk_connectplus)\n\t\tsandisk_set_iobase(local);\n}\n\n\nstatic void prism2_pccard_genesis_reset(local_info_t *local, int hcr)\n{\n\tint res;\n\tu8 old_cor;\n\tstruct hostap_cs_priv *hw_priv = local->hw_priv;\n\n\tif (!prism2_pccard_card_present(local))\n\t return;\n\n\tif (hw_priv->sandisk_connectplus) {\n\t\tsandisk_write_hcr(local, hcr);\n\t\treturn;\n\t}\n\n\tres = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &old_cor);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_genesis_sreset failed 1 \"\n\t\t \"(%d)\\n\", res);\n\t\treturn;\n\t}\n\tprintk(KERN_DEBUG \"prism2_pccard_genesis_sreset: original COR %02x\\n\",\n\t\told_cor);\n\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,\n\t\t\t\told_cor | COR_SOFT_RESET);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_genesis_sreset failed 2 \"\n\t\t \"(%d)\\n\", res);\n\t\treturn;\n\t}\n\n\tmdelay(10);\n\n\t/* Setup Genesis mode */\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_CCSR, hcr);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_genesis_sreset failed 3 \"\n\t\t \"(%d)\\n\", res);\n\t\treturn;\n\t}\n\tmdelay(10);\n\n\tres = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,\n\t\t\t\told_cor & ~COR_SOFT_RESET);\n\tif (res != 0) {\n\t\tprintk(KERN_DEBUG \"prism2_pccard_genesis_sreset failed 4 \"\n\t\t \"(%d)\\n\", res);\n\t\treturn;\n\t}\n\n\tmdelay(10);\n}\n\n\nstatic struct prism2_helper_functions prism2_pccard_funcs =\n{\n\t.card_present\t= prism2_pccard_card_present,\n\t.cor_sreset\t= prism2_pccard_cor_sreset,\n\t.genesis_reset\t= prism2_pccard_genesis_reset,\n\t.hw_type\t= HOSTAP_HW_PCCARD,\n};\n\n\n/* allocate local data and register with CardServices\n * initialize dev_link structure, but do not configure the card yet */\nstatic int hostap_cs_probe(struct pcmcia_device *p_dev)\n{\n\tint ret;\n\n\tPDEBUG(DEBUG_HW, \"%s: setting Vcc=33 (constant)\\n\", dev_info);\n\n\tret = prism2_config(p_dev);\n\tif (ret) {\n\t\tPDEBUG(DEBUG_EXTRA, \"prism2_config() failed\\n\");\n\t}\n\n\treturn ret;\n}\n\n\nstatic void prism2_detach(struct pcmcia_device *link)\n{\n\tPDEBUG(DEBUG_FLOW, \"prism2_detach\\n\");\n\n\tprism2_release((u_long)link);\n\n\t/* release net devices */\n\tif (link->priv) {\n\t\tstruct hostap_cs_priv *hw_priv;\n\t\tstruct net_device *dev;\n\t\tstruct hostap_interface *iface;\n\t\tdev = link->priv;\n\t\tiface = netdev_priv(dev);\n\t\thw_priv = iface->local->hw_priv;\n\t\tprism2_free_local_data(dev);\n\t\tkfree(hw_priv);\n\t}\n}\n\n\nstatic int prism2_config_check(struct pcmcia_device *p_dev, void *priv_data)\n{\n\tif (p_dev->config_index == 0)\n\t\treturn -EINVAL;\n\n\treturn pcmcia_request_io(p_dev);\n}\n\nstatic int prism2_config(struct pcmcia_device *link)\n{\n\tstruct net_device *dev;\n\tstruct hostap_interface *iface;\n\tlocal_info_t *local;\n\tint ret = 1;\n\tstruct hostap_cs_priv *hw_priv;\n\tunsigned long flags;\n\n\tPDEBUG(DEBUG_FLOW, \"prism2_config()\\n\");\n\n\thw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL);\n\tif (hw_priv == NULL) {\n\t\tret = -ENOMEM;\n\t\tgoto failed;\n\t}\n\n\t/* Look for an appropriate configuration table entry in the CIS */\n\tlink->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_AUDIO |\n\t\tCONF_AUTO_CHECK_VCC | CONF_AUTO_SET_IO | CONF_ENABLE_IRQ;\n\tif (ignore_cis_vcc)\n\t\tlink->config_flags &= ~CONF_AUTO_CHECK_VCC;\n\tret = pcmcia_loop_config(link, prism2_config_check, NULL);\n\tif (ret) {\n\t\tif (!ignore_cis_vcc)\n\t\t\tprintk(KERN_ERR \"GetNextTuple(): No matching \"\n\t\t\t \"CIS configuration. Maybe you need the \"\n\t\t\t \"ignore_cis_vcc=1 parameter.\\n\");\n\t\tgoto failed;\n\t}\n\n\t/* Need to allocate net_device before requesting IRQ handler */\n\tdev = prism2_init_local_data(&prism2_pccard_funcs, 0,\n\t\t\t\t &link->dev);\n\tif (dev == NULL)\n\t\tgoto failed;\n\tlink->priv = dev;\n\n\tiface = netdev_priv(dev);\n\tlocal = iface->local;\n\tlocal->hw_priv = hw_priv;\n\thw_priv->link = link;\n\n\t/*\n\t * Make sure the IRQ handler cannot proceed until at least\n\t * dev->base_addr is initialized.\n\t */\n\tspin_lock_irqsave(&local->irq_init_lock, flags);\n\n\tret = pcmcia_request_irq(link, prism2_interrupt);\n\tif (ret)\n\t\tgoto failed_unlock;\n\n\tret = pcmcia_enable_device(link);\n\tif (ret)\n\t\tgoto failed_unlock;\n\n\tdev->irq = link->irq;\n\tdev->base_addr = link->resource[0]->start;\n\n\tspin_unlock_irqrestore(&local->irq_init_lock, flags);\n\n\tlocal->shutdown = 0;\n\n\tsandisk_enable_wireless(dev);\n\n\tret = prism2_hw_config(dev, 1);\n\tif (!ret)\n\t\tret = hostap_hw_ready(dev);\n\n\treturn ret;\n\n failed_unlock:\n\tspin_unlock_irqrestore(&local->irq_init_lock, flags);\n failed:\n\tkfree(hw_priv);\n\tprism2_release((u_long)link);\n\treturn ret;\n}\n\n\nstatic void prism2_release(u_long arg)\n{\n\tstruct pcmcia_device *link = (struct pcmcia_device *)arg;\n\n\tPDEBUG(DEBUG_FLOW, \"prism2_release\\n\");\n\n\tif (link->priv) {\n\t\tstruct net_device *dev = link->priv;\n\t\tstruct hostap_interface *iface;\n\n\t\tiface = netdev_priv(dev);\n\t\tprism2_hw_shutdown(dev, 0);\n\t\tiface->local->shutdown = 1;\n\t}\n\n\tpcmcia_disable_device(link);\n\tPDEBUG(DEBUG_FLOW, \"release - done\\n\");\n}\n\nstatic int hostap_cs_suspend(struct pcmcia_device *link)\n{\n\tstruct net_device *dev = (struct net_device *) link->priv;\n\tint dev_open = 0;\n\tstruct hostap_interface *iface = NULL;\n\n\tif (!dev)\n\t\treturn -ENODEV;\n\n\tiface = netdev_priv(dev);\n\n\tPDEBUG(DEBUG_EXTRA, \"%s: CS_EVENT_PM_SUSPEND\\n\", dev_info);\n\tif (iface && iface->local)\n\t\tdev_open = iface->local->num_dev_open > 0;\n\tif (dev_open) {\n\t\tnetif_stop_queue(dev);\n\t\tnetif_device_detach(dev);\n\t}\n\tprism2_suspend(dev);\n\n\treturn 0;\n}\n\nstatic int hostap_cs_resume(struct pcmcia_device *link)\n{\n\tstruct net_device *dev = (struct net_device *) link->priv;\n\tint dev_open = 0;\n\tstruct hostap_interface *iface = NULL;\n\n\tif (!dev)\n\t\treturn -ENODEV;\n\n\tiface = netdev_priv(dev);\n\n\tPDEBUG(DEBUG_EXTRA, \"%s: CS_EVENT_PM_RESUME\\n\", dev_info);\n\n\tif (iface && iface->local)\n\t\tdev_open = iface->local->num_dev_open > 0;\n\n\tprism2_hw_shutdown(dev, 1);\n\tprism2_hw_config(dev, dev_open ? 0 : 1);\n\tif (dev_open) {\n\t\tnetif_device_attach(dev);\n\t\tnetif_start_queue(dev);\n\t}\n\n\treturn 0;\n}\n\nstatic struct pcmcia_device_id hostap_cs_ids[] = {\n\tPCMCIA_DEVICE_MANF_CARD(0x000b, 0x7100),\n\tPCMCIA_DEVICE_MANF_CARD(0x000b, 0x7300),\n\tPCMCIA_DEVICE_MANF_CARD(0x0101, 0x0777),\n\tPCMCIA_DEVICE_MANF_CARD(0x0126, 0x8000),\n\tPCMCIA_DEVICE_MANF_CARD(0x0138, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0x01bf, 0x3301),\n\tPCMCIA_DEVICE_MANF_CARD(0x0250, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0x026f, 0x030b),\n\tPCMCIA_DEVICE_MANF_CARD(0x0274, 0x1612),\n\tPCMCIA_DEVICE_MANF_CARD(0x0274, 0x1613),\n\tPCMCIA_DEVICE_MANF_CARD(0x028a, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0x02aa, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0x02d2, 0x0001),\n\tPCMCIA_DEVICE_MANF_CARD(0x50c2, 0x0001),\n\tPCMCIA_DEVICE_MANF_CARD(0x50c2, 0x7300),\n/*\tPCMCIA_DEVICE_MANF_CARD(0xc00f, 0x0000), conflict with pcnet_cs */\n\tPCMCIA_DEVICE_MANF_CARD(0xc250, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0xd601, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD(0xd601, 0x0005),\n\tPCMCIA_DEVICE_MANF_CARD(0xd601, 0x0010),\n\tPCMCIA_DEVICE_MANF_CARD(0x0126, 0x0002),\n\tPCMCIA_DEVICE_MANF_CARD_PROD_ID1(0xd601, 0x0005, \"ADLINK 345 CF\",\n\t\t\t\t\t 0x2d858104),\n\tPCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, \"INTERSIL\",\n\t\t\t\t\t 0x74c5e40d),\n\tPCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, \"Intersil\",\n\t\t\t\t\t 0x4b801a17),\n\tPCMCIA_MFC_DEVICE_PROD_ID12(0, \"SanDisk\", \"ConnectPlus\",\n\t\t\t\t 0x7a954bd9, 0x74be00c6),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"Addtron\", \"AWP-100 Wireless PCMCIA\", \"Version 01.02\",\n\t\t0xe6ec52ce, 0x08649af2, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"D\", \"Link DWL-650 11Mbps WLAN Card\", \"Version 01.02\",\n\t\t0x71b18589, 0xb6f1b0ab, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"Instant Wireless \", \" Network PC CARD\", \"Version 01.02\",\n\t\t0x11d901af, 0x6e9bd926, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"SMC\", \"SMC2632W\", \"Version 01.02\",\n\t\t0xc4f8b18b, 0x474a1f2a, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID12(\"BUFFALO\", \"WLI-CF-S11G\", \n\t\t\t\t0x2decece3, 0x82067c18),\n\tPCMCIA_DEVICE_PROD_ID12(\"Compaq\", \"WL200_11Mbps_Wireless_PCI_Card\",\n\t\t\t\t0x54f7c49c, 0x15a75e5b),\n\tPCMCIA_DEVICE_PROD_ID12(\"INTERSIL\", \"HFA384x/IEEE\",\n\t\t\t\t0x74c5e40d, 0xdb472a18),\n\tPCMCIA_DEVICE_PROD_ID12(\"Linksys\", \"Wireless CompactFlash Card\",\n\t\t\t\t0x0733cc81, 0x0c52f395),\n\tPCMCIA_DEVICE_PROD_ID12(\n\t\t\"ZoomAir 11Mbps High\", \"Rate wireless Networking\",\n\t\t0x273fe3db, 0x32a1eaee),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"Pretec\", \"CompactWLAN Card 802.11b\", \"2.5\",\n\t\t0x1cadd3e5, 0xe697636c, 0x7a5bfcf1),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"U.S. Robotics\", \"IEEE 802.11b PC-CARD\", \"Version 01.02\",\n\t\t0xc7b8df9d, 0x1700d087, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"Allied Telesyn\", \"AT-WCL452 Wireless PCMCIA Radio\",\n\t\t\"Ver. 1.00\",\n\t\t0x5cd01705, 0x4271660f, 0x9d08ee12),\n\tPCMCIA_DEVICE_PROD_ID123(\n\t\t\"Wireless LAN\" , \"11Mbps PC Card\", \"Version 01.02\",\n\t\t0x4b8870ff, 0x70e946d1, 0x4b74baa0),\n\tPCMCIA_DEVICE_PROD_ID3(\"HFA3863\", 0x355cb092),\n\tPCMCIA_DEVICE_PROD_ID3(\"ISL37100P\", 0x630d52b2),\n\tPCMCIA_DEVICE_PROD_ID3(\"ISL37101P-10\", 0xdd97a26b),\n\tPCMCIA_DEVICE_PROD_ID3(\"ISL37300P\", 0xc9049a39),\n\tPCMCIA_DEVICE_NULL\n};\nMODULE_DEVICE_TABLE(pcmcia, hostap_cs_ids);\n\n\nstatic struct pcmcia_driver hostap_driver = {\n\t.name\t\t= \"hostap_cs\",\n\t.probe\t\t= hostap_cs_probe,\n\t.remove\t\t= prism2_detach,\n\t.owner\t\t= THIS_MODULE,\n\t.id_table\t= hostap_cs_ids,\n\t.suspend\t= hostap_cs_suspend,\n\t.resume\t\t= hostap_cs_resume,\n};\n\nstatic int __init init_prism2_pccard(void)\n{\n\treturn pcmcia_register_driver(&hostap_driver);\n}\n\nstatic void __exit exit_prism2_pccard(void)\n{\n\tpcmcia_unregister_driver(&hostap_driver);\n}\n\n\nmodule_init(init_prism2_pccard);\nmodule_exit(exit_prism2_pccard);\n"},"repo_name":{"kind":"string","value":"nazgee/igep-kernel"},"path":{"kind":"string","value":"drivers/net/wireless/hostap/hostap_cs.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":18243,"string":"18,243"}}},{"rowIdx":115086561,"cells":{"code":{"kind":"string","value":"import frappe\n\ndef execute():\n\tduplicates = frappe.db.sql(\"\"\"select email_group, email, count(name)\n\t\tfrom `tabEmail Group Member`\n\t\tgroup by email_group, email\n\t\thaving count(name) > 1\"\"\")\n\n\t# delete all duplicates except 1\n\tfor email_group, email, count in duplicates:\n\t\tfrappe.db.sql(\"\"\"delete from `tabEmail Group Member`\n\t\t\twhere email_group=%s and email=%s limit %s\"\"\", (email_group, email, count-1))\n"},"repo_name":{"kind":"string","value":"hassanibi/erpnext"},"path":{"kind":"string","value":"erpnext/patches/v6_2/remove_newsletter_duplicates.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":407,"string":"407"}}},{"rowIdx":115086562,"cells":{"code":{"kind":"string","value":"import { Subscriber } from '../Subscriber';\nimport { tryCatch } from '../util/tryCatch';\nimport { errorObject } from '../util/errorObject';\n/**\n * Compares all values of two observables in sequence using an optional comparor function\n * and returns an observable of a single boolean value representing whether or not the two sequences\n * are equal.\n *\n * Checks to see of all values emitted by both observables are equal, in order.\n *\n * \n *\n * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either\n * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom\n * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the\n * observables completes, the operator will wait for the other observable to complete; If the other\n * observable emits before completing, the returned observable will emit `false` and complete. If one observable never\n * completes or emits after the other complets, the returned observable will never complete.\n *\n * @example figure out if the Konami code matches\n * var code = Rx.Observable.from([\n * \"ArrowUp\",\n * \"ArrowUp\",\n * \"ArrowDown\",\n * \"ArrowDown\",\n * \"ArrowLeft\",\n * \"ArrowRight\",\n * \"ArrowLeft\",\n * \"ArrowRight\",\n * \"KeyB\",\n * \"KeyA\",\n * \"Enter\" // no start key, clearly.\n * ]);\n *\n * var keys = Rx.Observable.fromEvent(document, 'keyup')\n * .map(e => e.code);\n * var matches = keys.bufferCount(11, 1)\n * .mergeMap(\n * last11 =>\n * Rx.Observable.from(last11)\n * .sequenceEqual(code)\n * );\n * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n * @see {@link withLatestFrom}\n *\n * @param {Observable} compareTo The observable sequence to compare the source sequence to.\n * @param {function} [comparor] An optional function to compare each value pair\n * @return {Observable} An Observable of a single boolean value representing whether or not\n * the values emitted by both observables were equal in sequence.\n * @method sequenceEqual\n * @owner Observable\n */\nexport function sequenceEqual(compareTo, comparor) {\n return (source) => source.lift(new SequenceEqualOperator(compareTo, comparor));\n}\nexport class SequenceEqualOperator {\n constructor(compareTo, comparor) {\n this.compareTo = compareTo;\n this.comparor = comparor;\n }\n call(subscriber, source) {\n return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));\n }\n}\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SequenceEqualSubscriber extends Subscriber {\n constructor(destination, compareTo, comparor) {\n super(destination);\n this.compareTo = compareTo;\n this.comparor = comparor;\n this._a = [];\n this._b = [];\n this._oneComplete = false;\n this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));\n }\n _next(value) {\n if (this._oneComplete && this._b.length === 0) {\n this.emit(false);\n }\n else {\n this._a.push(value);\n this.checkValues();\n }\n }\n _complete() {\n if (this._oneComplete) {\n this.emit(this._a.length === 0 && this._b.length === 0);\n }\n else {\n this._oneComplete = true;\n }\n }\n checkValues() {\n const { _a, _b, comparor } = this;\n while (_a.length > 0 && _b.length > 0) {\n let a = _a.shift();\n let b = _b.shift();\n let areEqual = false;\n if (comparor) {\n areEqual = tryCatch(comparor)(a, b);\n if (areEqual === errorObject) {\n this.destination.error(errorObject.e);\n }\n }\n else {\n areEqual = a === b;\n }\n if (!areEqual) {\n this.emit(false);\n }\n }\n }\n emit(value) {\n const { destination } = this;\n destination.next(value);\n destination.complete();\n }\n nextB(value) {\n if (this._oneComplete && this._a.length === 0) {\n this.emit(false);\n }\n else {\n this._b.push(value);\n this.checkValues();\n }\n }\n}\nclass SequenceEqualCompareToSubscriber extends Subscriber {\n constructor(destination, parent) {\n super(destination);\n this.parent = parent;\n }\n _next(value) {\n this.parent.nextB(value);\n }\n _error(err) {\n this.parent.error(err);\n }\n _complete() {\n this.parent._complete();\n }\n}\n//# sourceMappingURL=sequenceEqual.js.map"},"repo_name":{"kind":"string","value":"rospilot/rospilot"},"path":{"kind":"string","value":"share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operators/sequenceEqual.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":4896,"string":"4,896"}}},{"rowIdx":115086563,"cells":{"code":{"kind":"string","value":"/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage aws_ebs\n\nimport (\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/golang/glog\"\n\t\"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/types\"\n\t\"k8s.io/kubernetes/pkg/cloudprovider/providers/aws\"\n\t\"k8s.io/kubernetes/pkg/util/mount\"\n\tkstrings \"k8s.io/kubernetes/pkg/util/strings\"\n\t\"k8s.io/kubernetes/pkg/volume\"\n\t\"k8s.io/kubernetes/pkg/volume/util\"\n\t\"k8s.io/kubernetes/pkg/volume/util/volumepathhandler\"\n)\n\nvar _ volume.VolumePlugin = &awsElasticBlockStorePlugin{}\nvar _ volume.PersistentVolumePlugin = &awsElasticBlockStorePlugin{}\nvar _ volume.BlockVolumePlugin = &awsElasticBlockStorePlugin{}\nvar _ volume.DeletableVolumePlugin = &awsElasticBlockStorePlugin{}\nvar _ volume.ProvisionableVolumePlugin = &awsElasticBlockStorePlugin{}\n\nfunc (plugin *awsElasticBlockStorePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {\n\tpluginDir := plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName)\n\tblkutil := volumepathhandler.NewBlockVolumePathHandler()\n\tglobalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tglog.V(5).Infof(\"globalMapPathUUID: %s\", globalMapPathUUID)\n\n\tglobalMapPath := filepath.Dir(globalMapPathUUID)\n\tif len(globalMapPath) <= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get volume plugin information from globalMapPathUUID: %v\", globalMapPathUUID)\n\t}\n\n\treturn getVolumeSpecFromGlobalMapPath(globalMapPath)\n}\n\nfunc getVolumeSpecFromGlobalMapPath(globalMapPath string) (*volume.Spec, error) {\n\t// Get volume spec information from globalMapPath\n\t// globalMapPath example:\n\t// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID}\n\t// plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX\n\tvID := filepath.Base(globalMapPath)\n\tif len(vID) <= 1 {\n\t\treturn nil, fmt.Errorf(\"failed to get volumeID from global path=%s\", globalMapPath)\n\t}\n\tif !strings.Contains(vID, \"vol-\") {\n\t\treturn nil, fmt.Errorf(\"failed to get volumeID from global path=%s, invalid volumeID format = %s\", globalMapPath, vID)\n\t}\n\tblock := v1.PersistentVolumeBlock\n\tawsVolume := &v1.PersistentVolume{\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tAWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{\n\t\t\t\t\tVolumeID: vID,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMode: &block,\n\t\t},\n\t}\n\n\treturn volume.NewSpecFromPersistentVolume(awsVolume, true), nil\n}\n\n// NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification.\nfunc (plugin *awsElasticBlockStorePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {\n\t// If this is called via GenerateUnmapDeviceFunc(), pod is nil.\n\t// Pass empty string as dummy uid since uid isn't used in the case.\n\tvar uid types.UID\n\tif pod != nil {\n\t\tuid = pod.UID\n\t}\n\n\treturn plugin.newBlockVolumeMapperInternal(spec, uid, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}\n\nfunc (plugin *awsElasticBlockStorePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) {\n\tebs, readOnly, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvolumeID := aws.KubernetesVolumeID(ebs.VolumeID)\n\tpartition := \"\"\n\tif ebs.Partition != 0 {\n\t\tpartition = strconv.Itoa(int(ebs.Partition))\n\t}\n\n\treturn &awsElasticBlockStoreMapper{\n\t\tawsElasticBlockStore: &awsElasticBlockStore{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: spec.Name(),\n\t\t\tvolumeID: volumeID,\n\t\t\tpartition: partition,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t},\n\t\treadOnly: readOnly}, nil\n}\n\nfunc (plugin *awsElasticBlockStorePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {\n\treturn plugin.newUnmapperInternal(volName, podUID, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))\n}\n\nfunc (plugin *awsElasticBlockStorePlugin) newUnmapperInternal(volName string, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeUnmapper, error) {\n\treturn &awsElasticBlockStoreUnmapper{\n\t\tawsElasticBlockStore: &awsElasticBlockStore{\n\t\t\tpodUID: podUID,\n\t\t\tvolName: volName,\n\t\t\tmanager: manager,\n\t\t\tmounter: mounter,\n\t\t\tplugin: plugin,\n\t\t}}, nil\n}\n\nfunc (c *awsElasticBlockStoreUnmapper) TearDownDevice(mapPath, devicePath string) error {\n\treturn nil\n}\n\ntype awsElasticBlockStoreUnmapper struct {\n\t*awsElasticBlockStore\n}\n\nvar _ volume.BlockVolumeUnmapper = &awsElasticBlockStoreUnmapper{}\n\ntype awsElasticBlockStoreMapper struct {\n\t*awsElasticBlockStore\n\treadOnly bool\n}\n\nvar _ volume.BlockVolumeMapper = &awsElasticBlockStoreMapper{}\n\nfunc (b *awsElasticBlockStoreMapper) SetUpDevice() (string, error) {\n\treturn \"\", nil\n}\n\nfunc (b *awsElasticBlockStoreMapper) MapDevice(devicePath, globalMapPath, volumeMapPath, volumeMapName string, podUID types.UID) error {\n\treturn util.MapBlockVolume(devicePath, globalMapPath, volumeMapPath, volumeMapName, podUID)\n}\n\n// GetGlobalMapPath returns global map path and error\n// path: plugins/kubernetes.io/{PluginName}/volumeDevices/volumeID\n// plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX\nfunc (ebs *awsElasticBlockStore) GetGlobalMapPath(spec *volume.Spec) (string, error) {\n\tvolumeSource, _, err := getVolumeSource(spec)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(ebs.plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName), string(volumeSource.VolumeID)), nil\n}\n\n// GetPodDeviceMapPath returns pod device map path and volume name\n// path: pods/{podUid}/volumeDevices/kubernetes.io~aws\nfunc (ebs *awsElasticBlockStore) GetPodDeviceMapPath() (string, string) {\n\tname := awsElasticBlockStorePluginName\n\treturn ebs.plugin.host.GetPodVolumeDeviceDir(ebs.podUID, kstrings.EscapeQualifiedNameForDisk(name)), ebs.volName\n}\n"},"repo_name":{"kind":"string","value":"wjiangjay/origin"},"path":{"kind":"string","value":"vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs_block.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":6460,"string":"6,460"}}},{"rowIdx":115086564,"cells":{"code":{"kind":"string","value":"/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n#include \"tensorflow/core/common_runtime/session_factory.h\"\n\n#include \n\n#include \"tensorflow/core/lib/core/errors.h\"\n#include \"tensorflow/core/lib/strings/str_util.h\"\n#include \"tensorflow/core/platform/logging.h\"\n#include \"tensorflow/core/platform/mutex.h\"\n#include \"tensorflow/core/platform/types.h\"\n#include \"tensorflow/core/protobuf/config.pb_text.h\"\n#include \"tensorflow/core/public/session_options.h\"\n\nnamespace tensorflow {\nnamespace {\n\nstatic mutex* get_session_factory_lock() {\n static mutex session_factory_lock;\n return &session_factory_lock;\n}\n\ntypedef std::unordered_map SessionFactories;\nSessionFactories* session_factories() {\n static SessionFactories* factories = new SessionFactories;\n return factories;\n}\n\n} // namespace\n\nvoid SessionFactory::Register(const string& runtime_type,\n SessionFactory* factory) {\n mutex_lock l(*get_session_factory_lock());\n if (!session_factories()->insert({runtime_type, factory}).second) {\n LOG(ERROR) << \"Two session factories are being registered \"\n << \"under\" << runtime_type;\n }\n}\n\nnamespace {\nconst string RegisteredFactoriesErrorMessageLocked() {\n std::vector factory_types;\n for (const auto& session_factory : *session_factories()) {\n factory_types.push_back(session_factory.first);\n }\n return strings::StrCat(\"Registered factories are {\",\n str_util::Join(factory_types, \", \"), \"}.\");\n}\nstring SessionOptionsToString(const SessionOptions& options) {\n return strings::StrCat(\"target: \\\"\", options.target, \"\\\" config: \",\n ProtoShortDebugString(options.config));\n}\n} // namespace\n\nStatus SessionFactory::GetFactory(const SessionOptions& options,\n SessionFactory** out_factory) {\n mutex_lock l(*get_session_factory_lock()); // could use reader lock\n\n std::vector> candidate_factories;\n for (const auto& session_factory : *session_factories()) {\n if (session_factory.second->AcceptsOptions(options)) {\n VLOG(2) << \"SessionFactory type \" << session_factory.first\n << \" accepts target: \" << options.target;\n candidate_factories.push_back(session_factory);\n } else {\n VLOG(2) << \"SessionFactory type \" << session_factory.first\n << \" does not accept target: \" << options.target;\n }\n }\n\n if (candidate_factories.size() == 1) {\n *out_factory = candidate_factories[0].second;\n return Status::OK();\n } else if (candidate_factories.size() > 1) {\n // NOTE(mrry): This implementation assumes that the domains (in\n // terms of acceptable SessionOptions) of the registered\n // SessionFactory implementations do not overlap. This is fine for\n // now, but we may need an additional way of distinguishing\n // different runtimes (such as an additional session option) if\n // the number of sessions grows.\n // TODO(mrry): Consider providing a system-default fallback option\n // in this case.\n std::vector factory_types;\n factory_types.reserve(candidate_factories.size());\n for (const auto& candidate_factory : candidate_factories) {\n factory_types.push_back(candidate_factory.first);\n }\n return errors::Internal(\n \"Multiple session factories registered for the given session \"\n \"options: {\",\n SessionOptionsToString(options), \"} Candidate factories are {\",\n str_util::Join(factory_types, \", \"), \"}. \",\n RegisteredFactoriesErrorMessageLocked());\n } else {\n return errors::NotFound(\n \"No session factory registered for the given session options: {\",\n SessionOptionsToString(options), \"} \",\n RegisteredFactoriesErrorMessageLocked());\n }\n}\n\n} // namespace tensorflow\n"},"repo_name":{"kind":"string","value":"npuichigo/ttsflow"},"path":{"kind":"string","value":"third_party/tensorflow/tensorflow/core/common_runtime/session_factory.cc"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":4469,"string":"4,469"}}},{"rowIdx":115086565,"cells":{"code":{"kind":"string","value":"// \n// Copyright (c) Microsoft and contributors. All rights reserved.\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// \n// See the License for the specific language governing permissions and\n// limitations under the License.\n// \n\nvar mocha = require('mocha');\nvar should = require('should');\nvar sinon = require('sinon');\nvar _ = require('underscore');\n\n// Test includes\nvar testutil = require('../util/util');\n\n// Lib includes\nvar util = testutil.libRequire('util/utils');\nvar GetCommand = require('./util-GetCommand.js');\n\ndescribe('HDInsight list command (under unit test)', function() {\n\n after(function (done) {\n done();\n });\n\n // NOTE: To Do, we should actually create new accounts for our tests\n // So that we can work on any existing subscription.\n before (function (done) {\n done();\n });\n\n it('should call startProgress with the correct statement', function(done) {\n var command = new GetCommand();\n command.hdinsight.listClustersCommand.should.not.equal(null);\n command.hdinsight.listClustersCommand({}, _);\n command.user.startProgress.firstCall.args[0].should.be.equal('Getting HDInsight servers');\n done();\n });\n\n it('should call listClusters with the supplied subscriptionId (when none is supplied)', function(done) {\n var command = new GetCommand();\n command.hdinsight.listClustersCommand.should.not.equal(null);\n command.hdinsight.listClustersCommand({}, _);\n command.processor.listClusters.firstCall.should.not.equal(null);\n (command.processor.listClusters.firstCall.args[0] === undefined).should.equal(true);\n done();\n });\n\n it('should call listClusters with the supplied subscriptionId (when one is supplied)', function(done) {\n var command = new GetCommand();\n command.hdinsight.listClustersCommand.should.not.equal(null);\n command.hdinsight.listClustersCommand({ subscription: 'test1' }, _);\n command.processor.listClusters.firstCall.should.not.equal(null);\n command.processor.listClusters.firstCall.args[0].should.not.equal(null);\n command.processor.listClusters.firstCall.args[0].should.be.equal('test1');\n done();\n });\n});"},"repo_name":{"kind":"string","value":"Nepomuceno/azure-xplat-cli"},"path":{"kind":"string","value":"test/hdinsight/unit-list-command.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":2528,"string":"2,528"}}},{"rowIdx":115086566,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (C) 2009 - QLogic Corporation.\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston,\n * MA 02111-1307, USA.\n *\n * The full GNU General Public License is included in this distribution\n * in the file called \"COPYING\".\n *\n */\n\n#include \"qlcnic.h\"\n\n#include \n#include \n\n#define MASK(n) ((1ULL<<(n))-1)\n#define OCM_WIN_P3P(addr) (addr & 0xffc0000)\n\n#define GET_MEM_OFFS_2M(addr) (addr & MASK(18))\n\n#define CRB_BLK(off)\t((off >> 20) & 0x3f)\n#define CRB_SUBBLK(off)\t((off >> 16) & 0xf)\n#define CRB_WINDOW_2M\t(0x130060)\n#define CRB_HI(off)\t((crb_hub_agt[CRB_BLK(off)] << 20) | ((off) & 0xf0000))\n#define CRB_INDIRECT_2M\t(0x1e0000UL)\n\n\n#ifndef readq\nstatic inline u64 readq(void __iomem *addr)\n{\n\treturn readl(addr) | (((u64) readl(addr + 4)) << 32LL);\n}\n#endif\n\n#ifndef writeq\nstatic inline void writeq(u64 val, void __iomem *addr)\n{\n\twritel(((u32) (val)), (addr));\n\twritel(((u32) (val >> 32)), (addr + 4));\n}\n#endif\n\n#define ADDR_IN_RANGE(addr, low, high)\t\\\n\t(((addr) < (high)) && ((addr) >= (low)))\n\n#define PCI_OFFSET_FIRST_RANGE(adapter, off) \\\n\t((adapter)->ahw.pci_base0 + (off))\n\nstatic void __iomem *pci_base_offset(struct qlcnic_adapter *adapter,\n\t\t\t\t\t unsigned long off)\n{\n\tif (ADDR_IN_RANGE(off, FIRST_PAGE_GROUP_START, FIRST_PAGE_GROUP_END))\n\t\treturn PCI_OFFSET_FIRST_RANGE(adapter, off);\n\n\treturn NULL;\n}\n\nstatic const struct crb_128M_2M_block_map\ncrb_128M_2M_map[64] __cacheline_aligned_in_smp = {\n {{{0, 0, 0, 0} } },\t\t/* 0: PCI */\n {{{1, 0x0100000, 0x0102000, 0x120000},\t/* 1: PCIE */\n\t {1, 0x0110000, 0x0120000, 0x130000},\n\t {1, 0x0120000, 0x0122000, 0x124000},\n\t {1, 0x0130000, 0x0132000, 0x126000},\n\t {1, 0x0140000, 0x0142000, 0x128000},\n\t {1, 0x0150000, 0x0152000, 0x12a000},\n\t {1, 0x0160000, 0x0170000, 0x110000},\n\t {1, 0x0170000, 0x0172000, 0x12e000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {1, 0x01e0000, 0x01e0800, 0x122000},\n\t {0, 0x0000000, 0x0000000, 0x000000} } },\n\t{{{1, 0x0200000, 0x0210000, 0x180000} } },/* 2: MN */\n {{{0, 0, 0, 0} } },\t /* 3: */\n {{{1, 0x0400000, 0x0401000, 0x169000} } },/* 4: P2NR1 */\n {{{1, 0x0500000, 0x0510000, 0x140000} } },/* 5: SRE */\n {{{1, 0x0600000, 0x0610000, 0x1c0000} } },/* 6: NIU */\n {{{1, 0x0700000, 0x0704000, 0x1b8000} } },/* 7: QM */\n {{{1, 0x0800000, 0x0802000, 0x170000}, /* 8: SQM0 */\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {1, 0x08f0000, 0x08f2000, 0x172000} } },\n {{{1, 0x0900000, 0x0902000, 0x174000},\t/* 9: SQM1*/\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {1, 0x09f0000, 0x09f2000, 0x176000} } },\n {{{0, 0x0a00000, 0x0a02000, 0x178000},\t/* 10: SQM2*/\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {1, 0x0af0000, 0x0af2000, 0x17a000} } },\n {{{0, 0x0b00000, 0x0b02000, 0x17c000},\t/* 11: SQM3*/\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {0, 0x0000000, 0x0000000, 0x000000},\n {1, 0x0bf0000, 0x0bf2000, 0x17e000} } },\n\t{{{1, 0x0c00000, 0x0c04000, 0x1d4000} } },/* 12: I2Q */\n\t{{{1, 0x0d00000, 0x0d04000, 0x1a4000} } },/* 13: TMR */\n\t{{{1, 0x0e00000, 0x0e04000, 0x1a0000} } },/* 14: ROMUSB */\n\t{{{1, 0x0f00000, 0x0f01000, 0x164000} } },/* 15: PEG4 */\n\t{{{0, 0x1000000, 0x1004000, 0x1a8000} } },/* 16: XDMA */\n\t{{{1, 0x1100000, 0x1101000, 0x160000} } },/* 17: PEG0 */\n\t{{{1, 0x1200000, 0x1201000, 0x161000} } },/* 18: PEG1 */\n\t{{{1, 0x1300000, 0x1301000, 0x162000} } },/* 19: PEG2 */\n\t{{{1, 0x1400000, 0x1401000, 0x163000} } },/* 20: PEG3 */\n\t{{{1, 0x1500000, 0x1501000, 0x165000} } },/* 21: P2ND */\n\t{{{1, 0x1600000, 0x1601000, 0x166000} } },/* 22: P2NI */\n\t{{{0, 0, 0, 0} } },\t/* 23: */\n\t{{{0, 0, 0, 0} } },\t/* 24: */\n\t{{{0, 0, 0, 0} } },\t/* 25: */\n\t{{{0, 0, 0, 0} } },\t/* 26: */\n\t{{{0, 0, 0, 0} } },\t/* 27: */\n\t{{{0, 0, 0, 0} } },\t/* 28: */\n\t{{{1, 0x1d00000, 0x1d10000, 0x190000} } },/* 29: MS */\n {{{1, 0x1e00000, 0x1e01000, 0x16a000} } },/* 30: P2NR2 */\n {{{1, 0x1f00000, 0x1f10000, 0x150000} } },/* 31: EPG */\n\t{{{0} } },\t\t\t\t/* 32: PCI */\n\t{{{1, 0x2100000, 0x2102000, 0x120000},\t/* 33: PCIE */\n\t {1, 0x2110000, 0x2120000, 0x130000},\n\t {1, 0x2120000, 0x2122000, 0x124000},\n\t {1, 0x2130000, 0x2132000, 0x126000},\n\t {1, 0x2140000, 0x2142000, 0x128000},\n\t {1, 0x2150000, 0x2152000, 0x12a000},\n\t {1, 0x2160000, 0x2170000, 0x110000},\n\t {1, 0x2170000, 0x2172000, 0x12e000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000},\n\t {0, 0x0000000, 0x0000000, 0x000000} } },\n\t{{{1, 0x2200000, 0x2204000, 0x1b0000} } },/* 34: CAM */\n\t{{{0} } },\t\t\t\t/* 35: */\n\t{{{0} } },\t\t\t\t/* 36: */\n\t{{{0} } },\t\t\t\t/* 37: */\n\t{{{0} } },\t\t\t\t/* 38: */\n\t{{{0} } },\t\t\t\t/* 39: */\n\t{{{1, 0x2800000, 0x2804000, 0x1a4000} } },/* 40: TMR */\n\t{{{1, 0x2900000, 0x2901000, 0x16b000} } },/* 41: P2NR3 */\n\t{{{1, 0x2a00000, 0x2a00400, 0x1ac400} } },/* 42: RPMX1 */\n\t{{{1, 0x2b00000, 0x2b00400, 0x1ac800} } },/* 43: RPMX2 */\n\t{{{1, 0x2c00000, 0x2c00400, 0x1acc00} } },/* 44: RPMX3 */\n\t{{{1, 0x2d00000, 0x2d00400, 0x1ad000} } },/* 45: RPMX4 */\n\t{{{1, 0x2e00000, 0x2e00400, 0x1ad400} } },/* 46: RPMX5 */\n\t{{{1, 0x2f00000, 0x2f00400, 0x1ad800} } },/* 47: RPMX6 */\n\t{{{1, 0x3000000, 0x3000400, 0x1adc00} } },/* 48: RPMX7 */\n\t{{{0, 0x3100000, 0x3104000, 0x1a8000} } },/* 49: XDMA */\n\t{{{1, 0x3200000, 0x3204000, 0x1d4000} } },/* 50: I2Q */\n\t{{{1, 0x3300000, 0x3304000, 0x1a0000} } },/* 51: ROMUSB */\n\t{{{0} } },\t\t\t\t/* 52: */\n\t{{{1, 0x3500000, 0x3500400, 0x1ac000} } },/* 53: RPMX0 */\n\t{{{1, 0x3600000, 0x3600400, 0x1ae000} } },/* 54: RPMX8 */\n\t{{{1, 0x3700000, 0x3700400, 0x1ae400} } },/* 55: RPMX9 */\n\t{{{1, 0x3800000, 0x3804000, 0x1d0000} } },/* 56: OCM0 */\n\t{{{1, 0x3900000, 0x3904000, 0x1b4000} } },/* 57: CRYPTO */\n\t{{{1, 0x3a00000, 0x3a04000, 0x1d8000} } },/* 58: SMB */\n\t{{{0} } },\t\t\t\t/* 59: I2C0 */\n\t{{{0} } },\t\t\t\t/* 60: I2C1 */\n\t{{{1, 0x3d00000, 0x3d04000, 0x1d8000} } },/* 61: LPC */\n\t{{{1, 0x3e00000, 0x3e01000, 0x167000} } },/* 62: P2NC */\n\t{{{1, 0x3f00000, 0x3f01000, 0x168000} } }\t/* 63: P2NR0 */\n};\n\n/*\n * top 12 bits of crb internal address (hub, agent)\n */\nstatic const unsigned crb_hub_agt[64] = {\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PS,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_MN,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_MS,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SRE,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_NIU,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_QMN,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SQN0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SQN1,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SQN2,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SQN3,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGN4,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGN0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGN1,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGN2,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGN3,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGND,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGNI,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGS0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGS1,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGS2,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGS3,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGSI,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SN,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_EG,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PS,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_CAM,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX1,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX2,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX3,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX4,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX5,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX6,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX7,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX8,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_RPMX9,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_OCM0,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_SMB,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_I2C0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_I2C1,\n\t0,\n\tQLCNIC_HW_CRB_HUB_AGT_ADR_PGNC,\n\t0,\n};\n\n/* PCI Windowing for DDR regions. */\n\n#define QLCNIC_PCIE_SEM_TIMEOUT\t10000\n\nint\nqlcnic_pcie_sem_lock(struct qlcnic_adapter *adapter, int sem, u32 id_reg)\n{\n\tint done = 0, timeout = 0;\n\n\twhile (!done) {\n\t\tdone = QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_LOCK(sem)));\n\t\tif (done == 1)\n\t\t\tbreak;\n\t\tif (++timeout >= QLCNIC_PCIE_SEM_TIMEOUT)\n\t\t\treturn -EIO;\n\t\tmsleep(1);\n\t}\n\n\tif (id_reg)\n\t\tQLCWR32(adapter, id_reg, adapter->portnum);\n\n\treturn 0;\n}\n\nvoid\nqlcnic_pcie_sem_unlock(struct qlcnic_adapter *adapter, int sem)\n{\n\tQLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_UNLOCK(sem)));\n}\n\nstatic int\nqlcnic_send_cmd_descs(struct qlcnic_adapter *adapter,\n\t\tstruct cmd_desc_type0 *cmd_desc_arr, int nr_desc)\n{\n\tu32 i, producer, consumer;\n\tstruct qlcnic_cmd_buffer *pbuf;\n\tstruct cmd_desc_type0 *cmd_desc;\n\tstruct qlcnic_host_tx_ring *tx_ring;\n\n\ti = 0;\n\n\tif (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC)\n\t\treturn -EIO;\n\n\ttx_ring = adapter->tx_ring;\n\t__netif_tx_lock_bh(tx_ring->txq);\n\n\tproducer = tx_ring->producer;\n\tconsumer = tx_ring->sw_consumer;\n\n\tif (nr_desc >= qlcnic_tx_avail(tx_ring)) {\n\t\tnetif_tx_stop_queue(tx_ring->txq);\n\t\t__netif_tx_unlock_bh(tx_ring->txq);\n\t\tadapter->stats.xmit_off++;\n\t\treturn -EBUSY;\n\t}\n\n\tdo {\n\t\tcmd_desc = &cmd_desc_arr[i];\n\n\t\tpbuf = &tx_ring->cmd_buf_arr[producer];\n\t\tpbuf->skb = NULL;\n\t\tpbuf->frag_count = 0;\n\n\t\tmemcpy(&tx_ring->desc_head[producer],\n\t\t\t&cmd_desc_arr[i], sizeof(struct cmd_desc_type0));\n\n\t\tproducer = get_next_index(producer, tx_ring->num_desc);\n\t\ti++;\n\n\t} while (i != nr_desc);\n\n\ttx_ring->producer = producer;\n\n\tqlcnic_update_cmd_producer(adapter, tx_ring);\n\n\t__netif_tx_unlock_bh(tx_ring->txq);\n\n\treturn 0;\n}\n\nstatic int\nqlcnic_sre_macaddr_change(struct qlcnic_adapter *adapter, u8 *addr,\n\t\t\t\tunsigned op)\n{\n\tstruct qlcnic_nic_req req;\n\tstruct qlcnic_mac_req *mac_req;\n\tu64 word;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_REQUEST << 23);\n\n\tword = QLCNIC_MAC_EVENT | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\tmac_req = (struct qlcnic_mac_req *)&req.words[0];\n\tmac_req->op = op;\n\tmemcpy(mac_req->mac_addr, addr, 6);\n\n\treturn qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n}\n\nstatic int qlcnic_nic_add_mac(struct qlcnic_adapter *adapter, u8 *addr)\n{\n\tstruct list_head *head;\n\tstruct qlcnic_mac_list_s *cur;\n\n\t/* look up if already exists */\n\tlist_for_each(head, &adapter->mac_list) {\n\t\tcur = list_entry(head, struct qlcnic_mac_list_s, list);\n\t\tif (memcmp(addr, cur->mac_addr, ETH_ALEN) == 0)\n\t\t\treturn 0;\n\t}\n\n\tcur = kzalloc(sizeof(struct qlcnic_mac_list_s), GFP_ATOMIC);\n\tif (cur == NULL) {\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\"failed to add mac address filter\\n\");\n\t\treturn -ENOMEM;\n\t}\n\tmemcpy(cur->mac_addr, addr, ETH_ALEN);\n\tlist_add_tail(&cur->list, &adapter->mac_list);\n\n\treturn qlcnic_sre_macaddr_change(adapter,\n\t\t\t\tcur->mac_addr, QLCNIC_MAC_ADD);\n}\n\nvoid qlcnic_set_multi(struct net_device *netdev)\n{\n\tstruct qlcnic_adapter *adapter = netdev_priv(netdev);\n\tstruct dev_mc_list *mc_ptr;\n\tu8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };\n\tu32 mode = VPORT_MISS_MODE_DROP;\n\n\tif (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC)\n\t\treturn;\n\n\tqlcnic_nic_add_mac(adapter, adapter->mac_addr);\n\tqlcnic_nic_add_mac(adapter, bcast_addr);\n\n\tif (netdev->flags & IFF_PROMISC) {\n\t\tmode = VPORT_MISS_MODE_ACCEPT_ALL;\n\t\tgoto send_fw_cmd;\n\t}\n\n\tif ((netdev->flags & IFF_ALLMULTI) ||\n\t (netdev_mc_count(netdev) > adapter->max_mc_count)) {\n\t\tmode = VPORT_MISS_MODE_ACCEPT_MULTI;\n\t\tgoto send_fw_cmd;\n\t}\n\n\tif (!netdev_mc_empty(netdev)) {\n\t\tnetdev_for_each_mc_addr(mc_ptr, netdev) {\n\t\t\tqlcnic_nic_add_mac(adapter, mc_ptr->dmi_addr);\n\t\t}\n\t}\n\nsend_fw_cmd:\n\tqlcnic_nic_set_promisc(adapter, mode);\n}\n\nint qlcnic_nic_set_promisc(struct qlcnic_adapter *adapter, u32 mode)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_PROXY_SET_VPORT_MISS_MODE |\n\t\t\t((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\treq.words[0] = cpu_to_le64(mode);\n\n\treturn qlcnic_send_cmd_descs(adapter,\n\t\t\t\t(struct cmd_desc_type0 *)&req, 1);\n}\n\nvoid qlcnic_free_mac_list(struct qlcnic_adapter *adapter)\n{\n\tstruct qlcnic_mac_list_s *cur;\n\tstruct list_head *head = &adapter->mac_list;\n\n\twhile (!list_empty(head)) {\n\t\tcur = list_entry(head->next, struct qlcnic_mac_list_s, list);\n\t\tqlcnic_sre_macaddr_change(adapter,\n\t\t\t\tcur->mac_addr, QLCNIC_MAC_DEL);\n\t\tlist_del(&cur->list);\n\t\tkfree(cur);\n\t}\n}\n\n#define\tQLCNIC_CONFIG_INTR_COALESCE\t3\n\n/*\n * Send the interrupt coalescing parameter set by ethtool to the card.\n */\nint qlcnic_config_intr_coalesce(struct qlcnic_adapter *adapter)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word[6];\n\tint rv, i;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword[0] = QLCNIC_CONFIG_INTR_COALESCE | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word[0]);\n\n\tmemcpy(&word[0], &adapter->coal, sizeof(adapter->coal));\n\tfor (i = 0; i < 6; i++)\n\t\treq.words[i] = cpu_to_le64(word[i]);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\"Could not send interrupt coalescing parameters\\n\");\n\n\treturn rv;\n}\n\nint qlcnic_config_hw_lro(struct qlcnic_adapter *adapter, int enable)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint rv;\n\n\tif ((adapter->flags & QLCNIC_LRO_ENABLED) == enable)\n\t\treturn 0;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_HW_LRO | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\treq.words[0] = cpu_to_le64(enable);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\"Could not send configure hw lro request\\n\");\n\n\tadapter->flags ^= QLCNIC_LRO_ENABLED;\n\n\treturn rv;\n}\n\nint qlcnic_config_bridged_mode(struct qlcnic_adapter *adapter, int enable)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint rv;\n\n\tif (!!(adapter->flags & QLCNIC_BRIDGE_ENABLED) == enable)\n\t\treturn 0;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_BRIDGING |\n\t\t((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\treq.words[0] = cpu_to_le64(enable);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\"Could not send configure bridge mode request\\n\");\n\n\tadapter->flags ^= QLCNIC_BRIDGE_ENABLED;\n\n\treturn rv;\n}\n\n\n#define RSS_HASHTYPE_IP_TCP\t0x3\n\nint qlcnic_config_rss(struct qlcnic_adapter *adapter, int enable)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint i, rv;\n\n\tconst u64 key[] = { 0xbeac01fa6a42b73bULL, 0x8030f20c77cb2da3ULL,\n\t\t\t0xae7b30b4d0ca2bcbULL, 0x43a38fb04167253dULL,\n\t\t\t0x255b0ec26d5a56daULL };\n\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_RSS | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\t/*\n\t * RSS request:\n\t * bits 3-0: hash_method\n\t * 5-4: hash_type_ipv4\n\t *\t7-6: hash_type_ipv6\n\t *\t 8: enable\n\t * 9: use indirection table\n\t * 47-10: reserved\n\t * 63-48: indirection table mask\n\t */\n\tword = ((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 4) |\n\t\t((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 6) |\n\t\t((u64)(enable & 0x1) << 8) |\n\t\t((0x7ULL) << 48);\n\treq.words[0] = cpu_to_le64(word);\n\tfor (i = 0; i < 5; i++)\n\t\treq.words[i+1] = cpu_to_le64(key[i]);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev, \"could not configure RSS\\n\");\n\n\treturn rv;\n}\n\nint qlcnic_config_ipaddr(struct qlcnic_adapter *adapter, u32 ip, int cmd)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint rv;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_IPADDR | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\treq.words[0] = cpu_to_le64(cmd);\n\treq.words[1] = cpu_to_le64(ip);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\t\"could not notify %s IP 0x%x reuqest\\n\",\n\t\t\t\t(cmd == QLCNIC_IP_UP) ? \"Add\" : \"Remove\", ip);\n\n\treturn rv;\n}\n\nint qlcnic_linkevent_request(struct qlcnic_adapter *adapter, int enable)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint rv;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_GET_LINKEVENT | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\treq.words[0] = cpu_to_le64(enable | (enable << 8));\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\t\"could not configure link notification\\n\");\n\n\treturn rv;\n}\n\nint qlcnic_send_lro_cleanup(struct qlcnic_adapter *adapter)\n{\n\tstruct qlcnic_nic_req req;\n\tu64 word;\n\tint rv;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_LRO_REQUEST |\n\t\t((u64)adapter->portnum << 16) |\n\t\t((u64)QLCNIC_LRO_REQUEST_CLEANUP << 56) ;\n\n\treq.req_hdr = cpu_to_le64(word);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv != 0)\n\t\tdev_err(&adapter->netdev->dev,\n\t\t\t\t \"could not cleanup lro flows\\n\");\n\n\treturn rv;\n}\n\n/*\n * qlcnic_change_mtu - Change the Maximum Transfer Unit\n * @returns 0 on success, negative on failure\n */\n\nint qlcnic_change_mtu(struct net_device *netdev, int mtu)\n{\n\tstruct qlcnic_adapter *adapter = netdev_priv(netdev);\n\tint rc = 0;\n\n\tif (mtu > P3_MAX_MTU) {\n\t\tdev_err(&adapter->netdev->dev, \"mtu > %d bytes unsupported\\n\",\n\t\t\t\t\t\tP3_MAX_MTU);\n\t\treturn -EINVAL;\n\t}\n\n\trc = qlcnic_fw_cmd_set_mtu(adapter, mtu);\n\n\tif (!rc)\n\t\tnetdev->mtu = mtu;\n\n\treturn rc;\n}\n\nint qlcnic_get_mac_addr(struct qlcnic_adapter *adapter, u64 *mac)\n{\n\tu32 crbaddr, mac_hi, mac_lo;\n\tint pci_func = adapter->ahw.pci_func;\n\n\tcrbaddr = CRB_MAC_BLOCK_START +\n\t\t(4 * ((pci_func/2) * 3)) + (4 * (pci_func & 1));\n\n\tmac_lo = QLCRD32(adapter, crbaddr);\n\tmac_hi = QLCRD32(adapter, crbaddr+4);\n\n\tif (pci_func & 1)\n\t\t*mac = le64_to_cpu((mac_lo >> 16) | ((u64)mac_hi << 16));\n\telse\n\t\t*mac = le64_to_cpu((u64)mac_lo | ((u64)mac_hi << 32));\n\n\treturn 0;\n}\n\n/*\n * Changes the CRB window to the specified window.\n */\n /* Returns < 0 if off is not valid,\n *\t 1 if window access is needed. 'off' is set to offset from\n *\t CRB space in 128M pci map\n *\t 0 if no window access is needed. 'off' is set to 2M addr\n * In: 'off' is offset from base in 128M pci map\n */\nstatic int\nqlcnic_pci_get_crb_addr_2M(struct qlcnic_adapter *adapter,\n\t\tulong off, void __iomem **addr)\n{\n\tconst struct crb_128M_2M_sub_block_map *m;\n\n\tif ((off >= QLCNIC_CRB_MAX) || (off < QLCNIC_PCI_CRBSPACE))\n\t\treturn -EINVAL;\n\n\toff -= QLCNIC_PCI_CRBSPACE;\n\n\t/*\n\t * Try direct map\n\t */\n\tm = &crb_128M_2M_map[CRB_BLK(off)].sub_block[CRB_SUBBLK(off)];\n\n\tif (m->valid && (m->start_128M <= off) && (m->end_128M > off)) {\n\t\t*addr = adapter->ahw.pci_base0 + m->start_2M +\n\t\t\t(off - m->start_128M);\n\t\treturn 0;\n\t}\n\n\t/*\n\t * Not in direct map, use crb window\n\t */\n\t*addr = adapter->ahw.pci_base0 + CRB_INDIRECT_2M + (off & MASK(16));\n\treturn 1;\n}\n\n/*\n * In: 'off' is offset from CRB space in 128M pci map\n * Out: 'off' is 2M pci map addr\n * side effect: lock crb window\n */\nstatic void\nqlcnic_pci_set_crbwindow_2M(struct qlcnic_adapter *adapter, ulong off)\n{\n\tu32 window;\n\tvoid __iomem *addr = adapter->ahw.pci_base0 + CRB_WINDOW_2M;\n\n\toff -= QLCNIC_PCI_CRBSPACE;\n\n\twindow = CRB_HI(off);\n\n\tif (adapter->ahw.crb_win == window)\n\t\treturn;\n\n\twritel(window, addr);\n\tif (readl(addr) != window) {\n\t\tif (printk_ratelimit())\n\t\t\tdev_warn(&adapter->pdev->dev,\n\t\t\t\t\"failed to set CRB window to %d off 0x%lx\\n\",\n\t\t\t\twindow, off);\n\t}\n\tadapter->ahw.crb_win = window;\n}\n\nint\nqlcnic_hw_write_wx_2M(struct qlcnic_adapter *adapter, ulong off, u32 data)\n{\n\tunsigned long flags;\n\tint rv;\n\tvoid __iomem *addr = NULL;\n\n\trv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);\n\n\tif (rv == 0) {\n\t\twritel(data, addr);\n\t\treturn 0;\n\t}\n\n\tif (rv > 0) {\n\t\t/* indirect access */\n\t\twrite_lock_irqsave(&adapter->ahw.crb_lock, flags);\n\t\tcrb_win_lock(adapter);\n\t\tqlcnic_pci_set_crbwindow_2M(adapter, off);\n\t\twritel(data, addr);\n\t\tcrb_win_unlock(adapter);\n\t\twrite_unlock_irqrestore(&adapter->ahw.crb_lock, flags);\n\t\treturn 0;\n\t}\n\n\tdev_err(&adapter->pdev->dev,\n\t\t\t\"%s: invalid offset: 0x%016lx\\n\", __func__, off);\n\tdump_stack();\n\treturn -EIO;\n}\n\nu32\nqlcnic_hw_read_wx_2M(struct qlcnic_adapter *adapter, ulong off)\n{\n\tunsigned long flags;\n\tint rv;\n\tu32 data;\n\tvoid __iomem *addr = NULL;\n\n\trv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);\n\n\tif (rv == 0)\n\t\treturn readl(addr);\n\n\tif (rv > 0) {\n\t\t/* indirect access */\n\t\twrite_lock_irqsave(&adapter->ahw.crb_lock, flags);\n\t\tcrb_win_lock(adapter);\n\t\tqlcnic_pci_set_crbwindow_2M(adapter, off);\n\t\tdata = readl(addr);\n\t\tcrb_win_unlock(adapter);\n\t\twrite_unlock_irqrestore(&adapter->ahw.crb_lock, flags);\n\t\treturn data;\n\t}\n\n\tdev_err(&adapter->pdev->dev,\n\t\t\t\"%s: invalid offset: 0x%016lx\\n\", __func__, off);\n\tdump_stack();\n\treturn -1;\n}\n\n\nvoid __iomem *\nqlcnic_get_ioaddr(struct qlcnic_adapter *adapter, u32 offset)\n{\n\tvoid __iomem *addr = NULL;\n\n\tWARN_ON(qlcnic_pci_get_crb_addr_2M(adapter, offset, &addr));\n\n\treturn addr;\n}\n\n\nstatic int\nqlcnic_pci_set_window_2M(struct qlcnic_adapter *adapter,\n\t\tu64 addr, u32 *start)\n{\n\tu32 window;\n\tstruct pci_dev *pdev = adapter->pdev;\n\n\tif ((addr & 0x00ff800) == 0xff800) {\n\t\tif (printk_ratelimit())\n\t\t\tdev_warn(&pdev->dev, \"QM access not handled\\n\");\n\t\treturn -EIO;\n\t}\n\n\twindow = OCM_WIN_P3P(addr);\n\n\twritel(window, adapter->ahw.ocm_win_crb);\n\t/* read back to flush */\n\treadl(adapter->ahw.ocm_win_crb);\n\n\tadapter->ahw.ocm_win = window;\n\t*start = QLCNIC_PCI_OCM0_2M + GET_MEM_OFFS_2M(addr);\n\treturn 0;\n}\n\nstatic int\nqlcnic_pci_mem_access_direct(struct qlcnic_adapter *adapter, u64 off,\n\t\tu64 *data, int op)\n{\n\tvoid __iomem *addr, *mem_ptr = NULL;\n\tresource_size_t mem_base;\n\tint ret;\n\tu32 start;\n\n\tmutex_lock(&adapter->ahw.mem_lock);\n\n\tret = qlcnic_pci_set_window_2M(adapter, off, &start);\n\tif (ret != 0)\n\t\tgoto unlock;\n\n\taddr = pci_base_offset(adapter, start);\n\tif (addr)\n\t\tgoto noremap;\n\n\tmem_base = pci_resource_start(adapter->pdev, 0) + (start & PAGE_MASK);\n\n\tmem_ptr = ioremap(mem_base, PAGE_SIZE);\n\tif (mem_ptr == NULL) {\n\t\tret = -EIO;\n\t\tgoto unlock;\n\t}\n\n\taddr = mem_ptr + (start & (PAGE_SIZE - 1));\n\nnoremap:\n\tif (op == 0)\t/* read */\n\t\t*data = readq(addr);\n\telse\t\t/* write */\n\t\twriteq(*data, addr);\n\nunlock:\n\tmutex_unlock(&adapter->ahw.mem_lock);\n\n\tif (mem_ptr)\n\t\tiounmap(mem_ptr);\n\treturn ret;\n}\n\n#define MAX_CTL_CHECK 1000\n\nint\nqlcnic_pci_mem_write_2M(struct qlcnic_adapter *adapter,\n\t\tu64 off, u64 data)\n{\n\tint i, j, ret;\n\tu32 temp, off8;\n\tu64 stride;\n\tvoid __iomem *mem_crb;\n\n\t/* Only 64-bit aligned access */\n\tif (off & 7)\n\t\treturn -EIO;\n\n\t/* P3 onward, test agent base for MIU and SIU is same */\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,\n\t\t\t\tQLCNIC_ADDR_QDR_NET_MAX_P3)) {\n\t\tmem_crb = qlcnic_get_ioaddr(adapter,\n\t\t\t\tQLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);\n\t\tgoto correct;\n\t}\n\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {\n\t\tmem_crb = qlcnic_get_ioaddr(adapter,\n\t\t\t\tQLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);\n\t\tgoto correct;\n\t}\n\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX))\n\t\treturn qlcnic_pci_mem_access_direct(adapter, off, &data, 1);\n\n\treturn -EIO;\n\ncorrect:\n\tstride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8;\n\n\toff8 = off & ~(stride-1);\n\n\tmutex_lock(&adapter->ahw.mem_lock);\n\n\twritel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));\n\twritel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));\n\n\ti = 0;\n\tif (stride == 16) {\n\t\twritel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));\n\t\twritel((TA_CTL_START | TA_CTL_ENABLE),\n\t\t\t\t(mem_crb + TEST_AGT_CTRL));\n\n\t\tfor (j = 0; j < MAX_CTL_CHECK; j++) {\n\t\t\ttemp = readl(mem_crb + TEST_AGT_CTRL);\n\t\t\tif ((temp & TA_CTL_BUSY) == 0)\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (j >= MAX_CTL_CHECK) {\n\t\t\tret = -EIO;\n\t\t\tgoto done;\n\t\t}\n\n\t\ti = (off & 0xf) ? 0 : 2;\n\t\twritel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i)),\n\t\t\t\tmem_crb + MIU_TEST_AGT_WRDATA(i));\n\t\twritel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i+1)),\n\t\t\t\tmem_crb + MIU_TEST_AGT_WRDATA(i+1));\n\t\ti = (off & 0xf) ? 2 : 0;\n\t}\n\n\twritel(data & 0xffffffff,\n\t\t\tmem_crb + MIU_TEST_AGT_WRDATA(i));\n\twritel((data >> 32) & 0xffffffff,\n\t\t\tmem_crb + MIU_TEST_AGT_WRDATA(i+1));\n\n\twritel((TA_CTL_ENABLE | TA_CTL_WRITE), (mem_crb + TEST_AGT_CTRL));\n\twritel((TA_CTL_START | TA_CTL_ENABLE | TA_CTL_WRITE),\n\t\t\t(mem_crb + TEST_AGT_CTRL));\n\n\tfor (j = 0; j < MAX_CTL_CHECK; j++) {\n\t\ttemp = readl(mem_crb + TEST_AGT_CTRL);\n\t\tif ((temp & TA_CTL_BUSY) == 0)\n\t\t\tbreak;\n\t}\n\n\tif (j >= MAX_CTL_CHECK) {\n\t\tif (printk_ratelimit())\n\t\t\tdev_err(&adapter->pdev->dev,\n\t\t\t\t\t\"failed to write through agent\\n\");\n\t\tret = -EIO;\n\t} else\n\t\tret = 0;\n\ndone:\n\tmutex_unlock(&adapter->ahw.mem_lock);\n\n\treturn ret;\n}\n\nint\nqlcnic_pci_mem_read_2M(struct qlcnic_adapter *adapter,\n\t\tu64 off, u64 *data)\n{\n\tint j, ret;\n\tu32 temp, off8;\n\tu64 val, stride;\n\tvoid __iomem *mem_crb;\n\n\t/* Only 64-bit aligned access */\n\tif (off & 7)\n\t\treturn -EIO;\n\n\t/* P3 onward, test agent base for MIU and SIU is same */\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,\n\t\t\t\tQLCNIC_ADDR_QDR_NET_MAX_P3)) {\n\t\tmem_crb = qlcnic_get_ioaddr(adapter,\n\t\t\t\tQLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);\n\t\tgoto correct;\n\t}\n\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {\n\t\tmem_crb = qlcnic_get_ioaddr(adapter,\n\t\t\t\tQLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);\n\t\tgoto correct;\n\t}\n\n\tif (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX)) {\n\t\treturn qlcnic_pci_mem_access_direct(adapter,\n\t\t\t\toff, data, 0);\n\t}\n\n\treturn -EIO;\n\ncorrect:\n\tstride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8;\n\n\toff8 = off & ~(stride-1);\n\n\tmutex_lock(&adapter->ahw.mem_lock);\n\n\twritel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));\n\twritel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));\n\twritel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));\n\twritel((TA_CTL_START | TA_CTL_ENABLE), (mem_crb + TEST_AGT_CTRL));\n\n\tfor (j = 0; j < MAX_CTL_CHECK; j++) {\n\t\ttemp = readl(mem_crb + TEST_AGT_CTRL);\n\t\tif ((temp & TA_CTL_BUSY) == 0)\n\t\t\tbreak;\n\t}\n\n\tif (j >= MAX_CTL_CHECK) {\n\t\tif (printk_ratelimit())\n\t\t\tdev_err(&adapter->pdev->dev,\n\t\t\t\t\t\"failed to read through agent\\n\");\n\t\tret = -EIO;\n\t} else {\n\t\toff8 = MIU_TEST_AGT_RDDATA_LO;\n\t\tif ((stride == 16) && (off & 0xf))\n\t\t\toff8 = MIU_TEST_AGT_RDDATA_UPPER_LO;\n\n\t\ttemp = readl(mem_crb + off8 + 4);\n\t\tval = (u64)temp << 32;\n\t\tval |= readl(mem_crb + off8);\n\t\t*data = val;\n\t\tret = 0;\n\t}\n\n\tmutex_unlock(&adapter->ahw.mem_lock);\n\n\treturn ret;\n}\n\nint qlcnic_get_board_info(struct qlcnic_adapter *adapter)\n{\n\tint offset, board_type, magic;\n\tstruct pci_dev *pdev = adapter->pdev;\n\n\toffset = QLCNIC_FW_MAGIC_OFFSET;\n\tif (qlcnic_rom_fast_read(adapter, offset, &magic))\n\t\treturn -EIO;\n\n\tif (magic != QLCNIC_BDINFO_MAGIC) {\n\t\tdev_err(&pdev->dev, \"invalid board config, magic=%08x\\n\",\n\t\t\tmagic);\n\t\treturn -EIO;\n\t}\n\n\toffset = QLCNIC_BRDTYPE_OFFSET;\n\tif (qlcnic_rom_fast_read(adapter, offset, &board_type))\n\t\treturn -EIO;\n\n\tadapter->ahw.board_type = board_type;\n\n\tif (board_type == QLCNIC_BRDTYPE_P3_4_GB_MM) {\n\t\tu32 gpio = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_PAD_GPIO_I);\n\t\tif ((gpio & 0x8000) == 0)\n\t\t\tboard_type = QLCNIC_BRDTYPE_P3_10G_TP;\n\t}\n\n\tswitch (board_type) {\n\tcase QLCNIC_BRDTYPE_P3_HMEZ:\n\tcase QLCNIC_BRDTYPE_P3_XG_LOM:\n\tcase QLCNIC_BRDTYPE_P3_10G_CX4:\n\tcase QLCNIC_BRDTYPE_P3_10G_CX4_LP:\n\tcase QLCNIC_BRDTYPE_P3_IMEZ:\n\tcase QLCNIC_BRDTYPE_P3_10G_SFP_PLUS:\n\tcase QLCNIC_BRDTYPE_P3_10G_SFP_CT:\n\tcase QLCNIC_BRDTYPE_P3_10G_SFP_QT:\n\tcase QLCNIC_BRDTYPE_P3_10G_XFP:\n\tcase QLCNIC_BRDTYPE_P3_10000_BASE_T:\n\t\tadapter->ahw.port_type = QLCNIC_XGBE;\n\t\tbreak;\n\tcase QLCNIC_BRDTYPE_P3_REF_QG:\n\tcase QLCNIC_BRDTYPE_P3_4_GB:\n\tcase QLCNIC_BRDTYPE_P3_4_GB_MM:\n\t\tadapter->ahw.port_type = QLCNIC_GBE;\n\t\tbreak;\n\tcase QLCNIC_BRDTYPE_P3_10G_TP:\n\t\tadapter->ahw.port_type = (adapter->portnum < 2) ?\n\t\t\tQLCNIC_XGBE : QLCNIC_GBE;\n\t\tbreak;\n\tdefault:\n\t\tdev_err(&pdev->dev, \"unknown board type %x\\n\", board_type);\n\t\tadapter->ahw.port_type = QLCNIC_XGBE;\n\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nint\nqlcnic_wol_supported(struct qlcnic_adapter *adapter)\n{\n\tu32 wol_cfg;\n\n\twol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG_NV);\n\tif (wol_cfg & (1UL << adapter->portnum)) {\n\t\twol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG);\n\t\tif (wol_cfg & (1 << adapter->portnum))\n\t\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n\nint qlcnic_config_led(struct qlcnic_adapter *adapter, u32 state, u32 rate)\n{\n\tstruct qlcnic_nic_req req;\n\tint rv;\n\tu64 word;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_LED | ((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\n\treq.words[0] = cpu_to_le64((u64)rate << 32);\n\treq.words[1] = cpu_to_le64(state);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv)\n\t\tdev_err(&adapter->pdev->dev, \"LED configuration failed.\\n\");\n\n\treturn rv;\n}\n\nstatic int qlcnic_set_fw_loopback(struct qlcnic_adapter *adapter, u32 flag)\n{\n\tstruct qlcnic_nic_req\treq;\n\tint\t\t\trv;\n\tu64\t\t\tword;\n\n\tmemset(&req, 0, sizeof(struct qlcnic_nic_req));\n\treq.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);\n\n\tword = QLCNIC_H2C_OPCODE_CONFIG_LOOPBACK |\n\t\t\t((u64)adapter->portnum << 16);\n\treq.req_hdr = cpu_to_le64(word);\n\treq.words[0] = cpu_to_le64(flag);\n\n\trv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);\n\tif (rv)\n\t\tdev_err(&adapter->pdev->dev,\n\t\t\t\"%sting loopback mode failed.\\n\",\n\t\t\t\t\tflag ? \"Set\" : \"Reset\");\n\treturn rv;\n}\n\nint qlcnic_set_ilb_mode(struct qlcnic_adapter *adapter)\n{\n\tif (qlcnic_set_fw_loopback(adapter, 1))\n\t\treturn -EIO;\n\n\tif (qlcnic_nic_set_promisc(adapter,\n\t\t\t\tVPORT_MISS_MODE_ACCEPT_ALL)) {\n\t\tqlcnic_set_fw_loopback(adapter, 0);\n\t\treturn -EIO;\n\t}\n\n\tmsleep(1000);\n\treturn 0;\n}\n\nvoid qlcnic_clear_ilb_mode(struct qlcnic_adapter *adapter)\n{\n\tint mode = VPORT_MISS_MODE_DROP;\n\tstruct net_device *netdev = adapter->netdev;\n\n\tqlcnic_set_fw_loopback(adapter, 0);\n\n\tif (netdev->flags & IFF_PROMISC)\n\t\tmode = VPORT_MISS_MODE_ACCEPT_ALL;\n\telse if (netdev->flags & IFF_ALLMULTI)\n\t\tmode = VPORT_MISS_MODE_ACCEPT_MULTI;\n\n\tqlcnic_nic_set_promisc(adapter, mode);\n}\n"},"repo_name":{"kind":"string","value":"ggsamsa/sched_casio"},"path":{"kind":"string","value":"drivers/net/qlcnic/qlcnic_hw.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":33431,"string":"33,431"}}},{"rowIdx":115086567,"cells":{"code":{"kind":"string","value":"// SPDX-License-Identifier: GPL-2.0+\n/* I2C support for Dialog DA9063\n *\n * Copyright 2012 Dialog Semiconductor Ltd.\n * Copyright 2013 Philipp Zabel, Pengutronix\n *\n * Author: Krystian Garbaciak, Dialog Semiconductor\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n/*\n * Raw I2C access required for just accessing chip and variant info before we\n * know which device is present. The info read from the device using this\n * approach is then used to select the correct regmap tables.\n */\n\n#define DA9063_REG_PAGE_SIZE\t\t0x100\n#define DA9063_REG_PAGED_ADDR_MASK\t0xFF\n\nenum da9063_page_sel_buf_fmt {\n\tDA9063_PAGE_SEL_BUF_PAGE_REG = 0,\n\tDA9063_PAGE_SEL_BUF_PAGE_VAL,\n\tDA9063_PAGE_SEL_BUF_SIZE,\n};\n\nenum da9063_paged_read_msgs {\n\tDA9063_PAGED_READ_MSG_PAGE_SEL = 0,\n\tDA9063_PAGED_READ_MSG_REG_SEL,\n\tDA9063_PAGED_READ_MSG_DATA,\n\tDA9063_PAGED_READ_MSG_CNT,\n};\n\nstatic int da9063_i2c_blockreg_read(struct i2c_client *client, u16 addr,\n\t\t\t\t u8 *buf, int count)\n{\n\tstruct i2c_msg xfer[DA9063_PAGED_READ_MSG_CNT];\n\tu8 page_sel_buf[DA9063_PAGE_SEL_BUF_SIZE];\n\tu8 page_num, paged_addr;\n\tint ret;\n\n\t/* Determine page info based on register address */\n\tpage_num = (addr / DA9063_REG_PAGE_SIZE);\n\tif (page_num > 1) {\n\t\tdev_err(&client->dev, \"Invalid register address provided\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\tpaged_addr = (addr % DA9063_REG_PAGE_SIZE) & DA9063_REG_PAGED_ADDR_MASK;\n\tpage_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_REG] = DA9063_REG_PAGE_CON;\n\tpage_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_VAL] =\n\t\t(page_num << DA9063_I2C_PAGE_SEL_SHIFT) & DA9063_REG_PAGE_MASK;\n\n\t/* Write reg address, page selection */\n\txfer[DA9063_PAGED_READ_MSG_PAGE_SEL].addr = client->addr;\n\txfer[DA9063_PAGED_READ_MSG_PAGE_SEL].flags = 0;\n\txfer[DA9063_PAGED_READ_MSG_PAGE_SEL].len = DA9063_PAGE_SEL_BUF_SIZE;\n\txfer[DA9063_PAGED_READ_MSG_PAGE_SEL].buf = page_sel_buf;\n\n\t/* Select register address */\n\txfer[DA9063_PAGED_READ_MSG_REG_SEL].addr = client->addr;\n\txfer[DA9063_PAGED_READ_MSG_REG_SEL].flags = 0;\n\txfer[DA9063_PAGED_READ_MSG_REG_SEL].len = sizeof(paged_addr);\n\txfer[DA9063_PAGED_READ_MSG_REG_SEL].buf = &paged_addr;\n\n\t/* Read data */\n\txfer[DA9063_PAGED_READ_MSG_DATA].addr = client->addr;\n\txfer[DA9063_PAGED_READ_MSG_DATA].flags = I2C_M_RD;\n\txfer[DA9063_PAGED_READ_MSG_DATA].len = count;\n\txfer[DA9063_PAGED_READ_MSG_DATA].buf = buf;\n\n\tret = i2c_transfer(client->adapter, xfer, DA9063_PAGED_READ_MSG_CNT);\n\tif (ret < 0) {\n\t\tdev_err(&client->dev, \"Paged block read failed: %d\\n\", ret);\n\t\treturn ret;\n\t}\n\n\tif (ret != DA9063_PAGED_READ_MSG_CNT) {\n\t\tdev_err(&client->dev, \"Paged block read failed to complete\\n\");\n\t\treturn -EIO;\n\t}\n\n\treturn 0;\n}\n\nenum {\n\tDA9063_DEV_ID_REG = 0,\n\tDA9063_VAR_ID_REG,\n\tDA9063_CHIP_ID_REGS,\n};\n\nstatic int da9063_get_device_type(struct i2c_client *i2c, struct da9063 *da9063)\n{\n\tu8 buf[DA9063_CHIP_ID_REGS];\n\tint ret;\n\n\tret = da9063_i2c_blockreg_read(i2c, DA9063_REG_DEVICE_ID, buf,\n\t\t\t\t DA9063_CHIP_ID_REGS);\n\tif (ret)\n\t\treturn ret;\n\n\tif (buf[DA9063_DEV_ID_REG] != PMIC_CHIP_ID_DA9063) {\n\t\tdev_err(da9063->dev,\n\t\t\t\"Invalid chip device ID: 0x%02x\\n\",\n\t\t\tbuf[DA9063_DEV_ID_REG]);\n\t\treturn -ENODEV;\n\t}\n\n\tdev_info(da9063->dev,\n\t\t \"Device detected (chip-ID: 0x%02X, var-ID: 0x%02X)\\n\",\n\t\t buf[DA9063_DEV_ID_REG], buf[DA9063_VAR_ID_REG]);\n\n\tda9063->variant_code =\n\t\t(buf[DA9063_VAR_ID_REG] & DA9063_VARIANT_ID_MRC_MASK)\n\t\t>> DA9063_VARIANT_ID_MRC_SHIFT;\n\n\treturn 0;\n}\n\n/*\n * Variant specific regmap configs\n */\n\nstatic const struct regmap_range da9063_ad_readable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_AD_REG_SECOND_D),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_T_OFFSET, DA9063_AD_REG_GP_ID_19),\n\tregmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),\n};\n\nstatic const struct regmap_range da9063_ad_writeable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),\n\tregmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),\n\tregmap_reg_range(DA9063_REG_COUNT_S, DA9063_AD_REG_ALARM_Y),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_CONFIG_I, DA9063_AD_REG_MON_REG_4),\n\tregmap_reg_range(DA9063_AD_REG_GP_ID_0, DA9063_AD_REG_GP_ID_19),\n};\n\nstatic const struct regmap_range da9063_ad_volatile_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),\n\tregmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),\n\tregmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),\n\tregmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),\n\tregmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),\n\tregmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_AD_REG_SECOND_D),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),\n\tregmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),\n\tregmap_reg_range(DA9063_AD_REG_MON_REG_5, DA9063_AD_REG_MON_REG_6),\n};\n\nstatic const struct regmap_access_table da9063_ad_readable_table = {\n\t.yes_ranges = da9063_ad_readable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_ad_readable_ranges),\n};\n\nstatic const struct regmap_access_table da9063_ad_writeable_table = {\n\t.yes_ranges = da9063_ad_writeable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_ad_writeable_ranges),\n};\n\nstatic const struct regmap_access_table da9063_ad_volatile_table = {\n\t.yes_ranges = da9063_ad_volatile_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_ad_volatile_ranges),\n};\n\nstatic const struct regmap_range da9063_bb_readable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19),\n\tregmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),\n};\n\nstatic const struct regmap_range da9063_bb_writeable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),\n\tregmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),\n\tregmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),\n\tregmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19),\n};\n\nstatic const struct regmap_range da9063_bb_da_volatile_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),\n\tregmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),\n\tregmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),\n\tregmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),\n\tregmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),\n\tregmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_BB_REG_SECOND_D),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),\n\tregmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),\n\tregmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6),\n};\n\nstatic const struct regmap_access_table da9063_bb_readable_table = {\n\t.yes_ranges = da9063_bb_readable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_bb_readable_ranges),\n};\n\nstatic const struct regmap_access_table da9063_bb_writeable_table = {\n\t.yes_ranges = da9063_bb_writeable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_bb_writeable_ranges),\n};\n\nstatic const struct regmap_access_table da9063_bb_da_volatile_table = {\n\t.yes_ranges = da9063_bb_da_volatile_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_bb_da_volatile_ranges),\n};\n\nstatic const struct regmap_range da9063l_bb_readable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19),\n\tregmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),\n};\n\nstatic const struct regmap_range da9063l_bb_writeable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),\n\tregmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),\n\tregmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19),\n};\n\nstatic const struct regmap_range da9063l_bb_da_volatile_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),\n\tregmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),\n\tregmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),\n\tregmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),\n\tregmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),\n\tregmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_REG_MON_A10_RES),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),\n\tregmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),\n\tregmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6),\n};\n\nstatic const struct regmap_access_table da9063l_bb_readable_table = {\n\t.yes_ranges = da9063l_bb_readable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063l_bb_readable_ranges),\n};\n\nstatic const struct regmap_access_table da9063l_bb_writeable_table = {\n\t.yes_ranges = da9063l_bb_writeable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063l_bb_writeable_ranges),\n};\n\nstatic const struct regmap_access_table da9063l_bb_da_volatile_table = {\n\t.yes_ranges = da9063l_bb_da_volatile_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063l_bb_da_volatile_ranges),\n};\n\nstatic const struct regmap_range da9063_da_readable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11),\n\tregmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),\n};\n\nstatic const struct regmap_range da9063_da_writeable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),\n\tregmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),\n\tregmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),\n\tregmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11),\n};\n\nstatic const struct regmap_access_table da9063_da_readable_table = {\n\t.yes_ranges = da9063_da_readable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_da_readable_ranges),\n};\n\nstatic const struct regmap_access_table da9063_da_writeable_table = {\n\t.yes_ranges = da9063_da_writeable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063_da_writeable_ranges),\n};\n\nstatic const struct regmap_range da9063l_da_readable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11),\n\tregmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),\n};\n\nstatic const struct regmap_range da9063l_da_writeable_ranges[] = {\n\tregmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),\n\tregmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),\n\tregmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),\n\tregmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),\n\tregmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),\n\tregmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11),\n};\n\nstatic const struct regmap_access_table da9063l_da_readable_table = {\n\t.yes_ranges = da9063l_da_readable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063l_da_readable_ranges),\n};\n\nstatic const struct regmap_access_table da9063l_da_writeable_table = {\n\t.yes_ranges = da9063l_da_writeable_ranges,\n\t.n_yes_ranges = ARRAY_SIZE(da9063l_da_writeable_ranges),\n};\n\nstatic const struct regmap_range_cfg da9063_range_cfg[] = {\n\t{\n\t\t.range_min = DA9063_REG_PAGE_CON,\n\t\t.range_max = DA9063_REG_CONFIG_ID,\n\t\t.selector_reg = DA9063_REG_PAGE_CON,\n\t\t.selector_mask = 1 << DA9063_I2C_PAGE_SEL_SHIFT,\n\t\t.selector_shift = DA9063_I2C_PAGE_SEL_SHIFT,\n\t\t.window_start = 0,\n\t\t.window_len = 256,\n\t}\n};\n\nstatic struct regmap_config da9063_regmap_config = {\n\t.reg_bits = 8,\n\t.val_bits = 8,\n\t.ranges = da9063_range_cfg,\n\t.num_ranges = ARRAY_SIZE(da9063_range_cfg),\n\t.max_register = DA9063_REG_CONFIG_ID,\n\n\t.cache_type = REGCACHE_RBTREE,\n};\n\nstatic const struct of_device_id da9063_dt_ids[] = {\n\t{ .compatible = \"dlg,da9063\", },\n\t{ .compatible = \"dlg,da9063l\", },\n\t{ }\n};\nMODULE_DEVICE_TABLE(of, da9063_dt_ids);\nstatic int da9063_i2c_probe(struct i2c_client *i2c,\n\t\t\t const struct i2c_device_id *id)\n{\n\tstruct da9063 *da9063;\n\tint ret;\n\n\tda9063 = devm_kzalloc(&i2c->dev, sizeof(struct da9063), GFP_KERNEL);\n\tif (da9063 == NULL)\n\t\treturn -ENOMEM;\n\n\ti2c_set_clientdata(i2c, da9063);\n\tda9063->dev = &i2c->dev;\n\tda9063->chip_irq = i2c->irq;\n\tda9063->type = id->driver_data;\n\n\tret = da9063_get_device_type(i2c, da9063);\n\tif (ret)\n\t\treturn ret;\n\n\tswitch (da9063->type) {\n\tcase PMIC_TYPE_DA9063:\n\t\tswitch (da9063->variant_code) {\n\t\tcase PMIC_DA9063_AD:\n\t\t\tda9063_regmap_config.rd_table =\n\t\t\t\t&da9063_ad_readable_table;\n\t\t\tda9063_regmap_config.wr_table =\n\t\t\t\t&da9063_ad_writeable_table;\n\t\t\tda9063_regmap_config.volatile_table =\n\t\t\t\t&da9063_ad_volatile_table;\n\t\t\tbreak;\n\t\tcase PMIC_DA9063_BB:\n\t\tcase PMIC_DA9063_CA:\n\t\t\tda9063_regmap_config.rd_table =\n\t\t\t\t&da9063_bb_readable_table;\n\t\t\tda9063_regmap_config.wr_table =\n\t\t\t\t&da9063_bb_writeable_table;\n\t\t\tda9063_regmap_config.volatile_table =\n\t\t\t\t&da9063_bb_da_volatile_table;\n\t\t\tbreak;\n\t\tcase PMIC_DA9063_DA:\n\t\t\tda9063_regmap_config.rd_table =\n\t\t\t\t&da9063_da_readable_table;\n\t\t\tda9063_regmap_config.wr_table =\n\t\t\t\t&da9063_da_writeable_table;\n\t\t\tda9063_regmap_config.volatile_table =\n\t\t\t\t&da9063_bb_da_volatile_table;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdev_err(da9063->dev,\n\t\t\t\t\"Chip variant not supported for DA9063\\n\");\n\t\t\treturn -ENODEV;\n\t\t}\n\t\tbreak;\n\tcase PMIC_TYPE_DA9063L:\n\t\tswitch (da9063->variant_code) {\n\t\tcase PMIC_DA9063_BB:\n\t\tcase PMIC_DA9063_CA:\n\t\t\tda9063_regmap_config.rd_table =\n\t\t\t\t&da9063l_bb_readable_table;\n\t\t\tda9063_regmap_config.wr_table =\n\t\t\t\t&da9063l_bb_writeable_table;\n\t\t\tda9063_regmap_config.volatile_table =\n\t\t\t\t&da9063l_bb_da_volatile_table;\n\t\t\tbreak;\n\t\tcase PMIC_DA9063_DA:\n\t\t\tda9063_regmap_config.rd_table =\n\t\t\t\t&da9063l_da_readable_table;\n\t\t\tda9063_regmap_config.wr_table =\n\t\t\t\t&da9063l_da_writeable_table;\n\t\t\tda9063_regmap_config.volatile_table =\n\t\t\t\t&da9063l_bb_da_volatile_table;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tdev_err(da9063->dev,\n\t\t\t\t\"Chip variant not supported for DA9063L\\n\");\n\t\t\treturn -ENODEV;\n\t\t}\n\t\tbreak;\n\tdefault:\n\t\tdev_err(da9063->dev, \"Chip type not supported\\n\");\n\t\treturn -ENODEV;\n\t}\n\n\tda9063->regmap = devm_regmap_init_i2c(i2c, &da9063_regmap_config);\n\tif (IS_ERR(da9063->regmap)) {\n\t\tret = PTR_ERR(da9063->regmap);\n\t\tdev_err(da9063->dev, \"Failed to allocate register map: %d\\n\",\n\t\t\tret);\n\t\treturn ret;\n\t}\n\n\treturn da9063_device_init(da9063, i2c->irq);\n}\n\nstatic const struct i2c_device_id da9063_i2c_id[] = {\n\t{ \"da9063\", PMIC_TYPE_DA9063 },\n\t{ \"da9063l\", PMIC_TYPE_DA9063L },\n\t{},\n};\nMODULE_DEVICE_TABLE(i2c, da9063_i2c_id);\n\nstatic struct i2c_driver da9063_i2c_driver = {\n\t.driver = {\n\t\t.name = \"da9063\",\n\t\t.of_match_table = da9063_dt_ids,\n\t},\n\t.probe = da9063_i2c_probe,\n\t.id_table = da9063_i2c_id,\n};\n\nmodule_i2c_driver(da9063_i2c_driver);\n"},"repo_name":{"kind":"string","value":"GuillaumeSeren/linux"},"path":{"kind":"string","value":"drivers/mfd/da9063-i2c.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":15634,"string":"15,634"}}},{"rowIdx":115086568,"cells":{"code":{"kind":"string","value":"/*\n * Licensed to Elasticsearch under one or more contributor\n * license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright\n * ownership. Elasticsearch licenses this file to you under\n * the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage org.elasticsearch.search.aggregations.bucket.terms;\n\nimport com.google.common.collect.ArrayListMultimap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\n\nimport org.elasticsearch.common.io.stream.Streamable;\nimport org.elasticsearch.common.xcontent.ToXContent;\nimport org.elasticsearch.search.aggregations.AggregationExecutionException;\nimport org.elasticsearch.search.aggregations.Aggregations;\nimport org.elasticsearch.search.aggregations.InternalAggregation;\nimport org.elasticsearch.search.aggregations.InternalAggregations;\nimport org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;\nimport org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue;\nimport org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;\nimport org.elasticsearch.search.aggregations.support.format.ValueFormatter;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n *\n */\npublic abstract class InternalTerms extends InternalMultiBucketAggregation\n implements Terms, ToXContent, Streamable {\n\n protected static final String DOC_COUNT_ERROR_UPPER_BOUND_FIELD_NAME = \"doc_count_error_upper_bound\";\n protected static final String SUM_OF_OTHER_DOC_COUNTS = \"sum_other_doc_count\";\n\n public static abstract class Bucket extends Terms.Bucket {\n\n long bucketOrd;\n\n protected long docCount;\n protected long docCountError;\n protected InternalAggregations aggregations;\n protected boolean showDocCountError;\n transient final ValueFormatter formatter;\n\n protected Bucket(ValueFormatter formatter, boolean showDocCountError) {\n // for serialization\n this.showDocCountError = showDocCountError;\n this.formatter = formatter;\n }\n\n protected Bucket(long docCount, InternalAggregations aggregations, boolean showDocCountError, long docCountError,\n ValueFormatter formatter) {\n this(formatter, showDocCountError);\n this.docCount = docCount;\n this.aggregations = aggregations;\n this.docCountError = docCountError;\n }\n\n @Override\n public long getDocCount() {\n return docCount;\n }\n\n @Override\n public long getDocCountError() {\n if (!showDocCountError) {\n throw new IllegalStateException(\"show_terms_doc_count_error is false\");\n }\n return docCountError;\n }\n\n @Override\n public Aggregations getAggregations() {\n return aggregations;\n }\n\n abstract Bucket newBucket(long docCount, InternalAggregations aggs, long docCountError);\n\n public Bucket reduce(List buckets, ReduceContext context) {\n long docCount = 0;\n long docCountError = 0;\n List aggregationsList = new ArrayList<>(buckets.size());\n for (Bucket bucket : buckets) {\n docCount += bucket.docCount;\n if (docCountError != -1) {\n if (bucket.docCountError == -1) {\n docCountError = -1;\n } else {\n docCountError += bucket.docCountError;\n }\n }\n aggregationsList.add(bucket.aggregations);\n }\n InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context);\n return newBucket(docCount, aggs, docCountError);\n }\n }\n\n protected Terms.Order order;\n protected int requiredSize;\n protected int shardSize;\n protected long minDocCount;\n protected List buckets;\n protected Map bucketMap;\n protected long docCountError;\n protected boolean showTermDocCountError;\n protected long otherDocCount;\n\n protected InternalTerms() {} // for serialization\n\n protected InternalTerms(String name, Terms.Order order, int requiredSize, int shardSize, long minDocCount,\n List buckets, boolean showTermDocCountError, long docCountError, long otherDocCount, List pipelineAggregators,\n Map metaData) {\n super(name, pipelineAggregators, metaData);\n this.order = order;\n this.requiredSize = requiredSize;\n this.shardSize = shardSize;\n this.minDocCount = minDocCount;\n this.buckets = buckets;\n this.showTermDocCountError = showTermDocCountError;\n this.docCountError = docCountError;\n this.otherDocCount = otherDocCount;\n }\n\n @Override\n public List getBuckets() {\n Object o = buckets;\n return (List) o;\n }\n\n @Override\n public Terms.Bucket getBucketByKey(String term) {\n if (bucketMap == null) {\n bucketMap = Maps.newHashMapWithExpectedSize(buckets.size());\n for (Bucket bucket : buckets) {\n bucketMap.put(bucket.getKeyAsString(), bucket);\n }\n }\n return bucketMap.get(term);\n }\n\n @Override\n public long getDocCountError() {\n return docCountError;\n }\n\n @Override\n public long getSumOfOtherDocCounts() {\n return otherDocCount;\n }\n\n @Override\n public InternalAggregation doReduce(List aggregations, ReduceContext reduceContext) {\n\n Multimap buckets = ArrayListMultimap.create();\n long sumDocCountError = 0;\n long otherDocCount = 0;\n InternalTerms referenceTerms = null;\n for (InternalAggregation aggregation : aggregations) {\n InternalTerms terms = (InternalTerms) aggregation;\n if (referenceTerms == null && !terms.getClass().equals(UnmappedTerms.class)) {\n referenceTerms = (InternalTerms) aggregation;\n }\n if (referenceTerms != null &&\n !referenceTerms.getClass().equals(terms.getClass()) &&\n !terms.getClass().equals(UnmappedTerms.class)) {\n // control gets into this loop when the same field name against which the query is executed\n // is of different types in different indices.\n throw new AggregationExecutionException(\"Merging/Reducing the aggregations failed \" +\n \"when computing the aggregation [ Name: \" +\n referenceTerms.getName() + \", Type: \" +\n referenceTerms.type() + \" ]\" + \" because: \" +\n \"the field you gave in the aggregation query \" +\n \"existed as two different types \" +\n \"in two different indices\");\n }\n otherDocCount += terms.getSumOfOtherDocCounts();\n final long thisAggDocCountError;\n if (terms.buckets.size() < this.shardSize || this.order == InternalOrder.TERM_ASC || this.order == InternalOrder.TERM_DESC) {\n thisAggDocCountError = 0;\n } else if (InternalOrder.isCountDesc(this.order)) {\n thisAggDocCountError = terms.buckets.get(terms.buckets.size() - 1).docCount;\n } else {\n thisAggDocCountError = -1;\n }\n if (sumDocCountError != -1) {\n if (thisAggDocCountError == -1) {\n sumDocCountError = -1;\n } else {\n sumDocCountError += thisAggDocCountError;\n }\n }\n terms.docCountError = thisAggDocCountError;\n for (Bucket bucket : terms.buckets) {\n bucket.docCountError = thisAggDocCountError;\n buckets.put(bucket.getKey(), bucket);\n }\n }\n\n final int size = Math.min(requiredSize, buckets.size());\n BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null));\n for (Collection l : buckets.asMap().values()) {\n List sameTermBuckets = (List) l; // cast is ok according to javadocs\n final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext);\n if (b.docCountError != -1) {\n if (sumDocCountError == -1) {\n b.docCountError = -1;\n } else {\n b.docCountError = sumDocCountError - b.docCountError;\n }\n }\n if (b.docCount >= minDocCount) {\n Terms.Bucket removed = ordered.insertWithOverflow(b);\n if (removed != null) {\n otherDocCount += removed.getDocCount();\n }\n }\n }\n Bucket[] list = new Bucket[ordered.size()];\n for (int i = ordered.size() - 1; i >= 0; i--) {\n list[i] = (Bucket) ordered.pop();\n }\n long docCountError;\n if (sumDocCountError == -1) {\n docCountError = -1;\n } else {\n docCountError = aggregations.size() == 1 ? 0 : sumDocCountError;\n }\n return create(name, Arrays.asList(list), docCountError, otherDocCount, this);\n }\n\n protected abstract A create(String name, List buckets, long docCountError, long otherDocCount,\n InternalTerms prototype);\n\n}\n"},"repo_name":{"kind":"string","value":"queirozfcom/elasticsearch"},"path":{"kind":"string","value":"core/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":10492,"string":"10,492"}}},{"rowIdx":115086569,"cells":{"code":{"kind":"string","value":"// Copyright 2015 Google Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\npackage v2\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/golang/glog\"\n\t\"github.com/google/cadvisor/info/v1\"\n)\n\nfunc machineFsStatsFromV1(fsStats []v1.FsStats) []MachineFsStats {\n\tvar result []MachineFsStats\n\tfor _, stat := range fsStats {\n\t\treadDuration := time.Millisecond * time.Duration(stat.ReadTime)\n\t\twriteDuration := time.Millisecond * time.Duration(stat.WriteTime)\n\t\tioDuration := time.Millisecond * time.Duration(stat.IoTime)\n\t\tweightedDuration := time.Millisecond * time.Duration(stat.WeightedIoTime)\n\t\tresult = append(result, MachineFsStats{\n\t\t\tDevice: stat.Device,\n\t\t\tType: stat.Type,\n\t\t\tCapacity: &stat.Limit,\n\t\t\tUsage: &stat.Usage,\n\t\t\tAvailable: &stat.Available,\n\t\t\tInodesFree: &stat.InodesFree,\n\t\t\tDiskStats: DiskStats{\n\t\t\t\tReadsCompleted: &stat.ReadsCompleted,\n\t\t\t\tReadsMerged: &stat.ReadsMerged,\n\t\t\t\tSectorsRead: &stat.SectorsRead,\n\t\t\t\tReadDuration: &readDuration,\n\t\t\t\tWritesCompleted: &stat.WritesCompleted,\n\t\t\t\tWritesMerged: &stat.WritesMerged,\n\t\t\t\tSectorsWritten: &stat.SectorsWritten,\n\t\t\t\tWriteDuration: &writeDuration,\n\t\t\t\tIoInProgress: &stat.IoInProgress,\n\t\t\t\tIoDuration: &ioDuration,\n\t\t\t\tWeightedIoDuration: &weightedDuration,\n\t\t\t},\n\t\t})\n\t}\n\treturn result\n}\n\nfunc MachineStatsFromV1(cont *v1.ContainerInfo) []MachineStats {\n\tvar stats []MachineStats\n\tvar last *v1.ContainerStats\n\tfor _, val := range cont.Stats {\n\t\tstat := MachineStats{\n\t\t\tTimestamp: val.Timestamp,\n\t\t}\n\t\tif cont.Spec.HasCpu {\n\t\t\tstat.Cpu = &val.Cpu\n\t\t\tcpuInst, err := InstCpuStats(last, val)\n\t\t\tif err != nil {\n\t\t\t\tglog.Warningf(\"Could not get instant cpu stats: %v\", err)\n\t\t\t} else {\n\t\t\t\tstat.CpuInst = cpuInst\n\t\t\t}\n\t\t\tlast = val\n\t\t}\n\t\tif cont.Spec.HasMemory {\n\t\t\tstat.Memory = &val.Memory\n\t\t}\n\t\tif cont.Spec.HasNetwork {\n\t\t\tstat.Network = &NetworkStats{\n\t\t\t\t// FIXME: Use reflection instead.\n\t\t\t\tTcp: TcpStat(val.Network.Tcp),\n\t\t\t\tTcp6: TcpStat(val.Network.Tcp6),\n\t\t\t\tInterfaces: val.Network.Interfaces,\n\t\t\t}\n\t\t}\n\t\tif cont.Spec.HasFilesystem {\n\t\t\tstat.Filesystem = machineFsStatsFromV1(val.Filesystem)\n\t\t}\n\t\t// TODO(rjnagal): Handle load stats.\n\t\tstats = append(stats, stat)\n\t}\n\treturn stats\n}\n\nfunc ContainerStatsFromV1(spec *v1.ContainerSpec, stats []*v1.ContainerStats) []*ContainerStats {\n\tnewStats := make([]*ContainerStats, 0, len(stats))\n\tvar last *v1.ContainerStats\n\tfor _, val := range stats {\n\t\tstat := &ContainerStats{\n\t\t\tTimestamp: val.Timestamp,\n\t\t}\n\t\tif spec.HasCpu {\n\t\t\tstat.Cpu = &val.Cpu\n\t\t\tcpuInst, err := InstCpuStats(last, val)\n\t\t\tif err != nil {\n\t\t\t\tglog.Warningf(\"Could not get instant cpu stats: %v\", err)\n\t\t\t} else {\n\t\t\t\tstat.CpuInst = cpuInst\n\t\t\t}\n\t\t\tlast = val\n\t\t}\n\t\tif spec.HasMemory {\n\t\t\tstat.Memory = &val.Memory\n\t\t}\n\t\tif spec.HasNetwork {\n\t\t\t// TODO: Handle TcpStats\n\t\t\tstat.Network = &NetworkStats{\n\t\t\t\tInterfaces: val.Network.Interfaces,\n\t\t\t}\n\t\t}\n\t\tif spec.HasFilesystem {\n\t\t\tif len(val.Filesystem) == 1 {\n\t\t\t\tstat.Filesystem = &FilesystemStats{\n\t\t\t\t\tTotalUsageBytes: &val.Filesystem[0].Usage,\n\t\t\t\t\tBaseUsageBytes: &val.Filesystem[0].BaseUsage,\n\t\t\t\t}\n\t\t\t} else if len(val.Filesystem) > 1 {\n\t\t\t\t// Cannot handle multiple devices per container.\n\t\t\t\tglog.V(2).Infof(\"failed to handle multiple devices for container. Skipping Filesystem stats\")\n\t\t\t}\n\t\t}\n\t\tif spec.HasDiskIo {\n\t\t\tstat.DiskIo = &val.DiskIo\n\t\t}\n\t\tif spec.HasCustomMetrics {\n\t\t\tstat.CustomMetrics = val.CustomMetrics\n\t\t}\n\t\t// TODO(rjnagal): Handle load stats.\n\t\tnewStats = append(newStats, stat)\n\t}\n\treturn newStats\n}\n\nfunc DeprecatedStatsFromV1(cont *v1.ContainerInfo) []DeprecatedContainerStats {\n\tstats := make([]DeprecatedContainerStats, 0, len(cont.Stats))\n\tvar last *v1.ContainerStats\n\tfor _, val := range cont.Stats {\n\t\tstat := DeprecatedContainerStats{\n\t\t\tTimestamp: val.Timestamp,\n\t\t\tHasCpu: cont.Spec.HasCpu,\n\t\t\tHasMemory: cont.Spec.HasMemory,\n\t\t\tHasNetwork: cont.Spec.HasNetwork,\n\t\t\tHasFilesystem: cont.Spec.HasFilesystem,\n\t\t\tHasDiskIo: cont.Spec.HasDiskIo,\n\t\t\tHasCustomMetrics: cont.Spec.HasCustomMetrics,\n\t\t}\n\t\tif stat.HasCpu {\n\t\t\tstat.Cpu = val.Cpu\n\t\t\tcpuInst, err := InstCpuStats(last, val)\n\t\t\tif err != nil {\n\t\t\t\tglog.Warningf(\"Could not get instant cpu stats: %v\", err)\n\t\t\t} else {\n\t\t\t\tstat.CpuInst = cpuInst\n\t\t\t}\n\t\t\tlast = val\n\t\t}\n\t\tif stat.HasMemory {\n\t\t\tstat.Memory = val.Memory\n\t\t}\n\t\tif stat.HasNetwork {\n\t\t\tstat.Network.Interfaces = val.Network.Interfaces\n\t\t}\n\t\tif stat.HasFilesystem {\n\t\t\tstat.Filesystem = val.Filesystem\n\t\t}\n\t\tif stat.HasDiskIo {\n\t\t\tstat.DiskIo = val.DiskIo\n\t\t}\n\t\tif stat.HasCustomMetrics {\n\t\t\tstat.CustomMetrics = val.CustomMetrics\n\t\t}\n\t\t// TODO(rjnagal): Handle load stats.\n\t\tstats = append(stats, stat)\n\t}\n\treturn stats\n}\n\nfunc InstCpuStats(last, cur *v1.ContainerStats) (*CpuInstStats, error) {\n\tif last == nil {\n\t\treturn nil, nil\n\t}\n\tif !cur.Timestamp.After(last.Timestamp) {\n\t\treturn nil, fmt.Errorf(\"container stats move backwards in time\")\n\t}\n\tif len(last.Cpu.Usage.PerCpu) != len(cur.Cpu.Usage.PerCpu) {\n\t\treturn nil, fmt.Errorf(\"different number of cpus\")\n\t}\n\ttimeDelta := cur.Timestamp.Sub(last.Timestamp)\n\tif timeDelta <= 100*time.Millisecond {\n\t\treturn nil, fmt.Errorf(\"time delta unexpectedly small\")\n\t}\n\t// Nanoseconds to gain precision and avoid having zero seconds if the\n\t// difference between the timestamps is just under a second\n\ttimeDeltaNs := uint64(timeDelta.Nanoseconds())\n\tconvertToRate := func(lastValue, curValue uint64) (uint64, error) {\n\t\tif curValue < lastValue {\n\t\t\treturn 0, fmt.Errorf(\"cumulative stats decrease\")\n\t\t}\n\t\tvalueDelta := curValue - lastValue\n\t\t// Use float64 to keep precision\n\t\treturn uint64(float64(valueDelta) / float64(timeDeltaNs) * 1e9), nil\n\t}\n\ttotal, err := convertToRate(last.Cpu.Usage.Total, cur.Cpu.Usage.Total)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpercpu := make([]uint64, len(last.Cpu.Usage.PerCpu))\n\tfor i := range percpu {\n\t\tvar err error\n\t\tpercpu[i], err = convertToRate(last.Cpu.Usage.PerCpu[i], cur.Cpu.Usage.PerCpu[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tuser, err := convertToRate(last.Cpu.Usage.User, cur.Cpu.Usage.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsystem, err := convertToRate(last.Cpu.Usage.System, cur.Cpu.Usage.System)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CpuInstStats{\n\t\tUsage: CpuInstUsage{\n\t\t\tTotal: total,\n\t\t\tPerCpu: percpu,\n\t\t\tUser: user,\n\t\t\tSystem: system,\n\t\t},\n\t}, nil\n}\n\n// Get V2 container spec from v1 container info.\nfunc ContainerSpecFromV1(specV1 *v1.ContainerSpec, aliases []string, namespace string) ContainerSpec {\n\tspecV2 := ContainerSpec{\n\t\tCreationTime: specV1.CreationTime,\n\t\tHasCpu: specV1.HasCpu,\n\t\tHasMemory: specV1.HasMemory,\n\t\tHasFilesystem: specV1.HasFilesystem,\n\t\tHasNetwork: specV1.HasNetwork,\n\t\tHasDiskIo: specV1.HasDiskIo,\n\t\tHasCustomMetrics: specV1.HasCustomMetrics,\n\t\tImage: specV1.Image,\n\t\tLabels: specV1.Labels,\n\t}\n\tif specV1.HasCpu {\n\t\tspecV2.Cpu.Limit = specV1.Cpu.Limit\n\t\tspecV2.Cpu.MaxLimit = specV1.Cpu.MaxLimit\n\t\tspecV2.Cpu.Mask = specV1.Cpu.Mask\n\t}\n\tif specV1.HasMemory {\n\t\tspecV2.Memory.Limit = specV1.Memory.Limit\n\t\tspecV2.Memory.Reservation = specV1.Memory.Reservation\n\t\tspecV2.Memory.SwapLimit = specV1.Memory.SwapLimit\n\t}\n\tif specV1.HasCustomMetrics {\n\t\tspecV2.CustomMetrics = specV1.CustomMetrics\n\t}\n\tspecV2.Aliases = aliases\n\tspecV2.Namespace = namespace\n\treturn specV2\n}\n"},"repo_name":{"kind":"string","value":"dmirubtsov/k8s-executor"},"path":{"kind":"string","value":"vendor/k8s.io/kubernetes/vendor/github.com/google/cadvisor/info/v2/conversion.go"},"language":{"kind":"string","value":"GO"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":7941,"string":"7,941"}}},{"rowIdx":115086570,"cells":{"code":{"kind":"string","value":"\n\n\n \n BeOpinion examples\n \n \n \n \n \n \n\n\n\n

    BeOpinion

    \n\n

    Simple Question

    \n \n \n\n

    Question with Tweet

    \n \n \n\n

    Question with Instagram post

    \n \n \n\n

    Question with YouTube video

    \n \n \n\n

    Question with Dailymotion video

    \n \n \n\n

    Question with custom video

    \n \n \n\n

    Survey

    \n \n \n\n

    Quiz

    \n \n \n\n

    Personality test

    \n \n \n\n

    Form

    \n \n \n\n

    Game

    \n \n \n\n

    Intentionally non-existing content

    \n \n \n\n

    Unpublished content

    \n \n \n\n

    Unpublished content (with fallback)

    \n \n
    \n An error occurred while retrieving the content. It might have been deleted.\n
    \n
    \n\n

    Ad

    \n \n \n\n\n\n"},"repo_name":{"kind":"string","value":"luciancrasovan/amphtml"},"path":{"kind":"string","value":"examples/beopinion.amp.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":4630,"string":"4,630"}}},{"rowIdx":115086571,"cells":{"code":{"kind":"string","value":"/////////////////////////////////////////////////////////////////////////////\n// Name: wx/bmpbuttn.h\n// Purpose: wxBitmapButton class interface\n// Author: Vadim Zeitlin\n// Modified by:\n// Created: 25.08.00\n// Copyright: (c) 2000 Vadim Zeitlin\n// Licence: wxWindows licence\n/////////////////////////////////////////////////////////////////////////////\n\n#ifndef _WX_BMPBUTTON_H_BASE_\n#define _WX_BMPBUTTON_H_BASE_\n\n#include \"wx/defs.h\"\n\n#if wxUSE_BMPBUTTON\n\n#include \"wx/button.h\"\n\n// FIXME: right now only wxMSW, wxGTK and wxOSX implement bitmap support in wxButton\n// itself, this shouldn't be used for the other platforms neither\n// when all of them do it\n#if (defined(__WXMSW__) || defined(__WXGTK20__) || defined(__WXOSX__) || defined(__WXQT__)) && !defined(__WXUNIVERSAL__)\n #define wxHAS_BUTTON_BITMAP\n#endif\n\nclass WXDLLIMPEXP_FWD_CORE wxBitmapButton;\n\n// ----------------------------------------------------------------------------\n// wxBitmapButton: a button which shows bitmaps instead of the usual string.\n// It has different bitmaps for different states (focused/disabled/pressed)\n// ----------------------------------------------------------------------------\n\nclass WXDLLIMPEXP_CORE wxBitmapButtonBase : public wxButton\n{\npublic:\n wxBitmapButtonBase()\n {\n#ifndef wxHAS_BUTTON_BITMAP\n m_marginX =\n m_marginY = 0;\n#endif // wxHAS_BUTTON_BITMAP\n }\n\n bool Create(wxWindow *parent,\n wxWindowID winid,\n const wxPoint& pos,\n const wxSize& size,\n long style,\n const wxValidator& validator,\n const wxString& name)\n {\n // We use wxBU_NOTEXT to let the base class Create() know that we are\n // not going to show the label: this is a hack needed for wxGTK where\n // we can show both label and bitmap only with GTK 2.6+ but we always\n // can show just one of them and this style allows us to choose which\n // one we need.\n //\n // And we also use wxBU_EXACTFIT to avoid being resized up to the\n // standard button size as this doesn't make sense for bitmap buttons\n // which are not standard anyhow and should fit their bitmap size.\n return wxButton::Create(parent, winid, \"\",\n pos, size,\n style | wxBU_NOTEXT | wxBU_EXACTFIT,\n validator, name);\n }\n\n // Special creation function for a standard \"Close\" bitmap. It allows to\n // simply create a close button with the image appropriate for the current\n // platform.\n static wxBitmapButton* NewCloseButton(wxWindow* parent, wxWindowID winid);\n\n\n // set/get the margins around the button\n virtual void SetMargins(int x, int y)\n {\n DoSetBitmapMargins(x, y);\n }\n\n int GetMarginX() const { return DoGetBitmapMargins().x; }\n int GetMarginY() const { return DoGetBitmapMargins().y; }\n\nprotected:\n#ifndef wxHAS_BUTTON_BITMAP\n // function called when any of the bitmaps changes\n virtual void OnSetBitmap() { InvalidateBestSize(); Refresh(); }\n\n virtual wxBitmap DoGetBitmap(State which) const { return m_bitmaps[which]; }\n virtual void DoSetBitmap(const wxBitmap& bitmap, State which)\n { m_bitmaps[which] = bitmap; OnSetBitmap(); }\n\n virtual wxSize DoGetBitmapMargins() const\n {\n return wxSize(m_marginX, m_marginY);\n }\n\n virtual void DoSetBitmapMargins(int x, int y)\n {\n m_marginX = x;\n m_marginY = y;\n }\n\n // the bitmaps for various states\n wxBitmap m_bitmaps[State_Max];\n\n // the margins around the bitmap\n int m_marginX,\n m_marginY;\n#endif // !wxHAS_BUTTON_BITMAP\n\n wxDECLARE_NO_COPY_CLASS(wxBitmapButtonBase);\n};\n\n#if defined(__WXUNIVERSAL__)\n #include \"wx/univ/bmpbuttn.h\"\n#elif defined(__WXMSW__)\n #include \"wx/msw/bmpbuttn.h\"\n#elif defined(__WXMOTIF__)\n #include \"wx/motif/bmpbuttn.h\"\n#elif defined(__WXGTK20__)\n #include \"wx/gtk/bmpbuttn.h\"\n#elif defined(__WXGTK__)\n #include \"wx/gtk1/bmpbuttn.h\"\n#elif defined(__WXMAC__)\n #include \"wx/osx/bmpbuttn.h\"\n#elif defined(__WXQT__)\n #include \"wx/qt/bmpbuttn.h\"\n#endif\n\n#endif // wxUSE_BMPBUTTON\n\n#endif // _WX_BMPBUTTON_H_BASE_\n"},"repo_name":{"kind":"string","value":"adouble42/nemesis-current"},"path":{"kind":"string","value":"wxWidgets-3.1.0/include/wx/bmpbuttn.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"bsd-2-clause"},"size":{"kind":"number","value":4285,"string":"4,285"}}},{"rowIdx":115086572,"cells":{"code":{"kind":"string","value":"// Copyright 2014 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include \"base/message_loop/message_loop.h\"\n#include \"content/renderer/media/mock_web_rtc_peer_connection_handler_client.h\"\n#include \"content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h\"\n#include \"testing/gtest/include/gtest/gtest.h\"\n#include \"third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h\"\n\nnamespace content {\n\nclass PeerConnectionDependencyFactoryTest : public ::testing::Test {\n public:\n void SetUp() override {\n dependency_factory_.reset(new MockPeerConnectionDependencyFactory());\n }\n\n protected:\n base::MessageLoop message_loop_;\n scoped_ptr dependency_factory_;\n};\n\nTEST_F(PeerConnectionDependencyFactoryTest, CreateRTCPeerConnectionHandler) {\n MockWebRTCPeerConnectionHandlerClient client_jsep;\n scoped_ptr pc_handler(\n dependency_factory_->CreateRTCPeerConnectionHandler(&client_jsep));\n EXPECT_TRUE(pc_handler.get() != NULL);\n}\n\n} // namespace content\n"},"repo_name":{"kind":"string","value":"CTSRD-SOAAP/chromium-42.0.2311.135"},"path":{"kind":"string","value":"content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":1157,"string":"1,157"}}},{"rowIdx":115086573,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (C) 2009 Texas Instruments.\n * Copyright (C) 2010 EF Johnson Technologies\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#define CS_DEFAULT\t0xFF\n\n#define SPIFMT_PHASE_MASK\tBIT(16)\n#define SPIFMT_POLARITY_MASK\tBIT(17)\n#define SPIFMT_DISTIMER_MASK\tBIT(18)\n#define SPIFMT_SHIFTDIR_MASK\tBIT(20)\n#define SPIFMT_WAITENA_MASK\tBIT(21)\n#define SPIFMT_PARITYENA_MASK\tBIT(22)\n#define SPIFMT_ODD_PARITY_MASK\tBIT(23)\n#define SPIFMT_WDELAY_MASK\t0x3f000000u\n#define SPIFMT_WDELAY_SHIFT\t24\n#define SPIFMT_PRESCALE_SHIFT\t8\n\n/* SPIPC0 */\n#define SPIPC0_DIFUN_MASK\tBIT(11)\t\t/* MISO */\n#define SPIPC0_DOFUN_MASK\tBIT(10)\t\t/* MOSI */\n#define SPIPC0_CLKFUN_MASK\tBIT(9)\t\t/* CLK */\n#define SPIPC0_SPIENA_MASK\tBIT(8)\t\t/* nREADY */\n\n#define SPIINT_MASKALL\t\t0x0101035F\n#define SPIINT_MASKINT\t\t0x0000015F\n#define SPI_INTLVL_1\t\t0x000001FF\n#define SPI_INTLVL_0\t\t0x00000000\n\n/* SPIDAT1 (upper 16 bit defines) */\n#define SPIDAT1_CSHOLD_MASK\tBIT(12)\n#define SPIDAT1_WDEL\t\tBIT(10)\n\n/* SPIGCR1 */\n#define SPIGCR1_CLKMOD_MASK\tBIT(1)\n#define SPIGCR1_MASTER_MASK BIT(0)\n#define SPIGCR1_POWERDOWN_MASK\tBIT(8)\n#define SPIGCR1_LOOPBACK_MASK\tBIT(16)\n#define SPIGCR1_SPIENA_MASK\tBIT(24)\n\n/* SPIBUF */\n#define SPIBUF_TXFULL_MASK\tBIT(29)\n#define SPIBUF_RXEMPTY_MASK\tBIT(31)\n\n/* SPIDELAY */\n#define SPIDELAY_C2TDELAY_SHIFT 24\n#define SPIDELAY_C2TDELAY_MASK (0xFF << SPIDELAY_C2TDELAY_SHIFT)\n#define SPIDELAY_T2CDELAY_SHIFT 16\n#define SPIDELAY_T2CDELAY_MASK (0xFF << SPIDELAY_T2CDELAY_SHIFT)\n#define SPIDELAY_T2EDELAY_SHIFT 8\n#define SPIDELAY_T2EDELAY_MASK (0xFF << SPIDELAY_T2EDELAY_SHIFT)\n#define SPIDELAY_C2EDELAY_SHIFT 0\n#define SPIDELAY_C2EDELAY_MASK 0xFF\n\n/* Error Masks */\n#define SPIFLG_DLEN_ERR_MASK\t\tBIT(0)\n#define SPIFLG_TIMEOUT_MASK\t\tBIT(1)\n#define SPIFLG_PARERR_MASK\t\tBIT(2)\n#define SPIFLG_DESYNC_MASK\t\tBIT(3)\n#define SPIFLG_BITERR_MASK\t\tBIT(4)\n#define SPIFLG_OVRRUN_MASK\t\tBIT(6)\n#define SPIFLG_BUF_INIT_ACTIVE_MASK\tBIT(24)\n#define SPIFLG_ERROR_MASK\t\t(SPIFLG_DLEN_ERR_MASK \\\n\t\t\t\t| SPIFLG_TIMEOUT_MASK | SPIFLG_PARERR_MASK \\\n\t\t\t\t| SPIFLG_DESYNC_MASK | SPIFLG_BITERR_MASK \\\n\t\t\t\t| SPIFLG_OVRRUN_MASK)\n\n#define SPIINT_DMA_REQ_EN\tBIT(16)\n\n/* SPI Controller registers */\n#define SPIGCR0\t\t0x00\n#define SPIGCR1\t\t0x04\n#define SPIINT\t\t0x08\n#define SPILVL\t\t0x0c\n#define SPIFLG\t\t0x10\n#define SPIPC0\t\t0x14\n#define SPIDAT1\t\t0x3c\n#define SPIBUF\t\t0x40\n#define SPIDELAY\t0x48\n#define SPIDEF\t\t0x4c\n#define SPIFMT0\t\t0x50\n\n/* SPI Controller driver's private data. */\nstruct davinci_spi {\n\tstruct spi_bitbang\tbitbang;\n\tstruct clk\t\t*clk;\n\n\tu8\t\t\tversion;\n\tresource_size_t\t\tpbase;\n\tvoid __iomem\t\t*base;\n\tu32\t\t\tirq;\n\tstruct completion\tdone;\n\n\tconst void\t\t*tx;\n\tvoid\t\t\t*rx;\n\tint\t\t\trcount;\n\tint\t\t\twcount;\n\n\tstruct dma_chan\t\t*dma_rx;\n\tstruct dma_chan\t\t*dma_tx;\n\n\tstruct davinci_spi_platform_data pdata;\n\n\tvoid\t\t\t(*get_rx)(u32 rx_data, struct davinci_spi *);\n\tu32\t\t\t(*get_tx)(struct davinci_spi *);\n\n\tu8\t\t\t*bytes_per_word;\n\n\tu8\t\t\tprescaler_limit;\n};\n\nstatic struct davinci_spi_config davinci_spi_default_cfg;\n\nstatic void davinci_spi_rx_buf_u8(u32 data, struct davinci_spi *dspi)\n{\n\tif (dspi->rx) {\n\t\tu8 *rx = dspi->rx;\n\t\t*rx++ = (u8)data;\n\t\tdspi->rx = rx;\n\t}\n}\n\nstatic void davinci_spi_rx_buf_u16(u32 data, struct davinci_spi *dspi)\n{\n\tif (dspi->rx) {\n\t\tu16 *rx = dspi->rx;\n\t\t*rx++ = (u16)data;\n\t\tdspi->rx = rx;\n\t}\n}\n\nstatic u32 davinci_spi_tx_buf_u8(struct davinci_spi *dspi)\n{\n\tu32 data = 0;\n\n\tif (dspi->tx) {\n\t\tconst u8 *tx = dspi->tx;\n\n\t\tdata = *tx++;\n\t\tdspi->tx = tx;\n\t}\n\treturn data;\n}\n\nstatic u32 davinci_spi_tx_buf_u16(struct davinci_spi *dspi)\n{\n\tu32 data = 0;\n\n\tif (dspi->tx) {\n\t\tconst u16 *tx = dspi->tx;\n\n\t\tdata = *tx++;\n\t\tdspi->tx = tx;\n\t}\n\treturn data;\n}\n\nstatic inline void set_io_bits(void __iomem *addr, u32 bits)\n{\n\tu32 v = ioread32(addr);\n\n\tv |= bits;\n\tiowrite32(v, addr);\n}\n\nstatic inline void clear_io_bits(void __iomem *addr, u32 bits)\n{\n\tu32 v = ioread32(addr);\n\n\tv &= ~bits;\n\tiowrite32(v, addr);\n}\n\n/*\n * Interface to control the chip select signal\n */\nstatic void davinci_spi_chipselect(struct spi_device *spi, int value)\n{\n\tstruct davinci_spi *dspi;\n\tstruct davinci_spi_platform_data *pdata;\n\tstruct davinci_spi_config *spicfg = spi->controller_data;\n\tu8 chip_sel = spi->chip_select;\n\tu16 spidat1 = CS_DEFAULT;\n\n\tdspi = spi_master_get_devdata(spi->master);\n\tpdata = &dspi->pdata;\n\n\t/* program delay transfers if tx_delay is non zero */\n\tif (spicfg->wdelay)\n\t\tspidat1 |= SPIDAT1_WDEL;\n\n\t/*\n\t * Board specific chip select logic decides the polarity and cs\n\t * line for the controller\n\t */\n\tif (spi->cs_gpio >= 0) {\n\t\tif (value == BITBANG_CS_ACTIVE)\n\t\t\tgpio_set_value(spi->cs_gpio, spi->mode & SPI_CS_HIGH);\n\t\telse\n\t\t\tgpio_set_value(spi->cs_gpio,\n\t\t\t\t!(spi->mode & SPI_CS_HIGH));\n\t} else {\n\t\tif (value == BITBANG_CS_ACTIVE) {\n\t\t\tspidat1 |= SPIDAT1_CSHOLD_MASK;\n\t\t\tspidat1 &= ~(0x1 << chip_sel);\n\t\t}\n\t}\n\n\tiowrite16(spidat1, dspi->base + SPIDAT1 + 2);\n}\n\n/**\n * davinci_spi_get_prescale - Calculates the correct prescale value\n * @maxspeed_hz: the maximum rate the SPI clock can run at\n *\n * This function calculates the prescale value that generates a clock rate\n * less than or equal to the specified maximum.\n *\n * Returns: calculated prescale value for easy programming into SPI registers\n * or negative error number if valid prescalar cannot be updated.\n */\nstatic inline int davinci_spi_get_prescale(struct davinci_spi *dspi,\n\t\t\t\t\t\t\tu32 max_speed_hz)\n{\n\tint ret;\n\n\t/* Subtract 1 to match what will be programmed into SPI register. */\n\tret = DIV_ROUND_UP(clk_get_rate(dspi->clk), max_speed_hz) - 1;\n\n\tif (ret < dspi->prescaler_limit || ret > 255)\n\t\treturn -EINVAL;\n\n\treturn ret;\n}\n\n/**\n * davinci_spi_setup_transfer - This functions will determine transfer method\n * @spi: spi device on which data transfer to be done\n * @t: spi transfer in which transfer info is filled\n *\n * This function determines data transfer method (8/16/32 bit transfer).\n * It will also set the SPI Clock Control register according to\n * SPI slave device freq.\n */\nstatic int davinci_spi_setup_transfer(struct spi_device *spi,\n\t\tstruct spi_transfer *t)\n{\n\n\tstruct davinci_spi *dspi;\n\tstruct davinci_spi_config *spicfg;\n\tu8 bits_per_word = 0;\n\tu32 hz = 0, spifmt = 0;\n\tint prescale;\n\n\tdspi = spi_master_get_devdata(spi->master);\n\tspicfg = spi->controller_data;\n\tif (!spicfg)\n\t\tspicfg = &davinci_spi_default_cfg;\n\n\tif (t) {\n\t\tbits_per_word = t->bits_per_word;\n\t\thz = t->speed_hz;\n\t}\n\n\t/* if bits_per_word is not set then set it default */\n\tif (!bits_per_word)\n\t\tbits_per_word = spi->bits_per_word;\n\n\t/*\n\t * Assign function pointer to appropriate transfer method\n\t * 8bit, 16bit or 32bit transfer\n\t */\n\tif (bits_per_word <= 8) {\n\t\tdspi->get_rx = davinci_spi_rx_buf_u8;\n\t\tdspi->get_tx = davinci_spi_tx_buf_u8;\n\t\tdspi->bytes_per_word[spi->chip_select] = 1;\n\t} else {\n\t\tdspi->get_rx = davinci_spi_rx_buf_u16;\n\t\tdspi->get_tx = davinci_spi_tx_buf_u16;\n\t\tdspi->bytes_per_word[spi->chip_select] = 2;\n\t}\n\n\tif (!hz)\n\t\thz = spi->max_speed_hz;\n\n\t/* Set up SPIFMTn register, unique to this chipselect. */\n\n\tprescale = davinci_spi_get_prescale(dspi, hz);\n\tif (prescale < 0)\n\t\treturn prescale;\n\n\tspifmt = (prescale << SPIFMT_PRESCALE_SHIFT) | (bits_per_word & 0x1f);\n\n\tif (spi->mode & SPI_LSB_FIRST)\n\t\tspifmt |= SPIFMT_SHIFTDIR_MASK;\n\n\tif (spi->mode & SPI_CPOL)\n\t\tspifmt |= SPIFMT_POLARITY_MASK;\n\n\tif (!(spi->mode & SPI_CPHA))\n\t\tspifmt |= SPIFMT_PHASE_MASK;\n\n\t/*\n\t* Assume wdelay is used only on SPI peripherals that has this field\n\t* in SPIFMTn register and when it's configured from board file or DT.\n\t*/\n\tif (spicfg->wdelay)\n\t\tspifmt |= ((spicfg->wdelay << SPIFMT_WDELAY_SHIFT)\n\t\t\t\t& SPIFMT_WDELAY_MASK);\n\n\t/*\n\t * Version 1 hardware supports two basic SPI modes:\n\t * - Standard SPI mode uses 4 pins, with chipselect\n\t * - 3 pin SPI is a 4 pin variant without CS (SPI_NO_CS)\n\t *\t(distinct from SPI_3WIRE, with just one data wire;\n\t *\tor similar variants without MOSI or without MISO)\n\t *\n\t * Version 2 hardware supports an optional handshaking signal,\n\t * so it can support two more modes:\n\t * - 5 pin SPI variant is standard SPI plus SPI_READY\n\t * - 4 pin with enable is (SPI_READY | SPI_NO_CS)\n\t */\n\n\tif (dspi->version == SPI_VERSION_2) {\n\n\t\tu32 delay = 0;\n\n\t\tif (spicfg->odd_parity)\n\t\t\tspifmt |= SPIFMT_ODD_PARITY_MASK;\n\n\t\tif (spicfg->parity_enable)\n\t\t\tspifmt |= SPIFMT_PARITYENA_MASK;\n\n\t\tif (spicfg->timer_disable) {\n\t\t\tspifmt |= SPIFMT_DISTIMER_MASK;\n\t\t} else {\n\t\t\tdelay |= (spicfg->c2tdelay << SPIDELAY_C2TDELAY_SHIFT)\n\t\t\t\t\t\t& SPIDELAY_C2TDELAY_MASK;\n\t\t\tdelay |= (spicfg->t2cdelay << SPIDELAY_T2CDELAY_SHIFT)\n\t\t\t\t\t\t& SPIDELAY_T2CDELAY_MASK;\n\t\t}\n\n\t\tif (spi->mode & SPI_READY) {\n\t\t\tspifmt |= SPIFMT_WAITENA_MASK;\n\t\t\tdelay |= (spicfg->t2edelay << SPIDELAY_T2EDELAY_SHIFT)\n\t\t\t\t\t\t& SPIDELAY_T2EDELAY_MASK;\n\t\t\tdelay |= (spicfg->c2edelay << SPIDELAY_C2EDELAY_SHIFT)\n\t\t\t\t\t\t& SPIDELAY_C2EDELAY_MASK;\n\t\t}\n\n\t\tiowrite32(delay, dspi->base + SPIDELAY);\n\t}\n\n\tiowrite32(spifmt, dspi->base + SPIFMT0);\n\n\treturn 0;\n}\n\nstatic int davinci_spi_of_setup(struct spi_device *spi)\n{\n\tstruct davinci_spi_config *spicfg = spi->controller_data;\n\tstruct device_node *np = spi->dev.of_node;\n\tu32 prop;\n\n\tif (spicfg == NULL && np) {\n\t\tspicfg = kzalloc(sizeof(*spicfg), GFP_KERNEL);\n\t\tif (!spicfg)\n\t\t\treturn -ENOMEM;\n\t\t*spicfg = davinci_spi_default_cfg;\n\t\t/* override with dt configured values */\n\t\tif (!of_property_read_u32(np, \"ti,spi-wdelay\", &prop))\n\t\t\tspicfg->wdelay = (u8)prop;\n\t\tspi->controller_data = spicfg;\n\t}\n\n\treturn 0;\n}\n\n/**\n * davinci_spi_setup - This functions will set default transfer method\n * @spi: spi device on which data transfer to be done\n *\n * This functions sets the default transfer method.\n */\nstatic int davinci_spi_setup(struct spi_device *spi)\n{\n\tint retval = 0;\n\tstruct davinci_spi *dspi;\n\tstruct davinci_spi_platform_data *pdata;\n\tstruct spi_master *master = spi->master;\n\tstruct device_node *np = spi->dev.of_node;\n\tbool internal_cs = true;\n\n\tdspi = spi_master_get_devdata(spi->master);\n\tpdata = &dspi->pdata;\n\n\tif (!(spi->mode & SPI_NO_CS)) {\n\t\tif (np && (master->cs_gpios != NULL) && (spi->cs_gpio >= 0)) {\n\t\t\tretval = gpio_direction_output(\n\t\t\t\t spi->cs_gpio, !(spi->mode & SPI_CS_HIGH));\n\t\t\tinternal_cs = false;\n\t\t} else if (pdata->chip_sel &&\n\t\t\t spi->chip_select < pdata->num_chipselect &&\n\t\t\t pdata->chip_sel[spi->chip_select] != SPI_INTERN_CS) {\n\t\t\tspi->cs_gpio = pdata->chip_sel[spi->chip_select];\n\t\t\tretval = gpio_direction_output(\n\t\t\t\t spi->cs_gpio, !(spi->mode & SPI_CS_HIGH));\n\t\t\tinternal_cs = false;\n\t\t}\n\n\t\tif (retval) {\n\t\t\tdev_err(&spi->dev, \"GPIO %d setup failed (%d)\\n\",\n\t\t\t\tspi->cs_gpio, retval);\n\t\t\treturn retval;\n\t\t}\n\n\t\tif (internal_cs)\n\t\t\tset_io_bits(dspi->base + SPIPC0, 1 << spi->chip_select);\n\t}\n\n\tif (spi->mode & SPI_READY)\n\t\tset_io_bits(dspi->base + SPIPC0, SPIPC0_SPIENA_MASK);\n\n\tif (spi->mode & SPI_LOOP)\n\t\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK);\n\telse\n\t\tclear_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK);\n\n\treturn davinci_spi_of_setup(spi);\n}\n\nstatic void davinci_spi_cleanup(struct spi_device *spi)\n{\n\tstruct davinci_spi_config *spicfg = spi->controller_data;\n\n\tspi->controller_data = NULL;\n\tif (spi->dev.of_node)\n\t\tkfree(spicfg);\n}\n\nstatic int davinci_spi_check_error(struct davinci_spi *dspi, int int_status)\n{\n\tstruct device *sdev = dspi->bitbang.master->dev.parent;\n\n\tif (int_status & SPIFLG_TIMEOUT_MASK) {\n\t\tdev_err(sdev, \"SPI Time-out Error\\n\");\n\t\treturn -ETIMEDOUT;\n\t}\n\tif (int_status & SPIFLG_DESYNC_MASK) {\n\t\tdev_err(sdev, \"SPI Desynchronization Error\\n\");\n\t\treturn -EIO;\n\t}\n\tif (int_status & SPIFLG_BITERR_MASK) {\n\t\tdev_err(sdev, \"SPI Bit error\\n\");\n\t\treturn -EIO;\n\t}\n\n\tif (dspi->version == SPI_VERSION_2) {\n\t\tif (int_status & SPIFLG_DLEN_ERR_MASK) {\n\t\t\tdev_err(sdev, \"SPI Data Length Error\\n\");\n\t\t\treturn -EIO;\n\t\t}\n\t\tif (int_status & SPIFLG_PARERR_MASK) {\n\t\t\tdev_err(sdev, \"SPI Parity Error\\n\");\n\t\t\treturn -EIO;\n\t\t}\n\t\tif (int_status & SPIFLG_OVRRUN_MASK) {\n\t\t\tdev_err(sdev, \"SPI Data Overrun error\\n\");\n\t\t\treturn -EIO;\n\t\t}\n\t\tif (int_status & SPIFLG_BUF_INIT_ACTIVE_MASK) {\n\t\t\tdev_err(sdev, \"SPI Buffer Init Active\\n\");\n\t\t\treturn -EBUSY;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/**\n * davinci_spi_process_events - check for and handle any SPI controller events\n * @dspi: the controller data\n *\n * This function will check the SPIFLG register and handle any events that are\n * detected there\n */\nstatic int davinci_spi_process_events(struct davinci_spi *dspi)\n{\n\tu32 buf, status, errors = 0, spidat1;\n\n\tbuf = ioread32(dspi->base + SPIBUF);\n\n\tif (dspi->rcount > 0 && !(buf & SPIBUF_RXEMPTY_MASK)) {\n\t\tdspi->get_rx(buf & 0xFFFF, dspi);\n\t\tdspi->rcount--;\n\t}\n\n\tstatus = ioread32(dspi->base + SPIFLG);\n\n\tif (unlikely(status & SPIFLG_ERROR_MASK)) {\n\t\terrors = status & SPIFLG_ERROR_MASK;\n\t\tgoto out;\n\t}\n\n\tif (dspi->wcount > 0 && !(buf & SPIBUF_TXFULL_MASK)) {\n\t\tspidat1 = ioread32(dspi->base + SPIDAT1);\n\t\tdspi->wcount--;\n\t\tspidat1 &= ~0xFFFF;\n\t\tspidat1 |= 0xFFFF & dspi->get_tx(dspi);\n\t\tiowrite32(spidat1, dspi->base + SPIDAT1);\n\t}\n\nout:\n\treturn errors;\n}\n\nstatic void davinci_spi_dma_rx_callback(void *data)\n{\n\tstruct davinci_spi *dspi = (struct davinci_spi *)data;\n\n\tdspi->rcount = 0;\n\n\tif (!dspi->wcount && !dspi->rcount)\n\t\tcomplete(&dspi->done);\n}\n\nstatic void davinci_spi_dma_tx_callback(void *data)\n{\n\tstruct davinci_spi *dspi = (struct davinci_spi *)data;\n\n\tdspi->wcount = 0;\n\n\tif (!dspi->wcount && !dspi->rcount)\n\t\tcomplete(&dspi->done);\n}\n\n/**\n * davinci_spi_bufs - functions which will handle transfer data\n * @spi: spi device on which data transfer to be done\n * @t: spi transfer in which transfer info is filled\n *\n * This function will put data to be transferred into data register\n * of SPI controller and then wait until the completion will be marked\n * by the IRQ Handler.\n */\nstatic int davinci_spi_bufs(struct spi_device *spi, struct spi_transfer *t)\n{\n\tstruct davinci_spi *dspi;\n\tint data_type, ret = -ENOMEM;\n\tu32 tx_data, spidat1;\n\tu32 errors = 0;\n\tstruct davinci_spi_config *spicfg;\n\tstruct davinci_spi_platform_data *pdata;\n\tunsigned uninitialized_var(rx_buf_count);\n\tvoid *dummy_buf = NULL;\n\tstruct scatterlist sg_rx, sg_tx;\n\n\tdspi = spi_master_get_devdata(spi->master);\n\tpdata = &dspi->pdata;\n\tspicfg = (struct davinci_spi_config *)spi->controller_data;\n\tif (!spicfg)\n\t\tspicfg = &davinci_spi_default_cfg;\n\n\t/* convert len to words based on bits_per_word */\n\tdata_type = dspi->bytes_per_word[spi->chip_select];\n\n\tdspi->tx = t->tx_buf;\n\tdspi->rx = t->rx_buf;\n\tdspi->wcount = t->len / data_type;\n\tdspi->rcount = dspi->wcount;\n\n\tspidat1 = ioread32(dspi->base + SPIDAT1);\n\n\tclear_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);\n\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK);\n\n\treinit_completion(&dspi->done);\n\n\tif (spicfg->io_type == SPI_IO_TYPE_INTR)\n\t\tset_io_bits(dspi->base + SPIINT, SPIINT_MASKINT);\n\n\tif (spicfg->io_type != SPI_IO_TYPE_DMA) {\n\t\t/* start the transfer */\n\t\tdspi->wcount--;\n\t\ttx_data = dspi->get_tx(dspi);\n\t\tspidat1 &= 0xFFFF0000;\n\t\tspidat1 |= tx_data & 0xFFFF;\n\t\tiowrite32(spidat1, dspi->base + SPIDAT1);\n\t} else {\n\t\tstruct dma_slave_config dma_rx_conf = {\n\t\t\t.direction = DMA_DEV_TO_MEM,\n\t\t\t.src_addr = (unsigned long)dspi->pbase + SPIBUF,\n\t\t\t.src_addr_width = data_type,\n\t\t\t.src_maxburst = 1,\n\t\t};\n\t\tstruct dma_slave_config dma_tx_conf = {\n\t\t\t.direction = DMA_MEM_TO_DEV,\n\t\t\t.dst_addr = (unsigned long)dspi->pbase + SPIDAT1,\n\t\t\t.dst_addr_width = data_type,\n\t\t\t.dst_maxburst = 1,\n\t\t};\n\t\tstruct dma_async_tx_descriptor *rxdesc;\n\t\tstruct dma_async_tx_descriptor *txdesc;\n\t\tvoid *buf;\n\n\t\tdummy_buf = kzalloc(t->len, GFP_KERNEL);\n\t\tif (!dummy_buf)\n\t\t\tgoto err_alloc_dummy_buf;\n\n\t\tdmaengine_slave_config(dspi->dma_rx, &dma_rx_conf);\n\t\tdmaengine_slave_config(dspi->dma_tx, &dma_tx_conf);\n\n\t\tsg_init_table(&sg_rx, 1);\n\t\tif (!t->rx_buf)\n\t\t\tbuf = dummy_buf;\n\t\telse\n\t\t\tbuf = t->rx_buf;\n\t\tt->rx_dma = dma_map_single(&spi->dev, buf,\n\t\t\t\tt->len, DMA_FROM_DEVICE);\n\t\tif (dma_mapping_error(&spi->dev, !t->rx_dma)) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto err_rx_map;\n\t\t}\n\t\tsg_dma_address(&sg_rx) = t->rx_dma;\n\t\tsg_dma_len(&sg_rx) = t->len;\n\n\t\tsg_init_table(&sg_tx, 1);\n\t\tif (!t->tx_buf)\n\t\t\tbuf = dummy_buf;\n\t\telse\n\t\t\tbuf = (void *)t->tx_buf;\n\t\tt->tx_dma = dma_map_single(&spi->dev, buf,\n\t\t\t\tt->len, DMA_TO_DEVICE);\n\t\tif (dma_mapping_error(&spi->dev, t->tx_dma)) {\n\t\t\tret = -EFAULT;\n\t\t\tgoto err_tx_map;\n\t\t}\n\t\tsg_dma_address(&sg_tx) = t->tx_dma;\n\t\tsg_dma_len(&sg_tx) = t->len;\n\n\t\trxdesc = dmaengine_prep_slave_sg(dspi->dma_rx,\n\t\t\t\t&sg_rx, 1, DMA_DEV_TO_MEM,\n\t\t\t\tDMA_PREP_INTERRUPT | DMA_CTRL_ACK);\n\t\tif (!rxdesc)\n\t\t\tgoto err_desc;\n\n\t\ttxdesc = dmaengine_prep_slave_sg(dspi->dma_tx,\n\t\t\t\t&sg_tx, 1, DMA_MEM_TO_DEV,\n\t\t\t\tDMA_PREP_INTERRUPT | DMA_CTRL_ACK);\n\t\tif (!txdesc)\n\t\t\tgoto err_desc;\n\n\t\trxdesc->callback = davinci_spi_dma_rx_callback;\n\t\trxdesc->callback_param = (void *)dspi;\n\t\ttxdesc->callback = davinci_spi_dma_tx_callback;\n\t\ttxdesc->callback_param = (void *)dspi;\n\n\t\tif (pdata->cshold_bug)\n\t\t\tiowrite16(spidat1 >> 16, dspi->base + SPIDAT1 + 2);\n\n\t\tdmaengine_submit(rxdesc);\n\t\tdmaengine_submit(txdesc);\n\n\t\tdma_async_issue_pending(dspi->dma_rx);\n\t\tdma_async_issue_pending(dspi->dma_tx);\n\n\t\tset_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN);\n\t}\n\n\t/* Wait for the transfer to complete */\n\tif (spicfg->io_type != SPI_IO_TYPE_POLL) {\n\t\tif (wait_for_completion_timeout(&dspi->done, HZ) == 0)\n\t\t\terrors = SPIFLG_TIMEOUT_MASK;\n\t} else {\n\t\twhile (dspi->rcount > 0 || dspi->wcount > 0) {\n\t\t\terrors = davinci_spi_process_events(dspi);\n\t\t\tif (errors)\n\t\t\t\tbreak;\n\t\t\tcpu_relax();\n\t\t}\n\t}\n\n\tclear_io_bits(dspi->base + SPIINT, SPIINT_MASKALL);\n\tif (spicfg->io_type == SPI_IO_TYPE_DMA) {\n\t\tclear_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN);\n\n\t\tdma_unmap_single(&spi->dev, t->rx_dma,\n\t\t\t\tt->len, DMA_FROM_DEVICE);\n\t\tdma_unmap_single(&spi->dev, t->tx_dma,\n\t\t\t\tt->len, DMA_TO_DEVICE);\n\t\tkfree(dummy_buf);\n\t}\n\n\tclear_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK);\n\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);\n\n\t/*\n\t * Check for bit error, desync error,parity error,timeout error and\n\t * receive overflow errors\n\t */\n\tif (errors) {\n\t\tret = davinci_spi_check_error(dspi, errors);\n\t\tWARN(!ret, \"%s: error reported but no error found!\\n\",\n\t\t\t\t\t\t\tdev_name(&spi->dev));\n\t\treturn ret;\n\t}\n\n\tif (dspi->rcount != 0 || dspi->wcount != 0) {\n\t\tdev_err(&spi->dev, \"SPI data transfer error\\n\");\n\t\treturn -EIO;\n\t}\n\n\treturn t->len;\n\nerr_desc:\n\tdma_unmap_single(&spi->dev, t->tx_dma, t->len, DMA_TO_DEVICE);\nerr_tx_map:\n\tdma_unmap_single(&spi->dev, t->rx_dma, t->len, DMA_FROM_DEVICE);\nerr_rx_map:\n\tkfree(dummy_buf);\nerr_alloc_dummy_buf:\n\treturn ret;\n}\n\n/**\n * dummy_thread_fn - dummy thread function\n * @irq: IRQ number for this SPI Master\n * @context_data: structure for SPI Master controller davinci_spi\n *\n * This is to satisfy the request_threaded_irq() API so that the irq\n * handler is called in interrupt context.\n */\nstatic irqreturn_t dummy_thread_fn(s32 irq, void *data)\n{\n\treturn IRQ_HANDLED;\n}\n\n/**\n * davinci_spi_irq - Interrupt handler for SPI Master Controller\n * @irq: IRQ number for this SPI Master\n * @context_data: structure for SPI Master controller davinci_spi\n *\n * ISR will determine that interrupt arrives either for READ or WRITE command.\n * According to command it will do the appropriate action. It will check\n * transfer length and if it is not zero then dispatch transfer command again.\n * If transfer length is zero then it will indicate the COMPLETION so that\n * davinci_spi_bufs function can go ahead.\n */\nstatic irqreturn_t davinci_spi_irq(s32 irq, void *data)\n{\n\tstruct davinci_spi *dspi = data;\n\tint status;\n\n\tstatus = davinci_spi_process_events(dspi);\n\tif (unlikely(status != 0))\n\t\tclear_io_bits(dspi->base + SPIINT, SPIINT_MASKINT);\n\n\tif ((!dspi->rcount && !dspi->wcount) || status)\n\t\tcomplete(&dspi->done);\n\n\treturn IRQ_HANDLED;\n}\n\nstatic int davinci_spi_request_dma(struct davinci_spi *dspi)\n{\n\tstruct device *sdev = dspi->bitbang.master->dev.parent;\n\n\tdspi->dma_rx = dma_request_chan(sdev, \"rx\");\n\tif (IS_ERR(dspi->dma_rx))\n\t\treturn PTR_ERR(dspi->dma_rx);\n\n\tdspi->dma_tx = dma_request_chan(sdev, \"tx\");\n\tif (IS_ERR(dspi->dma_tx)) {\n\t\tdma_release_channel(dspi->dma_rx);\n\t\treturn PTR_ERR(dspi->dma_tx);\n\t}\n\n\treturn 0;\n}\n\n#if defined(CONFIG_OF)\n\n/* OF SPI data structure */\nstruct davinci_spi_of_data {\n\tu8\tversion;\n\tu8\tprescaler_limit;\n};\n\nstatic const struct davinci_spi_of_data dm6441_spi_data = {\n\t.version = SPI_VERSION_1,\n\t.prescaler_limit = 2,\n};\n\nstatic const struct davinci_spi_of_data da830_spi_data = {\n\t.version = SPI_VERSION_2,\n\t.prescaler_limit = 2,\n};\n\nstatic const struct davinci_spi_of_data keystone_spi_data = {\n\t.version = SPI_VERSION_1,\n\t.prescaler_limit = 0,\n};\n\nstatic const struct of_device_id davinci_spi_of_match[] = {\n\t{\n\t\t.compatible = \"ti,dm6441-spi\",\n\t\t.data = &dm6441_spi_data,\n\t},\n\t{\n\t\t.compatible = \"ti,da830-spi\",\n\t\t.data = &da830_spi_data,\n\t},\n\t{\n\t\t.compatible = \"ti,keystone-spi\",\n\t\t.data = &keystone_spi_data,\n\t},\n\t{ },\n};\nMODULE_DEVICE_TABLE(of, davinci_spi_of_match);\n\n/**\n * spi_davinci_get_pdata - Get platform data from DTS binding\n * @pdev: ptr to platform data\n * @dspi: ptr to driver data\n *\n * Parses and populates pdata in dspi from device tree bindings.\n *\n * NOTE: Not all platform data params are supported currently.\n */\nstatic int spi_davinci_get_pdata(struct platform_device *pdev,\n\t\t\tstruct davinci_spi *dspi)\n{\n\tstruct device_node *node = pdev->dev.of_node;\n\tstruct davinci_spi_of_data *spi_data;\n\tstruct davinci_spi_platform_data *pdata;\n\tunsigned int num_cs, intr_line = 0;\n\tconst struct of_device_id *match;\n\n\tpdata = &dspi->pdata;\n\n\tmatch = of_match_device(davinci_spi_of_match, &pdev->dev);\n\tif (!match)\n\t\treturn -ENODEV;\n\n\tspi_data = (struct davinci_spi_of_data *)match->data;\n\n\tpdata->version = spi_data->version;\n\tpdata->prescaler_limit = spi_data->prescaler_limit;\n\t/*\n\t * default num_cs is 1 and all chipsel are internal to the chip\n\t * indicated by chip_sel being NULL or cs_gpios being NULL or\n\t * set to -ENOENT. num-cs includes internal as well as gpios.\n\t * indicated by chip_sel being NULL. GPIO based CS is not\n\t * supported yet in DT bindings.\n\t */\n\tnum_cs = 1;\n\tof_property_read_u32(node, \"num-cs\", &num_cs);\n\tpdata->num_chipselect = num_cs;\n\tof_property_read_u32(node, \"ti,davinci-spi-intr-line\", &intr_line);\n\tpdata->intr_line = intr_line;\n\treturn 0;\n}\n#else\nstatic struct davinci_spi_platform_data\n\t*spi_davinci_get_pdata(struct platform_device *pdev,\n\t\tstruct davinci_spi *dspi)\n{\n\treturn -ENODEV;\n}\n#endif\n\n/**\n * davinci_spi_probe - probe function for SPI Master Controller\n * @pdev: platform_device structure which contains plateform specific data\n *\n * According to Linux Device Model this function will be invoked by Linux\n * with platform_device struct which contains the device specific info.\n * This function will map the SPI controller's memory, register IRQ,\n * Reset SPI controller and setting its registers to default value.\n * It will invoke spi_bitbang_start to create work queue so that client driver\n * can register transfer method to work queue.\n */\nstatic int davinci_spi_probe(struct platform_device *pdev)\n{\n\tstruct spi_master *master;\n\tstruct davinci_spi *dspi;\n\tstruct davinci_spi_platform_data *pdata;\n\tstruct resource *r;\n\tint ret = 0;\n\tu32 spipc0;\n\n\tmaster = spi_alloc_master(&pdev->dev, sizeof(struct davinci_spi));\n\tif (master == NULL) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}\n\n\tplatform_set_drvdata(pdev, master);\n\n\tdspi = spi_master_get_devdata(master);\n\n\tif (dev_get_platdata(&pdev->dev)) {\n\t\tpdata = dev_get_platdata(&pdev->dev);\n\t\tdspi->pdata = *pdata;\n\t} else {\n\t\t/* update dspi pdata with that from the DT */\n\t\tret = spi_davinci_get_pdata(pdev, dspi);\n\t\tif (ret < 0)\n\t\t\tgoto free_master;\n\t}\n\n\t/* pdata in dspi is now updated and point pdata to that */\n\tpdata = &dspi->pdata;\n\n\tdspi->bytes_per_word = devm_kzalloc(&pdev->dev,\n\t\t\t\t\t sizeof(*dspi->bytes_per_word) *\n\t\t\t\t\t pdata->num_chipselect, GFP_KERNEL);\n\tif (dspi->bytes_per_word == NULL) {\n\t\tret = -ENOMEM;\n\t\tgoto free_master;\n\t}\n\n\tr = platform_get_resource(pdev, IORESOURCE_MEM, 0);\n\tif (r == NULL) {\n\t\tret = -ENOENT;\n\t\tgoto free_master;\n\t}\n\n\tdspi->pbase = r->start;\n\n\tdspi->base = devm_ioremap_resource(&pdev->dev, r);\n\tif (IS_ERR(dspi->base)) {\n\t\tret = PTR_ERR(dspi->base);\n\t\tgoto free_master;\n\t}\n\n\tret = platform_get_irq(pdev, 0);\n\tif (ret == 0)\n\t\tret = -EINVAL;\n\tif (ret < 0)\n\t\tgoto free_master;\n\tdspi->irq = ret;\n\n\tret = devm_request_threaded_irq(&pdev->dev, dspi->irq, davinci_spi_irq,\n\t\t\t\tdummy_thread_fn, 0, dev_name(&pdev->dev), dspi);\n\tif (ret)\n\t\tgoto free_master;\n\n\tdspi->bitbang.master = master;\n\n\tdspi->clk = devm_clk_get(&pdev->dev, NULL);\n\tif (IS_ERR(dspi->clk)) {\n\t\tret = -ENODEV;\n\t\tgoto free_master;\n\t}\n\tclk_prepare_enable(dspi->clk);\n\n\tmaster->dev.of_node = pdev->dev.of_node;\n\tmaster->bus_num = pdev->id;\n\tmaster->num_chipselect = pdata->num_chipselect;\n\tmaster->bits_per_word_mask = SPI_BPW_RANGE_MASK(2, 16);\n\tmaster->setup = davinci_spi_setup;\n\tmaster->cleanup = davinci_spi_cleanup;\n\n\tdspi->bitbang.chipselect = davinci_spi_chipselect;\n\tdspi->bitbang.setup_transfer = davinci_spi_setup_transfer;\n\tdspi->prescaler_limit = pdata->prescaler_limit;\n\tdspi->version = pdata->version;\n\n\tdspi->bitbang.flags = SPI_NO_CS | SPI_LSB_FIRST | SPI_LOOP;\n\tif (dspi->version == SPI_VERSION_2)\n\t\tdspi->bitbang.flags |= SPI_READY;\n\n\tif (pdev->dev.of_node) {\n\t\tint i;\n\n\t\tfor (i = 0; i < pdata->num_chipselect; i++) {\n\t\t\tint cs_gpio = of_get_named_gpio(pdev->dev.of_node,\n\t\t\t\t\t\t\t\"cs-gpios\", i);\n\n\t\t\tif (cs_gpio == -EPROBE_DEFER) {\n\t\t\t\tret = cs_gpio;\n\t\t\t\tgoto free_clk;\n\t\t\t}\n\n\t\t\tif (gpio_is_valid(cs_gpio)) {\n\t\t\t\tret = devm_gpio_request(&pdev->dev, cs_gpio,\n\t\t\t\t\t\t\tdev_name(&pdev->dev));\n\t\t\t\tif (ret)\n\t\t\t\t\tgoto free_clk;\n\t\t\t}\n\t\t}\n\t}\n\n\tdspi->bitbang.txrx_bufs = davinci_spi_bufs;\n\n\tret = davinci_spi_request_dma(dspi);\n\tif (ret == -EPROBE_DEFER) {\n\t\tgoto free_clk;\n\t} else if (ret) {\n\t\tdev_info(&pdev->dev, \"DMA is not supported (%d)\\n\", ret);\n\t\tdspi->dma_rx = NULL;\n\t\tdspi->dma_tx = NULL;\n\t}\n\n\tdspi->get_rx = davinci_spi_rx_buf_u8;\n\tdspi->get_tx = davinci_spi_tx_buf_u8;\n\n\tinit_completion(&dspi->done);\n\n\t/* Reset In/OUT SPI module */\n\tiowrite32(0, dspi->base + SPIGCR0);\n\tudelay(100);\n\tiowrite32(1, dspi->base + SPIGCR0);\n\n\t/* Set up SPIPC0. CS and ENA init is done in davinci_spi_setup */\n\tspipc0 = SPIPC0_DIFUN_MASK | SPIPC0_DOFUN_MASK | SPIPC0_CLKFUN_MASK;\n\tiowrite32(spipc0, dspi->base + SPIPC0);\n\n\tif (pdata->intr_line)\n\t\tiowrite32(SPI_INTLVL_1, dspi->base + SPILVL);\n\telse\n\t\tiowrite32(SPI_INTLVL_0, dspi->base + SPILVL);\n\n\tiowrite32(CS_DEFAULT, dspi->base + SPIDEF);\n\n\t/* master mode default */\n\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_CLKMOD_MASK);\n\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_MASTER_MASK);\n\tset_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);\n\n\tret = spi_bitbang_start(&dspi->bitbang);\n\tif (ret)\n\t\tgoto free_dma;\n\n\tdev_info(&pdev->dev, \"Controller at 0x%p\\n\", dspi->base);\n\n\treturn ret;\n\nfree_dma:\n\tif (dspi->dma_rx) {\n\t\tdma_release_channel(dspi->dma_rx);\n\t\tdma_release_channel(dspi->dma_tx);\n\t}\nfree_clk:\n\tclk_disable_unprepare(dspi->clk);\nfree_master:\n\tspi_master_put(master);\nerr:\n\treturn ret;\n}\n\n/**\n * davinci_spi_remove - remove function for SPI Master Controller\n * @pdev: platform_device structure which contains plateform specific data\n *\n * This function will do the reverse action of davinci_spi_probe function\n * It will free the IRQ and SPI controller's memory region.\n * It will also call spi_bitbang_stop to destroy the work queue which was\n * created by spi_bitbang_start.\n */\nstatic int davinci_spi_remove(struct platform_device *pdev)\n{\n\tstruct davinci_spi *dspi;\n\tstruct spi_master *master;\n\n\tmaster = platform_get_drvdata(pdev);\n\tdspi = spi_master_get_devdata(master);\n\n\tspi_bitbang_stop(&dspi->bitbang);\n\n\tclk_disable_unprepare(dspi->clk);\n\tspi_master_put(master);\n\n\tif (dspi->dma_rx) {\n\t\tdma_release_channel(dspi->dma_rx);\n\t\tdma_release_channel(dspi->dma_tx);\n\t}\n\n\treturn 0;\n}\n\nstatic struct platform_driver davinci_spi_driver = {\n\t.driver = {\n\t\t.name = \"spi_davinci\",\n\t\t.of_match_table = of_match_ptr(davinci_spi_of_match),\n\t},\n\t.probe = davinci_spi_probe,\n\t.remove = davinci_spi_remove,\n};\nmodule_platform_driver(davinci_spi_driver);\n\nMODULE_DESCRIPTION(\"TI DaVinci SPI Master Controller Driver\");\nMODULE_LICENSE(\"GPL\");\n"},"repo_name":{"kind":"string","value":"jallen93/linux-vnic-dbg"},"path":{"kind":"string","value":"drivers/spi/spi-davinci.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":28957,"string":"28,957"}}},{"rowIdx":115086574,"cells":{"code":{"kind":"string","value":"// Copyright 2013 The Chromium Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#ifndef CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_\n#define CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_\n\n#include \"chrome/browser/ui/app_list/app_list_controller_delegate_views.h\"\n\n// Windows specific configuration and behaviour for the AppList.\nclass AppListControllerDelegateWin : public AppListControllerDelegateViews {\n public:\n explicit AppListControllerDelegateWin(AppListServiceViews* service);\n virtual ~AppListControllerDelegateWin();\n\n // AppListControllerDelegate overrides:\n virtual bool ForceNativeDesktop() const OVERRIDE;\n virtual gfx::ImageSkia GetWindowIcon() OVERRIDE;\n\n private:\n // AppListcontrollerDelegateImpl:\n virtual void FillLaunchParams(AppLaunchParams* params) OVERRIDE;\n\n DISALLOW_COPY_AND_ASSIGN(AppListControllerDelegateWin);\n};\n\n#endif // CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_\n"},"repo_name":{"kind":"string","value":"s20121035/rk3288_android5.1_repo"},"path":{"kind":"string","value":"external/chromium_org/chrome/browser/ui/views/app_list/win/app_list_controller_delegate_win.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":1077,"string":"1,077"}}},{"rowIdx":115086575,"cells":{"code":{"kind":"string","value":"// Support for booting from cdroms (the \"El Torito\" spec).\n//\n// Copyright (C) 2008,2009 Kevin O'Connor \n// Copyright (C) 2002 MandrakeSoft S.A.\n//\n// This file may be distributed under the terms of the GNU LGPLv3 license.\n\n#include \"disk.h\" // cdrom_13\n#include \"util.h\" // memset\n#include \"bregs.h\" // struct bregs\n#include \"biosvar.h\" // GET_EBDA\n#include \"ata.h\" // ATA_CMD_REQUEST_SENSE\n#include \"blockcmd.h\" // CDB_CMD_REQUEST_SENSE\n\n\n/****************************************************************\n * CD emulation\n ****************************************************************/\n\nstruct drive_s *cdemu_drive_gf VAR16VISIBLE;\n\nstatic int\ncdemu_read(struct disk_op_s *op)\n{\n u16 ebda_seg = get_ebda_seg();\n struct drive_s *drive_g;\n drive_g = GLOBALFLAT2GLOBAL(GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf));\n struct disk_op_s dop;\n dop.drive_g = drive_g;\n dop.command = op->command;\n dop.lba = GET_EBDA2(ebda_seg, cdemu.ilba) + op->lba / 4;\n\n int count = op->count;\n op->count = 0;\n u8 *cdbuf_fl = GET_GLOBAL(bounce_buf_fl);\n\n if (op->lba & 3) {\n // Partial read of first block.\n dop.count = 1;\n dop.buf_fl = cdbuf_fl;\n int ret = process_op(&dop);\n if (ret)\n return ret;\n u8 thiscount = 4 - (op->lba & 3);\n if (thiscount > count)\n thiscount = count;\n count -= thiscount;\n memcpy_fl(op->buf_fl, cdbuf_fl + (op->lba & 3) * 512, thiscount * 512);\n op->buf_fl += thiscount * 512;\n op->count += thiscount;\n dop.lba++;\n }\n\n if (count > 3) {\n // Read n number of regular blocks.\n dop.count = count / 4;\n dop.buf_fl = op->buf_fl;\n int ret = process_op(&dop);\n op->count += dop.count * 4;\n if (ret)\n return ret;\n u8 thiscount = count & ~3;\n count &= 3;\n op->buf_fl += thiscount * 512;\n dop.lba += thiscount / 4;\n }\n\n if (count) {\n // Partial read on last block.\n dop.count = 1;\n dop.buf_fl = cdbuf_fl;\n int ret = process_op(&dop);\n if (ret)\n return ret;\n u8 thiscount = count;\n memcpy_fl(op->buf_fl, cdbuf_fl, thiscount * 512);\n op->count += thiscount;\n }\n\n return DISK_RET_SUCCESS;\n}\n\nint\nprocess_cdemu_op(struct disk_op_s *op)\n{\n if (!CONFIG_CDROM_EMU)\n return 0;\n\n switch (op->command) {\n case CMD_READ:\n return cdemu_read(op);\n case CMD_WRITE:\n case CMD_FORMAT:\n return DISK_RET_EWRITEPROTECT;\n case CMD_VERIFY:\n case CMD_RESET:\n case CMD_SEEK:\n case CMD_ISREADY:\n return DISK_RET_SUCCESS;\n default:\n op->count = 0;\n return DISK_RET_EPARAM;\n }\n}\n\nvoid\ncdemu_setup(void)\n{\n if (!CONFIG_CDROM_EMU)\n return;\n if (!CDCount)\n return;\n if (bounce_buf_init() < 0)\n return;\n\n struct drive_s *drive_g = malloc_fseg(sizeof(*drive_g));\n if (!drive_g) {\n warn_noalloc();\n free(drive_g);\n return;\n }\n cdemu_drive_gf = drive_g;\n memset(drive_g, 0, sizeof(*drive_g));\n drive_g->type = DTYPE_CDEMU;\n drive_g->blksize = DISK_SECTOR_SIZE;\n drive_g->sectors = (u64)-1;\n}\n\nstruct eltorito_s {\n u8 size;\n u8 media;\n u8 emulated_drive;\n u8 controller_index;\n u32 ilba;\n u16 device_spec;\n u16 buffer_segment;\n u16 load_segment;\n u16 sector_count;\n u8 cylinders;\n u8 sectors;\n u8 heads;\n};\n\n#define SET_INT13ET(regs,var,val) \\\n SET_FARVAR((regs)->ds, ((struct eltorito_s*)((regs)->si+0))->var, (val))\n\n// ElTorito - Terminate disk emu\nvoid\ncdemu_134b(struct bregs *regs)\n{\n // FIXME ElTorito Hardcoded\n u16 ebda_seg = get_ebda_seg();\n SET_INT13ET(regs, size, 0x13);\n SET_INT13ET(regs, media, GET_EBDA2(ebda_seg, cdemu.media));\n SET_INT13ET(regs, emulated_drive\n , GET_EBDA2(ebda_seg, cdemu.emulated_extdrive));\n struct drive_s *drive_gf = GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf);\n u8 cntl_id = 0;\n if (drive_gf)\n cntl_id = GET_GLOBALFLAT(drive_gf->cntl_id);\n SET_INT13ET(regs, controller_index, cntl_id / 2);\n SET_INT13ET(regs, device_spec, cntl_id % 2);\n SET_INT13ET(regs, ilba, GET_EBDA2(ebda_seg, cdemu.ilba));\n SET_INT13ET(regs, buffer_segment, GET_EBDA2(ebda_seg, cdemu.buffer_segment));\n SET_INT13ET(regs, load_segment, GET_EBDA2(ebda_seg, cdemu.load_segment));\n SET_INT13ET(regs, sector_count, GET_EBDA2(ebda_seg, cdemu.sector_count));\n SET_INT13ET(regs, cylinders, GET_EBDA2(ebda_seg, cdemu.lchs.cylinders));\n SET_INT13ET(regs, sectors, GET_EBDA2(ebda_seg, cdemu.lchs.spt));\n SET_INT13ET(regs, heads, GET_EBDA2(ebda_seg, cdemu.lchs.heads));\n\n // If we have to terminate emulation\n if (regs->al == 0x00) {\n // FIXME ElTorito Various. Should be handled accordingly to spec\n SET_EBDA2(ebda_seg, cdemu.active, 0x00); // bye bye\n\n // XXX - update floppy/hd count.\n }\n\n disk_ret(regs, DISK_RET_SUCCESS);\n}\n\n\n/****************************************************************\n * CD booting\n ****************************************************************/\n\nint\ncdrom_boot(struct drive_s *drive_g)\n{\n struct disk_op_s dop;\n int cdid = getDriveId(EXTTYPE_CD, drive_g);\n memset(&dop, 0, sizeof(dop));\n dop.drive_g = drive_g;\n if (!dop.drive_g || cdid < 0)\n return 1;\n\n int ret = scsi_is_ready(&dop);\n if (ret)\n dprintf(1, \"scsi_is_ready returned %d\\n\", ret);\n\n // Read the Boot Record Volume Descriptor\n u8 buffer[2048];\n dop.lba = 0x11;\n dop.count = 1;\n dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);\n ret = cdb_read(&dop);\n if (ret)\n return 3;\n\n // Validity checks\n if (buffer[0])\n return 4;\n if (strcmp((char*)&buffer[1], \"CD001\\001EL TORITO SPECIFICATION\") != 0)\n return 5;\n\n // ok, now we calculate the Boot catalog address\n u32 lba = *(u32*)&buffer[0x47];\n\n // And we read the Boot Catalog\n dop.lba = lba;\n dop.count = 1;\n ret = cdb_read(&dop);\n if (ret)\n return 7;\n\n // Validation entry\n if (buffer[0x00] != 0x01)\n return 8; // Header\n if (buffer[0x01] != 0x00)\n return 9; // Platform\n if (buffer[0x1E] != 0x55)\n return 10; // key 1\n if (buffer[0x1F] != 0xAA)\n return 10; // key 2\n\n // Initial/Default Entry\n if (buffer[0x20] != 0x88)\n return 11; // Bootable\n\n u16 ebda_seg = get_ebda_seg();\n u8 media = buffer[0x21];\n SET_EBDA2(ebda_seg, cdemu.media, media);\n\n SET_EBDA2(ebda_seg, cdemu.emulated_drive_gf, dop.drive_g);\n\n u16 boot_segment = *(u16*)&buffer[0x22];\n if (!boot_segment)\n boot_segment = 0x07C0;\n SET_EBDA2(ebda_seg, cdemu.load_segment, boot_segment);\n SET_EBDA2(ebda_seg, cdemu.buffer_segment, 0x0000);\n\n u16 nbsectors = *(u16*)&buffer[0x26];\n SET_EBDA2(ebda_seg, cdemu.sector_count, nbsectors);\n\n lba = *(u32*)&buffer[0x28];\n SET_EBDA2(ebda_seg, cdemu.ilba, lba);\n\n // And we read the image in memory\n dop.lba = lba;\n dop.count = DIV_ROUND_UP(nbsectors, 4);\n dop.buf_fl = MAKE_FLATPTR(boot_segment, 0);\n ret = cdb_read(&dop);\n if (ret)\n return 12;\n\n if (media == 0) {\n // No emulation requested - return success.\n SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, EXTSTART_CD + cdid);\n return 0;\n }\n\n // Emulation of a floppy/harddisk requested\n if (! CONFIG_CDROM_EMU || !cdemu_drive_gf)\n return 13;\n\n // Set emulated drive id and increase bios installed hardware\n // number of devices\n if (media < 4) {\n // Floppy emulation\n SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x00);\n // XXX - get and set actual floppy count.\n SETBITS_BDA(equipment_list_flags, 0x41);\n\n switch (media) {\n case 0x01: // 1.2M floppy\n SET_EBDA2(ebda_seg, cdemu.lchs.spt, 15);\n SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);\n SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);\n break;\n case 0x02: // 1.44M floppy\n SET_EBDA2(ebda_seg, cdemu.lchs.spt, 18);\n SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);\n SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);\n break;\n case 0x03: // 2.88M floppy\n SET_EBDA2(ebda_seg, cdemu.lchs.spt, 36);\n SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);\n SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);\n break;\n }\n } else {\n // Harddrive emulation\n SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x80);\n SET_BDA(hdcount, GET_BDA(hdcount) + 1);\n\n // Peak at partition table to get chs.\n struct mbr_s *mbr = (void*)0;\n u8 sptcyl = GET_FARVAR(boot_segment, mbr->partitions[0].last.sptcyl);\n u8 cyllow = GET_FARVAR(boot_segment, mbr->partitions[0].last.cyllow);\n u8 heads = GET_FARVAR(boot_segment, mbr->partitions[0].last.heads);\n\n SET_EBDA2(ebda_seg, cdemu.lchs.spt, sptcyl & 0x3f);\n SET_EBDA2(ebda_seg, cdemu.lchs.cylinders\n , ((sptcyl<<2)&0x300) + cyllow + 1);\n SET_EBDA2(ebda_seg, cdemu.lchs.heads, heads + 1);\n }\n\n // everything is ok, so from now on, the emulation is active\n SET_EBDA2(ebda_seg, cdemu.active, 0x01);\n dprintf(6, \"cdemu media=%d\\n\", media);\n\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"bonzini/seabios"},"path":{"kind":"string","value":"src/cdrom.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":9412,"string":"9,412"}}},{"rowIdx":115086576,"cells":{"code":{"kind":"string","value":"class GstPluginsUgly < Formula\n desc \"GStreamer plugins (well-supported, possibly problematic for distributors)\"\n homepage \"https://gstreamer.freedesktop.org/\"\n url \"https://gstreamer.freedesktop.org/src/gst-plugins-ugly/gst-plugins-ugly-1.8.0.tar.xz\"\n sha256 \"53657ffb7d49ddc4ae40e3f52e56165db4c06eb016891debe2b6c0e9f134eb8c\"\n\n bottle do\n sha256 \"de81ae62cc34b67d54cb632dce97fb108e4dff3cf839cf99703c23415e64fa8b\" => :el_capitan\n sha256 \"5b471670878ccc08926394d973d3ddb5904921e7739ef11bb0f4fe3c67b77f09\" => :yosemite\n sha256 \"32c4fc7c2fa4a60390f4346f69b9f4d1bf3a260c94400319d122d2b4c634d5ad\" => :mavericks\n end\n\n head do\n url \"https://anongit.freedesktop.org/git/gstreamer/gst-plugins-ugly.git\"\n\n depends_on \"autoconf\" => :build\n depends_on \"automake\" => :build\n depends_on \"libtool\" => :build\n end\n\n depends_on \"pkg-config\" => :build\n depends_on \"gettext\"\n depends_on \"gst-plugins-base\"\n\n # The set of optional dependencies is based on the intersection of\n # gst-plugins-ugly-0.10.17/REQUIREMENTS and Homebrew formulae\n depends_on \"dirac\" => :optional\n depends_on \"mad\" => :optional\n depends_on \"jpeg\" => :optional\n depends_on \"libvorbis\" => :optional\n depends_on \"cdparanoia\" => :optional\n depends_on \"lame\" => :optional\n depends_on \"two-lame\" => :optional\n depends_on \"libshout\" => :optional\n depends_on \"aalib\" => :optional\n depends_on \"libcaca\" => :optional\n depends_on \"libdvdread\" => :optional\n depends_on \"libmpeg2\" => :optional\n depends_on \"a52dec\" => :optional\n depends_on \"liboil\" => :optional\n depends_on \"flac\" => :optional\n depends_on \"gtk+\" => :optional\n depends_on \"pango\" => :optional\n depends_on \"theora\" => :optional\n depends_on \"libmms\" => :optional\n depends_on \"x264\" => :optional\n depends_on \"opencore-amr\" => :optional\n # Does not work with libcdio 0.9\n\n def install\n args = %W[\n --prefix=#{prefix}\n --mandir=#{man}\n --disable-debug\n --disable-dependency-tracking\n ]\n\n if build.head?\n ENV[\"NOCONFIGURE\"] = \"yes\"\n system \"./autogen.sh\"\n end\n\n if build.with? \"opencore-amr\"\n # Fixes build error, missing includes.\n # https://github.com/Homebrew/homebrew/issues/14078\n nbcflags = `pkg-config --cflags opencore-amrnb`.chomp\n wbcflags = `pkg-config --cflags opencore-amrwb`.chomp\n ENV[\"AMRNB_CFLAGS\"] = nbcflags + \"-I#{HOMEBREW_PREFIX}/include/opencore-amrnb\"\n ENV[\"AMRWB_CFLAGS\"] = wbcflags + \"-I#{HOMEBREW_PREFIX}/include/opencore-amrwb\"\n else\n args << \"--disable-amrnb\" << \"--disable-amrwb\"\n end\n\n system \"./configure\", *args\n system \"make\"\n system \"make\", \"install\"\n end\nend\n"},"repo_name":{"kind":"string","value":"gnubila-france/linuxbrew"},"path":{"kind":"string","value":"Library/Formula/gst-plugins-ugly.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"bsd-2-clause"},"size":{"kind":"number","value":2650,"string":"2,650"}}},{"rowIdx":115086577,"cells":{"code":{"kind":"string","value":"cask 'netbeans-java-se' do\n version '8.2'\n sha256 '91652f03d8abba0ae9d76a612ed909c9f82e4f138cbd510f5d3679280323011b'\n\n url \"https://download.netbeans.org/netbeans/#{version}/final/bundles/netbeans-#{version}-javase-macosx.dmg\"\n name 'NetBeans IDE for Java SE'\n homepage 'https://netbeans.org/'\n\n pkg \"NetBeans #{version}.pkg\"\n\n uninstall pkgutil: 'org.netbeans.ide.*',\n delete: '/Applications/NetBeans'\nend\n"},"repo_name":{"kind":"string","value":"wastrachan/homebrew-cask"},"path":{"kind":"string","value":"Casks/netbeans-java-se.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"bsd-2-clause"},"size":{"kind":"number","value":426,"string":"426"}}},{"rowIdx":115086578,"cells":{"code":{"kind":"string","value":"/* Siemens ID Mouse driver v0.6\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License, or (at your option) any later version.\n\n Copyright (C) 2004-5 by Florian 'Floe' Echtler \n and Andreas 'ad' Deresch \n\n Derived from the USB Skeleton driver 1.1,\n Copyright (C) 2003 Greg Kroah-Hartman (greg@kroah.com)\n\n Additional information provided by Martin Reising\n \n\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* image constants */\n#define WIDTH 225\n#define HEIGHT 289\n#define HEADER \"P5 225 289 255 \"\n#define IMGSIZE ((WIDTH * HEIGHT) + sizeof(HEADER)-1)\n\n/* version information */\n#define DRIVER_VERSION \"0.6\"\n#define DRIVER_SHORT \"idmouse\"\n#define DRIVER_AUTHOR \"Florian 'Floe' Echtler \"\n#define DRIVER_DESC \"Siemens ID Mouse FingerTIP Sensor Driver\"\n\n/* minor number for misc USB devices */\n#define USB_IDMOUSE_MINOR_BASE 132\n\n/* vendor and device IDs */\n#define ID_SIEMENS 0x0681\n#define ID_IDMOUSE 0x0005\n#define ID_CHERRY 0x0010\n\n/* device ID table */\nstatic struct usb_device_id idmouse_table[] = {\n\t{USB_DEVICE(ID_SIEMENS, ID_IDMOUSE)}, /* Siemens ID Mouse (Professional) */\n\t{USB_DEVICE(ID_SIEMENS, ID_CHERRY )}, /* Cherry FingerTIP ID Board */\n\t{} /* terminating null entry */\n};\n\n/* sensor commands */\n#define FTIP_RESET 0x20\n#define FTIP_ACQUIRE 0x21\n#define FTIP_RELEASE 0x22\n#define FTIP_BLINK 0x23 /* LSB of value = blink pulse width */\n#define FTIP_SCROLL 0x24\n\n#define ftip_command(dev, command, value, index) \\\n\tusb_control_msg (dev->udev, usb_sndctrlpipe (dev->udev, 0), command, \\\n\tUSB_TYPE_VENDOR | USB_RECIP_ENDPOINT | USB_DIR_OUT, value, index, NULL, 0, 1000)\n\nMODULE_DEVICE_TABLE(usb, idmouse_table);\nstatic DEFINE_MUTEX(open_disc_mutex);\n\n/* structure to hold all of our device specific stuff */\nstruct usb_idmouse {\n\n\tstruct usb_device *udev; /* save off the usb device pointer */\n\tstruct usb_interface *interface; /* the interface for this device */\n\n\tunsigned char *bulk_in_buffer; /* the buffer to receive data */\n\tsize_t bulk_in_size; /* the maximum bulk packet size */\n\tsize_t orig_bi_size; /* same as above, but reported by the device */\n\t__u8 bulk_in_endpointAddr; /* the address of the bulk in endpoint */\n\n\tint open; /* if the port is open or not */\n\tint present; /* if the device is not disconnected */\n\tstruct mutex lock; /* locks this structure */\n\n};\n\n/* local function prototypes */\nstatic ssize_t idmouse_read(struct file *file, char __user *buffer,\n\t\t\t\tsize_t count, loff_t * ppos);\n\nstatic int idmouse_open(struct inode *inode, struct file *file);\nstatic int idmouse_release(struct inode *inode, struct file *file);\n\nstatic int idmouse_probe(struct usb_interface *interface,\n\t\t\t\tconst struct usb_device_id *id);\n\nstatic void idmouse_disconnect(struct usb_interface *interface);\nstatic int idmouse_suspend(struct usb_interface *intf, pm_message_t message);\nstatic int idmouse_resume(struct usb_interface *intf);\n\n/* file operation pointers */\nstatic const struct file_operations idmouse_fops = {\n\t.owner = THIS_MODULE,\n\t.read = idmouse_read,\n\t.open = idmouse_open,\n\t.release = idmouse_release,\n};\n\n/* class driver information */\nstatic struct usb_class_driver idmouse_class = {\n\t.name = \"idmouse%d\",\n\t.fops = &idmouse_fops,\n\t.minor_base = USB_IDMOUSE_MINOR_BASE,\n};\n\n/* usb specific object needed to register this driver with the usb subsystem */\nstatic struct usb_driver idmouse_driver = {\n\t.name = DRIVER_SHORT,\n\t.probe = idmouse_probe,\n\t.disconnect = idmouse_disconnect,\n\t.suspend = idmouse_suspend,\n\t.resume = idmouse_resume,\n\t.reset_resume = idmouse_resume,\n\t.id_table = idmouse_table,\n\t.supports_autosuspend = 1,\n};\n\nstatic int idmouse_create_image(struct usb_idmouse *dev)\n{\n\tint bytes_read;\n\tint bulk_read;\n\tint result;\n\n\tmemcpy(dev->bulk_in_buffer, HEADER, sizeof(HEADER)-1);\n\tbytes_read = sizeof(HEADER)-1;\n\n\t/* reset the device and set a fast blink rate */\n\tresult = ftip_command(dev, FTIP_RELEASE, 0, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\tresult = ftip_command(dev, FTIP_BLINK, 1, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\n\t/* initialize the sensor - sending this command twice */\n\t/* significantly reduces the rate of failed reads */\n\tresult = ftip_command(dev, FTIP_ACQUIRE, 0, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\tresult = ftip_command(dev, FTIP_ACQUIRE, 0, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\n\t/* start the readout - sending this command twice */\n\t/* presumably enables the high dynamic range mode */\n\tresult = ftip_command(dev, FTIP_RESET, 0, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\tresult = ftip_command(dev, FTIP_RESET, 0, 0);\n\tif (result < 0)\n\t\tgoto reset;\n\n\t/* loop over a blocking bulk read to get data from the device */\n\twhile (bytes_read < IMGSIZE) {\n\t\tresult = usb_bulk_msg (dev->udev,\n\t\t\t\tusb_rcvbulkpipe (dev->udev, dev->bulk_in_endpointAddr),\n\t\t\t\tdev->bulk_in_buffer + bytes_read,\n\t\t\t\tdev->bulk_in_size, &bulk_read, 5000);\n\t\tif (result < 0) {\n\t\t\t/* Maybe this error was caused by the increased packet size? */\n\t\t\t/* Reset to the original value and tell userspace to retry. */\n\t\t\tif (dev->bulk_in_size != dev->orig_bi_size) {\n\t\t\t\tdev->bulk_in_size = dev->orig_bi_size;\n\t\t\t\tresult = -EAGAIN;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (signal_pending(current)) {\n\t\t\tresult = -EINTR;\n\t\t\tbreak;\n\t\t}\n\t\tbytes_read += bulk_read;\n\t}\n\n\t/* reset the device */\nreset:\n\tftip_command(dev, FTIP_RELEASE, 0, 0);\n\n\t/* check for valid image */\n\t/* right border should be black (0x00) */\n\tfor (bytes_read = sizeof(HEADER)-1 + WIDTH-1; bytes_read < IMGSIZE; bytes_read += WIDTH)\n\t\tif (dev->bulk_in_buffer[bytes_read] != 0x00)\n\t\t\treturn -EAGAIN;\n\n\t/* lower border should be white (0xFF) */\n\tfor (bytes_read = IMGSIZE-WIDTH; bytes_read < IMGSIZE-1; bytes_read++)\n\t\tif (dev->bulk_in_buffer[bytes_read] != 0xFF)\n\t\t\treturn -EAGAIN;\n\n\t/* should be IMGSIZE == 65040 */\n\tdbg(\"read %d bytes fingerprint data\", bytes_read);\n\treturn result;\n}\n\n/* PM operations are nops as this driver does IO only during open() */\nstatic int idmouse_suspend(struct usb_interface *intf, pm_message_t message)\n{\n\treturn 0;\n}\n\nstatic int idmouse_resume(struct usb_interface *intf)\n{\n\treturn 0;\n}\n\nstatic inline void idmouse_delete(struct usb_idmouse *dev)\n{\n\tkfree(dev->bulk_in_buffer);\n\tkfree(dev);\n}\n\nstatic int idmouse_open(struct inode *inode, struct file *file)\n{\n\tstruct usb_idmouse *dev;\n\tstruct usb_interface *interface;\n\tint result;\n\n\t/* get the interface from minor number and driver information */\n\tinterface = usb_find_interface (&idmouse_driver, iminor (inode));\n\tif (!interface)\n\t\treturn -ENODEV;\n\n\tmutex_lock(&open_disc_mutex);\n\t/* get the device information block from the interface */\n\tdev = usb_get_intfdata(interface);\n\tif (!dev) {\n\t\tmutex_unlock(&open_disc_mutex);\n\t\treturn -ENODEV;\n\t}\n\n\t/* lock this device */\n\tmutex_lock(&dev->lock);\n\tmutex_unlock(&open_disc_mutex);\n\n\t/* check if already open */\n\tif (dev->open) {\n\n\t\t/* already open, so fail */\n\t\tresult = -EBUSY;\n\n\t} else {\n\n\t\t/* create a new image and check for success */\n\t\tresult = usb_autopm_get_interface(interface);\n\t\tif (result)\n\t\t\tgoto error;\n\t\tresult = idmouse_create_image (dev);\n\t\tif (result)\n\t\t\tgoto error;\n\t\tusb_autopm_put_interface(interface);\n\n\t\t/* increment our usage count for the driver */\n\t\t++dev->open;\n\n\t\t/* save our object in the file's private structure */\n\t\tfile->private_data = dev;\n\n\t} \n\nerror:\n\n\t/* unlock this device */\n\tmutex_unlock(&dev->lock);\n\treturn result;\n}\n\nstatic int idmouse_release(struct inode *inode, struct file *file)\n{\n\tstruct usb_idmouse *dev;\n\n\tdev = file->private_data;\n\n\tif (dev == NULL)\n\t\treturn -ENODEV;\n\n\tmutex_lock(&open_disc_mutex);\n\t/* lock our device */\n\tmutex_lock(&dev->lock);\n\n\t/* are we really open? */\n\tif (dev->open <= 0) {\n\t\tmutex_unlock(&dev->lock);\n\t\tmutex_unlock(&open_disc_mutex);\n\t\treturn -ENODEV;\n\t}\n\n\t--dev->open;\n\n\tif (!dev->present) {\n\t\t/* the device was unplugged before the file was released */\n\t\tmutex_unlock(&dev->lock);\n\t\tmutex_unlock(&open_disc_mutex);\n\t\tidmouse_delete(dev);\n\t} else {\n\t\tmutex_unlock(&dev->lock);\n\t\tmutex_unlock(&open_disc_mutex);\n\t}\n\treturn 0;\n}\n\nstatic ssize_t idmouse_read(struct file *file, char __user *buffer, size_t count,\n\t\t\t\tloff_t * ppos)\n{\n\tstruct usb_idmouse *dev = file->private_data;\n\tint result;\n\n\t/* lock this object */\n\tmutex_lock(&dev->lock);\n\n\t/* verify that the device wasn't unplugged */\n\tif (!dev->present) {\n\t\tmutex_unlock(&dev->lock);\n\t\treturn -ENODEV;\n\t}\n\n\tresult = simple_read_from_buffer(buffer, count, ppos,\n\t\t\t\t\tdev->bulk_in_buffer, IMGSIZE);\n\t/* unlock the device */\n\tmutex_unlock(&dev->lock);\n\treturn result;\n}\n\nstatic int idmouse_probe(struct usb_interface *interface,\n\t\t\t\tconst struct usb_device_id *id)\n{\n\tstruct usb_device *udev = interface_to_usbdev(interface);\n\tstruct usb_idmouse *dev;\n\tstruct usb_host_interface *iface_desc;\n\tstruct usb_endpoint_descriptor *endpoint;\n\tint result;\n\n\t/* check if we have gotten the data or the hid interface */\n\tiface_desc = &interface->altsetting[0];\n\tif (iface_desc->desc.bInterfaceClass != 0x0A)\n\t\treturn -ENODEV;\n\n\t/* allocate memory for our device state and initialize it */\n\tdev = kzalloc(sizeof(*dev), GFP_KERNEL);\n\tif (dev == NULL)\n\t\treturn -ENOMEM;\n\n\tmutex_init(&dev->lock);\n\tdev->udev = udev;\n\tdev->interface = interface;\n\n\t/* set up the endpoint information - use only the first bulk-in endpoint */\n\tendpoint = &iface_desc->endpoint[0].desc;\n\tif (!dev->bulk_in_endpointAddr && usb_endpoint_is_bulk_in(endpoint)) {\n\t\t/* we found a bulk in endpoint */\n\t\tdev->orig_bi_size = le16_to_cpu(endpoint->wMaxPacketSize);\n\t\tdev->bulk_in_size = 0x200; /* works _much_ faster */\n\t\tdev->bulk_in_endpointAddr = endpoint->bEndpointAddress;\n\t\tdev->bulk_in_buffer =\n\t\t\tkmalloc(IMGSIZE + dev->bulk_in_size, GFP_KERNEL);\n\n\t\tif (!dev->bulk_in_buffer) {\n\t\t\terr(\"Unable to allocate input buffer.\");\n\t\t\tidmouse_delete(dev);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tif (!(dev->bulk_in_endpointAddr)) {\n\t\terr(\"Unable to find bulk-in endpoint.\");\n\t\tidmouse_delete(dev);\n\t\treturn -ENODEV;\n\t}\n\t/* allow device read, write and ioctl */\n\tdev->present = 1;\n\n\t/* we can register the device now, as it is ready */\n\tusb_set_intfdata(interface, dev);\n\tresult = usb_register_dev(interface, &idmouse_class);\n\tif (result) {\n\t\t/* something prevented us from registering this device */\n\t\terr(\"Unble to allocate minor number.\");\n\t\tusb_set_intfdata(interface, NULL);\n\t\tidmouse_delete(dev);\n\t\treturn result;\n\t}\n\n\t/* be noisy */\n\tdev_info(&interface->dev,\"%s now attached\\n\",DRIVER_DESC);\n\n\treturn 0;\n}\n\nstatic void idmouse_disconnect(struct usb_interface *interface)\n{\n\tstruct usb_idmouse *dev;\n\n\t/* get device structure */\n\tdev = usb_get_intfdata(interface);\n\n\t/* give back our minor */\n\tusb_deregister_dev(interface, &idmouse_class);\n\n\tmutex_lock(&open_disc_mutex);\n\tusb_set_intfdata(interface, NULL);\n\t/* lock the device */\n\tmutex_lock(&dev->lock);\n\tmutex_unlock(&open_disc_mutex);\n\n\t/* prevent device read, write and ioctl */\n\tdev->present = 0;\n\n\t/* if the device is opened, idmouse_release will clean this up */\n\tif (!dev->open) {\n\t\tmutex_unlock(&dev->lock);\n\t\tidmouse_delete(dev);\n\t} else {\n\t\t/* unlock */\n\t\tmutex_unlock(&dev->lock);\n\t}\n\n\tdev_info(&interface->dev, \"disconnected\\n\");\n}\n\nstatic int __init usb_idmouse_init(void)\n{\n\tint result;\n\n\tprintk(KERN_INFO KBUILD_MODNAME \": \" DRIVER_VERSION \":\"\n\t DRIVER_DESC \"\\n\");\n\n\t/* register this driver with the USB subsystem */\n\tresult = usb_register(&idmouse_driver);\n\tif (result)\n\t\terr(\"Unable to register device (error %d).\", result);\n\n\treturn result;\n}\n\nstatic void __exit usb_idmouse_exit(void)\n{\n\t/* deregister this driver with the USB subsystem */\n\tusb_deregister(&idmouse_driver);\n}\n\nmodule_init(usb_idmouse_init);\nmodule_exit(usb_idmouse_exit);\n\nMODULE_AUTHOR(DRIVER_AUTHOR);\nMODULE_DESCRIPTION(DRIVER_DESC);\nMODULE_LICENSE(\"GPL\");\n\n"},"repo_name":{"kind":"string","value":"go2ev-devteam/Gplus_2159_0801"},"path":{"kind":"string","value":"openplatform/sdk/os/kernel-2.6.32/drivers/usb/misc/idmouse.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":12143,"string":"12,143"}}},{"rowIdx":115086579,"cells":{"code":{"kind":"string","value":"Input filter\n============\n\nThis type of filter displays an input field.\n\nA second input field is displayed if you select a range operator (between).\n\nThe two input fields are disabled if you select the `Is defined` and `Is not defined` operators.\n\n### Additionnal attributes for a column annotation for a property\n\n|Attribute|Type|Default value|Possible values|Description|\n|:--:|:--|:--|:--|:--|\n|inputType|string|text||Define the type of inputs. See [HTML5 input types](http://www.w3schools.com/html5/html5_form_input_types.asp)|\n"},"repo_name":{"kind":"string","value":"Roquet87/SIGESRHI"},"path":{"kind":"string","value":"vendor/apy/datagrid-bundle/APY/DataGridBundle/Resources/doc/columns_configuration/filters/input_filter.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":532,"string":"532"}}},{"rowIdx":115086580,"cells":{"code":{"kind":"string","value":"// SPDX-License-Identifier: GPL-2.0\n/*\n * prepare to run common code\n *\n * Copyright (C) 2000 Andrea Arcangeli SuSE\n */\n\n#define DISABLE_BRANCH_PROFILING\n\n/* cpu_feature_enabled() cannot be used this early */\n#define USE_EARLY_PGTABLE_L5\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n * Manage page tables very early on.\n */\nextern pmd_t early_dynamic_pgts[EARLY_DYNAMIC_PAGE_TABLES][PTRS_PER_PMD];\nstatic unsigned int __initdata next_early_pgt;\npmdval_t early_pmd_flags = __PAGE_KERNEL_LARGE & ~(_PAGE_GLOBAL | _PAGE_NX);\n\n#ifdef CONFIG_X86_5LEVEL\nunsigned int __pgtable_l5_enabled __ro_after_init;\nunsigned int pgdir_shift __ro_after_init = 39;\nEXPORT_SYMBOL(pgdir_shift);\nunsigned int ptrs_per_p4d __ro_after_init = 1;\nEXPORT_SYMBOL(ptrs_per_p4d);\n#endif\n\n#ifdef CONFIG_DYNAMIC_MEMORY_LAYOUT\nunsigned long page_offset_base __ro_after_init = __PAGE_OFFSET_BASE_L4;\nEXPORT_SYMBOL(page_offset_base);\nunsigned long vmalloc_base __ro_after_init = __VMALLOC_BASE_L4;\nEXPORT_SYMBOL(vmalloc_base);\nunsigned long vmemmap_base __ro_after_init = __VMEMMAP_BASE_L4;\nEXPORT_SYMBOL(vmemmap_base);\n#endif\n\n#define __head\t__section(.head.text)\n\nstatic void __head *fixup_pointer(void *ptr, unsigned long physaddr)\n{\n\treturn ptr - (void *)_text + (void *)physaddr;\n}\n\nstatic unsigned long __head *fixup_long(void *ptr, unsigned long physaddr)\n{\n\treturn fixup_pointer(ptr, physaddr);\n}\n\n#ifdef CONFIG_X86_5LEVEL\nstatic unsigned int __head *fixup_int(void *ptr, unsigned long physaddr)\n{\n\treturn fixup_pointer(ptr, physaddr);\n}\n\nstatic bool __head check_la57_support(unsigned long physaddr)\n{\n\t/*\n\t * 5-level paging is detected and enabled at kernel decomression\n\t * stage. Only check if it has been enabled there.\n\t */\n\tif (!(native_read_cr4() & X86_CR4_LA57))\n\t\treturn false;\n\n\t*fixup_int(&__pgtable_l5_enabled, physaddr) = 1;\n\t*fixup_int(&pgdir_shift, physaddr) = 48;\n\t*fixup_int(&ptrs_per_p4d, physaddr) = 512;\n\t*fixup_long(&page_offset_base, physaddr) = __PAGE_OFFSET_BASE_L5;\n\t*fixup_long(&vmalloc_base, physaddr) = __VMALLOC_BASE_L5;\n\t*fixup_long(&vmemmap_base, physaddr) = __VMEMMAP_BASE_L5;\n\n\treturn true;\n}\n#else\nstatic bool __head check_la57_support(unsigned long physaddr)\n{\n\treturn false;\n}\n#endif\n\n/* Code in __startup_64() can be relocated during execution, but the compiler\n * doesn't have to generate PC-relative relocations when accessing globals from\n * that function. Clang actually does not generate them, which leads to\n * boot-time crashes. To work around this problem, every global pointer must\n * be adjusted using fixup_pointer().\n */\nunsigned long __head __startup_64(unsigned long physaddr,\n\t\t\t\t struct boot_params *bp)\n{\n\tunsigned long vaddr, vaddr_end;\n\tunsigned long load_delta, *p;\n\tunsigned long pgtable_flags;\n\tpgdval_t *pgd;\n\tp4dval_t *p4d;\n\tpudval_t *pud;\n\tpmdval_t *pmd, pmd_entry;\n\tpteval_t *mask_ptr;\n\tbool la57;\n\tint i;\n\tunsigned int *next_pgt_ptr;\n\n\tla57 = check_la57_support(physaddr);\n\n\t/* Is the address too large? */\n\tif (physaddr >> MAX_PHYSMEM_BITS)\n\t\tfor (;;);\n\n\t/*\n\t * Compute the delta between the address I am compiled to run at\n\t * and the address I am actually running at.\n\t */\n\tload_delta = physaddr - (unsigned long)(_text - __START_KERNEL_map);\n\n\t/* Is the address not 2M aligned? */\n\tif (load_delta & ~PMD_PAGE_MASK)\n\t\tfor (;;);\n\n\t/* Activate Secure Memory Encryption (SME) if supported and enabled */\n\tsme_enable(bp);\n\n\t/* Include the SME encryption mask in the fixup value */\n\tload_delta += sme_get_me_mask();\n\n\t/* Fixup the physical addresses in the page table */\n\n\tpgd = fixup_pointer(&early_top_pgt, physaddr);\n\tp = pgd + pgd_index(__START_KERNEL_map);\n\tif (la57)\n\t\t*p = (unsigned long)level4_kernel_pgt;\n\telse\n\t\t*p = (unsigned long)level3_kernel_pgt;\n\t*p += _PAGE_TABLE_NOENC - __START_KERNEL_map + load_delta;\n\n\tif (la57) {\n\t\tp4d = fixup_pointer(&level4_kernel_pgt, physaddr);\n\t\tp4d[511] += load_delta;\n\t}\n\n\tpud = fixup_pointer(&level3_kernel_pgt, physaddr);\n\tpud[510] += load_delta;\n\tpud[511] += load_delta;\n\n\tpmd = fixup_pointer(level2_fixmap_pgt, physaddr);\n\tfor (i = FIXMAP_PMD_TOP; i > FIXMAP_PMD_TOP - FIXMAP_PMD_NUM; i--)\n\t\tpmd[i] += load_delta;\n\n\t/*\n\t * Set up the identity mapping for the switchover. These\n\t * entries should *NOT* have the global bit set! This also\n\t * creates a bunch of nonsense entries but that is fine --\n\t * it avoids problems around wraparound.\n\t */\n\n\tnext_pgt_ptr = fixup_pointer(&next_early_pgt, physaddr);\n\tpud = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr);\n\tpmd = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr);\n\n\tpgtable_flags = _KERNPG_TABLE_NOENC + sme_get_me_mask();\n\n\tif (la57) {\n\t\tp4d = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++],\n\t\t\t\t physaddr);\n\n\t\ti = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;\n\t\tpgd[i + 0] = (pgdval_t)p4d + pgtable_flags;\n\t\tpgd[i + 1] = (pgdval_t)p4d + pgtable_flags;\n\n\t\ti = physaddr >> P4D_SHIFT;\n\t\tp4d[(i + 0) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;\n\t\tp4d[(i + 1) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;\n\t} else {\n\t\ti = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;\n\t\tpgd[i + 0] = (pgdval_t)pud + pgtable_flags;\n\t\tpgd[i + 1] = (pgdval_t)pud + pgtable_flags;\n\t}\n\n\ti = physaddr >> PUD_SHIFT;\n\tpud[(i + 0) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;\n\tpud[(i + 1) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;\n\n\tpmd_entry = __PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL;\n\t/* Filter out unsupported __PAGE_KERNEL_* bits: */\n\tmask_ptr = fixup_pointer(&__supported_pte_mask, physaddr);\n\tpmd_entry &= *mask_ptr;\n\tpmd_entry += sme_get_me_mask();\n\tpmd_entry += physaddr;\n\n\tfor (i = 0; i < DIV_ROUND_UP(_end - _text, PMD_SIZE); i++) {\n\t\tint idx = i + (physaddr >> PMD_SHIFT);\n\n\t\tpmd[idx % PTRS_PER_PMD] = pmd_entry + i * PMD_SIZE;\n\t}\n\n\t/*\n\t * Fixup the kernel text+data virtual addresses. Note that\n\t * we might write invalid pmds, when the kernel is relocated\n\t * cleanup_highmap() fixes this up along with the mappings\n\t * beyond _end.\n\t */\n\n\tpmd = fixup_pointer(level2_kernel_pgt, physaddr);\n\tfor (i = 0; i < PTRS_PER_PMD; i++) {\n\t\tif (pmd[i] & _PAGE_PRESENT)\n\t\t\tpmd[i] += load_delta;\n\t}\n\n\t/*\n\t * Fixup phys_base - remove the memory encryption mask to obtain\n\t * the true physical address.\n\t */\n\t*fixup_long(&phys_base, physaddr) += load_delta - sme_get_me_mask();\n\n\t/* Encrypt the kernel and related (if SME is active) */\n\tsme_encrypt_kernel(bp);\n\n\t/*\n\t * Clear the memory encryption mask from the .bss..decrypted section.\n\t * The bss section will be memset to zero later in the initialization so\n\t * there is no need to zero it after changing the memory encryption\n\t * attribute.\n\t */\n\tif (mem_encrypt_active()) {\n\t\tvaddr = (unsigned long)__start_bss_decrypted;\n\t\tvaddr_end = (unsigned long)__end_bss_decrypted;\n\t\tfor (; vaddr < vaddr_end; vaddr += PMD_SIZE) {\n\t\t\ti = pmd_index(vaddr);\n\t\t\tpmd[i] -= sme_get_me_mask();\n\t\t}\n\t}\n\n\t/*\n\t * Return the SME encryption mask (if SME is active) to be used as a\n\t * modifier for the initial pgdir entry programmed into CR3.\n\t */\n\treturn sme_get_me_mask();\n}\n\nunsigned long __startup_secondary_64(void)\n{\n\t/*\n\t * Return the SME encryption mask (if SME is active) to be used as a\n\t * modifier for the initial pgdir entry programmed into CR3.\n\t */\n\treturn sme_get_me_mask();\n}\n\n/* Wipe all early page tables except for the kernel symbol map */\nstatic void __init reset_early_page_tables(void)\n{\n\tmemset(early_top_pgt, 0, sizeof(pgd_t)*(PTRS_PER_PGD-1));\n\tnext_early_pgt = 0;\n\twrite_cr3(__sme_pa_nodebug(early_top_pgt));\n}\n\n/* Create a new PMD entry */\nint __init __early_make_pgtable(unsigned long address, pmdval_t pmd)\n{\n\tunsigned long physaddr = address - __PAGE_OFFSET;\n\tpgdval_t pgd, *pgd_p;\n\tp4dval_t p4d, *p4d_p;\n\tpudval_t pud, *pud_p;\n\tpmdval_t *pmd_p;\n\n\t/* Invalid address or early pgt is done ? */\n\tif (physaddr >= MAXMEM || read_cr3_pa() != __pa_nodebug(early_top_pgt))\n\t\treturn -1;\n\nagain:\n\tpgd_p = &early_top_pgt[pgd_index(address)].pgd;\n\tpgd = *pgd_p;\n\n\t/*\n\t * The use of __START_KERNEL_map rather than __PAGE_OFFSET here is\n\t * critical -- __PAGE_OFFSET would point us back into the dynamic\n\t * range and we might end up looping forever...\n\t */\n\tif (!pgtable_l5_enabled())\n\t\tp4d_p = pgd_p;\n\telse if (pgd)\n\t\tp4d_p = (p4dval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);\n\telse {\n\t\tif (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {\n\t\t\treset_early_page_tables();\n\t\t\tgoto again;\n\t\t}\n\n\t\tp4d_p = (p4dval_t *)early_dynamic_pgts[next_early_pgt++];\n\t\tmemset(p4d_p, 0, sizeof(*p4d_p) * PTRS_PER_P4D);\n\t\t*pgd_p = (pgdval_t)p4d_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;\n\t}\n\tp4d_p += p4d_index(address);\n\tp4d = *p4d_p;\n\n\tif (p4d)\n\t\tpud_p = (pudval_t *)((p4d & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);\n\telse {\n\t\tif (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {\n\t\t\treset_early_page_tables();\n\t\t\tgoto again;\n\t\t}\n\n\t\tpud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++];\n\t\tmemset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD);\n\t\t*p4d_p = (p4dval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;\n\t}\n\tpud_p += pud_index(address);\n\tpud = *pud_p;\n\n\tif (pud)\n\t\tpmd_p = (pmdval_t *)((pud & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);\n\telse {\n\t\tif (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {\n\t\t\treset_early_page_tables();\n\t\t\tgoto again;\n\t\t}\n\n\t\tpmd_p = (pmdval_t *)early_dynamic_pgts[next_early_pgt++];\n\t\tmemset(pmd_p, 0, sizeof(*pmd_p) * PTRS_PER_PMD);\n\t\t*pud_p = (pudval_t)pmd_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;\n\t}\n\tpmd_p[pmd_index(address)] = pmd;\n\n\treturn 0;\n}\n\nint __init early_make_pgtable(unsigned long address)\n{\n\tunsigned long physaddr = address - __PAGE_OFFSET;\n\tpmdval_t pmd;\n\n\tpmd = (physaddr & PMD_MASK) + early_pmd_flags;\n\n\treturn __early_make_pgtable(address, pmd);\n}\n\n/* Don't add a printk in there. printk relies on the PDA which is not initialized \n yet. */\nstatic void __init clear_bss(void)\n{\n\tmemset(__bss_start, 0,\n\t (unsigned long) __bss_stop - (unsigned long) __bss_start);\n}\n\nstatic unsigned long get_cmd_line_ptr(void)\n{\n\tunsigned long cmd_line_ptr = boot_params.hdr.cmd_line_ptr;\n\n\tcmd_line_ptr |= (u64)boot_params.ext_cmd_line_ptr << 32;\n\n\treturn cmd_line_ptr;\n}\n\nstatic void __init copy_bootdata(char *real_mode_data)\n{\n\tchar * command_line;\n\tunsigned long cmd_line_ptr;\n\n\t/*\n\t * If SME is active, this will create decrypted mappings of the\n\t * boot data in advance of the copy operations.\n\t */\n\tsme_map_bootdata(real_mode_data);\n\n\tmemcpy(&boot_params, real_mode_data, sizeof(boot_params));\n\tsanitize_boot_params(&boot_params);\n\tcmd_line_ptr = get_cmd_line_ptr();\n\tif (cmd_line_ptr) {\n\t\tcommand_line = __va(cmd_line_ptr);\n\t\tmemcpy(boot_command_line, command_line, COMMAND_LINE_SIZE);\n\t}\n\n\t/*\n\t * The old boot data is no longer needed and won't be reserved,\n\t * freeing up that memory for use by the system. If SME is active,\n\t * we need to remove the mappings that were created so that the\n\t * memory doesn't remain mapped as decrypted.\n\t */\n\tsme_unmap_bootdata(real_mode_data);\n}\n\nasmlinkage __visible void __init x86_64_start_kernel(char * real_mode_data)\n{\n\t/*\n\t * Build-time sanity checks on the kernel image and module\n\t * area mappings. (these are purely build-time and produce no code)\n\t */\n\tBUILD_BUG_ON(MODULES_VADDR < __START_KERNEL_map);\n\tBUILD_BUG_ON(MODULES_VADDR - __START_KERNEL_map < KERNEL_IMAGE_SIZE);\n\tBUILD_BUG_ON(MODULES_LEN + KERNEL_IMAGE_SIZE > 2*PUD_SIZE);\n\tBUILD_BUG_ON((__START_KERNEL_map & ~PMD_MASK) != 0);\n\tBUILD_BUG_ON((MODULES_VADDR & ~PMD_MASK) != 0);\n\tBUILD_BUG_ON(!(MODULES_VADDR > __START_KERNEL));\n\tMAYBE_BUILD_BUG_ON(!(((MODULES_END - 1) & PGDIR_MASK) ==\n\t\t\t\t(__START_KERNEL & PGDIR_MASK)));\n\tBUILD_BUG_ON(__fix_to_virt(__end_of_fixed_addresses) <= MODULES_END);\n\n\tcr4_init_shadow();\n\n\t/* Kill off the identity-map trampoline */\n\treset_early_page_tables();\n\n\tclear_bss();\n\n\tclear_page(init_top_pgt);\n\n\t/*\n\t * SME support may update early_pmd_flags to include the memory\n\t * encryption mask, so it needs to be called before anything\n\t * that may generate a page fault.\n\t */\n\tsme_early_init();\n\n\tkasan_early_init();\n\n\tidt_setup_early_handler();\n\n\tcopy_bootdata(__va(real_mode_data));\n\n\t/*\n\t * Load microcode early on BSP.\n\t */\n\tload_ucode_bsp();\n\n\t/* set init_top_pgt kernel high mapping*/\n\tinit_top_pgt[511] = early_top_pgt[511];\n\n\tx86_64_start_reservations(real_mode_data);\n}\n\nvoid __init x86_64_start_reservations(char *real_mode_data)\n{\n\t/* version is always not zero if it is copied */\n\tif (!boot_params.hdr.version)\n\t\tcopy_bootdata(__va(real_mode_data));\n\n\tx86_early_init_platform_quirks();\n\n\tswitch (boot_params.hdr.hardware_subarch) {\n\tcase X86_SUBARCH_INTEL_MID:\n\t\tx86_intel_mid_early_setup();\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tstart_kernel();\n}\n"},"repo_name":{"kind":"string","value":"koct9i/linux"},"path":{"kind":"string","value":"arch/x86/kernel/head64.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":13218,"string":"13,218"}}},{"rowIdx":115086581,"cells":{"code":{"kind":"string","value":"/* SCTP kernel implementation\n * (C) Copyright IBM Corp. 2001, 2004\n * Copyright (c) 1999-2000 Cisco, Inc.\n * Copyright (c) 1999-2001 Motorola, Inc.\n * Copyright (c) 2001 Intel Corp.\n * Copyright (c) 2001 La Monte H.P. Yarroll\n *\n * This file is part of the SCTP kernel implementation\n *\n * This module provides the abstraction for an SCTP association.\n *\n * This SCTP implementation is free software;\n * you can redistribute it and/or modify it under the terms of\n * the GNU General Public License as published by\n * the Free Software Foundation; either version 2, or (at your option)\n * any later version.\n *\n * This SCTP implementation is distributed in the hope that it\n * will be useful, but WITHOUT ANY WARRANTY; without even the implied\n * ************************\n * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU CC; see the file COPYING. If not, write to\n * the Free Software Foundation, 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * Please send any bug reports or fixes you make to the\n * email address(es):\n * lksctp developers \n *\n * Or submit a bug report through the following website:\n * http://www.sf.net/projects/lksctp\n *\n * Written or modified by:\n * La Monte H.P. Yarroll \n * Karl Knutson \n * Jon Grimm \n * Xingang Guo \n * Hui Huang \n * Sridhar Samudrala\t \n * Daisy Chang\t \n * Ryan Layer\t \n * Kevin Gao \n *\n * Any bugs reported given to us we will try to fix... any fixes shared will\n * be incorporated into the next SCTP release.\n */\n\n#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n/* Forward declarations for internal functions. */\nstatic void sctp_assoc_bh_rcv(struct work_struct *work);\nstatic void sctp_assoc_free_asconf_acks(struct sctp_association *asoc);\nstatic void sctp_assoc_free_asconf_queue(struct sctp_association *asoc);\n\n/* Keep track of the new idr low so that we don't re-use association id\n * numbers too fast. It is protected by they idr spin lock is in the\n * range of 1 - INT_MAX.\n */\nstatic u32 idr_low = 1;\n\n\n/* 1st Level Abstractions. */\n\n/* Initialize a new association from provided memory. */\nstatic struct sctp_association *sctp_association_init(struct sctp_association *asoc,\n\t\t\t\t\t const struct sctp_endpoint *ep,\n\t\t\t\t\t const struct sock *sk,\n\t\t\t\t\t sctp_scope_t scope,\n\t\t\t\t\t gfp_t gfp)\n{\n\tstruct net *net = sock_net(sk);\n\tstruct sctp_sock *sp;\n\tint i;\n\tsctp_paramhdr_t *p;\n\tint err;\n\n\t/* Retrieve the SCTP per socket area. */\n\tsp = sctp_sk((struct sock *)sk);\n\n\t/* Discarding const is appropriate here. */\n\tasoc->ep = (struct sctp_endpoint *)ep;\n\tsctp_endpoint_hold(asoc->ep);\n\n\t/* Hold the sock. */\n\tasoc->base.sk = (struct sock *)sk;\n\tsock_hold(asoc->base.sk);\n\n\t/* Initialize the common base substructure. */\n\tasoc->base.type = SCTP_EP_TYPE_ASSOCIATION;\n\n\t/* Initialize the object handling fields. */\n\tatomic_set(&asoc->base.refcnt, 1);\n\tasoc->base.dead = 0;\n\tasoc->base.malloced = 0;\n\n\t/* Initialize the bind addr area. */\n\tsctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port);\n\n\tasoc->state = SCTP_STATE_CLOSED;\n\n\t/* Set these values from the socket values, a conversion between\n\t * millsecons to seconds/microseconds must also be done.\n\t */\n\tasoc->cookie_life.tv_sec = sp->assocparams.sasoc_cookie_life / 1000;\n\tasoc->cookie_life.tv_usec = (sp->assocparams.sasoc_cookie_life % 1000)\n\t\t\t\t\t* 1000;\n\tasoc->frag_point = 0;\n\tasoc->user_frag = sp->user_frag;\n\n\t/* Set the association max_retrans and RTO values from the\n\t * socket values.\n\t */\n\tasoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt;\n\tasoc->pf_retrans = net->sctp.pf_retrans;\n\n\tasoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial);\n\tasoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max);\n\tasoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min);\n\n\tasoc->overall_error_count = 0;\n\n\t/* Initialize the association's heartbeat interval based on the\n\t * sock configured value.\n\t */\n\tasoc->hbinterval = msecs_to_jiffies(sp->hbinterval);\n\n\t/* Initialize path max retrans value. */\n\tasoc->pathmaxrxt = sp->pathmaxrxt;\n\n\t/* Initialize default path MTU. */\n\tasoc->pathmtu = sp->pathmtu;\n\n\t/* Set association default SACK delay */\n\tasoc->sackdelay = msecs_to_jiffies(sp->sackdelay);\n\tasoc->sackfreq = sp->sackfreq;\n\n\t/* Set the association default flags controlling\n\t * Heartbeat, SACK delay, and Path MTU Discovery.\n\t */\n\tasoc->param_flags = sp->param_flags;\n\n\t/* Initialize the maximum mumber of new data packets that can be sent\n\t * in a burst.\n\t */\n\tasoc->max_burst = sp->max_burst;\n\n\t/* initialize association timers */\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_NONE] = 0;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T3_RTX] = 0;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T4_RTO] = 0;\n\n\t/* sctpimpguide Section 2.12.2\n\t * If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the\n\t * recommended value of 5 times 'RTO.Max'.\n\t */\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]\n\t\t= 5 * asoc->rto_max;\n\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_HEARTBEAT] = 0;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay;\n\tasoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] =\n\t\tmin_t(unsigned long, sp->autoclose, net->sctp.max_autoclose) * HZ;\n\n\t/* Initializes the timers */\n\tfor (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i)\n\t\tsetup_timer(&asoc->timers[i], sctp_timer_events[i],\n\t\t\t\t(unsigned long)asoc);\n\n\t/* Pull default initialization values from the sock options.\n\t * Note: This assumes that the values have already been\n\t * validated in the sock.\n\t */\n\tasoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams;\n\tasoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams;\n\tasoc->max_init_attempts\t= sp->initmsg.sinit_max_attempts;\n\n\tasoc->max_init_timeo =\n\t\t msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo);\n\n\t/* Allocate storage for the ssnmap after the inbound and outbound\n\t * streams have been negotiated during Init.\n\t */\n\tasoc->ssnmap = NULL;\n\n\t/* Set the local window size for receive.\n\t * This is also the rcvbuf space per association.\n\t * RFC 6 - A SCTP receiver MUST be able to receive a minimum of\n\t * 1500 bytes in one SCTP packet.\n\t */\n\tif ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW)\n\t\tasoc->rwnd = SCTP_DEFAULT_MINWINDOW;\n\telse\n\t\tasoc->rwnd = sk->sk_rcvbuf/2;\n\n\tasoc->a_rwnd = asoc->rwnd;\n\n\tasoc->rwnd_over = 0;\n\tasoc->rwnd_press = 0;\n\n\t/* Use my own max window until I learn something better. */\n\tasoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW;\n\n\t/* Set the sndbuf size for transmit. */\n\tasoc->sndbuf_used = 0;\n\n\t/* Initialize the receive memory counter */\n\tatomic_set(&asoc->rmem_alloc, 0);\n\n\tinit_waitqueue_head(&asoc->wait);\n\n\tasoc->c.my_vtag = sctp_generate_tag(ep);\n\tasoc->peer.i.init_tag = 0; /* INIT needs a vtag of 0. */\n\tasoc->c.peer_vtag = 0;\n\tasoc->c.my_ttag = 0;\n\tasoc->c.peer_ttag = 0;\n\tasoc->c.my_port = ep->base.bind_addr.port;\n\n\tasoc->c.initial_tsn = sctp_generate_tsn(ep);\n\n\tasoc->next_tsn = asoc->c.initial_tsn;\n\n\tasoc->ctsn_ack_point = asoc->next_tsn - 1;\n\tasoc->adv_peer_ack_point = asoc->ctsn_ack_point;\n\tasoc->highest_sacked = asoc->ctsn_ack_point;\n\tasoc->last_cwr_tsn = asoc->ctsn_ack_point;\n\tasoc->unack_data = 0;\n\n\t/* ADDIP Section 4.1 Asconf Chunk Procedures\n\t *\n\t * When an endpoint has an ASCONF signaled change to be sent to the\n\t * remote endpoint it should do the following:\n\t * ...\n\t * A2) a serial number should be assigned to the chunk. The serial\n\t * number SHOULD be a monotonically increasing number. The serial\n\t * numbers SHOULD be initialized at the start of the\n\t * association to the same value as the initial TSN.\n\t */\n\tasoc->addip_serial = asoc->c.initial_tsn;\n\n\tINIT_LIST_HEAD(&asoc->addip_chunk_list);\n\tINIT_LIST_HEAD(&asoc->asconf_ack_list);\n\n\t/* Make an empty list of remote transport addresses. */\n\tINIT_LIST_HEAD(&asoc->peer.transport_addr_list);\n\tasoc->peer.transport_count = 0;\n\n\t/* RFC 2960 5.1 Normal Establishment of an Association\n\t *\n\t * After the reception of the first data chunk in an\n\t * association the endpoint must immediately respond with a\n\t * sack to acknowledge the data chunk. Subsequent\n\t * acknowledgements should be done as described in Section\n\t * 6.2.\n\t *\n\t * [We implement this by telling a new association that it\n\t * already received one packet.]\n\t */\n\tasoc->peer.sack_needed = 1;\n\tasoc->peer.sack_cnt = 0;\n\tasoc->peer.sack_generation = 1;\n\n\t/* Assume that the peer will tell us if he recognizes ASCONF\n\t * as part of INIT exchange.\n\t * The sctp_addip_noauth option is there for backward compatibilty\n\t * and will revert old behavior.\n\t */\n\tasoc->peer.asconf_capable = 0;\n\tif (net->sctp.addip_noauth)\n\t\tasoc->peer.asconf_capable = 1;\n\tasoc->asconf_addr_del_pending = NULL;\n\tasoc->src_out_of_asoc_ok = 0;\n\tasoc->new_transport = NULL;\n\n\t/* Create an input queue. */\n\tsctp_inq_init(&asoc->base.inqueue);\n\tsctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv);\n\n\t/* Create an output queue. */\n\tsctp_outq_init(asoc, &asoc->outqueue);\n\n\tif (!sctp_ulpq_init(&asoc->ulpq, asoc))\n\t\tgoto fail_init;\n\n\tmemset(&asoc->peer.tsn_map, 0, sizeof(struct sctp_tsnmap));\n\n\tasoc->need_ecne = 0;\n\n\tasoc->assoc_id = 0;\n\n\t/* Assume that peer would support both address types unless we are\n\t * told otherwise.\n\t */\n\tasoc->peer.ipv4_address = 1;\n\tif (asoc->base.sk->sk_family == PF_INET6)\n\t\tasoc->peer.ipv6_address = 1;\n\tINIT_LIST_HEAD(&asoc->asocs);\n\n\tasoc->autoclose = sp->autoclose;\n\n\tasoc->default_stream = sp->default_stream;\n\tasoc->default_ppid = sp->default_ppid;\n\tasoc->default_flags = sp->default_flags;\n\tasoc->default_context = sp->default_context;\n\tasoc->default_timetolive = sp->default_timetolive;\n\tasoc->default_rcv_context = sp->default_rcv_context;\n\n\t/* SCTP_GET_ASSOC_STATS COUNTERS */\n\tmemset(&asoc->stats, 0, sizeof(struct sctp_priv_assoc_stats));\n\n\t/* AUTH related initializations */\n\tINIT_LIST_HEAD(&asoc->endpoint_shared_keys);\n\terr = sctp_auth_asoc_copy_shkeys(ep, asoc, gfp);\n\tif (err)\n\t\tgoto fail_init;\n\n\tasoc->active_key_id = ep->active_key_id;\n\tasoc->asoc_shared_key = NULL;\n\n\tasoc->default_hmac_id = 0;\n\t/* Save the hmacs and chunks list into this association */\n\tif (ep->auth_hmacs_list)\n\t\tmemcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list,\n\t\t\tntohs(ep->auth_hmacs_list->param_hdr.length));\n\tif (ep->auth_chunk_list)\n\t\tmemcpy(asoc->c.auth_chunks, ep->auth_chunk_list,\n\t\t\tntohs(ep->auth_chunk_list->param_hdr.length));\n\n\t/* Get the AUTH random number for this association */\n\tp = (sctp_paramhdr_t *)asoc->c.auth_random;\n\tp->type = SCTP_PARAM_RANDOM;\n\tp->length = htons(sizeof(sctp_paramhdr_t) + SCTP_AUTH_RANDOM_LENGTH);\n\tget_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH);\n\n\treturn asoc;\n\nfail_init:\n\tsctp_endpoint_put(asoc->ep);\n\tsock_put(asoc->base.sk);\n\treturn NULL;\n}\n\n/* Allocate and initialize a new association */\nstruct sctp_association *sctp_association_new(const struct sctp_endpoint *ep,\n\t\t\t\t\t const struct sock *sk,\n\t\t\t\t\t sctp_scope_t scope,\n\t\t\t\t\t gfp_t gfp)\n{\n\tstruct sctp_association *asoc;\n\n\tasoc = t_new(struct sctp_association, gfp);\n\tif (!asoc)\n\t\tgoto fail;\n\n\tif (!sctp_association_init(asoc, ep, sk, scope, gfp))\n\t\tgoto fail_init;\n\n\tasoc->base.malloced = 1;\n\tSCTP_DBG_OBJCNT_INC(assoc);\n\tSCTP_DEBUG_PRINTK(\"Created asoc %p\\n\", asoc);\n\n\treturn asoc;\n\nfail_init:\n\tkfree(asoc);\nfail:\n\treturn NULL;\n}\n\n/* Free this association if possible. There may still be users, so\n * the actual deallocation may be delayed.\n */\nvoid sctp_association_free(struct sctp_association *asoc)\n{\n\tstruct sock *sk = asoc->base.sk;\n\tstruct sctp_transport *transport;\n\tstruct list_head *pos, *temp;\n\tint i;\n\n\t/* Only real associations count against the endpoint, so\n\t * don't bother for if this is a temporary association.\n\t */\n\tif (!asoc->temp) {\n\t\tlist_del(&asoc->asocs);\n\n\t\t/* Decrement the backlog value for a TCP-style listening\n\t\t * socket.\n\t\t */\n\t\tif (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))\n\t\t\tsk->sk_ack_backlog--;\n\t}\n\n\t/* Mark as dead, so other users can know this structure is\n\t * going away.\n\t */\n\tasoc->base.dead = 1;\n\n\t/* Dispose of any data lying around in the outqueue. */\n\tsctp_outq_free(&asoc->outqueue);\n\n\t/* Dispose of any pending messages for the upper layer. */\n\tsctp_ulpq_free(&asoc->ulpq);\n\n\t/* Dispose of any pending chunks on the inqueue. */\n\tsctp_inq_free(&asoc->base.inqueue);\n\n\tsctp_tsnmap_free(&asoc->peer.tsn_map);\n\n\t/* Free ssnmap storage. */\n\tsctp_ssnmap_free(asoc->ssnmap);\n\n\t/* Clean up the bound address list. */\n\tsctp_bind_addr_free(&asoc->base.bind_addr);\n\n\t/* Do we need to go through all of our timers and\n\t * delete them? To be safe we will try to delete all, but we\n\t * should be able to go through and make a guess based\n\t * on our state.\n\t */\n\tfor (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {\n\t\tif (timer_pending(&asoc->timers[i]) &&\n\t\t del_timer(&asoc->timers[i]))\n\t\t\tsctp_association_put(asoc);\n\t}\n\n\t/* Free peer's cached cookie. */\n\tkfree(asoc->peer.cookie);\n\tkfree(asoc->peer.peer_random);\n\tkfree(asoc->peer.peer_chunks);\n\tkfree(asoc->peer.peer_hmacs);\n\n\t/* Release the transport structures. */\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttransport = list_entry(pos, struct sctp_transport, transports);\n\t\tlist_del_rcu(pos);\n\t\tsctp_transport_free(transport);\n\t}\n\n\tasoc->peer.transport_count = 0;\n\n\tsctp_asconf_queue_teardown(asoc);\n\n\t/* Free pending address space being deleted */\n\tif (asoc->asconf_addr_del_pending != NULL)\n\t\tkfree(asoc->asconf_addr_del_pending);\n\n\t/* AUTH - Free the endpoint shared keys */\n\tsctp_auth_destroy_keys(&asoc->endpoint_shared_keys);\n\n\t/* AUTH - Free the association shared key */\n\tsctp_auth_key_put(asoc->asoc_shared_key);\n\n\tsctp_association_put(asoc);\n}\n\n/* Cleanup and free up an association. */\nstatic void sctp_association_destroy(struct sctp_association *asoc)\n{\n\tSCTP_ASSERT(asoc->base.dead, \"Assoc is not dead\", return);\n\n\tsctp_endpoint_put(asoc->ep);\n\tsock_put(asoc->base.sk);\n\n\tif (asoc->assoc_id != 0) {\n\t\tspin_lock_bh(&sctp_assocs_id_lock);\n\t\tidr_remove(&sctp_assocs_id, asoc->assoc_id);\n\t\tspin_unlock_bh(&sctp_assocs_id_lock);\n\t}\n\n\tWARN_ON(atomic_read(&asoc->rmem_alloc));\n\n\tif (asoc->base.malloced) {\n\t\tkfree(asoc);\n\t\tSCTP_DBG_OBJCNT_DEC(assoc);\n\t}\n}\n\n/* Change the primary destination address for the peer. */\nvoid sctp_assoc_set_primary(struct sctp_association *asoc,\n\t\t\t struct sctp_transport *transport)\n{\n\tint changeover = 0;\n\n\t/* it's a changeover only if we already have a primary path\n\t * that we are changing\n\t */\n\tif (asoc->peer.primary_path != NULL &&\n\t asoc->peer.primary_path != transport)\n\t\tchangeover = 1 ;\n\n\tasoc->peer.primary_path = transport;\n\n\t/* Set a default msg_name for events. */\n\tmemcpy(&asoc->peer.primary_addr, &transport->ipaddr,\n\t sizeof(union sctp_addr));\n\n\t/* If the primary path is changing, assume that the\n\t * user wants to use this new path.\n\t */\n\tif ((transport->state == SCTP_ACTIVE) ||\n\t (transport->state == SCTP_UNKNOWN))\n\t\tasoc->peer.active_path = transport;\n\n\t/*\n\t * SFR-CACC algorithm:\n\t * Upon the receipt of a request to change the primary\n\t * destination address, on the data structure for the new\n\t * primary destination, the sender MUST do the following:\n\t *\n\t * 1) If CHANGEOVER_ACTIVE is set, then there was a switch\n\t * to this destination address earlier. The sender MUST set\n\t * CYCLING_CHANGEOVER to indicate that this switch is a\n\t * double switch to the same destination address.\n\t *\n\t * Really, only bother is we have data queued or outstanding on\n\t * the association.\n\t */\n\tif (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen)\n\t\treturn;\n\n\tif (transport->cacc.changeover_active)\n\t\ttransport->cacc.cycling_changeover = changeover;\n\n\t/* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that\n\t * a changeover has occurred.\n\t */\n\ttransport->cacc.changeover_active = changeover;\n\n\t/* 3) The sender MUST store the next TSN to be sent in\n\t * next_tsn_at_change.\n\t */\n\ttransport->cacc.next_tsn_at_change = asoc->next_tsn;\n}\n\n/* Remove a transport from an association. */\nvoid sctp_assoc_rm_peer(struct sctp_association *asoc,\n\t\t\tstruct sctp_transport *peer)\n{\n\tstruct list_head\t*pos;\n\tstruct sctp_transport\t*transport;\n\n\tSCTP_DEBUG_PRINTK_IPADDR(\"sctp_assoc_rm_peer:association %p addr: \",\n\t\t\t\t \" port: %d\\n\",\n\t\t\t\t asoc,\n\t\t\t\t (&peer->ipaddr),\n\t\t\t\t ntohs(peer->ipaddr.v4.sin_port));\n\n\t/* If we are to remove the current retran_path, update it\n\t * to the next peer before removing this peer from the list.\n\t */\n\tif (asoc->peer.retran_path == peer)\n\t\tsctp_assoc_update_retran_path(asoc);\n\n\t/* Remove this peer from the list. */\n\tlist_del_rcu(&peer->transports);\n\n\t/* Get the first transport of asoc. */\n\tpos = asoc->peer.transport_addr_list.next;\n\ttransport = list_entry(pos, struct sctp_transport, transports);\n\n\t/* Update any entries that match the peer to be deleted. */\n\tif (asoc->peer.primary_path == peer)\n\t\tsctp_assoc_set_primary(asoc, transport);\n\tif (asoc->peer.active_path == peer)\n\t\tasoc->peer.active_path = transport;\n\tif (asoc->peer.retran_path == peer)\n\t\tasoc->peer.retran_path = transport;\n\tif (asoc->peer.last_data_from == peer)\n\t\tasoc->peer.last_data_from = transport;\n\n\t/* If we remove the transport an INIT was last sent to, set it to\n\t * NULL. Combined with the update of the retran path above, this\n\t * will cause the next INIT to be sent to the next available\n\t * transport, maintaining the cycle.\n\t */\n\tif (asoc->init_last_sent_to == peer)\n\t\tasoc->init_last_sent_to = NULL;\n\n\t/* If we remove the transport an SHUTDOWN was last sent to, set it\n\t * to NULL. Combined with the update of the retran path above, this\n\t * will cause the next SHUTDOWN to be sent to the next available\n\t * transport, maintaining the cycle.\n\t */\n\tif (asoc->shutdown_last_sent_to == peer)\n\t\tasoc->shutdown_last_sent_to = NULL;\n\n\t/* If we remove the transport an ASCONF was last sent to, set it to\n\t * NULL.\n\t */\n\tif (asoc->addip_last_asconf &&\n\t asoc->addip_last_asconf->transport == peer)\n\t\tasoc->addip_last_asconf->transport = NULL;\n\n\t/* If we have something on the transmitted list, we have to\n\t * save it off. The best place is the active path.\n\t */\n\tif (!list_empty(&peer->transmitted)) {\n\t\tstruct sctp_transport *active = asoc->peer.active_path;\n\t\tstruct sctp_chunk *ch;\n\n\t\t/* Reset the transport of each chunk on this list */\n\t\tlist_for_each_entry(ch, &peer->transmitted,\n\t\t\t\t\ttransmitted_list) {\n\t\t\tch->transport = NULL;\n\t\t\tch->rtt_in_progress = 0;\n\t\t}\n\n\t\tlist_splice_tail_init(&peer->transmitted,\n\t\t\t\t\t&active->transmitted);\n\n\t\t/* Start a T3 timer here in case it wasn't running so\n\t\t * that these migrated packets have a chance to get\n\t\t * retrnasmitted.\n\t\t */\n\t\tif (!timer_pending(&active->T3_rtx_timer))\n\t\t\tif (!mod_timer(&active->T3_rtx_timer,\n\t\t\t\t\tjiffies + active->rto))\n\t\t\t\tsctp_transport_hold(active);\n\t}\n\n\tasoc->peer.transport_count--;\n\n\tsctp_transport_free(peer);\n}\n\n/* Add a transport address to an association. */\nstruct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc,\n\t\t\t\t\t const union sctp_addr *addr,\n\t\t\t\t\t const gfp_t gfp,\n\t\t\t\t\t const int peer_state)\n{\n\tstruct net *net = sock_net(asoc->base.sk);\n\tstruct sctp_transport *peer;\n\tstruct sctp_sock *sp;\n\tunsigned short port;\n\n\tsp = sctp_sk(asoc->base.sk);\n\n\t/* AF_INET and AF_INET6 share common port field. */\n\tport = ntohs(addr->v4.sin_port);\n\n\tSCTP_DEBUG_PRINTK_IPADDR(\"sctp_assoc_add_peer:association %p addr: \",\n\t\t\t\t \" port: %d state:%d\\n\",\n\t\t\t\t asoc,\n\t\t\t\t addr,\n\t\t\t\t port,\n\t\t\t\t peer_state);\n\n\t/* Set the port if it has not been set yet. */\n\tif (0 == asoc->peer.port)\n\t\tasoc->peer.port = port;\n\n\t/* Check to see if this is a duplicate. */\n\tpeer = sctp_assoc_lookup_paddr(asoc, addr);\n\tif (peer) {\n\t\t/* An UNKNOWN state is only set on transports added by\n\t\t * user in sctp_connectx() call. Such transports should be\n\t\t * considered CONFIRMED per RFC 4960, Section 5.4.\n\t\t */\n\t\tif (peer->state == SCTP_UNKNOWN) {\n\t\t\tpeer->state = SCTP_ACTIVE;\n\t\t}\n\t\treturn peer;\n\t}\n\n\tpeer = sctp_transport_new(net, addr, gfp);\n\tif (!peer)\n\t\treturn NULL;\n\n\tsctp_transport_set_owner(peer, asoc);\n\n\t/* Initialize the peer's heartbeat interval based on the\n\t * association configured value.\n\t */\n\tpeer->hbinterval = asoc->hbinterval;\n\n\t/* Set the path max_retrans. */\n\tpeer->pathmaxrxt = asoc->pathmaxrxt;\n\n\t/* And the partial failure retrnas threshold */\n\tpeer->pf_retrans = asoc->pf_retrans;\n\n\t/* Initialize the peer's SACK delay timeout based on the\n\t * association configured value.\n\t */\n\tpeer->sackdelay = asoc->sackdelay;\n\tpeer->sackfreq = asoc->sackfreq;\n\n\t/* Enable/disable heartbeat, SACK delay, and path MTU discovery\n\t * based on association setting.\n\t */\n\tpeer->param_flags = asoc->param_flags;\n\n\tsctp_transport_route(peer, NULL, sp);\n\n\t/* Initialize the pmtu of the transport. */\n\tif (peer->param_flags & SPP_PMTUD_DISABLE) {\n\t\tif (asoc->pathmtu)\n\t\t\tpeer->pathmtu = asoc->pathmtu;\n\t\telse\n\t\t\tpeer->pathmtu = SCTP_DEFAULT_MAXSEGMENT;\n\t}\n\n\t/* If this is the first transport addr on this association,\n\t * initialize the association PMTU to the peer's PMTU.\n\t * If not and the current association PMTU is higher than the new\n\t * peer's PMTU, reset the association PMTU to the new peer's PMTU.\n\t */\n\tif (asoc->pathmtu)\n\t\tasoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu);\n\telse\n\t\tasoc->pathmtu = peer->pathmtu;\n\n\tSCTP_DEBUG_PRINTK(\"sctp_assoc_add_peer:association %p PMTU set to \"\n\t\t\t \"%d\\n\", asoc, asoc->pathmtu);\n\tpeer->pmtu_pending = 0;\n\n\tasoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);\n\n\t/* The asoc->peer.port might not be meaningful yet, but\n\t * initialize the packet structure anyway.\n\t */\n\tsctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port,\n\t\t\t asoc->peer.port);\n\n\t/* 7.2.1 Slow-Start\n\t *\n\t * o The initial cwnd before DATA transmission or after a sufficiently\n\t * long idle period MUST be set to\n\t * min(4*MTU, max(2*MTU, 4380 bytes))\n\t *\n\t * o The initial value of ssthresh MAY be arbitrarily high\n\t * (for example, implementations MAY use the size of the\n\t * receiver advertised window).\n\t */\n\tpeer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));\n\n\t/* At this point, we may not have the receiver's advertised window,\n\t * so initialize ssthresh to the default value and it will be set\n\t * later when we process the INIT.\n\t */\n\tpeer->ssthresh = SCTP_DEFAULT_MAXWINDOW;\n\n\tpeer->partial_bytes_acked = 0;\n\tpeer->flight_size = 0;\n\tpeer->burst_limited = 0;\n\n\t/* Set the transport's RTO.initial value */\n\tpeer->rto = asoc->rto_initial;\n\tsctp_max_rto(asoc, peer);\n\n\t/* Set the peer's active state. */\n\tpeer->state = peer_state;\n\n\t/* Attach the remote transport to our asoc. */\n\tlist_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list);\n\tasoc->peer.transport_count++;\n\n\t/* If we do not yet have a primary path, set one. */\n\tif (!asoc->peer.primary_path) {\n\t\tsctp_assoc_set_primary(asoc, peer);\n\t\tasoc->peer.retran_path = peer;\n\t}\n\n\tif (asoc->peer.active_path == asoc->peer.retran_path &&\n\t peer->state != SCTP_UNCONFIRMED) {\n\t\tasoc->peer.retran_path = peer;\n\t}\n\n\treturn peer;\n}\n\n/* Delete a transport address from an association. */\nvoid sctp_assoc_del_peer(struct sctp_association *asoc,\n\t\t\t const union sctp_addr *addr)\n{\n\tstruct list_head\t*pos;\n\tstruct list_head\t*temp;\n\tstruct sctp_transport\t*transport;\n\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttransport = list_entry(pos, struct sctp_transport, transports);\n\t\tif (sctp_cmp_addr_exact(addr, &transport->ipaddr)) {\n\t\t\t/* Do book keeping for removing the peer and free it. */\n\t\t\tsctp_assoc_rm_peer(asoc, transport);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n/* Lookup a transport by address. */\nstruct sctp_transport *sctp_assoc_lookup_paddr(\n\t\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\t\tconst union sctp_addr *address)\n{\n\tstruct sctp_transport *t;\n\n\t/* Cycle through all transports searching for a peer address. */\n\n\tlist_for_each_entry(t, &asoc->peer.transport_addr_list,\n\t\t\ttransports) {\n\t\tif (sctp_cmp_addr_exact(address, &t->ipaddr))\n\t\t\treturn t;\n\t}\n\n\treturn NULL;\n}\n\n/* Remove all transports except a give one */\nvoid sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc,\n\t\t\t\t struct sctp_transport *primary)\n{\n\tstruct sctp_transport\t*temp;\n\tstruct sctp_transport\t*t;\n\n\tlist_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list,\n\t\t\t\t transports) {\n\t\t/* if the current transport is not the primary one, delete it */\n\t\tif (t != primary)\n\t\t\tsctp_assoc_rm_peer(asoc, t);\n\t}\n}\n\n/* Engage in transport control operations.\n * Mark the transport up or down and send a notification to the user.\n * Select and update the new active and retran paths.\n */\nvoid sctp_assoc_control_transport(struct sctp_association *asoc,\n\t\t\t\t struct sctp_transport *transport,\n\t\t\t\t sctp_transport_cmd_t command,\n\t\t\t\t sctp_sn_error_t error)\n{\n\tstruct sctp_transport *t = NULL;\n\tstruct sctp_transport *first;\n\tstruct sctp_transport *second;\n\tstruct sctp_ulpevent *event;\n\tstruct sockaddr_storage addr;\n\tint spc_state = 0;\n\tbool ulp_notify = true;\n\n\t/* Record the transition on the transport. */\n\tswitch (command) {\n\tcase SCTP_TRANSPORT_UP:\n\t\t/* If we are moving from UNCONFIRMED state due\n\t\t * to heartbeat success, report the SCTP_ADDR_CONFIRMED\n\t\t * state to the user, otherwise report SCTP_ADDR_AVAILABLE.\n\t\t */\n\t\tif (SCTP_UNCONFIRMED == transport->state &&\n\t\t SCTP_HEARTBEAT_SUCCESS == error)\n\t\t\tspc_state = SCTP_ADDR_CONFIRMED;\n\t\telse\n\t\t\tspc_state = SCTP_ADDR_AVAILABLE;\n\t\t/* Don't inform ULP about transition from PF to\n\t\t * active state and set cwnd to 1, see SCTP\n\t\t * Quick failover draft section 5.1, point 5\n\t\t */\n\t\tif (transport->state == SCTP_PF) {\n\t\t\tulp_notify = false;\n\t\t\ttransport->cwnd = 1;\n\t\t}\n\t\ttransport->state = SCTP_ACTIVE;\n\t\tbreak;\n\n\tcase SCTP_TRANSPORT_DOWN:\n\t\t/* If the transport was never confirmed, do not transition it\n\t\t * to inactive state. Also, release the cached route since\n\t\t * there may be a better route next time.\n\t\t */\n\t\tif (transport->state != SCTP_UNCONFIRMED)\n\t\t\ttransport->state = SCTP_INACTIVE;\n\t\telse {\n\t\t\tdst_release(transport->dst);\n\t\t\ttransport->dst = NULL;\n\t\t}\n\n\t\tspc_state = SCTP_ADDR_UNREACHABLE;\n\t\tbreak;\n\n\tcase SCTP_TRANSPORT_PF:\n\t\ttransport->state = SCTP_PF;\n\t\tulp_notify = false;\n\t\tbreak;\n\n\tdefault:\n\t\treturn;\n\t}\n\n\t/* Generate and send a SCTP_PEER_ADDR_CHANGE notification to the\n\t * user.\n\t */\n\tif (ulp_notify) {\n\t\tmemset(&addr, 0, sizeof(struct sockaddr_storage));\n\t\tmemcpy(&addr, &transport->ipaddr,\n\t\t transport->af_specific->sockaddr_len);\n\t\tevent = sctp_ulpevent_make_peer_addr_change(asoc, &addr,\n\t\t\t\t\t0, spc_state, error, GFP_ATOMIC);\n\t\tif (event)\n\t\t\tsctp_ulpq_tail_event(&asoc->ulpq, event);\n\t}\n\n\t/* Select new active and retran paths. */\n\n\t/* Look for the two most recently used active transports.\n\t *\n\t * This code produces the wrong ordering whenever jiffies\n\t * rolls over, but we still get usable transports, so we don't\n\t * worry about it.\n\t */\n\tfirst = NULL; second = NULL;\n\n\tlist_for_each_entry(t, &asoc->peer.transport_addr_list,\n\t\t\ttransports) {\n\n\t\tif ((t->state == SCTP_INACTIVE) ||\n\t\t (t->state == SCTP_UNCONFIRMED) ||\n\t\t (t->state == SCTP_PF))\n\t\t\tcontinue;\n\t\tif (!first || t->last_time_heard > first->last_time_heard) {\n\t\t\tsecond = first;\n\t\t\tfirst = t;\n\t\t}\n\t\tif (!second || t->last_time_heard > second->last_time_heard)\n\t\t\tsecond = t;\n\t}\n\n\t/* RFC 2960 6.4 Multi-Homed SCTP Endpoints\n\t *\n\t * By default, an endpoint should always transmit to the\n\t * primary path, unless the SCTP user explicitly specifies the\n\t * destination transport address (and possibly source\n\t * transport address) to use.\n\t *\n\t * [If the primary is active but not most recent, bump the most\n\t * recently used transport.]\n\t */\n\tif (((asoc->peer.primary_path->state == SCTP_ACTIVE) ||\n\t (asoc->peer.primary_path->state == SCTP_UNKNOWN)) &&\n\t first != asoc->peer.primary_path) {\n\t\tsecond = first;\n\t\tfirst = asoc->peer.primary_path;\n\t}\n\n\t/* If we failed to find a usable transport, just camp on the\n\t * primary, even if it is inactive.\n\t */\n\tif (!first) {\n\t\tfirst = asoc->peer.primary_path;\n\t\tsecond = asoc->peer.primary_path;\n\t}\n\n\t/* Set the active and retran transports. */\n\tasoc->peer.active_path = first;\n\tasoc->peer.retran_path = second;\n}\n\n/* Hold a reference to an association. */\nvoid sctp_association_hold(struct sctp_association *asoc)\n{\n\tatomic_inc(&asoc->base.refcnt);\n}\n\n/* Release a reference to an association and cleanup\n * if there are no more references.\n */\nvoid sctp_association_put(struct sctp_association *asoc)\n{\n\tif (atomic_dec_and_test(&asoc->base.refcnt))\n\t\tsctp_association_destroy(asoc);\n}\n\n/* Allocate the next TSN, Transmission Sequence Number, for the given\n * association.\n */\n__u32 sctp_association_get_next_tsn(struct sctp_association *asoc)\n{\n\t/* From Section 1.6 Serial Number Arithmetic:\n\t * Transmission Sequence Numbers wrap around when they reach\n\t * 2**32 - 1. That is, the next TSN a DATA chunk MUST use\n\t * after transmitting TSN = 2*32 - 1 is TSN = 0.\n\t */\n\t__u32 retval = asoc->next_tsn;\n\tasoc->next_tsn++;\n\tasoc->unack_data++;\n\n\treturn retval;\n}\n\n/* Compare two addresses to see if they match. Wildcard addresses\n * only match themselves.\n */\nint sctp_cmp_addr_exact(const union sctp_addr *ss1,\n\t\t\tconst union sctp_addr *ss2)\n{\n\tstruct sctp_af *af;\n\n\taf = sctp_get_af_specific(ss1->sa.sa_family);\n\tif (unlikely(!af))\n\t\treturn 0;\n\n\treturn af->cmp_addr(ss1, ss2);\n}\n\n/* Return an ecne chunk to get prepended to a packet.\n * Note: We are sly and return a shared, prealloced chunk. FIXME:\n * No we don't, but we could/should.\n */\nstruct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc)\n{\n\tstruct sctp_chunk *chunk;\n\n\t/* Send ECNE if needed.\n\t * Not being able to allocate a chunk here is not deadly.\n\t */\n\tif (asoc->need_ecne)\n\t\tchunk = sctp_make_ecne(asoc, asoc->last_ecne_tsn);\n\telse\n\t\tchunk = NULL;\n\n\treturn chunk;\n}\n\n/*\n * Find which transport this TSN was sent on.\n */\nstruct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc,\n\t\t\t\t\t __u32 tsn)\n{\n\tstruct sctp_transport *active;\n\tstruct sctp_transport *match;\n\tstruct sctp_transport *transport;\n\tstruct sctp_chunk *chunk;\n\t__be32 key = htonl(tsn);\n\n\tmatch = NULL;\n\n\t/*\n\t * FIXME: In general, find a more efficient data structure for\n\t * searching.\n\t */\n\n\t/*\n\t * The general strategy is to search each transport's transmitted\n\t * list. Return which transport this TSN lives on.\n\t *\n\t * Let's be hopeful and check the active_path first.\n\t * Another optimization would be to know if there is only one\n\t * outbound path and not have to look for the TSN at all.\n\t *\n\t */\n\n\tactive = asoc->peer.active_path;\n\n\tlist_for_each_entry(chunk, &active->transmitted,\n\t\t\ttransmitted_list) {\n\n\t\tif (key == chunk->subh.data_hdr->tsn) {\n\t\t\tmatch = active;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\t/* If not found, go search all the other transports. */\n\tlist_for_each_entry(transport, &asoc->peer.transport_addr_list,\n\t\t\ttransports) {\n\n\t\tif (transport == active)\n\t\t\tbreak;\n\t\tlist_for_each_entry(chunk, &transport->transmitted,\n\t\t\t\ttransmitted_list) {\n\t\t\tif (key == chunk->subh.data_hdr->tsn) {\n\t\t\t\tmatch = transport;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t}\nout:\n\treturn match;\n}\n\n/* Is this the association we are looking for? */\nstruct sctp_transport *sctp_assoc_is_match(struct sctp_association *asoc,\n\t\t\t\t\t struct net *net,\n\t\t\t\t\t const union sctp_addr *laddr,\n\t\t\t\t\t const union sctp_addr *paddr)\n{\n\tstruct sctp_transport *transport;\n\n\tif ((htons(asoc->base.bind_addr.port) == laddr->v4.sin_port) &&\n\t (htons(asoc->peer.port) == paddr->v4.sin_port) &&\n\t net_eq(sock_net(asoc->base.sk), net)) {\n\t\ttransport = sctp_assoc_lookup_paddr(asoc, paddr);\n\t\tif (!transport)\n\t\t\tgoto out;\n\n\t\tif (sctp_bind_addr_match(&asoc->base.bind_addr, laddr,\n\t\t\t\t\t sctp_sk(asoc->base.sk)))\n\t\t\tgoto out;\n\t}\n\ttransport = NULL;\n\nout:\n\treturn transport;\n}\n\n/* Do delayed input processing. This is scheduled by sctp_rcv(). */\nstatic void sctp_assoc_bh_rcv(struct work_struct *work)\n{\n\tstruct sctp_association *asoc =\n\t\tcontainer_of(work, struct sctp_association,\n\t\t\t base.inqueue.immediate);\n\tstruct net *net = sock_net(asoc->base.sk);\n\tstruct sctp_endpoint *ep;\n\tstruct sctp_chunk *chunk;\n\tstruct sctp_inq *inqueue;\n\tint state;\n\tsctp_subtype_t subtype;\n\tint error = 0;\n\n\t/* The association should be held so we should be safe. */\n\tep = asoc->ep;\n\n\tinqueue = &asoc->base.inqueue;\n\tsctp_association_hold(asoc);\n\twhile (NULL != (chunk = sctp_inq_pop(inqueue))) {\n\t\tstate = asoc->state;\n\t\tsubtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);\n\n\t\t/* SCTP-AUTH, Section 6.3:\n\t\t * The receiver has a list of chunk types which it expects\n\t\t * to be received only after an AUTH-chunk. This list has\n\t\t * been sent to the peer during the association setup. It\n\t\t * MUST silently discard these chunks if they are not placed\n\t\t * after an AUTH chunk in the packet.\n\t\t */\n\t\tif (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)\n\t\t\tcontinue;\n\n\t\t/* Remember where the last DATA chunk came from so we\n\t\t * know where to send the SACK.\n\t\t */\n\t\tif (sctp_chunk_is_data(chunk))\n\t\t\tasoc->peer.last_data_from = chunk->transport;\n\t\telse {\n\t\t\tSCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS);\n\t\t\tasoc->stats.ictrlchunks++;\n\t\t\tif (chunk->chunk_hdr->type == SCTP_CID_SACK)\n\t\t\t\tasoc->stats.isacks++;\n\t\t}\n\n\t\tif (chunk->transport)\n\t\t\tchunk->transport->last_time_heard = jiffies;\n\n\t\t/* Run through the state machine. */\n\t\terror = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype,\n\t\t\t\t state, ep, asoc, chunk, GFP_ATOMIC);\n\n\t\t/* Check to see if the association is freed in response to\n\t\t * the incoming chunk. If so, get out of the while loop.\n\t\t */\n\t\tif (asoc->base.dead)\n\t\t\tbreak;\n\n\t\t/* If there is an error on chunk, discard this packet. */\n\t\tif (error && chunk)\n\t\t\tchunk->pdiscard = 1;\n\t}\n\tsctp_association_put(asoc);\n}\n\n/* This routine moves an association from its old sk to a new sk. */\nvoid sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk)\n{\n\tstruct sctp_sock *newsp = sctp_sk(newsk);\n\tstruct sock *oldsk = assoc->base.sk;\n\n\t/* Delete the association from the old endpoint's list of\n\t * associations.\n\t */\n\tlist_del_init(&assoc->asocs);\n\n\t/* Decrement the backlog value for a TCP-style socket. */\n\tif (sctp_style(oldsk, TCP))\n\t\toldsk->sk_ack_backlog--;\n\n\t/* Release references to the old endpoint and the sock. */\n\tsctp_endpoint_put(assoc->ep);\n\tsock_put(assoc->base.sk);\n\n\t/* Get a reference to the new endpoint. */\n\tassoc->ep = newsp->ep;\n\tsctp_endpoint_hold(assoc->ep);\n\n\t/* Get a reference to the new sock. */\n\tassoc->base.sk = newsk;\n\tsock_hold(assoc->base.sk);\n\n\t/* Add the association to the new endpoint's list of associations. */\n\tsctp_endpoint_add_asoc(newsp->ep, assoc);\n}\n\n/* Update an association (possibly from unexpected COOKIE-ECHO processing). */\nvoid sctp_assoc_update(struct sctp_association *asoc,\n\t\t struct sctp_association *new)\n{\n\tstruct sctp_transport *trans;\n\tstruct list_head *pos, *temp;\n\n\t/* Copy in new parameters of peer. */\n\tasoc->c = new->c;\n\tasoc->peer.rwnd = new->peer.rwnd;\n\tasoc->peer.sack_needed = new->peer.sack_needed;\n\tasoc->peer.i = new->peer.i;\n\tsctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,\n\t\t\t asoc->peer.i.initial_tsn, GFP_ATOMIC);\n\n\t/* Remove any peer addresses not present in the new association. */\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttrans = list_entry(pos, struct sctp_transport, transports);\n\t\tif (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {\n\t\t\tsctp_assoc_rm_peer(asoc, trans);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (asoc->state >= SCTP_STATE_ESTABLISHED)\n\t\t\tsctp_transport_reset(trans);\n\t}\n\n\t/* If the case is A (association restart), use\n\t * initial_tsn as next_tsn. If the case is B, use\n\t * current next_tsn in case data sent to peer\n\t * has been discarded and needs retransmission.\n\t */\n\tif (asoc->state >= SCTP_STATE_ESTABLISHED) {\n\t\tasoc->next_tsn = new->next_tsn;\n\t\tasoc->ctsn_ack_point = new->ctsn_ack_point;\n\t\tasoc->adv_peer_ack_point = new->adv_peer_ack_point;\n\n\t\t/* Reinitialize SSN for both local streams\n\t\t * and peer's streams.\n\t\t */\n\t\tsctp_ssnmap_clear(asoc->ssnmap);\n\n\t\t/* Flush the ULP reassembly and ordered queue.\n\t\t * Any data there will now be stale and will\n\t\t * cause problems.\n\t\t */\n\t\tsctp_ulpq_flush(&asoc->ulpq);\n\n\t\t/* reset the overall association error count so\n\t\t * that the restarted association doesn't get torn\n\t\t * down on the next retransmission timer.\n\t\t */\n\t\tasoc->overall_error_count = 0;\n\n\t} else {\n\t\t/* Add any peer addresses from the new association. */\n\t\tlist_for_each_entry(trans, &new->peer.transport_addr_list,\n\t\t\t\ttransports) {\n\t\t\tif (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))\n\t\t\t\tsctp_assoc_add_peer(asoc, &trans->ipaddr,\n\t\t\t\t\t\t GFP_ATOMIC, trans->state);\n\t\t}\n\n\t\tasoc->ctsn_ack_point = asoc->next_tsn - 1;\n\t\tasoc->adv_peer_ack_point = asoc->ctsn_ack_point;\n\t\tif (!asoc->ssnmap) {\n\t\t\t/* Move the ssnmap. */\n\t\t\tasoc->ssnmap = new->ssnmap;\n\t\t\tnew->ssnmap = NULL;\n\t\t}\n\n\t\tif (!asoc->assoc_id) {\n\t\t\t/* get a new association id since we don't have one\n\t\t\t * yet.\n\t\t\t */\n\t\t\tsctp_assoc_set_id(asoc, GFP_ATOMIC);\n\t\t}\n\t}\n\n\t/* SCTP-AUTH: Save the peer parameters from the new assocaitions\n\t * and also move the association shared keys over\n\t */\n\tkfree(asoc->peer.peer_random);\n\tasoc->peer.peer_random = new->peer.peer_random;\n\tnew->peer.peer_random = NULL;\n\n\tkfree(asoc->peer.peer_chunks);\n\tasoc->peer.peer_chunks = new->peer.peer_chunks;\n\tnew->peer.peer_chunks = NULL;\n\n\tkfree(asoc->peer.peer_hmacs);\n\tasoc->peer.peer_hmacs = new->peer.peer_hmacs;\n\tnew->peer.peer_hmacs = NULL;\n\n\tsctp_auth_key_put(asoc->asoc_shared_key);\n\tsctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);\n}\n\n/* Update the retran path for sending a retransmitted packet.\n * Round-robin through the active transports, else round-robin\n * through the inactive transports as this is the next best thing\n * we can try.\n */\nvoid sctp_assoc_update_retran_path(struct sctp_association *asoc)\n{\n\tstruct sctp_transport *t, *next;\n\tstruct list_head *head = &asoc->peer.transport_addr_list;\n\tstruct list_head *pos;\n\n\tif (asoc->peer.transport_count == 1)\n\t\treturn;\n\n\t/* Find the next transport in a round-robin fashion. */\n\tt = asoc->peer.retran_path;\n\tpos = &t->transports;\n\tnext = NULL;\n\n\twhile (1) {\n\t\t/* Skip the head. */\n\t\tif (pos->next == head)\n\t\t\tpos = head->next;\n\t\telse\n\t\t\tpos = pos->next;\n\n\t\tt = list_entry(pos, struct sctp_transport, transports);\n\n\t\t/* We have exhausted the list, but didn't find any\n\t\t * other active transports. If so, use the next\n\t\t * transport.\n\t\t */\n\t\tif (t == asoc->peer.retran_path) {\n\t\t\tt = next;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Try to find an active transport. */\n\n\t\tif ((t->state == SCTP_ACTIVE) ||\n\t\t (t->state == SCTP_UNKNOWN)) {\n\t\t\tbreak;\n\t\t} else {\n\t\t\t/* Keep track of the next transport in case\n\t\t\t * we don't find any active transport.\n\t\t\t */\n\t\t\tif (t->state != SCTP_UNCONFIRMED && !next)\n\t\t\t\tnext = t;\n\t\t}\n\t}\n\n\tif (t)\n\t\tasoc->peer.retran_path = t;\n\telse\n\t\tt = asoc->peer.retran_path;\n\n\tSCTP_DEBUG_PRINTK_IPADDR(\"sctp_assoc_update_retran_path:association\"\n\t\t\t\t \" %p addr: \",\n\t\t\t\t \" port: %d\\n\",\n\t\t\t\t asoc,\n\t\t\t\t (&t->ipaddr),\n\t\t\t\t ntohs(t->ipaddr.v4.sin_port));\n}\n\n/* Choose the transport for sending retransmit packet. */\nstruct sctp_transport *sctp_assoc_choose_alter_transport(\n\tstruct sctp_association *asoc, struct sctp_transport *last_sent_to)\n{\n\t/* If this is the first time packet is sent, use the active path,\n\t * else use the retran path. If the last packet was sent over the\n\t * retran path, update the retran path and use it.\n\t */\n\tif (!last_sent_to)\n\t\treturn asoc->peer.active_path;\n\telse {\n\t\tif (last_sent_to == asoc->peer.retran_path)\n\t\t\tsctp_assoc_update_retran_path(asoc);\n\t\treturn asoc->peer.retran_path;\n\t}\n}\n\n/* Update the association's pmtu and frag_point by going through all the\n * transports. This routine is called when a transport's PMTU has changed.\n */\nvoid sctp_assoc_sync_pmtu(struct sock *sk, struct sctp_association *asoc)\n{\n\tstruct sctp_transport *t;\n\t__u32 pmtu = 0;\n\n\tif (!asoc)\n\t\treturn;\n\n\t/* Get the lowest pmtu of all the transports. */\n\tlist_for_each_entry(t, &asoc->peer.transport_addr_list,\n\t\t\t\ttransports) {\n\t\tif (t->pmtu_pending && t->dst) {\n\t\t\tsctp_transport_update_pmtu(sk, t, dst_mtu(t->dst));\n\t\t\tt->pmtu_pending = 0;\n\t\t}\n\t\tif (!pmtu || (t->pathmtu < pmtu))\n\t\t\tpmtu = t->pathmtu;\n\t}\n\n\tif (pmtu) {\n\t\tasoc->pathmtu = pmtu;\n\t\tasoc->frag_point = sctp_frag_point(asoc, pmtu);\n\t}\n\n\tSCTP_DEBUG_PRINTK(\"%s: asoc:%p, pmtu:%d, frag_point:%d\\n\",\n\t\t\t __func__, asoc, asoc->pathmtu, asoc->frag_point);\n}\n\n/* Should we send a SACK to update our peer? */\nstatic inline int sctp_peer_needs_update(struct sctp_association *asoc)\n{\n\tstruct net *net = sock_net(asoc->base.sk);\n\tswitch (asoc->state) {\n\tcase SCTP_STATE_ESTABLISHED:\n\tcase SCTP_STATE_SHUTDOWN_PENDING:\n\tcase SCTP_STATE_SHUTDOWN_RECEIVED:\n\tcase SCTP_STATE_SHUTDOWN_SENT:\n\t\tif ((asoc->rwnd > asoc->a_rwnd) &&\n\t\t ((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32,\n\t\t\t (asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift),\n\t\t\t asoc->pathmtu)))\n\t\t\treturn 1;\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\treturn 0;\n}\n\n/* Increase asoc's rwnd by len and send any window update SACK if needed. */\nvoid sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len)\n{\n\tstruct sctp_chunk *sack;\n\tstruct timer_list *timer;\n\n\tif (asoc->rwnd_over) {\n\t\tif (asoc->rwnd_over >= len) {\n\t\t\tasoc->rwnd_over -= len;\n\t\t} else {\n\t\t\tasoc->rwnd += (len - asoc->rwnd_over);\n\t\t\tasoc->rwnd_over = 0;\n\t\t}\n\t} else {\n\t\tasoc->rwnd += len;\n\t}\n\n\t/* If we had window pressure, start recovering it\n\t * once our rwnd had reached the accumulated pressure\n\t * threshold. The idea is to recover slowly, but up\n\t * to the initial advertised window.\n\t */\n\tif (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) {\n\t\tint change = min(asoc->pathmtu, asoc->rwnd_press);\n\t\tasoc->rwnd += change;\n\t\tasoc->rwnd_press -= change;\n\t}\n\n\tSCTP_DEBUG_PRINTK(\"%s: asoc %p rwnd increased by %d to (%u, %u) \"\n\t\t\t \"- %u\\n\", __func__, asoc, len, asoc->rwnd,\n\t\t\t asoc->rwnd_over, asoc->a_rwnd);\n\n\t/* Send a window update SACK if the rwnd has increased by at least the\n\t * minimum of the association's PMTU and half of the receive buffer.\n\t * The algorithm used is similar to the one described in\n\t * Section 4.2.3.3 of RFC 1122.\n\t */\n\tif (sctp_peer_needs_update(asoc)) {\n\t\tasoc->a_rwnd = asoc->rwnd;\n\t\tSCTP_DEBUG_PRINTK(\"%s: Sending window update SACK- asoc: %p \"\n\t\t\t\t \"rwnd: %u a_rwnd: %u\\n\", __func__,\n\t\t\t\t asoc, asoc->rwnd, asoc->a_rwnd);\n\t\tsack = sctp_make_sack(asoc);\n\t\tif (!sack)\n\t\t\treturn;\n\n\t\tasoc->peer.sack_needed = 0;\n\n\t\tsctp_outq_tail(&asoc->outqueue, sack);\n\n\t\t/* Stop the SACK timer. */\n\t\ttimer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];\n\t\tif (timer_pending(timer) && del_timer(timer))\n\t\t\tsctp_association_put(asoc);\n\t}\n}\n\n/* Decrease asoc's rwnd by len. */\nvoid sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len)\n{\n\tint rx_count;\n\tint over = 0;\n\n\tSCTP_ASSERT(asoc->rwnd, \"rwnd zero\", return);\n\tSCTP_ASSERT(!asoc->rwnd_over, \"rwnd_over not zero\", return);\n\n\tif (asoc->ep->rcvbuf_policy)\n\t\trx_count = atomic_read(&asoc->rmem_alloc);\n\telse\n\t\trx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);\n\n\t/* If we've reached or overflowed our receive buffer, announce\n\t * a 0 rwnd if rwnd would still be positive. Store the\n\t * the pottential pressure overflow so that the window can be restored\n\t * back to original value.\n\t */\n\tif (rx_count >= asoc->base.sk->sk_rcvbuf)\n\t\tover = 1;\n\n\tif (asoc->rwnd >= len) {\n\t\tasoc->rwnd -= len;\n\t\tif (over) {\n\t\t\tasoc->rwnd_press += asoc->rwnd;\n\t\t\tasoc->rwnd = 0;\n\t\t}\n\t} else {\n\t\tasoc->rwnd_over = len - asoc->rwnd;\n\t\tasoc->rwnd = 0;\n\t}\n\tSCTP_DEBUG_PRINTK(\"%s: asoc %p rwnd decreased by %d to (%u, %u, %u)\\n\",\n\t\t\t __func__, asoc, len, asoc->rwnd,\n\t\t\t asoc->rwnd_over, asoc->rwnd_press);\n}\n\n/* Build the bind address list for the association based on info from the\n * local endpoint and the remote peer.\n */\nint sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc,\n\t\t\t\t sctp_scope_t scope, gfp_t gfp)\n{\n\tint flags;\n\n\t/* Use scoping rules to determine the subset of addresses from\n\t * the endpoint.\n\t */\n\tflags = (PF_INET6 == asoc->base.sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0;\n\tif (asoc->peer.ipv4_address)\n\t\tflags |= SCTP_ADDR4_PEERSUPP;\n\tif (asoc->peer.ipv6_address)\n\t\tflags |= SCTP_ADDR6_PEERSUPP;\n\n\treturn sctp_bind_addr_copy(sock_net(asoc->base.sk),\n\t\t\t\t &asoc->base.bind_addr,\n\t\t\t\t &asoc->ep->base.bind_addr,\n\t\t\t\t scope, gfp, flags);\n}\n\n/* Build the association's bind address list from the cookie. */\nint sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc,\n\t\t\t\t\t struct sctp_cookie *cookie,\n\t\t\t\t\t gfp_t gfp)\n{\n\tint var_size2 = ntohs(cookie->peer_init->chunk_hdr.length);\n\tint var_size3 = cookie->raw_addr_list_len;\n\t__u8 *raw = (__u8 *)cookie->peer_init + var_size2;\n\n\treturn sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3,\n\t\t\t\t asoc->ep->base.bind_addr.port, gfp);\n}\n\n/* Lookup laddr in the bind address list of an association. */\nint sctp_assoc_lookup_laddr(struct sctp_association *asoc,\n\t\t\t const union sctp_addr *laddr)\n{\n\tint found = 0;\n\n\tif ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) &&\n\t sctp_bind_addr_match(&asoc->base.bind_addr, laddr,\n\t\t\t\t sctp_sk(asoc->base.sk)))\n\t\tfound = 1;\n\n\treturn found;\n}\n\n/* Set an association id for a given association */\nint sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp)\n{\n\tint assoc_id;\n\tint error = 0;\n\n\t/* If the id is already assigned, keep it. */\n\tif (asoc->assoc_id)\n\t\treturn error;\nretry:\n\tif (unlikely(!idr_pre_get(&sctp_assocs_id, gfp)))\n\t\treturn -ENOMEM;\n\n\tspin_lock_bh(&sctp_assocs_id_lock);\n\terror = idr_get_new_above(&sctp_assocs_id, (void *)asoc,\n\t\t\t\t idr_low, &assoc_id);\n\tif (!error) {\n\t\tidr_low = assoc_id + 1;\n\t\tif (idr_low == INT_MAX)\n\t\t\tidr_low = 1;\n\t}\n\tspin_unlock_bh(&sctp_assocs_id_lock);\n\tif (error == -EAGAIN)\n\t\tgoto retry;\n\telse if (error)\n\t\treturn error;\n\n\tasoc->assoc_id = (sctp_assoc_t) assoc_id;\n\treturn error;\n}\n\n/* Free the ASCONF queue */\nstatic void sctp_assoc_free_asconf_queue(struct sctp_association *asoc)\n{\n\tstruct sctp_chunk *asconf;\n\tstruct sctp_chunk *tmp;\n\n\tlist_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) {\n\t\tlist_del_init(&asconf->list);\n\t\tsctp_chunk_free(asconf);\n\t}\n}\n\n/* Free asconf_ack cache */\nstatic void sctp_assoc_free_asconf_acks(struct sctp_association *asoc)\n{\n\tstruct sctp_chunk *ack;\n\tstruct sctp_chunk *tmp;\n\n\tlist_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,\n\t\t\t\ttransmitted_list) {\n\t\tlist_del_init(&ack->transmitted_list);\n\t\tsctp_chunk_free(ack);\n\t}\n}\n\n/* Clean up the ASCONF_ACK queue */\nvoid sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc)\n{\n\tstruct sctp_chunk *ack;\n\tstruct sctp_chunk *tmp;\n\n\t/* We can remove all the entries from the queue up to\n\t * the \"Peer-Sequence-Number\".\n\t */\n\tlist_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,\n\t\t\t\ttransmitted_list) {\n\t\tif (ack->subh.addip_hdr->serial ==\n\t\t\t\thtonl(asoc->peer.addip_serial))\n\t\t\tbreak;\n\n\t\tlist_del_init(&ack->transmitted_list);\n\t\tsctp_chunk_free(ack);\n\t}\n}\n\n/* Find the ASCONF_ACK whose serial number matches ASCONF */\nstruct sctp_chunk *sctp_assoc_lookup_asconf_ack(\n\t\t\t\t\tconst struct sctp_association *asoc,\n\t\t\t\t\t__be32 serial)\n{\n\tstruct sctp_chunk *ack;\n\n\t/* Walk through the list of cached ASCONF-ACKs and find the\n\t * ack chunk whose serial number matches that of the request.\n\t */\n\tlist_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {\n\t\tif (ack->subh.addip_hdr->serial == serial) {\n\t\t\tsctp_chunk_hold(ack);\n\t\t\treturn ack;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nvoid sctp_asconf_queue_teardown(struct sctp_association *asoc)\n{\n\t/* Free any cached ASCONF_ACK chunk. */\n\tsctp_assoc_free_asconf_acks(asoc);\n\n\t/* Free the ASCONF queue. */\n\tsctp_assoc_free_asconf_queue(asoc);\n\n\t/* Free any cached ASCONF chunk. */\n\tif (asoc->addip_last_asconf)\n\t\tsctp_chunk_free(asoc->addip_last_asconf);\n}\n"},"repo_name":{"kind":"string","value":"Webee-IOT/webee210-linux-kernel-3.8"},"path":{"kind":"string","value":"net/sctp/associola.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":48370,"string":"48,370"}}},{"rowIdx":115086582,"cells":{"code":{"kind":"string","value":"dataRange = $dataRange;\n }\n public function getDataRange()\n {\n return $this->dataRange;\n }\n public function setFormat($format)\n {\n $this->format = $format;\n }\n public function getFormat()\n {\n return $this->format;\n }\n public function setGoogleCloudStoragePathForLatestReport($googleCloudStoragePathForLatestReport)\n {\n $this->googleCloudStoragePathForLatestReport = $googleCloudStoragePathForLatestReport;\n }\n public function getGoogleCloudStoragePathForLatestReport()\n {\n return $this->googleCloudStoragePathForLatestReport;\n }\n public function setGoogleDrivePathForLatestReport($googleDrivePathForLatestReport)\n {\n $this->googleDrivePathForLatestReport = $googleDrivePathForLatestReport;\n }\n public function getGoogleDrivePathForLatestReport()\n {\n return $this->googleDrivePathForLatestReport;\n }\n public function setLatestReportRunTimeMs($latestReportRunTimeMs)\n {\n $this->latestReportRunTimeMs = $latestReportRunTimeMs;\n }\n public function getLatestReportRunTimeMs()\n {\n return $this->latestReportRunTimeMs;\n }\n public function setLocale($locale)\n {\n $this->locale = $locale;\n }\n public function getLocale()\n {\n return $this->locale;\n }\n public function setReportCount($reportCount)\n {\n $this->reportCount = $reportCount;\n }\n public function getReportCount()\n {\n return $this->reportCount;\n }\n public function setRunning($running)\n {\n $this->running = $running;\n }\n public function getRunning()\n {\n return $this->running;\n }\n public function setSendNotification($sendNotification)\n {\n $this->sendNotification = $sendNotification;\n }\n public function getSendNotification()\n {\n return $this->sendNotification;\n }\n public function setShareEmailAddress($shareEmailAddress)\n {\n $this->shareEmailAddress = $shareEmailAddress;\n }\n public function getShareEmailAddress()\n {\n return $this->shareEmailAddress;\n }\n public function setTitle($title)\n {\n $this->title = $title;\n }\n public function getTitle()\n {\n return $this->title;\n }\n}\n"},"repo_name":{"kind":"string","value":"drthomas21/WordPress_Tutorial"},"path":{"kind":"string","value":"wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/DoubleClickBidManager/QueryMetadata.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":3146,"string":"3,146"}}},{"rowIdx":115086584,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2000-2009 JetBrains s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.intellij.openapi.vcs.changes.ui;\n\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.extensions.ExtensionPointName;\nimport com.intellij.openapi.extensions.PluginAware;\nimport com.intellij.openapi.extensions.PluginDescriptor;\nimport com.intellij.openapi.project.Project;\nimport com.intellij.util.NotNullFunction;\nimport com.intellij.util.pico.ConstructorInjectionComponentAdapter;\nimport com.intellij.util.xmlb.annotations.Attribute;\nimport org.jetbrains.annotations.Nullable;\n\n/**\n * @author yole\n */\npublic class ChangesViewContentEP implements PluginAware {\n private static final Logger LOG = Logger.getInstance(\"#com.intellij.openapi.vcs.changes.ui.ChangesViewContentEP\");\n\n public static final ExtensionPointName EP_NAME = new ExtensionPointName(\"com.intellij.changesViewContent\");\n\n @Attribute(\"tabName\")\n public String tabName;\n\n @Attribute(\"className\")\n public String className;\n\n @Attribute(\"predicateClassName\")\n public String predicateClassName;\n\n private PluginDescriptor myPluginDescriptor;\n private ChangesViewContentProvider myInstance;\n\n public void setPluginDescriptor(PluginDescriptor pluginDescriptor) {\n myPluginDescriptor = pluginDescriptor;\n }\n\n public String getTabName() {\n return tabName;\n }\n\n public void setTabName(final String tabName) {\n this.tabName = tabName;\n }\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(final String className) {\n this.className = className;\n }\n\n public String getPredicateClassName() {\n return predicateClassName;\n }\n\n public void setPredicateClassName(final String predicateClassName) {\n this.predicateClassName = predicateClassName;\n }\n\n public ChangesViewContentProvider getInstance(Project project) {\n if (myInstance == null) {\n myInstance = (ChangesViewContentProvider) newClassInstance(project, className); \n }\n return myInstance;\n }\n\n @Nullable\n public NotNullFunction newPredicateInstance(Project project) {\n //noinspection unchecked\n return predicateClassName != null ? (NotNullFunction)newClassInstance(project, predicateClassName) : null;\n }\n\n private Object newClassInstance(final Project project, final String className) {\n try {\n final Class aClass = Class.forName(className, true,\n myPluginDescriptor == null ? getClass().getClassLoader() : myPluginDescriptor.getPluginClassLoader());\n return new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(project.getPicoContainer());\n }\n catch(Exception e) {\n LOG.error(e);\n return null;\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"samthor/intellij-community"},"path":{"kind":"string","value":"platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentEP.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":3337,"string":"3,337"}}},{"rowIdx":115086585,"cells":{"code":{"kind":"string","value":"package com.marshalchen.common.demoofui.showcaseview.legacy;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.Toast;\nimport com.marshalchen.common.demoofui.R;\n\n\npublic class MultipleShowcaseSampleActivity extends Activity {\n\n private static final float SHOWCASE_KITTEN_SCALE = 1.2f;\n private static final float SHOWCASE_LIKE_SCALE = 0.5f;\n //ShowcaseViews mViews;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.showcase_activity_sample_legacy);\n\n findViewById(R.id.buttonLike).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n Toast.makeText(getApplicationContext(), \"like_message\", Toast.LENGTH_SHORT).show();\n }\n });\n\n //mOptions.block = false;\n// mViews = new ShowcaseViews(this,\n// new ShowcaseViews.OnShowcaseAcknowledged() {\n// @Override\n// public void onShowCaseAcknowledged(ShowcaseView showcaseView) {\n// Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show();\n// }\n// });\n// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.image,\n// R.string.showcase_image_title,\n// R.string.showcase_image_message,\n// SHOWCASE_KITTEN_SCALE));\n// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.buttonLike,\n// R.string.showcase_like_title,\n// R.string.showcase_like_message,\n// SHOWCASE_LIKE_SCALE));\n// mViews.show();\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n enableUp();\n }\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n private void enableUp() {\n getActionBar().setDisplayHomeAsUpEnabled(true);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n finish();\n }\n return super.onOptionsItemSelected(item);\n }\n}\n"},"repo_name":{"kind":"string","value":"cymcsg/UltimateAndroid"},"path":{"kind":"string","value":"deprecated/UltimateAndroidNormal/DemoOfUI/src/com/marshalchen/common/demoofui/showcaseview/legacy/MultipleShowcaseSampleActivity.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":2332,"string":"2,332"}}},{"rowIdx":115086586,"cells":{"code":{"kind":"string","value":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2014-Today OpenERP SA ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import osv, fields\nfrom itertools import groupby\n\n\ndef grouplines(self, ordered_lines, sortkey):\n \"\"\"Return lines from a specified invoice or sale order grouped by category\"\"\"\n grouped_lines = []\n for key, valuesiter in groupby(ordered_lines, sortkey):\n group = {}\n group['category'] = key\n group['lines'] = list(v for v in valuesiter)\n\n if 'subtotal' in key and key.subtotal is True:\n group['subtotal'] = sum(line.price_subtotal for line in group['lines'])\n grouped_lines.append(group)\n\n return grouped_lines\n\n\nclass SaleLayoutCategory(osv.Model):\n _name = 'sale_layout.category'\n _order = 'sequence'\n _columns = {\n 'name': fields.char('Name', required=True),\n 'sequence': fields.integer('Sequence', required=True),\n 'subtotal': fields.boolean('Add subtotal'),\n 'separator': fields.boolean('Add separator'),\n 'pagebreak': fields.boolean('Add pagebreak')\n }\n\n _defaults = {\n 'subtotal': True,\n 'separator': True,\n 'pagebreak': False,\n 'sequence': 10\n }\n\n\nclass AccountInvoice(osv.Model):\n _inherit = 'account.invoice'\n\n def sale_layout_lines(self, cr, uid, ids, invoice_id=None, context=None):\n \"\"\"\n Returns invoice lines from a specified invoice ordered by\n sale_layout_category sequence. Used in sale_layout module.\n\n :Parameters:\n -'invoice_id' (int): specify the concerned invoice.\n \"\"\"\n ordered_lines = self.browse(cr, uid, invoice_id, context=context).invoice_line\n # We chose to group first by category model and, if not present, by invoice name\n sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else ''\n\n return grouplines(self, ordered_lines, sortkey)\n\n\nimport openerp\n\nclass AccountInvoiceLine(osv.Model):\n _inherit = 'account.invoice.line'\n _order = 'invoice_id, categ_sequence, sequence, id'\n\n sale_layout_cat_id = openerp.fields.Many2one('sale_layout.category', string='Section')\n categ_sequence = openerp.fields.Integer(related='sale_layout_cat_id.sequence',\n string='Layout Sequence', store=True)\n\n\nclass SaleOrder(osv.Model):\n _inherit = 'sale.order'\n\n def sale_layout_lines(self, cr, uid, ids, order_id=None, context=None):\n \"\"\"\n Returns order lines from a specified sale ordered by\n sale_layout_category sequence. Used in sale_layout module.\n\n :Parameters:\n -'order_id' (int): specify the concerned sale order.\n \"\"\"\n ordered_lines = self.browse(cr, uid, order_id, context=context).order_line\n sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else ''\n\n return grouplines(self, ordered_lines, sortkey)\n\n\nclass SaleOrderLine(osv.Model):\n _inherit = 'sale.order.line'\n _columns = {\n 'sale_layout_cat_id': fields.many2one('sale_layout.category',\n string='Section'),\n 'categ_sequence': fields.related('sale_layout_cat_id',\n 'sequence', type='integer',\n string='Layout Sequence', store=True)\n # Store is intentionally set in order to keep the \"historic\" order.\n }\n _order = 'order_id, categ_sequence, sequence, id'\n\n def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None):\n \"\"\"Save the layout when converting to an invoice line.\"\"\"\n invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(cr, uid, line, account_id=account_id, context=context)\n if line.sale_layout_cat_id:\n invoice_vals['sale_layout_cat_id'] = line.sale_layout_cat_id.id\n if line.categ_sequence:\n invoice_vals['categ_sequence'] = line.categ_sequence\n return invoice_vals\n"},"repo_name":{"kind":"string","value":"diogocs1/comps"},"path":{"kind":"string","value":"web/addons/sale_layout/models/sale_layout.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":4907,"string":"4,907"}}},{"rowIdx":115086587,"cells":{"code":{"kind":"string","value":"\n\n\n\n\"WARNING\"\n\n\"WARNING\"\n\n\"WARNING\"\n\n\"WARNING\"\n\n\"WARNING\"\n\n\n

    PLEASE NOTE: This document applies to the HEAD of the source tree

    \n\nIf you are using a released version of Kubernetes, you should\nrefer to the docs that go with that version.\n\n\nThe latest 1.0.x release of this document can be found\n[here](http://releases.k8s.io/release-1.0/docs/user-guide/connecting-applications.md).\n\nDocumentation for other releases can be found at\n[releases.k8s.io](http://releases.k8s.io).\n\n--\n\n\n\n\n\n# Kubernetes User Guide: Managing Applications: Connecting applications\n\n**Table of Contents**\n\n\n- [Kubernetes User Guide: Managing Applications: Connecting applications](#kubernetes-user-guide-managing-applications-connecting-applications)\n- [The Kubernetes model for connecting containers](#the-kubernetes-model-for-connecting-containers)\n - [Exposing pods to the cluster](#exposing-pods-to-the-cluster)\n - [Creating a Service](#creating-a-service)\n - [Accessing the Service](#accessing-the-service)\n - [Environment Variables](#environment-variables)\n - [DNS](#dns)\n - [Securing the Service](#securing-the-service)\n - [Exposing the Service](#exposing-the-service)\n - [What's next?](#whats-next)\n\n\n\n# The Kubernetes model for connecting containers\n\nNow that you have a continuously running, replicated application you can expose it on a network. Before discussing the Kubernetes approach to networking, it is worthwhile to contrast it with the \"normal\" way networking works with Docker.\n\nBy default, Docker uses host-private networking, so containers can talk to other containers only if they are on the same machine. In order for Docker containers to communicate across nodes, they must be allocated ports on the machine's own IP address, which are then forwarded or proxied to the containers. This obviously means that containers must either coordinate which ports they use very carefully or else be allocated ports dynamically.\n\nCoordinating ports across multiple developers is very difficult to do at scale and exposes users to cluster-level issues outside of their control. Kubernetes assumes that pods can communicate with other pods, regardless of which host they land on. We give every pod its own cluster-private-IP address so you do not need to explicitly create links between pods or mapping container ports to host ports. This means that containers within a Pod can all reach each other’s ports on localhost, and all pods in a cluster can see each other without NAT. The rest of this document will elaborate on how you can run reliable services on such a networking model.\n\nThis guide uses a simple nginx server to demonstrate proof of concept. The same principles are embodied in a more complete [Jenkins CI application](http://blog.kubernetes.io/2015/07/strong-simple-ssl-for-kubernetes.html).\n\n## Exposing pods to the cluster\n\nWe did this in a previous example, but lets do it once again and focus on the networking perspective. Create an nginx pod, and note that it has a container port specification:\n\n```yaml\n$ cat nginxrc.yaml\napiVersion: v1\nkind: ReplicationController\nmetadata:\n name: my-nginx\nspec:\n replicas: 2\n template:\n metadata:\n labels:\n app: nginx\n spec:\n containers:\n - name: nginx\n image: nginx\n ports:\n - containerPort: 80\n```\n\nThis makes it accessible from any node in your cluster. Check the nodes the pod is running on:\n\n```console\n$ kubectl create -f ./nginxrc.yaml\n$ kubectl get pods -l app=nginx -o wide\nmy-nginx-6isf4 1/1 Running 0 2h e2e-test-beeps-minion-93ly\nmy-nginx-t26zt 1/1 Running 0 2h e2e-test-beeps-minion-93ly\n```\n\nCheck your pods' IPs:\n\n```console\n$ kubectl get pods -l app=nginx -o json | grep podIP\n \"podIP\": \"10.245.0.15\",\n \"podIP\": \"10.245.0.14\",\n```\n\nYou should be able to ssh into any node in your cluster and curl both IPs. Note that the containers are *not* using port 80 on the node, nor are there any special NAT rules to route traffic to the pod. This means you can run multiple nginx pods on the same node all using the same containerPort and access them from any other pod or node in your cluster using IP. Like Docker, ports can still be published to the host node's interface(s), but the need for this is radically diminished because of the networking model.\n\nYou can read more about [how we achieve this](../admin/networking.md#how-to-achieve-this) if you’re curious.\n\n## Creating a Service\n\nSo we have pods running nginx in a flat, cluster wide, address space. In theory, you could talk to these pods directly, but what happens when a node dies? The pods die with it, and the replication controller will create new ones, with different IPs. This is the problem a Service solves.\n\nA Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere in your cluster, that all provide the same functionality. When created, each Service is assigned a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service, and will not change while the Service is alive. Pods can be configured to talk to the Service, and know that communication to the Service will be automatically load-balanced out to some pod that is a member of the Service.\n\nYou can create a Service for your 2 nginx replicas with the following yaml:\n\n```yaml\n$ cat nginxsvc.yaml\napiVersion: v1\nkind: Service\nmetadata:\n name: nginxsvc\n labels:\n app: nginx\nspec:\n ports:\n - port: 80\n protocol: TCP\n selector:\n app: nginx\n```\n\nThis specification will create a Service which targets TCP port 80 on any Pod with the `app=nginx` label, and expose it on an abstracted Service port (`targetPort`: is the port the container accepts traffic on, `port`: is the abstracted Service port, which can be any port other pods use to access the Service). View [service API object](https://htmlpreview.github.io/?https://k8s.io/kubernetes/HEAD/docs/api-reference/definitions.html#_v1_service) to see the list of supported fields in service definition.\nCheck your Service:\n\n```console\n$ kubectl get svc\nNAME LABELS SELECTOR IP(S) PORT(S)\nnginxsvc app=nginx app=nginx 10.0.116.146 80/TCP\n```\n\nAs mentioned previously, a Service is backed by a group of pods. These pods are exposed through `endpoints`. The Service's selector will be evaluated continuously and the results will be POSTed to an Endpoints object also named `nginxsvc`. When a pod dies, it is automatically removed from the endpoints, and new pods matching the Service’s selector will automatically get added to the endpoints. Check the endpoints, and note that the IPs are the same as the pods created in the first step:\n\n```console\n$ kubectl describe svc nginxsvc\nName:\t\t\tnginxsvc\nNamespace:\t\tdefault\nLabels:\t\t\tapp=nginx\nSelector:\t\tapp=nginx\nType:\t\t\tClusterIP\nIP:\t\t\t10.0.116.146\nPort:\t\t\t\t80/TCP\nEndpoints:\t\t10.245.0.14:80,10.245.0.15:80\nSession Affinity:\tNone\nNo events.\n\n$ kubectl get ep\nNAME ENDPOINTS\nnginxsvc 10.245.0.14:80,10.245.0.15:80\n```\n\nYou should now be able to curl the nginx Service on `10.0.116.146:80` from any node in your cluster. Note that the Service IP is completely virtual, it never hits the wire, if you’re curious about how this works you can read more about the [service proxy](services.md#virtual-ips-and-service-proxies).\n\n## Accessing the Service\n\nKubernetes supports 2 primary modes of finding a Service - environment variables and DNS. The former works out of the box while the latter requires the [kube-dns cluster addon](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md).\n\n### Environment Variables\n\nWhen a Pod is run on a Node, the kubelet adds a set of environment variables for each active Service. This introduces an ordering problem. To see why, inspect the environment of your running nginx pods:\n\n```console\n$ kubectl exec my-nginx-6isf4 -- printenv | grep SERVICE\nKUBERNETES_SERVICE_HOST=10.0.0.1\nKUBERNETES_SERVICE_PORT=443\n```\n\nNote there’s no mention of your Service. This is because you created the replicas before the Service. Another disadvantage of doing this is that the scheduler might put both pods on the same machine, which will take your entire Service down if it dies. We can do this the right way by killing the 2 pods and waiting for the replication controller to recreate them. This time around the Service exists *before* the replicas. This will given you scheduler level Service spreading of your pods (provided all your nodes have equal capacity), as well as the right environment variables:\n\n```console\n$ kubectl scale rc my-nginx --replicas=0; kubectl scale rc my-nginx --replicas=2;\n$ kubectl get pods -l app=nginx -o wide\nNAME READY STATUS RESTARTS AGE NODE\nmy-nginx-5j8ok 1/1 Running \t0 2m node1\nmy-nginx-90vaf 1/1 Running 0 2m node2\n\n$ kubectl exec my-nginx-5j8ok -- printenv | grep SERVICE\nKUBERNETES_SERVICE_PORT=443\nNGINXSVC_SERVICE_HOST=10.0.116.146\nKUBERNETES_SERVICE_HOST=10.0.0.1\nNGINXSVC_SERVICE_PORT=80\n```\n\n### DNS\n\nKubernetes offers a DNS cluster addon Service that uses skydns to automatically assign dns names to other Services. You can check if it’s running on your cluster:\n\n```console\n$ kubectl get services kube-dns --namespace=kube-system\nNAME LABELS SELECTOR IP(S) PORT(S)\nkube-dns k8s-app=kube-dns 10.0.0.10 53/UDP\n 53/TCP\n```\n\nIf it isn’t running, you can [enable it](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md#how-do-i-configure-it). The rest of this section will assume you have a Service with a long lived IP (nginxsvc), and a dns server that has assigned a name to that IP (the kube-dns cluster addon), so you can talk to the Service from any pod in your cluster using standard methods (e.g. gethostbyname). Let’s create another pod to test this:\n\n```yaml\n$ cat curlpod.yaml\napiVersion: v1\nkind: Pod\nmetadata:\n name: curlpod\nspec:\n containers:\n - image: radial/busyboxplus:curl\n command:\n - sleep\n - \"3600\"\n imagePullPolicy: IfNotPresent\n name: curlcontainer\n restartPolicy: Always\n```\n\nAnd perform a lookup of the nginx Service\n\n```console\n$ kubectl create -f ./curlpod.yaml\ndefault/curlpod\n$ kubectl get pods curlpod\nNAME READY STATUS RESTARTS AGE\ncurlpod 1/1 Running 0 18s\n\n$ kubectl exec curlpod -- nslookup nginxsvc\nServer: 10.0.0.10\nAddress 1: 10.0.0.10\nName: nginxsvc\nAddress 1: 10.0.116.146\n```\n\n## Securing the Service\n\nTill now we have only accessed the nginx server from within the cluster. Before exposing the Service to the internet, you want to make sure the communication channel is secure. For this, you will need:\n* Self signed certificates for https (unless you already have an identitiy certificate)\n* An nginx server configured to use the cretificates\n* A [secret](secrets.md) that makes the certificates accessible to pods\n\nYou can acquire all these from the [nginx https example](../../examples/https-nginx/README.md), in short:\n\n```console\n$ make keys secret KEY=/tmp/nginx.key CERT=/tmp/nginx.crt SECRET=/tmp/secret.json\n$ kubectl create -f /tmp/secret.json\nsecrets/nginxsecret\n$ kubectl get secrets\nNAME TYPE DATA\ndefault-token-il9rc kubernetes.io/service-account-token 1\nnginxsecret Opaque 2\n```\n\nNow modify your nginx replicas to start a https server using the certificate in the secret, and the Service, to expose both ports (80 and 443):\n\n```yaml\n$ cat nginx-app.yaml\napiVersion: v1\nkind: Service\nmetadata:\n name: nginxsvc\n labels:\n app: nginx\nspec:\n type: NodePort\n ports:\n - port: 8080\n targetPort: 80\n protocol: TCP\n name: http\n - port: 443\n protocol: TCP\n name: https\n selector:\n app: nginx\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n name: my-nginx\nspec:\n replicas: 1\n template:\n metadata:\n labels:\n app: nginx\n spec:\n volumes:\n - name: secret-volume\n secret:\n secretName: nginxsecret\n containers:\n - name: nginxhttps\n image: bprashanth/nginxhttps:1.0\n ports:\n - containerPort: 443\n - containerPort: 80\n volumeMounts:\n - mountPath: /etc/nginx/ssl\n name: secret-volume\n```\n\nNoteworthy points about the nginx-app manifest:\n- It contains both rc and service specification in the same file\n- The [nginx server](../../examples/https-nginx/default.conf) serves http traffic on port 80 and https traffic on 443, and nginx Service exposes both ports.\n- Each container has access to the keys through a volume mounted at /etc/nginx/ssl. This is setup *before* the nginx server is started.\n\n```console\n$ kubectl delete rc,svc -l app=nginx; kubectl create -f ./nginx-app.yaml\nreplicationcontrollers/my-nginx\nservices/nginxsvc\nservices/nginxsvc\nreplicationcontrollers/my-nginx\n```\n\nAt this point you can reach the nginx server from any node.\n\n```console\n$ kubectl get pods -o json | grep -i podip\n \"podIP\": \"10.1.0.80\",\nnode $ curl -k https://10.1.0.80\n...\n

    Welcome to nginx!

    \n```\n\nNote how we supplied the `-k` parameter to curl in the last step, this is because we don't know anything about the pods running nginx at certificate generation time,\nso we have to tell curl to ignore the CName mismatch. By creating a Service we linked the CName used in the certificate with the actual DNS name used by pods during Service lookup.\nLets test this from a pod (the same secret is being reused for simplicity, the pod only needs nginx.crt to access the Service):\n\n```console\n$ cat curlpod.yaml\nvapiVersion: v1\nkind: ReplicationController\nmetadata:\n name: curlrc\nspec:\n replicas: 1\n template:\n metadata:\n labels:\n app: curlpod\n spec:\n volumes:\n - name: secret-volume\n secret:\n secretName: nginxsecret\n containers:\n - name: curlpod\n command:\n - sh\n - -c\n - while true; do sleep 1; done\n image: radial/busyboxplus:curl\n volumeMounts:\n - mountPath: /etc/nginx/ssl\n name: secret-volume\n\n$ kubectl create -f ./curlpod.yaml\n$ kubectl get pods\nNAME READY STATUS RESTARTS AGE\ncurlpod 1/1 Running 0 2m\nmy-nginx-7006w 1/1 Running 0 24m\n\n$ kubectl exec curlpod -- curl https://nginxsvc --cacert /etc/nginx/ssl/nginx.crt\n...\nWelcome to nginx!\n...\n```\n\n## Exposing the Service\n\nFor some parts of your applications you may want to expose a Service onto an external IP address. Kubernetes supports two ways of doing this: NodePorts and LoadBalancers. The Service created in the last section already used `NodePort`, so your nginx https replica is ready to serve traffic on the internet if your node has a public IP.\n\n```console\n$ kubectl get svc nginxsvc -o json | grep -i nodeport -C 5\n {\n \"name\": \"http\",\n \"protocol\": \"TCP\",\n \"port\": 80,\n \"targetPort\": 80,\n \"nodePort\": 32188\n },\n {\n \"name\": \"https\",\n \"protocol\": \"TCP\",\n \"port\": 443,\n \"targetPort\": 443,\n \"nodePort\": 30645\n }\n\n$ kubectl get nodes -o json | grep ExternalIP -C 2\n {\n \"type\": \"ExternalIP\",\n \"address\": \"104.197.63.17\"\n }\n--\n },\n {\n \"type\": \"ExternalIP\",\n \"address\": \"104.154.89.170\"\n }\n$ curl https://104.197.63.17:30645 -k\n...\n

    Welcome to nginx!

    \n```\n\nLets now recreate the Service to use a cloud load balancer, just change the `Type` of Service in the nginx-app.yaml from `NodePort` to `LoadBalancer`:\n\n```console\n$ kubectl delete rc, svc -l app=nginx\n$ kubectl create -f ./nginx-app.yaml\n$ kubectl get svc -o json | grep -i ingress -A 5\n \"ingress\": [\n {\n \"ip\": \"104.197.68.43\"\n }\n ]\n }\n$ curl https://104.197.68.43 -k\n...\nWelcome to nginx!\n```\n\n## What's next?\n\n[Learn about more Kubernetes features that will help you run containers reliably in production.](production-pods.md)\n\n\n\n[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/connecting-applications.md?pixel)]()\n\n"},"repo_name":{"kind":"string","value":"vongalpha/origin"},"path":{"kind":"string","value":"Godeps/_workspace/src/k8s.io/kubernetes/docs/user-guide/connecting-applications.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":17365,"string":"17,365"}}},{"rowIdx":115086588,"cells":{"code":{"kind":"string","value":"/*\n * Copyright 2012, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\npackage org.jf.dexlib2.dexbacked;\n\nimport com.google.common.io.ByteStreams;\nimport org.jf.dexlib2.Opcodes;\nimport org.jf.dexlib2.dexbacked.raw.*;\nimport org.jf.dexlib2.dexbacked.util.FixedSizeSet;\nimport org.jf.dexlib2.iface.DexFile;\nimport org.jf.util.ExceptionWithContext;\n\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport java.io.EOFException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Set;\n\npublic class DexBackedDexFile extends BaseDexBuffer implements DexFile {\n private final Opcodes opcodes;\n\n private final int stringCount;\n private final int stringStartOffset;\n private final int typeCount;\n private final int typeStartOffset;\n private final int protoCount;\n private final int protoStartOffset;\n private final int fieldCount;\n private final int fieldStartOffset;\n private final int methodCount;\n private final int methodStartOffset;\n private final int classCount;\n private final int classStartOffset;\n\n private DexBackedDexFile(Opcodes opcodes, @Nonnull byte[] buf, int offset, boolean verifyMagic) {\n super(buf);\n\n this.opcodes = opcodes;\n\n if (verifyMagic) {\n verifyMagicAndByteOrder(buf, offset);\n }\n\n stringCount = readSmallUint(HeaderItem.STRING_COUNT_OFFSET);\n stringStartOffset = readSmallUint(HeaderItem.STRING_START_OFFSET);\n typeCount = readSmallUint(HeaderItem.TYPE_COUNT_OFFSET);\n typeStartOffset = readSmallUint(HeaderItem.TYPE_START_OFFSET);\n protoCount = readSmallUint(HeaderItem.PROTO_COUNT_OFFSET);\n protoStartOffset = readSmallUint(HeaderItem.PROTO_START_OFFSET);\n fieldCount = readSmallUint(HeaderItem.FIELD_COUNT_OFFSET);\n fieldStartOffset = readSmallUint(HeaderItem.FIELD_START_OFFSET);\n methodCount = readSmallUint(HeaderItem.METHOD_COUNT_OFFSET);\n methodStartOffset = readSmallUint(HeaderItem.METHOD_START_OFFSET);\n classCount = readSmallUint(HeaderItem.CLASS_COUNT_OFFSET);\n classStartOffset = readSmallUint(HeaderItem.CLASS_START_OFFSET);\n }\n\n public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull BaseDexBuffer buf) {\n this(opcodes, buf.buf);\n }\n\n public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf, int offset) {\n this(opcodes, buf, offset, false);\n }\n\n public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf) {\n this(opcodes, buf, 0, true);\n }\n\n public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is)\n throws IOException {\n if (!is.markSupported()) {\n throw new IllegalArgumentException(\"InputStream must support mark\");\n }\n is.mark(44);\n byte[] partialHeader = new byte[44];\n try {\n ByteStreams.readFully(is, partialHeader);\n } catch (EOFException ex) {\n throw new NotADexFile(\"File is too short\");\n } finally {\n is.reset();\n }\n\n verifyMagicAndByteOrder(partialHeader, 0);\n\n byte[] buf = ByteStreams.toByteArray(is);\n return new DexBackedDexFile(opcodes, buf, 0, false);\n }\n\n public Opcodes getOpcodes() {\n return opcodes;\n }\n\n public boolean isOdexFile() {\n return false;\n }\n\n @Nonnull\n @Override\n public Set getClasses() {\n return new FixedSizeSet() {\n @Nonnull\n @Override\n public DexBackedClassDef readItem(int index) {\n return new DexBackedClassDef(DexBackedDexFile.this, getClassDefItemOffset(index));\n }\n\n @Override\n public int size() {\n return classCount;\n }\n };\n }\n\n private static void verifyMagicAndByteOrder(@Nonnull byte[] buf, int offset) {\n if (!HeaderItem.verifyMagic(buf, offset)) {\n StringBuilder sb = new StringBuilder(\"Invalid magic value:\");\n for (int i=0; i<8; i++) {\n sb.append(String.format(\" %02x\", buf[i]));\n }\n throw new NotADexFile(sb.toString());\n }\n\n int endian = HeaderItem.getEndian(buf, offset);\n if (endian == HeaderItem.BIG_ENDIAN_TAG) {\n throw new ExceptionWithContext(\"Big endian dex files are not currently supported\");\n }\n\n if (endian != HeaderItem.LITTLE_ENDIAN_TAG) {\n throw new ExceptionWithContext(\"Invalid endian tag: 0x%x\", endian);\n }\n }\n\n public int getStringIdItemOffset(int stringIndex) {\n if (stringIndex < 0 || stringIndex >= stringCount) {\n throw new InvalidItemIndex(stringIndex, \"String index out of bounds: %d\", stringIndex);\n }\n return stringStartOffset + stringIndex*StringIdItem.ITEM_SIZE;\n }\n\n public int getTypeIdItemOffset(int typeIndex) {\n if (typeIndex < 0 || typeIndex >= typeCount) {\n throw new InvalidItemIndex(typeIndex, \"Type index out of bounds: %d\", typeIndex);\n }\n return typeStartOffset + typeIndex*TypeIdItem.ITEM_SIZE;\n }\n\n public int getFieldIdItemOffset(int fieldIndex) {\n if (fieldIndex < 0 || fieldIndex >= fieldCount) {\n throw new InvalidItemIndex(fieldIndex, \"Field index out of bounds: %d\", fieldIndex);\n }\n return fieldStartOffset + fieldIndex*FieldIdItem.ITEM_SIZE;\n }\n\n public int getMethodIdItemOffset(int methodIndex) {\n if (methodIndex < 0 || methodIndex >= methodCount) {\n throw new InvalidItemIndex(methodIndex, \"Method index out of bounds: %d\", methodIndex);\n }\n return methodStartOffset + methodIndex*MethodIdItem.ITEM_SIZE;\n }\n\n public int getProtoIdItemOffset(int protoIndex) {\n if (protoIndex < 0 || protoIndex >= protoCount) {\n throw new InvalidItemIndex(protoIndex, \"Proto index out of bounds: %d\", protoIndex);\n }\n return protoStartOffset + protoIndex*ProtoIdItem.ITEM_SIZE;\n }\n\n public int getClassDefItemOffset(int classIndex) {\n if (classIndex < 0 || classIndex >= classCount) {\n throw new InvalidItemIndex(classIndex, \"Class index out of bounds: %d\", classIndex);\n }\n return classStartOffset + classIndex*ClassDefItem.ITEM_SIZE;\n }\n\n public int getClassCount() {\n return classCount;\n }\n\n public int getStringCount() {\n return stringCount;\n }\n\n public int getTypeCount() {\n return typeCount;\n }\n\n public int getProtoCount() {\n return protoCount;\n }\n\n public int getFieldCount() {\n return fieldCount;\n }\n\n public int getMethodCount() {\n return methodCount;\n }\n\n @Nonnull\n public String getString(int stringIndex) {\n int stringOffset = getStringIdItemOffset(stringIndex);\n int stringDataOffset = readSmallUint(stringOffset);\n DexReader reader = readerAt(stringDataOffset);\n int utf16Length = reader.readSmallUleb128();\n return reader.readString(utf16Length);\n }\n\n @Nullable\n public String getOptionalString(int stringIndex) {\n if (stringIndex == -1) {\n return null;\n }\n return getString(stringIndex);\n }\n\n @Nonnull\n public String getType(int typeIndex) {\n int typeOffset = getTypeIdItemOffset(typeIndex);\n int stringIndex = readSmallUint(typeOffset);\n return getString(stringIndex);\n }\n\n @Nullable\n public String getOptionalType(int typeIndex) {\n if (typeIndex == -1) {\n return null;\n }\n return getType(typeIndex);\n }\n\n @Override\n @Nonnull\n public DexReader readerAt(int offset) {\n return new DexReader(this, offset);\n }\n\n public static class NotADexFile extends RuntimeException {\n public NotADexFile() {\n }\n\n public NotADexFile(Throwable cause) {\n super(cause);\n }\n\n public NotADexFile(String message) {\n super(message);\n }\n\n public NotADexFile(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n public static class InvalidItemIndex extends ExceptionWithContext {\n private final int itemIndex;\n\n public InvalidItemIndex(int itemIndex) {\n super(\"\");\n this.itemIndex = itemIndex;\n }\n\n public InvalidItemIndex(int itemIndex, String message, Object... formatArgs) {\n super(message, formatArgs);\n this.itemIndex = itemIndex;\n }\n\n public int getInvalidIndex() {\n return itemIndex;\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"valery-barysok/Apktool"},"path":{"kind":"string","value":"brut.apktool.smali/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/DexBackedDexFile.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":10213,"string":"10,213"}}},{"rowIdx":115086589,"cells":{"code":{"kind":"string","value":"/* General netfs cache on cache files internal defs\n *\n * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.\n * Written by David Howells (dhowells@redhat.com)\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public Licence\n * as published by the Free Software Foundation; either version\n * 2 of the Licence, or (at your option) any later version.\n */\n\n#include \n#include \n#include \n#include \n#include \n\nstruct cachefiles_cache;\nstruct cachefiles_object;\n\nextern unsigned cachefiles_debug;\n#define CACHEFILES_DEBUG_KENTER\t1\n#define CACHEFILES_DEBUG_KLEAVE\t2\n#define CACHEFILES_DEBUG_KDEBUG\t4\n\n/*\n * node records\n */\nstruct cachefiles_object {\n\tstruct fscache_object\t\tfscache;\t/* fscache handle */\n\tstruct cachefiles_lookup_data\t*lookup_data;\t/* cached lookup data */\n\tstruct dentry\t\t\t*dentry;\t/* the file/dir representing this object */\n\tstruct dentry\t\t\t*backer;\t/* backing file */\n\tloff_t\t\t\t\ti_size;\t\t/* object size */\n\tunsigned long\t\t\tflags;\n#define CACHEFILES_OBJECT_ACTIVE\t0\t\t/* T if marked active */\n#define CACHEFILES_OBJECT_BURIED\t1\t\t/* T if preemptively buried */\n\tatomic_t\t\t\tusage;\t\t/* object usage count */\n\tuint8_t\t\t\t\ttype;\t\t/* object type */\n\tuint8_t\t\t\t\tnew;\t\t/* T if object new */\n\tspinlock_t\t\t\twork_lock;\n\tstruct rb_node\t\t\tactive_node;\t/* link in active tree (dentry is key) */\n};\n\nextern struct kmem_cache *cachefiles_object_jar;\n\n/*\n * Cache files cache definition\n */\nstruct cachefiles_cache {\n\tstruct fscache_cache\t\tcache;\t\t/* FS-Cache record */\n\tstruct vfsmount\t\t\t*mnt;\t\t/* mountpoint holding the cache */\n\tstruct dentry\t\t\t*graveyard;\t/* directory into which dead objects go */\n\tstruct file\t\t\t*cachefilesd;\t/* manager daemon handle */\n\tconst struct cred\t\t*cache_cred;\t/* security override for accessing cache */\n\tstruct mutex\t\t\tdaemon_mutex;\t/* command serialisation mutex */\n\twait_queue_head_t\t\tdaemon_pollwq;\t/* poll waitqueue for daemon */\n\tstruct rb_root\t\t\tactive_nodes;\t/* active nodes (can't be culled) */\n\trwlock_t\t\t\tactive_lock;\t/* lock for active_nodes */\n\tatomic_t\t\t\tgravecounter;\t/* graveyard uniquifier */\n\tunsigned\t\t\tfrun_percent;\t/* when to stop culling (% files) */\n\tunsigned\t\t\tfcull_percent;\t/* when to start culling (% files) */\n\tunsigned\t\t\tfstop_percent;\t/* when to stop allocating (% files) */\n\tunsigned\t\t\tbrun_percent;\t/* when to stop culling (% blocks) */\n\tunsigned\t\t\tbcull_percent;\t/* when to start culling (% blocks) */\n\tunsigned\t\t\tbstop_percent;\t/* when to stop allocating (% blocks) */\n\tunsigned\t\t\tbsize;\t\t/* cache's block size */\n\tunsigned\t\t\tbshift;\t\t/* min(ilog2(PAGE_SIZE / bsize), 0) */\n\tuint64_t\t\t\tfrun;\t\t/* when to stop culling */\n\tuint64_t\t\t\tfcull;\t\t/* when to start culling */\n\tuint64_t\t\t\tfstop;\t\t/* when to stop allocating */\n\tsector_t\t\t\tbrun;\t\t/* when to stop culling */\n\tsector_t\t\t\tbcull;\t\t/* when to start culling */\n\tsector_t\t\t\tbstop;\t\t/* when to stop allocating */\n\tunsigned long\t\t\tflags;\n#define CACHEFILES_READY\t\t0\t/* T if cache prepared */\n#define CACHEFILES_DEAD\t\t\t1\t/* T if cache dead */\n#define CACHEFILES_CULLING\t\t2\t/* T if cull engaged */\n#define CACHEFILES_STATE_CHANGED\t3\t/* T if state changed (poll trigger) */\n\tchar\t\t\t\t*rootdirname;\t/* name of cache root directory */\n\tchar\t\t\t\t*secctx;\t/* LSM security context */\n\tchar\t\t\t\t*tag;\t\t/* cache binding tag */\n};\n\n/*\n * backing file read tracking\n */\nstruct cachefiles_one_read {\n\twait_queue_t\t\t\tmonitor;\t/* link into monitored waitqueue */\n\tstruct page\t\t\t*back_page;\t/* backing file page we're waiting for */\n\tstruct page\t\t\t*netfs_page;\t/* netfs page we're going to fill */\n\tstruct fscache_retrieval\t*op;\t\t/* retrieval op covering this */\n\tstruct list_head\t\top_link;\t/* link in op's todo list */\n};\n\n/*\n * backing file write tracking\n */\nstruct cachefiles_one_write {\n\tstruct page\t\t\t*netfs_page;\t/* netfs page to copy */\n\tstruct cachefiles_object\t*object;\n\tstruct list_head\t\tobj_link;\t/* link in object's lists */\n\tfscache_rw_complete_t\t\tend_io_func;\n\tvoid\t\t\t\t*context;\n};\n\n/*\n * auxiliary data xattr buffer\n */\nstruct cachefiles_xattr {\n\tuint16_t\t\t\tlen;\n\tuint8_t\t\t\t\ttype;\n\tuint8_t\t\t\t\tdata[];\n};\n\n/*\n * note change of state for daemon\n */\nstatic inline void cachefiles_state_changed(struct cachefiles_cache *cache)\n{\n\tset_bit(CACHEFILES_STATE_CHANGED, &cache->flags);\n\twake_up_all(&cache->daemon_pollwq);\n}\n\n/*\n * bind.c\n */\nextern int cachefiles_daemon_bind(struct cachefiles_cache *cache, char *args);\nextern void cachefiles_daemon_unbind(struct cachefiles_cache *cache);\n\n/*\n * daemon.c\n */\nextern const struct file_operations cachefiles_daemon_fops;\n\nextern int cachefiles_has_space(struct cachefiles_cache *cache,\n\t\t\t\tunsigned fnr, unsigned bnr);\n\n/*\n * interface.c\n */\nextern const struct fscache_cache_ops cachefiles_cache_ops;\n\n/*\n * key.c\n */\nextern char *cachefiles_cook_key(const u8 *raw, int keylen, uint8_t type);\n\n/*\n * namei.c\n */\nextern int cachefiles_delete_object(struct cachefiles_cache *cache,\n\t\t\t\t struct cachefiles_object *object);\nextern int cachefiles_walk_to_object(struct cachefiles_object *parent,\n\t\t\t\t struct cachefiles_object *object,\n\t\t\t\t const char *key,\n\t\t\t\t struct cachefiles_xattr *auxdata);\nextern struct dentry *cachefiles_get_directory(struct cachefiles_cache *cache,\n\t\t\t\t\t struct dentry *dir,\n\t\t\t\t\t const char *name);\n\nextern int cachefiles_cull(struct cachefiles_cache *cache, struct dentry *dir,\n\t\t\t char *filename);\n\nextern int cachefiles_check_in_use(struct cachefiles_cache *cache,\n\t\t\t\t struct dentry *dir, char *filename);\n\n/*\n * proc.c\n */\n#ifdef CONFIG_CACHEFILES_HISTOGRAM\nextern atomic_t cachefiles_lookup_histogram[HZ];\nextern atomic_t cachefiles_mkdir_histogram[HZ];\nextern atomic_t cachefiles_create_histogram[HZ];\n\nextern int __init cachefiles_proc_init(void);\nextern void cachefiles_proc_cleanup(void);\nstatic inline\nvoid cachefiles_hist(atomic_t histogram[], unsigned long start_jif)\n{\n\tunsigned long jif = jiffies - start_jif;\n\tif (jif >= HZ)\n\t\tjif = HZ - 1;\n\tatomic_inc(&histogram[jif]);\n}\n\n#else\n#define cachefiles_proc_init()\t\t(0)\n#define cachefiles_proc_cleanup()\tdo {} while (0)\n#define cachefiles_hist(hist, start_jif) do {} while (0)\n#endif\n\n/*\n * rdwr.c\n */\nextern int cachefiles_read_or_alloc_page(struct fscache_retrieval *,\n\t\t\t\t\t struct page *, gfp_t);\nextern int cachefiles_read_or_alloc_pages(struct fscache_retrieval *,\n\t\t\t\t\t struct list_head *, unsigned *,\n\t\t\t\t\t gfp_t);\nextern int cachefiles_allocate_page(struct fscache_retrieval *, struct page *,\n\t\t\t\t gfp_t);\nextern int cachefiles_allocate_pages(struct fscache_retrieval *,\n\t\t\t\t struct list_head *, unsigned *, gfp_t);\nextern int cachefiles_write_page(struct fscache_storage *, struct page *);\nextern void cachefiles_uncache_page(struct fscache_object *, struct page *);\n\n/*\n * security.c\n */\nextern int cachefiles_get_security_ID(struct cachefiles_cache *cache);\nextern int cachefiles_determine_cache_security(struct cachefiles_cache *cache,\n\t\t\t\t\t struct dentry *root,\n\t\t\t\t\t const struct cred **_saved_cred);\n\nstatic inline void cachefiles_begin_secure(struct cachefiles_cache *cache,\n\t\t\t\t\t const struct cred **_saved_cred)\n{\n\t*_saved_cred = override_creds(cache->cache_cred);\n}\n\nstatic inline void cachefiles_end_secure(struct cachefiles_cache *cache,\n\t\t\t\t\t const struct cred *saved_cred)\n{\n\trevert_creds(saved_cred);\n}\n\n/*\n * xattr.c\n */\nextern int cachefiles_check_object_type(struct cachefiles_object *object);\nextern int cachefiles_set_object_xattr(struct cachefiles_object *object,\n\t\t\t\t struct cachefiles_xattr *auxdata);\nextern int cachefiles_update_object_xattr(struct cachefiles_object *object,\n\t\t\t\t\t struct cachefiles_xattr *auxdata);\nextern int cachefiles_check_object_xattr(struct cachefiles_object *object,\n\t\t\t\t\t struct cachefiles_xattr *auxdata);\nextern int cachefiles_remove_object_xattr(struct cachefiles_cache *cache,\n\t\t\t\t\t struct dentry *dentry);\n\n\n/*\n * error handling\n */\n#define kerror(FMT, ...) printk(KERN_ERR \"CacheFiles: \"FMT\"\\n\", ##__VA_ARGS__)\n\n#define cachefiles_io_error(___cache, FMT, ...)\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tkerror(\"I/O Error: \" FMT, ##__VA_ARGS__);\t\\\n\tfscache_io_error(&(___cache)->cache);\t\t\\\n\tset_bit(CACHEFILES_DEAD, &(___cache)->flags);\t\\\n} while (0)\n\n#define cachefiles_io_error_obj(object, FMT, ...)\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\t\\\n\tstruct cachefiles_cache *___cache;\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\\\n\t___cache = container_of((object)->fscache.cache,\t\t\\\n\t\t\t\tstruct cachefiles_cache, cache);\t\\\n\tcachefiles_io_error(___cache, FMT, ##__VA_ARGS__);\t\t\\\n} while (0)\n\n\n/*\n * debug tracing\n */\n#define dbgprintk(FMT, ...) \\\n\tprintk(KERN_DEBUG \"[%-6.6s] \"FMT\"\\n\", current->comm, ##__VA_ARGS__)\n\n/* make sure we maintain the format strings, even when debugging is disabled */\nstatic inline void _dbprintk(const char *fmt, ...)\n\t__attribute__((format(printf, 1, 2)));\nstatic inline void _dbprintk(const char *fmt, ...)\n{\n}\n\n#define kenter(FMT, ...) dbgprintk(\"==> %s(\"FMT\")\", __func__, ##__VA_ARGS__)\n#define kleave(FMT, ...) dbgprintk(\"<== %s()\"FMT\"\", __func__, ##__VA_ARGS__)\n#define kdebug(FMT, ...) dbgprintk(FMT, ##__VA_ARGS__)\n\n\n#if defined(__KDEBUG)\n#define _enter(FMT, ...) kenter(FMT, ##__VA_ARGS__)\n#define _leave(FMT, ...) kleave(FMT, ##__VA_ARGS__)\n#define _debug(FMT, ...) kdebug(FMT, ##__VA_ARGS__)\n\n#elif defined(CONFIG_CACHEFILES_DEBUG)\n#define _enter(FMT, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif (cachefiles_debug & CACHEFILES_DEBUG_KENTER)\t\\\n\t\tkenter(FMT, ##__VA_ARGS__);\t\t\\\n} while (0)\n\n#define _leave(FMT, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif (cachefiles_debug & CACHEFILES_DEBUG_KLEAVE)\t\\\n\t\tkleave(FMT, ##__VA_ARGS__);\t\t\\\n} while (0)\n\n#define _debug(FMT, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif (cachefiles_debug & CACHEFILES_DEBUG_KDEBUG)\t\\\n\t\tkdebug(FMT, ##__VA_ARGS__);\t\t\\\n} while (0)\n\n#else\n#define _enter(FMT, ...) _dbprintk(\"==> %s(\"FMT\")\", __func__, ##__VA_ARGS__)\n#define _leave(FMT, ...) _dbprintk(\"<== %s()\"FMT\"\", __func__, ##__VA_ARGS__)\n#define _debug(FMT, ...) _dbprintk(FMT, ##__VA_ARGS__)\n#endif\n\n#if 1 /* defined(__KDEBUGALL) */\n\n#define ASSERT(X)\t\t\t\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\t\\\n\tif (unlikely(!(X))) {\t\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"\\n\");\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"CacheFiles: Assertion failed\\n\");\t\\\n\t\tBUG();\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\n#define ASSERTCMP(X, OP, Y)\t\t\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\t\\\n\tif (unlikely(!((X) OP (Y)))) {\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"\\n\");\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"CacheFiles: Assertion failed\\n\");\t\\\n\t\tprintk(KERN_ERR \"%lx \" #OP \" %lx is false\\n\",\t\t\\\n\t\t (unsigned long)(X), (unsigned long)(Y));\t\t\\\n\t\tBUG();\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\n#define ASSERTIF(C, X)\t\t\t\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\t\\\n\tif (unlikely((C) && !(X))) {\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"\\n\");\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"CacheFiles: Assertion failed\\n\");\t\\\n\t\tBUG();\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\n#define ASSERTIFCMP(C, X, OP, Y)\t\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\t\t\\\n\tif (unlikely((C) && !((X) OP (Y)))) {\t\t\t\t\\\n\t\tprintk(KERN_ERR \"\\n\");\t\t\t\t\t\\\n\t\tprintk(KERN_ERR \"CacheFiles: Assertion failed\\n\");\t\\\n\t\tprintk(KERN_ERR \"%lx \" #OP \" %lx is false\\n\",\t\t\\\n\t\t (unsigned long)(X), (unsigned long)(Y));\t\t\\\n\t\tBUG();\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n} while (0)\n\n#else\n\n#define ASSERT(X)\t\t\tdo {} while (0)\n#define ASSERTCMP(X, OP, Y)\t\tdo {} while (0)\n#define ASSERTIF(C, X)\t\t\tdo {} while (0)\n#define ASSERTIFCMP(C, X, OP, Y)\tdo {} while (0)\n\n#endif\n"},"repo_name":{"kind":"string","value":"KOala888/GB_kernel"},"path":{"kind":"string","value":"linux_kernel_galaxyplayer-master/fs/cachefiles/internal.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":11228,"string":"11,228"}}},{"rowIdx":115086590,"cells":{"code":{"kind":"string","value":"/* Copyright 2012 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/* jshint globalstrict: false */\n/* umdutils ignore */\n\n(function (root, factory) {\n 'use strict';\n if (typeof define === 'function' && define.amd) {\ndefine('pdfjs-dist/build/pdf', ['exports'], factory);\n } else if (typeof exports !== 'undefined') {\n factory(exports);\n } else {\nfactory((root.pdfjsDistBuildPdf = {}));\n }\n}(this, function (exports) {\n // Use strict in our context only - users might not want it\n 'use strict';\n\nvar pdfjsVersion = '1.3.177';\nvar pdfjsBuild = '51b59bc';\n\n var pdfjsFilePath =\n typeof document !== 'undefined' && document.currentScript ?\n document.currentScript.src : null;\n\n var pdfjsLibs = {};\n\n (function pdfjsWrapper() {\n\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsSharedGlobal = {}));\n }\n}(this, function (exports) {\n\n var globalScope = (typeof window !== 'undefined') ? window :\n (typeof global !== 'undefined') ? global :\n (typeof self !== 'undefined') ? self : this;\n\n var isWorker = (typeof window === 'undefined');\n\n // The global PDFJS object exposes the API\n // In production, it will be declared outside a global wrapper\n // In development, it will be declared here\n if (!globalScope.PDFJS) {\n globalScope.PDFJS = {};\n }\n\n if (typeof pdfjsVersion !== 'undefined') {\n globalScope.PDFJS.version = pdfjsVersion;\n }\n if (typeof pdfjsVersion !== 'undefined') {\n globalScope.PDFJS.build = pdfjsBuild;\n }\n\n globalScope.PDFJS.pdfBug = false;\n\n exports.globalScope = globalScope;\n exports.isWorker = isWorker;\n exports.PDFJS = globalScope.PDFJS;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal);\n }\n}(this, function (exports, sharedGlobal) {\n\nvar PDFJS = sharedGlobal.PDFJS;\n\n/**\n * Optimised CSS custom property getter/setter.\n * @class\n */\nvar CustomStyle = (function CustomStyleClosure() {\n\n // As noted on: http://www.zachstronaut.com/posts/2009/02/17/\n // animate-css-transforms-firefox-webkit.html\n // in some versions of IE9 it is critical that ms appear in this list\n // before Moz\n var prefixes = ['ms', 'Moz', 'Webkit', 'O'];\n var _cache = {};\n\n function CustomStyle() {}\n\n CustomStyle.getProp = function get(propName, element) {\n // check cache only when no element is given\n if (arguments.length === 1 && typeof _cache[propName] === 'string') {\n return _cache[propName];\n }\n\n element = element || document.documentElement;\n var style = element.style, prefixed, uPropName;\n\n // test standard property first\n if (typeof style[propName] === 'string') {\n return (_cache[propName] = propName);\n }\n\n // capitalize\n uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);\n\n // test vendor specific properties\n for (var i = 0, l = prefixes.length; i < l; i++) {\n prefixed = prefixes[i] + uPropName;\n if (typeof style[prefixed] === 'string') {\n return (_cache[propName] = prefixed);\n }\n }\n\n //if all fails then set to undefined\n return (_cache[propName] = 'undefined');\n };\n\n CustomStyle.setProp = function set(propName, element, str) {\n var prop = this.getProp(propName);\n if (prop !== 'undefined') {\n element.style[prop] = str;\n }\n };\n\n return CustomStyle;\n})();\n\nPDFJS.CustomStyle = CustomStyle;\n\nexports.CustomStyle = CustomStyle;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal);\n }\n}(this, function (exports, sharedGlobal) {\n\nvar PDFJS = sharedGlobal.PDFJS;\nvar globalScope = sharedGlobal.globalScope;\n\nvar FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];\n\nvar TextRenderingMode = {\n FILL: 0,\n STROKE: 1,\n FILL_STROKE: 2,\n INVISIBLE: 3,\n FILL_ADD_TO_PATH: 4,\n STROKE_ADD_TO_PATH: 5,\n FILL_STROKE_ADD_TO_PATH: 6,\n ADD_TO_PATH: 7,\n FILL_STROKE_MASK: 3,\n ADD_TO_PATH_FLAG: 4\n};\n\nvar ImageKind = {\n GRAYSCALE_1BPP: 1,\n RGB_24BPP: 2,\n RGBA_32BPP: 3\n};\n\nvar AnnotationType = {\n TEXT: 1,\n LINK: 2,\n FREETEXT: 3,\n LINE: 4,\n SQUARE: 5,\n CIRCLE: 6,\n POLYGON: 7,\n POLYLINE: 8,\n HIGHLIGHT: 9,\n UNDERLINE: 10,\n SQUIGGLY: 11,\n STRIKEOUT: 12,\n STAMP: 13,\n CARET: 14,\n INK: 15,\n POPUP: 16,\n FILEATTACHMENT: 17,\n SOUND: 18,\n MOVIE: 19,\n WIDGET: 20,\n SCREEN: 21,\n PRINTERMARK: 22,\n TRAPNET: 23,\n WATERMARK: 24,\n THREED: 25,\n REDACT: 26\n};\n\nvar AnnotationFlag = {\n INVISIBLE: 0x01,\n HIDDEN: 0x02,\n PRINT: 0x04,\n NOZOOM: 0x08,\n NOROTATE: 0x10,\n NOVIEW: 0x20,\n READONLY: 0x40,\n LOCKED: 0x80,\n TOGGLENOVIEW: 0x100,\n LOCKEDCONTENTS: 0x200\n};\n\nvar AnnotationBorderStyleType = {\n SOLID: 1,\n DASHED: 2,\n BEVELED: 3,\n INSET: 4,\n UNDERLINE: 5\n};\n\nvar StreamType = {\n UNKNOWN: 0,\n FLATE: 1,\n LZW: 2,\n DCT: 3,\n JPX: 4,\n JBIG: 5,\n A85: 6,\n AHX: 7,\n CCF: 8,\n RL: 9\n};\n\nvar FontType = {\n UNKNOWN: 0,\n TYPE1: 1,\n TYPE1C: 2,\n CIDFONTTYPE0: 3,\n CIDFONTTYPE0C: 4,\n TRUETYPE: 5,\n CIDFONTTYPE2: 6,\n TYPE3: 7,\n OPENTYPE: 8,\n TYPE0: 9,\n MMTYPE1: 10\n};\n\nPDFJS.VERBOSITY_LEVELS = {\n errors: 0,\n warnings: 1,\n infos: 5\n};\n\n// All the possible operations for an operator list.\nvar OPS = PDFJS.OPS = {\n // Intentionally start from 1 so it is easy to spot bad operators that will be\n // 0's.\n dependency: 1,\n setLineWidth: 2,\n setLineCap: 3,\n setLineJoin: 4,\n setMiterLimit: 5,\n setDash: 6,\n setRenderingIntent: 7,\n setFlatness: 8,\n setGState: 9,\n save: 10,\n restore: 11,\n transform: 12,\n moveTo: 13,\n lineTo: 14,\n curveTo: 15,\n curveTo2: 16,\n curveTo3: 17,\n closePath: 18,\n rectangle: 19,\n stroke: 20,\n closeStroke: 21,\n fill: 22,\n eoFill: 23,\n fillStroke: 24,\n eoFillStroke: 25,\n closeFillStroke: 26,\n closeEOFillStroke: 27,\n endPath: 28,\n clip: 29,\n eoClip: 30,\n beginText: 31,\n endText: 32,\n setCharSpacing: 33,\n setWordSpacing: 34,\n setHScale: 35,\n setLeading: 36,\n setFont: 37,\n setTextRenderingMode: 38,\n setTextRise: 39,\n moveText: 40,\n setLeadingMoveText: 41,\n setTextMatrix: 42,\n nextLine: 43,\n showText: 44,\n showSpacedText: 45,\n nextLineShowText: 46,\n nextLineSetSpacingShowText: 47,\n setCharWidth: 48,\n setCharWidthAndBounds: 49,\n setStrokeColorSpace: 50,\n setFillColorSpace: 51,\n setStrokeColor: 52,\n setStrokeColorN: 53,\n setFillColor: 54,\n setFillColorN: 55,\n setStrokeGray: 56,\n setFillGray: 57,\n setStrokeRGBColor: 58,\n setFillRGBColor: 59,\n setStrokeCMYKColor: 60,\n setFillCMYKColor: 61,\n shadingFill: 62,\n beginInlineImage: 63,\n beginImageData: 64,\n endInlineImage: 65,\n paintXObject: 66,\n markPoint: 67,\n markPointProps: 68,\n beginMarkedContent: 69,\n beginMarkedContentProps: 70,\n endMarkedContent: 71,\n beginCompat: 72,\n endCompat: 73,\n paintFormXObjectBegin: 74,\n paintFormXObjectEnd: 75,\n beginGroup: 76,\n endGroup: 77,\n beginAnnotations: 78,\n endAnnotations: 79,\n beginAnnotation: 80,\n endAnnotation: 81,\n paintJpegXObject: 82,\n paintImageMaskXObject: 83,\n paintImageMaskXObjectGroup: 84,\n paintImageXObject: 85,\n paintInlineImageXObject: 86,\n paintInlineImageXObjectGroup: 87,\n paintImageXObjectRepeat: 88,\n paintImageMaskXObjectRepeat: 89,\n paintSolidColorImageMask: 90,\n constructPath: 91\n};\n\n// A notice for devs. These are good for things that are helpful to devs, such\n// as warning that Workers were disabled, which is important to devs but not\n// end users.\nfunction info(msg) {\n if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {\n console.log('Info: ' + msg);\n }\n}\n\n// Non-fatal warnings.\nfunction warn(msg) {\n if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {\n console.log('Warning: ' + msg);\n }\n}\n\n// Deprecated API function -- treated as warnings.\nfunction deprecated(details) {\n warn('Deprecated API usage: ' + details);\n}\n\n// Fatal errors that should trigger the fallback UI and halt execution by\n// throwing an exception.\nfunction error(msg) {\n if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {\n console.log('Error: ' + msg);\n console.log(backtrace());\n }\n throw new Error(msg);\n}\n\nfunction backtrace() {\n try {\n throw new Error();\n } catch (e) {\n return e.stack ? e.stack.split('\\n').slice(2).join('\\n') : '';\n }\n}\n\nfunction assert(cond, msg) {\n if (!cond) {\n error(msg);\n }\n}\n\nvar UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {\n unknown: 'unknown',\n forms: 'forms',\n javaScript: 'javaScript',\n smask: 'smask',\n shadingPattern: 'shadingPattern',\n font: 'font'\n};\n\n// Combines two URLs. The baseUrl shall be absolute URL. If the url is an\n// absolute URL, it will be returned as is.\nfunction combineUrl(baseUrl, url) {\n if (!url) {\n return baseUrl;\n }\n if (/^[a-z][a-z0-9+\\-.]*:/i.test(url)) {\n return url;\n }\n var i;\n if (url.charAt(0) === '/') {\n // absolute path\n i = baseUrl.indexOf('://');\n if (url.charAt(1) === '/') {\n ++i;\n } else {\n i = baseUrl.indexOf('/', i + 3);\n }\n return baseUrl.substring(0, i) + url;\n } else {\n // relative path\n var pathLength = baseUrl.length;\n i = baseUrl.lastIndexOf('#');\n pathLength = i >= 0 ? i : pathLength;\n i = baseUrl.lastIndexOf('?', pathLength);\n pathLength = i >= 0 ? i : pathLength;\n var prefixLength = baseUrl.lastIndexOf('/', pathLength);\n return baseUrl.substring(0, prefixLength + 1) + url;\n }\n}\n\n// Validates if URL is safe and allowed, e.g. to avoid XSS.\nfunction isValidUrl(url, allowRelative) {\n if (!url) {\n return false;\n }\n // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)\n // scheme = ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )\n var protocol = /^[a-z][a-z0-9+\\-.]*(?=:)/i.exec(url);\n if (!protocol) {\n return allowRelative;\n }\n protocol = protocol[0].toLowerCase();\n switch (protocol) {\n case 'http':\n case 'https':\n case 'ftp':\n case 'mailto':\n case 'tel':\n return true;\n default:\n return false;\n }\n}\nPDFJS.isValidUrl = isValidUrl;\n\nfunction shadow(obj, prop, value) {\n Object.defineProperty(obj, prop, { value: value,\n enumerable: true,\n configurable: true,\n writable: false });\n return value;\n}\nPDFJS.shadow = shadow;\n\nvar LinkTarget = PDFJS.LinkTarget = {\n NONE: 0, // Default value.\n SELF: 1,\n BLANK: 2,\n PARENT: 3,\n TOP: 4,\n};\nvar LinkTargetStringMap = [\n '',\n '_self',\n '_blank',\n '_parent',\n '_top'\n];\n\nfunction isExternalLinkTargetSet() {\n if (PDFJS.openExternalLinksInNewWindow) {\n deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +\n '\"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK\" instead.');\n if (PDFJS.externalLinkTarget === LinkTarget.NONE) {\n PDFJS.externalLinkTarget = LinkTarget.BLANK;\n }\n // Reset the deprecated parameter, to suppress further warnings.\n PDFJS.openExternalLinksInNewWindow = false;\n }\n switch (PDFJS.externalLinkTarget) {\n case LinkTarget.NONE:\n return false;\n case LinkTarget.SELF:\n case LinkTarget.BLANK:\n case LinkTarget.PARENT:\n case LinkTarget.TOP:\n return true;\n }\n warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget);\n // Reset the external link target, to suppress further warnings.\n PDFJS.externalLinkTarget = LinkTarget.NONE;\n return false;\n}\nPDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet;\n\nvar PasswordResponses = PDFJS.PasswordResponses = {\n NEED_PASSWORD: 1,\n INCORRECT_PASSWORD: 2\n};\n\nvar PasswordException = (function PasswordExceptionClosure() {\n function PasswordException(msg, code) {\n this.name = 'PasswordException';\n this.message = msg;\n this.code = code;\n }\n\n PasswordException.prototype = new Error();\n PasswordException.constructor = PasswordException;\n\n return PasswordException;\n})();\nPDFJS.PasswordException = PasswordException;\n\nvar UnknownErrorException = (function UnknownErrorExceptionClosure() {\n function UnknownErrorException(msg, details) {\n this.name = 'UnknownErrorException';\n this.message = msg;\n this.details = details;\n }\n\n UnknownErrorException.prototype = new Error();\n UnknownErrorException.constructor = UnknownErrorException;\n\n return UnknownErrorException;\n})();\nPDFJS.UnknownErrorException = UnknownErrorException;\n\nvar InvalidPDFException = (function InvalidPDFExceptionClosure() {\n function InvalidPDFException(msg) {\n this.name = 'InvalidPDFException';\n this.message = msg;\n }\n\n InvalidPDFException.prototype = new Error();\n InvalidPDFException.constructor = InvalidPDFException;\n\n return InvalidPDFException;\n})();\nPDFJS.InvalidPDFException = InvalidPDFException;\n\nvar MissingPDFException = (function MissingPDFExceptionClosure() {\n function MissingPDFException(msg) {\n this.name = 'MissingPDFException';\n this.message = msg;\n }\n\n MissingPDFException.prototype = new Error();\n MissingPDFException.constructor = MissingPDFException;\n\n return MissingPDFException;\n})();\nPDFJS.MissingPDFException = MissingPDFException;\n\nvar UnexpectedResponseException =\n (function UnexpectedResponseExceptionClosure() {\n function UnexpectedResponseException(msg, status) {\n this.name = 'UnexpectedResponseException';\n this.message = msg;\n this.status = status;\n }\n\n UnexpectedResponseException.prototype = new Error();\n UnexpectedResponseException.constructor = UnexpectedResponseException;\n\n return UnexpectedResponseException;\n})();\nPDFJS.UnexpectedResponseException = UnexpectedResponseException;\n\nvar NotImplementedException = (function NotImplementedExceptionClosure() {\n function NotImplementedException(msg) {\n this.message = msg;\n }\n\n NotImplementedException.prototype = new Error();\n NotImplementedException.prototype.name = 'NotImplementedException';\n NotImplementedException.constructor = NotImplementedException;\n\n return NotImplementedException;\n})();\n\nvar MissingDataException = (function MissingDataExceptionClosure() {\n function MissingDataException(begin, end) {\n this.begin = begin;\n this.end = end;\n this.message = 'Missing data [' + begin + ', ' + end + ')';\n }\n\n MissingDataException.prototype = new Error();\n MissingDataException.prototype.name = 'MissingDataException';\n MissingDataException.constructor = MissingDataException;\n\n return MissingDataException;\n})();\n\nvar XRefParseException = (function XRefParseExceptionClosure() {\n function XRefParseException(msg) {\n this.message = msg;\n }\n\n XRefParseException.prototype = new Error();\n XRefParseException.prototype.name = 'XRefParseException';\n XRefParseException.constructor = XRefParseException;\n\n return XRefParseException;\n})();\n\nvar NullCharactersRegExp = /\\x00/g;\n\nfunction removeNullCharacters(str) {\n if (typeof str !== 'string') {\n warn('The argument for removeNullCharacters must be a string.');\n return str;\n }\n return str.replace(NullCharactersRegExp, '');\n}\nPDFJS.removeNullCharacters = removeNullCharacters;\n\nfunction bytesToString(bytes) {\n assert(bytes !== null && typeof bytes === 'object' &&\n bytes.length !== undefined, 'Invalid argument for bytesToString');\n var length = bytes.length;\n var MAX_ARGUMENT_COUNT = 8192;\n if (length < MAX_ARGUMENT_COUNT) {\n return String.fromCharCode.apply(null, bytes);\n }\n var strBuf = [];\n for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {\n var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);\n var chunk = bytes.subarray(i, chunkEnd);\n strBuf.push(String.fromCharCode.apply(null, chunk));\n }\n return strBuf.join('');\n}\n\nfunction stringToBytes(str) {\n assert(typeof str === 'string', 'Invalid argument for stringToBytes');\n var length = str.length;\n var bytes = new Uint8Array(length);\n for (var i = 0; i < length; ++i) {\n bytes[i] = str.charCodeAt(i) & 0xFF;\n }\n return bytes;\n}\n\nfunction string32(value) {\n return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,\n (value >> 8) & 0xff, value & 0xff);\n}\n\nfunction log2(x) {\n var n = 1, i = 0;\n while (x > n) {\n n <<= 1;\n i++;\n }\n return i;\n}\n\nfunction readInt8(data, start) {\n return (data[start] << 24) >> 24;\n}\n\nfunction readUint16(data, offset) {\n return (data[offset] << 8) | data[offset + 1];\n}\n\nfunction readUint32(data, offset) {\n return ((data[offset] << 24) | (data[offset + 1] << 16) |\n (data[offset + 2] << 8) | data[offset + 3]) >>> 0;\n}\n\n// Lazy test the endianness of the platform\n// NOTE: This will be 'true' for simulated TypedArrays\nfunction isLittleEndian() {\n var buffer8 = new Uint8Array(2);\n buffer8[0] = 1;\n var buffer16 = new Uint16Array(buffer8.buffer);\n return (buffer16[0] === 1);\n}\n\nObject.defineProperty(PDFJS, 'isLittleEndian', {\n configurable: true,\n get: function PDFJS_isLittleEndian() {\n return shadow(PDFJS, 'isLittleEndian', isLittleEndian());\n }\n});\n\n // Lazy test if the userAgent support CanvasTypedArrays\nfunction hasCanvasTypedArrays() {\n var canvas = document.createElement('canvas');\n canvas.width = canvas.height = 1;\n var ctx = canvas.getContext('2d');\n var imageData = ctx.createImageData(1, 1);\n return (typeof imageData.data.buffer !== 'undefined');\n}\n\nObject.defineProperty(PDFJS, 'hasCanvasTypedArrays', {\n configurable: true,\n get: function PDFJS_hasCanvasTypedArrays() {\n return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());\n }\n});\n\nvar Uint32ArrayView = (function Uint32ArrayViewClosure() {\n\n function Uint32ArrayView(buffer, length) {\n this.buffer = buffer;\n this.byteLength = buffer.length;\n this.length = length === undefined ? (this.byteLength >> 2) : length;\n ensureUint32ArrayViewProps(this.length);\n }\n Uint32ArrayView.prototype = Object.create(null);\n\n var uint32ArrayViewSetters = 0;\n function createUint32ArrayProp(index) {\n return {\n get: function () {\n var buffer = this.buffer, offset = index << 2;\n return (buffer[offset] | (buffer[offset + 1] << 8) |\n (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;\n },\n set: function (value) {\n var buffer = this.buffer, offset = index << 2;\n buffer[offset] = value & 255;\n buffer[offset + 1] = (value >> 8) & 255;\n buffer[offset + 2] = (value >> 16) & 255;\n buffer[offset + 3] = (value >>> 24) & 255;\n }\n };\n }\n\n function ensureUint32ArrayViewProps(length) {\n while (uint32ArrayViewSetters < length) {\n Object.defineProperty(Uint32ArrayView.prototype,\n uint32ArrayViewSetters,\n createUint32ArrayProp(uint32ArrayViewSetters));\n uint32ArrayViewSetters++;\n }\n }\n\n return Uint32ArrayView;\n})();\n\nexports.Uint32ArrayView = Uint32ArrayView;\n\nvar IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];\n\nvar Util = PDFJS.Util = (function UtilClosure() {\n function Util() {}\n\n var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];\n\n // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids\n // creating many intermediate strings.\n Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {\n rgbBuf[1] = r;\n rgbBuf[3] = g;\n rgbBuf[5] = b;\n return rgbBuf.join('');\n };\n\n // Concatenates two transformation matrices together and returns the result.\n Util.transform = function Util_transform(m1, m2) {\n return [\n m1[0] * m2[0] + m1[2] * m2[1],\n m1[1] * m2[0] + m1[3] * m2[1],\n m1[0] * m2[2] + m1[2] * m2[3],\n m1[1] * m2[2] + m1[3] * m2[3],\n m1[0] * m2[4] + m1[2] * m2[5] + m1[4],\n m1[1] * m2[4] + m1[3] * m2[5] + m1[5]\n ];\n };\n\n // For 2d affine transforms\n Util.applyTransform = function Util_applyTransform(p, m) {\n var xt = p[0] * m[0] + p[1] * m[2] + m[4];\n var yt = p[0] * m[1] + p[1] * m[3] + m[5];\n return [xt, yt];\n };\n\n Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {\n var d = m[0] * m[3] - m[1] * m[2];\n var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;\n var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;\n return [xt, yt];\n };\n\n // Applies the transform to the rectangle and finds the minimum axially\n // aligned bounding box.\n Util.getAxialAlignedBoundingBox =\n function Util_getAxialAlignedBoundingBox(r, m) {\n\n var p1 = Util.applyTransform(r, m);\n var p2 = Util.applyTransform(r.slice(2, 4), m);\n var p3 = Util.applyTransform([r[0], r[3]], m);\n var p4 = Util.applyTransform([r[2], r[1]], m);\n return [\n Math.min(p1[0], p2[0], p3[0], p4[0]),\n Math.min(p1[1], p2[1], p3[1], p4[1]),\n Math.max(p1[0], p2[0], p3[0], p4[0]),\n Math.max(p1[1], p2[1], p3[1], p4[1])\n ];\n };\n\n Util.inverseTransform = function Util_inverseTransform(m) {\n var d = m[0] * m[3] - m[1] * m[2];\n return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,\n (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];\n };\n\n // Apply a generic 3d matrix M on a 3-vector v:\n // | a b c | | X |\n // | d e f | x | Y |\n // | g h i | | Z |\n // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],\n // with v as [X,Y,Z]\n Util.apply3dTransform = function Util_apply3dTransform(m, v) {\n return [\n m[0] * v[0] + m[1] * v[1] + m[2] * v[2],\n m[3] * v[0] + m[4] * v[1] + m[5] * v[2],\n m[6] * v[0] + m[7] * v[1] + m[8] * v[2]\n ];\n };\n\n // This calculation uses Singular Value Decomposition.\n // The SVD can be represented with formula A = USV. We are interested in the\n // matrix S here because it represents the scale values.\n Util.singularValueDecompose2dScale =\n function Util_singularValueDecompose2dScale(m) {\n\n var transpose = [m[0], m[2], m[1], m[3]];\n\n // Multiply matrix m with its transpose.\n var a = m[0] * transpose[0] + m[1] * transpose[2];\n var b = m[0] * transpose[1] + m[1] * transpose[3];\n var c = m[2] * transpose[0] + m[3] * transpose[2];\n var d = m[2] * transpose[1] + m[3] * transpose[3];\n\n // Solve the second degree polynomial to get roots.\n var first = (a + d) / 2;\n var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;\n var sx = first + second || 1;\n var sy = first - second || 1;\n\n // Scale values are the square roots of the eigenvalues.\n return [Math.sqrt(sx), Math.sqrt(sy)];\n };\n\n // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)\n // For coordinate systems whose origin lies in the bottom-left, this\n // means normalization to (BL,TR) ordering. For systems with origin in the\n // top-left, this means (TL,BR) ordering.\n Util.normalizeRect = function Util_normalizeRect(rect) {\n var r = rect.slice(0); // clone rect\n if (rect[0] > rect[2]) {\n r[0] = rect[2];\n r[2] = rect[0];\n }\n if (rect[1] > rect[3]) {\n r[1] = rect[3];\n r[3] = rect[1];\n }\n return r;\n };\n\n // Returns a rectangle [x1, y1, x2, y2] corresponding to the\n // intersection of rect1 and rect2. If no intersection, returns 'false'\n // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]\n Util.intersect = function Util_intersect(rect1, rect2) {\n function compare(a, b) {\n return a - b;\n }\n\n // Order points along the axes\n var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),\n orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),\n result = [];\n\n rect1 = Util.normalizeRect(rect1);\n rect2 = Util.normalizeRect(rect2);\n\n // X: first and second points belong to different rectangles?\n if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||\n (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {\n // Intersection must be between second and third points\n result[0] = orderedX[1];\n result[2] = orderedX[2];\n } else {\n return false;\n }\n\n // Y: first and second points belong to different rectangles?\n if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||\n (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {\n // Intersection must be between second and third points\n result[1] = orderedY[1];\n result[3] = orderedY[2];\n } else {\n return false;\n }\n\n return result;\n };\n\n Util.sign = function Util_sign(num) {\n return num < 0 ? -1 : 1;\n };\n\n Util.appendToArray = function Util_appendToArray(arr1, arr2) {\n Array.prototype.push.apply(arr1, arr2);\n };\n\n Util.prependToArray = function Util_prependToArray(arr1, arr2) {\n Array.prototype.unshift.apply(arr1, arr2);\n };\n\n Util.extendObj = function extendObj(obj1, obj2) {\n for (var key in obj2) {\n obj1[key] = obj2[key];\n }\n };\n\n Util.getInheritableProperty = function Util_getInheritableProperty(dict,\n name) {\n while (dict && !dict.has(name)) {\n dict = dict.get('Parent');\n }\n if (!dict) {\n return null;\n }\n return dict.get(name);\n };\n\n Util.inherit = function Util_inherit(sub, base, prototype) {\n sub.prototype = Object.create(base.prototype);\n sub.prototype.constructor = sub;\n for (var prop in prototype) {\n sub.prototype[prop] = prototype[prop];\n }\n };\n\n Util.loadScript = function Util_loadScript(src, callback) {\n var script = document.createElement('script');\n var loaded = false;\n script.setAttribute('src', src);\n if (callback) {\n script.onload = function() {\n if (!loaded) {\n callback();\n }\n loaded = true;\n };\n }\n document.getElementsByTagName('head')[0].appendChild(script);\n };\n\n return Util;\n})();\n\n/**\n * PDF page viewport created based on scale, rotation and offset.\n * @class\n * @alias PDFJS.PageViewport\n */\nvar PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {\n /**\n * @constructor\n * @private\n * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.\n * @param scale {number} scale of the viewport.\n * @param rotation {number} rotations of the viewport in degrees.\n * @param offsetX {number} offset X\n * @param offsetY {number} offset Y\n * @param dontFlip {boolean} if true, axis Y will not be flipped.\n */\n function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {\n this.viewBox = viewBox;\n this.scale = scale;\n this.rotation = rotation;\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n\n // creating transform to convert pdf coordinate system to the normal\n // canvas like coordinates taking in account scale and rotation\n var centerX = (viewBox[2] + viewBox[0]) / 2;\n var centerY = (viewBox[3] + viewBox[1]) / 2;\n var rotateA, rotateB, rotateC, rotateD;\n rotation = rotation % 360;\n rotation = rotation < 0 ? rotation + 360 : rotation;\n switch (rotation) {\n case 180:\n rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;\n break;\n case 90:\n rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;\n break;\n case 270:\n rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;\n break;\n //case 0:\n default:\n rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;\n break;\n }\n\n if (dontFlip) {\n rotateC = -rotateC; rotateD = -rotateD;\n }\n\n var offsetCanvasX, offsetCanvasY;\n var width, height;\n if (rotateA === 0) {\n offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;\n width = Math.abs(viewBox[3] - viewBox[1]) * scale;\n height = Math.abs(viewBox[2] - viewBox[0]) * scale;\n } else {\n offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;\n offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;\n width = Math.abs(viewBox[2] - viewBox[0]) * scale;\n height = Math.abs(viewBox[3] - viewBox[1]) * scale;\n }\n // creating transform for the following operations:\n // translate(-centerX, -centerY), rotate and flip vertically,\n // scale, and translate(offsetCanvasX, offsetCanvasY)\n this.transform = [\n rotateA * scale,\n rotateB * scale,\n rotateC * scale,\n rotateD * scale,\n offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,\n offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY\n ];\n\n this.width = width;\n this.height = height;\n this.fontScale = scale;\n }\n PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {\n /**\n * Clones viewport with additional properties.\n * @param args {Object} (optional) If specified, may contain the 'scale' or\n * 'rotation' properties to override the corresponding properties in\n * the cloned viewport.\n * @returns {PDFJS.PageViewport} Cloned viewport.\n */\n clone: function PageViewPort_clone(args) {\n args = args || {};\n var scale = 'scale' in args ? args.scale : this.scale;\n var rotation = 'rotation' in args ? args.rotation : this.rotation;\n return new PageViewport(this.viewBox.slice(), scale, rotation,\n this.offsetX, this.offsetY, args.dontFlip);\n },\n /**\n * Converts PDF point to the viewport coordinates. For examples, useful for\n * converting PDF location into canvas pixel coordinates.\n * @param x {number} X coordinate.\n * @param y {number} Y coordinate.\n * @returns {Object} Object that contains 'x' and 'y' properties of the\n * point in the viewport coordinate space.\n * @see {@link convertToPdfPoint}\n * @see {@link convertToViewportRectangle}\n */\n convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {\n return Util.applyTransform([x, y], this.transform);\n },\n /**\n * Converts PDF rectangle to the viewport coordinates.\n * @param rect {Array} xMin, yMin, xMax and yMax coordinates.\n * @returns {Array} Contains corresponding coordinates of the rectangle\n * in the viewport coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToViewportRectangle:\n function PageViewport_convertToViewportRectangle(rect) {\n var tl = Util.applyTransform([rect[0], rect[1]], this.transform);\n var br = Util.applyTransform([rect[2], rect[3]], this.transform);\n return [tl[0], tl[1], br[0], br[1]];\n },\n /**\n * Converts viewport coordinates to the PDF location. For examples, useful\n * for converting canvas pixel location into PDF one.\n * @param x {number} X coordinate.\n * @param y {number} Y coordinate.\n * @returns {Object} Object that contains 'x' and 'y' properties of the\n * point in the PDF coordinate space.\n * @see {@link convertToViewportPoint}\n */\n convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {\n return Util.applyInverseTransform([x, y], this.transform);\n }\n };\n return PageViewport;\n})();\n\nvar PDFStringTranslateTable = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,\n 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,\n 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,\n 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC\n];\n\nfunction stringToPDFString(str) {\n var i, n = str.length, strBuf = [];\n if (str[0] === '\\xFE' && str[1] === '\\xFF') {\n // UTF16BE BOM\n for (i = 2; i < n; i += 2) {\n strBuf.push(String.fromCharCode(\n (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));\n }\n } else {\n for (i = 0; i < n; ++i) {\n var code = PDFStringTranslateTable[str.charCodeAt(i)];\n strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));\n }\n }\n return strBuf.join('');\n}\n\nfunction stringToUTF8String(str) {\n return decodeURIComponent(escape(str));\n}\n\nfunction utf8StringToString(str) {\n return unescape(encodeURIComponent(str));\n}\n\nfunction isEmptyObj(obj) {\n for (var key in obj) {\n return false;\n }\n return true;\n}\n\nfunction isBool(v) {\n return typeof v === 'boolean';\n}\n\nfunction isInt(v) {\n return typeof v === 'number' && ((v | 0) === v);\n}\n\nfunction isNum(v) {\n return typeof v === 'number';\n}\n\nfunction isString(v) {\n return typeof v === 'string';\n}\n\nfunction isArray(v) {\n return v instanceof Array;\n}\n\nfunction isArrayBuffer(v) {\n return typeof v === 'object' && v !== null && v.byteLength !== undefined;\n}\n\n/**\n * Promise Capability object.\n *\n * @typedef {Object} PromiseCapability\n * @property {Promise} promise - A promise object.\n * @property {function} resolve - Fullfills the promise.\n * @property {function} reject - Rejects the promise.\n */\n\n/**\n * Creates a promise capability object.\n * @alias PDFJS.createPromiseCapability\n *\n * @return {PromiseCapability} A capability object contains:\n * - a Promise, resolve and reject methods.\n */\nfunction createPromiseCapability() {\n var capability = {};\n capability.promise = new Promise(function (resolve, reject) {\n capability.resolve = resolve;\n capability.reject = reject;\n });\n return capability;\n}\n\nPDFJS.createPromiseCapability = createPromiseCapability;\n\n/**\n * Polyfill for Promises:\n * The following promise implementation tries to generally implement the\n * Promise/A+ spec. Some notable differences from other promise libaries are:\n * - There currently isn't a seperate deferred and promise object.\n * - Unhandled rejections eventually show an error if they aren't handled.\n *\n * Based off of the work in:\n * https://bugzilla.mozilla.org/show_bug.cgi?id=810490\n */\n(function PromiseClosure() {\n if (globalScope.Promise) {\n // Promises existing in the DOM/Worker, checking presence of all/resolve\n if (typeof globalScope.Promise.all !== 'function') {\n globalScope.Promise.all = function (iterable) {\n var count = 0, results = [], resolve, reject;\n var promise = new globalScope.Promise(function (resolve_, reject_) {\n resolve = resolve_;\n reject = reject_;\n });\n iterable.forEach(function (p, i) {\n count++;\n p.then(function (result) {\n results[i] = result;\n count--;\n if (count === 0) {\n resolve(results);\n }\n }, reject);\n });\n if (count === 0) {\n resolve(results);\n }\n return promise;\n };\n }\n if (typeof globalScope.Promise.resolve !== 'function') {\n globalScope.Promise.resolve = function (value) {\n return new globalScope.Promise(function (resolve) { resolve(value); });\n };\n }\n if (typeof globalScope.Promise.reject !== 'function') {\n globalScope.Promise.reject = function (reason) {\n return new globalScope.Promise(function (resolve, reject) {\n reject(reason);\n });\n };\n }\n if (typeof globalScope.Promise.prototype.catch !== 'function') {\n globalScope.Promise.prototype.catch = function (onReject) {\n return globalScope.Promise.prototype.then(undefined, onReject);\n };\n }\n return;\n }\n var STATUS_PENDING = 0;\n var STATUS_RESOLVED = 1;\n var STATUS_REJECTED = 2;\n\n // In an attempt to avoid silent exceptions, unhandled rejections are\n // tracked and if they aren't handled in a certain amount of time an\n // error is logged.\n var REJECTION_TIMEOUT = 500;\n\n var HandlerManager = {\n handlers: [],\n running: false,\n unhandledRejections: [],\n pendingRejectionCheck: false,\n\n scheduleHandlers: function scheduleHandlers(promise) {\n if (promise._status === STATUS_PENDING) {\n return;\n }\n\n this.handlers = this.handlers.concat(promise._handlers);\n promise._handlers = [];\n\n if (this.running) {\n return;\n }\n this.running = true;\n\n setTimeout(this.runHandlers.bind(this), 0);\n },\n\n runHandlers: function runHandlers() {\n var RUN_TIMEOUT = 1; // ms\n var timeoutAt = Date.now() + RUN_TIMEOUT;\n while (this.handlers.length > 0) {\n var handler = this.handlers.shift();\n\n var nextStatus = handler.thisPromise._status;\n var nextValue = handler.thisPromise._value;\n\n try {\n if (nextStatus === STATUS_RESOLVED) {\n if (typeof handler.onResolve === 'function') {\n nextValue = handler.onResolve(nextValue);\n }\n } else if (typeof handler.onReject === 'function') {\n nextValue = handler.onReject(nextValue);\n nextStatus = STATUS_RESOLVED;\n\n if (handler.thisPromise._unhandledRejection) {\n this.removeUnhandeledRejection(handler.thisPromise);\n }\n }\n } catch (ex) {\n nextStatus = STATUS_REJECTED;\n nextValue = ex;\n }\n\n handler.nextPromise._updateStatus(nextStatus, nextValue);\n if (Date.now() >= timeoutAt) {\n break;\n }\n }\n\n if (this.handlers.length > 0) {\n setTimeout(this.runHandlers.bind(this), 0);\n return;\n }\n\n this.running = false;\n },\n\n addUnhandledRejection: function addUnhandledRejection(promise) {\n this.unhandledRejections.push({\n promise: promise,\n time: Date.now()\n });\n this.scheduleRejectionCheck();\n },\n\n removeUnhandeledRejection: function removeUnhandeledRejection(promise) {\n promise._unhandledRejection = false;\n for (var i = 0; i < this.unhandledRejections.length; i++) {\n if (this.unhandledRejections[i].promise === promise) {\n this.unhandledRejections.splice(i);\n i--;\n }\n }\n },\n\n scheduleRejectionCheck: function scheduleRejectionCheck() {\n if (this.pendingRejectionCheck) {\n return;\n }\n this.pendingRejectionCheck = true;\n setTimeout(function rejectionCheck() {\n this.pendingRejectionCheck = false;\n var now = Date.now();\n for (var i = 0; i < this.unhandledRejections.length; i++) {\n if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {\n var unhandled = this.unhandledRejections[i].promise._value;\n var msg = 'Unhandled rejection: ' + unhandled;\n if (unhandled.stack) {\n msg += '\\n' + unhandled.stack;\n }\n warn(msg);\n this.unhandledRejections.splice(i);\n i--;\n }\n }\n if (this.unhandledRejections.length) {\n this.scheduleRejectionCheck();\n }\n }.bind(this), REJECTION_TIMEOUT);\n }\n };\n\n function Promise(resolver) {\n this._status = STATUS_PENDING;\n this._handlers = [];\n try {\n resolver.call(this, this._resolve.bind(this), this._reject.bind(this));\n } catch (e) {\n this._reject(e);\n }\n }\n /**\n * Builds a promise that is resolved when all the passed in promises are\n * resolved.\n * @param {array} array of data and/or promises to wait for.\n * @return {Promise} New dependant promise.\n */\n Promise.all = function Promise_all(promises) {\n var resolveAll, rejectAll;\n var deferred = new Promise(function (resolve, reject) {\n resolveAll = resolve;\n rejectAll = reject;\n });\n var unresolved = promises.length;\n var results = [];\n if (unresolved === 0) {\n resolveAll(results);\n return deferred;\n }\n function reject(reason) {\n if (deferred._status === STATUS_REJECTED) {\n return;\n }\n results = [];\n rejectAll(reason);\n }\n for (var i = 0, ii = promises.length; i < ii; ++i) {\n var promise = promises[i];\n var resolve = (function(i) {\n return function(value) {\n if (deferred._status === STATUS_REJECTED) {\n return;\n }\n results[i] = value;\n unresolved--;\n if (unresolved === 0) {\n resolveAll(results);\n }\n };\n })(i);\n if (Promise.isPromise(promise)) {\n promise.then(resolve, reject);\n } else {\n resolve(promise);\n }\n }\n return deferred;\n };\n\n /**\n * Checks if the value is likely a promise (has a 'then' function).\n * @return {boolean} true if value is thenable\n */\n Promise.isPromise = function Promise_isPromise(value) {\n return value && typeof value.then === 'function';\n };\n\n /**\n * Creates resolved promise\n * @param value resolve value\n * @returns {Promise}\n */\n Promise.resolve = function Promise_resolve(value) {\n return new Promise(function (resolve) { resolve(value); });\n };\n\n /**\n * Creates rejected promise\n * @param reason rejection value\n * @returns {Promise}\n */\n Promise.reject = function Promise_reject(reason) {\n return new Promise(function (resolve, reject) { reject(reason); });\n };\n\n Promise.prototype = {\n _status: null,\n _value: null,\n _handlers: null,\n _unhandledRejection: null,\n\n _updateStatus: function Promise__updateStatus(status, value) {\n if (this._status === STATUS_RESOLVED ||\n this._status === STATUS_REJECTED) {\n return;\n }\n\n if (status === STATUS_RESOLVED &&\n Promise.isPromise(value)) {\n value.then(this._updateStatus.bind(this, STATUS_RESOLVED),\n this._updateStatus.bind(this, STATUS_REJECTED));\n return;\n }\n\n this._status = status;\n this._value = value;\n\n if (status === STATUS_REJECTED && this._handlers.length === 0) {\n this._unhandledRejection = true;\n HandlerManager.addUnhandledRejection(this);\n }\n\n HandlerManager.scheduleHandlers(this);\n },\n\n _resolve: function Promise_resolve(value) {\n this._updateStatus(STATUS_RESOLVED, value);\n },\n\n _reject: function Promise_reject(reason) {\n this._updateStatus(STATUS_REJECTED, reason);\n },\n\n then: function Promise_then(onResolve, onReject) {\n var nextPromise = new Promise(function (resolve, reject) {\n this.resolve = resolve;\n this.reject = reject;\n });\n this._handlers.push({\n thisPromise: this,\n onResolve: onResolve,\n onReject: onReject,\n nextPromise: nextPromise\n });\n HandlerManager.scheduleHandlers(this);\n return nextPromise;\n },\n\n catch: function Promise_catch(onReject) {\n return this.then(undefined, onReject);\n }\n };\n\n globalScope.Promise = Promise;\n})();\n\nvar StatTimer = (function StatTimerClosure() {\n function rpad(str, pad, length) {\n while (str.length < length) {\n str += pad;\n }\n return str;\n }\n function StatTimer() {\n this.started = {};\n this.times = [];\n this.enabled = true;\n }\n StatTimer.prototype = {\n time: function StatTimer_time(name) {\n if (!this.enabled) {\n return;\n }\n if (name in this.started) {\n warn('Timer is already running for ' + name);\n }\n this.started[name] = Date.now();\n },\n timeEnd: function StatTimer_timeEnd(name) {\n if (!this.enabled) {\n return;\n }\n if (!(name in this.started)) {\n warn('Timer has not been started for ' + name);\n }\n this.times.push({\n 'name': name,\n 'start': this.started[name],\n 'end': Date.now()\n });\n // Remove timer from started so it can be called again.\n delete this.started[name];\n },\n toString: function StatTimer_toString() {\n var i, ii;\n var times = this.times;\n var out = '';\n // Find the longest name for padding purposes.\n var longest = 0;\n for (i = 0, ii = times.length; i < ii; ++i) {\n var name = times[i]['name'];\n if (name.length > longest) {\n longest = name.length;\n }\n }\n for (i = 0, ii = times.length; i < ii; ++i) {\n var span = times[i];\n var duration = span.end - span.start;\n out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\\n';\n }\n return out;\n }\n };\n return StatTimer;\n})();\n\nPDFJS.createBlob = function createBlob(data, contentType) {\n if (typeof Blob !== 'undefined') {\n return new Blob([data], { type: contentType });\n }\n // Blob builder is deprecated in FF14 and removed in FF18.\n var bb = new MozBlobBuilder();\n bb.append(data);\n return bb.getBlob(contentType);\n};\n\nPDFJS.createObjectURL = (function createObjectURLClosure() {\n // Blob/createObjectURL is not available, falling back to data schema.\n var digits =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n\n return function createObjectURL(data, contentType) {\n if (!PDFJS.disableCreateObjectURL &&\n typeof URL !== 'undefined' && URL.createObjectURL) {\n var blob = PDFJS.createBlob(data, contentType);\n return URL.createObjectURL(blob);\n }\n\n var buffer = 'data:' + contentType + ';base64,';\n for (var i = 0, ii = data.length; i < ii; i += 3) {\n var b1 = data[i] & 0xFF;\n var b2 = data[i + 1] & 0xFF;\n var b3 = data[i + 2] & 0xFF;\n var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);\n var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;\n var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;\n buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];\n }\n return buffer;\n };\n})();\n\nfunction MessageHandler(sourceName, targetName, comObj) {\n this.sourceName = sourceName;\n this.targetName = targetName;\n this.comObj = comObj;\n this.callbackIndex = 1;\n this.postMessageTransfers = true;\n var callbacksCapabilities = this.callbacksCapabilities = {};\n var ah = this.actionHandler = {};\n\n this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {\n var data = event.data;\n if (data.targetName !== this.sourceName) {\n return;\n }\n if (data.isReply) {\n var callbackId = data.callbackId;\n if (data.callbackId in callbacksCapabilities) {\n var callback = callbacksCapabilities[callbackId];\n delete callbacksCapabilities[callbackId];\n if ('error' in data) {\n callback.reject(data.error);\n } else {\n callback.resolve(data.data);\n }\n } else {\n error('Cannot resolve callback ' + callbackId);\n }\n } else if (data.action in ah) {\n var action = ah[data.action];\n if (data.callbackId) {\n var sourceName = this.sourceName;\n var targetName = data.sourceName;\n Promise.resolve().then(function () {\n return action[0].call(action[1], data.data);\n }).then(function (result) {\n comObj.postMessage({\n sourceName: sourceName,\n targetName: targetName,\n isReply: true,\n callbackId: data.callbackId,\n data: result\n });\n }, function (reason) {\n if (reason instanceof Error) {\n // Serialize error to avoid \"DataCloneError\"\n reason = reason + '';\n }\n comObj.postMessage({\n sourceName: sourceName,\n targetName: targetName,\n isReply: true,\n callbackId: data.callbackId,\n error: reason\n });\n });\n } else {\n action[0].call(action[1], data.data);\n }\n } else {\n error('Unknown action from worker: ' + data.action);\n }\n }.bind(this);\n comObj.addEventListener('message', this._onComObjOnMessage);\n}\n\nMessageHandler.prototype = {\n on: function messageHandlerOn(actionName, handler, scope) {\n var ah = this.actionHandler;\n if (ah[actionName]) {\n error('There is already an actionName called \"' + actionName + '\"');\n }\n ah[actionName] = [handler, scope];\n },\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * @param {String} actionName Action to call.\n * @param {JSON} data JSON data to send.\n * @param {Array} [transfers] Optional list of transfers/ArrayBuffers\n */\n send: function messageHandlerSend(actionName, data, transfers) {\n var message = {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n data: data\n };\n this.postMessage(message, transfers);\n },\n /**\n * Sends a message to the comObj to invoke the action with the supplied data.\n * Expects that other side will callback with the response.\n * @param {String} actionName Action to call.\n * @param {JSON} data JSON data to send.\n * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.\n * @returns {Promise} Promise to be resolved with response data.\n */\n sendWithPromise:\n function messageHandlerSendWithPromise(actionName, data, transfers) {\n var callbackId = this.callbackIndex++;\n var message = {\n sourceName: this.sourceName,\n targetName: this.targetName,\n action: actionName,\n data: data,\n callbackId: callbackId\n };\n var capability = createPromiseCapability();\n this.callbacksCapabilities[callbackId] = capability;\n try {\n this.postMessage(message, transfers);\n } catch (e) {\n capability.reject(e);\n }\n return capability.promise;\n },\n /**\n * Sends raw message to the comObj.\n * @private\n * @param message {Object} Raw message.\n * @param transfers List of transfers/ArrayBuffers, or undefined.\n */\n postMessage: function (message, transfers) {\n if (transfers && this.postMessageTransfers) {\n this.comObj.postMessage(message, transfers);\n } else {\n this.comObj.postMessage(message);\n }\n },\n\n destroy: function () {\n this.comObj.removeEventListener('message', this._onComObjOnMessage);\n }\n};\n\nfunction loadJpegStream(id, imageUrl, objs) {\n var img = new Image();\n img.onload = (function loadJpegStream_onloadClosure() {\n objs.resolve(id, img);\n });\n img.onerror = (function loadJpegStream_onerrorClosure() {\n objs.resolve(id, null);\n warn('Error during JPEG image loading');\n });\n img.src = imageUrl;\n}\n\nexports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;\nexports.IDENTITY_MATRIX = IDENTITY_MATRIX;\nexports.OPS = OPS;\nexports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;\nexports.AnnotationBorderStyleType = AnnotationBorderStyleType;\nexports.AnnotationFlag = AnnotationFlag;\nexports.AnnotationType = AnnotationType;\nexports.FontType = FontType;\nexports.ImageKind = ImageKind;\nexports.InvalidPDFException = InvalidPDFException;\nexports.LinkTarget = LinkTarget;\nexports.LinkTargetStringMap = LinkTargetStringMap;\nexports.MessageHandler = MessageHandler;\nexports.MissingDataException = MissingDataException;\nexports.MissingPDFException = MissingPDFException;\nexports.NotImplementedException = NotImplementedException;\nexports.PasswordException = PasswordException;\nexports.PasswordResponses = PasswordResponses;\nexports.StatTimer = StatTimer;\nexports.StreamType = StreamType;\nexports.TextRenderingMode = TextRenderingMode;\nexports.UnexpectedResponseException = UnexpectedResponseException;\nexports.UnknownErrorException = UnknownErrorException;\nexports.Util = Util;\nexports.XRefParseException = XRefParseException;\nexports.assert = assert;\nexports.bytesToString = bytesToString;\nexports.combineUrl = combineUrl;\nexports.createPromiseCapability = createPromiseCapability;\nexports.deprecated = deprecated;\nexports.error = error;\nexports.info = info;\nexports.isArray = isArray;\nexports.isArrayBuffer = isArrayBuffer;\nexports.isBool = isBool;\nexports.isEmptyObj = isEmptyObj;\nexports.isExternalLinkTargetSet = isExternalLinkTargetSet;\nexports.isInt = isInt;\nexports.isNum = isNum;\nexports.isString = isString;\nexports.isValidUrl = isValidUrl;\nexports.loadJpegStream = loadJpegStream;\nexports.log2 = log2;\nexports.readInt8 = readInt8;\nexports.readUint16 = readUint16;\nexports.readUint32 = readUint32;\nexports.removeNullCharacters = removeNullCharacters;\nexports.shadow = shadow;\nexports.string32 = string32;\nexports.stringToBytes = stringToBytes;\nexports.stringToPDFString = stringToPDFString;\nexports.stringToUTF8String = stringToUTF8String;\nexports.utf8StringToString = utf8StringToString;\nexports.warn = warn;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,\n root.pdfjsDisplayDOMUtils);\n }\n}(this, function (exports, sharedUtil, displayDOMUtils) {\n\nvar AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;\nvar AnnotationType = sharedUtil.AnnotationType;\nvar Util = sharedUtil.Util;\nvar isExternalLinkTargetSet = sharedUtil.isExternalLinkTargetSet;\nvar LinkTargetStringMap = sharedUtil.LinkTargetStringMap;\nvar removeNullCharacters = sharedUtil.removeNullCharacters;\nvar warn = sharedUtil.warn;\nvar CustomStyle = displayDOMUtils.CustomStyle;\n\n/**\n * @typedef {Object} AnnotationElementParameters\n * @property {Object} data\n * @property {HTMLDivElement} layer\n * @property {PDFPage} page\n * @property {PageViewport} viewport\n * @property {IPDFLinkService} linkService\n */\n\n/**\n * @class\n * @alias AnnotationElementFactory\n */\nfunction AnnotationElementFactory() {}\nAnnotationElementFactory.prototype =\n /** @lends AnnotationElementFactory.prototype */ {\n /**\n * @param {AnnotationElementParameters} parameters\n * @returns {AnnotationElement}\n */\n create: function AnnotationElementFactory_create(parameters) {\n var subtype = parameters.data.annotationType;\n\n switch (subtype) {\n case AnnotationType.LINK:\n return new LinkAnnotationElement(parameters);\n\n case AnnotationType.TEXT:\n return new TextAnnotationElement(parameters);\n\n case AnnotationType.WIDGET:\n return new WidgetAnnotationElement(parameters);\n\n case AnnotationType.POPUP:\n return new PopupAnnotationElement(parameters);\n\n case AnnotationType.HIGHLIGHT:\n return new HighlightAnnotationElement(parameters);\n\n case AnnotationType.UNDERLINE:\n return new UnderlineAnnotationElement(parameters);\n\n case AnnotationType.SQUIGGLY:\n return new SquigglyAnnotationElement(parameters);\n\n case AnnotationType.STRIKEOUT:\n return new StrikeOutAnnotationElement(parameters);\n\n default:\n throw new Error('Unimplemented annotation type \"' + subtype + '\"');\n }\n }\n};\n\n/**\n * @class\n * @alias AnnotationElement\n */\nvar AnnotationElement = (function AnnotationElementClosure() {\n function AnnotationElement(parameters) {\n this.data = parameters.data;\n this.layer = parameters.layer;\n this.page = parameters.page;\n this.viewport = parameters.viewport;\n this.linkService = parameters.linkService;\n\n this.container = this._createContainer();\n }\n\n AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {\n /**\n * Create an empty container for the annotation's HTML element.\n *\n * @private\n * @memberof AnnotationElement\n * @returns {HTMLSectionElement}\n */\n _createContainer: function AnnotationElement_createContainer() {\n var data = this.data, page = this.page, viewport = this.viewport;\n var container = document.createElement('section');\n var width = data.rect[2] - data.rect[0];\n var height = data.rect[3] - data.rect[1];\n\n container.setAttribute('data-annotation-id', data.id);\n\n // Do *not* modify `data.rect`, since that will corrupt the annotation\n // position on subsequent calls to `_createContainer` (see issue 6804).\n var rect = Util.normalizeRect([\n data.rect[0],\n page.view[3] - data.rect[1] + page.view[1],\n data.rect[2],\n page.view[3] - data.rect[3] + page.view[1]\n ]);\n\n CustomStyle.setProp('transform', container,\n 'matrix(' + viewport.transform.join(',') + ')');\n CustomStyle.setProp('transformOrigin', container,\n -rect[0] + 'px ' + -rect[1] + 'px');\n\n if (data.borderStyle.width > 0) {\n container.style.borderWidth = data.borderStyle.width + 'px';\n if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {\n // Underline styles only have a bottom border, so we do not need\n // to adjust for all borders. This yields a similar result as\n // Adobe Acrobat/Reader.\n width = width - 2 * data.borderStyle.width;\n height = height - 2 * data.borderStyle.width;\n }\n\n var horizontalRadius = data.borderStyle.horizontalCornerRadius;\n var verticalRadius = data.borderStyle.verticalCornerRadius;\n if (horizontalRadius > 0 || verticalRadius > 0) {\n var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';\n CustomStyle.setProp('borderRadius', container, radius);\n }\n\n switch (data.borderStyle.style) {\n case AnnotationBorderStyleType.SOLID:\n container.style.borderStyle = 'solid';\n break;\n\n case AnnotationBorderStyleType.DASHED:\n container.style.borderStyle = 'dashed';\n break;\n\n case AnnotationBorderStyleType.BEVELED:\n warn('Unimplemented border style: beveled');\n break;\n\n case AnnotationBorderStyleType.INSET:\n warn('Unimplemented border style: inset');\n break;\n\n case AnnotationBorderStyleType.UNDERLINE:\n container.style.borderBottomStyle = 'solid';\n break;\n\n default:\n break;\n }\n\n if (data.color) {\n container.style.borderColor =\n Util.makeCssRgb(data.color[0] | 0,\n data.color[1] | 0,\n data.color[2] | 0);\n } else {\n // Transparent (invisible) border, so do not draw it at all.\n container.style.borderWidth = 0;\n }\n }\n\n container.style.left = rect[0] + 'px';\n container.style.top = rect[1] + 'px';\n\n container.style.width = width + 'px';\n container.style.height = height + 'px';\n\n return container;\n },\n\n /**\n * Render the annotation's HTML element in the empty container.\n *\n * @public\n * @memberof AnnotationElement\n */\n render: function AnnotationElement_render() {\n throw new Error('Abstract method AnnotationElement.render called');\n }\n };\n\n return AnnotationElement;\n})();\n\n/**\n * @class\n * @alias LinkAnnotationElement\n */\nvar LinkAnnotationElement = (function LinkAnnotationElementClosure() {\n function LinkAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(LinkAnnotationElement, AnnotationElement, {\n /**\n * Render the link annotation's HTML element in the empty container.\n *\n * @public\n * @memberof LinkAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function LinkAnnotationElement_render() {\n this.container.className = 'linkAnnotation';\n\n var link = document.createElement('a');\n link.href = link.title = (this.data.url ?\n removeNullCharacters(this.data.url) : '');\n\n if (this.data.url && isExternalLinkTargetSet()) {\n link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];\n }\n\n // Strip referrer from the URL.\n if (this.data.url) {\n link.rel = PDFJS.externalLinkRel;\n }\n\n if (!this.data.url) {\n if (this.data.action) {\n this._bindNamedAction(link, this.data.action);\n } else {\n this._bindLink(link, ('dest' in this.data) ? this.data.dest : null);\n }\n }\n\n this.container.appendChild(link);\n return this.container;\n },\n\n /**\n * Bind internal links to the link element.\n *\n * @private\n * @param {Object} link\n * @param {Object} destination\n * @memberof LinkAnnotationElement\n */\n _bindLink: function LinkAnnotationElement_bindLink(link, destination) {\n var self = this;\n\n link.href = this.linkService.getDestinationHash(destination);\n link.onclick = function() {\n if (destination) {\n self.linkService.navigateTo(destination);\n }\n return false;\n };\n if (destination) {\n link.className = 'internalLink';\n }\n },\n\n /**\n * Bind named actions to the link element.\n *\n * @private\n * @param {Object} link\n * @param {Object} action\n * @memberof LinkAnnotationElement\n */\n _bindNamedAction:\n function LinkAnnotationElement_bindNamedAction(link, action) {\n var self = this;\n\n link.href = this.linkService.getAnchorUrl('');\n link.onclick = function() {\n self.linkService.executeNamedAction(action);\n return false;\n };\n link.className = 'internalLink';\n }\n });\n\n return LinkAnnotationElement;\n})();\n\n/**\n * @class\n * @alias TextAnnotationElement\n */\nvar TextAnnotationElement = (function TextAnnotationElementClosure() {\n function TextAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(TextAnnotationElement, AnnotationElement, {\n /**\n * Render the text annotation's HTML element in the empty container.\n *\n * @public\n * @memberof TextAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function TextAnnotationElement_render() {\n this.container.className = 'textAnnotation';\n\n var image = document.createElement('img');\n image.style.height = this.container.style.height;\n image.style.width = this.container.style.width;\n image.src = PDFJS.imageResourcesPath + 'annotation-' +\n this.data.name.toLowerCase() + '.svg';\n image.alt = '[{{type}} Annotation]';\n image.dataset.l10nId = 'text_annotation_type';\n image.dataset.l10nArgs = JSON.stringify({type: this.data.name});\n\n if (!this.data.hasPopup) {\n var popupElement = new PopupElement({\n container: this.container,\n trigger: image,\n color: this.data.color,\n title: this.data.title,\n contents: this.data.contents,\n hideWrapper: true\n });\n var popup = popupElement.render();\n\n // Position the popup next to the Text annotation's container.\n popup.style.left = image.style.width;\n\n this.container.appendChild(popup);\n }\n\n this.container.appendChild(image);\n return this.container;\n }\n });\n\n return TextAnnotationElement;\n})();\n\n/**\n * @class\n * @alias WidgetAnnotationElement\n */\nvar WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {\n function WidgetAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(WidgetAnnotationElement, AnnotationElement, {\n /**\n * Render the widget annotation's HTML element in the empty container.\n *\n * @public\n * @memberof WidgetAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function WidgetAnnotationElement_render() {\n var content = document.createElement('div');\n content.textContent = this.data.fieldValue;\n var textAlignment = this.data.textAlignment;\n content.style.textAlign = ['left', 'center', 'right'][textAlignment];\n content.style.verticalAlign = 'middle';\n content.style.display = 'table-cell';\n\n var font = (this.data.fontRefName ?\n this.page.commonObjs.getData(this.data.fontRefName) : null);\n this._setTextStyle(content, font);\n\n this.container.appendChild(content);\n return this.container;\n },\n\n /**\n * Apply text styles to the text in the element.\n *\n * @private\n * @param {HTMLDivElement} element\n * @param {Object} font\n * @memberof WidgetAnnotationElement\n */\n _setTextStyle:\n function WidgetAnnotationElement_setTextStyle(element, font) {\n // TODO: This duplicates some of the logic in CanvasGraphics.setFont().\n var style = element.style;\n style.fontSize = this.data.fontSize + 'px';\n style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');\n\n if (!font) {\n return;\n }\n\n style.fontWeight = (font.black ?\n (font.bold ? '900' : 'bold') :\n (font.bold ? 'bold' : 'normal'));\n style.fontStyle = (font.italic ? 'italic' : 'normal');\n\n // Use a reasonable default font if the font doesn't specify a fallback.\n var fontFamily = font.loadedName ? '\"' + font.loadedName + '\", ' : '';\n var fallbackName = font.fallbackName || 'Helvetica, sans-serif';\n style.fontFamily = fontFamily + fallbackName;\n }\n });\n\n return WidgetAnnotationElement;\n})();\n\n/**\n * @class\n * @alias PopupAnnotationElement\n */\nvar PopupAnnotationElement = (function PopupAnnotationElementClosure() {\n function PopupAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(PopupAnnotationElement, AnnotationElement, {\n /**\n * Render the popup annotation's HTML element in the empty container.\n *\n * @public\n * @memberof PopupAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function PopupAnnotationElement_render() {\n this.container.className = 'popupAnnotation';\n\n var selector = '[data-annotation-id=\"' + this.data.parentId + '\"]';\n var parentElement = this.layer.querySelector(selector);\n if (!parentElement) {\n return this.container;\n }\n\n var popup = new PopupElement({\n container: this.container,\n trigger: parentElement,\n color: this.data.color,\n title: this.data.title,\n contents: this.data.contents\n });\n\n // Position the popup next to the parent annotation's container.\n // PDF viewers ignore a popup annotation's rectangle.\n var parentLeft = parseFloat(parentElement.style.left);\n var parentWidth = parseFloat(parentElement.style.width);\n CustomStyle.setProp('transformOrigin', this.container,\n -(parentLeft + parentWidth) + 'px -' +\n parentElement.style.top);\n this.container.style.left = (parentLeft + parentWidth) + 'px';\n\n this.container.appendChild(popup.render());\n return this.container;\n }\n });\n\n return PopupAnnotationElement;\n})();\n\n/**\n * @class\n * @alias PopupElement\n */\nvar PopupElement = (function PopupElementClosure() {\n var BACKGROUND_ENLIGHT = 0.7;\n\n function PopupElement(parameters) {\n this.container = parameters.container;\n this.trigger = parameters.trigger;\n this.color = parameters.color;\n this.title = parameters.title;\n this.contents = parameters.contents;\n this.hideWrapper = parameters.hideWrapper || false;\n\n this.pinned = false;\n }\n\n PopupElement.prototype = /** @lends PopupElement.prototype */ {\n /**\n * Render the popup's HTML element.\n *\n * @public\n * @memberof PopupElement\n * @returns {HTMLSectionElement}\n */\n render: function PopupElement_render() {\n var wrapper = document.createElement('div');\n wrapper.className = 'popupWrapper';\n\n // For Popup annotations we hide the entire section because it contains\n // only the popup. However, for Text annotations without a separate Popup\n // annotation, we cannot hide the entire container as the image would\n // disappear too. In that special case, hiding the wrapper suffices.\n this.hideElement = (this.hideWrapper ? wrapper : this.container);\n this.hideElement.setAttribute('hidden', true);\n\n var popup = document.createElement('div');\n popup.className = 'popup';\n\n var color = this.color;\n if (color) {\n // Enlighten the color.\n var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];\n var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];\n var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];\n popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);\n }\n\n var contents = this._formatContents(this.contents);\n var title = document.createElement('h1');\n title.textContent = this.title;\n\n // Attach the event listeners to the trigger element.\n this.trigger.addEventListener('click', this._toggle.bind(this));\n this.trigger.addEventListener('mouseover', this._show.bind(this, false));\n this.trigger.addEventListener('mouseout', this._hide.bind(this, false));\n popup.addEventListener('click', this._hide.bind(this, true));\n\n popup.appendChild(title);\n popup.appendChild(contents);\n wrapper.appendChild(popup);\n return wrapper;\n },\n\n /**\n * Format the contents of the popup by adding newlines where necessary.\n *\n * @private\n * @param {string} contents\n * @memberof PopupElement\n * @returns {HTMLParagraphElement}\n */\n _formatContents: function PopupElement_formatContents(contents) {\n var p = document.createElement('p');\n var lines = contents.split(/(?:\\r\\n?|\\n)/);\n for (var i = 0, ii = lines.length; i < ii; ++i) {\n var line = lines[i];\n p.appendChild(document.createTextNode(line));\n if (i < (ii - 1)) {\n p.appendChild(document.createElement('br'));\n }\n }\n return p;\n },\n\n /**\n * Toggle the visibility of the popup.\n *\n * @private\n * @memberof PopupElement\n */\n _toggle: function PopupElement_toggle() {\n if (this.pinned) {\n this._hide(true);\n } else {\n this._show(true);\n }\n },\n\n /**\n * Show the popup.\n *\n * @private\n * @param {boolean} pin\n * @memberof PopupElement\n */\n _show: function PopupElement_show(pin) {\n if (pin) {\n this.pinned = true;\n }\n if (this.hideElement.hasAttribute('hidden')) {\n this.hideElement.removeAttribute('hidden');\n this.container.style.zIndex += 1;\n }\n },\n\n /**\n * Hide the popup.\n *\n * @private\n * @param {boolean} unpin\n * @memberof PopupElement\n */\n _hide: function PopupElement_hide(unpin) {\n if (unpin) {\n this.pinned = false;\n }\n if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {\n this.hideElement.setAttribute('hidden', true);\n this.container.style.zIndex -= 1;\n }\n }\n };\n\n return PopupElement;\n})();\n\n/**\n * @class\n * @alias HighlightAnnotationElement\n */\nvar HighlightAnnotationElement = (\n function HighlightAnnotationElementClosure() {\n function HighlightAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(HighlightAnnotationElement, AnnotationElement, {\n /**\n * Render the highlight annotation's HTML element in the empty container.\n *\n * @public\n * @memberof HighlightAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function HighlightAnnotationElement_render() {\n this.container.className = 'highlightAnnotation';\n return this.container;\n }\n });\n\n return HighlightAnnotationElement;\n})();\n\n/**\n * @class\n * @alias UnderlineAnnotationElement\n */\nvar UnderlineAnnotationElement = (\n function UnderlineAnnotationElementClosure() {\n function UnderlineAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(UnderlineAnnotationElement, AnnotationElement, {\n /**\n * Render the underline annotation's HTML element in the empty container.\n *\n * @public\n * @memberof UnderlineAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function UnderlineAnnotationElement_render() {\n this.container.className = 'underlineAnnotation';\n return this.container;\n }\n });\n\n return UnderlineAnnotationElement;\n})();\n\n/**\n * @class\n * @alias SquigglyAnnotationElement\n */\nvar SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {\n function SquigglyAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(SquigglyAnnotationElement, AnnotationElement, {\n /**\n * Render the squiggly annotation's HTML element in the empty container.\n *\n * @public\n * @memberof SquigglyAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function SquigglyAnnotationElement_render() {\n this.container.className = 'squigglyAnnotation';\n return this.container;\n }\n });\n\n return SquigglyAnnotationElement;\n})();\n\n/**\n * @class\n * @alias StrikeOutAnnotationElement\n */\nvar StrikeOutAnnotationElement = (\n function StrikeOutAnnotationElementClosure() {\n function StrikeOutAnnotationElement(parameters) {\n AnnotationElement.call(this, parameters);\n }\n\n Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {\n /**\n * Render the strikeout annotation's HTML element in the empty container.\n *\n * @public\n * @memberof StrikeOutAnnotationElement\n * @returns {HTMLSectionElement}\n */\n render: function StrikeOutAnnotationElement_render() {\n this.container.className = 'strikeoutAnnotation';\n return this.container;\n }\n });\n\n return StrikeOutAnnotationElement;\n})();\n\n/**\n * @typedef {Object} AnnotationLayerParameters\n * @property {PageViewport} viewport\n * @property {HTMLDivElement} div\n * @property {Array} annotations\n * @property {PDFPage} page\n * @property {IPDFLinkService} linkService\n */\n\n/**\n * @class\n * @alias AnnotationLayer\n */\nvar AnnotationLayer = (function AnnotationLayerClosure() {\n return {\n /**\n * Render a new annotation layer with all annotation elements.\n *\n * @public\n * @param {AnnotationLayerParameters} parameters\n * @memberof AnnotationLayer\n */\n render: function AnnotationLayer_render(parameters) {\n var annotationElementFactory = new AnnotationElementFactory();\n\n for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {\n var data = parameters.annotations[i];\n if (!data || !data.hasHtml) {\n continue;\n }\n\n var properties = {\n data: data,\n layer: parameters.div,\n page: parameters.page,\n viewport: parameters.viewport,\n linkService: parameters.linkService\n };\n var element = annotationElementFactory.create(properties);\n parameters.div.appendChild(element.render());\n }\n },\n\n /**\n * Update the annotation elements on existing annotation layer.\n *\n * @public\n * @param {AnnotationLayerParameters} parameters\n * @memberof AnnotationLayer\n */\n update: function AnnotationLayer_update(parameters) {\n for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {\n var data = parameters.annotations[i];\n var element = parameters.div.querySelector(\n '[data-annotation-id=\"' + data.id + '\"]');\n if (element) {\n CustomStyle.setProp('transform', element,\n 'matrix(' + parameters.viewport.transform.join(',') + ')');\n }\n }\n parameters.div.removeAttribute('hidden');\n }\n };\n})();\n\nPDFJS.AnnotationLayer = AnnotationLayer;\n\nexports.AnnotationLayer = AnnotationLayer;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil,\n root.pdfjsSharedGlobal);\n }\n}(this, function (exports, sharedUtil, sharedGlobal) {\n\nvar assert = sharedUtil.assert;\nvar bytesToString = sharedUtil.bytesToString;\nvar string32 = sharedUtil.string32;\nvar shadow = sharedUtil.shadow;\nvar warn = sharedUtil.warn;\n\nvar PDFJS = sharedGlobal.PDFJS;\nvar globalScope = sharedGlobal.globalScope;\nvar isWorker = sharedGlobal.isWorker;\n\nfunction FontLoader(docId) {\n this.docId = docId;\n this.styleElement = null;\n this.nativeFontFaces = [];\n this.loadTestFontId = 0;\n this.loadingContext = {\n requests: [],\n nextRequestId: 0\n };\n}\nFontLoader.prototype = {\n insertRule: function fontLoaderInsertRule(rule) {\n var styleElement = this.styleElement;\n if (!styleElement) {\n styleElement = this.styleElement = document.createElement('style');\n styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;\n document.documentElement.getElementsByTagName('head')[0].appendChild(\n styleElement);\n }\n\n var styleSheet = styleElement.sheet;\n styleSheet.insertRule(rule, styleSheet.cssRules.length);\n },\n\n clear: function fontLoaderClear() {\n var styleElement = this.styleElement;\n if (styleElement) {\n styleElement.parentNode.removeChild(styleElement);\n styleElement = this.styleElement = null;\n }\n this.nativeFontFaces.forEach(function(nativeFontFace) {\n document.fonts.delete(nativeFontFace);\n });\n this.nativeFontFaces.length = 0;\n },\n get loadTestFont() {\n // This is a CFF font with 1 glyph for '.' that fills its entire width and\n // height.\n return shadow(this, 'loadTestFont', atob(\n 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +\n 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +\n 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +\n 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +\n 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +\n 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +\n 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +\n 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +\n 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +\n 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +\n 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +\n 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +\n 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +\n 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +\n 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +\n 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +\n 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +\n 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +\n 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +\n 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +\n 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +\n 'ABAAAAAAAAAAAD6AAAAAAAAA=='\n ));\n },\n\n addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {\n this.nativeFontFaces.push(nativeFontFace);\n document.fonts.add(nativeFontFace);\n },\n\n bind: function fontLoaderBind(fonts, callback) {\n assert(!isWorker, 'bind() shall be called from main thread');\n\n var rules = [];\n var fontsToLoad = [];\n var fontLoadPromises = [];\n var getNativeFontPromise = function(nativeFontFace) {\n // Return a promise that is always fulfilled, even when the font fails to\n // load.\n return nativeFontFace.loaded.catch(function(e) {\n warn('Failed to load font \"' + nativeFontFace.family + '\": ' + e);\n });\n };\n for (var i = 0, ii = fonts.length; i < ii; i++) {\n var font = fonts[i];\n\n // Add the font to the DOM only once or skip if the font\n // is already loaded.\n if (font.attached || font.loading === false) {\n continue;\n }\n font.attached = true;\n\n if (FontLoader.isFontLoadingAPISupported) {\n var nativeFontFace = font.createNativeFontFace();\n if (nativeFontFace) {\n this.addNativeFontFace(nativeFontFace);\n fontLoadPromises.push(getNativeFontPromise(nativeFontFace));\n }\n } else {\n var rule = font.createFontFaceRule();\n if (rule) {\n this.insertRule(rule);\n rules.push(rule);\n fontsToLoad.push(font);\n }\n }\n }\n\n var request = this.queueLoadingCallback(callback);\n if (FontLoader.isFontLoadingAPISupported) {\n Promise.all(fontLoadPromises).then(function() {\n request.complete();\n });\n } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {\n this.prepareFontLoadEvent(rules, fontsToLoad, request);\n } else {\n request.complete();\n }\n },\n\n queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {\n function LoadLoader_completeRequest() {\n assert(!request.end, 'completeRequest() cannot be called twice');\n request.end = Date.now();\n\n // sending all completed requests in order how they were queued\n while (context.requests.length > 0 && context.requests[0].end) {\n var otherRequest = context.requests.shift();\n setTimeout(otherRequest.callback, 0);\n }\n }\n\n var context = this.loadingContext;\n var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);\n var request = {\n id: requestId,\n complete: LoadLoader_completeRequest,\n callback: callback,\n started: Date.now()\n };\n context.requests.push(request);\n return request;\n },\n\n prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,\n fonts,\n request) {\n /** Hack begin */\n // There's currently no event when a font has finished downloading so the\n // following code is a dirty hack to 'guess' when a font is\n // ready. It's assumed fonts are loaded in order, so add a known test\n // font after the desired fonts and then test for the loading of that\n // test font.\n\n function int32(data, offset) {\n return (data.charCodeAt(offset) << 24) |\n (data.charCodeAt(offset + 1) << 16) |\n (data.charCodeAt(offset + 2) << 8) |\n (data.charCodeAt(offset + 3) & 0xff);\n }\n\n function spliceString(s, offset, remove, insert) {\n var chunk1 = s.substr(0, offset);\n var chunk2 = s.substr(offset + remove);\n return chunk1 + insert + chunk2;\n }\n\n var i, ii;\n\n var canvas = document.createElement('canvas');\n canvas.width = 1;\n canvas.height = 1;\n var ctx = canvas.getContext('2d');\n\n var called = 0;\n function isFontReady(name, callback) {\n called++;\n // With setTimeout clamping this gives the font ~100ms to load.\n if(called > 30) {\n warn('Load test font never loaded.');\n callback();\n return;\n }\n ctx.font = '30px ' + name;\n ctx.fillText('.', 0, 20);\n var imageData = ctx.getImageData(0, 0, 1, 1);\n if (imageData.data[3] > 0) {\n callback();\n return;\n }\n setTimeout(isFontReady.bind(null, name, callback));\n }\n\n var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;\n // Chromium seems to cache fonts based on a hash of the actual font data,\n // so the font must be modified for each load test else it will appear to\n // be loaded already.\n // TODO: This could maybe be made faster by avoiding the btoa of the full\n // font by splitting it in chunks before hand and padding the font id.\n var data = this.loadTestFont;\n var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)\n data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,\n loadTestFontId);\n // CFF checksum is important for IE, adjusting it\n var CFF_CHECKSUM_OFFSET = 16;\n var XXXX_VALUE = 0x58585858; // the \"comment\" filled with 'X'\n var checksum = int32(data, CFF_CHECKSUM_OFFSET);\n for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {\n checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;\n }\n if (i < loadTestFontId.length) { // align to 4 bytes boundary\n checksum = (checksum - XXXX_VALUE +\n int32(loadTestFontId + 'XXX', i)) | 0;\n }\n data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));\n\n var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';\n var rule = '@font-face { font-family:\"' + loadTestFontId + '\";src:' +\n url + '}';\n this.insertRule(rule);\n\n var names = [];\n for (i = 0, ii = fonts.length; i < ii; i++) {\n names.push(fonts[i].loadedName);\n }\n names.push(loadTestFontId);\n\n var div = document.createElement('div');\n div.setAttribute('style',\n 'visibility: hidden;' +\n 'width: 10px; height: 10px;' +\n 'position: absolute; top: 0px; left: 0px;');\n for (i = 0, ii = names.length; i < ii; ++i) {\n var span = document.createElement('span');\n span.textContent = 'Hi';\n span.style.fontFamily = names[i];\n div.appendChild(span);\n }\n document.body.appendChild(div);\n\n isFontReady(loadTestFontId, function() {\n document.body.removeChild(div);\n request.complete();\n });\n /** Hack end */\n }\n};\nFontLoader.isFontLoadingAPISupported = (!isWorker &&\n typeof document !== 'undefined' && !!document.fonts);\nObject.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {\n get: function () {\n var supported = false;\n\n // User agent string sniffing is bad, but there is no reliable way to tell\n // if font is fully loaded and ready to be used with canvas.\n var userAgent = window.navigator.userAgent;\n var m = /Mozilla\\/5.0.*?rv:(\\d+).*? Gecko/.exec(userAgent);\n if (m && m[1] >= 14) {\n supported = true;\n }\n // TODO other browsers\n if (userAgent === 'node') {\n supported = true;\n }\n return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);\n },\n enumerable: true,\n configurable: true\n});\n\nvar FontFaceObject = (function FontFaceObjectClosure() {\n function FontFaceObject(translatedData) {\n this.compiledGlyphs = {};\n // importing translated data\n for (var i in translatedData) {\n this[i] = translatedData[i];\n }\n }\n Object.defineProperty(FontFaceObject, 'isEvalSupported', {\n get: function () {\n var evalSupport = false;\n if (PDFJS.isEvalSupported) {\n try {\n /* jshint evil: true */\n new Function('');\n evalSupport = true;\n } catch (e) {}\n }\n return shadow(this, 'isEvalSupported', evalSupport);\n },\n enumerable: true,\n configurable: true\n });\n FontFaceObject.prototype = {\n createNativeFontFace: function FontFaceObject_createNativeFontFace() {\n if (!this.data) {\n return null;\n }\n\n if (PDFJS.disableFontFace) {\n this.disableFontFace = true;\n return null;\n }\n\n var nativeFontFace = new FontFace(this.loadedName, this.data, {});\n\n if (PDFJS.pdfBug && 'FontInspector' in globalScope &&\n globalScope['FontInspector'].enabled) {\n globalScope['FontInspector'].fontAdded(this);\n }\n return nativeFontFace;\n },\n\n createFontFaceRule: function FontFaceObject_createFontFaceRule() {\n if (!this.data) {\n return null;\n }\n\n if (PDFJS.disableFontFace) {\n this.disableFontFace = true;\n return null;\n }\n\n var data = bytesToString(new Uint8Array(this.data));\n var fontName = this.loadedName;\n\n // Add the font-face rule to the document\n var url = ('url(data:' + this.mimetype + ';base64,' +\n window.btoa(data) + ');');\n var rule = '@font-face { font-family:\"' + fontName + '\";src:' + url + '}';\n\n if (PDFJS.pdfBug && 'FontInspector' in globalScope &&\n globalScope['FontInspector'].enabled) {\n globalScope['FontInspector'].fontAdded(this, url);\n }\n\n return rule;\n },\n\n getPathGenerator:\n function FontFaceObject_getPathGenerator(objs, character) {\n if (!(character in this.compiledGlyphs)) {\n var cmds = objs.get(this.loadedName + '_path_' + character);\n var current, i, len;\n\n // If we can, compile cmds into JS for MAXIMUM SPEED\n if (FontFaceObject.isEvalSupported) {\n var args, js = '';\n for (i = 0, len = cmds.length; i < len; i++) {\n current = cmds[i];\n\n if (current.args !== undefined) {\n args = current.args.join(',');\n } else {\n args = '';\n }\n\n js += 'c.' + current.cmd + '(' + args + ');\\n';\n }\n /* jshint -W054 */\n this.compiledGlyphs[character] = new Function('c', 'size', js);\n } else {\n // But fall back on using Function.prototype.apply() if we're\n // blocked from using eval() for whatever reason (like CSP policies)\n this.compiledGlyphs[character] = function(c, size) {\n for (i = 0, len = cmds.length; i < len; i++) {\n current = cmds[i];\n\n if (current.cmd === 'scale') {\n current.args = [size, -size];\n }\n\n c[current.cmd].apply(c, current.args);\n }\n };\n }\n }\n return this.compiledGlyphs[character];\n }\n };\n return FontFaceObject;\n})();\n\nexports.FontFaceObject = FontFaceObject;\nexports.FontLoader = FontLoader;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);\n }\n}(this, function (exports, sharedUtil) {\n\nvar error = sharedUtil.error;\n\nvar Metadata = PDFJS.Metadata = (function MetadataClosure() {\n function fixMetadata(meta) {\n return meta.replace(/>\\\\376\\\\377([^<]+)/g, function(all, codes) {\n var bytes = codes.replace(/\\\\([0-3])([0-7])([0-7])/g,\n function(code, d1, d2, d3) {\n return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);\n });\n var chars = '';\n for (var i = 0; i < bytes.length; i += 2) {\n var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);\n chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&\n code !== 38 && false ? String.fromCharCode(code) :\n '&#x' + (0x10000 + code).toString(16).substring(1) + ';';\n }\n return '>' + chars;\n });\n }\n\n function Metadata(meta) {\n if (typeof meta === 'string') {\n // Ghostscript produces invalid metadata\n meta = fixMetadata(meta);\n\n var parser = new DOMParser();\n meta = parser.parseFromString(meta, 'application/xml');\n } else if (!(meta instanceof Document)) {\n error('Metadata: Invalid metadata object');\n }\n\n this.metaDocument = meta;\n this.metadata = {};\n this.parse();\n }\n\n Metadata.prototype = {\n parse: function Metadata_parse() {\n var doc = this.metaDocument;\n var rdf = doc.documentElement;\n\n if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in \n rdf = rdf.firstChild;\n while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {\n rdf = rdf.nextSibling;\n }\n }\n\n var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;\n if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {\n return;\n }\n\n var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;\n for (i = 0, length = children.length; i < length; i++) {\n desc = children[i];\n if (desc.nodeName.toLowerCase() !== 'rdf:description') {\n continue;\n }\n\n for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {\n if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {\n entry = desc.childNodes[ii];\n name = entry.nodeName.toLowerCase();\n this.metadata[name] = entry.textContent.trim();\n }\n }\n }\n },\n\n get: function Metadata_get(name) {\n return this.metadata[name] || null;\n },\n\n has: function Metadata_has(name) {\n return typeof this.metadata[name] !== 'undefined';\n }\n };\n\n return Metadata;\n})();\n\nexports.Metadata = Metadata;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);\n }\n}(this, function (exports, sharedUtil) {\n\nvar FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;\nvar IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;\nvar ImageKind = sharedUtil.ImageKind;\nvar OPS = sharedUtil.OPS;\nvar Util = sharedUtil.Util;\nvar isNum = sharedUtil.isNum;\nvar isArray = sharedUtil.isArray;\nvar warn = sharedUtil.warn;\n\nvar SVG_DEFAULTS = {\n fontStyle: 'normal',\n fontWeight: 'normal',\n fillColor: '#000000'\n};\n\nvar convertImgDataToPng = (function convertImgDataToPngClosure() {\n var PNG_HEADER =\n new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);\n\n var CHUNK_WRAPPER_SIZE = 12;\n\n var crcTable = new Int32Array(256);\n for (var i = 0; i < 256; i++) {\n var c = i;\n for (var h = 0; h < 8; h++) {\n if (c & 1) {\n c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);\n } else {\n c = (c >> 1) & 0x7fffffff;\n }\n }\n crcTable[i] = c;\n }\n\n function crc32(data, start, end) {\n var crc = -1;\n for (var i = start; i < end; i++) {\n var a = (crc ^ data[i]) & 0xff;\n var b = crcTable[a];\n crc = (crc >>> 8) ^ b;\n }\n return crc ^ -1;\n }\n\n function writePngChunk(type, body, data, offset) {\n var p = offset;\n var len = body.length;\n\n data[p] = len >> 24 & 0xff;\n data[p + 1] = len >> 16 & 0xff;\n data[p + 2] = len >> 8 & 0xff;\n data[p + 3] = len & 0xff;\n p += 4;\n\n data[p] = type.charCodeAt(0) & 0xff;\n data[p + 1] = type.charCodeAt(1) & 0xff;\n data[p + 2] = type.charCodeAt(2) & 0xff;\n data[p + 3] = type.charCodeAt(3) & 0xff;\n p += 4;\n\n data.set(body, p);\n p += body.length;\n\n var crc = crc32(data, offset + 4, p);\n\n data[p] = crc >> 24 & 0xff;\n data[p + 1] = crc >> 16 & 0xff;\n data[p + 2] = crc >> 8 & 0xff;\n data[p + 3] = crc & 0xff;\n }\n\n function adler32(data, start, end) {\n var a = 1;\n var b = 0;\n for (var i = start; i < end; ++i) {\n a = (a + (data[i] & 0xff)) % 65521;\n b = (b + a) % 65521;\n }\n return (b << 16) | a;\n }\n\n function encode(imgData, kind) {\n var width = imgData.width;\n var height = imgData.height;\n var bitDepth, colorType, lineSize;\n var bytes = imgData.data;\n\n switch (kind) {\n case ImageKind.GRAYSCALE_1BPP:\n colorType = 0;\n bitDepth = 1;\n lineSize = (width + 7) >> 3;\n break;\n case ImageKind.RGB_24BPP:\n colorType = 2;\n bitDepth = 8;\n lineSize = width * 3;\n break;\n case ImageKind.RGBA_32BPP:\n colorType = 6;\n bitDepth = 8;\n lineSize = width * 4;\n break;\n default:\n throw new Error('invalid format');\n }\n\n // prefix every row with predictor 0\n var literals = new Uint8Array((1 + lineSize) * height);\n var offsetLiterals = 0, offsetBytes = 0;\n var y, i;\n for (y = 0; y < height; ++y) {\n literals[offsetLiterals++] = 0; // no prediction\n literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),\n offsetLiterals);\n offsetBytes += lineSize;\n offsetLiterals += lineSize;\n }\n\n if (kind === ImageKind.GRAYSCALE_1BPP) {\n // inverting for B/W\n offsetLiterals = 0;\n for (y = 0; y < height; y++) {\n offsetLiterals++; // skipping predictor\n for (i = 0; i < lineSize; i++) {\n literals[offsetLiterals++] ^= 0xFF;\n }\n }\n }\n\n var ihdr = new Uint8Array([\n width >> 24 & 0xff,\n width >> 16 & 0xff,\n width >> 8 & 0xff,\n width & 0xff,\n height >> 24 & 0xff,\n height >> 16 & 0xff,\n height >> 8 & 0xff,\n height & 0xff,\n bitDepth, // bit depth\n colorType, // color type\n 0x00, // compression method\n 0x00, // filter method\n 0x00 // interlace method\n ]);\n\n var len = literals.length;\n var maxBlockLength = 0xFFFF;\n\n var deflateBlocks = Math.ceil(len / maxBlockLength);\n var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);\n var pi = 0;\n idat[pi++] = 0x78; // compression method and flags\n idat[pi++] = 0x9c; // flags\n\n var pos = 0;\n while (len > maxBlockLength) {\n // writing non-final DEFLATE blocks type 0 and length of 65535\n idat[pi++] = 0x00;\n idat[pi++] = 0xff;\n idat[pi++] = 0xff;\n idat[pi++] = 0x00;\n idat[pi++] = 0x00;\n idat.set(literals.subarray(pos, pos + maxBlockLength), pi);\n pi += maxBlockLength;\n pos += maxBlockLength;\n len -= maxBlockLength;\n }\n\n // writing non-final DEFLATE blocks type 0\n idat[pi++] = 0x01;\n idat[pi++] = len & 0xff;\n idat[pi++] = len >> 8 & 0xff;\n idat[pi++] = (~len & 0xffff) & 0xff;\n idat[pi++] = (~len & 0xffff) >> 8 & 0xff;\n idat.set(literals.subarray(pos), pi);\n pi += literals.length - pos;\n\n var adler = adler32(literals, 0, literals.length); // checksum\n idat[pi++] = adler >> 24 & 0xff;\n idat[pi++] = adler >> 16 & 0xff;\n idat[pi++] = adler >> 8 & 0xff;\n idat[pi++] = adler & 0xff;\n\n // PNG will consists: header, IHDR+data, IDAT+data, and IEND.\n var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +\n ihdr.length + idat.length;\n var data = new Uint8Array(pngLength);\n var offset = 0;\n data.set(PNG_HEADER, offset);\n offset += PNG_HEADER.length;\n writePngChunk('IHDR', ihdr, data, offset);\n offset += CHUNK_WRAPPER_SIZE + ihdr.length;\n writePngChunk('IDATA', idat, data, offset);\n offset += CHUNK_WRAPPER_SIZE + idat.length;\n writePngChunk('IEND', new Uint8Array(0), data, offset);\n\n return PDFJS.createObjectURL(data, 'image/png');\n }\n\n return function convertImgDataToPng(imgData) {\n var kind = (imgData.kind === undefined ?\n ImageKind.GRAYSCALE_1BPP : imgData.kind);\n return encode(imgData, kind);\n };\n})();\n\nvar SVGExtraState = (function SVGExtraStateClosure() {\n function SVGExtraState() {\n this.fontSizeScale = 1;\n this.fontWeight = SVG_DEFAULTS.fontWeight;\n this.fontSize = 0;\n\n this.textMatrix = IDENTITY_MATRIX;\n this.fontMatrix = FONT_IDENTITY_MATRIX;\n this.leading = 0;\n\n // Current point (in user coordinates)\n this.x = 0;\n this.y = 0;\n\n // Start of text line (in text coordinates)\n this.lineX = 0;\n this.lineY = 0;\n\n // Character and word spacing\n this.charSpacing = 0;\n this.wordSpacing = 0;\n this.textHScale = 1;\n this.textRise = 0;\n\n // Default foreground and background colors\n this.fillColor = SVG_DEFAULTS.fillColor;\n this.strokeColor = '#000000';\n\n this.fillAlpha = 1;\n this.strokeAlpha = 1;\n this.lineWidth = 1;\n this.lineJoin = '';\n this.lineCap = '';\n this.miterLimit = 0;\n\n this.dashArray = [];\n this.dashPhase = 0;\n\n this.dependencies = [];\n\n // Clipping\n this.clipId = '';\n this.pendingClip = false;\n\n this.maskId = '';\n }\n\n SVGExtraState.prototype = {\n clone: function SVGExtraState_clone() {\n return Object.create(this);\n },\n setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {\n this.x = x;\n this.y = y;\n }\n };\n return SVGExtraState;\n})();\n\nvar SVGGraphics = (function SVGGraphicsClosure() {\n function createScratchSVG(width, height) {\n var NS = 'http://www.w3.org/2000/svg';\n var svg = document.createElementNS(NS, 'svg:svg');\n svg.setAttributeNS(null, 'version', '1.1');\n svg.setAttributeNS(null, 'width', width + 'px');\n svg.setAttributeNS(null, 'height', height + 'px');\n svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);\n return svg;\n }\n\n function opListToTree(opList) {\n var opTree = [];\n var tmp = [];\n var opListLen = opList.length;\n\n for (var x = 0; x < opListLen; x++) {\n if (opList[x].fn === 'save') {\n opTree.push({'fnId': 92, 'fn': 'group', 'items': []});\n tmp.push(opTree);\n opTree = opTree[opTree.length - 1].items;\n continue;\n }\n\n if(opList[x].fn === 'restore') {\n opTree = tmp.pop();\n } else {\n opTree.push(opList[x]);\n }\n }\n return opTree;\n }\n\n /**\n * Formats float number.\n * @param value {number} number to format.\n * @returns {string}\n */\n function pf(value) {\n if (value === (value | 0)) { // integer number\n return value.toString();\n }\n var s = value.toFixed(10);\n var i = s.length - 1;\n if (s[i] !== '0') {\n return s;\n }\n // removing trailing zeros\n do {\n i--;\n } while (s[i] === '0');\n return s.substr(0, s[i] === '.' ? i : i + 1);\n }\n\n /**\n * Formats transform matrix. The standard rotation, scale and translate\n * matrices are replaced by their shorter forms, and for identity matrix\n * returns empty string to save the memory.\n * @param m {Array} matrix to format.\n * @returns {string}\n */\n function pm(m) {\n if (m[4] === 0 && m[5] === 0) {\n if (m[1] === 0 && m[2] === 0) {\n if (m[0] === 1 && m[3] === 1) {\n return '';\n }\n return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';\n }\n if (m[0] === m[3] && m[1] === -m[2]) {\n var a = Math.acos(m[0]) * 180 / Math.PI;\n return 'rotate(' + pf(a) + ')';\n }\n } else {\n if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {\n return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';\n }\n }\n return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +\n pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';\n }\n\n function SVGGraphics(commonObjs, objs) {\n this.current = new SVGExtraState();\n this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix\n this.transformStack = [];\n this.extraStack = [];\n this.commonObjs = commonObjs;\n this.objs = objs;\n this.pendingEOFill = false;\n\n this.embedFonts = false;\n this.embeddedFonts = {};\n this.cssStyle = null;\n }\n\n var NS = 'http://www.w3.org/2000/svg';\n var XML_NS = 'http://www.w3.org/XML/1998/namespace';\n var XLINK_NS = 'http://www.w3.org/1999/xlink';\n var LINE_CAP_STYLES = ['butt', 'round', 'square'];\n var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];\n var clipCount = 0;\n var maskCount = 0;\n\n SVGGraphics.prototype = {\n save: function SVGGraphics_save() {\n this.transformStack.push(this.transformMatrix);\n var old = this.current;\n this.extraStack.push(old);\n this.current = old.clone();\n },\n\n restore: function SVGGraphics_restore() {\n this.transformMatrix = this.transformStack.pop();\n this.current = this.extraStack.pop();\n\n this.tgrp = document.createElementNS(NS, 'svg:g');\n this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n this.pgrp.appendChild(this.tgrp);\n },\n\n group: function SVGGraphics_group(items) {\n this.save();\n this.executeOpTree(items);\n this.restore();\n },\n\n loadDependencies: function SVGGraphics_loadDependencies(operatorList) {\n var fnArray = operatorList.fnArray;\n var fnArrayLen = fnArray.length;\n var argsArray = operatorList.argsArray;\n\n var self = this;\n for (var i = 0; i < fnArrayLen; i++) {\n if (OPS.dependency === fnArray[i]) {\n var deps = argsArray[i];\n for (var n = 0, nn = deps.length; n < nn; n++) {\n var obj = deps[n];\n var common = obj.substring(0, 2) === 'g_';\n var promise;\n if (common) {\n promise = new Promise(function(resolve) {\n self.commonObjs.get(obj, resolve);\n });\n } else {\n promise = new Promise(function(resolve) {\n self.objs.get(obj, resolve);\n });\n }\n this.current.dependencies.push(promise);\n }\n }\n }\n return Promise.all(this.current.dependencies);\n },\n\n transform: function SVGGraphics_transform(a, b, c, d, e, f) {\n var transformMatrix = [a, b, c, d, e, f];\n this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,\n transformMatrix);\n\n this.tgrp = document.createElementNS(NS, 'svg:g');\n this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n },\n\n getSVG: function SVGGraphics_getSVG(operatorList, viewport) {\n this.svg = createScratchSVG(viewport.width, viewport.height);\n this.viewport = viewport;\n\n return this.loadDependencies(operatorList).then(function () {\n this.transformMatrix = IDENTITY_MATRIX;\n this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group\n this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));\n this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group\n this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n this.defs = document.createElementNS(NS, 'svg:defs');\n this.pgrp.appendChild(this.defs);\n this.pgrp.appendChild(this.tgrp);\n this.svg.appendChild(this.pgrp);\n var opTree = this.convertOpList(operatorList);\n this.executeOpTree(opTree);\n return this.svg;\n }.bind(this));\n },\n\n convertOpList: function SVGGraphics_convertOpList(operatorList) {\n var argsArray = operatorList.argsArray;\n var fnArray = operatorList.fnArray;\n var fnArrayLen = fnArray.length;\n var REVOPS = [];\n var opList = [];\n\n for (var op in OPS) {\n REVOPS[OPS[op]] = op;\n }\n\n for (var x = 0; x < fnArrayLen; x++) {\n var fnId = fnArray[x];\n opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});\n }\n return opListToTree(opList);\n },\n\n executeOpTree: function SVGGraphics_executeOpTree(opTree) {\n var opTreeLen = opTree.length;\n for(var x = 0; x < opTreeLen; x++) {\n var fn = opTree[x].fn;\n var fnId = opTree[x].fnId;\n var args = opTree[x].args;\n\n switch (fnId | 0) {\n case OPS.beginText:\n this.beginText();\n break;\n case OPS.setLeading:\n this.setLeading(args);\n break;\n case OPS.setLeadingMoveText:\n this.setLeadingMoveText(args[0], args[1]);\n break;\n case OPS.setFont:\n this.setFont(args);\n break;\n case OPS.showText:\n this.showText(args[0]);\n break;\n case OPS.showSpacedText:\n this.showText(args[0]);\n break;\n case OPS.endText:\n this.endText();\n break;\n case OPS.moveText:\n this.moveText(args[0], args[1]);\n break;\n case OPS.setCharSpacing:\n this.setCharSpacing(args[0]);\n break;\n case OPS.setWordSpacing:\n this.setWordSpacing(args[0]);\n break;\n case OPS.setHScale:\n this.setHScale(args[0]);\n break;\n case OPS.setTextMatrix:\n this.setTextMatrix(args[0], args[1], args[2],\n args[3], args[4], args[5]);\n break;\n case OPS.setLineWidth:\n this.setLineWidth(args[0]);\n break;\n case OPS.setLineJoin:\n this.setLineJoin(args[0]);\n break;\n case OPS.setLineCap:\n this.setLineCap(args[0]);\n break;\n case OPS.setMiterLimit:\n this.setMiterLimit(args[0]);\n break;\n case OPS.setFillRGBColor:\n this.setFillRGBColor(args[0], args[1], args[2]);\n break;\n case OPS.setStrokeRGBColor:\n this.setStrokeRGBColor(args[0], args[1], args[2]);\n break;\n case OPS.setDash:\n this.setDash(args[0], args[1]);\n break;\n case OPS.setGState:\n this.setGState(args[0]);\n break;\n case OPS.fill:\n this.fill();\n break;\n case OPS.eoFill:\n this.eoFill();\n break;\n case OPS.stroke:\n this.stroke();\n break;\n case OPS.fillStroke:\n this.fillStroke();\n break;\n case OPS.eoFillStroke:\n this.eoFillStroke();\n break;\n case OPS.clip:\n this.clip('nonzero');\n break;\n case OPS.eoClip:\n this.clip('evenodd');\n break;\n case OPS.paintSolidColorImageMask:\n this.paintSolidColorImageMask();\n break;\n case OPS.paintJpegXObject:\n this.paintJpegXObject(args[0], args[1], args[2]);\n break;\n case OPS.paintImageXObject:\n this.paintImageXObject(args[0]);\n break;\n case OPS.paintInlineImageXObject:\n this.paintInlineImageXObject(args[0]);\n break;\n case OPS.paintImageMaskXObject:\n this.paintImageMaskXObject(args[0]);\n break;\n case OPS.paintFormXObjectBegin:\n this.paintFormXObjectBegin(args[0], args[1]);\n break;\n case OPS.paintFormXObjectEnd:\n this.paintFormXObjectEnd();\n break;\n case OPS.closePath:\n this.closePath();\n break;\n case OPS.closeStroke:\n this.closeStroke();\n break;\n case OPS.closeFillStroke:\n this.closeFillStroke();\n break;\n case OPS.nextLine:\n this.nextLine();\n break;\n case OPS.transform:\n this.transform(args[0], args[1], args[2], args[3],\n args[4], args[5]);\n break;\n case OPS.constructPath:\n this.constructPath(args[0], args[1]);\n break;\n case OPS.endPath:\n this.endPath();\n break;\n case 92:\n this.group(opTree[x].items);\n break;\n default:\n warn('Unimplemented method '+ fn);\n break;\n }\n }\n },\n\n setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {\n this.current.wordSpacing = wordSpacing;\n },\n\n setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {\n this.current.charSpacing = charSpacing;\n },\n\n nextLine: function SVGGraphics_nextLine() {\n this.moveText(0, this.current.leading);\n },\n\n setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {\n var current = this.current;\n this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];\n\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n\n current.xcoords = [];\n current.tspan = document.createElementNS(NS, 'svg:tspan');\n current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);\n current.tspan.setAttributeNS(null, 'font-size',\n pf(current.fontSize) + 'px');\n current.tspan.setAttributeNS(null, 'y', pf(-current.y));\n\n current.txtElement = document.createElementNS(NS, 'svg:text');\n current.txtElement.appendChild(current.tspan);\n },\n\n beginText: function SVGGraphics_beginText() {\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n this.current.textMatrix = IDENTITY_MATRIX;\n this.current.lineMatrix = IDENTITY_MATRIX;\n this.current.tspan = document.createElementNS(NS, 'svg:tspan');\n this.current.txtElement = document.createElementNS(NS, 'svg:text');\n this.current.txtgrp = document.createElementNS(NS, 'svg:g');\n this.current.xcoords = [];\n },\n\n moveText: function SVGGraphics_moveText(x, y) {\n var current = this.current;\n this.current.x = this.current.lineX += x;\n this.current.y = this.current.lineY += y;\n\n current.xcoords = [];\n current.tspan = document.createElementNS(NS, 'svg:tspan');\n current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);\n current.tspan.setAttributeNS(null, 'font-size',\n pf(current.fontSize) + 'px');\n current.tspan.setAttributeNS(null, 'y', pf(-current.y));\n },\n\n showText: function SVGGraphics_showText(glyphs) {\n var current = this.current;\n var font = current.font;\n var fontSize = current.fontSize;\n\n if (fontSize === 0) {\n return;\n }\n\n var charSpacing = current.charSpacing;\n var wordSpacing = current.wordSpacing;\n var fontDirection = current.fontDirection;\n var textHScale = current.textHScale * fontDirection;\n var glyphsLength = glyphs.length;\n var vertical = font.vertical;\n var widthAdvanceScale = fontSize * current.fontMatrix[0];\n\n var x = 0, i;\n for (i = 0; i < glyphsLength; ++i) {\n var glyph = glyphs[i];\n if (glyph === null) {\n // word break\n x += fontDirection * wordSpacing;\n continue;\n } else if (isNum(glyph)) {\n x += -glyph * fontSize * 0.001;\n continue;\n }\n current.xcoords.push(current.x + x * textHScale);\n\n var width = glyph.width;\n var character = glyph.fontChar;\n var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;\n x += charWidth;\n\n current.tspan.textContent += character;\n }\n if (vertical) {\n current.y -= x * textHScale;\n } else {\n current.x += x * textHScale;\n }\n\n current.tspan.setAttributeNS(null, 'x',\n current.xcoords.map(pf).join(' '));\n current.tspan.setAttributeNS(null, 'y', pf(-current.y));\n current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);\n current.tspan.setAttributeNS(null, 'font-size',\n pf(current.fontSize) + 'px');\n if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {\n current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);\n }\n if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {\n current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);\n }\n if (current.fillColor !== SVG_DEFAULTS.fillColor) {\n current.tspan.setAttributeNS(null, 'fill', current.fillColor);\n }\n\n current.txtElement.setAttributeNS(null, 'transform',\n pm(current.textMatrix) +\n ' scale(1, -1)' );\n current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');\n current.txtElement.appendChild(current.tspan);\n current.txtgrp.appendChild(current.txtElement);\n\n this.tgrp.appendChild(current.txtElement);\n\n },\n\n setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {\n this.setLeading(-y);\n this.moveText(x, y);\n },\n\n addFontStyle: function SVGGraphics_addFontStyle(fontObj) {\n if (!this.cssStyle) {\n this.cssStyle = document.createElementNS(NS, 'svg:style');\n this.cssStyle.setAttributeNS(null, 'type', 'text/css');\n this.defs.appendChild(this.cssStyle);\n }\n\n var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);\n this.cssStyle.textContent +=\n '@font-face { font-family: \"' + fontObj.loadedName + '\";' +\n ' src: url(' + url + '); }\\n';\n },\n\n setFont: function SVGGraphics_setFont(details) {\n var current = this.current;\n var fontObj = this.commonObjs.get(details[0]);\n var size = details[1];\n this.current.font = fontObj;\n\n if (this.embedFonts && fontObj.data &&\n !this.embeddedFonts[fontObj.loadedName]) {\n this.addFontStyle(fontObj);\n this.embeddedFonts[fontObj.loadedName] = fontObj;\n }\n\n current.fontMatrix = (fontObj.fontMatrix ?\n fontObj.fontMatrix : FONT_IDENTITY_MATRIX);\n\n var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :\n (fontObj.bold ? 'bold' : 'normal');\n var italic = fontObj.italic ? 'italic' : 'normal';\n\n if (size < 0) {\n size = -size;\n current.fontDirection = -1;\n } else {\n current.fontDirection = 1;\n }\n current.fontSize = size;\n current.fontFamily = fontObj.loadedName;\n current.fontWeight = bold;\n current.fontStyle = italic;\n\n current.tspan = document.createElementNS(NS, 'svg:tspan');\n current.tspan.setAttributeNS(null, 'y', pf(-current.y));\n current.xcoords = [];\n },\n\n endText: function SVGGraphics_endText() {\n if (this.current.pendingClip) {\n this.cgrp.appendChild(this.tgrp);\n this.pgrp.appendChild(this.cgrp);\n } else {\n this.pgrp.appendChild(this.tgrp);\n }\n this.tgrp = document.createElementNS(NS, 'svg:g');\n this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n },\n\n // Path properties\n setLineWidth: function SVGGraphics_setLineWidth(width) {\n this.current.lineWidth = width;\n },\n setLineCap: function SVGGraphics_setLineCap(style) {\n this.current.lineCap = LINE_CAP_STYLES[style];\n },\n setLineJoin: function SVGGraphics_setLineJoin(style) {\n this.current.lineJoin = LINE_JOIN_STYLES[style];\n },\n setMiterLimit: function SVGGraphics_setMiterLimit(limit) {\n this.current.miterLimit = limit;\n },\n setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {\n var color = Util.makeCssRgb(r, g, b);\n this.current.strokeColor = color;\n },\n setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {\n var color = Util.makeCssRgb(r, g, b);\n this.current.fillColor = color;\n this.current.tspan = document.createElementNS(NS, 'svg:tspan');\n this.current.xcoords = [];\n },\n setDash: function SVGGraphics_setDash(dashArray, dashPhase) {\n this.current.dashArray = dashArray;\n this.current.dashPhase = dashPhase;\n },\n\n constructPath: function SVGGraphics_constructPath(ops, args) {\n var current = this.current;\n var x = current.x, y = current.y;\n current.path = document.createElementNS(NS, 'svg:path');\n var d = [];\n var opLength = ops.length;\n\n for (var i = 0, j = 0; i < opLength; i++) {\n switch (ops[i] | 0) {\n case OPS.rectangle:\n x = args[j++];\n y = args[j++];\n var width = args[j++];\n var height = args[j++];\n var xw = x + width;\n var yh = y + height;\n d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),\n 'L', pf(x), pf(yh), 'Z');\n break;\n case OPS.moveTo:\n x = args[j++];\n y = args[j++];\n d.push('M', pf(x), pf(y));\n break;\n case OPS.lineTo:\n x = args[j++];\n y = args[j++];\n d.push('L', pf(x) , pf(y));\n break;\n case OPS.curveTo:\n x = args[j + 4];\n y = args[j + 5];\n d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),\n pf(args[j + 3]), pf(x), pf(y));\n j += 6;\n break;\n case OPS.curveTo2:\n x = args[j + 2];\n y = args[j + 3];\n d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),\n pf(args[j + 2]), pf(args[j + 3]));\n j += 4;\n break;\n case OPS.curveTo3:\n x = args[j + 2];\n y = args[j + 3];\n d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),\n pf(x), pf(y));\n j += 4;\n break;\n case OPS.closePath:\n d.push('Z');\n break;\n }\n }\n current.path.setAttributeNS(null, 'd', d.join(' '));\n current.path.setAttributeNS(null, 'stroke-miterlimit',\n pf(current.miterLimit));\n current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);\n current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);\n current.path.setAttributeNS(null, 'stroke-width',\n pf(current.lineWidth) + 'px');\n current.path.setAttributeNS(null, 'stroke-dasharray',\n current.dashArray.map(pf).join(' '));\n current.path.setAttributeNS(null, 'stroke-dashoffset',\n pf(current.dashPhase) + 'px');\n current.path.setAttributeNS(null, 'fill', 'none');\n\n this.tgrp.appendChild(current.path);\n if (current.pendingClip) {\n this.cgrp.appendChild(this.tgrp);\n this.pgrp.appendChild(this.cgrp);\n } else {\n this.pgrp.appendChild(this.tgrp);\n }\n // Saving a reference in current.element so that it can be addressed\n // in 'fill' and 'stroke'\n current.element = current.path;\n current.setCurrentPoint(x, y);\n },\n\n endPath: function SVGGraphics_endPath() {\n var current = this.current;\n if (current.pendingClip) {\n this.cgrp.appendChild(this.tgrp);\n this.pgrp.appendChild(this.cgrp);\n } else {\n this.pgrp.appendChild(this.tgrp);\n }\n this.tgrp = document.createElementNS(NS, 'svg:g');\n this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n },\n\n clip: function SVGGraphics_clip(type) {\n var current = this.current;\n // Add current path to clipping path\n current.clipId = 'clippath' + clipCount;\n clipCount++;\n this.clippath = document.createElementNS(NS, 'svg:clipPath');\n this.clippath.setAttributeNS(null, 'id', current.clipId);\n var clipElement = current.element.cloneNode();\n if (type === 'evenodd') {\n clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');\n } else {\n clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');\n }\n this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));\n this.clippath.appendChild(clipElement);\n this.defs.appendChild(this.clippath);\n\n // Create a new group with that attribute\n current.pendingClip = true;\n this.cgrp = document.createElementNS(NS, 'svg:g');\n this.cgrp.setAttributeNS(null, 'clip-path',\n 'url(#' + current.clipId + ')');\n this.pgrp.appendChild(this.cgrp);\n },\n\n closePath: function SVGGraphics_closePath() {\n var current = this.current;\n var d = current.path.getAttributeNS(null, 'd');\n d += 'Z';\n current.path.setAttributeNS(null, 'd', d);\n },\n\n setLeading: function SVGGraphics_setLeading(leading) {\n this.current.leading = -leading;\n },\n\n setTextRise: function SVGGraphics_setTextRise(textRise) {\n this.current.textRise = textRise;\n },\n\n setHScale: function SVGGraphics_setHScale(scale) {\n this.current.textHScale = scale / 100;\n },\n\n setGState: function SVGGraphics_setGState(states) {\n for (var i = 0, ii = states.length; i < ii; i++) {\n var state = states[i];\n var key = state[0];\n var value = state[1];\n\n switch (key) {\n case 'LW':\n this.setLineWidth(value);\n break;\n case 'LC':\n this.setLineCap(value);\n break;\n case 'LJ':\n this.setLineJoin(value);\n break;\n case 'ML':\n this.setMiterLimit(value);\n break;\n case 'D':\n this.setDash(value[0], value[1]);\n break;\n case 'RI':\n break;\n case 'FL':\n break;\n case 'Font':\n this.setFont(value);\n break;\n case 'CA':\n break;\n case 'ca':\n break;\n case 'BM':\n break;\n case 'SMask':\n break;\n }\n }\n },\n\n fill: function SVGGraphics_fill() {\n var current = this.current;\n current.element.setAttributeNS(null, 'fill', current.fillColor);\n },\n\n stroke: function SVGGraphics_stroke() {\n var current = this.current;\n current.element.setAttributeNS(null, 'stroke', current.strokeColor);\n current.element.setAttributeNS(null, 'fill', 'none');\n },\n\n eoFill: function SVGGraphics_eoFill() {\n var current = this.current;\n current.element.setAttributeNS(null, 'fill', current.fillColor);\n current.element.setAttributeNS(null, 'fill-rule', 'evenodd');\n },\n\n fillStroke: function SVGGraphics_fillStroke() {\n // Order is important since stroke wants fill to be none.\n // First stroke, then if fill needed, it will be overwritten.\n this.stroke();\n this.fill();\n },\n\n eoFillStroke: function SVGGraphics_eoFillStroke() {\n this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');\n this.fillStroke();\n },\n\n closeStroke: function SVGGraphics_closeStroke() {\n this.closePath();\n this.stroke();\n },\n\n closeFillStroke: function SVGGraphics_closeFillStroke() {\n this.closePath();\n this.fillStroke();\n },\n\n paintSolidColorImageMask:\n function SVGGraphics_paintSolidColorImageMask() {\n var current = this.current;\n var rect = document.createElementNS(NS, 'svg:rect');\n rect.setAttributeNS(null, 'x', '0');\n rect.setAttributeNS(null, 'y', '0');\n rect.setAttributeNS(null, 'width', '1px');\n rect.setAttributeNS(null, 'height', '1px');\n rect.setAttributeNS(null, 'fill', current.fillColor);\n this.tgrp.appendChild(rect);\n },\n\n paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {\n var current = this.current;\n var imgObj = this.objs.get(objId);\n var imgEl = document.createElementNS(NS, 'svg:image');\n imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);\n imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');\n imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');\n imgEl.setAttributeNS(null, 'x', '0');\n imgEl.setAttributeNS(null, 'y', pf(-h));\n imgEl.setAttributeNS(null, 'transform',\n 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');\n\n this.tgrp.appendChild(imgEl);\n if (current.pendingClip) {\n this.cgrp.appendChild(this.tgrp);\n this.pgrp.appendChild(this.cgrp);\n } else {\n this.pgrp.appendChild(this.tgrp);\n }\n },\n\n paintImageXObject: function SVGGraphics_paintImageXObject(objId) {\n var imgData = this.objs.get(objId);\n if (!imgData) {\n warn('Dependent image isn\\'t ready yet');\n return;\n }\n this.paintInlineImageXObject(imgData);\n },\n\n paintInlineImageXObject:\n function SVGGraphics_paintInlineImageXObject(imgData, mask) {\n var current = this.current;\n var width = imgData.width;\n var height = imgData.height;\n\n var imgSrc = convertImgDataToPng(imgData);\n var cliprect = document.createElementNS(NS, 'svg:rect');\n cliprect.setAttributeNS(null, 'x', '0');\n cliprect.setAttributeNS(null, 'y', '0');\n cliprect.setAttributeNS(null, 'width', pf(width));\n cliprect.setAttributeNS(null, 'height', pf(height));\n current.element = cliprect;\n this.clip('nonzero');\n var imgEl = document.createElementNS(NS, 'svg:image');\n imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);\n imgEl.setAttributeNS(null, 'x', '0');\n imgEl.setAttributeNS(null, 'y', pf(-height));\n imgEl.setAttributeNS(null, 'width', pf(width) + 'px');\n imgEl.setAttributeNS(null, 'height', pf(height) + 'px');\n imgEl.setAttributeNS(null, 'transform',\n 'scale(' + pf(1 / width) + ' ' +\n pf(-1 / height) + ')');\n if (mask) {\n mask.appendChild(imgEl);\n } else {\n this.tgrp.appendChild(imgEl);\n }\n if (current.pendingClip) {\n this.cgrp.appendChild(this.tgrp);\n this.pgrp.appendChild(this.cgrp);\n } else {\n this.pgrp.appendChild(this.tgrp);\n }\n },\n\n paintImageMaskXObject:\n function SVGGraphics_paintImageMaskXObject(imgData) {\n var current = this.current;\n var width = imgData.width;\n var height = imgData.height;\n var fillColor = current.fillColor;\n\n current.maskId = 'mask' + maskCount++;\n var mask = document.createElementNS(NS, 'svg:mask');\n mask.setAttributeNS(null, 'id', current.maskId);\n\n var rect = document.createElementNS(NS, 'svg:rect');\n rect.setAttributeNS(null, 'x', '0');\n rect.setAttributeNS(null, 'y', '0');\n rect.setAttributeNS(null, 'width', pf(width));\n rect.setAttributeNS(null, 'height', pf(height));\n rect.setAttributeNS(null, 'fill', fillColor);\n rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');\n this.defs.appendChild(mask);\n this.tgrp.appendChild(rect);\n\n this.paintInlineImageXObject(imgData, mask);\n },\n\n paintFormXObjectBegin:\n function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {\n this.save();\n\n if (isArray(matrix) && matrix.length === 6) {\n this.transform(matrix[0], matrix[1], matrix[2],\n matrix[3], matrix[4], matrix[5]);\n }\n\n if (isArray(bbox) && bbox.length === 4) {\n var width = bbox[2] - bbox[0];\n var height = bbox[3] - bbox[1];\n\n var cliprect = document.createElementNS(NS, 'svg:rect');\n cliprect.setAttributeNS(null, 'x', bbox[0]);\n cliprect.setAttributeNS(null, 'y', bbox[1]);\n cliprect.setAttributeNS(null, 'width', pf(width));\n cliprect.setAttributeNS(null, 'height', pf(height));\n this.current.element = cliprect;\n this.clip('nonzero');\n this.endPath();\n }\n },\n\n paintFormXObjectEnd:\n function SVGGraphics_paintFormXObjectEnd() {\n this.restore();\n }\n };\n return SVGGraphics;\n})();\n\nPDFJS.SVGGraphics = SVGGraphics;\n\nexports.SVGGraphics = SVGGraphics;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,\n root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal);\n }\n}(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) {\n\nvar Util = sharedUtil.Util;\nvar createPromiseCapability = sharedUtil.createPromiseCapability;\nvar CustomStyle = displayDOMUtils.CustomStyle;\nvar PDFJS = sharedGlobal.PDFJS;\n\n/**\n * Text layer render parameters.\n *\n * @typedef {Object} TextLayerRenderParameters\n * @property {TextContent} textContent - Text content to render (the object is\n * returned by the page's getTextContent() method).\n * @property {HTMLElement} container - HTML element that will contain text runs.\n * @property {PDFJS.PageViewport} viewport - The target viewport to properly\n * layout the text runs.\n * @property {Array} textDivs - (optional) HTML elements that are correspond\n * the text items of the textContent input. This is output and shall be\n * initially be set to empty array.\n * @property {number} timeout - (optional) Delay in milliseconds before\n * rendering of the text runs occurs.\n */\nvar renderTextLayer = (function renderTextLayerClosure() {\n var MAX_TEXT_DIVS_TO_RENDER = 100000;\n\n var NonWhitespaceRegexp = /\\S/;\n\n function isAllWhitespace(str) {\n return !NonWhitespaceRegexp.test(str);\n }\n\n function appendText(textDivs, viewport, geom, styles) {\n var style = styles[geom.fontName];\n var textDiv = document.createElement('div');\n textDivs.push(textDiv);\n if (isAllWhitespace(geom.str)) {\n textDiv.dataset.isWhitespace = true;\n return;\n }\n var tx = Util.transform(viewport.transform, geom.transform);\n var angle = Math.atan2(tx[1], tx[0]);\n if (style.vertical) {\n angle += Math.PI / 2;\n }\n var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));\n var fontAscent = fontHeight;\n if (style.ascent) {\n fontAscent = style.ascent * fontAscent;\n } else if (style.descent) {\n fontAscent = (1 + style.descent) * fontAscent;\n }\n\n var left;\n var top;\n if (angle === 0) {\n left = tx[4];\n top = tx[5] - fontAscent;\n } else {\n left = tx[4] + (fontAscent * Math.sin(angle));\n top = tx[5] - (fontAscent * Math.cos(angle));\n }\n textDiv.style.left = left + 'px';\n textDiv.style.top = top + 'px';\n textDiv.style.fontSize = fontHeight + 'px';\n textDiv.style.fontFamily = style.fontFamily;\n\n textDiv.textContent = geom.str;\n // |fontName| is only used by the Font Inspector. This test will succeed\n // when e.g. the Font Inspector is off but the Stepper is on, but it's\n // not worth the effort to do a more accurate test.\n if (PDFJS.pdfBug) {\n textDiv.dataset.fontName = geom.fontName;\n }\n // Storing into dataset will convert number into string.\n if (angle !== 0) {\n textDiv.dataset.angle = angle * (180 / Math.PI);\n }\n // We don't bother scaling single-char text divs, because it has very\n // little effect on text highlighting. This makes scrolling on docs with\n // lots of such divs a lot faster.\n if (geom.str.length > 1) {\n if (style.vertical) {\n textDiv.dataset.canvasWidth = geom.height * viewport.scale;\n } else {\n textDiv.dataset.canvasWidth = geom.width * viewport.scale;\n }\n }\n }\n\n function render(task) {\n if (task._canceled) {\n return;\n }\n var textLayerFrag = task._container;\n var textDivs = task._textDivs;\n var capability = task._capability;\n var textDivsLength = textDivs.length;\n\n // No point in rendering many divs as it would make the browser\n // unusable even after the divs are rendered.\n if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {\n capability.resolve();\n return;\n }\n\n var canvas = document.createElement('canvas');\n canvas.mozOpaque = true;\n var ctx = canvas.getContext('2d', {alpha: false});\n\n var lastFontSize;\n var lastFontFamily;\n for (var i = 0; i < textDivsLength; i++) {\n var textDiv = textDivs[i];\n if (textDiv.dataset.isWhitespace !== undefined) {\n continue;\n }\n\n var fontSize = textDiv.style.fontSize;\n var fontFamily = textDiv.style.fontFamily;\n\n // Only build font string and set to context if different from last.\n if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {\n ctx.font = fontSize + ' ' + fontFamily;\n lastFontSize = fontSize;\n lastFontFamily = fontFamily;\n }\n\n var width = ctx.measureText(textDiv.textContent).width;\n if (width > 0) {\n textLayerFrag.appendChild(textDiv);\n var transform;\n if (textDiv.dataset.canvasWidth !== undefined) {\n // Dataset values come of type string.\n var textScale = textDiv.dataset.canvasWidth / width;\n transform = 'scaleX(' + textScale + ')';\n } else {\n transform = '';\n }\n var rotation = textDiv.dataset.angle;\n if (rotation) {\n transform = 'rotate(' + rotation + 'deg) ' + transform;\n }\n if (transform) {\n CustomStyle.setProp('transform' , textDiv, transform);\n }\n }\n }\n capability.resolve();\n }\n\n /**\n * Text layer rendering task.\n *\n * @param {TextContent} textContent\n * @param {HTMLElement} container\n * @param {PDFJS.PageViewport} viewport\n * @param {Array} textDivs\n * @private\n */\n function TextLayerRenderTask(textContent, container, viewport, textDivs) {\n this._textContent = textContent;\n this._container = container;\n this._viewport = viewport;\n textDivs = textDivs || [];\n this._textDivs = textDivs;\n this._canceled = false;\n this._capability = createPromiseCapability();\n this._renderTimer = null;\n }\n TextLayerRenderTask.prototype = {\n get promise() {\n return this._capability.promise;\n },\n\n cancel: function TextLayer_cancel() {\n this._canceled = true;\n if (this._renderTimer !== null) {\n clearTimeout(this._renderTimer);\n this._renderTimer = null;\n }\n this._capability.reject('canceled');\n },\n\n _render: function TextLayer_render(timeout) {\n var textItems = this._textContent.items;\n var styles = this._textContent.styles;\n var textDivs = this._textDivs;\n var viewport = this._viewport;\n for (var i = 0, len = textItems.length; i < len; i++) {\n appendText(textDivs, viewport, textItems[i], styles);\n }\n\n if (!timeout) { // Render right away\n render(this);\n } else { // Schedule\n var self = this;\n this._renderTimer = setTimeout(function() {\n render(self);\n self._renderTimer = null;\n }, timeout);\n }\n }\n };\n\n\n /**\n * Starts rendering of the text layer.\n *\n * @param {TextLayerRenderParameters} renderParameters\n * @returns {TextLayerRenderTask}\n */\n function renderTextLayer(renderParameters) {\n var task = new TextLayerRenderTask(renderParameters.textContent,\n renderParameters.container,\n renderParameters.viewport,\n renderParameters.textDivs);\n task._render(renderParameters.timeout);\n return task;\n }\n\n return renderTextLayer;\n})();\n\nPDFJS.renderTextLayer = renderTextLayer;\n\nexports.renderTextLayer = renderTextLayer;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil);\n }\n}(this, function (exports, sharedUtil) {\n\nvar shadow = sharedUtil.shadow;\n\nvar WebGLUtils = (function WebGLUtilsClosure() {\n function loadShader(gl, code, shaderType) {\n var shader = gl.createShader(shaderType);\n gl.shaderSource(shader, code);\n gl.compileShader(shader);\n var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);\n if (!compiled) {\n var errorMsg = gl.getShaderInfoLog(shader);\n throw new Error('Error during shader compilation: ' + errorMsg);\n }\n return shader;\n }\n function createVertexShader(gl, code) {\n return loadShader(gl, code, gl.VERTEX_SHADER);\n }\n function createFragmentShader(gl, code) {\n return loadShader(gl, code, gl.FRAGMENT_SHADER);\n }\n function createProgram(gl, shaders) {\n var program = gl.createProgram();\n for (var i = 0, ii = shaders.length; i < ii; ++i) {\n gl.attachShader(program, shaders[i]);\n }\n gl.linkProgram(program);\n var linked = gl.getProgramParameter(program, gl.LINK_STATUS);\n if (!linked) {\n var errorMsg = gl.getProgramInfoLog(program);\n throw new Error('Error during program linking: ' + errorMsg);\n }\n return program;\n }\n function createTexture(gl, image, textureId) {\n gl.activeTexture(textureId);\n var texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Set the parameters so we can render any size image.\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n // Upload the image into the texture.\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n return texture;\n }\n\n var currentGL, currentCanvas;\n function generateGL() {\n if (currentGL) {\n return;\n }\n currentCanvas = document.createElement('canvas');\n currentGL = currentCanvas.getContext('webgl',\n { premultipliedalpha: false });\n }\n\n var smaskVertexShaderCode = '\\\n attribute vec2 a_position; \\\n attribute vec2 a_texCoord; \\\n \\\n uniform vec2 u_resolution; \\\n \\\n varying vec2 v_texCoord; \\\n \\\n void main() { \\\n vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \\\n gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \\\n \\\n v_texCoord = a_texCoord; \\\n } ';\n\n var smaskFragmentShaderCode = '\\\n precision mediump float; \\\n \\\n uniform vec4 u_backdrop; \\\n uniform int u_subtype; \\\n uniform sampler2D u_image; \\\n uniform sampler2D u_mask; \\\n \\\n varying vec2 v_texCoord; \\\n \\\n void main() { \\\n vec4 imageColor = texture2D(u_image, v_texCoord); \\\n vec4 maskColor = texture2D(u_mask, v_texCoord); \\\n if (u_backdrop.a > 0.0) { \\\n maskColor.rgb = maskColor.rgb * maskColor.a + \\\n u_backdrop.rgb * (1.0 - maskColor.a); \\\n } \\\n float lum; \\\n if (u_subtype == 0) { \\\n lum = maskColor.a; \\\n } else { \\\n lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \\\n maskColor.b * 0.11; \\\n } \\\n imageColor.a *= lum; \\\n imageColor.rgb *= imageColor.a; \\\n gl_FragColor = imageColor; \\\n } ';\n\n var smaskCache = null;\n\n function initSmaskGL() {\n var canvas, gl;\n\n generateGL();\n canvas = currentCanvas;\n currentCanvas = null;\n gl = currentGL;\n currentGL = null;\n\n // setup a GLSL program\n var vertexShader = createVertexShader(gl, smaskVertexShaderCode);\n var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);\n var program = createProgram(gl, [vertexShader, fragmentShader]);\n gl.useProgram(program);\n\n var cache = {};\n cache.gl = gl;\n cache.canvas = canvas;\n cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');\n cache.positionLocation = gl.getAttribLocation(program, 'a_position');\n cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');\n cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');\n\n var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');\n var texLayerLocation = gl.getUniformLocation(program, 'u_image');\n var texMaskLocation = gl.getUniformLocation(program, 'u_mask');\n\n // provide texture coordinates for the rectangle.\n var texCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([\n 0.0, 0.0,\n 1.0, 0.0,\n 0.0, 1.0,\n 0.0, 1.0,\n 1.0, 0.0,\n 1.0, 1.0]), gl.STATIC_DRAW);\n gl.enableVertexAttribArray(texCoordLocation);\n gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);\n\n gl.uniform1i(texLayerLocation, 0);\n gl.uniform1i(texMaskLocation, 1);\n\n smaskCache = cache;\n }\n\n function composeSMask(layer, mask, properties) {\n var width = layer.width, height = layer.height;\n\n if (!smaskCache) {\n initSmaskGL();\n }\n var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;\n canvas.width = width;\n canvas.height = height;\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.uniform2f(cache.resolutionLocation, width, height);\n\n if (properties.backdrop) {\n gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],\n properties.backdrop[1], properties.backdrop[2], 1);\n } else {\n gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);\n }\n gl.uniform1i(cache.subtypeLocation,\n properties.subtype === 'Luminosity' ? 1 : 0);\n\n // Create a textures\n var texture = createTexture(gl, layer, gl.TEXTURE0);\n var maskTexture = createTexture(gl, mask, gl.TEXTURE1);\n\n\n // Create a buffer and put a single clipspace rectangle in\n // it (2 triangles)\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([\n 0, 0,\n width, 0,\n 0, height,\n 0, height,\n width, 0,\n width, height]), gl.STATIC_DRAW);\n gl.enableVertexAttribArray(cache.positionLocation);\n gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);\n\n // draw\n gl.clearColor(0, 0, 0, 0);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n\n gl.flush();\n\n gl.deleteTexture(texture);\n gl.deleteTexture(maskTexture);\n gl.deleteBuffer(buffer);\n\n return canvas;\n }\n\n var figuresVertexShaderCode = '\\\n attribute vec2 a_position; \\\n attribute vec3 a_color; \\\n \\\n uniform vec2 u_resolution; \\\n uniform vec2 u_scale; \\\n uniform vec2 u_offset; \\\n \\\n varying vec4 v_color; \\\n \\\n void main() { \\\n vec2 position = (a_position + u_offset) * u_scale; \\\n vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \\\n gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \\\n \\\n v_color = vec4(a_color / 255.0, 1.0); \\\n } ';\n\n var figuresFragmentShaderCode = '\\\n precision mediump float; \\\n \\\n varying vec4 v_color; \\\n \\\n void main() { \\\n gl_FragColor = v_color; \\\n } ';\n\n var figuresCache = null;\n\n function initFiguresGL() {\n var canvas, gl;\n\n generateGL();\n canvas = currentCanvas;\n currentCanvas = null;\n gl = currentGL;\n currentGL = null;\n\n // setup a GLSL program\n var vertexShader = createVertexShader(gl, figuresVertexShaderCode);\n var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);\n var program = createProgram(gl, [vertexShader, fragmentShader]);\n gl.useProgram(program);\n\n var cache = {};\n cache.gl = gl;\n cache.canvas = canvas;\n cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');\n cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');\n cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');\n cache.positionLocation = gl.getAttribLocation(program, 'a_position');\n cache.colorLocation = gl.getAttribLocation(program, 'a_color');\n\n figuresCache = cache;\n }\n\n function drawFigures(width, height, backgroundColor, figures, context) {\n if (!figuresCache) {\n initFiguresGL();\n }\n var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;\n\n canvas.width = width;\n canvas.height = height;\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n gl.uniform2f(cache.resolutionLocation, width, height);\n\n // count triangle points\n var count = 0;\n var i, ii, rows;\n for (i = 0, ii = figures.length; i < ii; i++) {\n switch (figures[i].type) {\n case 'lattice':\n rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;\n count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;\n break;\n case 'triangles':\n count += figures[i].coords.length;\n break;\n }\n }\n // transfer data\n var coords = new Float32Array(count * 2);\n var colors = new Uint8Array(count * 3);\n var coordsMap = context.coords, colorsMap = context.colors;\n var pIndex = 0, cIndex = 0;\n for (i = 0, ii = figures.length; i < ii; i++) {\n var figure = figures[i], ps = figure.coords, cs = figure.colors;\n switch (figure.type) {\n case 'lattice':\n var cols = figure.verticesPerRow;\n rows = (ps.length / cols) | 0;\n for (var row = 1; row < rows; row++) {\n var offset = row * cols + 1;\n for (var col = 1; col < cols; col++, offset++) {\n coords[pIndex] = coordsMap[ps[offset - cols - 1]];\n coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];\n coords[pIndex + 2] = coordsMap[ps[offset - cols]];\n coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];\n coords[pIndex + 4] = coordsMap[ps[offset - 1]];\n coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];\n colors[cIndex] = colorsMap[cs[offset - cols - 1]];\n colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];\n colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];\n colors[cIndex + 3] = colorsMap[cs[offset - cols]];\n colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];\n colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];\n colors[cIndex + 6] = colorsMap[cs[offset - 1]];\n colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];\n colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];\n\n coords[pIndex + 6] = coords[pIndex + 2];\n coords[pIndex + 7] = coords[pIndex + 3];\n coords[pIndex + 8] = coords[pIndex + 4];\n coords[pIndex + 9] = coords[pIndex + 5];\n coords[pIndex + 10] = coordsMap[ps[offset]];\n coords[pIndex + 11] = coordsMap[ps[offset] + 1];\n colors[cIndex + 9] = colors[cIndex + 3];\n colors[cIndex + 10] = colors[cIndex + 4];\n colors[cIndex + 11] = colors[cIndex + 5];\n colors[cIndex + 12] = colors[cIndex + 6];\n colors[cIndex + 13] = colors[cIndex + 7];\n colors[cIndex + 14] = colors[cIndex + 8];\n colors[cIndex + 15] = colorsMap[cs[offset]];\n colors[cIndex + 16] = colorsMap[cs[offset] + 1];\n colors[cIndex + 17] = colorsMap[cs[offset] + 2];\n pIndex += 12;\n cIndex += 18;\n }\n }\n break;\n case 'triangles':\n for (var j = 0, jj = ps.length; j < jj; j++) {\n coords[pIndex] = coordsMap[ps[j]];\n coords[pIndex + 1] = coordsMap[ps[j] + 1];\n colors[cIndex] = colorsMap[cs[j]];\n colors[cIndex + 1] = colorsMap[cs[j] + 1];\n colors[cIndex + 2] = colorsMap[cs[j] + 2];\n pIndex += 2;\n cIndex += 3;\n }\n break;\n }\n }\n\n // draw\n if (backgroundColor) {\n gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,\n backgroundColor[2] / 255, 1.0);\n } else {\n gl.clearColor(0, 0, 0, 0);\n }\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n var coordsBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(cache.positionLocation);\n gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);\n\n var colorsBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(cache.colorLocation);\n gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,\n 0, 0);\n\n gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);\n gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);\n\n gl.drawArrays(gl.TRIANGLES, 0, count);\n\n gl.flush();\n\n gl.deleteBuffer(coordsBuffer);\n gl.deleteBuffer(colorsBuffer);\n\n return canvas;\n }\n\n function cleanup() {\n if (smaskCache && smaskCache.canvas) {\n smaskCache.canvas.width = 0;\n smaskCache.canvas.height = 0;\n }\n if (figuresCache && figuresCache.canvas) {\n figuresCache.canvas.width = 0;\n figuresCache.canvas.height = 0;\n }\n smaskCache = null;\n figuresCache = null;\n }\n\n return {\n get isEnabled() {\n if (PDFJS.disableWebGL) {\n return false;\n }\n var enabled = false;\n try {\n generateGL();\n enabled = !!currentGL;\n } catch (e) { }\n return shadow(this, 'isEnabled', enabled);\n },\n composeSMask: composeSMask,\n drawFigures: drawFigures,\n clear: cleanup\n };\n})();\n\nexports.WebGLUtils = WebGLUtils;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,\n root.pdfjsDisplayWebGL);\n }\n}(this, function (exports, sharedUtil, displayWebGL) {\n\nvar Util = sharedUtil.Util;\nvar info = sharedUtil.info;\nvar isArray = sharedUtil.isArray;\nvar error = sharedUtil.error;\nvar WebGLUtils = displayWebGL.WebGLUtils;\n\nvar ShadingIRs = {};\n\nShadingIRs.RadialAxial = {\n fromIR: function RadialAxial_fromIR(raw) {\n var type = raw[1];\n var colorStops = raw[2];\n var p0 = raw[3];\n var p1 = raw[4];\n var r0 = raw[5];\n var r1 = raw[6];\n return {\n type: 'Pattern',\n getPattern: function RadialAxial_getPattern(ctx) {\n var grad;\n if (type === 'axial') {\n grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);\n } else if (type === 'radial') {\n grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);\n }\n\n for (var i = 0, ii = colorStops.length; i < ii; ++i) {\n var c = colorStops[i];\n grad.addColorStop(c[0], c[1]);\n }\n return grad;\n }\n };\n }\n};\n\nvar createMeshCanvas = (function createMeshCanvasClosure() {\n function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {\n // Very basic Gouraud-shaded triangle rasterization algorithm.\n var coords = context.coords, colors = context.colors;\n var bytes = data.data, rowSize = data.width * 4;\n var tmp;\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;\n }\n if (coords[p2 + 1] > coords[p3 + 1]) {\n tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;\n }\n if (coords[p1 + 1] > coords[p2 + 1]) {\n tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;\n }\n var x1 = (coords[p1] + context.offsetX) * context.scaleX;\n var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;\n var x2 = (coords[p2] + context.offsetX) * context.scaleX;\n var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;\n var x3 = (coords[p3] + context.offsetX) * context.scaleX;\n var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;\n if (y1 >= y3) {\n return;\n }\n var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];\n var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];\n var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];\n\n var minY = Math.round(y1), maxY = Math.round(y3);\n var xa, car, cag, cab;\n var xb, cbr, cbg, cbb;\n var k;\n for (var y = minY; y <= maxY; y++) {\n if (y < y2) {\n k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);\n xa = x1 - (x1 - x2) * k;\n car = c1r - (c1r - c2r) * k;\n cag = c1g - (c1g - c2g) * k;\n cab = c1b - (c1b - c2b) * k;\n } else {\n k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);\n xa = x2 - (x2 - x3) * k;\n car = c2r - (c2r - c3r) * k;\n cag = c2g - (c2g - c3g) * k;\n cab = c2b - (c2b - c3b) * k;\n }\n k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);\n xb = x1 - (x1 - x3) * k;\n cbr = c1r - (c1r - c3r) * k;\n cbg = c1g - (c1g - c3g) * k;\n cbb = c1b - (c1b - c3b) * k;\n var x1_ = Math.round(Math.min(xa, xb));\n var x2_ = Math.round(Math.max(xa, xb));\n var j = rowSize * y + x1_ * 4;\n for (var x = x1_; x <= x2_; x++) {\n k = (xa - x) / (xa - xb);\n k = k < 0 ? 0 : k > 1 ? 1 : k;\n bytes[j++] = (car - (car - cbr) * k) | 0;\n bytes[j++] = (cag - (cag - cbg) * k) | 0;\n bytes[j++] = (cab - (cab - cbb) * k) | 0;\n bytes[j++] = 255;\n }\n }\n }\n\n function drawFigure(data, figure, context) {\n var ps = figure.coords;\n var cs = figure.colors;\n var i, ii;\n switch (figure.type) {\n case 'lattice':\n var verticesPerRow = figure.verticesPerRow;\n var rows = Math.floor(ps.length / verticesPerRow) - 1;\n var cols = verticesPerRow - 1;\n for (i = 0; i < rows; i++) {\n var q = i * verticesPerRow;\n for (var j = 0; j < cols; j++, q++) {\n drawTriangle(data, context,\n ps[q], ps[q + 1], ps[q + verticesPerRow],\n cs[q], cs[q + 1], cs[q + verticesPerRow]);\n drawTriangle(data, context,\n ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],\n cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);\n }\n }\n break;\n case 'triangles':\n for (i = 0, ii = ps.length; i < ii; i += 3) {\n drawTriangle(data, context,\n ps[i], ps[i + 1], ps[i + 2],\n cs[i], cs[i + 1], cs[i + 2]);\n }\n break;\n default:\n error('illigal figure');\n break;\n }\n }\n\n function createMeshCanvas(bounds, combinesScale, coords, colors, figures,\n backgroundColor, cachedCanvases) {\n // we will increase scale on some weird factor to let antialiasing take\n // care of \"rough\" edges\n var EXPECTED_SCALE = 1.1;\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough\n\n var offsetX = Math.floor(bounds[0]);\n var offsetY = Math.floor(bounds[1]);\n var boundsWidth = Math.ceil(bounds[2]) - offsetX;\n var boundsHeight = Math.ceil(bounds[3]) - offsetY;\n\n var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *\n EXPECTED_SCALE)), MAX_PATTERN_SIZE);\n var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *\n EXPECTED_SCALE)), MAX_PATTERN_SIZE);\n var scaleX = boundsWidth / width;\n var scaleY = boundsHeight / height;\n\n var context = {\n coords: coords,\n colors: colors,\n offsetX: -offsetX,\n offsetY: -offsetY,\n scaleX: 1 / scaleX,\n scaleY: 1 / scaleY\n };\n\n var canvas, tmpCanvas, i, ii;\n if (WebGLUtils.isEnabled) {\n canvas = WebGLUtils.drawFigures(width, height, backgroundColor,\n figures, context);\n\n // https://bugzilla.mozilla.org/show_bug.cgi?id=972126\n tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);\n tmpCanvas.context.drawImage(canvas, 0, 0);\n canvas = tmpCanvas.canvas;\n } else {\n tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);\n var tmpCtx = tmpCanvas.context;\n\n var data = tmpCtx.createImageData(width, height);\n if (backgroundColor) {\n var bytes = data.data;\n for (i = 0, ii = bytes.length; i < ii; i += 4) {\n bytes[i] = backgroundColor[0];\n bytes[i + 1] = backgroundColor[1];\n bytes[i + 2] = backgroundColor[2];\n bytes[i + 3] = 255;\n }\n }\n for (i = 0; i < figures.length; i++) {\n drawFigure(data, figures[i], context);\n }\n tmpCtx.putImageData(data, 0, 0);\n canvas = tmpCanvas.canvas;\n }\n\n return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,\n scaleX: scaleX, scaleY: scaleY};\n }\n return createMeshCanvas;\n})();\n\nShadingIRs.Mesh = {\n fromIR: function Mesh_fromIR(raw) {\n //var type = raw[1];\n var coords = raw[2];\n var colors = raw[3];\n var figures = raw[4];\n var bounds = raw[5];\n var matrix = raw[6];\n //var bbox = raw[7];\n var background = raw[8];\n return {\n type: 'Pattern',\n getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {\n var scale;\n if (shadingFill) {\n scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);\n } else {\n // Obtain scale from matrix and current transformation matrix.\n scale = Util.singularValueDecompose2dScale(owner.baseTransform);\n if (matrix) {\n var matrixScale = Util.singularValueDecompose2dScale(matrix);\n scale = [scale[0] * matrixScale[0],\n scale[1] * matrixScale[1]];\n }\n }\n\n\n // Rasterizing on the main thread since sending/queue large canvases\n // might cause OOM.\n var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,\n colors, figures, shadingFill ? null : background,\n owner.cachedCanvases);\n\n if (!shadingFill) {\n ctx.setTransform.apply(ctx, owner.baseTransform);\n if (matrix) {\n ctx.transform.apply(ctx, matrix);\n }\n }\n\n ctx.translate(temporaryPatternCanvas.offsetX,\n temporaryPatternCanvas.offsetY);\n ctx.scale(temporaryPatternCanvas.scaleX,\n temporaryPatternCanvas.scaleY);\n\n return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');\n }\n };\n }\n};\n\nShadingIRs.Dummy = {\n fromIR: function Dummy_fromIR() {\n return {\n type: 'Pattern',\n getPattern: function Dummy_fromIR_getPattern() {\n return 'hotpink';\n }\n };\n }\n};\n\nfunction getShadingPatternFromIR(raw) {\n var shadingIR = ShadingIRs[raw[0]];\n if (!shadingIR) {\n error('Unknown IR type: ' + raw[0]);\n }\n return shadingIR.fromIR(raw);\n}\n\nvar TilingPattern = (function TilingPatternClosure() {\n var PaintType = {\n COLORED: 1,\n UNCOLORED: 2\n };\n\n var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough\n\n function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {\n this.operatorList = IR[2];\n this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];\n this.bbox = IR[4];\n this.xstep = IR[5];\n this.ystep = IR[6];\n this.paintType = IR[7];\n this.tilingType = IR[8];\n this.color = color;\n this.canvasGraphicsFactory = canvasGraphicsFactory;\n this.baseTransform = baseTransform;\n this.type = 'Pattern';\n this.ctx = ctx;\n }\n\n TilingPattern.prototype = {\n createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {\n var operatorList = this.operatorList;\n var bbox = this.bbox;\n var xstep = this.xstep;\n var ystep = this.ystep;\n var paintType = this.paintType;\n var tilingType = this.tilingType;\n var color = this.color;\n var canvasGraphicsFactory = this.canvasGraphicsFactory;\n\n info('TilingType: ' + tilingType);\n\n var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];\n\n var topLeft = [x0, y0];\n // we want the canvas to be as large as the step size\n var botRight = [x0 + xstep, y0 + ystep];\n\n var width = botRight[0] - topLeft[0];\n var height = botRight[1] - topLeft[1];\n\n // Obtain scale from matrix and current transformation matrix.\n var matrixScale = Util.singularValueDecompose2dScale(this.matrix);\n var curMatrixScale = Util.singularValueDecompose2dScale(\n this.baseTransform);\n var combinedScale = [matrixScale[0] * curMatrixScale[0],\n matrixScale[1] * curMatrixScale[1]];\n\n // MAX_PATTERN_SIZE is used to avoid OOM situation.\n // Use width and height values that are as close as possible to the end\n // result when the pattern is used. Too low value makes the pattern look\n // blurry. Too large value makes it look too crispy.\n width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),\n MAX_PATTERN_SIZE);\n\n height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),\n MAX_PATTERN_SIZE);\n\n var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',\n width, height, true);\n var tmpCtx = tmpCanvas.context;\n var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);\n graphics.groupLevel = owner.groupLevel;\n\n this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);\n\n this.setScale(width, height, xstep, ystep);\n this.transformToScale(graphics);\n\n // transform coordinates to pattern space\n var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];\n graphics.transform.apply(graphics, tmpTranslate);\n\n this.clipBbox(graphics, bbox, x0, y0, x1, y1);\n\n graphics.executeOperatorList(operatorList);\n return tmpCanvas.canvas;\n },\n\n setScale: function TilingPattern_setScale(width, height, xstep, ystep) {\n this.scale = [width / xstep, height / ystep];\n },\n\n transformToScale: function TilingPattern_transformToScale(graphics) {\n var scale = this.scale;\n var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];\n graphics.transform.apply(graphics, tmpScale);\n },\n\n scaleToContext: function TilingPattern_scaleToContext() {\n var scale = this.scale;\n this.ctx.scale(1 / scale[0], 1 / scale[1]);\n },\n\n clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {\n if (bbox && isArray(bbox) && bbox.length === 4) {\n var bboxWidth = x1 - x0;\n var bboxHeight = y1 - y0;\n graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);\n graphics.clip();\n graphics.endPath();\n }\n },\n\n setFillAndStrokeStyleToContext:\n function setFillAndStrokeStyleToContext(context, paintType, color) {\n switch (paintType) {\n case PaintType.COLORED:\n var ctx = this.ctx;\n context.fillStyle = ctx.fillStyle;\n context.strokeStyle = ctx.strokeStyle;\n break;\n case PaintType.UNCOLORED:\n var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);\n context.fillStyle = cssColor;\n context.strokeStyle = cssColor;\n break;\n default:\n error('Unsupported paint type: ' + paintType);\n }\n },\n\n getPattern: function TilingPattern_getPattern(ctx, owner) {\n var temporaryPatternCanvas = this.createPatternCanvas(owner);\n\n ctx = this.ctx;\n ctx.setTransform.apply(ctx, this.baseTransform);\n ctx.transform.apply(ctx, this.matrix);\n this.scaleToContext();\n\n return ctx.createPattern(temporaryPatternCanvas, 'repeat');\n }\n };\n\n return TilingPattern;\n})();\n\nexports.getShadingPatternFromIR = getShadingPatternFromIR;\nexports.TilingPattern = TilingPattern;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,\n root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);\n }\n}(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) {\n\nvar FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;\nvar IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;\nvar ImageKind = sharedUtil.ImageKind;\nvar OPS = sharedUtil.OPS;\nvar TextRenderingMode = sharedUtil.TextRenderingMode;\nvar Uint32ArrayView = sharedUtil.Uint32ArrayView;\nvar Util = sharedUtil.Util;\nvar assert = sharedUtil.assert;\nvar info = sharedUtil.info;\nvar isNum = sharedUtil.isNum;\nvar isArray = sharedUtil.isArray;\nvar error = sharedUtil.error;\nvar shadow = sharedUtil.shadow;\nvar warn = sharedUtil.warn;\nvar TilingPattern = displayPatternHelper.TilingPattern;\nvar getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;\nvar WebGLUtils = displayWebGL.WebGLUtils;\n\n// contexts store most of the state we need natively.\n// However, PDF needs a bit more state, which we store here.\n\n// Minimal font size that would be used during canvas fillText operations.\nvar MIN_FONT_SIZE = 16;\n// Maximum font size that would be used during canvas fillText operations.\nvar MAX_FONT_SIZE = 100;\nvar MAX_GROUP_SIZE = 4096;\n\n// Heuristic value used when enforcing minimum line widths.\nvar MIN_WIDTH_FACTOR = 0.65;\n\nvar COMPILE_TYPE3_GLYPHS = true;\nvar MAX_SIZE_TO_COMPILE = 1000;\n\nvar FULL_CHUNK_HEIGHT = 16;\n\nfunction createScratchCanvas(width, height) {\n var canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n}\n\nfunction addContextCurrentTransform(ctx) {\n // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.\n if (!ctx.mozCurrentTransform) {\n ctx._originalSave = ctx.save;\n ctx._originalRestore = ctx.restore;\n ctx._originalRotate = ctx.rotate;\n ctx._originalScale = ctx.scale;\n ctx._originalTranslate = ctx.translate;\n ctx._originalTransform = ctx.transform;\n ctx._originalSetTransform = ctx.setTransform;\n\n ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];\n ctx._transformStack = [];\n\n Object.defineProperty(ctx, 'mozCurrentTransform', {\n get: function getCurrentTransform() {\n return this._transformMatrix;\n }\n });\n\n Object.defineProperty(ctx, 'mozCurrentTransformInverse', {\n get: function getCurrentTransformInverse() {\n // Calculation done using WolframAlpha:\n // http://www.wolframalpha.com/input/?\n // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}\n\n var m = this._transformMatrix;\n var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];\n\n var ad_bc = a * d - b * c;\n var bc_ad = b * c - a * d;\n\n return [\n d / ad_bc,\n b / bc_ad,\n c / bc_ad,\n a / ad_bc,\n (d * e - c * f) / bc_ad,\n (b * e - a * f) / ad_bc\n ];\n }\n });\n\n ctx.save = function ctxSave() {\n var old = this._transformMatrix;\n this._transformStack.push(old);\n this._transformMatrix = old.slice(0, 6);\n\n this._originalSave();\n };\n\n ctx.restore = function ctxRestore() {\n var prev = this._transformStack.pop();\n if (prev) {\n this._transformMatrix = prev;\n this._originalRestore();\n }\n };\n\n ctx.translate = function ctxTranslate(x, y) {\n var m = this._transformMatrix;\n m[4] = m[0] * x + m[2] * y + m[4];\n m[5] = m[1] * x + m[3] * y + m[5];\n\n this._originalTranslate(x, y);\n };\n\n ctx.scale = function ctxScale(x, y) {\n var m = this._transformMatrix;\n m[0] = m[0] * x;\n m[1] = m[1] * x;\n m[2] = m[2] * y;\n m[3] = m[3] * y;\n\n this._originalScale(x, y);\n };\n\n ctx.transform = function ctxTransform(a, b, c, d, e, f) {\n var m = this._transformMatrix;\n this._transformMatrix = [\n m[0] * a + m[2] * b,\n m[1] * a + m[3] * b,\n m[0] * c + m[2] * d,\n m[1] * c + m[3] * d,\n m[0] * e + m[2] * f + m[4],\n m[1] * e + m[3] * f + m[5]\n ];\n\n ctx._originalTransform(a, b, c, d, e, f);\n };\n\n ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {\n this._transformMatrix = [a, b, c, d, e, f];\n\n ctx._originalSetTransform(a, b, c, d, e, f);\n };\n\n ctx.rotate = function ctxRotate(angle) {\n var cosValue = Math.cos(angle);\n var sinValue = Math.sin(angle);\n\n var m = this._transformMatrix;\n this._transformMatrix = [\n m[0] * cosValue + m[2] * sinValue,\n m[1] * cosValue + m[3] * sinValue,\n m[0] * (-sinValue) + m[2] * cosValue,\n m[1] * (-sinValue) + m[3] * cosValue,\n m[4],\n m[5]\n ];\n\n this._originalRotate(angle);\n };\n }\n}\n\nvar CachedCanvases = (function CachedCanvasesClosure() {\n function CachedCanvases() {\n this.cache = Object.create(null);\n }\n CachedCanvases.prototype = {\n getCanvas: function CachedCanvases_getCanvas(id, width, height,\n trackTransform) {\n var canvasEntry;\n if (this.cache[id] !== undefined) {\n canvasEntry = this.cache[id];\n canvasEntry.canvas.width = width;\n canvasEntry.canvas.height = height;\n // reset canvas transform for emulated mozCurrentTransform, if needed\n canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);\n } else {\n var canvas = createScratchCanvas(width, height);\n var ctx = canvas.getContext('2d');\n if (trackTransform) {\n addContextCurrentTransform(ctx);\n }\n this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};\n }\n return canvasEntry;\n },\n clear: function () {\n for (var id in this.cache) {\n var canvasEntry = this.cache[id];\n // Zeroing the width and height causes Firefox to release graphics\n // resources immediately, which can greatly reduce memory consumption.\n canvasEntry.canvas.width = 0;\n canvasEntry.canvas.height = 0;\n delete this.cache[id];\n }\n }\n };\n return CachedCanvases;\n})();\n\nfunction compileType3Glyph(imgData) {\n var POINT_TO_PROCESS_LIMIT = 1000;\n\n var width = imgData.width, height = imgData.height;\n var i, j, j0, width1 = width + 1;\n var points = new Uint8Array(width1 * (height + 1));\n var POINT_TYPES =\n new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);\n\n // decodes bit-packed mask data\n var lineSize = (width + 7) & ~7, data0 = imgData.data;\n var data = new Uint8Array(lineSize * height), pos = 0, ii;\n for (i = 0, ii = data0.length; i < ii; i++) {\n var mask = 128, elem = data0[i];\n while (mask > 0) {\n data[pos++] = (elem & mask) ? 0 : 255;\n mask >>= 1;\n }\n }\n\n // finding iteresting points: every point is located between mask pixels,\n // so there will be points of the (width + 1)x(height + 1) grid. Every point\n // will have flags assigned based on neighboring mask pixels:\n // 4 | 8\n // --P--\n // 2 | 1\n // We are interested only in points with the flags:\n // - outside corners: 1, 2, 4, 8;\n // - inside corners: 7, 11, 13, 14;\n // - and, intersections: 5, 10.\n var count = 0;\n pos = 0;\n if (data[pos] !== 0) {\n points[0] = 1;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j] = data[pos] ? 2 : 1;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j] = 2;\n ++count;\n }\n for (i = 1; i < height; i++) {\n pos = i * lineSize;\n j0 = i * width1;\n if (data[pos - lineSize] !== data[pos]) {\n points[j0] = data[pos] ? 1 : 8;\n ++count;\n }\n // 'sum' is the position of the current pixel configuration in the 'TYPES'\n // array (in order 8-1-2-4, so we can use '>>2' to shift the column).\n var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);\n for (j = 1; j < width; j++) {\n sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +\n (data[pos - lineSize + 1] ? 8 : 0);\n if (POINT_TYPES[sum]) {\n points[j0 + j] = POINT_TYPES[sum];\n ++count;\n }\n pos++;\n }\n if (data[pos - lineSize] !== data[pos]) {\n points[j0 + j] = data[pos] ? 2 : 4;\n ++count;\n }\n\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n }\n\n pos = lineSize * (height - 1);\n j0 = i * width1;\n if (data[pos] !== 0) {\n points[j0] = 8;\n ++count;\n }\n for (j = 1; j < width; j++) {\n if (data[pos] !== data[pos + 1]) {\n points[j0 + j] = data[pos] ? 4 : 8;\n ++count;\n }\n pos++;\n }\n if (data[pos] !== 0) {\n points[j0 + j] = 4;\n ++count;\n }\n if (count > POINT_TO_PROCESS_LIMIT) {\n return null;\n }\n\n // building outlines\n var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);\n var outlines = [];\n for (i = 0; count && i <= height; i++) {\n var p = i * width1;\n var end = p + width;\n while (p < end && !points[p]) {\n p++;\n }\n if (p === end) {\n continue;\n }\n var coords = [p % width1, i];\n\n var type = points[p], p0 = p, pp;\n do {\n var step = steps[type];\n do {\n p += step;\n } while (!points[p]);\n\n pp = points[p];\n if (pp !== 5 && pp !== 10) {\n // set new direction\n type = pp;\n // delete mark\n points[p] = 0;\n } else { // type is 5 or 10, ie, a crossing\n // set new direction\n type = pp & ((0x33 * type) >> 4);\n // set new type for \"future hit\"\n points[p] &= (type >> 2 | type << 2);\n }\n\n coords.push(p % width1);\n coords.push((p / width1) | 0);\n --count;\n } while (p0 !== p);\n outlines.push(coords);\n --i;\n }\n\n var drawOutline = function(c) {\n c.save();\n // the path shall be painted in [0..1]x[0..1] space\n c.scale(1 / width, -1 / height);\n c.translate(0, -height);\n c.beginPath();\n for (var i = 0, ii = outlines.length; i < ii; i++) {\n var o = outlines[i];\n c.moveTo(o[0], o[1]);\n for (var j = 2, jj = o.length; j < jj; j += 2) {\n c.lineTo(o[j], o[j+1]);\n }\n }\n c.fill();\n c.beginPath();\n c.restore();\n };\n\n return drawOutline;\n}\n\nvar CanvasExtraState = (function CanvasExtraStateClosure() {\n function CanvasExtraState(old) {\n // Are soft masks and alpha values shapes or opacities?\n this.alphaIsShape = false;\n this.fontSize = 0;\n this.fontSizeScale = 1;\n this.textMatrix = IDENTITY_MATRIX;\n this.textMatrixScale = 1;\n this.fontMatrix = FONT_IDENTITY_MATRIX;\n this.leading = 0;\n // Current point (in user coordinates)\n this.x = 0;\n this.y = 0;\n // Start of text line (in text coordinates)\n this.lineX = 0;\n this.lineY = 0;\n // Character and word spacing\n this.charSpacing = 0;\n this.wordSpacing = 0;\n this.textHScale = 1;\n this.textRenderingMode = TextRenderingMode.FILL;\n this.textRise = 0;\n // Default fore and background colors\n this.fillColor = '#000000';\n this.strokeColor = '#000000';\n this.patternFill = false;\n // Note: fill alpha applies to all non-stroking operations\n this.fillAlpha = 1;\n this.strokeAlpha = 1;\n this.lineWidth = 1;\n this.activeSMask = null; // nonclonable field (see the save method below)\n\n this.old = old;\n }\n\n CanvasExtraState.prototype = {\n clone: function CanvasExtraState_clone() {\n return Object.create(this);\n },\n setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {\n this.x = x;\n this.y = y;\n }\n };\n return CanvasExtraState;\n})();\n\nvar CanvasGraphics = (function CanvasGraphicsClosure() {\n // Defines the time the executeOperatorList is going to be executing\n // before it stops and shedules a continue of execution.\n var EXECUTION_TIME = 15;\n // Defines the number of steps before checking the execution time\n var EXECUTION_STEPS = 10;\n\n function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {\n this.ctx = canvasCtx;\n this.current = new CanvasExtraState();\n this.stateStack = [];\n this.pendingClip = null;\n this.pendingEOFill = false;\n this.res = null;\n this.xobjs = null;\n this.commonObjs = commonObjs;\n this.objs = objs;\n this.imageLayer = imageLayer;\n this.groupStack = [];\n this.processingType3 = null;\n // Patterns are painted relative to the initial page/form transform, see pdf\n // spec 8.7.2 NOTE 1.\n this.baseTransform = null;\n this.baseTransformStack = [];\n this.groupLevel = 0;\n this.smaskStack = [];\n this.smaskCounter = 0;\n this.tempSMask = null;\n this.cachedCanvases = new CachedCanvases();\n if (canvasCtx) {\n // NOTE: if mozCurrentTransform is polyfilled, then the current state of\n // the transformation must already be set in canvasCtx._transformMatrix.\n addContextCurrentTransform(canvasCtx);\n }\n this.cachedGetSinglePixelWidth = null;\n }\n\n function putBinaryImageData(ctx, imgData) {\n if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {\n ctx.putImageData(imgData, 0, 0);\n return;\n }\n\n // Put the image data to the canvas in chunks, rather than putting the\n // whole image at once. This saves JS memory, because the ImageData object\n // is smaller. It also possibly saves C++ memory within the implementation\n // of putImageData(). (E.g. in Firefox we make two short-lived copies of\n // the data passed to putImageData()). |n| shouldn't be too small, however,\n // because too many putImageData() calls will slow things down.\n //\n // Note: as written, if the last chunk is partial, the putImageData() call\n // will (conceptually) put pixels past the bounds of the canvas. But\n // that's ok; any such pixels are ignored.\n\n var height = imgData.height, width = imgData.width;\n var partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n var srcPos = 0, destPos;\n var src = imgData.data;\n var dest = chunkImgData.data;\n var i, j, thisChunkHeight, elemsInThisChunk;\n\n // There are multiple forms in which the pixel data can be passed, and\n // imgData.kind tells us which one this is.\n if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {\n // Grayscale, 1 bit per pixel (i.e. black-and-white).\n var srcLength = src.byteLength;\n var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :\n new Uint32ArrayView(dest);\n var dest32DataLength = dest32.length;\n var fullSrcDiff = (width + 7) >> 3;\n var white = 0xFFFFFFFF;\n var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?\n 0xFF000000 : 0x000000FF;\n for (i = 0; i < totalChunks; i++) {\n thisChunkHeight =\n (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n destPos = 0;\n for (j = 0; j < thisChunkHeight; j++) {\n var srcDiff = srcLength - srcPos;\n var k = 0;\n var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;\n var kEndUnrolled = kEnd & ~7;\n var mask = 0;\n var srcByte = 0;\n for (; k < kEndUnrolled; k += 8) {\n srcByte = src[srcPos++];\n dest32[destPos++] = (srcByte & 128) ? white : black;\n dest32[destPos++] = (srcByte & 64) ? white : black;\n dest32[destPos++] = (srcByte & 32) ? white : black;\n dest32[destPos++] = (srcByte & 16) ? white : black;\n dest32[destPos++] = (srcByte & 8) ? white : black;\n dest32[destPos++] = (srcByte & 4) ? white : black;\n dest32[destPos++] = (srcByte & 2) ? white : black;\n dest32[destPos++] = (srcByte & 1) ? white : black;\n }\n for (; k < kEnd; k++) {\n if (mask === 0) {\n srcByte = src[srcPos++];\n mask = 128;\n }\n\n dest32[destPos++] = (srcByte & mask) ? white : black;\n mask >>= 1;\n }\n }\n // We ran out of input. Make all remaining pixels transparent.\n while (destPos < dest32DataLength) {\n dest32[destPos++] = 0;\n }\n\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else if (imgData.kind === ImageKind.RGBA_32BPP) {\n // RGBA, 32-bits per pixel.\n\n j = 0;\n elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;\n for (i = 0; i < fullChunks; i++) {\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n srcPos += elemsInThisChunk;\n\n ctx.putImageData(chunkImgData, 0, j);\n j += FULL_CHUNK_HEIGHT;\n }\n if (i < totalChunks) {\n elemsInThisChunk = width * partialChunkHeight * 4;\n dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));\n ctx.putImageData(chunkImgData, 0, j);\n }\n\n } else if (imgData.kind === ImageKind.RGB_24BPP) {\n // RGB, 24-bits per pixel.\n thisChunkHeight = FULL_CHUNK_HEIGHT;\n elemsInThisChunk = width * thisChunkHeight;\n for (i = 0; i < totalChunks; i++) {\n if (i >= fullChunks) {\n thisChunkHeight = partialChunkHeight;\n elemsInThisChunk = width * thisChunkHeight;\n }\n\n destPos = 0;\n for (j = elemsInThisChunk; j--;) {\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = src[srcPos++];\n dest[destPos++] = 255;\n }\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n } else {\n error('bad image kind: ' + imgData.kind);\n }\n }\n\n function putBinaryImageMask(ctx, imgData) {\n var height = imgData.height, width = imgData.width;\n var partialChunkHeight = height % FULL_CHUNK_HEIGHT;\n var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;\n var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;\n\n var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);\n var srcPos = 0;\n var src = imgData.data;\n var dest = chunkImgData.data;\n\n for (var i = 0; i < totalChunks; i++) {\n var thisChunkHeight =\n (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;\n\n // Expand the mask so it can be used by the canvas. Any required\n // inversion has already been handled.\n var destPos = 3; // alpha component offset\n for (var j = 0; j < thisChunkHeight; j++) {\n var mask = 0;\n for (var k = 0; k < width; k++) {\n if (!mask) {\n var elem = src[srcPos++];\n mask = 128;\n }\n dest[destPos] = (elem & mask) ? 0 : 255;\n destPos += 4;\n mask >>= 1;\n }\n }\n ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);\n }\n }\n\n function copyCtxState(sourceCtx, destCtx) {\n var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',\n 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',\n 'globalCompositeOperation', 'font'];\n for (var i = 0, ii = properties.length; i < ii; i++) {\n var property = properties[i];\n if (sourceCtx[property] !== undefined) {\n destCtx[property] = sourceCtx[property];\n }\n }\n if (sourceCtx.setLineDash !== undefined) {\n destCtx.setLineDash(sourceCtx.getLineDash());\n destCtx.lineDashOffset = sourceCtx.lineDashOffset;\n } else if (sourceCtx.mozDashOffset !== undefined) {\n destCtx.mozDash = sourceCtx.mozDash;\n destCtx.mozDashOffset = sourceCtx.mozDashOffset;\n }\n }\n\n function composeSMaskBackdrop(bytes, r0, g0, b0) {\n var length = bytes.length;\n for (var i = 3; i < length; i += 4) {\n var alpha = bytes[i];\n if (alpha === 0) {\n bytes[i - 3] = r0;\n bytes[i - 2] = g0;\n bytes[i - 1] = b0;\n } else if (alpha < 255) {\n var alpha_ = 255 - alpha;\n bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;\n bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;\n bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;\n }\n }\n }\n\n function composeSMaskAlpha(maskData, layerData, transferMap) {\n var length = maskData.length;\n var scale = 1 / 255;\n for (var i = 3; i < length; i += 4) {\n var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];\n layerData[i] = (layerData[i] * alpha * scale) | 0;\n }\n }\n\n function composeSMaskLuminosity(maskData, layerData, transferMap) {\n var length = maskData.length;\n for (var i = 3; i < length; i += 4) {\n var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000\n (maskData[i - 2] * 152) + // * 0.59 ....\n (maskData[i - 1] * 28); // * 0.11 ....\n layerData[i] = transferMap ?\n (layerData[i] * transferMap[y >> 8]) >> 8 :\n (layerData[i] * y) >> 16;\n }\n }\n\n function genericComposeSMask(maskCtx, layerCtx, width, height,\n subtype, backdrop, transferMap) {\n var hasBackdrop = !!backdrop;\n var r0 = hasBackdrop ? backdrop[0] : 0;\n var g0 = hasBackdrop ? backdrop[1] : 0;\n var b0 = hasBackdrop ? backdrop[2] : 0;\n\n var composeFn;\n if (subtype === 'Luminosity') {\n composeFn = composeSMaskLuminosity;\n } else {\n composeFn = composeSMaskAlpha;\n }\n\n // processing image in chunks to save memory\n var PIXELS_TO_PROCESS = 1048576;\n var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));\n for (var row = 0; row < height; row += chunkSize) {\n var chunkHeight = Math.min(chunkSize, height - row);\n var maskData = maskCtx.getImageData(0, row, width, chunkHeight);\n var layerData = layerCtx.getImageData(0, row, width, chunkHeight);\n\n if (hasBackdrop) {\n composeSMaskBackdrop(maskData.data, r0, g0, b0);\n }\n composeFn(maskData.data, layerData.data, transferMap);\n\n maskCtx.putImageData(layerData, 0, row);\n }\n }\n\n function composeSMask(ctx, smask, layerCtx) {\n var mask = smask.canvas;\n var maskCtx = smask.context;\n\n ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,\n smask.offsetX, smask.offsetY);\n\n var backdrop = smask.backdrop || null;\n if (!smask.transferMap && WebGLUtils.isEnabled) {\n var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,\n {subtype: smask.subtype, backdrop: backdrop});\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.drawImage(composed, smask.offsetX, smask.offsetY);\n return;\n }\n genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,\n smask.subtype, backdrop, smask.transferMap);\n ctx.drawImage(mask, 0, 0);\n }\n\n var LINE_CAP_STYLES = ['butt', 'round', 'square'];\n var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];\n var NORMAL_CLIP = {};\n var EO_CLIP = {};\n\n CanvasGraphics.prototype = {\n\n beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,\n transparency) {\n // For pdfs that use blend modes we have to clear the canvas else certain\n // blend modes can look wrong since we'd be blending with a white\n // backdrop. The problem with a transparent backdrop though is we then\n // don't get sub pixel anti aliasing on text, creating temporary\n // transparent canvas when we have blend modes.\n var width = this.ctx.canvas.width;\n var height = this.ctx.canvas.height;\n\n this.ctx.save();\n this.ctx.fillStyle = 'rgb(255, 255, 255)';\n this.ctx.fillRect(0, 0, width, height);\n this.ctx.restore();\n\n if (transparency) {\n var transparentCanvas = this.cachedCanvases.getCanvas(\n 'transparent', width, height, true);\n this.compositeCtx = this.ctx;\n this.transparentCanvas = transparentCanvas.canvas;\n this.ctx = transparentCanvas.context;\n this.ctx.save();\n // The transform can be applied before rendering, transferring it to\n // the new canvas.\n this.ctx.transform.apply(this.ctx,\n this.compositeCtx.mozCurrentTransform);\n }\n\n this.ctx.save();\n if (transform) {\n this.ctx.transform.apply(this.ctx, transform);\n }\n this.ctx.transform.apply(this.ctx, viewport.transform);\n\n this.baseTransform = this.ctx.mozCurrentTransform.slice();\n\n if (this.imageLayer) {\n this.imageLayer.beginLayout();\n }\n },\n\n executeOperatorList: function CanvasGraphics_executeOperatorList(\n operatorList,\n executionStartIdx, continueCallback,\n stepper) {\n var argsArray = operatorList.argsArray;\n var fnArray = operatorList.fnArray;\n var i = executionStartIdx || 0;\n var argsArrayLen = argsArray.length;\n\n // Sometimes the OperatorList to execute is empty.\n if (argsArrayLen === i) {\n return i;\n }\n\n var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&\n typeof continueCallback === 'function');\n var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;\n var steps = 0;\n\n var commonObjs = this.commonObjs;\n var objs = this.objs;\n var fnId;\n\n while (true) {\n if (stepper !== undefined && i === stepper.nextBreakPoint) {\n stepper.breakIt(i, continueCallback);\n return i;\n }\n\n fnId = fnArray[i];\n\n if (fnId !== OPS.dependency) {\n this[fnId].apply(this, argsArray[i]);\n } else {\n var deps = argsArray[i];\n for (var n = 0, nn = deps.length; n < nn; n++) {\n var depObjId = deps[n];\n var common = depObjId[0] === 'g' && depObjId[1] === '_';\n var objsPool = common ? commonObjs : objs;\n\n // If the promise isn't resolved yet, add the continueCallback\n // to the promise and bail out.\n if (!objsPool.isResolved(depObjId)) {\n objsPool.get(depObjId, continueCallback);\n return i;\n }\n }\n }\n\n i++;\n\n // If the entire operatorList was executed, stop as were done.\n if (i === argsArrayLen) {\n return i;\n }\n\n // If the execution took longer then a certain amount of time and\n // `continueCallback` is specified, interrupt the execution.\n if (chunkOperations && ++steps > EXECUTION_STEPS) {\n if (Date.now() > endTime) {\n continueCallback();\n return i;\n }\n steps = 0;\n }\n\n // If the operatorList isn't executed completely yet OR the execution\n // time was short enough, do another execution round.\n }\n },\n\n endDrawing: function CanvasGraphics_endDrawing() {\n this.ctx.restore();\n\n if (this.transparentCanvas) {\n this.ctx = this.compositeCtx;\n this.ctx.drawImage(this.transparentCanvas, 0, 0);\n this.transparentCanvas = null;\n }\n\n this.cachedCanvases.clear();\n WebGLUtils.clear();\n\n if (this.imageLayer) {\n this.imageLayer.endLayout();\n }\n },\n\n // Graphics state\n setLineWidth: function CanvasGraphics_setLineWidth(width) {\n this.current.lineWidth = width;\n this.ctx.lineWidth = width;\n },\n setLineCap: function CanvasGraphics_setLineCap(style) {\n this.ctx.lineCap = LINE_CAP_STYLES[style];\n },\n setLineJoin: function CanvasGraphics_setLineJoin(style) {\n this.ctx.lineJoin = LINE_JOIN_STYLES[style];\n },\n setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {\n this.ctx.miterLimit = limit;\n },\n setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {\n var ctx = this.ctx;\n if (ctx.setLineDash !== undefined) {\n ctx.setLineDash(dashArray);\n ctx.lineDashOffset = dashPhase;\n } else {\n ctx.mozDash = dashArray;\n ctx.mozDashOffset = dashPhase;\n }\n },\n setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {\n // Maybe if we one day fully support color spaces this will be important\n // for now we can ignore.\n // TODO set rendering intent?\n },\n setFlatness: function CanvasGraphics_setFlatness(flatness) {\n // There's no way to control this with canvas, but we can safely ignore.\n // TODO set flatness?\n },\n setGState: function CanvasGraphics_setGState(states) {\n for (var i = 0, ii = states.length; i < ii; i++) {\n var state = states[i];\n var key = state[0];\n var value = state[1];\n\n switch (key) {\n case 'LW':\n this.setLineWidth(value);\n break;\n case 'LC':\n this.setLineCap(value);\n break;\n case 'LJ':\n this.setLineJoin(value);\n break;\n case 'ML':\n this.setMiterLimit(value);\n break;\n case 'D':\n this.setDash(value[0], value[1]);\n break;\n case 'RI':\n this.setRenderingIntent(value);\n break;\n case 'FL':\n this.setFlatness(value);\n break;\n case 'Font':\n this.setFont(value[0], value[1]);\n break;\n case 'CA':\n this.current.strokeAlpha = state[1];\n break;\n case 'ca':\n this.current.fillAlpha = state[1];\n this.ctx.globalAlpha = state[1];\n break;\n case 'BM':\n if (value && value.name && (value.name !== 'Normal')) {\n var mode = value.name.replace(/([A-Z])/g,\n function(c) {\n return '-' + c.toLowerCase();\n }\n ).substring(1);\n this.ctx.globalCompositeOperation = mode;\n if (this.ctx.globalCompositeOperation !== mode) {\n warn('globalCompositeOperation \"' + mode +\n '\" is not supported');\n }\n } else {\n this.ctx.globalCompositeOperation = 'source-over';\n }\n break;\n case 'SMask':\n if (this.current.activeSMask) {\n this.endSMaskGroup();\n }\n this.current.activeSMask = value ? this.tempSMask : null;\n if (this.current.activeSMask) {\n this.beginSMaskGroup();\n }\n this.tempSMask = null;\n break;\n }\n }\n },\n beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {\n\n var activeSMask = this.current.activeSMask;\n var drawnWidth = activeSMask.canvas.width;\n var drawnHeight = activeSMask.canvas.height;\n var cacheId = 'smaskGroupAt' + this.groupLevel;\n var scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId, drawnWidth, drawnHeight, true);\n\n var currentCtx = this.ctx;\n var currentTransform = currentCtx.mozCurrentTransform;\n this.ctx.save();\n\n var groupCtx = scratchCanvas.context;\n groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);\n groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);\n groupCtx.transform.apply(groupCtx, currentTransform);\n\n copyCtxState(currentCtx, groupCtx);\n this.ctx = groupCtx;\n this.setGState([\n ['BM', 'Normal'],\n ['ca', 1],\n ['CA', 1]\n ]);\n this.groupStack.push(currentCtx);\n this.groupLevel++;\n },\n endSMaskGroup: function CanvasGraphics_endSMaskGroup() {\n var groupCtx = this.ctx;\n this.groupLevel--;\n this.ctx = this.groupStack.pop();\n\n composeSMask(this.ctx, this.current.activeSMask, groupCtx);\n this.ctx.restore();\n copyCtxState(groupCtx, this.ctx);\n },\n save: function CanvasGraphics_save() {\n this.ctx.save();\n var old = this.current;\n this.stateStack.push(old);\n this.current = old.clone();\n this.current.activeSMask = null;\n },\n restore: function CanvasGraphics_restore() {\n if (this.stateStack.length !== 0) {\n if (this.current.activeSMask !== null) {\n this.endSMaskGroup();\n }\n\n this.current = this.stateStack.pop();\n this.ctx.restore();\n\n // Ensure that the clipping path is reset (fixes issue6413.pdf).\n this.pendingClip = null;\n\n this.cachedGetSinglePixelWidth = null;\n }\n },\n transform: function CanvasGraphics_transform(a, b, c, d, e, f) {\n this.ctx.transform(a, b, c, d, e, f);\n\n this.cachedGetSinglePixelWidth = null;\n },\n\n // Path\n constructPath: function CanvasGraphics_constructPath(ops, args) {\n var ctx = this.ctx;\n var current = this.current;\n var x = current.x, y = current.y;\n for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {\n switch (ops[i] | 0) {\n case OPS.rectangle:\n x = args[j++];\n y = args[j++];\n var width = args[j++];\n var height = args[j++];\n if (width === 0) {\n width = this.getSinglePixelWidth();\n }\n if (height === 0) {\n height = this.getSinglePixelWidth();\n }\n var xw = x + width;\n var yh = y + height;\n this.ctx.moveTo(x, y);\n this.ctx.lineTo(xw, y);\n this.ctx.lineTo(xw, yh);\n this.ctx.lineTo(x, yh);\n this.ctx.lineTo(x, y);\n this.ctx.closePath();\n break;\n case OPS.moveTo:\n x = args[j++];\n y = args[j++];\n ctx.moveTo(x, y);\n break;\n case OPS.lineTo:\n x = args[j++];\n y = args[j++];\n ctx.lineTo(x, y);\n break;\n case OPS.curveTo:\n x = args[j + 4];\n y = args[j + 5];\n ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],\n x, y);\n j += 6;\n break;\n case OPS.curveTo2:\n ctx.bezierCurveTo(x, y, args[j], args[j + 1],\n args[j + 2], args[j + 3]);\n x = args[j + 2];\n y = args[j + 3];\n j += 4;\n break;\n case OPS.curveTo3:\n x = args[j + 2];\n y = args[j + 3];\n ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);\n j += 4;\n break;\n case OPS.closePath:\n ctx.closePath();\n break;\n }\n }\n current.setCurrentPoint(x, y);\n },\n closePath: function CanvasGraphics_closePath() {\n this.ctx.closePath();\n },\n stroke: function CanvasGraphics_stroke(consumePath) {\n consumePath = typeof consumePath !== 'undefined' ? consumePath : true;\n var ctx = this.ctx;\n var strokeColor = this.current.strokeColor;\n // Prevent drawing too thin lines by enforcing a minimum line width.\n ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,\n this.current.lineWidth);\n // For stroke we want to temporarily change the global alpha to the\n // stroking alpha.\n ctx.globalAlpha = this.current.strokeAlpha;\n if (strokeColor && strokeColor.hasOwnProperty('type') &&\n strokeColor.type === 'Pattern') {\n // for patterns, we transform to pattern space, calculate\n // the pattern, call stroke, and restore to user space\n ctx.save();\n ctx.strokeStyle = strokeColor.getPattern(ctx, this);\n ctx.stroke();\n ctx.restore();\n } else {\n ctx.stroke();\n }\n if (consumePath) {\n this.consumePath();\n }\n // Restore the global alpha to the fill alpha\n ctx.globalAlpha = this.current.fillAlpha;\n },\n closeStroke: function CanvasGraphics_closeStroke() {\n this.closePath();\n this.stroke();\n },\n fill: function CanvasGraphics_fill(consumePath) {\n consumePath = typeof consumePath !== 'undefined' ? consumePath : true;\n var ctx = this.ctx;\n var fillColor = this.current.fillColor;\n var isPatternFill = this.current.patternFill;\n var needRestore = false;\n\n if (isPatternFill) {\n ctx.save();\n if (this.baseTransform) {\n ctx.setTransform.apply(ctx, this.baseTransform);\n }\n ctx.fillStyle = fillColor.getPattern(ctx, this);\n needRestore = true;\n }\n\n if (this.pendingEOFill) {\n if (ctx.mozFillRule !== undefined) {\n ctx.mozFillRule = 'evenodd';\n ctx.fill();\n ctx.mozFillRule = 'nonzero';\n } else {\n ctx.fill('evenodd');\n }\n this.pendingEOFill = false;\n } else {\n ctx.fill();\n }\n\n if (needRestore) {\n ctx.restore();\n }\n if (consumePath) {\n this.consumePath();\n }\n },\n eoFill: function CanvasGraphics_eoFill() {\n this.pendingEOFill = true;\n this.fill();\n },\n fillStroke: function CanvasGraphics_fillStroke() {\n this.fill(false);\n this.stroke(false);\n\n this.consumePath();\n },\n eoFillStroke: function CanvasGraphics_eoFillStroke() {\n this.pendingEOFill = true;\n this.fillStroke();\n },\n closeFillStroke: function CanvasGraphics_closeFillStroke() {\n this.closePath();\n this.fillStroke();\n },\n closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {\n this.pendingEOFill = true;\n this.closePath();\n this.fillStroke();\n },\n endPath: function CanvasGraphics_endPath() {\n this.consumePath();\n },\n\n // Clipping\n clip: function CanvasGraphics_clip() {\n this.pendingClip = NORMAL_CLIP;\n },\n eoClip: function CanvasGraphics_eoClip() {\n this.pendingClip = EO_CLIP;\n },\n\n // Text\n beginText: function CanvasGraphics_beginText() {\n this.current.textMatrix = IDENTITY_MATRIX;\n this.current.textMatrixScale = 1;\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n },\n endText: function CanvasGraphics_endText() {\n var paths = this.pendingTextPaths;\n var ctx = this.ctx;\n if (paths === undefined) {\n ctx.beginPath();\n return;\n }\n\n ctx.save();\n ctx.beginPath();\n for (var i = 0; i < paths.length; i++) {\n var path = paths[i];\n ctx.setTransform.apply(ctx, path.transform);\n ctx.translate(path.x, path.y);\n path.addToPath(ctx, path.fontSize);\n }\n ctx.restore();\n ctx.clip();\n ctx.beginPath();\n delete this.pendingTextPaths;\n },\n setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {\n this.current.charSpacing = spacing;\n },\n setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {\n this.current.wordSpacing = spacing;\n },\n setHScale: function CanvasGraphics_setHScale(scale) {\n this.current.textHScale = scale / 100;\n },\n setLeading: function CanvasGraphics_setLeading(leading) {\n this.current.leading = -leading;\n },\n setFont: function CanvasGraphics_setFont(fontRefName, size) {\n var fontObj = this.commonObjs.get(fontRefName);\n var current = this.current;\n\n if (!fontObj) {\n error('Can\\'t find font for ' + fontRefName);\n }\n\n current.fontMatrix = (fontObj.fontMatrix ?\n fontObj.fontMatrix : FONT_IDENTITY_MATRIX);\n\n // A valid matrix needs all main diagonal elements to be non-zero\n // This also ensures we bypass FF bugzilla bug #719844.\n if (current.fontMatrix[0] === 0 ||\n current.fontMatrix[3] === 0) {\n warn('Invalid font matrix for font ' + fontRefName);\n }\n\n // The spec for Tf (setFont) says that 'size' specifies the font 'scale',\n // and in some docs this can be negative (inverted x-y axes).\n if (size < 0) {\n size = -size;\n current.fontDirection = -1;\n } else {\n current.fontDirection = 1;\n }\n\n this.current.font = fontObj;\n this.current.fontSize = size;\n\n if (fontObj.isType3Font) {\n return; // we don't need ctx.font for Type3 fonts\n }\n\n var name = fontObj.loadedName || 'sans-serif';\n var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :\n (fontObj.bold ? 'bold' : 'normal');\n\n var italic = fontObj.italic ? 'italic' : 'normal';\n var typeface = '\"' + name + '\", ' + fontObj.fallbackName;\n\n // Some font backends cannot handle fonts below certain size.\n // Keeping the font at minimal size and using the fontSizeScale to change\n // the current transformation matrix before the fillText/strokeText.\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227\n var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :\n size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;\n this.current.fontSizeScale = size / browserFontSize;\n\n var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;\n this.ctx.font = rule;\n },\n setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {\n this.current.textRenderingMode = mode;\n },\n setTextRise: function CanvasGraphics_setTextRise(rise) {\n this.current.textRise = rise;\n },\n moveText: function CanvasGraphics_moveText(x, y) {\n this.current.x = this.current.lineX += x;\n this.current.y = this.current.lineY += y;\n },\n setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {\n this.setLeading(-y);\n this.moveText(x, y);\n },\n setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {\n this.current.textMatrix = [a, b, c, d, e, f];\n this.current.textMatrixScale = Math.sqrt(a * a + b * b);\n\n this.current.x = this.current.lineX = 0;\n this.current.y = this.current.lineY = 0;\n },\n nextLine: function CanvasGraphics_nextLine() {\n this.moveText(0, this.current.leading);\n },\n\n paintChar: function CanvasGraphics_paintChar(character, x, y) {\n var ctx = this.ctx;\n var current = this.current;\n var font = current.font;\n var textRenderingMode = current.textRenderingMode;\n var fontSize = current.fontSize / current.fontSizeScale;\n var fillStrokeMode = textRenderingMode &\n TextRenderingMode.FILL_STROKE_MASK;\n var isAddToPathSet = !!(textRenderingMode &\n TextRenderingMode.ADD_TO_PATH_FLAG);\n\n var addToPath;\n if (font.disableFontFace || isAddToPathSet) {\n addToPath = font.getPathGenerator(this.commonObjs, character);\n }\n\n if (font.disableFontFace) {\n ctx.save();\n ctx.translate(x, y);\n ctx.beginPath();\n addToPath(ctx, fontSize);\n if (fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n ctx.fill();\n }\n if (fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n ctx.stroke();\n }\n ctx.restore();\n } else {\n if (fillStrokeMode === TextRenderingMode.FILL ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n ctx.fillText(character, x, y);\n }\n if (fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n ctx.strokeText(character, x, y);\n }\n }\n\n if (isAddToPathSet) {\n var paths = this.pendingTextPaths || (this.pendingTextPaths = []);\n paths.push({\n transform: ctx.mozCurrentTransform,\n x: x,\n y: y,\n fontSize: fontSize,\n addToPath: addToPath\n });\n }\n },\n\n get isFontSubpixelAAEnabled() {\n // Checks if anti-aliasing is enabled when scaled text is painted.\n // On Windows GDI scaled fonts looks bad.\n var ctx = document.createElement('canvas').getContext('2d');\n ctx.scale(1.5, 1);\n ctx.fillText('I', 0, 10);\n var data = ctx.getImageData(0, 0, 10, 10).data;\n var enabled = false;\n for (var i = 3; i < data.length; i += 4) {\n if (data[i] > 0 && data[i] < 255) {\n enabled = true;\n break;\n }\n }\n return shadow(this, 'isFontSubpixelAAEnabled', enabled);\n },\n\n showText: function CanvasGraphics_showText(glyphs) {\n var current = this.current;\n var font = current.font;\n if (font.isType3Font) {\n return this.showType3Text(glyphs);\n }\n\n var fontSize = current.fontSize;\n if (fontSize === 0) {\n return;\n }\n\n var ctx = this.ctx;\n var fontSizeScale = current.fontSizeScale;\n var charSpacing = current.charSpacing;\n var wordSpacing = current.wordSpacing;\n var fontDirection = current.fontDirection;\n var textHScale = current.textHScale * fontDirection;\n var glyphsLength = glyphs.length;\n var vertical = font.vertical;\n var spacingDir = vertical ? 1 : -1;\n var defaultVMetrics = font.defaultVMetrics;\n var widthAdvanceScale = fontSize * current.fontMatrix[0];\n\n var simpleFillText =\n current.textRenderingMode === TextRenderingMode.FILL &&\n !font.disableFontFace;\n\n ctx.save();\n ctx.transform.apply(ctx, current.textMatrix);\n ctx.translate(current.x, current.y + current.textRise);\n\n if (current.patternFill) {\n // TODO: Some shading patterns are not applied correctly to text,\n // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.\n ctx.fillStyle = current.fillColor.getPattern(ctx, this);\n }\n\n if (fontDirection > 0) {\n ctx.scale(textHScale, -1);\n } else {\n ctx.scale(textHScale, 1);\n }\n\n var lineWidth = current.lineWidth;\n var scale = current.textMatrixScale;\n if (scale === 0 || lineWidth === 0) {\n var fillStrokeMode = current.textRenderingMode &\n TextRenderingMode.FILL_STROKE_MASK;\n if (fillStrokeMode === TextRenderingMode.STROKE ||\n fillStrokeMode === TextRenderingMode.FILL_STROKE) {\n this.cachedGetSinglePixelWidth = null;\n lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;\n }\n } else {\n lineWidth /= scale;\n }\n\n if (fontSizeScale !== 1.0) {\n ctx.scale(fontSizeScale, fontSizeScale);\n lineWidth /= fontSizeScale;\n }\n\n ctx.lineWidth = lineWidth;\n\n var x = 0, i;\n for (i = 0; i < glyphsLength; ++i) {\n var glyph = glyphs[i];\n if (isNum(glyph)) {\n x += spacingDir * glyph * fontSize / 1000;\n continue;\n }\n\n var restoreNeeded = false;\n var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n var character = glyph.fontChar;\n var accent = glyph.accent;\n var scaledX, scaledY, scaledAccentX, scaledAccentY;\n var width = glyph.width;\n if (vertical) {\n var vmetric, vx, vy;\n vmetric = glyph.vmetric || defaultVMetrics;\n vx = glyph.vmetric ? vmetric[1] : width * 0.5;\n vx = -vx * widthAdvanceScale;\n vy = vmetric[2] * widthAdvanceScale;\n\n width = vmetric ? -vmetric[0] : width;\n scaledX = vx / fontSizeScale;\n scaledY = (x + vy) / fontSizeScale;\n } else {\n scaledX = x / fontSizeScale;\n scaledY = 0;\n }\n\n if (font.remeasure && width > 0) {\n // Some standard fonts may not have the exact width: rescale per\n // character if measured width is greater than expected glyph width\n // and subpixel-aa is enabled, otherwise just center the glyph.\n var measuredWidth = ctx.measureText(character).width * 1000 /\n fontSize * fontSizeScale;\n if (width < measuredWidth && this.isFontSubpixelAAEnabled) {\n var characterScaleX = width / measuredWidth;\n restoreNeeded = true;\n ctx.save();\n ctx.scale(characterScaleX, 1);\n scaledX /= characterScaleX;\n } else if (width !== measuredWidth) {\n scaledX += (width - measuredWidth) / 2000 *\n fontSize / fontSizeScale;\n }\n }\n\n if (simpleFillText && !accent) {\n // common case\n ctx.fillText(character, scaledX, scaledY);\n } else {\n this.paintChar(character, scaledX, scaledY);\n if (accent) {\n scaledAccentX = scaledX + accent.offset.x / fontSizeScale;\n scaledAccentY = scaledY - accent.offset.y / fontSizeScale;\n this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);\n }\n }\n\n var charWidth = width * widthAdvanceScale + spacing * fontDirection;\n x += charWidth;\n\n if (restoreNeeded) {\n ctx.restore();\n }\n }\n if (vertical) {\n current.y -= x * textHScale;\n } else {\n current.x += x * textHScale;\n }\n ctx.restore();\n },\n\n showType3Text: function CanvasGraphics_showType3Text(glyphs) {\n // Type3 fonts - each glyph is a \"mini-PDF\"\n var ctx = this.ctx;\n var current = this.current;\n var font = current.font;\n var fontSize = current.fontSize;\n var fontDirection = current.fontDirection;\n var spacingDir = font.vertical ? 1 : -1;\n var charSpacing = current.charSpacing;\n var wordSpacing = current.wordSpacing;\n var textHScale = current.textHScale * fontDirection;\n var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;\n var glyphsLength = glyphs.length;\n var isTextInvisible =\n current.textRenderingMode === TextRenderingMode.INVISIBLE;\n var i, glyph, width, spacingLength;\n\n if (isTextInvisible || fontSize === 0) {\n return;\n }\n this.cachedGetSinglePixelWidth = null;\n\n ctx.save();\n ctx.transform.apply(ctx, current.textMatrix);\n ctx.translate(current.x, current.y);\n\n ctx.scale(textHScale, fontDirection);\n\n for (i = 0; i < glyphsLength; ++i) {\n glyph = glyphs[i];\n if (isNum(glyph)) {\n spacingLength = spacingDir * glyph * fontSize / 1000;\n this.ctx.translate(spacingLength, 0);\n current.x += spacingLength * textHScale;\n continue;\n }\n\n var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;\n var operatorList = font.charProcOperatorList[glyph.operatorListId];\n if (!operatorList) {\n warn('Type3 character \\\"' + glyph.operatorListId +\n '\\\" is not available');\n continue;\n }\n this.processingType3 = glyph;\n this.save();\n ctx.scale(fontSize, fontSize);\n ctx.transform.apply(ctx, fontMatrix);\n this.executeOperatorList(operatorList);\n this.restore();\n\n var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);\n width = transformed[0] * fontSize + spacing;\n\n ctx.translate(width, 0);\n current.x += width * textHScale;\n }\n ctx.restore();\n this.processingType3 = null;\n },\n\n // Type3 fonts\n setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {\n // We can safely ignore this since the width should be the same\n // as the width in the Widths array.\n },\n setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,\n yWidth,\n llx,\n lly,\n urx,\n ury) {\n // TODO According to the spec we're also suppose to ignore any operators\n // that set color or include images while processing this type3 font.\n this.ctx.rect(llx, lly, urx - llx, ury - lly);\n this.clip();\n this.endPath();\n },\n\n // Color\n getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {\n var pattern;\n if (IR[0] === 'TilingPattern') {\n var color = IR[1];\n var baseTransform = this.baseTransform ||\n this.ctx.mozCurrentTransform.slice();\n var self = this;\n var canvasGraphicsFactory = {\n createCanvasGraphics: function (ctx) {\n return new CanvasGraphics(ctx, self.commonObjs, self.objs);\n }\n };\n pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,\n baseTransform);\n } else {\n pattern = getShadingPatternFromIR(IR);\n }\n return pattern;\n },\n setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {\n this.current.strokeColor = this.getColorN_Pattern(arguments);\n },\n setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {\n this.current.fillColor = this.getColorN_Pattern(arguments);\n this.current.patternFill = true;\n },\n setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {\n var color = Util.makeCssRgb(r, g, b);\n this.ctx.strokeStyle = color;\n this.current.strokeColor = color;\n },\n setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {\n var color = Util.makeCssRgb(r, g, b);\n this.ctx.fillStyle = color;\n this.current.fillColor = color;\n this.current.patternFill = false;\n },\n\n shadingFill: function CanvasGraphics_shadingFill(patternIR) {\n var ctx = this.ctx;\n\n this.save();\n var pattern = getShadingPatternFromIR(patternIR);\n ctx.fillStyle = pattern.getPattern(ctx, this, true);\n\n var inv = ctx.mozCurrentTransformInverse;\n if (inv) {\n var canvas = ctx.canvas;\n var width = canvas.width;\n var height = canvas.height;\n\n var bl = Util.applyTransform([0, 0], inv);\n var br = Util.applyTransform([0, height], inv);\n var ul = Util.applyTransform([width, 0], inv);\n var ur = Util.applyTransform([width, height], inv);\n\n var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);\n var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);\n var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);\n var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);\n\n this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);\n } else {\n // HACK to draw the gradient onto an infinite rectangle.\n // PDF gradients are drawn across the entire image while\n // Canvas only allows gradients to be drawn in a rectangle\n // The following bug should allow us to remove this.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=664884\n\n this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);\n }\n\n this.restore();\n },\n\n // Images\n beginInlineImage: function CanvasGraphics_beginInlineImage() {\n error('Should not call beginInlineImage');\n },\n beginImageData: function CanvasGraphics_beginImageData() {\n error('Should not call beginImageData');\n },\n\n paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,\n bbox) {\n this.save();\n this.baseTransformStack.push(this.baseTransform);\n\n if (isArray(matrix) && 6 === matrix.length) {\n this.transform.apply(this, matrix);\n }\n\n this.baseTransform = this.ctx.mozCurrentTransform;\n\n if (isArray(bbox) && 4 === bbox.length) {\n var width = bbox[2] - bbox[0];\n var height = bbox[3] - bbox[1];\n this.ctx.rect(bbox[0], bbox[1], width, height);\n this.clip();\n this.endPath();\n }\n },\n\n paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {\n this.restore();\n this.baseTransform = this.baseTransformStack.pop();\n },\n\n beginGroup: function CanvasGraphics_beginGroup(group) {\n this.save();\n var currentCtx = this.ctx;\n // TODO non-isolated groups - according to Rik at adobe non-isolated\n // group results aren't usually that different and they even have tools\n // that ignore this setting. Notes from Rik on implmenting:\n // - When you encounter an transparency group, create a new canvas with\n // the dimensions of the bbox\n // - copy the content from the previous canvas to the new canvas\n // - draw as usual\n // - remove the backdrop alpha:\n // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha\n // value of your transparency group and 'alphaBackdrop' the alpha of the\n // backdrop\n // - remove background color:\n // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)\n if (!group.isolated) {\n info('TODO: Support non-isolated groups.');\n }\n\n // TODO knockout - supposedly possible with the clever use of compositing\n // modes.\n if (group.knockout) {\n warn('Knockout groups not supported.');\n }\n\n var currentTransform = currentCtx.mozCurrentTransform;\n if (group.matrix) {\n currentCtx.transform.apply(currentCtx, group.matrix);\n }\n assert(group.bbox, 'Bounding box is required.');\n\n // Based on the current transform figure out how big the bounding box\n // will actually be.\n var bounds = Util.getAxialAlignedBoundingBox(\n group.bbox,\n currentCtx.mozCurrentTransform);\n // Clip the bounding box to the current canvas.\n var canvasBounds = [0,\n 0,\n currentCtx.canvas.width,\n currentCtx.canvas.height];\n bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];\n // Use ceil in case we're between sizes so we don't create canvas that is\n // too small and make the canvas at least 1x1 pixels.\n var offsetX = Math.floor(bounds[0]);\n var offsetY = Math.floor(bounds[1]);\n var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);\n var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);\n var scaleX = 1, scaleY = 1;\n if (drawnWidth > MAX_GROUP_SIZE) {\n scaleX = drawnWidth / MAX_GROUP_SIZE;\n drawnWidth = MAX_GROUP_SIZE;\n }\n if (drawnHeight > MAX_GROUP_SIZE) {\n scaleY = drawnHeight / MAX_GROUP_SIZE;\n drawnHeight = MAX_GROUP_SIZE;\n }\n\n var cacheId = 'groupAt' + this.groupLevel;\n if (group.smask) {\n // Using two cache entries is case if masks are used one after another.\n cacheId += '_smask_' + ((this.smaskCounter++) % 2);\n }\n var scratchCanvas = this.cachedCanvases.getCanvas(\n cacheId, drawnWidth, drawnHeight, true);\n var groupCtx = scratchCanvas.context;\n\n // Since we created a new canvas that is just the size of the bounding box\n // we have to translate the group ctx.\n groupCtx.scale(1 / scaleX, 1 / scaleY);\n groupCtx.translate(-offsetX, -offsetY);\n groupCtx.transform.apply(groupCtx, currentTransform);\n\n if (group.smask) {\n // Saving state and cached mask to be used in setGState.\n this.smaskStack.push({\n canvas: scratchCanvas.canvas,\n context: groupCtx,\n offsetX: offsetX,\n offsetY: offsetY,\n scaleX: scaleX,\n scaleY: scaleY,\n subtype: group.smask.subtype,\n backdrop: group.smask.backdrop,\n transferMap: group.smask.transferMap || null\n });\n } else {\n // Setup the current ctx so when the group is popped we draw it at the\n // right location.\n currentCtx.setTransform(1, 0, 0, 1, 0, 0);\n currentCtx.translate(offsetX, offsetY);\n currentCtx.scale(scaleX, scaleY);\n }\n // The transparency group inherits all off the current graphics state\n // except the blend mode, soft mask, and alpha constants.\n copyCtxState(currentCtx, groupCtx);\n this.ctx = groupCtx;\n this.setGState([\n ['BM', 'Normal'],\n ['ca', 1],\n ['CA', 1]\n ]);\n this.groupStack.push(currentCtx);\n this.groupLevel++;\n },\n\n endGroup: function CanvasGraphics_endGroup(group) {\n this.groupLevel--;\n var groupCtx = this.ctx;\n this.ctx = this.groupStack.pop();\n // Turn off image smoothing to avoid sub pixel interpolation which can\n // look kind of blurry for some pdfs.\n if (this.ctx.imageSmoothingEnabled !== undefined) {\n this.ctx.imageSmoothingEnabled = false;\n } else {\n this.ctx.mozImageSmoothingEnabled = false;\n }\n if (group.smask) {\n this.tempSMask = this.smaskStack.pop();\n } else {\n this.ctx.drawImage(groupCtx.canvas, 0, 0);\n }\n this.restore();\n },\n\n beginAnnotations: function CanvasGraphics_beginAnnotations() {\n this.save();\n this.current = new CanvasExtraState();\n\n if (this.baseTransform) {\n this.ctx.setTransform.apply(this.ctx, this.baseTransform);\n }\n },\n\n endAnnotations: function CanvasGraphics_endAnnotations() {\n this.restore();\n },\n\n beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,\n matrix) {\n this.save();\n\n if (isArray(rect) && 4 === rect.length) {\n var width = rect[2] - rect[0];\n var height = rect[3] - rect[1];\n this.ctx.rect(rect[0], rect[1], width, height);\n this.clip();\n this.endPath();\n }\n\n this.transform.apply(this, transform);\n this.transform.apply(this, matrix);\n },\n\n endAnnotation: function CanvasGraphics_endAnnotation() {\n this.restore();\n },\n\n paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {\n var domImage = this.objs.get(objId);\n if (!domImage) {\n warn('Dependent image isn\\'t ready yet');\n return;\n }\n\n this.save();\n\n var ctx = this.ctx;\n // scale the image to the unit square\n ctx.scale(1 / w, -1 / h);\n\n ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,\n 0, -h, w, h);\n if (this.imageLayer) {\n var currentTransform = ctx.mozCurrentTransformInverse;\n var position = this.getCanvasPosition(0, 0);\n this.imageLayer.appendImage({\n objId: objId,\n left: position[0],\n top: position[1],\n width: w / currentTransform[0],\n height: h / currentTransform[3]\n });\n }\n this.restore();\n },\n\n paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {\n var ctx = this.ctx;\n var width = img.width, height = img.height;\n var fillColor = this.current.fillColor;\n var isPatternFill = this.current.patternFill;\n\n var glyph = this.processingType3;\n\n if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {\n if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {\n glyph.compiled =\n compileType3Glyph({data: img.data, width: width, height: height});\n } else {\n glyph.compiled = null;\n }\n }\n\n if (glyph && glyph.compiled) {\n glyph.compiled(ctx);\n return;\n }\n\n var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',\n width, height);\n var maskCtx = maskCanvas.context;\n maskCtx.save();\n\n putBinaryImageMask(maskCtx, img);\n\n maskCtx.globalCompositeOperation = 'source-in';\n\n maskCtx.fillStyle = isPatternFill ?\n fillColor.getPattern(maskCtx, this) : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n\n maskCtx.restore();\n\n this.paintInlineImageXObject(maskCanvas.canvas);\n },\n\n paintImageMaskXObjectRepeat:\n function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,\n scaleY, positions) {\n var width = imgData.width;\n var height = imgData.height;\n var fillColor = this.current.fillColor;\n var isPatternFill = this.current.patternFill;\n\n var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',\n width, height);\n var maskCtx = maskCanvas.context;\n maskCtx.save();\n\n putBinaryImageMask(maskCtx, imgData);\n\n maskCtx.globalCompositeOperation = 'source-in';\n\n maskCtx.fillStyle = isPatternFill ?\n fillColor.getPattern(maskCtx, this) : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n\n maskCtx.restore();\n\n var ctx = this.ctx;\n for (var i = 0, ii = positions.length; i < ii; i += 2) {\n ctx.save();\n ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);\n ctx.scale(1, -1);\n ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,\n 0, -1, 1, 1);\n ctx.restore();\n }\n },\n\n paintImageMaskXObjectGroup:\n function CanvasGraphics_paintImageMaskXObjectGroup(images) {\n var ctx = this.ctx;\n\n var fillColor = this.current.fillColor;\n var isPatternFill = this.current.patternFill;\n for (var i = 0, ii = images.length; i < ii; i++) {\n var image = images[i];\n var width = image.width, height = image.height;\n\n var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',\n width, height);\n var maskCtx = maskCanvas.context;\n maskCtx.save();\n\n putBinaryImageMask(maskCtx, image);\n\n maskCtx.globalCompositeOperation = 'source-in';\n\n maskCtx.fillStyle = isPatternFill ?\n fillColor.getPattern(maskCtx, this) : fillColor;\n maskCtx.fillRect(0, 0, width, height);\n\n maskCtx.restore();\n\n ctx.save();\n ctx.transform.apply(ctx, image.transform);\n ctx.scale(1, -1);\n ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,\n 0, -1, 1, 1);\n ctx.restore();\n }\n },\n\n paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {\n var imgData = this.objs.get(objId);\n if (!imgData) {\n warn('Dependent image isn\\'t ready yet');\n return;\n }\n\n this.paintInlineImageXObject(imgData);\n },\n\n paintImageXObjectRepeat:\n function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,\n positions) {\n var imgData = this.objs.get(objId);\n if (!imgData) {\n warn('Dependent image isn\\'t ready yet');\n return;\n }\n\n var width = imgData.width;\n var height = imgData.height;\n var map = [];\n for (var i = 0, ii = positions.length; i < ii; i += 2) {\n map.push({transform: [scaleX, 0, 0, scaleY, positions[i],\n positions[i + 1]], x: 0, y: 0, w: width, h: height});\n }\n this.paintInlineImageXObjectGroup(imgData, map);\n },\n\n paintInlineImageXObject:\n function CanvasGraphics_paintInlineImageXObject(imgData) {\n var width = imgData.width;\n var height = imgData.height;\n var ctx = this.ctx;\n\n this.save();\n // scale the image to the unit square\n ctx.scale(1 / width, -1 / height);\n\n var currentTransform = ctx.mozCurrentTransformInverse;\n var a = currentTransform[0], b = currentTransform[1];\n var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);\n var c = currentTransform[2], d = currentTransform[3];\n var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);\n\n var imgToPaint, tmpCanvas;\n // instanceof HTMLElement does not work in jsdom node.js module\n if (imgData instanceof HTMLElement || !imgData.data) {\n imgToPaint = imgData;\n } else {\n tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',\n width, height);\n var tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n imgToPaint = tmpCanvas.canvas;\n }\n\n var paintWidth = width, paintHeight = height;\n var tmpCanvasId = 'prescale1';\n // Vertial or horizontal scaling shall not be more than 2 to not loose the\n // pixels during drawImage operation, painting on the temporary canvas(es)\n // that are twice smaller in size\n while ((widthScale > 2 && paintWidth > 1) ||\n (heightScale > 2 && paintHeight > 1)) {\n var newWidth = paintWidth, newHeight = paintHeight;\n if (widthScale > 2 && paintWidth > 1) {\n newWidth = Math.ceil(paintWidth / 2);\n widthScale /= paintWidth / newWidth;\n }\n if (heightScale > 2 && paintHeight > 1) {\n newHeight = Math.ceil(paintHeight / 2);\n heightScale /= paintHeight / newHeight;\n }\n tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,\n newWidth, newHeight);\n tmpCtx = tmpCanvas.context;\n tmpCtx.clearRect(0, 0, newWidth, newHeight);\n tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,\n 0, 0, newWidth, newHeight);\n imgToPaint = tmpCanvas.canvas;\n paintWidth = newWidth;\n paintHeight = newHeight;\n tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';\n }\n ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,\n 0, -height, width, height);\n\n if (this.imageLayer) {\n var position = this.getCanvasPosition(0, -height);\n this.imageLayer.appendImage({\n imgData: imgData,\n left: position[0],\n top: position[1],\n width: width / currentTransform[0],\n height: height / currentTransform[3]\n });\n }\n this.restore();\n },\n\n paintInlineImageXObjectGroup:\n function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {\n var ctx = this.ctx;\n var w = imgData.width;\n var h = imgData.height;\n\n var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);\n var tmpCtx = tmpCanvas.context;\n putBinaryImageData(tmpCtx, imgData);\n\n for (var i = 0, ii = map.length; i < ii; i++) {\n var entry = map[i];\n ctx.save();\n ctx.transform.apply(ctx, entry.transform);\n ctx.scale(1, -1);\n ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,\n 0, -1, 1, 1);\n if (this.imageLayer) {\n var position = this.getCanvasPosition(entry.x, entry.y);\n this.imageLayer.appendImage({\n imgData: imgData,\n left: position[0],\n top: position[1],\n width: w,\n height: h\n });\n }\n ctx.restore();\n }\n },\n\n paintSolidColorImageMask:\n function CanvasGraphics_paintSolidColorImageMask() {\n this.ctx.fillRect(0, 0, 1, 1);\n },\n\n paintXObject: function CanvasGraphics_paintXObject() {\n warn('Unsupported \\'paintXObject\\' command.');\n },\n\n // Marked content\n\n markPoint: function CanvasGraphics_markPoint(tag) {\n // TODO Marked content.\n },\n markPointProps: function CanvasGraphics_markPointProps(tag, properties) {\n // TODO Marked content.\n },\n beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {\n // TODO Marked content.\n },\n beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(\n tag, properties) {\n // TODO Marked content.\n },\n endMarkedContent: function CanvasGraphics_endMarkedContent() {\n // TODO Marked content.\n },\n\n // Compatibility\n\n beginCompat: function CanvasGraphics_beginCompat() {\n // TODO ignore undefined operators (should we do that anyway?)\n },\n endCompat: function CanvasGraphics_endCompat() {\n // TODO stop ignoring undefined operators\n },\n\n // Helper functions\n\n consumePath: function CanvasGraphics_consumePath() {\n var ctx = this.ctx;\n if (this.pendingClip) {\n if (this.pendingClip === EO_CLIP) {\n if (ctx.mozFillRule !== undefined) {\n ctx.mozFillRule = 'evenodd';\n ctx.clip();\n ctx.mozFillRule = 'nonzero';\n } else {\n ctx.clip('evenodd');\n }\n } else {\n ctx.clip();\n }\n this.pendingClip = null;\n }\n ctx.beginPath();\n },\n getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {\n if (this.cachedGetSinglePixelWidth === null) {\n var inverse = this.ctx.mozCurrentTransformInverse;\n // max of the current horizontal and vertical scale\n this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(\n (inverse[0] * inverse[0] + inverse[1] * inverse[1]),\n (inverse[2] * inverse[2] + inverse[3] * inverse[3])));\n }\n return this.cachedGetSinglePixelWidth;\n },\n getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {\n var transform = this.ctx.mozCurrentTransform;\n return [\n transform[0] * x + transform[2] * y + transform[4],\n transform[1] * x + transform[3] * y + transform[5]\n ];\n }\n };\n\n for (var op in OPS) {\n CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];\n }\n\n return CanvasGraphics;\n})();\n\nexports.CanvasGraphics = CanvasGraphics;\nexports.createScratchCanvas = createScratchCanvas;\n}));\n\n\n(function (root, factory) {\n {\n factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,\n root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,\n root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal);\n }\n}(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,\n displayMetadata, sharedGlobal, amdRequire) {\n\nvar InvalidPDFException = sharedUtil.InvalidPDFException;\nvar MessageHandler = sharedUtil.MessageHandler;\nvar MissingPDFException = sharedUtil.MissingPDFException;\nvar PasswordResponses = sharedUtil.PasswordResponses;\nvar PasswordException = sharedUtil.PasswordException;\nvar StatTimer = sharedUtil.StatTimer;\nvar UnexpectedResponseException = sharedUtil.UnexpectedResponseException;\nvar UnknownErrorException = sharedUtil.UnknownErrorException;\nvar Util = sharedUtil.Util;\nvar createPromiseCapability = sharedUtil.createPromiseCapability;\nvar combineUrl = sharedUtil.combineUrl;\nvar error = sharedUtil.error;\nvar deprecated = sharedUtil.deprecated;\nvar info = sharedUtil.info;\nvar isArrayBuffer = sharedUtil.isArrayBuffer;\nvar loadJpegStream = sharedUtil.loadJpegStream;\nvar stringToBytes = sharedUtil.stringToBytes;\nvar warn = sharedUtil.warn;\nvar FontFaceObject = displayFontLoader.FontFaceObject;\nvar FontLoader = displayFontLoader.FontLoader;\nvar CanvasGraphics = displayCanvas.CanvasGraphics;\nvar createScratchCanvas = displayCanvas.createScratchCanvas;\nvar Metadata = displayMetadata.Metadata;\nvar PDFJS = sharedGlobal.PDFJS;\nvar globalScope = sharedGlobal.globalScope;\n\nvar DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536\n\n\nvar useRequireEnsure = false;\nif (typeof module !== 'undefined' && module.require) {\n // node.js - disable worker and set require.ensure.\n PDFJS.disableWorker = true;\n if (typeof require.ensure === 'undefined') {\n require.ensure = require('node-ensure');\n }\n useRequireEnsure = true;\n}\nif (typeof __webpack_require__ !== 'undefined') {\n // Webpack - get/bundle pdf.worker.js as additional file.\n PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js');\n useRequireEnsure = true;\n}\nif (typeof requirejs !== 'undefined' && requirejs.toUrl) {\n PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');\n}\nvar fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {\n require.ensure([], function () {\n require('./pdf.worker.js');\n callback();\n });\n}) : (typeof requirejs !== 'undefined') ? (function (callback) {\n requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {\n callback();\n });\n}) : null;\n\n\n/**\n * The maximum allowed image size in total pixels e.g. width * height. Images\n * above this value will not be drawn. Use -1 for no limit.\n * @var {number}\n */\nPDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?\n -1 : PDFJS.maxImageSize);\n\n/**\n * The url of where the predefined Adobe CMaps are located. Include trailing\n * slash.\n * @var {string}\n */\nPDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);\n\n/**\n * Specifies if CMaps are binary packed.\n * @var {boolean}\n */\nPDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;\n\n/**\n * By default fonts are converted to OpenType fonts and loaded via font face\n * rules. If disabled, the font will be rendered using a built in font renderer\n * that constructs the glyphs with primitive path commands.\n * @var {boolean}\n */\nPDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?\n false : PDFJS.disableFontFace);\n\n/**\n * Path for image resources, mainly for annotation icons. Include trailing\n * slash.\n * @var {string}\n */\nPDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?\n '' : PDFJS.imageResourcesPath);\n\n/**\n * Disable the web worker and run all code on the main thread. This will happen\n * automatically if the browser doesn't support workers or sending typed arrays\n * to workers.\n * @var {boolean}\n */\nPDFJS.disableWorker = (PDFJS.disableWorker === undefined ?\n false : PDFJS.disableWorker);\n\n/**\n * Path and filename of the worker file. Required when the worker is enabled in\n * development mode. If unspecified in the production build, the worker will be\n * loaded based on the location of the pdf.js file. It is recommended that\n * the workerSrc is set in a custom application to prevent issues caused by\n * third-party frameworks and libraries.\n * @var {string}\n */\nPDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);\n\n/**\n * Disable range request loading of PDF files. When enabled and if the server\n * supports partial content requests then the PDF will be fetched in chunks.\n * Enabled (false) by default.\n * @var {boolean}\n */\nPDFJS.disableRange = (PDFJS.disableRange === undefined ?\n false : PDFJS.disableRange);\n\n/**\n * Disable streaming of PDF file data. By default PDF.js attempts to load PDF\n * in chunks. This default behavior can be disabled.\n * @var {boolean}\n */\nPDFJS.disableStream = (PDFJS.disableStream === undefined ?\n false : PDFJS.disableStream);\n\n/**\n * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js\n * will automatically keep fetching more data even if it isn't needed to display\n * the current page. This default behavior can be disabled.\n *\n * NOTE: It is also necessary to disable streaming, see above,\n * in order for disabling of pre-fetching to work correctly.\n * @var {boolean}\n */\nPDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?\n false : PDFJS.disableAutoFetch);\n\n/**\n * Enables special hooks for debugging PDF.js.\n * @var {boolean}\n */\nPDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);\n\n/**\n * Enables transfer usage in postMessage for ArrayBuffers.\n * @var {boolean}\n */\nPDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?\n true : PDFJS.postMessageTransfers);\n\n/**\n * Disables URL.createObjectURL usage.\n * @var {boolean}\n */\nPDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?\n false : PDFJS.disableCreateObjectURL);\n\n/**\n * Disables WebGL usage.\n * @var {boolean}\n */\nPDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?\n true : PDFJS.disableWebGL);\n\n/**\n * Disables fullscreen support, and by extension Presentation Mode,\n * in browsers which support the fullscreen API.\n * @var {boolean}\n */\nPDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?\n false : PDFJS.disableFullscreen);\n\n/**\n * Enables CSS only zooming.\n * @var {boolean}\n */\nPDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?\n false : PDFJS.useOnlyCssZoom);\n\n/**\n * Controls the logging level.\n * The constants from PDFJS.VERBOSITY_LEVELS should be used:\n * - errors\n * - warnings [default]\n * - infos\n * @var {number}\n */\nPDFJS.verbosity = (PDFJS.verbosity === undefined ?\n PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);\n\n/**\n * The maximum supported canvas size in total pixels e.g. width * height.\n * The default value is 4096 * 4096. Use -1 for no limit.\n * @var {number}\n */\nPDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?\n 16777216 : PDFJS.maxCanvasPixels);\n\n/**\n * (Deprecated) Opens external links in a new window if enabled.\n * The default behavior opens external links in the PDF.js window.\n *\n * NOTE: This property has been deprecated, please use\n * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.\n * @var {boolean}\n */\nPDFJS.openExternalLinksInNewWindow = (\n PDFJS.openExternalLinksInNewWindow === undefined ?\n false : PDFJS.openExternalLinksInNewWindow);\n\n/**\n * Specifies the |target| attribute for external links.\n * The constants from PDFJS.LinkTarget should be used:\n * - NONE [default]\n * - SELF\n * - BLANK\n * - PARENT\n * - TOP\n * @var {number}\n */\nPDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?\n PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget);\n\n/**\n * Specifies the |rel| attribute for external links. Defaults to stripping\n * the referrer.\n * @var {string}\n */\nPDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?\n 'noreferrer' : PDFJS.externalLinkRel);\n\n/**\n * Determines if we can eval strings as JS. Primarily used to improve\n * performance for font rendering.\n * @var {boolean}\n */\nPDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?\n true : PDFJS.isEvalSupported);\n\n/**\n * Document initialization / loading parameters object.\n *\n * @typedef {Object} DocumentInitParameters\n * @property {string} url - The URL of the PDF.\n * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays\n * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,\n * use atob() to convert it to a binary string first.\n * @property {Object} httpHeaders - Basic authentication headers.\n * @property {boolean} withCredentials - Indicates whether or not cross-site\n * Access-Control requests should be made using credentials such as cookies\n * or authorization headers. The default is false.\n * @property {string} password - For decrypting password-protected PDFs.\n * @property {TypedArray} initialData - A typed array with the first portion or\n * all of the pdf data. Used by the extension since some data is already\n * loaded before the switch to range requests.\n * @property {number} length - The PDF file length. It's used for progress\n * reports and range requests operations.\n * @property {PDFDataRangeTransport} range\n * @property {number} rangeChunkSize - Optional parameter to specify\n * maximum number of bytes fetched per range request. The default value is\n * 2^16 = 65536.\n * @property {PDFWorker} worker - The worker that will be used for the loading\n * and parsing of the PDF data.\n */\n\n/**\n * @typedef {Object} PDFDocumentStats\n * @property {Array} streamTypes - Used stream types in the document (an item\n * is set to true if specific stream ID was used in the document).\n * @property {Array} fontTypes - Used font type in the document (an item is set\n * to true if specific font ID was used in the document).\n */\n\n/**\n * This is the main entry point for loading a PDF and interacting with it.\n * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)\n * is used, which means it must follow the same origin rules that any XHR does\n * e.g. No cross domain requests without CORS.\n *\n * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src\n * Can be a url to where a PDF is located, a typed array (Uint8Array)\n * already populated with data or parameter object.\n *\n * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used\n * if you want to manually serve range requests for data in the PDF.\n *\n * @param {function} passwordCallback (deprecated) It is used to request a\n * password if wrong or no password was provided. The callback receives two\n * parameters: function that needs to be called with new password and reason\n * (see {PasswordResponses}).\n *\n * @param {function} progressCallback (deprecated) It is used to be able to\n * monitor the loading progress of the PDF file (necessary to implement e.g.\n * a loading bar). The callback receives an {Object} with the properties:\n * {number} loaded and {number} total.\n *\n * @return {PDFDocumentLoadingTask}\n */\nPDFJS.getDocument = function getDocument(src,\n pdfDataRangeTransport,\n passwordCallback,\n progressCallback) {\n var task = new PDFDocumentLoadingTask();\n\n // Support of the obsolete arguments (for compatibility with API v1.0)\n if (arguments.length > 1) {\n deprecated('getDocument is called with pdfDataRangeTransport, ' +\n 'passwordCallback or progressCallback argument');\n }\n if (pdfDataRangeTransport) {\n if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {\n // Not a PDFDataRangeTransport instance, trying to add missing properties.\n pdfDataRangeTransport = Object.create(pdfDataRangeTransport);\n pdfDataRangeTransport.length = src.length;\n pdfDataRangeTransport.initialData = src.initialData;\n if (!pdfDataRangeTransport.abort) {\n pdfDataRangeTransport.abort = function () {};\n }\n }\n src = Object.create(src);\n src.range = pdfDataRangeTransport;\n }\n task.onPassword = passwordCallback || null;\n task.onProgress = progressCallback || null;\n\n var source;\n if (typeof src === 'string') {\n source = { url: src };\n } else if (isArrayBuffer(src)) {\n source = { data: src };\n } else if (src instanceof PDFDataRangeTransport) {\n source = { range: src };\n } else {\n if (typeof src !== 'object') {\n error('Invalid parameter in getDocument, need either Uint8Array, ' +\n 'string or a parameter object');\n }\n if (!src.url && !src.data && !src.range) {\n error('Invalid parameter object: need either .data, .range or .url');\n }\n\n source = src;\n }\n\n var params = {};\n var rangeTransport = null;\n var worker = null;\n for (var key in source) {\n if (key === 'url' && typeof window !== 'undefined') {\n // The full path is required in the 'url' field.\n params[key] = combineUrl(window.location.href, source[key]);\n continue;\n } else if (key === 'range') {\n rangeTransport = source[key];\n continue;\n } else if (key === 'worker') {\n worker = source[key];\n continue;\n } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {\n // Converting string or array-like data to Uint8Array.\n var pdfBytes = source[key];\n if (typeof pdfBytes === 'string') {\n params[key] = stringToBytes(pdfBytes);\n } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&\n !isNaN(pdfBytes.length)) {\n params[key] = new Uint8Array(pdfBytes);\n } else if (isArrayBuffer(pdfBytes)) {\n params[key] = new Uint8Array(pdfBytes);\n } else {\n error('Invalid PDF binary data: either typed array, string or ' +\n 'array-like object is expected in the data property.');\n }\n continue;\n }\n params[key] = source[key];\n }\n\n params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;\n\n if (!worker) {\n // Worker was not provided -- creating and owning our own.\n worker = new PDFWorker();\n task._worker = worker;\n }\n var docId = task.docId;\n worker.promise.then(function () {\n if (task.destroyed) {\n throw new Error('Loading aborted');\n }\n return _fetchDocument(worker, params, rangeTransport, docId).then(\n function (workerId) {\n if (task.destroyed) {\n throw new Error('Loading aborted');\n }\n var messageHandler = new MessageHandler(docId, workerId, worker.port);\n messageHandler.send('Ready', null);\n var transport = new WorkerTransport(messageHandler, task, rangeTransport);\n task._transport = transport;\n });\n }).catch(task._capability.reject);\n\n return task;\n};\n\n/**\n * Starts fetching of specified PDF document/data.\n * @param {PDFWorker} worker\n * @param {Object} source\n * @param {PDFDataRangeTransport} pdfDataRangeTransport\n * @param {string} docId Unique document id, used as MessageHandler id.\n * @returns {Promise} The promise, which is resolved when worker id of\n * MessageHandler is known.\n * @private\n */\nfunction _fetchDocument(worker, source, pdfDataRangeTransport, docId) {\n if (worker.destroyed) {\n return Promise.reject(new Error('Worker was destroyed'));\n }\n\n source.disableAutoFetch = PDFJS.disableAutoFetch;\n source.disableStream = PDFJS.disableStream;\n source.chunkedViewerLoading = !!pdfDataRangeTransport;\n if (pdfDataRangeTransport) {\n source.length = pdfDataRangeTransport.length;\n source.initialData = pdfDataRangeTransport.initialData;\n }\n return worker.messageHandler.sendWithPromise('GetDocRequest', {\n docId: docId,\n source: source,\n disableRange: PDFJS.disableRange,\n maxImageSize: PDFJS.maxImageSize,\n cMapUrl: PDFJS.cMapUrl,\n cMapPacked: PDFJS.cMapPacked,\n disableFontFace: PDFJS.disableFontFace,\n disableCreateObjectURL: PDFJS.disableCreateObjectURL,\n verbosity: PDFJS.verbosity\n }).then(function (workerId) {\n if (worker.destroyed) {\n throw new Error('Worker was destroyed');\n }\n return workerId;\n });\n}\n\n/**\n * PDF document loading operation.\n * @class\n * @alias PDFDocumentLoadingTask\n */\nvar PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {\n var nextDocumentId = 0;\n\n /** @constructs PDFDocumentLoadingTask */\n function PDFDocumentLoadingTask() {\n this._capability = createPromiseCapability();\n this._transport = null;\n this._worker = null;\n\n /**\n * Unique document loading task id -- used in MessageHandlers.\n * @type {string}\n */\n this.docId = 'd' + (nextDocumentId++);\n\n /**\n * Shows if loading task is destroyed.\n * @type {boolean}\n */\n this.destroyed = false;\n\n /**\n * Callback to request a password if wrong or no password was provided.\n * The callback receives two parameters: function that needs to be called\n * with new password and reason (see {PasswordResponses}).\n */\n this.onPassword = null;\n\n /**\n * Callback to be able to monitor the loading progress of the PDF file\n * (necessary to implement e.g. a loading bar). The callback receives\n * an {Object} with the properties: {number} loaded and {number} total.\n */\n this.onProgress = null;\n\n /**\n * Callback to when unsupported feature is used. The callback receives\n * an {PDFJS.UNSUPPORTED_FEATURES} argument.\n */\n this.onUnsupportedFeature = null;\n }\n\n PDFDocumentLoadingTask.prototype =\n /** @lends PDFDocumentLoadingTask.prototype */ {\n /**\n * @return {Promise}\n */\n get promise() {\n return this._capability.promise;\n },\n\n /**\n * Aborts all network requests and destroys worker.\n * @return {Promise} A promise that is resolved after destruction activity\n * is completed.\n */\n destroy: function () {\n this.destroyed = true;\n\n var transportDestroyed = !this._transport ? Promise.resolve() :\n this._transport.destroy();\n return transportDestroyed.then(function () {\n this._transport = null;\n if (this._worker) {\n this._worker.destroy();\n this._worker = null;\n }\n }.bind(this));\n },\n\n /**\n * Registers callbacks to indicate the document loading completion.\n *\n * @param {function} onFulfilled The callback for the loading completion.\n * @param {function} onRejected The callback for the loading failure.\n * @return {Promise} A promise that is resolved after the onFulfilled or\n * onRejected callback.\n */\n then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {\n return this.promise.then.apply(this.promise, arguments);\n }\n };\n\n return PDFDocumentLoadingTask;\n})();\n\n/**\n * Abstract class to support range requests file loading.\n * @class\n * @alias PDFJS.PDFDataRangeTransport\n * @param {number} length\n * @param {Uint8Array} initialData\n */\nvar PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {\n function PDFDataRangeTransport(length, initialData) {\n this.length = length;\n this.initialData = initialData;\n\n this._rangeListeners = [];\n this._progressListeners = [];\n this._progressiveReadListeners = [];\n this._readyCapability = createPromiseCapability();\n }\n PDFDataRangeTransport.prototype =\n /** @lends PDFDataRangeTransport.prototype */ {\n addRangeListener:\n function PDFDataRangeTransport_addRangeListener(listener) {\n this._rangeListeners.push(listener);\n },\n\n addProgressListener:\n function PDFDataRangeTransport_addProgressListener(listener) {\n this._progressListeners.push(listener);\n },\n\n addProgressiveReadListener:\n function PDFDataRangeTransport_addProgressiveReadListener(listener) {\n this._progressiveReadListeners.push(listener);\n },\n\n onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {\n var listeners = this._rangeListeners;\n for (var i = 0, n = listeners.length; i < n; ++i) {\n listeners[i](begin, chunk);\n }\n },\n\n onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {\n this._readyCapability.promise.then(function () {\n var listeners = this._progressListeners;\n for (var i = 0, n = listeners.length; i < n; ++i) {\n listeners[i](loaded);\n }\n }.bind(this));\n },\n\n onDataProgressiveRead:\n function PDFDataRangeTransport_onDataProgress(chunk) {\n this._readyCapability.promise.then(function () {\n var listeners = this._progressiveReadListeners;\n for (var i = 0, n = listeners.length; i < n; ++i) {\n listeners[i](chunk);\n }\n }.bind(this));\n },\n\n transportReady: function PDFDataRangeTransport_transportReady() {\n this._readyCapability.resolve();\n },\n\n requestDataRange:\n function PDFDataRangeTransport_requestDataRange(begin, end) {\n throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');\n },\n\n abort: function PDFDataRangeTransport_abort() {\n }\n };\n return PDFDataRangeTransport;\n})();\n\nPDFJS.PDFDataRangeTransport = PDFDataRangeTransport;\n\n/**\n * Proxy to a PDFDocument in the worker thread. Also, contains commonly used\n * properties that can be read synchronously.\n * @class\n * @alias PDFDocumentProxy\n */\nvar PDFDocumentProxy = (function PDFDocumentProxyClosure() {\n function PDFDocumentProxy(pdfInfo, transport, loadingTask) {\n this.pdfInfo = pdfInfo;\n this.transport = transport;\n this.loadingTask = loadingTask;\n }\n PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {\n /**\n * @return {number} Total number of pages the PDF contains.\n */\n get numPages() {\n return this.pdfInfo.numPages;\n },\n /**\n * @return {string} A unique ID to identify a PDF. Not guaranteed to be\n * unique.\n */\n get fingerprint() {\n return this.pdfInfo.fingerprint;\n },\n /**\n * @param {number} pageNumber The page number to get. The first page is 1.\n * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}\n * object.\n */\n getPage: function PDFDocumentProxy_getPage(pageNumber) {\n return this.transport.getPage(pageNumber);\n },\n /**\n * @param {{num: number, gen: number}} ref The page reference. Must have\n * the 'num' and 'gen' properties.\n * @return {Promise} A promise that is resolved with the page index that is\n * associated with the reference.\n */\n getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {\n return this.transport.getPageIndex(ref);\n },\n /**\n * @return {Promise} A promise that is resolved with a lookup table for\n * mapping named destinations to reference numbers.\n *\n * This can be slow for large documents: use getDestination instead\n */\n getDestinations: function PDFDocumentProxy_getDestinations() {\n return this.transport.getDestinations();\n },\n /**\n * @param {string} id The named destination to get.\n * @return {Promise} A promise that is resolved with all information\n * of the given named destination.\n */\n getDestination: function PDFDocumentProxy_getDestination(id) {\n return this.transport.getDestination(id);\n },\n /**\n * @return {Promise} A promise that is resolved with a lookup table for\n * mapping named attachments to their content.\n */\n getAttachments: function PDFDocumentProxy_getAttachments() {\n return this.transport.getAttachments();\n },\n /**\n * @return {Promise} A promise that is resolved with an array of all the\n * JavaScript strings in the name tree.\n */\n getJavaScript: function PDFDocumentProxy_getJavaScript() {\n return this.transport.getJavaScript();\n },\n /**\n * @return {Promise} A promise that is resolved with an {Array} that is a\n * tree outline (if it has one) of the PDF. The tree is in the format of:\n * [\n * {\n * title: string,\n * bold: boolean,\n * italic: boolean,\n * color: rgb array,\n * dest: dest obj,\n * items: array of more items like this\n * },\n * ...\n * ].\n */\n getOutline: function PDFDocumentProxy_getOutline() {\n return this.transport.getOutline();\n },\n /**\n * @return {Promise} A promise that is resolved with an {Object} that has\n * info and metadata properties. Info is an {Object} filled with anything\n * available in the information dictionary and similarly metadata is a\n * {Metadata} object with information from the metadata section of the PDF.\n */\n getMetadata: function PDFDocumentProxy_getMetadata() {\n return this.transport.getMetadata();\n },\n /**\n * @return {Promise} A promise that is resolved with a TypedArray that has\n * the raw data from the PDF.\n */\n getData: function PDFDocumentProxy_getData() {\n return this.transport.getData();\n },\n /**\n * @return {Promise} A promise that is resolved when the document's data\n * is loaded. It is resolved with an {Object} that contains the length\n * property that indicates size of the PDF data in bytes.\n */\n getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {\n return this.transport.downloadInfoCapability.promise;\n },\n /**\n * @return {Promise} A promise this is resolved with current stats about\n * document structures (see {@link PDFDocumentStats}).\n */\n getStats: function PDFDocumentProxy_getStats() {\n return this.transport.getStats();\n },\n /**\n * Cleans up resources allocated by the document, e.g. created @font-face.\n */\n cleanup: function PDFDocumentProxy_cleanup() {\n this.transport.startCleanup();\n },\n /**\n * Destroys current document instance and terminates worker.\n */\n destroy: function PDFDocumentProxy_destroy() {\n return this.loadingTask.destroy();\n }\n };\n return PDFDocumentProxy;\n})();\n\n/**\n * Page getTextContent parameters.\n *\n * @typedef {Object} getTextContentParameters\n * @param {boolean} normalizeWhitespace - replaces all occurrences of\n * whitespace with standard spaces (0x20). The default value is `false`.\n */\n\n/**\n * Page text content.\n *\n * @typedef {Object} TextContent\n * @property {array} items - array of {@link TextItem}\n * @property {Object} styles - {@link TextStyles} objects, indexed by font\n * name.\n */\n\n/**\n * Page text content part.\n *\n * @typedef {Object} TextItem\n * @property {string} str - text content.\n * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.\n * @property {array} transform - transformation matrix.\n * @property {number} width - width in device space.\n * @property {number} height - height in device space.\n * @property {string} fontName - font name used by pdf.js for converted font.\n */\n\n/**\n * Text style.\n *\n * @typedef {Object} TextStyle\n * @property {number} ascent - font ascent.\n * @property {number} descent - font descent.\n * @property {boolean} vertical - text is in vertical mode.\n * @property {string} fontFamily - possible font family\n */\n\n/**\n * Page annotation parameters.\n *\n * @typedef {Object} GetAnnotationsParameters\n * @param {string} intent - Determines the annotations that will be fetched,\n * can be either 'display' (viewable annotations) or 'print'\n * (printable annotations).\n * If the parameter is omitted, all annotations are fetched.\n */\n\n/**\n * Page render parameters.\n *\n * @typedef {Object} RenderParameters\n * @property {Object} canvasContext - A 2D context of a DOM Canvas object.\n * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by\n * calling of PDFPage.getViewport method.\n * @property {string} intent - Rendering intent, can be 'display' or 'print'\n * (default value is 'display').\n * @property {Array} transform - (optional) Additional transform, applied\n * just before viewport transform.\n * @property {Object} imageLayer - (optional) An object that has beginLayout,\n * endLayout and appendImage functions.\n * @property {function} continueCallback - (deprecated) A function that will be\n * called each time the rendering is paused. To continue\n * rendering call the function that is the first argument\n * to the callback.\n */\n\n/**\n * PDF page operator list.\n *\n * @typedef {Object} PDFOperatorList\n * @property {Array} fnArray - Array containing the operator functions.\n * @property {Array} argsArray - Array containing the arguments of the\n * functions.\n */\n\n/**\n * Proxy to a PDFPage in the worker thread.\n * @class\n * @alias PDFPageProxy\n */\nvar PDFPageProxy = (function PDFPageProxyClosure() {\n function PDFPageProxy(pageIndex, pageInfo, transport) {\n this.pageIndex = pageIndex;\n this.pageInfo = pageInfo;\n this.transport = transport;\n this.stats = new StatTimer();\n this.stats.enabled = !!globalScope.PDFJS.enableStats;\n this.commonObjs = transport.commonObjs;\n this.objs = new PDFObjects();\n this.cleanupAfterRender = false;\n this.pendingCleanup = false;\n this.intentStates = {};\n this.destroyed = false;\n }\n PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {\n /**\n * @return {number} Page number of the page. First page is 1.\n */\n get pageNumber() {\n return this.pageIndex + 1;\n },\n /**\n * @return {number} The number of degrees the page is rotated clockwise.\n */\n get rotate() {\n return this.pageInfo.rotate;\n },\n /**\n * @return {Object} The reference that points to this page. It has 'num' and\n * 'gen' properties.\n */\n get ref() {\n return this.pageInfo.ref;\n },\n /**\n * @return {Array} An array of the visible portion of the PDF page in the\n * user space units - [x1, y1, x2, y2].\n */\n get view() {\n return this.pageInfo.view;\n },\n /**\n * @param {number} scale The desired scale of the viewport.\n * @param {number} rotate Degrees to rotate the viewport. If omitted this\n * defaults to the page rotation.\n * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties\n * along with transforms required for rendering.\n */\n getViewport: function PDFPageProxy_getViewport(scale, rotate) {\n if (arguments.length < 2) {\n rotate = this.rotate;\n }\n return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);\n },\n /**\n * @param {GetAnnotationsParameters} params - Annotation parameters.\n * @return {Promise} A promise that is resolved with an {Array} of the\n * annotation objects.\n */\n getAnnotations: function PDFPageProxy_getAnnotations(params) {\n var intent = (params && params.intent) || null;\n\n if (!this.annotationsPromise || this.annotationsIntent !== intent) {\n this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,\n intent);\n this.annotationsIntent = intent;\n }\n return this.annotationsPromise;\n },\n /**\n * Begins the process of rendering a page to the desired context.\n * @param {RenderParameters} params Page render parameters.\n * @return {RenderTask} An object that contains the promise, which\n * is resolved when the page finishes rendering.\n */\n render: function PDFPageProxy_render(params) {\n var stats = this.stats;\n stats.time('Overall');\n\n // If there was a pending destroy cancel it so no cleanup happens during\n // this call to render.\n this.pendingCleanup = false;\n\n var renderingIntent = (params.intent === 'print' ? 'print' : 'display');\n\n if (!this.intentStates[renderingIntent]) {\n this.intentStates[renderingIntent] = {};\n }\n var intentState = this.intentStates[renderingIntent];\n\n // If there's no displayReadyCapability yet, then the operatorList\n // was never requested before. Make the request and create the promise.\n if (!intentState.displayReadyCapability) {\n intentState.receivingOperatorList = true;\n intentState.displayReadyCapability = createPromiseCapability();\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false\n };\n\n this.stats.time('Page Request');\n this.transport.messageHandler.send('RenderPageRequest', {\n pageIndex: this.pageNumber - 1,\n intent: renderingIntent\n });\n }\n\n var internalRenderTask = new InternalRenderTask(complete, params,\n this.objs,\n this.commonObjs,\n intentState.operatorList,\n this.pageNumber);\n internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';\n if (!intentState.renderTasks) {\n intentState.renderTasks = [];\n }\n intentState.renderTasks.push(internalRenderTask);\n var renderTask = internalRenderTask.task;\n\n // Obsolete parameter support\n if (params.continueCallback) {\n deprecated('render is used with continueCallback parameter');\n renderTask.onContinue = params.continueCallback;\n }\n\n var self = this;\n intentState.displayReadyCapability.promise.then(\n function pageDisplayReadyPromise(transparency) {\n if (self.pendingCleanup) {\n complete();\n return;\n }\n stats.time('Rendering');\n internalRenderTask.initalizeGraphics(transparency);\n internalRenderTask.operatorListChanged();\n },\n function pageDisplayReadPromiseError(reason) {\n complete(reason);\n }\n );\n\n function complete(error) {\n var i = intentState.renderTasks.indexOf(internalRenderTask);\n if (i >= 0) {\n intentState.renderTasks.splice(i, 1);\n }\n\n if (self.cleanupAfterRender) {\n self.pendingCleanup = true;\n }\n self._tryCleanup();\n\n if (error) {\n internalRenderTask.capability.reject(error);\n } else {\n internalRenderTask.capability.resolve();\n }\n stats.timeEnd('Rendering');\n stats.timeEnd('Overall');\n }\n\n return renderTask;\n },\n\n /**\n * @return {Promise} A promise resolved with an {@link PDFOperatorList}\n * object that represents page's operator list.\n */\n getOperatorList: function PDFPageProxy_getOperatorList() {\n function operatorListChanged() {\n if (intentState.operatorList.lastChunk) {\n intentState.opListReadCapability.resolve(intentState.operatorList);\n }\n }\n\n var renderingIntent = 'oplist';\n if (!this.intentStates[renderingIntent]) {\n this.intentStates[renderingIntent] = {};\n }\n var intentState = this.intentStates[renderingIntent];\n\n if (!intentState.opListReadCapability) {\n var opListTask = {};\n opListTask.operatorListChanged = operatorListChanged;\n intentState.receivingOperatorList = true;\n intentState.opListReadCapability = createPromiseCapability();\n intentState.renderTasks = [];\n intentState.renderTasks.push(opListTask);\n intentState.operatorList = {\n fnArray: [],\n argsArray: [],\n lastChunk: false\n };\n\n this.transport.messageHandler.send('RenderPageRequest', {\n pageIndex: this.pageIndex,\n intent: renderingIntent\n });\n }\n return intentState.opListReadCapability.promise;\n },\n\n /**\n * @param {getTextContentParameters} params - getTextContent parameters.\n * @return {Promise} That is resolved a {@link TextContent}\n * object that represent the page text content.\n */\n getTextContent: function PDFPageProxy_getTextContent(params) {\n var normalizeWhitespace = (params && params.normalizeWhitespace) || false;\n\n return this.transport.messageHandler.sendWithPromise('GetTextContent', {\n pageIndex: this.pageNumber - 1,\n normalizeWhitespace: normalizeWhitespace,\n });\n },\n\n /**\n * Destroys page object.\n */\n _destroy: function PDFPageProxy_destroy() {\n this.destroyed = true;\n this.transport.pageCache[this.pageIndex] = null;\n\n var waitOn = [];\n Object.keys(this.intentStates).forEach(function(intent) {\n var intentState = this.intentStates[intent];\n intentState.renderTasks.forEach(function(renderTask) {\n var renderCompleted = renderTask.capability.promise.\n catch(function () {}); // ignoring failures\n waitOn.push(renderCompleted);\n renderTask.cancel();\n });\n }, this);\n this.objs.clear();\n this.annotationsPromise = null;\n this.pendingCleanup = false;\n return Promise.all(waitOn);\n },\n\n /**\n * Cleans up resources allocated by the page. (deprecated)\n */\n destroy: function() {\n deprecated('page destroy method, use cleanup() instead');\n this.cleanup();\n },\n\n /**\n * Cleans up resources allocated by the page.\n */\n cleanup: function PDFPageProxy_cleanup() {\n this.pendingCleanup = true;\n this._tryCleanup();\n },\n /**\n * For internal use only. Attempts to clean up if rendering is in a state\n * where that's possible.\n * @ignore\n */\n _tryCleanup: function PDFPageProxy_tryCleanup() {\n if (!this.pendingCleanup ||\n Object.keys(this.intentStates).some(function(intent) {\n var intentState = this.intentStates[intent];\n return (intentState.renderTasks.length !== 0 ||\n intentState.receivingOperatorList);\n }, this)) {\n return;\n }\n\n Object.keys(this.intentStates).forEach(function(intent) {\n delete this.intentStates[intent];\n }, this);\n this.objs.clear();\n this.annotationsPromise = null;\n this.pendingCleanup = false;\n },\n /**\n * For internal use only.\n * @ignore\n */\n _startRenderPage: function PDFPageProxy_startRenderPage(transparency,\n intent) {\n var intentState = this.intentStates[intent];\n // TODO Refactor RenderPageRequest to separate rendering\n // and operator list logic\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.resolve(transparency);\n }\n },\n /**\n * For internal use only.\n * @ignore\n */\n _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,\n intent) {\n var intentState = this.intentStates[intent];\n var i, ii;\n // Add the new chunk to the current operator list.\n for (i = 0, ii = operatorListChunk.length; i < ii; i++) {\n intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);\n intentState.operatorList.argsArray.push(\n operatorListChunk.argsArray[i]);\n }\n intentState.operatorList.lastChunk = operatorListChunk.lastChunk;\n\n // Notify all the rendering tasks there are more operators to be consumed.\n for (i = 0; i < intentState.renderTasks.length; i++) {\n intentState.renderTasks[i].operatorListChanged();\n }\n\n if (operatorListChunk.lastChunk) {\n intentState.receivingOperatorList = false;\n this._tryCleanup();\n }\n }\n };\n return PDFPageProxy;\n})();\n\n/**\n * PDF.js web worker abstraction, it controls instantiation of PDF documents and\n * WorkerTransport for them. If creation of a web worker is not possible,\n * a \"fake\" worker will be used instead.\n * @class\n */\nvar PDFWorker = (function PDFWorkerClosure() {\n var nextFakeWorkerId = 0;\n\n function getWorkerSrc() {\n if (PDFJS.workerSrc) {\n return PDFJS.workerSrc;\n }\n if (pdfjsFilePath) {\n return pdfjsFilePath.replace(/\\.js$/i, '.worker.js');\n }\n error('No PDFJS.workerSrc specified');\n }\n\n // Loads worker code into main thread.\n function setupFakeWorkerGlobal() {\n if (!PDFJS.fakeWorkerFilesLoadedCapability) {\n PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();\n // In the developer build load worker_loader which in turn loads all the\n // other files and resolves the promise. In production only the\n // pdf.worker.js file is needed.\n var loader = fakeWorkerFilesLoader || function (callback) {\n Util.loadScript(getWorkerSrc(), callback);\n };\n loader(function () {\n PDFJS.fakeWorkerFilesLoadedCapability.resolve();\n });\n }\n return PDFJS.fakeWorkerFilesLoadedCapability.promise;\n }\n\n function PDFWorker(name) {\n this.name = name;\n this.destroyed = false;\n\n this._readyCapability = createPromiseCapability();\n this._port = null;\n this._webWorker = null;\n this._messageHandler = null;\n this._initialize();\n }\n\n PDFWorker.prototype = /** @lends PDFWorker.prototype */ {\n get promise() {\n return this._readyCapability.promise;\n },\n\n get port() {\n return this._port;\n },\n\n get messageHandler() {\n return this._messageHandler;\n },\n\n _initialize: function PDFWorker_initialize() {\n // If worker support isn't disabled explicit and the browser has worker\n // support, create a new web worker and test if it/the browser fullfills\n // all requirements to run parts of pdf.js in a web worker.\n // Right now, the requirement is, that an Uint8Array is still an\n // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)\n if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {\n var workerSrc = getWorkerSrc();\n\n try {\n // Some versions of FF can't create a worker on localhost, see:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=683280\n var worker = new Worker(workerSrc);\n var messageHandler = new MessageHandler('main', 'worker', worker);\n messageHandler.on('test', function PDFWorker_test(data) {\n if (this.destroyed) {\n this._readyCapability.reject(new Error('Worker was destroyed'));\n messageHandler.destroy();\n worker.terminate();\n return; // worker was destroyed\n }\n var supportTypedArray = data && data.supportTypedArray;\n if (supportTypedArray) {\n this._messageHandler = messageHandler;\n this._port = worker;\n this._webWorker = worker;\n if (!data.supportTransfers) {\n PDFJS.postMessageTransfers = false;\n }\n this._readyCapability.resolve();\n } else {\n this._setupFakeWorker();\n messageHandler.destroy();\n worker.terminate();\n }\n }.bind(this));\n\n messageHandler.on('console_log', function (data) {\n console.log.apply(console, data);\n });\n messageHandler.on('console_error', function (data) {\n console.error.apply(console, data);\n });\n\n messageHandler.on('ready', function (data) {\n if (this.destroyed) {\n this._readyCapability.reject(new Error('Worker was destroyed'));\n messageHandler.destroy();\n worker.terminate();\n return; // worker was destroyed\n }\n try {\n sendTest();\n } catch (e) {\n // We need fallback to a faked worker.\n this._setupFakeWorker();\n }\n }.bind(this));\n\n var sendTest = function () {\n var testObj = new Uint8Array(\n [PDFJS.postMessageTransfers ? 255 : 0]);\n // Some versions of Opera throw a DATA_CLONE_ERR on serializing the\n // typed array. Also, checking if we can use transfers.\n try {\n messageHandler.send('test', testObj, [testObj.buffer]);\n } catch (ex) {\n info('Cannot use postMessage transfers');\n testObj[0] = 0;\n messageHandler.send('test', testObj);\n }\n };\n\n // It might take time for worker to initialize (especially when AMD\n // loader is used). We will try to send test immediately, and then\n // when 'ready' message will arrive. The worker shall process only\n // first received 'test'.\n sendTest();\n return;\n } catch (e) {\n info('The worker has been disabled.');\n }\n }\n // Either workers are disabled, not supported or have thrown an exception.\n // Thus, we fallback to a faked worker.\n this._setupFakeWorker();\n },\n\n _setupFakeWorker: function PDFWorker_setupFakeWorker() {\n if (!globalScope.PDFJS.disableWorker) {\n warn('Setting up fake worker.');\n globalScope.PDFJS.disableWorker = true;\n }\n\n setupFakeWorkerGlobal().then(function () {\n if (this.destroyed) {\n this._readyCapability.reject(new Error('Worker was destroyed'));\n return;\n }\n\n // If we don't use a worker, just post/sendMessage to the main thread.\n var port = {\n _listeners: [],\n postMessage: function (obj) {\n var e = {data: obj};\n this._listeners.forEach(function (listener) {\n listener.call(this, e);\n }, this);\n },\n addEventListener: function (name, listener) {\n this._listeners.push(listener);\n },\n removeEventListener: function (name, listener) {\n var i = this._listeners.indexOf(listener);\n this._listeners.splice(i, 1);\n },\n terminate: function () {}\n };\n this._port = port;\n\n // All fake workers use the same port, making id unique.\n var id = 'fake' + (nextFakeWorkerId++);\n\n // If the main thread is our worker, setup the handling for the\n // messages -- the main thread sends to it self.\n var workerHandler = new MessageHandler(id + '_worker', id, port);\n PDFJS.WorkerMessageHandler.setup(workerHandler, port);\n\n var messageHandler = new MessageHandler(id, id + '_worker', port);\n this._messageHandler = messageHandler;\n this._readyCapability.resolve();\n }.bind(this));\n },\n\n /**\n * Destroys the worker instance.\n */\n destroy: function PDFWorker_destroy() {\n this.destroyed = true;\n if (this._webWorker) {\n // We need to terminate only web worker created resource.\n this._webWorker.terminate();\n this._webWorker = null;\n }\n this._port = null;\n if (this._messageHandler) {\n this._messageHandler.destroy();\n this._messageHandler = null;\n }\n }\n };\n\n return PDFWorker;\n})();\nPDFJS.PDFWorker = PDFWorker;\n\n/**\n * For internal use only.\n * @ignore\n */\nvar WorkerTransport = (function WorkerTransportClosure() {\n function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {\n this.messageHandler = messageHandler;\n this.loadingTask = loadingTask;\n this.pdfDataRangeTransport = pdfDataRangeTransport;\n this.commonObjs = new PDFObjects();\n this.fontLoader = new FontLoader(loadingTask.docId);\n\n this.destroyed = false;\n this.destroyCapability = null;\n\n this.pageCache = [];\n this.pagePromises = [];\n this.downloadInfoCapability = createPromiseCapability();\n\n this.setupMessageHandler();\n }\n WorkerTransport.prototype = {\n destroy: function WorkerTransport_destroy() {\n if (this.destroyCapability) {\n return this.destroyCapability.promise;\n }\n\n this.destroyed = true;\n this.destroyCapability = createPromiseCapability();\n\n var waitOn = [];\n // We need to wait for all renderings to be completed, e.g.\n // timeout/rAF can take a long time.\n this.pageCache.forEach(function (page) {\n if (page) {\n waitOn.push(page._destroy());\n }\n });\n this.pageCache = [];\n this.pagePromises = [];\n var self = this;\n // We also need to wait for the worker to finish its long running tasks.\n var terminated = this.messageHandler.sendWithPromise('Terminate', null);\n waitOn.push(terminated);\n Promise.all(waitOn).then(function () {\n self.fontLoader.clear();\n if (self.pdfDataRangeTransport) {\n self.pdfDataRangeTransport.abort();\n self.pdfDataRangeTransport = null;\n }\n if (self.messageHandler) {\n self.messageHandler.destroy();\n self.messageHandler = null;\n }\n self.destroyCapability.resolve();\n }, this.destroyCapability.reject);\n return this.destroyCapability.promise;\n },\n\n setupMessageHandler:\n function WorkerTransport_setupMessageHandler() {\n var messageHandler = this.messageHandler;\n\n function updatePassword(password) {\n messageHandler.send('UpdatePassword', password);\n }\n\n var pdfDataRangeTransport = this.pdfDataRangeTransport;\n if (pdfDataRangeTransport) {\n pdfDataRangeTransport.addRangeListener(function(begin, chunk) {\n messageHandler.send('OnDataRange', {\n begin: begin,\n chunk: chunk\n });\n });\n\n pdfDataRangeTransport.addProgressListener(function(loaded) {\n messageHandler.send('OnDataProgress', {\n loaded: loaded\n });\n });\n\n pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {\n messageHandler.send('OnDataRange', {\n chunk: chunk\n });\n });\n\n messageHandler.on('RequestDataRange',\n function transportDataRange(data) {\n pdfDataRangeTransport.requestDataRange(data.begin, data.end);\n }, this);\n }\n\n messageHandler.on('GetDoc', function transportDoc(data) {\n var pdfInfo = data.pdfInfo;\n this.numPages = data.pdfInfo.numPages;\n var loadingTask = this.loadingTask;\n var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);\n this.pdfDocument = pdfDocument;\n loadingTask._capability.resolve(pdfDocument);\n }, this);\n\n messageHandler.on('NeedPassword',\n function transportNeedPassword(exception) {\n var loadingTask = this.loadingTask;\n if (loadingTask.onPassword) {\n return loadingTask.onPassword(updatePassword,\n PasswordResponses.NEED_PASSWORD);\n }\n loadingTask._capability.reject(\n new PasswordException(exception.message, exception.code));\n }, this);\n\n messageHandler.on('IncorrectPassword',\n function transportIncorrectPassword(exception) {\n var loadingTask = this.loadingTask;\n if (loadingTask.onPassword) {\n return loadingTask.onPassword(updatePassword,\n PasswordResponses.INCORRECT_PASSWORD);\n }\n loadingTask._capability.reject(\n new PasswordException(exception.message, exception.code));\n }, this);\n\n messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {\n this.loadingTask._capability.reject(\n new InvalidPDFException(exception.message));\n }, this);\n\n messageHandler.on('MissingPDF', function transportMissingPDF(exception) {\n this.loadingTask._capability.reject(\n new MissingPDFException(exception.message));\n }, this);\n\n messageHandler.on('UnexpectedResponse',\n function transportUnexpectedResponse(exception) {\n this.loadingTask._capability.reject(\n new UnexpectedResponseException(exception.message, exception.status));\n }, this);\n\n messageHandler.on('UnknownError',\n function transportUnknownError(exception) {\n this.loadingTask._capability.reject(\n new UnknownErrorException(exception.message, exception.details));\n }, this);\n\n messageHandler.on('DataLoaded', function transportPage(data) {\n this.downloadInfoCapability.resolve(data);\n }, this);\n\n messageHandler.on('PDFManagerReady', function transportPage(data) {\n if (this.pdfDataRangeTransport) {\n this.pdfDataRangeTransport.transportReady();\n }\n }, this);\n\n messageHandler.on('StartRenderPage', function transportRender(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n var page = this.pageCache[data.pageIndex];\n\n page.stats.timeEnd('Page Request');\n page._startRenderPage(data.transparency, data.intent);\n }, this);\n\n messageHandler.on('RenderPageChunk', function transportRender(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n var page = this.pageCache[data.pageIndex];\n\n page._renderPageChunk(data.operatorList, data.intent);\n }, this);\n\n messageHandler.on('commonobj', function transportObj(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n\n var id = data[0];\n var type = data[1];\n if (this.commonObjs.hasData(id)) {\n return;\n }\n\n switch (type) {\n case 'Font':\n var exportedData = data[2];\n\n var font;\n if ('error' in exportedData) {\n var error = exportedData.error;\n warn('Error during font loading: ' + error);\n this.commonObjs.resolve(id, error);\n break;\n } else {\n font = new FontFaceObject(exportedData);\n }\n\n this.fontLoader.bind(\n [font],\n function fontReady(fontObjs) {\n this.commonObjs.resolve(id, font);\n }.bind(this)\n );\n break;\n case 'FontPath':\n this.commonObjs.resolve(id, data[2]);\n break;\n default:\n error('Got unknown common object type ' + type);\n }\n }, this);\n\n messageHandler.on('obj', function transportObj(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n\n var id = data[0];\n var pageIndex = data[1];\n var type = data[2];\n var pageProxy = this.pageCache[pageIndex];\n var imageData;\n if (pageProxy.objs.hasData(id)) {\n return;\n }\n\n switch (type) {\n case 'JpegStream':\n imageData = data[3];\n loadJpegStream(id, imageData, pageProxy.objs);\n break;\n case 'Image':\n imageData = data[3];\n pageProxy.objs.resolve(id, imageData);\n\n // heuristics that will allow not to store large data\n var MAX_IMAGE_SIZE_TO_STORE = 8000000;\n if (imageData && 'data' in imageData &&\n imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {\n pageProxy.cleanupAfterRender = true;\n }\n break;\n default:\n error('Got unknown object type ' + type);\n }\n }, this);\n\n messageHandler.on('DocProgress', function transportDocProgress(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n\n var loadingTask = this.loadingTask;\n if (loadingTask.onProgress) {\n loadingTask.onProgress({\n loaded: data.loaded,\n total: data.total\n });\n }\n }, this);\n\n messageHandler.on('PageError', function transportError(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n\n var page = this.pageCache[data.pageNum - 1];\n var intentState = page.intentStates[data.intent];\n if (intentState.displayReadyCapability) {\n intentState.displayReadyCapability.reject(data.error);\n } else {\n error(data.error);\n }\n }, this);\n\n messageHandler.on('UnsupportedFeature',\n function transportUnsupportedFeature(data) {\n if (this.destroyed) {\n return; // Ignore any pending requests if the worker was terminated.\n }\n var featureId = data.featureId;\n var loadingTask = this.loadingTask;\n if (loadingTask.onUnsupportedFeature) {\n loadingTask.onUnsupportedFeature(featureId);\n }\n PDFJS.UnsupportedManager.notify(featureId);\n }, this);\n\n messageHandler.on('JpegDecode', function(data) {\n if (this.destroyed) {\n return Promise.reject('Worker was terminated');\n }\n\n var imageUrl = data[0];\n var components = data[1];\n if (components !== 3 && components !== 1) {\n return Promise.reject(\n new Error('Only 3 components or 1 component can be returned'));\n }\n\n return new Promise(function (resolve, reject) {\n var img = new Image();\n img.onload = function () {\n var width = img.width;\n var height = img.height;\n var size = width * height;\n var rgbaLength = size * 4;\n var buf = new Uint8Array(size * components);\n var tmpCanvas = createScratchCanvas(width, height);\n var tmpCtx = tmpCanvas.getContext('2d');\n tmpCtx.drawImage(img, 0, 0);\n var data = tmpCtx.getImageData(0, 0, width, height).data;\n var i, j;\n\n if (components === 3) {\n for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {\n buf[j] = data[i];\n buf[j + 1] = data[i + 1];\n buf[j + 2] = data[i + 2];\n }\n } else if (components === 1) {\n for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {\n buf[j] = data[i];\n }\n }\n resolve({ data: buf, width: width, height: height});\n };\n img.onerror = function () {\n reject(new Error('JpegDecode failed to load image'));\n };\n img.src = imageUrl;\n });\n }, this);\n },\n\n getData: function WorkerTransport_getData() {\n return this.messageHandler.sendWithPromise('GetData', null);\n },\n\n getPage: function WorkerTransport_getPage(pageNumber, capability) {\n if (pageNumber <= 0 || pageNumber > this.numPages ||\n (pageNumber|0) !== pageNumber) {\n return Promise.reject(new Error('Invalid page request'));\n }\n\n var pageIndex = pageNumber - 1;\n if (pageIndex in this.pagePromises) {\n return this.pagePromises[pageIndex];\n }\n var promise = this.messageHandler.sendWithPromise('GetPage', {\n pageIndex: pageIndex\n }).then(function (pageInfo) {\n if (this.destroyed) {\n throw new Error('Transport destroyed');\n }\n var page = new PDFPageProxy(pageIndex, pageInfo, this);\n this.pageCache[pageIndex] = page;\n return page;\n }.bind(this));\n this.pagePromises[pageIndex] = promise;\n return promise;\n },\n\n getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {\n return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });\n },\n\n getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {\n return this.messageHandler.sendWithPromise('GetAnnotations', {\n pageIndex: pageIndex,\n intent: intent,\n });\n },\n\n getDestinations: function WorkerTransport_getDestinations() {\n return this.messageHandler.sendWithPromise('GetDestinations', null);\n },\n\n getDestination: function WorkerTransport_getDestination(id) {\n return this.messageHandler.sendWithPromise('GetDestination', { id: id });\n },\n\n getAttachments: function WorkerTransport_getAttachments() {\n return this.messageHandler.sendWithPromise('GetAttachments', null);\n },\n\n getJavaScript: function WorkerTransport_getJavaScript() {\n return this.messageHandler.sendWithPromise('GetJavaScript', null);\n },\n\n getOutline: function WorkerTransport_getOutline() {\n return this.messageHandler.sendWithPromise('GetOutline', null);\n },\n\n getMetadata: function WorkerTransport_getMetadata() {\n return this.messageHandler.sendWithPromise('GetMetadata', null).\n then(function transportMetadata(results) {\n return {\n info: results[0],\n metadata: (results[1] ? new Metadata(results[1]) : null)\n };\n });\n },\n\n getStats: function WorkerTransport_getStats() {\n return this.messageHandler.sendWithPromise('GetStats', null);\n },\n\n startCleanup: function WorkerTransport_startCleanup() {\n this.messageHandler.sendWithPromise('Cleanup', null).\n then(function endCleanup() {\n for (var i = 0, ii = this.pageCache.length; i < ii; i++) {\n var page = this.pageCache[i];\n if (page) {\n page.cleanup();\n }\n }\n this.commonObjs.clear();\n this.fontLoader.clear();\n }.bind(this));\n }\n };\n return WorkerTransport;\n\n})();\n\n/**\n * A PDF document and page is built of many objects. E.g. there are objects\n * for fonts, images, rendering code and such. These objects might get processed\n * inside of a worker. The `PDFObjects` implements some basic functions to\n * manage these objects.\n * @ignore\n */\nvar PDFObjects = (function PDFObjectsClosure() {\n function PDFObjects() {\n this.objs = {};\n }\n\n PDFObjects.prototype = {\n /**\n * Internal function.\n * Ensures there is an object defined for `objId`.\n */\n ensureObj: function PDFObjects_ensureObj(objId) {\n if (this.objs[objId]) {\n return this.objs[objId];\n }\n\n var obj = {\n capability: createPromiseCapability(),\n data: null,\n resolved: false\n };\n this.objs[objId] = obj;\n\n return obj;\n },\n\n /**\n * If called *without* callback, this returns the data of `objId` but the\n * object needs to be resolved. If it isn't, this function throws.\n *\n * If called *with* a callback, the callback is called with the data of the\n * object once the object is resolved. That means, if you call this\n * function and the object is already resolved, the callback gets called\n * right away.\n */\n get: function PDFObjects_get(objId, callback) {\n // If there is a callback, then the get can be async and the object is\n // not required to be resolved right now\n if (callback) {\n this.ensureObj(objId).capability.promise.then(callback);\n return null;\n }\n\n // If there isn't a callback, the user expects to get the resolved data\n // directly.\n var obj = this.objs[objId];\n\n // If there isn't an object yet or the object isn't resolved, then the\n // data isn't ready yet!\n if (!obj || !obj.resolved) {\n error('Requesting object that isn\\'t resolved yet ' + objId);\n }\n\n return obj.data;\n },\n\n /**\n * Resolves the object `objId` with optional `data`.\n */\n resolve: function PDFObjects_resolve(objId, data) {\n var obj = this.ensureObj(objId);\n\n obj.resolved = true;\n obj.data = data;\n obj.capability.resolve(data);\n },\n\n isResolved: function PDFObjects_isResolved(objId) {\n var objs = this.objs;\n\n if (!objs[objId]) {\n return false;\n } else {\n return objs[objId].resolved;\n }\n },\n\n hasData: function PDFObjects_hasData(objId) {\n return this.isResolved(objId);\n },\n\n /**\n * Returns the data of `objId` if object exists, null otherwise.\n */\n getData: function PDFObjects_getData(objId) {\n var objs = this.objs;\n if (!objs[objId] || !objs[objId].resolved) {\n return null;\n } else {\n return objs[objId].data;\n }\n },\n\n clear: function PDFObjects_clear() {\n this.objs = {};\n }\n };\n return PDFObjects;\n})();\n\n/**\n * Allows controlling of the rendering tasks.\n * @class\n * @alias RenderTask\n */\nvar RenderTask = (function RenderTaskClosure() {\n function RenderTask(internalRenderTask) {\n this._internalRenderTask = internalRenderTask;\n\n /**\n * Callback for incremental rendering -- a function that will be called\n * each time the rendering is paused. To continue rendering call the\n * function that is the first argument to the callback.\n * @type {function}\n */\n this.onContinue = null;\n }\n\n RenderTask.prototype = /** @lends RenderTask.prototype */ {\n /**\n * Promise for rendering task completion.\n * @return {Promise}\n */\n get promise() {\n return this._internalRenderTask.capability.promise;\n },\n\n /**\n * Cancels the rendering task. If the task is currently rendering it will\n * not be cancelled until graphics pauses with a timeout. The promise that\n * this object extends will resolved when cancelled.\n */\n cancel: function RenderTask_cancel() {\n this._internalRenderTask.cancel();\n },\n\n /**\n * Registers callbacks to indicate the rendering task completion.\n *\n * @param {function} onFulfilled The callback for the rendering completion.\n * @param {function} onRejected The callback for the rendering failure.\n * @return {Promise} A promise that is resolved after the onFulfilled or\n * onRejected callback.\n */\n then: function RenderTask_then(onFulfilled, onRejected) {\n return this.promise.then.apply(this.promise, arguments);\n }\n };\n\n return RenderTask;\n})();\n\n/**\n * For internal use only.\n * @ignore\n */\nvar InternalRenderTask = (function InternalRenderTaskClosure() {\n\n function InternalRenderTask(callback, params, objs, commonObjs, operatorList,\n pageNumber) {\n this.callback = callback;\n this.params = params;\n this.objs = objs;\n this.commonObjs = commonObjs;\n this.operatorListIdx = null;\n this.operatorList = operatorList;\n this.pageNumber = pageNumber;\n this.running = false;\n this.graphicsReadyCallback = null;\n this.graphicsReady = false;\n this.useRequestAnimationFrame = false;\n this.cancelled = false;\n this.capability = createPromiseCapability();\n this.task = new RenderTask(this);\n // caching this-bound methods\n this._continueBound = this._continue.bind(this);\n this._scheduleNextBound = this._scheduleNext.bind(this);\n this._nextBound = this._next.bind(this);\n }\n\n InternalRenderTask.prototype = {\n\n initalizeGraphics:\n function InternalRenderTask_initalizeGraphics(transparency) {\n\n if (this.cancelled) {\n return;\n }\n if (PDFJS.pdfBug && 'StepperManager' in globalScope &&\n globalScope.StepperManager.enabled) {\n this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);\n this.stepper.init(this.operatorList);\n this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();\n }\n\n var params = this.params;\n this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,\n this.objs, params.imageLayer);\n\n this.gfx.beginDrawing(params.transform, params.viewport, transparency);\n this.operatorListIdx = 0;\n this.graphicsReady = true;\n if (this.graphicsReadyCallback) {\n this.graphicsReadyCallback();\n }\n },\n\n cancel: function InternalRenderTask_cancel() {\n this.running = false;\n this.cancelled = true;\n this.callback('cancelled');\n },\n\n operatorListChanged: function InternalRenderTask_operatorListChanged() {\n if (!this.graphicsReady) {\n if (!this.graphicsReadyCallback) {\n this.graphicsReadyCallback = this._continueBound;\n }\n return;\n }\n\n if (this.stepper) {\n this.stepper.updateOperatorList(this.operatorList);\n }\n\n if (this.running) {\n return;\n }\n this._continue();\n },\n\n _continue: function InternalRenderTask__continue() {\n this.running = true;\n if (this.cancelled) {\n return;\n }\n if (this.task.onContinue) {\n this.task.onContinue.call(this.task, this._scheduleNextBound);\n } else {\n this._scheduleNext();\n }\n },\n\n _scheduleNext: function InternalRenderTask__scheduleNext() {\n if (this.useRequestAnimationFrame) {\n window.requestAnimationFrame(this._nextBound);\n } else {\n Promise.resolve(undefined).then(this._nextBound);\n }\n },\n\n _next: function InternalRenderTask__next() {\n if (this.cancelled) {\n return;\n }\n this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,\n this.operatorListIdx,\n this._continueBound,\n this.stepper);\n if (this.operatorListIdx === this.operatorList.argsArray.length) {\n this.running = false;\n if (this.operatorList.lastChunk) {\n this.gfx.endDrawing();\n this.callback();\n }\n }\n }\n\n };\n\n return InternalRenderTask;\n})();\n\n/**\n * (Deprecated) Global observer of unsupported feature usages. Use\n * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.\n */\nPDFJS.UnsupportedManager = (function UnsupportedManagerClosure() {\n var listeners = [];\n return {\n listen: function (cb) {\n deprecated('Global UnsupportedManager.listen is used: ' +\n ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');\n listeners.push(cb);\n },\n notify: function (featureId) {\n for (var i = 0, ii = listeners.length; i < ii; i++) {\n listeners[i](featureId);\n }\n }\n };\n})();\n\nexports.getDocument = PDFJS.getDocument;\nexports.PDFDataRangeTransport = PDFDataRangeTransport;\nexports.PDFDocumentProxy = PDFDocumentProxy;\nexports.PDFPageProxy = PDFPageProxy;\n}));\n\n\n }).call(pdfjsLibs);\n\n exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS;\n\n exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;\n exports.PDFDataRangeTransport =\n pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;\n exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;\n exports.AnnotationLayer =\n pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;\n exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;\n exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;\n exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;\n exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;\n exports.UnexpectedResponseException =\n pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;\n}));\n\n\n"},"repo_name":{"kind":"string","value":"sreym/cdnjs"},"path":{"kind":"string","value":"ajax/libs/pdf.js/1.3.177/pdf.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":313996,"string":"313,996"}}},{"rowIdx":115086591,"cells":{"code":{"kind":"string","value":"Submitting Issues\n=================\n\nIf you are submitting a bug with moment, please create a [jsfiddle](http://jsfiddle.net/) demonstrating the issue.\n\nContributing\n============\n\nTo contribute, fork the library and install these npm packages.\n\n npm install jshint uglify-js nodeunit\n\nYou can add tests to the files in `/test/moment` or add a new test file if you are adding a new feature.\n\nTo run the tests, do `make test` to run all tests, `make test-moment` to test the core library, and `make test-lang` to test all the languages.\n\nTo check the filesize, you can use `make size`.\n\nTo minify all the files, use `make moment` to minify moment, `make langs` to minify all the lang files, or just `make` to minfy everything.\n\nIf your code passes the unit tests (including the ones you wrote), submit a pull request.\n\nSubmitting pull requests\n========================\n\nMoment.js now uses [git-flow](https://github.com/nvie/gitflow). If you're not familiar with git-flow, please read up on it, you'll be glad you did.\n\nWhen submitting new features, please create a new feature branch using `git flow feature start ` and submit the pull request to the `develop` branch.\n\nPull requests for enhancements for features should be submitted to the `develop` branch as well.\n\nWhen submitting a bugfix, please check if there is an existing bugfix branch. If the latest stable version is `1.5.0`, the bugfix branch would be `hotfix/1.5.1`. All pull requests for bug fixes should be on a `hotfix` branch, unless the bug fix depends on a new feature.\n\nThe `master` branch should always have the latest stable version. When bugfix or minor releases are needed, the develop/hotfix branch will be merged into master and released.\n"},"repo_name":{"kind":"string","value":"ninjablocks/ninja-sentinel"},"path":{"kind":"string","value":"yeoman/components/moment/CONTRIBUTING.md"},"language":{"kind":"string","value":"Markdown"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1722,"string":"1,722"}}},{"rowIdx":115086592,"cells":{"code":{"kind":"string","value":"\"\"\"\nIntegration tests for third_party_auth LTI auth providers\n\"\"\"\nimport unittest\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.urlresolvers import reverse\nfrom oauthlib.oauth1.rfc5849 import Client, SIGNATURE_TYPE_BODY\nfrom third_party_auth.tests import testutil\n\nFORM_ENCODED = 'application/x-www-form-urlencoded'\n\nLTI_CONSUMER_KEY = 'consumer'\nLTI_CONSUMER_SECRET = 'secret'\nLTI_TPA_LOGIN_URL = 'http://testserver/auth/login/lti/'\nLTI_TPA_COMPLETE_URL = 'http://testserver/auth/complete/lti/'\nOTHER_LTI_CONSUMER_KEY = 'settings-consumer'\nOTHER_LTI_CONSUMER_SECRET = 'secret2'\nLTI_USER_ID = 'lti_user_id'\nEDX_USER_ID = 'test_user'\nEMAIL = 'lti_user@example.com'\n\n\n@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')\nclass IntegrationTestLTI(testutil.TestCase):\n \"\"\"\n Integration tests for third_party_auth LTI auth providers\n \"\"\"\n\n def setUp(self):\n super(IntegrationTestLTI, self).setUp()\n self.client.defaults['SERVER_NAME'] = 'testserver'\n self.url_prefix = 'http://testserver'\n self.configure_lti_provider(\n name='Other Tool Consumer 1', enabled=True,\n lti_consumer_key='other1',\n lti_consumer_secret='secret1',\n lti_max_timestamp_age=10,\n )\n self.configure_lti_provider(\n name='LTI Test Tool Consumer', enabled=True,\n lti_consumer_key=LTI_CONSUMER_KEY,\n lti_consumer_secret=LTI_CONSUMER_SECRET,\n lti_max_timestamp_age=10,\n )\n self.configure_lti_provider(\n name='Tool Consumer with Secret in Settings', enabled=True,\n lti_consumer_key=OTHER_LTI_CONSUMER_KEY,\n lti_consumer_secret='',\n lti_max_timestamp_age=10,\n )\n self.lti = Client(\n client_key=LTI_CONSUMER_KEY,\n client_secret=LTI_CONSUMER_SECRET,\n signature_type=SIGNATURE_TYPE_BODY,\n )\n\n def test_lti_login(self):\n # The user initiates a login from an external site\n (uri, _headers, body) = self.lti.sign(\n uri=LTI_TPA_LOGIN_URL, http_method='POST',\n headers={'Content-Type': FORM_ENCODED},\n body={\n 'user_id': LTI_USER_ID,\n 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll',\n }\n )\n login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)\n # The user should be redirected to the registration form\n self.assertEqual(login_response.status_code, 302)\n self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))\n register_response = self.client.get(login_response['Location'])\n self.assertEqual(register_response.status_code, 200)\n self.assertIn('\"currentProvider\": \"LTI Test Tool Consumer\"', register_response.content)\n self.assertIn('\"errorMessage\": null', register_response.content)\n\n # Now complete the form:\n ajax_register_response = self.client.post(\n reverse('user_api_registration'),\n {\n 'email': EMAIL,\n 'name': 'Myself',\n 'username': EDX_USER_ID,\n 'honor_code': True,\n }\n )\n self.assertEqual(ajax_register_response.status_code, 200)\n continue_response = self.client.get(LTI_TPA_COMPLETE_URL)\n # The user should be redirected to the finish_auth view which will enroll them.\n # FinishAuthView.js reads the URL parameters directly from $.url\n self.assertEqual(continue_response.status_code, 302)\n self.assertEqual(\n continue_response['Location'],\n 'http://testserver/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll'\n )\n\n # Now check that we can login again\n self.client.logout()\n self.verify_user_email(EMAIL)\n (uri, _headers, body) = self.lti.sign(\n uri=LTI_TPA_LOGIN_URL, http_method='POST',\n headers={'Content-Type': FORM_ENCODED},\n body={'user_id': LTI_USER_ID}\n )\n login_2_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)\n # The user should be redirected to the dashboard\n self.assertEqual(login_2_response.status_code, 302)\n self.assertEqual(login_2_response['Location'], LTI_TPA_COMPLETE_URL)\n continue_2_response = self.client.get(login_2_response['Location'])\n self.assertEqual(continue_2_response.status_code, 302)\n self.assertTrue(continue_2_response['Location'].endswith(reverse('dashboard')))\n\n # Check that the user was created correctly\n user = User.objects.get(email=EMAIL)\n self.assertEqual(user.username, EDX_USER_ID)\n\n def test_reject_initiating_login(self):\n response = self.client.get(LTI_TPA_LOGIN_URL)\n self.assertEqual(response.status_code, 405) # Not Allowed\n\n def test_reject_bad_login(self):\n login_response = self.client.post(\n path=LTI_TPA_LOGIN_URL, content_type=FORM_ENCODED,\n data=\"invalid=login\"\n )\n # The user should be redirected to the login page with an error message\n # (auth_entry defaults to login for this provider)\n self.assertEqual(login_response.status_code, 302)\n self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))\n error_response = self.client.get(login_response['Location'])\n self.assertIn(\n 'Authentication failed: LTI parameters could not be validated.',\n error_response.content\n )\n\n def test_can_load_consumer_secret_from_settings(self):\n lti = Client(\n client_key=OTHER_LTI_CONSUMER_KEY,\n client_secret=OTHER_LTI_CONSUMER_SECRET,\n signature_type=SIGNATURE_TYPE_BODY,\n )\n (uri, _headers, body) = lti.sign(\n uri=LTI_TPA_LOGIN_URL, http_method='POST',\n headers={'Content-Type': FORM_ENCODED},\n body={\n 'user_id': LTI_USER_ID,\n 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll',\n }\n )\n with self.settings(SOCIAL_AUTH_LTI_CONSUMER_SECRETS={OTHER_LTI_CONSUMER_KEY: OTHER_LTI_CONSUMER_SECRET}):\n login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)\n # The user should be redirected to the registration form\n self.assertEqual(login_response.status_code, 302)\n self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))\n register_response = self.client.get(login_response['Location'])\n self.assertEqual(register_response.status_code, 200)\n self.assertIn(\n '\"currentProvider\": \"Tool Consumer with Secret in Settings\"',\n register_response.content\n )\n self.assertIn('\"errorMessage\": null', register_response.content)\n"},"repo_name":{"kind":"string","value":"solashirai/edx-platform"},"path":{"kind":"string","value":"common/djangoapps/third_party_auth/tests/specs/test_lti.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"agpl-3.0"},"size":{"kind":"number","value":7079,"string":"7,079"}}},{"rowIdx":115086593,"cells":{"code":{"kind":"string","value":"/*\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.facebook.presto.sql.planner.sanity;\n\nimport com.facebook.presto.Session;\nimport com.facebook.presto.metadata.Metadata;\nimport com.facebook.presto.spi.type.Type;\nimport com.facebook.presto.sql.parser.SqlParser;\nimport com.facebook.presto.sql.planner.ExpressionExtractor;\nimport com.facebook.presto.sql.planner.Symbol;\nimport com.facebook.presto.sql.planner.plan.PlanNode;\nimport com.facebook.presto.sql.tree.DefaultTraversalVisitor;\nimport com.facebook.presto.sql.tree.Expression;\nimport com.facebook.presto.sql.tree.SubqueryExpression;\n\nimport java.util.Map;\n\nimport static java.lang.String.format;\n\npublic final class NoSubqueryExpressionLeftChecker\n implements PlanSanityChecker.Checker\n{\n @Override\n public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map types)\n {\n for (Expression expression : ExpressionExtractor.extractExpressions(plan)) {\n new DefaultTraversalVisitor()\n {\n @Override\n protected Void visitSubqueryExpression(SubqueryExpression node, Void context)\n {\n throw new IllegalStateException(format(\"Unexpected subquery expression in logical plan: %s\", node));\n }\n }.process(expression, null);\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"marsorp/blog"},"path":{"kind":"string","value":"presto166/presto-main/src/main/java/com/facebook/presto/sql/planner/sanity/NoSubqueryExpressionLeftChecker.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":1903,"string":"1,903"}}},{"rowIdx":115086594,"cells":{"code":{"kind":"string","value":"var FormData = require('form-data');\nfunction form(obj) {\n var form = new FormData();\n if (obj) {\n Object.keys(obj).forEach(function (name) {\n form.append(name, obj[name]);\n });\n }\n return form;\n}\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = form;\n//# sourceMappingURL=form.js.map"},"repo_name":{"kind":"string","value":"carmine/northshore"},"path":{"kind":"string","value":"ui/node_modules/popsicle/dist/form.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":353,"string":"353"}}},{"rowIdx":115086595,"cells":{"code":{"kind":"string","value":"if (!self.GLOBAL || self.GLOBAL.isWindow()) {\n test(() => {\n assert_equals(document.title, \"foo\");\n }, ' exists');\n\n test(() => {\n assert_equals(document.querySelectorAll(\"meta[name=timeout][content=long]\").length, 1);\n }, '<meta name=timeout> exists');\n}\n\nscripts.push('expect-title-meta.js');\n"},"repo_name":{"kind":"string","value":"scheib/chromium"},"path":{"kind":"string","value":"third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":312,"string":"312"}}},{"rowIdx":115086596,"cells":{"code":{"kind":"string","value":"\"\"\"\nBy specifying the 'proxy' Meta attribute, model subclasses can specify that\nthey will take data directly from the table of their base class table rather\nthan using a new table of their own. This allows them to act as simple proxies,\nproviding a modified interface to the data from the base class.\n\"\"\"\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\n# A couple of managers for testing managing overriding in proxy model cases.\n\n\nclass PersonManager(models.Manager):\n def get_queryset(self):\n return super(PersonManager, self).get_queryset().exclude(name=\"fred\")\n\n\nclass SubManager(models.Manager):\n def get_queryset(self):\n return super(SubManager, self).get_queryset().exclude(name=\"wilma\")\n\n\n@python_2_unicode_compatible\nclass Person(models.Model):\n \"\"\"\n A simple concrete base class.\n \"\"\"\n name = models.CharField(max_length=50)\n\n objects = PersonManager()\n\n def __str__(self):\n return self.name\n\n\nclass Abstract(models.Model):\n \"\"\"\n A simple abstract base class, to be used for error checking.\n \"\"\"\n data = models.CharField(max_length=10)\n\n class Meta:\n abstract = True\n\n\nclass MyPerson(Person):\n \"\"\"\n A proxy subclass, this should not get a new table. Overrides the default\n manager.\n \"\"\"\n class Meta:\n proxy = True\n ordering = [\"name\"]\n permissions = (\n (\"display_users\", \"May display users information\"),\n )\n\n objects = SubManager()\n other = PersonManager()\n\n def has_special_name(self):\n return self.name.lower() == \"special\"\n\n\nclass ManagerMixin(models.Model):\n excluder = SubManager()\n\n class Meta:\n abstract = True\n\n\nclass OtherPerson(Person, ManagerMixin):\n \"\"\"\n A class with the default manager from Person, plus an secondary manager.\n \"\"\"\n class Meta:\n proxy = True\n ordering = [\"name\"]\n\n\nclass StatusPerson(MyPerson):\n \"\"\"\n A non-proxy subclass of a proxy, it should get a new table.\n \"\"\"\n status = models.CharField(max_length=80)\n\n# We can even have proxies of proxies (and subclass of those).\n\n\nclass MyPersonProxy(MyPerson):\n class Meta:\n proxy = True\n\n\nclass LowerStatusPerson(MyPersonProxy):\n status = models.CharField(max_length=80)\n\n\n@python_2_unicode_compatible\nclass User(models.Model):\n name = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\n\nclass UserProxy(User):\n class Meta:\n proxy = True\n\n\nclass UserProxyProxy(UserProxy):\n class Meta:\n proxy = True\n\n# We can still use `select_related()` to include related models in our querysets.\n\n\nclass Country(models.Model):\n name = models.CharField(max_length=50)\n\n\n@python_2_unicode_compatible\nclass State(models.Model):\n name = models.CharField(max_length=50)\n country = models.ForeignKey(Country, models.CASCADE)\n\n def __str__(self):\n return self.name\n\n\nclass StateProxy(State):\n class Meta:\n proxy = True\n\n# Proxy models still works with filters (on related fields)\n# and select_related, even when mixed with model inheritance\n\n\n@python_2_unicode_compatible\nclass BaseUser(models.Model):\n name = models.CharField(max_length=255)\n\n def __str__(self):\n return ':'.join((self.__class__.__name__, self.name,))\n\n\nclass TrackerUser(BaseUser):\n status = models.CharField(max_length=50)\n\n\nclass ProxyTrackerUser(TrackerUser):\n class Meta:\n proxy = True\n\n\n@python_2_unicode_compatible\nclass Issue(models.Model):\n summary = models.CharField(max_length=255)\n assignee = models.ForeignKey(ProxyTrackerUser, models.CASCADE, related_name='issues')\n\n def __str__(self):\n return ':'.join((self.__class__.__name__, self.summary,))\n\n\nclass Bug(Issue):\n version = models.CharField(max_length=50)\n reporter = models.ForeignKey(BaseUser, models.CASCADE)\n\n\nclass ProxyBug(Bug):\n \"\"\"\n Proxy of an inherited class\n \"\"\"\n class Meta:\n proxy = True\n\n\nclass ProxyProxyBug(ProxyBug):\n \"\"\"\n A proxy of proxy model with related field\n \"\"\"\n class Meta:\n proxy = True\n\n\nclass Improvement(Issue):\n \"\"\"\n A model that has relation to a proxy model\n or to a proxy of proxy model\n \"\"\"\n version = models.CharField(max_length=50)\n reporter = models.ForeignKey(ProxyTrackerUser, models.CASCADE)\n associated_bug = models.ForeignKey(ProxyProxyBug, models.CASCADE)\n\n\nclass ProxyImprovement(Improvement):\n class Meta:\n proxy = True\n"},"repo_name":{"kind":"string","value":"benjaminjkraft/django"},"path":{"kind":"string","value":"tests/proxy_models/models.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":4514,"string":"4,514"}}},{"rowIdx":115086597,"cells":{"code":{"kind":"string","value":"/**\n * \\file bignum.h\n *\n * \\brief Multi-precision integer library\n *\n * Copyright (C) 2006-2010, Brainspark B.V.\n *\n * This file is part of PolarSSL (http://www.polarssl.org)\n * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>\n *\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\n#ifndef POLARSSL_BIGNUM_H\n#define POLARSSL_BIGNUM_H\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"config.h\"\n\n#define POLARSSL_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */\n#define POLARSSL_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */\n#define POLARSSL_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */\n#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The buffer is too small to write to. */\n#define POLARSSL_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */\n#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */\n#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */\n#define POLARSSL_ERR_MPI_MALLOC_FAILED -0x0010 /**< Memory allocation failed. */\n\n#define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup\n\n/*\n * Maximum size MPIs are allowed to grow to in number of limbs.\n */\n#define POLARSSL_MPI_MAX_LIMBS 10000\n\n/*\n * Maximum window size used for modular exponentiation. Default: 6\n * Minimum value: 1. Maximum value: 6.\n *\n * Result is an array of ( 2 << POLARSSL_MPI_WINDOW_SIZE ) MPIs used\n * for the sliding window calculation. (So 64 by default)\n *\n * Reduction in size, reduces speed.\n */\n#define POLARSSL_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */\n\n/*\n * Maximum size of MPIs allowed in bits and bytes for user-MPIs.\n * ( Default: 512 bytes => 4096 bits )\n *\n * Note: Calculations can results temporarily in larger MPIs. So the number\n * of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher.\n */\n#define POLARSSL_MPI_MAX_SIZE 512 /**< Maximum number of bytes for usable MPIs. */\n#define POLARSSL_MPI_MAX_BITS ( 8 * POLARSSL_MPI_MAX_SIZE ) /**< Maximum number of bits for usable MPIs. */\n\n/*\n * When reading from files with mpi_read_file() the buffer should have space\n * for a (short) label, the MPI (in the provided radix), the newline\n * characters and the '\\0'.\n *\n * By default we assume at least a 10 char label, a minimum radix of 10\n * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).\n */\n#define POLARSSL_MPI_READ_BUFFER_SIZE 1250 \n\n/*\n * Define the base integer type, architecture-wise\n */\n#if defined(POLARSSL_HAVE_INT8)\ntypedef signed char t_sint;\ntypedef unsigned char t_uint;\ntypedef unsigned short t_udbl;\n#else\n#if defined(POLARSSL_HAVE_INT16)\ntypedef signed short t_sint;\ntypedef unsigned short t_uint;\ntypedef unsigned long t_udbl;\n#else\n typedef signed long t_sint;\n typedef unsigned long t_uint;\n #if defined(_MSC_VER) && defined(_M_IX86)\n typedef unsigned __int64 t_udbl;\n #else\n #if defined(__GNUC__) && ( \\\n defined(__amd64__) || defined(__x86_64__) || \\\n defined(__ppc64__) || defined(__powerpc64__) || \\\n defined(__ia64__) || defined(__alpha__) || \\\n (defined(__sparc__) && defined(__arch64__)) || \\\n defined(__s390x__) )\n typedef unsigned int t_udbl __attribute__((mode(TI)));\n #define POLARSSL_HAVE_LONGLONG\n #else\n #if defined(POLARSSL_HAVE_LONGLONG)\n typedef unsigned long long t_udbl;\n #endif\n #endif\n #endif\n#endif\n#endif\n\n/**\n * \\brief MPI structure\n */\ntypedef struct\n{\n int s; /*!< integer sign */\n size_t n; /*!< total # of limbs */\n t_uint *p; /*!< pointer to limbs */\n}\nmpi;\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/**\n * \\brief Initialize one MPI\n *\n * \\param X One MPI to initialize.\n */\nvoid mpi_init( mpi *X );\n\n/**\n * \\brief Unallocate one MPI\n *\n * \\param X One MPI to unallocate.\n */\nvoid mpi_free( mpi *X );\n\n/**\n * \\brief Enlarge to the specified number of limbs\n *\n * \\param X MPI to grow\n * \\param nblimbs The target number of limbs\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_grow( mpi *X, size_t nblimbs );\n\n/**\n * \\brief Copy the contents of Y into X\n *\n * \\param X Destination MPI\n * \\param Y Source MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_copy( mpi *X, const mpi *Y );\n\n/**\n * \\brief Swap the contents of X and Y\n *\n * \\param X First MPI value\n * \\param Y Second MPI value\n */\nvoid mpi_swap( mpi *X, mpi *Y );\n\n/**\n * \\brief Set value from integer\n *\n * \\param X MPI to set\n * \\param z Value to use\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_lset( mpi *X, t_sint z );\n\n/*\n * \\brief Get a specific bit from X\n *\n * \\param X MPI to use\n * \\param pos Zero-based index of the bit in X\n *\n * \\return Either a 0 or a 1\n */\nint mpi_get_bit( mpi *X, size_t pos );\n\n/*\n * \\brief Set a bit of X to a specific value of 0 or 1\n *\n * \\note Will grow X if necessary to set a bit to 1 in a not yet\n * existing limb. Will not grow if bit should be set to 0\n *\n * \\param X MPI to use\n * \\param pos Zero-based index of the bit in X\n * \\param val The value to set the bit to (0 or 1)\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1\n */\nint mpi_set_bit( mpi *X, size_t pos, unsigned char val );\n\n/**\n * \\brief Return the number of least significant bits\n *\n * \\param X MPI to use\n */\nsize_t mpi_lsb( const mpi *X );\n\n/**\n * \\brief Return the number of most significant bits\n *\n * \\param X MPI to use\n */\nsize_t mpi_msb( const mpi *X );\n\n/**\n * \\brief Return the total size in bytes\n *\n * \\param X MPI to use\n */\nsize_t mpi_size( const mpi *X );\n\n/**\n * \\brief Import from an ASCII string\n *\n * \\param X Destination MPI\n * \\param radix Input numeric base\n * \\param s Null-terminated string buffer\n *\n * \\return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code\n */\nint mpi_read_string( mpi *X, int radix, const char *s );\n\n/**\n * \\brief Export into an ASCII string\n *\n * \\param X Source MPI\n * \\param radix Output numeric base\n * \\param s String buffer\n * \\param slen String buffer size\n *\n * \\return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code.\n * *slen is always updated to reflect the amount\n * of data that has (or would have) been written.\n *\n * \\note Call this function with *slen = 0 to obtain the\n * minimum required buffer size in *slen.\n */\nint mpi_write_string( const mpi *X, int radix, char *s, size_t *slen );\n\n/**\n * \\brief Read X from an opened file\n *\n * \\param X Destination MPI\n * \\param radix Input numeric base\n * \\param fin Input file handle\n *\n * \\return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if\n * the file read buffer is too small or a\n * POLARSSL_ERR_MPI_XXX error code\n */\nint mpi_read_file( mpi *X, int radix, FILE *fin );\n\n/**\n * \\brief Write X into an opened file, or stdout if fout is NULL\n *\n * \\param p Prefix, can be NULL\n * \\param X Source MPI\n * \\param radix Output numeric base\n * \\param fout Output file handle (can be NULL)\n *\n * \\return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code\n *\n * \\note Set fout == NULL to print X on the console.\n */\nint mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout );\n\n/**\n * \\brief Import X from unsigned binary data, big endian\n *\n * \\param X Destination MPI\n * \\param buf Input buffer\n * \\param buflen Input buffer size\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen );\n\n/**\n * \\brief Export X into unsigned binary data, big endian\n *\n * \\param X Source MPI\n * \\param buf Output buffer\n * \\param buflen Output buffer size\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough\n */\nint mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen );\n\n/**\n * \\brief Left-shift: X <<= count\n *\n * \\param X MPI to shift\n * \\param count Amount to shift\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_shift_l( mpi *X, size_t count );\n\n/**\n * \\brief Right-shift: X >>= count\n *\n * \\param X MPI to shift\n * \\param count Amount to shift\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_shift_r( mpi *X, size_t count );\n\n/**\n * \\brief Compare unsigned values\n *\n * \\param X Left-hand MPI\n * \\param Y Right-hand MPI\n *\n * \\return 1 if |X| is greater than |Y|,\n * -1 if |X| is lesser than |Y| or\n * 0 if |X| is equal to |Y|\n */\nint mpi_cmp_abs( const mpi *X, const mpi *Y );\n\n/**\n * \\brief Compare signed values\n *\n * \\param X Left-hand MPI\n * \\param Y Right-hand MPI\n *\n * \\return 1 if X is greater than Y,\n * -1 if X is lesser than Y or\n * 0 if X is equal to Y\n */\nint mpi_cmp_mpi( const mpi *X, const mpi *Y );\n\n/**\n * \\brief Compare signed values\n *\n * \\param X Left-hand MPI\n * \\param z The integer value to compare to\n *\n * \\return 1 if X is greater than z,\n * -1 if X is lesser than z or\n * 0 if X is equal to z\n */\nint mpi_cmp_int( const mpi *X, t_sint z );\n\n/**\n * \\brief Unsigned addition: X = |A| + |B|\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_add_abs( mpi *X, const mpi *A, const mpi *B );\n\n/**\n * \\brief Unsigned substraction: X = |A| - |B|\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B is greater than A\n */\nint mpi_sub_abs( mpi *X, const mpi *A, const mpi *B );\n\n/**\n * \\brief Signed addition: X = A + B\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_add_mpi( mpi *X, const mpi *A, const mpi *B );\n\n/**\n * \\brief Signed substraction: X = A - B\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B );\n\n/**\n * \\brief Signed addition: X = A + b\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param b The integer value to add\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_add_int( mpi *X, const mpi *A, t_sint b );\n\n/**\n * \\brief Signed substraction: X = A - b\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param b The integer value to subtract\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_sub_int( mpi *X, const mpi *A, t_sint b );\n\n/**\n * \\brief Baseline multiplication: X = A * B\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B );\n\n/**\n * \\brief Baseline multiplication: X = A * b\n * Note: b is an unsigned integer type, thus\n * Negative values of b are ignored.\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param b The integer value to multiply with\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_mul_int( mpi *X, const mpi *A, t_sint b );\n\n/**\n * \\brief Division by mpi: A = Q * B + R\n *\n * \\param Q Destination MPI for the quotient\n * \\param R Destination MPI for the rest value\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0\n *\n * \\note Either Q or R can be NULL.\n */\nint mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B );\n\n/**\n * \\brief Division by int: A = Q * b + R\n *\n * \\param Q Destination MPI for the quotient\n * \\param R Destination MPI for the rest value\n * \\param A Left-hand MPI\n * \\param b Integer to divide by\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0\n *\n * \\note Either Q or R can be NULL.\n */\nint mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b );\n\n/**\n * \\brief Modulo: R = A mod B\n *\n * \\param R Destination MPI for the rest value\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0,\n * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0\n */\nint mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B );\n\n/**\n * \\brief Modulo: r = A mod b\n *\n * \\param r Destination t_uint\n * \\param A Left-hand MPI\n * \\param b Integer to divide by\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0,\n * POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0\n */\nint mpi_mod_int( t_uint *r, const mpi *A, t_sint b );\n\n/**\n * \\brief Sliding-window exponentiation: X = A^E mod N\n *\n * \\param X Destination MPI \n * \\param A Left-hand MPI\n * \\param E Exponent MPI\n * \\param N Modular MPI\n * \\param _RR Speed-up MPI used for recalculations\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or even\n *\n * \\note _RR is used to avoid re-computing R*R mod N across\n * multiple calls, which speeds up things a bit. It can\n * be set to NULL if the extra performance is unneeded.\n */\nint mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR );\n\n/**\n * \\brief Fill an MPI X with size bytes of random\n *\n * \\param X Destination MPI\n * \\param size Size in bytes\n * \\param f_rng RNG function\n * \\param p_rng RNG parameter\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_fill_random( mpi *X, size_t size,\n int (*f_rng)(void *, unsigned char *, size_t),\n void *p_rng );\n\n/**\n * \\brief Greatest common divisor: G = gcd(A, B)\n *\n * \\param G Destination MPI\n * \\param A Left-hand MPI\n * \\param B Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed\n */\nint mpi_gcd( mpi *G, const mpi *A, const mpi *B );\n\n/**\n * \\brief Modular inverse: X = A^-1 mod N\n *\n * \\param X Destination MPI\n * \\param A Left-hand MPI\n * \\param N Right-hand MPI\n *\n * \\return 0 if successful,\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or nil\n POLARSSL_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N\n */\nint mpi_inv_mod( mpi *X, const mpi *A, const mpi *N );\n\n/**\n * \\brief Miller-Rabin primality test\n *\n * \\param X MPI to check\n * \\param f_rng RNG function\n * \\param p_rng RNG parameter\n *\n * \\return 0 if successful (probably prime),\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_NOT_ACCEPTABLE if X is not prime\n */\nint mpi_is_prime( mpi *X,\n int (*f_rng)(void *, unsigned char *, size_t),\n void *p_rng );\n\n/**\n * \\brief Prime number generation\n *\n * \\param X Destination MPI\n * \\param nbits Required size of X in bits ( 3 <= nbits <= POLARSSL_MPI_MAX_BITS )\n * \\param dh_flag If 1, then (X-1)/2 will be prime too\n * \\param f_rng RNG function\n * \\param p_rng RNG parameter\n *\n * \\return 0 if successful (probably prime),\n * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,\n * POLARSSL_ERR_MPI_BAD_INPUT_DATA if nbits is < 3\n */\nint mpi_gen_prime( mpi *X, size_t nbits, int dh_flag,\n int (*f_rng)(void *, unsigned char *, size_t),\n void *p_rng );\n\n/**\n * \\brief Checkup routine\n *\n * \\return 0 if successful, or 1 if the test failed\n */\nint mpi_self_test( int verbose );\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* bignum.h */\n"},"repo_name":{"kind":"string","value":"mimecine/mongrel2"},"path":{"kind":"string","value":"src/polarssl/bignum.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":19580,"string":"19,580"}}},{"rowIdx":115086598,"cells":{"code":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Diagnostics;\nusing System.Threading.Tasks;\nusing Xunit;\n\nnamespace System.Threading.Tests\n{\n /// <summary>\n /// SemaphoreSlim unit tests\n /// </summary>\n public class SemaphoreSlimTests\n {\n /// <summary>\n /// SemaphoreSlim public methods and properties to be tested\n /// </summary>\n private enum SemaphoreSlimActions\n {\n Constructor,\n Wait,\n WaitAsync,\n Release,\n Dispose,\n CurrentCount,\n AvailableWaitHandle\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest0_Ctor()\n {\n RunSemaphoreSlimTest0_Ctor(0, 10, null);\n RunSemaphoreSlimTest0_Ctor(5, 10, null);\n RunSemaphoreSlimTest0_Ctor(10, 10, null);\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest0_Ctor_Negative()\n {\n RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException));\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest1_Wait()\n {\n // Infinite timeout\n RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null);\n RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null);\n\n // Zero timeout\n RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null);\n RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null);\n RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null);\n\n // Positive timeout\n RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null);\n RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null);\n RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null);\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest1_Wait_NegativeCases()\n {\n // Invalid timeout\n RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest1_Wait\n (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException));\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest1_WaitAsync()\n {\n // Infinite timeout\n RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null);\n RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null);\n\n // Zero timeout\n RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null);\n RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null);\n RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null);\n\n // Positive timeout\n RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null);\n RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null);\n RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null);\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases()\n {\n // Invalid timeout\n RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest1_WaitAsync\n (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest1_WaitAsync2();\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest2_Release()\n {\n // Valid release count\n RunSemaphoreSlimTest2_Release(5, 10, 1, null);\n RunSemaphoreSlimTest2_Release(0, 10, 1, null);\n RunSemaphoreSlimTest2_Release(5, 10, 5, null);\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest2_Release_NegativeCases()\n {\n // Invalid release count\n RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException));\n RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException));\n\n // Semaphore Full\n RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException));\n RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException));\n RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException));\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest4_Dispose()\n {\n RunSemaphoreSlimTest4_Dispose(5, 10, null, null);\n RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null);\n RunSemaphoreSlimTest4_Dispose\n (5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException));\n RunSemaphoreSlimTest4_Dispose\n (5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException));\n RunSemaphoreSlimTest4_Dispose\n (5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException));\n RunSemaphoreSlimTest4_Dispose\n (5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException));\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest5_CurrentCount()\n {\n RunSemaphoreSlimTest5_CurrentCount(5, 10, null);\n RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait);\n RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync);\n RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release);\n }\n\n [Fact]\n public static void RunSemaphoreSlimTest7_AvailableWaitHandle()\n {\n RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true);\n RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false);\n\n RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);\n RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false);\n RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);\n\n RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);\n RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false);\n RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);\n RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true);\n }\n\n /// <summary>\n /// Test SemaphoreSlim constructor\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"exceptionType\">The type of the thrown exception in case of invalid cases,\n /// null for valid cases</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType)\n {\n string methodFailed = \"RunSemaphoreSlimTest0_Ctor(\" + initial + \",\" + maximum + \"): FAILED. \";\n Exception exception = null;\n try\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n Assert.Equal(initial, semaphore.CurrentCount);\n }\n catch (Exception ex)\n {\n Assert.NotNull(exceptionType);\n Assert.IsType(exceptionType, ex);\n exception = ex;\n }\n }\n\n /// <summary>\n /// Test SemaphoreSlim Wait\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"timeout\">The timeout parameter for the wait method, it must be either int or TimeSpan</param>\n /// <param name=\"returnValue\">The expected wait return value</param>\n /// <param name=\"exceptionType\">The type of the thrown exception in case of invalid cases,\n /// null for valid cases</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest1_Wait\n (int initial, int maximum, object timeout, bool returnValue, Type exceptionType)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n try\n {\n bool result = false;\n if (timeout is TimeSpan)\n {\n result = semaphore.Wait((TimeSpan)timeout);\n }\n else\n {\n result = semaphore.Wait((int)timeout);\n }\n Assert.Equal(returnValue, result);\n if (result)\n {\n Assert.Equal(initial - 1, semaphore.CurrentCount);\n }\n }\n catch (Exception ex)\n {\n Assert.NotNull(exceptionType);\n Assert.IsType(exceptionType, ex);\n }\n }\n\n /// <summary>\n /// Test SemaphoreSlim WaitAsync\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"timeout\">The timeout parameter for the wait method, it must be either int or TimeSpan</param>\n /// <param name=\"returnValue\">The expected wait return value</param>\n /// <param name=\"exceptionType\">The type of the thrown exception in case of invalid cases,\n /// null for valid cases</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest1_WaitAsync\n (int initial, int maximum, object timeout, bool returnValue, Type exceptionType)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n try\n {\n bool result = false;\n if (timeout is TimeSpan)\n {\n result = semaphore.WaitAsync((TimeSpan)timeout).Result;\n }\n else\n {\n result = semaphore.WaitAsync((int)timeout).Result;\n }\n Assert.Equal(returnValue, result);\n if (result)\n {\n Assert.Equal(initial - 1, semaphore.CurrentCount);\n }\n }\n catch (Exception ex)\n {\n Assert.NotNull(exceptionType);\n Assert.IsType(exceptionType, ex);\n }\n }\n\n /// <summary>\n /// Test SemaphoreSlim WaitAsync\n /// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously.\n /// </summary>\n private static void RunSemaphoreSlimTest1_WaitAsync2()\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(1);\n ThreadLocal<int> counter = new ThreadLocal<int>(() => 0);\n bool nonZeroObserved = false;\n\n const int asyncActions = 20;\n int remAsyncActions = asyncActions;\n ManualResetEvent mre = new ManualResetEvent(false);\n\n Action<int> doWorkAsync = async delegate (int i)\n {\n await semaphore.WaitAsync();\n if (counter.Value > 0)\n {\n nonZeroObserved = true;\n }\n\n counter.Value = counter.Value + 1;\n semaphore.Release();\n counter.Value = counter.Value - 1;\n\n if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set();\n };\n\n semaphore.Wait();\n for (int i = 0; i < asyncActions; i++) doWorkAsync(i);\n semaphore.Release();\n\n mre.WaitOne();\n\n Assert.False(nonZeroObserved, \"RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation.\");\n }\n\n /// <summary>\n /// Test SemaphoreSlim Release\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"releaseCount\">The release count for the release method</param>\n /// <param name=\"exceptionType\">The type of the thrown exception in case of invalid cases,\n /// null for valid cases</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest2_Release\n (int initial, int maximum, int releaseCount, Type exceptionType)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n try\n {\n int oldCount = semaphore.Release(releaseCount);\n Assert.Equal(initial, oldCount);\n Assert.Equal(initial + releaseCount, semaphore.CurrentCount);\n }\n catch (Exception ex)\n {\n Assert.NotNull(exceptionType);\n Assert.IsType(exceptionType, ex);\n }\n }\n\n /// <summary>\n /// Call specific SemaphoreSlim method or property\n /// </summary>\n /// <param name=\"semaphore\">The SemaphoreSlim instance</param>\n /// <param name=\"action\">The action name</param>\n /// <param name=\"param\">The action parameter, null if it takes no parameters</param>\n /// <returns>The action return value, null if the action returns void</returns>\n private static object CallSemaphoreAction\n (SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param)\n {\n if (action == SemaphoreSlimActions.Wait)\n {\n if (param is TimeSpan)\n {\n return semaphore.Wait((TimeSpan)param);\n }\n else if (param is int)\n {\n return semaphore.Wait((int)param);\n }\n semaphore.Wait();\n return null;\n }\n else if (action == SemaphoreSlimActions.WaitAsync)\n {\n if (param is TimeSpan)\n {\n return semaphore.WaitAsync((TimeSpan)param).Result;\n }\n else if (param is int)\n {\n return semaphore.WaitAsync((int)param).Result;\n }\n semaphore.WaitAsync().Wait();\n return null;\n }\n else if (action == SemaphoreSlimActions.Release)\n {\n if (param != null)\n {\n return semaphore.Release((int)param);\n }\n return semaphore.Release();\n }\n else if (action == SemaphoreSlimActions.Dispose)\n {\n semaphore.Dispose();\n return null;\n }\n else if (action == SemaphoreSlimActions.CurrentCount)\n {\n return semaphore.CurrentCount;\n }\n else if (action == SemaphoreSlimActions.AvailableWaitHandle)\n {\n return semaphore.AvailableWaitHandle;\n }\n\n return null;\n }\n\n /// <summary>\n /// Test SemaphoreSlim Dispose\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"action\">SemaphoreSlim action to be called after Dispose</param>\n /// <param name=\"exceptionType\">The type of the thrown exception in case of invalid cases,\n /// null for valid cases</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n try\n {\n semaphore.Dispose();\n CallSemaphoreAction(semaphore, action, null);\n }\n catch (Exception ex)\n {\n Assert.NotNull(exceptionType);\n Assert.IsType(exceptionType, ex);\n }\n }\n\n /// <summary>\n /// Test SemaphoreSlim CurrentCount property\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"action\">SemaphoreSlim action to be called before CurrentCount</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n\n CallSemaphoreAction(semaphore, action, null);\n if (action == null)\n {\n Assert.Equal(initial, semaphore.CurrentCount);\n }\n else\n {\n Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount);\n }\n }\n\n /// <summary>\n /// Test SemaphoreSlim AvailableWaitHandle property\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"action\">SemaphoreSlim action to be called before WaitHandle</param>\n /// <param name=\"state\">The expected wait handle state</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n\n CallSemaphoreAction(semaphore, action, null);\n Assert.NotNull(semaphore.AvailableWaitHandle);\n Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0));\n }\n\n /// <summary>\n /// Test SemaphoreSlim Wait and Release methods concurrently\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"waitThreads\">Number of the threads that call Wait method</param>\n /// <param name=\"releaseThreads\">Number of the threads that call Release method</param>\n /// <param name=\"succeededWait\">Number of succeeded wait threads</param>\n /// <param name=\"failedWait\">Number of failed wait threads</param>\n /// <param name=\"finalCount\">The final semaphore count</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n [Theory]\n [InlineData(5, 1000, 50, 50, 50, 0, 5, 1000)]\n [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]\n [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]\n public static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum,\n int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n Task[] threads = new Task[waitThreads + releaseThreads];\n int succeeded = 0;\n int failed = 0;\n ManualResetEvent mre = new ManualResetEvent(false);\n // launch threads\n for (int i = 0; i < threads.Length; i++)\n {\n if (i < waitThreads)\n {\n // We are creating the Task using TaskCreationOptions.LongRunning to\n // force usage of another thread (which will be the case on the default scheduler\n // with its current implementation). Without this, the release tasks will likely get\n // queued behind the wait tasks in the pool, making it very likely that the wait tasks\n // will starve the very tasks that when run would unblock them.\n threads[i] = new Task(delegate ()\n {\n mre.WaitOne();\n if (semaphore.Wait(timeout))\n {\n Interlocked.Increment(ref succeeded);\n }\n else\n {\n Interlocked.Increment(ref failed);\n }\n }, TaskCreationOptions.LongRunning);\n }\n else\n {\n threads[i] = new Task(delegate ()\n {\n mre.WaitOne();\n semaphore.Release();\n });\n }\n threads[i].Start(TaskScheduler.Default);\n }\n\n mre.Set();\n //wait work to be done;\n Task.WaitAll(threads);\n //check the number of succeeded and failed wait\n Assert.Equal(succeededWait, succeeded);\n Assert.Equal(failedWait, failed);\n Assert.Equal(finalCount, semaphore.CurrentCount);\n }\n\n /// <summary>\n /// Test SemaphoreSlim WaitAsync and Release methods concurrently\n /// </summary>\n /// <param name=\"initial\">The initial semaphore count</param>\n /// <param name=\"maximum\">The maximum semaphore count</param>\n /// <param name=\"waitThreads\">Number of the threads that call Wait method</param>\n /// <param name=\"releaseThreads\">Number of the threads that call Release method</param>\n /// <param name=\"succeededWait\">Number of succeeded wait threads</param>\n /// <param name=\"failedWait\">Number of failed wait threads</param>\n /// <param name=\"finalCount\">The final semaphore count</param>\n /// <returns>True if the test succeeded, false otherwise</returns>\n [Theory]\n [InlineData(5, 1000, 50, 50, 50, 0, 5, 500)]\n [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]\n [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]\n public static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum,\n int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)\n {\n SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);\n Task[] tasks = new Task[waitThreads + releaseThreads];\n int succeeded = 0;\n int failed = 0;\n ManualResetEvent mre = new ManualResetEvent(false);\n // launch threads\n for (int i = 0; i < tasks.Length; i++)\n {\n if (i < waitThreads)\n {\n tasks[i] = Task.Run(async delegate\n {\n mre.WaitOne();\n if (await semaphore.WaitAsync(timeout))\n {\n Interlocked.Increment(ref succeeded);\n }\n else\n {\n Interlocked.Increment(ref failed);\n }\n });\n }\n else\n {\n tasks[i] = Task.Run(delegate\n {\n mre.WaitOne();\n semaphore.Release();\n });\n }\n }\n\n mre.Set();\n //wait work to be done;\n Task.WaitAll(tasks);\n\n Assert.Equal(succeededWait, succeeded);\n Assert.Equal(failedWait, failed);\n Assert.Equal(finalCount, semaphore.CurrentCount);\n }\n\n [Theory]\n [InlineData(10, 10)]\n [InlineData(1, 10)]\n [InlineData(10, 1)]\n public static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters)\n {\n int totalWaiters = syncWaiters + asyncWaiters;\n\n var semaphore = new SemaphoreSlim(0);\n Task[] tasks = new Task[totalWaiters];\n\n const int ITERS = 10;\n int randSeed = unchecked((int)DateTime.Now.Ticks);\n for (int i = 0; i < syncWaiters; i++)\n {\n tasks[i] = Task.Run(delegate\n {\n //Random rand = new Random(Interlocked.Increment(ref randSeed));\n for (int iter = 0; iter < ITERS; iter++)\n {\n semaphore.Wait();\n semaphore.Release();\n }\n });\n }\n for (int i = syncWaiters; i < totalWaiters; i++)\n {\n tasks[i] = Task.Run(async delegate\n {\n //Random rand = new Random(Interlocked.Increment(ref randSeed));\n for (int iter = 0; iter < ITERS; iter++)\n {\n await semaphore.WaitAsync();\n semaphore.Release();\n }\n });\n }\n\n semaphore.Release(totalWaiters / 2);\n Task.WaitAll(tasks);\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"shimingsg/corefx"},"path":{"kind":"string","value":"src/System.Threading/tests/SemaphoreSlimTests.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":25845,"string":"25,845"}}},{"rowIdx":115086599,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (C) 2008 Apple Inc. All rights reserved.\n * Copyright (C) 2009 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.audits-sidebar-tree-item .icon {\n content: url(Images/resourcesTimeGraphIcon.png);\n}\n\n.audit-result-sidebar-tree-item .icon {\n content: url(Images/resourceDocumentIcon.png);\n}\n\n.audit-launcher-view {\n z-index: 1000;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: white;\n font-size: 13px;\n overflow-x: hidden;\n overflow-y: overlay;\n display: none;\n}\n\n.audit-launcher-view.visible {\n display: block;\n}\n\n.audit-launcher-view .audit-launcher-view-content {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n padding: 0 0 0 16px;\n white-space: nowrap;\n display: -webkit-box;\n text-align: left;\n -webkit-box-orient: vertical;\n}\n\n.audit-launcher-view h1 {\n padding-top: 15px;\n}\n\n.audit-launcher-view h1.no-audits {\n text-align: center;\n font-style: italic;\n position: relative;\n left: -8px;\n}\n\n.audit-launcher-view div.button-container {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n width: 100%;\n padding: 16px 0;\n}\n\n.audit-launcher-view div.audit-categories-container {\n position: relative;\n top: 11px;\n left: 0;\n width: 100%;\n overflow-y: auto;\n}\n\n.audit-launcher-view button {\n margin: 0 5px 0 0;\n}\n\n.audit-launcher-view button:active {\n background-color: rgb(215, 215, 215);\n background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(194, 194, 194)), to(rgb(239, 239, 239)));\n}\n\n.panel-enabler-view.audit-launcher-view label {\n padding: 0 0 5px 0;\n margin: 0;\n}\n\n.panel-enabler-view.audit-launcher-view label.disabled {\n color: rgb(130, 130, 130);\n}\n\n.audit-launcher-view input[type=\"checkbox\"] {\n margin-left: 0;\n}\n\n.audit-launcher-view .resource-progress > img {\n content: url(Images/spinner.gif);\n vertical-align: text-top;\n margin: 0 4px 0 8px;\n}\n\n.audit-result-view {\n overflow: auto;\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: none;\n}\n\n.audit-result-view.visible {\n display: block;\n}\n\n.audit-result-view .severity-severe {\n content: url(Images/errorRedDot.png);\n}\n\n.audit-result-view .severity-warning {\n content: url(Images/warningOrangeDot.png);\n}\n\n.audit-result-view .severity-info {\n content: url(Images/successGreenDot.png);\n}\n\n.audit-result-tree li.parent::before {\n content: url(Images/treeRightTriangleBlack.png);\n float: left;\n width: 8px;\n height: 8px;\n margin-top: 1px;\n padding-right: 2px;\n}\n\n.audit-result-tree {\n font-size: 11px;\n line-height: 14px;\n -webkit-user-select: text;\n}\n\n.audit-result-tree > ol {\n position: relative;\n padding: 2px 6px !important;\n margin: 0;\n color: rgb(84, 84, 84);\n cursor: default;\n min-width: 100%;\n}\n\n.audit-result-tree, .audit-result-tree ol {\n list-style-type: none;\n -webkit-padding-start: 12px;\n margin: 0;\n}\n\n.audit-result-tree ol.outline-disclosure {\n -webkit-padding-start: 0;\n}\n\n.audit-result-tree .section .header {\n padding-left: 13px;\n}\n\n.audit-result-tree .section .header::before {\n left: 2px;\n}\n\n.audit-result-tree li {\n padding: 0 0 0 14px;\n margin-top: 1px;\n margin-bottom: 1px;\n word-wrap: break-word;\n margin-left: -2px;\n}\n\n.audit-result-tree li.parent {\n margin-left: -12px\n}\n\n.audit-result-tree li.parent::before {\n content: url(Images/treeRightTriangleBlack.png);\n float: left;\n width: 8px;\n height: 8px;\n margin-top: 0;\n padding-right: 2px;\n}\n\n.audit-result-tree li.parent.expanded::before {\n content: url(Images/treeDownTriangleBlack.png);\n}\n\n.audit-result-tree ol.children {\n display: none;\n}\n\n.audit-result-tree ol.children.expanded {\n display: block;\n}\n\n.audit-result {\n font-weight: bold;\n color: black;\n}\n\n.audit-result img {\n float: left;\n margin-left: -28px;\n margin-top: -1px;\n}\n"},"repo_name":{"kind":"string","value":"NetEase/pomelo-admin-web"},"path":{"kind":"string","value":"public/front/auditsPanel.css"},"language":{"kind":"string","value":"CSS"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":5485,"string":"5,485"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":1150865,"numItemsPerPage":100,"numTotalItems":115086922,"offset":115086500,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjUwOTMzMSwic3ViIjoiL2RhdGFzZXRzL2xvdWJuYWJubC9naXRodWItY29kZS1kdXBsaWNhdGUiLCJleHAiOjE3NTY1MTI5MzEsImlzcyI6Imh0dHBzOi8vaHVnZ2luZ2ZhY2UuY28ifQ.HSnLYqbOZa-7JKkRtZCjldl3Fq2haMVKNBJzc1jueFH3WjE0uJIPQHjSylAohlDHGBzEHizL38XLbY4iPAQpDQ","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}"><div><header class="bg-linear-to-t border-b border-gray-100 pt-4 xl:pt-0 from-purple-500/8 dark:from-purple-500/20 to-white to-70% dark:to-gray-950"><div class="mx-4 relative flex flex-col xl:flex-row"><h1 class="flex flex-wrap items-center max-md:leading-tight gap-y-1 text-lg xl:flex-none"><a href="/datasets" class="group flex items-center"><svg class="sm:mr-1 -mr-1 text-gray-400" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 25 25"><ellipse cx="12.5" cy="5" fill="currentColor" fill-opacity="0.25" rx="7.5" ry="2"></ellipse><path d="M12.5 15C16.6421 15 20 14.1046 20 13V20C20 21.1046 16.6421 22 12.5 22C8.35786 22 5 21.1046 5 20V13C5 14.1046 8.35786 15 12.5 15Z" fill="currentColor" opacity="0.5"></path><path d="M12.5 7C16.6421 7 20 6.10457 20 5V11.5C20 12.6046 16.6421 13.5 12.5 13.5C8.35786 13.5 5 12.6046 5 11.5V5C5 6.10457 8.35786 7 12.5 7Z" fill="currentColor" opacity="0.5"></path><path d="M5.23628 12C5.08204 12.1598 5 12.8273 5 13C5 14.1046 8.35786 15 12.5 15C16.6421 15 20 14.1046 20 13C20 12.8273 19.918 12.1598 19.7637 12C18.9311 12.8626 15.9947 13.5 12.5 13.5C9.0053 13.5 6.06886 12.8626 5.23628 12Z" fill="currentColor"></path></svg> <span class="mr-2.5 font-semibold text-gray-400 group-hover:text-gray-500 max-sm:hidden">Datasets:</span></a> <hr class="mx-1.5 h-2 translate-y-px rounded-sm border-r dark:border-gray-600 sm:hidden"> <div class="group flex flex-none items-center"><div class="relative mr-1 flex items-center"> <span class="inline-block "><span class="contents"><a href="/loubnabnl" class="text-gray-400 hover:text-blue-600"><img alt="" class="size-3.5 rounded-full flex-none" src="https://aifasthub.com/avatars/v1/production/uploads/61c141342aac764ce1654e43/81AwoT5IQ_Xdw0OVw7TKu.jpeg" crossorigin="anonymous"></a></span> </span></div> <span class="inline-block "><span class="contents"><a href="/loubnabnl" class="text-gray-400 hover:text-blue-600">loubnabnl</a></span> </span> <div class="mx-0.5 text-gray-300">/</div></div> <div class="max-w-full xl:flex xl:min-w-0 xl:flex-nowrap xl:items-center xl:gap-x-1"><a class="break-words font-mono font-semibold hover:text-blue-600 text-[1.07rem] xl:truncate" href="/datasets/loubnabnl/github-code-duplicate">github-code-duplicate</a> <button class="text-xs mr-3 focus:outline-hidden inline-flex cursor-pointer items-center text-sm mx-0.5 text-gray-600 " title="Copy dataset name to clipboard" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> </button></div> <div class="inline-flex items-center overflow-hidden whitespace-nowrap rounded-md border bg-white text-sm leading-none text-gray-500 mr-2"><button class="relative flex items-center overflow-hidden from-red-50 to-transparent dark:from-red-900 px-1.5 py-1 hover:bg-linear-to-t focus:outline-hidden" title="Like"><svg class="left-1.5 absolute" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" fill="currentColor"><path d="M22.45,6a5.47,5.47,0,0,1,3.91,1.64,5.7,5.7,0,0,1,0,8L16,26.13,5.64,15.64a5.7,5.7,0,0,1,0-8,5.48,5.48,0,0,1,7.82,0L16,10.24l2.53-2.58A5.44,5.44,0,0,1,22.45,6m0-2a7.47,7.47,0,0,0-5.34,2.24L16,7.36,14.89,6.24a7.49,7.49,0,0,0-10.68,0,7.72,7.72,0,0,0,0,10.82L16,29,27.79,17.06a7.72,7.72,0,0,0,0-10.82A7.49,7.49,0,0,0,22.45,4Z"></path></svg> <span class="ml-4 pl-0.5 ">like</span></button> <button class="focus:outline-hidden flex items-center border-l px-1.5 py-1 text-gray-400 hover:bg-gray-50 focus:bg-gray-100 dark:hover:bg-gray-900 dark:focus:bg-gray-800" title="See users who liked this repository">1</button></div> </h1> <div class="flex flex-col-reverse gap-x-2 sm:flex-row sm:items-center sm:justify-between xl:ml-auto"><div class="-mb-px flex h-12 items-center overflow-x-auto overflow-y-hidden "> <a class="tab-alternate" href="/datasets/loubnabnl/github-code-duplicate"><svg class="mr-1.5 text-gray-400 flex-none" style="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-quaternary" d="M20.23 7.24L12 12L3.77 7.24a1.98 1.98 0 0 1 .7-.71L11 2.76c.62-.35 1.38-.35 2 0l6.53 3.77c.29.173.531.418.7.71z" opacity=".25" fill="currentColor"></path><path class="uim-tertiary" d="M12 12v9.5a2.09 2.09 0 0 1-.91-.21L4.5 17.48a2.003 2.003 0 0 1-1-1.73v-7.5a2.06 2.06 0 0 1 .27-1.01L12 12z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M20.5 8.25v7.5a2.003 2.003 0 0 1-1 1.73l-6.62 3.82c-.275.13-.576.198-.88.2V12l8.23-4.76c.175.308.268.656.27 1.01z" fill="currentColor"></path></svg> Dataset card </a><a class="tab-alternate active" href="/datasets/loubnabnl/github-code-duplicate/viewer/"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill="currentColor" d="M2.5 2h7a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1Zm0 2v2h3V4h-3Zm4 0v2h3V4h-3Zm-4 3v2h3V7h-3Zm4 0v2h3V7h-3Z"></path></svg> Data Studio </a><a class="tab-alternate" href="/datasets/loubnabnl/github-code-duplicate/tree/main"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path class="uim-tertiary" d="M21 19h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0-8h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2zm0 4h-8a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2z" opacity=".5" fill="currentColor"></path><path class="uim-primary" d="M9 19a1 1 0 0 1-1-1V6a1 1 0 0 1 2 0v12a1 1 0 0 1-1 1zm-6-4.333a1 1 0 0 1-.64-1.769L3.438 12l-1.078-.898a1 1 0 0 1 1.28-1.538l2 1.667a1 1 0 0 1 0 1.538l-2 1.667a.999.999 0 0 1-.64.231z" fill="currentColor"></path></svg> <span class="xl:hidden">Files</span> <span class="hidden xl:inline">Files and versions</span> <span class="inline-block "><span class="contents"><div slot="anchor" class="shadow-purple-500/10 ml-2 inline-flex -translate-y-px items-center gap-0.5 rounded-md border bg-white px-1 py-0.5 align-middle text-xs font-semibold leading-none text-gray-800 shadow-sm dark:border-gray-700 dark:bg-gradient-to-b dark:from-gray-925 dark:to-gray-925 dark:text-gray-300"><svg class="size-3 " xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path fill-rule="evenodd" clip-rule="evenodd" d="M6.14 3.64 5.1 4.92 2.98 2.28h2.06l1.1 1.36Zm0 4.72-1.1 1.36H2.98l2.13-2.64 1.03 1.28Zm4.9 1.36L8.03 6l3-3.72H8.96L5.97 6l3 3.72h2.06Z" fill="#7875FF"></path><path d="M4.24 6 2.6 8.03.97 6 2.6 3.97 4.24 6Z" fill="#FF7F41" opacity="1"></path></svg> <span>xet</span> </div></span> </span> </a><a class="tab-alternate" href="/datasets/loubnabnl/github-code-duplicate/discussions"><svg class="mr-1.5 text-gray-400 flex-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path><path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path></svg> Community </a></div> </div></div></header> </div> <div class="flex flex-col w-full"> <div class="flex h-full flex-1"> <div class="flex flex-1 flex-col overflow-hidden " style="height: calc(100vh - 48px)"><div class="flex flex-col overflow-hidden h-full "> <div class="flex flex-1 flex-col overflow-hidden "><div class="flex flex-1 flex-col overflow-hidden"><div class="flex min-h-0 flex-1"><div class="flex flex-1 flex-col overflow-hidden"><div class="md:shadow-xs dark:border-gray-800 md:my-4 md:ml-4 md:rounded-lg md:border flex min-w-0 flex-wrap "><div class="flex min-w-0 flex-1 flex-wrap"><div class="grid flex-1 grid-cols-1 overflow-hidden text-sm md:grid-cols-2 md:place-content-center md:rounded-lg"><label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-950 md:border-r md:border-r-0 hidden" title="default"><span class="text-gray-500">Subset (1)</span> <div class="flex items-center whitespace-nowrap"><span class="truncate">default</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">115M rows</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Subset (1)"><option value="default" selected>default (115M rows)</option></optgroup></select></label> <label class="relative block flex-1 px-3 py-2 hover:bg-gray-50 dark:border-gray-850 dark:hover:bg-gray-900 md:border-r md:border-r" title="train"><div class="text-gray-500">Split (1)</div> <div class="flex items-center overflow-hidden whitespace-nowrap"><span class="truncate">train</span> <span class="mx-2 text-gray-500">·</span> <span class="text-gray-500">115M rows</span> <svg class="ml-auto min-w-6 pl-2" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></div> <select class="absolute inset-0 z-10 w-full cursor-pointer border-0 bg-white text-base opacity-0"><optgroup label="Split (1)"><option value="train" selected>train (115M rows)</option></optgroup></select></label></div></div> <div class="hidden flex-none flex-col items-center gap-0.5 border-l px-1 md:flex justify-end"> <span class="inline-block "><span class="contents"><div slot="anchor"><button class="group text-gray-500 hover:text-gray-700" aria-label="Hide sidepanel"><div class="rounded-xs flex size-4 items-center justify-center border border-gray-400 bg-gray-100 hover:border-gray-600 hover:bg-blue-50 dark:border-gray-600 dark:bg-gray-800 dark:hover:bg-gray-700 dark:group-hover:border-gray-400"><div class="float-left h-full w-[65%]"></div> <div class="float-right h-full w-[35%] bg-gray-400 group-hover:bg-gray-600 dark:bg-gray-600 dark:group-hover:bg-gray-400"></div></div></button></div></span> </span> <div class="relative "> <button class="btn px-0.5 py-0.5 " type="button"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="p-0.5" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><circle cx="16" cy="7" r="3" fill="currentColor"></circle><circle cx="16" cy="16" r="3" fill="currentColor"></circle><circle cx="16" cy="25" r="3" fill="currentColor"></circle></svg> </button> </div></div></div> <div class="flex min-h-0 flex-1 flex-col border dark:border-gray-800 md:mb-4 md:ml-4 md:rounded-lg"> <div class="bg-linear-to-r text-smd relative flex items-center dark:border-gray-900 dark:bg-gray-950 false rounded-t-lg [&:has(:focus)]:from-gray-50 [&:has(:focus)]:to-transparent [&:has(:focus)]:to-20% dark:[&:has(:focus)]:from-gray-900"><form class="flex-1"><svg class="absolute left-3 top-1/2 transform -translate-y-1/2 pointer-events-none text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M30 28.59L22.45 21A11 11 0 1 0 21 22.45L28.59 30zM5 14a9 9 0 1 1 9 9a9 9 0 0 1-9-9z" fill="currentColor"></path></svg> <input disabled class="outline-hidden h-9 w-full border-none bg-transparent px-1 pl-9 pr-3 placeholder:text-gray-400 " placeholder="Search this dataset" dir="auto"></form> <div class="flex items-center gap-2 px-2 py-1"><button type="button" class="hover:bg-yellow-200/70 flex items-center gap-1 rounded-md border border-yellow-200 bg-yellow-100 pl-0.5 pr-1 text-[.8rem] leading-normal text-gray-700 dark:border-orange-500/25 dark:bg-orange-500/20 dark:text-gray-300 dark:hover:brightness-110 md:hidden"><div class="rounded-sm bg-yellow-300 px-1 font-mono text-[.7rem] font-bold text-black dark:bg-yellow-700 dark:text-gray-200">SQL </div> Console </button></div></div> <div class="flex flex-1 flex-col overflow-hidden min-h-64 flex w-full flex-col border-t md:rounded-b-lg md:shadow-lg"> <div class="flex-1 relative overflow-auto"><table class="w-full table-auto rounded-lg font-mono text-xs text-gray-900"><thead class="shadow-xs sticky left-0 right-0 top-0 z-1 bg-white align-top"><tr class="space-y-54 h-full min-w-fit divide-x border-b text-left"><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">code <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">3</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">1.05M</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">repo_name <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="16.238645690834474" width="11.2" height="13.761354309165526" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="19.201299589603284" width="11.2" height="10.798700410396716" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">4</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">116</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">path <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">lengths</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="13.2" y="23.866840067974223" width="11.2" height="6.133159932025778" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="52.8" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="66" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="79.19999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="92.39999999999999" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="105.6" y="26" width="11.2" height="4" fill-opacity="1"></rect><rect class="fill-gray-400 dark:fill-gray-500/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">3</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">942</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">language <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">classes</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="19.903139465314734" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="22.903139465314734" y="0" width="14.068347136064489" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="38.971486601379226" y="0" width="11.662751519350063" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="52.63423812072929" y="0" width="10.90134458544573" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="65.53558270617502" y="0" width="10.503038700129107" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="78.03862140630413" y="0" width="7.39907736876909" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="87.43769877507322" y="0" width="6.324715810687406" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="95.76241458576062" y="0" width="6.061907610920427" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="103.82432219668105" y="0" width="5.715999622130554" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="111.5403218188116" y="0" width="2.985987341373556" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="116.52630916018516" y="0" width="0.47620996945555305" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="119.00251912964072" y="0" width="0.16284598671159145" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="121.1653651163523" y="0" width="0.054570645841861776" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="21.903139465314734" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="21.903139465314734" y="0" width="16.06834713606449" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="37.971486601379226" y="0" width="13.662751519350063" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="51.63423812072929" y="0" width="12.90134458544573" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="64.53558270617502" y="0" width="12.503038700129107" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="77.03862140630413" y="0" width="9.39907736876909" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="86.43769877507322" y="0" width="8.324715810687406" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="94.76241458576062" y="0" width="8.061907610920427" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="102.82432219668105" y="0" width="7.715999622130554" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="110.5403218188116" y="0" width="4.985987341373556" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="115.52630916018516" y="0" width="2.476209969455553" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="118.00251912964072" y="0" width="2.1628459867115915" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="120.1653651163523" y="0" width="2.0545706458418618" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="122.21993576219417" y="0" width="1.5291589255912081" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="123.74909468778537" y="0" width="0.9257643984003527" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="124.67485908618572" y="0" width="0.7601788582044903" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="125.4350379443902" y="0" width="0.7552665554051076" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="126.19030449979532" y="0" width="0.6807632962811349" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="126.87106779607645" y="0" width="0.5624586705293321" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="127.43352646660578" y="0" width="0.4081304909153887" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="127.84165695752117" y="0" width="0.3702648235034795" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.21192178102464" y="0" width="0.3682180306704034" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.58013981169503" y="0" width="0.29248669584658504" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.8726265075416" y="0" width="0.2746795981988223" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.14730610574043" y="0" width="0.1913751298926221" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.33868123563306" y="0" width="0.17070252227855276" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.50938375791162" y="0" width="0.164152785212709" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.67353654312433" y="0" width="0.1606732373964795" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.8342097805208" y="0" width="0.0986554145542715" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.93286519507507" y="0" width="0.06713480492489844" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">30 values</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">license <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>string</span><span class="italic text-gray-400 before:mx-1 before:content-['·']">classes</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><defs><clipPath id="rounded-bar"><rect x="0" y="0" width="130" height="8" rx="4"></rect></clipPath><pattern id="hatching" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-400 dark:stroke-gray-500/80" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern><pattern id="hatching-faded" patternUnits="userSpaceOnUse" patternTransform="rotate(-45)" height="1" width="5"><line y1="0" class="stroke-gray-100 dark:stroke-gray-500/20" stroke-width="3" y2="1" x1="2" x2="2"></line></pattern></defs><g height="8" style="transform: translateY(20px)" clip-path="url(#rounded-bar)"><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="1" y="0" width="41.34963944957017" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="44.34963944957017" y="0" width="27.00755738892213" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="73.3571968384923" y="0" width="17.11704506093145" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="92.47424189942375" y="0" width="13.22404509242057" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="107.69828699184431" y="0" width="5.933164341719936" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="115.63145133356424" y="0" width="1.635104071543282" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="119.26655540510752" y="0" width="0.5208300532166135" height="8" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" x="121.78738545832414" y="0" width="0.32699877192430016" height="8" fill-opacity="1"></rect></g></g></g><g style="transform: scaleX(1.0153846153846153) translateX(-1px)"><g><rect class="fill-white cursor-pointer" x="0" y="0" width="43.34963944957017" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="43.34963944957017" y="0" width="29.00755738892213" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="72.3571968384923" y="0" width="19.11704506093145" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="91.47424189942375" y="0" width="15.22404509242057" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="106.69828699184431" y="0" width="7.933164341719936" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="114.63145133356424" y="0" width="3.635104071543282" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="118.26655540510752" y="0" width="2.5208300532166135" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="120.78738545832414" y="0" width="2.3269987719243" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="123.11438423024843" y="0" width="1.9516169663381302" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="125.06600119658657" y="0" width="1.3979595049910256" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="126.46396070157759" y="0" width="1.2290990962622415" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="127.69305979783984" y="0" width="1.0141858487892432" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="128.70724564662908" y="0" width="0.784945051484712" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.4921906981138" y="0" width="0.3661712378373272" height="28" fill-opacity="0"></rect><rect class="fill-white cursor-pointer" x="129.85836193595114" y="0" width="0.1416380640488711" height="28" fill-opacity="0"></rect></g></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 max-w-full overflow-hidden text-ellipsis whitespace-nowrap">15 values</div></div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th><th class="h-full max-w-sm p-2 text-left relative w-auto"><div class="flex h-full flex-col flex-nowrap justify-between"><div><div class="flex items-center justify-between">size <form class="flex flex-col"><button id="asc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="-rotate-180 transform text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button> <button id="desc" class="-mr-1 ml-2 h-[0.4rem] w-[0.8rem] transition ease-in-out"><svg class="text-gray-300 hover:text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 64 256 128" fill="currentColor" aria-hidden="true"><path d="M213.65674,101.657l-80,79.99976a7.99945,7.99945,0,0,1-11.31348,0l-80-79.99976A8,8,0,0,1,48,88H208a8,8,0,0,1,5.65674,13.657Z"></path></svg></button></form></div> <div class="mb-2 whitespace-nowrap text-xs font-normal text-gray-500"><span>int32</span></div></div> <div><div class="" style="height: 40px; padding-top: 2px"><svg width="130" height="28"><g><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="0" y="0" width="11.2" height="30" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="13.2" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="26.4" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="39.599999999999994" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="52.8" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="66" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="79.19999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="92.39999999999999" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="105.6" y="25" width="11.2" height="5" fill-opacity="1"></rect><rect class="fill-indigo-500 dark:fill-indigo-600/80" rx="2" x="118.8" y="25" width="11.2" height="5" fill-opacity="1"></rect></g><rect class="fill-white dark:fill-gray-900" x="0" y="26" width="130" height="2" stroke-opacity="1"></rect><line class="stroke-gray-100 dark:stroke-gray-500/20" x1="0" y1="27.5" x2="130" y2="27.5" stroke-opacity="1"></line><g><rect class="fill-indigo-500 cursor-pointer" x="-1" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="12.2" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="25.4" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="38.599999999999994" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="51.8" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="65" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="78.19999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="91.39999999999999" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="104.6" y="0" width="13.2" height="30" fill-opacity="0"></rect><rect class="fill-indigo-500 cursor-pointer" x="117.8" y="0" width="13.2" height="30" fill-opacity="0"></rect></g></svg> <div class="relative font-light text-gray-400" style="height: 10px; width: 130px;"><div class="absolute left-0 overflow-hidden text-ellipsis whitespace-nowrap" style="max-width: 60px">3</div> <div class="absolute overflow-hidden text-ellipsis whitespace-nowrap" style="right: 0px; max-width: 60px">1.05M</div> </div></div></div></div> <div class="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize hover:bg-indigo-100 active:bg-indigo-500 dark:hover:bg-indigo-800 dark:active:bg-indigo-600/80"><div class="absolute right-0 top-0 h-full w-1"></div> </div> </th></tr></thead> <tbody class="h-16 overflow-scroll"><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086500"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (C) 2007 Google, Inc. * Copyright (c) 2008-2011, Code Aurora Forum. All rights reserved. * Author: Brian Swetland <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26555143524a47484266414949414a430845494b">[email protected]</a>> * * 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. * * * The MSM peripherals are spread all over across 768MB of physical * space, which makes just having a simple IO_ADDRESS macro to slide * them into the right virtual location rough. Instead, we will * provide a master phys->virt mapping for peripherals here. * */ #ifndef __ASM_ARCH_MSM_IOMAP_8930_H #define __ASM_ARCH_MSM_IOMAP_8930_H /* Physical base address and size of peripherals. * Ordered by the virtual base addresses they will be mapped at. * * If you add or remove entries here, you'll want to edit the * msm_io_desc array in arch/arm/mach-msm/io.c to reflect your * changes. * */ #define MSM8930_TMR_PHYS 0x0200A000 #define MSM8930_TMR_SIZE SZ_4K #define MSM8930_TMR0_PHYS 0x0208A000 #define MSM8930_TMR0_SIZE SZ_4K #define MSM8930_RPM_PHYS 0x00108000 #define MSM8930_RPM_SIZE SZ_4K #define MSM8930_RPM_MPM_PHYS 0x00200000 #define MSM8930_RPM_MPM_SIZE SZ_4K #define MSM8930_TCSR_PHYS 0x1A400000 #define MSM8930_TCSR_SIZE SZ_4K #define MSM8930_APCS_GCC_PHYS 0x02011000 #define MSM8930_APCS_GCC_SIZE SZ_4K #define MSM8930_SAW_L2_PHYS 0x02012000 #define MSM8930_SAW_L2_SIZE SZ_4K #define MSM8930_SAW0_PHYS 0x02089000 #define MSM8930_SAW0_SIZE SZ_4K #define MSM8930_SAW1_PHYS 0x02099000 #define MSM8930_SAW1_SIZE SZ_4K #define MSM8930_IMEM_PHYS 0x2A03F000 #define MSM8930_IMEM_SIZE SZ_4K #define MSM8930_ACC0_PHYS 0x02088000 #define MSM8930_ACC0_SIZE SZ_4K #define MSM8930_ACC1_PHYS 0x02098000 #define MSM8930_ACC1_SIZE SZ_4K #define MSM8930_QGIC_DIST_PHYS 0x02000000 #define MSM8930_QGIC_DIST_SIZE SZ_4K #define MSM8930_QGIC_CPU_PHYS 0x02002000 #define MSM8930_QGIC_CPU_SIZE SZ_4K #define MSM8930_CLK_CTL_PHYS 0x00900000 #define MSM8930_CLK_CTL_SIZE SZ_16K #define MSM8930_MMSS_CLK_CTL_PHYS 0x04000000 #define MSM8930_MMSS_CLK_CTL_SIZE SZ_4K #define MSM8930_LPASS_CLK_CTL_PHYS 0x28000000 #define MSM8930_LPASS_CLK_CTL_SIZE SZ_4K #define MSM8930_HFPLL_PHYS 0x00903000 #define MSM8930_HFPLL_SIZE SZ_4K #define MSM8930_TLMM_PHYS 0x00800000 #define MSM8930_TLMM_SIZE SZ_16K #define MSM8930_DMOV_PHYS 0x18320000 #define MSM8930_DMOV_SIZE SZ_1M #define MSM8930_SIC_NON_SECURE_PHYS 0x12100000 #define MSM8930_SIC_NON_SECURE_SIZE SZ_64K #define MSM_GPT_BASE (MSM_TMR_BASE + 0x4) #define MSM_DGT_BASE (MSM_TMR_BASE + 0x24) #define MSM8930_HDMI_PHYS 0x04A00000 #define MSM8930_HDMI_SIZE SZ_4K #ifdef CONFIG_DEBUG_MSM8930_UART #define MSM_DEBUG_UART_BASE IOMEM(0xFA740000) #define MSM_DEBUG_UART_PHYS 0x16440000 #endif #define MSM8930_QFPROM_PHYS 0x00700000 #define MSM8930_QFPROM_SIZE SZ_4K #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">iAMr00t/android_kernel_lge_ls840</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">include/mach-msm/include/mach/msm_iomap-8930.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,201</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086501"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // SampleMap implements HistogramSamples interface. It is used by the // SparseHistogram class to store samples. #ifndef BASE_METRICS_SAMPLE_MAP_H_ #define BASE_METRICS_SAMPLE_MAP_H_ #include <map> #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/histogram_base.h" #include "base/metrics/histogram_samples.h" namespace base { class BASE_EXPORT_PRIVATE SampleMap : public HistogramSamples { public: SampleMap(); ~SampleMap() override; // HistogramSamples implementation: void Accumulate(HistogramBase::Sample value, HistogramBase::Count count) override; HistogramBase::Count GetCount(HistogramBase::Sample value) const override; HistogramBase::Count TotalCount() const override; scoped_ptr<SampleCountIterator> Iterator() const override; protected: bool AddSubtractImpl( SampleCountIterator* iter, HistogramSamples::Operator op) override; // |op| is ADD or SUBTRACT. private: std::map<HistogramBase::Sample, HistogramBase::Count> sample_counts_; DISALLOW_COPY_AND_ASSIGN(SampleMap); }; class BASE_EXPORT_PRIVATE SampleMapIterator : public SampleCountIterator { public: typedef std::map<HistogramBase::Sample, HistogramBase::Count> SampleToCountMap; explicit SampleMapIterator(const SampleToCountMap& sample_counts); ~SampleMapIterator() override; // SampleCountIterator implementation: bool Done() const override; void Next() override; void Get(HistogramBase::Sample* min, HistogramBase::Sample* max, HistogramBase::Count* count) const override; private: void SkipEmptyBuckets(); SampleToCountMap::const_iterator iter_; const SampleToCountMap::const_iterator end_; }; } // namespace base #endif // BASE_METRICS_SAMPLE_MAP_H_ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Teamxrtc/webrtc-streaming-node</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/webrtc/src/chromium/src/base/metrics/sample_map.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,962</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086502"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\ResourceBundle\Tests; use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait; use Sylius\Bundle\ResourceBundle\DependencyInjection\Configuration; /** * @author Anna Walasek <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37565959561940565b5644525c775b565c5e58591954585a">[email protected]</a>> * @author Kamil Kokot <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85eee4e8ece9abeeeaeeeaf1c5e9e4eeeceaebabe6eae8">[email protected]</a>> */ class ConfigurationTest extends \PHPUnit_Framework_TestCase { use ConfigurationTestCaseTrait; /** * @test */ public function it_does_not_break_if_not_customized() { $this->assertConfigurationIsValid( [ [] ] ); } /** * @test */ public function it_has_default_authorization_checker() { $this->assertProcessedConfigurationEquals( [ [] ], ['authorization_checker' => 'sylius.resource_controller.authorization_checker.disabled'], 'authorization_checker' ); } /** * @test */ public function its_authorization_checker_can_be_customized() { $this->assertProcessedConfigurationEquals( [ ['authorization_checker' => 'custom_service'] ], ['authorization_checker' => 'custom_service'], 'authorization_checker' ); } /** * @test */ public function its_authorization_checker_cannot_be_empty() { $this->assertPartialConfigurationIsInvalid( [ ['authorization_checker' => ''] ], 'authorization_checker' ); } /** * {@inheritdoc} */ protected function getConfiguration() { return new Configuration(); } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ejobs/Sylius</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/Sylius/Bundle/ResourceBundle/test/src/Tests/Configuration/ConfigurationTest.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,925</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086503"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/** * @author TristanVALCKE / https://github.com/Itee */ /* global QUnit */ import { PointLightHelper } from '../../../../src/helpers/PointLightHelper'; export default QUnit.module( 'Helpers', () => { QUnit.module( 'PointLightHelper', () => { // INHERITANCE QUnit.todo( "Extending", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // INSTANCING QUnit.todo( "Instancing", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); // PUBLIC STUFF QUnit.todo( "dispose", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); QUnit.todo( "update", ( assert ) => { assert.ok( false, "everything's gonna be alright" ); } ); } ); } ); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Aldrien-/three.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">test/unit/src/helpers/PointLightHelper.tests.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">745</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086504"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright (c) 2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __MSM_CPP_H__ #define __MSM_CPP_H__ #include <linux/clk.h> #include <linux/io.h> #include <linux/list.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <media/v4l2-subdev.h> #include "msm_sd.h" #define MAX_ACTIVE_CPP_INSTANCE 8 #define MAX_CPP_PROCESSING_FRAME 2 #define MAX_CPP_V4l2_EVENTS 30 #define MSM_CPP_MICRO_BASE 0x4000 #define MSM_CPP_MICRO_HW_VERSION 0x0000 #define MSM_CPP_MICRO_IRQGEN_STAT 0x0004 #define MSM_CPP_MICRO_IRQGEN_CLR 0x0008 #define MSM_CPP_MICRO_IRQGEN_MASK 0x000C #define MSM_CPP_MICRO_FIFO_TX_DATA 0x0010 #define MSM_CPP_MICRO_FIFO_TX_STAT 0x0014 #define MSM_CPP_MICRO_FIFO_RX_DATA 0x0018 #define MSM_CPP_MICRO_FIFO_RX_STAT 0x001C #define MSM_CPP_MICRO_BOOT_START 0x0020 #define MSM_CPP_MICRO_BOOT_LDORG 0x0024 #define MSM_CPP_MICRO_CLKEN_CTL 0x0030 #define MSM_CPP_CMD_GET_BOOTLOADER_VER 0x1 #define MSM_CPP_CMD_FW_LOAD 0x2 #define MSM_CPP_CMD_EXEC_JUMP 0x3 #define MSM_CPP_CMD_RESET_HW 0x5 #define MSM_CPP_CMD_PROCESS_FRAME 0x6 #define MSM_CPP_CMD_FLUSH_STREAM 0x7 #define MSM_CPP_CMD_CFG_MEM_PARAM 0x8 #define MSM_CPP_CMD_ERROR_REQUEST 0x9 #define MSM_CPP_CMD_GET_STATUS 0xA #define MSM_CPP_CMD_GET_FW_VER 0xB #define MSM_CPP_MSG_ID_CMD 0x3E646D63 #define MSM_CPP_MSG_ID_OK 0x0A0A4B4F #define MSM_CPP_MSG_ID_TRAILER 0xABCDEFAA #define MSM_CPP_MSG_ID_JUMP_ACK 0x00000001 #define MSM_CPP_MSG_ID_FRAME_ACK 0x00000002 #define MSM_CPP_MSG_ID_FRAME_NACK 0x00000003 #define MSM_CPP_MSG_ID_FLUSH_ACK 0x00000004 #define MSM_CPP_MSG_ID_FLUSH_NACK 0x00000005 #define MSM_CPP_MSG_ID_CFG_MEM_ACK 0x00000006 #define MSM_CPP_MSG_ID_CFG_MEM_INV 0x00000007 #define MSM_CPP_MSG_ID_ERROR_STATUS 0x00000008 #define MSM_CPP_MSG_ID_INVALID_CMD 0x00000009 #define MSM_CPP_MSG_ID_GEN_STATUS 0x0000000A #define MSM_CPP_MSG_ID_FLUSHED 0x0000000B #define MSM_CPP_MSG_ID_FW_VER 0x0000000C #define MSM_CPP_JUMP_ADDRESS 0x20 #define MSM_CPP_START_ADDRESS 0x0 #define MSM_CPP_END_ADDRESS 0x3F00 #define MSM_CPP_POLL_RETRIES 20 #define MSM_CPP_TASKLETQ_SIZE 16 #define MSM_CPP_TX_FIFO_LEVEL 16 struct cpp_subscribe_info { struct v4l2_fh *vfh; uint32_t active; }; enum cpp_state { CPP_STATE_BOOT, CPP_STATE_IDLE, CPP_STATE_ACTIVE, CPP_STATE_OFF, }; enum msm_queue { MSM_CAM_Q_CTRL, /* control command or control command status */ MSM_CAM_Q_VFE_EVT, /* adsp event */ MSM_CAM_Q_VFE_MSG, /* adsp message */ MSM_CAM_Q_V4L2_REQ, /* v4l2 request */ MSM_CAM_Q_VPE_MSG, /* vpe message */ MSM_CAM_Q_PP_MSG, /* pp message */ }; struct msm_queue_cmd { struct list_head list_config; struct list_head list_control; struct list_head list_frame; struct list_head list_pict; struct list_head list_vpe_frame; struct list_head list_eventdata; enum msm_queue type; void *command; atomic_t on_heap; struct timespec ts; uint32_t error_code; uint32_t trans_code; }; struct msm_device_queue { struct list_head list; spinlock_t lock; wait_queue_head_t wait; int max; int len; const char *name; }; struct msm_cpp_tasklet_queue_cmd { struct list_head list; uint32_t irq_status; uint32_t tx_fifo[MSM_CPP_TX_FIFO_LEVEL]; uint32_t tx_level; uint8_t cmd_used; }; struct msm_cpp_buffer_map_info_t { unsigned long len; unsigned long phy_addr; struct ion_handle *ion_handle; struct msm_cpp_buffer_info_t buff_info; }; struct msm_cpp_buffer_map_list_t { struct msm_cpp_buffer_map_info_t map_info; struct list_head entry; }; struct msm_cpp_buff_queue_info_t { uint32_t used; uint16_t session_id; uint16_t stream_id; struct list_head vb2_buff_head; struct list_head native_buff_head; }; struct msm_cpp_work_t { struct work_struct my_work; struct cpp_device *cpp_dev; }; struct cpp_device { struct platform_device *pdev; struct msm_sd_subdev msm_sd; struct v4l2_subdev subdev; struct resource *mem; struct resource *irq; struct resource *io; struct resource *vbif_mem; struct resource *vbif_io; struct resource *cpp_hw_mem; void __iomem *vbif_base; void __iomem *base; void __iomem *cpp_hw_base; struct clk **cpp_clk; struct regulator *fs_cpp; struct mutex mutex; enum cpp_state state; uint8_t is_firmware_loaded; char *fw_name_bin; struct workqueue_struct *timer_wq; struct msm_cpp_work_t *work; uint32_t fw_version; int domain_num; struct iommu_domain *domain; struct device *iommu_ctx; struct ion_client *client; struct kref refcount; /* Reusing proven tasklet from msm isp */ atomic_t irq_cnt; uint8_t taskletq_idx; spinlock_t tasklet_lock; struct list_head tasklet_q; struct tasklet_struct cpp_tasklet; struct msm_cpp_tasklet_queue_cmd tasklet_queue_cmd[MSM_CPP_TASKLETQ_SIZE]; struct cpp_subscribe_info cpp_subscribe_list[MAX_ACTIVE_CPP_INSTANCE]; uint32_t cpp_open_cnt; struct cpp_hw_info hw_info; struct msm_device_queue eventData_q; /* V4L2 Event Payload Queue */ /* Processing Queue * store frame info for frames sent to microcontroller */ struct msm_device_queue processing_q; struct msm_cpp_buff_queue_info_t *buff_queue; uint32_t num_buffq; struct v4l2_subdev *buf_mgr_subdev; }; #endif /* __MSM_CPP_H__ */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">chrisk44/android_kernel_lge_hammerhead</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/media/platform/msm/camera_v2/pproc/cpp/msm_cpp.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,681</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086505"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// 2001-11-25 Phil Edwards <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9aeaf7ffdafdf9f9b4fdf4efb4f5e8fd">[email protected]</a>> // // Copyright (C) 2001-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 20.4.1.1 allocator members #include <cstdlib> #include <ext/mt_allocator.h> #include <replacement_memory_operators.h> int main() { typedef __gnu_cxx::__mt_alloc<unsigned int> allocator_type; __gnu_test::check_delete<allocator_type, false>(); return 0; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">xinchoubiology/gcc</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">libstdc++-v3/testsuite/ext/mt_allocator/check_delete.cc</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C++</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,085</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086506"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/** * @license * Copyright 2013 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as ts from "typescript"; import * as Lint from "../index"; export declare class Rule extends Lint.Rules.AbstractRule { static metadata: Lint.IRuleMetadata; static FAILURE_STRING_FACTORY: (memberType: string, memberName: string | undefined, publicOnly: boolean) => string; apply(sourceFile: ts.SourceFile): Lint.RuleFailure[]; } export declare class MemberAccessWalker extends Lint.RuleWalker { visitConstructorDeclaration(node: ts.ConstructorDeclaration): void; visitMethodDeclaration(node: ts.MethodDeclaration): void; visitPropertyDeclaration(node: ts.PropertyDeclaration): void; visitGetAccessor(node: ts.AccessorDeclaration): void; visitSetAccessor(node: ts.AccessorDeclaration): void; private validateVisibilityModifiers(node); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mo-norant/FinHeartBel</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">website/node_modules/tslint/lib/rules/memberAccessRule.d.ts</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">TypeScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,404</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086507"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!doctype html> <html> <head> <title>Name test case 740</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "crazy Monday" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "crazy Monday" ] ], "IAccessible2" : [ [ "property", "accName", "is", "crazy Monday" ] ], "UIA" : [ [ "property", "Name", "is", "crazy Monday" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 740" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name test case 740.</p> <label for="test"> crazy <div role="spinbutton" aria-valuetext="Monday" aria-valuemin="1" aria-valuemax="7" aria-valuenow="4"> </div> </label> <input type="radio" id="test"/> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">UK992/servo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/wpt/web-platform-tests/accname/name_test_case_740-manual.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,849</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086508"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">'use strict'; var fs = require('fs'); var path = require('path'); var readdirp = require('readdirp'); var handlebars = require('handlebars'); var async = require('./async'); /** * Regex pattern for layout directive. {{!< layout }} */ var layoutPattern = /{{!<\s+([A-Za-z0-9\._\-\/]+)\s*}}/; /** * Constructor */ var ExpressHbs = function() { this.handlebars = handlebars.create(); this.SafeString = this.handlebars.SafeString; this.Utils = this.handlebars.Utils; this.beautify = null; this.beautifyrc = null; }; /** * Defines a block into which content is inserted via `content`. * * @example * In layout.hbs * * {{{block "pageStylesheets"}}} */ ExpressHbs.prototype.block = function(name) { var val = (this.blocks[name] || []).join('\n'); // free mem this.blocks[name] = null; return val; }; /** * Defines content for a named block declared in layout. * * @example * * {{#contentFor "pageStylesheets"}} * <link rel="stylesheet" href='{{{URL "css/style.css"}}}' /> * {{/contentFor}} */ ExpressHbs.prototype.content = function(name, options, context) { var block = this.blocks[name] || (this.blocks[name] = []); block.push(options.fn(context)); }; /** * Returns the layout filepath given the template filename and layout used. * Backward compatible with specifying layouts in locals like 'layouts/foo', * but if you have specified a layoutsDir you can specify layouts in locals with just the layout name. * * @param {String} filename Path to template file. * @param {String} layout Layout path. */ ExpressHbs.prototype.layoutPath = function(filename, layout) { var layoutPath; if (layout[0] === '.') { layoutPath = path.resolve(path.dirname(filename), layout); } else if (this.layoutsDir) { layoutPath = path.resolve(this.layoutsDir, layout); } else { layoutPath = path.resolve(this.viewsDir, layout); } return layoutPath; } /** * Find the path of the declared layout in `str`, if any * * @param {String} str The template string to parse * @param {String} filename Path to template * @returns {String|undefined} Returns the path to layout. */ ExpressHbs.prototype.declaredLayoutFile = function(str, filename) { var matches = str.match(layoutPattern); if (matches) { var layout = matches[1]; // behave like `require`, if '.' then relative, else look in // usual location (layoutsDir) if (this.layoutsDir && layout[0] !== '.') { layout = path.resolve(this.layoutsDir, layout); } return path.resolve(path.dirname(filename), layout); } }; /** * Compiles a layout file. * * The function checks whether the layout file declares a parent layout. * If it does, the parent layout is loaded recursively and checked as well * for a parent layout, and so on, until the top layout is reached. * All layouts are then returned as a stack to the caller via the callback. * * @param {String} layoutFile The path to the layout file to compile * @param {Boolean} useCache Cache the compiled layout? * @param {Function} cb Callback called with layouts stack */ ExpressHbs.prototype.cacheLayout = function(layoutFile, useCache, cb) { var self = this; // assume hbs extension if (path.extname(layoutFile) === '') layoutFile += this._options.extname; // path is relative in directive, make it absolute var layoutTemplates = this.cache[layoutFile]; if (layoutTemplates) return cb(null, layoutTemplates); fs.readFile(layoutFile, 'utf8', function(err, str) { if (err) return cb(err); // File path of eventual declared parent layout var parentLayoutFile = self.declaredLayoutFile(str, layoutFile); // This function returns the current layout stack to the caller var _returnLayouts = function(layouts) { var currentLayout; layouts = layouts.slice(0); currentLayout = self.compile(str, layoutFile); layouts.push(currentLayout); if (useCache) { self.cache[layoutFile] = layouts.slice(0); } cb(null, layouts); }; if (parentLayoutFile) { // Recursively compile/cache parent layouts self.cacheLayout(parentLayoutFile, useCache, function(err, parentLayouts) { if (err) return cb(err); _returnLayouts(parentLayouts); }); } else { // No parent layout: return current layout with an empty stack _returnLayouts([]); } }); }; /** * Cache partial templates found under directories configure in partialsDir. */ ExpressHbs.prototype.cachePartials = function(cb) { var self = this; if (!(this.partialsDir instanceof Array)) { this.partialsDir = [this.partialsDir]; } // Use to iterate all folder in series var count = 0; function readNext() { readdirp({ root: self.partialsDir[count], fileFilter: '*.*' }) .on('warn', function(err) { console.warn('Non-fatal error in express-hbs cachePartials.', err); }) .on('error', function(err) { console.error('Fatal error in express-hbs cachePartials', err); return cb(err); }) .on('data', function(entry) { if (!entry) return; var source = fs.readFileSync(entry.fullPath, 'utf8'); var dirname = path.dirname(entry.path); dirname = dirname === '.' ? '' : dirname + '/'; var name = dirname + path.basename(entry.name, path.extname(entry.name)); self.registerPartial(name, source); }) .on('end', function() { count += 1; // If all directories aren't read, read the next directory if (count < self.partialsDir.length) { readNext() } else { self.isPartialCachingComplete = true; cb && cb(null, true); } }); } readNext(); }; /** * Express 3.x template engine compliance. * * @param {Object} options = { * handlebars: "override handlebars", * defaultLayout: "path to default layout", * partialsDir: "absolute path to partials (one path or an array of paths)", * layoutsDir: "absolute path to the layouts", * extname: "extension to use", * contentHelperName: "contentFor", * blockHelperName: "block", * beautify: "{Boolean} whether to pretty print HTML" * } * */ ExpressHbs.prototype.express3 = function(options) { var self = this; // Set defaults if (!options) options = {}; if (!options.extname) options.extname = '.hbs'; if (!options.contentHelperName) options.contentHelperName = 'contentFor'; if (!options.blockHelperName) options.blockHelperName = 'block'; if (!options.templateOptions) options.templateOptions = {}; if (options.handlebars) this.handlebars = options.handlebars; this._options = options; if (this._options.handlebars) this.handlebars = this._options.handlebars; if (options.i18n) { var i18n = options.i18n; this.handlebars.registerHelper('__', function() { return i18n.__.apply(this, arguments); }); this.handlebars.registerHelper('__n', function() { return i18n.__n.apply(this, arguments); }); } this.handlebars.registerHelper(this._options.blockHelperName, function(name, options) { var val = self.block(name); if (val == '' && (typeof options.fn === 'function')) { val = options.fn(this); } // blocks may have async helpers if (val.indexOf('__aSyNcId_') >= 0) { if (self.asyncValues) { Object.keys(self.asyncValues).forEach(function (id) { val = val.replace(id, self.asyncValues[id]); val = val.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(self.asyncValues[id])); }); } } return val; }); // Pass 'this' as context of helper function to don't lose context call of helpers. this.handlebars.registerHelper(this._options.contentHelperName, function(name, options) { return self.content(name, options, this); }); // Absolute path to partials directory. this.partialsDir = this._options.partialsDir; // Absolute path to the layouts directory this.layoutsDir = this._options.layoutsDir; // express passes this through _express3 func, gulp pass in an option this.viewsDir = null this.viewsDirOpt = this._options.viewsDir; // Cache for templates, express 3.x doesn't do this for us this.cache = {}; // Blocks for layouts. Is this safe? What happens if the same block is used on multiple connections? // Isn't there a chance block and content are not in sync. The template and layout are processed asynchronously. this.blocks = {}; // Holds the default compiled layout if specified in options configuration. this.defaultLayoutTemplates = null; // Keep track of if partials have been cached already or not. this.isPartialCachingComplete = false; return _express3.bind(this); }; /** * Tries to load the default layout. * * @param {Boolean} useCache Whether to cache. */ ExpressHbs.prototype.loadDefaultLayout = function(useCache, cb) { var self = this; if (!this._options.defaultLayout) return cb(); if (useCache && this.defaultLayoutTemplates) return cb(null, this.defaultLayoutTemplates); this.cacheLayout(this._options.defaultLayout, useCache, function(err, templates) { if (err) return cb(err); self.defaultLayoutTemplates = templates.slice(0); return cb(null, templates); }); }; /** * express 3.x template engine compliance * * @param {String} filename Full path to template. * @param {Object} options Is the context or locals for templates. { * {Object} settings - subset of Express settings, `settings.views` is * the views directory * } * @param {Function} cb The callback expecting the rendered template as a string. * * @example * * Example options from express * * { * settings: { * 'x-powered-by': true, * env: 'production', * views: '/home/coder/barc/code/express-hbs/example/views', * 'jsonp callback name': 'callback', * 'view cache': true, * 'view engine': 'hbs' * }, * cache: true, * * // the rest are app-defined locals * title: 'My favorite veggies', * layout: 'layout/veggie' * } */ function _express3(filename, source, options, cb) { // console.log('filename', filename); // console.log('options', options); // support running as a gulp/grunt filter outside of express if (arguments.length === 3) { cb = options; options = source; source = null; } this.viewsDir = options.settings.views || this.viewsDirOpt; var self = this; /** * Allow a layout to be declared as a handlebars comment to remain spec * compatible with handlebars. * * Valid directives * * {{!< foo}} # foo.hbs in same directory as template * {{!< ../layouts/default}} # default.hbs in parent layout directory * {{!< ../layouts/default.html}} # default.html in parent layout directory */ function parseLayout(str, filename, cb) { var layoutFile = self.declaredLayoutFile(str, filename); if (layoutFile) { self.cacheLayout(layoutFile, options.cache, cb); } else { cb(null, null); } } /** * Renders `template` with given `locals` and calls `cb` with the * resulting HTML string. * * @param template * @param locals * @param cb */ function renderTemplate(template, locals, cb) { var res; try { res = template(locals, self._options.templateOptions); } catch (err) { if (err.message) { err.message = '[' + template.__filename + '] ' + err.message; } else if (typeof err === 'string') { err = '[' + template.__filename + '] ' + err; } return cb(err, null); } // Wait for async helpers async.done(function (values) { // Save for layout. Block helpers are called within layout, not in the // current template. self.asyncValues = values; Object.keys(values).forEach(function (id) { res = res.replace(id, values[id]); res = res.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(values[id])); }); cb(null, res); }); } /** * Renders `template` with an optional set of nested `layoutTemplates` using * data in `locals`. */ function render(template, locals, layoutTemplates, cb) { if (layoutTemplates == undefined) layoutTemplates = []; // We'll render templates from bottom to top of the stack, each template // being passed the rendered string of the previous ones as `body` var i = layoutTemplates.length - 1; var _stackRenderer = function(err, htmlStr) { if (err) return cb(err); if (i >= 0) { locals.body = htmlStr; renderTemplate(layoutTemplates[i--], locals, _stackRenderer); } else { cb(null, htmlStr); } }; // Start the rendering with the innermost page template renderTemplate(template, locals, _stackRenderer); } /** * Lazy loads js-beautify, which shouldn't be used in production env. */ function loadBeautify() { if (!self.beautify) { self.beautify = require('js-beautify').html; var rc = path.join(process.cwd(), '.jsbeautifyrc'); if (fs.existsSync(rc)) { self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8')); } } } /** * Compiles a file into a template and a layoutTemplate, then renders it above. */ function compileFile(locals, cb) { var source, info, template; if (options.cache) { info = self.cache[filename]; if (info) { source = info.source; template = info.template; } } if (!info) { source = fs.readFileSync(filename, 'utf8'); template = self.compile(source, filename); if (options.cache) { self.cache[filename] = { source: source, template: template }; } } // Try to get the layout parseLayout(source, filename, function (err, layoutTemplates) { if (err) return cb(err); function renderIt(layoutTemplates) { if (self._options.beautify) { return render(template, locals, layoutTemplates, function(err, html) { if (err) return cb(err); loadBeautify(); return cb(null, self.beautify(html, self.beautifyrc)); }); } else { return render(template, locals, layoutTemplates, cb); } } // Determine which layout to use // If options.layout is falsy, behave as if no layout should be used - suppress defaults if ((typeof (options.layout) !== 'undefined') && !options.layout) { renderIt(null); } else { // 1. Layout specified in template if (layoutTemplates) { renderIt(layoutTemplates); } // 2. Layout specified by options from render else if ((typeof (options.layout) !== 'undefined') && options.layout) { var layoutFile = self.layoutPath(filename, options.layout); self.cacheLayout(layoutFile, options.cache, function (err, layoutTemplates) { if (err) return cb(err); renderIt(layoutTemplates); }); } // 3. Default layout specified when middleware was configured. else if (self.defaultLayoutTemplates) { renderIt(self.defaultLayoutTemplates); } // render without a template else renderIt(null); } }); } // kick it off by loading default template (if any) this.loadDefaultLayout(options.cache, function(err) { if (err) return cb(err); // Force reloading of all partials if caching is not used. Inefficient but there // is no loading partial event. if (self.partialsDir && (!options.cache || !self.isPartialCachingComplete)) { return self.cachePartials(function(err) { if (err) return cb(err); return compileFile(options, cb); }); } return compileFile(options, cb); }); } /** * Expose useful methods. */ ExpressHbs.prototype.registerHelper = function(name, fn) { this.handlebars.registerHelper(name, fn); }; /** * Registers a partial. * * @param {String} name The name of the partial as used in a template. * @param {String} source String source of the partial. */ ExpressHbs.prototype.registerPartial = function(name, source) { this.handlebars.registerPartial(name, this.compile(source)); }; /** * Compiles a string. * * @param {String} source The source to compile. * @param {String} filename The path used to embed into __filename for errors. */ ExpressHbs.prototype.compile = function(source, filename) { // Handlebars has a bug with comment only partial causes errors. This must // be a string so the block below can add a space. if (typeof source !== 'string') { throw new Error('registerPartial must be a string for empty comment workaround'); } if (source.indexOf('}}') === source.length - 2) { source += ' '; } var compiled = this.handlebars.compile(source); if (filename) { // track for error message compiled.__filename = path.relative(this.viewsDir, filename).replace(path.sep, '/'); } return compiled; } /** * Registers an asynchronous helper. * * @param {String} name The name of the partial as used in a template. * @param {String} fn The `function(options, cb)` */ ExpressHbs.prototype.registerAsyncHelper = function(name, fn) { this.handlebars.registerHelper(name, function(context) { return async.resolve(fn.bind(this), context); }); }; ExpressHbs.prototype.updateTemplateOptions = function(templateOptions) { this._options.templateOptions = templateOptions; }; /** * Creates a new instance of ExpressHbs. */ ExpressHbs.prototype.create = function() { return new ExpressHbs(); }; module.exports = new ExpressHbs(); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vietpn/ghost-nodejs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">node_modules/express-hbs/lib/hbs.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">17,800</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086509"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// 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.IO; namespace System.Net { /// <summary> /// <para>The FtpWebResponse class contains the result of the FTP request. /// </summary> public class FtpWebResponse : WebResponse, IDisposable { internal Stream _responseStream; private long _contentLength; private Uri _responseUri; private FtpStatusCode _statusCode; private string _statusLine; private WebHeaderCollection _ftpRequestHeaders; private DateTime _lastModified; private string _bannerMessage; private string _welcomeMessage; private string _exitMessage; internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine); _responseStream = responseStream; if (responseStream == null && contentLength < 0) { contentLength = 0; } _contentLength = contentLength; _responseUri = responseUri; _statusCode = statusCode; _statusLine = statusLine; _lastModified = lastModified; _bannerMessage = bannerMessage; _welcomeMessage = welcomeMessage; _exitMessage = exitMessage; } internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage) { _statusCode = statusCode; _statusLine = statusLine; _exitMessage = exitMessage; } public override Stream GetResponseStream() { Stream responseStream = null; if (_responseStream != null) { responseStream = _responseStream; } else { responseStream = _responseStream = new EmptyStream(); } return responseStream; } internal sealed class EmptyStream : MemoryStream { internal EmptyStream() : base(Array.Empty<byte>(), false) { } } internal void SetResponseStream(Stream stream) { if (stream == null || stream == Stream.Null || stream is EmptyStream) return; _responseStream = stream; } /// <summary> /// <para>Closes the underlying FTP response stream, but does not close control connection</para> /// </summary> public override void Close() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); _responseStream?.Close(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } /// <summary> /// <para>Queries the length of the response</para> /// </summary> public override long ContentLength { get { return _contentLength; } } internal void SetContentLength(long value) { _contentLength = value; } public override WebHeaderCollection Headers { get { if (_ftpRequestHeaders == null) { lock (this) { if (_ftpRequestHeaders == null) { _ftpRequestHeaders = new WebHeaderCollection(); } } } return _ftpRequestHeaders; } } public override bool SupportsHeaders { get { return true; } } /// <summary> /// <para>Shows the final Uri that the FTP request ended up on</para> /// </summary> public override Uri ResponseUri { get { return _responseUri; } } /// <summary> /// <para>Last status code retrived</para> /// </summary> public FtpStatusCode StatusCode { get { return _statusCode; } } /// <summary> /// <para>Last status line retrived</para> /// </summary> public string StatusDescription { get { return _statusLine; } } /// <summary> /// <para>Returns last modified date time for given file (null if not relavant/avail)</para> /// </summary> public DateTime LastModified { get { return _lastModified; } } /// <summary> /// <para>Returns the server message sent before user credentials are sent</para> /// </summary> public string BannerMessage { get { return _bannerMessage; } } /// <summary> /// <para>Returns the server message sent after user credentials are sent</para> /// </summary> public string WelcomeMessage { get { return _welcomeMessage; } } /// <summary> /// <para>Returns the exit sent message on shutdown</para> /// </summary> public string ExitMessage { get { return _exitMessage; } } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">krk/corefx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/System.Net.Requests/src/System/Net/FtpWebResponse.cs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C#</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,923</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086510"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">WebMock.disable_net_connect!(allow: 'coveralls.io') # iTunes Lookup API RSpec.configure do |config| config.before(:each) do # iTunes Lookup API by Apple ID ["invalid", "", 0, '284882215', ['338986109', 'FR']].each do |current| if current.kind_of? Array id = current[0] country = current[1] url = "https://itunes.apple.com/lookup?id=#{id}&country=#{country}" body_file = "spec/responses/itunesLookup-#{id}_#{country}.json" else id = current url = "https://itunes.apple.com/lookup?id=#{id}" body_file = "spec/responses/itunesLookup-#{id}.json" end stub_request(:get, url). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read(body_file), headers: {}) end # iTunes Lookup API by App Identifier stub_request(:get, "https://itunes.apple.com/lookup?bundleId=com.facebook.Facebook"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-com.facebook.Facebook.json"), headers: {}) stub_request(:get, "https://itunes.apple.com/lookup?bundleId=net.sunapps.invalid"). with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }). to_return(status: 200, body: File.read("spec/responses/itunesLookup-net.sunapps.invalid.json"), headers: {}) end end describe FastlaneCore do describe FastlaneCore::ItunesSearchApi do it "returns nil when it could not be found" do expect(FastlaneCore::ItunesSearchApi.fetch("invalid")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch("")).to eq(nil) expect(FastlaneCore::ItunesSearchApi.fetch(0)).to eq(nil) end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch("284882215") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(FastlaneCore::ItunesSearchApi.fetch_bundle_identifier("284882215")).to eq('com.facebook.Facebook') end it "returns the actual object if it could be found" do response = FastlaneCore::ItunesSearchApi.fetch_by_identifier("com.facebook.Facebook") expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(284_882_215) end it "can find country specific object" do response = FastlaneCore::ItunesSearchApi.fetch(338_986_109, 'FR') expect(response['kind']).to eq('software') expect(response['supportedDevices'].count).to be > 8 expect(response['trackId']).to eq(338_986_109) end end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mathiasAichinger/fastlane_core</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">spec/itunes_search_api_spec.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,907</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086511"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* shmbutil.h -- utility functions for multibyte characters. */ /* Copyright (C) 2002-2004 Free Software Foundation, Inc. This file is part of GNU Bash, the Bourne Again SHell. Bash 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. Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>. */ #if !defined (_SH_MBUTIL_H_) #define _SH_MBUTIL_H_ #include "stdc.h" /* Include config.h for HANDLE_MULTIBYTE */ #include <config.h> #if defined (HANDLE_MULTIBYTE) #include "shmbchar.h" extern size_t xmbsrtowcs __P((wchar_t *, const char **, size_t, mbstate_t *)); extern size_t xdupmbstowcs __P((wchar_t **, char ***, const char *)); extern size_t mbstrlen __P((const char *)); extern char *xstrchr __P((const char *, int)); #ifndef MB_INVALIDCH #define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2) #define MB_NULLWCH(x) ((x) == 0) #endif #define MBSLEN(s) (((s) && (s)[0]) ? ((s)[1] ? mbstrlen (s) : 1) : 0) #define MB_STRLEN(s) ((MB_CUR_MAX > 1) ? MBSLEN (s) : STRLEN (s)) #define MBLEN(s, n) ((MB_CUR_MAX > 1) ? mblen ((s), (n)) : 1) #define MBRLEN(s, n, p) ((MB_CUR_MAX > 1) ? mbrlen ((s), (n), (p)) : 1) #else /* !HANDLE_MULTIBYTE */ #undef MB_LEN_MAX #undef MB_CUR_MAX #define MB_LEN_MAX 1 #define MB_CUR_MAX 1 #undef xstrchr #define xstrchr(s, c) strchr(s, c) #ifndef MB_INVALIDCH #define MB_INVALIDCH(x) (0) #define MB_NULLWCH(x) (0) #endif #define MB_STRLEN(s) (STRLEN(s)) #define MBLEN(s, n) 1 #define MBRLEN(s, n, p) 1 #ifndef wchar_t # define wchar_t int #endif #endif /* !HANDLE_MULTIBYTE */ /* Declare and initialize a multibyte state. Call must be terminated with `;'. */ #if defined (HANDLE_MULTIBYTE) # define DECLARE_MBSTATE \ mbstate_t state; \ memset (&state, '\0', sizeof (mbstate_t)) #else # define DECLARE_MBSTATE #endif /* !HANDLE_MULTIBYTE */ /* Initialize or reinitialize a multibyte state named `state'. Call must be terminated with `;'. */ #if defined (HANDLE_MULTIBYTE) # define INITIALIZE_MBSTATE memset (&state, '\0', sizeof (mbstate_t)) #else # define INITIALIZE_MBSTATE #endif /* !HANDLE_MULTIBYTE */ /* Advance one (possibly multi-byte) character in string _STR of length _STRSIZE, starting at index _I. STATE must have already been declared. */ #if defined (HANDLE_MULTIBYTE) # define ADVANCE_CHAR(_str, _strsize, _i) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _f; \ \ _f = is_basic ((_str)[_i]); \ if (_f) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_str) + (_i), (_strsize) - (_i), &state); \ } \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ (_i)++; \ } \ else if (mblength == 0) \ (_i)++; \ else \ (_i) += mblength; \ } \ else \ (_i)++; \ } \ while (0) #else # define ADVANCE_CHAR(_str, _strsize, _i) (_i)++ #endif /* !HANDLE_MULTIBYTE */ /* Advance one (possibly multibyte) character in the string _STR of length _STRSIZE. SPECIAL: assume that _STR will be incremented by 1 after this call. */ #if defined (HANDLE_MULTIBYTE) # define ADVANCE_CHAR_P(_str, _strsize) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _f; \ \ _f = is_basic (*(_str)); \ if (_f) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_str), (_strsize), &state); \ } \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ (_str) += (mblength < 1) ? 0 : (mblength - 1); \ } \ } \ while (0) #else # define ADVANCE_CHAR_P(_str, _strsize) #endif /* !HANDLE_MULTIBYTE */ /* Back up one (possibly multi-byte) character in string _STR of length _STRSIZE, starting at index _I. STATE must have already been declared. */ #if defined (HANDLE_MULTIBYTE) # define BACKUP_CHAR(_str, _strsize, _i) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _x, _p; /* _x == temp index into string, _p == prev index */ \ \ _x = _p = 0; \ while (_x < (_i)) \ { \ state_bak = state; \ mblength = mbrlen ((_str) + (_x), (_strsize) - (_x), &state); \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ _x++; \ } \ else if (mblength == 0) \ _x++; \ else \ { \ _p = _x; /* _p == start of prev mbchar */ \ _x += mblength; \ } \ } \ (_i) = _p; \ } \ else \ (_i)--; \ } \ while (0) #else # define BACKUP_CHAR(_str, _strsize, _i) (_i)-- #endif /* !HANDLE_MULTIBYTE */ /* Back up one (possibly multibyte) character in the string _BASE of length _STRSIZE starting at _STR (_BASE <= _STR <= (_BASE + _STRSIZE) ). SPECIAL: DO NOT assume that _STR will be decremented by 1 after this call. */ #if defined (HANDLE_MULTIBYTE) # define BACKUP_CHAR_P(_base, _strsize, _str) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ char *_x, _p; /* _x == temp pointer into string, _p == prev pointer */ \ \ _x = _p = _base; \ while (_x < (_str)) \ { \ state_bak = state; \ mblength = mbrlen (_x, (_strsize) - _x, &state); \ \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ _x++; \ } \ else if (mblength == 0) \ _x++; \ else \ { \ _p = _x; /* _p == start of prev mbchar */ \ _x += mblength; \ } \ } \ (_str) = _p; \ } \ else \ (_str)--; \ } \ while (0) #else # define BACKUP_CHAR_P(_base, _strsize, _str) (_str)-- #endif /* !HANDLE_MULTIBYTE */ /* Copy a single character from the string _SRC to the string _DST. _SRCEND is a pointer to the end of _SRC. */ #if defined (HANDLE_MULTIBYTE) # define COPY_CHAR_P(_dst, _src, _srcend) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _k; \ \ _k = is_basic (*(_src)); \ if (_k) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_src), (_srcend) - (_src), &state); \ } \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ for (_k = 0; _k < mblength; _k++) \ *(_dst)++ = *(_src)++; \ } \ else \ *(_dst)++ = *(_src)++; \ } \ while (0) #else # define COPY_CHAR_P(_dst, _src, _srcend) *(_dst)++ = *(_src)++ #endif /* !HANDLE_MULTIBYTE */ /* Copy a single character from the string _SRC at index _SI to the string _DST at index _DI. _SRCEND is a pointer to the end of _SRC. */ #if defined (HANDLE_MULTIBYTE) # define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _k; \ \ _k = is_basic (*((_src) + (_si))); \ if (_k) \ mblength = 1; \ else \ {\ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src)+(_si)), &state); \ } \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ for (_k = 0; _k < mblength; _k++) \ _dst[_di++] = _src[_si++]; \ } \ else \ _dst[_di++] = _src[_si++]; \ } \ while (0) #else # define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) _dst[_di++] = _src[_si++] #endif /* !HANDLE_MULTIBYTE */ /**************************************************************** * * * The following are only guaranteed to work in subst.c * * * ****************************************************************/ #if defined (HANDLE_MULTIBYTE) # define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _i; \ \ _i = is_basic (*((_src) + (_si))); \ if (_i) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_slen) - (_si), &state); \ } \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ temp = xmalloc (mblength + 2); \ temp[0] = _escchar; \ for (_i = 0; _i < mblength; _i++) \ temp[_i + 1] = _src[_si++]; \ temp[mblength + 1] = '\0'; \ \ goto add_string; \ } \ else \ { \ _dst[0] = _escchar; \ _dst[1] = _sc; \ } \ } \ while (0) #else # define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \ _dst[0] = _escchar; \ _dst[1] = _sc #endif /* !HANDLE_MULTIBYTE */ #if defined (HANDLE_MULTIBYTE) # define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ mbstate_t state_bak; \ size_t mblength; \ int _i; \ \ _i = is_basic (*((_src) + (_si))); \ if (_i) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src) + (_si)), &state); \ } \ if (mblength == (size_t)-2 || mblength == (size_t)-1) \ { \ state = state_bak; \ mblength = 1; \ } \ else \ mblength = (mblength < 1) ? 1 : mblength; \ \ FASTCOPY(((_src) + (_si)), (_dst), mblength); \ \ (_dst) += mblength; \ (_si) += mblength; \ } \ else \ { \ *(_dst)++ = _src[(_si)]; \ (_si)++; \ } \ } \ while (0) #else # define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \ *(_dst)++ = _src[(_si)]; \ (_si)++ #endif /* !HANDLE_MULTIBYTE */ #if HANDLE_MULTIBYTE # define SADD_MBCHAR(_dst, _src, _si, _srcsize) \ do \ { \ if (MB_CUR_MAX > 1) \ { \ int i; \ mbstate_t state_bak; \ size_t mblength; \ \ i = is_basic (*((_src) + (_si))); \ if (i) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \ } \ if (mblength == (size_t)-1 || mblength == (size_t)-2) \ { \ state = state_bak; \ mblength = 1; \ } \ if (mblength < 1) \ mblength = 1; \ \ _dst = (char *)xmalloc (mblength + 1); \ for (i = 0; i < mblength; i++) \ (_dst)[i] = (_src)[(_si)++]; \ (_dst)[mblength] = '\0'; \ \ goto add_string; \ } \ } \ while (0) #else # define SADD_MBCHAR(_dst, _src, _si, _srcsize) #endif /* Watch out when using this -- it's just straight textual subsitution */ #if defined (HANDLE_MULTIBYTE) # define SADD_MBQCHAR_BODY(_dst, _src, _si, _srcsize) \ \ int i; \ mbstate_t state_bak; \ size_t mblength; \ \ i = is_basic (*((_src) + (_si))); \ if (i) \ mblength = 1; \ else \ { \ state_bak = state; \ mblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \ } \ if (mblength == (size_t)-1 || mblength == (size_t)-2) \ { \ state = state_bak; \ mblength = 1; \ } \ if (mblength < 1) \ mblength = 1; \ \ (_dst) = (char *)xmalloc (mblength + 2); \ (_dst)[0] = CTLESC; \ for (i = 0; i < mblength; i++) \ (_dst)[i+1] = (_src)[(_si)++]; \ (_dst)[mblength+1] = '\0'; \ \ goto add_string #endif /* HANDLE_MULTIBYTE */ #endif /* _SH_MBUTIL_H_ */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tavaresdong/courses-notes</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">uw_cse333/hw/projdocs/test_tree/bash-4.2/include/shmbutil.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">12,303</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086512"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">var baz = "baz"; export default baz; </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">EliteScientist/webpack</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">test/statsCases/import-context-filter/templates/baz.noimport.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">38</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086513"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* $NoKeywords:$ */ /** * @file * * ma.h * * ARDK common header file * * @xrefitem bom "File Content Label" "Release Content" * @e project: AGESA * @e sub-project: (Mem) * @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $ * **/ /***************************************************************************** * * Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Advanced Micro Devices, Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. 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. * *************************************************************************** * */ #ifndef _MA_H_ #define _MA_H_ /*---------------------------------------------------------------------------- * Mixed (DEFINITIONS AND MACROS / TYPEDEFS, STRUCTURES, ENUMS) * *---------------------------------------------------------------------------- */ /*----------------------------------------------------------------------------- * DEFINITIONS AND MACROS * *----------------------------------------------------------------------------- */ #define MAX_CS_PER_CHANNEL 8 ///< Max CS per channel /*---------------------------------------------------------------------------- * TYPEDEFS, STRUCTURES, ENUMS * *---------------------------------------------------------------------------- */ /** MARDK Structure*/ typedef struct { UINT16 Speed; ///< Dram speed in MHz UINT8 Loads; ///< Number of Data Loads UINT32 AddrTmg; ///< Address Timing value UINT32 Odc; ///< Output Driver Compensation Value } PSCFG_ENTRY; /** MARDK Structure*/ typedef struct { UINT16 Speed; ///< Dram speed in MHz UINT8 Loads; ///< Number of Data Loads UINT32 AddrTmg; ///< Address Timing value UINT32 Odc; ///< Output Driver Compensation Value UINT8 Dimms; ///< Number of Dimms } ADV_PSCFG_ENTRY; /** MARDK Structure for RDIMMs*/ typedef struct { UINT16 Speed; ///< Dram speed in MHz UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3 UINT32 AddrTmg; ///< Address Timing value UINT16 RC2RC8; ///< RC2 and RC8 value //High byte: 1st pair value, Low byte: 2nd pair value UINT8 Dimms; ///< Number of Dimms } ADV_R_PSCFG_ENTRY; /** MARDK Structure*/ typedef struct { UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3 UINT32 PhyRODTCSLow; ///< Fn2_9C 180 UINT32 PhyRODTCSHigh; ///< Fn2_9C 181 UINT32 PhyWODTCSLow; ///< Fn2_9C 182 UINT32 PhyWODTCSHigh; ///< Fn2_9C 183 UINT8 Dimms; ///< Number of Dimms } ADV_PSCFG_ODT_ENTRY; /** MARDK Structure for Write Levelization ODT*/ typedef struct { UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3 UINT8 PhyWrLvOdt[MAX_CS_PER_CHANNEL / 2]; ///< WrLvOdt (Fn2_9C_0x08[11:8]) Value for each Dimm UINT8 Dimms; ///< Number of Dimms } ADV_R_PSCFG_WL_ODT_ENTRY; /*---------------------------------------------------------------------------- * FUNCTIONS PROTOTYPE * *---------------------------------------------------------------------------- */ AGESA_STATUS MemAGetPsCfgDef ( IN OUT MEM_DATA_STRUCT *MemData, IN UINT8 SocketID, IN OUT CH_DEF_STRUCT *CurrentChannel ); UINT16 MemAGetPsRankType ( IN CH_DEF_STRUCT *CurrentChannel ); AGESA_STATUS MemRecNGetPsCfgDef ( IN OUT MEM_DATA_STRUCT *MemData, IN UINT8 SocketID, IN OUT CH_DEF_STRUCT *CurrentChannel ); UINT16 MemRecNGetPsRankType ( IN CH_DEF_STRUCT *CurrentChannel ); AGESA_STATUS MemRecNGetPsCfgUDIMM3Nb ( IN OUT MEM_DATA_STRUCT *MemData, IN UINT8 SocketID, IN OUT CH_DEF_STRUCT *CurrentChannel ); AGESA_STATUS MemRecNGetPsCfgSODIMM3Nb ( IN OUT MEM_DATA_STRUCT *MemData, IN UINT8 SocketID, IN OUT CH_DEF_STRUCT *CurrentChannel ); AGESA_STATUS MemRecNGetPsCfgRDIMM3Nb ( IN OUT MEM_DATA_STRUCT *MemData, IN UINT8 SocketID, IN OUT CH_DEF_STRUCT *CurrentChannel ); #endif /* _MA_H_ */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">BTDC/coreboot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/vendorcode/amd/agesa/f16kb/Proc/Mem/ma.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,015</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086514"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* $NoKeywords:$ */ /** * @file * * PCIe training library * * * * @xrefitem bom "File Content Label" "Release Content" * @e project: AGESA * @e sub-project: GNB * @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $ * */ /* ***************************************************************************** * * Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Advanced Micro Devices, Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. 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. * *************************************************************************** * */ #ifndef _GNBPCIETRAININGV2_H_ #define _GNBPCIETRAININGV2_H_ #include "PcieTrainingV2.h" #include "PcieWorkaroundsV2.h" #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">BTDC/coreboot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/vendorcode/amd/agesa/f16kb/Proc/GNB/Modules/GnbPcieTrainingV2/GnbPcieTrainingV2.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,173</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086515"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (C) 2002 Roman Zippel <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="443e2d3434212804282d2a313c6929727c2f6a2b3623">[email protected]</a>> * Released under the terms of the GNU GPL v2.0. */ #include <stdlib.h> #include <string.h> #define LKC_DIRECT_LINK #include "lkc.h" struct menu rootmenu; static struct menu **last_entry_ptr; struct file *file_list; struct file *current_file; static void menu_warn(struct menu *menu, const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s:%d:warning: ", menu->file->name, menu->lineno); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } static void prop_warn(struct property *prop, const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s:%d:warning: ", prop->file->name, prop->lineno); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void menu_init(void) { current_entry = current_menu = &rootmenu; last_entry_ptr = &rootmenu.list; } void menu_add_entry(struct symbol *sym) { struct menu *menu; menu = malloc(sizeof(*menu)); memset(menu, 0, sizeof(*menu)); menu->sym = sym; menu->parent = current_menu; menu->file = current_file; menu->lineno = zconf_lineno(); *last_entry_ptr = menu; last_entry_ptr = &menu->next; current_entry = menu; } void menu_end_entry(void) { } struct menu *menu_add_menu(void) { menu_end_entry(); last_entry_ptr = &current_entry->list; return current_menu = current_entry; } void menu_end_menu(void) { last_entry_ptr = &current_menu->next; current_menu = current_menu->parent; } struct expr *menu_check_dep(struct expr *e) { if (!e) return e; switch (e->type) { case E_NOT: e->left.expr = menu_check_dep(e->left.expr); break; case E_OR: case E_AND: e->left.expr = menu_check_dep(e->left.expr); e->right.expr = menu_check_dep(e->right.expr); break; case E_SYMBOL: /* change 'm' into 'm' && MODULES */ if (e->left.sym == &symbol_mod) return expr_alloc_and(e, expr_alloc_symbol(modules_sym)); break; default: break; } return e; } void menu_add_dep(struct expr *dep) { current_entry->dep = expr_alloc_and(current_entry->dep, menu_check_dep(dep)); } void menu_set_type(int type) { struct symbol *sym = current_entry->sym; if (sym->type == type) return; if (sym->type == S_UNKNOWN) { sym->type = type; return; } menu_warn(current_entry, "type of '%s' redefined from '%s' to '%s'", sym->name ? sym->name : "<choice>", sym_type_name(sym->type), sym_type_name(type)); } struct property *menu_add_prop(enum prop_type type, char *prompt, struct expr *expr, struct expr *dep) { struct property *prop = prop_alloc(type, current_entry->sym); prop->menu = current_entry; prop->expr = expr; prop->visible.expr = menu_check_dep(dep); if (prompt) { if (isspace(*prompt)) { prop_warn(prop, "leading whitespace ignored"); while (isspace(*prompt)) prompt++; } if (current_entry->prompt) prop_warn(prop, "prompt redefined"); current_entry->prompt = prop; } prop->text = prompt; return prop; } struct property *menu_add_prompt(enum prop_type type, char *prompt, struct expr *dep) { return menu_add_prop(type, prompt, NULL, dep); } void menu_add_expr(enum prop_type type, struct expr *expr, struct expr *dep) { menu_add_prop(type, NULL, expr, dep); } void menu_add_symbol(enum prop_type type, struct symbol *sym, struct expr *dep) { menu_add_prop(type, NULL, expr_alloc_symbol(sym), dep); } void menu_add_option(int token, char *arg) { struct property *prop; switch (token) { case T_OPT_MODULES: prop = prop_alloc(P_DEFAULT, modules_sym); prop->expr = expr_alloc_symbol(current_entry->sym); break; case T_OPT_DEFCONFIG_LIST: if (!sym_defconfig_list) sym_defconfig_list = current_entry->sym; else if (sym_defconfig_list != current_entry->sym) zconf_error("trying to redefine defconfig symbol"); break; } } static int menu_range_valid_sym(struct symbol *sym, struct symbol *sym2) { return sym2->type == S_INT || sym2->type == S_HEX || (sym2->type == S_UNKNOWN && sym_string_valid(sym, sym2->name)); } void sym_check_prop(struct symbol *sym) { struct property *prop; struct symbol *sym2; for (prop = sym->prop; prop; prop = prop->next) { switch (prop->type) { case P_DEFAULT: if ((sym->type == S_STRING || sym->type == S_INT || sym->type == S_HEX) && prop->expr->type != E_SYMBOL) prop_warn(prop, "default for config symbol '%'" " must be a single symbol", sym->name); break; case P_SELECT: sym2 = prop_get_symbol(prop); if (sym->type != S_BOOLEAN && sym->type != S_TRISTATE) prop_warn(prop, "config symbol '%s' uses select, but is " "not boolean or tristate", sym->name); else if (sym2->type == S_UNKNOWN) prop_warn(prop, "'select' used by config symbol '%s' " "refers to undefined symbol '%s'", sym->name, sym2->name); else if (sym2->type != S_BOOLEAN && sym2->type != S_TRISTATE) prop_warn(prop, "'%s' has wrong type. 'select' only " "accept arguments of boolean and " "tristate type", sym2->name); break; case P_RANGE: if (sym->type != S_INT && sym->type != S_HEX) prop_warn(prop, "range is only allowed " "for int or hex symbols"); if (!menu_range_valid_sym(sym, prop->expr->left.sym) || !menu_range_valid_sym(sym, prop->expr->right.sym)) prop_warn(prop, "range is invalid"); break; default: ; } } } void menu_finalize(struct menu *parent) { struct menu *menu, *last_menu; struct symbol *sym; struct property *prop; struct expr *parentdep, *basedep, *dep, *dep2, **ep; sym = parent->sym; if (parent->list) { if (sym && sym_is_choice(sym)) { /* find the first choice value and find out choice type */ for (menu = parent->list; menu; menu = menu->next) { if (menu->sym) { current_entry = parent; menu_set_type(menu->sym->type); current_entry = menu; menu_set_type(sym->type); break; } } parentdep = expr_alloc_symbol(sym); } else if (parent->prompt) parentdep = parent->prompt->visible.expr; else parentdep = parent->dep; for (menu = parent->list; menu; menu = menu->next) { basedep = expr_transform(menu->dep); basedep = expr_alloc_and(expr_copy(parentdep), basedep); basedep = expr_eliminate_dups(basedep); menu->dep = basedep; if (menu->sym) prop = menu->sym->prop; else prop = menu->prompt; for (; prop; prop = prop->next) { if (prop->menu != menu) continue; dep = expr_transform(prop->visible.expr); dep = expr_alloc_and(expr_copy(basedep), dep); dep = expr_eliminate_dups(dep); if (menu->sym && menu->sym->type != S_TRISTATE) dep = expr_trans_bool(dep); prop->visible.expr = dep; if (prop->type == P_SELECT) { struct symbol *es = prop_get_symbol(prop); es->rev_dep.expr = expr_alloc_or(es->rev_dep.expr, expr_alloc_and(expr_alloc_symbol(menu->sym), expr_copy(dep))); } } } for (menu = parent->list; menu; menu = menu->next) menu_finalize(menu); } else if (sym) { basedep = parent->prompt ? parent->prompt->visible.expr : NULL; basedep = expr_trans_compare(basedep, E_UNEQUAL, &symbol_no); basedep = expr_eliminate_dups(expr_transform(basedep)); last_menu = NULL; for (menu = parent->next; menu; menu = menu->next) { dep = menu->prompt ? menu->prompt->visible.expr : menu->dep; if (!expr_contains_symbol(dep, sym)) break; if (expr_depends_symbol(dep, sym)) goto next; dep = expr_trans_compare(dep, E_UNEQUAL, &symbol_no); dep = expr_eliminate_dups(expr_transform(dep)); dep2 = expr_copy(basedep); expr_eliminate_eq(&dep, &dep2); expr_free(dep); if (!expr_is_yes(dep2)) { expr_free(dep2); break; } expr_free(dep2); next: menu_finalize(menu); menu->parent = parent; last_menu = menu; } if (last_menu) { parent->list = parent->next; parent->next = last_menu->next; last_menu->next = NULL; } } for (menu = parent->list; menu; menu = menu->next) { if (sym && sym_is_choice(sym) && menu->sym) { menu->sym->flags |= SYMBOL_CHOICEVAL; if (!menu->prompt) menu_warn(menu, "choice value must have a prompt"); for (prop = menu->sym->prop; prop; prop = prop->next) { if (prop->type == P_PROMPT && prop->menu != menu) { prop_warn(prop, "choice values " "currently only support a " "single prompt"); } if (prop->type == P_DEFAULT) prop_warn(prop, "defaults for choice " "values not supported"); } current_entry = menu; menu_set_type(sym->type); menu_add_symbol(P_CHOICE, sym, NULL); prop = sym_get_choice_prop(sym); for (ep = &prop->expr; *ep; ep = &(*ep)->left.expr) ; *ep = expr_alloc_one(E_CHOICE, NULL); (*ep)->right.sym = menu->sym; } if (menu->list && (!menu->prompt || !menu->prompt->text)) { for (last_menu = menu->list; ; last_menu = last_menu->next) { last_menu->parent = parent; if (!last_menu->next) break; } last_menu->next = menu->next; menu->next = menu->list; menu->list = NULL; } } if (sym && !(sym->flags & SYMBOL_WARNED)) { if (sym->type == S_UNKNOWN) menu_warn(parent, "config symbol defined without type"); if (sym_is_choice(sym) && !parent->prompt) menu_warn(parent, "choice must have a prompt"); /* Check properties connected to this symbol */ sym_check_prop(sym); sym->flags |= SYMBOL_WARNED; } if (sym && !sym_is_optional(sym) && parent->prompt) { sym->rev_dep.expr = expr_alloc_or(sym->rev_dep.expr, expr_alloc_and(parent->prompt->visible.expr, expr_alloc_symbol(&symbol_mod))); } } bool menu_is_visible(struct menu *menu) { struct menu *child; struct symbol *sym; tristate visible; if (!menu->prompt) return false; sym = menu->sym; if (sym) { sym_calc_value(sym); visible = menu->prompt->visible.tri; } else visible = menu->prompt->visible.tri = expr_calc_value(menu->prompt->visible.expr); if (visible != no) return true; if (!sym || sym_get_tristate_value(menu->sym) == no) return false; for (child = menu->list; child; child = child->next) if (menu_is_visible(child)) return true; return false; } const char *menu_get_prompt(struct menu *menu) { if (menu->prompt) return _(menu->prompt->text); else if (menu->sym) return _(menu->sym->name); return NULL; } struct menu *menu_get_root_menu(struct menu *menu) { return &rootmenu; } struct menu *menu_get_parent_menu(struct menu *menu) { enum prop_type type; for (; menu != &rootmenu; menu = menu->parent) { type = menu->prompt ? menu->prompt->type : 0; if (type == P_MENU) break; } return menu; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">janrinze/loox7xxport.loox2-6-22</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">scripts/kconfig/menu.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">10,632</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086516"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* $License: Copyright (C) 2011 InvenSense Corporation, All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. $ */ /** * @addtogroup ACCELDL * @brief Provides the interface to setup and handle an accelerometer. * * @{ * @file mma8450.c * @brief Accelerometer setup and handling methods for Freescale MMA8450. */ /* -------------------------------------------------------------------------- */ #include <linux/i2c.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/delay.h> #include "mpu-dev.h" #include <log.h> #include <linux/mpu.h> #include "mlsl.h" #include "mldl_cfg.h" #undef MPL_LOG_TAG #define MPL_LOG_TAG "MPL-acc" /* full scale setting - register & mask */ #define ACCEL_MMA8450_XYZ_DATA_CFG (0x16) #define ACCEL_MMA8450_CTRL_REG1 (0x38) #define ACCEL_MMA8450_CTRL_REG2 (0x39) #define ACCEL_MMA8450_CTRL_REG4 (0x3B) #define ACCEL_MMA8450_CTRL_REG5 (0x3C) #define ACCEL_MMA8450_CTRL_REG (0x38) #define ACCEL_MMA8450_CTRL_MASK (0x03) #define ACCEL_MMA8450_SLEEP_MASK (0x03) /* -------------------------------------------------------------------------- */ struct mma8450_config { unsigned int odr; unsigned int fsr; /** < full scale range mg */ unsigned int ths; /** < Motion no-motion thseshold mg */ unsigned int dur; /** < Motion no-motion duration ms */ unsigned char reg_ths; unsigned char reg_dur; unsigned char ctrl_reg1; unsigned char irq_type; unsigned char mot_int1_cfg; }; struct mma8450_private_data { struct mma8450_config suspend; struct mma8450_config resume; }; /* -------------------------------------------------------------------------- */ static int mma8450_set_ths(void *mlsl_handle, struct ext_slave_platform_data *pdata, struct mma8450_config *config, int apply, long ths) { return INV_ERROR_FEATURE_NOT_IMPLEMENTED; } static int mma8450_set_dur(void *mlsl_handle, struct ext_slave_platform_data *pdata, struct mma8450_config *config, int apply, long dur) { return INV_ERROR_FEATURE_NOT_IMPLEMENTED; } /** * @brief Sets the IRQ to fire when one of the IRQ events occur. * Threshold and duration will not be used unless the type is MOT or * NMOT. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param pdata * a pointer to the slave platform data. * @param config * configuration to apply to, suspend or resume * @param apply * whether to apply immediately or save the settings to be applied * at the next resume. * @param irq_type * the type of IRQ. Valid values are * - MPU_SLAVE_IRQ_TYPE_NONE * - MPU_SLAVE_IRQ_TYPE_MOTION * - MPU_SLAVE_IRQ_TYPE_DATA_READY * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_set_irq(void *mlsl_handle, struct ext_slave_platform_data *pdata, struct mma8450_config *config, int apply, long irq_type) { int result = INV_SUCCESS; unsigned char reg1; unsigned char reg2; unsigned char reg3; config->irq_type = (unsigned char)irq_type; if (irq_type == MPU_SLAVE_IRQ_TYPE_DATA_READY) { reg1 = 0x01; reg2 = 0x01; reg3 = 0x07; } else if (irq_type == MPU_SLAVE_IRQ_TYPE_NONE) { reg1 = 0x00; reg2 = 0x00; reg3 = 0x00; } else { return INV_ERROR_FEATURE_NOT_IMPLEMENTED; } if (apply) { /* XYZ_DATA_CFG: event flag enabled on Z axis */ result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_XYZ_DATA_CFG, reg3); if (result) { LOG_RESULT_LOCATION(result); return result; } result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG4, reg1); if (result) { LOG_RESULT_LOCATION(result); return result; } result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG5, reg2); if (result) { LOG_RESULT_LOCATION(result); return result; } } return result; } /** * @brief Set the output data rate for the particular configuration. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param pdata * a pointer to the slave platform data. * @param config * Config to modify with new ODR. * @param apply * whether to apply immediately or save the settings to be applied * at the next resume. * @param odr * Output data rate in units of 1/1000Hz (mHz). * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_set_odr(void *mlsl_handle, struct ext_slave_platform_data *pdata, struct mma8450_config *config, int apply, long odr) { unsigned char bits; int result = INV_SUCCESS; if (odr > 200000) { config->odr = 400000; bits = 0x00; } else if (odr > 100000) { config->odr = 200000; bits = 0x04; } else if (odr > 50000) { config->odr = 100000; bits = 0x08; } else if (odr > 25000) { config->odr = 50000; bits = 0x0C; } else if (odr > 12500) { config->odr = 25000; bits = 0x40; /* Sleep -> Auto wake mode */ } else if (odr > 1563) { config->odr = 12500; bits = 0x10; } else if (odr > 0) { config->odr = 1563; bits = 0x14; } else { config->ctrl_reg1 = 0; /* Set FS1.FS2 to Standby */ config->odr = 0; bits = 0; } config->ctrl_reg1 = bits | (config->ctrl_reg1 & 0x3); if (apply) { result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, 0); if (result) { LOG_RESULT_LOCATION(result); return result; } result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1); if (result) { LOG_RESULT_LOCATION(result); return result; } MPL_LOGV("ODR: %d mHz, 0x%02x\n", config->odr, (int)config->ctrl_reg1); } return result; } /** * @brief Set the full scale range of the accels * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param pdata * a pointer to the slave platform data. * @param config * pointer to configuration. * @param apply * whether to apply immediately or save the settings to be applied * at the next resume. * @param fsr * requested full scale range. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_set_fsr(void *mlsl_handle, struct ext_slave_platform_data *pdata, struct mma8450_config *config, int apply, long fsr) { unsigned char bits; int result = INV_SUCCESS; if (fsr <= 2000) { bits = 0x01; config->fsr = 2000; } else if (fsr <= 4000) { bits = 0x02; config->fsr = 4000; } else { bits = 0x03; config->fsr = 8000; } config->ctrl_reg1 = bits | (config->ctrl_reg1 & 0xFC); if (apply) { result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1); if (result) { LOG_RESULT_LOCATION(result); return result; } MPL_LOGV("FSR: %d mg\n", config->fsr); } return result; } /** * @brief suspends the device to put it in its lowest power mode. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_suspend(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata) { int result; struct mma8450_private_data *private_data = pdata->private_data; if (private_data->suspend.fsr == 4000) slave->range.mantissa = 4; else if (private_data->suspend.fsr == 8000) slave->range.mantissa = 8; else slave->range.mantissa = 2; slave->range.fraction = 0; result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, 0); if (result) { LOG_RESULT_LOCATION(result); return result; } if (private_data->suspend.ctrl_reg1) { result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, private_data->suspend.ctrl_reg1); if (result) { LOG_RESULT_LOCATION(result); return result; } } result = mma8450_set_irq(mlsl_handle, pdata, &private_data->suspend, true, private_data->suspend.irq_type); if (result) { LOG_RESULT_LOCATION(result); return result; } return result; } /** * @brief resume the device in the proper power state given the configuration * chosen. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_resume(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata) { int result = INV_SUCCESS; struct mma8450_private_data *private_data = pdata->private_data; /* Full Scale */ if (private_data->resume.fsr == 4000) slave->range.mantissa = 4; else if (private_data->resume.fsr == 8000) slave->range.mantissa = 8; else slave->range.mantissa = 2; slave->range.fraction = 0; if (result) { LOG_RESULT_LOCATION(result); return result; } result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, 0); if (result) { LOG_RESULT_LOCATION(result); return result; } if (private_data->resume.ctrl_reg1) { result = inv_serial_single_write(mlsl_handle, pdata->address, ACCEL_MMA8450_CTRL_REG1, private_data->resume.ctrl_reg1); if (result) { LOG_RESULT_LOCATION(result); return result; } } result = mma8450_set_irq(mlsl_handle, pdata, &private_data->resume, true, private_data->resume.irq_type); if (result) { LOG_RESULT_LOCATION(result); return result; } return result; } /** * @brief read the sensor data from the device. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * @param data * a buffer to store the data read. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_read(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata, unsigned char *data) { int result; unsigned char local_data[4]; /* Status register + 3 bytes data */ result = inv_serial_read(mlsl_handle, pdata->address, 0x00, sizeof(local_data), local_data); if (result) { LOG_RESULT_LOCATION(result); return result; } memcpy(data, &local_data[1], (slave->read_len) - 1); MPL_LOGV("Data Not Ready: %02x %02x %02x %02x\n", local_data[0], local_data[1], local_data[2], local_data[3]); return result; } /** * @brief one-time device driver initialization function. * If the driver is built as a kernel module, this function will be * called when the module is loaded in the kernel. * If the driver is built-in in the kernel, this function will be * called at boot time. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_init(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata) { struct mma8450_private_data *private_data; private_data = (struct mma8450_private_data *) kzalloc(sizeof(struct mma8450_private_data), GFP_KERNEL); if (!private_data) return INV_ERROR_MEMORY_EXAUSTED; pdata->private_data = private_data; mma8450_set_odr(mlsl_handle, pdata, &private_data->suspend, false, 0); mma8450_set_odr(mlsl_handle, pdata, &private_data->resume, false, 200000); mma8450_set_fsr(mlsl_handle, pdata, &private_data->suspend, false, 2000); mma8450_set_fsr(mlsl_handle, pdata, &private_data->resume, false, 2000); mma8450_set_irq(mlsl_handle, pdata, &private_data->suspend, false, MPU_SLAVE_IRQ_TYPE_NONE); mma8450_set_irq(mlsl_handle, pdata, &private_data->resume, false, MPU_SLAVE_IRQ_TYPE_NONE); return INV_SUCCESS; } /** * @brief one-time device driver exit function. * If the driver is built as a kernel module, this function will be * called when the module is removed from the kernel. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_exit(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata) { kfree(pdata->private_data); return INV_SUCCESS; } /** * @brief device configuration facility. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * @param data * a pointer to the configuration data structure. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_config(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata, struct ext_slave_config *data) { struct mma8450_private_data *private_data = pdata->private_data; if (!data->data) return INV_ERROR_INVALID_PARAMETER; switch (data->key) { case MPU_SLAVE_CONFIG_ODR_SUSPEND: return mma8450_set_odr(mlsl_handle, pdata, &private_data->suspend, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_ODR_RESUME: return mma8450_set_odr(mlsl_handle, pdata, &private_data->resume, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_FSR_SUSPEND: return mma8450_set_fsr(mlsl_handle, pdata, &private_data->suspend, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_FSR_RESUME: return mma8450_set_fsr(mlsl_handle, pdata, &private_data->resume, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_MOT_THS: return mma8450_set_ths(mlsl_handle, pdata, &private_data->suspend, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_NMOT_THS: return mma8450_set_ths(mlsl_handle, pdata, &private_data->resume, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_MOT_DUR: return mma8450_set_dur(mlsl_handle, pdata, &private_data->suspend, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_NMOT_DUR: return mma8450_set_dur(mlsl_handle, pdata, &private_data->resume, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_IRQ_SUSPEND: return mma8450_set_irq(mlsl_handle, pdata, &private_data->suspend, data->apply, *((long *)data->data)); case MPU_SLAVE_CONFIG_IRQ_RESUME: return mma8450_set_irq(mlsl_handle, pdata, &private_data->resume, data->apply, *((long *)data->data)); default: LOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED); return INV_ERROR_FEATURE_NOT_IMPLEMENTED; }; return INV_SUCCESS; } /** * @brief facility to retrieve the device configuration. * * @param mlsl_handle * the handle to the serial channel the device is connected to. * @param slave * a pointer to the slave descriptor data structure. * @param pdata * a pointer to the slave platform data. * @param data * a pointer to store the returned configuration data structure. * * @return INV_SUCCESS if successful or a non-zero error code. */ static int mma8450_get_config(void *mlsl_handle, struct ext_slave_descr *slave, struct ext_slave_platform_data *pdata, struct ext_slave_config *data) { struct mma8450_private_data *private_data = pdata->private_data; if (!data->data) return INV_ERROR_INVALID_PARAMETER; switch (data->key) { case MPU_SLAVE_CONFIG_ODR_SUSPEND: (*(unsigned long *)data->data) = (unsigned long) private_data->suspend.odr; break; case MPU_SLAVE_CONFIG_ODR_RESUME: (*(unsigned long *)data->data) = (unsigned long) private_data->resume.odr; break; case MPU_SLAVE_CONFIG_FSR_SUSPEND: (*(unsigned long *)data->data) = (unsigned long) private_data->suspend.fsr; break; case MPU_SLAVE_CONFIG_FSR_RESUME: (*(unsigned long *)data->data) = (unsigned long) private_data->resume.fsr; break; case MPU_SLAVE_CONFIG_MOT_THS: (*(unsigned long *)data->data) = (unsigned long) private_data->suspend.ths; break; case MPU_SLAVE_CONFIG_NMOT_THS: (*(unsigned long *)data->data) = (unsigned long) private_data->resume.ths; break; case MPU_SLAVE_CONFIG_MOT_DUR: (*(unsigned long *)data->data) = (unsigned long) private_data->suspend.dur; break; case MPU_SLAVE_CONFIG_NMOT_DUR: (*(unsigned long *)data->data) = (unsigned long) private_data->resume.dur; break; case MPU_SLAVE_CONFIG_IRQ_SUSPEND: (*(unsigned long *)data->data) = (unsigned long) private_data->suspend.irq_type; break; case MPU_SLAVE_CONFIG_IRQ_RESUME: (*(unsigned long *)data->data) = (unsigned long) private_data->resume.irq_type; break; default: LOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED); return INV_ERROR_FEATURE_NOT_IMPLEMENTED; }; return INV_SUCCESS; } static struct ext_slave_descr mma8450_descr = { .init = mma8450_init, .exit = mma8450_exit, .suspend = mma8450_suspend, .resume = mma8450_resume, .read = mma8450_read, .config = mma8450_config, .get_config = mma8450_get_config, .name = "mma8450", .type = EXT_SLAVE_TYPE_ACCEL, .id = ACCEL_ID_MMA8450, .read_reg = 0x00, .read_len = 4, .endian = EXT_SLAVE_FS8_BIG_ENDIAN, .range = {2, 0}, .trigger = NULL, }; static struct ext_slave_descr *mma8450_get_slave_descr(void) { return &mma8450_descr; } /* -------------------------------------------------------------------------- */ struct mma8450_mod_private_data { struct i2c_client *client; struct ext_slave_platform_data *pdata; }; static unsigned short normal_i2c[] = { I2C_CLIENT_END }; static int mma8450_mod_probe(struct i2c_client *client, const struct i2c_device_id *devid) { struct ext_slave_platform_data *pdata; struct mma8450_mod_private_data *private_data; int result = 0; dev_info(&client->adapter->dev, "%s: %s\n", __func__, devid->name); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { result = -ENODEV; goto out_no_free; } pdata = client->dev.platform_data; if (!pdata) { dev_err(&client->adapter->dev, "Missing platform data for slave %s\n", devid->name); result = -EFAULT; goto out_no_free; } private_data = kzalloc(sizeof(*private_data), GFP_KERNEL); if (!private_data) { result = -ENOMEM; goto out_no_free; } i2c_set_clientdata(client, private_data); private_data->client = client; private_data->pdata = pdata; result = inv_mpu_register_slave(THIS_MODULE, client, pdata, mma8450_get_slave_descr); if (result) { dev_err(&client->adapter->dev, "Slave registration failed: %s, %d\n", devid->name, result); goto out_free_memory; } return result; out_free_memory: kfree(private_data); out_no_free: dev_err(&client->adapter->dev, "%s failed %d\n", __func__, result); return result; } static int mma8450_mod_remove(struct i2c_client *client) { struct mma8450_mod_private_data *private_data = i2c_get_clientdata(client); dev_dbg(&client->adapter->dev, "%s\n", __func__); inv_mpu_unregister_slave(client, private_data->pdata, mma8450_get_slave_descr); kfree(private_data); return 0; } static const struct i2c_device_id mma8450_mod_id[] = { { "mma8450", ACCEL_ID_MMA8450 }, {} }; MODULE_DEVICE_TABLE(i2c, mma8450_mod_id); static struct i2c_driver mma8450_mod_driver = { .class = I2C_CLASS_HWMON, .probe = mma8450_mod_probe, .remove = mma8450_mod_remove, .id_table = mma8450_mod_id, .driver = { .owner = THIS_MODULE, .name = "mma8450_mod", }, .address_list = normal_i2c, }; static int __init mma8450_mod_init(void) { int res = i2c_add_driver(&mma8450_mod_driver); pr_info("%s: Probe name %s\n", __func__, "mma8450_mod"); if (res) pr_err("%s failed\n", __func__); return res; } static void __exit mma8450_mod_exit(void) { pr_info("%s\n", __func__); i2c_del_driver(&mma8450_mod_driver); } module_init(mma8450_mod_init); module_exit(mma8450_mod_exit); MODULE_AUTHOR("Invensense Corporation"); MODULE_DESCRIPTION("Driver to integrate MMA8450 sensor with the MPU"); MODULE_LICENSE("GPL"); MODULE_ALIAS("mma8450_mod"); /** * @} */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">akw28888/caf2</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/misc/inv_mpu/accel/mma8450.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">21,949</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086517"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * This file was created in part using the configuration script provided with * the libpng sources. However it was missing some symbols which caused the * linker to fail so those were added manually by scanning the library looking * for exported symbols missing the skia_ prefix and adding them to the end of * this file. * * ./third_party/externals/libpng/configure --with-libpng-prefix=skia_ */ #define png_sRGB_table skia_png_sRGB_table #define png_sRGB_base skia_png_sRGB_base #define png_sRGB_delta skia_png_sRGB_delta #define png_zstream_error skia_png_zstream_error #define png_free_buffer_list skia_png_free_buffer_list #define png_fixed skia_png_fixed #define png_user_version_check skia_png_user_version_check #define png_malloc_base skia_png_malloc_base #define png_malloc_array skia_png_malloc_array #define png_realloc_array skia_png_realloc_array #define png_create_png_struct skia_png_create_png_struct #define png_destroy_png_struct skia_png_destroy_png_struct #define png_free_jmpbuf skia_png_free_jmpbuf #define png_zalloc skia_png_zalloc #define png_zfree skia_png_zfree #define png_default_read_data skia_png_default_read_data #define png_push_fill_buffer skia_png_push_fill_buffer #define png_default_write_data skia_png_default_write_data #define png_default_flush skia_png_default_flush #define png_reset_crc skia_png_reset_crc #define png_write_data skia_png_write_data #define png_read_sig skia_png_read_sig #define png_read_chunk_header skia_png_read_chunk_header #define png_read_data skia_png_read_data #define png_crc_read skia_png_crc_read #define png_crc_finish skia_png_crc_finish #define png_crc_error skia_png_crc_error #define png_calculate_crc skia_png_calculate_crc #define png_flush skia_png_flush #define png_write_IHDR skia_png_write_IHDR #define png_write_PLTE skia_png_write_PLTE #define png_compress_IDAT skia_png_compress_IDAT #define png_write_IEND skia_png_write_IEND #define png_write_gAMA_fixed skia_png_write_gAMA_fixed #define png_write_sBIT skia_png_write_sBIT #define png_write_cHRM_fixed skia_png_write_cHRM_fixed #define png_write_sRGB skia_png_write_sRGB #define png_write_iCCP skia_png_write_iCCP #define png_write_sPLT skia_png_write_sPLT #define png_write_tRNS skia_png_write_tRNS #define png_write_bKGD skia_png_write_bKGD #define png_write_hIST skia_png_write_hIST #define png_write_tEXt skia_png_write_tEXt #define png_write_zTXt skia_png_write_zTXt #define png_write_iTXt skia_png_write_iTXt #define png_set_text_2 skia_png_set_text_2 #define png_write_oFFs skia_png_write_oFFs #define png_write_pCAL skia_png_write_pCAL #define png_write_pHYs skia_png_write_pHYs #define png_write_tIME skia_png_write_tIME #define png_write_sCAL_s skia_png_write_sCAL_s #define png_write_finish_row skia_png_write_finish_row #define png_write_start_row skia_png_write_start_row #define png_combine_row skia_png_combine_row #define png_do_read_interlace skia_png_do_read_interlace #define png_do_write_interlace skia_png_do_write_interlace #define png_read_filter_row skia_png_read_filter_row #define png_read_filter_row_up_neon skia_png_read_filter_row_up_neon #define png_read_filter_row_sub3_neon skia_png_read_filter_row_sub3_neon #define png_read_filter_row_sub4_neon skia_png_read_filter_row_sub4_neon #define png_read_filter_row_avg3_neon skia_png_read_filter_row_avg3_neon #define png_read_filter_row_avg4_neon skia_png_read_filter_row_avg4_neon #define png_read_filter_row_paeth3_neon skia_png_read_filter_row_paeth3_neon #define png_read_filter_row_paeth4_neon skia_png_read_filter_row_paeth4_neon #define png_write_find_filter skia_png_write_find_filter #define png_read_IDAT_data skia_png_read_IDAT_data #define png_read_finish_IDAT skia_png_read_finish_IDAT #define png_read_finish_row skia_png_read_finish_row #define png_read_start_row skia_png_read_start_row #define png_read_transform_info skia_png_read_transform_info #define png_do_read_filler skia_png_do_read_filler #define png_do_read_swap_alpha skia_png_do_read_swap_alpha #define png_do_write_swap_alpha skia_png_do_write_swap_alpha #define png_do_read_invert_alpha skia_png_do_read_invert_alpha #define png_do_write_invert_alpha skia_png_do_write_invert_alpha #define png_do_strip_channel skia_png_do_strip_channel #define png_do_swap skia_png_do_swap #define png_do_packswap skia_png_do_packswap #define png_do_rgb_to_gray skia_png_do_rgb_to_gray #define png_do_gray_to_rgb skia_png_do_gray_to_rgb #define png_do_unpack skia_png_do_unpack #define png_do_unshift skia_png_do_unshift #define png_do_invert skia_png_do_invert #define png_do_scale_16_to_8 skia_png_do_scale_16_to_8 #define png_do_chop skia_png_do_chop #define png_do_quantize skia_png_do_quantize #define png_do_bgr skia_png_do_bgr #define png_do_pack skia_png_do_pack #define png_do_shift skia_png_do_shift #define png_do_compose skia_png_do_compose #define png_do_gamma skia_png_do_gamma #define png_do_encode_alpha skia_png_do_encode_alpha #define png_do_expand_palette skia_png_do_expand_palette #define png_do_expand skia_png_do_expand #define png_do_expand_16 skia_png_do_expand_16 #define png_handle_IHDR skia_png_handle_IHDR #define png_handle_PLTE skia_png_handle_PLTE #define png_handle_IEND skia_png_handle_IEND #define png_handle_bKGD skia_png_handle_bKGD #define png_handle_cHRM skia_png_handle_cHRM #define png_handle_gAMA skia_png_handle_gAMA #define png_handle_hIST skia_png_handle_hIST #define png_handle_iCCP skia_png_handle_iCCP #define png_handle_iTXt skia_png_handle_iTXt #define png_handle_oFFs skia_png_handle_oFFs #define png_handle_pCAL skia_png_handle_pCAL #define png_handle_pHYs skia_png_handle_pHYs #define png_handle_sBIT skia_png_handle_sBIT #define png_handle_sCAL skia_png_handle_sCAL #define png_handle_sPLT skia_png_handle_sPLT #define png_handle_sRGB skia_png_handle_sRGB #define png_handle_tEXt skia_png_handle_tEXt #define png_handle_tIME skia_png_handle_tIME #define png_handle_tRNS skia_png_handle_tRNS #define png_handle_zTXt skia_png_handle_zTXt #define png_check_chunk_name skia_png_check_chunk_name #define png_handle_unknown skia_png_handle_unknown #define png_chunk_unknown_handling skia_png_chunk_unknown_handling #define png_do_read_transformations skia_png_do_read_transformations #define png_do_write_transformations skia_png_do_write_transformations #define png_init_read_transformations skia_png_init_read_transformations #define png_push_read_chunk skia_png_push_read_chunk #define png_push_read_sig skia_png_push_read_sig #define png_push_check_crc skia_png_push_check_crc #define png_push_crc_skip skia_png_push_crc_skip #define png_push_crc_finish skia_png_push_crc_finish #define png_push_save_buffer skia_png_push_save_buffer #define png_push_restore_buffer skia_png_push_restore_buffer #define png_push_read_IDAT skia_png_push_read_IDAT #define png_process_IDAT_data skia_png_process_IDAT_data #define png_push_process_row skia_png_push_process_row #define png_push_handle_unknown skia_png_push_handle_unknown #define png_push_have_info skia_png_push_have_info #define png_push_have_end skia_png_push_have_end #define png_push_have_row skia_png_push_have_row #define png_push_read_end skia_png_push_read_end #define png_process_some_data skia_png_process_some_data #define png_read_push_finish_row skia_png_read_push_finish_row #define png_push_handle_tEXt skia_png_push_handle_tEXt #define png_push_read_tEXt skia_png_push_read_tEXt #define png_push_handle_zTXt skia_png_push_handle_zTXt #define png_push_read_zTXt skia_png_push_read_zTXt #define png_push_handle_iTXt skia_png_push_handle_iTXt #define png_push_read_iTXt skia_png_push_read_iTXt #define png_do_read_intrapixel skia_png_do_read_intrapixel #define png_do_write_intrapixel skia_png_do_write_intrapixel #define png_colorspace_set_gamma skia_png_colorspace_set_gamma #define png_colorspace_sync_info skia_png_colorspace_sync_info #define png_colorspace_sync skia_png_colorspace_sync #define png_colorspace_set_chromaticities skia_png_colorspace_set_chromaticities #define png_colorspace_set_endpoints skia_png_colorspace_set_endpoints #define png_colorspace_set_sRGB skia_png_colorspace_set_sRGB #define png_colorspace_set_ICC skia_png_colorspace_set_ICC #define png_icc_check_length skia_png_icc_check_length #define png_icc_check_header skia_png_icc_check_header #define png_icc_check_tag_table skia_png_icc_check_tag_table #define png_icc_set_sRGB skia_png_icc_set_sRGB #define png_colorspace_set_rgb_coefficients skia_png_colorspace_set_rgb_coefficients #define png_check_IHDR skia_png_check_IHDR #define png_do_check_palette_indexes skia_png_do_check_palette_indexes #define png_fixed_error skia_png_fixed_error #define png_safecat skia_png_safecat #define png_format_number skia_png_format_number #define png_warning_parameter skia_png_warning_parameter #define png_warning_parameter_unsigned skia_png_warning_parameter_unsigned #define png_warning_parameter_signed skia_png_warning_parameter_signed #define png_formatted_warning skia_png_formatted_warning #define png_app_warning skia_png_app_warning #define png_app_error skia_png_app_error #define png_chunk_report skia_png_chunk_report #define png_ascii_from_fp skia_png_ascii_from_fp #define png_ascii_from_fixed skia_png_ascii_from_fixed #define png_check_fp_number skia_png_check_fp_number #define png_check_fp_string skia_png_check_fp_string #define png_muldiv skia_png_muldiv #define png_muldiv_warn skia_png_muldiv_warn #define png_reciprocal skia_png_reciprocal #define png_reciprocal2 skia_png_reciprocal2 #define png_gamma_significant skia_png_gamma_significant #define png_gamma_correct skia_png_gamma_correct #define png_gamma_16bit_correct skia_png_gamma_16bit_correct #define png_gamma_8bit_correct skia_png_gamma_8bit_correct #define png_destroy_gamma_table skia_png_destroy_gamma_table #define png_build_gamma_table skia_png_build_gamma_table #define png_safe_error skia_png_safe_error #define png_safe_warning skia_png_safe_warning #define png_safe_execute skia_png_safe_execute #define png_image_error skia_png_image_error #define png_access_version_number skia_png_access_version_number #define png_build_grayscale_palette skia_png_build_grayscale_palette #define png_convert_to_rfc1123 skia_png_convert_to_rfc1123 #define png_convert_to_rfc1123_buffer skia_png_convert_to_rfc1123_buffer #define png_create_info_struct skia_png_create_info_struct #define png_data_freer skia_png_data_freer #define png_destroy_info_struct skia_png_destroy_info_struct #define png_free_data skia_png_free_data #define png_get_copyright skia_png_get_copyright #define png_get_header_ver skia_png_get_header_ver #define png_get_header_version skia_png_get_header_version #define png_get_io_ptr skia_png_get_io_ptr #define png_get_libpng_ver skia_png_get_libpng_ver #define png_handle_as_unknown skia_png_handle_as_unknown #define png_image_free skia_png_image_free #define png_info_init_3 skia_png_info_init_3 #define png_init_io skia_png_init_io #define png_reset_zstream skia_png_reset_zstream #define png_save_int_32 skia_png_save_int_32 #define png_set_option skia_png_set_option #define png_set_sig_bytes skia_png_set_sig_bytes #define png_sig_cmp skia_png_sig_cmp #define png_benign_error skia_png_benign_error #define png_chunk_benign_error skia_png_chunk_benign_error #define png_chunk_error skia_png_chunk_error #define png_chunk_warning skia_png_chunk_warning #define png_error skia_png_error #define png_get_error_ptr skia_png_get_error_ptr #define png_longjmp skia_png_longjmp #define png_set_error_fn skia_png_set_error_fn #define png_set_longjmp_fn skia_png_set_longjmp_fn #define png_warning skia_png_warning #define png_get_bit_depth skia_png_get_bit_depth #define png_get_bKGD skia_png_get_bKGD #define png_get_channels skia_png_get_channels #define png_get_cHRM skia_png_get_cHRM #define png_get_cHRM_fixed skia_png_get_cHRM_fixed #define png_get_cHRM_XYZ skia_png_get_cHRM_XYZ #define png_get_cHRM_XYZ_fixed skia_png_get_cHRM_XYZ_fixed #define png_get_chunk_cache_max skia_png_get_chunk_cache_max #define png_get_chunk_malloc_max skia_png_get_chunk_malloc_max #define png_get_color_type skia_png_get_color_type #define png_get_compression_buffer_size skia_png_get_compression_buffer_size #define png_get_compression_type skia_png_get_compression_type #define png_get_filter_type skia_png_get_filter_type #define png_get_gAMA skia_png_get_gAMA #define png_get_gAMA_fixed skia_png_get_gAMA_fixed #define png_get_hIST skia_png_get_hIST #define png_get_iCCP skia_png_get_iCCP #define png_get_IHDR skia_png_get_IHDR #define png_get_image_height skia_png_get_image_height #define png_get_image_width skia_png_get_image_width #define png_get_interlace_type skia_png_get_interlace_type #define png_get_io_chunk_type skia_png_get_io_chunk_type #define png_get_io_state skia_png_get_io_state #define png_get_oFFs skia_png_get_oFFs #define png_get_palette_max skia_png_get_palette_max #define png_get_pCAL skia_png_get_pCAL #define png_get_pHYs skia_png_get_pHYs #define png_get_pHYs_dpi skia_png_get_pHYs_dpi #define png_get_pixel_aspect_ratio skia_png_get_pixel_aspect_ratio #define png_get_pixel_aspect_ratio_fixed skia_png_get_pixel_aspect_ratio_fixed #define png_get_pixels_per_inch skia_png_get_pixels_per_inch #define png_get_pixels_per_meter skia_png_get_pixels_per_meter #define png_get_PLTE skia_png_get_PLTE #define png_get_rgb_to_gray_status skia_png_get_rgb_to_gray_status #define png_get_rowbytes skia_png_get_rowbytes #define png_get_rows skia_png_get_rows #define png_get_sBIT skia_png_get_sBIT #define png_get_sCAL skia_png_get_sCAL #define png_get_sCAL_fixed skia_png_get_sCAL_fixed #define png_get_sCAL_s skia_png_get_sCAL_s #define png_get_signature skia_png_get_signature #define png_get_sPLT skia_png_get_sPLT #define png_get_sRGB skia_png_get_sRGB #define png_get_text skia_png_get_text #define png_get_tIME skia_png_get_tIME #define png_get_tRNS skia_png_get_tRNS #define png_get_unknown_chunks skia_png_get_unknown_chunks #define png_get_user_chunk_ptr skia_png_get_user_chunk_ptr #define png_get_user_height_max skia_png_get_user_height_max #define png_get_user_width_max skia_png_get_user_width_max #define png_get_valid skia_png_get_valid #define png_get_x_offset_inches skia_png_get_x_offset_inches #define png_get_x_offset_inches_fixed skia_png_get_x_offset_inches_fixed #define png_get_x_offset_microns skia_png_get_x_offset_microns #define png_get_x_offset_pixels skia_png_get_x_offset_pixels #define png_get_x_pixels_per_inch skia_png_get_x_pixels_per_inch #define png_get_x_pixels_per_meter skia_png_get_x_pixels_per_meter #define png_get_y_offset_inches skia_png_get_y_offset_inches #define png_get_y_offset_inches_fixed skia_png_get_y_offset_inches_fixed #define png_get_y_offset_microns skia_png_get_y_offset_microns #define png_get_y_offset_pixels skia_png_get_y_offset_pixels #define png_get_y_pixels_per_inch skia_png_get_y_pixels_per_inch #define png_get_y_pixels_per_meter skia_png_get_y_pixels_per_meter #define png_calloc skia_png_calloc #define png_free skia_png_free #define png_free_default skia_png_free_default #define png_get_mem_ptr skia_png_get_mem_ptr #define png_malloc skia_png_malloc #define png_malloc_default skia_png_malloc_default #define png_malloc_warn skia_png_malloc_warn #define png_set_mem_fn skia_png_set_mem_fn #define png_get_progressive_ptr skia_png_get_progressive_ptr #define png_process_data skia_png_process_data #define png_process_data_pause skia_png_process_data_pause #define png_process_data_skip skia_png_process_data_skip #define png_progressive_combine_row skia_png_progressive_combine_row #define png_set_progressive_read_fn skia_png_set_progressive_read_fn #define png_create_read_struct skia_png_create_read_struct #define png_create_read_struct_2 skia_png_create_read_struct_2 #define png_destroy_read_struct skia_png_destroy_read_struct #define png_image_begin_read_from_file skia_png_image_begin_read_from_file #define png_image_begin_read_from_memory skia_png_image_begin_read_from_memory #define png_image_begin_read_from_stdio skia_png_image_begin_read_from_stdio #define png_image_finish_read skia_png_image_finish_read #define png_read_end skia_png_read_end #define png_read_image skia_png_read_image #define png_read_info skia_png_read_info #define png_read_png skia_png_read_png #define png_read_row skia_png_read_row #define png_read_rows skia_png_read_rows #define png_read_update_info skia_png_read_update_info #define png_set_read_status_fn skia_png_set_read_status_fn #define png_start_read_image skia_png_start_read_image #define png_set_read_fn skia_png_set_read_fn #define png_set_alpha_mode skia_png_set_alpha_mode #define png_set_alpha_mode_fixed skia_png_set_alpha_mode_fixed #define png_set_background skia_png_set_background #define png_set_background_fixed skia_png_set_background_fixed #define png_set_crc_action skia_png_set_crc_action #define png_set_expand skia_png_set_expand #define png_set_expand_16 skia_png_set_expand_16 #define png_set_expand_gray_1_2_4_to_8 skia_png_set_expand_gray_1_2_4_to_8 #define png_set_gamma skia_png_set_gamma #define png_set_gamma_fixed skia_png_set_gamma_fixed #define png_set_gray_to_rgb skia_png_set_gray_to_rgb #define png_set_palette_to_rgb skia_png_set_palette_to_rgb #define png_set_quantize skia_png_set_quantize #define png_set_read_user_transform_fn skia_png_set_read_user_transform_fn #define png_set_rgb_to_gray skia_png_set_rgb_to_gray #define png_set_rgb_to_gray_fixed skia_png_set_rgb_to_gray_fixed #define png_set_scale_16 skia_png_set_scale_16 #define png_set_strip_16 skia_png_set_strip_16 #define png_set_strip_alpha skia_png_set_strip_alpha #define png_set_tRNS_to_alpha skia_png_set_tRNS_to_alpha #define png_get_int_32 skia_png_get_int_32 #define png_get_uint_16 skia_png_get_uint_16 #define png_get_uint_31 skia_png_get_uint_31 #define png_get_uint_32 skia_png_get_uint_32 #define png_permit_mng_features skia_png_permit_mng_features #define png_set_benign_errors skia_png_set_benign_errors #define png_set_bKGD skia_png_set_bKGD #define png_set_check_for_invalid_index skia_png_set_check_for_invalid_index #define png_set_cHRM skia_png_set_cHRM #define png_set_cHRM_fixed skia_png_set_cHRM_fixed #define png_set_cHRM_XYZ skia_png_set_cHRM_XYZ #define png_set_cHRM_XYZ_fixed skia_png_set_cHRM_XYZ_fixed #define png_set_chunk_cache_max skia_png_set_chunk_cache_max #define png_set_chunk_malloc_max skia_png_set_chunk_malloc_max #define png_set_compression_buffer_size skia_png_set_compression_buffer_size #define png_set_gAMA skia_png_set_gAMA #define png_set_gAMA_fixed skia_png_set_gAMA_fixed #define png_set_hIST skia_png_set_hIST #define png_set_iCCP skia_png_set_iCCP #define png_set_IHDR skia_png_set_IHDR #define png_set_invalid skia_png_set_invalid #define png_set_keep_unknown_chunks skia_png_set_keep_unknown_chunks #define png_set_oFFs skia_png_set_oFFs #define png_set_pCAL skia_png_set_pCAL #define png_set_pHYs skia_png_set_pHYs #define png_set_PLTE skia_png_set_PLTE #define png_set_read_user_chunk_fn skia_png_set_read_user_chunk_fn #define png_set_rows skia_png_set_rows #define png_set_sBIT skia_png_set_sBIT #define png_set_sCAL skia_png_set_sCAL #define png_set_sCAL_fixed skia_png_set_sCAL_fixed #define png_set_sCAL_s skia_png_set_sCAL_s #define png_set_sPLT skia_png_set_sPLT #define png_set_sRGB skia_png_set_sRGB #define png_set_sRGB_gAMA_and_cHRM skia_png_set_sRGB_gAMA_and_cHRM #define png_set_text skia_png_set_text #define png_set_tIME skia_png_set_tIME #define png_set_tRNS skia_png_set_tRNS #define png_set_unknown_chunk_location skia_png_set_unknown_chunk_location #define png_set_unknown_chunks skia_png_set_unknown_chunks #define png_set_user_limits skia_png_set_user_limits #define png_get_current_pass_number skia_png_get_current_pass_number #define png_get_current_row_number skia_png_get_current_row_number #define png_get_user_transform_ptr skia_png_get_user_transform_ptr #define png_set_add_alpha skia_png_set_add_alpha #define png_set_bgr skia_png_set_bgr #define png_set_filler skia_png_set_filler #define png_set_interlace_handling skia_png_set_interlace_handling #define png_set_invert_alpha skia_png_set_invert_alpha #define png_set_invert_mono skia_png_set_invert_mono #define png_set_packing skia_png_set_packing #define png_set_packswap skia_png_set_packswap #define png_set_shift skia_png_set_shift #define png_set_swap skia_png_set_swap #define png_set_swap_alpha skia_png_set_swap_alpha #define png_set_user_transform_info skia_png_set_user_transform_info #define png_set_write_fn skia_png_set_write_fn #define png_convert_from_struct_tm skia_png_convert_from_struct_tm #define png_convert_from_time_t skia_png_convert_from_time_t #define png_create_write_struct skia_png_create_write_struct #define png_create_write_struct_2 skia_png_create_write_struct_2 #define png_destroy_write_struct skia_png_destroy_write_struct #define png_image_write_to_file skia_png_image_write_to_file #define png_image_write_to_stdio skia_png_image_write_to_stdio #define png_set_compression_level skia_png_set_compression_level #define png_set_compression_mem_level skia_png_set_compression_mem_level #define png_set_compression_method skia_png_set_compression_method #define png_set_compression_strategy skia_png_set_compression_strategy #define png_set_compression_window_bits skia_png_set_compression_window_bits #define png_set_filter skia_png_set_filter #define png_set_filter_heuristics skia_png_set_filter_heuristics #define png_set_filter_heuristics_fixed skia_png_set_filter_heuristics_fixed #define png_set_flush skia_png_set_flush #define png_set_text_compression_level skia_png_set_text_compression_level #define png_set_text_compression_mem_level skia_png_set_text_compression_mem_level #define png_set_text_compression_method skia_png_set_text_compression_method #define png_set_text_compression_strategy skia_png_set_text_compression_strategy #define png_set_text_compression_window_bits skia_png_set_text_compression_window_bits #define png_set_write_status_fn skia_png_set_write_status_fn #define png_set_write_user_transform_fn skia_png_set_write_user_transform_fn #define png_write_end skia_png_write_end #define png_write_flush skia_png_write_flush #define png_write_image skia_png_write_image #define png_write_info skia_png_write_info #define png_write_info_before_PLTE skia_png_write_info_before_PLTE #define png_write_png skia_png_write_png #define png_write_row skia_png_write_row #define png_write_rows skia_png_write_rows #define png_save_uint_16 skia_png_save_uint_16 #define png_save_uint_32 skia_png_save_uint_32 #define png_write_chunk skia_png_write_chunk #define png_write_chunk_data skia_png_write_chunk_data #define png_write_chunk_start skia_png_write_chunk_start #define png_write_chunk_end skia_png_write_chunk_end #define png_write_sig skia_png_write_sig </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">zero-ui/miniblink49</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/skia/third_party/libpng/pngprefix.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">22,924</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086518"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">define( [ "js/views/baseview", "underscore", "js/models/metadata", "js/views/abstract_editor", "js/models/uploads", "js/views/uploads", "js/models/license", "js/views/license", "js/views/video/transcripts/metadata_videolist", "js/views/video/translations_editor" ], function(BaseView, _, MetadataModel, AbstractEditor, FileUpload, UploadDialog, LicenseModel, LicenseView, VideoList, VideoTranslations) { var Metadata = {}; Metadata.Editor = BaseView.extend({ // Model is CMS.Models.MetadataCollection, initialize : function() { var self = this, counter = 0, locator = self.$el.closest('[data-locator]').data('locator'), courseKey = self.$el.closest('[data-course-key]').data('course-key'); this.template = this.loadTemplate('metadata-editor'); this.$el.html(this.template({numEntries: this.collection.length})); this.collection.each( function (model) { var data = { el: self.$el.find('.metadata_entry')[counter++], courseKey: courseKey, locator: locator, model: model }, conversions = { 'Select': 'Option', 'Float': 'Number', 'Integer': 'Number' }, type = model.getType(); if (conversions[type]) { type = conversions[type]; } if (_.isFunction(Metadata[type])) { new Metadata[type](data); } else { // Everything else is treated as GENERIC_TYPE, which uses String editor. new Metadata.String(data); } }); }, /** * Returns just the modified metadata values, in the format used to persist to the server. */ getModifiedMetadataValues: function () { var modified_values = {}; this.collection.each( function (model) { if (model.isModified()) { modified_values[model.getFieldName()] = model.getValue(); } } ); return modified_values; }, /** * Returns a display name for the component related to this metadata. This method looks to see * if there is a metadata entry called 'display_name', and if so, it returns its value. If there * is no such entry, or if display_name does not have a value set, it returns an empty string. */ getDisplayName: function () { var displayName = ''; this.collection.each( function (model) { if (model.get('field_name') === 'display_name') { var displayNameValue = model.get('value'); // It is possible that there is no display name value set. In that case, return empty string. displayName = displayNameValue ? displayNameValue : ''; } } ); return displayName; } }); Metadata.VideoList = VideoList; Metadata.VideoTranslations = VideoTranslations; Metadata.String = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "showClearButton", "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", render: function () { AbstractEditor.prototype.render.apply(this); // If the model has property `non editable` equals `true`, // the field is disabled, but user is able to clear it. if (this.model.get('non_editable')) { this.$el.find('#' + this.uniqueId) .prop('readonly', true) .addClass('is-disabled') .attr('aria-disabled', true); } }, getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); } }); Metadata.Number = AbstractEditor.extend({ events : { "change input" : "updateModel", "keypress .setting-input" : "keyPressed", "change .setting-input" : "changed", "click .setting-clear" : "clear" }, render: function () { AbstractEditor.prototype.render.apply(this); if (!this.initialized) { var numToString = function (val) { return val.toFixed(4); }; var min = "min"; var max = "max"; var step = "step"; var options = this.model.getOptions(); if (options.hasOwnProperty(min)) { this.min = Number(options[min]); this.$el.find('input').attr(min, numToString(this.min)); } if (options.hasOwnProperty(max)) { this.max = Number(options[max]); this.$el.find('input').attr(max, numToString(this.max)); } var stepValue = undefined; if (options.hasOwnProperty(step)) { // Parse step and convert to String. Polyfill doesn't like float values like ".1" (expects "0.1"). stepValue = numToString(Number(options[step])); } else if (this.isIntegerField()) { stepValue = "1"; } if (stepValue !== undefined) { this.$el.find('input').attr(step, stepValue); } // Manually runs polyfill for input number types to correct for Firefox non-support. // inputNumber will be undefined when unit test is running. if ($.fn.inputNumber) { this.$el.find('.setting-input-number').inputNumber(); } this.initialized = true; } return this; }, templateName: "metadata-number-entry", getValueFromEditor : function () { return this.$el.find('#' + this.uniqueId).val(); }, setValueInEditor : function (value) { this.$el.find('input').val(value); }, /** * Returns true if this view is restricted to integers, as opposed to floating points values. */ isIntegerField : function () { return this.model.getType() === 'Integer'; }, keyPressed: function (e) { this.showClearButton(); // This first filtering if statement is take from polyfill to prevent // non-numeric input (for browsers that don't use polyfill because they DO have a number input type). var _ref, _ref1; if (((_ref = e.keyCode) !== 8 && _ref !== 9 && _ref !== 35 && _ref !== 36 && _ref !== 37 && _ref !== 39) && ((_ref1 = e.which) !== 45 && _ref1 !== 46 && _ref1 !== 48 && _ref1 !== 49 && _ref1 !== 50 && _ref1 !== 51 && _ref1 !== 52 && _ref1 !== 53 && _ref1 !== 54 && _ref1 !== 55 && _ref1 !== 56 && _ref1 !== 57)) { e.preventDefault(); } // For integers, prevent decimal points. if (this.isIntegerField() && e.keyCode === 46) { e.preventDefault(); } }, changed: function () { // Limit value to the range specified by min and max (necessary for browsers that aren't using polyfill). // Prevent integer/float fields value to be empty (set them to their defaults) var value = this.getValueFromEditor(); if (value) { if ((this.max !== undefined) && value > this.max) { value = this.max; } else if ((this.min != undefined) && value < this.min) { value = this.min; } this.setValueInEditor(value); this.updateModel(); } else { this.clear(); } } }); Metadata.Option = AbstractEditor.extend({ events : { "change select" : "updateModel", "click .setting-clear" : "clear" }, templateName: "metadata-option-entry", getValueFromEditor : function () { var selectedText = this.$el.find('#' + this.uniqueId).find(":selected").text(); var selectedValue; _.each(this.model.getOptions(), function (modelValue) { if (modelValue === selectedText) { selectedValue = modelValue; } else if (modelValue['display_name'] === selectedText) { selectedValue = modelValue['value']; } }); return selectedValue; }, setValueInEditor : function (value) { // Value here is the json value as used by the field. The choice may instead be showing display names. // Find the display name matching the value passed in. _.each(this.model.getOptions(), function (modelValue) { if (modelValue['value'] === value) { value = modelValue['display_name']; } }); this.$el.find('#' + this.uniqueId + " option").filter(function() { return $(this).text() === value; }).prop('selected', true); } }); Metadata.List = AbstractEditor.extend({ events : { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-list-entry", getValueFromEditor: function () { return _.map( this.$el.find('li input'), function (ele) { return ele.value.trim(); } ).filter(_.identity); }, setValueInEditor: function (value) { var list = this.$el.find('ol'); list.empty(); _.each(value, function(ele, index) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input" value="<%= ele %>">' + '<a href="#" class="remove-action remove-setting" data-index="<%= index %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); list.append($(template({'ele': ele, 'index': index}))); }); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var list = this.model.get('value') || []; this.setValueInEditor(list.concat([''])); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings().val(); this.setValueInEditor(_.without(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); Metadata.RelativeTime = AbstractEditor.extend({ defaultValue: '00:00:00', // By default max value of RelativeTime field on Backend is 23:59:59, // that is 86399 seconds. maxTimeInSeconds: 86399, events: { "focus input" : "addSelection", "mouseup input" : "mouseUpHandler", "change input" : "updateModel", "keypress .setting-input" : "showClearButton" , "click .setting-clear" : "clear" }, templateName: "metadata-string-entry", getValueFromEditor: function () { var $input = this.$el.find('#' + this.uniqueId); return $input.val(); }, updateModel: function () { var value = this.getValueFromEditor(), time = this.parseRelativeTime(value); this.model.setValue(time); // Sometimes, `parseRelativeTime` method returns the same value for // the different inputs. In this case, model will not be // updated (it already has the same value) and we should // call `render` method manually. // Examples: // value => 23:59:59; parseRelativeTime => 23:59:59 // value => 44:59:59; parseRelativeTime => 23:59:59 if (value !== time && !this.model.hasChanged('value')) { this.render(); } }, parseRelativeTime: function (value) { // This function ensure you have two-digits var pad = function (number) { return (number < 10) ? "0" + number : number; }, // Removes all white-spaces and splits by `:`. list = value.replace(/\s+/g, '').split(':'), seconds, date; list = _.map(list, function(num) { return Math.max(0, parseInt(num, 10) || 0); }).reverse(); seconds = _.reduce(list, function(memo, num, index) { return memo + num * Math.pow(60, index); }, 0); // multiply by 1000 because Date() requires milliseconds date = new Date(Math.min(seconds, this.maxTimeInSeconds) * 1000); return [ pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()) ].join(':'); }, setValueInEditor: function (value) { if (!value) { value = this.defaultValue; } this.$el.find('input').val(value); }, addSelection: function (event) { $(event.currentTarget).select(); }, mouseUpHandler: function (event) { // Prevents default behavior to make works selection in WebKit // browsers event.preventDefault(); } }); Metadata.Dict = AbstractEditor.extend({ events: { "click .setting-clear" : "clear", "keypress .setting-input" : "showClearButton", "change input" : "updateModel", "input input" : "enableAdd", "click .create-setting" : "addEntry", "click .remove-setting" : "removeEntry" }, templateName: "metadata-dict-entry", getValueFromEditor: function () { var dict = {}; _.each(this.$el.find('li'), function(li, index) { var key = $(li).find('.input-key').val().trim(), value = $(li).find('.input-value').val().trim(); // Keys should be unique, so if our keys are duplicated and // second key is empty or key and value are empty just do // nothing. Otherwise, it'll be overwritten by the new value. if (value === '') { if (key === '' || key in dict) { return false; } } dict[key] = value; }); return dict; }, setValueInEditor: function (value) { var list = this.$el.find('ol'), frag = document.createDocumentFragment(); _.each(value, function(value, key) { var template = _.template( '<li class="list-settings-item">' + '<input type="text" class="input input-key" value="<%= key %>">' + '<input type="text" class="input input-value" value="<%= value %>">' + '<a href="#" class="remove-action remove-setting" data-value="<%= value %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' + '</li>' ); frag.appendChild($(template({'key': key, 'value': value}))[0]); }); list.html([frag]); }, addEntry: function(event) { event.preventDefault(); // We don't call updateModel here since it's bound to the // change event var dict = $.extend(true, {}, this.model.get('value')) || {}; dict[''] = ''; this.setValueInEditor(dict); this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true); }, removeEntry: function(event) { event.preventDefault(); var entry = $(event.currentTarget).siblings('.input-key').val(); this.setValueInEditor(_.omit(this.model.get('value'), entry)); this.updateModel(); this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, enableAdd: function() { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); }, clear: function() { AbstractEditor.prototype.clear.apply(this, arguments); if (_.isNull(this.model.getValue())) { this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false); } } }); /** * Provides convenient way to upload/download files in component edit. * The editor uploads files directly to course assets and stores link * to uploaded file. */ Metadata.FileUploader = AbstractEditor.extend({ events : { "click .upload-setting" : "upload", "click .setting-clear" : "clear" }, templateName: "metadata-file-uploader-entry", templateButtonsName: "metadata-file-uploader-item", initialize: function () { this.buttonTemplate = this.loadTemplate(this.templateButtonsName); AbstractEditor.prototype.initialize.apply(this); }, getValueFromEditor: function () { return this.$('#' + this.uniqueId).val(); }, setValueInEditor: function (value) { var html = this.buttonTemplate({ model: this.model, uniqueId: this.uniqueId }); this.$('#' + this.uniqueId).val(value); this.$('.wrapper-uploader-actions').html(html); }, upload: function (event) { var self = this, target = $(event.currentTarget), url = '/assets/' + this.options.courseKey + '/', model = new FileUpload({ title: gettext('Upload File'), }), view = new UploadDialog({ model: model, url: url, parentElement: target.closest('.xblock-editor'), onSuccess: function (response) { if (response['asset'] && response['asset']['url']) { self.model.setValue(response['asset']['url']); } } }).show(); event.preventDefault(); } }); Metadata.License = AbstractEditor.extend({ initialize: function(options) { this.licenseModel = new LicenseModel({"asString": this.model.getValue()}); this.licenseView = new LicenseView({model: this.licenseModel}); // Rerender when the license model changes this.listenTo(this.licenseModel, 'change', this.setLicense); this.render(); }, render: function() { this.licenseView.render().$el.css("display", "inline"); this.licenseView.undelegateEvents(); this.$el.empty().append(this.licenseView.el); // restore event bindings this.licenseView.delegateEvents(); return this; }, setLicense: function() { this.model.setValue(this.licenseModel.toString()); this.render() } }); return Metadata; }); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">MakeHer/edx-platform</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cms/static/js/views/metadata.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">21,517</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086519"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (c) 2013 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef VP9_COMMON_VP9_CONVOLVE_H_ #define VP9_COMMON_VP9_CONVOLVE_H_ #include "./vpx_config.h" #include "vpx/vpx_integer.h" #ifdef __cplusplus extern "C" { #endif typedef void (*convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h); #if CONFIG_VP9_HIGHBITDEPTH typedef void (*highbd_convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride, uint8_t *dst, ptrdiff_t dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int bd); #endif #ifdef __cplusplus } // extern "C" #endif #endif // VP9_COMMON_VP9_CONVOLVE_H_ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jacklicn/webm.libvpx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vp9/common/vp9_convolve.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,386</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086520"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!DOCTYPE html> <title>flexbox | visibility: collapse and line wrapping</title> <link rel="author" href="http://opera.com" title="Opera Software"> <style> body { margin: 0; width: 602px; } div { background: #3366cc; border: 1px solid black; } div::after { content: ""; clear: both; display: block; } p { background: #ffcc00; margin: 1em 0; width: 300px; float: left; } </style> <div> <p>filler</p> <p>filler</p> <p>filler</p> <p>filler</p> </div> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">scheib/chromium</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/blink/web_tests/external/wpt/css/css-flexbox/flexbox_visibility-collapse-line-wrapping-ref.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">463</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086521"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";N;s:4:"type";s:6:"string";s:6:"length";i:40;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}');</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">juanc25/proyectoFinal</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">app/cache/test/annotations/Proyecto-UsuarioBundle-Entity-Usuario$useLogin.cache.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">254</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086522"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe CampaignsController do def get_data_for_sidebar @status = Setting.campaign_status.dup end before(:each) do require_user set_current_tab(:campaigns) end # GET /campaigns # GET /campaigns.xml #---------------------------------------------------------------------------- describe "responding to GET index" do before(:each) do get_data_for_sidebar end it "should expose all campaigns as @campaigns and render [index] template" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] get :index expect(assigns[:campaigns]).to eq(@campaigns) expect(response).to render_template("campaigns/index") end it "should collect the data for the opportunities sidebar" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] get :index expect(assigns[:campaign_status_total].keys.map(&:to_sym) - (@status << :all << :other)).to eq([]) end it "should filter out campaigns by status" do controller.session[:campaigns_filter] = "planned,started" @campaigns = [ FactoryGirl.create(:campaign, user: current_user, status: "started"), FactoryGirl.create(:campaign, user: current_user, status: "planned") ] # This one should be filtered out. FactoryGirl.create(:campaign, user: current_user, status: "completed") get :index # Note: can't compare campaigns directly because of BigDecimal objects. expect(assigns[:campaigns].size).to eq(2) expect(assigns[:campaigns].map(&:status).sort).to eq(%w(planned started)) end it "should perform lookup using query string" do @first = FactoryGirl.create(:campaign, user: current_user, name: "Hello, world!") @second = FactoryGirl.create(:campaign, user: current_user, name: "Hello again") get :index, query: "again" expect(assigns[:campaigns]).to eq([@second]) expect(assigns[:current_query]).to eq("again") expect(session[:campaigns_current_query]).to eq("again") end describe "AJAX pagination" do it "should pick up page number from params" do @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index, page: 42 expect(assigns[:current_page].to_i).to eq(42) expect(assigns[:campaigns]).to eq([]) # page #42 should be empty if there's only one campaign ;-) expect(session[:campaigns_current_page].to_i).to eq(42) expect(response).to render_template("campaigns/index") end it "should pick up saved page number from session" do session[:campaigns_current_page] = 42 @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index expect(assigns[:current_page]).to eq(42) expect(assigns[:campaigns]).to eq([]) expect(response).to render_template("campaigns/index") end it "should reset current_page when query is altered" do session[:campaigns_current_page] = 42 session[:campaigns_current_query] = "bill" @campaigns = [FactoryGirl.create(:campaign, user: current_user)] xhr :get, :index expect(assigns[:current_page]).to eq(1) expect(assigns[:campaigns]).to eq(@campaigns) expect(response).to render_template("campaigns/index") end end describe "with mime type of JSON" do it "should render all campaigns as JSON" do expect(@controller).to receive(:get_campaigns).and_return(@campaigns = []) expect(@campaigns).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :index expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render all campaigns as xml" do expect(@controller).to receive(:get_campaigns).and_return(@campaigns = []) expect(@campaigns).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :index expect(response.body).to eq("generated XML") end end end # GET /campaigns/1 # GET /campaigns/1.xml HTML #---------------------------------------------------------------------------- describe "responding to GET show" do describe "with mime type of HTML" do before(:each) do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) @stage = Setting.unroll(:opportunity_stage) @comment = Comment.new end it "should expose the requested campaign as @campaign and render [show] template" do get :show, id: 42 expect(assigns[:campaign]).to eq(@campaign) expect(assigns[:stage]).to eq(@stage) expect(assigns[:comment].attributes).to eq(@comment.attributes) expect(response).to render_template("campaigns/show") end it "should update an activity when viewing the campaign" do get :show, id: @campaign.id expect(@campaign.versions.last.event).to eq('view') end end describe "with mime type of JSON" do it "should render the requested campaign as JSON" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) expect(Campaign).to receive(:find).and_return(@campaign) expect(@campaign).to receive(:to_json).and_return("generated JSON") request.env["HTTP_ACCEPT"] = "application/json" get :show, id: 42 expect(response.body).to eq("generated JSON") end end describe "with mime type of XML" do it "should render the requested campaign as XML" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) expect(Campaign).to receive(:find).and_return(@campaign) expect(@campaign).to receive(:to_xml).and_return("generated XML") request.env["HTTP_ACCEPT"] = "application/xml" get :show, id: 42 expect(response.body).to eq("generated XML") end end describe "campaign got deleted or otherwise unavailable" do it "should redirect to campaign index if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy get :show, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index if the campaign is protected" do @campaign = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") get :show, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should return 404 (Not Found) JSON error" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/json" get :show, id: @campaign.id expect(response.code).to eq("404") # :not_found end it "should return 404 (Not Found) XML error" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy request.env["HTTP_ACCEPT"] = "application/xml" get :show, id: @campaign.id expect(response.code).to eq("404") # :not_found end end end # GET /campaigns/new # GET /campaigns/new.xml AJAX #---------------------------------------------------------------------------- describe "responding to GET new" do it "should expose a new campaign as @campaign" do @campaign = Campaign.new(user: current_user, access: Setting.default_access) xhr :get, :new expect(assigns[:campaign].attributes).to eq(@campaign.attributes) expect(response).to render_template("campaigns/new") end it "should create related object when necessary" do @lead = FactoryGirl.create(:lead, id: 42) xhr :get, :new, related: "lead_42" expect(assigns[:lead]).to eq(@lead) end end # GET /campaigns/1/edit AJAX #---------------------------------------------------------------------------- describe "responding to GET edit" do it "should expose the requested campaign as @campaign and render [edit] template" do @campaign = FactoryGirl.create(:campaign, id: 42, user: current_user) xhr :get, :edit, id: 42 expect(assigns[:campaign]).to eq(@campaign) expect(response).to render_template("campaigns/edit") end it "should find previous campaign as necessary" do @campaign = FactoryGirl.create(:campaign, id: 42) @previous = FactoryGirl.create(:campaign, id: 99) xhr :get, :edit, id: 42, previous: 99 expect(assigns[:campaign]).to eq(@campaign) expect(assigns[:previous]).to eq(@previous) end describe "(campaign got deleted or is otherwise unavailable)" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :get, :edit, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :get, :edit, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end describe "(previous campaign got deleted or is otherwise unavailable)" do before(:each) do @campaign = FactoryGirl.create(:campaign, user: current_user) @previous = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user)) end it "should notify the view if previous campaign got deleted" do @previous.destroy xhr :get, :edit, id: @campaign.id, previous: @previous.id expect(flash[:warning]).to eq(nil) # no warning, just silently remove the div expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("campaigns/edit") end it "should notify the view if previous campaign got protected" do @previous.update_attribute(:access, "Private") xhr :get, :edit, id: @campaign.id, previous: @previous.id expect(flash[:warning]).to eq(nil) expect(assigns[:previous]).to eq(@previous.id) expect(response).to render_template("campaigns/edit") end end end # POST /campaigns # POST /campaigns.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST create" do describe "with valid params" do it "should expose a newly created campaign as @campaign and render [create] template" do @campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/create") end it "should get data to update campaign sidebar" do @campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should reload campaigns to update pagination" do @campaign = FactoryGirl.build(:campaign, user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello" } expect(assigns[:campaigns]).to eq([@campaign]) end it "should add a new comment to the newly created campaign when specified" do @campaign = FactoryGirl.build(:campaign, name: "Hello world", user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: { name: "Hello world" }, comment_body: "Awesome comment is awesome" expect(@campaign.reload.comments.map(&:comment)).to include("Awesome comment is awesome") end end describe "with invalid params" do it "should expose a newly created but unsaved campaign as @campaign and still render [create] template" do @campaign = FactoryGirl.build(:campaign, id: nil, name: nil, user: current_user) allow(Campaign).to receive(:new).and_return(@campaign) xhr :post, :create, campaign: {} expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/create") end end end # PUT /campaigns/1 # PUT /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT update" do describe "with valid params" do it "should update the requested campaign and render [update] template" do @campaign = FactoryGirl.create(:campaign, id: 42, name: "Bye") xhr :put, :update, id: 42, campaign: { name: "Hello" } expect(@campaign.reload.name).to eq("Hello") expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/update") end it "should get data for campaigns sidebar when called from Campaigns index" do @campaign = FactoryGirl.create(:campaign, id: 42) request.env["HTTP_REFERER"] = "http://localhost/campaigns" xhr :put, :update, id: 42, campaign: { name: "Hello" } expect(assigns(:campaign)).to eq(@campaign) expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should update campaign permissions when sharing with specific users" do @campaign = FactoryGirl.create(:campaign, id: 42, access: "Public") he = FactoryGirl.create(:user, id: 7) she = FactoryGirl.create(:user, id: 8) xhr :put, :update, id: 42, campaign: { name: "Hello", access: "Shared", user_ids: %w(7 8) } expect(assigns[:campaign].access).to eq("Shared") expect(assigns[:campaign].user_ids.sort).to eq([7, 8]) end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :put, :update, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :put, :update, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "with invalid params" do it "should not update the requested campaign, but still expose it as @campaign and still render [update] template" do @campaign = FactoryGirl.create(:campaign, id: 42, name: "Hello", user: current_user) xhr :put, :update, id: 42, campaign: { name: nil } expect(@campaign.reload.name).to eq("Hello") expect(assigns(:campaign)).to eq(@campaign) expect(response).to render_template("campaigns/update") end end end # DELETE /campaigns/1 # DELETE /campaigns/1.xml AJAX #---------------------------------------------------------------------------- describe "responding to DELETE destroy" do before(:each) do @campaign = FactoryGirl.create(:campaign, user: current_user) end describe "AJAX request" do it "should destroy the requested campaign and render [destroy] template" do @another_campaign = FactoryGirl.create(:campaign, user: current_user) xhr :delete, :destroy, id: @campaign.id expect(assigns[:campaigns]).to eq([@another_campaign]) expect { Campaign.find(@campaign.id) }.to raise_error(ActiveRecord::RecordNotFound) expect(response).to render_template("campaigns/destroy") end it "should get data for campaigns sidebar" do xhr :delete, :destroy, id: @campaign.id expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess) end it "should try previous page and render index action if current page has no campaigns" do session[:campaigns_current_page] = 42 xhr :delete, :destroy, id: @campaign.id expect(session[:campaigns_current_page]).to eq(41) expect(response).to render_template("campaigns/index") end it "should render index action when deleting last campaign" do session[:campaigns_current_page] = 1 xhr :delete, :destroy, id: @campaign.id expect(session[:campaigns_current_page]).to eq(1) expect(response).to render_template("campaigns/index") end describe "campaign got deleted or otherwise unavailable" do it "should reload current page with the flash message if the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy xhr :delete, :destroy, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end it "should reload current page with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") xhr :delete, :destroy, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response.body).to eq("window.location.reload();") end end end describe "HTML request" do it "should redirect to Campaigns index when a campaign gets deleted from its landing page" do delete :destroy, id: @campaign.id expect(flash[:notice]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message is the campaign got deleted" do @campaign = FactoryGirl.create(:campaign, user: current_user) @campaign.destroy delete :destroy, id: @campaign.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end it "should redirect to campaign index with the flash message if the campaign is protected" do @private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private") delete :destroy, id: @private.id expect(flash[:warning]).not_to eq(nil) expect(response).to redirect_to(campaigns_path) end end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, campaign: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, campaign: nil) end it_should_behave_like("attach") end end # PUT /campaigns/1/attach # PUT /campaigns/1/attach.xml AJAX #---------------------------------------------------------------------------- describe "responding to PUT attach" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: nil) end it_should_behave_like("attach") end describe "leads" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:lead, campaign: nil) end it_should_behave_like("attach") end describe "opportunities" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:opportunity, campaign: nil) end it_should_behave_like("attach") end end # POST /campaigns/1/discard # POST /campaigns/1/discard.xml AJAX #---------------------------------------------------------------------------- describe "responding to POST discard" do describe "tasks" do before do @model = FactoryGirl.create(:campaign) @attachment = FactoryGirl.create(:task, asset: @model) end it_should_behave_like("discard") end describe "leads" do before do @attachment = FactoryGirl.create(:lead) @model = FactoryGirl.create(:campaign) @model.leads << @attachment end it_should_behave_like("discard") end describe "opportunities" do before do @attachment = FactoryGirl.create(:opportunity) @model = FactoryGirl.create(:campaign) @model.opportunities << @attachment end it_should_behave_like("discard") end end # POST /campaigns/auto_complete/query AJAX #---------------------------------------------------------------------------- describe "responding to POST auto_complete" do before(:each) do @auto_complete_matches = [FactoryGirl.create(:campaign, name: "Hello World", user: current_user)] end it_should_behave_like("auto complete") end # GET /campaigns/redraw AJAX #---------------------------------------------------------------------------- describe "responding to GET redraw" do it "should save user selected campaign preference" do xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name" expect(current_user.preference[:campaigns_per_page]).to eq("42") expect(current_user.preference[:campaigns_index_view]).to eq("brief") expect(current_user.preference[:campaigns_sort_by]).to eq("campaigns.name ASC") end it "should reset current page to 1" do xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name" expect(session[:campaigns_current_page]).to eq(1) end it "should select @campaigns and render [index] template" do @campaigns = [ FactoryGirl.create(:campaign, name: "A", user: current_user), FactoryGirl.create(:campaign, name: "B", user: current_user) ] xhr :get, :redraw, per_page: 1, sort_by: "name" expect(assigns(:campaigns)).to eq([@campaigns.first]) expect(response).to render_template("campaigns/index") end end # POST /campaigns/filter AJAX #---------------------------------------------------------------------------- describe "responding to POST filter" do it "should expose filtered campaigns as @campaigns and render [index] template" do session[:campaigns_filter] = "planned,started" @campaigns = [FactoryGirl.create(:campaign, status: "completed", user: current_user)] xhr :post, :filter, status: "completed" expect(assigns(:campaigns)).to eq(@campaigns) expect(response).to render_template("campaigns/index") end it "should reset current page to 1" do @campaigns = [] xhr :post, :filter, status: "completed" expect(session[:campaigns_current_page]).to eq(1) end end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">srinuvasuv/fat_free_crm</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">spec/controllers/entities/campaigns_controller_spec.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">24,917</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086523"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2009, Lars-Peter Clausen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d4d9cacbf8d5ddccd9ded7d796dcdd">[email protected]</a>> */ #ifndef __ASM_MACH_JZ4740_JZ4740_FB_H__ #define __ASM_MACH_JZ4740_JZ4740_FB_H__ #include <linux/fb.h> enum jz4740_fb_lcd_type { JZ_LCD_TYPE_GENERIC_16_BIT = 0, JZ_LCD_TYPE_GENERIC_18_BIT = 0 | (1 << 4), JZ_LCD_TYPE_SPECIAL_TFT_1 = 1, JZ_LCD_TYPE_SPECIAL_TFT_2 = 2, JZ_LCD_TYPE_SPECIAL_TFT_3 = 3, JZ_LCD_TYPE_NON_INTERLACED_CCIR656 = 5, JZ_LCD_TYPE_INTERLACED_CCIR656 = 7, JZ_LCD_TYPE_SINGLE_COLOR_STN = 8, JZ_LCD_TYPE_SINGLE_MONOCHROME_STN = 9, JZ_LCD_TYPE_DUAL_COLOR_STN = 10, JZ_LCD_TYPE_DUAL_MONOCHROME_STN = 11, JZ_LCD_TYPE_8BIT_SERIAL = 12, }; #define JZ4740_FB_SPECIAL_TFT_CONFIG(start, stop) (((start) << 16) | (stop)) /* * width: width of the lcd display in mm * height: height of the lcd display in mm * num_modes: size of modes * modes: list of valid video modes * bpp: bits per pixel for the lcd * lcd_type: lcd type */ struct jz4740_fb_platform_data { unsigned int width; unsigned int height; size_t num_modes; struct fb_videomode *modes; unsigned int bpp; enum jz4740_fb_lcd_type lcd_type; struct { uint32_t spl; uint32_t cls; uint32_t ps; uint32_t rev; } special_tft_config; unsigned pixclk_falling_edge:1; unsigned date_enable_active_low:1; }; #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">koct9i/linux</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">arch/mips/include/asm/mach-jz4740/jz4740_fb.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,323</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086524"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright 2020 Alexander Tulloh * * 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, see <http://www.gnu.org/licenses/>. */ #pragma once /* * Keyboard Matrix Assignments * * Change this to how you wired your keyboard * COLS: AVR pins used for columns, left to right * ROWS: AVR pins used for rows, top to bottom * DIODE_DIRECTION: COL2ROW = COL = Anode (+), ROW = Cathode (-, marked on diode) * ROW2COL = ROW = Anode (+), COL = Cathode (-, marked on diode) * */ #define MATRIX_ROW_PINS { F6, B5, B6, F7 } #define MATRIX_COL_PINS { D6, D7, B4, D3, C6, C7 } #define UNUSED_PINS { B7, D4, D5, E6, F0, F1, F4, F5 } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">kmtoki/qmk_firmware</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">keyboards/oddball/v1/config.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,203</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086525"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Bulk Transfers</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" /> <link rel="up" href="addfeatures.html" title="Chapter 5. Additional Features" /> <link rel="prev" href="c2ctransfer.html" title="Client to Client Transfer" /> </head> <body> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">Bulk Transfers</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="c2ctransfer.html">Prev</a> </td> <th width="60%" align="center">Chapter 5. Additional Features</th> <td width="20%" align="right"> </td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="bulk"></a>Bulk Transfers</h2> </div> </div> </div> <p> By default, messages are sent from the master to replicas as they are generated. This can degrade replication performance because the various participating environments must handle a fair amount of network I/O activity. </p> <p> You can alleviate this problem by configuring your master environment for bulk transfers. Bulk transfers simply cause replication messages to accumulate in a buffer until a triggering event occurs. When this event occurs, the entire contents of the buffer is sent to the replica, thereby eliminating excessive network I/O. </p> <p> Note that if you are using replica to replica transfers, then you might want any replica that can service replication requests to also be configured for bulk transfers. </p> <p> The events that result in a bulk transfer of replication messages to a replica will differ depending on if the transmitting environment is a master or a replica. </p> <p> If the servicing environment is a master environment, then bulk transfer occurs when: </p> <div class="orderedlist"> <ol type="1"> <li> <p> Bulk transfers are configured for the master environment, and </p> </li> <li> <p> the message buffer is full or </p> </li> <li> <p> a permanent record (for example, a transaction commit or a checkpoint record) is placed in the buffer for the replica. </p> </li> </ol> </div> <p> If the servicing environment is a replica environment (that is, replica to replica transfers are in use), then a bulk transfer occurs when: </p> <div class="orderedlist"> <ol type="1"> <li> <p> Bulk transfers are configured for the transmitting replica, and </p> </li> <li> <p> the message buffer is full or </p> </li> <li> <p> the replica servicing the request is able to completely satisfy the request with the contents of the message buffer. </p> </li> </ol> </div> <p> To configure bulk transfers, specify <span> <code class="literal">DB_REP_CONF_BULK</code> to <code class="methodname">DbEnv::rep_set_config()</code> and then specify <code class="literal">1</code> to the <code class="literal">onoff</code> parameter. (Specify <code class="literal">0</code> to turn the feature off.) </span> </p> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="c2ctransfer.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="addfeatures.html">Up</a> </td> <td width="40%" align="right"> </td> </tr> <tr> <td width="40%" align="left" valign="top">Client to Client Transfer </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> </td> </tr> </table> </div> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">joglomedia/masedi.net</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">work/berkeley-db/docs/gsg_db_rep/CXX/bulk.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,739</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086526"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * kexec-mips.c - kexec for mips * Copyright (C) 2007 Francesco Chiechi, Alessandro Rubini * Copyright (C) 2007 Tvblob s.r.l. * * derived from ../ppc/kexec-mips.c * Copyright (C) 2004, 2005 Albert Herranz * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #include <stddef.h> #include <stdio.h> #include <errno.h> #include <stdint.h> #include <string.h> #include <getopt.h> #include "../../kexec.h" #include "../../kexec-syscall.h" #include "kexec-mips.h" #include <arch/options.h> static struct memory_range memory_range[MAX_MEMORY_RANGES]; /* Return a sorted list of memory ranges. */ int get_memory_ranges(struct memory_range **range, int *ranges, unsigned long UNUSED(kexec_flags)) { int memory_ranges = 0; const char iomem[] = "/proc/iomem"; char line[MAX_LINE]; FILE *fp; unsigned long long start, end; char *str; int type, consumed, count; fp = fopen(iomem, "r"); if (!fp) { fprintf(stderr, "Cannot open %s: %s\n", iomem, strerror(errno)); return -1; } while (fgets(line, sizeof(line), fp) != 0) { if (memory_ranges >= MAX_MEMORY_RANGES) break; count = sscanf(line, "%Lx-%Lx : %n", &start, &end, &consumed); if (count != 2) continue; str = line + consumed; end = end + 1; if (memcmp(str, "System RAM\n", 11) == 0) { type = RANGE_RAM; } else if (memcmp(str, "reserved\n", 9) == 0) { type = RANGE_RESERVED; } else { continue; } memory_range[memory_ranges].start = start; memory_range[memory_ranges].end = end; memory_range[memory_ranges].type = type; memory_ranges++; } fclose(fp); *range = memory_range; *ranges = memory_ranges; return 0; } struct file_type file_type[] = { {"elf-mips", elf_mips_probe, elf_mips_load, elf_mips_usage}, }; int file_types = sizeof(file_type) / sizeof(file_type[0]); void arch_usage(void) { #ifdef __mips64 fprintf(stderr, " --elf32-core-headers Prepare core headers in " "ELF32 format\n"); #endif } #ifdef __mips64 struct arch_options_t arch_options = { .core_header_type = CORE_TYPE_ELF64 }; #endif int arch_process_options(int argc, char **argv) { return 0; } const struct arch_map_entry arches[] = { /* For compatibility with older patches * use KEXEC_ARCH_DEFAULT instead of KEXEC_ARCH_MIPS here. */ { "mips", KEXEC_ARCH_MIPS }, { "mips64", KEXEC_ARCH_MIPS }, { NULL, 0 }, }; int arch_compat_trampoline(struct kexec_info *UNUSED(info)) { return 0; } void arch_update_purgatory(struct kexec_info *UNUSED(info)) { } unsigned long virt_to_phys(unsigned long addr) { return addr & 0x7fffffff; } /* * add_segment() should convert base to a physical address on mips, * while the default is just to work with base as is */ void add_segment(struct kexec_info *info, const void *buf, size_t bufsz, unsigned long base, size_t memsz) { add_segment_phys_virt(info, buf, bufsz, virt_to_phys(base), memsz, 1); } /* * add_buffer() should convert base to a physical address on mips, * while the default is just to work with base as is */ unsigned long add_buffer(struct kexec_info *info, const void *buf, unsigned long bufsz, unsigned long memsz, unsigned long buf_align, unsigned long buf_min, unsigned long buf_max, int buf_end) { return add_buffer_phys_virt(info, buf, bufsz, memsz, buf_align, buf_min, buf_max, buf_end, 1); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wanghao-xznu/vte</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">testcases/third_party_suite/kexec/kexec-tools-2.0.2/kexec/arch/mips/kexec-mips.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,379</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086527"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// RUN: %clang_cc1 %s -emit-llvm -o - -fblocks -triple x86_64-apple-darwin10 | FileCheck %s // rdar://10033986 typedef void (^BLOCK)(void); int main () { _Complex double c; BLOCK b = ^() { _Complex double z; z = z + c; }; b(); } // CHECK-LABEL: define internal void @__main_block_invoke // CHECK: [[C1:%.*]] = alloca { double, double }, align 8 // CHECK: [[RP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 0 // CHECK-NEXT: [[R:%.*]] = load double, double* [[RP]] // CHECK-NEXT: [[IP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 1 // CHECK-NEXT: [[I:%.*]] = load double, double* [[IP]] </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cd80/UtilizedLLVM</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tools/clang/test/CodeGen/capture-complex-expr-in-block.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">unlicense</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">710</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086528"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!-- Good morning, Mr. Phelps. --> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>or-tools/src/constraint_solver/: Class Members - Doxy</title> <link rel="shortcut icon" href="../../../favicon.ico"> <!-- Both stylesheets are supplied by Doxygen, with maybe minor tweaks from Google. --> <link href="../../../doxygen.css" rel="stylesheet" type="text/css"> <link href="../../../tabs.css" rel="stylesheet" type="text/css"> </head> <body topmargin=0 leftmargin=20 bottommargin=0 rightmargin=20 marginwidth=20 marginheight=0> <!-- Second part of the secret behind Doxy logo always having the word "Doxy" with the color of the day. --> <style> a.doxy_logo:hover { background-color: #287003 } </style> <table width=100% cellpadding=0 cellspacing=0 border=0> <!-- Top horizontal line with the color of the day. --> <tr valign=top> <td colspan=3 bgcolor=#287003 height=3></td> </tr> <!-- Header row with the links at the right. --> <tr valign=top> <td colspan=3 align=right> <font size=-1> Generated on: <font color=#287003><b>Thu Mar 29 07:46:58 PDT 2012</b></font> for <b>custom file set</b> </font> </td> </tr> <!-- Header row with the logo and the search form. --> <tr valign=top> <!-- Logo. --> <td align=left width=150> <table width=150 height=54 cellpadding=0 cellspacing=0 border=0> <tr valign=top> <!-- First part of the secret behind Doxy logo always having the word "Doxy" with the color of the day. --> <td bgcolor=#287003> <a class="doxy_logo" href="../../../index.html"><img src="../../../doxy_logo.png" alt="Doxy" border=0></a> </td> </tr> </table> </td> </tr> <!-- Tiny vertical space below the form. --> <tr valign=top> <td colspan=3 height=3></td> </tr> </table> <!-- Header navigation row. --> <div class="memproto"> <table width=100% cellpadding=0 cellspacing=0 border=0> <tr> <td align=left style="padding-left: 20px"><font size=+1><b><tt><font color=#333333>// <a href="../../../index.html"><font color=#287003>doxy</font></a>/</font> <a href="../../../or-tools/index.html">or-tools</a>/ <a href="../../../or-tools/src/index.html">src</a>/ <a href="../../../or-tools/src/constraint_solver/index.html">constraint_solver</a>/ </tt></b></font> </td> </tr> </table> </div> <br /> <!-- No subdirs found. --> <!-- End of header. --> <!-- Generated by Doxygen 1.5.6 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li class="current"><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <div class="tabs"> <ul> <li class="current"><a href="globals.html"><span>All</span></a></li> <li><a href="globals_func.html"><span>Functions</span></a></li> <li><a href="globals_vars.html"><span>Variables</span></a></li> <li><a href="globals_defs.html"><span>Defines</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="globals.html#index_a"><span>a</span></a></li> <li><a href="globals_0x62.html#index_b"><span>b</span></a></li> <li><a href="globals_0x63.html#index_c"><span>c</span></a></li> <li><a href="globals_0x64.html#index_d"><span>d</span></a></li> <li><a href="globals_0x65.html#index_e"><span>e</span></a></li> <li><a href="globals_0x66.html#index_f"><span>f</span></a></li> <li><a href="globals_0x68.html#index_h"><span>h</span></a></li> <li><a href="globals_0x69.html#index_i"><span>i</span></a></li> <li><a href="globals_0x6b.html#index_k"><span>k</span></a></li> <li class="current"><a href="globals_0x6c.html#index_l"><span>l</span></a></li> <li><a href="globals_0x6d.html#index_m"><span>m</span></a></li> <li><a href="globals_0x6e.html#index_n"><span>n</span></a></li> <li><a href="globals_0x6f.html#index_o"><span>o</span></a></li> <li><a href="globals_0x70.html#index_p"><span>p</span></a></li> <li><a href="globals_0x72.html#index_r"><span>r</span></a></li> <li><a href="globals_0x73.html#index_s"><span>s</span></a></li> <li><a href="globals_0x74.html#index_t"><span>t</span></a></li> <li><a href="globals_0x75.html#index_u"><span>u</span></a></li> <li><a href="globals_0x76.html#index_v"><span>v</span></a></li> <li><a href="globals_0x77.html#index_w"><span>w</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all file members with links to the files they belong to: <p> <h3><a class="anchor" name="index_l">- l -</a></h3><ul> <li>last_ : <a class="el" href="constraint__solver_8cc.html#4a265269d82faeacc90eef4f9668cdbb">constraint_solver.cc</a> , <a class="el" href="local__search_8cc.html#ce15cb86cc6195f048432fe3c9857083">local_search.cc</a> , <a class="el" href="search_8cc.html#ce15cb86cc6195f048432fe3c9857083">search.cc</a> <li>last_base_ : <a class="el" href="local__search_8cc.html#ffac8499a8767632743720c4c3d32115">local_search.cc</a> <li>last_decision_ : <a class="el" href="tree__monitor_8cc.html#62099e67098897368ab69691ee56f301">tree_monitor.cc</a> <li>last_time_delta_ : <a class="el" href="search_8cc.html#1d986b3a0535ec8217518dd4678164ba">search.cc</a> <li>last_value_ : <a class="el" href="tree__monitor_8cc.html#7fa11d59f0ebd802fce510dcc0e11e86">tree_monitor.cc</a> <li>last_variable_ : <a class="el" href="tree__monitor_8cc.html#dc3a742b7141c7e72d475efbd90cb83d">tree_monitor.cc</a> <li>late_cost_ : <a class="el" href="expressions_8cc.html#a8e46190c772625168c8960dcd597918">expressions.cc</a> <li>late_date_ : <a class="el" href="expressions_8cc.html#4834f3ce5a1ed3e970208c3274eafe71">expressions.cc</a> <li>left_ : <a class="el" href="default__search_8cc.html#b6fe37aaf06c41be6dfaec01d28810b3">default_search.cc</a> , <a class="el" href="expressions_8cc.html#7076deac82dc0a4df6618e6037964b0d">expressions.cc</a> , <a class="el" href="range__cst_8cc.html#d9043b5cc6b0849d578d3e91decd673a">range_cst.cc</a> <li>length_ : <a class="el" href="table_8cc.html#7d5350e32a84386f3508693ad02992b1">table.cc</a> <li>limit_ : <a class="el" href="local__search_8cc.html#1c69e7dcf9d555da2ceac2a003b9e647">local_search.cc</a> <li>limit_1_ : <a class="el" href="search_8cc.html#60b4e7c65e65cfd88aaaa2a2303ba16d">search.cc</a> <li>limit_2_ : <a class="el" href="search_8cc.html#1b75e3a7942c823425afbadc670b866f">search.cc</a> <li>limiter_ : <a class="el" href="search_8cc.html#21fbf59b6ca09e01c1568e774a9f4a1e">search.cc</a> <li>loads_ : <a class="el" href="pack_8cc.html#aea3cda9f7389374c313391aa065589d">pack.cc</a> <li>ls_operator_ : <a class="el" href="local__search_8cc.html#1b511506766ee2e09a27e61830c13347">local_search.cc</a> <li>lt_tree_ : <a class="el" href="resource_8cc.html#27d3bf892939e964a3e650ab1a8f822d">resource.cc</a> </ul> </div> <!-- Start of footer. --> <table width=100% cellpadding=0 cellspacing=0 border=0> <tr valign=top> <td colspan=2 height=10></td> </tr> <tr valign=top> <td colspan=2 bgcolor=#287003 height=3></td> </tr> </table> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <br /><br /> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">capturePointer/or-tools</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">documentation/reference_manual/or-tools/src/constraint_solver/globals_0x6c.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,677</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086529"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php /** * Unit test class for the MultiLineAssignment sniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0661756e637471696962467577736f7c28686372">[email protected]</a>> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Unit test class for the MultiLineAssignment sniff. * * A sniff unit test checks a .inc file for expected violations of a single * coding standard. Expected errors and warnings are stored in this class. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5b2a6bdb0a7a2babab195a6a4a0bcaffbbbb0a1">[email protected]</a>> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class PEAR_Tests_Formatting_MultiLineAssignmentUnitTest extends AbstractSniffUnitTest { /** * Returns the lines where errors should occur. * * The key of the array should represent the line number and the value * should represent the number of errors that should occur on that line. * * @return array<int, int> */ public function getErrorList() { return array( 3 => 1, 6 => 1, 8 => 1, ); }//end getErrorList() /** * Returns the lines where warnings should occur. * * The key of the array should represent the line number and the value * should represent the number of warnings that should occur on that line. * * @return array<int, int> */ public function getWarningList() { return array(); }//end getWarningList() }//end class ?> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">danalec/dotfiles</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sublime/.config/sublime-text-3/Packages/anaconda_php/plugin/handlers_php/linting/phpcs/CodeSniffer/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,893</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086530"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * (C) Copyright 2003 * Wolfgang Denk, DENX Software Engineering, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b1a286a2a3a8bee8a2a3">[email protected]</a>. * * See file CREDITS for list of people who contributed to this * project. * * 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 * */ #include <common.h> #include <command.h> #include <image.h> #include <u-boot/zlib.h> #include <asm/byteorder.h> #include <asm/addrspace.h> DECLARE_GLOBAL_DATA_PTR; #define LINUX_MAX_ENVS 256 #define LINUX_MAX_ARGS 256 static int linux_argc; static char **linux_argv; static char **linux_env; static char *linux_env_p; static int linux_env_idx; static void linux_params_init(ulong start, char *commandline); static void linux_env_set(char *env_name, char *env_val); static void boot_prep_linux(bootm_headers_t *images) { char *commandline = getenv("bootargs"); char env_buf[12]; char *cp; linux_params_init(UNCACHED_SDRAM(gd->bd->bi_boot_params), commandline); #ifdef CONFIG_MEMSIZE_IN_BYTES sprintf(env_buf, "%lu", (ulong)gd->ram_size); debug("## Giving linux memsize in bytes, %lu\n", (ulong)gd->ram_size); #else sprintf(env_buf, "%lu", (ulong)(gd->ram_size >> 20)); debug("## Giving linux memsize in MB, %lu\n", (ulong)(gd->ram_size >> 20)); #endif /* CONFIG_MEMSIZE_IN_BYTES */ linux_env_set("memsize", env_buf); sprintf(env_buf, "0x%08X", (uint) UNCACHED_SDRAM(images->rd_start)); linux_env_set("initrd_start", env_buf); sprintf(env_buf, "0x%X", (uint) (images->rd_end - images->rd_start)); linux_env_set("initrd_size", env_buf); sprintf(env_buf, "0x%08X", (uint) (gd->bd->bi_flashstart)); linux_env_set("flash_start", env_buf); sprintf(env_buf, "0x%X", (uint) (gd->bd->bi_flashsize)); linux_env_set("flash_size", env_buf); cp = getenv("ethaddr"); if (cp) linux_env_set("ethaddr", cp); cp = getenv("eth1addr"); if (cp) linux_env_set("eth1addr", cp); } static void boot_jump_linux(bootm_headers_t *images) { void (*theKernel) (int, char **, char **, int *); /* find kernel entry point */ theKernel = (void (*)(int, char **, char **, int *))images->ep; debug("## Transferring control to Linux (at address %08lx) ...\n", (ulong) theKernel); bootstage_mark(BOOTSTAGE_ID_RUN_OS); /* we assume that the kernel is in place */ printf("\nStarting kernel ...\n\n"); theKernel(linux_argc, linux_argv, linux_env, 0); } int do_bootm_linux(int flag, int argc, char * const argv[], bootm_headers_t *images) { /* No need for those on MIPS */ if (flag & BOOTM_STATE_OS_BD_T || flag & BOOTM_STATE_OS_CMDLINE) return -1; if (flag & BOOTM_STATE_OS_PREP) { boot_prep_linux(images); return 0; } if (flag & BOOTM_STATE_OS_GO) { boot_jump_linux(images); return 0; } boot_prep_linux(images); boot_jump_linux(images); /* does not return */ return 1; } static void linux_params_init(ulong start, char *line) { char *next, *quote, *argp; linux_argc = 1; linux_argv = (char **) start; linux_argv[0] = 0; argp = (char *) (linux_argv + LINUX_MAX_ARGS); next = line; while (line && *line && linux_argc < LINUX_MAX_ARGS) { quote = strchr(line, '"'); next = strchr(line, ' '); while (next && quote && quote < next) { /* we found a left quote before the next blank * now we have to find the matching right quote */ next = strchr(quote + 1, '"'); if (next) { quote = strchr(next + 1, '"'); next = strchr(next + 1, ' '); } } if (!next) next = line + strlen(line); linux_argv[linux_argc] = argp; memcpy(argp, line, next - line); argp[next - line] = 0; argp += next - line + 1; linux_argc++; if (*next) next++; line = next; } linux_env = (char **) (((ulong) argp + 15) & ~15); linux_env[0] = 0; linux_env_p = (char *) (linux_env + LINUX_MAX_ENVS); linux_env_idx = 0; } static void linux_env_set(char *env_name, char *env_val) { if (linux_env_idx < LINUX_MAX_ENVS - 1) { linux_env[linux_env_idx] = linux_env_p; strcpy(linux_env_p, env_name); linux_env_p += strlen(env_name); strcpy(linux_env_p, "="); linux_env_p += 1; strcpy(linux_env_p, env_val); linux_env_p += strlen(env_val); linux_env_p++; linux_env[++linux_env_idx] = 0; } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">lxl1140989/dmsdk</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">uboot/u-boot-dm6291/arch/mips/lib/bootm.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,774</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086531"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php global $wpdb, $wp_version, $yarpp; /* Enforce YARPP setup: */ $yarpp->enforce(); if(!$yarpp->enabled() && !$yarpp->activate()) { echo '<div class="updated">'.__('The YARPP database has an error which could not be fixed.','yarpp').'</div>'; } /* Check to see that templates are in the right place */ if (!$yarpp->diagnostic_custom_templates()) { $template_option = yarpp_get_option('template'); if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('template', false); $template_option = yarpp_get_option('rss_template'); if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('rss_template', false); } /** * @since 3.3 Move version checking here, in PHP. */ if (current_user_can('update_plugins')) { $yarpp_version_info = $yarpp->version_info(); /* * These strings are not localizable, as long as the plugin data on wordpress.org cannot be. */ $slug = 'yet-another-related-posts-plugin'; $plugin_name = 'Yet Another Related Posts Plugin'; $file = basename(YARPP_DIR).'/yarpp.php'; if ($yarpp_version_info['result'] === 'new') { /* Make sure the update system is aware of this version. */ $current = get_site_transient('update_plugins'); if (!isset($current->response[$file])) { delete_site_transient('update_plugins'); wp_update_plugins(); } echo '<div class="updated"><p>'; $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin='.$slug.'&TB_iframe=true&width=600&height=800'); printf( __( 'There is a new version of %1$s available.'. '<a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>'. 'or <a href="%5$s">update automatically</a>.', 'yarpp'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $yarpp_version_info['current']['version'], wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_'.$file) ); echo '</p></div>'; } else if ($yarpp_version_info['result'] === 'newbeta') { echo '<div class="updated"><p>'; printf( __( "There is a new beta (%s) of Yet Another Related Posts Plugin. ". "You can <a href=\"%s\">download it here</a> at your own risk.", "yarpp"), $yarpp_version_info['beta']['version'], $yarpp_version_info['beta']['url'] ); echo '</p></div>'; } } /* MyISAM Check */ include 'yarpp_myisam_notice.php'; /* This is not a yarpp pluging update, it is an yarpp option update */ if (isset($_POST['update_yarpp'])) { $new_options = array(); foreach ($yarpp->default_options as $option => $default) { if ( is_bool($default) ) $new_options[$option] = isset($_POST[$option]); if ( (is_string($default) || is_int($default)) && isset($_POST[$option]) && is_string($_POST[$option]) ) $new_options[$option] = stripslashes($_POST[$option]); } if ( isset($_POST['weight']) ) { $new_options['weight'] = array(); $new_options['require_tax'] = array(); foreach ( (array) $_POST['weight'] as $key => $value) { if ( $value == 'consider' ) $new_options['weight'][$key] = 1; if ( $value == 'consider_extra' ) $new_options['weight'][$key] = YARPP_EXTRA_WEIGHT; } foreach ( (array) $_POST['weight']['tax'] as $tax => $value) { if ( $value == 'consider' ) $new_options['weight']['tax'][$tax] = 1; if ( $value == 'consider_extra' ) $new_options['weight']['tax'][$tax] = YARPP_EXTRA_WEIGHT; if ( $value == 'require_one' ) { $new_options['weight']['tax'][$tax] = 1; $new_options['require_tax'][$tax] = 1; } if ( $value == 'require_more' ) { $new_options['weight']['tax'][$tax] = 1; $new_options['require_tax'][$tax] = 2; } } } if ( isset( $_POST['auto_display_post_types'] ) ) { $new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] ); } else { $new_options['auto_display_post_types'] = array(); } $new_options['recent'] = isset($_POST['recent_only']) ? $_POST['recent_number'] . ' ' . $_POST['recent_units'] : false; if ( isset($_POST['exclude']) ) $new_options['exclude'] = implode(',',array_keys($_POST['exclude'])); else $new_options['exclude'] = ''; $new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] : ( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false ); $new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] : ( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false ); $new_options = apply_filters( 'yarpp_settings_save', $new_options ); yarpp_set_option($new_options); echo '<div class="updated fade"><p>'.__('Options saved!','yarpp').'</p></div>'; } wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false); wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false); wp_nonce_field('yarpp_display_demo', 'yarpp_display_demo-nonce', false); wp_nonce_field('yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false); wp_nonce_field('yarpp_optin_data', 'yarpp_optin_data-nonce', false); wp_nonce_field('yarpp_set_display_code', 'yarpp_set_display_code-nonce', false); if (!count($yarpp->admin->get_templates()) && $yarpp->admin->can_copy_templates()) { wp_nonce_field('yarpp_copy_templates', 'yarpp_copy_templates-nonce', false); } include(YARPP_DIR.'/includes/phtmls/yarpp_options.phtml');</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sarahkpeck/it-starts-with</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wp-content/plugins/yet-another-related-posts-plugin/includes/yarpp_options.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,985</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086532"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># # Copyright (C) 2010-2013 ARM Limited. All rights reserved. # # This program is free software and is provided to you under the terms of the GNU General Public License version 2 # as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. # # A copy of the licence is included with the program, and can also be obtained from Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # USE_UMPV2=0 USING_PROFILING ?= 1 USING_INTERNAL_PROFILING ?= 0 MALI_DMA_BUF_MAP_ON_ATTACH ?= 1 # The Makefile sets up "arch" based on the CONFIG, creates the version info # string and the __malidrv_build_info.c file, and then call the Linux build # system to actually build the driver. After that point the Kbuild file takes # over. # set up defaults if not defined by the user ARCH ?= arm OSKOS=linux FILES_PREFIX= check_cc2 = \ $(shell if $(1) -S -o /dev/null -xc /dev/null > /dev/null 2>&1; \ then \ echo "$(2)"; \ else \ echo "$(3)"; \ fi ;) # This conditional makefile exports the global definition ARM_INTERNAL_BUILD. Customer releases will not include arm_internal.mak -include ../../../arm_internal.mak # Give warning of old config parameters are used ifneq ($(CONFIG),) $(warning "You have specified the CONFIG variable which is no longer in used. Use TARGET_PLATFORM instead.") endif ifneq ($(CPU),) $(warning "You have specified the CPU variable which is no longer in used. Use TARGET_PLATFORM instead.") endif # Include the mapping between TARGET_PLATFORM and KDIR + MALI_PLATFORM -include MALI_CONFIGURATION export KDIR ?= $(KDIR-$(TARGET_PLATFORM)) export MALI_PLATFORM ?= $(MALI_PLATFORM-$(TARGET_PLATFORM)) ifneq ($(TARGET_PLATFORM),) ifeq ($(MALI_PLATFORM),) $(error "Invalid TARGET_PLATFORM: $(TARGET_PLATFORM)") endif endif # validate lookup result ifeq ($(KDIR),) $(error No KDIR found for platform $(TARGET_PLATFORM)) endif ifeq ($(USING_UMP),1) export CONFIG_MALI400_UMP=y export EXTRA_DEFINES += -DCONFIG_MALI400_UMP=1 ifeq ($(USE_UMPV2),1) UMP_SYMVERS_FILE ?= ../umpv2/Module.symvers else UMP_SYMVERS_FILE ?= ../ump/Module.symvers endif KBUILD_EXTRA_SYMBOLS = $(realpath $(UMP_SYMVERS_FILE)) $(warning $(KBUILD_EXTRA_SYMBOLS)) endif # Define host system directory KDIR-$(shell uname -m):=/lib/modules/$(shell uname -r)/build include $(KDIR)/.config ifeq ($(ARCH), arm) # when compiling for ARM we're cross compiling export CROSS_COMPILE ?= $(call check_cc2, arm-linux-gnueabi-gcc, arm-linux-gnueabi-, arm-none-linux-gnueabi-) endif # report detected/selected settings ifdef ARM_INTERNAL_BUILD $(warning TARGET_PLATFORM $(TARGET_PLATFORM)) $(warning KDIR $(KDIR)) $(warning MALI_PLATFORM $(MALI_PLATFORM)) endif # Set up build config export CONFIG_MALI400=m ifneq ($(MALI_PLATFORM),) export EXTRA_DEFINES += -DMALI_FAKE_PLATFORM_DEVICE=1 export MALI_PLATFORM_FILES = $(wildcard platform/$(MALI_PLATFORM)/*.c) endif ifeq ($(USING_PROFILING),1) ifeq ($(CONFIG_TRACEPOINTS),) $(warning CONFIG_TRACEPOINTS reqired for profiling) else export CONFIG_MALI400_PROFILING=y export EXTRA_DEFINES += -DCONFIG_MALI400_PROFILING=1 ifeq ($(USING_INTERNAL_PROFILING),1) export CONFIG_MALI400_INTERNAL_PROFILING=y export EXTRA_DEFINES += -DCONFIG_MALI400_INTERNAL_PROFILING=1 endif endif endif ifeq ($(MALI_DMA_BUF_MAP_ON_ATTACH),1) export CONFIG_MALI_DMA_BUF_MAP_ON_ATTACH=y export EXTRA_DEFINES += -DCONFIG_MALI_DMA_BUF_MAP_ON_ATTACH endif ifeq ($(MALI_SHARED_INTERRUPTS),1) export CONFIG_MALI_SHARED_INTERRUPTS=y export EXTRA_DEFINES += -DCONFIG_MALI_SHARED_INTERRUPTS endif ifneq ($(BUILD),release) export CONFIG_MALI400_DEBUG=y endif all: $(UMP_SYMVERS_FILE) $(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) modules @rm $(FILES_PREFIX)__malidrv_build_info.c $(FILES_PREFIX)__malidrv_build_info.o clean: $(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) clean kernelrelease: $(MAKE) ARCH=$(ARCH) -C $(KDIR) kernelrelease export CONFIG KBUILD_EXTRA_SYMBOLS </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gh1026/linux-3.4</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">modules/mali/DX910-SW-99002-r3p2-01rel3/driver/src/devicedrv/mali/Makefile</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Makefile</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,987</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086533"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* SPDX-License-Identifier: GPL-2.0+ */ /* Copyright (c) 2016-2017 Hisilicon Limited. */ #ifndef __HCLGEVF_CMD_H #define __HCLGEVF_CMD_H #include <linux/io.h> #include <linux/types.h> #include "hnae3.h" #define HCLGEVF_CMDQ_TX_TIMEOUT 30000 #define HCLGEVF_CMDQ_RX_INVLD_B 0 #define HCLGEVF_CMDQ_RX_OUTVLD_B 1 struct hclgevf_hw; struct hclgevf_dev; struct hclgevf_desc { __le16 opcode; __le16 flag; __le16 retval; __le16 rsv; __le32 data[6]; }; struct hclgevf_desc_cb { dma_addr_t dma; void *va; u32 length; }; struct hclgevf_cmq_ring { dma_addr_t desc_dma_addr; struct hclgevf_desc *desc; struct hclgevf_desc_cb *desc_cb; struct hclgevf_dev *dev; u32 head; u32 tail; u16 buf_size; u16 desc_num; int next_to_use; int next_to_clean; u8 flag; spinlock_t lock; /* Command queue lock */ }; enum hclgevf_cmd_return_status { HCLGEVF_CMD_EXEC_SUCCESS = 0, HCLGEVF_CMD_NO_AUTH = 1, HCLGEVF_CMD_NOT_EXEC = 2, HCLGEVF_CMD_QUEUE_FULL = 3, }; enum hclgevf_cmd_status { HCLGEVF_STATUS_SUCCESS = 0, HCLGEVF_ERR_CSQ_FULL = -1, HCLGEVF_ERR_CSQ_TIMEOUT = -2, HCLGEVF_ERR_CSQ_ERROR = -3 }; struct hclgevf_cmq { struct hclgevf_cmq_ring csq; struct hclgevf_cmq_ring crq; u16 tx_timeout; /* Tx timeout */ enum hclgevf_cmd_status last_status; }; #define HCLGEVF_CMD_FLAG_IN_VALID_SHIFT 0 #define HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT 1 #define HCLGEVF_CMD_FLAG_NEXT_SHIFT 2 #define HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT 3 #define HCLGEVF_CMD_FLAG_NO_INTR_SHIFT 4 #define HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT 5 #define HCLGEVF_CMD_FLAG_IN BIT(HCLGEVF_CMD_FLAG_IN_VALID_SHIFT) #define HCLGEVF_CMD_FLAG_OUT BIT(HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT) #define HCLGEVF_CMD_FLAG_NEXT BIT(HCLGEVF_CMD_FLAG_NEXT_SHIFT) #define HCLGEVF_CMD_FLAG_WR BIT(HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT) #define HCLGEVF_CMD_FLAG_NO_INTR BIT(HCLGEVF_CMD_FLAG_NO_INTR_SHIFT) #define HCLGEVF_CMD_FLAG_ERR_INTR BIT(HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT) enum hclgevf_opcode_type { /* Generic command */ HCLGEVF_OPC_QUERY_FW_VER = 0x0001, /* TQP command */ HCLGEVF_OPC_QUERY_TX_STATUS = 0x0B03, HCLGEVF_OPC_QUERY_RX_STATUS = 0x0B13, HCLGEVF_OPC_CFG_COM_TQP_QUEUE = 0x0B20, /* RSS cmd */ HCLGEVF_OPC_RSS_GENERIC_CONFIG = 0x0D01, HCLGEVF_OPC_RSS_INDIR_TABLE = 0x0D07, HCLGEVF_OPC_RSS_TC_MODE = 0x0D08, /* Mailbox cmd */ HCLGEVF_OPC_MBX_VF_TO_PF = 0x2001, }; #define HCLGEVF_TQP_REG_OFFSET 0x80000 #define HCLGEVF_TQP_REG_SIZE 0x200 struct hclgevf_tqp_map { __le16 tqp_id; /* Absolute tqp id for in this pf */ u8 tqp_vf; /* VF id */ #define HCLGEVF_TQP_MAP_TYPE_PF 0 #define HCLGEVF_TQP_MAP_TYPE_VF 1 #define HCLGEVF_TQP_MAP_TYPE_B 0 #define HCLGEVF_TQP_MAP_EN_B 1 u8 tqp_flag; /* Indicate it's pf or vf tqp */ __le16 tqp_vid; /* Virtual id in this pf/vf */ u8 rsv[18]; }; #define HCLGEVF_VECTOR_ELEMENTS_PER_CMD 10 enum hclgevf_int_type { HCLGEVF_INT_TX = 0, HCLGEVF_INT_RX, HCLGEVF_INT_EVENT, }; struct hclgevf_ctrl_vector_chain { u8 int_vector_id; u8 int_cause_num; #define HCLGEVF_INT_TYPE_S 0 #define HCLGEVF_INT_TYPE_M 0x3 #define HCLGEVF_TQP_ID_S 2 #define HCLGEVF_TQP_ID_M (0x3fff << HCLGEVF_TQP_ID_S) __le16 tqp_type_and_id[HCLGEVF_VECTOR_ELEMENTS_PER_CMD]; u8 vfid; u8 resv; }; struct hclgevf_query_version_cmd { __le32 firmware; __le32 firmware_rsv[5]; }; #define HCLGEVF_RSS_HASH_KEY_OFFSET 4 #define HCLGEVF_RSS_HASH_KEY_NUM 16 struct hclgevf_rss_config_cmd { u8 hash_config; u8 rsv[7]; u8 hash_key[HCLGEVF_RSS_HASH_KEY_NUM]; }; struct hclgevf_rss_input_tuple_cmd { u8 ipv4_tcp_en; u8 ipv4_udp_en; u8 ipv4_stcp_en; u8 ipv4_fragment_en; u8 ipv6_tcp_en; u8 ipv6_udp_en; u8 ipv6_stcp_en; u8 ipv6_fragment_en; u8 rsv[16]; }; #define HCLGEVF_RSS_CFG_TBL_SIZE 16 struct hclgevf_rss_indirection_table_cmd { u16 start_table_index; u16 rss_set_bitmap; u8 rsv[4]; u8 rss_result[HCLGEVF_RSS_CFG_TBL_SIZE]; }; #define HCLGEVF_RSS_TC_OFFSET_S 0 #define HCLGEVF_RSS_TC_OFFSET_M (0x3ff << HCLGEVF_RSS_TC_OFFSET_S) #define HCLGEVF_RSS_TC_SIZE_S 12 #define HCLGEVF_RSS_TC_SIZE_M (0x7 << HCLGEVF_RSS_TC_SIZE_S) #define HCLGEVF_RSS_TC_VALID_B 15 #define HCLGEVF_MAX_TC_NUM 8 struct hclgevf_rss_tc_mode_cmd { u16 rss_tc_mode[HCLGEVF_MAX_TC_NUM]; u8 rsv[8]; }; #define HCLGEVF_LINK_STS_B 0 #define HCLGEVF_LINK_STATUS BIT(HCLGEVF_LINK_STS_B) struct hclgevf_link_status_cmd { u8 status; u8 rsv[23]; }; #define HCLGEVF_RING_ID_MASK 0x3ff #define HCLGEVF_TQP_ENABLE_B 0 struct hclgevf_cfg_com_tqp_queue_cmd { __le16 tqp_id; __le16 stream_id; u8 enable; u8 rsv[19]; }; struct hclgevf_cfg_tx_queue_pointer_cmd { __le16 tqp_id; __le16 tx_tail; __le16 tx_head; __le16 fbd_num; __le16 ring_offset; u8 rsv[14]; }; #define HCLGEVF_TYPE_CRQ 0 #define HCLGEVF_TYPE_CSQ 1 #define HCLGEVF_NIC_CSQ_BASEADDR_L_REG 0x27000 #define HCLGEVF_NIC_CSQ_BASEADDR_H_REG 0x27004 #define HCLGEVF_NIC_CSQ_DEPTH_REG 0x27008 #define HCLGEVF_NIC_CSQ_TAIL_REG 0x27010 #define HCLGEVF_NIC_CSQ_HEAD_REG 0x27014 #define HCLGEVF_NIC_CRQ_BASEADDR_L_REG 0x27018 #define HCLGEVF_NIC_CRQ_BASEADDR_H_REG 0x2701c #define HCLGEVF_NIC_CRQ_DEPTH_REG 0x27020 #define HCLGEVF_NIC_CRQ_TAIL_REG 0x27024 #define HCLGEVF_NIC_CRQ_HEAD_REG 0x27028 #define HCLGEVF_NIC_CMQ_EN_B 16 #define HCLGEVF_NIC_CMQ_ENABLE BIT(HCLGEVF_NIC_CMQ_EN_B) #define HCLGEVF_NIC_CMQ_DESC_NUM 1024 #define HCLGEVF_NIC_CMQ_DESC_NUM_S 3 #define HCLGEVF_NIC_CMDQ_INT_SRC_REG 0x27100 static inline void hclgevf_write_reg(void __iomem *base, u32 reg, u32 value) { writel(value, base + reg); } static inline u32 hclgevf_read_reg(u8 __iomem *base, u32 reg) { u8 __iomem *reg_addr = READ_ONCE(base); return readl(reg_addr + reg); } #define hclgevf_write_dev(a, reg, value) \ hclgevf_write_reg((a)->io_base, (reg), (value)) #define hclgevf_read_dev(a, reg) \ hclgevf_read_reg((a)->io_base, (reg)) #define HCLGEVF_SEND_SYNC(flag) \ ((flag) & HCLGEVF_CMD_FLAG_NO_INTR) int hclgevf_cmd_init(struct hclgevf_dev *hdev); void hclgevf_cmd_uninit(struct hclgevf_dev *hdev); int hclgevf_cmd_send(struct hclgevf_hw *hw, struct hclgevf_desc *desc, int num); void hclgevf_cmd_setup_basic_desc(struct hclgevf_desc *desc, enum hclgevf_opcode_type opcode, bool is_read); #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">raumfeld/linux-am33xx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/net/ethernet/hisilicon/hns3/hns3vf/hclgevf_cmd.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,156</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086534"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Test the `vmaxQs32' ARM Neon intrinsic. */ /* This file was autogenerated by neon-testgen. */ /* { dg-do assemble } */ /* { dg-require-effective-target arm_neon_ok } */ /* { dg-options "-save-temps -O0" } */ /* { dg-add-options arm_neon } */ #include "arm_neon.h" void test_vmaxQs32 (void) { int32x4_t out_int32x4_t; int32x4_t arg0_int32x4_t; int32x4_t arg1_int32x4_t; out_int32x4_t = vmaxq_s32 (arg0_int32x4_t, arg1_int32x4_t); } /* { dg-final { scan-assembler "vmax\.s32\[ \]+\[qQ\]\[0-9\]+, \[qQ\]\[0-9\]+, \[qQ\]\[0-9\]+!?\(\[ \]+@\[a-zA-Z0-9 \]+\)?\n" } } */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">selmentdev/selment-toolchain</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">source/gcc-latest/gcc/testsuite/gcc.target/arm/neon/vmaxQs32.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">584</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086535"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" report test results in JUnit-XML format, for use with Jenkins and build integration servers. Based on initial code from Ross Lawley. Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/ src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd """ from __future__ import absolute_import, division, print_function import functools import py import os import re import sys import time import pytest from _pytest import nodes from _pytest.config import filename_arg # Python 2.X and 3.X compatibility if sys.version_info[0] < 3: from codecs import open else: unichr = chr unicode = str long = int class Junit(py.xml.Namespace): pass # We need to get the subset of the invalid unicode ranges according to # XML 1.0 which are valid in this python build. Hence we calculate # this dynamically instead of hardcoding it. The spec range of valid # chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] # | [#x10000-#x10FFFF] _legal_chars = (0x09, 0x0A, 0x0d) _legal_ranges = ( (0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF), ) _legal_xml_re = [ unicode("%s-%s") % (unichr(low), unichr(high)) for (low, high) in _legal_ranges if low < sys.maxunicode ] _legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re illegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re)) del _legal_chars del _legal_ranges del _legal_xml_re _py_ext_re = re.compile(r"\.py$") def bin_xml_escape(arg): def repl(matchobj): i = ord(matchobj.group()) if i <= 0xFF: return unicode('#x%02X') % i else: return unicode('#x%04X') % i return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg))) class _NodeReporter(object): def __init__(self, nodeid, xml): self.id = nodeid self.xml = xml self.add_stats = self.xml.add_stats self.duration = 0 self.properties = [] self.nodes = [] self.testcase = None self.attrs = {} def append(self, node): self.xml.add_stats(type(node).__name__) self.nodes.append(node) def add_property(self, name, value): self.properties.append((str(name), bin_xml_escape(value))) def make_properties_node(self): """Return a Junit node containing custom properties, if any. """ if self.properties: return Junit.properties([ Junit.property(name=name, value=value) for name, value in self.properties ]) return '' def record_testreport(self, testreport): assert not self.testcase names = mangle_test_address(testreport.nodeid) classnames = names[:-1] if self.xml.prefix: classnames.insert(0, self.xml.prefix) attrs = { "classname": ".".join(classnames), "name": bin_xml_escape(names[-1]), "file": testreport.location[0], } if testreport.location[1] is not None: attrs["line"] = testreport.location[1] if hasattr(testreport, "url"): attrs["url"] = testreport.url self.attrs = attrs def to_xml(self): testcase = Junit.testcase(time=self.duration, **self.attrs) testcase.append(self.make_properties_node()) for node in self.nodes: testcase.append(node) return testcase def _add_simple(self, kind, message, data=None): data = bin_xml_escape(data) node = kind(data, message=message) self.append(node) def write_captured_output(self, report): for capname in ('out', 'err'): content = getattr(report, 'capstd' + capname) if content: tag = getattr(Junit, 'system-' + capname) self.append(tag(bin_xml_escape(content))) def append_pass(self, report): self.add_stats('passed') def append_failure(self, report): # msg = str(report.longrepr.reprtraceback.extraline) if hasattr(report, "wasxfail"): self._add_simple( Junit.skipped, "xfail-marked test passes unexpectedly") else: if hasattr(report.longrepr, "reprcrash"): message = report.longrepr.reprcrash.message elif isinstance(report.longrepr, (unicode, str)): message = report.longrepr else: message = str(report.longrepr) message = bin_xml_escape(message) fail = Junit.failure(message=message) fail.append(bin_xml_escape(report.longrepr)) self.append(fail) def append_collect_error(self, report): # msg = str(report.longrepr.reprtraceback.extraline) self.append(Junit.error(bin_xml_escape(report.longrepr), message="collection failure")) def append_collect_skipped(self, report): self._add_simple( Junit.skipped, "collection skipped", report.longrepr) def append_error(self, report): if getattr(report, 'when', None) == 'teardown': msg = "test teardown failure" else: msg = "test setup failure" self._add_simple( Junit.error, msg, report.longrepr) def append_skipped(self, report): if hasattr(report, "wasxfail"): self._add_simple( Junit.skipped, "expected test failure", report.wasxfail ) else: filename, lineno, skipreason = report.longrepr if skipreason.startswith("Skipped: "): skipreason = bin_xml_escape(skipreason[9:]) self.append( Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason), type="pytest.skip", message=skipreason)) self.write_captured_output(report) def finalize(self): data = self.to_xml().unicode(indent=0) self.__dict__.clear() self.to_xml = lambda: py.xml.raw(data) @pytest.fixture def record_xml_property(request): """Add extra xml properties to the tag for the calling test. The fixture is callable with ``(name, value)``, with value being automatically xml-encoded. """ request.node.warn( code='C3', message='record_xml_property is an experimental feature', ) xml = getattr(request.config, "_xml", None) if xml is not None: node_reporter = xml.node_reporter(request.node.nodeid) return node_reporter.add_property else: def add_property_noop(name, value): pass return add_property_noop def pytest_addoption(parser): group = parser.getgroup("terminal reporting") group.addoption( '--junitxml', '--junit-xml', action="store", dest="xmlpath", metavar="path", type=functools.partial(filename_arg, optname="--junitxml"), default=None, help="create junit-xml style report file at given path.") group.addoption( '--junitprefix', '--junit-prefix', action="store", metavar="str", default=None, help="prepend prefix to classnames in junit-xml output") parser.addini("junit_suite_name", "Test suite name for JUnit report", default="pytest") def pytest_configure(config): xmlpath = config.option.xmlpath # prevent opening xmllog on slave nodes (xdist) if xmlpath and not hasattr(config, 'slaveinput'): config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini("junit_suite_name")) config.pluginmanager.register(config._xml) def pytest_unconfigure(config): xml = getattr(config, '_xml', None) if xml: del config._xml config.pluginmanager.unregister(xml) def mangle_test_address(address): path, possible_open_bracket, params = address.partition('[') names = path.split("::") try: names.remove('()') except ValueError: pass # convert file path to dotted path names[0] = names[0].replace(nodes.SEP, '.') names[0] = _py_ext_re.sub("", names[0]) # put any params back names[-1] += possible_open_bracket + params return names class LogXML(object): def __init__(self, logfile, prefix, suite_name="pytest"): logfile = os.path.expanduser(os.path.expandvars(logfile)) self.logfile = os.path.normpath(os.path.abspath(logfile)) self.prefix = prefix self.suite_name = suite_name self.stats = dict.fromkeys([ 'error', 'passed', 'failure', 'skipped', ], 0) self.node_reporters = {} # nodeid -> _NodeReporter self.node_reporters_ordered = [] self.global_properties = [] # List of reports that failed on call but teardown is pending. self.open_reports = [] self.cnt_double_fail_tests = 0 def finalize(self, report): nodeid = getattr(report, 'nodeid', report) # local hack to handle xdist report order slavenode = getattr(report, 'node', None) reporter = self.node_reporters.pop((nodeid, slavenode)) if reporter is not None: reporter.finalize() def node_reporter(self, report): nodeid = getattr(report, 'nodeid', report) # local hack to handle xdist report order slavenode = getattr(report, 'node', None) key = nodeid, slavenode if key in self.node_reporters: # TODO: breasks for --dist=each return self.node_reporters[key] reporter = _NodeReporter(nodeid, self) self.node_reporters[key] = reporter self.node_reporters_ordered.append(reporter) return reporter def add_stats(self, key): if key in self.stats: self.stats[key] += 1 def _opentestcase(self, report): reporter = self.node_reporter(report) reporter.record_testreport(report) return reporter def pytest_runtest_logreport(self, report): """handle a setup/call/teardown report, generating the appropriate xml tags as necessary. note: due to plugins like xdist, this hook may be called in interlaced order with reports from other nodes. for example: usual call order: -> setup node1 -> call node1 -> teardown node1 -> setup node2 -> call node2 -> teardown node2 possible call order in xdist: -> setup node1 -> call node1 -> setup node2 -> call node2 -> teardown node2 -> teardown node1 """ close_report = None if report.passed: if report.when == "call": # ignore setup/teardown reporter = self._opentestcase(report) reporter.append_pass(report) elif report.failed: if report.when == "teardown": # The following vars are needed when xdist plugin is used report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( (rep for rep in self.open_reports if (rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None) if close_report: # We need to open new testcase in case we have failure in # call and error in teardown in order to follow junit # schema self.finalize(close_report) self.cnt_double_fail_tests += 1 reporter = self._opentestcase(report) if report.when == "call": reporter.append_failure(report) self.open_reports.append(report) else: reporter.append_error(report) elif report.skipped: reporter = self._opentestcase(report) reporter.append_skipped(report) self.update_testcase_duration(report) if report.when == "teardown": reporter = self._opentestcase(report) reporter.write_captured_output(report) self.finalize(report) report_wid = getattr(report, "worker_id", None) report_ii = getattr(report, "item_index", None) close_report = next( (rep for rep in self.open_reports if (rep.nodeid == report.nodeid and getattr(rep, "item_index", None) == report_ii and getattr(rep, "worker_id", None) == report_wid ) ), None) if close_report: self.open_reports.remove(close_report) def update_testcase_duration(self, report): """accumulates total duration for nodeid from given report and updates the Junit.testcase with the new total if already created. """ reporter = self.node_reporter(report) reporter.duration += getattr(report, 'duration', 0.0) def pytest_collectreport(self, report): if not report.passed: reporter = self._opentestcase(report) if report.failed: reporter.append_collect_error(report) else: reporter.append_collect_skipped(report) def pytest_internalerror(self, excrepr): reporter = self.node_reporter('internal') reporter.attrs.update(classname="pytest", name='internal') reporter._add_simple(Junit.error, 'internal error', excrepr) def pytest_sessionstart(self): self.suite_start_time = time.time() def pytest_sessionfinish(self): dirname = os.path.dirname(os.path.abspath(self.logfile)) if not os.path.isdir(dirname): os.makedirs(dirname) logfile = open(self.logfile, 'w', encoding='utf-8') suite_stop_time = time.time() suite_time_delta = suite_stop_time - self.suite_start_time numtests = (self.stats['passed'] + self.stats['failure'] + self.stats['skipped'] + self.stats['error'] - self.cnt_double_fail_tests) logfile.write('<?xml version="1.0" encoding="utf-8"?>') logfile.write(Junit.testsuite( self._get_global_properties_node(), [x.to_xml() for x in self.node_reporters_ordered], name=self.suite_name, errors=self.stats['error'], failures=self.stats['failure'], skips=self.stats['skipped'], tests=numtests, time="%.3f" % suite_time_delta, ).unicode(indent=0)) logfile.close() def pytest_terminal_summary(self, terminalreporter): terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile)) def add_global_property(self, name, value): self.global_properties.append((str(name), bin_xml_escape(value))) def _get_global_properties_node(self): """Return a Junit node containing custom properties, if any. """ if self.global_properties: return Junit.properties( [ Junit.property(name=name, value=value) for name, value in self.global_properties ] ) return '' </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">anthgur/servo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/junitxml.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">15,681</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086536"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><html> <head> <script> if (window.testRunner) { testRunner.dumpAsText(); testRunner.waitUntilDone(); } document.cookie = "secret=PASS"; function log(msg) { var line = document.createElement("div"); line.appendChild(document.createTextNode(msg)); document.getElementById("console").appendChild(line); } function runTest() { log("Running test."); frames[1].document.open(); log(frames[1].document.cookie); frames[1].document.close(); log("Test complete."); if (window.testRunner) testRunner.notifyDone(); } </script> <base href="http://localhost:8000/security/cookies/resources/set-a-cookie.html"> </head> <body> <iframe onload="runTest()" src="http://localhost:8000/security/cookies/resources/set-a-cookie.html"> </iframe> <iframe></iframe> <div id="console"></div> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">js0701/chromium-crosswalk</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/WebKit/LayoutTests/http/tests/security/cookies/base-about-blank.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">842</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086537"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/** * Copyright (c) 2016 hustcc * License: MIT * https://github.com/hustcc/timeago.js **/ /* jshint expr: true */ !function (root, factory) { if (typeof module === 'object' && module.exports) module.exports = factory(root); else root.timeago = factory(root); }(typeof window !== 'undefined' ? window : this, function () { var cnt = 0, // the timer counter, for timer key indexMapEn = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'], indexMapZh = ['秒', '分钟', '小时', '天', '周', '月', '年'], // build-in locales: en & zh_CN locales = { 'en': function(number, index) { if (index === 0) return ['just now', 'a while']; else { var unit = indexMapEn[parseInt(index / 2)]; if (number > 1) unit += 's'; return [number + ' ' + unit + ' ago', 'in ' + number + ' ' + unit]; } }, 'zh_CN': function(number, index) { if (index === 0) return ['刚刚', '片刻后']; else { var unit = indexMapZh[parseInt(index / 2)]; return [number + unit + '前', number + unit + '后']; } } }, // second, minute, hour, day, week, month, year(365 days) SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12], SEC_ARRAY_LEN = 6, ATTR_DATETIME = 'datetime'; /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeago(nowDate, defaultLocale) { var timers = {}; // real-time render timers // if do not set the defaultLocale, set it with `en` if (! defaultLocale) defaultLocale = 'en'; // use default build-in locale // calculate the diff second between date to be formated an now date. function diffSec(date) { var now = new Date(); if (nowDate) now = toDate(nowDate); return (now - toDate(date)) / 1000; } // format the diff second to *** time ago, with setting locale function formatDiff(diff, locale) { if (! locales[locale]) locale = defaultLocale; var i = 0; agoin = diff < 0 ? 1 : 0, // timein or timeago diff = Math.abs(diff); for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; } diff = toInt(diff); i *= 2; if (diff > (i === 0 ? 9 : 1)) i += 1; return locales[locale](diff, i)[agoin].replace('%s', diff); } /** * format: format the date to *** time ago, with setting or default locale * - date: the date / string / timestamp to be formated * - locale: the formated string's locale name, e.g. en / zh_CN * * How to use it? * var timeago = require('timeago.js')(); * timeago.format(new Date(), 'pl'); // Date instance * timeago.format('2016-09-10', 'fr'); // formated date string * timeago.format(1473473400269); // timestamp with ms **/ this.format = function(date, locale) { return formatDiff(diffSec(date), locale); }; // format Date / string / timestamp to Date instance. function toDate(input) { if (input instanceof Date) { return input; } else if (!isNaN(input)) { return new Date(toInt(input)); } else if (/^\d+$/.test(input)) { return new Date(toInt(input, 10)); } else { var s = (input || '').trim(); s = s.replace(/\.\d+/, '') // remove milliseconds .replace(/-/, '/').replace(/-/, '/') .replace(/T/, ' ').replace(/Z/, ' UTC') .replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400 return new Date(s); } } // change f into int, remove Decimal. just for code compression function toInt(f) { return parseInt(f); } // function leftSec(diff, unit) { // diff = diff % unit; // diff = diff ? unit - diff : unit; // return Math.ceil(diff); // } /** * nextInterval: calculate the next interval time. * - diff: the diff sec between now and date to be formated. * * What's the meaning? * diff = 61 then return 59 * diff = 3601 (an hour + 1 second), then return 3599 * make the interval with high performace. **/ // this.nextInterval = function(diff) { // for dev test function nextInterval(diff) { var rst = 1, i = 0, d = diff; for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) { diff /= SEC_ARRAY[i]; rst *= SEC_ARRAY[i]; } // return leftSec(d, rst); d = d % rst; d = d ? rst - d : rst; return Math.ceil(d); // }; // for dev test } // what the timer will do function doRender(node, date, locale, cnt) { var diff = diffSec(date); node.innerHTML = formatDiff(diff, locale); // waiting %s seconds, do the next render timers['k' + cnt] = setTimeout(function() { doRender(node, date, locale, cnt); }, nextInterval(diff) * 1000); } // get the datetime attribute, jQuery and DOM function getDateAttr(node) { if (node.getAttribute) return node.getAttribute(ATTR_DATETIME); if(node.attr) return node.attr(ATTR_DATETIME); } /** * render: render the DOM real-time. * - nodes: which nodes will be rendered. * - locale: the locale name used to format date. * * How to use it? * var timeago = new require('timeago.js')(); * // 1. javascript selector * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * // 2. use jQuery selector * timeago.render($('.need_to_be_rendered'), 'pl'); * * Notice: please be sure the dom has attribute `datetime`. **/ this.render = function(nodes, locale) { if (nodes.length === undefined) nodes = [nodes]; for (var i = 0; i < nodes.length; i++) { doRender(nodes[i], getDateAttr(nodes[i]), locale, ++ cnt); // render item } }; /** * cancel: cancel all the timers which are doing real-time render. * * How to use it? * var timeago = new require('timeago.js')(); * timeago.render(document.querySelectorAll('.need_to_be_rendered')); * timeago.cancel(); // will stop all the timer, stop render in real time. **/ this.cancel = function() { for (var key in timers) { clearTimeout(timers[key]); } timers = {}; }; /** * setLocale: set the default locale name. * * How to use it? * var timeago = require('timeago.js'); * timeago = new timeago(); * timeago.setLocale('fr'); **/ this.setLocale = function(locale) { defaultLocale = locale; }; return this; } /** * timeago: the function to get `timeago` instance. * - nowDate: the relative date, default is new Date(). * - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you. * * How to use it? * var timeagoLib = require('timeago.js'); * var timeago = timeagoLib(); // all use default. * var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago. * var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`. * var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前. **/ function timeagoFactory(nowDate, defaultLocale) { return new timeago(nowDate, defaultLocale); } /** * register: register a new language locale * - locale: locale name, e.g. en / zh_CN, notice the standard. * - localeFunc: the locale process function * * How to use it? * var timeagoLib = require('timeago.js'); * * timeagoLib.register('the locale name', the_locale_func); * // or * timeagoLib.register('pl', require('timeago.js/locales/pl')); **/ timeagoFactory.register = function(locale, localeFunc) { locales[locale] = localeFunc; }; return timeagoFactory; });</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">froala/cdnjs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ajax/libs/timeago.js/2.0.0/timeago.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">8,824</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086538"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * drivers/net/ethernet/mellanox/mlxsw/cmd.h * Copyright (c) 2015 Mellanox Technologies. All rights reserved. * Copyright (c) 2015 Jiri Pirko <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8d2d1cad1f8d5ddd4d4d9d6d7c096dbd7d5">[email protected]</a>> * Copyright (c) 2015 Ido Schimmel <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365f525945555e765b535a5a5758594e1855595b">[email protected]</a>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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. * * 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. */ #ifndef _MLXSW_CMD_H #define _MLXSW_CMD_H #include "item.h" #define MLXSW_CMD_MBOX_SIZE 4096 static inline char *mlxsw_cmd_mbox_alloc(void) { return kzalloc(MLXSW_CMD_MBOX_SIZE, GFP_KERNEL); } static inline void mlxsw_cmd_mbox_free(char *mbox) { kfree(mbox); } static inline void mlxsw_cmd_mbox_zero(char *mbox) { memset(mbox, 0, MLXSW_CMD_MBOX_SIZE); } struct mlxsw_core; int mlxsw_cmd_exec(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod, u32 in_mod, bool out_mbox_direct, char *in_mbox, size_t in_mbox_size, char *out_mbox, size_t out_mbox_size); static inline int mlxsw_cmd_exec_in(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod, u32 in_mod, char *in_mbox, size_t in_mbox_size) { return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false, in_mbox, in_mbox_size, NULL, 0); } static inline int mlxsw_cmd_exec_out(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod, u32 in_mod, bool out_mbox_direct, char *out_mbox, size_t out_mbox_size) { return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, out_mbox_direct, NULL, 0, out_mbox, out_mbox_size); } static inline int mlxsw_cmd_exec_none(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod, u32 in_mod) { return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false, NULL, 0, NULL, 0); } enum mlxsw_cmd_opcode { MLXSW_CMD_OPCODE_QUERY_FW = 0x004, MLXSW_CMD_OPCODE_QUERY_BOARDINFO = 0x006, MLXSW_CMD_OPCODE_QUERY_AQ_CAP = 0x003, MLXSW_CMD_OPCODE_MAP_FA = 0xFFF, MLXSW_CMD_OPCODE_UNMAP_FA = 0xFFE, MLXSW_CMD_OPCODE_CONFIG_PROFILE = 0x100, MLXSW_CMD_OPCODE_ACCESS_REG = 0x040, MLXSW_CMD_OPCODE_SW2HW_DQ = 0x201, MLXSW_CMD_OPCODE_HW2SW_DQ = 0x202, MLXSW_CMD_OPCODE_2ERR_DQ = 0x01E, MLXSW_CMD_OPCODE_QUERY_DQ = 0x022, MLXSW_CMD_OPCODE_SW2HW_CQ = 0x016, MLXSW_CMD_OPCODE_HW2SW_CQ = 0x017, MLXSW_CMD_OPCODE_QUERY_CQ = 0x018, MLXSW_CMD_OPCODE_SW2HW_EQ = 0x013, MLXSW_CMD_OPCODE_HW2SW_EQ = 0x014, MLXSW_CMD_OPCODE_QUERY_EQ = 0x015, MLXSW_CMD_OPCODE_QUERY_RESOURCES = 0x101, }; static inline const char *mlxsw_cmd_opcode_str(u16 opcode) { switch (opcode) { case MLXSW_CMD_OPCODE_QUERY_FW: return "QUERY_FW"; case MLXSW_CMD_OPCODE_QUERY_BOARDINFO: return "QUERY_BOARDINFO"; case MLXSW_CMD_OPCODE_QUERY_AQ_CAP: return "QUERY_AQ_CAP"; case MLXSW_CMD_OPCODE_MAP_FA: return "MAP_FA"; case MLXSW_CMD_OPCODE_UNMAP_FA: return "UNMAP_FA"; case MLXSW_CMD_OPCODE_CONFIG_PROFILE: return "CONFIG_PROFILE"; case MLXSW_CMD_OPCODE_ACCESS_REG: return "ACCESS_REG"; case MLXSW_CMD_OPCODE_SW2HW_DQ: return "SW2HW_DQ"; case MLXSW_CMD_OPCODE_HW2SW_DQ: return "HW2SW_DQ"; case MLXSW_CMD_OPCODE_2ERR_DQ: return "2ERR_DQ"; case MLXSW_CMD_OPCODE_QUERY_DQ: return "QUERY_DQ"; case MLXSW_CMD_OPCODE_SW2HW_CQ: return "SW2HW_CQ"; case MLXSW_CMD_OPCODE_HW2SW_CQ: return "HW2SW_CQ"; case MLXSW_CMD_OPCODE_QUERY_CQ: return "QUERY_CQ"; case MLXSW_CMD_OPCODE_SW2HW_EQ: return "SW2HW_EQ"; case MLXSW_CMD_OPCODE_HW2SW_EQ: return "HW2SW_EQ"; case MLXSW_CMD_OPCODE_QUERY_EQ: return "QUERY_EQ"; case MLXSW_CMD_OPCODE_QUERY_RESOURCES: return "QUERY_RESOURCES"; default: return "*UNKNOWN*"; } } enum mlxsw_cmd_status { /* Command execution succeeded. */ MLXSW_CMD_STATUS_OK = 0x00, /* Internal error (e.g. bus error) occurred while processing command. */ MLXSW_CMD_STATUS_INTERNAL_ERR = 0x01, /* Operation/command not supported or opcode modifier not supported. */ MLXSW_CMD_STATUS_BAD_OP = 0x02, /* Parameter not supported, parameter out of range. */ MLXSW_CMD_STATUS_BAD_PARAM = 0x03, /* System was not enabled or bad system state. */ MLXSW_CMD_STATUS_BAD_SYS_STATE = 0x04, /* Attempt to access reserved or unallocated resource, or resource in * inappropriate ownership. */ MLXSW_CMD_STATUS_BAD_RESOURCE = 0x05, /* Requested resource is currently executing a command. */ MLXSW_CMD_STATUS_RESOURCE_BUSY = 0x06, /* Required capability exceeds device limits. */ MLXSW_CMD_STATUS_EXCEED_LIM = 0x08, /* Resource is not in the appropriate state or ownership. */ MLXSW_CMD_STATUS_BAD_RES_STATE = 0x09, /* Index out of range (might be beyond table size or attempt to * access a reserved resource). */ MLXSW_CMD_STATUS_BAD_INDEX = 0x0A, /* NVMEM checksum/CRC failed. */ MLXSW_CMD_STATUS_BAD_NVMEM = 0x0B, /* Bad management packet (silently discarded). */ MLXSW_CMD_STATUS_BAD_PKT = 0x30, }; static inline const char *mlxsw_cmd_status_str(u8 status) { switch (status) { case MLXSW_CMD_STATUS_OK: return "OK"; case MLXSW_CMD_STATUS_INTERNAL_ERR: return "INTERNAL_ERR"; case MLXSW_CMD_STATUS_BAD_OP: return "BAD_OP"; case MLXSW_CMD_STATUS_BAD_PARAM: return "BAD_PARAM"; case MLXSW_CMD_STATUS_BAD_SYS_STATE: return "BAD_SYS_STATE"; case MLXSW_CMD_STATUS_BAD_RESOURCE: return "BAD_RESOURCE"; case MLXSW_CMD_STATUS_RESOURCE_BUSY: return "RESOURCE_BUSY"; case MLXSW_CMD_STATUS_EXCEED_LIM: return "EXCEED_LIM"; case MLXSW_CMD_STATUS_BAD_RES_STATE: return "BAD_RES_STATE"; case MLXSW_CMD_STATUS_BAD_INDEX: return "BAD_INDEX"; case MLXSW_CMD_STATUS_BAD_NVMEM: return "BAD_NVMEM"; case MLXSW_CMD_STATUS_BAD_PKT: return "BAD_PKT"; default: return "*UNKNOWN*"; } } /* QUERY_FW - Query Firmware * ------------------------- * OpMod == 0, INMmod == 0 * ----------------------- * The QUERY_FW command retrieves information related to firmware, command * interface version and the amount of resources that should be allocated to * the firmware. */ static inline int mlxsw_cmd_query_fw(struct mlxsw_core *mlxsw_core, char *out_mbox) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_FW, 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_query_fw_fw_pages * Amount of physical memory to be allocatedfor firmware usage in 4KB pages. */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_pages, 0x00, 16, 16); /* cmd_mbox_query_fw_fw_rev_major * Firmware Revision - Major */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_major, 0x00, 0, 16); /* cmd_mbox_query_fw_fw_rev_subminor * Firmware Sub-minor version (Patch level) */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_subminor, 0x04, 16, 16); /* cmd_mbox_query_fw_fw_rev_minor * Firmware Revision - Minor */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_minor, 0x04, 0, 16); /* cmd_mbox_query_fw_core_clk * Internal Clock Frequency (in MHz) */ MLXSW_ITEM32(cmd_mbox, query_fw, core_clk, 0x08, 16, 16); /* cmd_mbox_query_fw_cmd_interface_rev * Command Interface Interpreter Revision ID. This number is bumped up * every time a non-backward-compatible change is done for the command * interface. The current cmd_interface_rev is 1. */ MLXSW_ITEM32(cmd_mbox, query_fw, cmd_interface_rev, 0x08, 0, 16); /* cmd_mbox_query_fw_dt * If set, Debug Trace is supported */ MLXSW_ITEM32(cmd_mbox, query_fw, dt, 0x0C, 31, 1); /* cmd_mbox_query_fw_api_version * Indicates the version of the API, to enable software querying * for compatibility. The current api_version is 1. */ MLXSW_ITEM32(cmd_mbox, query_fw, api_version, 0x0C, 0, 16); /* cmd_mbox_query_fw_fw_hour * Firmware timestamp - hour */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_hour, 0x10, 24, 8); /* cmd_mbox_query_fw_fw_minutes * Firmware timestamp - minutes */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_minutes, 0x10, 16, 8); /* cmd_mbox_query_fw_fw_seconds * Firmware timestamp - seconds */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_seconds, 0x10, 8, 8); /* cmd_mbox_query_fw_fw_year * Firmware timestamp - year */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_year, 0x14, 16, 16); /* cmd_mbox_query_fw_fw_month * Firmware timestamp - month */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_month, 0x14, 8, 8); /* cmd_mbox_query_fw_fw_day * Firmware timestamp - day */ MLXSW_ITEM32(cmd_mbox, query_fw, fw_day, 0x14, 0, 8); /* cmd_mbox_query_fw_clr_int_base_offset * Clear Interrupt register's offset from clr_int_bar register * in PCI address space. */ MLXSW_ITEM64(cmd_mbox, query_fw, clr_int_base_offset, 0x20, 0, 64); /* cmd_mbox_query_fw_clr_int_bar * PCI base address register (BAR) where clr_int register is located. * 00 - BAR 0-1 (64 bit BAR) */ MLXSW_ITEM32(cmd_mbox, query_fw, clr_int_bar, 0x28, 30, 2); /* cmd_mbox_query_fw_error_buf_offset * Read Only buffer for internal error reports of offset * from error_buf_bar register in PCI address space). */ MLXSW_ITEM64(cmd_mbox, query_fw, error_buf_offset, 0x30, 0, 64); /* cmd_mbox_query_fw_error_buf_size * Internal error buffer size in DWORDs */ MLXSW_ITEM32(cmd_mbox, query_fw, error_buf_size, 0x38, 0, 32); /* cmd_mbox_query_fw_error_int_bar * PCI base address register (BAR) where error buffer * register is located. * 00 - BAR 0-1 (64 bit BAR) */ MLXSW_ITEM32(cmd_mbox, query_fw, error_int_bar, 0x3C, 30, 2); /* cmd_mbox_query_fw_doorbell_page_offset * Offset of the doorbell page */ MLXSW_ITEM64(cmd_mbox, query_fw, doorbell_page_offset, 0x40, 0, 64); /* cmd_mbox_query_fw_doorbell_page_bar * PCI base address register (BAR) of the doorbell page * 00 - BAR 0-1 (64 bit BAR) */ MLXSW_ITEM32(cmd_mbox, query_fw, doorbell_page_bar, 0x48, 30, 2); /* QUERY_BOARDINFO - Query Board Information * ----------------------------------------- * OpMod == 0 (N/A), INMmod == 0 (N/A) * ----------------------------------- * The QUERY_BOARDINFO command retrieves adapter specific parameters. */ static inline int mlxsw_cmd_boardinfo(struct mlxsw_core *mlxsw_core, char *out_mbox) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_BOARDINFO, 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_boardinfo_intapin * When PCIe interrupt messages are being used, this value is used for clearing * an interrupt. When using MSI-X, this register is not used. */ MLXSW_ITEM32(cmd_mbox, boardinfo, intapin, 0x10, 24, 8); /* cmd_mbox_boardinfo_vsd_vendor_id * PCISIG Vendor ID (www.pcisig.com/membership/vid_search) of the vendor * specifying/formatting the VSD. The vsd_vendor_id identifies the management * domain of the VSD/PSID data. Different vendors may choose different VSD/PSID * format and encoding as long as they use their assigned vsd_vendor_id. */ MLXSW_ITEM32(cmd_mbox, boardinfo, vsd_vendor_id, 0x1C, 0, 16); /* cmd_mbox_boardinfo_vsd * Vendor Specific Data. The VSD string that is burnt to the Flash * with the firmware. */ #define MLXSW_CMD_BOARDINFO_VSD_LEN 208 MLXSW_ITEM_BUF(cmd_mbox, boardinfo, vsd, 0x20, MLXSW_CMD_BOARDINFO_VSD_LEN); /* cmd_mbox_boardinfo_psid * The PSID field is a 16-ascii (byte) character string which acts as * the board ID. The PSID format is used in conjunction with * Mellanox vsd_vendor_id (15B3h). */ #define MLXSW_CMD_BOARDINFO_PSID_LEN 16 MLXSW_ITEM_BUF(cmd_mbox, boardinfo, psid, 0xF0, MLXSW_CMD_BOARDINFO_PSID_LEN); /* QUERY_AQ_CAP - Query Asynchronous Queues Capabilities * ----------------------------------------------------- * OpMod == 0 (N/A), INMmod == 0 (N/A) * ----------------------------------- * The QUERY_AQ_CAP command returns the device asynchronous queues * capabilities supported. */ static inline int mlxsw_cmd_query_aq_cap(struct mlxsw_core *mlxsw_core, char *out_mbox) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_AQ_CAP, 0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_query_aq_cap_log_max_sdq_sz * Log (base 2) of max WQEs allowed on SDQ. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_sdq_sz, 0x00, 24, 8); /* cmd_mbox_query_aq_cap_max_num_sdqs * Maximum number of SDQs. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_sdqs, 0x00, 0, 8); /* cmd_mbox_query_aq_cap_log_max_rdq_sz * Log (base 2) of max WQEs allowed on RDQ. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_rdq_sz, 0x04, 24, 8); /* cmd_mbox_query_aq_cap_max_num_rdqs * Maximum number of RDQs. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_rdqs, 0x04, 0, 8); /* cmd_mbox_query_aq_cap_log_max_cq_sz * Log (base 2) of max CQEs allowed on CQ. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_cq_sz, 0x08, 24, 8); /* cmd_mbox_query_aq_cap_max_num_cqs * Maximum number of CQs. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_cqs, 0x08, 0, 8); /* cmd_mbox_query_aq_cap_log_max_eq_sz * Log (base 2) of max EQEs allowed on EQ. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_eq_sz, 0x0C, 24, 8); /* cmd_mbox_query_aq_cap_max_num_eqs * Maximum number of EQs. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_eqs, 0x0C, 0, 8); /* cmd_mbox_query_aq_cap_max_sg_sq * The maximum S/G list elements in an DSQ. DSQ must not contain * more S/G entries than indicated here. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_sq, 0x10, 8, 8); /* cmd_mbox_query_aq_cap_ * The maximum S/G list elements in an DRQ. DRQ must not contain * more S/G entries than indicated here. */ MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_rq, 0x10, 0, 8); /* MAP_FA - Map Firmware Area * -------------------------- * OpMod == 0 (N/A), INMmod == Number of VPM entries * ------------------------------------------------- * The MAP_FA command passes physical pages to the switch. These pages * are used to store the device firmware. MAP_FA can be executed multiple * times until all the firmware area is mapped (the size that should be * mapped is retrieved through the QUERY_FW command). All required pages * must be mapped to finish the initialization phase. Physical memory * passed in this command must be pinned. */ #define MLXSW_CMD_MAP_FA_VPM_ENTRIES_MAX 32 static inline int mlxsw_cmd_map_fa(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 vpm_entries_count) { return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_MAP_FA, 0, vpm_entries_count, in_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_map_fa_pa * Physical Address. */ MLXSW_ITEM64_INDEXED(cmd_mbox, map_fa, pa, 0x00, 12, 52, 0x08, 0x00, true); /* cmd_mbox_map_fa_log2size * Log (base 2) of the size in 4KB pages of the physical and contiguous memory * that starts at PA_L/H. */ MLXSW_ITEM32_INDEXED(cmd_mbox, map_fa, log2size, 0x00, 0, 5, 0x08, 0x04, false); /* UNMAP_FA - Unmap Firmware Area * ------------------------------ * OpMod == 0 (N/A), INMmod == 0 (N/A) * ----------------------------------- * The UNMAP_FA command unload the firmware and unmaps all the * firmware area. After this command is completed the device will not access * the pages that were mapped to the firmware area. After executing UNMAP_FA * command, software reset must be done prior to execution of MAP_FW command. */ static inline int mlxsw_cmd_unmap_fa(struct mlxsw_core *mlxsw_core) { return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_UNMAP_FA, 0, 0); } /* QUERY_RESOURCES - Query chip resources * -------------------------------------- * OpMod == 0 (N/A) , INMmod is index * ---------------------------------- * The QUERY_RESOURCES command retrieves information related to chip resources * by resource ID. Every command returns 32 entries. INmod is being use as base. * for example, index 1 will return entries 32-63. When the tables end and there * are no more sources in the table, will return resource id 0xFFF to indicate * it. */ #define MLXSW_CMD_QUERY_RESOURCES_TABLE_END_ID 0xffff #define MLXSW_CMD_QUERY_RESOURCES_MAX_QUERIES 100 #define MLXSW_CMD_QUERY_RESOURCES_PER_QUERY 32 static inline int mlxsw_cmd_query_resources(struct mlxsw_core *mlxsw_core, char *out_mbox, int index) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_RESOURCES, 0, index, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_query_resource_id * The resource id. 0xFFFF indicates table's end. */ MLXSW_ITEM32_INDEXED(cmd_mbox, query_resource, id, 0x00, 16, 16, 0x8, 0, false); /* cmd_mbox_query_resource_data * The resource */ MLXSW_ITEM64_INDEXED(cmd_mbox, query_resource, data, 0x00, 0, 40, 0x8, 0, false); /* CONFIG_PROFILE (Set) - Configure Switch Profile * ------------------------------ * OpMod == 1 (Set), INMmod == 0 (N/A) * ----------------------------------- * The CONFIG_PROFILE command sets the switch profile. The command can be * executed on the device only once at startup in order to allocate and * configure all switch resources and prepare it for operational mode. * It is not possible to change the device profile after the chip is * in operational mode. * Failure of the CONFIG_PROFILE command leaves the hardware in an indeterminate * state therefore it is required to perform software reset to the device * following an unsuccessful completion of the command. It is required * to perform software reset to the device to change an existing profile. */ static inline int mlxsw_cmd_config_profile_set(struct mlxsw_core *mlxsw_core, char *in_mbox) { return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_CONFIG_PROFILE, 1, 0, in_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_config_profile_set_max_vepa_channels * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_vepa_channels, 0x0C, 0, 1); /* cmd_mbox_config_profile_set_max_lag * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_lag, 0x0C, 1, 1); /* cmd_mbox_config_profile_set_max_port_per_lag * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_port_per_lag, 0x0C, 2, 1); /* cmd_mbox_config_profile_set_max_mid * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_mid, 0x0C, 3, 1); /* cmd_mbox_config_profile_set_max_pgt * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_pgt, 0x0C, 4, 1); /* cmd_mbox_config_profile_set_max_system_port * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_system_port, 0x0C, 5, 1); /* cmd_mbox_config_profile_set_max_vlan_groups * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_vlan_groups, 0x0C, 6, 1); /* cmd_mbox_config_profile_set_max_regions * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_regions, 0x0C, 7, 1); /* cmd_mbox_config_profile_set_flood_mode * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_flood_mode, 0x0C, 8, 1); /* cmd_mbox_config_profile_set_max_flood_tables * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_flood_tables, 0x0C, 9, 1); /* cmd_mbox_config_profile_set_max_ib_mc * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_ib_mc, 0x0C, 12, 1); /* cmd_mbox_config_profile_set_max_pkey * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_max_pkey, 0x0C, 13, 1); /* cmd_mbox_config_profile_set_adaptive_routing_group_cap * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_adaptive_routing_group_cap, 0x0C, 14, 1); /* cmd_mbox_config_profile_set_ar_sec * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_ar_sec, 0x0C, 15, 1); /* cmd_mbox_config_set_kvd_linear_size * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_linear_size, 0x0C, 24, 1); /* cmd_mbox_config_set_kvd_hash_single_size * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_single_size, 0x0C, 25, 1); /* cmd_mbox_config_set_kvd_hash_double_size * Capability bit. Setting a bit to 1 configures the profile * according to the mailbox contents. */ MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_double_size, 0x0C, 26, 1); /* cmd_mbox_config_profile_max_vepa_channels * Maximum number of VEPA channels per port (0 through 16) * 0 - multi-channel VEPA is disabled */ MLXSW_ITEM32(cmd_mbox, config_profile, max_vepa_channels, 0x10, 0, 8); /* cmd_mbox_config_profile_max_lag * Maximum number of LAG IDs requested. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_lag, 0x14, 0, 16); /* cmd_mbox_config_profile_max_port_per_lag * Maximum number of ports per LAG requested. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_port_per_lag, 0x18, 0, 16); /* cmd_mbox_config_profile_max_mid * Maximum Multicast IDs. * Multicast IDs are allocated from 0 to max_mid-1 */ MLXSW_ITEM32(cmd_mbox, config_profile, max_mid, 0x1C, 0, 16); /* cmd_mbox_config_profile_max_pgt * Maximum records in the Port Group Table per Switch Partition. * Port Group Table indexes are from 0 to max_pgt-1 */ MLXSW_ITEM32(cmd_mbox, config_profile, max_pgt, 0x20, 0, 16); /* cmd_mbox_config_profile_max_system_port * The maximum number of system ports that can be allocated. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_system_port, 0x24, 0, 16); /* cmd_mbox_config_profile_max_vlan_groups * Maximum number VLAN Groups for VLAN binding. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_vlan_groups, 0x28, 0, 12); /* cmd_mbox_config_profile_max_regions * Maximum number of TCAM Regions. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_regions, 0x2C, 0, 16); /* cmd_mbox_config_profile_max_flood_tables * Maximum number of single-entry flooding tables. Different flooding tables * can be associated with different packet types. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_flood_tables, 0x30, 16, 4); /* cmd_mbox_config_profile_max_vid_flood_tables * Maximum number of per-vid flooding tables. Flooding tables are associated * to the different packet types for the different switch partitions. * Table size is 4K entries covering all VID space. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_vid_flood_tables, 0x30, 8, 4); /* cmd_mbox_config_profile_flood_mode * Flooding mode to use. * 0-2 - Backward compatible modes for SwitchX devices. * 3 - Mixed mode, where: * max_flood_tables indicates the number of single-entry tables. * max_vid_flood_tables indicates the number of per-VID tables. * max_fid_offset_flood_tables indicates the number of FID-offset tables. * max_fid_flood_tables indicates the number of per-FID tables. */ MLXSW_ITEM32(cmd_mbox, config_profile, flood_mode, 0x30, 0, 2); /* cmd_mbox_config_profile_max_fid_offset_flood_tables * Maximum number of FID-offset flooding tables. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_fid_offset_flood_tables, 0x34, 24, 4); /* cmd_mbox_config_profile_fid_offset_flood_table_size * The size (number of entries) of each FID-offset flood table. */ MLXSW_ITEM32(cmd_mbox, config_profile, fid_offset_flood_table_size, 0x34, 0, 16); /* cmd_mbox_config_profile_max_fid_flood_tables * Maximum number of per-FID flooding tables. * * Note: This flooding tables cover special FIDs only (vFIDs), starting at * FID value 4K and higher. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_fid_flood_tables, 0x38, 24, 4); /* cmd_mbox_config_profile_fid_flood_table_size * The size (number of entries) of each per-FID table. */ MLXSW_ITEM32(cmd_mbox, config_profile, fid_flood_table_size, 0x38, 0, 16); /* cmd_mbox_config_profile_max_ib_mc * Maximum number of multicast FDB records for InfiniBand * FDB (in 512 chunks) per InfiniBand switch partition. */ MLXSW_ITEM32(cmd_mbox, config_profile, max_ib_mc, 0x40, 0, 15); /* cmd_mbox_config_profile_max_pkey * Maximum per port PKEY table size (for PKEY enforcement) */ MLXSW_ITEM32(cmd_mbox, config_profile, max_pkey, 0x44, 0, 15); /* cmd_mbox_config_profile_ar_sec * Primary/secondary capability * Describes the number of adaptive routing sub-groups * 0 - disable primary/secondary (single group) * 1 - enable primary/secondary (2 sub-groups) * 2 - 3 sub-groups: Not supported in SwitchX, SwitchX-2 * 3 - 4 sub-groups: Not supported in SwitchX, SwitchX-2 */ MLXSW_ITEM32(cmd_mbox, config_profile, ar_sec, 0x4C, 24, 2); /* cmd_mbox_config_profile_adaptive_routing_group_cap * Adaptive Routing Group Capability. Indicates the number of AR groups * supported. Note that when Primary/secondary is enabled, each * primary/secondary couple consumes 2 adaptive routing entries. */ MLXSW_ITEM32(cmd_mbox, config_profile, adaptive_routing_group_cap, 0x4C, 0, 16); /* cmd_mbox_config_profile_arn * Adaptive Routing Notification Enable * Not supported in SwitchX, SwitchX-2 */ MLXSW_ITEM32(cmd_mbox, config_profile, arn, 0x50, 31, 1); /* cmd_mbox_config_kvd_linear_size * KVD Linear Size * Valid for Spectrum only * Allowed values are 128*N where N=0 or higher */ MLXSW_ITEM32(cmd_mbox, config_profile, kvd_linear_size, 0x54, 0, 24); /* cmd_mbox_config_kvd_hash_single_size * KVD Hash single-entries size * Valid for Spectrum only * Allowed values are 128*N where N=0 or higher * Must be greater or equal to cap_min_kvd_hash_single_size * Must be smaller or equal to cap_kvd_size - kvd_linear_size */ MLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_single_size, 0x58, 0, 24); /* cmd_mbox_config_kvd_hash_double_size * KVD Hash double-entries size (units of single-size entries) * Valid for Spectrum only * Allowed values are 128*N where N=0 or higher * Must be either 0 or greater or equal to cap_min_kvd_hash_double_size * Must be smaller or equal to cap_kvd_size - kvd_linear_size */ MLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_double_size, 0x5C, 0, 24); /* cmd_mbox_config_profile_swid_config_mask * Modify Switch Partition Configuration mask. When set, the configu- * ration value for the Switch Partition are taken from the mailbox. * When clear, the current configuration values are used. * Bit 0 - set type * Bit 1 - properties * Other - reserved */ MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_mask, 0x60, 24, 8, 0x08, 0x00, false); /* cmd_mbox_config_profile_swid_config_type * Switch Partition type. * 0000 - disabled (Switch Partition does not exist) * 0001 - InfiniBand * 0010 - Ethernet * 1000 - router port (SwitchX-2 only) * Other - reserved */ MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_type, 0x60, 20, 4, 0x08, 0x00, false); /* cmd_mbox_config_profile_swid_config_properties * Switch Partition properties. */ MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_properties, 0x60, 0, 8, 0x08, 0x00, false); /* ACCESS_REG - Access EMAD Supported Register * ---------------------------------- * OpMod == 0 (N/A), INMmod == 0 (N/A) * ------------------------------------- * The ACCESS_REG command supports accessing device registers. This access * is mainly used for bootstrapping. */ static inline int mlxsw_cmd_access_reg(struct mlxsw_core *mlxsw_core, char *in_mbox, char *out_mbox) { return mlxsw_cmd_exec(mlxsw_core, MLXSW_CMD_OPCODE_ACCESS_REG, 0, 0, false, in_mbox, MLXSW_CMD_MBOX_SIZE, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* SW2HW_DQ - Software to Hardware DQ * ---------------------------------- * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ) * INMmod == DQ number * ---------------------------------------------- * The SW2HW_DQ command transitions a descriptor queue from software to * hardware ownership. The command enables posting WQEs and ringing DoorBells * on the descriptor queue. */ static inline int __mlxsw_cmd_sw2hw_dq(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 dq_number, u8 opcode_mod) { return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_DQ, opcode_mod, dq_number, in_mbox, MLXSW_CMD_MBOX_SIZE); } enum { MLXSW_CMD_OPCODE_MOD_SDQ = 0, MLXSW_CMD_OPCODE_MOD_RDQ = 1, }; static inline int mlxsw_cmd_sw2hw_sdq(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 dq_number) { return __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number, MLXSW_CMD_OPCODE_MOD_SDQ); } static inline int mlxsw_cmd_sw2hw_rdq(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 dq_number) { return __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number, MLXSW_CMD_OPCODE_MOD_RDQ); } /* cmd_mbox_sw2hw_dq_cq * Number of the CQ that this Descriptor Queue reports completions to. */ MLXSW_ITEM32(cmd_mbox, sw2hw_dq, cq, 0x00, 24, 8); /* cmd_mbox_sw2hw_dq_sdq_tclass * SDQ: CPU Egress TClass * RDQ: Reserved */ MLXSW_ITEM32(cmd_mbox, sw2hw_dq, sdq_tclass, 0x00, 16, 6); /* cmd_mbox_sw2hw_dq_log2_dq_sz * Log (base 2) of the Descriptor Queue size in 4KB pages. */ MLXSW_ITEM32(cmd_mbox, sw2hw_dq, log2_dq_sz, 0x00, 0, 6); /* cmd_mbox_sw2hw_dq_pa * Physical Address. */ MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_dq, pa, 0x10, 12, 52, 0x08, 0x00, true); /* HW2SW_DQ - Hardware to Software DQ * ---------------------------------- * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ) * INMmod == DQ number * ---------------------------------------------- * The HW2SW_DQ command transitions a descriptor queue from hardware to * software ownership. Incoming packets on the DQ are silently discarded, * SW should not post descriptors on nonoperational DQs. */ static inline int __mlxsw_cmd_hw2sw_dq(struct mlxsw_core *mlxsw_core, u32 dq_number, u8 opcode_mod) { return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_DQ, opcode_mod, dq_number); } static inline int mlxsw_cmd_hw2sw_sdq(struct mlxsw_core *mlxsw_core, u32 dq_number) { return __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number, MLXSW_CMD_OPCODE_MOD_SDQ); } static inline int mlxsw_cmd_hw2sw_rdq(struct mlxsw_core *mlxsw_core, u32 dq_number) { return __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number, MLXSW_CMD_OPCODE_MOD_RDQ); } /* 2ERR_DQ - To Error DQ * --------------------- * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ) * INMmod == DQ number * ---------------------------------------------- * The 2ERR_DQ command transitions the DQ into the error state from the state * in which it has been. While the command is executed, some in-process * descriptors may complete. Once the DQ transitions into the error state, * if there are posted descriptors on the RDQ/SDQ, the hardware writes * a completion with error (flushed) for all descriptors posted in the RDQ/SDQ. * When the command is completed successfully, the DQ is already in * the error state. */ static inline int __mlxsw_cmd_2err_dq(struct mlxsw_core *mlxsw_core, u32 dq_number, u8 opcode_mod) { return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ, opcode_mod, dq_number); } static inline int mlxsw_cmd_2err_sdq(struct mlxsw_core *mlxsw_core, u32 dq_number) { return __mlxsw_cmd_2err_dq(mlxsw_core, dq_number, MLXSW_CMD_OPCODE_MOD_SDQ); } static inline int mlxsw_cmd_2err_rdq(struct mlxsw_core *mlxsw_core, u32 dq_number) { return __mlxsw_cmd_2err_dq(mlxsw_core, dq_number, MLXSW_CMD_OPCODE_MOD_RDQ); } /* QUERY_DQ - Query DQ * --------------------- * OpMod == 0 (send DQ) / OpMod == 1 (receive DQ) * INMmod == DQ number * ---------------------------------------------- * The QUERY_DQ command retrieves a snapshot of DQ parameters from the hardware. * * Note: Output mailbox has the same format as SW2HW_DQ. */ static inline int __mlxsw_cmd_query_dq(struct mlxsw_core *mlxsw_core, char *out_mbox, u32 dq_number, u8 opcode_mod) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ, opcode_mod, dq_number, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } static inline int mlxsw_cmd_query_sdq(struct mlxsw_core *mlxsw_core, char *out_mbox, u32 dq_number) { return __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number, MLXSW_CMD_OPCODE_MOD_SDQ); } static inline int mlxsw_cmd_query_rdq(struct mlxsw_core *mlxsw_core, char *out_mbox, u32 dq_number) { return __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number, MLXSW_CMD_OPCODE_MOD_RDQ); } /* SW2HW_CQ - Software to Hardware CQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == CQ number * ------------------------------------- * The SW2HW_CQ command transfers ownership of a CQ context entry from software * to hardware. The command takes the CQ context entry from the input mailbox * and stores it in the CQC in the ownership of the hardware. The command fails * if the requested CQC entry is already in the ownership of the hardware. */ static inline int mlxsw_cmd_sw2hw_cq(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 cq_number) { return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_CQ, 0, cq_number, in_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_sw2hw_cq_cv * CQE Version. * 0 - CQE Version 0, 1 - CQE Version 1 */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, cv, 0x00, 28, 4); /* cmd_mbox_sw2hw_cq_c_eqn * Event Queue this CQ reports completion events to. */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, c_eqn, 0x00, 24, 1); /* cmd_mbox_sw2hw_cq_oi * When set, overrun ignore is enabled. When set, updates of * CQ consumer counter (poll for completion) or Request completion * notifications (Arm CQ) DoorBells should not be rung on that CQ. */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, oi, 0x00, 12, 1); /* cmd_mbox_sw2hw_cq_st * Event delivery state machine * 0x0 - FIRED * 0x1 - ARMED (Request for Notification) */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, st, 0x00, 8, 1); /* cmd_mbox_sw2hw_cq_log_cq_size * Log (base 2) of the CQ size (in entries). */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, log_cq_size, 0x00, 0, 4); /* cmd_mbox_sw2hw_cq_producer_counter * Producer Counter. The counter is incremented for each CQE that is * written by the HW to the CQ. * Maintained by HW (valid for the QUERY_CQ command only) */ MLXSW_ITEM32(cmd_mbox, sw2hw_cq, producer_counter, 0x04, 0, 16); /* cmd_mbox_sw2hw_cq_pa * Physical Address. */ MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_cq, pa, 0x10, 11, 53, 0x08, 0x00, true); /* HW2SW_CQ - Hardware to Software CQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == CQ number * ------------------------------------- * The HW2SW_CQ command transfers ownership of a CQ context entry from hardware * to software. The CQC entry is invalidated as a result of this command. */ static inline int mlxsw_cmd_hw2sw_cq(struct mlxsw_core *mlxsw_core, u32 cq_number) { return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_CQ, 0, cq_number); } /* QUERY_CQ - Query CQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == CQ number * ------------------------------------- * The QUERY_CQ command retrieves a snapshot of the current CQ context entry. * The command stores the snapshot in the output mailbox in the software format. * Note that the CQ context state and values are not affected by the QUERY_CQ * command. The QUERY_CQ command is for debug purposes only. * * Note: Output mailbox has the same format as SW2HW_CQ. */ static inline int mlxsw_cmd_query_cq(struct mlxsw_core *mlxsw_core, char *out_mbox, u32 cq_number) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_CQ, 0, cq_number, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } /* SW2HW_EQ - Software to Hardware EQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == EQ number * ------------------------------------- * The SW2HW_EQ command transfers ownership of an EQ context entry from software * to hardware. The command takes the EQ context entry from the input mailbox * and stores it in the EQC in the ownership of the hardware. The command fails * if the requested EQC entry is already in the ownership of the hardware. */ static inline int mlxsw_cmd_sw2hw_eq(struct mlxsw_core *mlxsw_core, char *in_mbox, u32 eq_number) { return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_EQ, 0, eq_number, in_mbox, MLXSW_CMD_MBOX_SIZE); } /* cmd_mbox_sw2hw_eq_int_msix * When set, MSI-X cycles will be generated by this EQ. * When cleared, an interrupt will be generated by this EQ. */ MLXSW_ITEM32(cmd_mbox, sw2hw_eq, int_msix, 0x00, 24, 1); /* cmd_mbox_sw2hw_eq_int_oi * When set, overrun ignore is enabled. */ MLXSW_ITEM32(cmd_mbox, sw2hw_eq, oi, 0x00, 12, 1); /* cmd_mbox_sw2hw_eq_int_st * Event delivery state machine * 0x0 - FIRED * 0x1 - ARMED (Request for Notification) * 0x11 - Always ARMED * other - reserved */ MLXSW_ITEM32(cmd_mbox, sw2hw_eq, st, 0x00, 8, 2); /* cmd_mbox_sw2hw_eq_int_log_eq_size * Log (base 2) of the EQ size (in entries). */ MLXSW_ITEM32(cmd_mbox, sw2hw_eq, log_eq_size, 0x00, 0, 4); /* cmd_mbox_sw2hw_eq_int_producer_counter * Producer Counter. The counter is incremented for each EQE that is written * by the HW to the EQ. * Maintained by HW (valid for the QUERY_EQ command only) */ MLXSW_ITEM32(cmd_mbox, sw2hw_eq, producer_counter, 0x04, 0, 16); /* cmd_mbox_sw2hw_eq_int_pa * Physical Address. */ MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_eq, pa, 0x10, 11, 53, 0x08, 0x00, true); /* HW2SW_EQ - Hardware to Software EQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == EQ number * ------------------------------------- */ static inline int mlxsw_cmd_hw2sw_eq(struct mlxsw_core *mlxsw_core, u32 eq_number) { return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_EQ, 0, eq_number); } /* QUERY_EQ - Query EQ * ---------------------------------- * OpMod == 0 (N/A), INMmod == EQ number * ------------------------------------- * * Note: Output mailbox has the same format as SW2HW_EQ. */ static inline int mlxsw_cmd_query_eq(struct mlxsw_core *mlxsw_core, char *out_mbox, u32 eq_number) { return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_EQ, 0, eq_number, false, out_mbox, MLXSW_CMD_MBOX_SIZE); } #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bas-t/linux_media</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/net/ethernet/mellanox/mlxsw/cmd.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">40,398</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086539"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/types.h> #include <linux/list.h> #include <linux/ioctl.h> #include <linux/spinlock.h> #include <linux/videodev2.h> #include <linux/proc_fs.h> #include <linux/vmalloc.h> #include <linux/module.h> #include <media/v4l2-dev.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-device.h> #include <linux/android_pmem.h> #include "msm.h" #include "msm_csid.h" #include "msm_csic.h" #include "msm_csiphy.h" #include "msm_ispif.h" #include "msm_sensor.h" #ifdef CONFIG_MSM_CAMERA_DEBUG #define D(fmt, args...) pr_debug("msm_mctl: " fmt, ##args) #else #define D(fmt, args...) do {} while (0) #endif #define MSM_V4L2_SWFI_LATENCY 3 /* VFE required buffer number for streaming */ static struct msm_isp_color_fmt msm_isp_formats[] = { { .name = "NV12YUV", .depth = 12, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV12, .pxlcode = V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV21YUV", .depth = 12, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV21, .pxlcode = V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV12BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV12, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV21BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV21, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV16BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV16, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV61BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV61, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "NV21BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_NV21, .pxlcode = V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "YU12BAYER", .depth = 8, .bitsperpxl = 8, .fourcc = V4L2_PIX_FMT_YUV420M, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "RAWBAYER", .depth = 10, .bitsperpxl = 10, .fourcc = V4L2_PIX_FMT_SBGGR10, .pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, { .name = "RAWBAYER", .depth = 10, .bitsperpxl = 10, .fourcc = V4L2_PIX_FMT_SBGGR10, .pxlcode = V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */ .colorspace = V4L2_COLORSPACE_JPEG, }, }; /* * V4l2 subdevice operations */ static int mctl_subdev_log_status(struct v4l2_subdev *sd) { return -EINVAL; } static long mctl_subdev_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg) { struct msm_cam_media_controller *pmctl = NULL; if (!sd) { pr_err("%s: param is NULL", __func__); return -EINVAL; } else pmctl = (struct msm_cam_media_controller *) v4l2_get_subdevdata(sd); return -EINVAL; } static int mctl_subdev_g_mbus_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { return -EINVAL; } static struct v4l2_subdev_core_ops mctl_subdev_core_ops = { .log_status = mctl_subdev_log_status, .ioctl = mctl_subdev_ioctl, }; static struct v4l2_subdev_video_ops mctl_subdev_video_ops = { .g_mbus_fmt = mctl_subdev_g_mbus_fmt, }; static struct v4l2_subdev_ops mctl_subdev_ops = { .core = &mctl_subdev_core_ops, .video = &mctl_subdev_video_ops, }; static int msm_get_sensor_info(struct msm_sync *sync, void __user *arg) { int rc = 0; struct msm_camsensor_info info; struct msm_camera_sensor_info *sdata; if (copy_from_user(&info, arg, sizeof(struct msm_camsensor_info))) { ERR_COPY_FROM_USER(); return -EFAULT; } sdata = sync->sdata; D("%s: sensor_name %s\n", __func__, sdata->sensor_name); memcpy(&info.name[0], sdata->sensor_name, MAX_SENSOR_NAME); info.flash_enabled = sdata->flash_data->flash_type != MSM_CAMERA_FLASH_NONE; /* copy back to user space */ if (copy_to_user((void *)arg, &info, sizeof(struct msm_camsensor_info))) { ERR_COPY_TO_USER(); rc = -EFAULT; } return rc; } /* called by other subdev to notify any changes*/ static int msm_mctl_notify(struct msm_cam_media_controller *p_mctl, unsigned int notification, void *arg) { int rc = -EINVAL; struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev); struct msm_camera_sensor_info *sinfo = (struct msm_camera_sensor_info *) s_ctrl->sensordata; struct msm_camera_device_platform_data *camdev = sinfo->pdata; uint8_t csid_core = camdev->csid_core; switch (notification) { case NOTIFY_CID_CHANGE: /* reconfig the ISPIF*/ if (p_mctl->ispif_sdev) { struct msm_ispif_params_list ispif_params; ispif_params.len = 1; ispif_params.params[0].intftype = PIX0; ispif_params.params[0].cid_mask = 0x0001; ispif_params.params[0].csid = csid_core; rc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl, VIDIOC_MSM_ISPIF_CFG, &ispif_params); if (rc < 0) return rc; } break; case NOTIFY_ISPIF_STREAM: /* call ISPIF stream on/off */ rc = v4l2_subdev_call(p_mctl->ispif_sdev, video, s_stream, (int)arg); if (rc < 0) return rc; break; case NOTIFY_ISP_MSG_EVT: case NOTIFY_VFE_MSG_OUT: case NOTIFY_VFE_MSG_STATS: case NOTIFY_VFE_MSG_COMP_STATS: case NOTIFY_VFE_BUF_EVT: case NOTIFY_VFE_BUF_FREE_EVT: if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) { rc = p_mctl->isp_sdev->isp_notify( p_mctl->isp_sdev->sd, notification, arg); } break; case NOTIFY_VPE_MSG_EVT: if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) { rc = p_mctl->isp_sdev->isp_notify( p_mctl->isp_sdev->sd_vpe, notification, arg); } break; case NOTIFY_PCLK_CHANGE: rc = v4l2_subdev_call(p_mctl->isp_sdev->sd, video, s_crystal_freq, *(uint32_t *)arg, 0); break; case NOTIFY_CSIPHY_CFG: rc = v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl, VIDIOC_MSM_CSIPHY_CFG, arg); break; case NOTIFY_CSID_CFG: rc = v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl, VIDIOC_MSM_CSID_CFG, arg); break; case NOTIFY_CSIC_CFG: rc = v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl, VIDIOC_MSM_CSIC_CFG, arg); break; default: break; } return rc; } static int msm_mctl_set_vfe_output_mode(struct msm_cam_media_controller *p_mctl, void __user *arg) { int rc = 0; if (copy_from_user(&p_mctl->vfe_output_mode, (void __user *)arg, sizeof(p_mctl->vfe_output_mode))) { pr_err("%s Copy from user failed ", __func__); rc = -EFAULT; } else { pr_info("%s: mctl=0x%p, vfe output mode =0x%x", __func__, p_mctl, p_mctl->vfe_output_mode); } return rc; } /* called by the server or the config nodes to handle user space commands*/ static int msm_mctl_cmd(struct msm_cam_media_controller *p_mctl, unsigned int cmd, unsigned long arg) { int rc = -EINVAL; void __user *argp = (void __user *)arg; if (!p_mctl) { pr_err("%s: param is NULL", __func__); return -EINVAL; } D("%s:%d: cmd %d\n", __func__, __LINE__, cmd); /* ... call sensor, ISPIF or VEF subdev*/ switch (cmd) { /* sensor config*/ case MSM_CAM_IOCTL_GET_SENSOR_INFO: rc = msm_get_sensor_info(&p_mctl->sync, argp); break; case MSM_CAM_IOCTL_SENSOR_IO_CFG: printk(KERN_DEBUG "MSM_CAM_IOCTL_SENSOR_IO_CFG\n"); rc = v4l2_subdev_call(p_mctl->sensor_sdev, core, ioctl, VIDIOC_MSM_SENSOR_CFG, argp); break; case MSM_CAM_IOCTL_SENSOR_V4l2_S_CTRL: { struct v4l2_control v4l2_ctrl; CDBG("subdev call\n"); if (copy_from_user(&v4l2_ctrl, (void *)argp, sizeof(struct v4l2_control))) { CDBG("copy fail\n"); return -EFAULT; } CDBG("subdev call ok\n"); rc = v4l2_subdev_call(p_mctl->sensor_sdev, core, s_ctrl, &v4l2_ctrl); break; } case MSM_CAM_IOCTL_SENSOR_V4l2_QUERY_CTRL: { struct v4l2_queryctrl v4l2_qctrl; CDBG("query called\n"); if (copy_from_user(&v4l2_qctrl, (void *)argp, sizeof(struct v4l2_queryctrl))) { CDBG("copy fail\n"); rc = -EFAULT; break; } rc = v4l2_subdev_call(p_mctl->sensor_sdev, core, queryctrl, &v4l2_qctrl); if (rc < 0) { rc = -EFAULT; break; } if (copy_to_user((void *)argp, &v4l2_qctrl, sizeof(struct v4l2_queryctrl))) { rc = -EFAULT; } break; } case MSM_CAM_IOCTL_ACTUATOR_IO_CFG: { struct msm_actuator_cfg_data act_data; if (p_mctl->sync.actctrl.a_config) { rc = p_mctl->sync.actctrl.a_config(argp); } else { rc = copy_from_user( &act_data, (void *)argp, sizeof(struct msm_actuator_cfg_data)); if (rc != 0) { rc = -EFAULT; break; } act_data.is_af_supported = 0; rc = copy_to_user((void *)argp, &act_data, sizeof(struct msm_actuator_cfg_data)); if (rc != 0) { rc = -EFAULT; break; } } break; } case MSM_CAM_IOCTL_GET_KERNEL_SYSTEM_TIME: { struct timeval timestamp; if (copy_from_user(&timestamp, argp, sizeof(timestamp))) { ERR_COPY_FROM_USER(); rc = -EFAULT; } else { msm_mctl_gettimeofday(&timestamp); rc = copy_to_user((void *)argp, &timestamp, sizeof(timestamp)); } break; } case MSM_CAM_IOCTL_FLASH_CTRL: { struct flash_ctrl_data flash_info; if (copy_from_user(&flash_info, argp, sizeof(flash_info))) { ERR_COPY_FROM_USER(); rc = -EFAULT; } else { rc = msm_flash_ctrl(p_mctl->sync.sdata, &flash_info); } break; } case MSM_CAM_IOCTL_PICT_PP: rc = msm_mctl_set_pp_key(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_PICT_PP_DIVERT_DONE: rc = msm_mctl_pp_divert_done(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_PICT_PP_DONE: rc = msm_mctl_pp_done(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_MCTL_POST_PROC: rc = msm_mctl_pp_ioctl(p_mctl, cmd, arg); break; case MSM_CAM_IOCTL_RESERVE_FREE_FRAME: rc = msm_mctl_pp_reserve_free_frame(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_RELEASE_FREE_FRAME: rc = msm_mctl_pp_release_free_frame(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_SET_VFE_OUTPUT_TYPE: rc = msm_mctl_set_vfe_output_mode(p_mctl, (void __user *)arg); break; case MSM_CAM_IOCTL_MCTL_DIVERT_DONE: rc = msm_mctl_pp_mctl_divert_done(p_mctl, (void __user *)arg); break; /* ISFIF config*/ default: /* ISP config*/ D("%s:%d: go to default. Calling msm_isp_config\n", __func__, __LINE__); rc = p_mctl->isp_sdev->isp_config(p_mctl, cmd, arg); break; } D("%s: !!! cmd = %d, rc = %d\n", __func__, _IOC_NR(cmd), rc); return rc; } static int msm_mctl_subdev_match_core(struct device *dev, void *data) { int core_index = (int)data; struct platform_device *pdev = to_platform_device(dev); if (pdev->id == core_index) return 1; else return 0; } static int msm_mctl_register_subdevs(struct msm_cam_media_controller *p_mctl, int core_index) { struct device_driver *driver; struct device *dev; int rc = -ENODEV; struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev); struct msm_camera_sensor_info *sinfo = (struct msm_camera_sensor_info *) s_ctrl->sensordata; struct msm_camera_device_platform_data *pdata = sinfo->pdata; if (pdata->is_csiphy) { /* register csiphy subdev */ driver = driver_find(MSM_CSIPHY_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, (void *)core_index, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->csiphy_sdev = dev_get_drvdata(dev); // put_driver(driver); } /* if (pdata->is_csic) { / * register csic subdev * / driver = driver_find(MSM_CSIC_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, (void *)core_index, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->csic_sdev = dev_get_drvdata(dev); // put_driver(driver); } */ if (pdata->is_csid) { /* register csid subdev */ driver = driver_find(MSM_CSID_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, (void *)core_index, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->csid_sdev = dev_get_drvdata(dev); // put_driver(driver); } if (pdata->is_ispif) { /* register ispif subdev */ driver = driver_find(MSM_ISPIF_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, 0, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->ispif_sdev = dev_get_drvdata(dev); // put_driver(driver); } /* register vfe subdev */ driver = driver_find(MSM_VFE_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, 0, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->isp_sdev->sd = dev_get_drvdata(dev); // put_driver(driver); if (pdata->is_vpe) { /* register vfe subdev */ driver = driver_find(MSM_VPE_DRV_NAME, &platform_bus_type); if (!driver) goto out; dev = driver_find_device(driver, NULL, 0, msm_mctl_subdev_match_core); if (!dev) goto out_put_driver; p_mctl->isp_sdev->sd_vpe = dev_get_drvdata(dev); // put_driver(driver); } rc = 0; /* register gemini subdev */ driver = driver_find(MSM_GEMINI_DRV_NAME, &platform_bus_type); if (!driver) { pr_err("%s:%d:Gemini: Failure: goto out\n", __func__, __LINE__); goto out; } pr_debug("%s:%d:Gemini: driver_find_device Gemini driver 0x%x\n", __func__, __LINE__, (uint32_t)driver); dev = driver_find_device(driver, NULL, NULL, msm_mctl_subdev_match_core); if (!dev) { pr_err("%s:%d:Gemini: Failure goto out_put_driver\n", __func__, __LINE__); goto out_put_driver; } p_mctl->gemini_sdev = dev_get_drvdata(dev); pr_debug("%s:%d:Gemini: After dev_get_drvdata gemini_sdev=0x%x\n", __func__, __LINE__, (uint32_t)p_mctl->gemini_sdev); if (p_mctl->gemini_sdev == NULL) { pr_err("%s:%d:Gemini: Failure gemini_sdev is null\n", __func__, __LINE__); goto out_put_driver; } rc = 0; return rc; out_put_driver: //put_driver(driver); out: return rc; } static int msm_mctl_open(struct msm_cam_media_controller *p_mctl, const char *const apps_id) { int rc = 0; struct msm_sync *sync = NULL; struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev); struct msm_camera_sensor_info *sinfo = (struct msm_camera_sensor_info *) s_ctrl->sensordata; struct msm_camera_device_platform_data *camdev = sinfo->pdata; uint8_t csid_core; D("%s\n", __func__); if (!p_mctl) { pr_err("%s: param is NULL", __func__); return -EINVAL; } /* msm_sync_init() muct be called before*/ sync = &(p_mctl->sync); mutex_lock(&sync->lock); /* open sub devices - once only*/ if (!sync->opencnt) { uint32_t csid_version; wake_lock(&sync->wake_lock); csid_core = camdev->csid_core; rc = msm_mctl_register_subdevs(p_mctl, csid_core); if (rc < 0) { pr_err("%s: msm_mctl_register_subdevs failed:%d\n", __func__, rc); goto register_sdev_failed; } /* then sensor - move sub dev later*/ rc = v4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 1); if (rc < 0) { pr_err("%s: isp init failed: %d\n", __func__, rc); goto msm_open_done; } if (sync->actctrl.a_power_up) rc = sync->actctrl.a_power_up( sync->sdata->actuator_info); if (rc < 0) { pr_err("%s: act power failed:%d\n", __func__, rc); goto msm_open_done; } if (camdev->is_csiphy) { rc = v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl, VIDIOC_MSM_CSIPHY_INIT, NULL); if (rc < 0) { pr_err("%s: csiphy initialization failed %d\n", __func__, rc); goto csiphy_init_failed; } } if (camdev->is_csid) { rc = v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl, VIDIOC_MSM_CSID_INIT, &csid_version); if (rc < 0) { pr_err("%s: csid initialization failed %d\n", __func__, rc); goto csid_init_failed; } } /* if (camdev->is_csic) { rc = v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl, VIDIOC_MSM_CSIC_INIT, &csid_version); if (rc < 0) { pr_err("%s: csic initialization failed %d\n", __func__, rc); goto csic_init_failed; } } */ /* ISP first*/ if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_open) rc = p_mctl->isp_sdev->isp_open( p_mctl->isp_sdev->sd, p_mctl->isp_sdev->sd_vpe, p_mctl->gemini_sdev, sync); if (rc < 0) { pr_err("%s: isp init failed: %d\n", __func__, rc); goto isp_open_failed; } if (camdev->is_ispif) { rc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl, VIDIOC_MSM_ISPIF_INIT, &csid_version); if (rc < 0) { pr_err("%s: ispif initialization failed %d\n", __func__, rc); goto ispif_init_failed; } } if (camdev->is_ispif) { pm_qos_add_request(p_mctl->pm_qos_req_list, PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE); pm_qos_update_request(p_mctl->pm_qos_req_list, MSM_V4L2_SWFI_LATENCY); } sync->apps_id = apps_id; sync->opencnt++; } else { D("%s: camera is already open", __func__); } mutex_unlock(&sync->lock); return rc; ispif_init_failed: if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release) p_mctl->isp_sdev->isp_release(&p_mctl->sync, p_mctl->gemini_sdev); isp_open_failed: /* if (camdev->is_csic) if (v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl, VIDIOC_MSM_CSIC_RELEASE, NULL) < 0) pr_err("%s: csic release failed %d\n", __func__, rc); csic_init_failed:*/ if (camdev->is_csid) if (v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl, VIDIOC_MSM_CSID_RELEASE, NULL) < 0) pr_err("%s: csid release failed %d\n", __func__, rc); csid_init_failed: if (camdev->is_csiphy) if (v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl, VIDIOC_MSM_CSIPHY_RELEASE, NULL) < 0) pr_err("%s: csiphy release failed %d\n", __func__, rc); csiphy_init_failed: if (p_mctl->sync.actctrl.a_power_down) p_mctl->sync.actctrl.a_power_down( p_mctl->sync.sdata->actuator_info); register_sdev_failed: msm_open_done: wake_unlock(&p_mctl->sync.wake_lock); mutex_unlock(&sync->lock); return rc; } static int msm_mctl_release(struct msm_cam_media_controller *p_mctl) { int rc = 0; struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev); struct msm_camera_sensor_info *sinfo = (struct msm_camera_sensor_info *) s_ctrl->sensordata; struct msm_camera_device_platform_data *camdev = sinfo->pdata; v4l2_subdev_call(p_mctl->sensor_sdev, core, ioctl, VIDIOC_MSM_SENSOR_RELEASE, NULL); if (camdev->is_ispif) { v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl, VIDIOC_MSM_ISPIF_RELEASE, NULL); } /* if (camdev->is_csic) { v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl, VIDIOC_MSM_CSIC_RELEASE, NULL); } */ if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release) p_mctl->isp_sdev->isp_release(&p_mctl->sync, p_mctl->gemini_sdev); if (camdev->is_csid) { v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl, VIDIOC_MSM_CSID_RELEASE, NULL); } if (camdev->is_csiphy) { v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl, VIDIOC_MSM_CSIPHY_RELEASE, NULL); } if (camdev->is_ispif) { pm_qos_update_request(p_mctl->pm_qos_req_list, PM_QOS_DEFAULT_VALUE); pm_qos_remove_request(p_mctl->pm_qos_req_list); } if (p_mctl->sync.actctrl.a_power_down) p_mctl->sync.actctrl.a_power_down( p_mctl->sync.sdata->actuator_info); v4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 0); wake_unlock(&p_mctl->sync.wake_lock); return rc; } int msm_mctl_init_user_formats(struct msm_cam_v4l2_device *pcam) { struct v4l2_subdev *sd = pcam->mctl.sensor_sdev; enum v4l2_mbus_pixelcode pxlcode; int numfmt_sensor = 0; int numfmt = 0; int rc = 0; int i, j; D("%s\n", __func__); while (!v4l2_subdev_call(sd, video, enum_mbus_fmt, numfmt_sensor, &pxlcode)) numfmt_sensor++; D("%s, numfmt_sensor = %d\n", __func__, numfmt_sensor); if (!numfmt_sensor) return -ENXIO; pcam->usr_fmts = vmalloc(numfmt_sensor * ARRAY_SIZE(msm_isp_formats) * sizeof(struct msm_isp_color_fmt)); if (!pcam->usr_fmts) return -ENOMEM; /* from sensor to ISP.. fill the data structure */ for (i = 0; i < numfmt_sensor; i++) { rc = v4l2_subdev_call(sd, video, enum_mbus_fmt, i, &pxlcode); D("rc is %d\n", rc); if (rc < 0) { vfree(pcam->usr_fmts); return rc; } for (j = 0; j < ARRAY_SIZE(msm_isp_formats); j++) { /* find the corresponding format */ if (pxlcode == msm_isp_formats[j].pxlcode) { pcam->usr_fmts[numfmt] = msm_isp_formats[j]; D("pcam->usr_fmts=0x%x\n", (u32)pcam->usr_fmts); D("format pxlcode 0x%x (0x%x) found\n", pcam->usr_fmts[numfmt].pxlcode, pcam->usr_fmts[numfmt].fourcc); numfmt++; } } } pcam->num_fmts = numfmt; if (numfmt == 0) { pr_err("%s: No supported formats.\n", __func__); vfree(pcam->usr_fmts); return -EINVAL; } D("Found %d supported formats.\n", pcam->num_fmts); /* set the default pxlcode, in any case, it will be set through * setfmt */ return 0; } /* this function plug in the implementation of a v4l2_subdev */ int msm_mctl_init_module(struct msm_cam_v4l2_device *pcam) { struct msm_cam_media_controller *pmctl = NULL; D("%s\n", __func__); if (!pcam) { pr_err("%s: param is NULL", __func__); return -EINVAL; } else pmctl = &pcam->mctl; pmctl->sync.opencnt = 0; /* init module operations*/ pmctl->mctl_open = msm_mctl_open; pmctl->mctl_cmd = msm_mctl_cmd; pmctl->mctl_notify = msm_mctl_notify; pmctl->mctl_release = msm_mctl_release; /* init mctl buf */ msm_mctl_buf_init(pcam); memset(&pmctl->pp_info, 0, sizeof(pmctl->pp_info)); pmctl->vfe_output_mode = 0; spin_lock_init(&pmctl->pp_info.lock); /* init sub device*/ v4l2_subdev_init(&(pmctl->mctl_sdev), &mctl_subdev_ops); v4l2_set_subdevdata(&(pmctl->mctl_sdev), pmctl); return 0; } /* mctl node v4l2_file_operations */ static int msm_mctl_dev_open(struct file *f) { int rc = -EINVAL, i; /* get the video device */ struct msm_cam_v4l2_device *pcam = video_drvdata(f); struct msm_cam_v4l2_dev_inst *pcam_inst; pr_err("%s : E ", __func__); if (!pcam) { pr_err("%s NULL pointer passed in!\n", __func__); return rc; } mutex_lock(&pcam->mctl_node.dev_lock); for (i = 0; i < MSM_DEV_INST_MAX; i++) { if (pcam->mctl_node.dev_inst[i] == NULL) break; } /* if no instance is available, return error */ if (i == MSM_DEV_INST_MAX) { mutex_unlock(&pcam->mctl_node.dev_lock); return rc; } pcam_inst = kzalloc(sizeof(struct msm_cam_v4l2_dev_inst), GFP_KERNEL); if (!pcam_inst) { mutex_unlock(&pcam->mctl_node.dev_lock); return rc; } pcam_inst->sensor_pxlcode = pcam->usr_fmts[0].pxlcode; pcam_inst->my_index = i; pcam_inst->pcam = pcam; pcam->mctl_node.dev_inst[i] = pcam_inst; D("%s pcam_inst %p my_index = %d\n", __func__, pcam_inst, pcam_inst->my_index); D("%s for %s\n", __func__, pcam->pdev->name); rc = msm_setup_v4l2_event_queue(&pcam_inst->eventHandle, pcam->mctl_node.pvdev); if (rc < 0) { mutex_unlock(&pcam->mctl_node.dev_lock); return rc; } pcam_inst->vbqueue_initialized = 0; kref_get(&pcam->mctl.refcount); f->private_data = &pcam_inst->eventHandle; D("f->private_data = 0x%x, pcam = 0x%x\n", (u32)f->private_data, (u32)pcam_inst); mutex_unlock(&pcam->mctl_node.dev_lock); D("%s : X ", __func__); return rc; } static unsigned int msm_mctl_dev_poll(struct file *f, struct poll_table_struct *wait) { int rc = 0; struct msm_cam_v4l2_device *pcam; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); pcam = pcam_inst->pcam; D("%s : E pcam_inst = %p", __func__, pcam_inst); if (!pcam) { pr_err("%s NULL pointer of camera device!\n", __func__); return -EINVAL; } poll_wait(f, &(pcam_inst->eventHandle.wait), wait); if (v4l2_event_pending(&pcam_inst->eventHandle)) { rc |= POLLPRI; D("%s Event available on mctl node ", __func__); } D("%s poll on vb2\n", __func__); if (!pcam_inst->vid_bufq.streaming) { D("%s vid_bufq.streaming is off, inst=0x%x\n", __func__, (u32)pcam_inst); return rc; } rc |= vb2_poll(&pcam_inst->vid_bufq, f, wait); D("%s : X ", __func__); return rc; } static int msm_mctl_dev_close(struct file *f) { int rc = 0; struct msm_cam_v4l2_device *pcam; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); pcam = pcam_inst->pcam; pr_err("%s : E ", __func__); if (!pcam) { pr_err("%s NULL pointer of camera device!\n", __func__); return -EINVAL; } mutex_lock(&pcam->mctl_node.dev_lock); pcam_inst->streamon = 0; pcam->mctl_node.dev_inst_map[pcam_inst->image_mode] = NULL; if (pcam_inst->vbqueue_initialized) vb2_queue_release(&pcam_inst->vid_bufq); D("%s Closing down instance %p ", __func__, pcam_inst); pcam->mctl_node.dev_inst[pcam_inst->my_index] = NULL; v4l2_fh_del(&pcam_inst->eventHandle); v4l2_fh_exit(&pcam_inst->eventHandle); kfree(pcam_inst); kref_put(&pcam->mctl.refcount, msm_release_ion_client); f->private_data = NULL; mutex_unlock(&pcam->mctl_node.dev_lock); D("%s : X ", __func__); return rc; } static struct v4l2_file_operations g_msm_mctl_fops = { .owner = THIS_MODULE, .open = msm_mctl_dev_open, .poll = msm_mctl_dev_poll, .release = msm_mctl_dev_close, .unlocked_ioctl = video_ioctl2, }; /* * * implementation of mctl node v4l2_ioctl_ops * */ static int msm_mctl_v4l2_querycap(struct file *f, void *pctx, struct v4l2_capability *pcaps) { struct msm_cam_v4l2_device *pcam = video_drvdata(f); D("%s\n", __func__); WARN_ON(pctx != f->private_data); strlcpy(pcaps->driver, pcam->pdev->name, sizeof(pcaps->driver)); pcaps->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING; return 0; } static int msm_mctl_v4l2_queryctrl(struct file *f, void *pctx, struct v4l2_queryctrl *pqctrl) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_g_ctrl(struct file *f, void *pctx, struct v4l2_control *c) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_s_ctrl(struct file *f, void *pctx, struct v4l2_control *ctrl) { int rc = 0; struct msm_cam_v4l2_device *pcam = video_drvdata(f); struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s\n", __func__); WARN_ON(pctx != f->private_data); mutex_lock(&pcam->mctl_node.dev_lock); if (ctrl->id == MSM_V4L2_PID_PP_PLANE_INFO) { if (copy_from_user(&pcam_inst->plane_info, (void *)ctrl->value, sizeof(struct img_plane_info))) { pr_err("%s inst %p Copying plane_info failed ", __func__, pcam_inst); rc = -EFAULT; } D("%s inst %p got plane info: num_planes = %d," "plane size = %ld %ld ", __func__, pcam_inst, pcam_inst->plane_info.num_planes, pcam_inst->plane_info.plane[0].size, pcam_inst->plane_info.plane[1].size); } else pr_err("%s Unsupported S_CTRL Value ", __func__); mutex_unlock(&pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_reqbufs(struct file *f, void *pctx, struct v4l2_requestbuffers *pb) { int rc = 0, i, j; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s\n", __func__); WARN_ON(pctx != f->private_data); rc = vb2_reqbufs(&pcam_inst->vid_bufq, pb); mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); if (rc < 0) { pr_err("%s reqbufs failed %d ", __func__, rc); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } if (!pb->count) { /* Deallocation. free buf_offset array */ D("%s Inst %p freeing buffer offsets array", __func__, pcam_inst); for (j = 0 ; j < pcam_inst->buf_count ; j++) kfree(pcam_inst->buf_offset[j]); kfree(pcam_inst->buf_offset); pcam_inst->buf_offset = NULL; /* If the userspace has deallocated all the * buffers, then release the vb2 queue */ if (pcam_inst->vbqueue_initialized) { vb2_queue_release(&pcam_inst->vid_bufq); pcam_inst->vbqueue_initialized = 0; } } else { D("%s Inst %p Allocating buf_offset array", __func__, pcam_inst); /* Allocation. allocate buf_offset array */ pcam_inst->buf_offset = (struct msm_cam_buf_offset **) kzalloc(pb->count * sizeof(struct msm_cam_buf_offset *), GFP_KERNEL); if (!pcam_inst->buf_offset) { pr_err("%s out of memory ", __func__); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -ENOMEM; } for (i = 0; i < pb->count; i++) { pcam_inst->buf_offset[i] = kzalloc(sizeof(struct msm_cam_buf_offset) * pcam_inst->plane_info.num_planes, GFP_KERNEL); if (!pcam_inst->buf_offset[i]) { pr_err("%s out of memory ", __func__); for (j = i-1 ; j >= 0; j--) kfree(pcam_inst->buf_offset[j]); kfree(pcam_inst->buf_offset); pcam_inst->buf_offset = NULL; mutex_unlock( &pcam_inst->pcam->mctl_node.dev_lock); return -ENOMEM; } } } pcam_inst->buf_count = pb->count; D("%s inst %p, buf count %d ", __func__, pcam_inst, pcam_inst->buf_count); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_querybuf(struct file *f, void *pctx, struct v4l2_buffer *pb) { /* get the video device */ struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s\n", __func__); WARN_ON(pctx != f->private_data); return vb2_querybuf(&pcam_inst->vid_bufq, pb); } static int msm_mctl_v4l2_qbuf(struct file *f, void *pctx, struct v4l2_buffer *pb) { int rc = 0, i = 0; /* get the camera device */ struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s Inst = %p\n", __func__, pcam_inst); WARN_ON(pctx != f->private_data); mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); if (!pcam_inst->buf_offset) { pr_err("%s Buffer is already released. Returning. ", __func__); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -EINVAL; } if (pb->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) { /* Reject the buffer if planes array was not allocated */ if (pb->m.planes == NULL) { pr_err("%s Planes array is null ", __func__); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -EINVAL; } for (i = 0; i < pcam_inst->plane_info.num_planes; i++) { D("%s stored offsets for plane %d as" "addr offset %d, data offset %d", __func__, i, pb->m.planes[i].reserved[0], pb->m.planes[i].data_offset); pcam_inst->buf_offset[pb->index][i].data_offset = pb->m.planes[i].data_offset; pcam_inst->buf_offset[pb->index][i].addr_offset = pb->m.planes[i].reserved[0]; } } else { D("%s stored reserved info %d", __func__, pb->reserved); pcam_inst->buf_offset[pb->index][0].addr_offset = pb->reserved; } rc = vb2_qbuf(&pcam_inst->vid_bufq, pb); D("%s, videobuf_qbuf returns %d\n", __func__, rc); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_dqbuf(struct file *f, void *pctx, struct v4l2_buffer *pb) { int rc = 0; /* get the camera device */ struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s\n", __func__); WARN_ON(pctx != f->private_data); mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); rc = vb2_dqbuf(&pcam_inst->vid_bufq, pb, f->f_flags & O_NONBLOCK); D("%s, videobuf_dqbuf returns %d\n", __func__, rc); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_streamon(struct file *f, void *pctx, enum v4l2_buf_type buf_type) { int rc = 0; /* get the camera device */ struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s Inst %p\n", __func__, pcam_inst); WARN_ON(pctx != f->private_data); mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); if ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) && (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) { pr_err("%s Invalid buffer type ", __func__); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -EINVAL; } D("%s Calling videobuf_streamon", __func__); /* if HW streaming on is successful, start buffer streaming */ rc = vb2_streamon(&pcam_inst->vid_bufq, buf_type); D("%s, videobuf_streamon returns %d\n", __func__, rc); /* turn HW (VFE/sensor) streaming */ pcam_inst->streamon = 1; mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); D("%s rc = %d\n", __func__, rc); return rc; } static int msm_mctl_v4l2_streamoff(struct file *f, void *pctx, enum v4l2_buf_type buf_type) { int rc = 0; /* get the camera device */ struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s Inst %p\n", __func__, pcam_inst); WARN_ON(pctx != f->private_data); mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); if ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) && (buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) { pr_err("%s Invalid buffer type ", __func__); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -EINVAL; } /* first turn of HW (VFE/sensor) streaming so that buffers are not in use when we free the buffers */ pcam_inst->streamon = 0; /* stop buffer streaming */ rc = vb2_streamoff(&pcam_inst->vid_bufq, buf_type); D("%s, videobuf_streamoff returns %d\n", __func__, rc); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_enum_fmt_cap(struct file *f, void *pctx, struct v4l2_fmtdesc *pfmtdesc) { /* get the video device */ struct msm_cam_v4l2_device *pcam = video_drvdata(f); const struct msm_isp_color_fmt *isp_fmt; D("%s\n", __func__); WARN_ON(pctx != f->private_data); if ((pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) && (pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) return -EINVAL; if (pfmtdesc->index >= pcam->num_fmts) return -EINVAL; isp_fmt = &pcam->usr_fmts[pfmtdesc->index]; if (isp_fmt->name) strlcpy(pfmtdesc->description, isp_fmt->name, sizeof(pfmtdesc->description)); pfmtdesc->pixelformat = isp_fmt->fourcc; D("%s: [%d] 0x%x, %s\n", __func__, pfmtdesc->index, isp_fmt->fourcc, isp_fmt->name); return 0; } static int msm_mctl_v4l2_g_fmt_cap(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); if (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; return rc; } static int msm_mctl_v4l2_g_fmt_cap_mplane(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); if (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; return rc; } /* This function will readjust the format parameters based in HW capabilities. Called by s_fmt_cap */ static int msm_mctl_v4l2_try_fmt_cap(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_try_fmt_cap_mplane(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } /* This function will reconfig the v4l2 driver and HW device, it should be called after the streaming is stopped. */ static int msm_mctl_v4l2_s_fmt_cap(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0; /* get the video device */ struct msm_cam_v4l2_device *pcam = video_drvdata(f); struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s\n", __func__); D("%s, inst=0x%x,idx=%d,priv = 0x%p\n", __func__, (u32)pcam_inst, pcam_inst->my_index, (void *)pfmt->fmt.pix.priv); WARN_ON(pctx != f->private_data); if (!pcam_inst->vbqueue_initialized) { pcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq, V4L2_BUF_TYPE_VIDEO_CAPTURE); pcam_inst->vbqueue_initialized = 1; } return rc; } static int msm_mctl_v4l2_s_fmt_cap_mplane(struct file *f, void *pctx, struct v4l2_format *pfmt) { int rc = 0, i; struct msm_cam_v4l2_device *pcam = video_drvdata(f); struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s Inst %p vbqueue %d\n", __func__, pcam_inst, pcam_inst->vbqueue_initialized); WARN_ON(pctx != f->private_data); if (!pcam_inst->vbqueue_initialized) { pcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); pcam_inst->vbqueue_initialized = 1; } for (i = 0; i < pcam->num_fmts; i++) if (pcam->usr_fmts[i].fourcc == pfmt->fmt.pix_mp.pixelformat) break; if (i == pcam->num_fmts) { pr_err("%s: User requested pixelformat %x not supported\n", __func__, pfmt->fmt.pix_mp.pixelformat); return -EINVAL; } pcam_inst->vid_fmt = *pfmt; pcam_inst->sensor_pxlcode = pcam->usr_fmts[i].pxlcode; D("%s: inst=%p, width=%d, heigth=%d\n", __func__, pcam_inst, pcam_inst->vid_fmt.fmt.pix_mp.width, pcam_inst->vid_fmt.fmt.pix_mp.height); return rc; } static int msm_mctl_v4l2_g_jpegcomp(struct file *f, void *pctx, struct v4l2_jpegcompression *pcomp) { int rc = -EINVAL; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_s_jpegcomp(struct file *f, void *pctx, struct v4l2_jpegcompression *pcomp) { int rc = -EINVAL; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_g_crop(struct file *f, void *pctx, struct v4l2_crop *crop) { int rc = -EINVAL; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } static int msm_mctl_v4l2_s_crop(struct file *f, void *pctx, struct v4l2_crop *a) { int rc = -EINVAL; D("%s\n", __func__); WARN_ON(pctx != f->private_data); return rc; } /* Stream type-dependent parameter ioctls */ static int msm_mctl_v4l2_g_parm(struct file *f, void *pctx, struct v4l2_streamparm *a) { int rc = -EINVAL; return rc; } static int msm_mctl_vidbuf_get_path(u32 extendedmode) { switch (extendedmode) { case MSM_V4L2_EXT_CAPTURE_MODE_THUMBNAIL: return OUTPUT_TYPE_T; case MSM_V4L2_EXT_CAPTURE_MODE_MAIN: return OUTPUT_TYPE_S; case MSM_V4L2_EXT_CAPTURE_MODE_VIDEO: return OUTPUT_TYPE_V; case MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT: case MSM_V4L2_EXT_CAPTURE_MODE_PREVIEW: default: return OUTPUT_TYPE_P; } } static int msm_mctl_v4l2_s_parm(struct file *f, void *pctx, struct v4l2_streamparm *a) { int rc = 0; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = container_of(f->private_data, struct msm_cam_v4l2_dev_inst, eventHandle); pcam_inst->image_mode = a->parm.capture.extendedmode; mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock); if (pcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode]) { pr_err("%s Stream type %d already used.", __func__, pcam_inst->image_mode); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return -EBUSY; } pcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode] = pcam_inst; pcam_inst->path = msm_mctl_vidbuf_get_path(pcam_inst->image_mode); D("%s path=%d, image mode = %d rc=%d\n", __func__, pcam_inst->path, pcam_inst->image_mode, rc); mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock); return rc; } static int msm_mctl_v4l2_subscribe_event(struct v4l2_fh *fh, struct v4l2_event_subscription *sub) { int rc = 0; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = (struct msm_cam_v4l2_dev_inst *)container_of(fh, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s:fh = 0x%x, type = 0x%x\n", __func__, (u32)fh, sub->type); if (sub->type == V4L2_EVENT_ALL) sub->type = V4L2_EVENT_PRIVATE_START+MSM_CAM_APP_NOTIFY_EVENT; rc = v4l2_event_subscribe(fh, sub, 30); if (rc < 0) pr_err("%s: failed for evtType = 0x%x, rc = %d\n", __func__, sub->type, rc); return rc; } static int msm_mctl_v4l2_unsubscribe_event(struct v4l2_fh *fh, struct v4l2_event_subscription *sub) { int rc = 0; struct msm_cam_v4l2_dev_inst *pcam_inst; pcam_inst = (struct msm_cam_v4l2_dev_inst *)container_of(fh, struct msm_cam_v4l2_dev_inst, eventHandle); D("%s: fh = 0x%x\n", __func__, (u32)fh); rc = v4l2_event_unsubscribe(fh, sub); D("%s: rc = %d\n", __func__, rc); return rc; } /* mctl node v4l2_ioctl_ops */ static const struct v4l2_ioctl_ops g_msm_mctl_ioctl_ops = { .vidioc_querycap = msm_mctl_v4l2_querycap, .vidioc_s_crop = msm_mctl_v4l2_s_crop, .vidioc_g_crop = msm_mctl_v4l2_g_crop, .vidioc_queryctrl = msm_mctl_v4l2_queryctrl, .vidioc_g_ctrl = msm_mctl_v4l2_g_ctrl, .vidioc_s_ctrl = msm_mctl_v4l2_s_ctrl, .vidioc_reqbufs = msm_mctl_v4l2_reqbufs, .vidioc_querybuf = msm_mctl_v4l2_querybuf, .vidioc_qbuf = msm_mctl_v4l2_qbuf, .vidioc_dqbuf = msm_mctl_v4l2_dqbuf, .vidioc_streamon = msm_mctl_v4l2_streamon, .vidioc_streamoff = msm_mctl_v4l2_streamoff, /* format ioctls */ .vidioc_enum_fmt_vid_cap = msm_mctl_v4l2_enum_fmt_cap, .vidioc_enum_fmt_vid_cap_mplane = msm_mctl_v4l2_enum_fmt_cap, .vidioc_try_fmt_vid_cap = msm_mctl_v4l2_try_fmt_cap, .vidioc_try_fmt_vid_cap_mplane = msm_mctl_v4l2_try_fmt_cap_mplane, .vidioc_g_fmt_vid_cap = msm_mctl_v4l2_g_fmt_cap, .vidioc_g_fmt_vid_cap_mplane = msm_mctl_v4l2_g_fmt_cap_mplane, .vidioc_s_fmt_vid_cap = msm_mctl_v4l2_s_fmt_cap, .vidioc_s_fmt_vid_cap_mplane = msm_mctl_v4l2_s_fmt_cap_mplane, .vidioc_g_jpegcomp = msm_mctl_v4l2_g_jpegcomp, .vidioc_s_jpegcomp = msm_mctl_v4l2_s_jpegcomp, /* Stream type-dependent parameter ioctls */ .vidioc_g_parm = msm_mctl_v4l2_g_parm, .vidioc_s_parm = msm_mctl_v4l2_s_parm, /* event subscribe/unsubscribe */ .vidioc_subscribe_event = msm_mctl_v4l2_subscribe_event, .vidioc_unsubscribe_event = msm_mctl_v4l2_unsubscribe_event, }; int msm_setup_mctl_node(struct msm_cam_v4l2_device *pcam) { int rc = -EINVAL; struct video_device *pvdev = NULL; struct i2c_client *client = v4l2_get_subdevdata(pcam->mctl.sensor_sdev); D("%s\n", __func__); /* first register the v4l2 device */ pcam->mctl_node.v4l2_dev.dev = &client->dev; rc = v4l2_device_register(pcam->mctl_node.v4l2_dev.dev, &pcam->mctl_node.v4l2_dev); if (rc < 0) return -EINVAL; /* else pcam->v4l2_dev.notify = msm_cam_v4l2_subdev_notify; */ /* now setup video device */ pvdev = video_device_alloc(); if (pvdev == NULL) { pr_err("%s: video_device_alloc failed\n", __func__); return rc; } /* init video device's driver interface */ D("sensor name = %s, sizeof(pvdev->name)=%d\n", pcam->mctl.sensor_sdev->name, sizeof(pvdev->name)); /* device info - strlcpy is safer than strncpy but only if architecture supports*/ strlcpy(pvdev->name, pcam->mctl.sensor_sdev->name, sizeof(pvdev->name)); pvdev->release = video_device_release; pvdev->fops = &g_msm_mctl_fops; pvdev->ioctl_ops = &g_msm_mctl_ioctl_ops; pvdev->minor = -1; pvdev->vfl_type = 1; /* register v4l2 video device to kernel as /dev/videoXX */ D("%s video_register_device\n", __func__); rc = video_register_device(pvdev, VFL_TYPE_GRABBER, -1); if (rc) { pr_err("%s: video_register_device failed\n", __func__); goto reg_fail; } D("%s: video device registered as /dev/video%d\n", __func__, pvdev->num); /* connect pcam and mctl video dev to each other */ pcam->mctl_node.pvdev = pvdev; video_set_drvdata(pcam->mctl_node.pvdev, pcam); return rc ; reg_fail: video_device_release(pvdev); v4l2_device_unregister(&pcam->mctl_node.v4l2_dev); pcam->mctl_node.v4l2_dev.dev = NULL; return rc; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">imoseyon/leanKernel-d2vzw</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/media/video/msm_apexq/msm_mctl.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">44,450</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086540"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.usages.impl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.Navigatable; import com.intellij.usages.Usage; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageView; import com.intellij.usages.rules.MergeableUsage; import com.intellij.util.Consumer; import com.intellij.util.SmartList; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreeNode; import java.util.*; /** * @author max */ public class GroupNode extends Node implements Navigatable, Comparable<GroupNode> { private static final NodeComparator COMPARATOR = new NodeComparator(); private final Object lock = new Object(); private final UsageGroup myGroup; private final int myRuleIndex; private final Map<UsageGroup, GroupNode> mySubgroupNodes = new THashMap<UsageGroup, GroupNode>(); private final List<UsageNode> myUsageNodes = new SmartList<UsageNode>(); @NotNull private final UsageViewTreeModelBuilder myUsageTreeModel; private volatile int myRecursiveUsageCount = 0; public GroupNode(@Nullable UsageGroup group, int ruleIndex, @NotNull UsageViewTreeModelBuilder treeModel) { super(treeModel); myUsageTreeModel = treeModel; setUserObject(group); myGroup = group; myRuleIndex = ruleIndex; } @Override protected void updateNotify() { if (myGroup != null) { myGroup.update(); } } public String toString() { String result = ""; if (myGroup != null) result = myGroup.getText(null); if (children == null) { return result; } return result + children.subList(0, Math.min(10, children.size())).toString(); } public GroupNode addGroup(@NotNull UsageGroup group, int ruleIndex, @NotNull Consumer<Runnable> edtQueue) { synchronized (lock) { GroupNode node = mySubgroupNodes.get(group); if (node == null) { final GroupNode node1 = node = new GroupNode(group, ruleIndex, getBuilder()); mySubgroupNodes.put(group, node); addNode(node1, edtQueue); } return node; } } void addNode(@NotNull final DefaultMutableTreeNode node, @NotNull Consumer<Runnable> edtQueue) { if (!getBuilder().isDetachedMode()) { edtQueue.consume(new Runnable() { @Override public void run() { myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node)); } }); } } private UsageViewTreeModelBuilder getBuilder() { return (UsageViewTreeModelBuilder)myTreeModel; } @Override public void removeAllChildren() { synchronized (lock) { ApplicationManager.getApplication().assertIsDispatchThread(); super.removeAllChildren(); mySubgroupNodes.clear(); myRecursiveUsageCount = 0; myUsageNodes.clear(); } myTreeModel.reload(this); } @Nullable UsageNode tryMerge(@NotNull Usage usage) { if (!(usage instanceof MergeableUsage)) return null; MergeableUsage mergeableUsage = (MergeableUsage)usage; for (UsageNode node : myUsageNodes) { Usage original = node.getUsage(); if (original == mergeableUsage) { // search returned duplicate usage, ignore return node; } if (original instanceof MergeableUsage) { if (((MergeableUsage)original).merge(mergeableUsage)) return node; } } return null; } public boolean removeUsage(@NotNull UsageNode usage) { ApplicationManager.getApplication().assertIsDispatchThread(); final Collection<GroupNode> groupNodes = mySubgroupNodes.values(); for(Iterator<GroupNode> iterator = groupNodes.iterator();iterator.hasNext();) { final GroupNode groupNode = iterator.next(); if(groupNode.removeUsage(usage)) { doUpdate(); if (groupNode.getRecursiveUsageCount() == 0) { myTreeModel.removeNodeFromParent(groupNode); iterator.remove(); } return true; } } boolean removed; synchronized (lock) { removed = myUsageNodes.remove(usage); } if (removed) { doUpdate(); return true; } return false; } public boolean removeUsagesBulk(@NotNull Set<UsageNode> usages) { boolean removed; synchronized (lock) { removed = myUsageNodes.removeAll(usages); } Collection<GroupNode> groupNodes = mySubgroupNodes.values(); for (Iterator<GroupNode> iterator = groupNodes.iterator(); iterator.hasNext(); ) { GroupNode groupNode = iterator.next(); if (groupNode.removeUsagesBulk(usages)) { if (groupNode.getRecursiveUsageCount() == 0) { MutableTreeNode parent = (MutableTreeNode)groupNode.getParent(); int childIndex = parent.getIndex(groupNode); if (childIndex != -1) { parent.remove(childIndex); } iterator.remove(); } removed = true; } } if (removed) { --myRecursiveUsageCount; } return removed; } private void doUpdate() { ApplicationManager.getApplication().assertIsDispatchThread(); --myRecursiveUsageCount; myTreeModel.nodeChanged(this); } public UsageNode addUsage(@NotNull Usage usage, @NotNull Consumer<Runnable> edtQueue) { final UsageNode node; synchronized (lock) { if (myUsageTreeModel.isFilterDuplicatedLine()) { UsageNode mergedWith = tryMerge(usage); if (mergedWith != null) { return mergedWith; } } node = new UsageNode(usage, getBuilder()); myUsageNodes.add(node); } if (!getBuilder().isDetachedMode()) { edtQueue.consume(new Runnable() { @Override public void run() { myTreeModel.insertNodeInto(node, GroupNode.this, getNodeIndex(node)); incrementUsageCount(); } }); } return node; } private int getNodeIndex(@NotNull UsageNode node) { int index = indexedBinarySearch(node); return index >= 0 ? index : -index-1; } private int indexedBinarySearch(@NotNull UsageNode key) { int low = 0; int high = getChildCount() - 1; while (low <= high) { int mid = (low + high) / 2; TreeNode treeNode = getChildAt(mid); int cmp; if (treeNode instanceof UsageNode) { UsageNode midVal = (UsageNode)treeNode; cmp = midVal.compareTo(key); } else { cmp = -1; } if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found } private void incrementUsageCount() { GroupNode groupNode = this; while (true) { groupNode.myRecursiveUsageCount++; final GroupNode node = groupNode; myTreeModel.nodeChanged(node); TreeNode parent = groupNode.getParent(); if (!(parent instanceof GroupNode)) return; groupNode = (GroupNode)parent; } } @Override public String tree2string(int indent, String lineSeparator) { StringBuffer result = new StringBuffer(); StringUtil.repeatSymbol(result, ' ', indent); if (myGroup != null) result.append(myGroup.toString()); result.append("["); result.append(lineSeparator); Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Node node = (Node)enumeration.nextElement(); result.append(node.tree2string(indent + 4, lineSeparator)); result.append(lineSeparator); } StringUtil.repeatSymbol(result, ' ', indent); result.append("]"); result.append(lineSeparator); return result.toString(); } @Override protected boolean isDataValid() { return myGroup == null || myGroup.isValid(); } @Override protected boolean isDataReadOnly() { Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Object element = enumeration.nextElement(); if (element instanceof Node && ((Node)element).isReadOnly()) return true; } return false; } private int getNodeInsertionIndex(@NotNull DefaultMutableTreeNode node) { Enumeration children = children(); int idx = 0; while (children.hasMoreElements()) { DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement(); if (COMPARATOR.compare(child, node) >= 0) break; idx++; } return idx; } private static class NodeComparator implements Comparator<DefaultMutableTreeNode> { private static int getClassIndex(DefaultMutableTreeNode node) { if (node instanceof UsageNode) return 3; if (node instanceof GroupNode) return 2; if (node instanceof UsageTargetNode) return 1; return 0; } @Override public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) { int classIdx1 = getClassIndex(n1); int classIdx2 = getClassIndex(n2); if (classIdx1 != classIdx2) return classIdx1 - classIdx2; if (classIdx1 == 2) return ((GroupNode)n1).compareTo((GroupNode)n2); return 0; } } @Override public int compareTo(@NotNull GroupNode groupNode) { if (myRuleIndex == groupNode.myRuleIndex) { return myGroup.compareTo(groupNode.myGroup); } return myRuleIndex - groupNode.myRuleIndex; } public UsageGroup getGroup() { return myGroup; } public int getRecursiveUsageCount() { return myRecursiveUsageCount; } @Override public void navigate(boolean requestFocus) { if (myGroup != null) { myGroup.navigate(requestFocus); } } @Override public boolean canNavigate() { return myGroup != null && myGroup.canNavigate(); } @Override public boolean canNavigateToSource() { return myGroup != null && myGroup.canNavigateToSource(); } @Override protected boolean isDataExcluded() { Enumeration enumeration = children(); while (enumeration.hasMoreElements()) { Node node = (Node)enumeration.nextElement(); if (!node.isExcluded()) return false; } return true; } @Override protected String getText(@NotNull UsageView view) { return myGroup.getText(view); } @NotNull public Collection<GroupNode> getSubGroups() { return mySubgroupNodes.values(); } @NotNull public Collection<UsageNode> getUsageNodes() { return myUsageNodes; } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">akosyakov/intellij-community</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">platform/usageView/src/com/intellij/usages/impl/GroupNode.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">11,143</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086541"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package testclient import ( ktestclient "k8s.io/kubernetes/pkg/client/testclient" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/watch" templateapi "github.com/openshift/origin/pkg/template/api" ) // FakeTemplates implements TemplateInterface. Meant to be embedded into a struct to get a default // implementation. This makes faking out just the methods you want to test easier. type FakeTemplates struct { Fake *Fake Namespace string } func (c *FakeTemplates) Get(name string) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewGetAction("templates", c.Namespace, name), &templateapi.Template{}) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) List(label labels.Selector, field fields.Selector) (*templateapi.TemplateList, error) { obj, err := c.Fake.Invokes(ktestclient.NewListAction("templates", c.Namespace, label, field), &templateapi.TemplateList{}) if obj == nil { return nil, err } return obj.(*templateapi.TemplateList), err } func (c *FakeTemplates) Create(inObj *templateapi.Template) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewCreateAction("templates", c.Namespace, inObj), inObj) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) Update(inObj *templateapi.Template) (*templateapi.Template, error) { obj, err := c.Fake.Invokes(ktestclient.NewUpdateAction("templates", c.Namespace, inObj), inObj) if obj == nil { return nil, err } return obj.(*templateapi.Template), err } func (c *FakeTemplates) Delete(name string) error { _, err := c.Fake.Invokes(ktestclient.NewDeleteAction("templates", c.Namespace, name), &templateapi.Template{}) return err } func (c *FakeTemplates) Watch(label labels.Selector, field fields.Selector, resourceVersion string) (watch.Interface, error) { c.Fake.Invokes(ktestclient.NewWatchAction("templates", c.Namespace, label, field, resourceVersion), nil) return c.Fake.Watch, nil } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">domenicbove/origin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">pkg/client/testclient/fake_templates.go</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">GO</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,068</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086542"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package im.actor.model.api.rpc; /* * Generated by the Actor API Scheme generator. DO NOT EDIT! */ import im.actor.model.droidkit.bser.Bser; import im.actor.model.droidkit.bser.BserParser; import im.actor.model.droidkit.bser.BserObject; import im.actor.model.droidkit.bser.BserValues; import im.actor.model.droidkit.bser.BserWriter; import im.actor.model.droidkit.bser.DataInput; import im.actor.model.droidkit.bser.DataOutput; import im.actor.model.droidkit.bser.util.SparseArray; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.NotNull; import com.google.j2objc.annotations.ObjectiveCName; import static im.actor.model.droidkit.bser.Utils.*; import java.io.IOException; import im.actor.model.network.parser.*; import java.util.List; import java.util.ArrayList; import im.actor.model.api.*; public class RequestSendMessage extends Request<ResponseSeqDate> { public static final int HEADER = 0x5c; public static RequestSendMessage fromBytes(byte[] data) throws IOException { return Bser.parse(new RequestSendMessage(), data); } private OutPeer peer; private long rid; private Message message; public RequestSendMessage(@NotNull OutPeer peer, long rid, @NotNull Message message) { this.peer = peer; this.rid = rid; this.message = message; } public RequestSendMessage() { } @NotNull public OutPeer getPeer() { return this.peer; } public long getRid() { return this.rid; } @NotNull public Message getMessage() { return this.message; } @Override public void parse(BserValues values) throws IOException { this.peer = values.getObj(1, new OutPeer()); this.rid = values.getLong(3); this.message = Message.fromBytes(values.getBytes(4)); } @Override public void serialize(BserWriter writer) throws IOException { if (this.peer == null) { throw new IOException(); } writer.writeObject(1, this.peer); writer.writeLong(3, this.rid); if (this.message == null) { throw new IOException(); } writer.writeBytes(4, this.message.buildContainer()); } @Override public String toString() { String res = "rpc SendMessage{"; res += "peer=" + this.peer; res += ", rid=" + this.rid; res += ", message=" + this.message; res += "}"; return res; } @Override public int getHeaderKey() { return HEADER; } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Rogerlin2013/actor-platform</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">actor-apps/core/src/main/java/im/actor/model/api/rpc/RequestSendMessage.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,557</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086543"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">require "spec_helper" describe Mongoid::Relations::Referenced::In do let(:person) do Person.create end describe "#=" do context "when the relation is named target" do let(:target) do User.new end context "when the relation is referenced from an embeds many" do context "when setting via create" do let(:service) do person.services.create(target: target) end it "sets the target relation" do service.target.should eq(target) end end end end context "when the inverse relation has no reference defined" do let(:agent) do Agent.new(title: "007") end let(:game) do Game.new(name: "Donkey Kong") end before do agent.game = game end it "sets the relation" do agent.game.should eq(game) end it "sets the foreign_key" do agent.game_id.should eq(game.id) end end context "when referencing a document from an embedded document" do let(:person) do Person.create end let(:address) do person.addresses.create(street: "Wienerstr") end let(:account) do Account.create(name: "1", number: 1000000) end before do address.account = account end it "sets the relation" do address.account.should eq(account) end it "does not erase the metadata" do address.metadata.should_not be_nil end it "allows saving of the embedded document" do address.save.should be_true end end context "when the parent is a references one" do context "when the relation is not polymorphic" do context "when the child is a new record" do let(:person) do Person.new end let(:game) do Game.new end before do game.person = person end it "sets the target of the relation" do game.person.target.should eq(person) end it "sets the foreign key on the relation" do game.person_id.should eq(person.id) end it "sets the base on the inverse relation" do person.game.should eq(game) end it "sets the same instance on the inverse relation" do person.game.should eql(game) end it "does not save the target" do person.should_not be_persisted end end context "when the child is not a new record" do let(:person) do Person.new end let(:game) do Game.create end before do game.person = person end it "sets the target of the relation" do game.person.target.should eq(person) end it "sets the foreign key of the relation" do game.person_id.should eq(person.id) end it "sets the base on the inverse relation" do person.game.should eq(game) end it "sets the same instance on the inverse relation" do person.game.should eql(game) end it "does not saves the target" do person.should_not be_persisted end end end context "when the relation is not polymorphic" do context "when the child is a new record" do let(:bar) do Bar.new end let(:rating) do Rating.new end before do rating.ratable = bar end it "sets the target of the relation" do rating.ratable.target.should eq(bar) end it "sets the foreign key on the relation" do rating.ratable_id.should eq(bar.id) end it "sets the base on the inverse relation" do bar.rating.should eq(rating) end it "sets the same instance on the inverse relation" do bar.rating.should eql(rating) end it "does not save the target" do bar.should_not be_persisted end end context "when the child is not a new record" do let(:bar) do Bar.new end let(:rating) do Rating.create end before do rating.ratable = bar end it "sets the target of the relation" do rating.ratable.target.should eq(bar) end it "sets the foreign key of the relation" do rating.ratable_id.should eq(bar.id) end it "sets the base on the inverse relation" do bar.rating.should eq(rating) end it "sets the same instance on the inverse relation" do bar.rating.should eql(rating) end it "does not saves the target" do bar.should_not be_persisted end end end end context "when the parent is a references many" do context "when the relation is not polymorphic" do context "when the child is a new record" do let(:person) do Person.new end let(:post) do Post.new end before do post.person = person end it "sets the target of the relation" do post.person.target.should eq(person) end it "sets the foreign key on the relation" do post.person_id.should eq(person.id) end it "does not save the target" do person.should_not be_persisted end end context "when the child is not a new record" do let(:person) do Person.new end let(:post) do Post.create end before do post.person = person end it "sets the target of the relation" do post.person.target.should eq(person) end it "sets the foreign key of the relation" do post.person_id.should eq(person.id) end it "does not saves the target" do person.should_not be_persisted end end end context "when the relation is polymorphic" do context "when multiple relations against the same class exist" do let(:face) do Face.new end let(:eye) do Eye.new end it "raises an error" do expect { eye.eyeable = face }.to raise_error(Mongoid::Errors::InvalidSetPolymorphicRelation) end end context "when one relation against the same class exists" do context "when the child is a new record" do let(:movie) do Movie.new end let(:rating) do Rating.new end before do rating.ratable = movie end it "sets the target of the relation" do rating.ratable.target.should eq(movie) end it "sets the foreign key on the relation" do rating.ratable_id.should eq(movie.id) end it "does not save the target" do movie.should_not be_persisted end end context "when the child is not a new record" do let(:movie) do Movie.new end let(:rating) do Rating.create end before do rating.ratable = movie end it "sets the target of the relation" do rating.ratable.target.should eq(movie) end it "sets the foreign key of the relation" do rating.ratable_id.should eq(movie.id) end it "does not saves the target" do movie.should_not be_persisted end end end end end end describe "#= nil" do context "when dependent is destroy" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :destroy Person.has_one :account person.account = account person.save end after :all do Account.belongs_to :person, dependent: :nullify Person.has_one :account, validate: false end context "when parent exists" do context "when child is destroyed" do before do account.delete end it "deletes child" do account.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :destroy Person.has_many :drugs person.drugs = [drug] person.save end after :all do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs, validate: false end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end end context "when dependent is delete" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :delete Person.has_one :account person.account = account person.save end after :all do Account.belongs_to :person, dependent: :nullify Person.has_one :account, validate: false end context "when parent is persisted" do context "when child is deleted" do before do account.delete end it "deletes child" do account.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :delete Person.has_many :drugs person.drugs = [drug] person.save end after :all do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs, validate: false end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "deletes parent" do person.should be_destroyed end end end end end context "when dependent is nullify" do let(:account) do Account.create end let(:drug) do Drug.create end let(:person) do Person.create end context "when relation is has_one" do before do Account.belongs_to :person, dependent: :nullify Person.has_one :account person.account = account person.save end context "when parent is persisted" do context "when child is deleted" do before do account.delete end it "deletes child" do account.should be_destroyed end it "doesn't delete parent" do person.should_not be_destroyed end it "removes the link" do person.account.should be_nil end end end end context "when relation is has_many" do before do Drug.belongs_to :person, dependent: :nullify Person.has_many :drugs person.drugs = [drug] person.save end context "when parent exists" do context "when child is destroyed" do before do drug.delete end it "deletes child" do drug.should be_destroyed end it "doesn't deletes parent" do person.should_not be_destroyed end it "removes the link" do person.drugs.should eq([]) end end end end end context "when the inverse relation has no reference defined" do let(:agent) do Agent.new(title: "007") end let(:game) do Game.new(name: "Donkey Kong") end before do agent.game = game agent.game = nil end it "removes the relation" do agent.game.should be_nil end it "removes the foreign_key" do agent.game_id.should be_nil end end context "when the parent is a references one" do context "when the relation is not polymorphic" do context "when the parent is a new record" do let(:person) do Person.new end let(:game) do Game.new end before do game.person = person game.person = nil end it "sets the relation to nil" do game.person.should be_nil end it "removed the inverse relation" do person.game.should be_nil end it "removes the foreign key value" do game.person_id.should be_nil end end context "when the parent is not a new record" do let(:person) do Person.create end let(:game) do Game.create end before do game.person = person game.person = nil end it "sets the relation to nil" do game.person.should be_nil end it "removed the inverse relation" do person.game.should be_nil end it "removes the foreign key value" do game.person_id.should be_nil end it "does not delete the child" do game.should_not be_destroyed end end end context "when the relation is polymorphic" do context "when multiple relations against the same class exist" do context "when the parent is a new record" do let(:face) do Face.new end let(:eye) do Eye.new end before do face.left_eye = eye eye.eyeable = nil end it "sets the relation to nil" do eye.eyeable.should be_nil end it "removed the inverse relation" do face.left_eye.should be_nil end it "removes the foreign key value" do eye.eyeable_id.should be_nil end end context "when the parent is not a new record" do let(:face) do Face.new end let(:eye) do Eye.create end before do face.left_eye = eye eye.eyeable = nil end it "sets the relation to nil" do eye.eyeable.should be_nil end it "removed the inverse relation" do face.left_eye.should be_nil end it "removes the foreign key value" do eye.eyeable_id.should be_nil end end end context "when one relation against the same class exists" do context "when the parent is a new record" do let(:bar) do Bar.new end let(:rating) do Rating.new end before do rating.ratable = bar rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do bar.rating.should be_nil end it "removes the foreign key value" do rating.ratable_id.should be_nil end end context "when the parent is not a new record" do let(:bar) do Bar.new end let(:rating) do Rating.create end before do rating.ratable = bar rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do bar.rating.should be_nil end it "removes the foreign key value" do rating.ratable_id.should be_nil end end end end end context "when the parent is a references many" do context "when the relation is not polymorphic" do context "when the parent is a new record" do let(:person) do Person.new end let(:post) do Post.new end before do post.person = person post.person = nil end it "sets the relation to nil" do post.person.should be_nil end it "removed the inverse relation" do person.posts.should be_empty end it "removes the foreign key value" do post.person_id.should be_nil end end context "when the parent is not a new record" do let(:person) do Person.new end let(:post) do Post.create end before do post.person = person post.person = nil end it "sets the relation to nil" do post.person.should be_nil end it "removed the inverse relation" do person.posts.should be_empty end it "removes the foreign key value" do post.person_id.should be_nil end end end context "when the relation is polymorphic" do context "when the parent is a new record" do let(:movie) do Movie.new end let(:rating) do Rating.new end before do rating.ratable = movie rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do movie.ratings.should be_empty end it "removes the foreign key value" do rating.ratable_id.should be_nil end end context "when the parent is not a new record" do let(:movie) do Movie.new end let(:rating) do Rating.create end before do rating.ratable = movie rating.ratable = nil end it "sets the relation to nil" do rating.ratable.should be_nil end it "removed the inverse relation" do movie.ratings.should be_empty end it "removes the foreign key value" do rating.ratable_id.should be_nil end end end end end describe ".builder" do let(:builder_klass) do Mongoid::Relations::Builders::Referenced::In end let(:document) do stub end let(:metadata) do stub(extension?: false) end it "returns the embedded in builder" do described_class.builder(nil, metadata, document).should be_a_kind_of(builder_klass) end end describe ".eager_load" do before do Mongoid.identity_map_enabled = true end after do Mongoid.identity_map_enabled = false end context "when the relation is not polymorphic" do let!(:person) do Person.create end let!(:post) do person.posts.create(title: "testing") end let(:metadata) do Post.relations["person"] end let(:eager) do described_class.eager_load(metadata, Post.all) end let!(:map) do Mongoid::IdentityMap.get(Person, person.id) end it "puts the document in the identity map" do map.should eq(person) end end context "when the relation is polymorphic" do let(:metadata) do Rating.relations["ratable"] end it "raises an error" do expect { described_class.eager_load(metadata, Rating.all) }.to raise_error(Mongoid::Errors::EagerLoad) end end context "when the ids has been duplicated" do let!(:person) do Person.create end let!(:posts) do 2.times {|i| person.posts.create(title: "testing#{i}") } person.posts end let(:metadata) do Post.relations["person"] end let(:eager) do described_class.eager_load(metadata, posts.map(&:person_id)) end it "duplication should be removed" do eager.count.should eq(1) end end end describe ".embedded?" do it "returns false" do described_class.should_not be_embedded end end describe ".foreign_key_suffix" do it "returns _id" do described_class.foreign_key_suffix.should eq("_id") end end describe ".macro" do it "returns belongs_to" do described_class.macro.should eq(:belongs_to) end end describe "#respond_to?" do let(:person) do Person.new end let(:game) do person.build_game(name: "Tron") end let(:document) do game.person end Mongoid::Document.public_instance_methods(true).each do |method| context "when checking #{method}" do it "returns true" do document.respond_to?(method).should be_true end end end end describe ".stores_foreign_key?" do it "returns true" do described_class.stores_foreign_key?.should be_true end end describe ".valid_options" do it "returns the valid options" do described_class.valid_options.should eq( [ :autobuild, :autosave, :dependent, :foreign_key, :index, :polymorphic, :touch ] ) end end describe ".validation_default" do it "returns false" do described_class.validation_default.should be_false end end context "when the relation is self referencing" do let(:game_one) do Game.new(name: "Diablo") end let(:game_two) do Game.new(name: "Warcraft") end context "when setting the parent" do before do game_one.parent = game_two end it "sets the parent" do game_one.parent.should eq(game_two) end it "does not set the parent recursively" do game_two.parent.should be_nil end end end context "when the relation belongs to a has many and has one" do before(:all) do class A include Mongoid::Document has_many :bs, inverse_of: :a end class B include Mongoid::Document belongs_to :a, inverse_of: :bs belongs_to :c, inverse_of: :b end class C include Mongoid::Document has_one :b, inverse_of: :c end end after(:all) do Object.send(:remove_const, :A) Object.send(:remove_const, :B) Object.send(:remove_const, :C) end context "when setting the has one" do let(:a) do A.new end let(:b) do B.new end let(:c) do C.new end before do b.c = c end context "when subsequently setting the has many" do before do b.a = a end context "when setting the has one again" do before do b.c = c end it "allows the reset of the has one" do b.c.should eq(c) end end end end end context "when replacing the relation with another" do let!(:person) do Person.create end let!(:post) do Post.create(title: "test") end let!(:game) do person.create_game(name: "Tron") end before do post.person = game.person post.save end it "clones the relation" do post.person.should eq(person) end it "sets the foreign key" do post.person_id.should eq(person.id) end it "does not remove the previous relation" do game.person.should eq(person) end it "does not remove the previous foreign key" do game.person_id.should eq(person.id) end context "when reloading" do before do post.reload game.reload end it "persists the relation" do post.reload.person.should eq(person) end it "persists the foreign key" do post.reload.person_id.should eq(game.person_id) end it "does not remove the previous relation" do game.person.should eq(person) end it "does not remove the previous foreign key" do game.person_id.should eq(person.id) end end end context "when the document belongs to a has one and has many" do let(:movie) do Movie.create(name: "Infernal Affairs") end let(:account) do Account.create(name: "Leung") end context "when creating the document" do let(:comment) do Comment.create(movie: movie, account: account) end it "sets the correct has one" do comment.account.should eq(account) end it "sets the correct has many" do comment.movie.should eq(movie) end end end context "when reloading the relation" do let!(:person_one) do Person.create end let!(:person_two) do Person.create(title: "Sir") end let!(:game) do Game.create(name: "Starcraft 2") end before do game.person = person_one game.save end context "when the relation references the same document" do before do Person.collection.find({ _id: person_one.id }). update({ "$set" => { title: "Madam" }}) end let(:reloaded) do game.person(true) end it "reloads the document from the database" do reloaded.title.should eq("Madam") end it "sets a new document instance" do reloaded.should_not equal(person_one) end end context "when the relation references a different document" do before do game.person_id = person_two.id game.save end let(:reloaded) do game.person(true) end it "reloads the new document from the database" do reloaded.title.should eq("Sir") end it "sets a new document instance" do reloaded.should_not equal(person_one) end end end context "when the parent and child are persisted" do context "when the identity map is enabled" do before do Mongoid.identity_map_enabled = true end after do Mongoid.identity_map_enabled = false end let(:series) do Series.create end let!(:book_one) do series.books.create end let!(:book_two) do series.books.create end let(:id) do Book.first.id end context "when asking for the inverse multiple times" do before do Book.find(id).series.books.to_a end it "does not append and save duplicate docs" do Book.find(id).series.books.to_a.length.should eq(2) end it "returns the same documents from the map" do Book.find(id).should equal(Book.find(id)) end end end end context "when creating with a reference to an integer id parent" do let!(:jar) do Jar.create do |doc| doc._id = 1 end end let(:cookie) do Cookie.create(jar_id: "1") end it "allows strings to be passed as the id" do cookie.jar.should eq(jar) end it "persists the relation" do cookie.reload.jar.should eq(jar) end end context "when setting the relation via the foreign key" do context "when the relation exists" do let!(:person_one) do Person.create end let!(:person_two) do Person.create end let!(:game) do Game.create(person: person_one) end before do game.person_id = person_two.id end it "sets the new document on the relation" do game.person.should eq(person_two) end end end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">peterwillcn/mongoid</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">spec/mongoid/relations/referenced/in_spec.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30,037</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086544"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// 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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { internal static class CertificateValidation { private static readonly IdnMapping s_idnMapping = new IdnMapping(); internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : SslPolicyErrors.RemoteCertificateChainErrors; if (!checkCertName) { return errors; } if (string.IsNullOrEmpty(hostName)) { return errors | SslPolicyErrors.RemoteCertificateNameMismatch; } int hostNameMatch; using (SafeX509Handle certHandle = Interop.Crypto.X509UpRef(remoteCertificate.Handle)) { IPAddress hostnameAsIp; if (IPAddress.TryParse(hostName, out hostnameAsIp)) { byte[] addressBytes = hostnameAsIp.GetAddressBytes(); hostNameMatch = Interop.Crypto.CheckX509IpAddress(certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length); } else { // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" string matchName = s_idnMapping.GetAscii(hostName); hostNameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length); } } Debug.Assert(hostNameMatch == 0 || hostNameMatch == 1, $"Expected 0 or 1 from CheckX509Hostname, got {hostNameMatch}"); return hostNameMatch == 1 ? errors : errors | SslPolicyErrors.RemoteCertificateNameMismatch; } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ptoonen/corefx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/Common/src/System/Net/Security/CertificateValidation.Unix.cs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C#</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,411</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086545"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2013-2015 Analog Devices Inc. * Author: Lars-Peter Clausen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54383526271439312035323b3b7a3031">[email protected]</a>> */ #include <linux/slab.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/device.h> #include <linux/workqueue.h> #include <linux/mutex.h> #include <linux/sched.h> #include <linux/poll.h> #include <linux/iio/buffer.h> #include <linux/iio/buffer_impl.h> #include <linux/iio/buffer-dma.h> #include <linux/dma-mapping.h> #include <linux/sizes.h> /* * For DMA buffers the storage is sub-divided into so called blocks. Each block * has its own memory buffer. The size of the block is the granularity at which * memory is exchanged between the hardware and the application. Increasing the * basic unit of data exchange from one sample to one block decreases the * management overhead that is associated with each sample. E.g. if we say the * management overhead for one exchange is x and the unit of exchange is one * sample the overhead will be x for each sample. Whereas when using a block * which contains n samples the overhead per sample is reduced to x/n. This * allows to achieve much higher samplerates than what can be sustained with * the one sample approach. * * Blocks are exchanged between the DMA controller and the application via the * means of two queues. The incoming queue and the outgoing queue. Blocks on the * incoming queue are waiting for the DMA controller to pick them up and fill * them with data. Block on the outgoing queue have been filled with data and * are waiting for the application to dequeue them and read the data. * * A block can be in one of the following states: * * Owned by the application. In this state the application can read data from * the block. * * On the incoming list: Blocks on the incoming list are queued up to be * processed by the DMA controller. * * Owned by the DMA controller: The DMA controller is processing the block * and filling it with data. * * On the outgoing list: Blocks on the outgoing list have been successfully * processed by the DMA controller and contain data. They can be dequeued by * the application. * * Dead: A block that is dead has been marked as to be freed. It might still * be owned by either the application or the DMA controller at the moment. * But once they are done processing it instead of going to either the * incoming or outgoing queue the block will be freed. * * In addition to this blocks are reference counted and the memory associated * with both the block structure as well as the storage memory for the block * will be freed when the last reference to the block is dropped. This means a * block must not be accessed without holding a reference. * * The iio_dma_buffer implementation provides a generic infrastructure for * managing the blocks. * * A driver for a specific piece of hardware that has DMA capabilities need to * implement the submit() callback from the iio_dma_buffer_ops structure. This * callback is supposed to initiate the DMA transfer copying data from the * converter to the memory region of the block. Once the DMA transfer has been * completed the driver must call iio_dma_buffer_block_done() for the completed * block. * * Prior to this it must set the bytes_used field of the block contains * the actual number of bytes in the buffer. Typically this will be equal to the * size of the block, but if the DMA hardware has certain alignment requirements * for the transfer length it might choose to use less than the full size. In * either case it is expected that bytes_used is a multiple of the bytes per * datum, i.e. the block must not contain partial samples. * * The driver must call iio_dma_buffer_block_done() for each block it has * received through its submit_block() callback, even if it does not actually * perform a DMA transfer for the block, e.g. because the buffer was disabled * before the block transfer was started. In this case it should set bytes_used * to 0. * * In addition it is recommended that a driver implements the abort() callback. * It will be called when the buffer is disabled and can be used to cancel * pending and stop active transfers. * * The specific driver implementation should use the default callback * implementations provided by this module for the iio_buffer_access_funcs * struct. It may overload some callbacks with custom variants if the hardware * has special requirements that are not handled by the generic functions. If a * driver chooses to overload a callback it has to ensure that the generic * callback is called from within the custom callback. */ static void iio_buffer_block_release(struct kref *kref) { struct iio_dma_buffer_block *block = container_of(kref, struct iio_dma_buffer_block, kref); WARN_ON(block->state != IIO_BLOCK_STATE_DEAD); dma_free_coherent(block->queue->dev, PAGE_ALIGN(block->size), block->vaddr, block->phys_addr); iio_buffer_put(&block->queue->buffer); kfree(block); } static void iio_buffer_block_get(struct iio_dma_buffer_block *block) { kref_get(&block->kref); } static void iio_buffer_block_put(struct iio_dma_buffer_block *block) { kref_put(&block->kref, iio_buffer_block_release); } /* * dma_free_coherent can sleep, hence we need to take some special care to be * able to drop a reference from an atomic context. */ static LIST_HEAD(iio_dma_buffer_dead_blocks); static DEFINE_SPINLOCK(iio_dma_buffer_dead_blocks_lock); static void iio_dma_buffer_cleanup_worker(struct work_struct *work) { struct iio_dma_buffer_block *block, *_block; LIST_HEAD(block_list); spin_lock_irq(&iio_dma_buffer_dead_blocks_lock); list_splice_tail_init(&iio_dma_buffer_dead_blocks, &block_list); spin_unlock_irq(&iio_dma_buffer_dead_blocks_lock); list_for_each_entry_safe(block, _block, &block_list, head) iio_buffer_block_release(&block->kref); } static DECLARE_WORK(iio_dma_buffer_cleanup_work, iio_dma_buffer_cleanup_worker); static void iio_buffer_block_release_atomic(struct kref *kref) { struct iio_dma_buffer_block *block; unsigned long flags; block = container_of(kref, struct iio_dma_buffer_block, kref); spin_lock_irqsave(&iio_dma_buffer_dead_blocks_lock, flags); list_add_tail(&block->head, &iio_dma_buffer_dead_blocks); spin_unlock_irqrestore(&iio_dma_buffer_dead_blocks_lock, flags); schedule_work(&iio_dma_buffer_cleanup_work); } /* * Version of iio_buffer_block_put() that can be called from atomic context */ static void iio_buffer_block_put_atomic(struct iio_dma_buffer_block *block) { kref_put(&block->kref, iio_buffer_block_release_atomic); } static struct iio_dma_buffer_queue *iio_buffer_to_queue(struct iio_buffer *buf) { return container_of(buf, struct iio_dma_buffer_queue, buffer); } static struct iio_dma_buffer_block *iio_dma_buffer_alloc_block( struct iio_dma_buffer_queue *queue, size_t size) { struct iio_dma_buffer_block *block; block = kzalloc(sizeof(*block), GFP_KERNEL); if (!block) return NULL; block->vaddr = dma_alloc_coherent(queue->dev, PAGE_ALIGN(size), &block->phys_addr, GFP_KERNEL); if (!block->vaddr) { kfree(block); return NULL; } block->size = size; block->state = IIO_BLOCK_STATE_DEQUEUED; block->queue = queue; INIT_LIST_HEAD(&block->head); kref_init(&block->kref); iio_buffer_get(&queue->buffer); return block; } static void _iio_dma_buffer_block_done(struct iio_dma_buffer_block *block) { struct iio_dma_buffer_queue *queue = block->queue; /* * The buffer has already been freed by the application, just drop the * reference. */ if (block->state != IIO_BLOCK_STATE_DEAD) { block->state = IIO_BLOCK_STATE_DONE; list_add_tail(&block->head, &queue->outgoing); } } /** * iio_dma_buffer_block_done() - Indicate that a block has been completed * @block: The completed block * * Should be called when the DMA controller has finished handling the block to * pass back ownership of the block to the queue. */ void iio_dma_buffer_block_done(struct iio_dma_buffer_block *block) { struct iio_dma_buffer_queue *queue = block->queue; unsigned long flags; spin_lock_irqsave(&queue->list_lock, flags); _iio_dma_buffer_block_done(block); spin_unlock_irqrestore(&queue->list_lock, flags); iio_buffer_block_put_atomic(block); wake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM); } EXPORT_SYMBOL_GPL(iio_dma_buffer_block_done); /** * iio_dma_buffer_block_list_abort() - Indicate that a list block has been * aborted * @queue: Queue for which to complete blocks. * @list: List of aborted blocks. All blocks in this list must be from @queue. * * Typically called from the abort() callback after the DMA controller has been * stopped. This will set bytes_used to 0 for each block in the list and then * hand the blocks back to the queue. */ void iio_dma_buffer_block_list_abort(struct iio_dma_buffer_queue *queue, struct list_head *list) { struct iio_dma_buffer_block *block, *_block; unsigned long flags; spin_lock_irqsave(&queue->list_lock, flags); list_for_each_entry_safe(block, _block, list, head) { list_del(&block->head); block->bytes_used = 0; _iio_dma_buffer_block_done(block); iio_buffer_block_put_atomic(block); } spin_unlock_irqrestore(&queue->list_lock, flags); wake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM); } EXPORT_SYMBOL_GPL(iio_dma_buffer_block_list_abort); static bool iio_dma_block_reusable(struct iio_dma_buffer_block *block) { /* * If the core owns the block it can be re-used. This should be the * default case when enabling the buffer, unless the DMA controller does * not support abort and has not given back the block yet. */ switch (block->state) { case IIO_BLOCK_STATE_DEQUEUED: case IIO_BLOCK_STATE_QUEUED: case IIO_BLOCK_STATE_DONE: return true; default: return false; } } /** * iio_dma_buffer_request_update() - DMA buffer request_update callback * @buffer: The buffer which to request an update * * Should be used as the iio_dma_buffer_request_update() callback for * iio_buffer_access_ops struct for DMA buffers. */ int iio_dma_buffer_request_update(struct iio_buffer *buffer) { struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer); struct iio_dma_buffer_block *block; bool try_reuse = false; size_t size; int ret = 0; int i; /* * Split the buffer into two even parts. This is used as a double * buffering scheme with usually one block at a time being used by the * DMA and the other one by the application. */ size = DIV_ROUND_UP(queue->buffer.bytes_per_datum * queue->buffer.length, 2); mutex_lock(&queue->lock); /* Allocations are page aligned */ if (PAGE_ALIGN(queue->fileio.block_size) == PAGE_ALIGN(size)) try_reuse = true; queue->fileio.block_size = size; queue->fileio.active_block = NULL; spin_lock_irq(&queue->list_lock); for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) { block = queue->fileio.blocks[i]; /* If we can't re-use it free it */ if (block && (!iio_dma_block_reusable(block) || !try_reuse)) block->state = IIO_BLOCK_STATE_DEAD; } /* * At this point all blocks are either owned by the core or marked as * dead. This means we can reset the lists without having to fear * corrution. */ INIT_LIST_HEAD(&queue->outgoing); spin_unlock_irq(&queue->list_lock); INIT_LIST_HEAD(&queue->incoming); for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) { if (queue->fileio.blocks[i]) { block = queue->fileio.blocks[i]; if (block->state == IIO_BLOCK_STATE_DEAD) { /* Could not reuse it */ iio_buffer_block_put(block); block = NULL; } else { block->size = size; } } else { block = NULL; } if (!block) { block = iio_dma_buffer_alloc_block(queue, size); if (!block) { ret = -ENOMEM; goto out_unlock; } queue->fileio.blocks[i] = block; } block->state = IIO_BLOCK_STATE_QUEUED; list_add_tail(&block->head, &queue->incoming); } out_unlock: mutex_unlock(&queue->lock); return ret; } EXPORT_SYMBOL_GPL(iio_dma_buffer_request_update); static void iio_dma_buffer_submit_block(struct iio_dma_buffer_queue *queue, struct iio_dma_buffer_block *block) { int ret; /* * If the hardware has already been removed we put the block into * limbo. It will neither be on the incoming nor outgoing list, nor will * it ever complete. It will just wait to be freed eventually. */ if (!queue->ops) return; block->state = IIO_BLOCK_STATE_ACTIVE; iio_buffer_block_get(block); ret = queue->ops->submit(queue, block); if (ret) { /* * This is a bit of a problem and there is not much we can do * other then wait for the buffer to be disabled and re-enabled * and try again. But it should not really happen unless we run * out of memory or something similar. * * TODO: Implement support in the IIO core to allow buffers to * notify consumers that something went wrong and the buffer * should be disabled. */ iio_buffer_block_put(block); } } /** * iio_dma_buffer_enable() - Enable DMA buffer * @buffer: IIO buffer to enable * @indio_dev: IIO device the buffer is attached to * * Needs to be called when the device that the buffer is attached to starts * sampling. Typically should be the iio_buffer_access_ops enable callback. * * This will allocate the DMA buffers and start the DMA transfers. */ int iio_dma_buffer_enable(struct iio_buffer *buffer, struct iio_dev *indio_dev) { struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer); struct iio_dma_buffer_block *block, *_block; mutex_lock(&queue->lock); queue->active = true; list_for_each_entry_safe(block, _block, &queue->incoming, head) { list_del(&block->head); iio_dma_buffer_submit_block(queue, block); } mutex_unlock(&queue->lock); return 0; } EXPORT_SYMBOL_GPL(iio_dma_buffer_enable); /** * iio_dma_buffer_disable() - Disable DMA buffer * @buffer: IIO DMA buffer to disable * @indio_dev: IIO device the buffer is attached to * * Needs to be called when the device that the buffer is attached to stops * sampling. Typically should be the iio_buffer_access_ops disable callback. */ int iio_dma_buffer_disable(struct iio_buffer *buffer, struct iio_dev *indio_dev) { struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer); mutex_lock(&queue->lock); queue->active = false; if (queue->ops && queue->ops->abort) queue->ops->abort(queue); mutex_unlock(&queue->lock); return 0; } EXPORT_SYMBOL_GPL(iio_dma_buffer_disable); static void iio_dma_buffer_enqueue(struct iio_dma_buffer_queue *queue, struct iio_dma_buffer_block *block) { if (block->state == IIO_BLOCK_STATE_DEAD) { iio_buffer_block_put(block); } else if (queue->active) { iio_dma_buffer_submit_block(queue, block); } else { block->state = IIO_BLOCK_STATE_QUEUED; list_add_tail(&block->head, &queue->incoming); } } static struct iio_dma_buffer_block *iio_dma_buffer_dequeue( struct iio_dma_buffer_queue *queue) { struct iio_dma_buffer_block *block; spin_lock_irq(&queue->list_lock); block = list_first_entry_or_null(&queue->outgoing, struct iio_dma_buffer_block, head); if (block != NULL) { list_del(&block->head); block->state = IIO_BLOCK_STATE_DEQUEUED; } spin_unlock_irq(&queue->list_lock); return block; } /** * iio_dma_buffer_read() - DMA buffer read callback * @buffer: Buffer to read form * @n: Number of bytes to read * @user_buffer: Userspace buffer to copy the data to * * Should be used as the read callback for iio_buffer_access_ops * struct for DMA buffers. */ int iio_dma_buffer_read(struct iio_buffer *buffer, size_t n, char __user *user_buffer) { struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer); struct iio_dma_buffer_block *block; int ret; if (n < buffer->bytes_per_datum) return -EINVAL; mutex_lock(&queue->lock); if (!queue->fileio.active_block) { block = iio_dma_buffer_dequeue(queue); if (block == NULL) { ret = 0; goto out_unlock; } queue->fileio.pos = 0; queue->fileio.active_block = block; } else { block = queue->fileio.active_block; } n = rounddown(n, buffer->bytes_per_datum); if (n > block->bytes_used - queue->fileio.pos) n = block->bytes_used - queue->fileio.pos; if (copy_to_user(user_buffer, block->vaddr + queue->fileio.pos, n)) { ret = -EFAULT; goto out_unlock; } queue->fileio.pos += n; if (queue->fileio.pos == block->bytes_used) { queue->fileio.active_block = NULL; iio_dma_buffer_enqueue(queue, block); } ret = n; out_unlock: mutex_unlock(&queue->lock); return ret; } EXPORT_SYMBOL_GPL(iio_dma_buffer_read); /** * iio_dma_buffer_data_available() - DMA buffer data_available callback * @buf: Buffer to check for data availability * * Should be used as the data_available callback for iio_buffer_access_ops * struct for DMA buffers. */ size_t iio_dma_buffer_data_available(struct iio_buffer *buf) { struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buf); struct iio_dma_buffer_block *block; size_t data_available = 0; /* * For counting the available bytes we'll use the size of the block not * the number of actual bytes available in the block. Otherwise it is * possible that we end up with a value that is lower than the watermark * but won't increase since all blocks are in use. */ mutex_lock(&queue->lock); if (queue->fileio.active_block) data_available += queue->fileio.active_block->size; spin_lock_irq(&queue->list_lock); list_for_each_entry(block, &queue->outgoing, head) data_available += block->size; spin_unlock_irq(&queue->list_lock); mutex_unlock(&queue->lock); return data_available; } EXPORT_SYMBOL_GPL(iio_dma_buffer_data_available); /** * iio_dma_buffer_set_bytes_per_datum() - DMA buffer set_bytes_per_datum callback * @buffer: Buffer to set the bytes-per-datum for * @bpd: The new bytes-per-datum value * * Should be used as the set_bytes_per_datum callback for iio_buffer_access_ops * struct for DMA buffers. */ int iio_dma_buffer_set_bytes_per_datum(struct iio_buffer *buffer, size_t bpd) { buffer->bytes_per_datum = bpd; return 0; } EXPORT_SYMBOL_GPL(iio_dma_buffer_set_bytes_per_datum); /** * iio_dma_buffer_set_length - DMA buffer set_length callback * @buffer: Buffer to set the length for * @length: The new buffer length * * Should be used as the set_length callback for iio_buffer_access_ops * struct for DMA buffers. */ int iio_dma_buffer_set_length(struct iio_buffer *buffer, unsigned int length) { /* Avoid an invalid state */ if (length < 2) length = 2; buffer->length = length; buffer->watermark = length / 2; return 0; } EXPORT_SYMBOL_GPL(iio_dma_buffer_set_length); /** * iio_dma_buffer_init() - Initialize DMA buffer queue * @queue: Buffer to initialize * @dev: DMA device * @ops: DMA buffer queue callback operations * * The DMA device will be used by the queue to do DMA memory allocations. So it * should refer to the device that will perform the DMA to ensure that * allocations are done from a memory region that can be accessed by the device. */ int iio_dma_buffer_init(struct iio_dma_buffer_queue *queue, struct device *dev, const struct iio_dma_buffer_ops *ops) { iio_buffer_init(&queue->buffer); queue->buffer.length = PAGE_SIZE; queue->buffer.watermark = queue->buffer.length / 2; queue->dev = dev; queue->ops = ops; INIT_LIST_HEAD(&queue->incoming); INIT_LIST_HEAD(&queue->outgoing); mutex_init(&queue->lock); spin_lock_init(&queue->list_lock); return 0; } EXPORT_SYMBOL_GPL(iio_dma_buffer_init); /** * iio_dma_buffer_exit() - Cleanup DMA buffer queue * @queue: Buffer to cleanup * * After this function has completed it is safe to free any resources that are * associated with the buffer and are accessed inside the callback operations. */ void iio_dma_buffer_exit(struct iio_dma_buffer_queue *queue) { unsigned int i; mutex_lock(&queue->lock); spin_lock_irq(&queue->list_lock); for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) { if (!queue->fileio.blocks[i]) continue; queue->fileio.blocks[i]->state = IIO_BLOCK_STATE_DEAD; } INIT_LIST_HEAD(&queue->outgoing); spin_unlock_irq(&queue->list_lock); INIT_LIST_HEAD(&queue->incoming); for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) { if (!queue->fileio.blocks[i]) continue; iio_buffer_block_put(queue->fileio.blocks[i]); queue->fileio.blocks[i] = NULL; } queue->fileio.active_block = NULL; queue->ops = NULL; mutex_unlock(&queue->lock); } EXPORT_SYMBOL_GPL(iio_dma_buffer_exit); /** * iio_dma_buffer_release() - Release final buffer resources * @queue: Buffer to release * * Frees resources that can't yet be freed in iio_dma_buffer_exit(). Should be * called in the buffers release callback implementation right before freeing * the memory associated with the buffer. */ void iio_dma_buffer_release(struct iio_dma_buffer_queue *queue) { mutex_destroy(&queue->lock); } EXPORT_SYMBOL_GPL(iio_dma_buffer_release); MODULE_AUTHOR("Lars-Peter Clausen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74181506073419110015121b1b5a1011">[email protected]</a>>"); MODULE_DESCRIPTION("DMA buffer for the IIO framework"); MODULE_LICENSE("GPL v2"); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">c0d3z3r0/linux-rockchip</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/iio/buffer/industrialio-buffer-dma.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">21,128</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086546"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ #include "qisf_ns.h" /* * Tables for function q_gain2() * * g_pitch(Q14), g_code(Q11) * * pitch gain are ordered in table to reduce complexity * during quantization of gains. */ const int16 t_qua_gain6b[NB_QUA_GAIN6B*2] = { 1566, 1332, 1577, 3557, 3071, 6490, 4193, 10163, 4496, 2534, 5019, 4488, 5586, 15614, 5725, 1422, 6453, 580, 6724, 6831, 7657, 3527, 8072, 2099, 8232, 5319, 8827, 8775, 9740, 2868, 9856, 1465, 10087, 12488, 10241, 4453, 10859, 6618, 11321, 3587, 11417, 1800, 11643, 2428, 11718, 988, 12312, 5093, 12523, 8413, 12574, 26214, 12601, 3396, 13172, 1623, 13285, 2423, 13418, 6087, 13459, 12810, 13656, 3607, 14111, 4521, 14144, 1229, 14425, 1871, 14431, 7234, 14445, 2834, 14628, 10036, 14860, 17496, 15161, 3629, 15209, 5819, 15299, 2256, 15518, 4722, 15663, 1060, 15759, 7972, 15939, 11964, 16020, 2996, 16086, 1707, 16521, 4254, 16576, 6224, 16894, 2380, 16906, 681, 17213, 8406, 17610, 3418, 17895, 5269, 18168, 11748, 18230, 1575, 18607, 32767, 18728, 21684, 19137, 2543, 19422, 6577, 19446, 4097, 19450, 9056, 20371, 14885 }; const int16 t_qua_gain7b[NB_QUA_GAIN7B*2] = { 204, 441, 464, 1977, 869, 1077, 1072, 3062, 1281, 4759, 1647, 1539, 1845, 7020, 1853, 634, 1995, 2336, 2351, 15400, 2661, 1165, 2702, 3900, 2710, 10133, 3195, 1752, 3498, 2624, 3663, 849, 3984, 5697, 4214, 3399, 4415, 1304, 4695, 2056, 5376, 4558, 5386, 676, 5518, 23554, 5567, 7794, 5644, 3061, 5672, 1513, 5957, 2338, 6533, 1060, 6804, 5998, 6820, 1767, 6937, 3837, 7277, 414, 7305, 2665, 7466, 11304, 7942, 794, 8007, 1982, 8007, 1366, 8326, 3105, 8336, 4810, 8708, 7954, 8989, 2279, 9031, 1055, 9247, 3568, 9283, 1631, 9654, 6311, 9811, 2605, 10120, 683, 10143, 4179, 10245, 1946, 10335, 1218, 10468, 9960, 10651, 3000, 10951, 1530, 10969, 5290, 11203, 2305, 11325, 3562, 11771, 6754, 11839, 1849, 11941, 4495, 11954, 1298, 11975, 15223, 11977, 883, 11986, 2842, 12438, 2141, 12593, 3665, 12636, 8367, 12658, 1594, 12886, 2628, 12984, 4942, 13146, 1115, 13224, 524, 13341, 3163, 13399, 1923, 13549, 5961, 13606, 1401, 13655, 2399, 13782, 3909, 13868, 10923, 14226, 1723, 14232, 2939, 14278, 7528, 14439, 4598, 14451, 984, 14458, 2265, 14792, 1403, 14818, 3445, 14899, 5709, 15017, 15362, 15048, 1946, 15069, 2655, 15405, 9591, 15405, 4079, 15570, 7183, 15687, 2286, 15691, 1624, 15699, 3068, 15772, 5149, 15868, 1205, 15970, 696, 16249, 3584, 16338, 1917, 16424, 2560, 16483, 4438, 16529, 6410, 16620, 11966, 16839, 8780, 17030, 3050, 17033, 18325, 17092, 1568, 17123, 5197, 17351, 2113, 17374, 980, 17566, 26214, 17609, 3912, 17639, 32767, 18151, 7871, 18197, 2516, 18202, 5649, 18679, 3283, 18930, 1370, 19271, 13757, 19317, 4120, 19460, 1973, 19654, 10018, 19764, 6792, 19912, 5135, 20040, 2841, 21234, 19833 }; </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">raj-bhatia/grooveip-ios-public</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">submodules/externals/opencore-amr/opencore/codecs_v2/audio/gsm_amr/amr_wb/dec/src/q_gain2_tab.cpp</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C++</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,030</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086547"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// SPDX-License-Identifier: GPL-2.0-or-later /* * PowerPC version * Copyright (C) 1995-1996 Gary Thomas (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76111202361a1f18030e06061558190411">[email protected]</a>) * * Derived from "arch/i386/kernel/signal.c" * Copyright (C) 1991, 1992 Linus Torvalds * 1997-11-28 Modified for POSIX.1b signals by Richard Henderson */ #include <linux/sched.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/unistd.h> #include <linux/stddef.h> #include <linux/elf.h> #include <linux/ptrace.h> #include <linux/ratelimit.h> #include <linux/syscalls.h> #include <linux/pagemap.h> #include <asm/sigcontext.h> #include <asm/ucontext.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <asm/cacheflush.h> #include <asm/syscalls.h> #include <asm/vdso.h> #include <asm/switch_to.h> #include <asm/tm.h> #include <asm/asm-prototypes.h> #include "signal.h" #define GP_REGS_SIZE min(sizeof(elf_gregset_t), sizeof(struct pt_regs)) #define FP_REGS_SIZE sizeof(elf_fpregset_t) #define TRAMP_TRACEBACK 4 #define TRAMP_SIZE 7 /* * When we have signals to deliver, we set up on the user stack, * going down from the original stack pointer: * 1) a rt_sigframe struct which contains the ucontext * 2) a gap of __SIGNAL_FRAMESIZE bytes which acts as a dummy caller * frame for the signal handler. */ struct rt_sigframe { /* sys_rt_sigreturn requires the ucontext be the first field */ struct ucontext uc; #ifdef CONFIG_PPC_TRANSACTIONAL_MEM struct ucontext uc_transact; #endif unsigned long _unused[2]; unsigned int tramp[TRAMP_SIZE]; struct siginfo __user *pinfo; void __user *puc; struct siginfo info; /* New 64 bit little-endian ABI allows redzone of 512 bytes below sp */ char abigap[USER_REDZONE_SIZE]; } __attribute__ ((aligned (16))); /* * This computes a quad word aligned pointer inside the vmx_reserve array * element. For historical reasons sigcontext might not be quad word aligned, * but the location we write the VMX regs to must be. See the comment in * sigcontext for more detail. */ #ifdef CONFIG_ALTIVEC static elf_vrreg_t __user *sigcontext_vmx_regs(struct sigcontext __user *sc) { return (elf_vrreg_t __user *) (((unsigned long)sc->vmx_reserve + 15) & ~0xful); } #endif static void prepare_setup_sigcontext(struct task_struct *tsk) { #ifdef CONFIG_ALTIVEC /* save altivec registers */ if (tsk->thread.used_vr) flush_altivec_to_thread(tsk); if (cpu_has_feature(CPU_FTR_ALTIVEC)) tsk->thread.vrsave = mfspr(SPRN_VRSAVE); #endif /* CONFIG_ALTIVEC */ flush_fp_to_thread(tsk); #ifdef CONFIG_VSX if (tsk->thread.used_vsr) flush_vsx_to_thread(tsk); #endif /* CONFIG_VSX */ } /* * Set up the sigcontext for the signal frame. */ #define unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region, label)\ do { \ if (__unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region))\ goto label; \ } while (0) static long notrace __unsafe_setup_sigcontext(struct sigcontext __user *sc, struct task_struct *tsk, int signr, sigset_t *set, unsigned long handler, int ctx_has_vsx_region) { /* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the * process never used altivec yet (MSR_VEC is zero in pt_regs of * the context). This is very important because we must ensure we * don't lose the VRSAVE content that may have been set prior to * the process doing its first vector operation * Userland shall check AT_HWCAP to know whether it can rely on the * v_regs pointer or not */ #ifdef CONFIG_ALTIVEC elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc); #endif struct pt_regs *regs = tsk->thread.regs; unsigned long msr = regs->msr; /* Force usr to alway see softe as 1 (interrupts enabled) */ unsigned long softe = 0x1; BUG_ON(tsk != current); #ifdef CONFIG_ALTIVEC unsafe_put_user(v_regs, &sc->v_regs, efault_out); /* save altivec registers */ if (tsk->thread.used_vr) { /* Copy 33 vec registers (vr0..31 and vscr) to the stack */ unsafe_copy_to_user(v_regs, &tsk->thread.vr_state, 33 * sizeof(vector128), efault_out); /* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg) * contains valid data. */ msr |= MSR_VEC; } /* We always copy to/from vrsave, it's 0 if we don't have or don't * use altivec. */ unsafe_put_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out); #else /* CONFIG_ALTIVEC */ unsafe_put_user(0, &sc->v_regs, efault_out); #endif /* CONFIG_ALTIVEC */ /* copy fpr regs and fpscr */ unsafe_copy_fpr_to_user(&sc->fp_regs, tsk, efault_out); /* * Clear the MSR VSX bit to indicate there is no valid state attached * to this context, except in the specific case below where we set it. */ msr &= ~MSR_VSX; #ifdef CONFIG_VSX /* * Copy VSX low doubleword to local buffer for formatting, * then out to userspace. Update v_regs to point after the * VMX data. */ if (tsk->thread.used_vsr && ctx_has_vsx_region) { v_regs += ELF_NVRREG; unsafe_copy_vsx_to_user(v_regs, tsk, efault_out); /* set MSR_VSX in the MSR value in the frame to * indicate that sc->vs_reg) contains valid data. */ msr |= MSR_VSX; } #endif /* CONFIG_VSX */ unsafe_put_user(&sc->gp_regs, &sc->regs, efault_out); unsafe_copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE, efault_out); unsafe_put_user(msr, &sc->gp_regs[PT_MSR], efault_out); unsafe_put_user(softe, &sc->gp_regs[PT_SOFTE], efault_out); unsafe_put_user(signr, &sc->signal, efault_out); unsafe_put_user(handler, &sc->handler, efault_out); if (set != NULL) unsafe_put_user(set->sig[0], &sc->oldmask, efault_out); return 0; efault_out: return -EFAULT; } #ifdef CONFIG_PPC_TRANSACTIONAL_MEM /* * As above, but Transactional Memory is in use, so deliver sigcontexts * containing checkpointed and transactional register states. * * To do this, we treclaim (done before entering here) to gather both sets of * registers and set up the 'normal' sigcontext registers with rolled-back * register values such that a simple signal handler sees a correct * checkpointed register state. If interested, a TM-aware sighandler can * examine the transactional registers in the 2nd sigcontext to determine the * real origin of the signal. */ static long setup_tm_sigcontexts(struct sigcontext __user *sc, struct sigcontext __user *tm_sc, struct task_struct *tsk, int signr, sigset_t *set, unsigned long handler, unsigned long msr) { /* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the * process never used altivec yet (MSR_VEC is zero in pt_regs of * the context). This is very important because we must ensure we * don't lose the VRSAVE content that may have been set prior to * the process doing its first vector operation * Userland shall check AT_HWCAP to know wether it can rely on the * v_regs pointer or not. */ #ifdef CONFIG_ALTIVEC elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc); elf_vrreg_t __user *tm_v_regs = sigcontext_vmx_regs(tm_sc); #endif struct pt_regs *regs = tsk->thread.regs; long err = 0; BUG_ON(tsk != current); BUG_ON(!MSR_TM_ACTIVE(msr)); WARN_ON(tm_suspend_disabled); /* Restore checkpointed FP, VEC, and VSX bits from ckpt_regs as * it contains the correct FP, VEC, VSX state after we treclaimed * the transaction and giveup_all() was called on reclaiming. */ msr |= tsk->thread.ckpt_regs.msr & (MSR_FP | MSR_VEC | MSR_VSX); #ifdef CONFIG_ALTIVEC err |= __put_user(v_regs, &sc->v_regs); err |= __put_user(tm_v_regs, &tm_sc->v_regs); /* save altivec registers */ if (tsk->thread.used_vr) { /* Copy 33 vec registers (vr0..31 and vscr) to the stack */ err |= __copy_to_user(v_regs, &tsk->thread.ckvr_state, 33 * sizeof(vector128)); /* If VEC was enabled there are transactional VRs valid too, * else they're a copy of the checkpointed VRs. */ if (msr & MSR_VEC) err |= __copy_to_user(tm_v_regs, &tsk->thread.vr_state, 33 * sizeof(vector128)); else err |= __copy_to_user(tm_v_regs, &tsk->thread.ckvr_state, 33 * sizeof(vector128)); /* set MSR_VEC in the MSR value in the frame to indicate * that sc->v_reg contains valid data. */ msr |= MSR_VEC; } /* We always copy to/from vrsave, it's 0 if we don't have or don't * use altivec. */ if (cpu_has_feature(CPU_FTR_ALTIVEC)) tsk->thread.ckvrsave = mfspr(SPRN_VRSAVE); err |= __put_user(tsk->thread.ckvrsave, (u32 __user *)&v_regs[33]); if (msr & MSR_VEC) err |= __put_user(tsk->thread.vrsave, (u32 __user *)&tm_v_regs[33]); else err |= __put_user(tsk->thread.ckvrsave, (u32 __user *)&tm_v_regs[33]); #else /* CONFIG_ALTIVEC */ err |= __put_user(0, &sc->v_regs); err |= __put_user(0, &tm_sc->v_regs); #endif /* CONFIG_ALTIVEC */ /* copy fpr regs and fpscr */ err |= copy_ckfpr_to_user(&sc->fp_regs, tsk); if (msr & MSR_FP) err |= copy_fpr_to_user(&tm_sc->fp_regs, tsk); else err |= copy_ckfpr_to_user(&tm_sc->fp_regs, tsk); #ifdef CONFIG_VSX /* * Copy VSX low doubleword to local buffer for formatting, * then out to userspace. Update v_regs to point after the * VMX data. */ if (tsk->thread.used_vsr) { v_regs += ELF_NVRREG; tm_v_regs += ELF_NVRREG; err |= copy_ckvsx_to_user(v_regs, tsk); if (msr & MSR_VSX) err |= copy_vsx_to_user(tm_v_regs, tsk); else err |= copy_ckvsx_to_user(tm_v_regs, tsk); /* set MSR_VSX in the MSR value in the frame to * indicate that sc->vs_reg) contains valid data. */ msr |= MSR_VSX; } #endif /* CONFIG_VSX */ err |= __put_user(&sc->gp_regs, &sc->regs); err |= __put_user(&tm_sc->gp_regs, &tm_sc->regs); err |= __copy_to_user(&tm_sc->gp_regs, regs, GP_REGS_SIZE); err |= __copy_to_user(&sc->gp_regs, &tsk->thread.ckpt_regs, GP_REGS_SIZE); err |= __put_user(msr, &tm_sc->gp_regs[PT_MSR]); err |= __put_user(msr, &sc->gp_regs[PT_MSR]); err |= __put_user(signr, &sc->signal); err |= __put_user(handler, &sc->handler); if (set != NULL) err |= __put_user(set->sig[0], &sc->oldmask); return err; } #endif /* * Restore the sigcontext from the signal frame. */ #define unsafe_restore_sigcontext(tsk, set, sig, sc, label) do { \ if (__unsafe_restore_sigcontext(tsk, set, sig, sc)) \ goto label; \ } while (0) static long notrace __unsafe_restore_sigcontext(struct task_struct *tsk, sigset_t *set, int sig, struct sigcontext __user *sc) { #ifdef CONFIG_ALTIVEC elf_vrreg_t __user *v_regs; #endif unsigned long save_r13 = 0; unsigned long msr; struct pt_regs *regs = tsk->thread.regs; #ifdef CONFIG_VSX int i; #endif BUG_ON(tsk != current); /* If this is not a signal return, we preserve the TLS in r13 */ if (!sig) save_r13 = regs->gpr[13]; /* copy the GPRs */ unsafe_copy_from_user(regs->gpr, sc->gp_regs, sizeof(regs->gpr), efault_out); unsafe_get_user(regs->nip, &sc->gp_regs[PT_NIP], efault_out); /* get MSR separately, transfer the LE bit if doing signal return */ unsafe_get_user(msr, &sc->gp_regs[PT_MSR], efault_out); if (sig) regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE)); unsafe_get_user(regs->orig_gpr3, &sc->gp_regs[PT_ORIG_R3], efault_out); unsafe_get_user(regs->ctr, &sc->gp_regs[PT_CTR], efault_out); unsafe_get_user(regs->link, &sc->gp_regs[PT_LNK], efault_out); unsafe_get_user(regs->xer, &sc->gp_regs[PT_XER], efault_out); unsafe_get_user(regs->ccr, &sc->gp_regs[PT_CCR], efault_out); /* Don't allow userspace to set SOFTE */ set_trap_norestart(regs); unsafe_get_user(regs->dar, &sc->gp_regs[PT_DAR], efault_out); unsafe_get_user(regs->dsisr, &sc->gp_regs[PT_DSISR], efault_out); unsafe_get_user(regs->result, &sc->gp_regs[PT_RESULT], efault_out); if (!sig) regs->gpr[13] = save_r13; if (set != NULL) unsafe_get_user(set->sig[0], &sc->oldmask, efault_out); /* * Force reload of FP/VEC. * This has to be done before copying stuff into tsk->thread.fpr/vr * for the reasons explained in the previous comment. */ regs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX)); #ifdef CONFIG_ALTIVEC unsafe_get_user(v_regs, &sc->v_regs, efault_out); if (v_regs && !access_ok(v_regs, 34 * sizeof(vector128))) return -EFAULT; /* Copy 33 vec registers (vr0..31 and vscr) from the stack */ if (v_regs != NULL && (msr & MSR_VEC) != 0) { unsafe_copy_from_user(&tsk->thread.vr_state, v_regs, 33 * sizeof(vector128), efault_out); tsk->thread.used_vr = true; } else if (tsk->thread.used_vr) { memset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128)); } /* Always get VRSAVE back */ if (v_regs != NULL) unsafe_get_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out); else tsk->thread.vrsave = 0; if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, tsk->thread.vrsave); #endif /* CONFIG_ALTIVEC */ /* restore floating point */ unsafe_copy_fpr_from_user(tsk, &sc->fp_regs, efault_out); #ifdef CONFIG_VSX /* * Get additional VSX data. Update v_regs to point after the * VMX data. Copy VSX low doubleword from userspace to local * buffer for formatting, then into the taskstruct. */ v_regs += ELF_NVRREG; if ((msr & MSR_VSX) != 0) { unsafe_copy_vsx_from_user(tsk, v_regs, efault_out); tsk->thread.used_vsr = true; } else { for (i = 0; i < 32 ; i++) tsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; } #endif return 0; efault_out: return -EFAULT; } #ifdef CONFIG_PPC_TRANSACTIONAL_MEM /* * Restore the two sigcontexts from the frame of a transactional processes. */ static long restore_tm_sigcontexts(struct task_struct *tsk, struct sigcontext __user *sc, struct sigcontext __user *tm_sc) { #ifdef CONFIG_ALTIVEC elf_vrreg_t __user *v_regs, *tm_v_regs; #endif unsigned long err = 0; unsigned long msr; struct pt_regs *regs = tsk->thread.regs; #ifdef CONFIG_VSX int i; #endif BUG_ON(tsk != current); if (tm_suspend_disabled) return -EINVAL; /* copy the GPRs */ err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr)); err |= __copy_from_user(&tsk->thread.ckpt_regs, sc->gp_regs, sizeof(regs->gpr)); /* * TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP. * TEXASR was set by the signal delivery reclaim, as was TFIAR. * Users doing anything abhorrent like thread-switching w/ signals for * TM-Suspended code will have to back TEXASR/TFIAR up themselves. * For the case of getting a signal and simply returning from it, * we don't need to re-copy them here. */ err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]); err |= __get_user(tsk->thread.tm_tfhar, &sc->gp_regs[PT_NIP]); /* get MSR separately, transfer the LE bit if doing signal return */ err |= __get_user(msr, &sc->gp_regs[PT_MSR]); /* Don't allow reserved mode. */ if (MSR_TM_RESV(msr)) return -EINVAL; /* pull in MSR LE from user context */ regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE)); /* The following non-GPR non-FPR non-VR state is also checkpointed: */ err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]); err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]); err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]); err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]); err |= __get_user(tsk->thread.ckpt_regs.ctr, &sc->gp_regs[PT_CTR]); err |= __get_user(tsk->thread.ckpt_regs.link, &sc->gp_regs[PT_LNK]); err |= __get_user(tsk->thread.ckpt_regs.xer, &sc->gp_regs[PT_XER]); err |= __get_user(tsk->thread.ckpt_regs.ccr, &sc->gp_regs[PT_CCR]); /* Don't allow userspace to set SOFTE */ set_trap_norestart(regs); /* These regs are not checkpointed; they can go in 'regs'. */ err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]); err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]); err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]); /* * Force reload of FP/VEC. * This has to be done before copying stuff into tsk->thread.fpr/vr * for the reasons explained in the previous comment. */ regs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX)); #ifdef CONFIG_ALTIVEC err |= __get_user(v_regs, &sc->v_regs); err |= __get_user(tm_v_regs, &tm_sc->v_regs); if (err) return err; if (v_regs && !access_ok(v_regs, 34 * sizeof(vector128))) return -EFAULT; if (tm_v_regs && !access_ok(tm_v_regs, 34 * sizeof(vector128))) return -EFAULT; /* Copy 33 vec registers (vr0..31 and vscr) from the stack */ if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) { err |= __copy_from_user(&tsk->thread.ckvr_state, v_regs, 33 * sizeof(vector128)); err |= __copy_from_user(&tsk->thread.vr_state, tm_v_regs, 33 * sizeof(vector128)); current->thread.used_vr = true; } else if (tsk->thread.used_vr) { memset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128)); memset(&tsk->thread.ckvr_state, 0, 33 * sizeof(vector128)); } /* Always get VRSAVE back */ if (v_regs != NULL && tm_v_regs != NULL) { err |= __get_user(tsk->thread.ckvrsave, (u32 __user *)&v_regs[33]); err |= __get_user(tsk->thread.vrsave, (u32 __user *)&tm_v_regs[33]); } else { tsk->thread.vrsave = 0; tsk->thread.ckvrsave = 0; } if (cpu_has_feature(CPU_FTR_ALTIVEC)) mtspr(SPRN_VRSAVE, tsk->thread.vrsave); #endif /* CONFIG_ALTIVEC */ /* restore floating point */ err |= copy_fpr_from_user(tsk, &tm_sc->fp_regs); err |= copy_ckfpr_from_user(tsk, &sc->fp_regs); #ifdef CONFIG_VSX /* * Get additional VSX data. Update v_regs to point after the * VMX data. Copy VSX low doubleword from userspace to local * buffer for formatting, then into the taskstruct. */ if (v_regs && ((msr & MSR_VSX) != 0)) { v_regs += ELF_NVRREG; tm_v_regs += ELF_NVRREG; err |= copy_vsx_from_user(tsk, tm_v_regs); err |= copy_ckvsx_from_user(tsk, v_regs); tsk->thread.used_vsr = true; } else { for (i = 0; i < 32 ; i++) { tsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0; tsk->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET] = 0; } } #endif tm_enable(); /* Make sure the transaction is marked as failed */ tsk->thread.tm_texasr |= TEXASR_FS; /* * Disabling preemption, since it is unsafe to be preempted * with MSR[TS] set without recheckpointing. */ preempt_disable(); /* pull in MSR TS bits from user context */ regs_set_return_msr(regs, regs->msr | (msr & MSR_TS_MASK)); /* * Ensure that TM is enabled in regs->msr before we leave the signal * handler. It could be the case that (a) user disabled the TM bit * through the manipulation of the MSR bits in uc_mcontext or (b) the * TM bit was disabled because a sufficient number of context switches * happened whilst in the signal handler and load_tm overflowed, * disabling the TM bit. In either case we can end up with an illegal * TM state leading to a TM Bad Thing when we return to userspace. * * CAUTION: * After regs->MSR[TS] being updated, make sure that get_user(), * put_user() or similar functions are *not* called. These * functions can generate page faults which will cause the process * to be de-scheduled with MSR[TS] set but without calling * tm_recheckpoint(). This can cause a bug. */ regs_set_return_msr(regs, regs->msr | MSR_TM); /* This loads the checkpointed FP/VEC state, if used */ tm_recheckpoint(&tsk->thread); msr_check_and_set(msr & (MSR_FP | MSR_VEC)); if (msr & MSR_FP) { load_fp_state(&tsk->thread.fp_state); regs_set_return_msr(regs, regs->msr | (MSR_FP | tsk->thread.fpexc_mode)); } if (msr & MSR_VEC) { load_vr_state(&tsk->thread.vr_state); regs_set_return_msr(regs, regs->msr | MSR_VEC); } preempt_enable(); return err; } #else /* !CONFIG_PPC_TRANSACTIONAL_MEM */ static long restore_tm_sigcontexts(struct task_struct *tsk, struct sigcontext __user *sc, struct sigcontext __user *tm_sc) { return -EINVAL; } #endif /* * Setup the trampoline code on the stack */ static long setup_trampoline(unsigned int syscall, unsigned int __user *tramp) { int i; long err = 0; /* Call the handler and pop the dummy stackframe*/ err |= __put_user(PPC_RAW_BCTRL(), &tramp[0]); err |= __put_user(PPC_RAW_ADDI(_R1, _R1, __SIGNAL_FRAMESIZE), &tramp[1]); err |= __put_user(PPC_RAW_LI(_R0, syscall), &tramp[2]); err |= __put_user(PPC_RAW_SC(), &tramp[3]); /* Minimal traceback info */ for (i=TRAMP_TRACEBACK; i < TRAMP_SIZE ;i++) err |= __put_user(0, &tramp[i]); if (!err) flush_icache_range((unsigned long) &tramp[0], (unsigned long) &tramp[TRAMP_SIZE]); return err; } /* * Userspace code may pass a ucontext which doesn't include VSX added * at the end. We need to check for this case. */ #define UCONTEXTSIZEWITHOUTVSX \ (sizeof(struct ucontext) - 32*sizeof(long)) /* * Handle {get,set,swap}_context operations */ SYSCALL_DEFINE3(swapcontext, struct ucontext __user *, old_ctx, struct ucontext __user *, new_ctx, long, ctx_size) { sigset_t set; unsigned long new_msr = 0; int ctx_has_vsx_region = 0; if (new_ctx && get_user(new_msr, &new_ctx->uc_mcontext.gp_regs[PT_MSR])) return -EFAULT; /* * Check that the context is not smaller than the original * size (with VMX but without VSX) */ if (ctx_size < UCONTEXTSIZEWITHOUTVSX) return -EINVAL; /* * If the new context state sets the MSR VSX bits but * it doesn't provide VSX state. */ if ((ctx_size < sizeof(struct ucontext)) && (new_msr & MSR_VSX)) return -EINVAL; /* Does the context have enough room to store VSX data? */ if (ctx_size >= sizeof(struct ucontext)) ctx_has_vsx_region = 1; if (old_ctx != NULL) { prepare_setup_sigcontext(current); if (!user_write_access_begin(old_ctx, ctx_size)) return -EFAULT; unsafe_setup_sigcontext(&old_ctx->uc_mcontext, current, 0, NULL, 0, ctx_has_vsx_region, efault_out); unsafe_copy_to_user(&old_ctx->uc_sigmask, &current->blocked, sizeof(sigset_t), efault_out); user_write_access_end(); } if (new_ctx == NULL) return 0; if (!access_ok(new_ctx, ctx_size) || fault_in_pages_readable((u8 __user *)new_ctx, ctx_size)) return -EFAULT; /* * If we get a fault copying the context into the kernel's * image of the user's registers, we can't just return -EFAULT * because the user's registers will be corrupted. For instance * the NIP value may have been updated but not some of the * other registers. Given that we have done the access_ok * and successfully read the first and last bytes of the region * above, this should only happen in an out-of-memory situation * or if another thread unmaps the region containing the context. * We kill the task with a SIGSEGV in this situation. */ if (__get_user_sigset(&set, &new_ctx->uc_sigmask)) do_exit(SIGSEGV); set_current_blocked(&set); if (!user_read_access_begin(new_ctx, ctx_size)) return -EFAULT; if (__unsafe_restore_sigcontext(current, NULL, 0, &new_ctx->uc_mcontext)) { user_read_access_end(); do_exit(SIGSEGV); } user_read_access_end(); /* This returns like rt_sigreturn */ set_thread_flag(TIF_RESTOREALL); return 0; efault_out: user_write_access_end(); return -EFAULT; } /* * Do a signal return; undo the signal stack. */ SYSCALL_DEFINE0(rt_sigreturn) { struct pt_regs *regs = current_pt_regs(); struct ucontext __user *uc = (struct ucontext __user *)regs->gpr[1]; sigset_t set; unsigned long msr; /* Always make any pending restarted system calls return -EINTR */ current->restart_block.fn = do_no_restart_syscall; if (!access_ok(uc, sizeof(*uc))) goto badframe; if (__get_user_sigset(&set, &uc->uc_sigmask)) goto badframe; set_current_blocked(&set); if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM)) { /* * If there is a transactional state then throw it away. * The purpose of a sigreturn is to destroy all traces of the * signal frame, this includes any transactional state created * within in. We only check for suspended as we can never be * active in the kernel, we are active, there is nothing better to * do than go ahead and Bad Thing later. * The cause is not important as there will never be a * recheckpoint so it's not user visible. */ if (MSR_TM_SUSPENDED(mfmsr())) tm_reclaim_current(0); /* * Disable MSR[TS] bit also, so, if there is an exception in the * code below (as a page fault in copy_ckvsx_to_user()), it does * not recheckpoint this task if there was a context switch inside * the exception. * * A major page fault can indirectly call schedule(). A reschedule * process in the middle of an exception can have a side effect * (Changing the CPU MSR[TS] state), since schedule() is called * with the CPU MSR[TS] disable and returns with MSR[TS]=Suspended * (switch_to() calls tm_recheckpoint() for the 'new' process). In * this case, the process continues to be the same in the CPU, but * the CPU state just changed. * * This can cause a TM Bad Thing, since the MSR in the stack will * have the MSR[TS]=0, and this is what will be used to RFID. * * Clearing MSR[TS] state here will avoid a recheckpoint if there * is any process reschedule in kernel space. The MSR[TS] state * does not need to be saved also, since it will be replaced with * the MSR[TS] that came from user context later, at * restore_tm_sigcontexts. */ regs_set_return_msr(regs, regs->msr & ~MSR_TS_MASK); if (__get_user(msr, &uc->uc_mcontext.gp_regs[PT_MSR])) goto badframe; } if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM) && MSR_TM_ACTIVE(msr)) { /* We recheckpoint on return. */ struct ucontext __user *uc_transact; /* Trying to start TM on non TM system */ if (!cpu_has_feature(CPU_FTR_TM)) goto badframe; if (__get_user(uc_transact, &uc->uc_link)) goto badframe; if (restore_tm_sigcontexts(current, &uc->uc_mcontext, &uc_transact->uc_mcontext)) goto badframe; } else { /* * Fall through, for non-TM restore * * Unset MSR[TS] on the thread regs since MSR from user * context does not have MSR active, and recheckpoint was * not called since restore_tm_sigcontexts() was not called * also. * * If not unsetting it, the code can RFID to userspace with * MSR[TS] set, but without CPU in the proper state, * causing a TM bad thing. */ regs_set_return_msr(current->thread.regs, current->thread.regs->msr & ~MSR_TS_MASK); if (!user_read_access_begin(&uc->uc_mcontext, sizeof(uc->uc_mcontext))) goto badframe; unsafe_restore_sigcontext(current, NULL, 1, &uc->uc_mcontext, badframe_block); user_read_access_end(); } if (restore_altstack(&uc->uc_stack)) goto badframe; set_thread_flag(TIF_RESTOREALL); return 0; badframe_block: user_read_access_end(); badframe: signal_fault(current, regs, "rt_sigreturn", uc); force_sig(SIGSEGV); return 0; } int handle_rt_signal64(struct ksignal *ksig, sigset_t *set, struct task_struct *tsk) { struct rt_sigframe __user *frame; unsigned long newsp = 0; long err = 0; struct pt_regs *regs = tsk->thread.regs; /* Save the thread's msr before get_tm_stackpointer() changes it */ unsigned long msr = regs->msr; frame = get_sigframe(ksig, tsk, sizeof(*frame), 0); /* * This only applies when calling unsafe_setup_sigcontext() and must be * called before opening the uaccess window. */ if (!MSR_TM_ACTIVE(msr)) prepare_setup_sigcontext(tsk); if (!user_write_access_begin(frame, sizeof(*frame))) goto badframe; unsafe_put_user(&frame->info, &frame->pinfo, badframe_block); unsafe_put_user(&frame->uc, &frame->puc, badframe_block); /* Create the ucontext. */ unsafe_put_user(0, &frame->uc.uc_flags, badframe_block); unsafe_save_altstack(&frame->uc.uc_stack, regs->gpr[1], badframe_block); if (MSR_TM_ACTIVE(msr)) { #ifdef CONFIG_PPC_TRANSACTIONAL_MEM /* The ucontext_t passed to userland points to the second * ucontext_t (for transactional state) with its uc_link ptr. */ unsafe_put_user(&frame->uc_transact, &frame->uc.uc_link, badframe_block); user_write_access_end(); err |= setup_tm_sigcontexts(&frame->uc.uc_mcontext, &frame->uc_transact.uc_mcontext, tsk, ksig->sig, NULL, (unsigned long)ksig->ka.sa.sa_handler, msr); if (!user_write_access_begin(&frame->uc.uc_sigmask, sizeof(frame->uc.uc_sigmask))) goto badframe; #endif } else { unsafe_put_user(0, &frame->uc.uc_link, badframe_block); unsafe_setup_sigcontext(&frame->uc.uc_mcontext, tsk, ksig->sig, NULL, (unsigned long)ksig->ka.sa.sa_handler, 1, badframe_block); } unsafe_copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set), badframe_block); user_write_access_end(); /* Save the siginfo outside of the unsafe block. */ if (copy_siginfo_to_user(&frame->info, &ksig->info)) goto badframe; /* Make sure signal handler doesn't get spurious FP exceptions */ tsk->thread.fp_state.fpscr = 0; /* Set up to return from userspace. */ if (tsk->mm->context.vdso) { regs_set_return_ip(regs, VDSO64_SYMBOL(tsk->mm->context.vdso, sigtramp_rt64)); } else { err |= setup_trampoline(__NR_rt_sigreturn, &frame->tramp[0]); if (err) goto badframe; regs_set_return_ip(regs, (unsigned long) &frame->tramp[0]); } /* Allocate a dummy caller frame for the signal handler. */ newsp = ((unsigned long)frame) - __SIGNAL_FRAMESIZE; err |= put_user(regs->gpr[1], (unsigned long __user *)newsp); /* Set up "regs" so we "return" to the signal handler. */ if (is_elf2_task()) { regs->ctr = (unsigned long) ksig->ka.sa.sa_handler; regs->gpr[12] = regs->ctr; } else { /* Handler is *really* a pointer to the function descriptor for * the signal routine. The first entry in the function * descriptor is the entry address of signal and the second * entry is the TOC value we need to use. */ func_descr_t __user *funct_desc_ptr = (func_descr_t __user *) ksig->ka.sa.sa_handler; err |= get_user(regs->ctr, &funct_desc_ptr->entry); err |= get_user(regs->gpr[2], &funct_desc_ptr->toc); } /* enter the signal handler in native-endian mode */ regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (MSR_KERNEL & MSR_LE)); regs->gpr[1] = newsp; regs->gpr[3] = ksig->sig; regs->result = 0; if (ksig->ka.sa.sa_flags & SA_SIGINFO) { regs->gpr[4] = (unsigned long)&frame->info; regs->gpr[5] = (unsigned long)&frame->uc; regs->gpr[6] = (unsigned long) frame; } else { regs->gpr[4] = (unsigned long)&frame->uc.uc_mcontext; } if (err) goto badframe; return 0; badframe_block: user_write_access_end(); badframe: signal_fault(current, regs, "handle_rt_signal64", frame); return 1; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tprrt/linux-stable</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">arch/powerpc/kernel/signal_64.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">30,604</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086548"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::AttrValue; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use std::default::Default; use string_cache::Atom; use util::str::DOMString; #[dom_struct] pub struct HTMLAreaElement { htmlelement: HTMLElement, rel_list: MutNullableHeap<JS<DOMTokenList>>, } impl HTMLAreaElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement { HTMLAreaElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document), rel_list: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLAreaElement> { let element = HTMLAreaElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap) } } impl VirtualMethods for HTMLAreaElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("rel") => AttrValue::from_serialized_tokenlist(value), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } } impl HTMLAreaElementMethods for HTMLAreaElement { // https://html.spec.whatwg.org/multipage/#dom-area-rellist fn RelList(&self) -> Root<DOMTokenList> { self.rel_list.or_init(|| { DOMTokenList::new(self.upcast(), &atom!("rel")) }) } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rohlandm/servo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">components/script/dom/htmlareaelement.rs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Rust</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,237</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086549"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">require 'will_paginate/core_ext' module WillPaginate # A mixin for ActiveRecord::Base. Provides +per_page+ class method # and hooks things up to provide paginating finders. # # Find out more in WillPaginate::Finder::ClassMethods # module Finder def self.included(base) base.extend ClassMethods class << base alias_method_chain :method_missing, :paginate # alias_method_chain :find_every, :paginate define_method(:per_page) { 30 } unless respond_to?(:per_page) end end # = Paginating finders for ActiveRecord models # # WillPaginate adds +paginate+, +per_page+ and other methods to # ActiveRecord::Base class methods and associations. It also hooks into # +method_missing+ to intercept pagination calls to dynamic finders such as # +paginate_by_user_id+ and translate them to ordinary finders # (+find_all_by_user_id+ in this case). # # In short, paginating finders are equivalent to ActiveRecord finders; the # only difference is that we start with "paginate" instead of "find" and # that <tt>:page</tt> is required parameter: # # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC' # # In paginating finders, "all" is implicit. There is no sense in paginating # a single record, right? So, you can drop the <tt>:all</tt> argument: # # Post.paginate(...) => Post.find :all # Post.paginate_all_by_something => Post.find_all_by_something # Post.paginate_by_something => Post.find_all_by_something # # == The importance of the <tt>:order</tt> parameter # # In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for # the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since # pagination only makes sense with ordered sets. Without the <tt>ORDER # BY</tt> clause, databases aren't required to do consistent ordering when # performing <tt>SELECT</tt> queries; this is especially true for # PostgreSQL. # # Therefore, make sure you are doing ordering on a column that makes the # most sense in the current context. Make that obvious to the user, also. # For perfomance reasons you will also want to add an index to that column. module ClassMethods # This is the main paginating finder. # # == Special parameters for paginating finders # * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil # * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden) # * <tt>:total_entries</tt> -- use only if you manually count total entries # * <tt>:count</tt> -- additional options that are passed on to +count+ # * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find") # # All other options (+conditions+, +order+, ...) are forwarded to +find+ # and +count+ calls. def paginate(*args, &block) options = args.pop page, per_page, total_entries = wp_parse_options(options) finder = (options[:finder] || 'find').to_s if finder == 'find' # an array of IDs may have been given: total_entries ||= (Array === args.first and args.first.size) # :all is implicit args.unshift(:all) if args.empty? end WillPaginate::Collection.create(page, per_page, total_entries) do |pager| count_options = options.except :page, :per_page, :total_entries, :finder find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) args << find_options # @options_from_last_find = nil pager.replace send(finder, *args, &block) # magic counting for user convenience: pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries end end # Iterates through all records by loading one page at a time. This is useful # for migrations or any other use case where you don't want to load all the # records in memory at once. # # It uses +paginate+ internally; therefore it accepts all of its options. # You can specify a starting page with <tt>:page</tt> (default is 1). Default # <tt>:order</tt> is <tt>"id"</tt>, override if necessary. # # See http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord where # Jamis Buck describes this and also uses a more efficient way for MySQL. def paginated_each(options = {}, &block) options = { :order => 'id', :page => 1 }.merge options options[:page] = options[:page].to_i options[:total_entries] = 0 # skip the individual count queries total = 0 begin collection = paginate(options) total += collection.each(&block).size options[:page] += 1 end until collection.size < collection.per_page total end # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string # based on the params otherwise used by paginating finds: +page+ and # +per_page+. # # Example: # # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000], # :page => params[:page], :per_page => 3 # # A query for counting rows will automatically be generated if you don't # supply <tt>:total_entries</tt>. If you experience problems with this # generated SQL, you might want to perform the count manually in your # application. # def paginate_by_sql(sql, options) WillPaginate::Collection.create(*wp_parse_options(options)) do |pager| query = sanitize_sql(sql) original_query = query.dup # add limit, offset add_limit! query, :offset => pager.offset, :limit => pager.per_page # perfom the find pager.replace find_by_sql(query) unless pager.total_entries count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, '' count_query = "SELECT COUNT(*) FROM (#{count_query})" unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase) count_query << ' AS count_table' end # perform the count query pager.total_entries = count_by_sql(count_query) end end end def respond_to?(method, include_priv = false) #:nodoc: case method.to_sym when :paginate, :paginate_by_sql true else super(method.to_s.sub(/^paginate/, 'find'), include_priv) end end protected def method_missing_with_paginate(method, *args, &block) #:nodoc: # did somebody tried to paginate? if not, let them be unless method.to_s.index('paginate') == 0 return method_missing_without_paginate(method, *args, &block) end # paginate finders are really just find_* with limit and offset finder = method.to_s.sub('paginate', 'find') finder.sub!('find', 'find_all') if finder.index('find_by_') == 0 options = args.pop raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys options = options.dup options[:finder] = finder args << options paginate(*args, &block) end # Does the not-so-trivial job of finding out the total number of entries # in the database. It relies on the ActiveRecord +count+ method. def wp_count(options, args, finder) excludees = [:count, :order, :limit, :offset, :readonly] unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i excludees << :select # only exclude the select param if it doesn't begin with DISTINCT end # count expects (almost) the same options as find count_options = options.except *excludees # merge the hash found in :count # this allows you to specify :select, :order, or anything else just for the count query count_options.update options[:count] if options[:count] # we may be in a model or an association proxy klass = (@owner and @reflection) ? @reflection.klass : self # forget about includes if they are irrelevant (Rails 2.1) if count_options[:include] and klass.private_methods.include?('references_eager_loaded_tables?') and !klass.send(:references_eager_loaded_tables?, count_options) count_options.delete :include end # we may have to scope ... counter = Proc.new { count(count_options) } count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with')) # scope_out adds a 'with_finder' method which acts like with_scope, if it's present # then execute the count with the scoping provided by the with_finder send(scoper, &counter) elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder) # extract conditions from calls like "paginate_by_foo_and_bar" attribute_names = extract_attribute_names_from_match(match) conditions = construct_attributes_from_arguments(attribute_names, args) with_scope(:find => { :conditions => conditions }, &counter) else counter.call end count.respond_to?(:length) ? count.length : count end def wp_parse_options(options) #:nodoc: raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys options = options.symbolize_keys raise ArgumentError, ':page parameter required' unless options.key? :page if options[:count] and options[:total_entries] raise ArgumentError, ':count and :total_entries are mutually exclusive' end page = options[:page] || 1 per_page = options[:per_page] || self.per_page total = options[:total_entries] [page, per_page, total] end private # def find_every_with_paginate(options) # @options_from_last_find = options # find_every_without_paginate(options) # end end end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gkneighb/insoshi</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/plugins/will_paginate/lib/will_paginate/finder.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">10,582</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086550"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// // basic_serial_port.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab3b4bcb59aa8bfaab3b4acbba8b3bbb4aef4b9b5b7">[email protected]</a>) // // 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) // #ifndef ASIO_BASIC_SERIAL_PORT_HPP #define ASIO_BASIC_SERIAL_PORT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include "asio/basic_io_object.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/serial_port_base.hpp" #include "asio/serial_port_service.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides serial port functionality. /** * The basic_serial_port class template provides functionality that is common * to all serial ports. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename SerialPortService = serial_port_service> class basic_serial_port : public basic_io_object<SerialPortService>, public serial_port_base { public: /// (Deprecated: Use native_handle_type.) The native representation of a /// serial port. typedef typename SerialPortService::native_handle_type native_type; /// The native representation of a serial port. typedef typename SerialPortService::native_handle_type native_handle_type; /// A basic_serial_port is always the lowest layer. typedef basic_serial_port<SerialPortService> lowest_layer_type; /// Construct a basic_serial_port without opening it. /** * This constructor creates a serial port without opening it. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. */ explicit basic_serial_port(asio::io_service& io_service) : basic_io_object<SerialPortService>(io_service) { } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param device The platform-specific device name for this serial * port. */ explicit basic_serial_port(asio::io_service& io_service, const char* device) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_serial_port. /** * This constructor creates and opens a serial port for the specified device * name. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param device The platform-specific device name for this serial * port. */ explicit basic_serial_port(asio::io_service& io_service, const std::string& device) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_serial_port on an existing native serial port. /** * This constructor creates a serial port object to hold an existing native * serial port. * * @param io_service The io_service object that the serial port will use to * dispatch handlers for any asynchronous operations performed on the port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ basic_serial_port(asio::io_service& io_service, const native_handle_type& native_serial_port) : basic_io_object<SerialPortService>(io_service) { asio::error_code ec; this->get_service().assign(this->get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_serial_port from another. /** * This constructor moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(io_service&) constructor. */ basic_serial_port(basic_serial_port&& other) : basic_io_object<SerialPortService>( ASIO_MOVE_CAST(basic_serial_port)(other)) { } /// Move-assign a basic_serial_port from another. /** * This assignment operator moves a serial port from one object to another. * * @param other The other basic_serial_port object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_serial_port(io_service&) constructor. */ basic_serial_port& operator=(basic_serial_port&& other) { basic_io_object<SerialPortService>::operator=( ASIO_MOVE_CAST(basic_serial_port)(other)); return *this; } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_serial_port cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Open the serial port using the specified device name. /** * This function opens the serial port for the specified device name. * * @param device The platform-specific device name. * * @throws asio::system_error Thrown on failure. */ void open(const std::string& device) { asio::error_code ec; this->get_service().open(this->get_implementation(), device, ec); asio::detail::throw_error(ec, "open"); } /// Open the serial port using the specified device name. /** * This function opens the serial port using the given platform-specific * device name. * * @param device The platform-specific device name. * * @param ec Set the indicate what error occurred, if any. */ asio::error_code open(const std::string& device, asio::error_code& ec) { return this->get_service().open(this->get_implementation(), device, ec); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_serial_port) { asio::error_code ec; this->get_service().assign(this->get_implementation(), native_serial_port, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native serial port to the serial port. /* * This function opens the serial port to hold an existing native serial port. * * @param native_serial_port A native serial port. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code assign(const native_handle_type& native_serial_port, asio::error_code& ec) { return this->get_service().assign(this->get_implementation(), native_serial_port, ec); } /// Determine whether the serial port is open. bool is_open() const { return this->get_service().is_open(this->get_implementation()); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; this->get_service().close(this->get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the serial port. /** * This function is used to close the serial port. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code close(asio::error_code& ec) { return this->get_service().close(this->get_implementation(), ec); } /// (Deprecated: Use native_handle().) Get the native serial port /// representation. /** * This function may be used to obtain the underlying representation of the * serial port. This is intended to allow access to native serial port * functionality that is not otherwise provided. */ native_type native() { return this->get_service().native_handle(this->get_implementation()); } /// Get the native serial port representation. /** * This function may be used to obtain the underlying representation of the * serial port. This is intended to allow access to native serial port * functionality that is not otherwise provided. */ native_handle_type native_handle() { return this->get_service().native_handle(this->get_implementation()); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; this->get_service().cancel(this->get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the serial port. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code cancel(asio::error_code& ec) { return this->get_service().cancel(this->get_implementation(), ec); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @throws asio::system_error Thrown on failure. */ void send_break() { asio::error_code ec; this->get_service().send_break(this->get_implementation(), ec); asio::detail::throw_error(ec, "send_break"); } /// Send a break sequence to the serial port. /** * This function causes a break sequence of platform-specific duration to be * sent out the serial port. * * @param ec Set to indicate what error occurred, if any. */ asio::error_code send_break(asio::error_code& ec) { return this->get_service().send_break(this->get_implementation(), ec); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @throws asio::system_error Thrown on failure. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> void set_option(const SettableSerialPortOption& option) { asio::error_code ec; this->get_service().set_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the serial port. /** * This function is used to set an option on the serial port. * * @param option The option value to be set on the serial port. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename SettableSerialPortOption> asio::error_code set_option(const SettableSerialPortOption& option, asio::error_code& ec) { return this->get_service().set_option( this->get_implementation(), option, ec); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @throws asio::system_error Thrown on failure. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> void get_option(GettableSerialPortOption& option) { asio::error_code ec; this->get_service().get_option(this->get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the serial port. /** * This function is used to get the current value of an option on the serial * port. * * @param option The option value to be obtained from the serial port. * * @param ec Set to indicate what error occured, if any. * * @sa GettableSerialPortOption @n * asio::serial_port_base::baud_rate @n * asio::serial_port_base::flow_control @n * asio::serial_port_base::parity @n * asio::serial_port_base::stop_bits @n * asio::serial_port_base::character_size */ template <typename GettableSerialPortOption> asio::error_code get_option(GettableSerialPortOption& option, asio::error_code& ec) { return this->get_service().get_option( this->get_implementation(), option, ec); } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * serial_port.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->get_service().write_some( this->get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the serial port. /** * This function is used to write data to the serial port. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the serial port. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->get_service().write_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the serial port. * The function call always returns immediately. * * @param buffers One or more data buffers to be written to the serial port. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * serial_port.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence, typename WriteHandler> ASIO_INITFN_RESULT_TYPE(WriteHandler, void (asio::error_code, std::size_t)) async_write_some(const ConstBufferSequence& buffers, ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; return this->get_service().async_write_some(this->get_implementation(), buffers, ASIO_MOVE_CAST(WriteHandler)(handler)); } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * serial_port.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->get_service().read_some( this->get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the serial port. /** * This function is used to read data from the serial port. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->get_service().read_some( this->get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the serial port. * The function call always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation * of the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * serial_port.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read_some(const MutableBufferSequence& buffers, ASIO_MOVE_ARG(ReadHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; return this->get_service().async_read_some(this->get_implementation(), buffers, ASIO_MOVE_CAST(ReadHandler)(handler)); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_SERIAL_PORT_HPP </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">julien3/vertxbuspp</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vertxbuspp/asio/include/asio/basic_serial_port.hpp</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C++</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">24,579</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086551"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.test.spring; import org.apache.camel.management.JmxSystemPropertyKeys; import org.apache.camel.spring.SpringCamelContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.support.DelegatingSmartContextLoader; /** * CamelSpringDelegatingTestContextLoader which fixes issues in Camel's JavaConfigContextLoader. (adds support for Camel's test annotations) * <br> * <em>This loader can handle either classes or locations for configuring the context.</em> * <br> * NOTE: This TestContextLoader doesn't support the annotation of ExcludeRoutes now. */ public class CamelSpringDelegatingTestContextLoader extends DelegatingSmartContextLoader { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Override public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception { Class<?> testClass = getTestClass(); if (logger.isDebugEnabled()) { logger.debug("Loading ApplicationContext for merged context configuration [{}].", mergedConfig); } // Pre CamelContext(s) instantiation setup CamelAnnotationsHandler.handleDisableJmx(null, testClass); try { SpringCamelContext.setNoStart(true); System.setProperty("skipStartingCamelContext", "true"); ConfigurableApplicationContext context = (ConfigurableApplicationContext) super.loadContext(mergedConfig); SpringCamelContext.setNoStart(false); System.clearProperty("skipStartingCamelContext"); return loadContext(context, testClass); } finally { cleanup(testClass); } } /** * Performs the bulk of the Spring application context loading/customization. * * @param context the partially configured context. The context should have the bean definitions loaded, but nothing else. * @param testClass the test class being executed * @return the initialized (refreshed) Spring application context * * @throws Exception if there is an error during initialization/customization */ public ApplicationContext loadContext(ConfigurableApplicationContext context, Class<?> testClass) throws Exception { AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) context); // Post CamelContext(s) instantiation but pre CamelContext(s) start setup CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass); CamelAnnotationsHandler.handleShutdownTimeout(context, testClass); CamelAnnotationsHandler.handleMockEndpoints(context, testClass); CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass); CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass); // CamelContext(s) startup CamelAnnotationsHandler.handleCamelContextStartup(context, testClass); return context; } /** * Cleanup/restore global state to defaults / pre-test values after the test setup * is complete. * * @param testClass the test class being executed */ protected void cleanup(Class<?> testClass) { SpringCamelContext.setNoStart(false); if (testClass.isAnnotationPresent(DisableJmx.class)) { if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) { System.clearProperty(JmxSystemPropertyKeys.DISABLED); } else { System.setProperty(JmxSystemPropertyKeys.DISABLED, CamelSpringTestHelper.getOriginalJmxDisabled()); } } } /** * Returns the class under test in order to enable inspection of annotations while the * Spring context is being created. * * @return the test class that is being executed * @see CamelSpringTestHelper */ protected Class<?> getTestClass() { return CamelSpringTestHelper.getTestClass(); } }</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jmandawg/camel</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,252</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086552"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See the LICENSE file in builder/azure for license information. package arm import ( "golang.org/x/crypto/ssh" "testing" ) func TestFart(t *testing.T) { } func TestAuthorizedKeyShouldParse(t *testing.T) { testSubject, err := NewOpenSshKeyPairWithSize(512) if err != nil { t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) } authorizedKey := testSubject.AuthorizedKey() _, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey)) if err != nil { t.Fatalf("Failed to parse the authorized key, err=%s", err) } } func TestPrivateKeyShouldParse(t *testing.T) { testSubject, err := NewOpenSshKeyPairWithSize(512) if err != nil { t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err) } _, err = ssh.ParsePrivateKey([]byte(testSubject.PrivateKey())) if err != nil { t.Fatalf("Failed to parse the private key, err=%s\n", err) } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">stardog-union/stardog-graviton</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/github.com/mitchellh/packer/builder/azure/arm/openssh_key_pair_test.go</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">GO</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">980</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086553"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#!/usr/bin/env bash # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This script performs disaster recovery of etcd from the backup data. # Assumptions: # - backup was done using etcdctl command: # a) in case of etcd2 # $ etcdctl backup --data-dir=<dir> # produced .snap and .wal files # b) in case of etcd3 # $ etcdctl --endpoints=<address> snapshot save # produced .db file # - version.txt file is in the current directory (if it isn't it will be # defaulted to "3.0.17/etcd3"). Based on this file, the script will # decide to which version we are restoring (procedures are different # for etcd2 and etcd3). # - in case of etcd2 - *.snap and *.wal files are in current directory # - in case of etcd3 - *.db file is in the current directory # - the script is run as root # - for event etcd, we only support clearing it - to do it, you need to # set RESET_EVENT_ETCD=true env var. set -o errexit set -o nounset set -o pipefail # Version file contains information about current version in the format: # <etcd binary version>/<etcd api mode> (e.g. "3.0.12/etcd3"). # # If the file doesn't exist we assume "3.0.17/etcd3" configuration is # the current one and create a file with such configuration. # The restore procedure is chosen based on this information. VERSION_FILE="version.txt" # Make it possible to overwrite version file (or default version) # with VERSION_CONTENTS env var. if [ -n "${VERSION_CONTENTS:-}" ]; then echo "${VERSION_CONTENTS}" > "${VERSION_FILE}" fi if [ ! -f "${VERSION_FILE}" ]; then echo "3.0.17/etcd3" > "${VERSION_FILE}" fi VERSION_CONTENTS="$(cat ${VERSION_FILE})" ETCD_VERSION="$(echo "$VERSION_CONTENTS" | cut -d '/' -f 1)" ETCD_API="$(echo "$VERSION_CONTENTS" | cut -d '/' -f 2)" # Name is used only in case of etcd3 mode, to appropriate set the metadata # for the etcd data. # NOTE: NAME HAS TO BE EQUAL TO WHAT WE USE IN --name flag when starting etcd. NAME="${NAME:-etcd-$(hostname)}" INITIAL_CLUSTER="${INITIAL_CLUSTER:-${NAME}=http://localhost:2380}" INITIAL_ADVERTISE_PEER_URLS="${INITIAL_ADVERTISE_PEER_URLS:-http://localhost:2380}" # Port on which etcd is exposed. etcd_port=2379 event_etcd_port=4002 # Wait until both etcd instances are up wait_for_etcd_up() { port=$1 # TODO: As of 3.0.x etcd versions, all 2.* and 3.* versions return # {"health": "true"} on /health endpoint in healthy case. # However, we should come with a regex for it to avoid future break. health_ok="{\"health\": \"true\"}" for _ in $(seq 120); do # TODO: Is it enough to look into /health endpoint? health=$(curl --silent "http://127.0.0.1:${port}/health") if [ "${health}" == "${health_ok}" ]; then return 0 fi sleep 1 done return 1 } # Wait until apiserver is up. wait_for_cluster_healthy() { for _ in $(seq 120); do cs_status=$(kubectl get componentstatuses -o template --template='{{range .items}}{{with index .conditions 0}}{{.type}}:{{.status}}{{end}}{{"\n"}}{{end}}') || true componentstatuses=$(echo "${cs_status}" | grep -c 'Healthy:') || true healthy=$(echo "${cs_status}" | grep -c 'Healthy:True') || true if [ "${componentstatuses}" -eq "${healthy}" ]; then return 0 fi sleep 1 done return 1 } # Wait until etcd and apiserver pods are down. wait_for_etcd_and_apiserver_down() { for _ in $(seq 120); do etcd=$(docker ps | grep -c etcd-server) apiserver=$(docker ps | grep -c apiserver) # TODO: Theoretically it is possible, that apiserver and or etcd # are currently down, but Kubelet is now restarting them and they # will reappear again. We should avoid it. if [ "${etcd}" -eq "0" ] && [ "${apiserver}" -eq "0" ]; then return 0 fi sleep 1 done return 1 } # Move the manifest files to stop etcd and kube-apiserver # while we swap the data out from under them. MANIFEST_DIR="/etc/kubernetes/manifests" MANIFEST_BACKUP_DIR="/etc/kubernetes/manifests-backups" mkdir -p "${MANIFEST_BACKUP_DIR}" echo "Moving etcd(s) & apiserver manifest files to ${MANIFEST_BACKUP_DIR}" # If those files were already moved (e.g. during previous # try of backup) don't fail on it. mv "${MANIFEST_DIR}/kube-apiserver.manifest" "${MANIFEST_BACKUP_DIR}" || true mv "${MANIFEST_DIR}/etcd.manifest" "${MANIFEST_BACKUP_DIR}" || true mv "${MANIFEST_DIR}/etcd-events.manifest" "${MANIFEST_BACKUP_DIR}" || true # Wait for the pods to be stopped echo "Waiting for etcd and kube-apiserver to be down" if ! wait_for_etcd_and_apiserver_down; then # Couldn't kill etcd and apiserver. echo "Downing etcd and apiserver failed" exit 1 fi read -rsp $'Press enter when all etcd instances are down...\n' # Create the sort of directory structure that etcd expects. # If this directory already exists, remove it. BACKUP_DIR="/var/tmp/backup" rm -rf "${BACKUP_DIR}" if [ "${ETCD_API}" == "etcd2" ]; then echo "Preparing etcd backup data for restore" # In v2 mode, we simply copy both snap and wal files to a newly created # directory. After that, we start etcd with --force-new-cluster option # that (according to the etcd documentation) is required to recover from # a backup. echo "Copying data to ${BACKUP_DIR} and restoring there" mkdir -p "${BACKUP_DIR}/member/snap" mkdir -p "${BACKUP_DIR}/member/wal" # If the cluster is relatively new, there can be no .snap file. mv ./*.snap "${BACKUP_DIR}/member/snap/" || true mv ./*.wal "${BACKUP_DIR}/member/wal/" # TODO(jsz): This won't work with HA setups (e.g. do we need to set --name flag)? echo "Starting etcd ${ETCD_VERSION} to restore data" if ! image=$(docker run -d -v ${BACKUP_DIR}:/var/etcd/data \ --net=host -p ${etcd_port}:${etcd_port} \ "k8s.gcr.io/etcd:${ETCD_VERSION}" /bin/sh -c \ "/usr/local/bin/etcd --data-dir /var/etcd/data --force-new-cluster"); then echo "Docker container didn't started correctly" exit 1 fi echo "Container ${image} created, waiting for etcd to report as healthy" if ! wait_for_etcd_up "${etcd_port}"; then echo "Etcd didn't come back correctly" exit 1 fi # Kill that etcd instance. echo "Etcd healthy - killing ${image} container" docker kill "${image}" elif [ "${ETCD_API}" == "etcd3" ]; then echo "Preparing etcd snapshot for restore" mkdir -p "${BACKUP_DIR}" echo "Copying data to ${BACKUP_DIR} and restoring there" number_files=$(find . -maxdepth 1 -type f -name "*.db" | wc -l) if [ "${number_files}" -ne "1" ]; then echo "Incorrect number of *.db files - expected 1" exit 1 fi mv ./*.db "${BACKUP_DIR}/" snapshot="$(ls ${BACKUP_DIR})" # Run etcdctl snapshot restore command and wait until it is finished. # setting with --name in the etcd manifest file and then it seems to work. if ! docker run -v ${BACKUP_DIR}:/var/tmp/backup --env ETCDCTL_API=3 \ "k8s.gcr.io/etcd:${ETCD_VERSION}" /bin/sh -c \ "/usr/local/bin/etcdctl snapshot restore ${BACKUP_DIR}/${snapshot} --name ${NAME} --initial-cluster ${INITIAL_CLUSTER} --initial-advertise-peer-urls ${INITIAL_ADVERTISE_PEER_URLS}; mv /${NAME}.etcd/member /var/tmp/backup/"; then echo "Docker container didn't started correctly" exit 1 fi rm -f "${BACKUP_DIR}/${snapshot}" fi # Also copy version.txt file. cp "${VERSION_FILE}" "${BACKUP_DIR}" export MNT_DISK="/mnt/disks/master-pd" # Save the corrupted data (clean directory if it is already non-empty). rm -rf "${MNT_DISK}/var/etcd-corrupted" mkdir -p "${MNT_DISK}/var/etcd-corrupted" echo "Saving corrupted data to ${MNT_DISK}/var/etcd-corrupted" mv /var/etcd/data "${MNT_DISK}/var/etcd-corrupted" # Replace the corrupted data dir with the restored data. echo "Copying restored data to /var/etcd/data" mv "${BACKUP_DIR}" /var/etcd/data if [ "${RESET_EVENT_ETCD:-}" == "true" ]; then echo "Removing event-etcd corrupted data" EVENTS_CORRUPTED_DIR="${MNT_DISK}/var/etcd-events-corrupted" # Save the corrupted data (clean directory if it is already non-empty). rm -rf "${EVENTS_CORRUPTED_DIR}" mkdir -p "${EVENTS_CORRUPTED_DIR}" mv /var/etcd/data-events "${EVENTS_CORRUPTED_DIR}" fi # Start etcd and kube-apiserver again. echo "Restarting etcd and apiserver from restored snapshot" mv "${MANIFEST_BACKUP_DIR}"/* "${MANIFEST_DIR}/" rm -rf "${MANIFEST_BACKUP_DIR}" # Verify that etcd is back. echo "Waiting for etcd to come back" if ! wait_for_etcd_up "${etcd_port}"; then echo "Etcd didn't come back correctly" exit 1 fi # Verify that event etcd is back. echo "Waiting for event etcd to come back" if ! wait_for_etcd_up "${event_etcd_port}"; then echo "Event etcd didn't come back correctly" exit 1 fi # Verify that kube-apiserver is back and cluster is healthy. echo "Waiting for apiserver to come back" if ! wait_for_cluster_healthy; then echo "Apiserver didn't come back correctly" exit 1 fi echo "Cluster successfully restored!" </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mkumatag/origin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/k8s.io/kubernetes/cluster/restore-from-backup.sh</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Shell</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">9,389</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086554"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import {isPresent, RegExpWrapper, StringWrapper} from 'angular2/src/core/facade/lang'; import {MapWrapper} from 'angular2/src/core/facade/collection'; import {Parser} from 'angular2/src/core/change_detection/change_detection'; import {CompileStep} from './compile_step'; import {CompileElement} from './compile_element'; import {CompileControl} from './compile_control'; import {dashCaseToCamelCase} from '../util'; // Group 1 = "bind-" // Group 2 = "var-" or "#" // Group 3 = "on-" // Group 4 = "bindon-" // Group 5 = the identifier after "bind-", "var-/#", or "on-" // Group 6 = identifier inside [()] // Group 7 = identifier inside [] // Group 8 = identifier inside () var BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g; /** * Parses the property bindings on a single element. */ export class PropertyBindingParser implements CompileStep { constructor(private _parser: Parser) {} processStyle(style: string): string { return style; } processElement(parent: CompileElement, current: CompileElement, control: CompileControl) { var attrs = current.attrs(); var newAttrs = new Map(); MapWrapper.forEach(attrs, (attrValue, attrName) => { attrName = this._normalizeAttributeName(attrName); var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName); if (isPresent(bindParts)) { if (isPresent(bindParts[1])) { // match: bind-prop this._bindProperty(bindParts[5], attrValue, current, newAttrs); } else if (isPresent( bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden" var identifier = bindParts[5]; var value = attrValue == '' ? '\$implicit' : attrValue; this._bindVariable(identifier, value, current, newAttrs); } else if (isPresent(bindParts[3])) { // match: on-event this._bindEvent(bindParts[5], attrValue, current, newAttrs); } else if (isPresent(bindParts[4])) { // match: bindon-prop this._bindProperty(bindParts[5], attrValue, current, newAttrs); this._bindAssignmentEvent(bindParts[5], attrValue, current, newAttrs); } else if (isPresent(bindParts[6])) { // match: [(expr)] this._bindProperty(bindParts[6], attrValue, current, newAttrs); this._bindAssignmentEvent(bindParts[6], attrValue, current, newAttrs); } else if (isPresent(bindParts[7])) { // match: [expr] this._bindProperty(bindParts[7], attrValue, current, newAttrs); } else if (isPresent(bindParts[8])) { // match: (event) this._bindEvent(bindParts[8], attrValue, current, newAttrs); } } else { var expr = this._parser.parseInterpolation(attrValue, current.elementDescription); if (isPresent(expr)) { this._bindPropertyAst(attrName, expr, current, newAttrs); } } }); MapWrapper.forEach(newAttrs, (attrValue, attrName) => { attrs.set(attrName, attrValue); }); } _normalizeAttributeName(attrName: string): string { return StringWrapper.startsWith(attrName, 'data-') ? StringWrapper.substring(attrName, 5) : attrName; } _bindVariable(identifier, value, current: CompileElement, newAttrs: Map<any, any>) { current.bindElement().bindVariable(dashCaseToCamelCase(identifier), value); newAttrs.set(identifier, value); } _bindProperty(name, expression, current: CompileElement, newAttrs) { this._bindPropertyAst(name, this._parser.parseBinding(expression, current.elementDescription), current, newAttrs); } _bindPropertyAst(name, ast, current: CompileElement, newAttrs: Map<any, any>) { var binder = current.bindElement(); binder.bindProperty(dashCaseToCamelCase(name), ast); newAttrs.set(name, ast.source); } _bindAssignmentEvent(name, expression, current: CompileElement, newAttrs) { this._bindEvent(name, `${expression}=$event`, current, newAttrs); } _bindEvent(name, expression, current: CompileElement, newAttrs) { current.bindElement().bindEvent( dashCaseToCamelCase(name), this._parser.parseAction(expression, current.elementDescription)); // Don't detect directives for event names for now, // so don't add the event name to the CompileElement.attrs } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">shahata/angular</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">modules/angular2/src/core/render/dom/compiler/property_binding_parser.ts</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">TypeScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,415</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086555"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">public class Test { void fooBarGoo() { try {} finally {} fbg<caret> } }</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">smmribeiro/intellij-community</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">java/java-tests/testData/codeInsight/completion/normal/MethodCallAfterFinally.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">87</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086556"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style> .outer { width: 120px; height: 230px; margin: 20px; border: 1px solid black; -webkit-box-reflect: right 10px; } .inner { margin: 10px; width: 100px; height: 100px; background-color: green; text-align: center; font-size: 50pt; -webkit-box-reflect: below 10px; } .composited { transform: translateZ(0); } </style> <script type="text/javascript" charset="utf-8"> function doTest() { document.getElementById('inner').style.webkitTransform = 'rotate(10deg)'; } window.addEventListener('load', doTest, false); </script> </head> <body> <p>Test transform change on reflected elements. Left and right side should be symmetrical.</p> <div class="outer composited"> <div id="inner" class="inner composited"> 1 </div> </div> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">js0701/chromium-crosswalk</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/WebKit/LayoutTests/compositing/reflections/nested-reflection-transformed.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">959</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086557"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># rank 1 class CandidateTest def test4 end def test5 end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">phstc/sshp</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/ruby/1.9.1/gems/pry-0.9.12.2/spec/fixtures/candidate_helper2.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">70</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086558"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright 2004, Instant802 Networks, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/module.h> #include <linux/if_arp.h> #include <linux/types.h> #include <net/ip.h> #include <net/pkt_sched.h> #include <net/mac80211.h> #include "ieee80211_i.h" #include "wme.h" /* Default mapping in classifier to work with default * queue setup. */ const int ieee802_1d_to_ac[8] = { 2, 3, 3, 2, 1, 1, 0, 0 }; static int wme_downgrade_ac(struct sk_buff *skb) { switch (skb->priority) { case 6: case 7: skb->priority = 5; /* VO -> VI */ return 0; case 4: case 5: skb->priority = 3; /* VI -> BE */ return 0; case 0: case 3: skb->priority = 2; /* BE -> BK */ return 0; default: return -1; } } /* Indicate which queue to use. */ u16 ieee80211_select_queue(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb) { struct ieee80211_local *local = sdata->local; struct sta_info *sta = NULL; u32 sta_flags = 0; const u8 *ra = NULL; bool qos = false; if (local->hw.queues < 4 || skb->len < 6) { skb->priority = 0; /* required for correct WPA/11i MIC */ return min_t(u16, local->hw.queues - 1, ieee802_1d_to_ac[skb->priority]); } rcu_read_lock(); switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: rcu_read_lock(); sta = rcu_dereference(sdata->u.vlan.sta); if (sta) sta_flags = get_sta_flags(sta); rcu_read_unlock(); if (sta) break; case NL80211_IFTYPE_AP: ra = skb->data; break; case NL80211_IFTYPE_WDS: ra = sdata->u.wds.remote_addr; break; #ifdef CONFIG_MAC80211_MESH case NL80211_IFTYPE_MESH_POINT: break; #endif case NL80211_IFTYPE_STATION: ra = sdata->u.mgd.bssid; break; case NL80211_IFTYPE_ADHOC: ra = skb->data; break; default: break; } if (!sta && ra && !is_multicast_ether_addr(ra)) { sta = sta_info_get(sdata, ra); if (sta) sta_flags = get_sta_flags(sta); } if (sta_flags & WLAN_STA_WME) qos = true; rcu_read_unlock(); if (!qos) { skb->priority = 0; /* required for correct WPA/11i MIC */ return ieee802_1d_to_ac[skb->priority]; } /* use the data classifier to determine what 802.1d tag the * data frame has */ skb->priority = cfg80211_classify8021d(skb); return ieee80211_downgrade_queue(local, skb); } u16 ieee80211_downgrade_queue(struct ieee80211_local *local, struct sk_buff *skb) { /* in case we are a client verify acm is not set for this ac */ while (unlikely(local->wmm_acm & BIT(skb->priority))) { if (wme_downgrade_ac(skb)) { break; } } /* look up which queue to use for frames with this 1d tag */ return ieee802_1d_to_ac[skb->priority]; } void ieee80211_set_qos_hdr(struct ieee80211_local *local, struct sk_buff *skb) { struct ieee80211_hdr *hdr = (void *)skb->data; /* Fill in the QoS header if there is one. */ if (ieee80211_is_data_qos(hdr->frame_control)) { u8 *p = ieee80211_get_qos_ctl(hdr); u8 ack_policy = 0, tid; tid = skb->priority & IEEE80211_QOS_CTL_TAG1D_MASK; if (unlikely(local->wifi_wme_noack_test)) ack_policy |= QOS_CONTROL_ACK_POLICY_NOACK << QOS_CONTROL_ACK_POLICY_SHIFT; /* qos header is 2 bytes, second reserved */ *p++ = ack_policy | tid; *p = 0; } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sigma-random/asuswrt-merlin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">release/src-rt-7.x.main/src/linux/linux-2.6.36/net/mac80211/wme.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,394</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086559"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* tuner-xc2028 * * Copyright (c) 2007-2008 Mauro Carvalho Chehab (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2cfc1cac7cac3c0e2cbccc4d0c3c6c7c3c68ccdd0c5">[email protected]</a>) * This code is placed under the terms of the GNU General Public License v2 */ #ifndef __TUNER_XC2028_H__ #define __TUNER_XC2028_H__ #include "dvb_frontend.h" #define XC2028_DEFAULT_FIRMWARE "xc3028-v27.fw" #define XC3028L_DEFAULT_FIRMWARE "xc3028L-v36.fw" /* Dmoduler IF (kHz) */ #define XC3028_FE_DEFAULT 0 /* Don't load SCODE */ #define XC3028_FE_LG60 6000 #define XC3028_FE_ATI638 6380 #define XC3028_FE_OREN538 5380 #define XC3028_FE_OREN36 3600 #define XC3028_FE_TOYOTA388 3880 #define XC3028_FE_TOYOTA794 7940 #define XC3028_FE_DIBCOM52 5200 #define XC3028_FE_ZARLINK456 4560 #define XC3028_FE_CHINA 5200 enum firmware_type { XC2028_AUTO = 0, /* By default, auto-detects */ XC2028_D2633, XC2028_D2620, }; struct xc2028_ctrl { char *fname; int max_len; int msleep; unsigned int scode_table; unsigned int mts :1; unsigned int input1:1; unsigned int vhfbw7:1; unsigned int uhfbw8:1; unsigned int disable_power_mgmt:1; unsigned int read_not_reliable:1; unsigned int demod; enum firmware_type type:2; }; struct xc2028_config { struct i2c_adapter *i2c_adap; u8 i2c_addr; struct xc2028_ctrl *ctrl; }; /* xc2028 commands for callback */ #define XC2028_TUNER_RESET 0 #define XC2028_RESET_CLK 1 #if defined(CONFIG_MEDIA_TUNER_XC2028) || (defined(CONFIG_MEDIA_TUNER_XC2028_MODULE) && \ defined(MODULE)) extern struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe, struct xc2028_config *cfg); #else static inline struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe, struct xc2028_config *cfg) { printk(KERN_INFO "%s: not probed - driver disabled by Kconfig\n", __func__); return NULL; } #endif #endif /* __TUNER_XC2028_H__ */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wkritzinger/asuswrt-merlin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/media/common/tuners/tuner-xc2028.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,827</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086560"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">#define PRISM2_PCCARD #include <linux/module.h> #include <linux/init.h> #include <linux/if.h> #include <linux/slab.h> #include <linux/wait.h> #include <linux/timer.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/workqueue.h> #include <linux/wireless.h> #include <net/iw_handler.h> #include <pcmcia/cistpl.h> #include <pcmcia/cisreg.h> #include <pcmcia/ds.h> #include <asm/io.h> #include "hostap_wlan.h" static char *dev_info = "hostap_cs"; MODULE_AUTHOR("Jouni Malinen"); MODULE_DESCRIPTION("Support for Intersil Prism2-based 802.11 wireless LAN " "cards (PC Card)."); MODULE_SUPPORTED_DEVICE("Intersil Prism2-based WLAN cards (PC Card)"); MODULE_LICENSE("GPL"); static int ignore_cis_vcc; module_param(ignore_cis_vcc, int, 0444); MODULE_PARM_DESC(ignore_cis_vcc, "Ignore broken CIS VCC entry"); /* struct local_info::hw_priv */ struct hostap_cs_priv { struct pcmcia_device *link; int sandisk_connectplus; }; #ifdef PRISM2_IO_DEBUG static inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v); outb(v, dev->base_addr + a); spin_unlock_irqrestore(&local->lock, flags); } static inline u8 hfa384x_inb_debug(struct net_device *dev, int a) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; u8 v; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); v = inb(dev->base_addr + a); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v); spin_unlock_irqrestore(&local->lock, flags); return v; } static inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v); outw(v, dev->base_addr + a); spin_unlock_irqrestore(&local->lock, flags); } static inline u16 hfa384x_inw_debug(struct net_device *dev, int a) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; u16 v; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); v = inw(dev->base_addr + a); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v); spin_unlock_irqrestore(&local->lock, flags); return v; } static inline void hfa384x_outsw_debug(struct net_device *dev, int a, u8 *buf, int wc) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc); outsw(dev->base_addr + a, buf, wc); spin_unlock_irqrestore(&local->lock, flags); } static inline void hfa384x_insw_debug(struct net_device *dev, int a, u8 *buf, int wc) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc); insw(dev->base_addr + a, buf, wc); spin_unlock_irqrestore(&local->lock, flags); } #define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v)) #define HFA384X_INB(a) hfa384x_inb_debug(dev, (a)) #define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v)) #define HFA384X_INW(a) hfa384x_inw_debug(dev, (a)) #define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc)) #define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc)) #else /* PRISM2_IO_DEBUG */ #define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a)) #define HFA384X_INB(a) inb(dev->base_addr + (a)) #define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a)) #define HFA384X_INW(a) inw(dev->base_addr + (a)) #define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc) #define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc) #endif /* PRISM2_IO_DEBUG */ static int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf, int len) { u16 d_off; u16 *pos; d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF; pos = (u16 *) buf; if (len / 2) HFA384X_INSW(d_off, buf, len / 2); pos += len / 2; if (len & 1) *((char *) pos) = HFA384X_INB(d_off); return 0; } static int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len) { u16 d_off; u16 *pos; d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF; pos = (u16 *) buf; if (len / 2) HFA384X_OUTSW(d_off, buf, len / 2); pos += len / 2; if (len & 1) HFA384X_OUTB(*((char *) pos), d_off); return 0; } /* FIX: This might change at some point.. */ #include "hostap_hw.c" static void prism2_detach(struct pcmcia_device *p_dev); static void prism2_release(u_long arg); static int prism2_config(struct pcmcia_device *link); static int prism2_pccard_card_present(local_info_t *local) { struct hostap_cs_priv *hw_priv = local->hw_priv; if (hw_priv != NULL && hw_priv->link != NULL && pcmcia_dev_present(hw_priv->link)) return 1; return 0; } /* * SanDisk CompactFlash WLAN Flashcard - Product Manual v1.0 * Document No. 20-10-00058, January 2004 * http://www.sandisk.com/pdf/industrial/ProdManualCFWLANv1.0.pdf */ #define SANDISK_WLAN_ACTIVATION_OFF 0x40 #define SANDISK_HCR_OFF 0x42 static void sandisk_set_iobase(local_info_t *local) { int res; struct hostap_cs_priv *hw_priv = local->hw_priv; res = pcmcia_write_config_byte(hw_priv->link, 0x10, hw_priv->link->resource[0]->start & 0x00ff); if (res != 0) { printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 0 -" " res=%d\n", res); } udelay(10); res = pcmcia_write_config_byte(hw_priv->link, 0x12, (hw_priv->link->resource[0]->start >> 8) & 0x00ff); if (res != 0) { printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 1 -" " res=%d\n", res); } } static void sandisk_write_hcr(local_info_t *local, int hcr) { struct net_device *dev = local->dev; int i; HFA384X_OUTB(0x80, SANDISK_WLAN_ACTIVATION_OFF); udelay(50); for (i = 0; i < 10; i++) { HFA384X_OUTB(hcr, SANDISK_HCR_OFF); } udelay(55); HFA384X_OUTB(0x45, SANDISK_WLAN_ACTIVATION_OFF); } static int sandisk_enable_wireless(struct net_device *dev) { int res, ret = 0; struct hostap_interface *iface = netdev_priv(dev); local_info_t *local = iface->local; struct hostap_cs_priv *hw_priv = local->hw_priv; if (resource_size(hw_priv->link->resource[0]) < 0x42) { /* Not enough ports to be SanDisk multi-function card */ ret = -ENODEV; goto done; } if (hw_priv->link->manf_id != 0xd601 || hw_priv->link->card_id != 0x0101) { /* No SanDisk manfid found */ ret = -ENODEV; goto done; } if (hw_priv->link->socket->functions < 2) { /* No multi-function links found */ ret = -ENODEV; goto done; } printk(KERN_DEBUG "%s: Multi-function SanDisk ConnectPlus detected" " - using vendor-specific initialization\n", dev->name); hw_priv->sandisk_connectplus = 1; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n", dev->name, res); goto done; } mdelay(5); /* * Do not enable interrupts here to avoid some bogus events. Interrupts * will be enabled during the first cor_sreset call. */ res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, (COR_LEVEL_REQ | 0x8 | COR_ADDR_DECODE | COR_FUNC_ENA)); if (res != 0) { printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n", dev->name, res); goto done; } mdelay(5); sandisk_set_iobase(local); HFA384X_OUTB(0xc5, SANDISK_WLAN_ACTIVATION_OFF); udelay(10); HFA384X_OUTB(0x4b, SANDISK_WLAN_ACTIVATION_OFF); udelay(10); done: return ret; } static void prism2_pccard_cor_sreset(local_info_t *local) { int res; u8 val; struct hostap_cs_priv *hw_priv = local->hw_priv; if (!prism2_pccard_card_present(local)) return; res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 1 (%d)\n", res); return; } printk(KERN_DEBUG "prism2_pccard_cor_sreset: original COR %02x\n", val); val |= COR_SOFT_RESET; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 2 (%d)\n", res); return; } mdelay(hw_priv->sandisk_connectplus ? 5 : 2); val &= ~COR_SOFT_RESET; if (hw_priv->sandisk_connectplus) val |= COR_IREQ_ENA; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 3 (%d)\n", res); return; } mdelay(hw_priv->sandisk_connectplus ? 5 : 2); if (hw_priv->sandisk_connectplus) sandisk_set_iobase(local); } static void prism2_pccard_genesis_reset(local_info_t *local, int hcr) { int res; u8 old_cor; struct hostap_cs_priv *hw_priv = local->hw_priv; if (!prism2_pccard_card_present(local)) return; if (hw_priv->sandisk_connectplus) { sandisk_write_hcr(local, hcr); return; } res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &old_cor); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 1 " "(%d)\n", res); return; } printk(KERN_DEBUG "prism2_pccard_genesis_sreset: original COR %02x\n", old_cor); res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, old_cor | COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 2 " "(%d)\n", res); return; } mdelay(10); /* Setup Genesis mode */ res = pcmcia_write_config_byte(hw_priv->link, CISREG_CCSR, hcr); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 3 " "(%d)\n", res); return; } mdelay(10); res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, old_cor & ~COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 4 " "(%d)\n", res); return; } mdelay(10); } static struct prism2_helper_functions prism2_pccard_funcs = { .card_present = prism2_pccard_card_present, .cor_sreset = prism2_pccard_cor_sreset, .genesis_reset = prism2_pccard_genesis_reset, .hw_type = HOSTAP_HW_PCCARD, }; /* allocate local data and register with CardServices * initialize dev_link structure, but do not configure the card yet */ static int hostap_cs_probe(struct pcmcia_device *p_dev) { int ret; PDEBUG(DEBUG_HW, "%s: setting Vcc=33 (constant)\n", dev_info); ret = prism2_config(p_dev); if (ret) { PDEBUG(DEBUG_EXTRA, "prism2_config() failed\n"); } return ret; } static void prism2_detach(struct pcmcia_device *link) { PDEBUG(DEBUG_FLOW, "prism2_detach\n"); prism2_release((u_long)link); /* release net devices */ if (link->priv) { struct hostap_cs_priv *hw_priv; struct net_device *dev; struct hostap_interface *iface; dev = link->priv; iface = netdev_priv(dev); hw_priv = iface->local->hw_priv; prism2_free_local_data(dev); kfree(hw_priv); } } static int prism2_config_check(struct pcmcia_device *p_dev, void *priv_data) { if (p_dev->config_index == 0) return -EINVAL; return pcmcia_request_io(p_dev); } static int prism2_config(struct pcmcia_device *link) { struct net_device *dev; struct hostap_interface *iface; local_info_t *local; int ret = 1; struct hostap_cs_priv *hw_priv; unsigned long flags; PDEBUG(DEBUG_FLOW, "prism2_config()\n"); hw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL); if (hw_priv == NULL) { ret = -ENOMEM; goto failed; } /* Look for an appropriate configuration table entry in the CIS */ link->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_AUDIO | CONF_AUTO_CHECK_VCC | CONF_AUTO_SET_IO | CONF_ENABLE_IRQ; if (ignore_cis_vcc) link->config_flags &= ~CONF_AUTO_CHECK_VCC; ret = pcmcia_loop_config(link, prism2_config_check, NULL); if (ret) { if (!ignore_cis_vcc) printk(KERN_ERR "GetNextTuple(): No matching " "CIS configuration. Maybe you need the " "ignore_cis_vcc=1 parameter.\n"); goto failed; } /* Need to allocate net_device before requesting IRQ handler */ dev = prism2_init_local_data(&prism2_pccard_funcs, 0, &link->dev); if (dev == NULL) goto failed; link->priv = dev; iface = netdev_priv(dev); local = iface->local; local->hw_priv = hw_priv; hw_priv->link = link; /* * Make sure the IRQ handler cannot proceed until at least * dev->base_addr is initialized. */ spin_lock_irqsave(&local->irq_init_lock, flags); ret = pcmcia_request_irq(link, prism2_interrupt); if (ret) goto failed_unlock; ret = pcmcia_enable_device(link); if (ret) goto failed_unlock; dev->irq = link->irq; dev->base_addr = link->resource[0]->start; spin_unlock_irqrestore(&local->irq_init_lock, flags); local->shutdown = 0; sandisk_enable_wireless(dev); ret = prism2_hw_config(dev, 1); if (!ret) ret = hostap_hw_ready(dev); return ret; failed_unlock: spin_unlock_irqrestore(&local->irq_init_lock, flags); failed: kfree(hw_priv); prism2_release((u_long)link); return ret; } static void prism2_release(u_long arg) { struct pcmcia_device *link = (struct pcmcia_device *)arg; PDEBUG(DEBUG_FLOW, "prism2_release\n"); if (link->priv) { struct net_device *dev = link->priv; struct hostap_interface *iface; iface = netdev_priv(dev); prism2_hw_shutdown(dev, 0); iface->local->shutdown = 1; } pcmcia_disable_device(link); PDEBUG(DEBUG_FLOW, "release - done\n"); } static int hostap_cs_suspend(struct pcmcia_device *link) { struct net_device *dev = (struct net_device *) link->priv; int dev_open = 0; struct hostap_interface *iface = NULL; if (!dev) return -ENODEV; iface = netdev_priv(dev); PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_SUSPEND\n", dev_info); if (iface && iface->local) dev_open = iface->local->num_dev_open > 0; if (dev_open) { netif_stop_queue(dev); netif_device_detach(dev); } prism2_suspend(dev); return 0; } static int hostap_cs_resume(struct pcmcia_device *link) { struct net_device *dev = (struct net_device *) link->priv; int dev_open = 0; struct hostap_interface *iface = NULL; if (!dev) return -ENODEV; iface = netdev_priv(dev); PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_RESUME\n", dev_info); if (iface && iface->local) dev_open = iface->local->num_dev_open > 0; prism2_hw_shutdown(dev, 1); prism2_hw_config(dev, dev_open ? 0 : 1); if (dev_open) { netif_device_attach(dev); netif_start_queue(dev); } return 0; } static struct pcmcia_device_id hostap_cs_ids[] = { PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7100), PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7300), PCMCIA_DEVICE_MANF_CARD(0x0101, 0x0777), PCMCIA_DEVICE_MANF_CARD(0x0126, 0x8000), PCMCIA_DEVICE_MANF_CARD(0x0138, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x01bf, 0x3301), PCMCIA_DEVICE_MANF_CARD(0x0250, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x026f, 0x030b), PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1612), PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1613), PCMCIA_DEVICE_MANF_CARD(0x028a, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x02aa, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x02d2, 0x0001), PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x0001), PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x7300), /* PCMCIA_DEVICE_MANF_CARD(0xc00f, 0x0000), conflict with pcnet_cs */ PCMCIA_DEVICE_MANF_CARD(0xc250, 0x0002), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0002), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0005), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0010), PCMCIA_DEVICE_MANF_CARD(0x0126, 0x0002), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0xd601, 0x0005, "ADLINK 345 CF", 0x2d858104), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "INTERSIL", 0x74c5e40d), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "Intersil", 0x4b801a17), PCMCIA_MFC_DEVICE_PROD_ID12(0, "SanDisk", "ConnectPlus", 0x7a954bd9, 0x74be00c6), PCMCIA_DEVICE_PROD_ID123( "Addtron", "AWP-100 Wireless PCMCIA", "Version 01.02", 0xe6ec52ce, 0x08649af2, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "D", "Link DWL-650 11Mbps WLAN Card", "Version 01.02", 0x71b18589, 0xb6f1b0ab, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "Instant Wireless ", " Network PC CARD", "Version 01.02", 0x11d901af, 0x6e9bd926, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "SMC", "SMC2632W", "Version 01.02", 0xc4f8b18b, 0x474a1f2a, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID12("BUFFALO", "WLI-CF-S11G", 0x2decece3, 0x82067c18), PCMCIA_DEVICE_PROD_ID12("Compaq", "WL200_11Mbps_Wireless_PCI_Card", 0x54f7c49c, 0x15a75e5b), PCMCIA_DEVICE_PROD_ID12("INTERSIL", "HFA384x/IEEE", 0x74c5e40d, 0xdb472a18), PCMCIA_DEVICE_PROD_ID12("Linksys", "Wireless CompactFlash Card", 0x0733cc81, 0x0c52f395), PCMCIA_DEVICE_PROD_ID12( "ZoomAir 11Mbps High", "Rate wireless Networking", 0x273fe3db, 0x32a1eaee), PCMCIA_DEVICE_PROD_ID123( "Pretec", "CompactWLAN Card 802.11b", "2.5", 0x1cadd3e5, 0xe697636c, 0x7a5bfcf1), PCMCIA_DEVICE_PROD_ID123( "U.S. Robotics", "IEEE 802.11b PC-CARD", "Version 01.02", 0xc7b8df9d, 0x1700d087, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "Allied Telesyn", "AT-WCL452 Wireless PCMCIA Radio", "Ver. 1.00", 0x5cd01705, 0x4271660f, 0x9d08ee12), PCMCIA_DEVICE_PROD_ID123( "Wireless LAN" , "11Mbps PC Card", "Version 01.02", 0x4b8870ff, 0x70e946d1, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID3("HFA3863", 0x355cb092), PCMCIA_DEVICE_PROD_ID3("ISL37100P", 0x630d52b2), PCMCIA_DEVICE_PROD_ID3("ISL37101P-10", 0xdd97a26b), PCMCIA_DEVICE_PROD_ID3("ISL37300P", 0xc9049a39), PCMCIA_DEVICE_NULL }; MODULE_DEVICE_TABLE(pcmcia, hostap_cs_ids); static struct pcmcia_driver hostap_driver = { .name = "hostap_cs", .probe = hostap_cs_probe, .remove = prism2_detach, .owner = THIS_MODULE, .id_table = hostap_cs_ids, .suspend = hostap_cs_suspend, .resume = hostap_cs_resume, }; static int __init init_prism2_pccard(void) { return pcmcia_register_driver(&hostap_driver); } static void __exit exit_prism2_pccard(void) { pcmcia_unregister_driver(&hostap_driver); } module_init(init_prism2_pccard); module_exit(exit_prism2_pccard); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">nazgee/igep-kernel</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/net/wireless/hostap/hostap_cs.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">18,243</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086561"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import frappe def execute(): duplicates = frappe.db.sql("""select email_group, email, count(name) from `tabEmail Group Member` group by email_group, email having count(name) > 1""") # delete all duplicates except 1 for email_group, email, count in duplicates: frappe.db.sql("""delete from `tabEmail Group Member` where email_group=%s and email=%s limit %s""", (email_group, email, count-1)) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">hassanibi/erpnext</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">erpnext/patches/v6_2/remove_newsletter_duplicates.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">407</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086562"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">import { Subscriber } from '../Subscriber'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; /** * Compares all values of two observables in sequence using an optional comparor function * and returns an observable of a single boolean value representing whether or not the two sequences * are equal. * * <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span> * * <img src="./img/sequenceEqual.png" width="100%"> * * `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the * observables completes, the operator will wait for the other observable to complete; If the other * observable emits before completing, the returned observable will emit `false` and complete. If one observable never * completes or emits after the other complets, the returned observable will never complete. * * @example <caption>figure out if the Konami code matches</caption> * var code = Rx.Observable.from([ * "ArrowUp", * "ArrowUp", * "ArrowDown", * "ArrowDown", * "ArrowLeft", * "ArrowRight", * "ArrowLeft", * "ArrowRight", * "KeyB", * "KeyA", * "Enter" // no start key, clearly. * ]); * * var keys = Rx.Observable.fromEvent(document, 'keyup') * .map(e => e.code); * var matches = keys.bufferCount(11, 1) * .mergeMap( * last11 => * Rx.Observable.from(last11) * .sequenceEqual(code) * ); * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched)); * * @see {@link combineLatest} * @see {@link zip} * @see {@link withLatestFrom} * * @param {Observable} compareTo The observable sequence to compare the source sequence to. * @param {function} [comparor] An optional function to compare each value pair * @return {Observable} An Observable of a single boolean value representing whether or not * the values emitted by both observables were equal in sequence. * @method sequenceEqual * @owner Observable */ export function sequenceEqual(compareTo, comparor) { return (source) => source.lift(new SequenceEqualOperator(compareTo, comparor)); } export class SequenceEqualOperator { constructor(compareTo, comparor) { this.compareTo = compareTo; this.comparor = comparor; } call(subscriber, source) { return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export class SequenceEqualSubscriber extends Subscriber { constructor(destination, compareTo, comparor) { super(destination); this.compareTo = compareTo; this.comparor = comparor; this._a = []; this._b = []; this._oneComplete = false; this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this))); } _next(value) { if (this._oneComplete && this._b.length === 0) { this.emit(false); } else { this._a.push(value); this.checkValues(); } } _complete() { if (this._oneComplete) { this.emit(this._a.length === 0 && this._b.length === 0); } else { this._oneComplete = true; } } checkValues() { const { _a, _b, comparor } = this; while (_a.length > 0 && _b.length > 0) { let a = _a.shift(); let b = _b.shift(); let areEqual = false; if (comparor) { areEqual = tryCatch(comparor)(a, b); if (areEqual === errorObject) { this.destination.error(errorObject.e); } } else { areEqual = a === b; } if (!areEqual) { this.emit(false); } } } emit(value) { const { destination } = this; destination.next(value); destination.complete(); } nextB(value) { if (this._oneComplete && this._a.length === 0) { this.emit(false); } else { this._b.push(value); this.checkValues(); } } } class SequenceEqualCompareToSubscriber extends Subscriber { constructor(destination, parent) { super(destination); this.parent = parent; } _next(value) { this.parent.nextB(value); } _error(err) { this.parent.error(err); } _complete() { this.parent._complete(); } } //# sourceMappingURL=sequenceEqual.js.map</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">rospilot/rospilot</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operators/sequenceEqual.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,896</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086563"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright 2018 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 aws_ebs import ( "fmt" "path/filepath" "strconv" "strings" "github.com/golang/glog" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/kubernetes/pkg/cloudprovider/providers/aws" "k8s.io/kubernetes/pkg/util/mount" kstrings "k8s.io/kubernetes/pkg/util/strings" "k8s.io/kubernetes/pkg/volume" "k8s.io/kubernetes/pkg/volume/util" "k8s.io/kubernetes/pkg/volume/util/volumepathhandler" ) var _ volume.VolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.PersistentVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.BlockVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.DeletableVolumePlugin = &awsElasticBlockStorePlugin{} var _ volume.ProvisionableVolumePlugin = &awsElasticBlockStorePlugin{} func (plugin *awsElasticBlockStorePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) { pluginDir := plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName) blkutil := volumepathhandler.NewBlockVolumePathHandler() globalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID) if err != nil { return nil, err } glog.V(5).Infof("globalMapPathUUID: %s", globalMapPathUUID) globalMapPath := filepath.Dir(globalMapPathUUID) if len(globalMapPath) <= 1 { return nil, fmt.Errorf("failed to get volume plugin information from globalMapPathUUID: %v", globalMapPathUUID) } return getVolumeSpecFromGlobalMapPath(globalMapPath) } func getVolumeSpecFromGlobalMapPath(globalMapPath string) (*volume.Spec, error) { // Get volume spec information from globalMapPath // globalMapPath example: // plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID} // plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX vID := filepath.Base(globalMapPath) if len(vID) <= 1 { return nil, fmt.Errorf("failed to get volumeID from global path=%s", globalMapPath) } if !strings.Contains(vID, "vol-") { return nil, fmt.Errorf("failed to get volumeID from global path=%s, invalid volumeID format = %s", globalMapPath, vID) } block := v1.PersistentVolumeBlock awsVolume := &v1.PersistentVolume{ Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: vID, }, }, VolumeMode: &block, }, } return volume.NewSpecFromPersistentVolume(awsVolume, true), nil } // NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification. func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) { // If this is called via GenerateUnmapDeviceFunc(), pod is nil. // Pass empty string as dummy uid since uid isn't used in the case. var uid types.UID if pod != nil { uid = pod.UID } return plugin.newBlockVolumeMapperInternal(spec, uid, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName())) } func (plugin *awsElasticBlockStorePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) { ebs, readOnly, err := getVolumeSource(spec) if err != nil { return nil, err } volumeID := aws.KubernetesVolumeID(ebs.VolumeID) partition := "" if ebs.Partition != 0 { partition = strconv.Itoa(int(ebs.Partition)) } return &awsElasticBlockStoreMapper{ awsElasticBlockStore: &awsElasticBlockStore{ podUID: podUID, volName: spec.Name(), volumeID: volumeID, partition: partition, manager: manager, mounter: mounter, plugin: plugin, }, readOnly: readOnly}, nil } func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) { return plugin.newUnmapperInternal(volName, podUID, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName())) } func (plugin *awsElasticBlockStorePlugin) newUnmapperInternal(volName string, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeUnmapper, error) { return &awsElasticBlockStoreUnmapper{ awsElasticBlockStore: &awsElasticBlockStore{ podUID: podUID, volName: volName, manager: manager, mounter: mounter, plugin: plugin, }}, nil } func (c *awsElasticBlockStoreUnmapper) TearDownDevice(mapPath, devicePath string) error { return nil } type awsElasticBlockStoreUnmapper struct { *awsElasticBlockStore } var _ volume.BlockVolumeUnmapper = &awsElasticBlockStoreUnmapper{} type awsElasticBlockStoreMapper struct { *awsElasticBlockStore readOnly bool } var _ volume.BlockVolumeMapper = &awsElasticBlockStoreMapper{} func (b *awsElasticBlockStoreMapper) SetUpDevice() (string, error) { return "", nil } func (b *awsElasticBlockStoreMapper) MapDevice(devicePath, globalMapPath, volumeMapPath, volumeMapName string, podUID types.UID) error { return util.MapBlockVolume(devicePath, globalMapPath, volumeMapPath, volumeMapName, podUID) } // GetGlobalMapPath returns global map path and error // path: plugins/kubernetes.io/{PluginName}/volumeDevices/volumeID // plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX func (ebs *awsElasticBlockStore) GetGlobalMapPath(spec *volume.Spec) (string, error) { volumeSource, _, err := getVolumeSource(spec) if err != nil { return "", err } return filepath.Join(ebs.plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName), string(volumeSource.VolumeID)), nil } // GetPodDeviceMapPath returns pod device map path and volume name // path: pods/{podUid}/volumeDevices/kubernetes.io~aws func (ebs *awsElasticBlockStore) GetPodDeviceMapPath() (string, string) { name := awsElasticBlockStorePluginName return ebs.plugin.host.GetPodVolumeDeviceDir(ebs.podUID, kstrings.EscapeQualifiedNameForDisk(name)), ebs.volName } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wjiangjay/origin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs_block.go</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">GO</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">6,460</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086564"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/session_factory.h" #include <unordered_map> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/protobuf/config.pb_text.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { namespace { static mutex* get_session_factory_lock() { static mutex session_factory_lock; return &session_factory_lock; } typedef std::unordered_map<string, SessionFactory*> SessionFactories; SessionFactories* session_factories() { static SessionFactories* factories = new SessionFactories; return factories; } } // namespace void SessionFactory::Register(const string& runtime_type, SessionFactory* factory) { mutex_lock l(*get_session_factory_lock()); if (!session_factories()->insert({runtime_type, factory}).second) { LOG(ERROR) << "Two session factories are being registered " << "under" << runtime_type; } } namespace { const string RegisteredFactoriesErrorMessageLocked() { std::vector<string> factory_types; for (const auto& session_factory : *session_factories()) { factory_types.push_back(session_factory.first); } return strings::StrCat("Registered factories are {", str_util::Join(factory_types, ", "), "}."); } string SessionOptionsToString(const SessionOptions& options) { return strings::StrCat("target: \"", options.target, "\" config: ", ProtoShortDebugString(options.config)); } } // namespace Status SessionFactory::GetFactory(const SessionOptions& options, SessionFactory** out_factory) { mutex_lock l(*get_session_factory_lock()); // could use reader lock std::vector<std::pair<string, SessionFactory*>> candidate_factories; for (const auto& session_factory : *session_factories()) { if (session_factory.second->AcceptsOptions(options)) { VLOG(2) << "SessionFactory type " << session_factory.first << " accepts target: " << options.target; candidate_factories.push_back(session_factory); } else { VLOG(2) << "SessionFactory type " << session_factory.first << " does not accept target: " << options.target; } } if (candidate_factories.size() == 1) { *out_factory = candidate_factories[0].second; return Status::OK(); } else if (candidate_factories.size() > 1) { // NOTE(mrry): This implementation assumes that the domains (in // terms of acceptable SessionOptions) of the registered // SessionFactory implementations do not overlap. This is fine for // now, but we may need an additional way of distinguishing // different runtimes (such as an additional session option) if // the number of sessions grows. // TODO(mrry): Consider providing a system-default fallback option // in this case. std::vector<string> factory_types; factory_types.reserve(candidate_factories.size()); for (const auto& candidate_factory : candidate_factories) { factory_types.push_back(candidate_factory.first); } return errors::Internal( "Multiple session factories registered for the given session " "options: {", SessionOptionsToString(options), "} Candidate factories are {", str_util::Join(factory_types, ", "), "}. ", RegisteredFactoriesErrorMessageLocked()); } else { return errors::NotFound( "No session factory registered for the given session options: {", SessionOptionsToString(options), "} ", RegisteredFactoriesErrorMessageLocked()); } } } // namespace tensorflow </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">npuichigo/ttsflow</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/tensorflow/tensorflow/core/common_runtime/session_factory.cc</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C++</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,469</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086565"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // var mocha = require('mocha'); var should = require('should'); var sinon = require('sinon'); var _ = require('underscore'); // Test includes var testutil = require('../util/util'); // Lib includes var util = testutil.libRequire('util/utils'); var GetCommand = require('./util-GetCommand.js'); describe('HDInsight list command (under unit test)', function() { after(function (done) { done(); }); // NOTE: To Do, we should actually create new accounts for our tests // So that we can work on any existing subscription. before (function (done) { done(); }); it('should call startProgress with the correct statement', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.user.startProgress.firstCall.args[0].should.be.equal('Getting HDInsight servers'); done(); }); it('should call listClusters with the supplied subscriptionId (when none is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({}, _); command.processor.listClusters.firstCall.should.not.equal(null); (command.processor.listClusters.firstCall.args[0] === undefined).should.equal(true); done(); }); it('should call listClusters with the supplied subscriptionId (when one is supplied)', function(done) { var command = new GetCommand(); command.hdinsight.listClustersCommand.should.not.equal(null); command.hdinsight.listClustersCommand({ subscription: 'test1' }, _); command.processor.listClusters.firstCall.should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.not.equal(null); command.processor.listClusters.firstCall.args[0].should.be.equal('test1'); done(); }); });</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Nepomuceno/azure-xplat-cli</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">test/hdinsight/unit-list-command.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,528</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086566"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (C) 2009 - QLogic Corporation. * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; 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. * * The full GNU General Public License is included in this distribution * in the file called "COPYING". * */ #include "qlcnic.h" #include <linux/slab.h> #include <net/ip.h> #define MASK(n) ((1ULL<<(n))-1) #define OCM_WIN_P3P(addr) (addr & 0xffc0000) #define GET_MEM_OFFS_2M(addr) (addr & MASK(18)) #define CRB_BLK(off) ((off >> 20) & 0x3f) #define CRB_SUBBLK(off) ((off >> 16) & 0xf) #define CRB_WINDOW_2M (0x130060) #define CRB_HI(off) ((crb_hub_agt[CRB_BLK(off)] << 20) | ((off) & 0xf0000)) #define CRB_INDIRECT_2M (0x1e0000UL) #ifndef readq static inline u64 readq(void __iomem *addr) { return readl(addr) | (((u64) readl(addr + 4)) << 32LL); } #endif #ifndef writeq static inline void writeq(u64 val, void __iomem *addr) { writel(((u32) (val)), (addr)); writel(((u32) (val >> 32)), (addr + 4)); } #endif #define ADDR_IN_RANGE(addr, low, high) \ (((addr) < (high)) && ((addr) >= (low))) #define PCI_OFFSET_FIRST_RANGE(adapter, off) \ ((adapter)->ahw.pci_base0 + (off)) static void __iomem *pci_base_offset(struct qlcnic_adapter *adapter, unsigned long off) { if (ADDR_IN_RANGE(off, FIRST_PAGE_GROUP_START, FIRST_PAGE_GROUP_END)) return PCI_OFFSET_FIRST_RANGE(adapter, off); return NULL; } static const struct crb_128M_2M_block_map crb_128M_2M_map[64] __cacheline_aligned_in_smp = { {{{0, 0, 0, 0} } }, /* 0: PCI */ {{{1, 0x0100000, 0x0102000, 0x120000}, /* 1: PCIE */ {1, 0x0110000, 0x0120000, 0x130000}, {1, 0x0120000, 0x0122000, 0x124000}, {1, 0x0130000, 0x0132000, 0x126000}, {1, 0x0140000, 0x0142000, 0x128000}, {1, 0x0150000, 0x0152000, 0x12a000}, {1, 0x0160000, 0x0170000, 0x110000}, {1, 0x0170000, 0x0172000, 0x12e000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {1, 0x01e0000, 0x01e0800, 0x122000}, {0, 0x0000000, 0x0000000, 0x000000} } }, {{{1, 0x0200000, 0x0210000, 0x180000} } },/* 2: MN */ {{{0, 0, 0, 0} } }, /* 3: */ {{{1, 0x0400000, 0x0401000, 0x169000} } },/* 4: P2NR1 */ {{{1, 0x0500000, 0x0510000, 0x140000} } },/* 5: SRE */ {{{1, 0x0600000, 0x0610000, 0x1c0000} } },/* 6: NIU */ {{{1, 0x0700000, 0x0704000, 0x1b8000} } },/* 7: QM */ {{{1, 0x0800000, 0x0802000, 0x170000}, /* 8: SQM0 */ {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {1, 0x08f0000, 0x08f2000, 0x172000} } }, {{{1, 0x0900000, 0x0902000, 0x174000}, /* 9: SQM1*/ {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {1, 0x09f0000, 0x09f2000, 0x176000} } }, {{{0, 0x0a00000, 0x0a02000, 0x178000}, /* 10: SQM2*/ {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {1, 0x0af0000, 0x0af2000, 0x17a000} } }, {{{0, 0x0b00000, 0x0b02000, 0x17c000}, /* 11: SQM3*/ {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {1, 0x0bf0000, 0x0bf2000, 0x17e000} } }, {{{1, 0x0c00000, 0x0c04000, 0x1d4000} } },/* 12: I2Q */ {{{1, 0x0d00000, 0x0d04000, 0x1a4000} } },/* 13: TMR */ {{{1, 0x0e00000, 0x0e04000, 0x1a0000} } },/* 14: ROMUSB */ {{{1, 0x0f00000, 0x0f01000, 0x164000} } },/* 15: PEG4 */ {{{0, 0x1000000, 0x1004000, 0x1a8000} } },/* 16: XDMA */ {{{1, 0x1100000, 0x1101000, 0x160000} } },/* 17: PEG0 */ {{{1, 0x1200000, 0x1201000, 0x161000} } },/* 18: PEG1 */ {{{1, 0x1300000, 0x1301000, 0x162000} } },/* 19: PEG2 */ {{{1, 0x1400000, 0x1401000, 0x163000} } },/* 20: PEG3 */ {{{1, 0x1500000, 0x1501000, 0x165000} } },/* 21: P2ND */ {{{1, 0x1600000, 0x1601000, 0x166000} } },/* 22: P2NI */ {{{0, 0, 0, 0} } }, /* 23: */ {{{0, 0, 0, 0} } }, /* 24: */ {{{0, 0, 0, 0} } }, /* 25: */ {{{0, 0, 0, 0} } }, /* 26: */ {{{0, 0, 0, 0} } }, /* 27: */ {{{0, 0, 0, 0} } }, /* 28: */ {{{1, 0x1d00000, 0x1d10000, 0x190000} } },/* 29: MS */ {{{1, 0x1e00000, 0x1e01000, 0x16a000} } },/* 30: P2NR2 */ {{{1, 0x1f00000, 0x1f10000, 0x150000} } },/* 31: EPG */ {{{0} } }, /* 32: PCI */ {{{1, 0x2100000, 0x2102000, 0x120000}, /* 33: PCIE */ {1, 0x2110000, 0x2120000, 0x130000}, {1, 0x2120000, 0x2122000, 0x124000}, {1, 0x2130000, 0x2132000, 0x126000}, {1, 0x2140000, 0x2142000, 0x128000}, {1, 0x2150000, 0x2152000, 0x12a000}, {1, 0x2160000, 0x2170000, 0x110000}, {1, 0x2170000, 0x2172000, 0x12e000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000}, {0, 0x0000000, 0x0000000, 0x000000} } }, {{{1, 0x2200000, 0x2204000, 0x1b0000} } },/* 34: CAM */ {{{0} } }, /* 35: */ {{{0} } }, /* 36: */ {{{0} } }, /* 37: */ {{{0} } }, /* 38: */ {{{0} } }, /* 39: */ {{{1, 0x2800000, 0x2804000, 0x1a4000} } },/* 40: TMR */ {{{1, 0x2900000, 0x2901000, 0x16b000} } },/* 41: P2NR3 */ {{{1, 0x2a00000, 0x2a00400, 0x1ac400} } },/* 42: RPMX1 */ {{{1, 0x2b00000, 0x2b00400, 0x1ac800} } },/* 43: RPMX2 */ {{{1, 0x2c00000, 0x2c00400, 0x1acc00} } },/* 44: RPMX3 */ {{{1, 0x2d00000, 0x2d00400, 0x1ad000} } },/* 45: RPMX4 */ {{{1, 0x2e00000, 0x2e00400, 0x1ad400} } },/* 46: RPMX5 */ {{{1, 0x2f00000, 0x2f00400, 0x1ad800} } },/* 47: RPMX6 */ {{{1, 0x3000000, 0x3000400, 0x1adc00} } },/* 48: RPMX7 */ {{{0, 0x3100000, 0x3104000, 0x1a8000} } },/* 49: XDMA */ {{{1, 0x3200000, 0x3204000, 0x1d4000} } },/* 50: I2Q */ {{{1, 0x3300000, 0x3304000, 0x1a0000} } },/* 51: ROMUSB */ {{{0} } }, /* 52: */ {{{1, 0x3500000, 0x3500400, 0x1ac000} } },/* 53: RPMX0 */ {{{1, 0x3600000, 0x3600400, 0x1ae000} } },/* 54: RPMX8 */ {{{1, 0x3700000, 0x3700400, 0x1ae400} } },/* 55: RPMX9 */ {{{1, 0x3800000, 0x3804000, 0x1d0000} } },/* 56: OCM0 */ {{{1, 0x3900000, 0x3904000, 0x1b4000} } },/* 57: CRYPTO */ {{{1, 0x3a00000, 0x3a04000, 0x1d8000} } },/* 58: SMB */ {{{0} } }, /* 59: I2C0 */ {{{0} } }, /* 60: I2C1 */ {{{1, 0x3d00000, 0x3d04000, 0x1d8000} } },/* 61: LPC */ {{{1, 0x3e00000, 0x3e01000, 0x167000} } },/* 62: P2NC */ {{{1, 0x3f00000, 0x3f01000, 0x168000} } } /* 63: P2NR0 */ }; /* * top 12 bits of crb internal address (hub, agent) */ static const unsigned crb_hub_agt[64] = { 0, QLCNIC_HW_CRB_HUB_AGT_ADR_PS, QLCNIC_HW_CRB_HUB_AGT_ADR_MN, QLCNIC_HW_CRB_HUB_AGT_ADR_MS, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_SRE, QLCNIC_HW_CRB_HUB_AGT_ADR_NIU, QLCNIC_HW_CRB_HUB_AGT_ADR_QMN, QLCNIC_HW_CRB_HUB_AGT_ADR_SQN0, QLCNIC_HW_CRB_HUB_AGT_ADR_SQN1, QLCNIC_HW_CRB_HUB_AGT_ADR_SQN2, QLCNIC_HW_CRB_HUB_AGT_ADR_SQN3, QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q, QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR, QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB, QLCNIC_HW_CRB_HUB_AGT_ADR_PGN4, QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA, QLCNIC_HW_CRB_HUB_AGT_ADR_PGN0, QLCNIC_HW_CRB_HUB_AGT_ADR_PGN1, QLCNIC_HW_CRB_HUB_AGT_ADR_PGN2, QLCNIC_HW_CRB_HUB_AGT_ADR_PGN3, QLCNIC_HW_CRB_HUB_AGT_ADR_PGND, QLCNIC_HW_CRB_HUB_AGT_ADR_PGNI, QLCNIC_HW_CRB_HUB_AGT_ADR_PGS0, QLCNIC_HW_CRB_HUB_AGT_ADR_PGS1, QLCNIC_HW_CRB_HUB_AGT_ADR_PGS2, QLCNIC_HW_CRB_HUB_AGT_ADR_PGS3, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_PGSI, QLCNIC_HW_CRB_HUB_AGT_ADR_SN, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_EG, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_PS, QLCNIC_HW_CRB_HUB_AGT_ADR_CAM, 0, 0, 0, 0, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX1, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX2, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX3, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX4, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX5, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX6, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX7, QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA, QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q, QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX0, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX8, QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX9, QLCNIC_HW_CRB_HUB_AGT_ADR_OCM0, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_SMB, QLCNIC_HW_CRB_HUB_AGT_ADR_I2C0, QLCNIC_HW_CRB_HUB_AGT_ADR_I2C1, 0, QLCNIC_HW_CRB_HUB_AGT_ADR_PGNC, 0, }; /* PCI Windowing for DDR regions. */ #define QLCNIC_PCIE_SEM_TIMEOUT 10000 int qlcnic_pcie_sem_lock(struct qlcnic_adapter *adapter, int sem, u32 id_reg) { int done = 0, timeout = 0; while (!done) { done = QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_LOCK(sem))); if (done == 1) break; if (++timeout >= QLCNIC_PCIE_SEM_TIMEOUT) return -EIO; msleep(1); } if (id_reg) QLCWR32(adapter, id_reg, adapter->portnum); return 0; } void qlcnic_pcie_sem_unlock(struct qlcnic_adapter *adapter, int sem) { QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_UNLOCK(sem))); } static int qlcnic_send_cmd_descs(struct qlcnic_adapter *adapter, struct cmd_desc_type0 *cmd_desc_arr, int nr_desc) { u32 i, producer, consumer; struct qlcnic_cmd_buffer *pbuf; struct cmd_desc_type0 *cmd_desc; struct qlcnic_host_tx_ring *tx_ring; i = 0; if (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC) return -EIO; tx_ring = adapter->tx_ring; __netif_tx_lock_bh(tx_ring->txq); producer = tx_ring->producer; consumer = tx_ring->sw_consumer; if (nr_desc >= qlcnic_tx_avail(tx_ring)) { netif_tx_stop_queue(tx_ring->txq); __netif_tx_unlock_bh(tx_ring->txq); adapter->stats.xmit_off++; return -EBUSY; } do { cmd_desc = &cmd_desc_arr[i]; pbuf = &tx_ring->cmd_buf_arr[producer]; pbuf->skb = NULL; pbuf->frag_count = 0; memcpy(&tx_ring->desc_head[producer], &cmd_desc_arr[i], sizeof(struct cmd_desc_type0)); producer = get_next_index(producer, tx_ring->num_desc); i++; } while (i != nr_desc); tx_ring->producer = producer; qlcnic_update_cmd_producer(adapter, tx_ring); __netif_tx_unlock_bh(tx_ring->txq); return 0; } static int qlcnic_sre_macaddr_change(struct qlcnic_adapter *adapter, u8 *addr, unsigned op) { struct qlcnic_nic_req req; struct qlcnic_mac_req *mac_req; u64 word; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_REQUEST << 23); word = QLCNIC_MAC_EVENT | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); mac_req = (struct qlcnic_mac_req *)&req.words[0]; mac_req->op = op; memcpy(mac_req->mac_addr, addr, 6); return qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); } static int qlcnic_nic_add_mac(struct qlcnic_adapter *adapter, u8 *addr) { struct list_head *head; struct qlcnic_mac_list_s *cur; /* look up if already exists */ list_for_each(head, &adapter->mac_list) { cur = list_entry(head, struct qlcnic_mac_list_s, list); if (memcmp(addr, cur->mac_addr, ETH_ALEN) == 0) return 0; } cur = kzalloc(sizeof(struct qlcnic_mac_list_s), GFP_ATOMIC); if (cur == NULL) { dev_err(&adapter->netdev->dev, "failed to add mac address filter\n"); return -ENOMEM; } memcpy(cur->mac_addr, addr, ETH_ALEN); list_add_tail(&cur->list, &adapter->mac_list); return qlcnic_sre_macaddr_change(adapter, cur->mac_addr, QLCNIC_MAC_ADD); } void qlcnic_set_multi(struct net_device *netdev) { struct qlcnic_adapter *adapter = netdev_priv(netdev); struct dev_mc_list *mc_ptr; u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; u32 mode = VPORT_MISS_MODE_DROP; if (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC) return; qlcnic_nic_add_mac(adapter, adapter->mac_addr); qlcnic_nic_add_mac(adapter, bcast_addr); if (netdev->flags & IFF_PROMISC) { mode = VPORT_MISS_MODE_ACCEPT_ALL; goto send_fw_cmd; } if ((netdev->flags & IFF_ALLMULTI) || (netdev_mc_count(netdev) > adapter->max_mc_count)) { mode = VPORT_MISS_MODE_ACCEPT_MULTI; goto send_fw_cmd; } if (!netdev_mc_empty(netdev)) { netdev_for_each_mc_addr(mc_ptr, netdev) { qlcnic_nic_add_mac(adapter, mc_ptr->dmi_addr); } } send_fw_cmd: qlcnic_nic_set_promisc(adapter, mode); } int qlcnic_nic_set_promisc(struct qlcnic_adapter *adapter, u32 mode) { struct qlcnic_nic_req req; u64 word; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_PROXY_SET_VPORT_MISS_MODE | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(mode); return qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); } void qlcnic_free_mac_list(struct qlcnic_adapter *adapter) { struct qlcnic_mac_list_s *cur; struct list_head *head = &adapter->mac_list; while (!list_empty(head)) { cur = list_entry(head->next, struct qlcnic_mac_list_s, list); qlcnic_sre_macaddr_change(adapter, cur->mac_addr, QLCNIC_MAC_DEL); list_del(&cur->list); kfree(cur); } } #define QLCNIC_CONFIG_INTR_COALESCE 3 /* * Send the interrupt coalescing parameter set by ethtool to the card. */ int qlcnic_config_intr_coalesce(struct qlcnic_adapter *adapter) { struct qlcnic_nic_req req; u64 word[6]; int rv, i; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word[0] = QLCNIC_CONFIG_INTR_COALESCE | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word[0]); memcpy(&word[0], &adapter->coal, sizeof(adapter->coal)); for (i = 0; i < 6; i++) req.words[i] = cpu_to_le64(word[i]); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "Could not send interrupt coalescing parameters\n"); return rv; } int qlcnic_config_hw_lro(struct qlcnic_adapter *adapter, int enable) { struct qlcnic_nic_req req; u64 word; int rv; if ((adapter->flags & QLCNIC_LRO_ENABLED) == enable) return 0; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_HW_LRO | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(enable); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "Could not send configure hw lro request\n"); adapter->flags ^= QLCNIC_LRO_ENABLED; return rv; } int qlcnic_config_bridged_mode(struct qlcnic_adapter *adapter, int enable) { struct qlcnic_nic_req req; u64 word; int rv; if (!!(adapter->flags & QLCNIC_BRIDGE_ENABLED) == enable) return 0; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_BRIDGING | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(enable); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "Could not send configure bridge mode request\n"); adapter->flags ^= QLCNIC_BRIDGE_ENABLED; return rv; } #define RSS_HASHTYPE_IP_TCP 0x3 int qlcnic_config_rss(struct qlcnic_adapter *adapter, int enable) { struct qlcnic_nic_req req; u64 word; int i, rv; const u64 key[] = { 0xbeac01fa6a42b73bULL, 0x8030f20c77cb2da3ULL, 0xae7b30b4d0ca2bcbULL, 0x43a38fb04167253dULL, 0x255b0ec26d5a56daULL }; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_RSS | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); /* * RSS request: * bits 3-0: hash_method * 5-4: hash_type_ipv4 * 7-6: hash_type_ipv6 * 8: enable * 9: use indirection table * 47-10: reserved * 63-48: indirection table mask */ word = ((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 4) | ((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 6) | ((u64)(enable & 0x1) << 8) | ((0x7ULL) << 48); req.words[0] = cpu_to_le64(word); for (i = 0; i < 5; i++) req.words[i+1] = cpu_to_le64(key[i]); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "could not configure RSS\n"); return rv; } int qlcnic_config_ipaddr(struct qlcnic_adapter *adapter, u32 ip, int cmd) { struct qlcnic_nic_req req; u64 word; int rv; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_IPADDR | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(cmd); req.words[1] = cpu_to_le64(ip); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "could not notify %s IP 0x%x reuqest\n", (cmd == QLCNIC_IP_UP) ? "Add" : "Remove", ip); return rv; } int qlcnic_linkevent_request(struct qlcnic_adapter *adapter, int enable) { struct qlcnic_nic_req req; u64 word; int rv; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_GET_LINKEVENT | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(enable | (enable << 8)); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "could not configure link notification\n"); return rv; } int qlcnic_send_lro_cleanup(struct qlcnic_adapter *adapter) { struct qlcnic_nic_req req; u64 word; int rv; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_LRO_REQUEST | ((u64)adapter->portnum << 16) | ((u64)QLCNIC_LRO_REQUEST_CLEANUP << 56) ; req.req_hdr = cpu_to_le64(word); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv != 0) dev_err(&adapter->netdev->dev, "could not cleanup lro flows\n"); return rv; } /* * qlcnic_change_mtu - Change the Maximum Transfer Unit * @returns 0 on success, negative on failure */ int qlcnic_change_mtu(struct net_device *netdev, int mtu) { struct qlcnic_adapter *adapter = netdev_priv(netdev); int rc = 0; if (mtu > P3_MAX_MTU) { dev_err(&adapter->netdev->dev, "mtu > %d bytes unsupported\n", P3_MAX_MTU); return -EINVAL; } rc = qlcnic_fw_cmd_set_mtu(adapter, mtu); if (!rc) netdev->mtu = mtu; return rc; } int qlcnic_get_mac_addr(struct qlcnic_adapter *adapter, u64 *mac) { u32 crbaddr, mac_hi, mac_lo; int pci_func = adapter->ahw.pci_func; crbaddr = CRB_MAC_BLOCK_START + (4 * ((pci_func/2) * 3)) + (4 * (pci_func & 1)); mac_lo = QLCRD32(adapter, crbaddr); mac_hi = QLCRD32(adapter, crbaddr+4); if (pci_func & 1) *mac = le64_to_cpu((mac_lo >> 16) | ((u64)mac_hi << 16)); else *mac = le64_to_cpu((u64)mac_lo | ((u64)mac_hi << 32)); return 0; } /* * Changes the CRB window to the specified window. */ /* Returns < 0 if off is not valid, * 1 if window access is needed. 'off' is set to offset from * CRB space in 128M pci map * 0 if no window access is needed. 'off' is set to 2M addr * In: 'off' is offset from base in 128M pci map */ static int qlcnic_pci_get_crb_addr_2M(struct qlcnic_adapter *adapter, ulong off, void __iomem **addr) { const struct crb_128M_2M_sub_block_map *m; if ((off >= QLCNIC_CRB_MAX) || (off < QLCNIC_PCI_CRBSPACE)) return -EINVAL; off -= QLCNIC_PCI_CRBSPACE; /* * Try direct map */ m = &crb_128M_2M_map[CRB_BLK(off)].sub_block[CRB_SUBBLK(off)]; if (m->valid && (m->start_128M <= off) && (m->end_128M > off)) { *addr = adapter->ahw.pci_base0 + m->start_2M + (off - m->start_128M); return 0; } /* * Not in direct map, use crb window */ *addr = adapter->ahw.pci_base0 + CRB_INDIRECT_2M + (off & MASK(16)); return 1; } /* * In: 'off' is offset from CRB space in 128M pci map * Out: 'off' is 2M pci map addr * side effect: lock crb window */ static void qlcnic_pci_set_crbwindow_2M(struct qlcnic_adapter *adapter, ulong off) { u32 window; void __iomem *addr = adapter->ahw.pci_base0 + CRB_WINDOW_2M; off -= QLCNIC_PCI_CRBSPACE; window = CRB_HI(off); if (adapter->ahw.crb_win == window) return; writel(window, addr); if (readl(addr) != window) { if (printk_ratelimit()) dev_warn(&adapter->pdev->dev, "failed to set CRB window to %d off 0x%lx\n", window, off); } adapter->ahw.crb_win = window; } int qlcnic_hw_write_wx_2M(struct qlcnic_adapter *adapter, ulong off, u32 data) { unsigned long flags; int rv; void __iomem *addr = NULL; rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr); if (rv == 0) { writel(data, addr); return 0; } if (rv > 0) { /* indirect access */ write_lock_irqsave(&adapter->ahw.crb_lock, flags); crb_win_lock(adapter); qlcnic_pci_set_crbwindow_2M(adapter, off); writel(data, addr); crb_win_unlock(adapter); write_unlock_irqrestore(&adapter->ahw.crb_lock, flags); return 0; } dev_err(&adapter->pdev->dev, "%s: invalid offset: 0x%016lx\n", __func__, off); dump_stack(); return -EIO; } u32 qlcnic_hw_read_wx_2M(struct qlcnic_adapter *adapter, ulong off) { unsigned long flags; int rv; u32 data; void __iomem *addr = NULL; rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr); if (rv == 0) return readl(addr); if (rv > 0) { /* indirect access */ write_lock_irqsave(&adapter->ahw.crb_lock, flags); crb_win_lock(adapter); qlcnic_pci_set_crbwindow_2M(adapter, off); data = readl(addr); crb_win_unlock(adapter); write_unlock_irqrestore(&adapter->ahw.crb_lock, flags); return data; } dev_err(&adapter->pdev->dev, "%s: invalid offset: 0x%016lx\n", __func__, off); dump_stack(); return -1; } void __iomem * qlcnic_get_ioaddr(struct qlcnic_adapter *adapter, u32 offset) { void __iomem *addr = NULL; WARN_ON(qlcnic_pci_get_crb_addr_2M(adapter, offset, &addr)); return addr; } static int qlcnic_pci_set_window_2M(struct qlcnic_adapter *adapter, u64 addr, u32 *start) { u32 window; struct pci_dev *pdev = adapter->pdev; if ((addr & 0x00ff800) == 0xff800) { if (printk_ratelimit()) dev_warn(&pdev->dev, "QM access not handled\n"); return -EIO; } window = OCM_WIN_P3P(addr); writel(window, adapter->ahw.ocm_win_crb); /* read back to flush */ readl(adapter->ahw.ocm_win_crb); adapter->ahw.ocm_win = window; *start = QLCNIC_PCI_OCM0_2M + GET_MEM_OFFS_2M(addr); return 0; } static int qlcnic_pci_mem_access_direct(struct qlcnic_adapter *adapter, u64 off, u64 *data, int op) { void __iomem *addr, *mem_ptr = NULL; resource_size_t mem_base; int ret; u32 start; mutex_lock(&adapter->ahw.mem_lock); ret = qlcnic_pci_set_window_2M(adapter, off, &start); if (ret != 0) goto unlock; addr = pci_base_offset(adapter, start); if (addr) goto noremap; mem_base = pci_resource_start(adapter->pdev, 0) + (start & PAGE_MASK); mem_ptr = ioremap(mem_base, PAGE_SIZE); if (mem_ptr == NULL) { ret = -EIO; goto unlock; } addr = mem_ptr + (start & (PAGE_SIZE - 1)); noremap: if (op == 0) /* read */ *data = readq(addr); else /* write */ writeq(*data, addr); unlock: mutex_unlock(&adapter->ahw.mem_lock); if (mem_ptr) iounmap(mem_ptr); return ret; } #define MAX_CTL_CHECK 1000 int qlcnic_pci_mem_write_2M(struct qlcnic_adapter *adapter, u64 off, u64 data) { int i, j, ret; u32 temp, off8; u64 stride; void __iomem *mem_crb; /* Only 64-bit aligned access */ if (off & 7) return -EIO; /* P3 onward, test agent base for MIU and SIU is same */ if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET, QLCNIC_ADDR_QDR_NET_MAX_P3)) { mem_crb = qlcnic_get_ioaddr(adapter, QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE); goto correct; } if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) { mem_crb = qlcnic_get_ioaddr(adapter, QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE); goto correct; } if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX)) return qlcnic_pci_mem_access_direct(adapter, off, &data, 1); return -EIO; correct: stride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8; off8 = off & ~(stride-1); mutex_lock(&adapter->ahw.mem_lock); writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO)); writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI)); i = 0; if (stride == 16) { writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL)); writel((TA_CTL_START | TA_CTL_ENABLE), (mem_crb + TEST_AGT_CTRL)); for (j = 0; j < MAX_CTL_CHECK; j++) { temp = readl(mem_crb + TEST_AGT_CTRL); if ((temp & TA_CTL_BUSY) == 0) break; } if (j >= MAX_CTL_CHECK) { ret = -EIO; goto done; } i = (off & 0xf) ? 0 : 2; writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i)), mem_crb + MIU_TEST_AGT_WRDATA(i)); writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i+1)), mem_crb + MIU_TEST_AGT_WRDATA(i+1)); i = (off & 0xf) ? 2 : 0; } writel(data & 0xffffffff, mem_crb + MIU_TEST_AGT_WRDATA(i)); writel((data >> 32) & 0xffffffff, mem_crb + MIU_TEST_AGT_WRDATA(i+1)); writel((TA_CTL_ENABLE | TA_CTL_WRITE), (mem_crb + TEST_AGT_CTRL)); writel((TA_CTL_START | TA_CTL_ENABLE | TA_CTL_WRITE), (mem_crb + TEST_AGT_CTRL)); for (j = 0; j < MAX_CTL_CHECK; j++) { temp = readl(mem_crb + TEST_AGT_CTRL); if ((temp & TA_CTL_BUSY) == 0) break; } if (j >= MAX_CTL_CHECK) { if (printk_ratelimit()) dev_err(&adapter->pdev->dev, "failed to write through agent\n"); ret = -EIO; } else ret = 0; done: mutex_unlock(&adapter->ahw.mem_lock); return ret; } int qlcnic_pci_mem_read_2M(struct qlcnic_adapter *adapter, u64 off, u64 *data) { int j, ret; u32 temp, off8; u64 val, stride; void __iomem *mem_crb; /* Only 64-bit aligned access */ if (off & 7) return -EIO; /* P3 onward, test agent base for MIU and SIU is same */ if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET, QLCNIC_ADDR_QDR_NET_MAX_P3)) { mem_crb = qlcnic_get_ioaddr(adapter, QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE); goto correct; } if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) { mem_crb = qlcnic_get_ioaddr(adapter, QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE); goto correct; } if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX)) { return qlcnic_pci_mem_access_direct(adapter, off, data, 0); } return -EIO; correct: stride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8; off8 = off & ~(stride-1); mutex_lock(&adapter->ahw.mem_lock); writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO)); writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI)); writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL)); writel((TA_CTL_START | TA_CTL_ENABLE), (mem_crb + TEST_AGT_CTRL)); for (j = 0; j < MAX_CTL_CHECK; j++) { temp = readl(mem_crb + TEST_AGT_CTRL); if ((temp & TA_CTL_BUSY) == 0) break; } if (j >= MAX_CTL_CHECK) { if (printk_ratelimit()) dev_err(&adapter->pdev->dev, "failed to read through agent\n"); ret = -EIO; } else { off8 = MIU_TEST_AGT_RDDATA_LO; if ((stride == 16) && (off & 0xf)) off8 = MIU_TEST_AGT_RDDATA_UPPER_LO; temp = readl(mem_crb + off8 + 4); val = (u64)temp << 32; val |= readl(mem_crb + off8); *data = val; ret = 0; } mutex_unlock(&adapter->ahw.mem_lock); return ret; } int qlcnic_get_board_info(struct qlcnic_adapter *adapter) { int offset, board_type, magic; struct pci_dev *pdev = adapter->pdev; offset = QLCNIC_FW_MAGIC_OFFSET; if (qlcnic_rom_fast_read(adapter, offset, &magic)) return -EIO; if (magic != QLCNIC_BDINFO_MAGIC) { dev_err(&pdev->dev, "invalid board config, magic=%08x\n", magic); return -EIO; } offset = QLCNIC_BRDTYPE_OFFSET; if (qlcnic_rom_fast_read(adapter, offset, &board_type)) return -EIO; adapter->ahw.board_type = board_type; if (board_type == QLCNIC_BRDTYPE_P3_4_GB_MM) { u32 gpio = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_PAD_GPIO_I); if ((gpio & 0x8000) == 0) board_type = QLCNIC_BRDTYPE_P3_10G_TP; } switch (board_type) { case QLCNIC_BRDTYPE_P3_HMEZ: case QLCNIC_BRDTYPE_P3_XG_LOM: case QLCNIC_BRDTYPE_P3_10G_CX4: case QLCNIC_BRDTYPE_P3_10G_CX4_LP: case QLCNIC_BRDTYPE_P3_IMEZ: case QLCNIC_BRDTYPE_P3_10G_SFP_PLUS: case QLCNIC_BRDTYPE_P3_10G_SFP_CT: case QLCNIC_BRDTYPE_P3_10G_SFP_QT: case QLCNIC_BRDTYPE_P3_10G_XFP: case QLCNIC_BRDTYPE_P3_10000_BASE_T: adapter->ahw.port_type = QLCNIC_XGBE; break; case QLCNIC_BRDTYPE_P3_REF_QG: case QLCNIC_BRDTYPE_P3_4_GB: case QLCNIC_BRDTYPE_P3_4_GB_MM: adapter->ahw.port_type = QLCNIC_GBE; break; case QLCNIC_BRDTYPE_P3_10G_TP: adapter->ahw.port_type = (adapter->portnum < 2) ? QLCNIC_XGBE : QLCNIC_GBE; break; default: dev_err(&pdev->dev, "unknown board type %x\n", board_type); adapter->ahw.port_type = QLCNIC_XGBE; break; } return 0; } int qlcnic_wol_supported(struct qlcnic_adapter *adapter) { u32 wol_cfg; wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG_NV); if (wol_cfg & (1UL << adapter->portnum)) { wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG); if (wol_cfg & (1 << adapter->portnum)) return 1; } return 0; } int qlcnic_config_led(struct qlcnic_adapter *adapter, u32 state, u32 rate) { struct qlcnic_nic_req req; int rv; u64 word; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_LED | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64((u64)rate << 32); req.words[1] = cpu_to_le64(state); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv) dev_err(&adapter->pdev->dev, "LED configuration failed.\n"); return rv; } static int qlcnic_set_fw_loopback(struct qlcnic_adapter *adapter, u32 flag) { struct qlcnic_nic_req req; int rv; u64 word; memset(&req, 0, sizeof(struct qlcnic_nic_req)); req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23); word = QLCNIC_H2C_OPCODE_CONFIG_LOOPBACK | ((u64)adapter->portnum << 16); req.req_hdr = cpu_to_le64(word); req.words[0] = cpu_to_le64(flag); rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1); if (rv) dev_err(&adapter->pdev->dev, "%sting loopback mode failed.\n", flag ? "Set" : "Reset"); return rv; } int qlcnic_set_ilb_mode(struct qlcnic_adapter *adapter) { if (qlcnic_set_fw_loopback(adapter, 1)) return -EIO; if (qlcnic_nic_set_promisc(adapter, VPORT_MISS_MODE_ACCEPT_ALL)) { qlcnic_set_fw_loopback(adapter, 0); return -EIO; } msleep(1000); return 0; } void qlcnic_clear_ilb_mode(struct qlcnic_adapter *adapter) { int mode = VPORT_MISS_MODE_DROP; struct net_device *netdev = adapter->netdev; qlcnic_set_fw_loopback(adapter, 0); if (netdev->flags & IFF_PROMISC) mode = VPORT_MISS_MODE_ACCEPT_ALL; else if (netdev->flags & IFF_ALLMULTI) mode = VPORT_MISS_MODE_ACCEPT_MULTI; qlcnic_nic_set_promisc(adapter, mode); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ggsamsa/sched_casio</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/net/qlcnic/qlcnic_hw.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">33,431</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086567"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// SPDX-License-Identifier: GPL-2.0+ /* I2C support for Dialog DA9063 * * Copyright 2012 Dialog Semiconductor Ltd. * Copyright 2013 Philipp Zabel, Pengutronix * * Author: Krystian Garbaciak, Dialog Semiconductor */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/regmap.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/mfd/core.h> #include <linux/mfd/da9063/core.h> #include <linux/mfd/da9063/registers.h> #include <linux/of.h> #include <linux/regulator/of_regulator.h> /* * Raw I2C access required for just accessing chip and variant info before we * know which device is present. The info read from the device using this * approach is then used to select the correct regmap tables. */ #define DA9063_REG_PAGE_SIZE 0x100 #define DA9063_REG_PAGED_ADDR_MASK 0xFF enum da9063_page_sel_buf_fmt { DA9063_PAGE_SEL_BUF_PAGE_REG = 0, DA9063_PAGE_SEL_BUF_PAGE_VAL, DA9063_PAGE_SEL_BUF_SIZE, }; enum da9063_paged_read_msgs { DA9063_PAGED_READ_MSG_PAGE_SEL = 0, DA9063_PAGED_READ_MSG_REG_SEL, DA9063_PAGED_READ_MSG_DATA, DA9063_PAGED_READ_MSG_CNT, }; static int da9063_i2c_blockreg_read(struct i2c_client *client, u16 addr, u8 *buf, int count) { struct i2c_msg xfer[DA9063_PAGED_READ_MSG_CNT]; u8 page_sel_buf[DA9063_PAGE_SEL_BUF_SIZE]; u8 page_num, paged_addr; int ret; /* Determine page info based on register address */ page_num = (addr / DA9063_REG_PAGE_SIZE); if (page_num > 1) { dev_err(&client->dev, "Invalid register address provided\n"); return -EINVAL; } paged_addr = (addr % DA9063_REG_PAGE_SIZE) & DA9063_REG_PAGED_ADDR_MASK; page_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_REG] = DA9063_REG_PAGE_CON; page_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_VAL] = (page_num << DA9063_I2C_PAGE_SEL_SHIFT) & DA9063_REG_PAGE_MASK; /* Write reg address, page selection */ xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].addr = client->addr; xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].flags = 0; xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].len = DA9063_PAGE_SEL_BUF_SIZE; xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].buf = page_sel_buf; /* Select register address */ xfer[DA9063_PAGED_READ_MSG_REG_SEL].addr = client->addr; xfer[DA9063_PAGED_READ_MSG_REG_SEL].flags = 0; xfer[DA9063_PAGED_READ_MSG_REG_SEL].len = sizeof(paged_addr); xfer[DA9063_PAGED_READ_MSG_REG_SEL].buf = &paged_addr; /* Read data */ xfer[DA9063_PAGED_READ_MSG_DATA].addr = client->addr; xfer[DA9063_PAGED_READ_MSG_DATA].flags = I2C_M_RD; xfer[DA9063_PAGED_READ_MSG_DATA].len = count; xfer[DA9063_PAGED_READ_MSG_DATA].buf = buf; ret = i2c_transfer(client->adapter, xfer, DA9063_PAGED_READ_MSG_CNT); if (ret < 0) { dev_err(&client->dev, "Paged block read failed: %d\n", ret); return ret; } if (ret != DA9063_PAGED_READ_MSG_CNT) { dev_err(&client->dev, "Paged block read failed to complete\n"); return -EIO; } return 0; } enum { DA9063_DEV_ID_REG = 0, DA9063_VAR_ID_REG, DA9063_CHIP_ID_REGS, }; static int da9063_get_device_type(struct i2c_client *i2c, struct da9063 *da9063) { u8 buf[DA9063_CHIP_ID_REGS]; int ret; ret = da9063_i2c_blockreg_read(i2c, DA9063_REG_DEVICE_ID, buf, DA9063_CHIP_ID_REGS); if (ret) return ret; if (buf[DA9063_DEV_ID_REG] != PMIC_CHIP_ID_DA9063) { dev_err(da9063->dev, "Invalid chip device ID: 0x%02x\n", buf[DA9063_DEV_ID_REG]); return -ENODEV; } dev_info(da9063->dev, "Device detected (chip-ID: 0x%02X, var-ID: 0x%02X)\n", buf[DA9063_DEV_ID_REG], buf[DA9063_VAR_ID_REG]); da9063->variant_code = (buf[DA9063_VAR_ID_REG] & DA9063_VARIANT_ID_MRC_MASK) >> DA9063_VARIANT_ID_MRC_SHIFT; return 0; } /* * Variant specific regmap configs */ static const struct regmap_range da9063_ad_readable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_AD_REG_SECOND_D), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_AD_REG_GP_ID_19), regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID), }; static const struct regmap_range da9063_ad_writeable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON), regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON), regmap_reg_range(DA9063_REG_COUNT_S, DA9063_AD_REG_ALARM_Y), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_AD_REG_MON_REG_4), regmap_reg_range(DA9063_AD_REG_GP_ID_0, DA9063_AD_REG_GP_ID_19), }; static const struct regmap_range da9063_ad_volatile_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D), regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B), regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F), regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT), regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN), regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_AD_REG_SECOND_D), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ), regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K), regmap_reg_range(DA9063_AD_REG_MON_REG_5, DA9063_AD_REG_MON_REG_6), }; static const struct regmap_access_table da9063_ad_readable_table = { .yes_ranges = da9063_ad_readable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_ad_readable_ranges), }; static const struct regmap_access_table da9063_ad_writeable_table = { .yes_ranges = da9063_ad_writeable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_ad_writeable_ranges), }; static const struct regmap_access_table da9063_ad_volatile_table = { .yes_ranges = da9063_ad_volatile_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_ad_volatile_ranges), }; static const struct regmap_range da9063_bb_readable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19), regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID), }; static const struct regmap_range da9063_bb_writeable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON), regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON), regmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4), regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19), }; static const struct regmap_range da9063_bb_da_volatile_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D), regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B), regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F), regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT), regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN), regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_BB_REG_SECOND_D), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ), regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K), regmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6), }; static const struct regmap_access_table da9063_bb_readable_table = { .yes_ranges = da9063_bb_readable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_bb_readable_ranges), }; static const struct regmap_access_table da9063_bb_writeable_table = { .yes_ranges = da9063_bb_writeable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_bb_writeable_ranges), }; static const struct regmap_access_table da9063_bb_da_volatile_table = { .yes_ranges = da9063_bb_da_volatile_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_bb_da_volatile_ranges), }; static const struct regmap_range da9063l_bb_readable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19), regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID), }; static const struct regmap_range da9063l_bb_writeable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON), regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4), regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19), }; static const struct regmap_range da9063l_bb_da_volatile_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D), regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B), regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F), regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT), regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN), regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_REG_MON_A10_RES), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ), regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K), regmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6), }; static const struct regmap_access_table da9063l_bb_readable_table = { .yes_ranges = da9063l_bb_readable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063l_bb_readable_ranges), }; static const struct regmap_access_table da9063l_bb_writeable_table = { .yes_ranges = da9063l_bb_writeable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063l_bb_writeable_ranges), }; static const struct regmap_access_table da9063l_bb_da_volatile_table = { .yes_ranges = da9063l_bb_da_volatile_ranges, .n_yes_ranges = ARRAY_SIZE(da9063l_bb_da_volatile_ranges), }; static const struct regmap_range da9063_da_readable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11), regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID), }; static const struct regmap_range da9063_da_writeable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON), regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON), regmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4), regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11), }; static const struct regmap_access_table da9063_da_readable_table = { .yes_ranges = da9063_da_readable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_da_readable_ranges), }; static const struct regmap_access_table da9063_da_writeable_table = { .yes_ranges = da9063_da_writeable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063_da_writeable_ranges), }; static const struct regmap_range da9063l_da_readable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11), regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID), }; static const struct regmap_range da9063l_da_writeable_ranges[] = { regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON), regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON), regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31), regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW), regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4), regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11), }; static const struct regmap_access_table da9063l_da_readable_table = { .yes_ranges = da9063l_da_readable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063l_da_readable_ranges), }; static const struct regmap_access_table da9063l_da_writeable_table = { .yes_ranges = da9063l_da_writeable_ranges, .n_yes_ranges = ARRAY_SIZE(da9063l_da_writeable_ranges), }; static const struct regmap_range_cfg da9063_range_cfg[] = { { .range_min = DA9063_REG_PAGE_CON, .range_max = DA9063_REG_CONFIG_ID, .selector_reg = DA9063_REG_PAGE_CON, .selector_mask = 1 << DA9063_I2C_PAGE_SEL_SHIFT, .selector_shift = DA9063_I2C_PAGE_SEL_SHIFT, .window_start = 0, .window_len = 256, } }; static struct regmap_config da9063_regmap_config = { .reg_bits = 8, .val_bits = 8, .ranges = da9063_range_cfg, .num_ranges = ARRAY_SIZE(da9063_range_cfg), .max_register = DA9063_REG_CONFIG_ID, .cache_type = REGCACHE_RBTREE, }; static const struct of_device_id da9063_dt_ids[] = { { .compatible = "dlg,da9063", }, { .compatible = "dlg,da9063l", }, { } }; MODULE_DEVICE_TABLE(of, da9063_dt_ids); static int da9063_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct da9063 *da9063; int ret; da9063 = devm_kzalloc(&i2c->dev, sizeof(struct da9063), GFP_KERNEL); if (da9063 == NULL) return -ENOMEM; i2c_set_clientdata(i2c, da9063); da9063->dev = &i2c->dev; da9063->chip_irq = i2c->irq; da9063->type = id->driver_data; ret = da9063_get_device_type(i2c, da9063); if (ret) return ret; switch (da9063->type) { case PMIC_TYPE_DA9063: switch (da9063->variant_code) { case PMIC_DA9063_AD: da9063_regmap_config.rd_table = &da9063_ad_readable_table; da9063_regmap_config.wr_table = &da9063_ad_writeable_table; da9063_regmap_config.volatile_table = &da9063_ad_volatile_table; break; case PMIC_DA9063_BB: case PMIC_DA9063_CA: da9063_regmap_config.rd_table = &da9063_bb_readable_table; da9063_regmap_config.wr_table = &da9063_bb_writeable_table; da9063_regmap_config.volatile_table = &da9063_bb_da_volatile_table; break; case PMIC_DA9063_DA: da9063_regmap_config.rd_table = &da9063_da_readable_table; da9063_regmap_config.wr_table = &da9063_da_writeable_table; da9063_regmap_config.volatile_table = &da9063_bb_da_volatile_table; break; default: dev_err(da9063->dev, "Chip variant not supported for DA9063\n"); return -ENODEV; } break; case PMIC_TYPE_DA9063L: switch (da9063->variant_code) { case PMIC_DA9063_BB: case PMIC_DA9063_CA: da9063_regmap_config.rd_table = &da9063l_bb_readable_table; da9063_regmap_config.wr_table = &da9063l_bb_writeable_table; da9063_regmap_config.volatile_table = &da9063l_bb_da_volatile_table; break; case PMIC_DA9063_DA: da9063_regmap_config.rd_table = &da9063l_da_readable_table; da9063_regmap_config.wr_table = &da9063l_da_writeable_table; da9063_regmap_config.volatile_table = &da9063l_bb_da_volatile_table; break; default: dev_err(da9063->dev, "Chip variant not supported for DA9063L\n"); return -ENODEV; } break; default: dev_err(da9063->dev, "Chip type not supported\n"); return -ENODEV; } da9063->regmap = devm_regmap_init_i2c(i2c, &da9063_regmap_config); if (IS_ERR(da9063->regmap)) { ret = PTR_ERR(da9063->regmap); dev_err(da9063->dev, "Failed to allocate register map: %d\n", ret); return ret; } return da9063_device_init(da9063, i2c->irq); } static const struct i2c_device_id da9063_i2c_id[] = { { "da9063", PMIC_TYPE_DA9063 }, { "da9063l", PMIC_TYPE_DA9063L }, {}, }; MODULE_DEVICE_TABLE(i2c, da9063_i2c_id); static struct i2c_driver da9063_i2c_driver = { .driver = { .name = "da9063", .of_match_table = da9063_dt_ids, }, .probe = da9063_i2c_probe, .id_table = da9063_i2c_id, }; module_i2c_driver(da9063_i2c_driver); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">GuillaumeSeren/linux</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/mfd/da9063-i2c.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">15,634</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086568"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * 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.search.aggregations.bucket.terms; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import org.elasticsearch.common.io.stream.Streamable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.search.aggregations.AggregationExecutionException; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation; import org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator; import org.elasticsearch.search.aggregations.support.format.ValueFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; /** * */ public abstract class InternalTerms<A extends InternalTerms, B extends InternalTerms.Bucket> extends InternalMultiBucketAggregation<A, B> implements Terms, ToXContent, Streamable { protected static final String DOC_COUNT_ERROR_UPPER_BOUND_FIELD_NAME = "doc_count_error_upper_bound"; protected static final String SUM_OF_OTHER_DOC_COUNTS = "sum_other_doc_count"; public static abstract class Bucket extends Terms.Bucket { long bucketOrd; protected long docCount; protected long docCountError; protected InternalAggregations aggregations; protected boolean showDocCountError; transient final ValueFormatter formatter; protected Bucket(ValueFormatter formatter, boolean showDocCountError) { // for serialization this.showDocCountError = showDocCountError; this.formatter = formatter; } protected Bucket(long docCount, InternalAggregations aggregations, boolean showDocCountError, long docCountError, ValueFormatter formatter) { this(formatter, showDocCountError); this.docCount = docCount; this.aggregations = aggregations; this.docCountError = docCountError; } @Override public long getDocCount() { return docCount; } @Override public long getDocCountError() { if (!showDocCountError) { throw new IllegalStateException("show_terms_doc_count_error is false"); } return docCountError; } @Override public Aggregations getAggregations() { return aggregations; } abstract Bucket newBucket(long docCount, InternalAggregations aggs, long docCountError); public Bucket reduce(List<? extends Bucket> buckets, ReduceContext context) { long docCount = 0; long docCountError = 0; List<InternalAggregations> aggregationsList = new ArrayList<>(buckets.size()); for (Bucket bucket : buckets) { docCount += bucket.docCount; if (docCountError != -1) { if (bucket.docCountError == -1) { docCountError = -1; } else { docCountError += bucket.docCountError; } } aggregationsList.add(bucket.aggregations); } InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context); return newBucket(docCount, aggs, docCountError); } } protected Terms.Order order; protected int requiredSize; protected int shardSize; protected long minDocCount; protected List<? extends Bucket> buckets; protected Map<String, Bucket> bucketMap; protected long docCountError; protected boolean showTermDocCountError; protected long otherDocCount; protected InternalTerms() {} // for serialization protected InternalTerms(String name, Terms.Order order, int requiredSize, int shardSize, long minDocCount, List<? extends Bucket> buckets, boolean showTermDocCountError, long docCountError, long otherDocCount, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) { super(name, pipelineAggregators, metaData); this.order = order; this.requiredSize = requiredSize; this.shardSize = shardSize; this.minDocCount = minDocCount; this.buckets = buckets; this.showTermDocCountError = showTermDocCountError; this.docCountError = docCountError; this.otherDocCount = otherDocCount; } @Override public List<Terms.Bucket> getBuckets() { Object o = buckets; return (List<Terms.Bucket>) o; } @Override public Terms.Bucket getBucketByKey(String term) { if (bucketMap == null) { bucketMap = Maps.newHashMapWithExpectedSize(buckets.size()); for (Bucket bucket : buckets) { bucketMap.put(bucket.getKeyAsString(), bucket); } } return bucketMap.get(term); } @Override public long getDocCountError() { return docCountError; } @Override public long getSumOfOtherDocCounts() { return otherDocCount; } @Override public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) { Multimap<Object, InternalTerms.Bucket> buckets = ArrayListMultimap.create(); long sumDocCountError = 0; long otherDocCount = 0; InternalTerms<A, B> referenceTerms = null; for (InternalAggregation aggregation : aggregations) { InternalTerms<A, B> terms = (InternalTerms<A, B>) aggregation; if (referenceTerms == null && !terms.getClass().equals(UnmappedTerms.class)) { referenceTerms = (InternalTerms<A, B>) aggregation; } if (referenceTerms != null && !referenceTerms.getClass().equals(terms.getClass()) && !terms.getClass().equals(UnmappedTerms.class)) { // control gets into this loop when the same field name against which the query is executed // is of different types in different indices. throw new AggregationExecutionException("Merging/Reducing the aggregations failed " + "when computing the aggregation [ Name: " + referenceTerms.getName() + ", Type: " + referenceTerms.type() + " ]" + " because: " + "the field you gave in the aggregation query " + "existed as two different types " + "in two different indices"); } otherDocCount += terms.getSumOfOtherDocCounts(); final long thisAggDocCountError; if (terms.buckets.size() < this.shardSize || this.order == InternalOrder.TERM_ASC || this.order == InternalOrder.TERM_DESC) { thisAggDocCountError = 0; } else if (InternalOrder.isCountDesc(this.order)) { thisAggDocCountError = terms.buckets.get(terms.buckets.size() - 1).docCount; } else { thisAggDocCountError = -1; } if (sumDocCountError != -1) { if (thisAggDocCountError == -1) { sumDocCountError = -1; } else { sumDocCountError += thisAggDocCountError; } } terms.docCountError = thisAggDocCountError; for (Bucket bucket : terms.buckets) { bucket.docCountError = thisAggDocCountError; buckets.put(bucket.getKey(), bucket); } } final int size = Math.min(requiredSize, buckets.size()); BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null)); for (Collection<Bucket> l : buckets.asMap().values()) { List<Bucket> sameTermBuckets = (List<Bucket>) l; // cast is ok according to javadocs final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext); if (b.docCountError != -1) { if (sumDocCountError == -1) { b.docCountError = -1; } else { b.docCountError = sumDocCountError - b.docCountError; } } if (b.docCount >= minDocCount) { Terms.Bucket removed = ordered.insertWithOverflow(b); if (removed != null) { otherDocCount += removed.getDocCount(); } } } Bucket[] list = new Bucket[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (Bucket) ordered.pop(); } long docCountError; if (sumDocCountError == -1) { docCountError = -1; } else { docCountError = aggregations.size() == 1 ? 0 : sumDocCountError; } return create(name, Arrays.asList(list), docCountError, otherDocCount, this); } protected abstract A create(String name, List<InternalTerms.Bucket> buckets, long docCountError, long otherDocCount, InternalTerms prototype); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">queirozfcom/elasticsearch</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">core/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">10,492</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086569"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v2 import ( "fmt" "time" "github.com/golang/glog" "github.com/google/cadvisor/info/v1" ) func machineFsStatsFromV1(fsStats []v1.FsStats) []MachineFsStats { var result []MachineFsStats for _, stat := range fsStats { readDuration := time.Millisecond * time.Duration(stat.ReadTime) writeDuration := time.Millisecond * time.Duration(stat.WriteTime) ioDuration := time.Millisecond * time.Duration(stat.IoTime) weightedDuration := time.Millisecond * time.Duration(stat.WeightedIoTime) result = append(result, MachineFsStats{ Device: stat.Device, Type: stat.Type, Capacity: &stat.Limit, Usage: &stat.Usage, Available: &stat.Available, InodesFree: &stat.InodesFree, DiskStats: DiskStats{ ReadsCompleted: &stat.ReadsCompleted, ReadsMerged: &stat.ReadsMerged, SectorsRead: &stat.SectorsRead, ReadDuration: &readDuration, WritesCompleted: &stat.WritesCompleted, WritesMerged: &stat.WritesMerged, SectorsWritten: &stat.SectorsWritten, WriteDuration: &writeDuration, IoInProgress: &stat.IoInProgress, IoDuration: &ioDuration, WeightedIoDuration: &weightedDuration, }, }) } return result } func MachineStatsFromV1(cont *v1.ContainerInfo) []MachineStats { var stats []MachineStats var last *v1.ContainerStats for _, val := range cont.Stats { stat := MachineStats{ Timestamp: val.Timestamp, } if cont.Spec.HasCpu { stat.Cpu = &val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if cont.Spec.HasMemory { stat.Memory = &val.Memory } if cont.Spec.HasNetwork { stat.Network = &NetworkStats{ // FIXME: Use reflection instead. Tcp: TcpStat(val.Network.Tcp), Tcp6: TcpStat(val.Network.Tcp6), Interfaces: val.Network.Interfaces, } } if cont.Spec.HasFilesystem { stat.Filesystem = machineFsStatsFromV1(val.Filesystem) } // TODO(rjnagal): Handle load stats. stats = append(stats, stat) } return stats } func ContainerStatsFromV1(spec *v1.ContainerSpec, stats []*v1.ContainerStats) []*ContainerStats { newStats := make([]*ContainerStats, 0, len(stats)) var last *v1.ContainerStats for _, val := range stats { stat := &ContainerStats{ Timestamp: val.Timestamp, } if spec.HasCpu { stat.Cpu = &val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if spec.HasMemory { stat.Memory = &val.Memory } if spec.HasNetwork { // TODO: Handle TcpStats stat.Network = &NetworkStats{ Interfaces: val.Network.Interfaces, } } if spec.HasFilesystem { if len(val.Filesystem) == 1 { stat.Filesystem = &FilesystemStats{ TotalUsageBytes: &val.Filesystem[0].Usage, BaseUsageBytes: &val.Filesystem[0].BaseUsage, } } else if len(val.Filesystem) > 1 { // Cannot handle multiple devices per container. glog.V(2).Infof("failed to handle multiple devices for container. Skipping Filesystem stats") } } if spec.HasDiskIo { stat.DiskIo = &val.DiskIo } if spec.HasCustomMetrics { stat.CustomMetrics = val.CustomMetrics } // TODO(rjnagal): Handle load stats. newStats = append(newStats, stat) } return newStats } func DeprecatedStatsFromV1(cont *v1.ContainerInfo) []DeprecatedContainerStats { stats := make([]DeprecatedContainerStats, 0, len(cont.Stats)) var last *v1.ContainerStats for _, val := range cont.Stats { stat := DeprecatedContainerStats{ Timestamp: val.Timestamp, HasCpu: cont.Spec.HasCpu, HasMemory: cont.Spec.HasMemory, HasNetwork: cont.Spec.HasNetwork, HasFilesystem: cont.Spec.HasFilesystem, HasDiskIo: cont.Spec.HasDiskIo, HasCustomMetrics: cont.Spec.HasCustomMetrics, } if stat.HasCpu { stat.Cpu = val.Cpu cpuInst, err := InstCpuStats(last, val) if err != nil { glog.Warningf("Could not get instant cpu stats: %v", err) } else { stat.CpuInst = cpuInst } last = val } if stat.HasMemory { stat.Memory = val.Memory } if stat.HasNetwork { stat.Network.Interfaces = val.Network.Interfaces } if stat.HasFilesystem { stat.Filesystem = val.Filesystem } if stat.HasDiskIo { stat.DiskIo = val.DiskIo } if stat.HasCustomMetrics { stat.CustomMetrics = val.CustomMetrics } // TODO(rjnagal): Handle load stats. stats = append(stats, stat) } return stats } func InstCpuStats(last, cur *v1.ContainerStats) (*CpuInstStats, error) { if last == nil { return nil, nil } if !cur.Timestamp.After(last.Timestamp) { return nil, fmt.Errorf("container stats move backwards in time") } if len(last.Cpu.Usage.PerCpu) != len(cur.Cpu.Usage.PerCpu) { return nil, fmt.Errorf("different number of cpus") } timeDelta := cur.Timestamp.Sub(last.Timestamp) if timeDelta <= 100*time.Millisecond { return nil, fmt.Errorf("time delta unexpectedly small") } // Nanoseconds to gain precision and avoid having zero seconds if the // difference between the timestamps is just under a second timeDeltaNs := uint64(timeDelta.Nanoseconds()) convertToRate := func(lastValue, curValue uint64) (uint64, error) { if curValue < lastValue { return 0, fmt.Errorf("cumulative stats decrease") } valueDelta := curValue - lastValue // Use float64 to keep precision return uint64(float64(valueDelta) / float64(timeDeltaNs) * 1e9), nil } total, err := convertToRate(last.Cpu.Usage.Total, cur.Cpu.Usage.Total) if err != nil { return nil, err } percpu := make([]uint64, len(last.Cpu.Usage.PerCpu)) for i := range percpu { var err error percpu[i], err = convertToRate(last.Cpu.Usage.PerCpu[i], cur.Cpu.Usage.PerCpu[i]) if err != nil { return nil, err } } user, err := convertToRate(last.Cpu.Usage.User, cur.Cpu.Usage.User) if err != nil { return nil, err } system, err := convertToRate(last.Cpu.Usage.System, cur.Cpu.Usage.System) if err != nil { return nil, err } return &CpuInstStats{ Usage: CpuInstUsage{ Total: total, PerCpu: percpu, User: user, System: system, }, }, nil } // Get V2 container spec from v1 container info. func ContainerSpecFromV1(specV1 *v1.ContainerSpec, aliases []string, namespace string) ContainerSpec { specV2 := ContainerSpec{ CreationTime: specV1.CreationTime, HasCpu: specV1.HasCpu, HasMemory: specV1.HasMemory, HasFilesystem: specV1.HasFilesystem, HasNetwork: specV1.HasNetwork, HasDiskIo: specV1.HasDiskIo, HasCustomMetrics: specV1.HasCustomMetrics, Image: specV1.Image, Labels: specV1.Labels, } if specV1.HasCpu { specV2.Cpu.Limit = specV1.Cpu.Limit specV2.Cpu.MaxLimit = specV1.Cpu.MaxLimit specV2.Cpu.Mask = specV1.Cpu.Mask } if specV1.HasMemory { specV2.Memory.Limit = specV1.Memory.Limit specV2.Memory.Reservation = specV1.Memory.Reservation specV2.Memory.SwapLimit = specV1.Memory.SwapLimit } if specV1.HasCustomMetrics { specV2.CustomMetrics = specV1.CustomMetrics } specV2.Aliases = aliases specV2.Namespace = namespace return specV2 } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">dmirubtsov/k8s-executor</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/k8s.io/kubernetes/vendor/github.com/google/cadvisor/info/v2/conversion.go</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">GO</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,941</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086570"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!doctype html> <html ⚡> <head> <meta charset="utf-8"> <title>BeOpinion examples</title> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'> <link rel="canonical" href="https://www.example.com/url/to/full/document.html"> <script async custom-element="amp-beopinion" src="https://cdn.ampproject.org/v0/amp-beopinion-0.1.js"></script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> <script async src="https://cdn.ampproject.org/v0.js"></script> </head> <body> <h2>BeOpinion</h2> <h3>Simple Question</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c383c46e0fb00017ef05a"> </amp-beopinion> <h3>Question with Tweet</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c504fc9e77c00018d1f1a"> </amp-beopinion> <h3>Question with Instagram post</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c50a646e0fb00018039df"> </amp-beopinion> <h3>Question with YouTube video</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8d4f0046e0fb00018bc17d"> </amp-beopinion> <h3>Question with Dailymotion video</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8d7fddc9e77c00019c3f72"> </amp-beopinion> <h3>Question with custom video</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c5232c9e77c00018d3a3d"> </amp-beopinion> <h3>Survey</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c3b69c9e77c00018bffeb"> </amp-beopinion> <h3>Quiz</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c3d1246e0fb00017f2f47"> </amp-beopinion> <h3>Personality test</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c3ed0c9e77c00018c2d81"> </amp-beopinion> <h3>Form</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c3f62c9e77c00018c35dc"> </amp-beopinion> <h3>Game</h3> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8c41c846e0fb00017f7093"> </amp-beopinion> <h2>Intentionally non-existing content</h2> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="aaaaaaaaaaaaaaaaaaaaaaaa"> </amp-beopinion> <h2>Unpublished content</h2> <amp-beopinion width="375" height="1" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8afe1746e0fb00017282f7"> </amp-beopinion> <h2>Unpublished content (with fallback)</h2> <amp-beopinion width="375" height="100" layout="responsive" data-account="5a8af83d46e0fb0001720141" data-content="5a8afe1746e0fb00017282f7"> <div fallback> An error occurred while retrieving the content. It might have been deleted. </div> </amp-beopinion> <h2>Ad</h2> <amp-ad width="300" height="1" type="beopinion" layout="responsive" data-name="slot_0" data-my-content="0" data-account="5a8af83d46e0fb0001720141"> </amp-ad> </body> </html> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">luciancrasovan/amphtml</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">examples/beopinion.amp.html</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">HTML</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,630</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086571"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">///////////////////////////////////////////////////////////////////////////// // Name: wx/bmpbuttn.h // Purpose: wxBitmapButton class interface // Author: Vadim Zeitlin // Modified by: // Created: 25.08.00 // Copyright: (c) 2000 Vadim Zeitlin // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_BMPBUTTON_H_BASE_ #define _WX_BMPBUTTON_H_BASE_ #include "wx/defs.h" #if wxUSE_BMPBUTTON #include "wx/button.h" // FIXME: right now only wxMSW, wxGTK and wxOSX implement bitmap support in wxButton // itself, this shouldn't be used for the other platforms neither // when all of them do it #if (defined(__WXMSW__) || defined(__WXGTK20__) || defined(__WXOSX__) || defined(__WXQT__)) && !defined(__WXUNIVERSAL__) #define wxHAS_BUTTON_BITMAP #endif class WXDLLIMPEXP_FWD_CORE wxBitmapButton; // ---------------------------------------------------------------------------- // wxBitmapButton: a button which shows bitmaps instead of the usual string. // It has different bitmaps for different states (focused/disabled/pressed) // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxBitmapButtonBase : public wxButton { public: wxBitmapButtonBase() { #ifndef wxHAS_BUTTON_BITMAP m_marginX = m_marginY = 0; #endif // wxHAS_BUTTON_BITMAP } bool Create(wxWindow *parent, wxWindowID winid, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { // We use wxBU_NOTEXT to let the base class Create() know that we are // not going to show the label: this is a hack needed for wxGTK where // we can show both label and bitmap only with GTK 2.6+ but we always // can show just one of them and this style allows us to choose which // one we need. // // And we also use wxBU_EXACTFIT to avoid being resized up to the // standard button size as this doesn't make sense for bitmap buttons // which are not standard anyhow and should fit their bitmap size. return wxButton::Create(parent, winid, "", pos, size, style | wxBU_NOTEXT | wxBU_EXACTFIT, validator, name); } // Special creation function for a standard "Close" bitmap. It allows to // simply create a close button with the image appropriate for the current // platform. static wxBitmapButton* NewCloseButton(wxWindow* parent, wxWindowID winid); // set/get the margins around the button virtual void SetMargins(int x, int y) { DoSetBitmapMargins(x, y); } int GetMarginX() const { return DoGetBitmapMargins().x; } int GetMarginY() const { return DoGetBitmapMargins().y; } protected: #ifndef wxHAS_BUTTON_BITMAP // function called when any of the bitmaps changes virtual void OnSetBitmap() { InvalidateBestSize(); Refresh(); } virtual wxBitmap DoGetBitmap(State which) const { return m_bitmaps[which]; } virtual void DoSetBitmap(const wxBitmap& bitmap, State which) { m_bitmaps[which] = bitmap; OnSetBitmap(); } virtual wxSize DoGetBitmapMargins() const { return wxSize(m_marginX, m_marginY); } virtual void DoSetBitmapMargins(int x, int y) { m_marginX = x; m_marginY = y; } // the bitmaps for various states wxBitmap m_bitmaps[State_Max]; // the margins around the bitmap int m_marginX, m_marginY; #endif // !wxHAS_BUTTON_BITMAP wxDECLARE_NO_COPY_CLASS(wxBitmapButtonBase); }; #if defined(__WXUNIVERSAL__) #include "wx/univ/bmpbuttn.h" #elif defined(__WXMSW__) #include "wx/msw/bmpbuttn.h" #elif defined(__WXMOTIF__) #include "wx/motif/bmpbuttn.h" #elif defined(__WXGTK20__) #include "wx/gtk/bmpbuttn.h" #elif defined(__WXGTK__) #include "wx/gtk1/bmpbuttn.h" #elif defined(__WXMAC__) #include "wx/osx/bmpbuttn.h" #elif defined(__WXQT__) #include "wx/qt/bmpbuttn.h" #endif #endif // wxUSE_BMPBUTTON #endif // _WX_BMPBUTTON_H_BASE_ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">adouble42/nemesis-current</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wxWidgets-3.1.0/include/wx/bmpbuttn.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-2-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,285</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086572"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop/message_loop.h" #include "content/renderer/media/mock_web_rtc_peer_connection_handler_client.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h" namespace content { class PeerConnectionDependencyFactoryTest : public ::testing::Test { public: void SetUp() override { dependency_factory_.reset(new MockPeerConnectionDependencyFactory()); } protected: base::MessageLoop message_loop_; scoped_ptr<MockPeerConnectionDependencyFactory> dependency_factory_; }; TEST_F(PeerConnectionDependencyFactoryTest, CreateRTCPeerConnectionHandler) { MockWebRTCPeerConnectionHandlerClient client_jsep; scoped_ptr<blink::WebRTCPeerConnectionHandler> pc_handler( dependency_factory_->CreateRTCPeerConnectionHandler(&client_jsep)); EXPECT_TRUE(pc_handler.get() != NULL); } } // namespace content </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">CTSRD-SOAAP/chromium-42.0.2311.135</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C++</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,157</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086573"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (C) 2009 Texas Instruments. * Copyright (C) 2010 EF Johnson Technologies * * 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. */ #include <linux/interrupt.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/module.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/clk.h> #include <linux/dmaengine.h> #include <linux/dma-mapping.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/spi/spi.h> #include <linux/spi/spi_bitbang.h> #include <linux/slab.h> #include <linux/platform_data/spi-davinci.h> #define CS_DEFAULT 0xFF #define SPIFMT_PHASE_MASK BIT(16) #define SPIFMT_POLARITY_MASK BIT(17) #define SPIFMT_DISTIMER_MASK BIT(18) #define SPIFMT_SHIFTDIR_MASK BIT(20) #define SPIFMT_WAITENA_MASK BIT(21) #define SPIFMT_PARITYENA_MASK BIT(22) #define SPIFMT_ODD_PARITY_MASK BIT(23) #define SPIFMT_WDELAY_MASK 0x3f000000u #define SPIFMT_WDELAY_SHIFT 24 #define SPIFMT_PRESCALE_SHIFT 8 /* SPIPC0 */ #define SPIPC0_DIFUN_MASK BIT(11) /* MISO */ #define SPIPC0_DOFUN_MASK BIT(10) /* MOSI */ #define SPIPC0_CLKFUN_MASK BIT(9) /* CLK */ #define SPIPC0_SPIENA_MASK BIT(8) /* nREADY */ #define SPIINT_MASKALL 0x0101035F #define SPIINT_MASKINT 0x0000015F #define SPI_INTLVL_1 0x000001FF #define SPI_INTLVL_0 0x00000000 /* SPIDAT1 (upper 16 bit defines) */ #define SPIDAT1_CSHOLD_MASK BIT(12) #define SPIDAT1_WDEL BIT(10) /* SPIGCR1 */ #define SPIGCR1_CLKMOD_MASK BIT(1) #define SPIGCR1_MASTER_MASK BIT(0) #define SPIGCR1_POWERDOWN_MASK BIT(8) #define SPIGCR1_LOOPBACK_MASK BIT(16) #define SPIGCR1_SPIENA_MASK BIT(24) /* SPIBUF */ #define SPIBUF_TXFULL_MASK BIT(29) #define SPIBUF_RXEMPTY_MASK BIT(31) /* SPIDELAY */ #define SPIDELAY_C2TDELAY_SHIFT 24 #define SPIDELAY_C2TDELAY_MASK (0xFF << SPIDELAY_C2TDELAY_SHIFT) #define SPIDELAY_T2CDELAY_SHIFT 16 #define SPIDELAY_T2CDELAY_MASK (0xFF << SPIDELAY_T2CDELAY_SHIFT) #define SPIDELAY_T2EDELAY_SHIFT 8 #define SPIDELAY_T2EDELAY_MASK (0xFF << SPIDELAY_T2EDELAY_SHIFT) #define SPIDELAY_C2EDELAY_SHIFT 0 #define SPIDELAY_C2EDELAY_MASK 0xFF /* Error Masks */ #define SPIFLG_DLEN_ERR_MASK BIT(0) #define SPIFLG_TIMEOUT_MASK BIT(1) #define SPIFLG_PARERR_MASK BIT(2) #define SPIFLG_DESYNC_MASK BIT(3) #define SPIFLG_BITERR_MASK BIT(4) #define SPIFLG_OVRRUN_MASK BIT(6) #define SPIFLG_BUF_INIT_ACTIVE_MASK BIT(24) #define SPIFLG_ERROR_MASK (SPIFLG_DLEN_ERR_MASK \ | SPIFLG_TIMEOUT_MASK | SPIFLG_PARERR_MASK \ | SPIFLG_DESYNC_MASK | SPIFLG_BITERR_MASK \ | SPIFLG_OVRRUN_MASK) #define SPIINT_DMA_REQ_EN BIT(16) /* SPI Controller registers */ #define SPIGCR0 0x00 #define SPIGCR1 0x04 #define SPIINT 0x08 #define SPILVL 0x0c #define SPIFLG 0x10 #define SPIPC0 0x14 #define SPIDAT1 0x3c #define SPIBUF 0x40 #define SPIDELAY 0x48 #define SPIDEF 0x4c #define SPIFMT0 0x50 /* SPI Controller driver's private data. */ struct davinci_spi { struct spi_bitbang bitbang; struct clk *clk; u8 version; resource_size_t pbase; void __iomem *base; u32 irq; struct completion done; const void *tx; void *rx; int rcount; int wcount; struct dma_chan *dma_rx; struct dma_chan *dma_tx; struct davinci_spi_platform_data pdata; void (*get_rx)(u32 rx_data, struct davinci_spi *); u32 (*get_tx)(struct davinci_spi *); u8 *bytes_per_word; u8 prescaler_limit; }; static struct davinci_spi_config davinci_spi_default_cfg; static void davinci_spi_rx_buf_u8(u32 data, struct davinci_spi *dspi) { if (dspi->rx) { u8 *rx = dspi->rx; *rx++ = (u8)data; dspi->rx = rx; } } static void davinci_spi_rx_buf_u16(u32 data, struct davinci_spi *dspi) { if (dspi->rx) { u16 *rx = dspi->rx; *rx++ = (u16)data; dspi->rx = rx; } } static u32 davinci_spi_tx_buf_u8(struct davinci_spi *dspi) { u32 data = 0; if (dspi->tx) { const u8 *tx = dspi->tx; data = *tx++; dspi->tx = tx; } return data; } static u32 davinci_spi_tx_buf_u16(struct davinci_spi *dspi) { u32 data = 0; if (dspi->tx) { const u16 *tx = dspi->tx; data = *tx++; dspi->tx = tx; } return data; } static inline void set_io_bits(void __iomem *addr, u32 bits) { u32 v = ioread32(addr); v |= bits; iowrite32(v, addr); } static inline void clear_io_bits(void __iomem *addr, u32 bits) { u32 v = ioread32(addr); v &= ~bits; iowrite32(v, addr); } /* * Interface to control the chip select signal */ static void davinci_spi_chipselect(struct spi_device *spi, int value) { struct davinci_spi *dspi; struct davinci_spi_platform_data *pdata; struct davinci_spi_config *spicfg = spi->controller_data; u8 chip_sel = spi->chip_select; u16 spidat1 = CS_DEFAULT; dspi = spi_master_get_devdata(spi->master); pdata = &dspi->pdata; /* program delay transfers if tx_delay is non zero */ if (spicfg->wdelay) spidat1 |= SPIDAT1_WDEL; /* * Board specific chip select logic decides the polarity and cs * line for the controller */ if (spi->cs_gpio >= 0) { if (value == BITBANG_CS_ACTIVE) gpio_set_value(spi->cs_gpio, spi->mode & SPI_CS_HIGH); else gpio_set_value(spi->cs_gpio, !(spi->mode & SPI_CS_HIGH)); } else { if (value == BITBANG_CS_ACTIVE) { spidat1 |= SPIDAT1_CSHOLD_MASK; spidat1 &= ~(0x1 << chip_sel); } } iowrite16(spidat1, dspi->base + SPIDAT1 + 2); } /** * davinci_spi_get_prescale - Calculates the correct prescale value * @maxspeed_hz: the maximum rate the SPI clock can run at * * This function calculates the prescale value that generates a clock rate * less than or equal to the specified maximum. * * Returns: calculated prescale value for easy programming into SPI registers * or negative error number if valid prescalar cannot be updated. */ static inline int davinci_spi_get_prescale(struct davinci_spi *dspi, u32 max_speed_hz) { int ret; /* Subtract 1 to match what will be programmed into SPI register. */ ret = DIV_ROUND_UP(clk_get_rate(dspi->clk), max_speed_hz) - 1; if (ret < dspi->prescaler_limit || ret > 255) return -EINVAL; return ret; } /** * davinci_spi_setup_transfer - This functions will determine transfer method * @spi: spi device on which data transfer to be done * @t: spi transfer in which transfer info is filled * * This function determines data transfer method (8/16/32 bit transfer). * It will also set the SPI Clock Control register according to * SPI slave device freq. */ static int davinci_spi_setup_transfer(struct spi_device *spi, struct spi_transfer *t) { struct davinci_spi *dspi; struct davinci_spi_config *spicfg; u8 bits_per_word = 0; u32 hz = 0, spifmt = 0; int prescale; dspi = spi_master_get_devdata(spi->master); spicfg = spi->controller_data; if (!spicfg) spicfg = &davinci_spi_default_cfg; if (t) { bits_per_word = t->bits_per_word; hz = t->speed_hz; } /* if bits_per_word is not set then set it default */ if (!bits_per_word) bits_per_word = spi->bits_per_word; /* * Assign function pointer to appropriate transfer method * 8bit, 16bit or 32bit transfer */ if (bits_per_word <= 8) { dspi->get_rx = davinci_spi_rx_buf_u8; dspi->get_tx = davinci_spi_tx_buf_u8; dspi->bytes_per_word[spi->chip_select] = 1; } else { dspi->get_rx = davinci_spi_rx_buf_u16; dspi->get_tx = davinci_spi_tx_buf_u16; dspi->bytes_per_word[spi->chip_select] = 2; } if (!hz) hz = spi->max_speed_hz; /* Set up SPIFMTn register, unique to this chipselect. */ prescale = davinci_spi_get_prescale(dspi, hz); if (prescale < 0) return prescale; spifmt = (prescale << SPIFMT_PRESCALE_SHIFT) | (bits_per_word & 0x1f); if (spi->mode & SPI_LSB_FIRST) spifmt |= SPIFMT_SHIFTDIR_MASK; if (spi->mode & SPI_CPOL) spifmt |= SPIFMT_POLARITY_MASK; if (!(spi->mode & SPI_CPHA)) spifmt |= SPIFMT_PHASE_MASK; /* * Assume wdelay is used only on SPI peripherals that has this field * in SPIFMTn register and when it's configured from board file or DT. */ if (spicfg->wdelay) spifmt |= ((spicfg->wdelay << SPIFMT_WDELAY_SHIFT) & SPIFMT_WDELAY_MASK); /* * Version 1 hardware supports two basic SPI modes: * - Standard SPI mode uses 4 pins, with chipselect * - 3 pin SPI is a 4 pin variant without CS (SPI_NO_CS) * (distinct from SPI_3WIRE, with just one data wire; * or similar variants without MOSI or without MISO) * * Version 2 hardware supports an optional handshaking signal, * so it can support two more modes: * - 5 pin SPI variant is standard SPI plus SPI_READY * - 4 pin with enable is (SPI_READY | SPI_NO_CS) */ if (dspi->version == SPI_VERSION_2) { u32 delay = 0; if (spicfg->odd_parity) spifmt |= SPIFMT_ODD_PARITY_MASK; if (spicfg->parity_enable) spifmt |= SPIFMT_PARITYENA_MASK; if (spicfg->timer_disable) { spifmt |= SPIFMT_DISTIMER_MASK; } else { delay |= (spicfg->c2tdelay << SPIDELAY_C2TDELAY_SHIFT) & SPIDELAY_C2TDELAY_MASK; delay |= (spicfg->t2cdelay << SPIDELAY_T2CDELAY_SHIFT) & SPIDELAY_T2CDELAY_MASK; } if (spi->mode & SPI_READY) { spifmt |= SPIFMT_WAITENA_MASK; delay |= (spicfg->t2edelay << SPIDELAY_T2EDELAY_SHIFT) & SPIDELAY_T2EDELAY_MASK; delay |= (spicfg->c2edelay << SPIDELAY_C2EDELAY_SHIFT) & SPIDELAY_C2EDELAY_MASK; } iowrite32(delay, dspi->base + SPIDELAY); } iowrite32(spifmt, dspi->base + SPIFMT0); return 0; } static int davinci_spi_of_setup(struct spi_device *spi) { struct davinci_spi_config *spicfg = spi->controller_data; struct device_node *np = spi->dev.of_node; u32 prop; if (spicfg == NULL && np) { spicfg = kzalloc(sizeof(*spicfg), GFP_KERNEL); if (!spicfg) return -ENOMEM; *spicfg = davinci_spi_default_cfg; /* override with dt configured values */ if (!of_property_read_u32(np, "ti,spi-wdelay", &prop)) spicfg->wdelay = (u8)prop; spi->controller_data = spicfg; } return 0; } /** * davinci_spi_setup - This functions will set default transfer method * @spi: spi device on which data transfer to be done * * This functions sets the default transfer method. */ static int davinci_spi_setup(struct spi_device *spi) { int retval = 0; struct davinci_spi *dspi; struct davinci_spi_platform_data *pdata; struct spi_master *master = spi->master; struct device_node *np = spi->dev.of_node; bool internal_cs = true; dspi = spi_master_get_devdata(spi->master); pdata = &dspi->pdata; if (!(spi->mode & SPI_NO_CS)) { if (np && (master->cs_gpios != NULL) && (spi->cs_gpio >= 0)) { retval = gpio_direction_output( spi->cs_gpio, !(spi->mode & SPI_CS_HIGH)); internal_cs = false; } else if (pdata->chip_sel && spi->chip_select < pdata->num_chipselect && pdata->chip_sel[spi->chip_select] != SPI_INTERN_CS) { spi->cs_gpio = pdata->chip_sel[spi->chip_select]; retval = gpio_direction_output( spi->cs_gpio, !(spi->mode & SPI_CS_HIGH)); internal_cs = false; } if (retval) { dev_err(&spi->dev, "GPIO %d setup failed (%d)\n", spi->cs_gpio, retval); return retval; } if (internal_cs) set_io_bits(dspi->base + SPIPC0, 1 << spi->chip_select); } if (spi->mode & SPI_READY) set_io_bits(dspi->base + SPIPC0, SPIPC0_SPIENA_MASK); if (spi->mode & SPI_LOOP) set_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK); else clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK); return davinci_spi_of_setup(spi); } static void davinci_spi_cleanup(struct spi_device *spi) { struct davinci_spi_config *spicfg = spi->controller_data; spi->controller_data = NULL; if (spi->dev.of_node) kfree(spicfg); } static int davinci_spi_check_error(struct davinci_spi *dspi, int int_status) { struct device *sdev = dspi->bitbang.master->dev.parent; if (int_status & SPIFLG_TIMEOUT_MASK) { dev_err(sdev, "SPI Time-out Error\n"); return -ETIMEDOUT; } if (int_status & SPIFLG_DESYNC_MASK) { dev_err(sdev, "SPI Desynchronization Error\n"); return -EIO; } if (int_status & SPIFLG_BITERR_MASK) { dev_err(sdev, "SPI Bit error\n"); return -EIO; } if (dspi->version == SPI_VERSION_2) { if (int_status & SPIFLG_DLEN_ERR_MASK) { dev_err(sdev, "SPI Data Length Error\n"); return -EIO; } if (int_status & SPIFLG_PARERR_MASK) { dev_err(sdev, "SPI Parity Error\n"); return -EIO; } if (int_status & SPIFLG_OVRRUN_MASK) { dev_err(sdev, "SPI Data Overrun error\n"); return -EIO; } if (int_status & SPIFLG_BUF_INIT_ACTIVE_MASK) { dev_err(sdev, "SPI Buffer Init Active\n"); return -EBUSY; } } return 0; } /** * davinci_spi_process_events - check for and handle any SPI controller events * @dspi: the controller data * * This function will check the SPIFLG register and handle any events that are * detected there */ static int davinci_spi_process_events(struct davinci_spi *dspi) { u32 buf, status, errors = 0, spidat1; buf = ioread32(dspi->base + SPIBUF); if (dspi->rcount > 0 && !(buf & SPIBUF_RXEMPTY_MASK)) { dspi->get_rx(buf & 0xFFFF, dspi); dspi->rcount--; } status = ioread32(dspi->base + SPIFLG); if (unlikely(status & SPIFLG_ERROR_MASK)) { errors = status & SPIFLG_ERROR_MASK; goto out; } if (dspi->wcount > 0 && !(buf & SPIBUF_TXFULL_MASK)) { spidat1 = ioread32(dspi->base + SPIDAT1); dspi->wcount--; spidat1 &= ~0xFFFF; spidat1 |= 0xFFFF & dspi->get_tx(dspi); iowrite32(spidat1, dspi->base + SPIDAT1); } out: return errors; } static void davinci_spi_dma_rx_callback(void *data) { struct davinci_spi *dspi = (struct davinci_spi *)data; dspi->rcount = 0; if (!dspi->wcount && !dspi->rcount) complete(&dspi->done); } static void davinci_spi_dma_tx_callback(void *data) { struct davinci_spi *dspi = (struct davinci_spi *)data; dspi->wcount = 0; if (!dspi->wcount && !dspi->rcount) complete(&dspi->done); } /** * davinci_spi_bufs - functions which will handle transfer data * @spi: spi device on which data transfer to be done * @t: spi transfer in which transfer info is filled * * This function will put data to be transferred into data register * of SPI controller and then wait until the completion will be marked * by the IRQ Handler. */ static int davinci_spi_bufs(struct spi_device *spi, struct spi_transfer *t) { struct davinci_spi *dspi; int data_type, ret = -ENOMEM; u32 tx_data, spidat1; u32 errors = 0; struct davinci_spi_config *spicfg; struct davinci_spi_platform_data *pdata; unsigned uninitialized_var(rx_buf_count); void *dummy_buf = NULL; struct scatterlist sg_rx, sg_tx; dspi = spi_master_get_devdata(spi->master); pdata = &dspi->pdata; spicfg = (struct davinci_spi_config *)spi->controller_data; if (!spicfg) spicfg = &davinci_spi_default_cfg; /* convert len to words based on bits_per_word */ data_type = dspi->bytes_per_word[spi->chip_select]; dspi->tx = t->tx_buf; dspi->rx = t->rx_buf; dspi->wcount = t->len / data_type; dspi->rcount = dspi->wcount; spidat1 = ioread32(dspi->base + SPIDAT1); clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK); set_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK); reinit_completion(&dspi->done); if (spicfg->io_type == SPI_IO_TYPE_INTR) set_io_bits(dspi->base + SPIINT, SPIINT_MASKINT); if (spicfg->io_type != SPI_IO_TYPE_DMA) { /* start the transfer */ dspi->wcount--; tx_data = dspi->get_tx(dspi); spidat1 &= 0xFFFF0000; spidat1 |= tx_data & 0xFFFF; iowrite32(spidat1, dspi->base + SPIDAT1); } else { struct dma_slave_config dma_rx_conf = { .direction = DMA_DEV_TO_MEM, .src_addr = (unsigned long)dspi->pbase + SPIBUF, .src_addr_width = data_type, .src_maxburst = 1, }; struct dma_slave_config dma_tx_conf = { .direction = DMA_MEM_TO_DEV, .dst_addr = (unsigned long)dspi->pbase + SPIDAT1, .dst_addr_width = data_type, .dst_maxburst = 1, }; struct dma_async_tx_descriptor *rxdesc; struct dma_async_tx_descriptor *txdesc; void *buf; dummy_buf = kzalloc(t->len, GFP_KERNEL); if (!dummy_buf) goto err_alloc_dummy_buf; dmaengine_slave_config(dspi->dma_rx, &dma_rx_conf); dmaengine_slave_config(dspi->dma_tx, &dma_tx_conf); sg_init_table(&sg_rx, 1); if (!t->rx_buf) buf = dummy_buf; else buf = t->rx_buf; t->rx_dma = dma_map_single(&spi->dev, buf, t->len, DMA_FROM_DEVICE); if (dma_mapping_error(&spi->dev, !t->rx_dma)) { ret = -EFAULT; goto err_rx_map; } sg_dma_address(&sg_rx) = t->rx_dma; sg_dma_len(&sg_rx) = t->len; sg_init_table(&sg_tx, 1); if (!t->tx_buf) buf = dummy_buf; else buf = (void *)t->tx_buf; t->tx_dma = dma_map_single(&spi->dev, buf, t->len, DMA_TO_DEVICE); if (dma_mapping_error(&spi->dev, t->tx_dma)) { ret = -EFAULT; goto err_tx_map; } sg_dma_address(&sg_tx) = t->tx_dma; sg_dma_len(&sg_tx) = t->len; rxdesc = dmaengine_prep_slave_sg(dspi->dma_rx, &sg_rx, 1, DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!rxdesc) goto err_desc; txdesc = dmaengine_prep_slave_sg(dspi->dma_tx, &sg_tx, 1, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!txdesc) goto err_desc; rxdesc->callback = davinci_spi_dma_rx_callback; rxdesc->callback_param = (void *)dspi; txdesc->callback = davinci_spi_dma_tx_callback; txdesc->callback_param = (void *)dspi; if (pdata->cshold_bug) iowrite16(spidat1 >> 16, dspi->base + SPIDAT1 + 2); dmaengine_submit(rxdesc); dmaengine_submit(txdesc); dma_async_issue_pending(dspi->dma_rx); dma_async_issue_pending(dspi->dma_tx); set_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN); } /* Wait for the transfer to complete */ if (spicfg->io_type != SPI_IO_TYPE_POLL) { if (wait_for_completion_timeout(&dspi->done, HZ) == 0) errors = SPIFLG_TIMEOUT_MASK; } else { while (dspi->rcount > 0 || dspi->wcount > 0) { errors = davinci_spi_process_events(dspi); if (errors) break; cpu_relax(); } } clear_io_bits(dspi->base + SPIINT, SPIINT_MASKALL); if (spicfg->io_type == SPI_IO_TYPE_DMA) { clear_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN); dma_unmap_single(&spi->dev, t->rx_dma, t->len, DMA_FROM_DEVICE); dma_unmap_single(&spi->dev, t->tx_dma, t->len, DMA_TO_DEVICE); kfree(dummy_buf); } clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK); set_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK); /* * Check for bit error, desync error,parity error,timeout error and * receive overflow errors */ if (errors) { ret = davinci_spi_check_error(dspi, errors); WARN(!ret, "%s: error reported but no error found!\n", dev_name(&spi->dev)); return ret; } if (dspi->rcount != 0 || dspi->wcount != 0) { dev_err(&spi->dev, "SPI data transfer error\n"); return -EIO; } return t->len; err_desc: dma_unmap_single(&spi->dev, t->tx_dma, t->len, DMA_TO_DEVICE); err_tx_map: dma_unmap_single(&spi->dev, t->rx_dma, t->len, DMA_FROM_DEVICE); err_rx_map: kfree(dummy_buf); err_alloc_dummy_buf: return ret; } /** * dummy_thread_fn - dummy thread function * @irq: IRQ number for this SPI Master * @context_data: structure for SPI Master controller davinci_spi * * This is to satisfy the request_threaded_irq() API so that the irq * handler is called in interrupt context. */ static irqreturn_t dummy_thread_fn(s32 irq, void *data) { return IRQ_HANDLED; } /** * davinci_spi_irq - Interrupt handler for SPI Master Controller * @irq: IRQ number for this SPI Master * @context_data: structure for SPI Master controller davinci_spi * * ISR will determine that interrupt arrives either for READ or WRITE command. * According to command it will do the appropriate action. It will check * transfer length and if it is not zero then dispatch transfer command again. * If transfer length is zero then it will indicate the COMPLETION so that * davinci_spi_bufs function can go ahead. */ static irqreturn_t davinci_spi_irq(s32 irq, void *data) { struct davinci_spi *dspi = data; int status; status = davinci_spi_process_events(dspi); if (unlikely(status != 0)) clear_io_bits(dspi->base + SPIINT, SPIINT_MASKINT); if ((!dspi->rcount && !dspi->wcount) || status) complete(&dspi->done); return IRQ_HANDLED; } static int davinci_spi_request_dma(struct davinci_spi *dspi) { struct device *sdev = dspi->bitbang.master->dev.parent; dspi->dma_rx = dma_request_chan(sdev, "rx"); if (IS_ERR(dspi->dma_rx)) return PTR_ERR(dspi->dma_rx); dspi->dma_tx = dma_request_chan(sdev, "tx"); if (IS_ERR(dspi->dma_tx)) { dma_release_channel(dspi->dma_rx); return PTR_ERR(dspi->dma_tx); } return 0; } #if defined(CONFIG_OF) /* OF SPI data structure */ struct davinci_spi_of_data { u8 version; u8 prescaler_limit; }; static const struct davinci_spi_of_data dm6441_spi_data = { .version = SPI_VERSION_1, .prescaler_limit = 2, }; static const struct davinci_spi_of_data da830_spi_data = { .version = SPI_VERSION_2, .prescaler_limit = 2, }; static const struct davinci_spi_of_data keystone_spi_data = { .version = SPI_VERSION_1, .prescaler_limit = 0, }; static const struct of_device_id davinci_spi_of_match[] = { { .compatible = "ti,dm6441-spi", .data = &dm6441_spi_data, }, { .compatible = "ti,da830-spi", .data = &da830_spi_data, }, { .compatible = "ti,keystone-spi", .data = &keystone_spi_data, }, { }, }; MODULE_DEVICE_TABLE(of, davinci_spi_of_match); /** * spi_davinci_get_pdata - Get platform data from DTS binding * @pdev: ptr to platform data * @dspi: ptr to driver data * * Parses and populates pdata in dspi from device tree bindings. * * NOTE: Not all platform data params are supported currently. */ static int spi_davinci_get_pdata(struct platform_device *pdev, struct davinci_spi *dspi) { struct device_node *node = pdev->dev.of_node; struct davinci_spi_of_data *spi_data; struct davinci_spi_platform_data *pdata; unsigned int num_cs, intr_line = 0; const struct of_device_id *match; pdata = &dspi->pdata; match = of_match_device(davinci_spi_of_match, &pdev->dev); if (!match) return -ENODEV; spi_data = (struct davinci_spi_of_data *)match->data; pdata->version = spi_data->version; pdata->prescaler_limit = spi_data->prescaler_limit; /* * default num_cs is 1 and all chipsel are internal to the chip * indicated by chip_sel being NULL or cs_gpios being NULL or * set to -ENOENT. num-cs includes internal as well as gpios. * indicated by chip_sel being NULL. GPIO based CS is not * supported yet in DT bindings. */ num_cs = 1; of_property_read_u32(node, "num-cs", &num_cs); pdata->num_chipselect = num_cs; of_property_read_u32(node, "ti,davinci-spi-intr-line", &intr_line); pdata->intr_line = intr_line; return 0; } #else static struct davinci_spi_platform_data *spi_davinci_get_pdata(struct platform_device *pdev, struct davinci_spi *dspi) { return -ENODEV; } #endif /** * davinci_spi_probe - probe function for SPI Master Controller * @pdev: platform_device structure which contains plateform specific data * * According to Linux Device Model this function will be invoked by Linux * with platform_device struct which contains the device specific info. * This function will map the SPI controller's memory, register IRQ, * Reset SPI controller and setting its registers to default value. * It will invoke spi_bitbang_start to create work queue so that client driver * can register transfer method to work queue. */ static int davinci_spi_probe(struct platform_device *pdev) { struct spi_master *master; struct davinci_spi *dspi; struct davinci_spi_platform_data *pdata; struct resource *r; int ret = 0; u32 spipc0; master = spi_alloc_master(&pdev->dev, sizeof(struct davinci_spi)); if (master == NULL) { ret = -ENOMEM; goto err; } platform_set_drvdata(pdev, master); dspi = spi_master_get_devdata(master); if (dev_get_platdata(&pdev->dev)) { pdata = dev_get_platdata(&pdev->dev); dspi->pdata = *pdata; } else { /* update dspi pdata with that from the DT */ ret = spi_davinci_get_pdata(pdev, dspi); if (ret < 0) goto free_master; } /* pdata in dspi is now updated and point pdata to that */ pdata = &dspi->pdata; dspi->bytes_per_word = devm_kzalloc(&pdev->dev, sizeof(*dspi->bytes_per_word) * pdata->num_chipselect, GFP_KERNEL); if (dspi->bytes_per_word == NULL) { ret = -ENOMEM; goto free_master; } r = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (r == NULL) { ret = -ENOENT; goto free_master; } dspi->pbase = r->start; dspi->base = devm_ioremap_resource(&pdev->dev, r); if (IS_ERR(dspi->base)) { ret = PTR_ERR(dspi->base); goto free_master; } ret = platform_get_irq(pdev, 0); if (ret == 0) ret = -EINVAL; if (ret < 0) goto free_master; dspi->irq = ret; ret = devm_request_threaded_irq(&pdev->dev, dspi->irq, davinci_spi_irq, dummy_thread_fn, 0, dev_name(&pdev->dev), dspi); if (ret) goto free_master; dspi->bitbang.master = master; dspi->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(dspi->clk)) { ret = -ENODEV; goto free_master; } clk_prepare_enable(dspi->clk); master->dev.of_node = pdev->dev.of_node; master->bus_num = pdev->id; master->num_chipselect = pdata->num_chipselect; master->bits_per_word_mask = SPI_BPW_RANGE_MASK(2, 16); master->setup = davinci_spi_setup; master->cleanup = davinci_spi_cleanup; dspi->bitbang.chipselect = davinci_spi_chipselect; dspi->bitbang.setup_transfer = davinci_spi_setup_transfer; dspi->prescaler_limit = pdata->prescaler_limit; dspi->version = pdata->version; dspi->bitbang.flags = SPI_NO_CS | SPI_LSB_FIRST | SPI_LOOP; if (dspi->version == SPI_VERSION_2) dspi->bitbang.flags |= SPI_READY; if (pdev->dev.of_node) { int i; for (i = 0; i < pdata->num_chipselect; i++) { int cs_gpio = of_get_named_gpio(pdev->dev.of_node, "cs-gpios", i); if (cs_gpio == -EPROBE_DEFER) { ret = cs_gpio; goto free_clk; } if (gpio_is_valid(cs_gpio)) { ret = devm_gpio_request(&pdev->dev, cs_gpio, dev_name(&pdev->dev)); if (ret) goto free_clk; } } } dspi->bitbang.txrx_bufs = davinci_spi_bufs; ret = davinci_spi_request_dma(dspi); if (ret == -EPROBE_DEFER) { goto free_clk; } else if (ret) { dev_info(&pdev->dev, "DMA is not supported (%d)\n", ret); dspi->dma_rx = NULL; dspi->dma_tx = NULL; } dspi->get_rx = davinci_spi_rx_buf_u8; dspi->get_tx = davinci_spi_tx_buf_u8; init_completion(&dspi->done); /* Reset In/OUT SPI module */ iowrite32(0, dspi->base + SPIGCR0); udelay(100); iowrite32(1, dspi->base + SPIGCR0); /* Set up SPIPC0. CS and ENA init is done in davinci_spi_setup */ spipc0 = SPIPC0_DIFUN_MASK | SPIPC0_DOFUN_MASK | SPIPC0_CLKFUN_MASK; iowrite32(spipc0, dspi->base + SPIPC0); if (pdata->intr_line) iowrite32(SPI_INTLVL_1, dspi->base + SPILVL); else iowrite32(SPI_INTLVL_0, dspi->base + SPILVL); iowrite32(CS_DEFAULT, dspi->base + SPIDEF); /* master mode default */ set_io_bits(dspi->base + SPIGCR1, SPIGCR1_CLKMOD_MASK); set_io_bits(dspi->base + SPIGCR1, SPIGCR1_MASTER_MASK); set_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK); ret = spi_bitbang_start(&dspi->bitbang); if (ret) goto free_dma; dev_info(&pdev->dev, "Controller at 0x%p\n", dspi->base); return ret; free_dma: if (dspi->dma_rx) { dma_release_channel(dspi->dma_rx); dma_release_channel(dspi->dma_tx); } free_clk: clk_disable_unprepare(dspi->clk); free_master: spi_master_put(master); err: return ret; } /** * davinci_spi_remove - remove function for SPI Master Controller * @pdev: platform_device structure which contains plateform specific data * * This function will do the reverse action of davinci_spi_probe function * It will free the IRQ and SPI controller's memory region. * It will also call spi_bitbang_stop to destroy the work queue which was * created by spi_bitbang_start. */ static int davinci_spi_remove(struct platform_device *pdev) { struct davinci_spi *dspi; struct spi_master *master; master = platform_get_drvdata(pdev); dspi = spi_master_get_devdata(master); spi_bitbang_stop(&dspi->bitbang); clk_disable_unprepare(dspi->clk); spi_master_put(master); if (dspi->dma_rx) { dma_release_channel(dspi->dma_rx); dma_release_channel(dspi->dma_tx); } return 0; } static struct platform_driver davinci_spi_driver = { .driver = { .name = "spi_davinci", .of_match_table = of_match_ptr(davinci_spi_of_match), }, .probe = davinci_spi_probe, .remove = davinci_spi_remove, }; module_platform_driver(davinci_spi_driver); MODULE_DESCRIPTION("TI DaVinci SPI Master Controller Driver"); MODULE_LICENSE("GPL"); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">jallen93/linux-vnic-dbg</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drivers/spi/spi-davinci.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">28,957</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086574"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_ #define CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_ #include "chrome/browser/ui/app_list/app_list_controller_delegate_views.h" // Windows specific configuration and behaviour for the AppList. class AppListControllerDelegateWin : public AppListControllerDelegateViews { public: explicit AppListControllerDelegateWin(AppListServiceViews* service); virtual ~AppListControllerDelegateWin(); // AppListControllerDelegate overrides: virtual bool ForceNativeDesktop() const OVERRIDE; virtual gfx::ImageSkia GetWindowIcon() OVERRIDE; private: // AppListcontrollerDelegateImpl: virtual void FillLaunchParams(AppLaunchParams* params) OVERRIDE; DISALLOW_COPY_AND_ASSIGN(AppListControllerDelegateWin); }; #endif // CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">s20121035/rk3288_android5.1_repo</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">external/chromium_org/chrome/browser/ui/views/app_list/win/app_list_controller_delegate_win.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,077</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086575"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// Support for booting from cdroms (the "El Torito" spec). // // Copyright (C) 2008,2009 Kevin O'Connor <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="315a5447585f715a5e525e5f5f5e431f5f5445">[email protected]</a>> // Copyright (C) 2002 MandrakeSoft S.A. // // This file may be distributed under the terms of the GNU LGPLv3 license. #include "disk.h" // cdrom_13 #include "util.h" // memset #include "bregs.h" // struct bregs #include "biosvar.h" // GET_EBDA #include "ata.h" // ATA_CMD_REQUEST_SENSE #include "blockcmd.h" // CDB_CMD_REQUEST_SENSE /**************************************************************** * CD emulation ****************************************************************/ struct drive_s *cdemu_drive_gf VAR16VISIBLE; static int cdemu_read(struct disk_op_s *op) { u16 ebda_seg = get_ebda_seg(); struct drive_s *drive_g; drive_g = GLOBALFLAT2GLOBAL(GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf)); struct disk_op_s dop; dop.drive_g = drive_g; dop.command = op->command; dop.lba = GET_EBDA2(ebda_seg, cdemu.ilba) + op->lba / 4; int count = op->count; op->count = 0; u8 *cdbuf_fl = GET_GLOBAL(bounce_buf_fl); if (op->lba & 3) { // Partial read of first block. dop.count = 1; dop.buf_fl = cdbuf_fl; int ret = process_op(&dop); if (ret) return ret; u8 thiscount = 4 - (op->lba & 3); if (thiscount > count) thiscount = count; count -= thiscount; memcpy_fl(op->buf_fl, cdbuf_fl + (op->lba & 3) * 512, thiscount * 512); op->buf_fl += thiscount * 512; op->count += thiscount; dop.lba++; } if (count > 3) { // Read n number of regular blocks. dop.count = count / 4; dop.buf_fl = op->buf_fl; int ret = process_op(&dop); op->count += dop.count * 4; if (ret) return ret; u8 thiscount = count & ~3; count &= 3; op->buf_fl += thiscount * 512; dop.lba += thiscount / 4; } if (count) { // Partial read on last block. dop.count = 1; dop.buf_fl = cdbuf_fl; int ret = process_op(&dop); if (ret) return ret; u8 thiscount = count; memcpy_fl(op->buf_fl, cdbuf_fl, thiscount * 512); op->count += thiscount; } return DISK_RET_SUCCESS; } int process_cdemu_op(struct disk_op_s *op) { if (!CONFIG_CDROM_EMU) return 0; switch (op->command) { case CMD_READ: return cdemu_read(op); case CMD_WRITE: case CMD_FORMAT: return DISK_RET_EWRITEPROTECT; case CMD_VERIFY: case CMD_RESET: case CMD_SEEK: case CMD_ISREADY: return DISK_RET_SUCCESS; default: op->count = 0; return DISK_RET_EPARAM; } } void cdemu_setup(void) { if (!CONFIG_CDROM_EMU) return; if (!CDCount) return; if (bounce_buf_init() < 0) return; struct drive_s *drive_g = malloc_fseg(sizeof(*drive_g)); if (!drive_g) { warn_noalloc(); free(drive_g); return; } cdemu_drive_gf = drive_g; memset(drive_g, 0, sizeof(*drive_g)); drive_g->type = DTYPE_CDEMU; drive_g->blksize = DISK_SECTOR_SIZE; drive_g->sectors = (u64)-1; } struct eltorito_s { u8 size; u8 media; u8 emulated_drive; u8 controller_index; u32 ilba; u16 device_spec; u16 buffer_segment; u16 load_segment; u16 sector_count; u8 cylinders; u8 sectors; u8 heads; }; #define SET_INT13ET(regs,var,val) \ SET_FARVAR((regs)->ds, ((struct eltorito_s*)((regs)->si+0))->var, (val)) // ElTorito - Terminate disk emu void cdemu_134b(struct bregs *regs) { // FIXME ElTorito Hardcoded u16 ebda_seg = get_ebda_seg(); SET_INT13ET(regs, size, 0x13); SET_INT13ET(regs, media, GET_EBDA2(ebda_seg, cdemu.media)); SET_INT13ET(regs, emulated_drive , GET_EBDA2(ebda_seg, cdemu.emulated_extdrive)); struct drive_s *drive_gf = GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf); u8 cntl_id = 0; if (drive_gf) cntl_id = GET_GLOBALFLAT(drive_gf->cntl_id); SET_INT13ET(regs, controller_index, cntl_id / 2); SET_INT13ET(regs, device_spec, cntl_id % 2); SET_INT13ET(regs, ilba, GET_EBDA2(ebda_seg, cdemu.ilba)); SET_INT13ET(regs, buffer_segment, GET_EBDA2(ebda_seg, cdemu.buffer_segment)); SET_INT13ET(regs, load_segment, GET_EBDA2(ebda_seg, cdemu.load_segment)); SET_INT13ET(regs, sector_count, GET_EBDA2(ebda_seg, cdemu.sector_count)); SET_INT13ET(regs, cylinders, GET_EBDA2(ebda_seg, cdemu.lchs.cylinders)); SET_INT13ET(regs, sectors, GET_EBDA2(ebda_seg, cdemu.lchs.spt)); SET_INT13ET(regs, heads, GET_EBDA2(ebda_seg, cdemu.lchs.heads)); // If we have to terminate emulation if (regs->al == 0x00) { // FIXME ElTorito Various. Should be handled accordingly to spec SET_EBDA2(ebda_seg, cdemu.active, 0x00); // bye bye // XXX - update floppy/hd count. } disk_ret(regs, DISK_RET_SUCCESS); } /**************************************************************** * CD booting ****************************************************************/ int cdrom_boot(struct drive_s *drive_g) { struct disk_op_s dop; int cdid = getDriveId(EXTTYPE_CD, drive_g); memset(&dop, 0, sizeof(dop)); dop.drive_g = drive_g; if (!dop.drive_g || cdid < 0) return 1; int ret = scsi_is_ready(&dop); if (ret) dprintf(1, "scsi_is_ready returned %d\n", ret); // Read the Boot Record Volume Descriptor u8 buffer[2048]; dop.lba = 0x11; dop.count = 1; dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer); ret = cdb_read(&dop); if (ret) return 3; // Validity checks if (buffer[0]) return 4; if (strcmp((char*)&buffer[1], "CD001\001EL TORITO SPECIFICATION") != 0) return 5; // ok, now we calculate the Boot catalog address u32 lba = *(u32*)&buffer[0x47]; // And we read the Boot Catalog dop.lba = lba; dop.count = 1; ret = cdb_read(&dop); if (ret) return 7; // Validation entry if (buffer[0x00] != 0x01) return 8; // Header if (buffer[0x01] != 0x00) return 9; // Platform if (buffer[0x1E] != 0x55) return 10; // key 1 if (buffer[0x1F] != 0xAA) return 10; // key 2 // Initial/Default Entry if (buffer[0x20] != 0x88) return 11; // Bootable u16 ebda_seg = get_ebda_seg(); u8 media = buffer[0x21]; SET_EBDA2(ebda_seg, cdemu.media, media); SET_EBDA2(ebda_seg, cdemu.emulated_drive_gf, dop.drive_g); u16 boot_segment = *(u16*)&buffer[0x22]; if (!boot_segment) boot_segment = 0x07C0; SET_EBDA2(ebda_seg, cdemu.load_segment, boot_segment); SET_EBDA2(ebda_seg, cdemu.buffer_segment, 0x0000); u16 nbsectors = *(u16*)&buffer[0x26]; SET_EBDA2(ebda_seg, cdemu.sector_count, nbsectors); lba = *(u32*)&buffer[0x28]; SET_EBDA2(ebda_seg, cdemu.ilba, lba); // And we read the image in memory dop.lba = lba; dop.count = DIV_ROUND_UP(nbsectors, 4); dop.buf_fl = MAKE_FLATPTR(boot_segment, 0); ret = cdb_read(&dop); if (ret) return 12; if (media == 0) { // No emulation requested - return success. SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, EXTSTART_CD + cdid); return 0; } // Emulation of a floppy/harddisk requested if (! CONFIG_CDROM_EMU || !cdemu_drive_gf) return 13; // Set emulated drive id and increase bios installed hardware // number of devices if (media < 4) { // Floppy emulation SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x00); // XXX - get and set actual floppy count. SETBITS_BDA(equipment_list_flags, 0x41); switch (media) { case 0x01: // 1.2M floppy SET_EBDA2(ebda_seg, cdemu.lchs.spt, 15); SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80); SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2); break; case 0x02: // 1.44M floppy SET_EBDA2(ebda_seg, cdemu.lchs.spt, 18); SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80); SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2); break; case 0x03: // 2.88M floppy SET_EBDA2(ebda_seg, cdemu.lchs.spt, 36); SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80); SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2); break; } } else { // Harddrive emulation SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x80); SET_BDA(hdcount, GET_BDA(hdcount) + 1); // Peak at partition table to get chs. struct mbr_s *mbr = (void*)0; u8 sptcyl = GET_FARVAR(boot_segment, mbr->partitions[0].last.sptcyl); u8 cyllow = GET_FARVAR(boot_segment, mbr->partitions[0].last.cyllow); u8 heads = GET_FARVAR(boot_segment, mbr->partitions[0].last.heads); SET_EBDA2(ebda_seg, cdemu.lchs.spt, sptcyl & 0x3f); SET_EBDA2(ebda_seg, cdemu.lchs.cylinders , ((sptcyl<<2)&0x300) + cyllow + 1); SET_EBDA2(ebda_seg, cdemu.lchs.heads, heads + 1); } // everything is ok, so from now on, the emulation is active SET_EBDA2(ebda_seg, cdemu.active, 0x01); dprintf(6, "cdemu media=%d\n", media); return 0; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bonzini/seabios</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/cdrom.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">9,412</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086576"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">class GstPluginsUgly < Formula desc "GStreamer plugins (well-supported, possibly problematic for distributors)" homepage "https://gstreamer.freedesktop.org/" url "https://gstreamer.freedesktop.org/src/gst-plugins-ugly/gst-plugins-ugly-1.8.0.tar.xz" sha256 "53657ffb7d49ddc4ae40e3f52e56165db4c06eb016891debe2b6c0e9f134eb8c" bottle do sha256 "de81ae62cc34b67d54cb632dce97fb108e4dff3cf839cf99703c23415e64fa8b" => :el_capitan sha256 "5b471670878ccc08926394d973d3ddb5904921e7739ef11bb0f4fe3c67b77f09" => :yosemite sha256 "32c4fc7c2fa4a60390f4346f69b9f4d1bf3a260c94400319d122d2b4c634d5ad" => :mavericks end head do url "https://anongit.freedesktop.org/git/gstreamer/gst-plugins-ugly.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "gettext" depends_on "gst-plugins-base" # The set of optional dependencies is based on the intersection of # gst-plugins-ugly-0.10.17/REQUIREMENTS and Homebrew formulae depends_on "dirac" => :optional depends_on "mad" => :optional depends_on "jpeg" => :optional depends_on "libvorbis" => :optional depends_on "cdparanoia" => :optional depends_on "lame" => :optional depends_on "two-lame" => :optional depends_on "libshout" => :optional depends_on "aalib" => :optional depends_on "libcaca" => :optional depends_on "libdvdread" => :optional depends_on "libmpeg2" => :optional depends_on "a52dec" => :optional depends_on "liboil" => :optional depends_on "flac" => :optional depends_on "gtk+" => :optional depends_on "pango" => :optional depends_on "theora" => :optional depends_on "libmms" => :optional depends_on "x264" => :optional depends_on "opencore-amr" => :optional # Does not work with libcdio 0.9 def install args = %W[ --prefix=#{prefix} --mandir=#{man} --disable-debug --disable-dependency-tracking ] if build.head? ENV["NOCONFIGURE"] = "yes" system "./autogen.sh" end if build.with? "opencore-amr" # Fixes build error, missing includes. # https://github.com/Homebrew/homebrew/issues/14078 nbcflags = `pkg-config --cflags opencore-amrnb`.chomp wbcflags = `pkg-config --cflags opencore-amrwb`.chomp ENV["AMRNB_CFLAGS"] = nbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrnb" ENV["AMRWB_CFLAGS"] = wbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrwb" else args << "--disable-amrnb" << "--disable-amrwb" end system "./configure", *args system "make" system "make", "install" end end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gnubila-france/linuxbrew</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Library/Formula/gst-plugins-ugly.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-2-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,650</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086577"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cask 'netbeans-java-se' do version '8.2' sha256 '91652f03d8abba0ae9d76a612ed909c9f82e4f138cbd510f5d3679280323011b' url "https://download.netbeans.org/netbeans/#{version}/final/bundles/netbeans-#{version}-javase-macosx.dmg" name 'NetBeans IDE for Java SE' homepage 'https://netbeans.org/' pkg "NetBeans #{version}.pkg" uninstall pkgutil: 'org.netbeans.ide.*', delete: '/Applications/NetBeans' end </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wastrachan/homebrew-cask</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Casks/netbeans-java-se.rb</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Ruby</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-2-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">426</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086578"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Siemens ID Mouse driver v0.6 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. Copyright (C) 2004-5 by Florian 'Floe' Echtler <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="680d0b001c040d1a280e1b461c1d05460c0d">[email protected]</a>> and Andreas 'ad' Deresch <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e18085849384928289a18792cf95948ccf8584">[email protected]</a>> Derived from the USB Skeleton driver 1.1, Copyright (C) 2003 Greg Kroah-Hartman (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0a1f080a2d061f020c05430e0200">[email protected]</a>) Additional information provided by Martin Reising <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86cbe7f4f2efe8a8d4e3eff5efe8e1c6e8e7f2f3f4e7eaabe5e9ebf6f3f2efe8e1a8e2e3">[email protected]</a>> */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/completion.h> #include <linux/mutex.h> #include <asm/uaccess.h> #include <linux/usb.h> /* image constants */ #define WIDTH 225 #define HEIGHT 289 #define HEADER "P5 225 289 255 " #define IMGSIZE ((WIDTH * HEIGHT) + sizeof(HEADER)-1) /* version information */ #define DRIVER_VERSION "0.6" #define DRIVER_SHORT "idmouse" #define DRIVER_AUTHOR "Florian 'Floe' Echtler <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d080e051901081f2d0b1e43191800430908">[email protected]</a>>" #define DRIVER_DESC "Siemens ID Mouse FingerTIP Sensor Driver" /* minor number for misc USB devices */ #define USB_IDMOUSE_MINOR_BASE 132 /* vendor and device IDs */ #define ID_SIEMENS 0x0681 #define ID_IDMOUSE 0x0005 #define ID_CHERRY 0x0010 /* device ID table */ static struct usb_device_id idmouse_table[] = { {USB_DEVICE(ID_SIEMENS, ID_IDMOUSE)}, /* Siemens ID Mouse (Professional) */ {USB_DEVICE(ID_SIEMENS, ID_CHERRY )}, /* Cherry FingerTIP ID Board */ {} /* terminating null entry */ }; /* sensor commands */ #define FTIP_RESET 0x20 #define FTIP_ACQUIRE 0x21 #define FTIP_RELEASE 0x22 #define FTIP_BLINK 0x23 /* LSB of value = blink pulse width */ #define FTIP_SCROLL 0x24 #define ftip_command(dev, command, value, index) \ usb_control_msg (dev->udev, usb_sndctrlpipe (dev->udev, 0), command, \ USB_TYPE_VENDOR | USB_RECIP_ENDPOINT | USB_DIR_OUT, value, index, NULL, 0, 1000) MODULE_DEVICE_TABLE(usb, idmouse_table); static DEFINE_MUTEX(open_disc_mutex); /* structure to hold all of our device specific stuff */ struct usb_idmouse { struct usb_device *udev; /* save off the usb device pointer */ struct usb_interface *interface; /* the interface for this device */ unsigned char *bulk_in_buffer; /* the buffer to receive data */ size_t bulk_in_size; /* the maximum bulk packet size */ size_t orig_bi_size; /* same as above, but reported by the device */ __u8 bulk_in_endpointAddr; /* the address of the bulk in endpoint */ int open; /* if the port is open or not */ int present; /* if the device is not disconnected */ struct mutex lock; /* locks this structure */ }; /* local function prototypes */ static ssize_t idmouse_read(struct file *file, char __user *buffer, size_t count, loff_t * ppos); static int idmouse_open(struct inode *inode, struct file *file); static int idmouse_release(struct inode *inode, struct file *file); static int idmouse_probe(struct usb_interface *interface, const struct usb_device_id *id); static void idmouse_disconnect(struct usb_interface *interface); static int idmouse_suspend(struct usb_interface *intf, pm_message_t message); static int idmouse_resume(struct usb_interface *intf); /* file operation pointers */ static const struct file_operations idmouse_fops = { .owner = THIS_MODULE, .read = idmouse_read, .open = idmouse_open, .release = idmouse_release, }; /* class driver information */ static struct usb_class_driver idmouse_class = { .name = "idmouse%d", .fops = &idmouse_fops, .minor_base = USB_IDMOUSE_MINOR_BASE, }; /* usb specific object needed to register this driver with the usb subsystem */ static struct usb_driver idmouse_driver = { .name = DRIVER_SHORT, .probe = idmouse_probe, .disconnect = idmouse_disconnect, .suspend = idmouse_suspend, .resume = idmouse_resume, .reset_resume = idmouse_resume, .id_table = idmouse_table, .supports_autosuspend = 1, }; static int idmouse_create_image(struct usb_idmouse *dev) { int bytes_read; int bulk_read; int result; memcpy(dev->bulk_in_buffer, HEADER, sizeof(HEADER)-1); bytes_read = sizeof(HEADER)-1; /* reset the device and set a fast blink rate */ result = ftip_command(dev, FTIP_RELEASE, 0, 0); if (result < 0) goto reset; result = ftip_command(dev, FTIP_BLINK, 1, 0); if (result < 0) goto reset; /* initialize the sensor - sending this command twice */ /* significantly reduces the rate of failed reads */ result = ftip_command(dev, FTIP_ACQUIRE, 0, 0); if (result < 0) goto reset; result = ftip_command(dev, FTIP_ACQUIRE, 0, 0); if (result < 0) goto reset; /* start the readout - sending this command twice */ /* presumably enables the high dynamic range mode */ result = ftip_command(dev, FTIP_RESET, 0, 0); if (result < 0) goto reset; result = ftip_command(dev, FTIP_RESET, 0, 0); if (result < 0) goto reset; /* loop over a blocking bulk read to get data from the device */ while (bytes_read < IMGSIZE) { result = usb_bulk_msg (dev->udev, usb_rcvbulkpipe (dev->udev, dev->bulk_in_endpointAddr), dev->bulk_in_buffer + bytes_read, dev->bulk_in_size, &bulk_read, 5000); if (result < 0) { /* Maybe this error was caused by the increased packet size? */ /* Reset to the original value and tell userspace to retry. */ if (dev->bulk_in_size != dev->orig_bi_size) { dev->bulk_in_size = dev->orig_bi_size; result = -EAGAIN; } break; } if (signal_pending(current)) { result = -EINTR; break; } bytes_read += bulk_read; } /* reset the device */ reset: ftip_command(dev, FTIP_RELEASE, 0, 0); /* check for valid image */ /* right border should be black (0x00) */ for (bytes_read = sizeof(HEADER)-1 + WIDTH-1; bytes_read < IMGSIZE; bytes_read += WIDTH) if (dev->bulk_in_buffer[bytes_read] != 0x00) return -EAGAIN; /* lower border should be white (0xFF) */ for (bytes_read = IMGSIZE-WIDTH; bytes_read < IMGSIZE-1; bytes_read++) if (dev->bulk_in_buffer[bytes_read] != 0xFF) return -EAGAIN; /* should be IMGSIZE == 65040 */ dbg("read %d bytes fingerprint data", bytes_read); return result; } /* PM operations are nops as this driver does IO only during open() */ static int idmouse_suspend(struct usb_interface *intf, pm_message_t message) { return 0; } static int idmouse_resume(struct usb_interface *intf) { return 0; } static inline void idmouse_delete(struct usb_idmouse *dev) { kfree(dev->bulk_in_buffer); kfree(dev); } static int idmouse_open(struct inode *inode, struct file *file) { struct usb_idmouse *dev; struct usb_interface *interface; int result; /* get the interface from minor number and driver information */ interface = usb_find_interface (&idmouse_driver, iminor (inode)); if (!interface) return -ENODEV; mutex_lock(&open_disc_mutex); /* get the device information block from the interface */ dev = usb_get_intfdata(interface); if (!dev) { mutex_unlock(&open_disc_mutex); return -ENODEV; } /* lock this device */ mutex_lock(&dev->lock); mutex_unlock(&open_disc_mutex); /* check if already open */ if (dev->open) { /* already open, so fail */ result = -EBUSY; } else { /* create a new image and check for success */ result = usb_autopm_get_interface(interface); if (result) goto error; result = idmouse_create_image (dev); if (result) goto error; usb_autopm_put_interface(interface); /* increment our usage count for the driver */ ++dev->open; /* save our object in the file's private structure */ file->private_data = dev; } error: /* unlock this device */ mutex_unlock(&dev->lock); return result; } static int idmouse_release(struct inode *inode, struct file *file) { struct usb_idmouse *dev; dev = file->private_data; if (dev == NULL) return -ENODEV; mutex_lock(&open_disc_mutex); /* lock our device */ mutex_lock(&dev->lock); /* are we really open? */ if (dev->open <= 0) { mutex_unlock(&dev->lock); mutex_unlock(&open_disc_mutex); return -ENODEV; } --dev->open; if (!dev->present) { /* the device was unplugged before the file was released */ mutex_unlock(&dev->lock); mutex_unlock(&open_disc_mutex); idmouse_delete(dev); } else { mutex_unlock(&dev->lock); mutex_unlock(&open_disc_mutex); } return 0; } static ssize_t idmouse_read(struct file *file, char __user *buffer, size_t count, loff_t * ppos) { struct usb_idmouse *dev = file->private_data; int result; /* lock this object */ mutex_lock(&dev->lock); /* verify that the device wasn't unplugged */ if (!dev->present) { mutex_unlock(&dev->lock); return -ENODEV; } result = simple_read_from_buffer(buffer, count, ppos, dev->bulk_in_buffer, IMGSIZE); /* unlock the device */ mutex_unlock(&dev->lock); return result; } static int idmouse_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct usb_idmouse *dev; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int result; /* check if we have gotten the data or the hid interface */ iface_desc = &interface->altsetting[0]; if (iface_desc->desc.bInterfaceClass != 0x0A) return -ENODEV; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (dev == NULL) return -ENOMEM; mutex_init(&dev->lock); dev->udev = udev; dev->interface = interface; /* set up the endpoint information - use only the first bulk-in endpoint */ endpoint = &iface_desc->endpoint[0].desc; if (!dev->bulk_in_endpointAddr && usb_endpoint_is_bulk_in(endpoint)) { /* we found a bulk in endpoint */ dev->orig_bi_size = le16_to_cpu(endpoint->wMaxPacketSize); dev->bulk_in_size = 0x200; /* works _much_ faster */ dev->bulk_in_endpointAddr = endpoint->bEndpointAddress; dev->bulk_in_buffer = kmalloc(IMGSIZE + dev->bulk_in_size, GFP_KERNEL); if (!dev->bulk_in_buffer) { err("Unable to allocate input buffer."); idmouse_delete(dev); return -ENOMEM; } } if (!(dev->bulk_in_endpointAddr)) { err("Unable to find bulk-in endpoint."); idmouse_delete(dev); return -ENODEV; } /* allow device read, write and ioctl */ dev->present = 1; /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); result = usb_register_dev(interface, &idmouse_class); if (result) { /* something prevented us from registering this device */ err("Unble to allocate minor number."); usb_set_intfdata(interface, NULL); idmouse_delete(dev); return result; } /* be noisy */ dev_info(&interface->dev,"%s now attached\n",DRIVER_DESC); return 0; } static void idmouse_disconnect(struct usb_interface *interface) { struct usb_idmouse *dev; /* get device structure */ dev = usb_get_intfdata(interface); /* give back our minor */ usb_deregister_dev(interface, &idmouse_class); mutex_lock(&open_disc_mutex); usb_set_intfdata(interface, NULL); /* lock the device */ mutex_lock(&dev->lock); mutex_unlock(&open_disc_mutex); /* prevent device read, write and ioctl */ dev->present = 0; /* if the device is opened, idmouse_release will clean this up */ if (!dev->open) { mutex_unlock(&dev->lock); idmouse_delete(dev); } else { /* unlock */ mutex_unlock(&dev->lock); } dev_info(&interface->dev, "disconnected\n"); } static int __init usb_idmouse_init(void) { int result; printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":" DRIVER_DESC "\n"); /* register this driver with the USB subsystem */ result = usb_register(&idmouse_driver); if (result) err("Unable to register device (error %d).", result); return result; } static void __exit usb_idmouse_exit(void) { /* deregister this driver with the USB subsystem */ usb_deregister(&idmouse_driver); } module_init(usb_idmouse_init); module_exit(usb_idmouse_exit); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">go2ev-devteam/Gplus_2159_0801</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">openplatform/sdk/os/kernel-2.6.32/drivers/usb/misc/idmouse.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">12,143</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086579"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Input filter ============ This type of filter displays an input field. A second input field is displayed if you select a range operator (between). The two input fields are disabled if you select the `Is defined` and `Is not defined` operators. ### Additionnal attributes for a column annotation for a property |Attribute|Type|Default value|Possible values|Description| |:--:|:--|:--|:--|:--| |inputType|string|text||Define the type of inputs. See [HTML5 input types](http://www.w3schools.com/html5/html5_form_input_types.asp)| </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Roquet87/SIGESRHI</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vendor/apy/datagrid-bundle/APY/DataGridBundle/Resources/doc/columns_configuration/filters/input_filter.md</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Markdown</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">532</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086580"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// SPDX-License-Identifier: GPL-2.0 /* * prepare to run common code * * Copyright (C) 2000 Andrea Arcangeli <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573639332532361724222432793332">[email protected]</a>> SuSE */ #define DISABLE_BRANCH_PROFILING /* cpu_feature_enabled() cannot be used this early */ #define USE_EARLY_PGTABLE_L5 #include <linux/init.h> #include <linux/linkage.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/percpu.h> #include <linux/start_kernel.h> #include <linux/io.h> #include <linux/memblock.h> #include <linux/mem_encrypt.h> #include <asm/processor.h> #include <asm/proto.h> #include <asm/smp.h> #include <asm/setup.h> #include <asm/desc.h> #include <asm/pgtable.h> #include <asm/tlbflush.h> #include <asm/sections.h> #include <asm/kdebug.h> #include <asm/e820/api.h> #include <asm/bios_ebda.h> #include <asm/bootparam_utils.h> #include <asm/microcode.h> #include <asm/kasan.h> #include <asm/fixmap.h> /* * Manage page tables very early on. */ extern pmd_t early_dynamic_pgts[EARLY_DYNAMIC_PAGE_TABLES][PTRS_PER_PMD]; static unsigned int __initdata next_early_pgt; pmdval_t early_pmd_flags = __PAGE_KERNEL_LARGE & ~(_PAGE_GLOBAL | _PAGE_NX); #ifdef CONFIG_X86_5LEVEL unsigned int __pgtable_l5_enabled __ro_after_init; unsigned int pgdir_shift __ro_after_init = 39; EXPORT_SYMBOL(pgdir_shift); unsigned int ptrs_per_p4d __ro_after_init = 1; EXPORT_SYMBOL(ptrs_per_p4d); #endif #ifdef CONFIG_DYNAMIC_MEMORY_LAYOUT unsigned long page_offset_base __ro_after_init = __PAGE_OFFSET_BASE_L4; EXPORT_SYMBOL(page_offset_base); unsigned long vmalloc_base __ro_after_init = __VMALLOC_BASE_L4; EXPORT_SYMBOL(vmalloc_base); unsigned long vmemmap_base __ro_after_init = __VMEMMAP_BASE_L4; EXPORT_SYMBOL(vmemmap_base); #endif #define __head __section(.head.text) static void __head *fixup_pointer(void *ptr, unsigned long physaddr) { return ptr - (void *)_text + (void *)physaddr; } static unsigned long __head *fixup_long(void *ptr, unsigned long physaddr) { return fixup_pointer(ptr, physaddr); } #ifdef CONFIG_X86_5LEVEL static unsigned int __head *fixup_int(void *ptr, unsigned long physaddr) { return fixup_pointer(ptr, physaddr); } static bool __head check_la57_support(unsigned long physaddr) { /* * 5-level paging is detected and enabled at kernel decomression * stage. Only check if it has been enabled there. */ if (!(native_read_cr4() & X86_CR4_LA57)) return false; *fixup_int(&__pgtable_l5_enabled, physaddr) = 1; *fixup_int(&pgdir_shift, physaddr) = 48; *fixup_int(&ptrs_per_p4d, physaddr) = 512; *fixup_long(&page_offset_base, physaddr) = __PAGE_OFFSET_BASE_L5; *fixup_long(&vmalloc_base, physaddr) = __VMALLOC_BASE_L5; *fixup_long(&vmemmap_base, physaddr) = __VMEMMAP_BASE_L5; return true; } #else static bool __head check_la57_support(unsigned long physaddr) { return false; } #endif /* Code in __startup_64() can be relocated during execution, but the compiler * doesn't have to generate PC-relative relocations when accessing globals from * that function. Clang actually does not generate them, which leads to * boot-time crashes. To work around this problem, every global pointer must * be adjusted using fixup_pointer(). */ unsigned long __head __startup_64(unsigned long physaddr, struct boot_params *bp) { unsigned long vaddr, vaddr_end; unsigned long load_delta, *p; unsigned long pgtable_flags; pgdval_t *pgd; p4dval_t *p4d; pudval_t *pud; pmdval_t *pmd, pmd_entry; pteval_t *mask_ptr; bool la57; int i; unsigned int *next_pgt_ptr; la57 = check_la57_support(physaddr); /* Is the address too large? */ if (physaddr >> MAX_PHYSMEM_BITS) for (;;); /* * Compute the delta between the address I am compiled to run at * and the address I am actually running at. */ load_delta = physaddr - (unsigned long)(_text - __START_KERNEL_map); /* Is the address not 2M aligned? */ if (load_delta & ~PMD_PAGE_MASK) for (;;); /* Activate Secure Memory Encryption (SME) if supported and enabled */ sme_enable(bp); /* Include the SME encryption mask in the fixup value */ load_delta += sme_get_me_mask(); /* Fixup the physical addresses in the page table */ pgd = fixup_pointer(&early_top_pgt, physaddr); p = pgd + pgd_index(__START_KERNEL_map); if (la57) *p = (unsigned long)level4_kernel_pgt; else *p = (unsigned long)level3_kernel_pgt; *p += _PAGE_TABLE_NOENC - __START_KERNEL_map + load_delta; if (la57) { p4d = fixup_pointer(&level4_kernel_pgt, physaddr); p4d[511] += load_delta; } pud = fixup_pointer(&level3_kernel_pgt, physaddr); pud[510] += load_delta; pud[511] += load_delta; pmd = fixup_pointer(level2_fixmap_pgt, physaddr); for (i = FIXMAP_PMD_TOP; i > FIXMAP_PMD_TOP - FIXMAP_PMD_NUM; i--) pmd[i] += load_delta; /* * Set up the identity mapping for the switchover. These * entries should *NOT* have the global bit set! This also * creates a bunch of nonsense entries but that is fine -- * it avoids problems around wraparound. */ next_pgt_ptr = fixup_pointer(&next_early_pgt, physaddr); pud = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); pmd = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); pgtable_flags = _KERNPG_TABLE_NOENC + sme_get_me_mask(); if (la57) { p4d = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr); i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD; pgd[i + 0] = (pgdval_t)p4d + pgtable_flags; pgd[i + 1] = (pgdval_t)p4d + pgtable_flags; i = physaddr >> P4D_SHIFT; p4d[(i + 0) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags; p4d[(i + 1) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags; } else { i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD; pgd[i + 0] = (pgdval_t)pud + pgtable_flags; pgd[i + 1] = (pgdval_t)pud + pgtable_flags; } i = physaddr >> PUD_SHIFT; pud[(i + 0) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags; pud[(i + 1) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags; pmd_entry = __PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL; /* Filter out unsupported __PAGE_KERNEL_* bits: */ mask_ptr = fixup_pointer(&__supported_pte_mask, physaddr); pmd_entry &= *mask_ptr; pmd_entry += sme_get_me_mask(); pmd_entry += physaddr; for (i = 0; i < DIV_ROUND_UP(_end - _text, PMD_SIZE); i++) { int idx = i + (physaddr >> PMD_SHIFT); pmd[idx % PTRS_PER_PMD] = pmd_entry + i * PMD_SIZE; } /* * Fixup the kernel text+data virtual addresses. Note that * we might write invalid pmds, when the kernel is relocated * cleanup_highmap() fixes this up along with the mappings * beyond _end. */ pmd = fixup_pointer(level2_kernel_pgt, physaddr); for (i = 0; i < PTRS_PER_PMD; i++) { if (pmd[i] & _PAGE_PRESENT) pmd[i] += load_delta; } /* * Fixup phys_base - remove the memory encryption mask to obtain * the true physical address. */ *fixup_long(&phys_base, physaddr) += load_delta - sme_get_me_mask(); /* Encrypt the kernel and related (if SME is active) */ sme_encrypt_kernel(bp); /* * Clear the memory encryption mask from the .bss..decrypted section. * The bss section will be memset to zero later in the initialization so * there is no need to zero it after changing the memory encryption * attribute. */ if (mem_encrypt_active()) { vaddr = (unsigned long)__start_bss_decrypted; vaddr_end = (unsigned long)__end_bss_decrypted; for (; vaddr < vaddr_end; vaddr += PMD_SIZE) { i = pmd_index(vaddr); pmd[i] -= sme_get_me_mask(); } } /* * Return the SME encryption mask (if SME is active) to be used as a * modifier for the initial pgdir entry programmed into CR3. */ return sme_get_me_mask(); } unsigned long __startup_secondary_64(void) { /* * Return the SME encryption mask (if SME is active) to be used as a * modifier for the initial pgdir entry programmed into CR3. */ return sme_get_me_mask(); } /* Wipe all early page tables except for the kernel symbol map */ static void __init reset_early_page_tables(void) { memset(early_top_pgt, 0, sizeof(pgd_t)*(PTRS_PER_PGD-1)); next_early_pgt = 0; write_cr3(__sme_pa_nodebug(early_top_pgt)); } /* Create a new PMD entry */ int __init __early_make_pgtable(unsigned long address, pmdval_t pmd) { unsigned long physaddr = address - __PAGE_OFFSET; pgdval_t pgd, *pgd_p; p4dval_t p4d, *p4d_p; pudval_t pud, *pud_p; pmdval_t *pmd_p; /* Invalid address or early pgt is done ? */ if (physaddr >= MAXMEM || read_cr3_pa() != __pa_nodebug(early_top_pgt)) return -1; again: pgd_p = &early_top_pgt[pgd_index(address)].pgd; pgd = *pgd_p; /* * The use of __START_KERNEL_map rather than __PAGE_OFFSET here is * critical -- __PAGE_OFFSET would point us back into the dynamic * range and we might end up looping forever... */ if (!pgtable_l5_enabled()) p4d_p = pgd_p; else if (pgd) p4d_p = (p4dval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } p4d_p = (p4dval_t *)early_dynamic_pgts[next_early_pgt++]; memset(p4d_p, 0, sizeof(*p4d_p) * PTRS_PER_P4D); *pgd_p = (pgdval_t)p4d_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } p4d_p += p4d_index(address); p4d = *p4d_p; if (p4d) pud_p = (pudval_t *)((p4d & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } pud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++]; memset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD); *p4d_p = (p4dval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } pud_p += pud_index(address); pud = *pud_p; if (pud) pmd_p = (pmdval_t *)((pud & PTE_PFN_MASK) + __START_KERNEL_map - phys_base); else { if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) { reset_early_page_tables(); goto again; } pmd_p = (pmdval_t *)early_dynamic_pgts[next_early_pgt++]; memset(pmd_p, 0, sizeof(*pmd_p) * PTRS_PER_PMD); *pud_p = (pudval_t)pmd_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE; } pmd_p[pmd_index(address)] = pmd; return 0; } int __init early_make_pgtable(unsigned long address) { unsigned long physaddr = address - __PAGE_OFFSET; pmdval_t pmd; pmd = (physaddr & PMD_MASK) + early_pmd_flags; return __early_make_pgtable(address, pmd); } /* Don't add a printk in there. printk relies on the PDA which is not initialized yet. */ static void __init clear_bss(void) { memset(__bss_start, 0, (unsigned long) __bss_stop - (unsigned long) __bss_start); } static unsigned long get_cmd_line_ptr(void) { unsigned long cmd_line_ptr = boot_params.hdr.cmd_line_ptr; cmd_line_ptr |= (u64)boot_params.ext_cmd_line_ptr << 32; return cmd_line_ptr; } static void __init copy_bootdata(char *real_mode_data) { char * command_line; unsigned long cmd_line_ptr; /* * If SME is active, this will create decrypted mappings of the * boot data in advance of the copy operations. */ sme_map_bootdata(real_mode_data); memcpy(&boot_params, real_mode_data, sizeof(boot_params)); sanitize_boot_params(&boot_params); cmd_line_ptr = get_cmd_line_ptr(); if (cmd_line_ptr) { command_line = __va(cmd_line_ptr); memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE); } /* * The old boot data is no longer needed and won't be reserved, * freeing up that memory for use by the system. If SME is active, * we need to remove the mappings that were created so that the * memory doesn't remain mapped as decrypted. */ sme_unmap_bootdata(real_mode_data); } asmlinkage __visible void __init x86_64_start_kernel(char * real_mode_data) { /* * Build-time sanity checks on the kernel image and module * area mappings. (these are purely build-time and produce no code) */ BUILD_BUG_ON(MODULES_VADDR < __START_KERNEL_map); BUILD_BUG_ON(MODULES_VADDR - __START_KERNEL_map < KERNEL_IMAGE_SIZE); BUILD_BUG_ON(MODULES_LEN + KERNEL_IMAGE_SIZE > 2*PUD_SIZE); BUILD_BUG_ON((__START_KERNEL_map & ~PMD_MASK) != 0); BUILD_BUG_ON((MODULES_VADDR & ~PMD_MASK) != 0); BUILD_BUG_ON(!(MODULES_VADDR > __START_KERNEL)); MAYBE_BUILD_BUG_ON(!(((MODULES_END - 1) & PGDIR_MASK) == (__START_KERNEL & PGDIR_MASK))); BUILD_BUG_ON(__fix_to_virt(__end_of_fixed_addresses) <= MODULES_END); cr4_init_shadow(); /* Kill off the identity-map trampoline */ reset_early_page_tables(); clear_bss(); clear_page(init_top_pgt); /* * SME support may update early_pmd_flags to include the memory * encryption mask, so it needs to be called before anything * that may generate a page fault. */ sme_early_init(); kasan_early_init(); idt_setup_early_handler(); copy_bootdata(__va(real_mode_data)); /* * Load microcode early on BSP. */ load_ucode_bsp(); /* set init_top_pgt kernel high mapping*/ init_top_pgt[511] = early_top_pgt[511]; x86_64_start_reservations(real_mode_data); } void __init x86_64_start_reservations(char *real_mode_data) { /* version is always not zero if it is copied */ if (!boot_params.hdr.version) copy_bootdata(__va(real_mode_data)); x86_early_init_platform_quirks(); switch (boot_params.hdr.hardware_subarch) { case X86_SUBARCH_INTEL_MID: x86_intel_mid_early_setup(); break; default: break; } start_kernel(); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">koct9i/linux</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">arch/x86/kernel/head64.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">13,218</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086581"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001 Intel Corp. * Copyright (c) 2001 La Monte H.P. Yarroll * * This file is part of the SCTP kernel implementation * * This module provides the abstraction for an SCTP association. * * This SCTP implementation 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 SCTP implementation is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied * ************************ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU CC; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4824233b2b3c38652c2d3e2d2427382d3a3b0824213b3c3b663b273d3a2b2d2e273a2f2d66262d3c">[email protected]</a>> * * Or submit a bug report through the following website: * http://www.sf.net/projects/lksctp * * Written or modified by: * La Monte H.P. Yarroll <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8d8c1cfcfd1e8c9cbc586c7dacf">[email protected]</a>> * Karl Knutson <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f242e3d230f2e3b272a212e612c27262c2e2820612623613a3c">[email protected]</a>> * Jon Grimm <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac0cdd8c3c7c7eadfd984c3c8c784c9c5c7">[email protected]</a>> * Xingang Guo <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="057d6c6b62646b622b62706a456c6b7160692b666a68">[email protected]</a>> * Hui Huang <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234b564a0d4b56424d44634d4c484a420d404c4e">[email protected]</a>> * Sridhar Samudrala <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6d6c775e6b6d30777c73307d7173">[email protected]</a>> * Daisy Chang <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="600401091319032015134e09020d4e030f0d">[email protected]</a>> * Ryan Layer <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4f50515c44584f7d484e13545f50135e5250">[email protected]</a>> * Kevin Gao <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f49f91829d9ada93959bb49d9a809198da979b99">[email protected]</a>> * * Any bugs reported given to us we will try to fix... any fixes shared will * be incorporated into the next SCTP release. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/types.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/in.h> #include <net/ipv6.h> #include <net/sctp/sctp.h> #include <net/sctp/sm.h> /* Forward declarations for internal functions. */ static void sctp_assoc_bh_rcv(struct work_struct *work); static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc); static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc); /* Keep track of the new idr low so that we don't re-use association id * numbers too fast. It is protected by they idr spin lock is in the * range of 1 - INT_MAX. */ static u32 idr_low = 1; /* 1st Level Abstractions. */ /* Initialize a new association from provided memory. */ static struct sctp_association *sctp_association_init(struct sctp_association *asoc, const struct sctp_endpoint *ep, const struct sock *sk, sctp_scope_t scope, gfp_t gfp) { struct net *net = sock_net(sk); struct sctp_sock *sp; int i; sctp_paramhdr_t *p; int err; /* Retrieve the SCTP per socket area. */ sp = sctp_sk((struct sock *)sk); /* Discarding const is appropriate here. */ asoc->ep = (struct sctp_endpoint *)ep; sctp_endpoint_hold(asoc->ep); /* Hold the sock. */ asoc->base.sk = (struct sock *)sk; sock_hold(asoc->base.sk); /* Initialize the common base substructure. */ asoc->base.type = SCTP_EP_TYPE_ASSOCIATION; /* Initialize the object handling fields. */ atomic_set(&asoc->base.refcnt, 1); asoc->base.dead = 0; asoc->base.malloced = 0; /* Initialize the bind addr area. */ sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port); asoc->state = SCTP_STATE_CLOSED; /* Set these values from the socket values, a conversion between * millsecons to seconds/microseconds must also be done. */ asoc->cookie_life.tv_sec = sp->assocparams.sasoc_cookie_life / 1000; asoc->cookie_life.tv_usec = (sp->assocparams.sasoc_cookie_life % 1000) * 1000; asoc->frag_point = 0; asoc->user_frag = sp->user_frag; /* Set the association max_retrans and RTO values from the * socket values. */ asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt; asoc->pf_retrans = net->sctp.pf_retrans; asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial); asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max); asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min); asoc->overall_error_count = 0; /* Initialize the association's heartbeat interval based on the * sock configured value. */ asoc->hbinterval = msecs_to_jiffies(sp->hbinterval); /* Initialize path max retrans value. */ asoc->pathmaxrxt = sp->pathmaxrxt; /* Initialize default path MTU. */ asoc->pathmtu = sp->pathmtu; /* Set association default SACK delay */ asoc->sackdelay = msecs_to_jiffies(sp->sackdelay); asoc->sackfreq = sp->sackfreq; /* Set the association default flags controlling * Heartbeat, SACK delay, and Path MTU Discovery. */ asoc->param_flags = sp->param_flags; /* Initialize the maximum mumber of new data packets that can be sent * in a burst. */ asoc->max_burst = sp->max_burst; /* initialize association timers */ asoc->timeouts[SCTP_EVENT_TIMEOUT_NONE] = 0; asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial; asoc->timeouts[SCTP_EVENT_TIMEOUT_T3_RTX] = 0; asoc->timeouts[SCTP_EVENT_TIMEOUT_T4_RTO] = 0; /* sctpimpguide Section 2.12.2 * If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the * recommended value of 5 times 'RTO.Max'. */ asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD] = 5 * asoc->rto_max; asoc->timeouts[SCTP_EVENT_TIMEOUT_HEARTBEAT] = 0; asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay; asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = min_t(unsigned long, sp->autoclose, net->sctp.max_autoclose) * HZ; /* Initializes the timers */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) setup_timer(&asoc->timers[i], sctp_timer_events[i], (unsigned long)asoc); /* Pull default initialization values from the sock options. * Note: This assumes that the values have already been * validated in the sock. */ asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams; asoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams; asoc->max_init_attempts = sp->initmsg.sinit_max_attempts; asoc->max_init_timeo = msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo); /* Allocate storage for the ssnmap after the inbound and outbound * streams have been negotiated during Init. */ asoc->ssnmap = NULL; /* Set the local window size for receive. * This is also the rcvbuf space per association. * RFC 6 - A SCTP receiver MUST be able to receive a minimum of * 1500 bytes in one SCTP packet. */ if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW) asoc->rwnd = SCTP_DEFAULT_MINWINDOW; else asoc->rwnd = sk->sk_rcvbuf/2; asoc->a_rwnd = asoc->rwnd; asoc->rwnd_over = 0; asoc->rwnd_press = 0; /* Use my own max window until I learn something better. */ asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW; /* Set the sndbuf size for transmit. */ asoc->sndbuf_used = 0; /* Initialize the receive memory counter */ atomic_set(&asoc->rmem_alloc, 0); init_waitqueue_head(&asoc->wait); asoc->c.my_vtag = sctp_generate_tag(ep); asoc->peer.i.init_tag = 0; /* INIT needs a vtag of 0. */ asoc->c.peer_vtag = 0; asoc->c.my_ttag = 0; asoc->c.peer_ttag = 0; asoc->c.my_port = ep->base.bind_addr.port; asoc->c.initial_tsn = sctp_generate_tsn(ep); asoc->next_tsn = asoc->c.initial_tsn; asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; asoc->highest_sacked = asoc->ctsn_ack_point; asoc->last_cwr_tsn = asoc->ctsn_ack_point; asoc->unack_data = 0; /* ADDIP Section 4.1 Asconf Chunk Procedures * * When an endpoint has an ASCONF signaled change to be sent to the * remote endpoint it should do the following: * ... * A2) a serial number should be assigned to the chunk. The serial * number SHOULD be a monotonically increasing number. The serial * numbers SHOULD be initialized at the start of the * association to the same value as the initial TSN. */ asoc->addip_serial = asoc->c.initial_tsn; INIT_LIST_HEAD(&asoc->addip_chunk_list); INIT_LIST_HEAD(&asoc->asconf_ack_list); /* Make an empty list of remote transport addresses. */ INIT_LIST_HEAD(&asoc->peer.transport_addr_list); asoc->peer.transport_count = 0; /* RFC 2960 5.1 Normal Establishment of an Association * * After the reception of the first data chunk in an * association the endpoint must immediately respond with a * sack to acknowledge the data chunk. Subsequent * acknowledgements should be done as described in Section * 6.2. * * [We implement this by telling a new association that it * already received one packet.] */ asoc->peer.sack_needed = 1; asoc->peer.sack_cnt = 0; asoc->peer.sack_generation = 1; /* Assume that the peer will tell us if he recognizes ASCONF * as part of INIT exchange. * The sctp_addip_noauth option is there for backward compatibilty * and will revert old behavior. */ asoc->peer.asconf_capable = 0; if (net->sctp.addip_noauth) asoc->peer.asconf_capable = 1; asoc->asconf_addr_del_pending = NULL; asoc->src_out_of_asoc_ok = 0; asoc->new_transport = NULL; /* Create an input queue. */ sctp_inq_init(&asoc->base.inqueue); sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv); /* Create an output queue. */ sctp_outq_init(asoc, &asoc->outqueue); if (!sctp_ulpq_init(&asoc->ulpq, asoc)) goto fail_init; memset(&asoc->peer.tsn_map, 0, sizeof(struct sctp_tsnmap)); asoc->need_ecne = 0; asoc->assoc_id = 0; /* Assume that peer would support both address types unless we are * told otherwise. */ asoc->peer.ipv4_address = 1; if (asoc->base.sk->sk_family == PF_INET6) asoc->peer.ipv6_address = 1; INIT_LIST_HEAD(&asoc->asocs); asoc->autoclose = sp->autoclose; asoc->default_stream = sp->default_stream; asoc->default_ppid = sp->default_ppid; asoc->default_flags = sp->default_flags; asoc->default_context = sp->default_context; asoc->default_timetolive = sp->default_timetolive; asoc->default_rcv_context = sp->default_rcv_context; /* SCTP_GET_ASSOC_STATS COUNTERS */ memset(&asoc->stats, 0, sizeof(struct sctp_priv_assoc_stats)); /* AUTH related initializations */ INIT_LIST_HEAD(&asoc->endpoint_shared_keys); err = sctp_auth_asoc_copy_shkeys(ep, asoc, gfp); if (err) goto fail_init; asoc->active_key_id = ep->active_key_id; asoc->asoc_shared_key = NULL; asoc->default_hmac_id = 0; /* Save the hmacs and chunks list into this association */ if (ep->auth_hmacs_list) memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list, ntohs(ep->auth_hmacs_list->param_hdr.length)); if (ep->auth_chunk_list) memcpy(asoc->c.auth_chunks, ep->auth_chunk_list, ntohs(ep->auth_chunk_list->param_hdr.length)); /* Get the AUTH random number for this association */ p = (sctp_paramhdr_t *)asoc->c.auth_random; p->type = SCTP_PARAM_RANDOM; p->length = htons(sizeof(sctp_paramhdr_t) + SCTP_AUTH_RANDOM_LENGTH); get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH); return asoc; fail_init: sctp_endpoint_put(asoc->ep); sock_put(asoc->base.sk); return NULL; } /* Allocate and initialize a new association */ struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep, const struct sock *sk, sctp_scope_t scope, gfp_t gfp) { struct sctp_association *asoc; asoc = t_new(struct sctp_association, gfp); if (!asoc) goto fail; if (!sctp_association_init(asoc, ep, sk, scope, gfp)) goto fail_init; asoc->base.malloced = 1; SCTP_DBG_OBJCNT_INC(assoc); SCTP_DEBUG_PRINTK("Created asoc %p\n", asoc); return asoc; fail_init: kfree(asoc); fail: return NULL; } /* Free this association if possible. There may still be users, so * the actual deallocation may be delayed. */ void sctp_association_free(struct sctp_association *asoc) { struct sock *sk = asoc->base.sk; struct sctp_transport *transport; struct list_head *pos, *temp; int i; /* Only real associations count against the endpoint, so * don't bother for if this is a temporary association. */ if (!asoc->temp) { list_del(&asoc->asocs); /* Decrement the backlog value for a TCP-style listening * socket. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) sk->sk_ack_backlog--; } /* Mark as dead, so other users can know this structure is * going away. */ asoc->base.dead = 1; /* Dispose of any data lying around in the outqueue. */ sctp_outq_free(&asoc->outqueue); /* Dispose of any pending messages for the upper layer. */ sctp_ulpq_free(&asoc->ulpq); /* Dispose of any pending chunks on the inqueue. */ sctp_inq_free(&asoc->base.inqueue); sctp_tsnmap_free(&asoc->peer.tsn_map); /* Free ssnmap storage. */ sctp_ssnmap_free(asoc->ssnmap); /* Clean up the bound address list. */ sctp_bind_addr_free(&asoc->base.bind_addr); /* Do we need to go through all of our timers and * delete them? To be safe we will try to delete all, but we * should be able to go through and make a guess based * on our state. */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) { if (timer_pending(&asoc->timers[i]) && del_timer(&asoc->timers[i])) sctp_association_put(asoc); } /* Free peer's cached cookie. */ kfree(asoc->peer.cookie); kfree(asoc->peer.peer_random); kfree(asoc->peer.peer_chunks); kfree(asoc->peer.peer_hmacs); /* Release the transport structures. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); list_del_rcu(pos); sctp_transport_free(transport); } asoc->peer.transport_count = 0; sctp_asconf_queue_teardown(asoc); /* Free pending address space being deleted */ if (asoc->asconf_addr_del_pending != NULL) kfree(asoc->asconf_addr_del_pending); /* AUTH - Free the endpoint shared keys */ sctp_auth_destroy_keys(&asoc->endpoint_shared_keys); /* AUTH - Free the association shared key */ sctp_auth_key_put(asoc->asoc_shared_key); sctp_association_put(asoc); } /* Cleanup and free up an association. */ static void sctp_association_destroy(struct sctp_association *asoc) { SCTP_ASSERT(asoc->base.dead, "Assoc is not dead", return); sctp_endpoint_put(asoc->ep); sock_put(asoc->base.sk); if (asoc->assoc_id != 0) { spin_lock_bh(&sctp_assocs_id_lock); idr_remove(&sctp_assocs_id, asoc->assoc_id); spin_unlock_bh(&sctp_assocs_id_lock); } WARN_ON(atomic_read(&asoc->rmem_alloc)); if (asoc->base.malloced) { kfree(asoc); SCTP_DBG_OBJCNT_DEC(assoc); } } /* Change the primary destination address for the peer. */ void sctp_assoc_set_primary(struct sctp_association *asoc, struct sctp_transport *transport) { int changeover = 0; /* it's a changeover only if we already have a primary path * that we are changing */ if (asoc->peer.primary_path != NULL && asoc->peer.primary_path != transport) changeover = 1 ; asoc->peer.primary_path = transport; /* Set a default msg_name for events. */ memcpy(&asoc->peer.primary_addr, &transport->ipaddr, sizeof(union sctp_addr)); /* If the primary path is changing, assume that the * user wants to use this new path. */ if ((transport->state == SCTP_ACTIVE) || (transport->state == SCTP_UNKNOWN)) asoc->peer.active_path = transport; /* * SFR-CACC algorithm: * Upon the receipt of a request to change the primary * destination address, on the data structure for the new * primary destination, the sender MUST do the following: * * 1) If CHANGEOVER_ACTIVE is set, then there was a switch * to this destination address earlier. The sender MUST set * CYCLING_CHANGEOVER to indicate that this switch is a * double switch to the same destination address. * * Really, only bother is we have data queued or outstanding on * the association. */ if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen) return; if (transport->cacc.changeover_active) transport->cacc.cycling_changeover = changeover; /* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that * a changeover has occurred. */ transport->cacc.changeover_active = changeover; /* 3) The sender MUST store the next TSN to be sent in * next_tsn_at_change. */ transport->cacc.next_tsn_at_change = asoc->next_tsn; } /* Remove a transport from an association. */ void sctp_assoc_rm_peer(struct sctp_association *asoc, struct sctp_transport *peer) { struct list_head *pos; struct sctp_transport *transport; SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_rm_peer:association %p addr: ", " port: %d\n", asoc, (&peer->ipaddr), ntohs(peer->ipaddr.v4.sin_port)); /* If we are to remove the current retran_path, update it * to the next peer before removing this peer from the list. */ if (asoc->peer.retran_path == peer) sctp_assoc_update_retran_path(asoc); /* Remove this peer from the list. */ list_del_rcu(&peer->transports); /* Get the first transport of asoc. */ pos = asoc->peer.transport_addr_list.next; transport = list_entry(pos, struct sctp_transport, transports); /* Update any entries that match the peer to be deleted. */ if (asoc->peer.primary_path == peer) sctp_assoc_set_primary(asoc, transport); if (asoc->peer.active_path == peer) asoc->peer.active_path = transport; if (asoc->peer.retran_path == peer) asoc->peer.retran_path = transport; if (asoc->peer.last_data_from == peer) asoc->peer.last_data_from = transport; /* If we remove the transport an INIT was last sent to, set it to * NULL. Combined with the update of the retran path above, this * will cause the next INIT to be sent to the next available * transport, maintaining the cycle. */ if (asoc->init_last_sent_to == peer) asoc->init_last_sent_to = NULL; /* If we remove the transport an SHUTDOWN was last sent to, set it * to NULL. Combined with the update of the retran path above, this * will cause the next SHUTDOWN to be sent to the next available * transport, maintaining the cycle. */ if (asoc->shutdown_last_sent_to == peer) asoc->shutdown_last_sent_to = NULL; /* If we remove the transport an ASCONF was last sent to, set it to * NULL. */ if (asoc->addip_last_asconf && asoc->addip_last_asconf->transport == peer) asoc->addip_last_asconf->transport = NULL; /* If we have something on the transmitted list, we have to * save it off. The best place is the active path. */ if (!list_empty(&peer->transmitted)) { struct sctp_transport *active = asoc->peer.active_path; struct sctp_chunk *ch; /* Reset the transport of each chunk on this list */ list_for_each_entry(ch, &peer->transmitted, transmitted_list) { ch->transport = NULL; ch->rtt_in_progress = 0; } list_splice_tail_init(&peer->transmitted, &active->transmitted); /* Start a T3 timer here in case it wasn't running so * that these migrated packets have a chance to get * retrnasmitted. */ if (!timer_pending(&active->T3_rtx_timer)) if (!mod_timer(&active->T3_rtx_timer, jiffies + active->rto)) sctp_transport_hold(active); } asoc->peer.transport_count--; sctp_transport_free(peer); } /* Add a transport address to an association. */ struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc, const union sctp_addr *addr, const gfp_t gfp, const int peer_state) { struct net *net = sock_net(asoc->base.sk); struct sctp_transport *peer; struct sctp_sock *sp; unsigned short port; sp = sctp_sk(asoc->base.sk); /* AF_INET and AF_INET6 share common port field. */ port = ntohs(addr->v4.sin_port); SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_add_peer:association %p addr: ", " port: %d state:%d\n", asoc, addr, port, peer_state); /* Set the port if it has not been set yet. */ if (0 == asoc->peer.port) asoc->peer.port = port; /* Check to see if this is a duplicate. */ peer = sctp_assoc_lookup_paddr(asoc, addr); if (peer) { /* An UNKNOWN state is only set on transports added by * user in sctp_connectx() call. Such transports should be * considered CONFIRMED per RFC 4960, Section 5.4. */ if (peer->state == SCTP_UNKNOWN) { peer->state = SCTP_ACTIVE; } return peer; } peer = sctp_transport_new(net, addr, gfp); if (!peer) return NULL; sctp_transport_set_owner(peer, asoc); /* Initialize the peer's heartbeat interval based on the * association configured value. */ peer->hbinterval = asoc->hbinterval; /* Set the path max_retrans. */ peer->pathmaxrxt = asoc->pathmaxrxt; /* And the partial failure retrnas threshold */ peer->pf_retrans = asoc->pf_retrans; /* Initialize the peer's SACK delay timeout based on the * association configured value. */ peer->sackdelay = asoc->sackdelay; peer->sackfreq = asoc->sackfreq; /* Enable/disable heartbeat, SACK delay, and path MTU discovery * based on association setting. */ peer->param_flags = asoc->param_flags; sctp_transport_route(peer, NULL, sp); /* Initialize the pmtu of the transport. */ if (peer->param_flags & SPP_PMTUD_DISABLE) { if (asoc->pathmtu) peer->pathmtu = asoc->pathmtu; else peer->pathmtu = SCTP_DEFAULT_MAXSEGMENT; } /* If this is the first transport addr on this association, * initialize the association PMTU to the peer's PMTU. * If not and the current association PMTU is higher than the new * peer's PMTU, reset the association PMTU to the new peer's PMTU. */ if (asoc->pathmtu) asoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu); else asoc->pathmtu = peer->pathmtu; SCTP_DEBUG_PRINTK("sctp_assoc_add_peer:association %p PMTU set to " "%d\n", asoc, asoc->pathmtu); peer->pmtu_pending = 0; asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu); /* The asoc->peer.port might not be meaningful yet, but * initialize the packet structure anyway. */ sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port, asoc->peer.port); /* 7.2.1 Slow-Start * * o The initial cwnd before DATA transmission or after a sufficiently * long idle period MUST be set to * min(4*MTU, max(2*MTU, 4380 bytes)) * * o The initial value of ssthresh MAY be arbitrarily high * (for example, implementations MAY use the size of the * receiver advertised window). */ peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380)); /* At this point, we may not have the receiver's advertised window, * so initialize ssthresh to the default value and it will be set * later when we process the INIT. */ peer->ssthresh = SCTP_DEFAULT_MAXWINDOW; peer->partial_bytes_acked = 0; peer->flight_size = 0; peer->burst_limited = 0; /* Set the transport's RTO.initial value */ peer->rto = asoc->rto_initial; sctp_max_rto(asoc, peer); /* Set the peer's active state. */ peer->state = peer_state; /* Attach the remote transport to our asoc. */ list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list); asoc->peer.transport_count++; /* If we do not yet have a primary path, set one. */ if (!asoc->peer.primary_path) { sctp_assoc_set_primary(asoc, peer); asoc->peer.retran_path = peer; } if (asoc->peer.active_path == asoc->peer.retran_path && peer->state != SCTP_UNCONFIRMED) { asoc->peer.retran_path = peer; } return peer; } /* Delete a transport address from an association. */ void sctp_assoc_del_peer(struct sctp_association *asoc, const union sctp_addr *addr) { struct list_head *pos; struct list_head *temp; struct sctp_transport *transport; list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); if (sctp_cmp_addr_exact(addr, &transport->ipaddr)) { /* Do book keeping for removing the peer and free it. */ sctp_assoc_rm_peer(asoc, transport); break; } } } /* Lookup a transport by address. */ struct sctp_transport *sctp_assoc_lookup_paddr( const struct sctp_association *asoc, const union sctp_addr *address) { struct sctp_transport *t; /* Cycle through all transports searching for a peer address. */ list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) { if (sctp_cmp_addr_exact(address, &t->ipaddr)) return t; } return NULL; } /* Remove all transports except a give one */ void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc, struct sctp_transport *primary) { struct sctp_transport *temp; struct sctp_transport *t; list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list, transports) { /* if the current transport is not the primary one, delete it */ if (t != primary) sctp_assoc_rm_peer(asoc, t); } } /* Engage in transport control operations. * Mark the transport up or down and send a notification to the user. * Select and update the new active and retran paths. */ void sctp_assoc_control_transport(struct sctp_association *asoc, struct sctp_transport *transport, sctp_transport_cmd_t command, sctp_sn_error_t error) { struct sctp_transport *t = NULL; struct sctp_transport *first; struct sctp_transport *second; struct sctp_ulpevent *event; struct sockaddr_storage addr; int spc_state = 0; bool ulp_notify = true; /* Record the transition on the transport. */ switch (command) { case SCTP_TRANSPORT_UP: /* If we are moving from UNCONFIRMED state due * to heartbeat success, report the SCTP_ADDR_CONFIRMED * state to the user, otherwise report SCTP_ADDR_AVAILABLE. */ if (SCTP_UNCONFIRMED == transport->state && SCTP_HEARTBEAT_SUCCESS == error) spc_state = SCTP_ADDR_CONFIRMED; else spc_state = SCTP_ADDR_AVAILABLE; /* Don't inform ULP about transition from PF to * active state and set cwnd to 1, see SCTP * Quick failover draft section 5.1, point 5 */ if (transport->state == SCTP_PF) { ulp_notify = false; transport->cwnd = 1; } transport->state = SCTP_ACTIVE; break; case SCTP_TRANSPORT_DOWN: /* If the transport was never confirmed, do not transition it * to inactive state. Also, release the cached route since * there may be a better route next time. */ if (transport->state != SCTP_UNCONFIRMED) transport->state = SCTP_INACTIVE; else { dst_release(transport->dst); transport->dst = NULL; } spc_state = SCTP_ADDR_UNREACHABLE; break; case SCTP_TRANSPORT_PF: transport->state = SCTP_PF; ulp_notify = false; break; default: return; } /* Generate and send a SCTP_PEER_ADDR_CHANGE notification to the * user. */ if (ulp_notify) { memset(&addr, 0, sizeof(struct sockaddr_storage)); memcpy(&addr, &transport->ipaddr, transport->af_specific->sockaddr_len); event = sctp_ulpevent_make_peer_addr_change(asoc, &addr, 0, spc_state, error, GFP_ATOMIC); if (event) sctp_ulpq_tail_event(&asoc->ulpq, event); } /* Select new active and retran paths. */ /* Look for the two most recently used active transports. * * This code produces the wrong ordering whenever jiffies * rolls over, but we still get usable transports, so we don't * worry about it. */ first = NULL; second = NULL; list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) { if ((t->state == SCTP_INACTIVE) || (t->state == SCTP_UNCONFIRMED) || (t->state == SCTP_PF)) continue; if (!first || t->last_time_heard > first->last_time_heard) { second = first; first = t; } if (!second || t->last_time_heard > second->last_time_heard) second = t; } /* RFC 2960 6.4 Multi-Homed SCTP Endpoints * * By default, an endpoint should always transmit to the * primary path, unless the SCTP user explicitly specifies the * destination transport address (and possibly source * transport address) to use. * * [If the primary is active but not most recent, bump the most * recently used transport.] */ if (((asoc->peer.primary_path->state == SCTP_ACTIVE) || (asoc->peer.primary_path->state == SCTP_UNKNOWN)) && first != asoc->peer.primary_path) { second = first; first = asoc->peer.primary_path; } /* If we failed to find a usable transport, just camp on the * primary, even if it is inactive. */ if (!first) { first = asoc->peer.primary_path; second = asoc->peer.primary_path; } /* Set the active and retran transports. */ asoc->peer.active_path = first; asoc->peer.retran_path = second; } /* Hold a reference to an association. */ void sctp_association_hold(struct sctp_association *asoc) { atomic_inc(&asoc->base.refcnt); } /* Release a reference to an association and cleanup * if there are no more references. */ void sctp_association_put(struct sctp_association *asoc) { if (atomic_dec_and_test(&asoc->base.refcnt)) sctp_association_destroy(asoc); } /* Allocate the next TSN, Transmission Sequence Number, for the given * association. */ __u32 sctp_association_get_next_tsn(struct sctp_association *asoc) { /* From Section 1.6 Serial Number Arithmetic: * Transmission Sequence Numbers wrap around when they reach * 2**32 - 1. That is, the next TSN a DATA chunk MUST use * after transmitting TSN = 2*32 - 1 is TSN = 0. */ __u32 retval = asoc->next_tsn; asoc->next_tsn++; asoc->unack_data++; return retval; } /* Compare two addresses to see if they match. Wildcard addresses * only match themselves. */ int sctp_cmp_addr_exact(const union sctp_addr *ss1, const union sctp_addr *ss2) { struct sctp_af *af; af = sctp_get_af_specific(ss1->sa.sa_family); if (unlikely(!af)) return 0; return af->cmp_addr(ss1, ss2); } /* Return an ecne chunk to get prepended to a packet. * Note: We are sly and return a shared, prealloced chunk. FIXME: * No we don't, but we could/should. */ struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc) { struct sctp_chunk *chunk; /* Send ECNE if needed. * Not being able to allocate a chunk here is not deadly. */ if (asoc->need_ecne) chunk = sctp_make_ecne(asoc, asoc->last_ecne_tsn); else chunk = NULL; return chunk; } /* * Find which transport this TSN was sent on. */ struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc, __u32 tsn) { struct sctp_transport *active; struct sctp_transport *match; struct sctp_transport *transport; struct sctp_chunk *chunk; __be32 key = htonl(tsn); match = NULL; /* * FIXME: In general, find a more efficient data structure for * searching. */ /* * The general strategy is to search each transport's transmitted * list. Return which transport this TSN lives on. * * Let's be hopeful and check the active_path first. * Another optimization would be to know if there is only one * outbound path and not have to look for the TSN at all. * */ active = asoc->peer.active_path; list_for_each_entry(chunk, &active->transmitted, transmitted_list) { if (key == chunk->subh.data_hdr->tsn) { match = active; goto out; } } /* If not found, go search all the other transports. */ list_for_each_entry(transport, &asoc->peer.transport_addr_list, transports) { if (transport == active) break; list_for_each_entry(chunk, &transport->transmitted, transmitted_list) { if (key == chunk->subh.data_hdr->tsn) { match = transport; goto out; } } } out: return match; } /* Is this the association we are looking for? */ struct sctp_transport *sctp_assoc_is_match(struct sctp_association *asoc, struct net *net, const union sctp_addr *laddr, const union sctp_addr *paddr) { struct sctp_transport *transport; if ((htons(asoc->base.bind_addr.port) == laddr->v4.sin_port) && (htons(asoc->peer.port) == paddr->v4.sin_port) && net_eq(sock_net(asoc->base.sk), net)) { transport = sctp_assoc_lookup_paddr(asoc, paddr); if (!transport) goto out; if (sctp_bind_addr_match(&asoc->base.bind_addr, laddr, sctp_sk(asoc->base.sk))) goto out; } transport = NULL; out: return transport; } /* Do delayed input processing. This is scheduled by sctp_rcv(). */ static void sctp_assoc_bh_rcv(struct work_struct *work) { struct sctp_association *asoc = container_of(work, struct sctp_association, base.inqueue.immediate); struct net *net = sock_net(asoc->base.sk); struct sctp_endpoint *ep; struct sctp_chunk *chunk; struct sctp_inq *inqueue; int state; sctp_subtype_t subtype; int error = 0; /* The association should be held so we should be safe. */ ep = asoc->ep; inqueue = &asoc->base.inqueue; sctp_association_hold(asoc); while (NULL != (chunk = sctp_inq_pop(inqueue))) { state = asoc->state; subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type); /* SCTP-AUTH, Section 6.3: * The receiver has a list of chunk types which it expects * to be received only after an AUTH-chunk. This list has * been sent to the peer during the association setup. It * MUST silently discard these chunks if they are not placed * after an AUTH chunk in the packet. */ if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth) continue; /* Remember where the last DATA chunk came from so we * know where to send the SACK. */ if (sctp_chunk_is_data(chunk)) asoc->peer.last_data_from = chunk->transport; else { SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS); asoc->stats.ictrlchunks++; if (chunk->chunk_hdr->type == SCTP_CID_SACK) asoc->stats.isacks++; } if (chunk->transport) chunk->transport->last_time_heard = jiffies; /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype, state, ep, asoc, chunk, GFP_ATOMIC); /* Check to see if the association is freed in response to * the incoming chunk. If so, get out of the while loop. */ if (asoc->base.dead) break; /* If there is an error on chunk, discard this packet. */ if (error && chunk) chunk->pdiscard = 1; } sctp_association_put(asoc); } /* This routine moves an association from its old sk to a new sk. */ void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk) { struct sctp_sock *newsp = sctp_sk(newsk); struct sock *oldsk = assoc->base.sk; /* Delete the association from the old endpoint's list of * associations. */ list_del_init(&assoc->asocs); /* Decrement the backlog value for a TCP-style socket. */ if (sctp_style(oldsk, TCP)) oldsk->sk_ack_backlog--; /* Release references to the old endpoint and the sock. */ sctp_endpoint_put(assoc->ep); sock_put(assoc->base.sk); /* Get a reference to the new endpoint. */ assoc->ep = newsp->ep; sctp_endpoint_hold(assoc->ep); /* Get a reference to the new sock. */ assoc->base.sk = newsk; sock_hold(assoc->base.sk); /* Add the association to the new endpoint's list of associations. */ sctp_endpoint_add_asoc(newsp->ep, assoc); } /* Update an association (possibly from unexpected COOKIE-ECHO processing). */ void sctp_assoc_update(struct sctp_association *asoc, struct sctp_association *new) { struct sctp_transport *trans; struct list_head *pos, *temp; /* Copy in new parameters of peer. */ asoc->c = new->c; asoc->peer.rwnd = new->peer.rwnd; asoc->peer.sack_needed = new->peer.sack_needed; asoc->peer.i = new->peer.i; sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, asoc->peer.i.initial_tsn, GFP_ATOMIC); /* Remove any peer addresses not present in the new association. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { trans = list_entry(pos, struct sctp_transport, transports); if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { sctp_assoc_rm_peer(asoc, trans); continue; } if (asoc->state >= SCTP_STATE_ESTABLISHED) sctp_transport_reset(trans); } /* If the case is A (association restart), use * initial_tsn as next_tsn. If the case is B, use * current next_tsn in case data sent to peer * has been discarded and needs retransmission. */ if (asoc->state >= SCTP_STATE_ESTABLISHED) { asoc->next_tsn = new->next_tsn; asoc->ctsn_ack_point = new->ctsn_ack_point; asoc->adv_peer_ack_point = new->adv_peer_ack_point; /* Reinitialize SSN for both local streams * and peer's streams. */ sctp_ssnmap_clear(asoc->ssnmap); /* Flush the ULP reassembly and ordered queue. * Any data there will now be stale and will * cause problems. */ sctp_ulpq_flush(&asoc->ulpq); /* reset the overall association error count so * that the restarted association doesn't get torn * down on the next retransmission timer. */ asoc->overall_error_count = 0; } else { /* Add any peer addresses from the new association. */ list_for_each_entry(trans, &new->peer.transport_addr_list, transports) { if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) sctp_assoc_add_peer(asoc, &trans->ipaddr, GFP_ATOMIC, trans->state); } asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; if (!asoc->ssnmap) { /* Move the ssnmap. */ asoc->ssnmap = new->ssnmap; new->ssnmap = NULL; } if (!asoc->assoc_id) { /* get a new association id since we don't have one * yet. */ sctp_assoc_set_id(asoc, GFP_ATOMIC); } } /* SCTP-AUTH: Save the peer parameters from the new assocaitions * and also move the association shared keys over */ kfree(asoc->peer.peer_random); asoc->peer.peer_random = new->peer.peer_random; new->peer.peer_random = NULL; kfree(asoc->peer.peer_chunks); asoc->peer.peer_chunks = new->peer.peer_chunks; new->peer.peer_chunks = NULL; kfree(asoc->peer.peer_hmacs); asoc->peer.peer_hmacs = new->peer.peer_hmacs; new->peer.peer_hmacs = NULL; sctp_auth_key_put(asoc->asoc_shared_key); sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); } /* Update the retran path for sending a retransmitted packet. * Round-robin through the active transports, else round-robin * through the inactive transports as this is the next best thing * we can try. */ void sctp_assoc_update_retran_path(struct sctp_association *asoc) { struct sctp_transport *t, *next; struct list_head *head = &asoc->peer.transport_addr_list; struct list_head *pos; if (asoc->peer.transport_count == 1) return; /* Find the next transport in a round-robin fashion. */ t = asoc->peer.retran_path; pos = &t->transports; next = NULL; while (1) { /* Skip the head. */ if (pos->next == head) pos = head->next; else pos = pos->next; t = list_entry(pos, struct sctp_transport, transports); /* We have exhausted the list, but didn't find any * other active transports. If so, use the next * transport. */ if (t == asoc->peer.retran_path) { t = next; break; } /* Try to find an active transport. */ if ((t->state == SCTP_ACTIVE) || (t->state == SCTP_UNKNOWN)) { break; } else { /* Keep track of the next transport in case * we don't find any active transport. */ if (t->state != SCTP_UNCONFIRMED && !next) next = t; } } if (t) asoc->peer.retran_path = t; else t = asoc->peer.retran_path; SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_update_retran_path:association" " %p addr: ", " port: %d\n", asoc, (&t->ipaddr), ntohs(t->ipaddr.v4.sin_port)); } /* Choose the transport for sending retransmit packet. */ struct sctp_transport *sctp_assoc_choose_alter_transport( struct sctp_association *asoc, struct sctp_transport *last_sent_to) { /* If this is the first time packet is sent, use the active path, * else use the retran path. If the last packet was sent over the * retran path, update the retran path and use it. */ if (!last_sent_to) return asoc->peer.active_path; else { if (last_sent_to == asoc->peer.retran_path) sctp_assoc_update_retran_path(asoc); return asoc->peer.retran_path; } } /* Update the association's pmtu and frag_point by going through all the * transports. This routine is called when a transport's PMTU has changed. */ void sctp_assoc_sync_pmtu(struct sock *sk, struct sctp_association *asoc) { struct sctp_transport *t; __u32 pmtu = 0; if (!asoc) return; /* Get the lowest pmtu of all the transports. */ list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) { if (t->pmtu_pending && t->dst) { sctp_transport_update_pmtu(sk, t, dst_mtu(t->dst)); t->pmtu_pending = 0; } if (!pmtu || (t->pathmtu < pmtu)) pmtu = t->pathmtu; } if (pmtu) { asoc->pathmtu = pmtu; asoc->frag_point = sctp_frag_point(asoc, pmtu); } SCTP_DEBUG_PRINTK("%s: asoc:%p, pmtu:%d, frag_point:%d\n", __func__, asoc, asoc->pathmtu, asoc->frag_point); } /* Should we send a SACK to update our peer? */ static inline int sctp_peer_needs_update(struct sctp_association *asoc) { struct net *net = sock_net(asoc->base.sk); switch (asoc->state) { case SCTP_STATE_ESTABLISHED: case SCTP_STATE_SHUTDOWN_PENDING: case SCTP_STATE_SHUTDOWN_RECEIVED: case SCTP_STATE_SHUTDOWN_SENT: if ((asoc->rwnd > asoc->a_rwnd) && ((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32, (asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift), asoc->pathmtu))) return 1; break; default: break; } return 0; } /* Increase asoc's rwnd by len and send any window update SACK if needed. */ void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len) { struct sctp_chunk *sack; struct timer_list *timer; if (asoc->rwnd_over) { if (asoc->rwnd_over >= len) { asoc->rwnd_over -= len; } else { asoc->rwnd += (len - asoc->rwnd_over); asoc->rwnd_over = 0; } } else { asoc->rwnd += len; } /* If we had window pressure, start recovering it * once our rwnd had reached the accumulated pressure * threshold. The idea is to recover slowly, but up * to the initial advertised window. */ if (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) { int change = min(asoc->pathmtu, asoc->rwnd_press); asoc->rwnd += change; asoc->rwnd_press -= change; } SCTP_DEBUG_PRINTK("%s: asoc %p rwnd increased by %d to (%u, %u) " "- %u\n", __func__, asoc, len, asoc->rwnd, asoc->rwnd_over, asoc->a_rwnd); /* Send a window update SACK if the rwnd has increased by at least the * minimum of the association's PMTU and half of the receive buffer. * The algorithm used is similar to the one described in * Section 4.2.3.3 of RFC 1122. */ if (sctp_peer_needs_update(asoc)) { asoc->a_rwnd = asoc->rwnd; SCTP_DEBUG_PRINTK("%s: Sending window update SACK- asoc: %p " "rwnd: %u a_rwnd: %u\n", __func__, asoc, asoc->rwnd, asoc->a_rwnd); sack = sctp_make_sack(asoc); if (!sack) return; asoc->peer.sack_needed = 0; sctp_outq_tail(&asoc->outqueue, sack); /* Stop the SACK timer. */ timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK]; if (timer_pending(timer) && del_timer(timer)) sctp_association_put(asoc); } } /* Decrease asoc's rwnd by len. */ void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len) { int rx_count; int over = 0; SCTP_ASSERT(asoc->rwnd, "rwnd zero", return); SCTP_ASSERT(!asoc->rwnd_over, "rwnd_over not zero", return); if (asoc->ep->rcvbuf_policy) rx_count = atomic_read(&asoc->rmem_alloc); else rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc); /* If we've reached or overflowed our receive buffer, announce * a 0 rwnd if rwnd would still be positive. Store the * the pottential pressure overflow so that the window can be restored * back to original value. */ if (rx_count >= asoc->base.sk->sk_rcvbuf) over = 1; if (asoc->rwnd >= len) { asoc->rwnd -= len; if (over) { asoc->rwnd_press += asoc->rwnd; asoc->rwnd = 0; } } else { asoc->rwnd_over = len - asoc->rwnd; asoc->rwnd = 0; } SCTP_DEBUG_PRINTK("%s: asoc %p rwnd decreased by %d to (%u, %u, %u)\n", __func__, asoc, len, asoc->rwnd, asoc->rwnd_over, asoc->rwnd_press); } /* Build the bind address list for the association based on info from the * local endpoint and the remote peer. */ int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc, sctp_scope_t scope, gfp_t gfp) { int flags; /* Use scoping rules to determine the subset of addresses from * the endpoint. */ flags = (PF_INET6 == asoc->base.sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0; if (asoc->peer.ipv4_address) flags |= SCTP_ADDR4_PEERSUPP; if (asoc->peer.ipv6_address) flags |= SCTP_ADDR6_PEERSUPP; return sctp_bind_addr_copy(sock_net(asoc->base.sk), &asoc->base.bind_addr, &asoc->ep->base.bind_addr, scope, gfp, flags); } /* Build the association's bind address list from the cookie. */ int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc, struct sctp_cookie *cookie, gfp_t gfp) { int var_size2 = ntohs(cookie->peer_init->chunk_hdr.length); int var_size3 = cookie->raw_addr_list_len; __u8 *raw = (__u8 *)cookie->peer_init + var_size2; return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3, asoc->ep->base.bind_addr.port, gfp); } /* Lookup laddr in the bind address list of an association. */ int sctp_assoc_lookup_laddr(struct sctp_association *asoc, const union sctp_addr *laddr) { int found = 0; if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) && sctp_bind_addr_match(&asoc->base.bind_addr, laddr, sctp_sk(asoc->base.sk))) found = 1; return found; } /* Set an association id for a given association */ int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp) { int assoc_id; int error = 0; /* If the id is already assigned, keep it. */ if (asoc->assoc_id) return error; retry: if (unlikely(!idr_pre_get(&sctp_assocs_id, gfp))) return -ENOMEM; spin_lock_bh(&sctp_assocs_id_lock); error = idr_get_new_above(&sctp_assocs_id, (void *)asoc, idr_low, &assoc_id); if (!error) { idr_low = assoc_id + 1; if (idr_low == INT_MAX) idr_low = 1; } spin_unlock_bh(&sctp_assocs_id_lock); if (error == -EAGAIN) goto retry; else if (error) return error; asoc->assoc_id = (sctp_assoc_t) assoc_id; return error; } /* Free the ASCONF queue */ static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc) { struct sctp_chunk *asconf; struct sctp_chunk *tmp; list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) { list_del_init(&asconf->list); sctp_chunk_free(asconf); } } /* Free asconf_ack cache */ static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc) { struct sctp_chunk *ack; struct sctp_chunk *tmp; list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list, transmitted_list) { list_del_init(&ack->transmitted_list); sctp_chunk_free(ack); } } /* Clean up the ASCONF_ACK queue */ void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc) { struct sctp_chunk *ack; struct sctp_chunk *tmp; /* We can remove all the entries from the queue up to * the "Peer-Sequence-Number". */ list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list, transmitted_list) { if (ack->subh.addip_hdr->serial == htonl(asoc->peer.addip_serial)) break; list_del_init(&ack->transmitted_list); sctp_chunk_free(ack); } } /* Find the ASCONF_ACK whose serial number matches ASCONF */ struct sctp_chunk *sctp_assoc_lookup_asconf_ack( const struct sctp_association *asoc, __be32 serial) { struct sctp_chunk *ack; /* Walk through the list of cached ASCONF-ACKs and find the * ack chunk whose serial number matches that of the request. */ list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) { if (ack->subh.addip_hdr->serial == serial) { sctp_chunk_hold(ack); return ack; } } return NULL; } void sctp_asconf_queue_teardown(struct sctp_association *asoc) { /* Free any cached ASCONF_ACK chunk. */ sctp_assoc_free_asconf_acks(asoc); /* Free the ASCONF queue. */ sctp_assoc_free_asconf_queue(asoc); /* Free any cached ASCONF chunk. */ if (asoc->addip_last_asconf) sctp_chunk_free(asoc->addip_last_asconf); } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Webee-IOT/webee210-linux-kernel-3.8</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">net/sctp/associola.c</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">48,370</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086582"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Dataproc_DataprocEmpty extends Google_Model { } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drthomas21/WordPress_Tutorial</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/Dataproc/DataprocEmpty.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">667</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086583"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_DoubleClickBidManager_QueryMetadata extends Google_Collection { protected $collection_key = 'shareEmailAddress'; public $dataRange; public $format; public $googleCloudStoragePathForLatestReport; public $googleDrivePathForLatestReport; public $latestReportRunTimeMs; public $locale; public $reportCount; public $running; public $sendNotification; public $shareEmailAddress; public $title; public function setDataRange($dataRange) { $this->dataRange = $dataRange; } public function getDataRange() { return $this->dataRange; } public function setFormat($format) { $this->format = $format; } public function getFormat() { return $this->format; } public function setGoogleCloudStoragePathForLatestReport($googleCloudStoragePathForLatestReport) { $this->googleCloudStoragePathForLatestReport = $googleCloudStoragePathForLatestReport; } public function getGoogleCloudStoragePathForLatestReport() { return $this->googleCloudStoragePathForLatestReport; } public function setGoogleDrivePathForLatestReport($googleDrivePathForLatestReport) { $this->googleDrivePathForLatestReport = $googleDrivePathForLatestReport; } public function getGoogleDrivePathForLatestReport() { return $this->googleDrivePathForLatestReport; } public function setLatestReportRunTimeMs($latestReportRunTimeMs) { $this->latestReportRunTimeMs = $latestReportRunTimeMs; } public function getLatestReportRunTimeMs() { return $this->latestReportRunTimeMs; } public function setLocale($locale) { $this->locale = $locale; } public function getLocale() { return $this->locale; } public function setReportCount($reportCount) { $this->reportCount = $reportCount; } public function getReportCount() { return $this->reportCount; } public function setRunning($running) { $this->running = $running; } public function getRunning() { return $this->running; } public function setSendNotification($sendNotification) { $this->sendNotification = $sendNotification; } public function getSendNotification() { return $this->sendNotification; } public function setShareEmailAddress($shareEmailAddress) { $this->shareEmailAddress = $shareEmailAddress; } public function getShareEmailAddress() { return $this->shareEmailAddress; } public function setTitle($title) { $this->title = $title; } public function getTitle() { return $this->title; } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">drthomas21/WordPress_Tutorial</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/DoubleClickBidManager/QueryMetadata.php</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">PHP</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,146</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086584"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.changes.ui; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginAware; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.Project; import com.intellij.util.NotNullFunction; import com.intellij.util.pico.ConstructorInjectionComponentAdapter; import com.intellij.util.xmlb.annotations.Attribute; import org.jetbrains.annotations.Nullable; /** * @author yole */ public class ChangesViewContentEP implements PluginAware { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ui.ChangesViewContentEP"); public static final ExtensionPointName<ChangesViewContentEP> EP_NAME = new ExtensionPointName<ChangesViewContentEP>("com.intellij.changesViewContent"); @Attribute("tabName") public String tabName; @Attribute("className") public String className; @Attribute("predicateClassName") public String predicateClassName; private PluginDescriptor myPluginDescriptor; private ChangesViewContentProvider myInstance; public void setPluginDescriptor(PluginDescriptor pluginDescriptor) { myPluginDescriptor = pluginDescriptor; } public String getTabName() { return tabName; } public void setTabName(final String tabName) { this.tabName = tabName; } public String getClassName() { return className; } public void setClassName(final String className) { this.className = className; } public String getPredicateClassName() { return predicateClassName; } public void setPredicateClassName(final String predicateClassName) { this.predicateClassName = predicateClassName; } public ChangesViewContentProvider getInstance(Project project) { if (myInstance == null) { myInstance = (ChangesViewContentProvider) newClassInstance(project, className); } return myInstance; } @Nullable public NotNullFunction<Project, Boolean> newPredicateInstance(Project project) { //noinspection unchecked return predicateClassName != null ? (NotNullFunction<Project, Boolean>)newClassInstance(project, predicateClassName) : null; } private Object newClassInstance(final Project project, final String className) { try { final Class<?> aClass = Class.forName(className, true, myPluginDescriptor == null ? getClass().getClassLoader() : myPluginDescriptor.getPluginClassLoader()); return new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(project.getPicoContainer()); } catch(Exception e) { LOG.error(e); return null; } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">samthor/intellij-community</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentEP.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">3,337</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086585"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">package com.marshalchen.common.demoofui.showcaseview.legacy; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.marshalchen.common.demoofui.R; public class MultipleShowcaseSampleActivity extends Activity { private static final float SHOWCASE_KITTEN_SCALE = 1.2f; private static final float SHOWCASE_LIKE_SCALE = 0.5f; //ShowcaseViews mViews; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.showcase_activity_sample_legacy); findViewById(R.id.buttonLike).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "like_message", Toast.LENGTH_SHORT).show(); } }); //mOptions.block = false; // mViews = new ShowcaseViews(this, // new ShowcaseViews.OnShowcaseAcknowledged() { // @Override // public void onShowCaseAcknowledged(ShowcaseView showcaseView) { // Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show(); // } // }); // mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.image, // R.string.showcase_image_title, // R.string.showcase_image_message, // SHOWCASE_KITTEN_SCALE)); // mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.buttonLike, // R.string.showcase_like_title, // R.string.showcase_like_message, // SHOWCASE_LIKE_SCALE)); // mViews.show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { enableUp(); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void enableUp() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">cymcsg/UltimateAndroid</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">deprecated/UltimateAndroidNormal/DemoOfUI/src/com/marshalchen/common/demoofui/showcaseview/legacy/MultipleShowcaseSampleActivity.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">2,332</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086586"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv, fields from itertools import groupby def grouplines(self, ordered_lines, sortkey): """Return lines from a specified invoice or sale order grouped by category""" grouped_lines = [] for key, valuesiter in groupby(ordered_lines, sortkey): group = {} group['category'] = key group['lines'] = list(v for v in valuesiter) if 'subtotal' in key and key.subtotal is True: group['subtotal'] = sum(line.price_subtotal for line in group['lines']) grouped_lines.append(group) return grouped_lines class SaleLayoutCategory(osv.Model): _name = 'sale_layout.category' _order = 'sequence' _columns = { 'name': fields.char('Name', required=True), 'sequence': fields.integer('Sequence', required=True), 'subtotal': fields.boolean('Add subtotal'), 'separator': fields.boolean('Add separator'), 'pagebreak': fields.boolean('Add pagebreak') } _defaults = { 'subtotal': True, 'separator': True, 'pagebreak': False, 'sequence': 10 } class AccountInvoice(osv.Model): _inherit = 'account.invoice' def sale_layout_lines(self, cr, uid, ids, invoice_id=None, context=None): """ Returns invoice lines from a specified invoice ordered by sale_layout_category sequence. Used in sale_layout module. :Parameters: -'invoice_id' (int): specify the concerned invoice. """ ordered_lines = self.browse(cr, uid, invoice_id, context=context).invoice_line # We chose to group first by category model and, if not present, by invoice name sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else '' return grouplines(self, ordered_lines, sortkey) import openerp class AccountInvoiceLine(osv.Model): _inherit = 'account.invoice.line' _order = 'invoice_id, categ_sequence, sequence, id' sale_layout_cat_id = openerp.fields.Many2one('sale_layout.category', string='Section') categ_sequence = openerp.fields.Integer(related='sale_layout_cat_id.sequence', string='Layout Sequence', store=True) class SaleOrder(osv.Model): _inherit = 'sale.order' def sale_layout_lines(self, cr, uid, ids, order_id=None, context=None): """ Returns order lines from a specified sale ordered by sale_layout_category sequence. Used in sale_layout module. :Parameters: -'order_id' (int): specify the concerned sale order. """ ordered_lines = self.browse(cr, uid, order_id, context=context).order_line sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else '' return grouplines(self, ordered_lines, sortkey) class SaleOrderLine(osv.Model): _inherit = 'sale.order.line' _columns = { 'sale_layout_cat_id': fields.many2one('sale_layout.category', string='Section'), 'categ_sequence': fields.related('sale_layout_cat_id', 'sequence', type='integer', string='Layout Sequence', store=True) # Store is intentionally set in order to keep the "historic" order. } _order = 'order_id, categ_sequence, sequence, id' def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None): """Save the layout when converting to an invoice line.""" invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(cr, uid, line, account_id=account_id, context=context) if line.sale_layout_cat_id: invoice_vals['sale_layout_cat_id'] = line.sale_layout_cat_id.id if line.categ_sequence: invoice_vals['categ_sequence'] = line.categ_sequence return invoice_vals </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">diogocs1/comps</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">web/addons/sale_layout/models/sale_layout.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,907</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086587"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block "><!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <strong> The latest 1.0.x release of this document can be found [here](http://releases.k8s.io/release-1.0/docs/user-guide/connecting-applications.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> # Kubernetes User Guide: Managing Applications: Connecting applications **Table of Contents** <!-- BEGIN MUNGE: GENERATED_TOC --> - [Kubernetes User Guide: Managing Applications: Connecting applications](#kubernetes-user-guide-managing-applications-connecting-applications) - [The Kubernetes model for connecting containers](#the-kubernetes-model-for-connecting-containers) - [Exposing pods to the cluster](#exposing-pods-to-the-cluster) - [Creating a Service](#creating-a-service) - [Accessing the Service](#accessing-the-service) - [Environment Variables](#environment-variables) - [DNS](#dns) - [Securing the Service](#securing-the-service) - [Exposing the Service](#exposing-the-service) - [What's next?](#whats-next) <!-- END MUNGE: GENERATED_TOC --> # The Kubernetes model for connecting containers Now that you have a continuously running, replicated application you can expose it on a network. Before discussing the Kubernetes approach to networking, it is worthwhile to contrast it with the "normal" way networking works with Docker. By default, Docker uses host-private networking, so containers can talk to other containers only if they are on the same machine. In order for Docker containers to communicate across nodes, they must be allocated ports on the machine's own IP address, which are then forwarded or proxied to the containers. This obviously means that containers must either coordinate which ports they use very carefully or else be allocated ports dynamically. Coordinating ports across multiple developers is very difficult to do at scale and exposes users to cluster-level issues outside of their control. Kubernetes assumes that pods can communicate with other pods, regardless of which host they land on. We give every pod its own cluster-private-IP address so you do not need to explicitly create links between pods or mapping container ports to host ports. This means that containers within a Pod can all reach each other’s ports on localhost, and all pods in a cluster can see each other without NAT. The rest of this document will elaborate on how you can run reliable services on such a networking model. This guide uses a simple nginx server to demonstrate proof of concept. The same principles are embodied in a more complete [Jenkins CI application](http://blog.kubernetes.io/2015/07/strong-simple-ssl-for-kubernetes.html). ## Exposing pods to the cluster We did this in a previous example, but lets do it once again and focus on the networking perspective. Create an nginx pod, and note that it has a container port specification: ```yaml $ cat nginxrc.yaml apiVersion: v1 kind: ReplicationController metadata: name: my-nginx spec: replicas: 2 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx ports: - containerPort: 80 ``` This makes it accessible from any node in your cluster. Check the nodes the pod is running on: ```console $ kubectl create -f ./nginxrc.yaml $ kubectl get pods -l app=nginx -o wide my-nginx-6isf4 1/1 Running 0 2h e2e-test-beeps-minion-93ly my-nginx-t26zt 1/1 Running 0 2h e2e-test-beeps-minion-93ly ``` Check your pods' IPs: ```console $ kubectl get pods -l app=nginx -o json | grep podIP "podIP": "10.245.0.15", "podIP": "10.245.0.14", ``` You should be able to ssh into any node in your cluster and curl both IPs. Note that the containers are *not* using port 80 on the node, nor are there any special NAT rules to route traffic to the pod. This means you can run multiple nginx pods on the same node all using the same containerPort and access them from any other pod or node in your cluster using IP. Like Docker, ports can still be published to the host node's interface(s), but the need for this is radically diminished because of the networking model. You can read more about [how we achieve this](../admin/networking.md#how-to-achieve-this) if you’re curious. ## Creating a Service So we have pods running nginx in a flat, cluster wide, address space. In theory, you could talk to these pods directly, but what happens when a node dies? The pods die with it, and the replication controller will create new ones, with different IPs. This is the problem a Service solves. A Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere in your cluster, that all provide the same functionality. When created, each Service is assigned a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service, and will not change while the Service is alive. Pods can be configured to talk to the Service, and know that communication to the Service will be automatically load-balanced out to some pod that is a member of the Service. You can create a Service for your 2 nginx replicas with the following yaml: ```yaml $ cat nginxsvc.yaml apiVersion: v1 kind: Service metadata: name: nginxsvc labels: app: nginx spec: ports: - port: 80 protocol: TCP selector: app: nginx ``` This specification will create a Service which targets TCP port 80 on any Pod with the `app=nginx` label, and expose it on an abstracted Service port (`targetPort`: is the port the container accepts traffic on, `port`: is the abstracted Service port, which can be any port other pods use to access the Service). View [service API object](https://htmlpreview.github.io/?https://k8s.io/kubernetes/HEAD/docs/api-reference/definitions.html#_v1_service) to see the list of supported fields in service definition. Check your Service: ```console $ kubectl get svc NAME LABELS SELECTOR IP(S) PORT(S) nginxsvc app=nginx app=nginx 10.0.116.146 80/TCP ``` As mentioned previously, a Service is backed by a group of pods. These pods are exposed through `endpoints`. The Service's selector will be evaluated continuously and the results will be POSTed to an Endpoints object also named `nginxsvc`. When a pod dies, it is automatically removed from the endpoints, and new pods matching the Service’s selector will automatically get added to the endpoints. Check the endpoints, and note that the IPs are the same as the pods created in the first step: ```console $ kubectl describe svc nginxsvc Name: nginxsvc Namespace: default Labels: app=nginx Selector: app=nginx Type: ClusterIP IP: 10.0.116.146 Port: <unnamed> 80/TCP Endpoints: 10.245.0.14:80,10.245.0.15:80 Session Affinity: None No events. $ kubectl get ep NAME ENDPOINTS nginxsvc 10.245.0.14:80,10.245.0.15:80 ``` You should now be able to curl the nginx Service on `10.0.116.146:80` from any node in your cluster. Note that the Service IP is completely virtual, it never hits the wire, if you’re curious about how this works you can read more about the [service proxy](services.md#virtual-ips-and-service-proxies). ## Accessing the Service Kubernetes supports 2 primary modes of finding a Service - environment variables and DNS. The former works out of the box while the latter requires the [kube-dns cluster addon](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md). ### Environment Variables When a Pod is run on a Node, the kubelet adds a set of environment variables for each active Service. This introduces an ordering problem. To see why, inspect the environment of your running nginx pods: ```console $ kubectl exec my-nginx-6isf4 -- printenv | grep SERVICE KUBERNETES_SERVICE_HOST=10.0.0.1 KUBERNETES_SERVICE_PORT=443 ``` Note there’s no mention of your Service. This is because you created the replicas before the Service. Another disadvantage of doing this is that the scheduler might put both pods on the same machine, which will take your entire Service down if it dies. We can do this the right way by killing the 2 pods and waiting for the replication controller to recreate them. This time around the Service exists *before* the replicas. This will given you scheduler level Service spreading of your pods (provided all your nodes have equal capacity), as well as the right environment variables: ```console $ kubectl scale rc my-nginx --replicas=0; kubectl scale rc my-nginx --replicas=2; $ kubectl get pods -l app=nginx -o wide NAME READY STATUS RESTARTS AGE NODE my-nginx-5j8ok 1/1 Running 0 2m node1 my-nginx-90vaf 1/1 Running 0 2m node2 $ kubectl exec my-nginx-5j8ok -- printenv | grep SERVICE KUBERNETES_SERVICE_PORT=443 NGINXSVC_SERVICE_HOST=10.0.116.146 KUBERNETES_SERVICE_HOST=10.0.0.1 NGINXSVC_SERVICE_PORT=80 ``` ### DNS Kubernetes offers a DNS cluster addon Service that uses skydns to automatically assign dns names to other Services. You can check if it’s running on your cluster: ```console $ kubectl get services kube-dns --namespace=kube-system NAME LABELS SELECTOR IP(S) PORT(S) kube-dns <none> k8s-app=kube-dns 10.0.0.10 53/UDP 53/TCP ``` If it isn’t running, you can [enable it](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md#how-do-i-configure-it). The rest of this section will assume you have a Service with a long lived IP (nginxsvc), and a dns server that has assigned a name to that IP (the kube-dns cluster addon), so you can talk to the Service from any pod in your cluster using standard methods (e.g. gethostbyname). Let’s create another pod to test this: ```yaml $ cat curlpod.yaml apiVersion: v1 kind: Pod metadata: name: curlpod spec: containers: - image: radial/busyboxplus:curl command: - sleep - "3600" imagePullPolicy: IfNotPresent name: curlcontainer restartPolicy: Always ``` And perform a lookup of the nginx Service ```console $ kubectl create -f ./curlpod.yaml default/curlpod $ kubectl get pods curlpod NAME READY STATUS RESTARTS AGE curlpod 1/1 Running 0 18s $ kubectl exec curlpod -- nslookup nginxsvc Server: 10.0.0.10 Address 1: 10.0.0.10 Name: nginxsvc Address 1: 10.0.116.146 ``` ## Securing the Service Till now we have only accessed the nginx server from within the cluster. Before exposing the Service to the internet, you want to make sure the communication channel is secure. For this, you will need: * Self signed certificates for https (unless you already have an identitiy certificate) * An nginx server configured to use the cretificates * A [secret](secrets.md) that makes the certificates accessible to pods You can acquire all these from the [nginx https example](../../examples/https-nginx/README.md), in short: ```console $ make keys secret KEY=/tmp/nginx.key CERT=/tmp/nginx.crt SECRET=/tmp/secret.json $ kubectl create -f /tmp/secret.json secrets/nginxsecret $ kubectl get secrets NAME TYPE DATA default-token-il9rc kubernetes.io/service-account-token 1 nginxsecret Opaque 2 ``` Now modify your nginx replicas to start a https server using the certificate in the secret, and the Service, to expose both ports (80 and 443): ```yaml $ cat nginx-app.yaml apiVersion: v1 kind: Service metadata: name: nginxsvc labels: app: nginx spec: type: NodePort ports: - port: 8080 targetPort: 80 protocol: TCP name: http - port: 443 protocol: TCP name: https selector: app: nginx --- apiVersion: v1 kind: ReplicationController metadata: name: my-nginx spec: replicas: 1 template: metadata: labels: app: nginx spec: volumes: - name: secret-volume secret: secretName: nginxsecret containers: - name: nginxhttps image: bprashanth/nginxhttps:1.0 ports: - containerPort: 443 - containerPort: 80 volumeMounts: - mountPath: /etc/nginx/ssl name: secret-volume ``` Noteworthy points about the nginx-app manifest: - It contains both rc and service specification in the same file - The [nginx server](../../examples/https-nginx/default.conf) serves http traffic on port 80 and https traffic on 443, and nginx Service exposes both ports. - Each container has access to the keys through a volume mounted at /etc/nginx/ssl. This is setup *before* the nginx server is started. ```console $ kubectl delete rc,svc -l app=nginx; kubectl create -f ./nginx-app.yaml replicationcontrollers/my-nginx services/nginxsvc services/nginxsvc replicationcontrollers/my-nginx ``` At this point you can reach the nginx server from any node. ```console $ kubectl get pods -o json | grep -i podip "podIP": "10.1.0.80", node $ curl -k https://10.1.0.80 ... <h1>Welcome to nginx!</h1> ``` Note how we supplied the `-k` parameter to curl in the last step, this is because we don't know anything about the pods running nginx at certificate generation time, so we have to tell curl to ignore the CName mismatch. By creating a Service we linked the CName used in the certificate with the actual DNS name used by pods during Service lookup. Lets test this from a pod (the same secret is being reused for simplicity, the pod only needs nginx.crt to access the Service): ```console $ cat curlpod.yaml vapiVersion: v1 kind: ReplicationController metadata: name: curlrc spec: replicas: 1 template: metadata: labels: app: curlpod spec: volumes: - name: secret-volume secret: secretName: nginxsecret containers: - name: curlpod command: - sh - -c - while true; do sleep 1; done image: radial/busyboxplus:curl volumeMounts: - mountPath: /etc/nginx/ssl name: secret-volume $ kubectl create -f ./curlpod.yaml $ kubectl get pods NAME READY STATUS RESTARTS AGE curlpod 1/1 Running 0 2m my-nginx-7006w 1/1 Running 0 24m $ kubectl exec curlpod -- curl https://nginxsvc --cacert /etc/nginx/ssl/nginx.crt ... <title>Welcome to nginx!</title> ... ``` ## Exposing the Service For some parts of your applications you may want to expose a Service onto an external IP address. Kubernetes supports two ways of doing this: NodePorts and LoadBalancers. The Service created in the last section already used `NodePort`, so your nginx https replica is ready to serve traffic on the internet if your node has a public IP. ```console $ kubectl get svc nginxsvc -o json | grep -i nodeport -C 5 { "name": "http", "protocol": "TCP", "port": 80, "targetPort": 80, "nodePort": 32188 }, { "name": "https", "protocol": "TCP", "port": 443, "targetPort": 443, "nodePort": 30645 } $ kubectl get nodes -o json | grep ExternalIP -C 2 { "type": "ExternalIP", "address": "104.197.63.17" } -- }, { "type": "ExternalIP", "address": "104.154.89.170" } $ curl https://104.197.63.17:30645 -k ... <h1>Welcome to nginx!</h1> ``` Lets now recreate the Service to use a cloud load balancer, just change the `Type` of Service in the nginx-app.yaml from `NodePort` to `LoadBalancer`: ```console $ kubectl delete rc, svc -l app=nginx $ kubectl create -f ./nginx-app.yaml $ kubectl get svc -o json | grep -i ingress -A 5 "ingress": [ { "ip": "104.197.68.43" } ] } $ curl https://104.197.68.43 -k ... <title>Welcome to nginx!</title> ``` ## What's next? [Learn about more Kubernetes features that will help you run containers reliably in production.](production-pods.md) <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/connecting-applications.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS --> </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">vongalpha/origin</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Godeps/_workspace/src/k8s.io/kubernetes/docs/user-guide/connecting-applications.md</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Markdown</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">17,365</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086588"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.dexbacked; import com.google.common.io.ByteStreams; import org.jf.dexlib2.Opcodes; import org.jf.dexlib2.dexbacked.raw.*; import org.jf.dexlib2.dexbacked.util.FixedSizeSet; import org.jf.dexlib2.iface.DexFile; import org.jf.util.ExceptionWithContext; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Set; public class DexBackedDexFile extends BaseDexBuffer implements DexFile { private final Opcodes opcodes; private final int stringCount; private final int stringStartOffset; private final int typeCount; private final int typeStartOffset; private final int protoCount; private final int protoStartOffset; private final int fieldCount; private final int fieldStartOffset; private final int methodCount; private final int methodStartOffset; private final int classCount; private final int classStartOffset; private DexBackedDexFile(Opcodes opcodes, @Nonnull byte[] buf, int offset, boolean verifyMagic) { super(buf); this.opcodes = opcodes; if (verifyMagic) { verifyMagicAndByteOrder(buf, offset); } stringCount = readSmallUint(HeaderItem.STRING_COUNT_OFFSET); stringStartOffset = readSmallUint(HeaderItem.STRING_START_OFFSET); typeCount = readSmallUint(HeaderItem.TYPE_COUNT_OFFSET); typeStartOffset = readSmallUint(HeaderItem.TYPE_START_OFFSET); protoCount = readSmallUint(HeaderItem.PROTO_COUNT_OFFSET); protoStartOffset = readSmallUint(HeaderItem.PROTO_START_OFFSET); fieldCount = readSmallUint(HeaderItem.FIELD_COUNT_OFFSET); fieldStartOffset = readSmallUint(HeaderItem.FIELD_START_OFFSET); methodCount = readSmallUint(HeaderItem.METHOD_COUNT_OFFSET); methodStartOffset = readSmallUint(HeaderItem.METHOD_START_OFFSET); classCount = readSmallUint(HeaderItem.CLASS_COUNT_OFFSET); classStartOffset = readSmallUint(HeaderItem.CLASS_START_OFFSET); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull BaseDexBuffer buf) { this(opcodes, buf.buf); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf, int offset) { this(opcodes, buf, offset, false); } public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf) { this(opcodes, buf, 0, true); } public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is) throws IOException { if (!is.markSupported()) { throw new IllegalArgumentException("InputStream must support mark"); } is.mark(44); byte[] partialHeader = new byte[44]; try { ByteStreams.readFully(is, partialHeader); } catch (EOFException ex) { throw new NotADexFile("File is too short"); } finally { is.reset(); } verifyMagicAndByteOrder(partialHeader, 0); byte[] buf = ByteStreams.toByteArray(is); return new DexBackedDexFile(opcodes, buf, 0, false); } public Opcodes getOpcodes() { return opcodes; } public boolean isOdexFile() { return false; } @Nonnull @Override public Set<? extends DexBackedClassDef> getClasses() { return new FixedSizeSet<DexBackedClassDef>() { @Nonnull @Override public DexBackedClassDef readItem(int index) { return new DexBackedClassDef(DexBackedDexFile.this, getClassDefItemOffset(index)); } @Override public int size() { return classCount; } }; } private static void verifyMagicAndByteOrder(@Nonnull byte[] buf, int offset) { if (!HeaderItem.verifyMagic(buf, offset)) { StringBuilder sb = new StringBuilder("Invalid magic value:"); for (int i=0; i<8; i++) { sb.append(String.format(" %02x", buf[i])); } throw new NotADexFile(sb.toString()); } int endian = HeaderItem.getEndian(buf, offset); if (endian == HeaderItem.BIG_ENDIAN_TAG) { throw new ExceptionWithContext("Big endian dex files are not currently supported"); } if (endian != HeaderItem.LITTLE_ENDIAN_TAG) { throw new ExceptionWithContext("Invalid endian tag: 0x%x", endian); } } public int getStringIdItemOffset(int stringIndex) { if (stringIndex < 0 || stringIndex >= stringCount) { throw new InvalidItemIndex(stringIndex, "String index out of bounds: %d", stringIndex); } return stringStartOffset + stringIndex*StringIdItem.ITEM_SIZE; } public int getTypeIdItemOffset(int typeIndex) { if (typeIndex < 0 || typeIndex >= typeCount) { throw new InvalidItemIndex(typeIndex, "Type index out of bounds: %d", typeIndex); } return typeStartOffset + typeIndex*TypeIdItem.ITEM_SIZE; } public int getFieldIdItemOffset(int fieldIndex) { if (fieldIndex < 0 || fieldIndex >= fieldCount) { throw new InvalidItemIndex(fieldIndex, "Field index out of bounds: %d", fieldIndex); } return fieldStartOffset + fieldIndex*FieldIdItem.ITEM_SIZE; } public int getMethodIdItemOffset(int methodIndex) { if (methodIndex < 0 || methodIndex >= methodCount) { throw new InvalidItemIndex(methodIndex, "Method index out of bounds: %d", methodIndex); } return methodStartOffset + methodIndex*MethodIdItem.ITEM_SIZE; } public int getProtoIdItemOffset(int protoIndex) { if (protoIndex < 0 || protoIndex >= protoCount) { throw new InvalidItemIndex(protoIndex, "Proto index out of bounds: %d", protoIndex); } return protoStartOffset + protoIndex*ProtoIdItem.ITEM_SIZE; } public int getClassDefItemOffset(int classIndex) { if (classIndex < 0 || classIndex >= classCount) { throw new InvalidItemIndex(classIndex, "Class index out of bounds: %d", classIndex); } return classStartOffset + classIndex*ClassDefItem.ITEM_SIZE; } public int getClassCount() { return classCount; } public int getStringCount() { return stringCount; } public int getTypeCount() { return typeCount; } public int getProtoCount() { return protoCount; } public int getFieldCount() { return fieldCount; } public int getMethodCount() { return methodCount; } @Nonnull public String getString(int stringIndex) { int stringOffset = getStringIdItemOffset(stringIndex); int stringDataOffset = readSmallUint(stringOffset); DexReader reader = readerAt(stringDataOffset); int utf16Length = reader.readSmallUleb128(); return reader.readString(utf16Length); } @Nullable public String getOptionalString(int stringIndex) { if (stringIndex == -1) { return null; } return getString(stringIndex); } @Nonnull public String getType(int typeIndex) { int typeOffset = getTypeIdItemOffset(typeIndex); int stringIndex = readSmallUint(typeOffset); return getString(stringIndex); } @Nullable public String getOptionalType(int typeIndex) { if (typeIndex == -1) { return null; } return getType(typeIndex); } @Override @Nonnull public DexReader readerAt(int offset) { return new DexReader(this, offset); } public static class NotADexFile extends RuntimeException { public NotADexFile() { } public NotADexFile(Throwable cause) { super(cause); } public NotADexFile(String message) { super(message); } public NotADexFile(String message, Throwable cause) { super(message, cause); } } public static class InvalidItemIndex extends ExceptionWithContext { private final int itemIndex; public InvalidItemIndex(int itemIndex) { super(""); this.itemIndex = itemIndex; } public InvalidItemIndex(int itemIndex, String message, Object... formatArgs) { super(message, formatArgs); this.itemIndex = itemIndex; } public int getInvalidIndex() { return itemIndex; } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">valery-barysok/Apktool</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">brut.apktool.smali/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/DexBackedDexFile.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">10,213</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086589"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* General netfs cache on cache files internal defs * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd9d5d2cad8d1d1cefdcfd8d9d5dcc993ded2d0">[email protected]</a>) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/fscache-cache.h> #include <linux/timer.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/security.h> struct cachefiles_cache; struct cachefiles_object; extern unsigned cachefiles_debug; #define CACHEFILES_DEBUG_KENTER 1 #define CACHEFILES_DEBUG_KLEAVE 2 #define CACHEFILES_DEBUG_KDEBUG 4 /* * node records */ struct cachefiles_object { struct fscache_object fscache; /* fscache handle */ struct cachefiles_lookup_data *lookup_data; /* cached lookup data */ struct dentry *dentry; /* the file/dir representing this object */ struct dentry *backer; /* backing file */ loff_t i_size; /* object size */ unsigned long flags; #define CACHEFILES_OBJECT_ACTIVE 0 /* T if marked active */ #define CACHEFILES_OBJECT_BURIED 1 /* T if preemptively buried */ atomic_t usage; /* object usage count */ uint8_t type; /* object type */ uint8_t new; /* T if object new */ spinlock_t work_lock; struct rb_node active_node; /* link in active tree (dentry is key) */ }; extern struct kmem_cache *cachefiles_object_jar; /* * Cache files cache definition */ struct cachefiles_cache { struct fscache_cache cache; /* FS-Cache record */ struct vfsmount *mnt; /* mountpoint holding the cache */ struct dentry *graveyard; /* directory into which dead objects go */ struct file *cachefilesd; /* manager daemon handle */ const struct cred *cache_cred; /* security override for accessing cache */ struct mutex daemon_mutex; /* command serialisation mutex */ wait_queue_head_t daemon_pollwq; /* poll waitqueue for daemon */ struct rb_root active_nodes; /* active nodes (can't be culled) */ rwlock_t active_lock; /* lock for active_nodes */ atomic_t gravecounter; /* graveyard uniquifier */ unsigned frun_percent; /* when to stop culling (% files) */ unsigned fcull_percent; /* when to start culling (% files) */ unsigned fstop_percent; /* when to stop allocating (% files) */ unsigned brun_percent; /* when to stop culling (% blocks) */ unsigned bcull_percent; /* when to start culling (% blocks) */ unsigned bstop_percent; /* when to stop allocating (% blocks) */ unsigned bsize; /* cache's block size */ unsigned bshift; /* min(ilog2(PAGE_SIZE / bsize), 0) */ uint64_t frun; /* when to stop culling */ uint64_t fcull; /* when to start culling */ uint64_t fstop; /* when to stop allocating */ sector_t brun; /* when to stop culling */ sector_t bcull; /* when to start culling */ sector_t bstop; /* when to stop allocating */ unsigned long flags; #define CACHEFILES_READY 0 /* T if cache prepared */ #define CACHEFILES_DEAD 1 /* T if cache dead */ #define CACHEFILES_CULLING 2 /* T if cull engaged */ #define CACHEFILES_STATE_CHANGED 3 /* T if state changed (poll trigger) */ char *rootdirname; /* name of cache root directory */ char *secctx; /* LSM security context */ char *tag; /* cache binding tag */ }; /* * backing file read tracking */ struct cachefiles_one_read { wait_queue_t monitor; /* link into monitored waitqueue */ struct page *back_page; /* backing file page we're waiting for */ struct page *netfs_page; /* netfs page we're going to fill */ struct fscache_retrieval *op; /* retrieval op covering this */ struct list_head op_link; /* link in op's todo list */ }; /* * backing file write tracking */ struct cachefiles_one_write { struct page *netfs_page; /* netfs page to copy */ struct cachefiles_object *object; struct list_head obj_link; /* link in object's lists */ fscache_rw_complete_t end_io_func; void *context; }; /* * auxiliary data xattr buffer */ struct cachefiles_xattr { uint16_t len; uint8_t type; uint8_t data[]; }; /* * note change of state for daemon */ static inline void cachefiles_state_changed(struct cachefiles_cache *cache) { set_bit(CACHEFILES_STATE_CHANGED, &cache->flags); wake_up_all(&cache->daemon_pollwq); } /* * bind.c */ extern int cachefiles_daemon_bind(struct cachefiles_cache *cache, char *args); extern void cachefiles_daemon_unbind(struct cachefiles_cache *cache); /* * daemon.c */ extern const struct file_operations cachefiles_daemon_fops; extern int cachefiles_has_space(struct cachefiles_cache *cache, unsigned fnr, unsigned bnr); /* * interface.c */ extern const struct fscache_cache_ops cachefiles_cache_ops; /* * key.c */ extern char *cachefiles_cook_key(const u8 *raw, int keylen, uint8_t type); /* * namei.c */ extern int cachefiles_delete_object(struct cachefiles_cache *cache, struct cachefiles_object *object); extern int cachefiles_walk_to_object(struct cachefiles_object *parent, struct cachefiles_object *object, const char *key, struct cachefiles_xattr *auxdata); extern struct dentry *cachefiles_get_directory(struct cachefiles_cache *cache, struct dentry *dir, const char *name); extern int cachefiles_cull(struct cachefiles_cache *cache, struct dentry *dir, char *filename); extern int cachefiles_check_in_use(struct cachefiles_cache *cache, struct dentry *dir, char *filename); /* * proc.c */ #ifdef CONFIG_CACHEFILES_HISTOGRAM extern atomic_t cachefiles_lookup_histogram[HZ]; extern atomic_t cachefiles_mkdir_histogram[HZ]; extern atomic_t cachefiles_create_histogram[HZ]; extern int __init cachefiles_proc_init(void); extern void cachefiles_proc_cleanup(void); static inline void cachefiles_hist(atomic_t histogram[], unsigned long start_jif) { unsigned long jif = jiffies - start_jif; if (jif >= HZ) jif = HZ - 1; atomic_inc(&histogram[jif]); } #else #define cachefiles_proc_init() (0) #define cachefiles_proc_cleanup() do {} while (0) #define cachefiles_hist(hist, start_jif) do {} while (0) #endif /* * rdwr.c */ extern int cachefiles_read_or_alloc_page(struct fscache_retrieval *, struct page *, gfp_t); extern int cachefiles_read_or_alloc_pages(struct fscache_retrieval *, struct list_head *, unsigned *, gfp_t); extern int cachefiles_allocate_page(struct fscache_retrieval *, struct page *, gfp_t); extern int cachefiles_allocate_pages(struct fscache_retrieval *, struct list_head *, unsigned *, gfp_t); extern int cachefiles_write_page(struct fscache_storage *, struct page *); extern void cachefiles_uncache_page(struct fscache_object *, struct page *); /* * security.c */ extern int cachefiles_get_security_ID(struct cachefiles_cache *cache); extern int cachefiles_determine_cache_security(struct cachefiles_cache *cache, struct dentry *root, const struct cred **_saved_cred); static inline void cachefiles_begin_secure(struct cachefiles_cache *cache, const struct cred **_saved_cred) { *_saved_cred = override_creds(cache->cache_cred); } static inline void cachefiles_end_secure(struct cachefiles_cache *cache, const struct cred *saved_cred) { revert_creds(saved_cred); } /* * xattr.c */ extern int cachefiles_check_object_type(struct cachefiles_object *object); extern int cachefiles_set_object_xattr(struct cachefiles_object *object, struct cachefiles_xattr *auxdata); extern int cachefiles_update_object_xattr(struct cachefiles_object *object, struct cachefiles_xattr *auxdata); extern int cachefiles_check_object_xattr(struct cachefiles_object *object, struct cachefiles_xattr *auxdata); extern int cachefiles_remove_object_xattr(struct cachefiles_cache *cache, struct dentry *dentry); /* * error handling */ #define kerror(FMT, ...) printk(KERN_ERR "CacheFiles: "FMT"\n", ##__VA_ARGS__) #define cachefiles_io_error(___cache, FMT, ...) \ do { \ kerror("I/O Error: " FMT, ##__VA_ARGS__); \ fscache_io_error(&(___cache)->cache); \ set_bit(CACHEFILES_DEAD, &(___cache)->flags); \ } while (0) #define cachefiles_io_error_obj(object, FMT, ...) \ do { \ struct cachefiles_cache *___cache; \ \ ___cache = container_of((object)->fscache.cache, \ struct cachefiles_cache, cache); \ cachefiles_io_error(___cache, FMT, ##__VA_ARGS__); \ } while (0) /* * debug tracing */ #define dbgprintk(FMT, ...) \ printk(KERN_DEBUG "[%-6.6s] "FMT"\n", current->comm, ##__VA_ARGS__) /* make sure we maintain the format strings, even when debugging is disabled */ static inline void _dbprintk(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static inline void _dbprintk(const char *fmt, ...) { } #define kenter(FMT, ...) dbgprintk("==> %s("FMT")", __func__, ##__VA_ARGS__) #define kleave(FMT, ...) dbgprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__) #define kdebug(FMT, ...) dbgprintk(FMT, ##__VA_ARGS__) #if defined(__KDEBUG) #define _enter(FMT, ...) kenter(FMT, ##__VA_ARGS__) #define _leave(FMT, ...) kleave(FMT, ##__VA_ARGS__) #define _debug(FMT, ...) kdebug(FMT, ##__VA_ARGS__) #elif defined(CONFIG_CACHEFILES_DEBUG) #define _enter(FMT, ...) \ do { \ if (cachefiles_debug & CACHEFILES_DEBUG_KENTER) \ kenter(FMT, ##__VA_ARGS__); \ } while (0) #define _leave(FMT, ...) \ do { \ if (cachefiles_debug & CACHEFILES_DEBUG_KLEAVE) \ kleave(FMT, ##__VA_ARGS__); \ } while (0) #define _debug(FMT, ...) \ do { \ if (cachefiles_debug & CACHEFILES_DEBUG_KDEBUG) \ kdebug(FMT, ##__VA_ARGS__); \ } while (0) #else #define _enter(FMT, ...) _dbprintk("==> %s("FMT")", __func__, ##__VA_ARGS__) #define _leave(FMT, ...) _dbprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__) #define _debug(FMT, ...) _dbprintk(FMT, ##__VA_ARGS__) #endif #if 1 /* defined(__KDEBUGALL) */ #define ASSERT(X) \ do { \ if (unlikely(!(X))) { \ printk(KERN_ERR "\n"); \ printk(KERN_ERR "CacheFiles: Assertion failed\n"); \ BUG(); \ } \ } while (0) #define ASSERTCMP(X, OP, Y) \ do { \ if (unlikely(!((X) OP (Y)))) { \ printk(KERN_ERR "\n"); \ printk(KERN_ERR "CacheFiles: Assertion failed\n"); \ printk(KERN_ERR "%lx " #OP " %lx is false\n", \ (unsigned long)(X), (unsigned long)(Y)); \ BUG(); \ } \ } while (0) #define ASSERTIF(C, X) \ do { \ if (unlikely((C) && !(X))) { \ printk(KERN_ERR "\n"); \ printk(KERN_ERR "CacheFiles: Assertion failed\n"); \ BUG(); \ } \ } while (0) #define ASSERTIFCMP(C, X, OP, Y) \ do { \ if (unlikely((C) && !((X) OP (Y)))) { \ printk(KERN_ERR "\n"); \ printk(KERN_ERR "CacheFiles: Assertion failed\n"); \ printk(KERN_ERR "%lx " #OP " %lx is false\n", \ (unsigned long)(X), (unsigned long)(Y)); \ BUG(); \ } \ } while (0) #else #define ASSERT(X) do {} while (0) #define ASSERTCMP(X, OP, Y) do {} while (0) #define ASSERTIF(C, X) do {} while (0) #define ASSERTIFCMP(C, X, OP, Y) do {} while (0) #endif </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">KOala888/GB_kernel</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">linux_kernel_galaxyplayer-master/fs/cachefiles/internal.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">gpl-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">11,228</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086590"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* Copyright 2012 Mozilla Foundation * * 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. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/build/pdf', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsDistBuildPdf = {})); } }(this, function (exports) { // Use strict in our context only - users might not want it 'use strict'; var pdfjsVersion = '1.3.177'; var pdfjsBuild = '51b59bc'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { (function (root, factory) { { factory((root.pdfjsSharedGlobal = {})); } }(this, function (exports) { var globalScope = (typeof window !== 'undefined') ? window : (typeof global !== 'undefined') ? global : (typeof self !== 'undefined') ? self : this; var isWorker = (typeof window === 'undefined'); // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.version = pdfjsVersion; } if (typeof pdfjsVersion !== 'undefined') { globalScope.PDFJS.build = pdfjsBuild; } globalScope.PDFJS.pdfBug = false; exports.globalScope = globalScope; exports.isWorker = isWorker; exports.PDFJS = globalScope.PDFJS; })); (function (root, factory) { { factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = {}; function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); PDFJS.CustomStyle = CustomStyle; exports.CustomStyle = CustomStyle; })); (function (root, factory) { { factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal); } }(this, function (exports, sharedGlobal) { var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- treated as warnings. function deprecated(details) { warn('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { return url; } var i; if (url.charAt(0) === '/') { // absolute path i = baseUrl.indexOf('://'); if (url.charAt(1) === '/') { ++i; } else { i = baseUrl.indexOf('/', i + 3); } return baseUrl.substring(0, i) + url; } else { // relative path var pathLength = baseUrl.length; i = baseUrl.lastIndexOf('#'); pathLength = i >= 0 ? i : pathLength; i = baseUrl.lastIndexOf('?', pathLength); pathLength = i >= 0 ? i : pathLength; var prefixLength = baseUrl.lastIndexOf('/', pathLength); return baseUrl.substring(0, prefixLength + 1) + url; } } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var LinkTarget = PDFJS.LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; function isExternalLinkTargetSet() { if (PDFJS.openExternalLinksInNewWindow) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); if (PDFJS.externalLinkTarget === LinkTarget.NONE) { PDFJS.externalLinkTarget = LinkTarget.BLANK; } // Reset the deprecated parameter, to suppress further warnings. PDFJS.openExternalLinksInNewWindow = false; } switch (PDFJS.externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget); // Reset the external link target, to suppress further warnings. PDFJS.externalLinkTarget = LinkTarget.NONE; return false; } PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } PDFJS.removeNullCharacters = removeNullCharacters; function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgent support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); exports.Uint32ArrayView = Uint32ArrayView; var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArray(v) { return v instanceof Array; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.InvalidPDFException = InvalidPDFException; exports.LinkTarget = LinkTarget; exports.LinkTargetStringMap = LinkTargetStringMap; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NotImplementedException = NotImplementedException; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.assert = assert; exports.bytesToString = bytesToString; exports.combineUrl = combineUrl; exports.createPromiseCapability = createPromiseCapability; exports.deprecated = deprecated; exports.error = error; exports.info = info; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.isInt = isInt; exports.isNum = isNum; exports.isString = isString; exports.isValidUrl = isValidUrl; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; })); (function (root, factory) { { factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; var AnnotationType = sharedUtil.AnnotationType; var Util = sharedUtil.Util; var isExternalLinkTargetSet = sharedUtil.isExternalLinkTargetSet; var LinkTargetStringMap = sharedUtil.LinkTargetStringMap; var removeNullCharacters = sharedUtil.removeNullCharacters; var warn = sharedUtil.warn; var CustomStyle = displayDOMUtils.CustomStyle; /** * @typedef {Object} AnnotationElementParameters * @property {Object} data * @property {HTMLDivElement} layer * @property {PDFPage} page * @property {PageViewport} viewport * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationElementFactory */ function AnnotationElementFactory() {} AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */ { /** * @param {AnnotationElementParameters} parameters * @returns {AnnotationElement} */ create: function AnnotationElementFactory_create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case AnnotationType.LINK: return new LinkAnnotationElement(parameters); case AnnotationType.TEXT: return new TextAnnotationElement(parameters); case AnnotationType.WIDGET: return new WidgetAnnotationElement(parameters); case AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); default: throw new Error('Unimplemented annotation type "' + subtype + '"'); } } }; /** * @class * @alias AnnotationElement */ var AnnotationElement = (function AnnotationElementClosure() { function AnnotationElement(parameters) { this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.container = this._createContainer(); } AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ { /** * Create an empty container for the annotation's HTML element. * * @private * @memberof AnnotationElement * @returns {HTMLSectionElement} */ _createContainer: function AnnotationElement_createContainer() { var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); // Do *not* modify `data.rect`, since that will corrupt the annotation // position on subsequent calls to `_createContainer` (see issue 6804). var rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; }, /** * Render the annotation's HTML element in the empty container. * * @public * @memberof AnnotationElement */ render: function AnnotationElement_render() { throw new Error('Abstract method AnnotationElement.render called'); } }; return AnnotationElement; })(); /** * @class * @alias LinkAnnotationElement */ var LinkAnnotationElement = (function LinkAnnotationElementClosure() { function LinkAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(LinkAnnotationElement, AnnotationElement, { /** * Render the link annotation's HTML element in the empty container. * * @public * @memberof LinkAnnotationElement * @returns {HTMLSectionElement} */ render: function LinkAnnotationElement_render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); link.href = link.title = (this.data.url ? removeNullCharacters(this.data.url) : ''); if (this.data.url && isExternalLinkTargetSet()) { link.target = LinkTargetStringMap[PDFJS.externalLinkTarget]; } // Strip referrer from the URL. if (this.data.url) { link.rel = PDFJS.externalLinkRel; } if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, ('dest' in this.data) ? this.data.dest : null); } } this.container.appendChild(link); return this.container; }, /** * Bind internal links to the link element. * * @private * @param {Object} link * @param {Object} destination * @memberof LinkAnnotationElement */ _bindLink: function LinkAnnotationElement_bindLink(link, destination) { var self = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function() { if (destination) { self.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } }, /** * Bind named actions to the link element. * * @private * @param {Object} link * @param {Object} action * @memberof LinkAnnotationElement */ _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) { var self = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function() { self.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }); return LinkAnnotationElement; })(); /** * @class * @alias TextAnnotationElement */ var TextAnnotationElement = (function TextAnnotationElementClosure() { function TextAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(TextAnnotationElement, AnnotationElement, { /** * Render the text annotation's HTML element in the empty container. * * @public * @memberof TextAnnotationElement * @returns {HTMLSectionElement} */ render: function TextAnnotationElement_render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = PDFJS.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: this.data.name}); if (!this.data.hasPopup) { var popupElement = new PopupElement({ container: this.container, trigger: image, color: this.data.color, title: this.data.title, contents: this.data.contents, hideWrapper: true }); var popup = popupElement.render(); // Position the popup next to the Text annotation's container. popup.style.left = image.style.width; this.container.appendChild(popup); } this.container.appendChild(image); return this.container; } }); return TextAnnotationElement; })(); /** * @class * @alias WidgetAnnotationElement */ var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() { function WidgetAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(WidgetAnnotationElement, AnnotationElement, { /** * Render the widget annotation's HTML element in the empty container. * * @public * @memberof WidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function WidgetAnnotationElement_render() { var content = document.createElement('div'); content.textContent = this.data.fieldValue; var textAlignment = this.data.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var font = (this.data.fontRefName ? this.page.commonObjs.getData(this.data.fontRefName) : null); this._setTextStyle(content, font); this.container.appendChild(content); return this.container; }, /** * Apply text styles to the text in the element. * * @private * @param {HTMLDivElement} element * @param {Object} font * @memberof WidgetAnnotationElement */ _setTextStyle: function WidgetAnnotationElement_setTextStyle(element, font) { // TODO: This duplicates some of the logic in CanvasGraphics.setFont(). var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr'); if (!font) { return; } style.fontWeight = (font.black ? (font.bold ? '900' : 'bold') : (font.bold ? 'bold' : 'normal')); style.fontStyle = (font.italic ? 'italic' : 'normal'); // Use a reasonable default font if the font doesn't specify a fallback. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }); return WidgetAnnotationElement; })(); /** * @class * @alias PopupAnnotationElement */ var PopupAnnotationElement = (function PopupAnnotationElementClosure() { function PopupAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(PopupAnnotationElement, AnnotationElement, { /** * Render the popup annotation's HTML element in the empty container. * * @public * @memberof PopupAnnotationElement * @returns {HTMLSectionElement} */ render: function PopupAnnotationElement_render() { this.container.className = 'popupAnnotation'; var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); // Position the popup next to the parent annotation's container. // PDF viewers ignore a popup annotation's rectangle. var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = (parentLeft + parentWidth) + 'px'; this.container.appendChild(popup.render()); return this.container; } }); return PopupAnnotationElement; })(); /** * @class * @alias PopupElement */ var PopupElement = (function PopupElementClosure() { var BACKGROUND_ENLIGHT = 0.7; function PopupElement(parameters) { this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } PopupElement.prototype = /** @lends PopupElement.prototype */ { /** * Render the popup's HTML element. * * @public * @memberof PopupElement * @returns {HTMLSectionElement} */ render: function PopupElement_render() { var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; // For Popup annotations we hide the entire section because it contains // only the popup. However, for Text annotations without a separate Popup // annotation, we cannot hide the entire container as the image would // disappear too. In that special case, hiding the wrapper suffices. this.hideElement = (this.hideWrapper ? wrapper : this.container); this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { // Enlighten the color. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; // Attach the event listeners to the trigger element. this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; }, /** * Format the contents of the popup by adding newlines where necessary. * * @private * @param {string} contents * @memberof PopupElement * @returns {HTMLParagraphElement} */ _formatContents: function PopupElement_formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { p.appendChild(document.createElement('br')); } } return p; }, /** * Toggle the visibility of the popup. * * @private * @memberof PopupElement */ _toggle: function PopupElement_toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } }, /** * Show the popup. * * @private * @param {boolean} pin * @memberof PopupElement */ _show: function PopupElement_show(pin) { if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } }, /** * Hide the popup. * * @private * @param {boolean} unpin * @memberof PopupElement */ _hide: function PopupElement_hide(unpin) { if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }; return PopupElement; })(); /** * @class * @alias HighlightAnnotationElement */ var HighlightAnnotationElement = ( function HighlightAnnotationElementClosure() { function HighlightAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(HighlightAnnotationElement, AnnotationElement, { /** * Render the highlight annotation's HTML element in the empty container. * * @public * @memberof HighlightAnnotationElement * @returns {HTMLSectionElement} */ render: function HighlightAnnotationElement_render() { this.container.className = 'highlightAnnotation'; return this.container; } }); return HighlightAnnotationElement; })(); /** * @class * @alias UnderlineAnnotationElement */ var UnderlineAnnotationElement = ( function UnderlineAnnotationElementClosure() { function UnderlineAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(UnderlineAnnotationElement, AnnotationElement, { /** * Render the underline annotation's HTML element in the empty container. * * @public * @memberof UnderlineAnnotationElement * @returns {HTMLSectionElement} */ render: function UnderlineAnnotationElement_render() { this.container.className = 'underlineAnnotation'; return this.container; } }); return UnderlineAnnotationElement; })(); /** * @class * @alias SquigglyAnnotationElement */ var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() { function SquigglyAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(SquigglyAnnotationElement, AnnotationElement, { /** * Render the squiggly annotation's HTML element in the empty container. * * @public * @memberof SquigglyAnnotationElement * @returns {HTMLSectionElement} */ render: function SquigglyAnnotationElement_render() { this.container.className = 'squigglyAnnotation'; return this.container; } }); return SquigglyAnnotationElement; })(); /** * @class * @alias StrikeOutAnnotationElement */ var StrikeOutAnnotationElement = ( function StrikeOutAnnotationElementClosure() { function StrikeOutAnnotationElement(parameters) { AnnotationElement.call(this, parameters); } Util.inherit(StrikeOutAnnotationElement, AnnotationElement, { /** * Render the strikeout annotation's HTML element in the empty container. * * @public * @memberof StrikeOutAnnotationElement * @returns {HTMLSectionElement} */ render: function StrikeOutAnnotationElement_render() { this.container.className = 'strikeoutAnnotation'; return this.container; } }); return StrikeOutAnnotationElement; })(); /** * @typedef {Object} AnnotationLayerParameters * @property {PageViewport} viewport * @property {HTMLDivElement} div * @property {Array} annotations * @property {PDFPage} page * @property {IPDFLinkService} linkService */ /** * @class * @alias AnnotationLayer */ var AnnotationLayer = (function AnnotationLayerClosure() { return { /** * Render a new annotation layer with all annotation elements. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ render: function AnnotationLayer_render(parameters) { var annotationElementFactory = new AnnotationElementFactory(); for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data || !data.hasHtml) { continue; } var properties = { data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService }; var element = annotationElementFactory.create(properties); parameters.div.appendChild(element.render()); } }, /** * Update the annotation elements on existing annotation layer. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ update: function AnnotationLayer_update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }; })(); PDFJS.AnnotationLayer = AnnotationLayer; exports.AnnotationLayer = AnnotationLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, sharedGlobal) { var assert = sharedUtil.assert; var bytesToString = sharedUtil.bytesToString; var string32 = sharedUtil.string32; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var isWorker = sharedGlobal.isWorker; function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = (!isWorker && typeof document !== 'undefined' && !!document.fonts); Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers if (userAgent === 'node') { supported = true; } return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData) { this.compiledGlyphs = {}; // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } } Object.defineProperty(FontFaceObject, 'isEvalSupported', { get: function () { var evalSupport = false; if (PDFJS.isEvalSupported) { try { /* jshint evil: true */ new Function(''); evalSupport = true; } catch (e) {} } return shadow(this, 'isEvalSupported', evalSupport); }, enumerable: true, configurable: true }); FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (FontFaceObject.isEvalSupported) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; })); (function (root, factory) { { factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var error = sharedUtil.error; var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); exports.Metadata = Metadata; })); (function (root, factory) { { factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var Util = sharedUtil.Util; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var warn = sharedUtil.warn; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; exports.SVGGraphics = SVGGraphics; })); (function (root, factory) { { factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) { var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var CustomStyle = displayDOMUtils.CustomStyle; var PDFJS = sharedGlobal.PDFJS; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PDFJS.PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } function appendText(textDivs, viewport, geom, styles) { var style = styles[geom.fontName]; var textDiv = document.createElement('div'); textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDiv.dataset.isWhitespace = true; return; } var tx = Util.transform(viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } textDiv.style.left = left + 'px'; textDiv.style.top = top + 'px'; textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontFamily = style.fontFamily; textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. if (PDFJS.pdfBug) { textDiv.dataset.fontName = geom.fontName; } // Storing into dataset will convert number into string. if (angle !== 0) { textDiv.dataset.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDiv.dataset.canvasWidth = geom.height * viewport.scale; } else { textDiv.dataset.canvasWidth = geom.width * viewport.scale; } } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; if (textDiv.dataset.isWhitespace !== undefined) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; if (width > 0) { textLayerFrag.appendChild(textDiv); var transform; if (textDiv.dataset.canvasWidth !== undefined) { // Dataset values come of type string. var textScale = textDiv.dataset.canvasWidth / width; transform = 'scaleX(' + textScale + ')'; } else { transform = ''; } var rotation = textDiv.dataset.angle; if (rotation) { transform = 'rotate(' + rotation + 'deg) ' + transform; } if (transform) { CustomStyle.setProp('transform' , textDiv, transform); } } } capability.resolve(); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PDFJS.PageViewport} viewport * @param {Array} textDivs * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs) { this._textContent = textContent; this._container = container; this._viewport = viewport; textDivs = textDivs || []; this._textDivs = textDivs; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var styles = this._textContent.styles; var textDivs = this._textDivs; var viewport = this._viewport; for (var i = 0, len = textItems.length; i < len; i++) { appendText(textDivs, viewport, textItems[i], styles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } } }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); PDFJS.renderTextLayer = renderTextLayer; exports.renderTextLayer = renderTextLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var shadow = sharedUtil.shadow; var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); exports.WebGLUtils = WebGLUtils; })); (function (root, factory) { { factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayWebGL) { var Util = sharedUtil.Util; var info = sharedUtil.info; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var WebGLUtils = displayWebGL.WebGLUtils; var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; })); (function (root, factory) { { factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var TextRenderingMode = sharedUtil.TextRenderingMode; var Uint32ArrayView = sharedUtil.Uint32ArrayView; var Util = sharedUtil.Util; var assert = sharedUtil.assert; var info = sharedUtil.info; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var TilingPattern = displayPatternHelper.TilingPattern; var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR; var WebGLUtils = displayWebGL.WebGLUtils; // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.drawImage(this.transparentCanvas, 0, 0); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { // TODO: Some shading patterns are not applied correctly to text, // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf. ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var self = this; var canvasGraphicsFactory = { createCanvasGraphics: function (ctx) { return new CanvasGraphics(ctx, self.commonObjs, self.objs); } }; pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); exports.CanvasGraphics = CanvasGraphics; exports.createScratchCanvas = createScratchCanvas; })); (function (root, factory) { { factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal); } }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, sharedGlobal, amdRequire) { var InvalidPDFException = sharedUtil.InvalidPDFException; var MessageHandler = sharedUtil.MessageHandler; var MissingPDFException = sharedUtil.MissingPDFException; var PasswordResponses = sharedUtil.PasswordResponses; var PasswordException = sharedUtil.PasswordException; var StatTimer = sharedUtil.StatTimer; var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; var UnknownErrorException = sharedUtil.UnknownErrorException; var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var combineUrl = sharedUtil.combineUrl; var error = sharedUtil.error; var deprecated = sharedUtil.deprecated; var info = sharedUtil.info; var isArrayBuffer = sharedUtil.isArrayBuffer; var loadJpegStream = sharedUtil.loadJpegStream; var stringToBytes = sharedUtil.stringToBytes; var warn = sharedUtil.warn; var FontFaceObject = displayFontLoader.FontFaceObject; var FontLoader = displayFontLoader.FontLoader; var CanvasGraphics = displayCanvas.CanvasGraphics; var createScratchCanvas = displayCanvas.createScratchCanvas; var Metadata = displayMetadata.Metadata; var PDFJS = sharedGlobal.PDFJS; var globalScope = sharedGlobal.globalScope; var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 var useRequireEnsure = false; if (typeof module !== 'undefined' && module.require) { // node.js - disable worker and set require.ensure. PDFJS.disableWorker = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } if (typeof __webpack_require__ !== 'undefined') { // Webpack - get/bundle pdf.worker.js as additional file. PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js'); useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) { require.ensure([], function () { require('./pdf.worker.js'); callback(); }); }) : (typeof requirejs !== 'undefined') ? (function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(); }); }) : null; /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. It is recommended that * the workerSrc is set in a custom application to prevent issues caused by * third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Specifies the |rel| attribute for external links. Defaults to stripping * the referrer. * @var {string} */ PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); messageHandler.send('Ready', null); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; }); }).catch(task._capability.reject); return task; }; /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {PDFJS.UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFJS.PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = {}; this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { var normalizeWhitespace = (params && params.normalizeWhitespace) || false; return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: normalizeWhitespace, }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (PDFJS.workerSrc) { return PDFJS.workerSrc; } if (pdfjsFilePath) { return pdfjsFilePath.replace(/\.js$/i, '.worker.js'); } error('No PDFJS.workerSrc specified'); } // Loads worker code into main thread. function setupFakeWorkerGlobal() { if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. var loader = fakeWorkerFilesLoader || function (callback) { Util.loadScript(getWorkerSrc(), callback); }; loader(function () { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedCapability.promise; } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); messageHandler.on('test', function PDFWorker_test(data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this._readyCapability.resolve(); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } try { sendTest(); } catch (e) { // We need fallback to a faked worker. this._setupFakeWorker(); } }.bind(this)); var sendTest = function () { var testObj = new Uint8Array( [PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; // It might take time for worker to initialize (especially when AMD // loader is used). We will try to send test immediately, and then // when 'ready' message will arrive. The worker shall process only // first received 'test'. sendTest(); return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { if (!globalScope.PDFJS.disableWorker) { warn('Setting up fake worker.'); globalScope.PDFJS.disableWorker = true; } setupFakeWorkerGlobal().then(function () { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // If we don't use a worker, just post/sendMessage to the main thread. var port = { _listeners: [], postMessage: function (obj) { var e = {data: obj}; this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () {} }; this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); PDFJS.WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); PDFJS.PDFWorker = PDFWorker; /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } PDFJS.UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject('Worker was terminated'); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame) { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); exports.getDocument = PDFJS.getDocument; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; })); }).call(pdfjsLibs); exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS; exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport; exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle; exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException; exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException; })); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">sreym/cdnjs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ajax/libs/pdf.js/1.3.177/pdf.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">313,996</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086591"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Submitting Issues ================= If you are submitting a bug with moment, please create a [jsfiddle](http://jsfiddle.net/) demonstrating the issue. Contributing ============ To contribute, fork the library and install these npm packages. npm install jshint uglify-js nodeunit You can add tests to the files in `/test/moment` or add a new test file if you are adding a new feature. To run the tests, do `make test` to run all tests, `make test-moment` to test the core library, and `make test-lang` to test all the languages. To check the filesize, you can use `make size`. To minify all the files, use `make moment` to minify moment, `make langs` to minify all the lang files, or just `make` to minfy everything. If your code passes the unit tests (including the ones you wrote), submit a pull request. Submitting pull requests ======================== Moment.js now uses [git-flow](https://github.com/nvie/gitflow). If you're not familiar with git-flow, please read up on it, you'll be glad you did. When submitting new features, please create a new feature branch using `git flow feature start <name>` and submit the pull request to the `develop` branch. Pull requests for enhancements for features should be submitted to the `develop` branch as well. When submitting a bugfix, please check if there is an existing bugfix branch. If the latest stable version is `1.5.0`, the bugfix branch would be `hotfix/1.5.1`. All pull requests for bug fixes should be on a `hotfix` branch, unless the bug fix depends on a new feature. The `master` branch should always have the latest stable version. When bugfix or minor releases are needed, the develop/hotfix branch will be merged into master and released. </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ninjablocks/ninja-sentinel</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">yeoman/components/moment/CONTRIBUTING.md</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Markdown</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,722</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086592"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" Integration tests for third_party_auth LTI auth providers """ import unittest from django.conf import settings from django.contrib.auth.models import User from django.core.urlresolvers import reverse from oauthlib.oauth1.rfc5849 import Client, SIGNATURE_TYPE_BODY from third_party_auth.tests import testutil FORM_ENCODED = 'application/x-www-form-urlencoded' LTI_CONSUMER_KEY = 'consumer' LTI_CONSUMER_SECRET = 'secret' LTI_TPA_LOGIN_URL = 'http://testserver/auth/login/lti/' LTI_TPA_COMPLETE_URL = 'http://testserver/auth/complete/lti/' OTHER_LTI_CONSUMER_KEY = 'settings-consumer' OTHER_LTI_CONSUMER_SECRET = 'secret2' LTI_USER_ID = 'lti_user_id' EDX_USER_ID = 'test_user' EMAIL = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0468706d5b7177617644617c65697468612a676b69">[email protected]</a>' @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class IntegrationTestLTI(testutil.TestCase): """ Integration tests for third_party_auth LTI auth providers """ def setUp(self): super(IntegrationTestLTI, self).setUp() self.client.defaults['SERVER_NAME'] = 'testserver' self.url_prefix = 'http://testserver' self.configure_lti_provider( name='Other Tool Consumer 1', enabled=True, lti_consumer_key='other1', lti_consumer_secret='secret1', lti_max_timestamp_age=10, ) self.configure_lti_provider( name='LTI Test Tool Consumer', enabled=True, lti_consumer_key=LTI_CONSUMER_KEY, lti_consumer_secret=LTI_CONSUMER_SECRET, lti_max_timestamp_age=10, ) self.configure_lti_provider( name='Tool Consumer with Secret in Settings', enabled=True, lti_consumer_key=OTHER_LTI_CONSUMER_KEY, lti_consumer_secret='', lti_max_timestamp_age=10, ) self.lti = Client( client_key=LTI_CONSUMER_KEY, client_secret=LTI_CONSUMER_SECRET, signature_type=SIGNATURE_TYPE_BODY, ) def test_lti_login(self): # The user initiates a login from an external site (uri, _headers, body) = self.lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={ 'user_id': LTI_USER_ID, 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll', } ) login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the registration form self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) register_response = self.client.get(login_response['Location']) self.assertEqual(register_response.status_code, 200) self.assertIn('"currentProvider": "LTI Test Tool Consumer"', register_response.content) self.assertIn('"errorMessage": null', register_response.content) # Now complete the form: ajax_register_response = self.client.post( reverse('user_api_registration'), { 'email': EMAIL, 'name': 'Myself', 'username': EDX_USER_ID, 'honor_code': True, } ) self.assertEqual(ajax_register_response.status_code, 200) continue_response = self.client.get(LTI_TPA_COMPLETE_URL) # The user should be redirected to the finish_auth view which will enroll them. # FinishAuthView.js reads the URL parameters directly from $.url self.assertEqual(continue_response.status_code, 302) self.assertEqual( continue_response['Location'], 'http://testserver/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll' ) # Now check that we can login again self.client.logout() self.verify_user_email(EMAIL) (uri, _headers, body) = self.lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={'user_id': LTI_USER_ID} ) login_2_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the dashboard self.assertEqual(login_2_response.status_code, 302) self.assertEqual(login_2_response['Location'], LTI_TPA_COMPLETE_URL) continue_2_response = self.client.get(login_2_response['Location']) self.assertEqual(continue_2_response.status_code, 302) self.assertTrue(continue_2_response['Location'].endswith(reverse('dashboard'))) # Check that the user was created correctly user = User.objects.get(email=EMAIL) self.assertEqual(user.username, EDX_USER_ID) def test_reject_initiating_login(self): response = self.client.get(LTI_TPA_LOGIN_URL) self.assertEqual(response.status_code, 405) # Not Allowed def test_reject_bad_login(self): login_response = self.client.post( path=LTI_TPA_LOGIN_URL, content_type=FORM_ENCODED, data="invalid=login" ) # The user should be redirected to the login page with an error message # (auth_entry defaults to login for this provider) self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) error_response = self.client.get(login_response['Location']) self.assertIn( 'Authentication failed: LTI parameters could not be validated.', error_response.content ) def test_can_load_consumer_secret_from_settings(self): lti = Client( client_key=OTHER_LTI_CONSUMER_KEY, client_secret=OTHER_LTI_CONSUMER_SECRET, signature_type=SIGNATURE_TYPE_BODY, ) (uri, _headers, body) = lti.sign( uri=LTI_TPA_LOGIN_URL, http_method='POST', headers={'Content-Type': FORM_ENCODED}, body={ 'user_id': LTI_USER_ID, 'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll', } ) with self.settings(SOCIAL_AUTH_LTI_CONSUMER_SECRETS={OTHER_LTI_CONSUMER_KEY: OTHER_LTI_CONSUMER_SECRET}): login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body) # The user should be redirected to the registration form self.assertEqual(login_response.status_code, 302) self.assertTrue(login_response['Location'].endswith(reverse('signin_user'))) register_response = self.client.get(login_response['Location']) self.assertEqual(register_response.status_code, 200) self.assertIn( '"currentProvider": "Tool Consumer with Secret in Settings"', register_response.content ) self.assertIn('"errorMessage": null', register_response.content) </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">solashirai/edx-platform</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">common/djangoapps/third_party_auth/tests/specs/test_lti.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">agpl-3.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">7,079</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086593"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.sanity; import com.facebook.presto.Session; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.ExpressionExtractor; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.tree.DefaultTraversalVisitor; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.SubqueryExpression; import java.util.Map; import static java.lang.String.format; public final class NoSubqueryExpressionLeftChecker implements PlanSanityChecker.Checker { @Override public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map<Symbol, Type> types) { for (Expression expression : ExpressionExtractor.extractExpressions(plan)) { new DefaultTraversalVisitor<Void, Void>() { @Override protected Void visitSubqueryExpression(SubqueryExpression node, Void context) { throw new IllegalStateException(format("Unexpected subquery expression in logical plan: %s", node)); } }.process(expression, null); } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">marsorp/blog</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">presto166/presto-main/src/main/java/com/facebook/presto/sql/planner/sanity/NoSubqueryExpressionLeftChecker.java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Java</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">1,903</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086594"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">var FormData = require('form-data'); function form(obj) { var form = new FormData(); if (obj) { Object.keys(obj).forEach(function (name) { form.append(name, obj[name]); }); } return form; } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = form; //# sourceMappingURL=form.js.map</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">carmine/northshore</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">ui/node_modules/popsicle/dist/form.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">apache-2.0</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">353</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086595"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">if (!self.GLOBAL || self.GLOBAL.isWindow()) { test(() => { assert_equals(document.title, "foo"); }, '<title> exists'); test(() => { assert_equals(document.querySelectorAll("meta[name=timeout][content=long]").length, 1); }, '<meta name=timeout> exists'); } scripts.push('expect-title-meta.js'); </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">scheib/chromium</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">JavaScript</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">312</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086596"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">""" By specifying the 'proxy' Meta attribute, model subclasses can specify that they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible # A couple of managers for testing managing overriding in proxy model cases. class PersonManager(models.Manager): def get_queryset(self): return super(PersonManager, self).get_queryset().exclude(name="fred") class SubManager(models.Manager): def get_queryset(self): return super(SubManager, self).get_queryset().exclude(name="wilma") @python_2_unicode_compatible class Person(models.Model): """ A simple concrete base class. """ name = models.CharField(max_length=50) objects = PersonManager() def __str__(self): return self.name class Abstract(models.Model): """ A simple abstract base class, to be used for error checking. """ data = models.CharField(max_length=10) class Meta: abstract = True class MyPerson(Person): """ A proxy subclass, this should not get a new table. Overrides the default manager. """ class Meta: proxy = True ordering = ["name"] permissions = ( ("display_users", "May display users information"), ) objects = SubManager() other = PersonManager() def has_special_name(self): return self.name.lower() == "special" class ManagerMixin(models.Model): excluder = SubManager() class Meta: abstract = True class OtherPerson(Person, ManagerMixin): """ A class with the default manager from Person, plus an secondary manager. """ class Meta: proxy = True ordering = ["name"] class StatusPerson(MyPerson): """ A non-proxy subclass of a proxy, it should get a new table. """ status = models.CharField(max_length=80) # We can even have proxies of proxies (and subclass of those). class MyPersonProxy(MyPerson): class Meta: proxy = True class LowerStatusPerson(MyPersonProxy): status = models.CharField(max_length=80) @python_2_unicode_compatible class User(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class UserProxy(User): class Meta: proxy = True class UserProxyProxy(UserProxy): class Meta: proxy = True # We can still use `select_related()` to include related models in our querysets. class Country(models.Model): name = models.CharField(max_length=50) @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country, models.CASCADE) def __str__(self): return self.name class StateProxy(State): class Meta: proxy = True # Proxy models still works with filters (on related fields) # and select_related, even when mixed with model inheritance @python_2_unicode_compatible class BaseUser(models.Model): name = models.CharField(max_length=255) def __str__(self): return ':'.join((self.__class__.__name__, self.name,)) class TrackerUser(BaseUser): status = models.CharField(max_length=50) class ProxyTrackerUser(TrackerUser): class Meta: proxy = True @python_2_unicode_compatible class Issue(models.Model): summary = models.CharField(max_length=255) assignee = models.ForeignKey(ProxyTrackerUser, models.CASCADE, related_name='issues') def __str__(self): return ':'.join((self.__class__.__name__, self.summary,)) class Bug(Issue): version = models.CharField(max_length=50) reporter = models.ForeignKey(BaseUser, models.CASCADE) class ProxyBug(Bug): """ Proxy of an inherited class """ class Meta: proxy = True class ProxyProxyBug(ProxyBug): """ A proxy of proxy model with related field """ class Meta: proxy = True class Improvement(Issue): """ A model that has relation to a proxy model or to a proxy of proxy model """ version = models.CharField(max_length=50) reporter = models.ForeignKey(ProxyTrackerUser, models.CASCADE) associated_bug = models.ForeignKey(ProxyProxyBug, models.CASCADE) class ProxyImprovement(Improvement): class Meta: proxy = True </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">benjaminjkraft/django</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">tests/proxy_models/models.py</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">Python</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">4,514</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086597"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/** * \file bignum.h * * \brief Multi-precision integer library * * Copyright (C) 2006-2010, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; 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. */ #ifndef POLARSSL_BIGNUM_H #define POLARSSL_BIGNUM_H #include <stdio.h> #include <string.h> #include "config.h" #define POLARSSL_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */ #define POLARSSL_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */ #define POLARSSL_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */ #define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The buffer is too small to write to. */ #define POLARSSL_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */ #define POLARSSL_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */ #define POLARSSL_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */ #define POLARSSL_ERR_MPI_MALLOC_FAILED -0x0010 /**< Memory allocation failed. */ #define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup /* * Maximum size MPIs are allowed to grow to in number of limbs. */ #define POLARSSL_MPI_MAX_LIMBS 10000 /* * Maximum window size used for modular exponentiation. Default: 6 * Minimum value: 1. Maximum value: 6. * * Result is an array of ( 2 << POLARSSL_MPI_WINDOW_SIZE ) MPIs used * for the sliding window calculation. (So 64 by default) * * Reduction in size, reduces speed. */ #define POLARSSL_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */ /* * Maximum size of MPIs allowed in bits and bytes for user-MPIs. * ( Default: 512 bytes => 4096 bits ) * * Note: Calculations can results temporarily in larger MPIs. So the number * of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher. */ #define POLARSSL_MPI_MAX_SIZE 512 /**< Maximum number of bytes for usable MPIs. */ #define POLARSSL_MPI_MAX_BITS ( 8 * POLARSSL_MPI_MAX_SIZE ) /**< Maximum number of bits for usable MPIs. */ /* * When reading from files with mpi_read_file() the buffer should have space * for a (short) label, the MPI (in the provided radix), the newline * characters and the '\0'. * * By default we assume at least a 10 char label, a minimum radix of 10 * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars). */ #define POLARSSL_MPI_READ_BUFFER_SIZE 1250 /* * Define the base integer type, architecture-wise */ #if defined(POLARSSL_HAVE_INT8) typedef signed char t_sint; typedef unsigned char t_uint; typedef unsigned short t_udbl; #else #if defined(POLARSSL_HAVE_INT16) typedef signed short t_sint; typedef unsigned short t_uint; typedef unsigned long t_udbl; #else typedef signed long t_sint; typedef unsigned long t_uint; #if defined(_MSC_VER) && defined(_M_IX86) typedef unsigned __int64 t_udbl; #else #if defined(__GNUC__) && ( \ defined(__amd64__) || defined(__x86_64__) || \ defined(__ppc64__) || defined(__powerpc64__) || \ defined(__ia64__) || defined(__alpha__) || \ (defined(__sparc__) && defined(__arch64__)) || \ defined(__s390x__) ) typedef unsigned int t_udbl __attribute__((mode(TI))); #define POLARSSL_HAVE_LONGLONG #else #if defined(POLARSSL_HAVE_LONGLONG) typedef unsigned long long t_udbl; #endif #endif #endif #endif #endif /** * \brief MPI structure */ typedef struct { int s; /*!< integer sign */ size_t n; /*!< total # of limbs */ t_uint *p; /*!< pointer to limbs */ } mpi; #ifdef __cplusplus extern "C" { #endif /** * \brief Initialize one MPI * * \param X One MPI to initialize. */ void mpi_init( mpi *X ); /** * \brief Unallocate one MPI * * \param X One MPI to unallocate. */ void mpi_free( mpi *X ); /** * \brief Enlarge to the specified number of limbs * * \param X MPI to grow * \param nblimbs The target number of limbs * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_grow( mpi *X, size_t nblimbs ); /** * \brief Copy the contents of Y into X * * \param X Destination MPI * \param Y Source MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_copy( mpi *X, const mpi *Y ); /** * \brief Swap the contents of X and Y * * \param X First MPI value * \param Y Second MPI value */ void mpi_swap( mpi *X, mpi *Y ); /** * \brief Set value from integer * * \param X MPI to set * \param z Value to use * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_lset( mpi *X, t_sint z ); /* * \brief Get a specific bit from X * * \param X MPI to use * \param pos Zero-based index of the bit in X * * \return Either a 0 or a 1 */ int mpi_get_bit( mpi *X, size_t pos ); /* * \brief Set a bit of X to a specific value of 0 or 1 * * \note Will grow X if necessary to set a bit to 1 in a not yet * existing limb. Will not grow if bit should be set to 0 * * \param X MPI to use * \param pos Zero-based index of the bit in X * \param val The value to set the bit to (0 or 1) * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1 */ int mpi_set_bit( mpi *X, size_t pos, unsigned char val ); /** * \brief Return the number of least significant bits * * \param X MPI to use */ size_t mpi_lsb( const mpi *X ); /** * \brief Return the number of most significant bits * * \param X MPI to use */ size_t mpi_msb( const mpi *X ); /** * \brief Return the total size in bytes * * \param X MPI to use */ size_t mpi_size( const mpi *X ); /** * \brief Import from an ASCII string * * \param X Destination MPI * \param radix Input numeric base * \param s Null-terminated string buffer * * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code */ int mpi_read_string( mpi *X, int radix, const char *s ); /** * \brief Export into an ASCII string * * \param X Source MPI * \param radix Output numeric base * \param s String buffer * \param slen String buffer size * * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code. * *slen is always updated to reflect the amount * of data that has (or would have) been written. * * \note Call this function with *slen = 0 to obtain the * minimum required buffer size in *slen. */ int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen ); /** * \brief Read X from an opened file * * \param X Destination MPI * \param radix Input numeric base * \param fin Input file handle * * \return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if * the file read buffer is too small or a * POLARSSL_ERR_MPI_XXX error code */ int mpi_read_file( mpi *X, int radix, FILE *fin ); /** * \brief Write X into an opened file, or stdout if fout is NULL * * \param p Prefix, can be NULL * \param X Source MPI * \param radix Output numeric base * \param fout Output file handle (can be NULL) * * \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code * * \note Set fout == NULL to print X on the console. */ int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout ); /** * \brief Import X from unsigned binary data, big endian * * \param X Destination MPI * \param buf Input buffer * \param buflen Input buffer size * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen ); /** * \brief Export X into unsigned binary data, big endian * * \param X Source MPI * \param buf Output buffer * \param buflen Output buffer size * * \return 0 if successful, * POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough */ int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen ); /** * \brief Left-shift: X <<= count * * \param X MPI to shift * \param count Amount to shift * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_shift_l( mpi *X, size_t count ); /** * \brief Right-shift: X >>= count * * \param X MPI to shift * \param count Amount to shift * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_shift_r( mpi *X, size_t count ); /** * \brief Compare unsigned values * * \param X Left-hand MPI * \param Y Right-hand MPI * * \return 1 if |X| is greater than |Y|, * -1 if |X| is lesser than |Y| or * 0 if |X| is equal to |Y| */ int mpi_cmp_abs( const mpi *X, const mpi *Y ); /** * \brief Compare signed values * * \param X Left-hand MPI * \param Y Right-hand MPI * * \return 1 if X is greater than Y, * -1 if X is lesser than Y or * 0 if X is equal to Y */ int mpi_cmp_mpi( const mpi *X, const mpi *Y ); /** * \brief Compare signed values * * \param X Left-hand MPI * \param z The integer value to compare to * * \return 1 if X is greater than z, * -1 if X is lesser than z or * 0 if X is equal to z */ int mpi_cmp_int( const mpi *X, t_sint z ); /** * \brief Unsigned addition: X = |A| + |B| * * \param X Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_add_abs( mpi *X, const mpi *A, const mpi *B ); /** * \brief Unsigned substraction: X = |A| - |B| * * \param X Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B is greater than A */ int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B ); /** * \brief Signed addition: X = A + B * * \param X Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B ); /** * \brief Signed substraction: X = A - B * * \param X Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B ); /** * \brief Signed addition: X = A + b * * \param X Destination MPI * \param A Left-hand MPI * \param b The integer value to add * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_add_int( mpi *X, const mpi *A, t_sint b ); /** * \brief Signed substraction: X = A - b * * \param X Destination MPI * \param A Left-hand MPI * \param b The integer value to subtract * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_sub_int( mpi *X, const mpi *A, t_sint b ); /** * \brief Baseline multiplication: X = A * B * * \param X Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B ); /** * \brief Baseline multiplication: X = A * b * Note: b is an unsigned integer type, thus * Negative values of b are ignored. * * \param X Destination MPI * \param A Left-hand MPI * \param b The integer value to multiply with * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_mul_int( mpi *X, const mpi *A, t_sint b ); /** * \brief Division by mpi: A = Q * B + R * * \param Q Destination MPI for the quotient * \param R Destination MPI for the rest value * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0 * * \note Either Q or R can be NULL. */ int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B ); /** * \brief Division by int: A = Q * b + R * * \param Q Destination MPI for the quotient * \param R Destination MPI for the rest value * \param A Left-hand MPI * \param b Integer to divide by * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0 * * \note Either Q or R can be NULL. */ int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b ); /** * \brief Modulo: R = A mod B * * \param R Destination MPI for the rest value * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0, * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0 */ int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B ); /** * \brief Modulo: r = A mod b * * \param r Destination t_uint * \param A Left-hand MPI * \param b Integer to divide by * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0, * POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0 */ int mpi_mod_int( t_uint *r, const mpi *A, t_sint b ); /** * \brief Sliding-window exponentiation: X = A^E mod N * * \param X Destination MPI * \param A Left-hand MPI * \param E Exponent MPI * \param N Modular MPI * \param _RR Speed-up MPI used for recalculations * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or even * * \note _RR is used to avoid re-computing R*R mod N across * multiple calls, which speeds up things a bit. It can * be set to NULL if the extra performance is unneeded. */ int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR ); /** * \brief Fill an MPI X with size bytes of random * * \param X Destination MPI * \param size Size in bytes * \param f_rng RNG function * \param p_rng RNG parameter * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_fill_random( mpi *X, size_t size, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Greatest common divisor: G = gcd(A, B) * * \param G Destination MPI * \param A Left-hand MPI * \param B Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed */ int mpi_gcd( mpi *G, const mpi *A, const mpi *B ); /** * \brief Modular inverse: X = A^-1 mod N * * \param X Destination MPI * \param A Left-hand MPI * \param N Right-hand MPI * * \return 0 if successful, * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or nil POLARSSL_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N */ int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N ); /** * \brief Miller-Rabin primality test * * \param X MPI to check * \param f_rng RNG function * \param p_rng RNG parameter * * \return 0 if successful (probably prime), * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_NOT_ACCEPTABLE if X is not prime */ int mpi_is_prime( mpi *X, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Prime number generation * * \param X Destination MPI * \param nbits Required size of X in bits ( 3 <= nbits <= POLARSSL_MPI_MAX_BITS ) * \param dh_flag If 1, then (X-1)/2 will be prime too * \param f_rng RNG function * \param p_rng RNG parameter * * \return 0 if successful (probably prime), * POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed, * POLARSSL_ERR_MPI_BAD_INPUT_DATA if nbits is < 3 */ int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mpi_self_test( int verbose ); #ifdef __cplusplus } #endif #endif /* bignum.h */ </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mimecine/mongrel2</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/polarssl/bignum.h</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">bsd-3-clause</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">19,580</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086598"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">// 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.Diagnostics; using System.Threading.Tasks; using Xunit; namespace System.Threading.Tests { /// <summary> /// SemaphoreSlim unit tests /// </summary> public class SemaphoreSlimTests { /// <summary> /// SemaphoreSlim public methods and properties to be tested /// </summary> private enum SemaphoreSlimActions { Constructor, Wait, WaitAsync, Release, Dispose, CurrentCount, AvailableWaitHandle } [Fact] public static void RunSemaphoreSlimTest0_Ctor() { RunSemaphoreSlimTest0_Ctor(0, 10, null); RunSemaphoreSlimTest0_Ctor(5, 10, null); RunSemaphoreSlimTest0_Ctor(10, 10, null); } [Fact] public static void RunSemaphoreSlimTest0_Ctor_Negative() { RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException)); } [Fact] public static void RunSemaphoreSlimTest1_Wait() { // Infinite timeout RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null); RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null); // Zero timeout RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null); RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null); RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null); // Positive timeout RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null); RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null); RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null); } [Fact] public static void RunSemaphoreSlimTest1_Wait_NegativeCases() { // Invalid timeout RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_Wait (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException)); } [Fact] public static void RunSemaphoreSlimTest1_WaitAsync() { // Infinite timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null); // Zero timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null); RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null); // Positive timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null); RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null); RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null); } [Fact] public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases() { // Invalid timeout RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_WaitAsync (10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest1_WaitAsync2(); } [Fact] public static void RunSemaphoreSlimTest2_Release() { // Valid release count RunSemaphoreSlimTest2_Release(5, 10, 1, null); RunSemaphoreSlimTest2_Release(0, 10, 1, null); RunSemaphoreSlimTest2_Release(5, 10, 5, null); } [Fact] public static void RunSemaphoreSlimTest2_Release_NegativeCases() { // Invalid release count RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException)); RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException)); // Semaphore Full RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException)); RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException)); RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException)); } [Fact] public static void RunSemaphoreSlimTest4_Dispose() { RunSemaphoreSlimTest4_Dispose(5, 10, null, null); RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException)); RunSemaphoreSlimTest4_Dispose (5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException)); } [Fact] public static void RunSemaphoreSlimTest5_CurrentCount() { RunSemaphoreSlimTest5_CurrentCount(5, 10, null); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync); RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release); } [Fact] public static void RunSemaphoreSlimTest7_AvailableWaitHandle() { RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true); RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true); RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true); RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false); RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true); RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true); } /// <summary> /// Test SemaphoreSlim constructor /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType) { string methodFailed = "RunSemaphoreSlimTest0_Ctor(" + initial + "," + maximum + "): FAILED. "; Exception exception = null; try { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Assert.Equal(initial, semaphore.CurrentCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); exception = ex; } } /// <summary> /// Test SemaphoreSlim Wait /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param> /// <param name="returnValue">The expected wait return value</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest1_Wait (int initial, int maximum, object timeout, bool returnValue, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { bool result = false; if (timeout is TimeSpan) { result = semaphore.Wait((TimeSpan)timeout); } else { result = semaphore.Wait((int)timeout); } Assert.Equal(returnValue, result); if (result) { Assert.Equal(initial - 1, semaphore.CurrentCount); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim WaitAsync /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param> /// <param name="returnValue">The expected wait return value</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest1_WaitAsync (int initial, int maximum, object timeout, bool returnValue, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { bool result = false; if (timeout is TimeSpan) { result = semaphore.WaitAsync((TimeSpan)timeout).Result; } else { result = semaphore.WaitAsync((int)timeout).Result; } Assert.Equal(returnValue, result); if (result) { Assert.Equal(initial - 1, semaphore.CurrentCount); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim WaitAsync /// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously. /// </summary> private static void RunSemaphoreSlimTest1_WaitAsync2() { SemaphoreSlim semaphore = new SemaphoreSlim(1); ThreadLocal<int> counter = new ThreadLocal<int>(() => 0); bool nonZeroObserved = false; const int asyncActions = 20; int remAsyncActions = asyncActions; ManualResetEvent mre = new ManualResetEvent(false); Action<int> doWorkAsync = async delegate (int i) { await semaphore.WaitAsync(); if (counter.Value > 0) { nonZeroObserved = true; } counter.Value = counter.Value + 1; semaphore.Release(); counter.Value = counter.Value - 1; if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set(); }; semaphore.Wait(); for (int i = 0; i < asyncActions; i++) doWorkAsync(i); semaphore.Release(); mre.WaitOne(); Assert.False(nonZeroObserved, "RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation."); } /// <summary> /// Test SemaphoreSlim Release /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="releaseCount">The release count for the release method</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest2_Release (int initial, int maximum, int releaseCount, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { int oldCount = semaphore.Release(releaseCount); Assert.Equal(initial, oldCount); Assert.Equal(initial + releaseCount, semaphore.CurrentCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Call specific SemaphoreSlim method or property /// </summary> /// <param name="semaphore">The SemaphoreSlim instance</param> /// <param name="action">The action name</param> /// <param name="param">The action parameter, null if it takes no parameters</param> /// <returns>The action return value, null if the action returns void</returns> private static object CallSemaphoreAction (SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param) { if (action == SemaphoreSlimActions.Wait) { if (param is TimeSpan) { return semaphore.Wait((TimeSpan)param); } else if (param is int) { return semaphore.Wait((int)param); } semaphore.Wait(); return null; } else if (action == SemaphoreSlimActions.WaitAsync) { if (param is TimeSpan) { return semaphore.WaitAsync((TimeSpan)param).Result; } else if (param is int) { return semaphore.WaitAsync((int)param).Result; } semaphore.WaitAsync().Wait(); return null; } else if (action == SemaphoreSlimActions.Release) { if (param != null) { return semaphore.Release((int)param); } return semaphore.Release(); } else if (action == SemaphoreSlimActions.Dispose) { semaphore.Dispose(); return null; } else if (action == SemaphoreSlimActions.CurrentCount) { return semaphore.CurrentCount; } else if (action == SemaphoreSlimActions.AvailableWaitHandle) { return semaphore.AvailableWaitHandle; } return null; } /// <summary> /// Test SemaphoreSlim Dispose /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called after Dispose</param> /// <param name="exceptionType">The type of the thrown exception in case of invalid cases, /// null for valid cases</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); try { semaphore.Dispose(); CallSemaphoreAction(semaphore, action, null); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } } /// <summary> /// Test SemaphoreSlim CurrentCount property /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called before CurrentCount</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); CallSemaphoreAction(semaphore, action, null); if (action == null) { Assert.Equal(initial, semaphore.CurrentCount); } else { Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount); } } /// <summary> /// Test SemaphoreSlim AvailableWaitHandle property /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="action">SemaphoreSlim action to be called before WaitHandle</param> /// <param name="state">The expected wait handle state</param> /// <returns>True if the test succeeded, false otherwise</returns> private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); CallSemaphoreAction(semaphore, action, null); Assert.NotNull(semaphore.AvailableWaitHandle); Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0)); } /// <summary> /// Test SemaphoreSlim Wait and Release methods concurrently /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="waitThreads">Number of the threads that call Wait method</param> /// <param name="releaseThreads">Number of the threads that call Release method</param> /// <param name="succeededWait">Number of succeeded wait threads</param> /// <param name="failedWait">Number of failed wait threads</param> /// <param name="finalCount">The final semaphore count</param> /// <returns>True if the test succeeded, false otherwise</returns> [Theory] [InlineData(5, 1000, 50, 50, 50, 0, 5, 1000)] [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)] [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)] public static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum, int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Task[] threads = new Task[waitThreads + releaseThreads]; int succeeded = 0; int failed = 0; ManualResetEvent mre = new ManualResetEvent(false); // launch threads for (int i = 0; i < threads.Length; i++) { if (i < waitThreads) { // We are creating the Task using TaskCreationOptions.LongRunning to // force usage of another thread (which will be the case on the default scheduler // with its current implementation). Without this, the release tasks will likely get // queued behind the wait tasks in the pool, making it very likely that the wait tasks // will starve the very tasks that when run would unblock them. threads[i] = new Task(delegate () { mre.WaitOne(); if (semaphore.Wait(timeout)) { Interlocked.Increment(ref succeeded); } else { Interlocked.Increment(ref failed); } }, TaskCreationOptions.LongRunning); } else { threads[i] = new Task(delegate () { mre.WaitOne(); semaphore.Release(); }); } threads[i].Start(TaskScheduler.Default); } mre.Set(); //wait work to be done; Task.WaitAll(threads); //check the number of succeeded and failed wait Assert.Equal(succeededWait, succeeded); Assert.Equal(failedWait, failed); Assert.Equal(finalCount, semaphore.CurrentCount); } /// <summary> /// Test SemaphoreSlim WaitAsync and Release methods concurrently /// </summary> /// <param name="initial">The initial semaphore count</param> /// <param name="maximum">The maximum semaphore count</param> /// <param name="waitThreads">Number of the threads that call Wait method</param> /// <param name="releaseThreads">Number of the threads that call Release method</param> /// <param name="succeededWait">Number of succeeded wait threads</param> /// <param name="failedWait">Number of failed wait threads</param> /// <param name="finalCount">The final semaphore count</param> /// <returns>True if the test succeeded, false otherwise</returns> [Theory] [InlineData(5, 1000, 50, 50, 50, 0, 5, 500)] [InlineData(0, 1000, 50, 25, 25, 25, 0, 500)] [InlineData(0, 1000, 50, 0, 0, 50, 0, 100)] public static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum, int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout) { SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum); Task[] tasks = new Task[waitThreads + releaseThreads]; int succeeded = 0; int failed = 0; ManualResetEvent mre = new ManualResetEvent(false); // launch threads for (int i = 0; i < tasks.Length; i++) { if (i < waitThreads) { tasks[i] = Task.Run(async delegate { mre.WaitOne(); if (await semaphore.WaitAsync(timeout)) { Interlocked.Increment(ref succeeded); } else { Interlocked.Increment(ref failed); } }); } else { tasks[i] = Task.Run(delegate { mre.WaitOne(); semaphore.Release(); }); } } mre.Set(); //wait work to be done; Task.WaitAll(tasks); Assert.Equal(succeededWait, succeeded); Assert.Equal(failedWait, failed); Assert.Equal(finalCount, semaphore.CurrentCount); } [Theory] [InlineData(10, 10)] [InlineData(1, 10)] [InlineData(10, 1)] public static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters) { int totalWaiters = syncWaiters + asyncWaiters; var semaphore = new SemaphoreSlim(0); Task[] tasks = new Task[totalWaiters]; const int ITERS = 10; int randSeed = unchecked((int)DateTime.Now.Ticks); for (int i = 0; i < syncWaiters; i++) { tasks[i] = Task.Run(delegate { //Random rand = new Random(Interlocked.Increment(ref randSeed)); for (int iter = 0; iter < ITERS; iter++) { semaphore.Wait(); semaphore.Release(); } }); } for (int i = syncWaiters; i < totalWaiters; i++) { tasks[i] = Task.Run(async delegate { //Random rand = new Random(Interlocked.Increment(ref randSeed)); for (int iter = 0; iter < ITERS; iter++) { await semaphore.WaitAsync(); semaphore.Release(); } }); } semaphore.Release(totalWaiters / 2); Task.WaitAll(tasks); } } } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">shimingsg/corefx</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">src/System.Threading/tests/SemaphoreSlimTests.cs</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">C#</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">25,845</div></div> </td> </tr><tr class="group cursor-pointer space-x-4 divide-x border-b outline-offset-[-2px] odd:bg-gray-50 hover:bg-gray-100 dark:odd:bg-gray-925 dark:hover:bg-gray-850 " tabindex="0" data-row-idx="115086599"><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">/* * Copyright (C) 2008 Apple Inc. All rights reserved. * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ .audits-sidebar-tree-item .icon { content: url(Images/resourcesTimeGraphIcon.png); } .audit-result-sidebar-tree-item .icon { content: url(Images/resourceDocumentIcon.png); } .audit-launcher-view { z-index: 1000; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: white; font-size: 13px; overflow-x: hidden; overflow-y: overlay; display: none; } .audit-launcher-view.visible { display: block; } .audit-launcher-view .audit-launcher-view-content { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding: 0 0 0 16px; white-space: nowrap; display: -webkit-box; text-align: left; -webkit-box-orient: vertical; } .audit-launcher-view h1 { padding-top: 15px; } .audit-launcher-view h1.no-audits { text-align: center; font-style: italic; position: relative; left: -8px; } .audit-launcher-view div.button-container { display: -webkit-box; -webkit-box-orient: vertical; width: 100%; padding: 16px 0; } .audit-launcher-view div.audit-categories-container { position: relative; top: 11px; left: 0; width: 100%; overflow-y: auto; } .audit-launcher-view button { margin: 0 5px 0 0; } .audit-launcher-view button:active { background-color: rgb(215, 215, 215); background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(194, 194, 194)), to(rgb(239, 239, 239))); } .panel-enabler-view.audit-launcher-view label { padding: 0 0 5px 0; margin: 0; } .panel-enabler-view.audit-launcher-view label.disabled { color: rgb(130, 130, 130); } .audit-launcher-view input[type="checkbox"] { margin-left: 0; } .audit-launcher-view .resource-progress > img { content: url(Images/spinner.gif); vertical-align: text-top; margin: 0 4px 0 8px; } .audit-result-view { overflow: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: none; } .audit-result-view.visible { display: block; } .audit-result-view .severity-severe { content: url(Images/errorRedDot.png); } .audit-result-view .severity-warning { content: url(Images/warningOrangeDot.png); } .audit-result-view .severity-info { content: url(Images/successGreenDot.png); } .audit-result-tree li.parent::before { content: url(Images/treeRightTriangleBlack.png); float: left; width: 8px; height: 8px; margin-top: 1px; padding-right: 2px; } .audit-result-tree { font-size: 11px; line-height: 14px; -webkit-user-select: text; } .audit-result-tree > ol { position: relative; padding: 2px 6px !important; margin: 0; color: rgb(84, 84, 84); cursor: default; min-width: 100%; } .audit-result-tree, .audit-result-tree ol { list-style-type: none; -webkit-padding-start: 12px; margin: 0; } .audit-result-tree ol.outline-disclosure { -webkit-padding-start: 0; } .audit-result-tree .section .header { padding-left: 13px; } .audit-result-tree .section .header::before { left: 2px; } .audit-result-tree li { padding: 0 0 0 14px; margin-top: 1px; margin-bottom: 1px; word-wrap: break-word; margin-left: -2px; } .audit-result-tree li.parent { margin-left: -12px } .audit-result-tree li.parent::before { content: url(Images/treeRightTriangleBlack.png); float: left; width: 8px; height: 8px; margin-top: 0; padding-right: 2px; } .audit-result-tree li.parent.expanded::before { content: url(Images/treeDownTriangleBlack.png); } .audit-result-tree ol.children { display: none; } .audit-result-tree ol.children.expanded { display: block; } .audit-result { font-weight: bold; color: black; } .audit-result img { float: left; margin-left: -28px; margin-top: -1px; } </span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">NetEase/pomelo-admin-web</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">public/front/auditsPanel.css</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">CSS</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="" dir="auto"> <div> <span class="block ">mit</span></div> </div></div> </td><td class="min-w-fit max-w-sm break-words p-2 "><div class="line-clamp-2 "><div class="text-right" dir="auto">5,485</div></div> </td> </tr></tbody></table> </div> <div class="bg-linear-to-b from-gray-100 to-white dark:from-gray-950 dark:to-gray-900 rounded-b-lg"><hr class="flex-none -translate-y-px border-t border-dashed border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-950"> <nav><ul class="flex select-none items-center justify-between space-x-2 text-gray-700 sm:justify-center py-1 text-center font-mono text-xs "><li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150864"><svg class="mr-1.5" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg> Previous</a></li> <li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=0">1</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 pointer-events-none cursor-default" href="#">...</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150863">1,150,864</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150864">1,150,865</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 bg-gray-50 font-semibold ring-1 ring-inset ring-gray-200 dark:bg-gray-900 dark:text-yellow-500 dark:ring-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150865">1,150,866</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150866">1,150,867</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150867">1,150,868</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 pointer-events-none cursor-default" href="#">...</a> </li><li class="hidden sm:block"><a class="rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800" href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150869">1,150,870</a> </li> <li><a class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 " href="/datasets/loubnabnl/github-code-duplicate/viewer/default/train?p=1150866">Next <svg class="ml-1.5 transform rotate-180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z" fill="currentColor"></path></svg></a></li></ul></nav></div></div> </div></div></div></div></div></div></div> <div class="hidden items-center md:flex"> <div class="mx-1 flex items-center justify-center"><div class="h-8 w-1 cursor-ew-resize rounded-full bg-gray-200 hover:bg-gray-400 dark:bg-gray-700 dark:hover:bg-gray-600 max-sm:hidden" role="separator"></div></div> <div class="flex h-full flex-col" style="height: calc(100vh - 48px)"><div class="my-4 mr-4 h-full overflow-auto rounded-lg border shadow-lg dark:border-gray-800" style="width: 480px"><div class="flex h-full flex-col"><div class="flex flex-col "> <div class="px-4 md:mt-4"><div class="mb-4 flex justify-end"> <div class="flex w-full flex-col rounded-lg border-slate-200 bg-white p-2 shadow-md ring-1 ring-slate-200 dark:border-slate-700 dark:bg-slate-800 dark:ring-slate-700"> <div class="mt-0 flex items-start gap-1"><div class="flex items-center rounded-md bg-slate-100 p-2 dark:bg-slate-700"><svg class="size-4 text-gray-700 dark:text-gray-300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 11 11"><path fill="currentColor" d="M4.881 4.182c0 .101-.031.2-.087.283a.5.5 0 0 1-.242.18l-.65.217a1.3 1.3 0 0 0-.484.299 1.3 1.3 0 0 0-.298.484l-.222.639a.46.46 0 0 1-.18.242.5.5 0 0 1-.288.092.5.5 0 0 1-.294-.097.5.5 0 0 1-.175-.242l-.211-.644a1.26 1.26 0 0 0-.299-.48 1.14 1.14 0 0 0-.479-.298L.328 4.64a.48.48 0 0 1-.247-.18.515.515 0 0 1 .247-.758l.644-.21a1.28 1.28 0 0 0 .788-.789l.211-.634a.5.5 0 0 1 .165-.242.5.5 0 0 1 .283-.103.5.5 0 0 1 .294.083c.086.058.152.14.19.237l.217.659a1.28 1.28 0 0 0 .788.788l.644.222a.476.476 0 0 1 .237.18.5.5 0 0 1 .092.288"></path><path fill="currentColor" d="M10.031 7.458a.5.5 0 0 1-.098.314.5.5 0 0 1-.267.196l-.881.293c-.272.09-.519.242-.721.443a1.8 1.8 0 0 0-.443.721l-.31.876a.5.5 0 0 1-.185.263.56.56 0 0 1-.319.098.515.515 0 0 1-.515-.366l-.294-.88a1.8 1.8 0 0 0-.443-.722c-.204-.2-.45-.353-.72-.448l-.881-.288a.57.57 0 0 1-.263-.191.56.56 0 0 1-.014-.64.5.5 0 0 1 .271-.194l.886-.294A1.82 1.82 0 0 0 6.01 5.465l.293-.87a.515.515 0 0 1 .49-.377c.11 0 .219.03.314.088a.56.56 0 0 1 .206.263l.298.896a1.82 1.82 0 0 0 1.175 1.174l.875.31a.5.5 0 0 1 .263.195c.07.09.108.2.108.314"></path><path fill="currentColor" d="M7.775 1.684a.5.5 0 0 0 .088-.262.45.45 0 0 0-.088-.263.5.5 0 0 0-.21-.155L7.24.896a.5.5 0 0 1-.165-.103.5.5 0 0 1-.103-.17l-.108-.33a.5.5 0 0 0-.165-.21A.5.5 0 0 0 6.426 0a.5.5 0 0 0-.252.098.5.5 0 0 0-.145.206l-.108.32a.5.5 0 0 1-.103.17.5.5 0 0 1-.17.102L5.334 1a.45.45 0 0 0-.216.155.5.5 0 0 0-.088.262c0 .094.029.186.083.263a.5.5 0 0 0 .216.16l.32.103q.095.03.164.103a.37.37 0 0 1 .103.165l.108.319c.031.09.088.17.165.227a.56.56 0 0 0 .252.077.42.42 0 0 0 .268-.093.5.5 0 0 0 .15-.2l.113-.325a.43.43 0 0 1 .268-.268l.32-.108a.42.42 0 0 0 .215-.155"></path></svg></div> <div class="flex min-w-0 flex-1"><textarea placeholder="Ask AI to help write your query..." class="max-h-64 min-h-8 w-full resize-none overflow-y-auto border-none bg-transparent py-1 text-sm leading-6 text-slate-700 placeholder-slate-400 [scrollbar-width:thin] focus:ring-0 dark:text-slate-200 dark:placeholder-slate-400" rows="1"></textarea> </div> </div> </div></div> <div class="relative flex flex-col rounded-md bg-gray-100 pt-2 dark:bg-gray-800/50"> <div class="flex h-64 items-center justify-center "><svg class="animate-spin text-xs" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 12 12"><path class="opacity-75" fill-rule="evenodd" clip-rule="evenodd" d="M6 0C2.6862 0 0 2.6862 0 6H1.8C1.8 4.88609 2.2425 3.8178 3.03015 3.03015C3.8178 2.2425 4.88609 1.8 6 1.8V0ZM12 6C12 9.3138 9.3138 12 6 12V10.2C7.11391 10.2 8.1822 9.7575 8.96985 8.96985C9.7575 8.1822 10.2 7.11391 10.2 6H12Z" fill="currentColor"></path><path class="opacity-25" fill-rule="evenodd" clip-rule="evenodd" d="M3.03015 8.96985C3.8178 9.7575 4.88609 10.2 6 10.2V12C2.6862 12 0 9.3138 0 6H1.8C1.8 7.11391 2.2425 8.1822 3.03015 8.96985ZM7.60727 2.11971C7.0977 1.90864 6.55155 1.8 6 1.8V0C9.3138 0 12 2.6862 12 6H10.2C10.2 5.44845 10.0914 4.9023 9.88029 4.39273C9.66922 3.88316 9.35985 3.42016 8.96985 3.03015C8.57984 2.64015 8.11684 2.33078 7.60727 2.11971Z" fill="currentColor"></path></svg></div></div> <div class="mt-2 flex flex-col gap-2"><div class="flex items-center justify-between max-sm:text-sm"><div class="flex w-full items-center justify-between gap-4"> <span class="flex flex-shrink-0 items-center gap-1"><span class="font-semibold">Subsets and Splits</span> <span class="inline-block "><span class="contents"><svg class="text-xs text-gray-500 dark:text-gray-400" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M17 22v-8h-4v2h2v6h-3v2h8v-2h-3z" fill="currentColor"></path><path d="M16 8a1.5 1.5 0 1 0 1.5 1.5A1.5 1.5 0 0 0 16 8z" fill="currentColor"></path><path d="M16 30a14 14 0 1 1 14-14a14 14 0 0 1-14 14zm0-26a12 12 0 1 0 12 12A12 12 0 0 0 16 4z" fill="currentColor"></path></svg></span> </span> </span> <div class="ml-4 flex flex-1 items-center justify-end gap-1"> </div></div></div> <div class="flex flex-nowrap gap-1 overflow-x-auto"></div></div> <button type="button" class="btn mt-2 h-10 w-full text-sm font-semibold md:text-base" ><span class="flex items-center gap-1.5"> <span>Run Query</span> <span class="shadow-xs ml-2 hidden items-center rounded-sm border bg-white px-0.5 text-xs font-medium text-gray-700 sm:inline-flex">Ctrl+↵</span></span></button></div> <div class="flex flex-col px-2 pb-4"></div></div> <div class="mt-auto pb-4"><div class="flex justify-center"><div class="w-full sm:px-4"><div class="mb-3"><ul class="flex gap-1 text-sm "><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-900 dark:hover:text-gray-300">Saved Queries </button> </li><li><button class="flex items-center whitespace-nowrap rounded-lg px-2 bg-black text-white dark:bg-gray-800">Top Community Queries </button> </li></ul></div> <div class="h-48 overflow-y-auto"><div class="flex flex-col gap-2"><div class="flex h-48 flex-col items-center justify-center rounded border border-gray-200 bg-gray-50 p-4 text-center dark:border-gray-700/60 dark:bg-gray-900"><p class="mb-1 font-semibold text-gray-600 dark:text-gray-400">No community queries yet</p> <p class="max-w-xs text-xs text-gray-500 dark:text-gray-400">The top public SQL queries from the community will appear here once available.</p></div></div></div></div></div></div></div></div></div></div> </div></div></div></main> </div> <script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script> import("\/front\/build\/kube-37f3ff5\/index.js"); window.moonSha = "kube-37f3ff5\/"; window.__hf_deferred = {}; </script> <!-- Stripe --> <script> if (["hf.co", "huggingface.co"].includes(window.location.hostname)) { const script = document.createElement("script"); script.src = "https://js.stripe.com/v3/"; script.async = true; document.head.appendChild(script); } </script> </body> </html>