{ // 获取包含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":"gwq5210/litlib"},"path":{"kind":"string","value":"thirdparty/sources/boost_1_60_0/libs/fusion/doc/html/fusion/adapted/adapt_tpl_adt.html"},"language":{"kind":"string","value":"HTML"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":19325,"string":"19,325"}}},{"rowIdx":115086009,"cells":{"code":{"kind":"string","value":"/// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-\n\n#include \n#include \"AP_InertialSensor_MPU6000.h\"\n\nextern const AP_HAL::HAL& hal;\n\n// MPU6000 accelerometer scaling\n#define MPU6000_ACCEL_SCALE_1G (GRAVITY_MSS / 4096.0f)\n\n// MPU 6000 registers\n#define MPUREG_XG_OFFS_TC 0x00\n#define MPUREG_YG_OFFS_TC 0x01\n#define MPUREG_ZG_OFFS_TC 0x02\n#define MPUREG_X_FINE_GAIN 0x03\n#define MPUREG_Y_FINE_GAIN 0x04\n#define MPUREG_Z_FINE_GAIN 0x05\n#define MPUREG_XA_OFFS_H 0x06 // X axis accelerometer offset (high byte)\n#define MPUREG_XA_OFFS_L 0x07 // X axis accelerometer offset (low byte)\n#define MPUREG_YA_OFFS_H 0x08 // Y axis accelerometer offset (high byte)\n#define MPUREG_YA_OFFS_L 0x09 // Y axis accelerometer offset (low byte)\n#define MPUREG_ZA_OFFS_H 0x0A // Z axis accelerometer offset (high byte)\n#define MPUREG_ZA_OFFS_L 0x0B // Z axis accelerometer offset (low byte)\n#define MPUREG_PRODUCT_ID 0x0C // Product ID Register\n#define MPUREG_XG_OFFS_USRH 0x13 // X axis gyro offset (high byte)\n#define MPUREG_XG_OFFS_USRL 0x14 // X axis gyro offset (low byte)\n#define MPUREG_YG_OFFS_USRH 0x15 // Y axis gyro offset (high byte)\n#define MPUREG_YG_OFFS_USRL 0x16 // Y axis gyro offset (low byte)\n#define MPUREG_ZG_OFFS_USRH 0x17 // Z axis gyro offset (high byte)\n#define MPUREG_ZG_OFFS_USRL 0x18 // Z axis gyro offset (low byte)\n#define MPUREG_SMPLRT_DIV 0x19 // sample rate. Fsample= 1Khz/(+1) = 200Hz\n# define MPUREG_SMPLRT_1000HZ 0x00\n# define MPUREG_SMPLRT_500HZ 0x01\n# define MPUREG_SMPLRT_250HZ 0x03\n# define MPUREG_SMPLRT_200HZ 0x04\n# define MPUREG_SMPLRT_100HZ 0x09\n# define MPUREG_SMPLRT_50HZ 0x13\n#define MPUREG_CONFIG 0x1A\n#define MPUREG_GYRO_CONFIG 0x1B\n// bit definitions for MPUREG_GYRO_CONFIG\n# define BITS_GYRO_FS_250DPS 0x00\n# define BITS_GYRO_FS_500DPS 0x08\n# define BITS_GYRO_FS_1000DPS 0x10\n# define BITS_GYRO_FS_2000DPS 0x18\n# define BITS_GYRO_FS_MASK 0x18 // only bits 3 and 4 are used for gyro full scale so use this to mask off other bits\n# define BITS_GYRO_ZGYRO_SELFTEST 0x20\n# define BITS_GYRO_YGYRO_SELFTEST 0x40\n# define BITS_GYRO_XGYRO_SELFTEST 0x80\n#define MPUREG_ACCEL_CONFIG 0x1C\n#define MPUREG_MOT_THR 0x1F // detection threshold for Motion interrupt generation. Motion is detected when the absolute value of any of the accelerometer measurements exceeds this\n#define MPUREG_MOT_DUR 0x20 // duration counter threshold for Motion interrupt generation. The duration counter ticks at 1 kHz, therefore MOT_DUR has a unit of 1 LSB = 1 ms\n#define MPUREG_ZRMOT_THR 0x21 // detection threshold for Zero Motion interrupt generation.\n#define MPUREG_ZRMOT_DUR 0x22 // duration counter threshold for Zero Motion interrupt generation. The duration counter ticks at 16 Hz, therefore ZRMOT_DUR has a unit of 1 LSB = 64 ms.\n#define MPUREG_FIFO_EN 0x23\n#define MPUREG_INT_PIN_CFG 0x37\n# define BIT_INT_RD_CLEAR 0x10 // clear the interrupt when any read occurs\n# define BIT_LATCH_INT_EN 0x20 // latch data ready pin \n#define MPUREG_INT_ENABLE 0x38\n// bit definitions for MPUREG_INT_ENABLE\n# define BIT_RAW_RDY_EN 0x01\n# define BIT_DMP_INT_EN 0x02 // enabling this bit (DMP_INT_EN) also enables RAW_RDY_EN it seems\n# define BIT_UNKNOWN_INT_EN 0x04\n# define BIT_I2C_MST_INT_EN 0x08\n# define BIT_FIFO_OFLOW_EN 0x10\n# define BIT_ZMOT_EN 0x20\n# define BIT_MOT_EN 0x40\n# define BIT_FF_EN 0x80\n#define MPUREG_INT_STATUS 0x3A\n// bit definitions for MPUREG_INT_STATUS (same bit pattern as above because this register shows what interrupt actually fired)\n# define BIT_RAW_RDY_INT 0x01\n# define BIT_DMP_INT 0x02\n# define BIT_UNKNOWN_INT 0x04\n# define BIT_I2C_MST_INT 0x08\n# define BIT_FIFO_OFLOW_INT 0x10\n# define BIT_ZMOT_INT 0x20\n# define BIT_MOT_INT 0x40\n# define BIT_FF_INT 0x80\n#define MPUREG_ACCEL_XOUT_H 0x3B\n#define MPUREG_ACCEL_XOUT_L 0x3C\n#define MPUREG_ACCEL_YOUT_H 0x3D\n#define MPUREG_ACCEL_YOUT_L 0x3E\n#define MPUREG_ACCEL_ZOUT_H 0x3F\n#define MPUREG_ACCEL_ZOUT_L 0x40\n#define MPUREG_TEMP_OUT_H 0x41\n#define MPUREG_TEMP_OUT_L 0x42\n#define MPUREG_GYRO_XOUT_H 0x43\n#define MPUREG_GYRO_XOUT_L 0x44\n#define MPUREG_GYRO_YOUT_H 0x45\n#define MPUREG_GYRO_YOUT_L 0x46\n#define MPUREG_GYRO_ZOUT_H 0x47\n#define MPUREG_GYRO_ZOUT_L 0x48\n#define MPUREG_USER_CTRL 0x6A\n// bit definitions for MPUREG_USER_CTRL\n# define BIT_USER_CTRL_SIG_COND_RESET 0x01 // resets signal paths and results registers for all sensors (gyros, accel, temp)\n# define BIT_USER_CTRL_I2C_MST_RESET 0x02 // reset I2C Master (only applicable if I2C_MST_EN bit is set)\n# define BIT_USER_CTRL_FIFO_RESET 0x04 // Reset (i.e. clear) FIFO buffer\n# define BIT_USER_CTRL_DMP_RESET 0x08 // Reset DMP\n# define BIT_USER_CTRL_I2C_IF_DIS 0x10 // Disable primary I2C interface and enable hal.spi->interface\n# define BIT_USER_CTRL_I2C_MST_EN 0x20 // Enable MPU to act as the I2C Master to external slave sensors\n# define BIT_USER_CTRL_FIFO_EN 0x40 // Enable FIFO operations\n# define BIT_USER_CTRL_DMP_EN 0x80 // Enable DMP operations\n#define MPUREG_PWR_MGMT_1 0x6B\n# define BIT_PWR_MGMT_1_CLK_INTERNAL 0x00 // clock set to internal 8Mhz oscillator\n# define BIT_PWR_MGMT_1_CLK_XGYRO 0x01 // PLL with X axis gyroscope reference\n# define BIT_PWR_MGMT_1_CLK_YGYRO 0x02 // PLL with Y axis gyroscope reference\n# define BIT_PWR_MGMT_1_CLK_ZGYRO 0x03 // PLL with Z axis gyroscope reference\n# define BIT_PWR_MGMT_1_CLK_EXT32KHZ 0x04 // PLL with external 32.768kHz reference\n# define BIT_PWR_MGMT_1_CLK_EXT19MHZ 0x05 // PLL with external 19.2MHz reference\n# define BIT_PWR_MGMT_1_CLK_STOP 0x07 // Stops the clock and keeps the timing generator in reset\n# define BIT_PWR_MGMT_1_TEMP_DIS 0x08 // disable temperature sensor\n# define BIT_PWR_MGMT_1_CYCLE 0x20 // put sensor into cycle mode. cycles between sleep mode and waking up to take a single sample of data from active sensors at a rate determined by LP_WAKE_CTRL\n# define BIT_PWR_MGMT_1_SLEEP 0x40 // put sensor into low power sleep mode\n# define BIT_PWR_MGMT_1_DEVICE_RESET 0x80 // reset entire device\n#define MPUREG_PWR_MGMT_2 0x6C // allows the user to configure the frequency of wake-ups in Accelerometer Only Low Power Mode\n#define MPUREG_BANK_SEL 0x6D // DMP bank selection register (used to indirectly access DMP registers)\n#define MPUREG_MEM_START_ADDR 0x6E // DMP memory start address (used to indirectly write to dmp memory)\n#define MPUREG_MEM_R_W 0x6F // DMP related register\n#define MPUREG_DMP_CFG_1 0x70 // DMP related register\n#define MPUREG_DMP_CFG_2 0x71 // DMP related register\n#define MPUREG_FIFO_COUNTH 0x72\n#define MPUREG_FIFO_COUNTL 0x73\n#define MPUREG_FIFO_R_W 0x74\n#define MPUREG_WHOAMI 0x75\n\n\n// Configuration bits MPU 3000 and MPU 6000 (not revised)?\n#define BITS_DLPF_CFG_256HZ_NOLPF2 0x00\n#define BITS_DLPF_CFG_188HZ 0x01\n#define BITS_DLPF_CFG_98HZ 0x02\n#define BITS_DLPF_CFG_42HZ 0x03\n#define BITS_DLPF_CFG_20HZ 0x04\n#define BITS_DLPF_CFG_10HZ 0x05\n#define BITS_DLPF_CFG_5HZ 0x06\n#define BITS_DLPF_CFG_2100HZ_NOLPF 0x07\n#define BITS_DLPF_CFG_MASK 0x07\n\n// Product ID Description for MPU6000\n// high 4 bits low 4 bits\n// Product Name\tProduct Revision\n#define MPU6000ES_REV_C4 0x14 // 0001\t\t\t0100\n#define MPU6000ES_REV_C5 0x15 // 0001\t\t\t0101\n#define MPU6000ES_REV_D6 0x16 // 0001\t\t\t0110\n#define MPU6000ES_REV_D7 0x17 // 0001\t\t\t0111\n#define MPU6000ES_REV_D8 0x18 // 0001\t\t\t1000\n#define MPU6000_REV_C4 0x54 // 0101\t\t\t0100\n#define MPU6000_REV_C5 0x55 // 0101\t\t\t0101\n#define MPU6000_REV_D6 0x56 // 0101\t\t\t0110\n#define MPU6000_REV_D7 0x57 // 0101\t\t\t0111\n#define MPU6000_REV_D8 0x58 // 0101\t\t\t1000\n#define MPU6000_REV_D9 0x59 // 0101\t\t\t1001\n\n// DMP output rate constants\n#define MPU6000_200HZ 0x00 // default value\n#define MPU6000_100HZ 0x01\n#define MPU6000_66HZ 0x02\n#define MPU6000_50HZ 0x03\n\n// DMP FIFO constants\n// Default quaternion FIFO size (4*4) + Footer(2)\n#define FIFO_PACKET_SIZE 18 \n// Rate of the gyro bias from gravity correction (200Hz/4) => 50Hz\n#define GYRO_BIAS_FROM_GRAVITY_RATE 4\n// Default gain for accel fusion (with gyros)\n#define DEFAULT_ACCEL_FUSION_GAIN 0x80\n\n/*\n * RM-MPU-6000A-00.pdf, page 33, section 4.25 lists LSB sensitivity of\n * gyro as 16.4 LSB/DPS at scale factor of +/- 2000dps (FS_SEL==3)\n */\nconst float AP_InertialSensor_MPU6000::_gyro_scale = (0.0174532 / 16.4);\n\n/* pch: I believe the accel and gyro indicies are correct\n * but somone else should please confirm.\n *\n * jamesjb: Y and Z axes are flipped on the PX4FMU\n */\nconst uint8_t AP_InertialSensor_MPU6000::_gyro_data_index[3] = { 5, 4, 6 };\nconst uint8_t AP_InertialSensor_MPU6000::_accel_data_index[3] = { 1, 0, 2 };\n\n#if CONFIG_HAL_BOARD == HAL_BOARD_SMACCM\nconst int8_t AP_InertialSensor_MPU6000::_gyro_data_sign[3] = { 1, -1, 1 };\nconst int8_t AP_InertialSensor_MPU6000::_accel_data_sign[3] = { 1, -1, 1 };\n#else\nconst int8_t AP_InertialSensor_MPU6000::_gyro_data_sign[3] = { 1, 1, -1 };\nconst int8_t AP_InertialSensor_MPU6000::_accel_data_sign[3] = { 1, 1, -1 };\n#endif\n\nconst uint8_t AP_InertialSensor_MPU6000::_temp_data_index = 3;\n\nint16_t AP_InertialSensor_MPU6000::_mpu6000_product_id = AP_PRODUCT_ID_NONE;\nAP_HAL::DigitalSource *AP_InertialSensor_MPU6000::_drdy_pin = NULL;\n\n// time we start collecting sample (reset on update)\n// time latest sample was collected\nstatic volatile uint32_t _last_sample_time_micros = 0;\n\n// DMP related static variables\nbool AP_InertialSensor_MPU6000::_dmp_initialised = false;\n// high byte of number of elements in fifo buffer\nuint8_t AP_InertialSensor_MPU6000::_fifoCountH;\n// low byte of number of elements in fifo buffer\nuint8_t AP_InertialSensor_MPU6000::_fifoCountL;\n// holds the 4 quaternions representing attitude taken directly from the DMP\nQuaternion AP_InertialSensor_MPU6000::quaternion;\n\n/* Static SPI device driver */\nAP_HAL::SPIDeviceDriver* AP_InertialSensor_MPU6000::_spi = NULL;\nAP_HAL::Semaphore* AP_InertialSensor_MPU6000::_spi_sem = NULL;\n\n/*\n * RM-MPU-6000A-00.pdf, page 31, section 4.23 lists LSB sensitivity of\n * accel as 4096 LSB/mg at scale factor of +/- 8g (AFS_SEL==2)\n *\n * See note below about accel scaling of engineering sample MPU6k\n * variants however\n */\n\nAP_InertialSensor_MPU6000::AP_InertialSensor_MPU6000() : AP_InertialSensor()\n{\n _temp = 0;\n _initialised = false;\n _dmp_initialised = false;\n}\n\nuint16_t AP_InertialSensor_MPU6000::_init_sensor( Sample_rate sample_rate )\n{\n if (_initialised) return _mpu6000_product_id;\n _initialised = true;\n\n _spi = hal.spi->device(AP_HAL::SPIDevice_MPU6000);\n _spi_sem = _spi->get_semaphore();\n\n /* Pin 70 defined especially to hook\n up PE6 to the hal.gpio abstraction.\n (It is not a valid pin under Arduino.) */\n _drdy_pin = hal.gpio->channel(70);\n\n hal.scheduler->suspend_timer_procs();\n\n uint8_t tries = 0;\n do {\n bool success = hardware_init(sample_rate);\n if (success) {\n hal.scheduler->delay(5+2);\n if (_data_ready()) {\n break;\n } else {\n hal.console->println_P(\n PSTR(\"MPU6000 startup failed: no data ready\"));\n }\n }\n if (tries++ > 5) {\n hal.scheduler->panic(PSTR(\"PANIC: failed to boot MPU6000 5 times\")); \n }\n } while (1);\n\n hal.scheduler->resume_timer_procs();\n \n\n /* read the first lot of data.\n * _read_data_transaction requires the spi semaphore to be taken by\n * its caller. */\n _last_sample_time_micros = hal.scheduler->micros();\n _read_data_transaction();\n\n // start the timer process to read samples\n hal.scheduler->register_timer_process(_poll_data);\n\n#if MPU6000_DEBUG\n _dump_registers();\n#endif\n return _mpu6000_product_id;\n}\n\n// accumulation in ISR - must be read with interrupts disabled\n// the sum of the values since last read\nstatic volatile int32_t _sum[7];\n\n// how many values we've accumulated since last read\nstatic volatile uint16_t _count;\n\n/*================ AP_INERTIALSENSOR PUBLIC INTERFACE ==================== */\n\nvoid AP_InertialSensor_MPU6000::wait_for_sample()\n{\n uint32_t tstart = hal.scheduler->micros();\n while (num_samples_available() == 0) {\n uint32_t now = hal.scheduler->micros();\n uint32_t dt = now - tstart;\n if (dt > 50000) {\n hal.scheduler->panic(\n PSTR(\"PANIC: AP_InertialSensor_MPU6000::update \"\n \"waited 50ms for data from interrupt\"));\n }\n }\n}\n\nbool AP_InertialSensor_MPU6000::update( void )\n{\n int32_t sum[7];\n float count_scale;\n Vector3f accel_scale = _accel_scale.get();\n\n // wait for at least 1 sample\n wait_for_sample();\n\n // disable timer procs for mininum time\n hal.scheduler->suspend_timer_procs();\n /** ATOMIC SECTION w/r/t TIMER PROCESS */\n {\n for (int i=0; i<7; i++) {\n sum[i] = _sum[i];\n _sum[i] = 0;\n }\n\n _num_samples = _count;\n _count = 0;\n }\n hal.scheduler->resume_timer_procs();\n\n count_scale = 1.0f / _num_samples;\n\n _gyro = Vector3f(_gyro_data_sign[0] * sum[_gyro_data_index[0]],\n _gyro_data_sign[1] * sum[_gyro_data_index[1]],\n _gyro_data_sign[2] * sum[_gyro_data_index[2]]);\n _gyro.rotate(_board_orientation);\n _gyro *= _gyro_scale * count_scale;\n _gyro -= _gyro_offset;\n\n _accel = Vector3f(_accel_data_sign[0] * sum[_accel_data_index[0]],\n _accel_data_sign[1] * sum[_accel_data_index[1]],\n _accel_data_sign[2] * sum[_accel_data_index[2]]);\n _accel.rotate(_board_orientation);\n _accel *= count_scale * MPU6000_ACCEL_SCALE_1G;\n _accel.x *= accel_scale.x;\n _accel.y *= accel_scale.y;\n _accel.z *= accel_scale.z;\n _accel -= _accel_offset;\n\n _temp = _temp_to_celsius(sum[_temp_data_index] * count_scale);\n\n if (_last_filter_hz != _mpu6000_filter) {\n if (_spi_sem->take(10)) {\n _set_filter_register(_mpu6000_filter, 0);\n _spi_sem->give();\n }\n }\n\n return true;\n}\n\n/*================ HARDWARE FUNCTIONS ==================== */\n\n/**\n * Return true if the MPU6000 has new data available for reading.\n *\n * We use the data ready pin if it is available. Otherwise, read the\n * status register.\n */\nbool AP_InertialSensor_MPU6000::_data_ready()\n{\n if (_drdy_pin) {\n return _drdy_pin->read() != 0;\n }\n\n if (hal.scheduler->in_timerprocess()) {\n bool got = _spi_sem->take_nonblocking();\n if (got) {\n uint8_t status = _register_read(MPUREG_INT_STATUS);\n _spi_sem->give();\n return (status & BIT_RAW_RDY_INT) != 0;\n } else {\n return false;\n }\n } else {\n bool got = _spi_sem->take(10);\n if (got) {\n uint8_t status = _register_read(MPUREG_INT_STATUS);\n _spi_sem->give();\n return (status & BIT_RAW_RDY_INT) != 0;\n } else {\n hal.scheduler->panic(\n PSTR(\"PANIC: AP_InertialSensor_MPU6000::_data_ready failed to \"\n \"take SPI semaphore synchronously\"));\n }\n }\n return false;\n}\n\n/**\n * Timer process to poll for new data from the MPU6000.\n */\nvoid AP_InertialSensor_MPU6000::_poll_data(uint32_t now)\n{\n if (_data_ready()) {\n if (hal.scheduler->in_timerprocess()) {\n _read_data_from_timerprocess();\n } else {\n /* Synchronous read - take semaphore */\n bool got = _spi_sem->take(10);\n if (got) {\n _last_sample_time_micros = hal.scheduler->micros();\n _read_data_transaction(); \n _spi_sem->give();\n } else {\n hal.scheduler->panic(\n PSTR(\"PANIC: AP_InertialSensor_MPU6000::_poll_data \"\n \"failed to take SPI semaphore synchronously\"));\n }\n }\n }\n}\n\n/*\n * this is called from the _poll_data, in the timer process context.\n * when the MPU6000 has new sensor data available and add it to _sum[] to\n * ensure this is the case, these other devices must perform their spi reads\n * after being called by the AP_TimerProcess.\n */\nvoid AP_InertialSensor_MPU6000::_read_data_from_timerprocess()\n{\n static uint8_t semfail_ctr = 0;\n bool got = _spi_sem->take_nonblocking();\n if (!got) { \n semfail_ctr++;\n if (semfail_ctr > 100) {\n hal.scheduler->panic(PSTR(\"PANIC: failed to take SPI semaphore \"\n \"100 times in AP_InertialSensor_MPU6000::\"\n \"_read_data_from_timerprocess\"));\n }\n return;\n } else {\n semfail_ctr = 0;\n } \n\n _last_sample_time_micros = hal.scheduler->micros();\n _read_data_transaction();\n\n _spi_sem->give();\n}\n\nvoid AP_InertialSensor_MPU6000::_read_data_transaction() {\n /* one resister address followed by seven 2-byte registers */\n uint8_t tx[15];\n uint8_t rx[15];\n memset(tx,0,15);\n tx[0] = MPUREG_ACCEL_XOUT_H | 0x80;\n _spi->transaction(tx, rx, 15);\n\n for (uint8_t i = 0; i < 7; i++) {\n _sum[i] += (int16_t)(((uint16_t)rx[2*i+1] << 8) | rx[2*i+2]);\n } \n \n _count++;\n if (_count == 0) {\n // rollover - v unlikely\n memset((void*)_sum, 0, sizeof(_sum));\n }\n\n // should also read FIFO data if enabled\n if( _dmp_initialised ) {\n if( FIFO_ready() ) {\n FIFO_getPacket();\n }\n }\n}\n\nuint8_t AP_InertialSensor_MPU6000::_register_read( uint8_t reg )\n{\n uint8_t addr = reg | 0x80; // Set most significant bit\n\n uint8_t tx[2];\n uint8_t rx[2];\n\n tx[0] = addr;\n tx[1] = 0;\n _spi->transaction(tx, rx, 2);\n\n return rx[1];\n}\n\nvoid AP_InertialSensor_MPU6000::register_write(uint8_t reg, uint8_t val)\n{\n uint8_t tx[2];\n uint8_t rx[2];\n\n tx[0] = reg;\n tx[1] = val;\n _spi->transaction(tx, rx, 2);\n}\n\n/*\n set the DLPF filter frequency. Assumes caller has taken semaphore\n */\nvoid AP_InertialSensor_MPU6000::_set_filter_register(uint8_t filter_hz, uint8_t default_filter)\n{\n uint8_t filter = default_filter;\n // choose filtering frequency\n switch (filter_hz) {\n case 5:\n filter = BITS_DLPF_CFG_5HZ;\n break;\n case 10:\n filter = BITS_DLPF_CFG_10HZ;\n break;\n case 20:\n filter = BITS_DLPF_CFG_20HZ;\n break;\n case 42:\n filter = BITS_DLPF_CFG_42HZ;\n break;\n case 98:\n filter = BITS_DLPF_CFG_98HZ;\n break;\n }\n\n if (filter != 0) {\n _last_filter_hz = filter_hz;\n\n register_write(MPUREG_CONFIG, filter);\n }\n}\n\n\nbool AP_InertialSensor_MPU6000::hardware_init(Sample_rate sample_rate)\n{\n if (!_spi_sem->take(100)) {\n hal.scheduler->panic(PSTR(\"MPU6000: Unable to get semaphore\"));\n }\n\n // Chip reset\n uint8_t tries;\n for (tries = 0; tries<5; tries++) {\n register_write(MPUREG_PWR_MGMT_1, BIT_PWR_MGMT_1_DEVICE_RESET);\n hal.scheduler->delay(100);\n\n // Wake up device and select GyroZ clock. Note that the\n // MPU6000 starts up in sleep mode, and it can take some time\n // for it to come out of sleep\n register_write(MPUREG_PWR_MGMT_1, BIT_PWR_MGMT_1_CLK_ZGYRO);\n hal.scheduler->delay(5);\n\n // check it has woken up\n if (_register_read(MPUREG_PWR_MGMT_1) == BIT_PWR_MGMT_1_CLK_ZGYRO) {\n break;\n }\n#if MPU6000_DEBUG\n _dump_registers();\n#endif\n }\n if (tries == 5) {\n hal.console->println_P(PSTR(\"Failed to boot MPU6000 5 times\"));\n _spi_sem->give();\n return false;\n }\n\n register_write(MPUREG_PWR_MGMT_2, 0x00); // only used for wake-up in accelerometer only low power mode\n hal.scheduler->delay(1);\n\n // Disable I2C bus (recommended on datasheet)\n register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_I2C_IF_DIS);\n hal.scheduler->delay(1);\n\n uint8_t default_filter;\n\n // sample rate and filtering\n // to minimise the effects of aliasing we choose a filter\n // that is less than half of the sample rate\n switch (sample_rate) {\n case RATE_50HZ:\n // this is used for plane and rover, where noise resistance is\n // more important than update rate. Tests on an aerobatic plane\n // show that 10Hz is fine, and makes it very noise resistant\n default_filter = BITS_DLPF_CFG_10HZ;\n _sample_shift = 2;\n break;\n case RATE_100HZ:\n default_filter = BITS_DLPF_CFG_20HZ;\n _sample_shift = 1;\n break;\n case RATE_200HZ:\n default:\n default_filter = BITS_DLPF_CFG_20HZ;\n _sample_shift = 0;\n break;\n }\n\n _set_filter_register(_mpu6000_filter, default_filter);\n\n // set sample rate to 200Hz, and use _sample_divider to give\n // the requested rate to the application\n register_write(MPUREG_SMPLRT_DIV, MPUREG_SMPLRT_200HZ);\n hal.scheduler->delay(1);\n\n register_write(MPUREG_GYRO_CONFIG, BITS_GYRO_FS_2000DPS); // Gyro scale 2000º/s\n hal.scheduler->delay(1);\n\n // read the product ID rev c has 1/2 the sensitivity of rev d\n _mpu6000_product_id = _register_read(MPUREG_PRODUCT_ID);\n //Serial.printf(\"Product_ID= 0x%x\\n\", (unsigned) _mpu6000_product_id);\n\n if ((_mpu6000_product_id == MPU6000ES_REV_C4) || (_mpu6000_product_id == MPU6000ES_REV_C5) ||\n (_mpu6000_product_id == MPU6000_REV_C4) || (_mpu6000_product_id == MPU6000_REV_C5)) {\n // Accel scale 8g (4096 LSB/g)\n // Rev C has different scaling than rev D\n register_write(MPUREG_ACCEL_CONFIG,1<<3);\n } else {\n // Accel scale 8g (4096 LSB/g)\n register_write(MPUREG_ACCEL_CONFIG,2<<3);\n }\n hal.scheduler->delay(1);\n\n // configure interrupt to fire when new data arrives\n register_write(MPUREG_INT_ENABLE, BIT_RAW_RDY_EN);\n hal.scheduler->delay(1);\n\n // clear interrupt on any read, and hold the data ready pin high\n // until we clear the interrupt\n register_write(MPUREG_INT_PIN_CFG, BIT_INT_RD_CLEAR | BIT_LATCH_INT_EN);\n hal.scheduler->delay(1);\n\n _spi_sem->give();\n\n return true;\n}\n\nfloat AP_InertialSensor_MPU6000::_temp_to_celsius ( uint16_t regval )\n{\n /* TODO */\n return 20.0;\n}\n\n// return the MPU6k gyro drift rate in radian/s/s\n// note that this is much better than the oilpan gyros\nfloat AP_InertialSensor_MPU6000::get_gyro_drift_rate(void)\n{\n // 0.5 degrees/second/minute\n return ToRad(0.5/60);\n}\n\n// get number of samples read from the sensors\nuint16_t AP_InertialSensor_MPU6000::num_samples_available()\n{\n _poll_data(0);\n return _count >> _sample_shift;\n}\n\n\n#if MPU6000_DEBUG\n// dump all config registers - used for debug\nvoid AP_InertialSensor_MPU6000::_dump_registers(void)\n{\n hal.console->println_P(PSTR(\"MPU6000 registers\"));\n for (uint8_t reg=MPUREG_PRODUCT_ID; reg<=108; reg++) {\n uint8_t v = _register_read(reg);\n hal.console->printf_P(PSTR(\"%02x:%02x \"), (unsigned)reg, (unsigned)v);\n if ((reg - (MPUREG_PRODUCT_ID-1)) % 16 == 0) {\n hal.console->println();\n }\n }\n hal.console->println();\n}\n#endif\n\n\n// get_delta_time returns the time period in seconds overwhich the sensor data was collected\nfloat AP_InertialSensor_MPU6000::get_delta_time() \n{\n // the sensor runs at 200Hz\n return 0.005 * _num_samples;\n}\n\n// Update gyro offsets with new values. Offsets provided in as scaled deg/sec values\nvoid AP_InertialSensor_MPU6000::push_gyro_offsets_to_dmp()\n{\n Vector3f gyro_offsets = _gyro_offset.get();\n\n int16_t offsetX = gyro_offsets.x / _gyro_scale * _gyro_data_sign[0];\n int16_t offsetY = gyro_offsets.y / _gyro_scale * _gyro_data_sign[1];\n int16_t offsetZ = gyro_offsets.z / _gyro_scale * _gyro_data_sign[2];\n\n set_dmp_gyro_offsets(offsetX, offsetY, offsetZ);\n\n // remove ins level offsets to avoid double counting\n gyro_offsets.x = 0;\n gyro_offsets.y = 0;\n gyro_offsets.z = 0;\n _gyro_offset = gyro_offsets;\n}\n\n// Update gyro offsets with new values. New offset values are substracted to actual offset values.\n// offset values in gyro LSB units (as read from registers)\nvoid AP_InertialSensor_MPU6000::set_dmp_gyro_offsets(int16_t offsetX, int16_t offsetY, int16_t offsetZ)\n{\n int16_t aux_int;\n\n if (offsetX != 0) {\n // Read actual value\n aux_int = (_register_read(MPUREG_XG_OFFS_USRH)<<8) | _register_read(MPUREG_XG_OFFS_USRL);\n aux_int -= offsetX<<1; // Adjust to internal units\n // Write to MPU registers\n register_write(MPUREG_XG_OFFS_USRH, (aux_int>>8)&0xFF);\n register_write(MPUREG_XG_OFFS_USRL, aux_int&0xFF);\n }\n if (offsetY != 0) {\n aux_int = (_register_read(MPUREG_YG_OFFS_USRH)<<8) | _register_read(MPUREG_YG_OFFS_USRL);\n aux_int -= offsetY<<1; // Adjust to internal units\n // Write to MPU registers\n register_write(MPUREG_YG_OFFS_USRH, (aux_int>>8)&0xFF);\n register_write(MPUREG_YG_OFFS_USRL, aux_int&0xFF);\n }\n if (offsetZ != 0) {\n aux_int = (_register_read(MPUREG_ZG_OFFS_USRH)<<8) | _register_read(MPUREG_ZG_OFFS_USRL);\n aux_int -= offsetZ<<1; // Adjust to internal units\n // Write to MPU registers\n register_write(MPUREG_ZG_OFFS_USRH, (aux_int>>8)&0xFF);\n register_write(MPUREG_ZG_OFFS_USRL, aux_int&0xFF);\n }\n}\n\n// Update accel offsets with new values. Offsets provided in as scaled values (1G)\nvoid AP_InertialSensor_MPU6000::push_accel_offsets_to_dmp()\n{\n Vector3f accel_offset = _accel_offset.get();\n Vector3f accel_scale = _accel_scale.get();\n int16_t offsetX = accel_offset.x / (accel_scale.x * _accel_data_sign[0] * MPU6000_ACCEL_SCALE_1G);\n int16_t offsetY = accel_offset.y / (accel_scale.y * _accel_data_sign[1] * MPU6000_ACCEL_SCALE_1G);\n int16_t offsetZ = accel_offset.z / (accel_scale.z * _accel_data_sign[2] * MPU6000_ACCEL_SCALE_1G);\n\n // strangely x and y are reversed\n set_dmp_accel_offsets(offsetY, offsetX, offsetZ);\n}\n\n// set_accel_offsets - adds an offset to acceleromter readings\n// This is useful for dynamic acceleration correction (for example centripetal force correction)\n// and for the initial offset calibration\n// Input, accel offsets for X,Y and Z in LSB units (as read from raw values)\nvoid AP_InertialSensor_MPU6000::set_dmp_accel_offsets(int16_t offsetX, int16_t offsetY, int16_t offsetZ)\n{\n int aux_int;\n uint8_t regs[2];\n\n // Write accel offsets to DMP memory...\n // TO-DO: why don't we write to main accel offset registries? i.e. MPUREG_XA_OFFS_H\n aux_int = offsetX>>1; // Transform to internal units\n regs[0]=(aux_int>>8)&0xFF;\n regs[1]=aux_int&0xFF;\n dmp_register_write(0x01,0x08,2,regs); // key KEY_D_1_8 Accel X offset\n\n aux_int = offsetY>>1;\n regs[0]=(aux_int>>8)&0xFF;\n regs[1]=aux_int&0xFF;\n dmp_register_write(0x01,0x0A,2,regs); // key KEY_D_1_10 Accel Y offset\n\n aux_int = offsetZ>>1;\n regs[0]=(aux_int>>8)&0xFF;\n regs[1]=aux_int&0xFF;\n dmp_register_write(0x01,0x02,2,regs); // key KEY_D_1_2 Accel Z offset\n}\n\n// dmp_register_write - method to write to dmp's registers\n// the dmp is logically separated from the main mpu6000. To write a block of memory to the DMP's memory you\n// write the \"bank\" and starting address into two of the main MPU's registers, then write the data one byte\n// at a time into the MPUREG_MEM_R_W register\nvoid AP_InertialSensor_MPU6000::dmp_register_write(uint8_t bank, uint8_t address, uint8_t num_bytes, uint8_t data[])\n{\n register_write(MPUREG_BANK_SEL,bank);\n register_write(MPUREG_MEM_START_ADDR,address);\n\n _spi->cs_assert();\n _spi->transfer(MPUREG_MEM_R_W);\n for (uint8_t i=0; itransfer(data[i]);\n }\n _spi->cs_release();\n}\n\n// MPU6000 DMP initialization\n// this should be called after hardware_init if you wish to enable the dmp\nvoid AP_InertialSensor_MPU6000::dmp_init()\n{\n uint8_t regs[4]; // for writing to dmp\n\n // ensure we only initialise once\n if( _dmp_initialised ) {\n return;\n }\n\n // load initial values into DMP memory\n dmp_load_mem();\n\n dmp_set_gyro_calibration();\n dmp_set_accel_calibration();\n dmp_apply_endian_accel();\n dmp_set_mpu_sensors();\n dmp_set_bias_none();\n dmp_set_fifo_interrupt();\n dmp_send_quaternion(); // By default we only send the quaternion to the FIFO (18 bytes packet size)\n dmp_set_fifo_rate(MPU6000_200HZ); // 200Hz DMP output rate\n\n register_write(MPUREG_INT_ENABLE, BIT_RAW_RDY_EN | BIT_DMP_INT_EN ); // configure interrupts to fire only when new data arrives from DMP (in fifo buffer)\n\n // Randy: no idea what this does\n register_write(MPUREG_DMP_CFG_1, 0x03); //MPUREG_DMP_CFG_1, 0x03\n register_write(MPUREG_DMP_CFG_2, 0x00); //MPUREG_DMP_CFG_2, 0x00\n\n //inv_state_change_fifo\n regs[0] = 0xFF;\n regs[1] = 0xFF;\n dmp_register_write(0x01, 0xB2, 0x02, regs); // D_1_178\n\n // ?? FIFO ??\n regs[0] = 0x09;\n regs[1] = 0x23;\n regs[2] = 0xA1;\n regs[3] = 0x35;\n dmp_register_write(0x01, 0x90, 0x04, regs); // D_1_144\n\n //register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET);\t\t//MPUREG_USER_CTRL, BIT_FIFO_RST\n FIFO_reset();\n\n FIFO_ready();\n\n //register_write(MPUREG_USER_CTRL, 0x00);\t\t// MPUREG_USER_CTRL, 0. TO-DO: is all this setting of USER_CTRL really necessary?\n\n register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET); //MPUREG_USER_CTRL, BIT_FIFO_RST. TO-DO: replace this call with FIFO_reset()?\n register_write(MPUREG_USER_CTRL, 0x00); // MPUREG_USER_CTRL: 0\n register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_DMP_EN | BIT_USER_CTRL_FIFO_EN | BIT_USER_CTRL_DMP_RESET);\n\n // Set the gain of the accel in the sensor fusion\n dmp_set_sensor_fusion_accel_gain(DEFAULT_ACCEL_FUSION_GAIN); // default value\n\n // dmp initialisation complete\n _dmp_initialised = true;\n\n}\n\n// dmp_reset - reset dmp (required for changes in gains or offsets to take effect)\nvoid AP_InertialSensor_MPU6000::dmp_reset()\n{\n //uint8_t tmp = register_read(MPUREG_USER_CTRL);\n //tmp |= BIT_USER_CTRL_DMP_RESET;\n //register_write(MPUREG_USER_CTRL,tmp);\n register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_FIFO_RESET); //MPUREG_USER_CTRL, BIT_FIFO_RST. TO-DO: replace this call with FIFO_reset()?\n register_write(MPUREG_USER_CTRL, 0x00); // MPUREG_USER_CTRL: 0\n register_write(MPUREG_USER_CTRL, BIT_USER_CTRL_DMP_EN | BIT_USER_CTRL_FIFO_EN | BIT_USER_CTRL_DMP_RESET);\n}\n\n// New data packet in FIFO?\nbool AP_InertialSensor_MPU6000::FIFO_ready()\n{\n _fifoCountH = _register_read(MPUREG_FIFO_COUNTH);\n _fifoCountL = _register_read(MPUREG_FIFO_COUNTL);\n if(_fifoCountL == FIFO_PACKET_SIZE) {\n return 1;\n }\n else{\n //We should not reach this point or maybe we have more than one packet (we should manage this!)\n FIFO_reset();\n return 0;\n }\n}\n\n// FIFO_reset - reset/clear FIFO buffer used to capture attitude information from DMP\nvoid AP_InertialSensor_MPU6000::FIFO_reset()\n{\n uint8_t temp;\n temp = _register_read(MPUREG_USER_CTRL);\n temp = temp | BIT_USER_CTRL_FIFO_RESET; // FIFO RESET BIT\n register_write(MPUREG_USER_CTRL, temp);\n}\n\n// FIFO_getPacket - read an attitude packet from FIFO buffer\n// TO-DO: interpret results instead of just dumping into a buffer\nvoid AP_InertialSensor_MPU6000::FIFO_getPacket()\n{\n uint8_t i;\n int16_t q_data[4];\n uint8_t addr = MPUREG_FIFO_R_W | 0x80; // Set most significant bit to indicate a read\n uint8_t received_packet[DMP_FIFO_BUFFER_SIZE]; // FIFO packet buffer\n _spi->cs_assert();\n _spi->transfer(addr); // send address we want to read from\n for(i = 0; i < _fifoCountL; i++) {\n received_packet[i] = _spi->transfer(0); // request value\n }\n _spi->cs_release();\n\n // we are using 16 bits resolution\n q_data[0] = (int16_t) ((((uint16_t) received_packet[0]) << 8) + ((uint16_t) received_packet[1]));\n q_data[1] = (int16_t) ((((uint16_t) received_packet[4]) << 8) + ((uint16_t) received_packet[5]));\n q_data[2] = (int16_t) ((((uint16_t) received_packet[8]) << 8) + ((uint16_t) received_packet[9]));\n q_data[3] = (int16_t) ((((uint16_t) received_packet[12]) << 8) + ((uint16_t) received_packet[13]));\n\n quaternion.q1 = ((float)q_data[0]) / 16384.0f; // convert from fixed point to float\n quaternion.q2 = ((float)q_data[2]) / 16384.0f; // convert from fixed point to float\n quaternion.q3 = ((float)q_data[1]) / 16384.0f; // convert from fixed point to float\n quaternion.q4 = ((float)-q_data[3]) / 16384.0f; // convert from fixed point to float\n}\n\n// dmp_set_gyro_calibration - apply default gyro calibration FS=2000dps and default orientation\nvoid AP_InertialSensor_MPU6000::dmp_set_gyro_calibration()\n{\n uint8_t regs[4];\n regs[0]=0x4C;\n regs[1]=0xCD;\n regs[2]=0x6C;\n dmp_register_write(0x03, 0x7B, 0x03, regs); //FCFG_1 inv_set_gyro_calibration\n regs[0]=0x36;\n regs[1]=0x56;\n regs[2]=0x76;\n dmp_register_write(0x03, 0xAB, 0x03, regs); //FCFG_3 inv_set_gyro_calibration\n regs[0]=0x02;\n regs[1]=0xCB;\n regs[2]=0x47;\n regs[3]=0xA2;\n dmp_register_write(0x00, 0x68, 0x04, regs); //D_0_104 inv_set_gyro_calibration\n regs[0]=0x00;\n regs[1]=0x05;\n regs[2]=0x8B;\n regs[3]=0xC1;\n dmp_register_write(0x02, 0x18, 0x04, regs); //D_0_24 inv_set_gyro_calibration\n}\n\n// dmp_set_accel_calibration - apply default accel calibration scale=8g and default orientation\nvoid AP_InertialSensor_MPU6000::dmp_set_accel_calibration()\n{\n uint8_t regs[6];\n regs[0]=0x00;\n regs[1]=0x00;\n regs[2]=0x00;\n regs[3]=0x00;\n dmp_register_write(0x01, 0x0C, 0x04, regs); //D_1_152 inv_set_accel_calibration\n regs[0]=0x0C;\n regs[1]=0xC9;\n regs[2]=0x2C;\n regs[3]=0x97;\n regs[4]=0x97;\n regs[5]=0x97;\n dmp_register_write(0x03, 0x7F, 0x06, regs); //FCFG_2 inv_set_accel_calibration\n regs[0]=0x26;\n regs[1]=0x46;\n regs[2]=0x66;\n dmp_register_write(0x03, 0x89, 0x03, regs); //FCFG_7 inv_set_accel_calibration\n // accel range, 0x20,0x00 => 2g, 0x10,0x00=>4g regs= (1073741824/accel_scale*65536)\n //regs[0]=0x20;\t// 2g\n regs[0]=0x08; // 8g\n regs[1]=0x00;\n dmp_register_write(0x00, 0x6C, 0x02, regs); //D_0_108 inv_set_accel_calibration\n}\n\n// dmp_apply_endian_accel - set byte order of accelerometer values?\nvoid AP_InertialSensor_MPU6000::dmp_apply_endian_accel()\n{\n uint8_t regs[4];\n regs[0]=0x00;\n regs[1]=0x00;\n regs[2]=0x40;\n regs[3]=0x00;\n dmp_register_write(0x01, 0xEC, 0x04, regs); //D_1_236 inv_apply_endian_accel\n}\n\n// dmp_set_mpu_sensors - to configure for SIX_AXIS output\nvoid AP_InertialSensor_MPU6000::dmp_set_mpu_sensors()\n{\n uint8_t regs[6];\n regs[0]=0x0C;\n regs[1]=0xC9;\n regs[2]=0x2C;\n regs[3]=0x97;\n regs[4]=0x97;\n regs[5]=0x97;\n dmp_register_write(0x03, 0x7F, 0x06, regs); //FCFG_2 inv_set_mpu_sensors(INV_SIX_AXIS_GYRO_ACCEL);\n}\n\n// dmp_set_bias_from_no_motion - turn on bias from no motion\nvoid AP_InertialSensor_MPU6000::dmp_set_bias_from_no_motion()\n{\n uint8_t regs[4];\n regs[0]=0x0D;\n regs[1]=0x35;\n regs[2]=0x5D;\n dmp_register_write(0x04, 0x02, 0x03, regs); //CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion\n regs[0]=0x87;\n regs[1]=0x2D;\n regs[2]=0x35;\n regs[3]=0x3D;\n dmp_register_write(0x04, 0x09, 0x04, regs); //FCFG_5 inv_set_bias_update( INV_BIAS_FROM_NO_MOTION );\n}\n\n// dmp_set_bias_none - turn off internal bias correction (we will use this and we handle the gyro bias correction externally)\nvoid AP_InertialSensor_MPU6000::dmp_set_bias_none()\n{\n uint8_t regs[4];\n regs[0]=0x98;\n regs[1]=0x98;\n regs[2]=0x98;\n dmp_register_write(0x04, 0x02, 0x03, regs); //CFG_MOTION_BIAS inv_turn_off_bias_from_no_motion\n regs[0]=0x87;\n regs[1]=0x2D;\n regs[2]=0x35;\n regs[3]=0x3D;\n dmp_register_write(0x04, 0x09, 0x04, regs); //FCFG_5 inv_set_bias_update( INV_BIAS_FROM_NO_MOTION );\n}\n\n// dmp_set_fifo_interrupt\nvoid AP_InertialSensor_MPU6000::dmp_set_fifo_interrupt()\n{\n uint8_t regs[1];\n regs[0]=0xFE;\n dmp_register_write(0x07, 0x86, 0x01, regs); //CFG_6 inv_set_fifo_interupt\n}\n\n// dmp_send_quaternion - send quaternion data to FIFO\nvoid AP_InertialSensor_MPU6000::dmp_send_quaternion()\n{\n uint8_t regs[5];\n regs[0]=0xF1;\n regs[1]=0x20;\n regs[2]=0x28;\n regs[3]=0x30;\n regs[4]=0x38;\n dmp_register_write(0x07, 0x41, 0x05, regs); //CFG_8 inv_send_quaternion\n regs[0]=0x30;\n dmp_register_write(0x07, 0x7E, 0x01, regs); //CFG_16 inv_set_footer\n}\n\n// dmp_send_gyro - send gyro data to FIFO\nvoid AP_InertialSensor_MPU6000::dmp_send_gyro()\n{\n uint8_t regs[4];\n regs[0]=0xF1;\n regs[1]=0x28;\n regs[2]=0x30;\n regs[3]=0x38;\n dmp_register_write(0x07, 0x47, 0x04, regs); //CFG_9 inv_send_gyro\n}\n\n// dmp_send_accel - send accel data to FIFO\nvoid AP_InertialSensor_MPU6000::dmp_send_accel()\n{\n uint8_t regs[54];\n regs[0]=0xF1;\n regs[1]=0x28;\n regs[2]=0x30;\n regs[3]=0x38;\n dmp_register_write(0x07, 0x6C, 0x04, regs); //CFG_12 inv_send_accel\n}\n\n// This functions defines the rate at wich attitude data is send to FIFO\n// Rate: 0 => SAMPLE_RATE(ex:200Hz), 1=> SAMPLE_RATE/2 (ex:100Hz), 2=> SAMPLE_RATE/3 (ex:66Hz)\n// rate constant definitions in MPU6000.h\nvoid AP_InertialSensor_MPU6000::dmp_set_fifo_rate(uint8_t rate)\n{\n uint8_t regs[2];\n regs[0]=0x00;\n regs[1]=rate;\n dmp_register_write(0x02, 0x16, 0x02, regs); //D_0_22 inv_set_fifo_rate\n}\n\n// This function defines the weight of the accel on the sensor fusion\n// default value is 0x80\n// The official invensense name is inv_key_0_96 (??)\nvoid AP_InertialSensor_MPU6000::dmp_set_sensor_fusion_accel_gain(uint8_t gain)\n{\n //inv_key_0_96\n register_write(MPUREG_BANK_SEL,0x00);\n register_write(MPUREG_MEM_START_ADDR, 0x60);\n _spi->cs_assert();\n _spi->transfer(MPUREG_MEM_R_W);\n _spi->transfer(0x00);\n _spi->transfer(gain); // Original : 0x80 To test: 0x40, 0x20 (too less)\n _spi->transfer(0x00);\n _spi->transfer(0x00);\n _spi->cs_release();\n}\n\n// Load initial memory values into DMP memory banks\nvoid AP_InertialSensor_MPU6000::dmp_load_mem()\n{\n\n for(int i = 0; i < 7; i++) {\n register_write(MPUREG_BANK_SEL,i); //MPUREG_BANK_SEL\n for(uint8_t j = 0; j < 16; j++) {\n uint8_t start_addy = j * 0x10;\n register_write(MPUREG_MEM_START_ADDR,start_addy);\n _spi->cs_assert();\n _spi->transfer(MPUREG_MEM_R_W);\n for(int k = 0; k < 16; k++) {\n uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[i][j][k]));\n _spi->transfer((uint8_t) byteToSend);\n }\n _spi->cs_release();\n }\n }\n\n register_write(MPUREG_BANK_SEL,7); //MPUREG_BANK_SEL\n for(uint8_t j = 0; j < 8; j++) {\n uint8_t start_addy = j * 0x10;\n register_write(MPUREG_MEM_START_ADDR,start_addy);\n _spi->cs_assert();\n _spi->transfer(MPUREG_MEM_R_W);\n for(int k = 0; k < 16; k++) {\n uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[7][j][k]));\n _spi->transfer((uint8_t) byteToSend);\n }\n _spi->cs_release();\n }\n\n register_write(MPUREG_MEM_START_ADDR,0x80);\n _spi->cs_assert();\n _spi->transfer(MPUREG_MEM_R_W);\n for(int k = 0; k < 9; k++) {\n uint8_t byteToSend = pgm_read_byte((const prog_char *)&(dmpMem[7][8][k]));\n _spi->transfer((uint8_t) byteToSend);\n }\n _spi->cs_release();\n}\n\n// ========= DMP MEMORY ================================\n\nconst uint8_t dmpMem[8][16][16] PROGMEM = {\n {\n {\n 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01\n }\n ,\n {\n 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01\n }\n ,\n {\n 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00\n }\n ,\n {\n 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82\n }\n ,\n {\n 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00\n }\n ,\n {\n 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0\n }\n ,\n {\n 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC\n }\n ,\n {\n 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4\n }\n ,\n {\n 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10\n }\n }\n ,\n {\n {\n 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8\n }\n ,\n {\n 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C\n }\n ,\n {\n 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C\n }\n ,\n {\n 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0\n }\n }\n ,\n {\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n ,\n {\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00\n }\n }\n ,\n {\n {\n 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F\n }\n ,\n {\n 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2\n }\n ,\n {\n 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF\n }\n ,\n {\n 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C\n }\n ,\n {\n 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1\n }\n ,\n {\n 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01\n }\n ,\n {\n 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80\n }\n ,\n {\n 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C\n }\n ,\n {\n 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80\n }\n ,\n {\n 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E\n }\n ,\n {\n 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9\n }\n ,\n {\n 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24\n }\n ,\n {\n 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0\n }\n ,\n {\n 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86\n }\n ,\n {\n 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1\n }\n ,\n {\n 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86\n }\n }\n ,\n {\n {\n 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA\n }\n ,\n {\n 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C\n }\n ,\n {\n 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8\n }\n ,\n {\n 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3\n }\n ,\n {\n 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84\n }\n ,\n {\n 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5\n }\n ,\n {\n 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3\n }\n ,\n {\n 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1\n }\n ,\n {\n 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5\n }\n ,\n {\n 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D\n }\n ,\n {\n 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9\n }\n ,\n {\n 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D\n }\n ,\n {\n 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9\n }\n ,\n {\n 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A\n }\n ,\n {\n 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8\n }\n ,\n {\n 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87\n }\n }\n ,\n {\n {\n 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8\n }\n ,\n {\n 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68\n }\n ,\n {\n 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D\n }\n ,\n {\n 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94\n }\n ,\n {\n 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA\n }\n ,\n {\n 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56\n }\n ,\n {\n 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9\n }\n ,\n {\n 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA\n }\n ,\n {\n 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A\n }\n ,\n {\n 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60\n }\n ,\n {\n 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97\n }\n ,\n {\n 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04\n }\n ,\n {\n 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78\n }\n ,\n {\n 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79\n }\n ,\n {\n 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68\n }\n ,\n {\n 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68\n }\n }\n ,\n {\n {\n 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04\n }\n ,\n {\n 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66\n }\n ,\n {\n 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31\n }\n ,\n {\n 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60\n }\n ,\n {\n 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76\n }\n ,\n {\n 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56\n }\n ,\n {\n 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD\n }\n ,\n {\n 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91\n }\n ,\n {\n 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8\n }\n ,\n {\n 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE\n }\n ,\n {\n 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9\n }\n ,\n {\n 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD\n }\n ,\n {\n 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E\n }\n ,\n {\n 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8\n }\n ,\n {\n 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89\n }\n ,\n {\n 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79\n }\n }\n ,\n {\n {\n 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8\n }\n ,\n {\n 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA\n }\n ,\n {\n 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB\n }\n ,\n {\n 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3\n }\n ,\n {\n 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3\n }\n ,\n {\n 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3\n }\n ,\n {\n 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3\n }\n ,\n {\n 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC\n }\n ,\n {\n 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF\n }\n }\n};\n"},"repo_name":{"kind":"string","value":"andybarry/ardupilot"},"path":{"kind":"string","value":"libraries/AP_InertialSensor/AP_InertialSensor_MPU6000.cpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":60871,"string":"60,871"}}},{"rowIdx":115086010,"cells":{"code":{"kind":"string","value":".\n */\n\n/* NOTE: This file is auto-generated by pdbgen.pl */\n\n#include \"config.h\"\n\n#include \"gimp.h\"\n\n\n/**\n * SECTION: gimpmessage\n * @title: gimpmessage\n * @short_description: Display a dialog box with a message.\n *\n * Display a dialog box with a message.\n **/\n\n\n/**\n * gimp_message:\n * @message: Message to display in the dialog.\n *\n * Displays a dialog box with a message.\n *\n * Displays a dialog box with a message. Useful for status or error\n * reporting. The message must be in UTF-8 encoding.\n *\n * Returns: TRUE on success.\n **/\ngboolean\ngimp_message (const gchar *message)\n{\n GimpParam *return_vals;\n gint nreturn_vals;\n gboolean success = TRUE;\n\n return_vals = gimp_run_procedure (\"gimp-message\",\n &nreturn_vals,\n GIMP_PDB_STRING, message,\n GIMP_PDB_END);\n\n success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;\n\n gimp_destroy_params (return_vals, nreturn_vals);\n\n return success;\n}\n\n/**\n * gimp_message_get_handler:\n *\n * Returns the current state of where warning messages are displayed.\n *\n * This procedure returns the way g_message warnings are displayed.\n * They can be shown in a dialog box or printed on the console where\n * gimp was started.\n *\n * Returns: The current handler type.\n **/\nGimpMessageHandlerType\ngimp_message_get_handler (void)\n{\n GimpParam *return_vals;\n gint nreturn_vals;\n GimpMessageHandlerType handler = 0;\n\n return_vals = gimp_run_procedure (\"gimp-message-get-handler\",\n &nreturn_vals,\n GIMP_PDB_END);\n\n if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)\n handler = return_vals[1].data.d_int32;\n\n gimp_destroy_params (return_vals, nreturn_vals);\n\n return handler;\n}\n\n/**\n * gimp_message_set_handler:\n * @handler: The new handler type.\n *\n * Controls where warning messages are displayed.\n *\n * This procedure controls how g_message warnings are displayed. They\n * can be shown in a dialog box or printed on the console where gimp\n * was started.\n *\n * Returns: TRUE on success.\n **/\ngboolean\ngimp_message_set_handler (GimpMessageHandlerType handler)\n{\n GimpParam *return_vals;\n gint nreturn_vals;\n gboolean success = TRUE;\n\n return_vals = gimp_run_procedure (\"gimp-message-set-handler\",\n &nreturn_vals,\n GIMP_PDB_INT32, handler,\n GIMP_PDB_END);\n\n success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;\n\n gimp_destroy_params (return_vals, nreturn_vals);\n\n return success;\n}\n"},"repo_name":{"kind":"string","value":"brion/gimp"},"path":{"kind":"string","value":"libgimp/gimpmessage_pdb.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":3415,"string":"3,415"}}},{"rowIdx":115086012,"cells":{"code":{"kind":"string","value":"#pragma once\n\n#include \n#include \n#include \n\n#include \"AP_Baro_Backend.h\"\n\n#ifndef HAL_BARO_BMP388_I2C_ADDR\n #define HAL_BARO_BMP388_I2C_ADDR (0x76)\n#endif\n#ifndef HAL_BARO_BMP388_I2C_ADDR2\n #define HAL_BARO_BMP388_I2C_ADDR2 (0x77)\n#endif\n\nclass AP_Baro_BMP388 : public AP_Baro_Backend\n{\npublic:\n AP_Baro_BMP388(AP_Baro &baro, AP_HAL::OwnPtr _dev);\n\n /* AP_Baro public interface: */\n void update() override;\n\n static AP_Baro_Backend *probe(AP_Baro &baro, AP_HAL::OwnPtr _dev);\n\nprivate:\n\n bool init(void);\n void timer(void);\n void update_temperature(uint32_t);\n void update_pressure(uint32_t);\n\n AP_HAL::OwnPtr dev;\n\n uint8_t instance;\n float pressure_sum;\n uint32_t pressure_count;\n float temperature;\n\n // Internal calibration registers\n struct PACKED {\n int16_t nvm_par_p1; // at 0x36\n int16_t nvm_par_p2;\n int8_t nvm_par_p3;\n int8_t nvm_par_p4;\n int16_t nvm_par_p5;\n int16_t nvm_par_p6;\n int8_t nvm_par_p7;\n int8_t nvm_par_p8;\n int16_t nvm_par_p9;\n int8_t nvm_par_p10;\n int8_t nvm_par_p11;\n } calib_p;\n\n struct PACKED {\n uint16_t nvm_par_t1; // at 0x31\n uint16_t nvm_par_t2;\n int8_t nvm_par_t3;\n } calib_t;\n\n // scaled calibration data\n struct {\n float par_t1;\n float par_t2;\n float par_t3;\n float par_p1;\n float par_p2;\n float par_p3;\n float par_p4;\n float par_p5;\n float par_p6;\n float par_p7;\n float par_p8;\n float par_p9;\n float par_p10;\n float par_p11;\n float t_lin;\n } calib;\n\n void scale_calibration_data(void);\n bool read_registers(uint8_t reg, uint8_t *data, uint8_t len);\n};\n"},"repo_name":{"kind":"string","value":"lthall/Leonard_ardupilot"},"path":{"kind":"string","value":"libraries/AP_Baro/AP_Baro_BMP388.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":1869,"string":"1,869"}}},{"rowIdx":115086013,"cells":{"code":{"kind":"string","value":"getName() . ' claps hands!';\n }\n}\n"},"repo_name":{"kind":"string","value":"neos/typo3cr"},"path":{"kind":"string","value":"Tests/Functional/Domain/Fixtures/HappyNode.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"gpl-3.0"},"size":{"kind":"number","value":665,"string":"665"}}},{"rowIdx":115086014,"cells":{"code":{"kind":"string","value":"/*=====================================================================\n \n QGroundControl Open Source Ground Control Station\n \n (c) 2009 - 2014 QGROUNDCONTROL PROJECT \n \n This file is part of the QGROUNDCONTROL project\n \n QGROUNDCONTROL 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 QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see .\n \n ======================================================================*/\n\n/// @file\n/// @brief Command line option parser\n///\n/// @author Don Gagne \n\n#include \"CmdLineOptParser.h\"\n\n#include \n\n/// @brief Implements a simple command line parser which sets booleans to true if the option is found.\nvoid ParseCmdLineOptions(int& argc, ///< count of arguments in argv\n char* argv[], ///< command line arguments\n CmdLineOpt_t* prgOpts, ///< command line options\n size_t cOpts, ///< count of command line options\n bool removeParsedOptions) ///< true: remove parsed option from argc/argv\n{\n // Start with all options off\n for (size_t iOption=0; iOption\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\n\ntemplate \nvoid check ()\n{\n Triangulation triangulation;\n GridGenerator::truncated_cone (triangulation);\n Point p1, p2;\n p1[0] = -1;\n p2[0] = 1;\n static const ConeBoundary boundary (1, 0.5, p1, p2);\n triangulation.set_boundary (0, boundary);\n\n triangulation.refine_global (2);\n\n GridOut().write_gnuplot (triangulation,\n deallog.get_file_stream());\n}\n\n\nint main ()\n{\n std::ofstream logfile(\"output\");\n deallog.attach(logfile);\n deallog.threshold_double(1.e-10);\n\n check<2> ();\n check<3> ();\n}\n\n\n\n"},"repo_name":{"kind":"string","value":"pesser/dealii"},"path":{"kind":"string","value":"tests/bits/cone_01.cc"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"lgpl-2.1"},"size":{"kind":"number","value":1753,"string":"1,753"}}},{"rowIdx":115086016,"cells":{"code":{"kind":"string","value":"//* This file is part of the MOOSE framework\n//* https://www.mooseframework.org\n//*\n//* All rights reserved, see COPYRIGHT for full restrictions\n//* https://github.com/idaholab/moose/blob/master/COPYRIGHT\n//*\n//* Licensed under LGPL 2.1, please see LICENSE for details\n//* https://www.gnu.org/licenses/lgpl-2.1.html\n\n#include \"AreaPostprocessor.h\"\n\nregisterMooseObject(\"MooseApp\", AreaPostprocessor);\n\ndefineLegacyParams(AreaPostprocessor);\n\nInputParameters\nAreaPostprocessor::validParams()\n{\n InputParameters params = SideIntegralPostprocessor::validParams();\n\n params.addClassDescription(\"Computes the \\\"area\\\" or dimension - 1 \\\"volume\\\" of a given \"\n \"boundary or boundaries in your mesh.\");\n return params;\n}\n\nAreaPostprocessor::AreaPostprocessor(const InputParameters & parameters)\n : SideIntegralPostprocessor(parameters)\n{\n}\n\nvoid\nAreaPostprocessor::threadJoin(const UserObject & y)\n{\n const AreaPostprocessor & pps = static_cast(y);\n _integral_value += pps._integral_value;\n}\n\nReal\nAreaPostprocessor::computeQpIntegral()\n{\n return 1.0;\n}\n"},"repo_name":{"kind":"string","value":"nuclear-wizard/moose"},"path":{"kind":"string","value":"framework/src/postprocessors/AreaPostprocessor.C"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"lgpl-2.1"},"size":{"kind":"number","value":1109,"string":"1,109"}}},{"rowIdx":115086017,"cells":{"code":{"kind":"string","value":"# Import the SlideSet base class\nimport math\nfrom ..slidesets import RemarkSlideSet\n\n##\n# A special set of slides for creating cover page and contents\nclass MergeCoverSet(RemarkSlideSet):\n\n ##\n # Extract the valid parameters for this object\n @staticmethod\n def validParams():\n params = RemarkSlideSet.validParams()\n params.addRequiredParam('slide_sets', 'A vector of slideset names to combine into a single contents')\n return params\n\n def __init__(self, name, params, **kwargs):\n RemarkSlideSet.__init__(self, name, params)\n\n # The SlideSetWarehoue\n self.__warehouse = self.getParam('_warehouse')\n\n # Build a list of sets to merge\n self.__merge_list = self.getParam('slide_sets').split()\n\n ##\n # Search through all the slides in the specified slide sets for table of contents content\n def _extractContents(self):\n\n# print len(self.__merge_list)\n# print self.__merge_list\n\n # Count the number of contents entries\n contents = []\n for obj in self.__warehouse.objects:\n if (obj is not self) and (len(self.__merge_list) == 0 or obj.name() in self.__merge_list):\n # print 'TUTORIAL_SUMMARY_COVER:', obj.name()\n pages = obj._extractContents()\n for page in pages:\n contents += page\n\n n = int(self.getParam('contents_items_per_slide'))\n output = [contents[i:i+n] for i in range(0, len(contents),n)]\n return output\n"},"repo_name":{"kind":"string","value":"danielru/moose"},"path":{"kind":"string","value":"python/PresentationBuilder/slidesets/MergeCoverSet.py"},"language":{"kind":"string","value":"Python"},"license":{"kind":"string","value":"lgpl-2.1"},"size":{"kind":"number","value":1395,"string":"1,395"}}},{"rowIdx":115086018,"cells":{"code":{"kind":"string","value":"/**\n * This component provides a grid holding selected items from a second store of potential\n * members. The `store` of this component represents the selected items. The `searchStore`\n * represents the potentially selected items.\n *\n * The default view defined by this class is intended to be easily replaced by deriving a\n * new class and overriding the appropriate methods. For example, the following is a very\n * different view that uses a date range and a data view:\n *\n * Ext.define('App.view.DateBoundSearch', {\n * extend: 'Ext.view.MultiSelectorSearch',\n *\n * makeDockedItems: function () {\n * return {\n * xtype: 'toolbar',\n * items: [{\n * xtype: 'datefield',\n * emptyText: 'Start date...',\n * flex: 1\n * },{\n * xtype: 'datefield',\n * emptyText: 'End date...',\n * flex: 1\n * }]\n * };\n * },\n *\n * makeItems: function () {\n * return [{\n * xtype: 'dataview',\n * itemSelector: '.search-item',\n * selModel: 'rowselection',\n * store: this.store,\n * scrollable: true,\n * tpl:\n * '' +\n * '
' +\n * '' +\n * '
{name}
' +\n * '
' +\n * '
'\n * }];\n * },\n *\n * getSearchStore: function () {\n * return this.items.getAt(0).getStore();\n * },\n *\n * selectRecords: function (records) {\n * var view = this.items.getAt(0);\n * return view.getSelectionModel().select(records);\n * }\n * });\n *\n * **Important**: This class assumes there are two components with specific `reference`\n * names assigned to them. These are `\"searchField\"` and `\"searchGrid\"`. These components\n * are produced by the `makeDockedItems` and `makeItems` method, respectively. When\n * overriding these it is important to remember to place these `reference` values on the\n * appropriate components.\n */\nExt.define('Ext.view.MultiSelectorSearch', {\n extend: 'Ext.panel.Panel',\n\n xtype: 'multiselector-search',\n\n layout: 'fit',\n\n floating: true,\n resizable: true,\n minWidth: 200,\n minHeight: 200,\n border: true,\n\n defaultListenerScope: true,\n referenceHolder: true,\n\n /**\n * @cfg {String} searchText\n * This text is displayed as the \"emptyText\" of the search `textfield`.\n */\n searchText: 'Search...',\n\n initComponent: function () {\n var me = this,\n owner = me.owner,\n items = me.makeItems(),\n i, item, records, store;\n\n me.dockedItems = me.makeDockedItems();\n me.items = items;\n\n store = Ext.data.StoreManager.lookup(me.store);\n\n for (i = items.length; i--; ) {\n if ((item = items[i]).xtype === 'grid') {\n item.store = store;\n item.isSearchGrid = true;\n item.selModel = item.selModel || {\n type: 'checkboxmodel',\n pruneRemoved: false,\n listeners: {\n selectionchange: 'onSelectionChange'\n }\n };\n\n Ext.merge(item, me.grid);\n\n if (!item.columns) {\n item.hideHeaders = true;\n item.columns = [{\n flex: 1,\n dataIndex: me.field\n }];\n }\n\n break;\n }\n }\n\n me.callParent();\n\n records = me.getOwnerStore().getRange();\n if (!owner.convertSelectionRecord.$nullFn) {\n for (i = records.length; i--; ) {\n records[i] = owner.convertSelectionRecord(records[i]);\n }\n }\n\n if (store.isLoading() || (store.loadCount === 0 && !store.getCount())) {\n store.on('load', function() {\n if (!me.isDestroyed) {\n me.selectRecords(records);\n }\n }, null, {single: true});\n } else {\n me.selectRecords(records);\n }\n },\n\n getOwnerStore: function() {\n return this.owner.getStore();\n },\n\n afterShow: function () {\n var searchField = this.lookupReference('searchField');\n\n this.callParent(arguments);\n\n if (searchField) {\n searchField.focus();\n }\n },\n\n /**\n * Returns the store that holds search results. By default this comes from the\n * \"search grid\". If this aspect of the view is changed sufficiently so that the\n * search grid cannot be found, this method should be overridden to return the proper\n * store.\n * @return {Ext.data.Store}\n */\n getSearchStore: function () {\n var searchGrid = this.lookupReference('searchGrid');\n return searchGrid.getStore();\n },\n\n makeDockedItems: function () {\n return [{\n xtype: 'textfield',\n reference: 'searchField',\n dock: 'top',\n hideFieldLabel: true,\n emptyText: this.searchText,\n triggers: {\n clear: {\n cls: Ext.baseCSSPrefix + 'form-clear-trigger',\n handler: 'onClearSearch',\n hidden: true\n }\n },\n listeners: {\n change: 'onSearchChange',\n buffer: 300\n }\n }];\n },\n\n makeItems: function () {\n return [{\n xtype: 'grid',\n reference: 'searchGrid',\n trailingBufferZone: 2,\n leadingBufferZone: 2,\n viewConfig: {\n deferEmptyText: false,\n emptyText: 'No results.'\n }\n }];\n },\n\n selectRecords: function (records) {\n var searchGrid = this.lookupReference('searchGrid');\n return searchGrid.getSelectionModel().select(records);\n },\n\n deselectRecords: function(records) {\n var searchGrid = this.lookupReference('searchGrid');\n return searchGrid.getSelectionModel().deselect(records);\n },\n\n search: function (text) {\n var me = this,\n filter = me.searchFilter,\n filters = me.getSearchStore().getFilters();\n\n if (text) {\n filters.beginUpdate();\n\n if (filter) {\n filter.setValue(text);\n } else {\n me.searchFilter = filter = new Ext.util.Filter({\n id: 'search',\n property: me.field,\n value: text\n });\n }\n\n filters.add(filter);\n\n filters.endUpdate();\n } else if (filter) {\n filters.remove(filter);\n }\n },\n\n privates: {\n onClearSearch: function () {\n var searchField = this.lookupReference('searchField');\n searchField.setValue(null);\n searchField.focus();\n },\n\n onSearchChange: function (searchField) {\n var value = searchField.getValue(),\n trigger = searchField.getTrigger('clear');\n\n trigger.setHidden(!value);\n this.search(value);\n },\n\n onSelectionChange: function (selModel, selection) {\n var owner = this.owner,\n store = owner.getStore(),\n data = store.data,\n remove = 0,\n map = {},\n add, i, id, record;\n\n for (i = selection.length; i--; ) {\n record = selection[i];\n id = record.id;\n map[id] = record;\n\n if (!data.containsKey(id)) {\n (add || (add = [])).push(owner.convertSearchRecord(record));\n }\n }\n\n for (i = data.length; i--; ) {\n record = data.getAt(i);\n if (!map[record.id]) {\n (remove || (remove = [])).push(record);\n }\n }\n\n if (add || remove) {\n data.splice(data.length, remove, add);\n }\n }\n }\n});\n"},"repo_name":{"kind":"string","value":"department-of-veterans-affairs/ChartReview"},"path":{"kind":"string","value":"web-app/js/ext-5.1.0/src/view/MultiSelectorSearch.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":8477,"string":"8,477"}}},{"rowIdx":115086019,"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 assert = require('assert');\n\nvar fs = require('fs');\nvar path = require('path');\nvar util = require('util');\nvar sinon = require('sinon');\nvar url = require('url');\n\nvar request = require('request');\n\n// Test includes\nvar testutil = require('../../util/util');\nvar blobtestutil = require('../../framework/blob-test-utils');\n\n// Lib includes\nvar common = require('azure-common');\nvar storage = testutil.libRequire('services/legacyStorage');\n\nvar azureutil = common.util;\nvar azure = testutil.libRequire('azure');\nvar WebResource = common.WebResource;\n\nvar SharedAccessSignature = storage.SharedAccessSignature;\nvar BlobService = storage.BlobService;\nvar ServiceClient = common.ServiceClient;\nvar ExponentialRetryPolicyFilter = common.ExponentialRetryPolicyFilter;\nvar Constants = common.Constants;\nvar BlobConstants = Constants.BlobConstants;\nvar HttpConstants = Constants.HttpConstants;\nvar ServiceClientConstants = common.ServiceClientConstants;\nvar QueryStringConstants = Constants.QueryStringConstants;\n\nvar containerNames = [];\nvar containerNamesPrefix = 'cont';\n\nvar blobNames = [];\nvar blobNamesPrefix = 'blob';\n\nvar testPrefix = 'blobservice-tests';\n\nvar blobService;\nvar suiteUtil;\n\ndescribe('BlobService', function () {\n before(function (done) {\n blobService = storage.createBlobService()\n .withFilter(new common.ExponentialRetryPolicyFilter());\n\n suiteUtil = blobtestutil.createBlobTestUtils(blobService, testPrefix);\n suiteUtil.setupSuite(done);\n });\n\n after(function (done) {\n suiteUtil.teardownSuite(done);\n });\n\n beforeEach(function (done) {\n suiteUtil.setupTest(done);\n });\n\n afterEach(function (done) {\n suiteUtil.teardownTest(done);\n });\n\n describe('createContainer', function () {\n it('should detect incorrect container names', function (done) {\n assert.throws(function () { blobService.createContainer(null, function () { }); },\n BlobService.incorrectContainerNameErr);\n\n assert.throws(function () { blobService.createContainer('', function () { }); },\n BlobService.incorrectContainerNameErr);\n\n assert.throws(function () { blobService.createContainer('as', function () { }); },\n BlobService.incorrectContainerNameFormatErr);\n\n assert.throws(function () { blobService.createContainer('a--s', function () { }); },\n BlobService.incorrectContainerNameFormatErr);\n\n assert.throws(function () { blobService.createContainer('cont-', function () { }); },\n BlobService.incorrectContainerNameFormatErr);\n\n assert.throws(function () { blobService.createContainer('conTain', function () { }); },\n BlobService.incorrectContainerNameFormatErr);\n\n done();\n });\n\n it('should work', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n\n blobService.createContainer(containerName, function (createError, container1, createContainerResponse) {\n assert.equal(createError, null);\n assert.notEqual(container1, null);\n if (container1) {\n assert.notEqual(container1.name, null);\n assert.notEqual(container1.etag, null);\n assert.notEqual(container1.lastModified, null);\n }\n\n assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created);\n\n // creating again will result in a duplicate error\n blobService.createContainer(containerName, function (createError2, container2) {\n assert.equal(createError2.code, Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS);\n assert.equal(container2, null);\n\n done();\n });\n });\n });\n });\n\n describe('blobExists', function () {\n it('should detect incorrect blob names', function (done) {\n assert.throws(function () { blobService.blobExists('container', null, function () { }); },\n BlobService.incorrectBlobNameFormatErr);\n\n assert.throws(function () { blobService.blobExists('container', '', function () { }); },\n BlobService.incorrectBlobNameFormatErr);\n\n done();\n });\n });\n\n describe('getServiceProperties', function () {\n it('should get blob service properties', function (done) {\n blobService.getServiceProperties(function (error, serviceProperties) {\n assert.equal(error, null);\n assert.notEqual(serviceProperties, null);\n\n if (serviceProperties) {\n assert.notEqual(serviceProperties.Logging, null);\n if (serviceProperties.Logging) {\n assert.notEqual(serviceProperties.Logging.RetentionPolicy);\n assert.notEqual(serviceProperties.Logging.Version);\n }\n\n if (serviceProperties.Metrics) {\n assert.notEqual(serviceProperties.Metrics, null);\n assert.notEqual(serviceProperties.Metrics.RetentionPolicy);\n assert.notEqual(serviceProperties.Metrics.Version);\n }\n }\n\n done();\n });\n });\n });\n\n describe('getServiceProperties', function () {\n it('should set blob service properties', function (done) {\n blobService.getServiceProperties(function (error, serviceProperties) {\n assert.equal(error, null);\n\n serviceProperties.DefaultServiceVersion = '2009-09-19';\n serviceProperties.Logging.Read = true;\n blobService.setServiceProperties(serviceProperties, function (error2) {\n assert.equal(error2, null);\n\n blobService.getServiceProperties(function (error3, serviceProperties2) {\n assert.equal(error3, null);\n assert.equal(serviceProperties2.DefaultServiceVersion, '2009-09-19');\n assert.equal(serviceProperties2.Logging.Read, true);\n\n done();\n });\n });\n });\n });\n });\n\n describe('listContainers', function () {\n it('should work', function (done) {\n var containerName1 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var metadata1 = {\n color: 'orange',\n containernumber: '01',\n somemetadataname: 'SomeMetadataValue'\n };\n\n var containerName2 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var metadata2 = {\n color: 'pink',\n containernumber: '02',\n somemetadataname: 'SomeMetadataValue'\n };\n\n var containerName3 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var metadata3 = {\n color: 'brown',\n containernumber: '03',\n somemetadataname: 'SomeMetadataValue'\n };\n\n var containerName4 = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var metadata4 = {\n color: 'blue',\n containernumber: '04',\n somemetadataname: 'SomeMetadataValue'\n };\n\n var validateContainers = function (containers, entries) {\n containers.forEach(function (container) {\n if (container.name == containerName1) {\n assert.equal(container.metadata.color, metadata1.color);\n assert.equal(container.metadata.containernumber, metadata1.containernumber);\n assert.equal(container.metadata.somemetadataname, metadata1.somemetadataname);\n entries.push(container.name);\n }\n else if (container.name == containerName2) {\n assert.equal(container.metadata.color, metadata2.color);\n assert.equal(container.metadata.containernumber, metadata2.containernumber);\n assert.equal(container.metadata.somemetadataname, metadata2.somemetadataname);\n entries.push(container.name);\n }\n else if (container.name == containerName3) {\n assert.equal(container.metadata.color, metadata3.color);\n assert.equal(container.metadata.containernumber, metadata3.containernumber);\n assert.equal(container.metadata.somemetadataname, metadata3.somemetadataname);\n entries.push(container.name);\n }\n else if (container.name == containerName4) {\n assert.equal(container.metadata.color, metadata4.color);\n assert.equal(container.metadata.containernumber, metadata4.containernumber);\n assert.equal(container.metadata.somemetadataname, metadata4.somemetadataname);\n entries.push(container.name);\n }\n });\n\n return entries;\n };\n\n blobService.createContainer(containerName1, { metadata: metadata1 }, function (createError1, createContainer1, createResponse1) {\n assert.equal(createError1, null);\n assert.notEqual(createContainer1, null);\n assert.ok(createResponse1.isSuccessful);\n\n blobService.createContainer(containerName2, { metadata: metadata2 }, function (createError2, createContainer2, createResponse2) {\n assert.equal(createError2, null);\n assert.notEqual(createContainer2, null);\n assert.ok(createResponse2.isSuccessful);\n\n blobService.createContainer(containerName3, { metadata: metadata3 }, function (createError3, createContainer3, createResponse3) {\n assert.equal(createError3, null);\n assert.notEqual(createContainer3, null);\n assert.ok(createResponse3.isSuccessful);\n\n blobService.createContainer(containerName4, { metadata: metadata4 }, function (createError4, createContainer4, createResponse4) {\n assert.equal(createError4, null);\n assert.notEqual(createContainer4, null);\n assert.ok(createResponse4.isSuccessful);\n\n var options = {\n 'maxresults': 3,\n 'include': 'metadata'\n };\n\n blobService.listContainers(options, function (listError, containers, containersContinuation, listResponse) {\n assert.equal(listError, null);\n assert.ok(listResponse.isSuccessful);\n assert.equal(containers.length, 3);\n\n var entries = validateContainers(containers, []);\n\n assert.equal(containersContinuation.hasNextPage(), true);\n containersContinuation.getNextPage(function (listErrorContinuation, containers2) {\n assert.equal(listErrorContinuation, null);\n assert.ok(listResponse.isSuccessful);\n validateContainers(containers2, entries);\n assert.equal(entries.length, 4);\n\n done();\n });\n });\n });\n });\n });\n });\n });\n\n it('should work with optional parameters', function (done) {\n blobService.listContainers(null, function (err) {\n assert.equal(err, null);\n done();\n });\n });\n\n it('should work with prefix parameter', function (done) {\n blobService.listContainers({ prefix : '中文' }, function (err) {\n assert.equal(err, null);\n done();\n });\n });\n });\n\n describe('createContainerIfNotExists', function() {\n it('should create a container if not exists', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n\n blobService.createContainer(containerName, function (createError, container1, createContainerResponse) {\n assert.equal(createError, null);\n assert.notEqual(container1, null);\n if (container1) {\n assert.notEqual(container1.name, null);\n assert.notEqual(container1.etag, null);\n assert.notEqual(container1.lastModified, null);\n }\n\n assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created);\n\n // creating again will result in a duplicate error\n blobService.createContainerIfNotExists(containerName, function (createError2, isCreated) {\n assert.equal(createError2, null);\n assert.equal(isCreated, false);\n\n done();\n });\n });\n });\n\n it('should throw if called with a callback', function (done) {\n assert.throws(function () { blobService.createContainerIfNotExists('name'); },\n Error\n );\n\n done();\n });\n });\n\n describe('container', function () {\n var containerName;\n var metadata;\n\n beforeEach(function (done) {\n containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n metadata = { color: 'blue' };\n\n blobService.createContainer(containerName, { metadata: metadata }, done);\n });\n\n describe('getContainerProperties', function () {\n it('should work', function (done) {\n blobService.getContainerProperties(containerName, function (getError, container2, getResponse) {\n assert.equal(getError, null);\n assert.notEqual(container2, null);\n if (container2) {\n assert.equal('unlocked', container2.leaseStatus);\n assert.equal('available', container2.leaseState);\n assert.equal(null, container2.leaseDuration);\n assert.notEqual(null, container2.requestId);\n assert.equal(container2.metadata.color, metadata.color);\n }\n\n assert.notEqual(getResponse, null);\n assert.equal(getResponse.isSuccessful, true);\n\n done();\n });\n });\n });\n\n describe('setContainerMetadata', function () {\n it('should work', function (done) {\n var metadata = { 'class': 'test' };\n blobService.setContainerMetadata(containerName, metadata, function (setMetadataError, setMetadataResponse) {\n assert.equal(setMetadataError, null);\n assert.ok(setMetadataResponse.isSuccessful);\n\n blobService.getContainerMetadata(containerName, function (getMetadataError, containerMetadata, getMetadataResponse) {\n assert.equal(getMetadataError, null);\n assert.notEqual(containerMetadata, null);\n assert.notEqual(containerMetadata.metadata, null);\n if (containerMetadata.metadata) {\n assert.equal(containerMetadata.metadata.class, 'test');\n }\n\n assert.ok(getMetadataResponse.isSuccessful);\n\n done();\n });\n });\n });\n });\n\n describe('getContainerAcl', function () {\n it('should work', function (done) {\n blobService.getContainerAcl(containerName, function (containerAclError, containerBlob, containerAclResponse) {\n assert.equal(containerAclError, null);\n assert.notEqual(containerBlob, null);\n if (containerBlob) {\n assert.equal(containerBlob.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.OFF);\n }\n\n assert.equal(containerAclResponse.isSuccessful, true);\n\n done();\n });\n });\n });\n\n describe('setContainerAcl', function () {\n it('should work', function (done) {\n blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, function (setAclError, setAclContainer1, setResponse1) {\n assert.equal(setAclError, null);\n assert.notEqual(setAclContainer1, null);\n assert.ok(setResponse1.isSuccessful);\n\n blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) {\n assert.equal(getAclError, null);\n assert.notEqual(getAclContainer1, null);\n if (getAclContainer1) {\n assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB);\n }\n\n assert.ok(getResponse1.isSuccessful);\n\n blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) {\n assert.equal(setAclError2, null);\n assert.notEqual(setAclContainer2, null);\n assert.ok(setResponse2.isSuccessful);\n\n setTimeout(function () {\n blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) {\n assert.equal(getAclError2, null);\n assert.notEqual(getAclContainer2, null);\n if (getAclContainer2) {\n assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER);\n }\n\n assert.ok(getResponse3.isSuccessful);\n\n done();\n });\n }, (suiteUtil.isMocked && !suiteUtil.isRecording) ? 0 : 5000);\n });\n });\n });\n });\n\n it('should work with policies', function (done) {\n var readWriteStartDate = new Date(Date.UTC(2012, 10, 10));\n var readWriteExpiryDate = new Date(readWriteStartDate);\n readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10);\n readWriteExpiryDate.setMilliseconds(999);\n\n var readWriteSharedAccessPolicy = {\n Id: 'readwrite',\n AccessPolicy: {\n Start: readWriteStartDate,\n Expiry: readWriteExpiryDate,\n Permissions: 'rw'\n }\n };\n\n var readSharedAccessPolicy = {\n Id: 'read',\n AccessPolicy: {\n Expiry: readWriteStartDate,\n Permissions: 'r'\n }\n };\n\n var options = {};\n options.signedIdentifiers = [readWriteSharedAccessPolicy, readSharedAccessPolicy];\n\n blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.BLOB, options, function (setAclError, setAclContainer1, setResponse1) {\n assert.equal(setAclError, null);\n assert.notEqual(setAclContainer1, null);\n assert.ok(setResponse1.isSuccessful);\n\n blobService.getContainerAcl(containerName, function (getAclError, getAclContainer1, getResponse1) {\n assert.equal(getAclError, null);\n assert.notEqual(getAclContainer1, null);\n if (getAclContainer1) {\n assert.equal(getAclContainer1.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.BLOB);\n assert.equal(getAclContainer1.signedIdentifiers[0].AccessPolicy.Expiry.getTime(), readWriteExpiryDate.getTime());\n }\n\n assert.ok(getResponse1.isSuccessful);\n\n blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.CONTAINER, function (setAclError2, setAclContainer2, setResponse2) {\n assert.equal(setAclError2, null);\n assert.notEqual(setAclContainer2, null);\n assert.ok(setResponse2.isSuccessful);\n\n blobService.getContainerAcl(containerName, function (getAclError2, getAclContainer2, getResponse3) {\n assert.equal(getAclError2, null);\n assert.notEqual(getAclContainer2, null);\n if (getAclContainer2) {\n assert.equal(getAclContainer2.publicAccessLevel, BlobConstants.BlobContainerPublicAccessType.CONTAINER);\n }\n\n assert.ok(getResponse3.isSuccessful);\n\n done();\n });\n });\n });\n });\n });\n\n it('should work with signed identifiers', function (done) {\n var options = {};\n options.signedIdentifiers = [\n { Id: 'id1',\n AccessPolicy: {\n Start: '2009-10-10T00:00:00.123Z',\n Expiry: '2009-10-11T00:00:00.456Z',\n Permissions: 'r'\n }\n },\n { Id: 'id2',\n AccessPolicy: {\n Start: '2009-11-10T00:00:00.006Z',\n Expiry: '2009-11-11T00:00:00.4Z',\n Permissions: 'w'\n }\n }];\n\n blobService.setContainerAcl(containerName, BlobConstants.BlobContainerPublicAccessType.OFF, options, function (setAclError, setAclContainer, setAclResponse) {\n assert.equal(setAclError, null);\n assert.notEqual(setAclContainer, null);\n assert.ok(setAclResponse.isSuccessful);\n\n blobService.getContainerAcl(containerName, function (getAclError, containerAcl, getAclResponse) {\n assert.equal(getAclError, null);\n assert.notEqual(containerAcl, null);\n assert.notEqual(getAclResponse, null);\n\n if (getAclResponse) {\n assert.equal(getAclResponse.isSuccessful, true);\n }\n\n var entries = 0;\n if (containerAcl) {\n if (containerAcl.signedIdentifiers) {\n containerAcl.signedIdentifiers.forEach(function (identifier) {\n if (identifier.Id === 'id1') {\n assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-10-10T00:00:00.123Z').getTime());\n assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-10-11T00:00:00.456Z').getTime());\n assert.equal(identifier.AccessPolicy.Permission, 'r');\n entries += 1;\n }\n else if (identifier.Id === 'id2') {\n assert.equal(identifier.AccessPolicy.Start.getTime(), new Date('2009-11-10T00:00:00.006Z').getTime());\n assert.equal(identifier.AccessPolicy.Start.getMilliseconds(), 6);\n assert.equal(identifier.AccessPolicy.Expiry.getTime(), new Date('2009-11-11T00:00:00.4Z').getTime());\n assert.equal(identifier.AccessPolicy.Expiry.getMilliseconds(), 400);\n assert.equal(identifier.AccessPolicy.Permission, 'w');\n entries += 2;\n }\n });\n }\n }\n\n assert.equal(entries, 3);\n\n done();\n });\n });\n });\n });\n\n describe('createBlockBlobFromText', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText = 'Hello World';\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {\n assert.equal(uploadError, null);\n assert.ok(uploadResponse.isSuccessful);\n\n blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {\n assert.equal(downloadErr, null);\n assert.equal(blobTextResponse, blobText);\n\n done();\n });\n });\n });\n });\n\n describe('createBlobSnapshot', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText = 'Hello World';\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, putResponse) {\n assert.equal(uploadError, null);\n assert.notEqual(putResponse, null);\n if (putResponse) {\n assert.ok(putResponse.isSuccessful);\n }\n\n blobService.createBlobSnapshot(containerName, blobName, function (snapshotError, snapshotId, snapshotResponse) {\n assert.equal(snapshotError, null);\n assert.notEqual(snapshotResponse, null);\n assert.notEqual(snapshotId, null);\n\n if (snapshotResponse) {\n assert.ok(snapshotResponse.isSuccessful);\n }\n\n blobService.getBlobToText(containerName, blobName, function (getError, content, blockBlob, getResponse) {\n assert.equal(getError, null);\n assert.notEqual(blockBlob, null);\n assert.notEqual(getResponse, null);\n if (getResponse) {\n assert.ok(getResponse.isSuccessful);\n }\n\n assert.equal(blobText, content);\n done();\n });\n });\n });\n });\n });\n\n describe('acquireLease', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText = 'hello';\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {\n assert.equal(uploadError, null);\n assert.notEqual(blob, null);\n assert.ok(uploadResponse.isSuccessful);\n\n // Acquire a lease\n blobService.acquireLease(containerName, blobName, function (leaseBlobError, lease, leaseBlobResponse) {\n assert.equal(leaseBlobError, null);\n assert.notEqual(lease, null);\n if (lease) {\n assert.ok(lease.id);\n }\n\n assert.notEqual(leaseBlobResponse, null);\n if (leaseBlobResponse) {\n assert.ok(leaseBlobResponse.isSuccessful);\n }\n\n // Second lease should not be possible\n blobService.acquireLease(containerName, blobName, function (secondLeaseBlobError, secondLease, secondLeaseBlobResponse) {\n assert.equal(secondLeaseBlobError.code, 'LeaseAlreadyPresent');\n assert.equal(secondLease, null);\n assert.equal(secondLeaseBlobResponse.isSuccessful, false);\n\n // Delete should not be possible\n blobService.deleteBlob(containerName, blobName, function (deleteError, deleted, deleteResponse) {\n assert.equal(deleteError.code, 'LeaseIdMissing');\n assert.equal(deleteResponse.isSuccessful, false);\n\n done();\n });\n });\n });\n });\n });\n });\n\n describe('getBlobProperties', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var metadata = {\n color: 'blue'\n };\n\n blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) {\n assert.equal(blobErr, null);\n\n blobService.getBlobProperties(containerName, blobName, function (getErr, blob) {\n assert.equal(getErr, null);\n\n assert.notEqual(blob, null);\n\n if (blob) {\n assert.notEqual(blob.metadata, null);\n if (blob.metadata) {\n assert.equal(blob.metadata.color, metadata.color);\n }\n }\n\n done();\n });\n });\n });\n });\n\n describe('setBlobProperties', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var text = 'hello';\n\n blobService.createBlockBlobFromText(containerName, blobName, text, function (blobErr) {\n assert.equal(blobErr, null);\n\n var options = {};\n options.contentType = 'text';\n options.contentEncoding = 'utf8';\n options.contentLanguage = 'pt';\n options.cacheControl = 'true';\n\n blobService.setBlobProperties(containerName, blobName, options, function (setErr) {\n assert.equal(setErr, null);\n\n blobService.getBlobProperties(containerName, blobName, function (getErr, blob) {\n assert.equal(getErr, null);\n\n assert.notEqual(blob, null);\n if (blob) {\n assert.equal(blob.contentLength, text.length);\n assert.equal(blob.contentType, options.contentType);\n assert.equal(blob.contentEncoding, options.contentEncoding);\n assert.equal(blob.contentLanguage, options.contentLanguage);\n assert.equal(blob.cacheControl, options.cacheControl);\n }\n\n done();\n });\n });\n });\n });\n });\n\n describe('getBlobMetadata', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var metadata = { color: 'blue' };\n\n blobService.createBlockBlobFromText(containerName, blobName, 'hello', { metadata: metadata }, function (blobErr) {\n assert.equal(blobErr, null);\n\n blobService.getBlobMetadata(containerName, blobName, function (getErr, blob) {\n assert.equal(getErr, null);\n\n assert.notEqual(blob, null);\n if (blob) {\n assert.notEqual(blob.metadata, null);\n if (blob.metadata) {\n assert.equal(blob.metadata.color, metadata.color);\n }\n }\n\n done();\n });\n });\n });\n });\n\n describe('pageBlob', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var data1 = 'Hello, World!' + repeat(' ', 1024 - 13);\n var data2 = 'Hello, World!' + repeat(' ', 512 - 13);\n\n // Create the empty page blob\n blobService.createPageBlob(containerName, blobName, 1024, function (err) {\n assert.equal(err, null);\n\n // Upload all data\n blobService.createBlobPagesFromText(containerName, blobName, data1, 0, 1023, function (err2) {\n assert.equal(err2, null);\n\n // Verify contents\n blobService.getBlobToText(containerName, blobName, function (err3, content1) {\n assert.equal(err3, null);\n assert.equal(content1, data1);\n\n // Clear the page blob\n blobService.clearBlobPages(containerName, blobName, 0, 1023, function (err4) {\n assert.equal(err4);\n\n // Upload other data in 2 pages\n blobService.createBlobPagesFromText(containerName, blobName, data2, 0, 511, function (err5) {\n assert.equal(err5, null);\n\n blobService.createBlobPagesFromText(containerName, blobName, data2, 512, 1023, function (err6) {\n assert.equal(err6, null);\n\n blobService.getBlobToText(containerName, blobName, function (err7, content2) {\n assert.equal(err7, null);\n assert.equal(data2 + data2, content2);\n\n done();\n });\n });\n });\n });\n });\n });\n });\n });\n });\n\n describe('createBlockBlobFromText', function () {\n it('should work with access condition', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText = 'hello';\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error2) {\n assert.equal(error2, null);\n\n blobService.getBlobProperties(containerName, blobName, function (error4, blobProperties) {\n assert.equal(error4, null);\n\n var options = { accessConditions: { 'if-none-match': blobProperties.etag} };\n blobService.createBlockBlobFromText(containerName, blobName, blobText, options, function (error3) {\n assert.notEqual(error3, null);\n assert.equal(error3.code, Constants.StorageErrorCodeStrings.CONDITION_NOT_MET);\n\n done();\n });\n });\n });\n });\n\n it('should work for small size from file', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' a';\n var blobText = 'Hello World';\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blobResponse, uploadResponse) {\n assert.equal(uploadError, null);\n assert.notEqual(blobResponse, null);\n assert.ok(uploadResponse.isSuccessful);\n\n blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {\n assert.equal(downloadErr, null);\n assert.equal(blobTextResponse, blobText);\n\n done();\n });\n });\n });\n });\n\n describe('getBlobRange', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var data1 = 'Hello, World!';\n\n // Create the empty page blob\n blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) {\n assert.equal(err, null);\n\n blobService.getBlobToText(containerName, blobName, { rangeStart: 2, rangeEnd: 3 }, function (err3, content1) {\n assert.equal(err3, null);\n\n // get the double ll's in the hello\n assert.equal(content1, 'll');\n\n done();\n });\n });\n });\n });\n\n describe('getBlobRangeOpenEnded', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var data1 = 'Hello, World!';\n\n // Create the empty page blob\n blobService.createBlockBlobFromText(containerName, blobName, data1, function (err) {\n assert.equal(err, null);\n\n blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1) {\n assert.equal(err3, null);\n\n // get the last bytes from the message\n assert.equal(content1, 'llo, World!');\n\n done();\n });\n });\n });\n });\n\n describe('setBlobMime', function () {\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileNameSource = testutil.generateId('file') + '.bmp'; // fake bmp file with text...\n var blobText = 'Hello World!';\n\n fs.writeFile(fileNameSource, blobText, function () {\n\n // Create the empty page blob\n var blobOptions = {blockIdPrefix : 'blockId' };\n blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (err) {\n assert.equal(err, null);\n\n blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) {\n assert.equal(err3, null);\n\n // get the last bytes from the message\n assert.equal(content1, 'llo World!');\n assert.ok(blob.contentType === 'image/bmp' || blob.contentType === 'image/x-ms-bmp');\n\n fs.unlink(fileNameSource, function () {\n done();\n });\n });\n });\n });\n });\n\n it('should work with skip', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text...\n var blobText = 'Hello World!';\n\n fs.writeFile(fileNameSource, blobText, function () {\n // Create the empty page blob\n blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, { contentType: null, contentTypeHeader: null, blockIdPrefix : 'blockId' }, function (err) {\n assert.equal(err, null);\n\n blobService.getBlobToText(containerName, blobName, { rangeStart: 2 }, function (err3, content1, blob) {\n assert.equal(err3, null);\n\n // get the last bytes from the message\n assert.equal(content1, 'llo World!');\n assert.equal(blob.contentType, 'application/octet-stream');\n\n fs.unlink(fileNameSource, function () {\n done();\n });\n });\n });\n });\n });\n });\n });\n\n describe('copyBlob', function () {\n it('should work', function (done) {\n var sourceContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var targetContainerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n\n var sourceBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var targetBlobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var blobText = 'hi there';\n\n blobService.createContainer(sourceContainerName, function (createErr1) {\n assert.equal(createErr1, null);\n\n blobService.createContainer(targetContainerName, function (createErr2) {\n assert.equal(createErr2, null);\n\n blobService.createBlockBlobFromText(sourceContainerName, sourceBlobName, blobText, function (uploadErr) {\n assert.equal(uploadErr, null);\n\n blobService.copyBlob(blobService.getBlobUrl(sourceContainerName, sourceBlobName), targetContainerName, targetBlobName, function (copyErr) {\n assert.equal(copyErr, null);\n\n blobService.getBlobToText(targetContainerName, targetBlobName, function (downloadErr, text) {\n assert.equal(downloadErr, null);\n assert.equal(text, blobText);\n\n done();\n });\n });\n });\n });\n });\n });\n });\n\n describe('listBlobs', function () {\n var containerName;\n\n beforeEach(function (done) {\n containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n\n blobService.createContainer(containerName, done);\n });\n\n it('should work', function (done) {\n var blobName1 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobName2 = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText1 = 'hello1';\n var blobText2 = 'hello2';\n\n // Test listing 0 blobs\n blobService.listBlobs(containerName, function (listErrNoBlobs, listNoBlobs) {\n assert.equal(listErrNoBlobs, null);\n assert.notEqual(listNoBlobs, null);\n if (listNoBlobs) {\n assert.equal(listNoBlobs.length, 0);\n }\n\n blobService.createBlockBlobFromText(containerName, blobName1, blobText1, function (blobErr1) {\n assert.equal(blobErr1, null);\n\n // Test listing 1 blob\n blobService.listBlobs(containerName, function (listErr, listBlobs) {\n assert.equal(listErr, null);\n assert.notEqual(listBlobs, null);\n assert.equal(listBlobs.length, 1);\n\n blobService.createBlockBlobFromText(containerName, blobName2, blobText2, function (blobErr2) {\n assert.equal(blobErr2, null);\n\n // Test listing multiple blobs\n blobService.listBlobs(containerName, function (listErr2, listBlobs2) {\n assert.equal(listErr2, null);\n assert.notEqual(listBlobs2, null);\n if (listBlobs2) {\n assert.equal(listBlobs2.length, 2);\n\n var entries = 0;\n listBlobs2.forEach(function (blob) {\n if (blob.name === blobName1) {\n entries += 1;\n }\n else if (blob.name === blobName2) {\n entries += 2;\n }\n });\n\n assert.equal(entries, 3);\n }\n\n blobService.createBlobSnapshot(containerName, blobName1, function (snapErr) {\n assert.equal(snapErr, null);\n\n // Test listing without requesting snapshots\n blobService.listBlobs(containerName, function (listErr3, listBlobs3) {\n assert.equal(listErr3, null);\n assert.notEqual(listBlobs3, null);\n if (listBlobs3) {\n assert.equal(listBlobs3.length, 2);\n }\n\n // Test listing including snapshots\n blobService.listBlobs(containerName, { include: BlobConstants.BlobListingDetails.SNAPSHOTS }, function (listErr4, listBlobs4) {\n assert.equal(listErr4, null);\n assert.notEqual(listBlobs4, null);\n\n if (listBlobs3) {\n assert.equal(listBlobs4.length, 3);\n }\n\n done();\n });\n });\n });\n });\n });\n });\n });\n });\n });\n });\n\n describe('getPageRegions', function () {\n var containerName;\n\n beforeEach(function (done) {\n containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n\n blobService.createContainer(containerName, done);\n });\n\n it('should work', function (done) {\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var data = 'Hello, World!' + repeat(' ', 512 - 13);\n\n // Upload contents in 2 parts\n blobService.createPageBlob(containerName, blobName, 1024 * 1024 * 1024, function (err) {\n assert.equal(err, null);\n\n // Upload all data\n blobService.createBlobPagesFromText(containerName, blobName, data, 0, 511, function (err2) {\n assert.equal(err2, null);\n\n // Only one region present\n blobService.listBlobRegions(containerName, blobName, 0, null, function (error, regions) {\n assert.equal(error, null);\n assert.notEqual(regions, null);\n if (regions) {\n assert.equal(regions.length, 1);\n\n var entries = 0;\n regions.forEach(function (region) {\n if (region.start === 0) {\n assert.equal(region.end, 511);\n entries += 1;\n }\n });\n\n assert.equal(entries, 1);\n }\n\n blobService.createBlobPagesFromText(containerName, blobName, data, 1048576, 1049087, null, function (err3) {\n assert.equal(err3, null);\n\n // Get page regions\n blobService.listBlobRegions(containerName, blobName, 0, null, function (error5, regions) {\n assert.equal(error5, null);\n assert.notEqual(regions, null);\n if (regions) {\n assert.equal(regions.length, 2);\n\n var entries = 0;\n regions.forEach(function (region) {\n if (region.start === 0) {\n assert.equal(region.end, 511);\n entries += 1;\n }\n else if (region.start === 1048576) {\n assert.equal(region.end, 1049087);\n entries += 2;\n }\n });\n\n assert.equal(entries, 3);\n }\n\n done();\n });\n });\n });\n });\n });\n });\n });\n\n it('CreateBlobWithBars', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = 'blobs/' + testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var blobText = 'Hello World!';\n\n blobService.createContainer(containerName, function (createError) {\n assert.equal(createError, null);\n\n // Create the empty page blob\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) {\n assert.equal(err, null);\n\n blobService.getBlobProperties(containerName, blobName, function (error, properties) {\n assert.equal(error, null);\n assert.equal(properties.container, containerName);\n assert.equal(properties.blob, blobName);\n\n done();\n });\n });\n });\n });\n\n it('works with files without specifying content type', function (done) {\n // This test ensures that blocks can be created from files correctly\n // and was created to ensure that the request module does not magically add\n // a content type to the request when the user did not specify one.\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileName= testutil.generateId('prefix') + '.txt';\n var blobText = 'Hello World!';\n\n try { fs.unlinkSync(fileName); } catch (e) {}\n fs.writeFileSync(fileName, blobText);\n\n var stat = fs.statSync(fileName);\n\n blobService.createContainer(containerName, function (createErr1) {\n assert.equal(createErr1, null);\n\n blobService.createBlobBlockFromStream('test', containerName, blobName, fs.createReadStream(fileName), stat.size, function (error) {\n try { fs.unlinkSync(fileName); } catch (e) {}\n\n assert.equal(error, null);\n\n done();\n });\n });\n });\n\n it('CommitBlockList', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n blobService.createContainer(containerName, function (error) {\n assert.equal(error, null);\n\n blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) {\n assert.equal(error2, null);\n\n blobService.createBlobBlockFromText('id2', containerName, blobName, 'id2', function (error3) {\n assert.equal(error3, null);\n\n var blockList = {\n LatestBlocks: ['id1'],\n UncommittedBlocks: ['id2']\n };\n\n blobService.commitBlobBlocks(containerName, blobName, blockList, function (error4) {\n assert.equal(error4, null);\n\n blobService.listBlobBlocks(containerName, blobName, BlobConstants.BlockListFilter.ALL, function (error5, list) {\n assert.equal(error5, null);\n assert.notEqual(list, null);\n assert.notEqual(list.CommittedBlocks, null);\n assert.equal(list.CommittedBlocks.length, 2);\n\n done();\n });\n });\n });\n });\n });\n });\n\n describe('shared access signature', function () {\n describe('getBlobUrl', function () {\n it('should work', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');\n\n var blobUrl = blobServiceassert.getBlobUrl(containerName);\n assert.equal(blobUrl, 'https://host.com:80/' + containerName);\n\n blobUrl = blobServiceassert.getBlobUrl(containerName, blobName);\n assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName);\n\n done();\n });\n\n it('should work with shared access policy', function (done) {\n var containerName = 'container';\n var blobName = 'blob';\n\n var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');\n\n var sharedAccessPolicy = {\n AccessPolicy: {\n Expiry: new Date('October 12, 2011 11:53:40 am GMT')\n }\n };\n\n var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy);\n assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=2011-10-12T11%3A53%3A40Z&sr=b&sv=2012-02-12&sig=gDOuwDoa4F7hhQJW9ReCimoHN2qp7NF1Nu3sdHjwIfs%3D');\n\n done();\n });\n\n it('should work with container acl permissions and spaces in name', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked) + ' foobar';\n var blobText = 'Hello World';\n var fileNameSource = testutil.generateId('prefix') + '.txt'; // fake bmp file with text...\n\n blobService.createContainer(containerName, function (err) {\n assert.equal(err, null);\n\n var startTime = new Date('April 15, 2013 11:53:40 am GMT');\n\n var readWriteSharedAccessPolicy = {\n Id: 'readwrite',\n AccessPolicy: {\n Start: startTime,\n Permissions: 'rwdl'\n }\n };\n\n blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) {\n assert.equal(err, null);\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (uploadError, blob, uploadResponse) {\n assert.equal(uploadError, null);\n assert.ok(uploadResponse.isSuccessful);\n\n var blobUrl = blobService.getBlobUrl(containerName, blobName, {\n Id: 'readwrite',\n AccessPolicy: {\n Expiry: new Date('April 15, 2099 11:53:40 am GMT')\n }\n });\n\n function responseCallback(err, rsp) {\n assert.equal(rsp.statusCode, 200);\n assert.equal(err, null);\n\n fs.unlink(fileNameSource, done);\n }\n\n request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource));\n });\n });\n });\n });\n\n it('should work with container acl permissions', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileNameSource = testutil.generateId('prefix') + '.bmp'; // fake bmp file with text...\n var blobText = 'Hello World!';\n\n blobService.createContainer(containerName, function (error) {\n assert.equal(error, null);\n\n var startTime = new Date('April 15, 2013 11:53:40 am GMT');\n\n var readWriteSharedAccessPolicy = {\n Id: 'readwrite',\n AccessPolicy: {\n Start: startTime,\n Permissions: 'rwdl'\n }\n };\n\n blobService.setContainerAcl(containerName, null, { signedIdentifiers: [ readWriteSharedAccessPolicy ] }, function (err) {\n assert.equal(err, null);\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (err) {\n assert.equal(err, null);\n\n var blobUrl = blobService.getBlobUrl(containerName, blobName, {\n Id: 'readwrite',\n AccessPolicy: {\n Expiry: new Date('April 15, 2099 11:53:40 am GMT')\n }\n });\n\n function responseCallback(err, rsp) {\n assert.equal(rsp.statusCode, 200);\n assert.equal(err, null);\n\n fs.unlink(fileNameSource, done);\n }\n\n request.get(blobUrl, responseCallback).pipe(fs.createWriteStream(fileNameSource));\n });\n });\n });\n });\n\n it('should work with duration', function (done) {\n var containerName = 'container';\n var blobName = 'blob';\n\n var blobServiceassert = storage.createBlobService('storageAccount', 'storageAccessKey', 'host.com:80');\n\n // Mock Date just to ensure a fixed signature\n this.clock = sinon.useFakeTimers(0);\n\n var sharedAccessPolicy = {\n AccessPolicy: {\n Expiry: storage.date.minutesFromNow(10)\n }\n };\n\n this.clock.restore();\n\n var blobUrl = blobServiceassert.getBlobUrl(containerName, blobName, sharedAccessPolicy);\n assert.equal(blobUrl, 'https://host.com:80/' + containerName + '/' + blobName + '?se=1970-01-01T00%3A10%3A00Z&sr=b&sv=2012-02-12&sig=ca700zLsjqapO1sUBVHIBblj2XoJCON1V4gMSfyQZc8%3D');\n\n done();\n });\n });\n\n it('GenerateSharedAccessSignature', function (done) {\n var containerName = 'images';\n var blobName = 'pic1.png';\n\n var devStorageBlobService = storage.createBlobService(ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY);\n\n var sharedAccessPolicy = {\n AccessPolicy: {\n Permissions: BlobConstants.SharedAccessPermissions.READ,\n Start: new Date('October 11, 2011 11:03:40 am GMT'),\n Expiry: new Date('October 12, 2011 11:53:40 am GMT')\n }\n };\n\n var sharedAccessSignature = devStorageBlobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);\n\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_START], '2011-10-11T11:03:40Z');\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_EXPIRY], '2011-10-12T11:53:40Z');\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_RESOURCE], BlobConstants.ResourceTypes.BLOB);\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_PERMISSIONS], BlobConstants.SharedAccessPermissions.READ);\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNED_VERSION], '2012-02-12');\n assert.equal(sharedAccessSignature.queryString[QueryStringConstants.SIGNATURE], 'ju4tX0G79vPxMOkBb7UfNVEgrj9+ZnSMutpUemVYHLY=');\n\n done();\n });\n });\n\n it('responseEmits', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n\n var responseReceived = false;\n blobService.on('response', function (response) {\n assert.notEqual(response, null);\n responseReceived = true;\n blobService.removeAllListeners('response');\n });\n\n blobService.createContainer(containerName, function (error) {\n assert.equal(error, null);\n\n blobService.createBlobBlockFromText('id1', containerName, blobName, 'id1', function (error2) {\n assert.equal(error2, null);\n // By the time the complete callback is processed the response header callback must have been called before\n assert.equal(responseReceived, true);\n\n done();\n });\n });\n });\n\n it('getBlobToStream', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileNameTarget = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test';\n var blobText = 'Hello World';\n\n blobService.createContainer(containerName, function (createError1, container1) {\n assert.equal(createError1, null);\n assert.notEqual(container1, null);\n\n blobService.createBlockBlobFromText(containerName, blobName, blobText, function (error1) {\n assert.equal(error1, null);\n\n blobService.getBlobToFile(containerName, blobName, fileNameTarget, function (error2) {\n assert.equal(error2, null);\n\n var exists = azureutil.pathExistsSync(fileNameTarget);\n assert.equal(exists, true);\n\n fs.readFile(fileNameTarget, function (err, fileText) {\n assert.equal(blobText, fileText);\n\n done();\n });\n });\n });\n });\n });\n\n it('SmallUploadBlobFromFile', function (done) {\n var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);\n var blobName = testutil.generateId(blobNamesPrefix, blobNames, suiteUtil.isMocked);\n var fileNameSource = testutil.generateId('getBlobFile', [], suiteUtil.isMocked) + '.test';\n var blobText = 'Hello World';\n\n fs.writeFile(fileNameSource, blobText, function () {\n blobService.createContainer(containerName, function (createError1, container1, createResponse1) {\n assert.equal(createError1, null);\n assert.notEqual(container1, null);\n assert.ok(createResponse1.isSuccessful);\n assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);\n\n var blobOptions = { contentType: 'text', blockIdPrefix : 'blockId' };\n blobService.createBlockBlobFromFile(containerName, blobName, fileNameSource, blobOptions, function (uploadError, blobResponse, uploadResponse) {\n assert.equal(uploadError, null);\n assert.notEqual(blobResponse, null);\n assert.ok(uploadResponse.isSuccessful);\n\n blobService.getBlobToText(containerName, blobName, function (downloadErr, blobTextResponse) {\n assert.equal(downloadErr, null);\n assert.equal(blobTextResponse, blobText);\n\n blobService.getBlobProperties(containerName, blobName, function (getBlobPropertiesErr, blobGetResponse) {\n assert.equal(getBlobPropertiesErr, null);\n assert.notEqual(blobGetResponse, null);\n if (blobGetResponse) {\n assert.equal(blobOptions.contentType, blobGetResponse.contentType);\n }\n\n done();\n });\n });\n });\n });\n });\n });\n\n it('storageConnectionStrings', function (done) {\n var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==';\n var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key;\n var blobService = storage.createBlobService(connectionString);\n\n assert.equal(blobService.storageAccount, 'myaccount');\n assert.equal(blobService.storageAccessKey, key);\n assert.equal(blobService.protocol, 'https:');\n assert.equal(blobService.host, 'myaccount.blob.core.windows.net');\n\n done();\n });\n\n it('storageConnectionStringsDevStore', function (done) {\n var connectionString = 'UseDevelopmentStorage=true';\n var blobService = storage.createBlobService(connectionString);\n\n assert.equal(blobService.storageAccount, ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT);\n assert.equal(blobService.storageAccessKey, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY);\n assert.equal(blobService.protocol, 'http:');\n assert.equal(blobService.host, '127.0.0.1');\n assert.equal(blobService.port, '10000');\n\n done();\n });\n\n it('should be creatable from config', function (done) {\n var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==';\n var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key;\n var config = common.configure('testenvironment', function (c) {\n c.storage(connectionString);\n });\n\n var blobService = storage.createBlobService(common.config('testenvironment'));\n\n assert.equal(blobService.storageAccount, 'myaccount');\n assert.equal(blobService.storageAccessKey, key);\n assert.equal(blobService.protocol, 'https:');\n assert.equal(blobService.host, 'myaccount.blob.core.windows.net');\n\n done();\n });\n});\n\nfunction repeat(s, n) {\n var ret = '';\n for (var i = 0; i < n; i++) {\n ret += s;\n }\n return ret;\n}\n"},"repo_name":{"kind":"string","value":"begoldsm/azure-sdk-for-node"},"path":{"kind":"string","value":"test/services/blob/blobservice-tests.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":59746,"string":"59,746"}}},{"rowIdx":115086020,"cells":{"code":{"kind":"string","value":"// =================================================================================================\n// Copyright 2011 Twitter, Inc.\n// -------------------------------------------------------------------------------------------------\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this work except in compliance with the License.\n// You may obtain a copy of the License in the LICENSE file, or 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\npackage com.twitter.common.net;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.Semaphore;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.annotation.Nullable;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.ListenableFutureTask;\nimport com.google.common.util.concurrent.ThreadFactoryBuilder;\n\nimport com.twitter.common.base.ExceptionalFunction;\nimport com.twitter.common.net.UrlResolver.ResolvedUrl.EndState;\nimport com.twitter.common.quantity.Amount;\nimport com.twitter.common.quantity.Time;\nimport com.twitter.common.stats.PrintableHistogram;\nimport com.twitter.common.util.BackoffStrategy;\nimport com.twitter.common.util.Clock;\nimport com.twitter.common.util.TruncatedBinaryBackoff;\nimport com.twitter.common.util.caching.Cache;\nimport com.twitter.common.util.caching.LRUCache;\n\n/**\n * Class to aid in resolving URLs by following redirects, which can optionally be performed\n * asynchronously using a thread pool.\n *\n * @author William Farner\n */\npublic class UrlResolver {\n private static final Logger LOG = Logger.getLogger(UrlResolver.class.getName());\n\n private static final String TWITTER_UA = \"Twitterbot/0.1\";\n private static final UrlResolverUtil URL_RESOLVER =\n new UrlResolverUtil(Functions.constant(TWITTER_UA));\n\n private static final ExceptionalFunction RESOLVER =\n new ExceptionalFunction() {\n @Override public String apply(String url) throws IOException {\n return URL_RESOLVER.getEffectiveUrl(url, null);\n }\n };\n\n private static ExceptionalFunction\n getUrlResolver(final @Nullable ProxyConfig proxyConfig) {\n if (proxyConfig != null) {\n return new ExceptionalFunction() {\n @Override public String apply(String url) throws IOException {\n return URL_RESOLVER.getEffectiveUrl(url, proxyConfig);\n }\n };\n } else {\n return RESOLVER;\n }\n }\n\n private final ExceptionalFunction resolver;\n private final int maxRedirects;\n\n // Tracks the number of active tasks (threads in use).\n private final Semaphore poolEntrySemaphore;\n private final Integer threadPoolSize;\n\n // Helps with signaling the handler.\n private final Executor handlerExecutor;\n\n // Manages the thread pool and task execution.\n private ExecutorService executor;\n\n // Cache to store resolved URLs.\n private final Cache urlCache = LRUCache.builder()\n .maxSize(10000)\n .makeSynchronized(true)\n .build();\n\n // Variables to track connection/request stats.\n private AtomicInteger requestCount = new AtomicInteger(0);\n private AtomicInteger cacheHits = new AtomicInteger(0);\n private AtomicInteger failureCount = new AtomicInteger(0);\n // Tracks the time (in milliseconds) required to resolve URLs.\n private final PrintableHistogram urlResolutionTimesMs = new PrintableHistogram(\n 1, 5, 10, 25, 50, 75, 100, 150, 200, 250, 300, 500, 750, 1000, 1500, 2000);\n\n private final Clock clock;\n private final BackoffStrategy backoffStrategy;\n\n @VisibleForTesting\n UrlResolver(Clock clock, BackoffStrategy backoffStrategy,\n ExceptionalFunction resolver, int maxRedirects) {\n this(clock, backoffStrategy, resolver, maxRedirects, null);\n }\n\n /**\n * Creates a new asynchronous URL resolver. A thread pool will be used to resolve URLs, and\n * resolved URLs will be announced via {@code handler}.\n *\n * @param maxRedirects The maximum number of HTTP redirects to follow.\n * @param threadPoolSize The number of threads to use for resolving URLs.\n * @param proxyConfig The proxy settings with which to make the HTTP request, or null for the\n * default configured proxy.\n */\n public UrlResolver(int maxRedirects, int threadPoolSize, @Nullable ProxyConfig proxyConfig) {\n this(Clock.SYSTEM_CLOCK,\n new TruncatedBinaryBackoff(Amount.of(100L, Time.MILLISECONDS), Amount.of(1L, Time.SECONDS)),\n getUrlResolver(proxyConfig), maxRedirects, threadPoolSize);\n }\n\n public UrlResolver(int maxRedirects, int threadPoolSize) {\n this(maxRedirects, threadPoolSize, null);\n }\n\n private UrlResolver(Clock clock, BackoffStrategy backoffStrategy,\n ExceptionalFunction resolver, int maxRedirects,\n @Nullable Integer threadPoolSize) {\n this.clock = clock;\n this.backoffStrategy = backoffStrategy;\n this.resolver = resolver;\n this.maxRedirects = maxRedirects;\n\n if (threadPoolSize != null) {\n this.threadPoolSize = threadPoolSize;\n Preconditions.checkState(threadPoolSize > 0);\n poolEntrySemaphore = new Semaphore(threadPoolSize);\n\n // Start up the thread pool.\n reset();\n\n // Executor to send notifications back to the handler. This also needs to be\n // a daemon thread.\n handlerExecutor =\n Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).build());\n } else {\n this.threadPoolSize = null;\n poolEntrySemaphore = null;\n handlerExecutor = null;\n }\n }\n\n public Future resolveUrlAsync(final String url, final ResolvedUrlHandler handler) {\n Preconditions.checkNotNull(\n \"Asynchronous URL resolution cannot be performed without a valid handler.\", handler);\n\n try {\n poolEntrySemaphore.acquire();\n } catch (InterruptedException e) {\n LOG.log(Level.SEVERE, \"Interrupted while waiting for thread to resolve URL: \" + url, e);\n return null;\n }\n final ListenableFutureTask future =\n ListenableFutureTask.create(\n new Callable() {\n @Override public ResolvedUrl call() {\n return resolveUrl(url);\n }\n });\n\n future.addListener(new Runnable() {\n @Override public void run() {\n try {\n handler.resolved(future);\n } finally {\n poolEntrySemaphore.release();\n }\n }\n }, handlerExecutor);\n\n executor.execute(future);\n return future;\n }\n\n private void logThreadpoolInfo() {\n LOG.info(\"Shutting down thread pool, available permits: \"\n + poolEntrySemaphore.availablePermits());\n LOG.info(\"Queued threads? \" + poolEntrySemaphore.hasQueuedThreads());\n LOG.info(\"Queue length: \" + poolEntrySemaphore.getQueueLength());\n }\n\n public void reset() {\n Preconditions.checkState(threadPoolSize != null);\n if (executor != null) {\n Preconditions.checkState(executor.isShutdown(),\n \"The thread pool must be shut down before resetting.\");\n Preconditions.checkState(executor.isTerminated(), \"There may still be pending async tasks.\");\n }\n\n // Create a thread pool with daemon threads, so that they may be terminated when no\n // application threads are running.\n executor = Executors.newFixedThreadPool(threadPoolSize,\n new ThreadFactoryBuilder().setDaemon(true).setNameFormat(\"UrlResolver[%d]\").build());\n }\n\n /**\n * Terminates the thread pool, waiting at most {@code waitSeconds} for active threads to complete.\n * After this method is called, no more URLs may be submitted for resolution.\n *\n * @param waitSeconds The number of seconds to wait for active threads to complete.\n */\n public void clearAsyncTasks(int waitSeconds) {\n Preconditions.checkState(threadPoolSize != null,\n \"finish() should not be called on a synchronous URL resolver.\");\n\n logThreadpoolInfo();\n executor.shutdown(); // Disable new tasks from being submitted.\n try {\n // Wait a while for existing tasks to terminate\n if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {\n LOG.info(\"Pool did not terminate, forcing shutdown.\");\n logThreadpoolInfo();\n List remaining = executor.shutdownNow();\n LOG.info(\"Tasks still running: \" + remaining);\n // Wait a while for tasks to respond to being cancelled\n if (!executor.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {\n LOG.warning(\"Pool did not terminate.\");\n logThreadpoolInfo();\n }\n }\n } catch (InterruptedException e) {\n LOG.log(Level.WARNING, \"Interrupted while waiting for threadpool to finish.\", e);\n // (Re-)Cancel if current thread also interrupted\n executor.shutdownNow();\n // Preserve interrupt status\n Thread.currentThread().interrupt();\n }\n }\n\n /**\n * Resolves a URL synchronously.\n *\n * @param url The URL to resolve.\n * @return The resolved URL.\n */\n public ResolvedUrl resolveUrl(String url) {\n ResolvedUrl resolvedUrl = new ResolvedUrl();\n resolvedUrl.setStartUrl(url);\n\n String cached = urlCache.get(url);\n if (cached != null) {\n cacheHits.incrementAndGet();\n resolvedUrl.setNextResolve(cached);\n resolvedUrl.setEndState(EndState.CACHED);\n return resolvedUrl;\n }\n\n String currentUrl = url;\n long backoffMs = 0L;\n String next = null;\n for (int i = 0; i < maxRedirects; i++) {\n try {\n next = resolveOnce(currentUrl);\n\n // If there was a 4xx or a 5xx, we''ll get a null back, so we pretend like we never advanced\n // to allow for a retry within the redirect limit.\n // TODO(John Sirois): we really need access to the return code here to do the right thing; ie:\n // retry for internal server errors but probably not for unauthorized\n if (next == null) {\n if (i < maxRedirects - 1) { // don't wait if we're about to exit the loop\n backoffMs = backoffStrategy.calculateBackoffMs(backoffMs);\n try {\n clock.waitFor(backoffMs);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new RuntimeException(\n \"Interrupted waiting to retry a failed resolution for: \" + currentUrl, e);\n }\n }\n continue;\n }\n\n backoffMs = 0L;\n if (next.equals(currentUrl)) {\n // We've reached the end of the redirect chain.\n resolvedUrl.setEndState(EndState.REACHED_LANDING);\n urlCache.put(url, currentUrl);\n for (String intermediateUrl : resolvedUrl.getIntermediateUrls()) {\n urlCache.put(intermediateUrl, currentUrl);\n }\n return resolvedUrl;\n } else if (!url.equals(next)) {\n resolvedUrl.setNextResolve(next);\n }\n currentUrl = next;\n } catch (IOException e) {\n LOG.log(Level.INFO, \"Failed to resolve url: \" + url, e);\n resolvedUrl.setEndState(EndState.ERROR);\n return resolvedUrl;\n }\n }\n\n resolvedUrl.setEndState(next == null || url.equals(currentUrl) ? EndState.ERROR\n : EndState.REDIRECT_LIMIT);\n return resolvedUrl;\n }\n\n /**\n * Resolves a url, following at most one redirect. Thread-safe.\n *\n * @param url The URL to resolve.\n * @return The result of following the URL through at most one redirect or null if the url could\n * not be followed\n * @throws IOException If an error occurs while resolving the URL.\n */\n private String resolveOnce(String url) throws IOException {\n requestCount.incrementAndGet();\n\n String resolvedUrl = urlCache.get(url);\n if (resolvedUrl != null) {\n cacheHits.incrementAndGet();\n return resolvedUrl;\n }\n\n try {\n long startTimeMs = System.currentTimeMillis();\n resolvedUrl = resolver.apply(url);\n if (resolvedUrl == null) {\n return null;\n }\n\n urlCache.put(url, resolvedUrl);\n\n synchronized (urlResolutionTimesMs) {\n urlResolutionTimesMs.addValue(System.currentTimeMillis() - startTimeMs);\n }\n return resolvedUrl;\n } catch (IOException e) {\n failureCount.incrementAndGet();\n throw e;\n }\n }\n\n @Override\n public String toString() {\n return String.format(\"Cache: %s\\nFailed requests: %d,\\nResolution Times: %s\",\n urlCache, failureCount.get(),\n urlResolutionTimesMs.toString());\n }\n\n /**\n * Class to wrap the result of a URL resolution.\n */\n public static class ResolvedUrl {\n public enum EndState {\n REACHED_LANDING,\n ERROR,\n CACHED,\n REDIRECT_LIMIT\n }\n\n private String startUrl;\n private final List resolveChain;\n private EndState endState;\n\n public ResolvedUrl() {\n resolveChain = Lists.newArrayList();\n }\n\n @VisibleForTesting\n public ResolvedUrl(EndState endState, String startUrl, String... resolveChain) {\n this.endState = endState;\n this.startUrl = startUrl;\n this.resolveChain = Lists.newArrayList(resolveChain);\n }\n\n public String getStartUrl() {\n return startUrl;\n }\n\n void setStartUrl(String startUrl) {\n this.startUrl = startUrl;\n }\n\n /**\n * Returns the last URL resolved following a redirect chain, or null if the startUrl is a\n * landing URL.\n */\n public String getEndUrl() {\n return resolveChain.isEmpty() ? null : Iterables.getLast(resolveChain);\n }\n\n void setNextResolve(String endUrl) {\n this.resolveChain.add(endUrl);\n }\n\n /**\n * Returns any immediate URLs encountered on the resolution chain. If the startUrl redirects\n * directly to the endUrl or they are the same the imtermediate URLs will be empty.\n */\n public Iterable getIntermediateUrls() {\n return resolveChain.size() <= 1 ? ImmutableList.of()\n : resolveChain.subList(0, resolveChain.size() - 1);\n }\n\n public EndState getEndState() {\n return endState;\n }\n\n void setEndState(EndState endState) {\n this.endState = endState;\n }\n\n public String toString() {\n return String.format(\"%s -> %s [%s, %d redirects]\",\n startUrl, Joiner.on(\" -> \").join(resolveChain), endState, resolveChain.size());\n }\n }\n\n /**\n * Interface to use for notifying the caller of resolved URLs.\n */\n public interface ResolvedUrlHandler {\n /**\n * Signals that a URL has been resolved to its target. The implementation of this method must\n * be thread safe.\n *\n * @param future The future that has finished resolving a URL.\n */\n public void resolved(Future future);\n }\n}\n"},"repo_name":{"kind":"string","value":"abel-von/commons"},"path":{"kind":"string","value":"src/java/com/twitter/common/net/UrlResolver.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":15827,"string":"15,827"}}},{"rowIdx":115086021,"cells":{"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with 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 com.twitter.elephantbird.pig.piggybank;\n\nimport org.apache.pig.impl.logicalLayer.FrontendException;\n\n/**\n * @see GenericInvoker\n */\npublic class InvokeForDouble extends GenericInvoker {\n\n public InvokeForDouble() {}\n\n public InvokeForDouble(String fullName) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException {\n super(fullName);\n }\n \n public InvokeForDouble(String fullName, String paramSpecsStr) throws FrontendException, SecurityException, ClassNotFoundException, NoSuchMethodException {\n super(fullName, paramSpecsStr);\n }\n\n public InvokeForDouble(String fullName, String paramSpecsStr, String isStatic)\n throws ClassNotFoundException, FrontendException, SecurityException, NoSuchMethodException {\n super(fullName, paramSpecsStr, isStatic);\n }\n\n\n }\n"},"repo_name":{"kind":"string","value":"ketralnis/elephant-bird"},"path":{"kind":"string","value":"src/java/com/twitter/elephantbird/pig/piggybank/InvokeForDouble.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":1672,"string":"1,672"}}},{"rowIdx":115086022,"cells":{"code":{"kind":"string","value":"define([\r\n './addExtensionsRequired',\r\n './addToArray',\r\n './ForEach',\r\n './getAccessorByteStride',\r\n '../../Core/Cartesian3',\r\n '../../Core/Math',\r\n '../../Core/clone',\r\n '../../Core/defaultValue',\r\n '../../Core/defined',\r\n '../../Core/Quaternion',\r\n '../../Core/WebGLConstants'\r\n ], function(\r\n addExtensionsRequired,\r\n addToArray,\r\n ForEach,\r\n getAccessorByteStride,\r\n Cartesian3,\r\n CesiumMath,\r\n clone,\r\n defaultValue,\r\n defined,\r\n Quaternion,\r\n WebGLConstants) {\r\n 'use strict';\r\n\r\n var updateFunctions = {\r\n '0.8' : glTF08to10,\r\n '1.0' : glTF10to20,\r\n '2.0' : undefined\r\n };\r\n\r\n /**\r\n * Update the glTF version to the latest version (2.0), or targetVersion if specified.\r\n * Applies changes made to the glTF spec between revisions so that the core library\r\n * only has to handle the latest version.\r\n *\r\n * @param {Object} gltf A javascript object containing a glTF asset.\r\n * @param {Object} [options] Options for updating the glTF.\r\n * @param {String} [options.targetVersion] The glTF will be upgraded until it hits the specified version.\r\n * @returns {Object} The updated glTF asset.\r\n */\r\n function updateVersion(gltf, options) {\r\n options = defaultValue(options, {});\r\n var targetVersion = options.targetVersion;\r\n var version = gltf.version;\r\n\r\n gltf.asset = defaultValue(gltf.asset, {\r\n version: '1.0'\r\n });\r\n\r\n version = defaultValue(version, gltf.asset.version);\r\n // invalid version\r\n if (!updateFunctions.hasOwnProperty(version)) {\r\n // try truncating trailing version numbers, could be a number as well if it is 0.8\r\n if (defined(version)) {\r\n version = ('' + version).substring(0, 3);\r\n }\r\n // default to 1.0 if it cannot be determined\r\n if (!updateFunctions.hasOwnProperty(version)) {\r\n version = '1.0';\r\n }\r\n }\r\n\r\n var updateFunction = updateFunctions[version];\r\n\r\n while (defined(updateFunction)) {\r\n if (version === targetVersion) {\r\n break;\r\n }\r\n updateFunction(gltf);\r\n version = gltf.asset.version;\r\n updateFunction = updateFunctions[version];\r\n }\r\n return gltf;\r\n }\r\n\r\n function updateInstanceTechniques(gltf) {\r\n var materials = gltf.materials;\r\n for (var materialId in materials) {\r\n if (materials.hasOwnProperty(materialId)) {\r\n var material = materials[materialId];\r\n var instanceTechnique = material.instanceTechnique;\r\n if (defined(instanceTechnique)) {\r\n material.technique = instanceTechnique.technique;\r\n material.values = instanceTechnique.values;\r\n delete material.instanceTechnique;\r\n }\r\n }\r\n }\r\n }\r\n\r\n function setPrimitiveModes(gltf) {\r\n var meshes = gltf.meshes;\r\n for (var meshId in meshes) {\r\n if (meshes.hasOwnProperty(meshId)) {\r\n var mesh = meshes[meshId];\r\n var primitives = mesh.primitives;\r\n if (defined(primitives)) {\r\n var primitivesLength = primitives.length;\r\n for (var i = 0; i < primitivesLength; i++) {\r\n var primitive = primitives[i];\r\n var defaultMode = defaultValue(primitive.primitive, WebGLConstants.TRIANGLES);\r\n primitive.mode = defaultValue(primitive.mode, defaultMode);\r\n delete primitive.primitive;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n function updateNodes(gltf) {\r\n var nodes = gltf.nodes;\r\n var axis = new Cartesian3();\r\n var quat = new Quaternion();\r\n for (var nodeId in nodes) {\r\n if (nodes.hasOwnProperty(nodeId)) {\r\n var node = nodes[nodeId];\r\n if (defined(node.rotation)) {\r\n var rotation = node.rotation;\r\n Cartesian3.fromArray(rotation, 0, axis);\r\n Quaternion.fromAxisAngle(axis, rotation[3], quat);\r\n node.rotation = [quat.x, quat.y, quat.z, quat.w];\r\n }\r\n var instanceSkin = node.instanceSkin;\r\n if (defined(instanceSkin)) {\r\n node.skeletons = instanceSkin.skeletons;\r\n node.skin = instanceSkin.skin;\r\n node.meshes = instanceSkin.meshes;\r\n delete node.instanceSkin;\r\n }\r\n }\r\n }\r\n }\r\n\r\n function removeTechniquePasses(gltf) {\r\n var techniques = gltf.techniques;\r\n for (var techniqueId in techniques) {\r\n if (techniques.hasOwnProperty(techniqueId)) {\r\n var technique = techniques[techniqueId];\r\n var passes = technique.passes;\r\n if (defined(passes)) {\r\n var passName = defaultValue(technique.pass, 'defaultPass');\r\n if (passes.hasOwnProperty(passName)) {\r\n var pass = passes[passName];\r\n var instanceProgram = pass.instanceProgram;\r\n technique.attributes = defaultValue(technique.attributes, instanceProgram.attributes);\r\n technique.program = defaultValue(technique.program, instanceProgram.program);\r\n technique.uniforms = defaultValue(technique.uniforms, instanceProgram.uniforms);\r\n technique.states = defaultValue(technique.states, pass.states);\r\n }\r\n delete technique.passes;\r\n delete technique.pass;\r\n }\r\n }\r\n }\r\n }\r\n\r\n function glTF08to10(gltf) {\r\n if (!defined(gltf.asset)) {\r\n gltf.asset = {};\r\n }\r\n var asset = gltf.asset;\r\n asset.version = '1.0';\r\n // profile should be an object, not a string\r\n if (!defined(asset.profile) || (typeof asset.profile === 'string')) {\r\n asset.profile = {};\r\n }\r\n // version property should be in asset, not on the root element\r\n if (defined(gltf.version)) {\r\n delete gltf.version;\r\n }\r\n // material.instanceTechnique properties should be directly on the material\r\n updateInstanceTechniques(gltf);\r\n // primitive.primitive should be primitive.mode\r\n setPrimitiveModes(gltf);\r\n // node rotation should be quaternion, not axis-angle\r\n // node.instanceSkin is deprecated\r\n updateNodes(gltf);\r\n // technique.pass and techniques.passes are deprecated\r\n removeTechniquePasses(gltf);\r\n // gltf.lights -> khrMaterialsCommon.lights\r\n if (defined(gltf.lights)) {\r\n var extensions = defaultValue(gltf.extensions, {});\r\n gltf.extensions = extensions;\r\n var materialsCommon = defaultValue(extensions.KHR_materials_common, {});\r\n extensions.KHR_materials_common = materialsCommon;\r\n materialsCommon.lights = gltf.lights;\r\n delete gltf.lights;\r\n }\r\n // gltf.allExtensions -> extensionsUsed\r\n if (defined(gltf.allExtensions)) {\r\n gltf.extensionsUsed = gltf.allExtensions;\r\n gltf.allExtensions = undefined;\r\n }\r\n }\r\n\r\n function removeAnimationSamplersIndirection(gltf) {\r\n var animations = gltf.animations;\r\n for (var animationId in animations) {\r\n if (animations.hasOwnProperty(animationId)) {\r\n var animation = animations[animationId];\r\n var parameters = animation.parameters;\r\n if (defined(parameters)) {\r\n var samplers = animation.samplers;\r\n for (var samplerId in samplers) {\r\n if (samplers.hasOwnProperty(samplerId)) {\r\n var sampler = samplers[samplerId];\r\n sampler.input = parameters[sampler.input];\r\n sampler.output = parameters[sampler.output];\r\n }\r\n }\r\n delete animation.parameters;\r\n }\r\n }\r\n }\r\n }\r\n\r\n function objectToArray(object, mapping) {\r\n var array = [];\r\n for (var id in object) {\r\n if (object.hasOwnProperty(id)) {\r\n var value = object[id];\r\n mapping[id] = array.length;\r\n array.push(value);\r\n if (!defined(value.name) && typeof(value) === 'object') {\r\n value.name = id;\r\n }\r\n }\r\n }\r\n return array;\r\n }\r\n\r\n function objectsToArrays(gltf) {\r\n var i;\r\n var globalMapping = {\r\n accessors: {},\r\n animations: {},\r\n bufferViews: {},\r\n buffers: {},\r\n cameras: {},\r\n materials: {},\r\n meshes: {},\r\n nodes: {},\r\n programs: {},\r\n shaders: {},\r\n skins: {},\r\n techniques: {}\r\n };\r\n\r\n // Map joint names to id names\r\n var jointName;\r\n var jointNameToId = {};\r\n var nodes = gltf.nodes;\r\n for (var id in nodes) {\r\n if (nodes.hasOwnProperty(id)) {\r\n jointName = nodes[id].jointName;\r\n if (defined(jointName)) {\r\n jointNameToId[jointName] = id;\r\n }\r\n }\r\n }\r\n\r\n // Convert top level objects to arrays\r\n for (var topLevelId in gltf) {\r\n if (gltf.hasOwnProperty(topLevelId) && topLevelId !== 'extras' && topLevelId !== 'asset' && topLevelId !== 'extensions') {\r\n var objectMapping = {};\r\n var object = gltf[topLevelId];\r\n if (typeof(object) === 'object' && !Array.isArray(object)) {\r\n gltf[topLevelId] = objectToArray(object, objectMapping);\r\n globalMapping[topLevelId] = objectMapping;\r\n if (topLevelId === 'animations') {\r\n objectMapping = {};\r\n object.samplers = objectToArray(object.samplers, objectMapping);\r\n globalMapping[topLevelId].samplers = objectMapping;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Remap joint names to array indexes\r\n for (jointName in jointNameToId) {\r\n if (jointNameToId.hasOwnProperty(jointName)) {\r\n jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]];\r\n }\r\n }\r\n\r\n // Fix references\r\n if (defined(gltf.scene)) {\r\n gltf.scene = globalMapping.scenes[gltf.scene];\r\n }\r\n ForEach.bufferView(gltf, function(bufferView) {\r\n if (defined(bufferView.buffer)) {\r\n bufferView.buffer = globalMapping.buffers[bufferView.buffer];\r\n }\r\n });\r\n ForEach.accessor(gltf, function(accessor) {\r\n if (defined(accessor.bufferView)) {\r\n accessor.bufferView = globalMapping.bufferViews[accessor.bufferView];\r\n }\r\n });\r\n ForEach.shader(gltf, function(shader) {\r\n var extensions = shader.extensions;\r\n if (defined(extensions)) {\r\n var binaryGltf = extensions.KHR_binary_glTF;\r\n if (defined(binaryGltf)) {\r\n shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];\r\n delete extensions.KHR_binary_glTF;\r\n }\r\n if (Object.keys(extensions).length === 0) {\r\n delete shader.extensions;\r\n }\r\n }\r\n });\r\n ForEach.program(gltf, function(program) {\r\n if (defined(program.vertexShader)) {\r\n program.vertexShader = globalMapping.shaders[program.vertexShader];\r\n }\r\n if (defined(program.fragmentShader)) {\r\n program.fragmentShader = globalMapping.shaders[program.fragmentShader];\r\n }\r\n });\r\n ForEach.technique(gltf, function(technique) {\r\n if (defined(technique.program)) {\r\n technique.program = globalMapping.programs[technique.program];\r\n }\r\n ForEach.techniqueParameter(technique, function(parameter) {\r\n if (defined(parameter.node)) {\r\n parameter.node = globalMapping.nodes[parameter.node];\r\n }\r\n var value = parameter.value;\r\n if (defined(value)) {\r\n if (Array.isArray(value)) {\r\n if (value.length === 1) {\r\n var textureId = value[0];\r\n if (typeof textureId === 'string') {\r\n value[0] = globalMapping.textures[textureId];\r\n }\r\n }\r\n }\r\n else if (typeof value === 'string') {\r\n parameter.value = [globalMapping.textures[value]];\r\n }\r\n }\r\n });\r\n });\r\n ForEach.mesh(gltf, function(mesh) {\r\n ForEach.meshPrimitive(mesh, function(primitive) {\r\n if (defined(primitive.indices)) {\r\n primitive.indices = globalMapping.accessors[primitive.indices];\r\n }\r\n ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {\r\n primitive.attributes[semantic] = globalMapping.accessors[accessorId];\r\n });\r\n if (defined(primitive.material)) {\r\n primitive.material = globalMapping.materials[primitive.material];\r\n }\r\n });\r\n });\r\n ForEach.node(gltf, function(node) {\r\n var children = node.children;\r\n if (defined(children)) {\r\n var childrenLength = children.length;\r\n for (i = 0; i < childrenLength; i++) {\r\n children[i] = globalMapping.nodes[children[i]];\r\n }\r\n }\r\n if (defined(node.meshes)) {\r\n // Split out meshes on nodes\r\n var meshes = node.meshes;\r\n var meshesLength = meshes.length;\r\n if (meshesLength > 0) {\r\n node.mesh = globalMapping.meshes[meshes[0]];\r\n for (i = 1; i < meshesLength; i++) {\r\n var meshNode = {\r\n mesh: globalMapping.meshes[meshes[i]],\r\n extras: {\r\n _pipeline: {}\r\n }\r\n };\r\n var meshNodeId = addToArray(gltf.nodes, meshNode);\r\n if (!defined(children)) {\r\n children = [];\r\n node.children = children;\r\n }\r\n children.push(meshNodeId);\r\n }\r\n }\r\n delete node.meshes;\r\n }\r\n if (defined(node.camera)) {\r\n node.camera = globalMapping.cameras[node.camera];\r\n }\r\n if (defined(node.skeletons)) {\r\n // Assign skeletons to skins\r\n var skeletons = node.skeletons;\r\n var skeletonsLength = skeletons.length;\r\n if ((skeletonsLength > 0) && defined(node.skin)) {\r\n var skin = gltf.skins[globalMapping.skins[node.skin]];\r\n skin.skeleton = globalMapping.nodes[skeletons[0]];\r\n }\r\n delete node.skeletons;\r\n }\r\n if (defined(node.skin)) {\r\n node.skin = globalMapping.skins[node.skin];\r\n }\r\n if (defined(node.jointName)) {\r\n delete(node.jointName);\r\n }\r\n });\r\n ForEach.skin(gltf, function(skin) {\r\n if (defined(skin.inverseBindMatrices)) {\r\n skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices];\r\n }\r\n var joints = [];\r\n var jointNames = skin.jointNames;\r\n if (defined(jointNames)) {\r\n for (i = 0; i < jointNames.length; i++) {\r\n joints[i] = jointNameToId[jointNames[i]];\r\n }\r\n skin.joints = joints;\r\n delete skin.jointNames;\r\n }\r\n });\r\n ForEach.scene(gltf, function(scene) {\r\n var sceneNodes = scene.nodes;\r\n if (defined(sceneNodes)) {\r\n var sceneNodesLength = sceneNodes.length;\r\n for (i = 0; i < sceneNodesLength; i++) {\r\n sceneNodes[i] = globalMapping.nodes[sceneNodes[i]];\r\n }\r\n }\r\n });\r\n ForEach.animation(gltf, function(animation) {\r\n var samplerMapping = {};\r\n animation.samplers = objectToArray(animation.samplers, samplerMapping);\r\n ForEach.animationSampler(animation, function(sampler) {\r\n sampler.input = globalMapping.accessors[sampler.input];\r\n sampler.output = globalMapping.accessors[sampler.output];\r\n });\r\n var channels = animation.channels;\r\n if (defined(channels)) {\r\n var channelsLength = channels.length;\r\n for (i = 0; i < channelsLength; i++) {\r\n var channel = channels[i];\r\n channel.sampler = samplerMapping[channel.sampler];\r\n var target = channel.target;\r\n if (defined(target)) {\r\n target.node = globalMapping.nodes[target.id];\r\n delete target.id;\r\n }\r\n }\r\n }\r\n });\r\n ForEach.material(gltf, function(material) {\r\n if (defined(material.technique)) {\r\n material.technique = globalMapping.techniques[material.technique];\r\n }\r\n ForEach.materialValue(material, function(value, name) {\r\n if (Array.isArray(value)) {\r\n if (value.length === 1) {\r\n var textureId = value[0];\r\n if (typeof textureId === 'string') {\r\n value[0] = globalMapping.textures[textureId];\r\n }\r\n }\r\n }\r\n else if (typeof value === 'string') {\r\n material.values[name] = {\r\n index : globalMapping.textures[value]\r\n };\r\n }\r\n });\r\n var extensions = material.extensions;\r\n if (defined(extensions)) {\r\n var materialsCommon = extensions.KHR_materials_common;\r\n if (defined(materialsCommon)) {\r\n ForEach.materialValue(materialsCommon, function(value, name) {\r\n if (Array.isArray(value)) {\r\n if (value.length === 1) {\r\n var textureId = value[0];\r\n if (typeof textureId === 'string') {\r\n value[0] = globalMapping.textures[textureId];\r\n }\r\n }\r\n }\r\n else if (typeof value === 'string') {\r\n materialsCommon.values[name] = {\r\n index: globalMapping.textures[value]\r\n };\r\n }\r\n });\r\n }\r\n }\r\n });\r\n ForEach.image(gltf, function(image) {\r\n var extensions = image.extensions;\r\n if (defined(extensions)) {\r\n var binaryGltf = extensions.KHR_binary_glTF;\r\n if (defined(binaryGltf)) {\r\n image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];\r\n image.mimeType = binaryGltf.mimeType;\r\n delete extensions.KHR_binary_glTF;\r\n }\r\n if (Object.keys(extensions).length === 0) {\r\n delete image.extensions;\r\n }\r\n }\r\n if (defined(image.extras)) {\r\n var compressedImages = image.extras.compressedImage3DTiles;\r\n for (var type in compressedImages) {\r\n if (compressedImages.hasOwnProperty(type)) {\r\n var compressedImage = compressedImages[type];\r\n var compressedExtensions = compressedImage.extensions;\r\n if (defined(compressedExtensions)) {\r\n var compressedBinaryGltf = compressedExtensions.KHR_binary_glTF;\r\n if (defined(compressedBinaryGltf)) {\r\n compressedImage.bufferView = globalMapping.bufferViews[compressedBinaryGltf.bufferView];\r\n compressedImage.mimeType = compressedBinaryGltf.mimeType;\r\n delete compressedExtensions.KHR_binary_glTF;\r\n }\r\n if (Object.keys(compressedExtensions).length === 0) {\r\n delete compressedImage.extensions;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n });\r\n ForEach.texture(gltf, function(texture) {\r\n if (defined(texture.sampler)) {\r\n texture.sampler = globalMapping.samplers[texture.sampler];\r\n }\r\n if (defined(texture.source)) {\r\n texture.source = globalMapping.images[texture.source];\r\n }\r\n });\r\n }\r\n\r\n function stripProfile(gltf) {\r\n var asset = gltf.asset;\r\n delete asset.profile;\r\n }\r\n\r\n var knownExtensions = {\r\n CESIUM_RTC : true,\r\n KHR_materials_common : true,\r\n WEB3D_quantized_attributes : true\r\n };\r\n function requireKnownExtensions(gltf) {\r\n var extensionsUsed = gltf.extensionsUsed;\r\n gltf.extensionsRequired = defaultValue(gltf.extensionsRequired, []);\r\n if (defined(extensionsUsed)) {\r\n var extensionsUsedLength = extensionsUsed.length;\r\n for (var i = 0; i < extensionsUsedLength; i++) {\r\n var extension = extensionsUsed[i];\r\n if (defined(knownExtensions[extension])) {\r\n gltf.extensionsRequired.push(extension);\r\n }\r\n }\r\n }\r\n }\r\n\r\n function removeBufferType(gltf) {\r\n ForEach.buffer(gltf, function(buffer) {\r\n delete buffer.type;\r\n });\r\n }\r\n\r\n function requireAttributeSetIndex(gltf) {\r\n ForEach.mesh(gltf, function(mesh) {\r\n ForEach.meshPrimitive(mesh, function(primitive) {\r\n ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {\r\n if (semantic === 'TEXCOORD') {\r\n primitive.attributes.TEXCOORD_0 = accessorId;\r\n } else if (semantic === 'COLOR') {\r\n primitive.attributes.COLOR_0 = accessorId;\r\n }\r\n });\r\n delete primitive.attributes.TEXCOORD;\r\n delete primitive.attributes.COLOR;\r\n });\r\n });\r\n ForEach.technique(gltf, function(technique) {\r\n ForEach.techniqueParameter(technique, function(parameter) {\r\n var semantic = parameter.semantic;\r\n if (defined(semantic)) {\r\n if (semantic === 'TEXCOORD') {\r\n parameter.semantic = 'TEXCOORD_0';\r\n } else if (semantic === 'COLOR') {\r\n parameter.semantic = 'COLOR_0';\r\n }\r\n }\r\n });\r\n });\r\n }\r\n\r\n var knownSemantics = {\r\n POSITION: true,\r\n NORMAL: true,\r\n TEXCOORD: true,\r\n COLOR: true,\r\n JOINT: true,\r\n WEIGHT: true\r\n };\r\n function underscoreApplicationSpecificSemantics(gltf) {\r\n var mappedSemantics = {};\r\n ForEach.mesh(gltf, function(mesh) {\r\n ForEach.meshPrimitive(mesh, function(primitive) {\r\n /* jshint unused:vars */\r\n ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {\r\n if (semantic.charAt(0) !== '_') {\r\n var setIndex = semantic.search(/_[0-9]+/g);\r\n var strippedSemantic = semantic;\r\n if (setIndex >= 0) {\r\n strippedSemantic = semantic.substring(0, setIndex);\r\n }\r\n if (!defined(knownSemantics[strippedSemantic])) {\r\n var newSemantic = '_' + semantic;\r\n mappedSemantics[semantic] = newSemantic;\r\n }\r\n }\r\n });\r\n for (var semantic in mappedSemantics) {\r\n if (mappedSemantics.hasOwnProperty(semantic)) {\r\n var mappedSemantic = mappedSemantics[semantic];\r\n var accessorId = primitive.attributes[semantic];\r\n if (defined(accessorId)) {\r\n delete primitive.attributes[semantic];\r\n primitive.attributes[mappedSemantic] = accessorId;\r\n }\r\n }\r\n }\r\n });\r\n });\r\n ForEach.technique(gltf, function(technique) {\r\n ForEach.techniqueParameter(technique, function(parameter) {\r\n var mappedSemantic = mappedSemantics[parameter.semantic];\r\n if (defined(mappedSemantic)) {\r\n parameter.semantic = mappedSemantic;\r\n }\r\n });\r\n });\r\n }\r\n\r\n function removeScissorFromTechniques(gltf) {\r\n ForEach.technique(gltf, function(technique) {\r\n var techniqueStates = technique.states;\r\n if (defined(techniqueStates)) {\r\n var techniqueFunctions = techniqueStates.functions;\r\n if (defined(techniqueFunctions)) {\r\n delete techniqueFunctions.scissor;\r\n }\r\n var enableStates = techniqueStates.enable;\r\n if (defined(enableStates)) {\r\n var scissorIndex = enableStates.indexOf(WebGLConstants.SCISSOR_TEST);\r\n if (scissorIndex >= 0) {\r\n enableStates.splice(scissorIndex, 1);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n function clampTechniqueFunctionStates(gltf) {\r\n ForEach.technique(gltf, function(technique) {\r\n var techniqueStates = technique.states;\r\n if (defined(techniqueStates)) {\r\n var functions = techniqueStates.functions;\r\n if (defined(functions)) {\r\n var blendColor = functions.blendColor;\r\n if (defined(blendColor)) {\r\n for (var i = 0; i < 4; i++) {\r\n blendColor[i] = CesiumMath.clamp(blendColor[i], 0.0, 1.0);\r\n }\r\n }\r\n var depthRange = functions.depthRange;\r\n if (defined(depthRange)) {\r\n depthRange[1] = CesiumMath.clamp(depthRange[1], 0.0, 1.0);\r\n depthRange[0] = CesiumMath.clamp(depthRange[0], 0.0, depthRange[1]);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n function clampCameraParameters(gltf) {\r\n ForEach.camera(gltf, function(camera) {\r\n var perspective = camera.perspective;\r\n if (defined(perspective)) {\r\n var aspectRatio = perspective.aspectRatio;\r\n if (defined(aspectRatio) && aspectRatio === 0.0) {\r\n delete perspective.aspectRatio;\r\n }\r\n var yfov = perspective.yfov;\r\n if (defined(yfov) && yfov === 0.0) {\r\n perspective.yfov = 1.0;\r\n }\r\n }\r\n });\r\n }\r\n\r\n function requireByteLength(gltf) {\r\n ForEach.buffer(gltf, function(buffer) {\r\n if (!defined(buffer.byteLength)) {\r\n buffer.byteLength = buffer.extras._pipeline.source.length;\r\n }\r\n });\r\n ForEach.bufferView(gltf, function(bufferView) {\r\n if (!defined(bufferView.byteLength)) {\r\n var bufferViewBufferId = bufferView.buffer;\r\n var bufferViewBuffer = gltf.buffers[bufferViewBufferId];\r\n bufferView.byteLength = bufferViewBuffer.byteLength;\r\n }\r\n });\r\n }\r\n\r\n function moveByteStrideToBufferView(gltf) {\r\n var bufferViews = gltf.bufferViews;\r\n var bufferViewsToDelete = {};\r\n ForEach.accessor(gltf, function(accessor) {\r\n var oldBufferViewId = accessor.bufferView;\r\n if (defined(oldBufferViewId)) {\r\n if (!defined(bufferViewsToDelete[oldBufferViewId])) {\r\n bufferViewsToDelete[oldBufferViewId] = true;\r\n }\r\n var bufferView = clone(bufferViews[oldBufferViewId]);\r\n var accessorByteStride = (defined(accessor.byteStride) && accessor.byteStride !== 0) ? accessor.byteStride : getAccessorByteStride(gltf, accessor);\r\n if (defined(accessorByteStride)) {\r\n bufferView.byteStride = accessorByteStride;\r\n if (bufferView.byteStride !== 0) {\r\n bufferView.byteLength = accessor.count * accessorByteStride;\r\n }\r\n bufferView.byteOffset += accessor.byteOffset;\r\n accessor.byteOffset = 0;\r\n delete accessor.byteStride;\r\n }\r\n accessor.bufferView = addToArray(bufferViews, bufferView);\r\n }\r\n });\r\n\r\n var bufferViewShiftMap = {};\r\n var bufferViewRemovalCount = 0;\r\n /* jshint unused:vars */\r\n ForEach.bufferView(gltf, function(bufferView, bufferViewId) {\r\n if (defined(bufferViewsToDelete[bufferViewId])) {\r\n bufferViewRemovalCount++;\r\n } else {\r\n bufferViewShiftMap[bufferViewId] = bufferViewId - bufferViewRemovalCount;\r\n }\r\n });\r\n\r\n var removedCount = 0;\r\n for (var bufferViewId in bufferViewsToDelete) {\r\n if (defined(bufferViewId)) {\r\n var index = parseInt(bufferViewId) - removedCount;\r\n bufferViews.splice(index, 1);\r\n removedCount++;\r\n }\r\n }\r\n\r\n ForEach.accessor(gltf, function(accessor) {\r\n var accessorBufferView = accessor.bufferView;\r\n if (defined(accessorBufferView)) {\r\n accessor.bufferView = bufferViewShiftMap[accessorBufferView];\r\n }\r\n });\r\n\r\n ForEach.shader(gltf, function(shader) {\r\n var shaderBufferView = shader.bufferView;\r\n if (defined(shaderBufferView)) {\r\n shader.bufferView = bufferViewShiftMap[shaderBufferView];\r\n }\r\n });\r\n\r\n ForEach.image(gltf, function(image) {\r\n var imageBufferView = image.bufferView;\r\n if (defined(imageBufferView)) {\r\n image.bufferView = bufferViewShiftMap[imageBufferView];\r\n }\r\n if (defined(image.extras)) {\r\n var compressedImages = image.extras.compressedImage3DTiles;\r\n for (var type in compressedImages) {\r\n if (compressedImages.hasOwnProperty(type)) {\r\n var compressedImage = compressedImages[type];\r\n var compressedImageBufferView = compressedImage.bufferView;\r\n if (defined(compressedImageBufferView)) {\r\n compressedImage.bufferView = bufferViewShiftMap[compressedImageBufferView];\r\n }\r\n }\r\n }\r\n }\r\n });\r\n }\r\n\r\n function stripTechniqueAttributeValues(gltf) {\r\n ForEach.technique(gltf, function(technique) {\r\n ForEach.techniqueAttribute(technique, function(attribute) {\r\n var parameter = technique.parameters[attribute];\r\n if (defined(parameter.value)) {\r\n delete parameter.value;\r\n }\r\n });\r\n });\r\n }\r\n\r\n function stripTechniqueParameterCount(gltf) {\r\n ForEach.technique(gltf, function(technique) {\r\n ForEach.techniqueParameter(technique, function(parameter) {\r\n if (defined(parameter.count)) {\r\n var semantic = parameter.semantic;\r\n if (!defined(semantic) || (semantic !== 'JOINTMATRIX' && semantic.indexOf('_') !== 0)) {\r\n delete parameter.count;\r\n }\r\n }\r\n });\r\n });\r\n }\r\n\r\n function addKHRTechniqueExtension(gltf) {\r\n var techniques = gltf.techniques;\r\n if (defined(techniques) && techniques.length > 0) {\r\n addExtensionsRequired(gltf, 'KHR_technique_webgl');\r\n }\r\n }\r\n\r\n function glTF10to20(gltf) {\r\n if (!defined(gltf.asset)) {\r\n gltf.asset = {};\r\n }\r\n var asset = gltf.asset;\r\n asset.version = '2.0';\r\n // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models.\r\n updateInstanceTechniques(gltf);\r\n // animation.samplers now refers directly to accessors and animation.parameters should be removed\r\n removeAnimationSamplersIndirection(gltf);\r\n // top-level objects are now arrays referenced by index instead of id\r\n objectsToArrays(gltf);\r\n // asset.profile no longer exists\r\n stripProfile(gltf);\r\n // move known extensions from extensionsUsed to extensionsRequired\r\n requireKnownExtensions(gltf);\r\n // bufferView.byteLength and buffer.byteLength are required\r\n requireByteLength(gltf);\r\n // byteStride moved from accessor to bufferView\r\n moveByteStrideToBufferView(gltf);\r\n // buffer.type is unnecessary and should be removed\r\n removeBufferType(gltf);\r\n // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#)\r\n requireAttributeSetIndex(gltf);\r\n // Add underscores to application-specific parameters\r\n underscoreApplicationSpecificSemantics(gltf);\r\n // remove scissor from techniques\r\n removeScissorFromTechniques(gltf);\r\n // clamp technique function states to min/max\r\n clampTechniqueFunctionStates(gltf);\r\n // clamp camera parameters\r\n clampCameraParameters(gltf);\r\n // a technique parameter specified as an attribute cannot have a value\r\n stripTechniqueAttributeValues(gltf);\r\n // only techniques with a JOINTMATRIX or application specific semantic may have a defined count property\r\n stripTechniqueParameterCount(gltf);\r\n // add KHR_technique_webgl extension\r\n addKHRTechniqueExtension(gltf);\r\n }\r\n return updateVersion;\r\n});\r\n"},"repo_name":{"kind":"string","value":"EnquistLab/ffdm-frontend"},"path":{"kind":"string","value":"public/assets/images/Workers/ThirdParty/GltfPipeline/updateVersion.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":36201,"string":"36,201"}}},{"rowIdx":115086023,"cells":{"code":{"kind":"string","value":"// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing Microsoft.CodeAnalysis;\nusing Microsoft.CodeAnalysis.Editor.Shared.Utilities;\nusing Microsoft.CodeAnalysis.ErrorLogger;\nusing Microsoft.CodeAnalysis.ErrorReporting;\nusing Microsoft.CodeAnalysis.Internal.Log;\nusing Microsoft.CodeAnalysis.Navigation;\nusing Microsoft.CodeAnalysis.Options;\nusing Microsoft.CodeAnalysis.Text;\nusing Microsoft.VisualStudio.Editor;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;\nusing Microsoft.VisualStudio.LanguageServices.Implementation.Venus;\nusing Microsoft.VisualStudio.Shell;\nusing Microsoft.VisualStudio.Shell.Interop;\nusing Microsoft.VisualStudio.Text;\nusing Microsoft.VisualStudio.TextManager.Interop;\nusing Roslyn.Utilities;\nusing TextSpan = Microsoft.CodeAnalysis.Text.TextSpan;\nusing VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;\n\nnamespace Microsoft.VisualStudio.LanguageServices.Implementation\n{\n using Workspace = Microsoft.CodeAnalysis.Workspace;\n\n internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService\n {\n private readonly IServiceProvider _serviceProvider;\n private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;\n\n public VisualStudioDocumentNavigationService(\n SVsServiceProvider serviceProvider,\n IVsEditorAdaptersFactoryService editorAdaptersFactoryService)\n {\n _serviceProvider = serviceProvider;\n _editorAdaptersFactoryService = editorAdaptersFactoryService;\n }\n\n public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsSecondaryBuffer(workspace, documentId))\n {\n return true;\n }\n\n var document = workspace.CurrentSolution.GetDocument(documentId);\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n\n var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length);\n if (boundedTextSpan != textSpan)\n {\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))\n {\n }\n\n return false;\n }\n\n var vsTextSpan = text.GetVsTextSpanForSpan(textSpan);\n\n return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);\n }\n\n public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsSecondaryBuffer(workspace, documentId))\n {\n return true;\n }\n\n var document = workspace.CurrentSolution.GetDocument(documentId);\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);\n\n return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);\n }\n\n public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsSecondaryBuffer(workspace, documentId))\n {\n return true;\n }\n\n var document = workspace.CurrentSolution.GetDocument(documentId);\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n\n var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length);\n if (boundedPosition != position)\n {\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))\n {\n }\n\n return false;\n }\n\n var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace);\n\n return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);\n }\n\n public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsForeground())\n {\n throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);\n }\n\n var document = OpenDocument(workspace, documentId, options);\n if (document == null)\n {\n return false;\n }\n\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n var textBuffer = text.Container.GetTextBuffer();\n\n var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length);\n if (boundedTextSpan != textSpan)\n {\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))\n {\n }\n }\n\n var vsTextSpan = text.GetVsTextSpanForSpan(boundedTextSpan);\n\n if (IsSecondaryBuffer(workspace, documentId) &&\n !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))\n {\n return false;\n }\n\n return NavigateTo(textBuffer, vsTextSpan);\n }\n\n public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsForeground())\n {\n throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);\n }\n\n var document = OpenDocument(workspace, documentId, options);\n if (document == null)\n {\n return false;\n }\n\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n var textBuffer = text.Container.GetTextBuffer();\n\n var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);\n\n if (IsSecondaryBuffer(workspace, documentId) &&\n !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))\n {\n return false;\n }\n\n return NavigateTo(textBuffer, vsTextSpan);\n }\n\n public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options)\n {\n // Navigation should not change the context of linked files and Shared Projects.\n documentId = workspace.GetDocumentIdInCurrentContext(documentId);\n\n if (!IsForeground())\n {\n throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);\n }\n\n var document = OpenDocument(workspace, documentId, options);\n if (document == null)\n {\n return false;\n }\n\n var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);\n var textBuffer = text.Container.GetTextBuffer();\n\n var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length);\n if (boundedPosition != position)\n {\n try\n {\n throw new ArgumentOutOfRangeException();\n }\n catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))\n {\n }\n }\n\n var vsTextSpan = text.GetVsTextSpanForPosition(boundedPosition, virtualSpace);\n\n if (IsSecondaryBuffer(workspace, documentId) &&\n !vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))\n {\n return false;\n }\n\n return NavigateTo(textBuffer, vsTextSpan);\n }\n\n /// \n /// It is unclear why, but we are sometimes asked to navigate to a position that is not\n /// inside the bounds of the associated . This method returns a\n /// position that is guaranteed to be inside the bounds. If the\n /// returned position is different from the given position, then the worst observable\n /// behavior is either no navigation or navigation to the end of the document. See the\n /// following bugs for more details:\n /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211\n /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895\n /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318\n /// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409\n /// \n private static int GetPositionWithinDocumentBounds(int position, int documentLength)\n {\n return Math.Min(documentLength, Math.Max(position, 0));\n }\n\n /// \n /// It is unclear why, but we are sometimes asked to navigate to a \n /// that is not inside the bounds of the associated . This method\n /// returns a span that is guaranteed to be inside the bounds. If\n /// the returned span is different from the given span, then the worst observable behavior\n /// is either no navigation or navigation to the end of the document.\n /// See https://github.com/dotnet/roslyn/issues/7660 for more details.\n /// \n private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength)\n {\n return TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength));\n }\n\n private static Document OpenDocument(Workspace workspace, DocumentId documentId, OptionSet options)\n {\n options = options ?? workspace.Options;\n\n // Always open the document again, even if the document is already open in the \n // workspace. If a document is already open in a preview tab and it is opened again \n // in a permanent tab, this allows the document to transition to the new state.\n if (workspace.CanOpenDocuments)\n {\n if (options.GetOption(NavigationOptions.PreferProvisionalTab))\n {\n // If we're just opening the provisional tab, then do not \"activate\" the document\n // (i.e. don't give it focus). This way if a user is just arrowing through a set \n // of FindAllReferences results, they don't have their cursor placed into the document.\n var state = __VSNEWDOCUMENTSTATE.NDS_Provisional | __VSNEWDOCUMENTSTATE.NDS_NoActivate;\n using (var scope = new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation))\n {\n workspace.OpenDocument(documentId);\n }\n }\n else\n {\n workspace.OpenDocument(documentId);\n }\n }\n\n if (!workspace.IsDocumentOpen(documentId))\n {\n return null;\n }\n\n return workspace.CurrentSolution.GetDocument(documentId);\n }\n\n private bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan)\n {\n using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, CancellationToken.None))\n {\n var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer);\n if (vsTextBuffer == null)\n {\n Debug.Fail(\"Could not get IVsTextBuffer for document!\");\n return false;\n }\n\n var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager));\n if (textManager == null)\n {\n Debug.Fail(\"Could not get IVsTextManager service!\");\n return false;\n }\n\n return ErrorHandler.Succeeded(\n textManager.NavigateToLineAndColumn2(\n vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow));\n }\n }\n\n private bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId)\n {\n var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;\n if (visualStudioWorkspace == null)\n {\n return false;\n }\n\n var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument;\n if (containedDocument == null)\n {\n return false;\n }\n\n return true;\n }\n\n private bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer)\n {\n return spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out var spanInPrimaryBuffer);\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"jkotas/roslyn"},"path":{"kind":"string","value":"src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioDocumentNavigationService.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":15102,"string":"15,102"}}},{"rowIdx":115086024,"cells":{"code":{"kind":"string","value":"/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with 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 */\n\npackage org.apache.jena.sparql.expr;\n\nimport org.apache.jena.sparql.expr.nodevalue.XSDFuncOp ;\nimport org.apache.jena.sparql.sse.Tags ;\n\npublic class E_StrEncodeForURI extends ExprFunction1\n{\n private static final String symbol = Tags.tagStrEncodeForURI ;\n\n public E_StrEncodeForURI(Expr expr)\n {\n super(expr, symbol) ;\n }\n \n @Override\n public NodeValue eval(NodeValue v)\n { \n return XSDFuncOp.strEncodeForURI(v) ;\n }\n \n @Override\n public Expr copy(Expr expr) { return new E_StrEncodeForURI(expr) ; } \n}\n"},"repo_name":{"kind":"string","value":"tr3vr/jena"},"path":{"kind":"string","value":"jena-arq/src/main/java/org/apache/jena/sparql/expr/E_StrEncodeForURI.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":1365,"string":"1,365"}}},{"rowIdx":115086025,"cells":{"code":{"kind":"string","value":"/*\n*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.\n*\n*WSO2 Inc. licenses this file to you under the Apache License,\n*Version 2.0 (the \"License\"); you may not use this file except\n*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.wso2.appserver.ui.integration.test.webapp.spring;\n\nimport org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.testng.Assert;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\nimport org.wso2.appserver.integration.common.ui.page.LoginPage;\nimport org.wso2.appserver.integration.common.ui.page.main.WebAppListPage;\nimport org.wso2.appserver.integration.common.ui.page.main.WebAppUploadingPage;\nimport org.wso2.appserver.integration.common.utils.ASIntegrationUITest;\nimport org.wso2.carbon.automation.extensions.selenium.BrowserManager;\nimport org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Calendar;\n\nimport static org.testng.AssertJUnit.assertTrue;\n\n/**\n * This class tests the deployment and accessibility of a web application which use spring framework\n */\npublic class SpringWebApplicationDeploymentTestCase extends ASIntegrationUITest {\n private WebDriver driver;\n private final String context = \"/booking-faces\";\n\n @BeforeClass(alwaysRun = true, enabled = false)\n public void setUp() throws Exception {\n super.init();\n driver = BrowserManager.getWebDriver();\n driver.get(getLoginURL());\n LoginPage test = new LoginPage(driver);\n test.loginAs(userInfo.getUserName(), userInfo.getPassword());\n }\n\n @Test(groups = \"wso2.as\", description = \"Uploading the web app which use spring\", enabled = false)\n public void uploadSpringWebApplicationTest() throws Exception {\n String filePath = TestConfigurationProvider.getResourceLocation(\"AS\")\n + File.separator + \"war\" + File.separator + \"spring\" + File.separator + \"booking-faces.war\";\n WebAppUploadingPage uploadPage = new WebAppUploadingPage(driver);\n Assert.assertTrue(uploadPage.uploadWebApp(filePath), \"Web Application uploading failed\");\n\n }\n\n @Test(groups = \"wso2.as\", description = \"Verifying Deployment the web app which use spring\"\n , dependsOnMethods = \"uploadSpringWebApplicationTest\", enabled = false)\n public void webApplicationDeploymentTest() throws Exception {\n WebAppListPage webAppListPage = new WebAppListPage(driver);\n assertTrue(\"Web Application Deployment Failed. Web Application /booking-faces not found in Web application List\"\n , isWebAppDeployed(webAppListPage, context));\n driver.findElement(By.id(\"webappsTable\")).findElement(By.linkText(\"/booking-faces\")).click();\n\n }\n\n @Test(groups = \"wso2.as\", description = \"Access the spring application\"\n , dependsOnMethods = \"webApplicationDeploymentTest\", enabled = false)\n public void invokeSpringApplicationTest() throws Exception {\n WebDriver driverForApp = null;\n try {\n driverForApp = BrowserManager.getWebDriver();\n //Go to application\n driverForApp.get(webAppURL + \"/booking-faces/spring/intro\");\n driverForApp.findElement(By.linkText(\"Start your Spring Travel experience\")).click();\n\n //searching hotels to reserve\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"j_idt13:searchString\\\"]\")).sendKeys(\"Con\");\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"j_idt13:findHotels\\\"]\")).click();\n\n //view hotel information\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"j_idt12:hotels:0:viewHotelLink\\\"]\")).click();\n //go to book hotel\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"hotel:book\\\"]\")).click();\n\n //providing user name and password\n driverForApp.findElement(By.xpath(\"/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[1]/input\"))\n .sendKeys(\"keith\");\n driverForApp.findElement(By.xpath(\"/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[2]/input\"))\n .sendKeys(\"melbourne\");\n //authenticating\n driverForApp.findElement(By.xpath(\"/html/body/div/div[3]/div[2]/div[2]/form/fieldset/p[4]/input\"))\n .click();\n\n //booking hotel\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"hotel:book\\\"]\")).click();\n\n //providing payments information\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"bookingForm:creditCard\\\"]\")).sendKeys(\"1234567890123456\");\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"bookingForm:creditCardName\\\"]\")).sendKeys(\"xyz\");\n\n //proceed transaction\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"bookingForm:proceed\\\"]\")).click();\n\n //confirm booking\n driverForApp.findElement(By.xpath(\"//*[@id=\\\"j_idt13:confirm\\\"]\")).click();\n\n //verify whether the hotel booked is in the booked hotel tabled\n Assert.assertEquals(driverForApp.findElement(By.xpath(\"//*[@id=\\\"bookings_header\\\"]\")).getText()\n , \"Your Hotel Bookings\", \"Booked Hotel table Not Found\");\n\n //verify the hotel name is exist in the booked hotel table\n Assert.assertEquals(driverForApp.findElement(By.xpath(\"//*[@id=\\\"j_idt23:j_idt24_data\\\"]/tr/td[1]\"))\n .getText(), \"Conrad Miami\\n\" +\n \"1395 Brickell Ave\\n\" +\n \"Miami, FL\", \"Hotel Name mismatch\");\n } finally {\n if (driverForApp != null) {\n driverForApp.quit();\n }\n }\n }\n\n @AfterClass(alwaysRun = true, enabled = false)\n public void deleteWebApplication() throws Exception {\n try {\n WebAppListPage webAppListPage = new WebAppListPage(driver);\n if (webAppListPage.findWebApp(context)) {\n Assert.assertTrue(webAppListPage.deleteWebApp(context), \"Web Application Deletion failed\");\n Assert.assertTrue(isWebAppUnDeployed(webAppListPage, context));\n }\n } finally {\n driver.quit();\n }\n\n }\n\n private boolean isWebAppDeployed(WebAppListPage listPage, String webAppContext)\n throws IOException {\n\n boolean isServiceDeployed = false;\n Calendar startTime = Calendar.getInstance();\n long time;\n while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) {\n listPage = new WebAppListPage(driver);\n if (listPage.findWebApp(webAppContext)) {\n isServiceDeployed = true;\n break;\n }\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ignored) {\n\n }\n\n }\n\n return isServiceDeployed;\n\n }\n\n private boolean isWebAppUnDeployed(WebAppListPage listPage, String webAppContext)\n throws IOException {\n\n boolean isServiceUnDeployed = false;\n Calendar startTime = Calendar.getInstance();\n long time;\n while ((time = (Calendar.getInstance().getTimeInMillis() - startTime.getTimeInMillis())) < 1000 * 60 * 2) {\n listPage = new WebAppListPage(driver);\n if (!listPage.findWebApp(webAppContext)) {\n isServiceUnDeployed = true;\n break;\n }\n try {\n Thread.sleep(1000);\n } catch (InterruptedException ignored) {\n\n }\n\n }\n\n return isServiceUnDeployed;\n\n }\n}\n"},"repo_name":{"kind":"string","value":"kasungayan/product-as"},"path":{"kind":"string","value":"modules/integration/tests-ui-integration/tests-ui/src/test/java/org/wso2/appserver/ui/integration/test/webapp/spring/SpringWebApplicationDeploymentTestCase.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":8185,"string":"8,185"}}},{"rowIdx":115086026,"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 */\n\npackage org.apache.flink.streaming.connectors.kinesis.proxy;\n\nimport org.apache.flink.annotation.Internal;\n\nimport software.amazon.awssdk.services.kinesis.model.DeregisterStreamConsumerResponse;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamConsumerResponse;\nimport software.amazon.awssdk.services.kinesis.model.DescribeStreamSummaryResponse;\nimport software.amazon.awssdk.services.kinesis.model.RegisterStreamConsumerResponse;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;\nimport software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;\n\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.ExecutionException;\n\n/**\n * Interface for a Kinesis proxy using AWS SDK v2.x operating on multiple Kinesis streams within the\n * same AWS service region.\n */\n@Internal\npublic interface KinesisProxyV2Interface {\n\n DescribeStreamSummaryResponse describeStreamSummary(String stream)\n throws InterruptedException, ExecutionException;\n\n DescribeStreamConsumerResponse describeStreamConsumer(final String streamConsumerArn)\n throws InterruptedException, ExecutionException;\n\n DescribeStreamConsumerResponse describeStreamConsumer(\n final String streamArn, final String consumerName)\n throws InterruptedException, ExecutionException;\n\n RegisterStreamConsumerResponse registerStreamConsumer(\n final String streamArn, final String consumerName)\n throws InterruptedException, ExecutionException;\n\n DeregisterStreamConsumerResponse deregisterStreamConsumer(final String consumerArn)\n throws InterruptedException, ExecutionException;\n\n CompletableFuture subscribeToShard(\n SubscribeToShardRequest request, SubscribeToShardResponseHandler responseHandler);\n\n /** Destroy any open resources used by the factory. */\n default void close() {\n // Do nothing by default\n }\n}\n"},"repo_name":{"kind":"string","value":"apache/flink"},"path":{"kind":"string","value":"flink-connectors/flink-connector-kinesis/src/main/java/org/apache/flink/streaming/connectors/kinesis/proxy/KinesisProxyV2Interface.java"},"language":{"kind":"string","value":"Java"},"license":{"kind":"string","value":"apache-2.0"},"size":{"kind":"number","value":2775,"string":"2,775"}}},{"rowIdx":115086027,"cells":{"code":{"kind":"string","value":"cask 'dragthing' do\n version '5.9.12'\n sha256 '4a351c593aff1c3214613d622a4e81f184e8ae238df6db921dd822efeefe27e6'\n\n # amazonaws.com is the official download host per the vendor homepage\n url \"https://s3.amazonaws.com/tlasystems/DragThing-#{version}.dmg\"\n name 'DragThing'\n homepage 'http://www.dragthing.com'\n license :freemium\n\n app 'DragThing.app'\nend\n"},"repo_name":{"kind":"string","value":"mingzhi22/homebrew-cask"},"path":{"kind":"string","value":"Casks/dragthing.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"bsd-2-clause"},"size":{"kind":"number","value":361,"string":"361"}}},{"rowIdx":115086028,"cells":{"code":{"kind":"string","value":" 'bar'), -4);\n }\n\n /**\n * assemble(): defined by RouteInterface interface.\n *\n * @see Route::assemble()\n * @param array $params\n * @param array $options\n * @return mixed\n */\n public function assemble(array $params = null, array $options = null)\n {\n if (isset($params['foo'])) {\n return $params['foo'];\n }\n\n return '';\n }\n}\n"},"repo_name":{"kind":"string","value":"exclie/Imagenologia"},"path":{"kind":"string","value":"vendor/zendframework/zendframework/tests/ZendTest/Mvc/Router/Http/TestAsset/DummyRouteWithParam.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":1223,"string":"1,223"}}},{"rowIdx":115086029,"cells":{"code":{"kind":"string","value":"goog.module('javascript.protobuf.conformance');\n\nconst ConformanceRequest = goog.require('proto.conformance.ConformanceRequest');\nconst ConformanceResponse = goog.require('proto.conformance.ConformanceResponse');\nconst TestAllTypesProto2 = goog.require('proto.conformance.TestAllTypesProto2');\nconst TestAllTypesProto3 = goog.require('proto.conformance.TestAllTypesProto3');\nconst WireFormat = goog.require('proto.conformance.WireFormat');\nconst base64 = goog.require('goog.crypt.base64');\n\n/**\n * Creates a `proto.conformance.ConformanceResponse` response according to the\n * `proto.conformance.ConformanceRequest` request.\n * @param {!ConformanceRequest} request\n * @return {!ConformanceResponse} response\n */\nfunction doTest(request) {\n const response = ConformanceResponse.createEmpty();\n\n if(request.getPayloadCase() === ConformanceRequest.PayloadCase.JSON_PAYLOAD) {\n response.setSkipped('Json is not supported as input format.');\n return response;\n }\n\n if(request.getPayloadCase() === ConformanceRequest.PayloadCase.TEXT_PAYLOAD) {\n response.setSkipped('Text format is not supported as input format.');\n return response;\n }\n\n if(request.getPayloadCase() === ConformanceRequest.PayloadCase.PAYLOAD_NOT_SET) {\n response.setRuntimeError('Request didn\\'t have payload.');\n return response;\n }\n\n if(request.getPayloadCase() !== ConformanceRequest.PayloadCase.PROTOBUF_PAYLOAD) {\n throw new Error('Request didn\\'t have accepted input format.');\n }\n\n if (request.getRequestedOutputFormat() === WireFormat.JSON) {\n response.setSkipped('Json is not supported as output format.');\n return response;\n }\n\n if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) {\n response.setSkipped('Text format is not supported as output format.');\n return response;\n }\n\n if (request.getRequestedOutputFormat() === WireFormat.TEXT_FORMAT) {\n response.setRuntimeError('Unspecified output format');\n return response;\n }\n\n if (request.getRequestedOutputFormat() !== WireFormat.PROTOBUF) {\n throw new Error('Request didn\\'t have accepted output format.');\n }\n\n if (request.getMessageType() === 'conformance.FailureSet') {\n response.setProtobufPayload(new ArrayBuffer(0));\n } else if (\n request.getMessageType() ===\n 'protobuf_test_messages.proto2.TestAllTypesProto2') {\n try {\n const testMessage =\n TestAllTypesProto2.deserialize(request.getProtobufPayload());\n response.setProtobufPayload(testMessage.serialize());\n } catch (err) {\n response.setParseError(err.toString());\n }\n } else if (\n request.getMessageType() ===\n 'protobuf_test_messages.proto3.TestAllTypesProto3') {\n try {\n const testMessage =\n TestAllTypesProto3.deserialize(request.getProtobufPayload());\n response.setProtobufPayload(testMessage.serialize());\n } catch (err) {\n response.setParseError(err.toString());\n }\n } else {\n throw new Error(\n `Payload message not supported: ${request.getMessageType()}.`);\n }\n\n return response;\n}\n\n/**\n * Same as doTest, but both request and response are in base64.\n * @param {string} base64Request\n * @return {string} response\n */\nfunction runConformanceTest(base64Request) {\n const request =\n ConformanceRequest.deserialize(\n base64.decodeStringToUint8Array(base64Request).buffer);\n const response = doTest(request);\n return base64.encodeByteArray(new Uint8Array(response.serialize()));\n}\n\n// Needed for node test\nexports.doTest = doTest;\n// Needed for browser test\ngoog.exportSymbol('runConformanceTest', runConformanceTest);\n"},"repo_name":{"kind":"string","value":"nwjs/chromium.src"},"path":{"kind":"string","value":"third_party/protobuf/js/experimental/runtime/kernel/conformance/conformance_testee.js"},"language":{"kind":"string","value":"JavaScript"},"license":{"kind":"string","value":"bsd-3-clause"},"size":{"kind":"number","value":3602,"string":"3,602"}}},{"rowIdx":115086030,"cells":{"code":{"kind":"string","value":"require 'spec_helper'\n\nmodule RailsBestPractices::Core\n describe Klasses do\n it { should be_a_kind_of Array }\n\n context \"Klass\" do\n context \"#class_name\" do\n it \"gets class name without module\" do\n klass = Klass.new(\"BlogPost\", \"Post\", [])\n expect(klass.class_name).to eq(\"BlogPost\")\n end\n\n it \"gets class name with moduel\" do\n klass = Klass.new(\"BlogPost\", \"Post\", [\"Admin\"])\n expect(klass.class_name).to eq(\"Admin::BlogPost\")\n end\n end\n\n context \"#extend_class_name\" do\n it \"gets extend class name without module\" do\n klass = Klass.new(\"BlogPost\", \"Post\", [])\n expect(klass.extend_class_name).to eq(\"Post\")\n end\n\n it \"gets extend class name with module\" do\n klass = Klass.new(\"BlogPost\", \"Post\", [\"Admin\"])\n expect(klass.extend_class_name).to eq(\"Admin::Post\")\n end\n end\n\n it \"gets to_s equal to class_name\" do\n klass = Klass.new(\"BlogPost\", \"Post\", [\"Admin\"])\n expect(klass.to_s).to eq(klass.class_name)\n end\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"eprislac/guard-yard"},"path":{"kind":"string","value":"vendor/jruby/1.9/gems/rails_best_practices-1.15.7/spec/rails_best_practices/core/klasses_spec.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1109,"string":"1,109"}}},{"rowIdx":115086031,"cells":{"code":{"kind":"string","value":"// ==++==\n// \n// Copyright (c) Microsoft Corporation. All rights reserved.\n// \n// ==--==\n/*=============================================================================\n**\n** Class: ArithmeticException\n**\n**\n** Purpose: Exception class for bad arithmetic conditions!\n**\n**\n=============================================================================*/\n\nnamespace System {\n \n using System;\n using System.Runtime.Serialization;\n // The ArithmeticException is thrown when overflow or underflow\n // occurs.\n // \n[System.Runtime.InteropServices.ComVisible(true)]\n [Serializable] public class ArithmeticException : SystemException\n { \n // Creates a new ArithmeticException with its message string set to\n // the empty string, its HRESULT set to COR_E_ARITHMETIC, \n // and its ExceptionInfo reference set to null. \n public ArithmeticException() \n : base(Environment.GetResourceString(\"Arg_ArithmeticException\")) {\n SetErrorCode(__HResults.COR_E_ARITHMETIC);\n }\n \n // Creates a new ArithmeticException with its message string set to\n // message, its HRESULT set to COR_E_ARITHMETIC, \n // and its ExceptionInfo reference set to null. \n // \n public ArithmeticException(String message) \n : base(message) {\n SetErrorCode(__HResults.COR_E_ARITHMETIC);\n }\n \n public ArithmeticException(String message, Exception innerException) \n : base(message, innerException) {\n SetErrorCode(__HResults.COR_E_ARITHMETIC);\n }\n\n protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) {\n }\n\n }\n\n}\n"},"repo_name":{"kind":"string","value":"sekcheong/referencesource"},"path":{"kind":"string","value":"mscorlib/system/arithmeticexception.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":1736,"string":"1,736"}}},{"rowIdx":115086032,"cells":{"code":{"kind":"string","value":"#include \"cache.h\"\n#include \"tree.h\"\n#include \"tree-walk.h\"\n#include \"cache-tree.h\"\n\n#ifndef DEBUG\n#define DEBUG 0\n#endif\n\nstruct cache_tree *cache_tree(void)\n{\n\tstruct cache_tree *it = xcalloc(1, sizeof(struct cache_tree));\n\tit->entry_count = -1;\n\treturn it;\n}\n\nvoid cache_tree_free(struct cache_tree **it_p)\n{\n\tint i;\n\tstruct cache_tree *it = *it_p;\n\n\tif (!it)\n\t\treturn;\n\tfor (i = 0; i < it->subtree_nr; i++)\n\t\tif (it->down[i]) {\n\t\t\tcache_tree_free(&it->down[i]->cache_tree);\n\t\t\tfree(it->down[i]);\n\t\t}\n\tfree(it->down);\n\tfree(it);\n\t*it_p = NULL;\n}\n\nstatic int subtree_name_cmp(const char *one, int onelen,\n\t\t\t const char *two, int twolen)\n{\n\tif (onelen < twolen)\n\t\treturn -1;\n\tif (twolen < onelen)\n\t\treturn 1;\n\treturn memcmp(one, two, onelen);\n}\n\nstatic int subtree_pos(struct cache_tree *it, const char *path, int pathlen)\n{\n\tstruct cache_tree_sub **down = it->down;\n\tint lo, hi;\n\tlo = 0;\n\thi = it->subtree_nr;\n\twhile (lo < hi) {\n\t\tint mi = (lo + hi) / 2;\n\t\tstruct cache_tree_sub *mdl = down[mi];\n\t\tint cmp = subtree_name_cmp(path, pathlen,\n\t\t\t\t\t mdl->name, mdl->namelen);\n\t\tif (!cmp)\n\t\t\treturn mi;\n\t\tif (cmp < 0)\n\t\t\thi = mi;\n\t\telse\n\t\t\tlo = mi + 1;\n\t}\n\treturn -lo-1;\n}\n\nstatic struct cache_tree_sub *find_subtree(struct cache_tree *it,\n\t\t\t\t\t const char *path,\n\t\t\t\t\t int pathlen,\n\t\t\t\t\t int create)\n{\n\tstruct cache_tree_sub *down;\n\tint pos = subtree_pos(it, path, pathlen);\n\tif (0 <= pos)\n\t\treturn it->down[pos];\n\tif (!create)\n\t\treturn NULL;\n\n\tpos = -pos-1;\n\tif (it->subtree_alloc <= it->subtree_nr) {\n\t\tit->subtree_alloc = alloc_nr(it->subtree_alloc);\n\t\tit->down = xrealloc(it->down, it->subtree_alloc *\n\t\t\t\t sizeof(*it->down));\n\t}\n\tit->subtree_nr++;\n\n\tdown = xmalloc(sizeof(*down) + pathlen + 1);\n\tdown->cache_tree = NULL;\n\tdown->namelen = pathlen;\n\tmemcpy(down->name, path, pathlen);\n\tdown->name[pathlen] = 0;\n\n\tif (pos < it->subtree_nr)\n\t\tmemmove(it->down + pos + 1,\n\t\t\tit->down + pos,\n\t\t\tsizeof(down) * (it->subtree_nr - pos - 1));\n\tit->down[pos] = down;\n\treturn down;\n}\n\nstruct cache_tree_sub *cache_tree_sub(struct cache_tree *it, const char *path)\n{\n\tint pathlen = strlen(path);\n\treturn find_subtree(it, path, pathlen, 1);\n}\n\nvoid cache_tree_invalidate_path(struct cache_tree *it, const char *path)\n{\n\t/* a/b/c\n\t * ==> invalidate self\n\t * ==> find \"a\", have it invalidate \"b/c\"\n\t * a\n\t * ==> invalidate self\n\t * ==> if \"a\" exists as a subtree, remove it.\n\t */\n\tconst char *slash;\n\tint namelen;\n\tstruct cache_tree_sub *down;\n\n#if DEBUG\n\tfprintf(stderr, \"cache-tree invalidate <%s>\\n\", path);\n#endif\n\n\tif (!it)\n\t\treturn;\n\tslash = strchr(path, '/');\n\tit->entry_count = -1;\n\tif (!slash) {\n\t\tint pos;\n\t\tnamelen = strlen(path);\n\t\tpos = subtree_pos(it, path, namelen);\n\t\tif (0 <= pos) {\n\t\t\tcache_tree_free(&it->down[pos]->cache_tree);\n\t\t\tfree(it->down[pos]);\n\t\t\t/* 0 1 2 3 4 5\n\t\t\t * ^ ^subtree_nr = 6\n\t\t\t * pos\n\t\t\t * move 4 and 5 up one place (2 entries)\n\t\t\t * 2 = 6 - 3 - 1 = subtree_nr - pos - 1\n\t\t\t */\n\t\t\tmemmove(it->down+pos, it->down+pos+1,\n\t\t\t\tsizeof(struct cache_tree_sub *) *\n\t\t\t\t(it->subtree_nr - pos - 1));\n\t\t\tit->subtree_nr--;\n\t\t}\n\t\treturn;\n\t}\n\tnamelen = slash - path;\n\tdown = find_subtree(it, path, namelen, 0);\n\tif (down)\n\t\tcache_tree_invalidate_path(down->cache_tree, slash + 1);\n}\n\nstatic int verify_cache(struct cache_entry **cache,\n\t\t\tint entries, int flags)\n{\n\tint i, funny;\n\tint silent = flags & WRITE_TREE_SILENT;\n\n\t/* Verify that the tree is merged */\n\tfunny = 0;\n\tfor (i = 0; i < entries; i++) {\n\t\tstruct cache_entry *ce = cache[i];\n\t\tif (ce_stage(ce)) {\n\t\t\tif (silent)\n\t\t\t\treturn -1;\n\t\t\tif (10 < ++funny) {\n\t\t\t\tfprintf(stderr, \"...\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfprintf(stderr, \"%s: unmerged (%s)\\n\",\n\t\t\t\tce->name, sha1_to_hex(ce->sha1));\n\t\t}\n\t}\n\tif (funny)\n\t\treturn -1;\n\n\t/* Also verify that the cache does not have path and path/file\n\t * at the same time. At this point we know the cache has only\n\t * stage 0 entries.\n\t */\n\tfunny = 0;\n\tfor (i = 0; i < entries - 1; i++) {\n\t\t/* path/file always comes after path because of the way\n\t\t * the cache is sorted. Also path can appear only once,\n\t\t * which means conflicting one would immediately follow.\n\t\t */\n\t\tconst char *this_name = cache[i]->name;\n\t\tconst char *next_name = cache[i+1]->name;\n\t\tint this_len = strlen(this_name);\n\t\tif (this_len < strlen(next_name) &&\n\t\t strncmp(this_name, next_name, this_len) == 0 &&\n\t\t next_name[this_len] == '/') {\n\t\t\tif (10 < ++funny) {\n\t\t\t\tfprintf(stderr, \"...\\n\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfprintf(stderr, \"You have both %s and %s\\n\",\n\t\t\t\tthis_name, next_name);\n\t\t}\n\t}\n\tif (funny)\n\t\treturn -1;\n\treturn 0;\n}\n\nstatic void discard_unused_subtrees(struct cache_tree *it)\n{\n\tstruct cache_tree_sub **down = it->down;\n\tint nr = it->subtree_nr;\n\tint dst, src;\n\tfor (dst = src = 0; src < nr; src++) {\n\t\tstruct cache_tree_sub *s = down[src];\n\t\tif (s->used)\n\t\t\tdown[dst++] = s;\n\t\telse {\n\t\t\tcache_tree_free(&s->cache_tree);\n\t\t\tfree(s);\n\t\t\tit->subtree_nr--;\n\t\t}\n\t}\n}\n\nint cache_tree_fully_valid(struct cache_tree *it)\n{\n\tint i;\n\tif (!it)\n\t\treturn 0;\n\tif (it->entry_count < 0 || !has_sha1_file(it->sha1))\n\t\treturn 0;\n\tfor (i = 0; i < it->subtree_nr; i++) {\n\t\tif (!cache_tree_fully_valid(it->down[i]->cache_tree))\n\t\t\treturn 0;\n\t}\n\treturn 1;\n}\n\nstatic int update_one(struct cache_tree *it,\n\t\t struct cache_entry **cache,\n\t\t int entries,\n\t\t const char *base,\n\t\t int baselen,\n\t\t int *skip_count,\n\t\t int flags)\n{\n\tstruct strbuf buffer;\n\tint missing_ok = flags & WRITE_TREE_MISSING_OK;\n\tint dryrun = flags & WRITE_TREE_DRY_RUN;\n\tint to_invalidate = 0;\n\tint i;\n\n\t*skip_count = 0;\n\n\tif (0 <= it->entry_count && has_sha1_file(it->sha1))\n\t\treturn it->entry_count;\n\n\t/*\n\t * We first scan for subtrees and update them; we start by\n\t * marking existing subtrees -- the ones that are unmarked\n\t * should not be in the result.\n\t */\n\tfor (i = 0; i < it->subtree_nr; i++)\n\t\tit->down[i]->used = 0;\n\n\t/*\n\t * Find the subtrees and update them.\n\t */\n\ti = 0;\n\twhile (i < entries) {\n\t\tstruct cache_entry *ce = cache[i];\n\t\tstruct cache_tree_sub *sub;\n\t\tconst char *path, *slash;\n\t\tint pathlen, sublen, subcnt, subskip;\n\n\t\tpath = ce->name;\n\t\tpathlen = ce_namelen(ce);\n\t\tif (pathlen <= baselen || memcmp(base, path, baselen))\n\t\t\tbreak; /* at the end of this level */\n\n\t\tslash = strchr(path + baselen, '/');\n\t\tif (!slash) {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\t/*\n\t\t * a/bbb/c (base = a/, slash = /c)\n\t\t * ==>\n\t\t * path+baselen = bbb/c, sublen = 3\n\t\t */\n\t\tsublen = slash - (path + baselen);\n\t\tsub = find_subtree(it, path + baselen, sublen, 1);\n\t\tif (!sub->cache_tree)\n\t\t\tsub->cache_tree = cache_tree();\n\t\tsubcnt = update_one(sub->cache_tree,\n\t\t\t\t cache + i, entries - i,\n\t\t\t\t path,\n\t\t\t\t baselen + sublen + 1,\n\t\t\t\t &subskip,\n\t\t\t\t flags);\n\t\tif (subcnt < 0)\n\t\t\treturn subcnt;\n\t\ti += subcnt;\n\t\tsub->count = subcnt; /* to be used in the next loop */\n\t\t*skip_count += subskip;\n\t\tsub->used = 1;\n\t}\n\n\tdiscard_unused_subtrees(it);\n\n\t/*\n\t * Then write out the tree object for this level.\n\t */\n\tstrbuf_init(&buffer, 8192);\n\n\ti = 0;\n\twhile (i < entries) {\n\t\tstruct cache_entry *ce = cache[i];\n\t\tstruct cache_tree_sub *sub;\n\t\tconst char *path, *slash;\n\t\tint pathlen, entlen;\n\t\tconst unsigned char *sha1;\n\t\tunsigned mode;\n\n\t\tpath = ce->name;\n\t\tpathlen = ce_namelen(ce);\n\t\tif (pathlen <= baselen || memcmp(base, path, baselen))\n\t\t\tbreak; /* at the end of this level */\n\n\t\tslash = strchr(path + baselen, '/');\n\t\tif (slash) {\n\t\t\tentlen = slash - (path + baselen);\n\t\t\tsub = find_subtree(it, path + baselen, entlen, 0);\n\t\t\tif (!sub)\n\t\t\t\tdie(\"cache-tree.c: '%.*s' in '%s' not found\",\n\t\t\t\t entlen, path + baselen, path);\n\t\t\ti += sub->count;\n\t\t\tsha1 = sub->cache_tree->sha1;\n\t\t\tmode = S_IFDIR;\n\t\t\tif (sub->cache_tree->entry_count < 0)\n\t\t\t\tto_invalidate = 1;\n\t\t}\n\t\telse {\n\t\t\tsha1 = ce->sha1;\n\t\t\tmode = ce->ce_mode;\n\t\t\tentlen = pathlen - baselen;\n\t\t\ti++;\n\t\t}\n\t\tif (mode != S_IFGITLINK && !missing_ok && !has_sha1_file(sha1)) {\n\t\t\tstrbuf_release(&buffer);\n\t\t\treturn error(\"invalid object %06o %s for '%.*s'\",\n\t\t\t\tmode, sha1_to_hex(sha1), entlen+baselen, path);\n\t\t}\n\n\t\t/*\n\t\t * CE_REMOVE entries are removed before the index is\n\t\t * written to disk. Skip them to remain consistent\n\t\t * with the future on-disk index.\n\t\t */\n\t\tif (ce->ce_flags & CE_REMOVE) {\n\t\t\t*skip_count = *skip_count + 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t/*\n\t\t * CE_INTENT_TO_ADD entries exist on on-disk index but\n\t\t * they are not part of generated trees. Invalidate up\n\t\t * to root to force cache-tree users to read elsewhere.\n\t\t */\n\t\tif (ce->ce_flags & CE_INTENT_TO_ADD) {\n\t\t\tto_invalidate = 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\tstrbuf_grow(&buffer, entlen + 100);\n\t\tstrbuf_addf(&buffer, \"%o %.*s%c\", mode, entlen, path + baselen, '\\0');\n\t\tstrbuf_add(&buffer, sha1, 20);\n\n#if DEBUG\n\t\tfprintf(stderr, \"cache-tree update-one %o %.*s\\n\",\n\t\t\tmode, entlen, path + baselen);\n#endif\n\t}\n\n\tif (dryrun)\n\t\thash_sha1_file(buffer.buf, buffer.len, tree_type, it->sha1);\n\telse if (write_sha1_file(buffer.buf, buffer.len, tree_type, it->sha1)) {\n\t\tstrbuf_release(&buffer);\n\t\treturn -1;\n\t}\n\n\tstrbuf_release(&buffer);\n\tit->entry_count = to_invalidate ? -1 : i - *skip_count;\n#if DEBUG\n\tfprintf(stderr, \"cache-tree update-one (%d ent, %d subtree) %s\\n\",\n\t\tit->entry_count, it->subtree_nr,\n\t\tsha1_to_hex(it->sha1));\n#endif\n\treturn i;\n}\n\nint cache_tree_update(struct cache_tree *it,\n\t\t struct cache_entry **cache,\n\t\t int entries,\n\t\t int flags)\n{\n\tint i, skip;\n\ti = verify_cache(cache, entries, flags);\n\tif (i)\n\t\treturn i;\n\ti = update_one(it, cache, entries, \"\", 0, &skip, flags);\n\tif (i < 0)\n\t\treturn i;\n\treturn 0;\n}\n\nstatic void write_one(struct strbuf *buffer, struct cache_tree *it,\n const char *path, int pathlen)\n{\n\tint i;\n\n\t/* One \"cache-tree\" entry consists of the following:\n\t * path (NUL terminated)\n\t * entry_count, subtree_nr (\"%d %d\\n\")\n\t * tree-sha1 (missing if invalid)\n\t * subtree_nr \"cache-tree\" entries for subtrees.\n\t */\n\tstrbuf_grow(buffer, pathlen + 100);\n\tstrbuf_add(buffer, path, pathlen);\n\tstrbuf_addf(buffer, \"%c%d %d\\n\", 0, it->entry_count, it->subtree_nr);\n\n#if DEBUG\n\tif (0 <= it->entry_count)\n\t\tfprintf(stderr, \"cache-tree <%.*s> (%d ent, %d subtree) %s\\n\",\n\t\t\tpathlen, path, it->entry_count, it->subtree_nr,\n\t\t\tsha1_to_hex(it->sha1));\n\telse\n\t\tfprintf(stderr, \"cache-tree <%.*s> (%d subtree) invalid\\n\",\n\t\t\tpathlen, path, it->subtree_nr);\n#endif\n\n\tif (0 <= it->entry_count) {\n\t\tstrbuf_add(buffer, it->sha1, 20);\n\t}\n\tfor (i = 0; i < it->subtree_nr; i++) {\n\t\tstruct cache_tree_sub *down = it->down[i];\n\t\tif (i) {\n\t\t\tstruct cache_tree_sub *prev = it->down[i-1];\n\t\t\tif (subtree_name_cmp(down->name, down->namelen,\n\t\t\t\t\t prev->name, prev->namelen) <= 0)\n\t\t\t\tdie(\"fatal - unsorted cache subtree\");\n\t\t}\n\t\twrite_one(buffer, down->cache_tree, down->name, down->namelen);\n\t}\n}\n\nvoid cache_tree_write(struct strbuf *sb, struct cache_tree *root)\n{\n\twrite_one(sb, root, \"\", 0);\n}\n\nstatic struct cache_tree *read_one(const char **buffer, unsigned long *size_p)\n{\n\tconst char *buf = *buffer;\n\tunsigned long size = *size_p;\n\tconst char *cp;\n\tchar *ep;\n\tstruct cache_tree *it;\n\tint i, subtree_nr;\n\n\tit = NULL;\n\t/* skip name, but make sure name exists */\n\twhile (size && *buf) {\n\t\tsize--;\n\t\tbuf++;\n\t}\n\tif (!size)\n\t\tgoto free_return;\n\tbuf++; size--;\n\tit = cache_tree();\n\n\tcp = buf;\n\tit->entry_count = strtol(cp, &ep, 10);\n\tif (cp == ep)\n\t\tgoto free_return;\n\tcp = ep;\n\tsubtree_nr = strtol(cp, &ep, 10);\n\tif (cp == ep)\n\t\tgoto free_return;\n\twhile (size && *buf && *buf != '\\n') {\n\t\tsize--;\n\t\tbuf++;\n\t}\n\tif (!size)\n\t\tgoto free_return;\n\tbuf++; size--;\n\tif (0 <= it->entry_count) {\n\t\tif (size < 20)\n\t\t\tgoto free_return;\n\t\thashcpy(it->sha1, (const unsigned char*)buf);\n\t\tbuf += 20;\n\t\tsize -= 20;\n\t}\n\n#if DEBUG\n\tif (0 <= it->entry_count)\n\t\tfprintf(stderr, \"cache-tree <%s> (%d ent, %d subtree) %s\\n\",\n\t\t\t*buffer, it->entry_count, subtree_nr,\n\t\t\tsha1_to_hex(it->sha1));\n\telse\n\t\tfprintf(stderr, \"cache-tree <%s> (%d subtrees) invalid\\n\",\n\t\t\t*buffer, subtree_nr);\n#endif\n\n\t/*\n\t * Just a heuristic -- we do not add directories that often but\n\t * we do not want to have to extend it immediately when we do,\n\t * hence +2.\n\t */\n\tit->subtree_alloc = subtree_nr + 2;\n\tit->down = xcalloc(it->subtree_alloc, sizeof(struct cache_tree_sub *));\n\tfor (i = 0; i < subtree_nr; i++) {\n\t\t/* read each subtree */\n\t\tstruct cache_tree *sub;\n\t\tstruct cache_tree_sub *subtree;\n\t\tconst char *name = buf;\n\n\t\tsub = read_one(&buf, &size);\n\t\tif (!sub)\n\t\t\tgoto free_return;\n\t\tsubtree = cache_tree_sub(it, name);\n\t\tsubtree->cache_tree = sub;\n\t}\n\tif (subtree_nr != it->subtree_nr)\n\t\tdie(\"cache-tree: internal error\");\n\t*buffer = buf;\n\t*size_p = size;\n\treturn it;\n\n free_return:\n\tcache_tree_free(&it);\n\treturn NULL;\n}\n\nstruct cache_tree *cache_tree_read(const char *buffer, unsigned long size)\n{\n\tif (buffer[0])\n\t\treturn NULL; /* not the whole tree */\n\treturn read_one(&buffer, &size);\n}\n\nstatic struct cache_tree *cache_tree_find(struct cache_tree *it, const char *path)\n{\n\tif (!it)\n\t\treturn NULL;\n\twhile (*path) {\n\t\tconst char *slash;\n\t\tstruct cache_tree_sub *sub;\n\n\t\tslash = strchr(path, '/');\n\t\tif (!slash)\n\t\t\tslash = path + strlen(path);\n\t\t/* between path and slash is the name of the\n\t\t * subtree to look for.\n\t\t */\n\t\tsub = find_subtree(it, path, slash - path, 0);\n\t\tif (!sub)\n\t\t\treturn NULL;\n\t\tit = sub->cache_tree;\n\t\tif (slash)\n\t\t\twhile (*slash && *slash == '/')\n\t\t\t\tslash++;\n\t\tif (!slash || !*slash)\n\t\t\treturn it; /* prefix ended with slashes */\n\t\tpath = slash;\n\t}\n\treturn it;\n}\n\nint write_cache_as_tree(unsigned char *sha1, int flags, const char *prefix)\n{\n\tint entries, was_valid, newfd;\n\tstruct lock_file *lock_file;\n\n\t/*\n\t * We can't free this memory, it becomes part of a linked list\n\t * parsed atexit()\n\t */\n\tlock_file = xcalloc(1, sizeof(struct lock_file));\n\n\tnewfd = hold_locked_index(lock_file, 1);\n\n\tentries = read_cache();\n\tif (entries < 0)\n\t\treturn WRITE_TREE_UNREADABLE_INDEX;\n\tif (flags & WRITE_TREE_IGNORE_CACHE_TREE)\n\t\tcache_tree_free(&(active_cache_tree));\n\n\tif (!active_cache_tree)\n\t\tactive_cache_tree = cache_tree();\n\n\twas_valid = cache_tree_fully_valid(active_cache_tree);\n\tif (!was_valid) {\n\t\tif (cache_tree_update(active_cache_tree,\n\t\t\t\t active_cache, active_nr,\n\t\t\t\t flags) < 0)\n\t\t\treturn WRITE_TREE_UNMERGED_INDEX;\n\t\tif (0 <= newfd) {\n\t\t\tif (!write_cache(newfd, active_cache, active_nr) &&\n\t\t\t !commit_lock_file(lock_file))\n\t\t\t\tnewfd = -1;\n\t\t}\n\t\t/* Not being able to write is fine -- we are only interested\n\t\t * in updating the cache-tree part, and if the next caller\n\t\t * ends up using the old index with unupdated cache-tree part\n\t\t * it misses the work we did here, but that is just a\n\t\t * performance penalty and not a big deal.\n\t\t */\n\t}\n\n\tif (prefix) {\n\t\tstruct cache_tree *subtree =\n\t\t\tcache_tree_find(active_cache_tree, prefix);\n\t\tif (!subtree)\n\t\t\treturn WRITE_TREE_PREFIX_ERROR;\n\t\thashcpy(sha1, subtree->sha1);\n\t}\n\telse\n\t\thashcpy(sha1, active_cache_tree->sha1);\n\n\tif (0 <= newfd)\n\t\trollback_lock_file(lock_file);\n\n\treturn 0;\n}\n\nstatic void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree)\n{\n\tstruct tree_desc desc;\n\tstruct name_entry entry;\n\tint cnt;\n\n\thashcpy(it->sha1, tree->object.sha1);\n\tinit_tree_desc(&desc, tree->buffer, tree->size);\n\tcnt = 0;\n\twhile (tree_entry(&desc, &entry)) {\n\t\tif (!S_ISDIR(entry.mode))\n\t\t\tcnt++;\n\t\telse {\n\t\t\tstruct cache_tree_sub *sub;\n\t\t\tstruct tree *subtree = lookup_tree(entry.sha1);\n\t\t\tif (!subtree->object.parsed)\n\t\t\t\tparse_tree(subtree);\n\t\t\tsub = cache_tree_sub(it, entry.path);\n\t\t\tsub->cache_tree = cache_tree();\n\t\t\tprime_cache_tree_rec(sub->cache_tree, subtree);\n\t\t\tcnt += sub->cache_tree->entry_count;\n\t\t}\n\t}\n\tit->entry_count = cnt;\n}\n\nvoid prime_cache_tree(struct cache_tree **it, struct tree *tree)\n{\n\tcache_tree_free(it);\n\t*it = cache_tree();\n\tprime_cache_tree_rec(*it, tree);\n}\n\n/*\n * find the cache_tree that corresponds to the current level without\n * exploding the full path into textual form. The root of the\n * cache tree is given as \"root\", and our current level is \"info\".\n * (1) When at root level, info->prev is NULL, so it is \"root\" itself.\n * (2) Otherwise, find the cache_tree that corresponds to one level\n * above us, and find ourselves in there.\n */\nstatic struct cache_tree *find_cache_tree_from_traversal(struct cache_tree *root,\n\t\t\t\t\t\t\t struct traverse_info *info)\n{\n\tstruct cache_tree *our_parent;\n\n\tif (!info->prev)\n\t\treturn root;\n\tour_parent = find_cache_tree_from_traversal(root, info->prev);\n\treturn cache_tree_find(our_parent, info->name.path);\n}\n\nint cache_tree_matches_traversal(struct cache_tree *root,\n\t\t\t\t struct name_entry *ent,\n\t\t\t\t struct traverse_info *info)\n{\n\tstruct cache_tree *it;\n\n\tit = find_cache_tree_from_traversal(root, info);\n\tit = cache_tree_find(it, ent->path);\n\tif (it && it->entry_count > 0 && !hashcmp(ent->sha1, it->sha1))\n\t\treturn it->entry_count;\n\treturn 0;\n}\n\nint update_main_cache_tree(int flags)\n{\n\tif (!the_index.cache_tree)\n\t\tthe_index.cache_tree = cache_tree();\n\treturn cache_tree_update(the_index.cache_tree,\n\t\t\t\t the_index.cache, the_index.cache_nr, flags);\n}\n"},"repo_name":{"kind":"string","value":"pniebla/test-repo-console"},"path":{"kind":"string","value":"svn/git-1.8.3.3.tar/git-1.8.3.3/git-1.8.3.3/cache-tree.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":16875,"string":"16,875"}}},{"rowIdx":115086033,"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.DotNet.Build.VstsBuildsApi.Configuration;\nusing Newtonsoft.Json.Linq;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.DotNet.Build.VstsBuildsApi\n{\n internal class VstsReleaseHttpClient : VstsDefinitionHttpClient\n {\n private const string ReleaseApiType = \"release\";\n\n public VstsReleaseHttpClient(JObject definition, VstsApiEndpointConfig config)\n : base(new Uri(definition[\"url\"].ToString()), config, ReleaseApiType)\n {\n }\n\n public override async Task UpdateDefinitionAsync(JObject definition) =>\n await JsonClient.PutAsync(\n GetRequestUri(definition, \"definitions\"),\n definition);\n\n protected override bool IsMatching(JObject localDefinition, JObject retrievedDefinition)\n {\n return localDefinition[\"name\"].ToString() == retrievedDefinition[\"name\"].ToString();\n }\n\n protected override IEnumerable FindObjectsWithIdentifiableProperties(JObject definition)\n {\n IEnumerable environments = definition[\"environments\"].Children();\n\n IEnumerable approvals = environments\n .SelectMany(env => new[] { env[\"preDeployApprovals\"], env[\"postDeployApprovals\"] })\n .SelectMany(approvalWrapper => approvalWrapper[\"approvals\"].Values());\n\n return new[] { definition }\n .Concat(environments)\n .Concat(approvals);\n }\n\n /// \n /// From a url like https://devdiv.vsrm.visualstudio.com/1234/_apis/Release/definitions/1\n /// in the url property of the given definition, gets the project, \"1234\".\n /// \n protected override string GetDefinitionProject(JObject definition)\n {\n return new Uri(definition[\"url\"].ToString()).Segments[1].TrimEnd('/');\n }\n }\n}\n"},"repo_name":{"kind":"string","value":"AlexGhiondea/buildtools"},"path":{"kind":"string","value":"src/Microsoft.DotNet.Build.VstsBuildsApi/VstsReleaseHttpClient.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":2198,"string":"2,198"}}},{"rowIdx":115086034,"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\n// Add any internal types that we need to forward from mscorlib. \n\n// These types are required for Desktop to Core serialization as they are not covered by GenAPI because they are marked as internal.\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.CultureAwareComparer))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.OrdinalComparer))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.GenericEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NullableEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ObjectEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.NonRandomizedStringEqualityComparer))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ByteEqualityComparer))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.EnumEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.SByteEnumEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ShortEnumEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.LongEnumEqualityComparer<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.ListDictionaryInternal))]\n\n// This is temporary as we are building the mscorlib shim against netfx461 which doesn't contain ValueTuples.\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,>))]\n[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple<,,,,,,,>))]\n"},"repo_name":{"kind":"string","value":"nbarbettini/corefx"},"path":{"kind":"string","value":"src/shims/manual/mscorlib.forwards.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3065,"string":"3,065"}}},{"rowIdx":115086035,"cells":{"code":{"kind":"string","value":"require 'spec_helper'\n\ndescribe 'logrotate::rule' do\n context 'with an alphanumeric title' do\n let(:title) { 'test' }\n\n context 'and ensure => absent' do\n let(:params) { {:ensure => 'absent'} }\n\n it do\n should contain_file('/etc/logrotate.d/test').with_ensure('absent')\n end\n end\n\n let(:params) { {:path => '/var/log/foo.log'} }\n it do\n should contain_class('logrotate::base')\n should contain_file('/etc/logrotate.d/test').with({\n 'owner' => 'root',\n 'group' => 'root',\n 'ensure' => 'present',\n 'mode' => '0444',\n }).with_content(%r{^/var/log/foo\\.log \\{\\n\\}\\n})\n end\n\n context 'with an array path' do\n let (:params) { {:path => ['/var/log/foo1.log','/var/log/foo2.log']} }\n it do\n should contain_file('/etc/logrotate.d/test').with_content(\n %r{/var/log/foo1\\.log /var/log/foo2\\.log \\{\\n\\}\\n}\n )\n end\n end\n\n ###########################################################################\n # COMPRESS\n context 'and compress => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :compress => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ compress$/)\n end\n end\n\n context 'and compress => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :compress => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nocompress$/)\n end\n end\n\n context 'and compress => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :compress => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /compress must be a boolean/)\n end\n end\n\n ###########################################################################\n # COMPRESSCMD\n context 'and compresscmd => bzip2' do\n let(:params) {\n {:path => '/var/log/foo.log', :compresscmd => 'bzip2'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ compresscmd bzip2$/)\n end\n end\n\n ###########################################################################\n # COMPRESSEXT\n context 'and compressext => .bz2' do\n let(:params) {\n {:path => '/var/log/foo.log', :compressext => '.bz2'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ compressext .bz2$/)\n end\n end\n\n ###########################################################################\n # COMPRESSOPTIONS\n context 'and compressoptions => -9' do\n let(:params) {\n {:path => '/var/log/foo.log', :compressoptions => '-9'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ compressoptions -9$/)\n end\n end\n\n ###########################################################################\n # COPY\n context 'and copy => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :copy => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test').with_content(/^ copy$/)\n end\n end\n\n context 'and copy => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :copy => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test').with_content(/^ nocopy$/)\n end\n end\n\n context 'and copy => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :copy => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /copy must be a boolean/)\n end\n end\n\n ###########################################################################\n # COPYTRUNCATE\n context 'and copytruncate => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :copytruncate => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ copytruncate$/)\n end\n end\n\n context 'and copytruncate => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :copytruncate => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nocopytruncate$/)\n end\n end\n\n context 'and copytruncate => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :copytruncate => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /copytruncate must be a boolean/)\n end\n end\n\n ###########################################################################\n # CREATE / CREATE_MODE / CREATE_OWNER / CREATE_GROUP\n context 'and create => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :create => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ create$/)\n end\n\n context 'and create_mode => 0777' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => true,\n :create_mode => '0777',\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ create 0777$/)\n end\n\n context 'and create_owner => www-data' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => true,\n :create_mode => '0777',\n :create_owner => 'www-data',\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ create 0777 www-data/)\n end\n\n context 'and create_group => admin' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => true,\n :create_mode => '0777',\n :create_owner => 'www-data',\n :create_group => 'admin',\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ create 0777 www-data admin$/)\n end\n end\n end\n\n context 'and create_group => admin' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => true,\n :create_mode => '0777',\n :create_group => 'admin',\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /create_group requires create_owner/)\n end\n end\n end\n\n context 'and create_owner => www-data' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => true,\n :create_owner => 'www-data',\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /create_owner requires create_mode/)\n end\n end\n end\n\n context 'and create => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :create => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nocreate$/)\n end\n\n context 'and create_mode => 0777' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :create => false,\n :create_mode => '0777',\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /create_mode requires create/)\n end\n end\n end\n\n context 'and create => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :create => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /create must be a boolean/)\n end\n end\n\n ###########################################################################\n # DATEEXT\n context 'and dateext => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :dateext => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ dateext$/)\n end\n end\n\n context 'and dateext => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :dateext => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nodateext$/)\n end\n end\n\n context 'and dateext => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :dateext => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /dateext must be a boolean/)\n end\n end\n\n ###########################################################################\n # DATEFORMAT\n context 'and dateformat => -%Y%m%d' do\n let(:params) {\n {:path => '/var/log/foo.log', :dateformat => '-%Y%m%d'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ dateformat -%Y%m%d$/)\n end\n end\n\n ###########################################################################\n # DELAYCOMPRESS\n context 'and delaycompress => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :delaycompress => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ delaycompress$/)\n end\n end\n\n context 'and delaycompress => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :delaycompress => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nodelaycompress$/)\n end\n end\n\n context 'and delaycompress => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :delaycompress => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /delaycompress must be a boolean/)\n end\n end\n\n ###########################################################################\n # EXTENSION\n context 'and extension => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :extension => '.foo'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ extension \\.foo$/)\n end\n end\n\n ###########################################################################\n # IFEMPTY\n context 'and ifempty => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :ifempty => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ ifempty$/)\n end\n end\n\n context 'and ifempty => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :ifempty => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ notifempty$/)\n end\n end\n\n context 'and ifempty => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :ifempty => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /ifempty must be a boolean/)\n end\n end\n\n ###########################################################################\n # MAIL / MAILFIRST / MAILLAST\n context 'and mail => test.example.com' do\n let(:params) {\n {:path => '/var/log/foo.log', :mail => 'test@example.com'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ mail test@example.com$/)\n end\n\n context 'and mailfirst => true' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :mail => 'test@example.com',\n :mailfirst => true,\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ mailfirst$/)\n end\n\n context 'and maillast => true' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :mail => 'test@example.com',\n :mailfirst => true,\n :maillast => true,\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /set both mailfirst and maillast/)\n end\n end\n end\n\n context 'and maillast => true' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :mail => 'test@example.com',\n :maillast => true,\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ maillast$/)\n end\n end\n end\n\n context 'and mail => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :mail => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nomail$/)\n end\n end\n\n ###########################################################################\n # MAXAGE\n context 'and maxage => 3' do\n let(:params) {\n {:path => '/var/log/foo.log', :maxage => 3}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ maxage 3$/)\n end\n end\n\n context 'and maxage => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :maxage => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /maxage must be an integer/)\n end\n end\n\n ###########################################################################\n # MINSIZE\n context 'and minsize => 100' do\n let(:params) {\n {:path => '/var/log/foo.log', :minsize => 100}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ minsize 100$/)\n end\n end\n\n context 'and minsize => 100k' do\n let(:params) {\n {:path => '/var/log/foo.log', :minsize => '100k'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ minsize 100k$/)\n end\n end\n\n context 'and minsize => 100M' do\n let(:params) {\n {:path => '/var/log/foo.log', :minsize => '100M'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ minsize 100M$/)\n end\n end\n\n context 'and minsize => 100G' do\n let(:params) {\n {:path => '/var/log/foo.log', :minsize => '100G'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ minsize 100G$/)\n end\n end\n\n context 'and minsize => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :minsize => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /minsize must match/)\n end\n end\n\n ###########################################################################\n # MISSINGOK\n context 'and missingok => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :missingok => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ missingok$/)\n end\n end\n\n context 'and missingok => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :missingok => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nomissingok$/)\n end\n end\n\n context 'and missingok => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :missingok => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /missingok must be a boolean/)\n end\n end\n\n ###########################################################################\n # OLDDIR\n context 'and olddir => /var/log/old' do\n let(:params) {\n {:path => '/var/log/foo.log', :olddir => '/var/log/old'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ olddir \\/var\\/log\\/old$/)\n end\n end\n\n context 'and olddir => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :olddir => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ noolddir$/)\n end\n end\n\n ###########################################################################\n # POSTROTATE\n context 'and postrotate => /bin/true' do\n let(:params) {\n {:path => '/var/log/foo.log', :postrotate => '/bin/true'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/postrotate\\n \\/bin\\/true\\n endscript/)\n end\n end\n\n context \"and postrotate => ['/bin/true', '/bin/false']\" do\n let(:params) {\n {:path => '/var/log/foo.log', :postrotate => ['/bin/true', '/bin/false']}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/postrotate\\n \\/bin\\/true\\n \\/bin\\/false\\n endscript/)\n end\n end\n\n ###########################################################################\n # PREROTATE\n context 'and prerotate => /bin/true' do\n let(:params) {\n {:path => '/var/log/foo.log', :prerotate => '/bin/true'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/prerotate\\n \\/bin\\/true\\n endscript/)\n end\n end\n\n context \"and prerotate => ['/bin/true', '/bin/false']\" do\n let(:params) {\n {:path => '/var/log/foo.log', :prerotate => ['/bin/true', '/bin/false']}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/prerotate\\n \\/bin\\/true\\n \\/bin\\/false\\n endscript/)\n end\n end\n\n ###########################################################################\n # FIRSTACTION\n context 'and firstaction => /bin/true' do\n let(:params) {\n {:path => '/var/log/foo.log', :firstaction => '/bin/true'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/firstaction\\n \\/bin\\/true\\n endscript/)\n end\n end\n\n context \"and firstaction => ['/bin/true', '/bin/false']\" do\n let(:params) {\n {:path => '/var/log/foo.log', :firstaction => ['/bin/true', '/bin/false']}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/firstaction\\n \\/bin\\/true\\n \\/bin\\/false\\n endscript/)\n end\n end\n\n ###########################################################################\n # LASTACTION\n context 'and lastaction => /bin/true' do\n let(:params) {\n {:path => '/var/log/foo.log', :lastaction => '/bin/true'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/lastaction\\n \\/bin\\/true\\n endscript/)\n end\n end\n\n context \"and lastaction => ['/bin/true', '/bin/false']\" do\n let(:params) {\n {:path => '/var/log/foo.log', :lastaction => ['/bin/true', '/bin/false']}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/lastaction\\n \\/bin\\/true\\n \\/bin\\/false\\n endscript/)\n end\n end\n\n ###########################################################################\n # ROTATE\n context 'and rotate => 3' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate => 3}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ rotate 3$/)\n end\n end\n\n context 'and rotate => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /rotate must be an integer/)\n end\n end\n\n ###########################################################################\n # ROTATE_EVERY\n context 'and rotate_every => hour' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'hour'}\n }\n\n it { should contain_class('logrotate::hourly') }\n it { should contain_file('/etc/logrotate.d/hourly/test') }\n it { should contain_file('/etc/logrotate.d/test').with_ensure('absent') }\n end\n\n context 'and rotate_every => day' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'day'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ daily$/)\n end\n\n it do\n should contain_file('/etc/logrotate.d/hourly/test') \\\n .with_ensure('absent')\n end\n end\n\n context 'and rotate_every => week' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'week'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ weekly$/)\n end\n\n it do\n should contain_file('/etc/logrotate.d/hourly/test') \\\n .with_ensure('absent')\n end\n end\n\n context 'and rotate_every => month' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'month'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ monthly$/)\n end\n\n it do\n should contain_file('/etc/logrotate.d/hourly/test') \\\n .with_ensure('absent')\n end\n end\n\n context 'and rotate_every => year' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'year'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ yearly$/)\n end\n\n it do\n should contain_file('/etc/logrotate.d/hourly/test') \\\n .with_ensure('absent')\n end\n end\n\n context 'and rotate_every => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :rotate_every => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /invalid rotate_every value/)\n end\n end\n\n ###########################################################################\n # SIZE\n context 'and size => 100' do\n let(:params) {\n {:path => '/var/log/foo.log', :size => 100}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ size 100$/)\n end\n end\n\n context 'and size => 100k' do\n let(:params) {\n {:path => '/var/log/foo.log', :size => '100k'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ size 100k$/)\n end\n end\n\n context 'and size => 100M' do\n let(:params) {\n {:path => '/var/log/foo.log', :size => '100M'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ size 100M$/)\n end\n end\n\n context 'and size => 100G' do\n let(:params) {\n {:path => '/var/log/foo.log', :size => '100G'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ size 100G$/)\n end\n end\n\n context 'and size => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :size => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /size must match/)\n end\n end\n\n ###########################################################################\n # SHAREDSCRIPTS\n context 'and sharedscripts => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :sharedscripts => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ sharedscripts$/)\n end\n end\n\n context 'and sharedscripts => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :sharedscripts => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ nosharedscripts$/)\n end\n end\n\n context 'and sharedscripts => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :sharedscripts => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /sharedscripts must be a boolean/)\n end\n end\n\n ###########################################################################\n # SHRED / SHREDCYCLES\n context 'and shred => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :shred => true}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ shred$/)\n end\n\n context 'and shredcycles => 3' do\n let(:params) {\n {:path => '/var/log/foo.log', :shred => true, :shredcycles => 3}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ shredcycles 3$/)\n end\n end\n\n context 'and shredcycles => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :shred => true, :shredcycles => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /shredcycles must be an integer/)\n end\n end\n end\n\n context 'and shred => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :shred => false}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ noshred$/)\n end\n end\n\n context 'and shred => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :shred => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /shred must be a boolean/)\n end\n end\n\n ###########################################################################\n # START\n context 'and start => 0' do\n let(:params) {\n {:path => '/var/log/foo.log', :start => 0}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ start 0$/)\n end\n end\n\n context 'and start => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :start => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /start must be an integer/)\n end\n end\n\n ###########################################################################\n # SU / SU_OWNER / SU_GROUP\n context 'and su => true' do\n let(:params) {\n {:path => '/var/log/foo.log', :su => true}\n }\n\n context 'and su_owner => www-data' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :su => true,\n :su_owner => 'www-data',\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ su www-data/)\n end\n\n context 'and su_group => admin' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :su => true,\n :su_owner => 'www-data',\n :su_group => 'admin',\n }\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ su www-data admin$/)\n end\n end\n end\n\n context 'and missing su_owner' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :su => true,\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /su requires su_owner/)\n end\n end\n end\n\n context 'and su => false' do\n let(:params) {\n {:path => '/var/log/foo.log', :su => false}\n }\n\n it do\n should_not contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ su\\s/)\n end\n\n context 'and su_owner => wwww-data' do\n let(:params) {\n {\n :path => '/var/log/foo.log',\n :su => false,\n :su_owner => 'www-data',\n }\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /su_owner requires su/)\n end\n end\n end\n\n context 'and su => foo' do\n let(:params) {\n {:path => '/var/log/foo.log', :su => 'foo'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/test')\n }.to raise_error(Puppet::Error, /su must be a boolean/)\n end\n end\n\n ###########################################################################\n # UNCOMPRESSCMD\n context 'and uncompresscmd => bunzip2' do\n let(:params) {\n {:path => '/var/log/foo.log', :uncompresscmd => 'bunzip2'}\n }\n\n it do\n should contain_file('/etc/logrotate.d/test') \\\n .with_content(/^ uncompresscmd bunzip2$/)\n end\n end\n end\n\n context 'with a non-alphanumeric title' do\n let(:title) { 'foo bar' }\n let(:params) {\n {:path => '/var/log/foo.log'}\n }\n\n it do\n expect {\n should contain_file('/etc/logrotate.d/foo bar')\n }.to raise_error(Puppet::Error, /namevar must be alphanumeric/)\n end\n end\nend\n"},"repo_name":{"kind":"string","value":"MelanieGault/puppet-logrotate"},"path":{"kind":"string","value":"spec/defines/rule_spec.rb"},"language":{"kind":"string","value":"Ruby"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":30362,"string":"30,362"}}},{"rowIdx":115086036,"cells":{"code":{"kind":"string","value":"\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nnamespace Symfony\\Component\\Console\\Tests\\Style;\n\nuse PHPUnit\\Framework\\TestCase;\nuse Symfony\\Component\\Console\\Command\\Command;\nuse Symfony\\Component\\Console\\Formatter\\OutputFormatter;\nuse Symfony\\Component\\Console\\Input\\InputInterface;\nuse Symfony\\Component\\Console\\Output\\ConsoleOutputInterface;\nuse Symfony\\Component\\Console\\Output\\OutputInterface;\nuse Symfony\\Component\\Console\\Style\\SymfonyStyle;\nuse Symfony\\Component\\Console\\Tester\\CommandTester;\n\nclass SymfonyStyleTest extends TestCase\n{\n /** @var Command */\n protected $command;\n /** @var CommandTester */\n protected $tester;\n\n protected function setUp()\n {\n putenv('COLUMNS=121');\n $this->command = new Command('sfstyle');\n $this->tester = new CommandTester($this->command);\n }\n\n protected function tearDown()\n {\n putenv('COLUMNS');\n $this->command = null;\n $this->tester = null;\n }\n\n /**\n * @dataProvider inputCommandToOutputFilesProvider\n */\n public function testOutputs($inputCommandFilepath, $outputFilepath)\n {\n $code = require $inputCommandFilepath;\n $this->command->setCode($code);\n $this->tester->execute(array(), array('interactive' => false, 'decorated' => false));\n $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true));\n }\n\n /**\n * @dataProvider inputInteractiveCommandToOutputFilesProvider\n */\n public function testInteractiveOutputs($inputCommandFilepath, $outputFilepath)\n {\n $code = require $inputCommandFilepath;\n $this->command->setCode($code);\n $this->tester->execute(array(), array('interactive' => true, 'decorated' => false));\n $this->assertStringEqualsFile($outputFilepath, $this->tester->getDisplay(true));\n }\n\n public function inputInteractiveCommandToOutputFilesProvider()\n {\n $baseDir = __DIR__.'/../Fixtures/Style/SymfonyStyle';\n\n return array_map(null, glob($baseDir.'/command/interactive_command_*.php'), glob($baseDir.'/output/interactive_output_*.txt'));\n }\n\n public function inputCommandToOutputFilesProvider()\n {\n $baseDir = __DIR__.'/../Fixtures/Style/SymfonyStyle';\n\n return array_map(null, glob($baseDir.'/command/command_*.php'), glob($baseDir.'/output/output_*.txt'));\n }\n\n public function testGetErrorStyle()\n {\n $input = $this->getMockBuilder(InputInterface::class)->getMock();\n\n $errorOutput = $this->getMockBuilder(OutputInterface::class)->getMock();\n $errorOutput\n ->method('getFormatter')\n ->willReturn(new OutputFormatter());\n $errorOutput\n ->expects($this->once())\n ->method('write');\n\n $output = $this->getMockBuilder(ConsoleOutputInterface::class)->getMock();\n $output\n ->method('getFormatter')\n ->willReturn(new OutputFormatter());\n $output\n ->expects($this->once())\n ->method('getErrorOutput')\n ->willReturn($errorOutput);\n\n $io = new SymfonyStyle($input, $output);\n $io->getErrorStyle()->write('');\n }\n\n public function testGetErrorStyleUsesTheCurrentOutputIfNoErrorOutputIsAvailable()\n {\n $output = $this->getMockBuilder(OutputInterface::class)->getMock();\n $output\n ->method('getFormatter')\n ->willReturn(new OutputFormatter());\n\n $style = new SymfonyStyle($this->getMockBuilder(InputInterface::class)->getMock(), $output);\n\n $this->assertInstanceOf(SymfonyStyle::class, $style->getErrorStyle());\n }\n}\n"},"repo_name":{"kind":"string","value":"Teisi/typo3-deploy"},"path":{"kind":"string","value":"vendor/symfony/console/Tests/Style/SymfonyStyleTest.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":3826,"string":"3,826"}}},{"rowIdx":115086037,"cells":{"code":{"kind":"string","value":"//------------------------------------------------------------\n// Copyright (c) Microsoft Corporation. All rights reserved.\n//------------------------------------------------------------\n\nnamespace System.ServiceModel.Channels\n{\n using System.Threading;\n\n enum AsyncReceiveResult\n {\n Completed,\n Pending,\n }\n\n interface IMessageSource\n {\n AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state);\n Message EndReceive();\n Message Receive(TimeSpan timeout);\n\n AsyncReceiveResult BeginWaitForMessage(TimeSpan timeout, WaitCallback callback, object state);\n bool EndWaitForMessage();\n bool WaitForMessage(TimeSpan timeout);\n }\n}\n"},"repo_name":{"kind":"string","value":"akoeplinger/referencesource"},"path":{"kind":"string","value":"System.ServiceModel/System/ServiceModel/Channels/IMessageSource.cs"},"language":{"kind":"string","value":"C#"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":733,"string":"733"}}},{"rowIdx":115086038,"cells":{"code":{"kind":"string","value":"/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\nimport {Type} from '@angular/core';\nimport {forwardRef, resolveForwardRef} from '@angular/core/src/di';\nimport {describe, expect, it} from '@angular/core/testing/testing_internal';\n\nexport function main() {\n describe('forwardRef', function() {\n it('should wrap and unwrap the reference', () => {\n const ref = forwardRef(() => String);\n expect(ref instanceof Type).toBe(true);\n expect(resolveForwardRef(ref)).toBe(String);\n });\n });\n}\n"},"repo_name":{"kind":"string","value":"xcaliber-tech/angular"},"path":{"kind":"string","value":"modules/@angular/core/test/di/forward_ref_spec.ts"},"language":{"kind":"string","value":"TypeScript"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":661,"string":"661"}}},{"rowIdx":115086039,"cells":{"code":{"kind":"string","value":"\n#ifdef HAVE_CONFIG_H\n#include \"../ext_config.h\"\n#endif\n\n#include \n#include \"../php_ext.h\"\n#include \"../ext.h\"\n\n#include \n#include \n#include \n\n#include \"kernel/main.h\"\n#include \"kernel/operators.h\"\n#include \"kernel/memory.h\"\n\n\nZEPHIR_INIT_CLASS(test_7__closure) {\n\n\tZEPHIR_REGISTER_CLASS(test, 7__closure, test, 7__closure, test_7__closure_method_entry, ZEND_ACC_FINAL_CLASS);\n\n\treturn SUCCESS;\n\n}\n\nPHP_METHOD(test_7__closure, __invoke) {\n\n\tzval *x;\n\n\tzephir_fetch_params(0, 1, 0, &x);\n\n\n\n\tRETURN_LONG((((zephir_get_numberval(x) + 100)) + ((zephir_get_numberval(x) * 150))));\n\n}\n\n"},"repo_name":{"kind":"string","value":"imadige/zephirbuild"},"path":{"kind":"string","value":"zephir/ext/test/7__closure.zep.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"mit"},"size":{"kind":"number","value":658,"string":"658"}}},{"rowIdx":115086040,"cells":{"code":{"kind":"string","value":"/*\n * Chromaprint -- Audio fingerprinting toolkit\n * Copyright (C) 2010 Lukas Lalinsky \n * \n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library 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 GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301\n * USA\n */\n\n#include \n#include \n#include \n#include \"chroma_filter.h\"\n#include \"utils.h\"\n\nusing namespace std;\nusing namespace Chromaprint;\n\nChromaFilter::ChromaFilter(const double *coefficients, int length, FeatureVectorConsumer *consumer)\n\t: m_coefficients(coefficients),\n\t m_length(length),\n\t m_buffer(8),\n\t m_result(12),\n\t m_buffer_offset(0),\n\t m_buffer_size(1),\n\t m_consumer(consumer)\n{\n}\n\nChromaFilter::~ChromaFilter()\n{\n}\n\nvoid ChromaFilter::Reset()\n{\n\tm_buffer_size = 1;\n\tm_buffer_offset = 0;\n}\n\nvoid ChromaFilter::Consume(std::vector &features)\n{\n\tm_buffer[m_buffer_offset] = features;\n\tm_buffer_offset = (m_buffer_offset + 1) % 8;\n\tif (m_buffer_size >= m_length) {\n\t\tint offset = (m_buffer_offset + 8 - m_length) % 8;\n\t\tfill(m_result.begin(), m_result.end(), 0.0);\n\t\tfor (int i = 0; i < 12; i++) {\n\t\t\tfor (int j = 0; j < m_length; j++) {\n\t\t\t\tm_result[i] += m_buffer[(offset + j) % 8][i] * m_coefficients[j];\n\t\t\t}\n\t\t}\n\t\tm_consumer->Consume(m_result);\n\t}\n\telse {\n\t\tm_buffer_size++;\n\t}\n}\n\n"},"repo_name":{"kind":"string","value":"josephwilk/finger-smudge"},"path":{"kind":"string","value":"vendor/chromaprint/src/chroma_filter.cpp"},"language":{"kind":"string","value":"C++"},"license":{"kind":"string","value":"epl-1.0"},"size":{"kind":"number","value":1885,"string":"1,885"}}},{"rowIdx":115086041,"cells":{"code":{"kind":"string","value":"/*\n * This file is part of mpv.\n *\n * mpv is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * mpv 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 Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with mpv. If not, see .\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"common/common.h\"\n#include \"draw_bmp.h\"\n#include \"img_convert.h\"\n#include \"video/mp_image.h\"\n#include \"video/sws_utils.h\"\n#include \"video/img_format.h\"\n#include \"video/csputils.h\"\n\nconst bool mp_draw_sub_formats[SUBBITMAP_COUNT] = {\n [SUBBITMAP_LIBASS] = true,\n [SUBBITMAP_RGBA] = true,\n};\n\nstruct sub_cache {\n struct mp_image *i, *a;\n};\n\nstruct part {\n int change_id;\n int imgfmt;\n enum mp_csp colorspace;\n enum mp_csp_levels levels;\n int num_imgs;\n struct sub_cache *imgs;\n};\n\nstruct mp_draw_sub_cache\n{\n struct part *parts[MAX_OSD_PARTS];\n struct mp_image *upsample_img;\n struct mp_image upsample_temp;\n};\n\n\nstatic struct part *get_cache(struct mp_draw_sub_cache *cache,\n struct sub_bitmaps *sbs, struct mp_image *format);\nstatic bool get_sub_area(struct mp_rect bb, struct mp_image *temp,\n struct sub_bitmap *sb, struct mp_image *out_area,\n int *out_src_x, int *out_src_y);\n\n#define CONDITIONAL 1\n\n#define BLEND_CONST_ALPHA(TYPE) \\\n TYPE *dst_r = dst_rp; \\\n for (int x = 0; x < w; x++) { \\\n uint32_t srcap = srca_r[x]; \\\n if (CONDITIONAL && !srcap) continue; \\\n srcap *= srcamul; /* now 0..65025 */ \\\n dst_r[x] = (srcp * srcap + dst_r[x] * (65025 - srcap) + 32512) / 65025; \\\n }\n\n// dst = srcp * (srca * srcamul) + dst * (1 - (srca * srcamul))\nstatic void blend_const_alpha(void *dst, int dst_stride, int srcp,\n uint8_t *srca, int srca_stride, uint8_t srcamul,\n int w, int h, int bytes)\n{\n if (!srcamul)\n return;\n for (int y = 0; y < h; y++) {\n void *dst_rp = (uint8_t *)dst + dst_stride * y;\n uint8_t *srca_r = srca + srca_stride * y;\n if (bytes == 2) {\n BLEND_CONST_ALPHA(uint16_t)\n } else if (bytes == 1) {\n BLEND_CONST_ALPHA(uint8_t)\n }\n }\n}\n\n#define BLEND_SRC_ALPHA(TYPE) \\\n TYPE *dst_r = dst_rp, *src_r = src_rp; \\\n for (int x = 0; x < w; x++) { \\\n uint32_t srcap = srca_r[x]; \\\n if (CONDITIONAL && !srcap) continue; \\\n dst_r[x] = (src_r[x] * srcap + dst_r[x] * (255 - srcap) + 127) / 255; \\\n }\n\n// dst = src * srca + dst * (1 - srca)\nstatic void blend_src_alpha(void *dst, int dst_stride, void *src,\n int src_stride, uint8_t *srca, int srca_stride,\n int w, int h, int bytes)\n{\n for (int y = 0; y < h; y++) {\n void *dst_rp = (uint8_t *)dst + dst_stride * y;\n void *src_rp = (uint8_t *)src + src_stride * y;\n uint8_t *srca_r = srca + srca_stride * y;\n if (bytes == 2) {\n BLEND_SRC_ALPHA(uint16_t)\n } else if (bytes == 1) {\n BLEND_SRC_ALPHA(uint8_t)\n }\n }\n}\n\n#define BLEND_SRC_DST_MUL(TYPE, MAX) \\\n TYPE *dst_r = dst_rp; \\\n for (int x = 0; x < w; x++) { \\\n uint16_t srcp = src_r[x] * srcmul; /* now 0..65025 */ \\\n dst_r[x] = (srcp * (MAX) + dst_r[x] * (65025 - srcp) + 32512) / 65025; \\\n }\n\n// dst = src * srcmul + dst * (1 - src * srcmul)\nstatic void blend_src_dst_mul(void *dst, int dst_stride,\n uint8_t *src, int src_stride, uint8_t srcmul,\n int w, int h, int dst_bytes)\n{\n for (int y = 0; y < h; y++) {\n void *dst_rp = (uint8_t *)dst + dst_stride * y;\n uint8_t *src_r = (uint8_t *)src + src_stride * y;\n if (dst_bytes == 2) {\n BLEND_SRC_DST_MUL(uint16_t, 65025)\n } else if (dst_bytes == 1) {\n BLEND_SRC_DST_MUL(uint8_t, 255)\n }\n }\n}\n\nstatic void unpremultiply_and_split_BGR32(struct mp_image *img,\n struct mp_image *alpha)\n{\n for (int y = 0; y < img->h; ++y) {\n uint32_t *irow = (uint32_t *) &img->planes[0][img->stride[0] * y];\n uint8_t *arow = &alpha->planes[0][alpha->stride[0] * y];\n for (int x = 0; x < img->w; ++x) {\n uint32_t pval = irow[x];\n uint8_t aval = (pval >> 24);\n uint8_t rval = (pval >> 16) & 0xFF;\n uint8_t gval = (pval >> 8) & 0xFF;\n uint8_t bval = pval & 0xFF;\n // multiplied = separate * alpha / 255\n // separate = rint(multiplied * 255 / alpha)\n // = floor(multiplied * 255 / alpha + 0.5)\n // = floor((multiplied * 255 + 0.5 * alpha) / alpha)\n // = floor((multiplied * 255 + floor(0.5 * alpha)) / alpha)\n int div = (int) aval;\n int add = div / 2;\n if (aval) {\n rval = FFMIN(255, (rval * 255 + add) / div);\n gval = FFMIN(255, (gval * 255 + add) / div);\n bval = FFMIN(255, (bval * 255 + add) / div);\n irow[x] = bval + (gval << 8) + (rval << 16) + (aval << 24);\n }\n arow[x] = aval;\n }\n }\n}\n\n// dst_format merely contains the target colorspace/format information\nstatic void scale_sb_rgba(struct sub_bitmap *sb, struct mp_image *dst_format,\n struct mp_image **out_sbi, struct mp_image **out_sba)\n{\n struct mp_image sbisrc = {0};\n mp_image_setfmt(&sbisrc, IMGFMT_BGR32);\n mp_image_set_size(&sbisrc, sb->w, sb->h);\n sbisrc.planes[0] = sb->bitmap;\n sbisrc.stride[0] = sb->stride;\n struct mp_image *sbisrc2 = mp_image_alloc(IMGFMT_BGR32, sb->dw, sb->dh);\n struct mp_image *sba = mp_image_alloc(IMGFMT_Y8, sb->dw, sb->dh);\n struct mp_image *sbi = mp_image_alloc(dst_format->imgfmt, sb->dw, sb->dh);\n if (!sbisrc2 || !sba || !sbi) {\n talloc_free(sbisrc2);\n talloc_free(sba);\n talloc_free(sbi);\n return;\n }\n\n mp_image_swscale(sbisrc2, &sbisrc, SWS_BILINEAR);\n unpremultiply_and_split_BGR32(sbisrc2, sba);\n\n sbi->params.color = dst_format->params.color;\n mp_image_swscale(sbi, sbisrc2, SWS_BILINEAR);\n\n talloc_free(sbisrc2);\n\n *out_sbi = sbi;\n *out_sba = sba;\n}\n\nstatic void draw_rgba(struct mp_draw_sub_cache *cache, struct mp_rect bb,\n struct mp_image *temp, int bits,\n struct sub_bitmaps *sbs)\n{\n struct part *part = get_cache(cache, sbs, temp);\n assert(part);\n\n for (int i = 0; i < sbs->num_parts; ++i) {\n struct sub_bitmap *sb = &sbs->parts[i];\n\n if (sb->w < 1 || sb->h < 1)\n continue;\n\n struct mp_image dst;\n int src_x, src_y;\n if (!get_sub_area(bb, temp, sb, &dst, &src_x, &src_y))\n continue;\n\n struct mp_image *sbi = part->imgs[i].i;\n struct mp_image *sba = part->imgs[i].a;\n\n if (!(sbi && sba))\n scale_sb_rgba(sb, temp, &sbi, &sba);\n // on OOM, skip drawing\n if (!(sbi && sba))\n continue;\n\n int bytes = (bits + 7) / 8;\n uint8_t *alpha_p = sba->planes[0] + src_y * sba->stride[0] + src_x;\n for (int p = 0; p < (temp->num_planes > 2 ? 3 : 1); p++) {\n void *src = sbi->planes[p] + src_y * sbi->stride[p] + src_x * bytes;\n blend_src_alpha(dst.planes[p], dst.stride[p], src, sbi->stride[p],\n alpha_p, sba->stride[0], dst.w, dst.h, bytes);\n }\n if (temp->num_planes >= 4) {\n blend_src_dst_mul(dst.planes[3], dst.stride[3], alpha_p,\n sba->stride[0], 255, dst.w, dst.h, bytes);\n }\n\n part->imgs[i].i = talloc_steal(part, sbi);\n part->imgs[i].a = talloc_steal(part, sba);\n }\n}\n\nstatic void draw_ass(struct mp_draw_sub_cache *cache, struct mp_rect bb,\n struct mp_image *temp, int bits, struct sub_bitmaps *sbs)\n{\n struct mp_csp_params cspar = MP_CSP_PARAMS_DEFAULTS;\n mp_csp_set_image_params(&cspar, &temp->params);\n cspar.levels_out = MP_CSP_LEVELS_PC; // RGB (libass.color)\n cspar.input_bits = bits;\n cspar.texture_bits = (bits + 7) / 8 * 8;\n\n struct mp_cmat yuv2rgb, rgb2yuv;\n bool need_conv = temp->fmt.flags & MP_IMGFLAG_YUV;\n if (need_conv) {\n mp_get_csp_matrix(&cspar, &yuv2rgb);\n mp_invert_cmat(&rgb2yuv, &yuv2rgb);\n }\n\n for (int i = 0; i < sbs->num_parts; ++i) {\n struct sub_bitmap *sb = &sbs->parts[i];\n\n struct mp_image dst;\n int src_x, src_y;\n if (!get_sub_area(bb, temp, sb, &dst, &src_x, &src_y))\n continue;\n\n int r = (sb->libass.color >> 24) & 0xFF;\n int g = (sb->libass.color >> 16) & 0xFF;\n int b = (sb->libass.color >> 8) & 0xFF;\n int a = 255 - (sb->libass.color & 0xFF);\n int color_yuv[3];\n if (need_conv) {\n int rgb[3] = {r, g, b};\n mp_map_fixp_color(&rgb2yuv, 8, rgb, cspar.texture_bits, color_yuv);\n } else {\n color_yuv[0] = g;\n color_yuv[1] = b;\n color_yuv[2] = r;\n }\n\n int bytes = (bits + 7) / 8;\n uint8_t *alpha_p = (uint8_t *)sb->bitmap + src_y * sb->stride + src_x;\n for (int p = 0; p < (temp->num_planes > 2 ? 3 : 1); p++) {\n blend_const_alpha(dst.planes[p], dst.stride[p], color_yuv[p],\n alpha_p, sb->stride, a, dst.w, dst.h, bytes);\n }\n if (temp->num_planes >= 4) {\n blend_src_dst_mul(dst.planes[3], dst.stride[3], alpha_p,\n sb->stride, a, dst.w, dst.h, bytes);\n }\n }\n}\n\nstatic void get_swscale_alignment(const struct mp_image *img, int *out_xstep,\n int *out_ystep)\n{\n int sx = (1 << img->fmt.chroma_xs);\n int sy = (1 << img->fmt.chroma_ys);\n\n for (int p = 0; p < img->num_planes; ++p) {\n int bits = img->fmt.bpp[p];\n // the * 2 fixes problems with writing past the destination width\n while (((sx >> img->fmt.chroma_xs) * bits) % (SWS_MIN_BYTE_ALIGN * 8 * 2))\n sx *= 2;\n }\n\n *out_xstep = sx;\n *out_ystep = sy;\n}\n\nstatic void align_bbox(int xstep, int ystep, struct mp_rect *rc)\n{\n rc->x0 = rc->x0 & ~(xstep - 1);\n rc->y0 = rc->y0 & ~(ystep - 1);\n rc->x1 = FFALIGN(rc->x1, xstep);\n rc->y1 = FFALIGN(rc->y1, ystep);\n}\n\n// Post condition, if true returned: rc is inside img\nstatic bool align_bbox_for_swscale(struct mp_image *img, struct mp_rect *rc)\n{\n struct mp_rect img_rect = {0, 0, img->w, img->h};\n // Get rid of negative coordinates\n if (!mp_rect_intersection(rc, &img_rect))\n return false;\n int xstep, ystep;\n get_swscale_alignment(img, &xstep, &ystep);\n align_bbox(xstep, ystep, rc);\n return mp_rect_intersection(rc, &img_rect);\n}\n\n// Try to find best/closest YUV 444 format (or similar) for imgfmt\nstatic void get_closest_y444_format(int imgfmt, int *out_format, int *out_bits)\n{\n struct mp_imgfmt_desc desc = mp_imgfmt_get_desc(imgfmt);\n int planes = desc.flags & MP_IMGFLAG_ALPHA ? 4 : 3;\n int bits = desc.component_bits > 8 ? 16 : 8;\n if (desc.flags & MP_IMGFLAG_RGB) {\n *out_format = mp_imgfmt_find(0, 0, planes, bits, MP_IMGFLAG_RGB_P);\n if (!mp_sws_supported_format(*out_format))\n *out_format = mp_imgfmt_find(0, 0, planes, 8, MP_IMGFLAG_RGB_P);\n } else if (desc.flags & MP_IMGFLAG_YUV_P) {\n *out_format = mp_imgfmt_find(0, 0, planes, bits, MP_IMGFLAG_YUV_P);\n } else {\n *out_format = 0;\n }\n if (!mp_sws_supported_format(*out_format))\n *out_format = IMGFMT_444P; // generic fallback\n *out_bits = mp_imgfmt_get_desc(*out_format).component_bits;\n}\n\nstatic struct part *get_cache(struct mp_draw_sub_cache *cache,\n struct sub_bitmaps *sbs, struct mp_image *format)\n{\n struct part *part = NULL;\n\n bool use_cache = sbs->format == SUBBITMAP_RGBA;\n if (use_cache) {\n part = cache->parts[sbs->render_index];\n if (part) {\n if (part->change_id != sbs->change_id\n || part->imgfmt != format->imgfmt\n || part->colorspace != format->params.color.space\n || part->levels != format->params.color.levels)\n {\n talloc_free(part);\n part = NULL;\n }\n }\n if (!part) {\n part = talloc(cache, struct part);\n *part = (struct part) {\n .change_id = sbs->change_id,\n .num_imgs = sbs->num_parts,\n .imgfmt = format->imgfmt,\n .levels = format->params.color.levels,\n .colorspace = format->params.color.space,\n };\n part->imgs = talloc_zero_array(part, struct sub_cache,\n part->num_imgs);\n }\n assert(part->num_imgs == sbs->num_parts);\n cache->parts[sbs->render_index] = part;\n }\n\n return part;\n}\n\n// Return area of intersection between target and sub-bitmap as cropped image\nstatic bool get_sub_area(struct mp_rect bb, struct mp_image *temp,\n struct sub_bitmap *sb, struct mp_image *out_area,\n int *out_src_x, int *out_src_y)\n{\n // coordinates are relative to the bbox\n struct mp_rect dst = {sb->x - bb.x0, sb->y - bb.y0};\n dst.x1 = dst.x0 + sb->dw;\n dst.y1 = dst.y0 + sb->dh;\n if (!mp_rect_intersection(&dst, &(struct mp_rect){0, 0, temp->w, temp->h}))\n return false;\n\n *out_src_x = (dst.x0 - sb->x) + bb.x0;\n *out_src_y = (dst.y0 - sb->y) + bb.y0;\n *out_area = *temp;\n mp_image_crop_rc(out_area, dst);\n\n return true;\n}\n\n// Convert the src image to imgfmt (which should be a 444 format)\nstatic struct mp_image *chroma_up(struct mp_draw_sub_cache *cache, int imgfmt,\n struct mp_image *src)\n{\n if (src->imgfmt == imgfmt)\n return src;\n\n if (!cache->upsample_img || cache->upsample_img->imgfmt != imgfmt ||\n cache->upsample_img->w < src->w || cache->upsample_img->h < src->h)\n {\n talloc_free(cache->upsample_img);\n cache->upsample_img = mp_image_alloc(imgfmt, src->w, src->h);\n talloc_steal(cache, cache->upsample_img);\n if (!cache->upsample_img)\n return NULL;\n }\n\n cache->upsample_temp = *cache->upsample_img;\n struct mp_image *temp = &cache->upsample_temp;\n mp_image_set_size(temp, src->w, src->h);\n\n // The temp image is always YUV, but src not necessarily.\n // Reduce amount of conversions in YUV case (upsampling/shifting only)\n if (src->fmt.flags & MP_IMGFLAG_YUV)\n temp->params.color = src->params.color;\n\n if (src->imgfmt == IMGFMT_420P) {\n assert(imgfmt == IMGFMT_444P);\n // Faster upsampling: keep Y plane, upsample chroma planes only\n // The whole point is not having swscale copy the Y plane\n struct mp_image t_dst = *temp;\n mp_image_setfmt(&t_dst, IMGFMT_Y8);\n mp_image_set_size(&t_dst, temp->w, temp->h);\n struct mp_image t_src = t_dst;\n mp_image_set_size(&t_src, src->w >> 1, src->h >> 1);\n for (int c = 0; c < 2; c++) {\n t_dst.planes[0] = temp->planes[1 + c];\n t_dst.stride[0] = temp->stride[1 + c];\n t_src.planes[0] = src->planes[1 + c];\n t_src.stride[0] = src->stride[1 + c];\n mp_image_swscale(&t_dst, &t_src, SWS_POINT);\n }\n temp->planes[0] = src->planes[0];\n temp->stride[0] = src->stride[0];\n } else {\n mp_image_swscale(temp, src, SWS_POINT);\n }\n\n return temp;\n}\n\n// Undo chroma_up() (copy temp to old_src if needed)\nstatic void chroma_down(struct mp_image *old_src, struct mp_image *temp)\n{\n assert(old_src->w == temp->w && old_src->h == temp->h);\n if (temp != old_src) {\n if (old_src->imgfmt == IMGFMT_420P) {\n // Downsampling, skipping the Y plane (see chroma_up())\n assert(temp->imgfmt == IMGFMT_444P);\n assert(temp->planes[0] == old_src->planes[0]);\n struct mp_image t_dst = *temp;\n mp_image_setfmt(&t_dst, IMGFMT_Y8);\n mp_image_set_size(&t_dst, old_src->w >> 1, old_src->h >> 1);\n struct mp_image t_src = t_dst;\n mp_image_set_size(&t_src, temp->w, temp->h);\n for (int c = 0; c < 2; c++) {\n t_dst.planes[0] = old_src->planes[1 + c];\n t_dst.stride[0] = old_src->stride[1 + c];\n t_src.planes[0] = temp->planes[1 + c];\n t_src.stride[0] = temp->stride[1 + c];\n mp_image_swscale(&t_dst, &t_src, SWS_AREA);\n }\n } else {\n mp_image_swscale(old_src, temp, SWS_AREA); // chroma down\n }\n }\n}\n\n// cache: if not NULL, the function will set *cache to a talloc-allocated cache\n// containing scaled versions of sbs contents - free the cache with\n// talloc_free()\nvoid mp_draw_sub_bitmaps(struct mp_draw_sub_cache **cache, struct mp_image *dst,\n struct sub_bitmaps *sbs)\n{\n assert(mp_draw_sub_formats[sbs->format]);\n if (!mp_sws_supported_format(dst->imgfmt))\n return;\n\n struct mp_draw_sub_cache *cache_ = cache ? *cache : NULL;\n if (!cache_)\n cache_ = talloc_zero(NULL, struct mp_draw_sub_cache);\n\n int format, bits;\n get_closest_y444_format(dst->imgfmt, &format, &bits);\n\n struct mp_rect rc_list[MP_SUB_BB_LIST_MAX];\n int num_rc = mp_get_sub_bb_list(sbs, rc_list, MP_SUB_BB_LIST_MAX);\n\n for (int r = 0; r < num_rc; r++) {\n struct mp_rect bb = rc_list[r];\n\n if (!align_bbox_for_swscale(dst, &bb))\n return;\n\n struct mp_image dst_region = *dst;\n mp_image_crop_rc(&dst_region, bb);\n struct mp_image *temp = chroma_up(cache_, format, &dst_region);\n if (!temp)\n continue; // on OOM, skip region\n\n if (sbs->format == SUBBITMAP_RGBA) {\n draw_rgba(cache_, bb, temp, bits, sbs);\n } else if (sbs->format == SUBBITMAP_LIBASS) {\n draw_ass(cache_, bb, temp, bits, sbs);\n }\n\n chroma_down(&dst_region, temp);\n }\n\n if (cache) {\n *cache = cache_;\n } else {\n talloc_free(cache_);\n }\n}\n\n// vim: ts=4 sw=4 et tw=80\n"},"repo_name":{"kind":"string","value":"tobiasjakobi/mpv"},"path":{"kind":"string","value":"sub/draw_bmp.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":19551,"string":"19,551"}}},{"rowIdx":115086042,"cells":{"code":{"kind":"string","value":"/*\n** $Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/os/linux/gl_wext_priv.c#4 $\n*/\n\n/*! \\file gl_wext_priv.c\n \\brief This file includes private ioctl support.\n*/\n\n\n\n/*\n** $Log: gl_wext_priv.c $\n *\n * 07 17 2012 yuche.tsai\n * NULL\n * Let netdev bring up.\n *\n * 06 13 2012 yuche.tsai\n * NULL\n * Update maintrunk driver.\n * Add support for driver compose assoc request frame.\n *\n * 03 20 2012 wh.su\n * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function[WCXRP00001202] [MT6628 Wi-Fi][FW] Adding the New PN init code\n * use return to avoid the ioctl return not supported\n *\n * 03 02 2012 terry.wu\n * NULL\n * Snc CFG80211 modification for ICS migration from branch 2.2.\n *\n * 01 16 2012 wh.su\n * [WCXRP00001170] [MT6620 Wi-Fi][Driver] Adding the related code for set/get band ioctl\n * Adding the template code for set / get band IOCTL (with ICS supplicant_6)..\n *\n * 01 05 2012 wh.su\n * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function\n * Adding the related ioctl / wlan oid function to set the Tx power cfg.\n *\n * 01 02 2012 wh.su\n * [WCXRP00001153] [MT6620 Wi-Fi][Driver] Adding the get_ch_list and set_tx_power proto type function\n * Adding the proto type function for set_int set_tx_power and get int get_ch_list.\n *\n * 11 10 2011 cp.wu\n * [WCXRP00001098] [MT6620 Wi-Fi][Driver] Replace printk by DBG LOG macros in linux porting layer\n * 1. eliminaite direct calls to printk in porting layer.\n * 2. replaced by DBGLOG, which would be XLOG on ALPS platforms.\n *\n * 11 02 2011 chinghwa.yu\n * [WCXRP00000063] Update BCM CoEx design and settings\n * Fixed typo.\n *\n * 09 20 2011 chinglan.wang\n * [WCXRP00000989] [WiFi Direct] [Driver] Add a new io control API to start the formation for the sigma test.\n * .\n *\n * 07 28 2011 chinghwa.yu\n * [WCXRP00000063] Update BCM CoEx design and settings\n * Add BWCS cmd and event.\n *\n * 07 18 2011 chinghwa.yu\n * [WCXRP00000063] Update BCM CoEx design and settings[WCXRP00000612] [MT6620 Wi-Fi] [FW] CSD update SWRDD algorithm\n * Add CMD/Event for RDD and BWCS.\n *\n * 03 17 2011 chinglan.wang\n * [WCXRP00000570] [MT6620 Wi-Fi][Driver] Add Wi-Fi Protected Setup v2.0 feature\n * .\n *\n * 03 07 2011 terry.wu\n * [WCXRP00000521] [MT6620 Wi-Fi][Driver] Remove non-standard debug message\n * Toggle non-standard debug messages to comments.\n *\n * 01 27 2011 cm.chang\n * [WCXRP00000402] [MT6620 Wi-Fi][Driver] Enable MCR read/write by iwpriv by default\n * .\n *\n * 01 26 2011 wh.su\n * [WCXRP00000396] [MT6620 Wi-Fi][Driver] Support Sw Ctrl ioctl at linux\n * adding the SW cmd ioctl support, use set/get structure ioctl.\n *\n * 01 20 2011 eddie.chen\n * [WCXRP00000374] [MT6620 Wi-Fi][DRV] SW debug control\n * Adjust OID order.\n *\n * 01 20 2011 eddie.chen\n * [WCXRP00000374] [MT6620 Wi-Fi][DRV] SW debug control\n * Add Oid for sw control debug command\n *\n * 01 07 2011 cm.chang\n * [WCXRP00000336] [MT6620 Wi-Fi][Driver] Add test mode commands in normal phone operation\n * Add a new compiling option to control if MCR read/write is permitted\n *\n * 12 31 2010 cm.chang\n * [WCXRP00000336] [MT6620 Wi-Fi][Driver] Add test mode commands in normal phone operation\n * Add some iwpriv commands to support test mode operation\n *\n * 12 15 2010 george.huang\n * [WCXRP00000152] [MT6620 Wi-Fi] AP mode power saving function\n * Support set PS profile and set WMM-PS related iwpriv.\n *\n * 11 08 2010 wh.su\n * [WCXRP00000171] [MT6620 Wi-Fi][Driver] Add message check code same behavior as mt5921\n * add the message check code from mt5921.\n *\n * 10 18 2010 cp.wu\n * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000086] [MT6620 Wi-Fi][Driver] The mac address is all zero at android\n * complete implementation of Android NVRAM access\n *\n * 09 24 2010 cp.wu\n * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check\n * correct typo for NVRAM access.\n *\n * 09 23 2010 cp.wu\n * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check\n * add skeleton for NVRAM integration\n *\n * 08 04 2010 cp.wu\n * NULL\n * revert changelist #15371, efuse read/write access will be done by RF test approach\n *\n * 08 04 2010 cp.wu\n * NULL\n * add OID definitions for EFUSE read/write access.\n *\n * 07 08 2010 cp.wu\n *\n * [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository.\n *\n * 06 06 2010 kevin.huang\n * [WPD00003832][MT6620 5931] Create driver base\n * [MT6620 5931] Create driver base\n *\n * 06 01 2010 cp.wu\n * [WPD00001943]Create WiFi test driver framework on WinXP\n * enable OID_CUSTOM_MTK_WIFI_TEST for RFTest & META tool\n *\n * 05 29 2010 jeffrey.chang\n * [WPD00003826]Initial import for Linux port\n * fix private ioctl for rftest\n *\n * 04 21 2010 jeffrey.chang\n * [WPD00003826]Initial import for Linux port\n * add for private ioctl support\n** \\main\\maintrunk.MT5921\\32 2009-10-08 10:33:25 GMT mtk01090\n** Avoid accessing private data of net_device directly. Replace with netdev_priv(). Add more checking for input parameters and pointers.\n** \\main\\maintrunk.MT5921\\31 2009-09-29 16:46:21 GMT mtk01090\n** Remove unused functions\n** \\main\\maintrunk.MT5921\\30 2009-09-29 14:46:47 GMT mtk01090\n** Fix compile warning\n** \\main\\maintrunk.MT5921\\29 2009-09-29 14:28:48 GMT mtk01090\n** Fix compile warning\n** \\main\\maintrunk.MT5921\\28 2009-09-28 22:21:38 GMT mtk01090\n** Refine lines to supress compile warning\n** \\main\\maintrunk.MT5921\\27 2009-09-28 20:19:14 GMT mtk01090\n** Add private ioctl to carry OID structures. Restructure public/private ioctl interfaces to Linux kernel.\n** \\main\\maintrunk.MT5921\\26 2009-08-18 22:56:53 GMT mtk01090\n** Add Linux SDIO (with mmc core) support.\n** Add Linux 2.6.21, 2.6.25, 2.6.26.\n** Fix compile warning in Linux.\n** \\main\\maintrunk.MT5921\\25 2009-05-07 22:26:15 GMT mtk01089\n** Add mandatory and private IO control for Linux BWCS\n** \\main\\maintrunk.MT5921\\24 2009-04-29 10:07:05 GMT mtk01088\n** fixed the compiling error at linux\n** \\main\\maintrunk.MT5921\\23 2009-04-24 09:09:45 GMT mtk01088\n** mark the code not used at linux supplicant v0.6.7\n** \\main\\maintrunk.MT5921\\22 2008-11-24 21:03:51 GMT mtk01425\n** 1. Add PTA_ENABLED flag\n** \\main\\maintrunk.MT5921\\21 2008-08-29 14:55:59 GMT mtk01088\n** adjust the code for meet the coding style, and add assert check\n** \\main\\maintrunk.MT5921\\20 2008-07-16 15:23:20 GMT mtk01104\n** Support GPIO2 mode\n** \\main\\maintrunk.MT5921\\19 2008-07-15 17:43:11 GMT mtk01084\n** modify variable name\n** \\main\\maintrunk.MT5921\\18 2008-07-14 14:37:58 GMT mtk01104\n** Add exception handle about length in function priv_set_struct()\n** \\main\\maintrunk.MT5921\\17 2008-07-14 13:55:32 GMT mtk01104\n** Support PRIV_CMD_BT_COEXIST\n** \\main\\maintrunk.MT5921\\16 2008-07-09 00:20:15 GMT mtk01461\n** Add priv oid to support WMM_PS_TEST\n** \\main\\maintrunk.MT5921\\15 2008-06-02 11:15:22 GMT mtk01461\n** Update after wlanoidSetPowerMode changed\n** \\main\\maintrunk.MT5921\\14 2008-05-30 19:31:07 GMT mtk01461\n** Add IOCTL for Power Mode\n** \\main\\maintrunk.MT5921\\13 2008-05-30 18:57:15 GMT mtk01461\n** Not use wlanoidSetCSUMOffloadForLinux()\n** \\main\\maintrunk.MT5921\\12 2008-05-30 15:13:18 GMT mtk01084\n** rename wlanoid\n** \\main\\maintrunk.MT5921\\11 2008-05-29 14:16:31 GMT mtk01084\n** rename for wlanoidSetBeaconIntervalForLinux\n** \\main\\maintrunk.MT5921\\10 2008-04-17 23:06:37 GMT mtk01461\n** Add iwpriv support for AdHocMode setting\n** \\main\\maintrunk.MT5921\\9 2008-03-31 21:00:55 GMT mtk01461\n** Add priv IOCTL for VOIP setting\n** \\main\\maintrunk.MT5921\\8 2008-03-31 13:49:43 GMT mtk01461\n** Add priv ioctl to turn on / off roaming\n** \\main\\maintrunk.MT5921\\7 2008-03-26 15:35:14 GMT mtk01461\n** Add CSUM offload priv ioctl for Linux\n** \\main\\maintrunk.MT5921\\6 2008-03-11 14:50:59 GMT mtk01461\n** Unify priv ioctl\n** \\main\\maintrunk.MT5921\\5 2007-11-06 19:32:30 GMT mtk01088\n** add WPS code\n** \\main\\maintrunk.MT5921\\4 2007-10-30 12:01:39 GMT MTK01425\n** 1. Update wlanQueryInformation and wlanSetInformation\n*/\n\n/*******************************************************************************\n* C O M P I L E R F L A G S\n********************************************************************************\n*/\n\n/*******************************************************************************\n* E X T E R N A L R E F E R E N C E S\n********************************************************************************\n*/\n#include \"gl_os.h\"\n#include \"gl_wext_priv.h\"\n#if CFG_SUPPORT_WAPI\n#include \"gl_sec.h\"\n#endif\n#if CFG_ENABLE_WIFI_DIRECT\n#include \"gl_p2p_os.h\"\n#endif\n\n/*******************************************************************************\n* C O N S T A N T S\n********************************************************************************\n*/\n#define NUM_SUPPORTED_OIDS (sizeof(arWlanOidReqTable) / sizeof(WLAN_REQ_ENTRY))\n\n/*******************************************************************************\n* F U N C T I O N D E C L A R A T I O N S\n********************************************************************************\n*/\n\nstatic int\npriv_get_ndis (\n IN struct net_device *prNetDev,\n IN NDIS_TRANSPORT_STRUCT* prNdisReq,\n OUT PUINT_32 pu4OutputLen\n );\n\nstatic int\npriv_set_ndis (\n IN struct net_device *prNetDev,\n IN NDIS_TRANSPORT_STRUCT* prNdisReq,\n OUT PUINT_32 pu4OutputLen\n );\n\n#if 0 /* CFG_SUPPORT_WPS */\nstatic int\npriv_set_appie (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n OUT char *pcExtra\n );\n\nstatic int\npriv_set_filter (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n OUT char *pcExtra\n );\n#endif /* CFG_SUPPORT_WPS */\n\nstatic BOOLEAN\nreqSearchSupportedOidEntry (\n IN UINT_32 rOid,\n OUT P_WLAN_REQ_ENTRY *ppWlanReqEntry\n );\n\n#if 0\nstatic WLAN_STATUS\nreqExtQueryConfiguration (\n IN P_GLUE_INFO_T prGlueInfo,\n OUT PVOID pvQueryBuffer,\n IN UINT_32 u4QueryBufferLen,\n OUT PUINT_32 pu4QueryInfoLen\n );\n\nstatic WLAN_STATUS\nreqExtSetConfiguration (\n IN P_GLUE_INFO_T prGlueInfo,\n IN PVOID pvSetBuffer,\n IN UINT_32 u4SetBufferLen,\n OUT PUINT_32 pu4SetInfoLen\n );\n#endif\n\nstatic WLAN_STATUS\nreqExtSetAcpiDevicePowerState (\n IN P_GLUE_INFO_T prGlueInfo,\n IN PVOID pvSetBuffer,\n IN UINT_32 u4SetBufferLen,\n OUT PUINT_32 pu4SetInfoLen\n );\n\n/*******************************************************************************\n* P R I V A T E D A T A\n********************************************************************************\n*/\nstatic UINT_8 aucOidBuf[4096] = {0};\n\n/* OID processing table */\n/* Order is important here because the OIDs should be in order of\n increasing value for binary searching. */\nstatic WLAN_REQ_ENTRY arWlanOidReqTable[] = {\n /*\n {(NDIS_OID)rOid,\n (PUINT_8)pucOidName,\n fgQryBufLenChecking, fgSetBufLenChecking, fgIsHandleInGlueLayerOnly, u4InfoBufLen,\n pfOidQueryHandler,\n pfOidSetHandler}\n */\n /* General Operational Characteristics */\n\n /* Ethernet Operational Characteristics */\n {OID_802_3_CURRENT_ADDRESS,\n DISP_STRING(\"OID_802_3_CURRENT_ADDRESS\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 6,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCurrentAddr,\n NULL},\n\n /* OID_802_3_MULTICAST_LIST */\n /* OID_802_3_MAXIMUM_LIST_SIZE */\n /* Ethernet Statistics */\n\n /* NDIS 802.11 Wireless LAN OIDs */\n {OID_802_11_SUPPORTED_RATES,\n DISP_STRING(\"OID_802_11_SUPPORTED_RATES\"),\n TRUE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_RATES_EX),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySupportedRates,\n NULL},\n /*\n {OID_802_11_CONFIGURATION,\n DISP_STRING(\"OID_802_11_CONFIGURATION\"),\n TRUE, TRUE, ENUM_OID_GLUE_EXTENSION, sizeof(PARAM_802_11_CONFIG_T),\n (PFN_OID_HANDLER_FUNC_REQ)reqExtQueryConfiguration,\n (PFN_OID_HANDLER_FUNC_REQ)reqExtSetConfiguration},\n */\n {OID_PNP_SET_POWER,\n DISP_STRING(\"OID_PNP_SET_POWER\"),\n TRUE, FALSE, ENUM_OID_GLUE_EXTENSION, sizeof(PARAM_DEVICE_POWER_STATE),\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)reqExtSetAcpiDevicePowerState},\n\n /* Custom OIDs */\n {OID_CUSTOM_OID_INTERFACE_VERSION,\n DISP_STRING(\"OID_CUSTOM_OID_INTERFACE_VERSION\"),\n TRUE, FALSE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryOidInterfaceVersion,\n NULL},\n\n /*\n#if PTA_ENABLED\n {OID_CUSTOM_BT_COEXIST_CTRL,\n DISP_STRING(\"OID_CUSTOM_BT_COEXIST_CTRL\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_BT_COEXIST_T),\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBtCoexistCtrl},\n#endif\n */\n\n /*\n {OID_CUSTOM_POWER_MANAGEMENT_PROFILE,\n DISP_STRING(\"OID_CUSTOM_POWER_MANAGEMENT_PROFILE\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryPwrMgmtProfParam,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPwrMgmtProfParam},\n {OID_CUSTOM_PATTERN_CONFIG,\n DISP_STRING(\"OID_CUSTOM_PATTERN_CONFIG\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_PATTERN_SEARCH_CONFIG_STRUC_T),\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPatternConfig},\n {OID_CUSTOM_BG_SSID_SEARCH_CONFIG,\n DISP_STRING(\"OID_CUSTOM_BG_SSID_SEARCH_CONFIG\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBgSsidParam},\n {OID_CUSTOM_VOIP_SETUP,\n DISP_STRING(\"OID_CUSTOM_VOIP_SETUP\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryVoipConnectionStatus,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetVoipConnectionStatus},\n {OID_CUSTOM_ADD_TS,\n DISP_STRING(\"OID_CUSTOM_ADD_TS\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidAddTS},\n {OID_CUSTOM_DEL_TS,\n DISP_STRING(\"OID_CUSTOM_DEL_TS\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidDelTS},\n */\n\n /*\n#if CFG_LP_PATTERN_SEARCH_SLT\n {OID_CUSTOM_SLT,\n DISP_STRING(\"OID_CUSTOM_SLT\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySltResult,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetSltMode},\n#endif\n\n {OID_CUSTOM_ROAMING_EN,\n DISP_STRING(\"OID_CUSTOM_ROAMING_EN\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRoamingFunction,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetRoamingFunction},\n {OID_CUSTOM_WMM_PS_TEST,\n DISP_STRING(\"OID_CUSTOM_WMM_PS_TEST\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWiFiWmmPsTest},\n {OID_CUSTOM_COUNTRY_STRING,\n DISP_STRING(\"OID_CUSTOM_COUNTRY_STRING\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCurrentCountry,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetCurrentCountry},\n\n#if CFG_SUPPORT_802_11D\n {OID_CUSTOM_MULTI_DOMAIN_CAPABILITY,\n DISP_STRING(\"OID_CUSTOM_MULTI_DOMAIN_CAPABILITY\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMultiDomainCap,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetMultiDomainCap},\n#endif\n\n {OID_CUSTOM_GPIO2_MODE,\n DISP_STRING(\"OID_CUSTOM_GPIO2_MODE\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_PARAM_GPIO2_MODE_T),\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetGPIO2Mode},\n {OID_CUSTOM_CONTINUOUS_POLL,\n DISP_STRING(\"OID_CUSTOM_CONTINUOUS_POLL\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CONTINUOUS_POLL_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryContinuousPollInterval,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetContinuousPollProfile},\n {OID_CUSTOM_DISABLE_BEACON_DETECTION,\n DISP_STRING(\"OID_CUSTOM_DISABLE_BEACON_DETECTION\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryDisableBeaconDetectionFunc,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetDisableBeaconDetectionFunc},\n */\n\n /* WPS */\n /*\n {OID_CUSTOM_DISABLE_PRIVACY_CHECK,\n DISP_STRING(\"OID_CUSTOM_DISABLE_PRIVACY_CHECK\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetDisablePriavcyCheck},\n */\n\n {OID_CUSTOM_MCR_RW,\n DISP_STRING(\"OID_CUSTOM_MCR_RW\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_MCR_RW_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMcrRead,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetMcrWrite},\n\n {OID_CUSTOM_EEPROM_RW,\n DISP_STRING(\"OID_CUSTOM_EEPROM_RW\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_EEPROM_RW_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryEepromRead,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetEepromWrite},\n\n {OID_CUSTOM_SW_CTRL,\n DISP_STRING(\"OID_CUSTOM_SW_CTRL\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_SW_CTRL_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQuerySwCtrlRead,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetSwCtrlWrite},\n\n {OID_CUSTOM_MEM_DUMP,\n DISP_STRING(\"OID_CUSTOM_MEM_DUMP\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryMemDump,\n NULL},\n\n {OID_CUSTOM_TEST_MODE,\n DISP_STRING(\"OID_CUSTOM_TEST_MODE\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetTestMode},\n\n /*\n {OID_CUSTOM_TEST_RX_STATUS,\n DISP_STRING(\"OID_CUSTOM_TEST_RX_STATUS\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_RFTEST_RX_STATUS_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRfTestRxStatus,\n NULL},\n {OID_CUSTOM_TEST_TX_STATUS,\n DISP_STRING(\"OID_CUSTOM_TEST_TX_STATUS\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_RFTEST_TX_STATUS_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryRfTestTxStatus,\n NULL},\n */\n {OID_CUSTOM_ABORT_TEST_MODE,\n DISP_STRING(\"OID_CUSTOM_ABORT_TEST_MODE\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetAbortTestMode},\n {OID_CUSTOM_MTK_WIFI_TEST,\n DISP_STRING(\"OID_CUSTOM_MTK_WIFI_TEST\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_MTK_WIFI_TEST_STRUC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestQueryAutoTest,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidRftestSetAutoTest},\n\n /* OID_CUSTOM_EMULATION_VERSION_CONTROL */\n\n /* BWCS */\n#if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS\n {OID_CUSTOM_BWCS_CMD,\n DISP_STRING(\"OID_CUSTOM_BWCS_CMD\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PTA_IPC_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryBT,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBT},\n#endif\n\n/* {OID_CUSTOM_SINGLE_ANTENNA,\n DISP_STRING(\"OID_CUSTOM_SINGLE_ANTENNA\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryBtSingleAntenna,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetBtSingleAntenna},\n {OID_CUSTOM_SET_PTA,\n DISP_STRING(\"OID_CUSTOM_SET_PTA\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 4,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryPta,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetPta},\n */\n\n { OID_CUSTOM_MTK_NVRAM_RW,\n DISP_STRING(\"OID_CUSTOM_MTK_NVRAM_RW\"),\n TRUE, TRUE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_CUSTOM_NVRAM_RW_STRUCT_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryNvramRead,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetNvramWrite },\n\n { OID_CUSTOM_CFG_SRC_TYPE,\n DISP_STRING(\"OID_CUSTOM_CFG_SRC_TYPE\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_CFG_SRC_TYPE_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryCfgSrcType,\n NULL },\n\n { OID_CUSTOM_EEPROM_TYPE,\n DISP_STRING(\"OID_CUSTOM_EEPROM_TYPE\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(ENUM_EEPROM_TYPE_T),\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidQueryEepromType,\n NULL },\n\n#if CFG_SUPPORT_WAPI\n {OID_802_11_WAPI_MODE,\n DISP_STRING(\"OID_802_11_WAPI_MODE\"),\n FALSE, TRUE, ENUM_OID_DRIVER_CORE, 4,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiMode},\n {OID_802_11_WAPI_ASSOC_INFO,\n DISP_STRING(\"OID_802_11_WAPI_ASSOC_INFO\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiAssocInfo},\n {OID_802_11_SET_WAPI_KEY,\n DISP_STRING(\"OID_802_11_SET_WAPI_KEY\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, sizeof(PARAM_WPI_KEY_T),\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWapiKey},\n#endif\n\n#if CFG_SUPPORT_WPS2\n {OID_802_11_WSC_ASSOC_INFO,\n DISP_STRING(\"OID_802_11_WSC_ASSOC_INFO\"),\n FALSE, FALSE, ENUM_OID_DRIVER_CORE, 0,\n NULL,\n (PFN_OID_HANDLER_FUNC_REQ)wlanoidSetWSCAssocInfo},\n#endif\n};\n\n/*******************************************************************************\n* F U N C T I O N S\n********************************************************************************\n*/\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Dispatching function for private ioctl region (SIOCIWFIRSTPRIV ~\n* SIOCIWLASTPRIV).\n*\n* \\param[in] prNetDev Net device requested.\n* \\param[in] prIfReq Pointer to ifreq structure.\n* \\param[in] i4Cmd Command ID between SIOCIWFIRSTPRIV and SIOCIWLASTPRIV.\n*\n* \\retval 0 for success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EFAULT For fail.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_support_ioctl (\n IN struct net_device *prNetDev,\n IN OUT struct ifreq *prIfReq,\n IN int i4Cmd\n )\n{\n /* prIfReq is verified in the caller function wlanDoIOCTL() */\n struct iwreq *prIwReq = (struct iwreq *)prIfReq;\n struct iw_request_info rIwReqInfo;\n\n /* prDev is verified in the caller function wlanDoIOCTL() */\n\n /* Prepare the call */\n rIwReqInfo.cmd = (__u16)i4Cmd;\n rIwReqInfo.flags = 0;\n\n switch (i4Cmd) {\n case IOCTL_SET_INT:\n /* NOTE(Kevin): 1/3 INT Type <= IFNAMSIZ, so we don't need copy_from/to_user() */\n return priv_set_int(prNetDev, &rIwReqInfo, &(prIwReq->u), (char *) &(prIwReq->u));\n\n case IOCTL_GET_INT:\n /* NOTE(Kevin): 1/3 INT Type <= IFNAMSIZ, so we don't need copy_from/to_user() */\n return priv_get_int(prNetDev, &rIwReqInfo, &(prIwReq->u), (char *) &(prIwReq->u));\n\n case IOCTL_SET_STRUCT:\n case IOCTL_SET_STRUCT_FOR_EM:\n return priv_set_struct(prNetDev, &rIwReqInfo, &prIwReq->u, (char *) &(prIwReq->u));\n\n case IOCTL_GET_STRUCT:\n return priv_get_struct(prNetDev, &rIwReqInfo, &prIwReq->u, (char *) &(prIwReq->u));\n\n default:\n return -EOPNOTSUPP;\n\n } /* end of switch */\n\n}/* priv_support_ioctl */\n\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl set int handler.\n*\n* \\param[in] prNetDev Net device requested.\n* \\param[in] prIwReqInfo Pointer to iwreq structure.\n* \\param[in] prIwReqData The ioctl data structure, use the field of sub-command.\n* \\param[in] pcExtra The buffer with input value\n*\n* \\retval 0 For success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EINVAL If a value is out of range.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_set_int (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN char *pcExtra\n )\n{\n UINT_32 u4SubCmd;\n PUINT_32 pu4IntBuf;\n P_NDIS_TRANSPORT_STRUCT prNdisReq;\n P_GLUE_INFO_T prGlueInfo;\n UINT_32 u4BufLen = 0;\n int status = 0;\n P_PTA_IPC_T prPtaIpc;\n\n ASSERT(prNetDev);\n ASSERT(prIwReqInfo);\n ASSERT(prIwReqData);\n ASSERT(pcExtra);\n\n if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) {\n return -EINVAL;\n }\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n\n u4SubCmd = (UINT_32) prIwReqData->mode;\n pu4IntBuf = (PUINT_32) pcExtra;\n\n switch (u4SubCmd) {\n case PRIV_CMD_TEST_MODE:\n //printk(\"TestMode=%ld\\n\", pu4IntBuf[1]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n if (pu4IntBuf[1] == PRIV_CMD_TEST_MAGIC_KEY) {\n prNdisReq->ndisOidCmd = OID_CUSTOM_TEST_MODE;\n }\n else if (pu4IntBuf[1] == 0) {\n prNdisReq->ndisOidCmd = OID_CUSTOM_ABORT_TEST_MODE;\n }\n else {\n status = 0;\n break;\n }\n prNdisReq->inNdisOidlength = 0;\n prNdisReq->outNdisOidLength = 0;\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen);\n break;\n\n case PRIV_CMD_TEST_CMD:\n //printk(\"CMD=0x%08lx, data=0x%08lx\\n\", pu4IntBuf[1], pu4IntBuf[2]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_MTK_WIFI_TEST;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen);\n break;\n\n#if CFG_SUPPORT_PRIV_MCR_RW\n case PRIV_CMD_ACCESS_MCR:\n //printk(\"addr=0x%08lx, data=0x%08lx\\n\", pu4IntBuf[1], pu4IntBuf[2]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n if (!prGlueInfo->fgMcrAccessAllowed) {\n if (pu4IntBuf[1] == PRIV_CMD_TEST_MAGIC_KEY &&\n pu4IntBuf[2] == PRIV_CMD_TEST_MAGIC_KEY) {\n prGlueInfo->fgMcrAccessAllowed = TRUE;\n }\n status = 0;\n break;\n }\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_MCR_RW;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen);\n break;\n#endif\n\n case PRIV_CMD_SW_CTRL:\n //printk(\"addr=0x%08lx, data=0x%08lx\\n\", pu4IntBuf[1], pu4IntBuf[2]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen);\n break;\n\n\n #if 0\n case PRIV_CMD_BEACON_PERIOD:\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetBeaconInterval,\n (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */\n sizeof(UINT_32),\n &u4BufLen);\n break;\n #endif\n\n#if CFG_TCP_IP_CHKSUM_OFFLOAD\n case PRIV_CMD_CSUM_OFFLOAD:\n {\n UINT_32 u4CSUMFlags;\n\n\n if (pu4IntBuf[1] == 1) {\n u4CSUMFlags = CSUM_OFFLOAD_EN_ALL;\n }\n else if (pu4IntBuf[1] == 0) {\n u4CSUMFlags = 0;\n }\n else {\n return -EINVAL;\n }\n\n if (kalIoctl(prGlueInfo,\n wlanoidSetCSUMOffload,\n (PVOID)&u4CSUMFlags,\n sizeof(UINT_32),\n FALSE,\n FALSE,\n TRUE,\n FALSE,\n &u4BufLen\n ) == WLAN_STATUS_SUCCESS) {\n if (pu4IntBuf[1] == 1) {\n prNetDev->features |= NETIF_F_HW_CSUM;\n } else if (pu4IntBuf[1] == 0) {\n prNetDev->features &= ~NETIF_F_HW_CSUM;\n }\n }\n }\n break;\n#endif /* CFG_TCP_IP_CHKSUM_OFFLOAD */\n\n case PRIV_CMD_POWER_MODE:\n kalIoctl(prGlueInfo,\n wlanoidSet802dot11PowerSaveProfile,\n (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */\n sizeof(UINT_32),\n FALSE,\n FALSE,\n TRUE,\n FALSE,\n &u4BufLen);\n break;\n\n case PRIV_CMD_WMM_PS:\n {\n PARAM_CUSTOM_WMM_PS_TEST_STRUC_T rWmmPsTest;\n\n rWmmPsTest.bmfgApsdEnAc = (UINT_8)pu4IntBuf[1];\n rWmmPsTest.ucIsEnterPsAtOnce = (UINT_8)pu4IntBuf[2];\n rWmmPsTest.ucIsDisableUcTrigger = (UINT_8)pu4IntBuf[3];\n rWmmPsTest.reserved = 0;\n\n kalIoctl(prGlueInfo,\n wlanoidSetWiFiWmmPsTest,\n (PVOID)&rWmmPsTest,\n sizeof(PARAM_CUSTOM_WMM_PS_TEST_STRUC_T),\n FALSE,\n FALSE,\n TRUE,\n FALSE,\n &u4BufLen);\n }\n break;\n\n #if 0\n case PRIV_CMD_ADHOC_MODE:\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetAdHocMode,\n (PVOID)&pu4IntBuf[1], /* pu4IntBuf[0] is used as input SubCmd */\n sizeof(UINT_32),\n &u4BufLen);\n break;\n #endif\n\n case PRIV_CUSTOM_BWCS_CMD:\n\n DBGLOG(REQ, INFO, (\"pu4IntBuf[1] = %lx, size of PTA_IPC_T = %d.\\n\", pu4IntBuf[1], sizeof(PARAM_PTA_IPC_T)));\n\n prPtaIpc = (P_PTA_IPC_T) aucOidBuf;\n prPtaIpc->u.aucBTPParams[0] = (UINT_8) (pu4IntBuf[1] >> 24);\n prPtaIpc->u.aucBTPParams[1] = (UINT_8) (pu4IntBuf[1] >> 16);\n prPtaIpc->u.aucBTPParams[2] = (UINT_8) (pu4IntBuf[1] >> 8);\n prPtaIpc->u.aucBTPParams[3] = (UINT_8) (pu4IntBuf[1]);\n\n DBGLOG(REQ, INFO, (\"BCM BWCS CMD : PRIV_CUSTOM_BWCS_CMD : aucBTPParams[0] = %02x, aucBTPParams[1] = %02x, aucBTPParams[2] = %02x, aucBTPParams[3] = %02x.\\n\",\n prPtaIpc->u.aucBTPParams[0],\n prPtaIpc->u.aucBTPParams[1],\n prPtaIpc->u.aucBTPParams[2],\n prPtaIpc->u.aucBTPParams[3]));\n\n#if 0\n status = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetBT,\n (PVOID)&aucOidBuf[0],\n u4CmdLen,\n &u4BufLen);\n#endif\n\n status = wlanoidSetBT(prGlueInfo->prAdapter,\n (PVOID)&aucOidBuf[0],\n sizeof(PARAM_PTA_IPC_T),\n &u4BufLen);\n\n if (WLAN_STATUS_SUCCESS != status) {\n status = -EFAULT;\n }\n\n break;\n\n case PRIV_CMD_BAND_CONFIG:\n {\n DBGLOG(INIT, INFO, (\"CMD set_band=%lu\\n\", pu4IntBuf[1]));\n }\n break;\n\n#if CFG_ENABLE_WIFI_DIRECT\n case PRIV_CMD_P2P_MODE:\n {\n PARAM_CUSTOM_P2P_SET_STRUC_T rSetP2P;\n WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS;\n\n rSetP2P.u4Enable = pu4IntBuf[1];\n rSetP2P.u4Mode = pu4IntBuf[2];\n\n if(!rSetP2P.u4Enable) {\n p2pNetUnregister(prGlueInfo, TRUE);\n }\n\n rWlanStatus = kalIoctl(prGlueInfo,\n wlanoidSetP2pMode,\n (PVOID)&rSetP2P, /* pu4IntBuf[0] is used as input SubCmd */\n sizeof(PARAM_CUSTOM_P2P_SET_STRUC_T),\n FALSE,\n FALSE,\n TRUE,\n FALSE,\n &u4BufLen);\n\n if(rSetP2P.u4Enable) {\n p2pNetRegister(prGlueInfo, TRUE);\n }\n\n\n }\n break;\n#endif\n\n default:\n return -EOPNOTSUPP;\n }\n\n return status;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl get int handler.\n*\n* \\param[in] pDev Net device requested.\n* \\param[out] pIwReq Pointer to iwreq structure.\n* \\param[in] prIwReqData The ioctl req structure, use the field of sub-command.\n* \\param[out] pcExtra The buffer with put the return value\n*\n* \\retval 0 For success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EFAULT For fail.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_get_int (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN OUT char *pcExtra\n )\n{\n UINT_32 u4SubCmd;\n PUINT_32 pu4IntBuf;\n P_GLUE_INFO_T prGlueInfo;\n UINT_32 u4BufLen = 0;\n int status = 0;\n P_NDIS_TRANSPORT_STRUCT prNdisReq;\n INT_32 ch[50];\n\n ASSERT(prNetDev);\n ASSERT(prIwReqInfo);\n ASSERT(prIwReqData);\n ASSERT(pcExtra);\n if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) {\n return -EINVAL;\n }\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n\n u4SubCmd = (UINT_32) prIwReqData->mode;\n pu4IntBuf = (PUINT_32) pcExtra;\n\n switch (u4SubCmd) {\n case PRIV_CMD_TEST_CMD:\n //printk(\"CMD=0x%08lx, data=0x%08lx\\n\", pu4IntBuf[1], pu4IntBuf[2]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_MTK_WIFI_TEST;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen);\n if (status == 0) {\n //printk(\"Result=%ld\\n\", *(PUINT_32)&prNdisReq->ndisOidContent[4]);\n prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4];\n /*\n if (copy_to_user(prIwReqData->data.pointer,\n &prNdisReq->ndisOidContent[4], 4)) {\n printk(KERN_NOTICE \"priv_get_int() copy_to_user oidBuf fail(3)\\n\");\n return -EFAULT;\n }\n */\n }\n return status;\n\n#if CFG_SUPPORT_PRIV_MCR_RW\n case PRIV_CMD_ACCESS_MCR:\n //printk(\"addr=0x%08lx\\n\", pu4IntBuf[1]);\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n if (!prGlueInfo->fgMcrAccessAllowed) {\n status = 0;\n return status;\n }\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_MCR_RW;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen);\n if (status == 0) {\n //printk(\"Result=%ld\\n\", *(PUINT_32)&prNdisReq->ndisOidContent[4]);\n prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4];\n }\n return status;\n#endif\n\n case PRIV_CMD_DUMP_MEM:\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n#if 1\n if (!prGlueInfo->fgMcrAccessAllowed) {\n status = 0;\n return status;\n }\n#endif\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_MEM_DUMP;\n prNdisReq->inNdisOidlength = sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T);\n prNdisReq->outNdisOidLength = sizeof(PARAM_CUSTOM_MEM_DUMP_STRUC_T);\n\n status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen);\n if (status == 0) {\n prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[0];\n }\n return status;\n\n case PRIV_CMD_SW_CTRL:\n //printk(\" addr=0x%08lx\\n\", pu4IntBuf[1]);\n\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n kalMemCopy(&prNdisReq->ndisOidContent[0], &pu4IntBuf[1], 8);\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen);\n if (status == 0) {\n //printk(\"Result=%ld\\n\", *(PUINT_32)&prNdisReq->ndisOidContent[4]);\n prIwReqData->mode = *(PUINT_32)&prNdisReq->ndisOidContent[4];\n }\n return status;\n\n #if 0\n case PRIV_CMD_BEACON_PERIOD:\n status = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQueryBeaconInterval,\n (PVOID)pu4IntBuf,\n sizeof(UINT_32),\n &u4BufLen);\n return status;\n\n case PRIV_CMD_POWER_MODE:\n status = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQuery802dot11PowerSaveProfile,\n (PVOID)pu4IntBuf,\n sizeof(UINT_32),\n &u4BufLen);\n return status;\n\n case PRIV_CMD_ADHOC_MODE:\n status = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQueryAdHocMode,\n (PVOID)pu4IntBuf,\n sizeof(UINT_32),\n &u4BufLen);\n return status;\n #endif\n\n case PRIV_CMD_BAND_CONFIG:\n DBGLOG(INIT, INFO, (\"CMD get_band=\\n\"));\n prIwReqData->mode = 0;\n return status;\n\n default:\n break;\n }\n\n u4SubCmd = (UINT_32) prIwReqData->data.flags;\n\n switch (u4SubCmd) {\n case PRIV_CMD_GET_CH_LIST:\n {\n UINT_16 i, j = 0;\n UINT_8 NumOfChannel = 50;\n UINT_8 ucMaxChannelNum = 50;\n RF_CHANNEL_INFO_T aucChannelList[50];\n\n kalGetChannelList(prGlueInfo, BAND_NULL, ucMaxChannelNum, &NumOfChannel, aucChannelList);\n if (NumOfChannel > 50)\n NumOfChannel = 50;\n\n if (kalIsAPmode(prGlueInfo)) {\n for (i = 0; i < NumOfChannel; i++) {\n if ((aucChannelList[i].ucChannelNum <= 13) ||\n (aucChannelList[i].ucChannelNum == 36 || aucChannelList[i].ucChannelNum == 40 ||\n aucChannelList[i].ucChannelNum == 44 || aucChannelList[i].ucChannelNum == 48)) {\n ch[j] = (INT_32)aucChannelList[i].ucChannelNum;\n j++;\n }\n }\n }\n else {\n for (j = 0; j < NumOfChannel; j++) {\n ch[j] = (INT_32)aucChannelList[j].ucChannelNum;\n }\n }\n\n prIwReqData->data.length = j;\n if (copy_to_user(prIwReqData->data.pointer, ch, NumOfChannel*sizeof(INT_32))) {\n return -EFAULT;\n }\n else\n return status;\n }\n\n case PRIV_CMD_GET_BUILD_DATE_CODE:\n {\n UINT_8 aucBuffer[16];\n\n if(kalIoctl(prGlueInfo,\n wlanoidQueryBuildDateCode,\n (PVOID)aucBuffer,\n sizeof(UINT_8) * 16,\n TRUE,\n TRUE,\n TRUE,\n FALSE,\n &u4BufLen) == WLAN_STATUS_SUCCESS) {\n prIwReqData->data.length = sizeof(UINT_8) * 16;\n\n if (copy_to_user(prIwReqData->data.pointer, aucBuffer, prIwReqData->data.length)) {\n return -EFAULT;\n }\n else\n return status;\n }\n else {\n return -EFAULT;\n }\n }\n\n default:\n return -EOPNOTSUPP;\n }\n\n return status;\n} /* priv_get_int */\n\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl set int array handler.\n*\n* \\param[in] prNetDev Net device requested.\n* \\param[in] prIwReqInfo Pointer to iwreq structure.\n* \\param[in] prIwReqData The ioctl data structure, use the field of sub-command.\n* \\param[in] pcExtra The buffer with input value\n*\n* \\retval 0 For success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EINVAL If a value is out of range.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_set_ints (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN char *pcExtra\n )\n{\n UINT_32 u4SubCmd, u4BufLen;\n P_GLUE_INFO_T prGlueInfo;\n int status = 0;\n WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;\n P_SET_TXPWR_CTRL_T prTxpwr;\n\n ASSERT(prNetDev);\n ASSERT(prIwReqInfo);\n ASSERT(prIwReqData);\n ASSERT(pcExtra);\n\n if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) {\n return -EINVAL;\n }\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n\n u4SubCmd = (UINT_32) prIwReqData->data.flags;\n\n switch (u4SubCmd) {\n case PRIV_CMD_SET_TX_POWER:\n {\n INT_32 *setting = prIwReqData->data.pointer;\n UINT_16 i;\n\n#if 0\n printk(\"Tx power num = %d\\n\", prIwReqData->data.length);\n\n printk(\"Tx power setting = %d %d %d %d\\n\",\n setting[0], setting[1], setting[2], setting[3]);\n#endif\n prTxpwr = &prGlueInfo->rTxPwr;\n if (setting[0] == 0 && prIwReqData->data.length == 4 /* argc num */) {\n /* 0 (All networks), 1 (legacy STA), 2 (Hotspot AP), 3 (P2P), 4 (BT over Wi-Fi) */\n if (setting[1] == 1 || setting[1] == 0) {\n if (setting[2] == 0 || setting[2] == 1)\n prTxpwr->c2GLegacyStaPwrOffset = setting[3];\n if (setting[2] == 0 || setting[2] == 2)\n prTxpwr->c5GLegacyStaPwrOffset = setting[3];\n }\n if (setting[1] == 2 || setting[1] == 0) {\n if (setting[2] == 0 || setting[2] == 1)\n prTxpwr->c2GHotspotPwrOffset = setting[3];\n if (setting[2] == 0 || setting[2] == 2)\n prTxpwr->c5GHotspotPwrOffset = setting[3];\n }\n if (setting[1] == 3 || setting[1] == 0) {\n if (setting[2] == 0 || setting[2] == 1)\n prTxpwr->c2GP2pPwrOffset = setting[3];\n if (setting[2] == 0 || setting[2] == 2)\n prTxpwr->c5GP2pPwrOffset = setting[3];\n }\n if (setting[1] == 4 || setting[1] == 0) {\n if (setting[2] == 0 || setting[2] == 1)\n prTxpwr->c2GBowPwrOffset = setting[3];\n if (setting[2] == 0 || setting[2] == 2)\n prTxpwr->c5GBowPwrOffset = setting[3];\n }\n }\n else if (setting[0] == 1 && prIwReqData->data.length == 2) {\n prTxpwr->ucConcurrencePolicy = setting[1];\n }\n else if (setting[0] == 2 && prIwReqData->data.length == 3) {\n if (setting[1] == 0) {\n for (i=0; i<14; i++)\n prTxpwr->acTxPwrLimit2G[i] = setting[2];\n }\n else if (setting[1] <= 14)\n prTxpwr->acTxPwrLimit2G[setting[1] - 1] = setting[2];\n }\n else if (setting[0] == 3 && prIwReqData->data.length == 3) {\n if (setting[1] == 0) {\n for (i=0; i<4; i++)\n prTxpwr->acTxPwrLimit5G[i] = setting[2];\n }\n else if (setting[1] <= 4)\n prTxpwr->acTxPwrLimit5G[setting[1] - 1] = setting[2];\n }\n else if (setting[0] == 4 && prIwReqData->data.length == 2) {\n if (setting[1] == 0) {\n wlanDefTxPowerCfg(prGlueInfo->prAdapter);\n }\n rStatus = kalIoctl(prGlueInfo,\n wlanoidSetTxPower,\n prTxpwr,\n sizeof(SET_TXPWR_CTRL_T),\n TRUE,\n FALSE,\n FALSE,\n FALSE,\n &u4BufLen);\n }\n else\n return -EFAULT;\n }\n return status;\n default:\n break;\n }\n\n return status;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl get int array handler.\n*\n* \\param[in] pDev Net device requested.\n* \\param[out] pIwReq Pointer to iwreq structure.\n* \\param[in] prIwReqData The ioctl req structure, use the field of sub-command.\n* \\param[out] pcExtra The buffer with put the return value\n*\n* \\retval 0 For success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EFAULT For fail.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_get_ints (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN OUT char *pcExtra\n )\n{\n UINT_32 u4SubCmd;\n P_GLUE_INFO_T prGlueInfo;\n int status = 0;\n INT_32 ch[50];\n\n ASSERT(prNetDev);\n ASSERT(prIwReqInfo);\n ASSERT(prIwReqData);\n ASSERT(pcExtra);\n if (FALSE == GLUE_CHK_PR3(prNetDev, prIwReqData, pcExtra)) {\n return -EINVAL;\n }\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n\n u4SubCmd = (UINT_32) prIwReqData->data.flags;\n\n switch (u4SubCmd) {\n case PRIV_CMD_GET_CH_LIST:\n {\n UINT_16 i;\n UINT_8 NumOfChannel = 50;\n UINT_8 ucMaxChannelNum = 50;\n RF_CHANNEL_INFO_T aucChannelList[50];\n\n kalGetChannelList(prGlueInfo, BAND_NULL, ucMaxChannelNum, &NumOfChannel, aucChannelList);\n if (NumOfChannel > 50)\n NumOfChannel = 50;\n\n for (i = 0; i < NumOfChannel; i++) {\n ch[i] = (INT_32)aucChannelList[i].ucChannelNum;\n }\n\n prIwReqData->data.length = NumOfChannel;\n if (copy_to_user(prIwReqData->data.pointer, ch, NumOfChannel*sizeof(INT_32))) {\n return -EFAULT;\n }\n else\n return status;\n }\n default:\n break;\n }\n\n return status;\n} /* priv_get_int */\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl set structure handler.\n*\n* \\param[in] pDev Net device requested.\n* \\param[in] prIwReqData Pointer to iwreq_data structure.\n*\n* \\retval 0 For success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EINVAL If a value is out of range.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_set_struct (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN char *pcExtra\n )\n{\n UINT_32 u4SubCmd = 0;\n int status = 0;\n //WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;\n UINT_32 u4CmdLen = 0;\n P_NDIS_TRANSPORT_STRUCT prNdisReq;\n PUINT_32 pu4IntBuf = NULL;\n\n P_GLUE_INFO_T prGlueInfo = NULL;\n UINT_32 u4BufLen = 0;\n\n ASSERT(prNetDev);\n //ASSERT(prIwReqInfo);\n ASSERT(prIwReqData);\n //ASSERT(pcExtra);\n\n\tkalMemZero(&aucOidBuf[0], sizeof(aucOidBuf));\n\n if (FALSE == GLUE_CHK_PR2(prNetDev, prIwReqData)) {\n return -EINVAL;\n }\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n\n u4SubCmd = (UINT_32) prIwReqData->data.flags;\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_set_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\\n\",\n prIwReqInfo->cmd,\n u4SubCmd\n );\n#endif\n\n switch (u4SubCmd) {\n#if 0 //PTA_ENABLED\n case PRIV_CMD_BT_COEXIST:\n u4CmdLen = prIwReqData->data.length * sizeof(UINT_32);\n ASSERT(sizeof(PARAM_CUSTOM_BT_COEXIST_T) >= u4CmdLen);\n if (sizeof(PARAM_CUSTOM_BT_COEXIST_T) < u4CmdLen) {\n return -EFAULT;\n }\n\n if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, u4CmdLen)) {\n status = -EFAULT; //return -EFAULT;\n break;\n }\n\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetBtCoexistCtrl,\n (PVOID)&aucOidBuf[0],\n u4CmdLen,\n &u4BufLen);\n if (WLAN_STATUS_SUCCESS != rStatus) {\n status = -EFAULT;\n }\n break;\n#endif\n\n case PRIV_CUSTOM_BWCS_CMD:\n u4CmdLen = prIwReqData->data.length * sizeof(UINT_32);\n ASSERT(sizeof(PARAM_PTA_IPC_T) >= u4CmdLen);\n if (sizeof(PARAM_PTA_IPC_T) < u4CmdLen) {\n return -EFAULT;\n }\n#if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS && CFG_SUPPORT_BCM_BWCS_DEBUG\n DBGLOG(REQ, INFO, (\"ucCmdLen = %d, size of PTA_IPC_T = %d, prIwReqData->data = 0x%x.\\n\", u4CmdLen, sizeof(PARAM_PTA_IPC_T), prIwReqData->data));\n\n DBGLOG(REQ, INFO, (\"priv_set_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\\n\",\n prIwReqInfo->cmd,\n u4SubCmd\n ));\n\n DBGLOG(REQ, INFO, (\"*pcExtra = 0x%x\\n\", *pcExtra));\n #endif\n\n if (copy_from_user(&aucOidBuf[0], prIwReqData->data.pointer, u4CmdLen)) {\n status = -EFAULT; //return -EFAULT;\n break;\n }\n#if CFG_SUPPORT_BCM && CFG_SUPPORT_BCM_BWCS && CFG_SUPPORT_BCM_BWCS_DEBUG\n DBGLOG(REQ, INFO, (\"priv_set_struct(): BWCS CMD = %02x%02x%02x%02x\\n\",\n aucOidBuf[2], aucOidBuf[3], aucOidBuf[4], aucOidBuf[5]));\n#endif\n\n#if 0\n status = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetBT,\n (PVOID)&aucOidBuf[0],\n u4CmdLen,\n &u4BufLen);\n#endif\n\n#if 1\n status = wlanoidSetBT(prGlueInfo->prAdapter,\n (PVOID)&aucOidBuf[0],\n u4CmdLen,\n &u4BufLen);\n#endif\n\n if (WLAN_STATUS_SUCCESS != status) {\n status = -EFAULT;\n }\n\n break;\n\n#if CFG_SUPPORT_WPS2\n case PRIV_CMD_WSC_PROBE_REQ:\n\t\t{\n\t\t\t/* retrieve IE for Probe Request */\n if (prIwReqData->data.length > 0) {\n\t\t\t\tif (copy_from_user(prGlueInfo->aucWSCIE, prIwReqData->data.pointer,\n\t\t\t\t\tprIwReqData->data.length)) {\n status = -EFAULT;\n\t\t\t\t break;\n }\n\t\t\t\tprGlueInfo->u2WSCIELen = prIwReqData->data.length;\n }\n\t\t\telse {\n\t\t\t prGlueInfo->u2WSCIELen = 0;\n\t\t\t}\n \t}\n\t\tbreak;\n#endif\n case PRIV_CMD_OID:\n if (copy_from_user(&aucOidBuf[0],\n prIwReqData->data.pointer,\n prIwReqData->data.length)) {\n status = -EFAULT;\n break;\n }\n if (!kalMemCmp(&aucOidBuf[0], pcExtra, prIwReqData->data.length)) {\n DBGLOG(REQ, INFO, (\"pcExtra buffer is valid\\n\"));\n }\n else\n DBGLOG(REQ, INFO, (\"pcExtra 0x%p\\n\", pcExtra));\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, (P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0], &u4BufLen);\n /* Copy result to user space */\n ((P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0])->outNdisOidLength = u4BufLen;\n\n if (copy_to_user(prIwReqData->data.pointer,\n &aucOidBuf[0],\n OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent))) {\n DBGLOG(REQ, INFO, (\"copy_to_user oidBuf fail\\n\"));\n status = -EFAULT;\n }\n\n break;\n\n case PRIV_CMD_SW_CTRL:\n pu4IntBuf = (PUINT_32)prIwReqData->data.pointer;\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n //kalMemCopy(&prNdisReq->ndisOidContent[0], prIwReqData->data.pointer, 8);\n if (copy_from_user(&prNdisReq->ndisOidContent[0],\n prIwReqData->data.pointer,\n prIwReqData->data.length)) {\n status = -EFAULT;\n break;\n }\n prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n /* Execute this OID */\n status = priv_set_ndis(prNetDev, prNdisReq, &u4BufLen);\n break;\n\n default:\n return -EOPNOTSUPP;\n }\n\n return status;\n}\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief Private ioctl get struct handler.\n*\n* \\param[in] pDev Net device requested.\n* \\param[out] pIwReq Pointer to iwreq structure.\n* \\param[in] cmd Private sub-command.\n*\n* \\retval 0 For success.\n* \\retval -EFAULT If copy from user space buffer fail.\n* \\retval -EOPNOTSUPP Parameter \"cmd\" not recognized.\n*\n*/\n/*----------------------------------------------------------------------------*/\nint\npriv_get_struct (\n IN struct net_device *prNetDev,\n IN struct iw_request_info *prIwReqInfo,\n IN union iwreq_data *prIwReqData,\n IN OUT char *pcExtra\n )\n{\n UINT_32 u4SubCmd = 0;\n P_NDIS_TRANSPORT_STRUCT prNdisReq= NULL;\n\n P_GLUE_INFO_T prGlueInfo = NULL;\n UINT_32 u4BufLen = 0;\n PUINT_32 pu4IntBuf = NULL;\n int status = 0;\n\n kalMemZero(&aucOidBuf[0], sizeof(aucOidBuf));\n\n ASSERT(prNetDev);\n ASSERT(prIwReqData);\n if (!prNetDev || !prIwReqData) {\n DBGLOG(REQ, INFO, (\"priv_get_struct(): invalid param(0x%p, 0x%p)\\n\",\n prNetDev, prIwReqData));\n return -EINVAL;\n }\n\n u4SubCmd = (UINT_32) prIwReqData->data.flags;\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n ASSERT(prGlueInfo);\n if (!prGlueInfo) {\n DBGLOG(REQ, INFO, (\"priv_get_struct(): invalid prGlueInfo(0x%p, 0x%p)\\n\",\n prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev))));\n return -EINVAL;\n }\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_get_struct(): prIwReqInfo->cmd(0x%X), u4SubCmd(%ld)\\n\",\n prIwReqInfo->cmd,\n u4SubCmd\n );\n#endif\n memset(aucOidBuf, 0, sizeof(aucOidBuf));\n\n switch (u4SubCmd) {\n case PRIV_CMD_OID:\n if (copy_from_user(&aucOidBuf[0],\n prIwReqData->data.pointer,\n sizeof(NDIS_TRANSPORT_STRUCT))) {\n DBGLOG(REQ, INFO, (\"priv_get_struct() copy_from_user oidBuf fail\\n\"));\n return -EFAULT;\n }\n\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT)&aucOidBuf[0];\n#if 0\n printk(KERN_NOTICE \"\\n priv_get_struct cmd 0x%02x len:%d OID:0x%08x OID Len:%d\\n\",\n cmd,\n pIwReq->u.data.length,\n ndisReq->ndisOidCmd,\n ndisReq->inNdisOidlength);\n#endif\n if (priv_get_ndis(prNetDev, prNdisReq, &u4BufLen) == 0) {\n prNdisReq->outNdisOidLength = u4BufLen;\n if (copy_to_user(prIwReqData->data.pointer,\n &aucOidBuf[0],\n u4BufLen + sizeof(NDIS_TRANSPORT_STRUCT) - sizeof(prNdisReq->ndisOidContent))) {\n DBGLOG(REQ, INFO, (\"priv_get_struct() copy_to_user oidBuf fail(1)\\n\"));\n return -EFAULT;\n }\n return 0;\n }\n else {\n prNdisReq->outNdisOidLength = u4BufLen;\n if (copy_to_user(prIwReqData->data.pointer,\n &aucOidBuf[0],\n OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent))) {\n DBGLOG(REQ, INFO, (\"priv_get_struct() copy_to_user oidBuf fail(2)\\n\"));\n }\n return -EFAULT;\n }\n break;\n\n case PRIV_CMD_SW_CTRL:\n pu4IntBuf = (PUINT_32)prIwReqData->data.pointer;\n prNdisReq = (P_NDIS_TRANSPORT_STRUCT) &aucOidBuf[0];\n\n if (copy_from_user(&prNdisReq->ndisOidContent[0],\n prIwReqData->data.pointer,\n prIwReqData->data.length)) {\n DBGLOG(REQ, INFO, (\"priv_get_struct() copy_from_user oidBuf fail\\n\"));\n return -EFAULT;\n }\n\n prNdisReq->ndisOidCmd = OID_CUSTOM_SW_CTRL;\n prNdisReq->inNdisOidlength = 8;\n prNdisReq->outNdisOidLength = 8;\n\n status = priv_get_ndis(prNetDev, prNdisReq, &u4BufLen);\n if (status == 0) {\n prNdisReq->outNdisOidLength = u4BufLen;\n //printk(\"len=%d Result=%08lx\\n\", u4BufLen, *(PUINT_32)&prNdisReq->ndisOidContent[4]);\n\n if (copy_to_user(prIwReqData->data.pointer,\n &prNdisReq->ndisOidContent[4],\n 4 /* OFFSET_OF(NDIS_TRANSPORT_STRUCT, ndisOidContent)*/)) {\n DBGLOG(REQ, INFO, (\"priv_get_struct() copy_to_user oidBuf fail(2)\\n\"));\n }\n }\n return 0;\n break;\n default:\n DBGLOG(REQ, WARN, (\"get struct cmd:0x%lx\\n\", u4SubCmd));\n return -EOPNOTSUPP;\n }\n} /* priv_get_struct */\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief The routine handles a set operation for a single OID.\n*\n* \\param[in] pDev Net device requested.\n* \\param[in] ndisReq Ndis request OID information copy from user.\n* \\param[out] outputLen_p If the call is successful, returns the number of\n* bytes written into the query buffer. If the\n* call failed due to invalid length of the query\n* buffer, returns the amount of storage needed..\n*\n* \\retval 0 On success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n*\n*/\n/*----------------------------------------------------------------------------*/\nstatic int\npriv_set_ndis (\n IN struct net_device *prNetDev,\n IN NDIS_TRANSPORT_STRUCT* prNdisReq,\n OUT PUINT_32 pu4OutputLen\n )\n{\n P_WLAN_REQ_ENTRY prWlanReqEntry = NULL;\n WLAN_STATUS status = WLAN_STATUS_SUCCESS;\n P_GLUE_INFO_T prGlueInfo = NULL;\n UINT_32 u4SetInfoLen = 0;\n\n ASSERT(prNetDev);\n ASSERT(prNdisReq);\n ASSERT(pu4OutputLen);\n\n if (!prNetDev || !prNdisReq || !pu4OutputLen) {\n DBGLOG(REQ, INFO, (\"priv_set_ndis(): invalid param(0x%p, 0x%p, 0x%p)\\n\",\n prNetDev, prNdisReq, pu4OutputLen));\n return -EINVAL;\n }\n\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n ASSERT(prGlueInfo);\n if (!prGlueInfo) {\n DBGLOG(REQ, INFO, (\"priv_set_ndis(): invalid prGlueInfo(0x%p, 0x%p)\\n\",\n prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev))));\n return -EINVAL;\n }\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_set_ndis(): prNdisReq->ndisOidCmd(0x%lX)\\n\",\n prNdisReq->ndisOidCmd\n );\n#endif\n\n if (FALSE == reqSearchSupportedOidEntry(prNdisReq->ndisOidCmd,\n &prWlanReqEntry)) {\n //WARNLOG((\"Set OID: 0x%08lx (unknown)\\n\", prNdisReq->ndisOidCmd));\n return -EOPNOTSUPP;\n }\n\n if (NULL == prWlanReqEntry->pfOidSetHandler) {\n //WARNLOG((\"Set %s: Null set handler\\n\", prWlanReqEntry->pucOidName));\n return -EOPNOTSUPP;\n }\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_set_ndis(): %s\\n\",\n prWlanReqEntry->pucOidName\n );\n#endif\n\n if (prWlanReqEntry->fgSetBufLenChecking) {\n if (prNdisReq->inNdisOidlength != prWlanReqEntry->u4InfoBufLen) {\n DBGLOG(REQ, WARN, (\"Set %s: Invalid length (current=%ld, needed=%ld)\\n\",\n prWlanReqEntry->pucOidName,\n prNdisReq->inNdisOidlength,\n prWlanReqEntry->u4InfoBufLen));\n\n *pu4OutputLen = prWlanReqEntry->u4InfoBufLen;\n return -EINVAL;\n }\n }\n\n if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_ONLY) {\n /* GLUE sw info only */\n status = prWlanReqEntry->pfOidSetHandler(prGlueInfo,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n &u4SetInfoLen);\n }\n else if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_EXTENSION) {\n /* multiple sw operations */\n status = prWlanReqEntry->pfOidSetHandler(prGlueInfo,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n &u4SetInfoLen);\n }\n else if (prWlanReqEntry->eOidMethod == ENUM_OID_DRIVER_CORE) {\n /* driver core*/\n\n status = kalIoctl(prGlueInfo,\n (PFN_OID_HANDLER_FUNC)prWlanReqEntry->pfOidSetHandler,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n FALSE,\n FALSE,\n TRUE,\n FALSE,\n &u4SetInfoLen);\n }\n else {\n DBGLOG(REQ, INFO, (\"priv_set_ndis(): unsupported OID method:0x%x\\n\",\n prWlanReqEntry->eOidMethod));\n return -EOPNOTSUPP;\n }\n\n *pu4OutputLen = u4SetInfoLen;\n\n switch (status) {\n case WLAN_STATUS_SUCCESS:\n break;\n\n case WLAN_STATUS_INVALID_LENGTH:\n //WARNLOG((\"Set %s: Invalid length (current=%ld, needed=%ld)\\n\",\n // prWlanReqEntry->pucOidName,\n //prNdisReq->inNdisOidlength,\n //u4SetInfoLen));\n break;\n }\n\n if (WLAN_STATUS_SUCCESS != status) {\n return -EFAULT;\n }\n\n return 0;\n} /* priv_set_ndis */\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief The routine handles a query operation for a single OID. Basically we\n* return information about the current state of the OID in question.\n*\n* \\param[in] pDev Net device requested.\n* \\param[in] ndisReq Ndis request OID information copy from user.\n* \\param[out] outputLen_p If the call is successful, returns the number of\n* bytes written into the query buffer. If the\n* call failed due to invalid length of the query\n* buffer, returns the amount of storage needed..\n*\n* \\retval 0 On success.\n* \\retval -EOPNOTSUPP If cmd is not supported.\n* \\retval -EINVAL invalid input parameters\n*\n*/\n/*----------------------------------------------------------------------------*/\nstatic int\npriv_get_ndis (\n IN struct net_device *prNetDev,\n IN NDIS_TRANSPORT_STRUCT* prNdisReq,\n OUT PUINT_32 pu4OutputLen\n )\n{\n P_WLAN_REQ_ENTRY prWlanReqEntry = NULL;\n UINT_32 u4BufLen = 0;\n WLAN_STATUS status = WLAN_STATUS_SUCCESS;\n P_GLUE_INFO_T prGlueInfo = NULL;\n\n ASSERT(prNetDev);\n ASSERT(prNdisReq);\n ASSERT(pu4OutputLen);\n\n if (!prNetDev || !prNdisReq || !pu4OutputLen) {\n DBGLOG(REQ, INFO, (\"priv_get_ndis(): invalid param(0x%p, 0x%p, 0x%p)\\n\",\n prNetDev, prNdisReq, pu4OutputLen));\n return -EINVAL;\n }\n\n prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prNetDev));\n ASSERT(prGlueInfo);\n if (!prGlueInfo) {\n DBGLOG(REQ, INFO, (\"priv_get_ndis(): invalid prGlueInfo(0x%p, 0x%p)\\n\",\n prNetDev, *((P_GLUE_INFO_T *) netdev_priv(prNetDev))));\n return -EINVAL;\n }\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_get_ndis(): prNdisReq->ndisOidCmd(0x%lX)\\n\",\n prNdisReq->ndisOidCmd\n );\n#endif\n\n if (FALSE == reqSearchSupportedOidEntry(prNdisReq->ndisOidCmd,\n &prWlanReqEntry)) {\n //WARNLOG((\"Query OID: 0x%08lx (unknown)\\n\", prNdisReq->ndisOidCmd));\n return -EOPNOTSUPP;\n }\n\n\n if (NULL == prWlanReqEntry->pfOidQueryHandler) {\n //WARNLOG((\"Query %s: Null query handler\\n\", prWlanReqEntry->pucOidName));\n return -EOPNOTSUPP;\n }\n\n#if 0\n printk(KERN_INFO DRV_NAME\"priv_get_ndis(): %s\\n\",\n prWlanReqEntry->pucOidName\n );\n#endif\n\n if (prWlanReqEntry->fgQryBufLenChecking) {\n if (prNdisReq->inNdisOidlength < prWlanReqEntry->u4InfoBufLen) {\n /* Not enough room in InformationBuffer. Punt */\n //WARNLOG((\"Query %s: Buffer too short (current=%ld, needed=%ld)\\n\",\n //prWlanReqEntry->pucOidName,\n //prNdisReq->inNdisOidlength,\n //prWlanReqEntry->u4InfoBufLen));\n\n *pu4OutputLen = prWlanReqEntry->u4InfoBufLen;\n\n status = WLAN_STATUS_INVALID_LENGTH;\n return -EINVAL;\n }\n }\n\n\n if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_ONLY) {\n /* GLUE sw info only */\n status = prWlanReqEntry->pfOidQueryHandler(prGlueInfo,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n &u4BufLen);\n }\n else if (prWlanReqEntry->eOidMethod == ENUM_OID_GLUE_EXTENSION) {\n /* multiple sw operations */\n status = prWlanReqEntry->pfOidQueryHandler(prGlueInfo,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n &u4BufLen);\n }\n else if (prWlanReqEntry->eOidMethod == ENUM_OID_DRIVER_CORE) {\n /* driver core*/\n\n status = kalIoctl(prGlueInfo,\n (PFN_OID_HANDLER_FUNC)prWlanReqEntry->pfOidQueryHandler,\n prNdisReq->ndisOidContent,\n prNdisReq->inNdisOidlength,\n TRUE,\n TRUE,\n TRUE,\n FALSE,\n &u4BufLen);\n }\n else {\n DBGLOG(REQ, INFO, (\"priv_set_ndis(): unsupported OID method:0x%x\\n\",\n prWlanReqEntry->eOidMethod));\n return -EOPNOTSUPP;\n }\n\n *pu4OutputLen = u4BufLen;\n\n switch (status) {\n case WLAN_STATUS_SUCCESS:\n break;\n\n case WLAN_STATUS_INVALID_LENGTH:\n //WARNLOG((\"Set %s: Invalid length (current=%ld, needed=%ld)\\n\",\n // prWlanReqEntry->pucOidName,\n //prNdisReq->inNdisOidlength,\n //u4BufLen));\n break;\n }\n\n if (WLAN_STATUS_SUCCESS != status) {\n return -EOPNOTSUPP;\n }\n\n return 0;\n} /* priv_get_ndis */\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief This routine is called to search desired OID.\n*\n* \\param rOid[in] Desired NDIS_OID\n* \\param ppWlanReqEntry[out] Found registered OID entry\n*\n* \\retval TRUE: Matched OID is found\n* \\retval FALSE: No matched OID is found\n*/\n/*----------------------------------------------------------------------------*/\nstatic BOOLEAN\nreqSearchSupportedOidEntry (\n IN UINT_32 rOid,\n OUT P_WLAN_REQ_ENTRY *ppWlanReqEntry\n )\n{\n INT_32 i, j, k;\n\n i = 0;\n j = NUM_SUPPORTED_OIDS - 1;\n\n while (i <= j) {\n k = (i + j) / 2;\n\n if (rOid == arWlanOidReqTable[k].rOid) {\n *ppWlanReqEntry = &arWlanOidReqTable[k];\n return TRUE;\n } else if (rOid < arWlanOidReqTable[k].rOid) {\n j = k - 1;\n } else {\n i = k + 1;\n }\n }\n\n return FALSE;\n} /* reqSearchSupportedOidEntry */\n\n#if 0\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief This routine is called to query the radio configuration used in IBSS\n* mode and RF test mode.\n*\n* \\param[in] prGlueInfo Pointer to the GLUE_INFO_T structure.\n* \\param[out] pvQueryBuffer Pointer to the buffer that holds the result of the query.\n* \\param[in] u4QueryBufferLen The length of the query buffer.\n* \\param[out] pu4QueryInfoLen If the call is successful, returns the number of\n* bytes written into the query buffer. If the call\n* failed due to invalid length of the query buffer,\n* returns the amount of storage needed.\n*\n* \\retval WLAN_STATUS_SUCCESS\n* \\retval WLAN_STATUS_INVALID_LENGTH\n*/\n/*----------------------------------------------------------------------------*/\nstatic WLAN_STATUS\nreqExtQueryConfiguration (\n IN P_GLUE_INFO_T prGlueInfo,\n OUT PVOID pvQueryBuffer,\n IN UINT_32 u4QueryBufferLen,\n OUT PUINT_32 pu4QueryInfoLen\n )\n{\n P_PARAM_802_11_CONFIG_T prQueryConfig = (P_PARAM_802_11_CONFIG_T)pvQueryBuffer;\n WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;\n UINT_32 u4QueryInfoLen = 0;\n\n DEBUGFUNC(\"wlanoidQueryConfiguration\");\n\n\n ASSERT(prGlueInfo);\n ASSERT(pu4QueryInfoLen);\n\n *pu4QueryInfoLen = sizeof(PARAM_802_11_CONFIG_T);\n if (u4QueryBufferLen < sizeof(PARAM_802_11_CONFIG_T)) {\n return WLAN_STATUS_INVALID_LENGTH;\n }\n\n ASSERT(pvQueryBuffer);\n\n kalMemZero(prQueryConfig, sizeof(PARAM_802_11_CONFIG_T));\n\n /* Update the current radio configuration. */\n prQueryConfig->u4Length = sizeof(PARAM_802_11_CONFIG_T);\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidSetBeaconInterval,\n &prQueryConfig->u4BeaconPeriod,\n sizeof(UINT_32),\n TRUE,\n TRUE,\n &u4QueryInfoLen);\n#else\n rStatus = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQueryBeaconInterval,\n &prQueryConfig->u4BeaconPeriod,\n sizeof(UINT_32),\n &u4QueryInfoLen);\n#endif\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidQueryAtimWindow,\n &prQueryConfig->u4ATIMWindow,\n sizeof(UINT_32),\n TRUE,\n TRUE,\n &u4QueryInfoLen);\n#else\n rStatus = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQueryAtimWindow,\n &prQueryConfig->u4ATIMWindow,\n sizeof(UINT_32),\n &u4QueryInfoLen);\n#endif\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidQueryFrequency,\n &prQueryConfig->u4DSConfig,\n sizeof(UINT_32),\n TRUE,\n TRUE,\n &u4QueryInfoLen);\n#else\n rStatus = wlanQueryInformation(prGlueInfo->prAdapter,\n wlanoidQueryFrequency,\n &prQueryConfig->u4DSConfig,\n sizeof(UINT_32),\n &u4QueryInfoLen);\n#endif\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n prQueryConfig->rFHConfig.u4Length = sizeof(PARAM_802_11_CONFIG_FH_T);\n\n return rStatus;\n\n} /* end of reqExtQueryConfiguration() */\n\n\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief This routine is called to set the radio configuration used in IBSS\n* mode.\n*\n* \\param[in] prGlueInfo Pointer to the GLUE_INFO_T structure.\n* \\param[in] pvSetBuffer A pointer to the buffer that holds the data to be set.\n* \\param[in] u4SetBufferLen The length of the set buffer.\n* \\param[out] pu4SetInfoLen If the call is successful, returns the number of\n* bytes read from the set buffer. If the call failed\n* due to invalid length of the set buffer, returns\n* the amount of storage needed.\n*\n* \\retval WLAN_STATUS_SUCCESS\n* \\retval WLAN_STATUS_INVALID_LENGTH\n* \\retval WLAN_STATUS_NOT_ACCEPTED\n*/\n/*----------------------------------------------------------------------------*/\nstatic WLAN_STATUS\nreqExtSetConfiguration (\n IN P_GLUE_INFO_T prGlueInfo,\n IN PVOID pvSetBuffer,\n IN UINT_32 u4SetBufferLen,\n OUT PUINT_32 pu4SetInfoLen\n )\n{\n WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;\n P_PARAM_802_11_CONFIG_T prNewConfig = (P_PARAM_802_11_CONFIG_T)pvSetBuffer;\n UINT_32 u4SetInfoLen = 0;\n\n DEBUGFUNC(\"wlanoidSetConfiguration\");\n\n\n ASSERT(prGlueInfo);\n ASSERT(pu4SetInfoLen);\n\n *pu4SetInfoLen = sizeof(PARAM_802_11_CONFIG_T);\n\n if (u4SetBufferLen < *pu4SetInfoLen) {\n return WLAN_STATUS_INVALID_LENGTH;\n }\n\n /* OID_802_11_CONFIGURATION. If associated, NOT_ACCEPTED shall be returned. */\n if (prGlueInfo->eParamMediaStateIndicated == PARAM_MEDIA_STATE_CONNECTED) {\n return WLAN_STATUS_NOT_ACCEPTED;\n }\n\n ASSERT(pvSetBuffer);\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidSetBeaconInterval,\n &prNewConfig->u4BeaconPeriod,\n sizeof(UINT_32),\n FALSE,\n TRUE,\n &u4SetInfoLen);\n#else\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetBeaconInterval,\n &prNewConfig->u4BeaconPeriod,\n sizeof(UINT_32),\n &u4SetInfoLen);\n#endif\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidSetAtimWindow,\n &prNewConfig->u4ATIMWindow,\n sizeof(UINT_32),\n FALSE,\n TRUE,\n &u4SetInfoLen);\n#else\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetAtimWindow,\n &prNewConfig->u4ATIMWindow,\n sizeof(UINT_32),\n &u4SetInfoLen);\n#endif\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n#if defined(_HIF_SDIO)\n rStatus = sdio_io_ctrl(prGlueInfo,\n wlanoidSetFrequency,\n &prNewConfig->u4DSConfig,\n sizeof(UINT_32),\n FALSE,\n TRUE,\n &u4SetInfoLen);\n#else\n rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n wlanoidSetFrequency,\n &prNewConfig->u4DSConfig,\n sizeof(UINT_32),\n &u4SetInfoLen);\n#endif\n\n if (rStatus != WLAN_STATUS_SUCCESS) {\n return rStatus;\n }\n\n return rStatus;\n\n} /* end of reqExtSetConfiguration() */\n\n#endif\n/*----------------------------------------------------------------------------*/\n/*!\n* \\brief This routine is called to set beacon detection function enable/disable state\n* This is mainly designed for usage under BT inquiry state (disable function).\n*\n* \\param[in] pvAdapter Pointer to the Adapter structure\n* \\param[in] pvSetBuffer A pointer to the buffer that holds the data to be set\n* \\param[in] u4SetBufferLen The length of the set buffer\n* \\param[out] pu4SetInfoLen If the call is successful, returns the number of\n* bytes read from the set buffer. If the call failed due to invalid length of\n* the set buffer, returns the amount of storage needed.\n*\n* \\retval WLAN_STATUS_SUCCESS\n* \\retval WLAN_STATUS_INVALID_DATA If new setting value is wrong.\n* \\retval WLAN_STATUS_INVALID_LENGTH\n*\n*/\n/*----------------------------------------------------------------------------*/\nstatic WLAN_STATUS\nreqExtSetAcpiDevicePowerState (\n IN P_GLUE_INFO_T prGlueInfo,\n IN PVOID pvSetBuffer,\n IN UINT_32 u4SetBufferLen,\n OUT PUINT_32 pu4SetInfoLen\n )\n{\n WLAN_STATUS rStatus = WLAN_STATUS_SUCCESS;\n\n ASSERT(prGlueInfo);\n ASSERT(pvSetBuffer);\n ASSERT(pu4SetInfoLen);\n\n /* WIFI is enabled, when ACPI is D0 (ParamDeviceStateD0 = 1). And vice versa */\n\n //rStatus = wlanSetInformation(prGlueInfo->prAdapter,\n // wlanoidSetAcpiDevicePowerState,\n // pvSetBuffer,\n // u4SetBufferLen,\n // pu4SetInfoLen);\n return rStatus;\n}\n\n"},"repo_name":{"kind":"string","value":"visi0nary/mediatek"},"path":{"kind":"string","value":"mt6732/mediatek/kernel/drivers/combo/drv_wlan/mt6628/wlan/os/linux/gl_wext_priv.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":76740,"string":"76,740"}}},{"rowIdx":115086043,"cells":{"code":{"kind":"string","value":"/******************************************************************************\n * xc_compression.c\n *\n * Checkpoint Compression using Page Delta Algorithm.\n * - A LRU cache of recently dirtied guest pages is maintained.\n * - For each dirty guest page in the checkpoint, if a previous version of the\n * page exists in the cache, XOR both pages and send the non-zero sections\n * to the receiver. The cache is then updated with the newer copy of guest page.\n * - The receiver will XOR the non-zero sections against its copy of the guest\n * page, thereby bringing the guest page up-to-date with the sender side.\n *\n * Copyright (c) 2011 Shriram Rajagopalan (rshriram@cs.ubc.ca).\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License.\n *\n * This library 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 GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \"xc_private.h\"\n#include \"xenctrl.h\"\n#include \"xg_save_restore.h\"\n#include \"xg_private.h\"\n#include \"xc_dom.h\"\n\n/* Page Cache for Delta Compression*/\n#define DELTA_CACHE_SIZE (XC_PAGE_SIZE * 8192)\n\n/* Internal page buffer to hold dirty pages of a checkpoint,\n * to be compressed after the domain is resumed for execution.\n */\n#define PAGE_BUFFER_SIZE (XC_PAGE_SIZE * 8192)\n\nstruct cache_page\n{\n char *page;\n xen_pfn_t pfn;\n struct cache_page *next;\n struct cache_page *prev;\n};\n\nstruct compression_ctx\n{\n /* compression buffer - holds compressed data */\n char *compbuf;\n unsigned long compbuf_size;\n unsigned long compbuf_pos;\n\n /* Page buffer to hold pages to be compressed */\n char *inputbuf;\n /* pfns of pages to be compressed */\n xen_pfn_t *sendbuf_pfns;\n unsigned int pfns_len;\n unsigned int pfns_index;\n\n /* Compression Cache (LRU) */\n char *cache_base;\n struct cache_page **pfn2cache;\n struct cache_page *cache;\n struct cache_page *page_list_head;\n struct cache_page *page_list_tail;\n unsigned long dom_pfnlist_size;\n};\n\n#define RUNFLAG 0\n#define SKIPFLAG ((char)128)\n#define FLAGMASK SKIPFLAG\n#define LENMASK ((char)127)\n\n/*\n * see xg_save_restore.h for details on the compressed stream format.\n * delta size = 4 bytes.\n * run header = 1 byte (1 bit for runtype, 7bits for run length).\n * i.e maximum size of a run = 127 * 4 = 508 bytes.\n * Worst case compression: Entire page has changed.\n * In the worst case, the size of the compressed page is\n * 8 runs of 508 bytes + 1 run of 32 bytes + 9 run headers \n * = 4105 bytes.\n * We could detect this worst case and send the entire page with a\n * FULL_PAGE marker, reducing the total size to 4097 bytes. The cost\n * of this size reduction is an additional memcpy, on top of two previous\n * memcpy (to the compressed stream and the cache page in the for loop).\n *\n * We might as well sacrifice an extra 8 bytes instead of a memcpy.\n */\n#define WORST_COMP_PAGE_SIZE (XC_PAGE_SIZE + 9)\n\n/*\n * A zero length skip indicates full page.\n */\n#define EMPTY_PAGE 0\n#define FULL_PAGE SKIPFLAG\n#define FULL_PAGE_SIZE (XC_PAGE_SIZE + 1)\n#define MAX_DELTAS (XC_PAGE_SIZE/sizeof(uint32_t))\n\n/*\n * Add a pagetable page or a new page (uncached)\n * if srcpage is a pagetable page, cache_page is null.\n * if srcpage is a page that was not previously in the cache,\n * cache_page points to a free page slot in the cache where\n * this new page can be copied to.\n */\nstatic int add_full_page(comp_ctx *ctx, char *srcpage, char *cache_page)\n{\n char *dest = (ctx->compbuf + ctx->compbuf_pos);\n\n if ( (ctx->compbuf_pos + FULL_PAGE_SIZE) > ctx->compbuf_size)\n return -1;\n\n if (cache_page)\n memcpy(cache_page, srcpage, XC_PAGE_SIZE);\n dest[0] = FULL_PAGE;\n memcpy(&dest[1], srcpage, XC_PAGE_SIZE);\n ctx->compbuf_pos += FULL_PAGE_SIZE;\n\n return FULL_PAGE_SIZE;\n}\n\nstatic int compress_page(comp_ctx *ctx, char *srcpage, char *cache_page)\n{\n char *dest = (ctx->compbuf + ctx->compbuf_pos);\n uint32_t *new, *old;\n\n int off, runptr = 0;\n int wascopying = 0, copying = 0, bytes_skipped = 0;\n int complen = 0, pageoff = 0, runbytes = 0;\n\n char runlen = 0;\n\n if ( (ctx->compbuf_pos + WORST_COMP_PAGE_SIZE) > ctx->compbuf_size)\n return -1;\n\n /*\n * There are no alignment issues here since srcpage is\n * domU's page passed from xc_domain_save and cache_page is\n * a ptr to cache page (cache is page aligned).\n */\n new = (uint32_t*)srcpage;\n old = (uint32_t*)cache_page;\n\n for (off = 0; off <= MAX_DELTAS; off++)\n {\n /*\n * At (off == MAX_DELTAS), we are processing the last run\n * in the page. Since there is no XORing, make wascopying != copying\n * to satisfy the if-block below.\n */\n copying = ((off < MAX_DELTAS) ? (old[off] != new[off]) : !wascopying);\n\n if (runlen)\n {\n /* switching between run types or current run is full */\n if ( (wascopying != copying) || (runlen == LENMASK) )\n {\n runbytes = runlen * sizeof(uint32_t);\n runlen |= (wascopying ? RUNFLAG : SKIPFLAG);\n dest[complen++] = runlen;\n\n if (wascopying) /* RUNFLAG */\n {\n pageoff = runptr * sizeof(uint32_t);\n memcpy(dest + complen, srcpage + pageoff, runbytes);\n memcpy(cache_page + pageoff, srcpage + pageoff, runbytes);\n complen += runbytes;\n }\n else /* SKIPFLAG */\n {\n bytes_skipped += runbytes;\n }\n\n runlen = 0;\n runptr = off;\n }\n }\n runlen++;\n wascopying = copying;\n }\n\n /*\n * Check for empty page.\n */\n if (bytes_skipped == XC_PAGE_SIZE)\n {\n complen = 1;\n dest[0] = EMPTY_PAGE;\n }\n ctx->compbuf_pos += complen;\n\n return complen;\n}\n\nstatic\nchar *get_cache_page(comp_ctx *ctx, xen_pfn_t pfn,\n int *israw)\n{\n struct cache_page *item = NULL;\n\n item = ctx->pfn2cache[pfn];\n\n if (!item)\n {\n *israw = 1;\n\n /* If the list is full, evict a page from the tail end. */\n item = ctx->page_list_tail;\n if (item->pfn != INVALID_P2M_ENTRY)\n ctx->pfn2cache[item->pfn] = NULL;\n\n item->pfn = pfn;\n ctx->pfn2cache[pfn] = item;\n }\n \n /* \tif requested item is in cache move to head of list */\n if (item != ctx->page_list_head)\n {\n if (item == ctx->page_list_tail)\n {\n /* item at tail of list. */\n ctx->page_list_tail = item->prev;\n (ctx->page_list_tail)->next = NULL;\n }\n else\n {\n /* item in middle of list */\n item->prev->next = item->next;\n item->next->prev = item->prev;\n }\n\n item->prev = NULL;\n item->next = ctx->page_list_head;\n (ctx->page_list_head)->prev = item;\n ctx->page_list_head = item;\n }\n\n return (ctx->page_list_head)->page;\n}\n\n/* Remove pagetable pages from cache and move to tail, as free pages */\nstatic\nvoid invalidate_cache_page(comp_ctx *ctx, xen_pfn_t pfn)\n{\n struct cache_page *item = NULL;\n\n item = ctx->pfn2cache[pfn];\n if (item)\n {\n if (item != ctx->page_list_tail)\n {\n /* item at head of list */\n if (item == ctx->page_list_head)\n {\n ctx->page_list_head = (ctx->page_list_head)->next;\n (ctx->page_list_head)->prev = NULL;\n }\n else /* item in middle of list */\n { \n item->prev->next = item->next;\n item->next->prev = item->prev;\n }\n\n item->next = NULL;\n item->prev = ctx->page_list_tail;\n (ctx->page_list_tail)->next = item;\n ctx->page_list_tail = item;\n }\n ctx->pfn2cache[pfn] = NULL;\n (ctx->page_list_tail)->pfn = INVALID_P2M_ENTRY;\n }\n}\n\nint xc_compression_add_page(xc_interface *xch, comp_ctx *ctx,\n char *page, xen_pfn_t pfn, int israw)\n{\n if (pfn > ctx->dom_pfnlist_size)\n {\n ERROR(\"Invalid pfn passed into \"\n \"xc_compression_add_page %\" PRIpfn \"\\n\", pfn);\n return -2;\n }\n\n /* pagetable page */\n if (israw)\n invalidate_cache_page(ctx, pfn);\n ctx->sendbuf_pfns[ctx->pfns_len] = israw ? INVALID_P2M_ENTRY : pfn;\n memcpy(ctx->inputbuf + ctx->pfns_len * XC_PAGE_SIZE, page, XC_PAGE_SIZE);\n ctx->pfns_len++;\n\n /* check if we have run out of space. If so,\n * we need to synchronously compress the pages and flush them out\n */\n if (ctx->pfns_len == NRPAGES(PAGE_BUFFER_SIZE))\n return -1;\n return 0;\n}\n\nint xc_compression_compress_pages(xc_interface *xch, comp_ctx *ctx,\n char *compbuf, unsigned long compbuf_size,\n unsigned long *compbuf_len)\n{\n char *cache_copy = NULL, *current_page = NULL;\n int israw, rc = 1;\n\n if (!ctx->pfns_len || (ctx->pfns_index == ctx->pfns_len)) {\n ctx->pfns_len = ctx->pfns_index = 0;\n return 0;\n }\n\n ctx->compbuf_pos = 0;\n ctx->compbuf = compbuf;\n ctx->compbuf_size = compbuf_size;\n\n for (; ctx->pfns_index < ctx->pfns_len; ctx->pfns_index++)\n {\n israw = 0;\n cache_copy = NULL;\n current_page = ctx->inputbuf + ctx->pfns_index * XC_PAGE_SIZE;\n\n if (ctx->sendbuf_pfns[ctx->pfns_index] == INVALID_P2M_ENTRY)\n israw = 1;\n else\n cache_copy = get_cache_page(ctx,\n ctx->sendbuf_pfns[ctx->pfns_index],\n &israw);\n\n if (israw)\n rc = (add_full_page(ctx, current_page, cache_copy) >= 0);\n else\n rc = (compress_page(ctx, current_page, cache_copy) >= 0);\n\n if ( !rc )\n {\n /* Out of space in outbuf! flush and come back */\n rc = -1;\n break;\n }\n }\n if (compbuf_len)\n *compbuf_len = ctx->compbuf_pos;\n\n return rc;\n}\n\ninline\nvoid xc_compression_reset_pagebuf(xc_interface *xch, comp_ctx *ctx)\n{\n ctx->pfns_index = ctx->pfns_len = 0;\n}\n\nint xc_compression_uncompress_page(xc_interface *xch, char *compbuf,\n unsigned long compbuf_size,\n unsigned long *compbuf_pos, char *destpage)\n{\n unsigned long pos;\n unsigned int len = 0, pagepos = 0;\n char flag;\n\n pos = *compbuf_pos;\n if (pos >= compbuf_size)\n {\n ERROR(\"Out of bounds exception in compression buffer (a):\"\n \"read ptr:%lu, bufsize = %lu\\n\",\n *compbuf_pos, compbuf_size);\n return -1;\n }\n\n switch (compbuf[pos])\n {\n case EMPTY_PAGE:\n pos++;\n break;\n\n case FULL_PAGE:\n {\n /* Check if the input buffer has 4KB of data */\n if ((pos + FULL_PAGE_SIZE) > compbuf_size)\n {\n ERROR(\"Out of bounds exception in compression buffer (b):\"\n \"read ptr = %lu, bufsize = %lu\\n\",\n *compbuf_pos, compbuf_size);\n return -1;\n }\n memcpy(destpage, &compbuf[pos + 1], XC_PAGE_SIZE);\n pos += FULL_PAGE_SIZE;\n }\n break;\n\n default: /* Normal page with one or more runs */\n {\n do\n {\n flag = compbuf[pos] & FLAGMASK;\n len = (compbuf[pos] & LENMASK) * sizeof(uint32_t);\n /* Sanity Check: Zero-length runs are allowed only for\n * FULL_PAGE and EMPTY_PAGE.\n */\n if (!len)\n {\n ERROR(\"Zero length run encountered for normal page: \"\n \"buffer (d):read ptr = %lu, flag = %u, \"\n \"bufsize = %lu, pagepos = %u\\n\",\n pos, (unsigned int)flag, compbuf_size, pagepos);\n return -1;\n }\n\n pos++;\n if (flag == RUNFLAG)\n {\n /* Check if the input buffer has len bytes of data\n * and whether it would fit in the destination page.\n */\n if (((pos + len) > compbuf_size)\n || ((pagepos + len) > XC_PAGE_SIZE))\n {\n ERROR(\"Out of bounds exception in compression \"\n \"buffer (c):read ptr = %lu, runlen = %u, \"\n \"bufsize = %lu, pagepos = %u\\n\",\n pos, len, compbuf_size, pagepos);\n return -1;\n }\n memcpy(&destpage[pagepos], &compbuf[pos], len);\n pos += len;\n }\n pagepos += len;\n } while ((pagepos < XC_PAGE_SIZE) && (pos < compbuf_size));\n\n /* Make sure we have copied/skipped 4KB worth of data */\n if (pagepos != XC_PAGE_SIZE)\n {\n ERROR(\"Invalid data in compression buffer:\"\n \"read ptr = %lu, bufsize = %lu, pagepos = %u\\n\",\n pos, compbuf_size, pagepos);\n return -1;\n }\n }\n }\n *compbuf_pos = pos;\n return 0;\n}\n\nvoid xc_compression_free_context(xc_interface *xch, comp_ctx *ctx)\n{\n if (!ctx) return;\n\n free(ctx->inputbuf);\n free(ctx->sendbuf_pfns);\n free(ctx->cache_base);\n free(ctx->pfn2cache);\n free(ctx->cache);\n free(ctx);\n}\n\ncomp_ctx *xc_compression_create_context(xc_interface *xch,\n unsigned long p2m_size)\n{\n unsigned long i;\n comp_ctx *ctx = NULL;\n unsigned long num_cache_pages = DELTA_CACHE_SIZE/XC_PAGE_SIZE;\n\n ctx = (comp_ctx *)malloc(sizeof(comp_ctx));\n if (!ctx)\n {\n ERROR(\"Failed to allocate compression_ctx\\n\");\n goto error;\n }\n memset(ctx, 0, sizeof(comp_ctx));\n\n ctx->inputbuf = xc_memalign(xch, XC_PAGE_SIZE, PAGE_BUFFER_SIZE);\n if (!ctx->inputbuf)\n {\n ERROR(\"Failed to allocate page buffer\\n\");\n goto error;\n }\n\n ctx->cache_base = xc_memalign(xch, XC_PAGE_SIZE, DELTA_CACHE_SIZE);\n if (!ctx->cache_base)\n {\n ERROR(\"Failed to allocate delta cache\\n\");\n goto error;\n }\n\n ctx->sendbuf_pfns = malloc(NRPAGES(PAGE_BUFFER_SIZE) *\n sizeof(xen_pfn_t));\n if (!ctx->sendbuf_pfns)\n {\n ERROR(\"Could not alloc sendbuf_pfns\\n\");\n goto error;\n }\n memset(ctx->sendbuf_pfns, -1,\n NRPAGES(PAGE_BUFFER_SIZE) * sizeof(xen_pfn_t));\n\n ctx->pfn2cache = calloc(p2m_size, sizeof(struct cache_page *));\n if (!ctx->pfn2cache)\n {\n ERROR(\"Could not alloc pfn2cache map\\n\");\n goto error;\n }\n\n ctx->cache = malloc(num_cache_pages * sizeof(struct cache_page));\n if (!ctx->cache)\n {\n ERROR(\"Could not alloc compression cache\\n\");\n goto error;\n }\n\n for (i = 0; i < num_cache_pages; i++)\n {\n ctx->cache[i].pfn = INVALID_P2M_ENTRY;\n ctx->cache[i].page = ctx->cache_base + i * XC_PAGE_SIZE;\n ctx->cache[i].prev = (i == 0) ? NULL : &(ctx->cache[i - 1]);\n ctx->cache[i].next = ((i+1) == num_cache_pages)? NULL :\n &(ctx->cache[i + 1]);\n }\n ctx->page_list_head = &(ctx->cache[0]);\n ctx->page_list_tail = &(ctx->cache[num_cache_pages -1]);\n ctx->dom_pfnlist_size = p2m_size;\n\n return ctx;\nerror:\n xc_compression_free_context(xch, ctx);\n return NULL;\n}\n\n/*\n * Local variables:\n * mode: C\n * c-file-style: \"BSD\"\n * c-basic-offset: 4\n * tab-width: 4\n * indent-tabs-mode: nil\n * End:\n */\n"},"repo_name":{"kind":"string","value":"Chong-Li/RTDS-ToolStack"},"path":{"kind":"string","value":"tools/libxc/xc_compression.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":16432,"string":"16,432"}}},{"rowIdx":115086044,"cells":{"code":{"kind":"string","value":"#ifdef HAVE_CONFIG_H\n# include \n#endif\n#include \n#include \n#include \n#include \n\n#include \"libmd5sum.h\"\n#include \"md5.h\"\n#include \"getline.h\"\n\n#define STREQ(a, b) (strcmp ((a), (b)) == 0)\n\nstatic int have_read_stdin;\n\n#if O_BINARY\n# define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)\n# define TEXT1TO1 \"rb\"\n# define TEXTCNVT \"r\"\n#else\n# if defined VMS\n# define OPENOPTS(BINARY) ((BINARY) != 0 ? TEXT1TO1 : TEXTCNVT)\n# define TEXT1TO1 \"rb\", \"ctx=stm\"\n# define TEXTCNVT \"r\", \"ctx=stm\"\n# else\n# if UNIX || __UNIX__ || unix || __unix__ || _POSIX_VERSION\n# define OPENOPTS(BINARY) \"r\"\n# else\n /* The following line is intended to evoke an error.\n Using #error is not portable enough. */\n \"Cannot determine system type.\"\n# endif\n# endif\n#endif\n\nint md5_file (const char *filename, int binary, unsigned char *md5_result)\n{\n FILE *fp;\n int err;\n\n (void)binary;\n\n if (STREQ (filename, \"-\"))\n {\n have_read_stdin = 1;\n fp = stdin;\n#if O_BINARY\n /* If we need binary reads from a pipe or redirected stdin, we need\n to switch it to BINARY mode here, since stdin is already open. */\n if (binary)\n SET_BINARY (fileno (stdin));\n#endif\n }\n else\n {\n /* OPENOPTS is a macro. It varies with the system.\n Some systems distinguish between internal and\n external text representations. */\n\n fp = fopen (filename, OPENOPTS (binary));\n if (fp == NULL)\n {\n error (0, errno, \"%s\", filename);\n return 1;\n }\n }\n \n err = md5_stream (fp, md5_result);\n if (err)\n {\n error (0, errno, \"%s\", filename);\n if (fp != stdin)\n fclose (fp);\n return 1;\n }\n\n if (fp != stdin && fclose (fp) == EOF)\n {\n error (0, errno, \"%s\", filename);\n return 1;\n }\n\n return 0;\n}\n"},"repo_name":{"kind":"string","value":"neutrino-mp/neutrino-mp"},"path":{"kind":"string","value":"lib/libmd5sum/libmd5sum.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":1867,"string":"1,867"}}},{"rowIdx":115086045,"cells":{"code":{"kind":"string","value":"/*\n * Synopsys DesignWare Multimedia Card Interface driver\n * (Based on NXP driver for lpc 31xx)\n *\n * Copyright (C) 2009 NXP Semiconductors\n * Copyright (C) 2009, 2010 Imagination Technologies Ltd.\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\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#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 \"dw_mmc.h\"\n\n/* Common flag combinations */\n#define DW_MCI_DATA_ERROR_FLAGS\t(SDMMC_INT_DRTO | SDMMC_INT_DCRC | \\\n\t\t\t\t SDMMC_INT_HTO | SDMMC_INT_SBE | \\\n\t\t\t\t SDMMC_INT_EBE | SDMMC_INT_HLE)\n#define DW_MCI_CMD_ERROR_FLAGS\t(SDMMC_INT_RTO | SDMMC_INT_RCRC | \\\n\t\t\t\t SDMMC_INT_RESP_ERR | SDMMC_INT_HLE)\n#define DW_MCI_ERROR_FLAGS\t(DW_MCI_DATA_ERROR_FLAGS | \\\n\t\t\t\t DW_MCI_CMD_ERROR_FLAGS)\n#define DW_MCI_SEND_STATUS\t1\n#define DW_MCI_RECV_STATUS\t2\n#define DW_MCI_DMA_THRESHOLD\t16\n\n#define DW_MCI_FREQ_MAX\t200000000\t/* unit: HZ */\n#define DW_MCI_FREQ_MIN\t100000\t\t/* unit: HZ */\n\n#define IDMAC_INT_CLR\t\t(SDMMC_IDMAC_INT_AI | SDMMC_IDMAC_INT_NI | \\\n\t\t\t\t SDMMC_IDMAC_INT_CES | SDMMC_IDMAC_INT_DU | \\\n\t\t\t\t SDMMC_IDMAC_INT_FBE | SDMMC_IDMAC_INT_RI | \\\n\t\t\t\t SDMMC_IDMAC_INT_TI)\n\n#define DESC_RING_BUF_SZ\tPAGE_SIZE\n\nstruct idmac_desc_64addr {\n\tu32\t\tdes0;\t/* Control Descriptor */\n#define IDMAC_OWN_CLR64(x) \\\n\t!((x) & cpu_to_le32(IDMAC_DES0_OWN))\n\n\tu32\t\tdes1;\t/* Reserved */\n\n\tu32\t\tdes2;\t/*Buffer sizes */\n#define IDMAC_64ADDR_SET_BUFFER1_SIZE(d, s) \\\n\t((d)->des2 = ((d)->des2 & cpu_to_le32(0x03ffe000)) | \\\n\t ((cpu_to_le32(s)) & cpu_to_le32(0x1fff)))\n\n\tu32\t\tdes3;\t/* Reserved */\n\n\tu32\t\tdes4;\t/* Lower 32-bits of Buffer Address Pointer 1*/\n\tu32\t\tdes5;\t/* Upper 32-bits of Buffer Address Pointer 1*/\n\n\tu32\t\tdes6;\t/* Lower 32-bits of Next Descriptor Address */\n\tu32\t\tdes7;\t/* Upper 32-bits of Next Descriptor Address */\n};\n\nstruct idmac_desc {\n\t__le32\t\tdes0;\t/* Control Descriptor */\n#define IDMAC_DES0_DIC\tBIT(1)\n#define IDMAC_DES0_LD\tBIT(2)\n#define IDMAC_DES0_FD\tBIT(3)\n#define IDMAC_DES0_CH\tBIT(4)\n#define IDMAC_DES0_ER\tBIT(5)\n#define IDMAC_DES0_CES\tBIT(30)\n#define IDMAC_DES0_OWN\tBIT(31)\n\n\t__le32\t\tdes1;\t/* Buffer sizes */\n#define IDMAC_SET_BUFFER1_SIZE(d, s) \\\n\t((d)->des1 = ((d)->des1 & cpu_to_le32(0x03ffe000)) | (cpu_to_le32((s) & 0x1fff)))\n\n\t__le32\t\tdes2;\t/* buffer 1 physical address */\n\n\t__le32\t\tdes3;\t/* buffer 2 physical address */\n};\n\n/* Each descriptor can transfer up to 4KB of data in chained mode */\n#define DW_MCI_DESC_DATA_LENGTH\t0x1000\n\n#if defined(CONFIG_DEBUG_FS)\nstatic int dw_mci_req_show(struct seq_file *s, void *v)\n{\n\tstruct dw_mci_slot *slot = s->private;\n\tstruct mmc_request *mrq;\n\tstruct mmc_command *cmd;\n\tstruct mmc_command *stop;\n\tstruct mmc_data\t*data;\n\n\t/* Make sure we get a consistent snapshot */\n\tspin_lock_bh(&slot->host->lock);\n\tmrq = slot->mrq;\n\n\tif (mrq) {\n\t\tcmd = mrq->cmd;\n\t\tdata = mrq->data;\n\t\tstop = mrq->stop;\n\n\t\tif (cmd)\n\t\t\tseq_printf(s,\n\t\t\t\t \"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\\n\",\n\t\t\t\t cmd->opcode, cmd->arg, cmd->flags,\n\t\t\t\t cmd->resp[0], cmd->resp[1], cmd->resp[2],\n\t\t\t\t cmd->resp[2], cmd->error);\n\t\tif (data)\n\t\t\tseq_printf(s, \"DATA %u / %u * %u flg %x err %d\\n\",\n\t\t\t\t data->bytes_xfered, data->blocks,\n\t\t\t\t data->blksz, data->flags, data->error);\n\t\tif (stop)\n\t\t\tseq_printf(s,\n\t\t\t\t \"CMD%u(0x%x) flg %x rsp %x %x %x %x err %d\\n\",\n\t\t\t\t stop->opcode, stop->arg, stop->flags,\n\t\t\t\t stop->resp[0], stop->resp[1], stop->resp[2],\n\t\t\t\t stop->resp[2], stop->error);\n\t}\n\n\tspin_unlock_bh(&slot->host->lock);\n\n\treturn 0;\n}\nDEFINE_SHOW_ATTRIBUTE(dw_mci_req);\n\nstatic int dw_mci_regs_show(struct seq_file *s, void *v)\n{\n\tstruct dw_mci *host = s->private;\n\n\tpm_runtime_get_sync(host->dev);\n\n\tseq_printf(s, \"STATUS:\\t0x%08x\\n\", mci_readl(host, STATUS));\n\tseq_printf(s, \"RINTSTS:\\t0x%08x\\n\", mci_readl(host, RINTSTS));\n\tseq_printf(s, \"CMD:\\t0x%08x\\n\", mci_readl(host, CMD));\n\tseq_printf(s, \"CTRL:\\t0x%08x\\n\", mci_readl(host, CTRL));\n\tseq_printf(s, \"INTMASK:\\t0x%08x\\n\", mci_readl(host, INTMASK));\n\tseq_printf(s, \"CLKENA:\\t0x%08x\\n\", mci_readl(host, CLKENA));\n\n\tpm_runtime_put_autosuspend(host->dev);\n\n\treturn 0;\n}\nDEFINE_SHOW_ATTRIBUTE(dw_mci_regs);\n\nstatic void dw_mci_init_debugfs(struct dw_mci_slot *slot)\n{\n\tstruct mmc_host\t*mmc = slot->mmc;\n\tstruct dw_mci *host = slot->host;\n\tstruct dentry *root;\n\tstruct dentry *node;\n\n\troot = mmc->debugfs_root;\n\tif (!root)\n\t\treturn;\n\n\tnode = debugfs_create_file(\"regs\", S_IRUSR, root, host,\n\t\t\t\t &dw_mci_regs_fops);\n\tif (!node)\n\t\tgoto err;\n\n\tnode = debugfs_create_file(\"req\", S_IRUSR, root, slot,\n\t\t\t\t &dw_mci_req_fops);\n\tif (!node)\n\t\tgoto err;\n\n\tnode = debugfs_create_u32(\"state\", S_IRUSR, root, (u32 *)&host->state);\n\tif (!node)\n\t\tgoto err;\n\n\tnode = debugfs_create_x32(\"pending_events\", S_IRUSR, root,\n\t\t\t\t (u32 *)&host->pending_events);\n\tif (!node)\n\t\tgoto err;\n\n\tnode = debugfs_create_x32(\"completed_events\", S_IRUSR, root,\n\t\t\t\t (u32 *)&host->completed_events);\n\tif (!node)\n\t\tgoto err;\n\n\treturn;\n\nerr:\n\tdev_err(&mmc->class_dev, \"failed to initialize debugfs for slot\\n\");\n}\n#endif /* defined(CONFIG_DEBUG_FS) */\n\nstatic bool dw_mci_ctrl_reset(struct dw_mci *host, u32 reset)\n{\n\tu32 ctrl;\n\n\tctrl = mci_readl(host, CTRL);\n\tctrl |= reset;\n\tmci_writel(host, CTRL, ctrl);\n\n\t/* wait till resets clear */\n\tif (readl_poll_timeout_atomic(host->regs + SDMMC_CTRL, ctrl,\n\t\t\t\t !(ctrl & reset),\n\t\t\t\t 1, 500 * USEC_PER_MSEC)) {\n\t\tdev_err(host->dev,\n\t\t\t\"Timeout resetting block (ctrl reset %#x)\\n\",\n\t\t\tctrl & reset);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nstatic void dw_mci_wait_while_busy(struct dw_mci *host, u32 cmd_flags)\n{\n\tu32 status;\n\n\t/*\n\t * Databook says that before issuing a new data transfer command\n\t * we need to check to see if the card is busy. Data transfer commands\n\t * all have SDMMC_CMD_PRV_DAT_WAIT set, so we'll key off that.\n\t *\n\t * ...also allow sending for SDMMC_CMD_VOLT_SWITCH where busy is\n\t * expected.\n\t */\n\tif ((cmd_flags & SDMMC_CMD_PRV_DAT_WAIT) &&\n\t !(cmd_flags & SDMMC_CMD_VOLT_SWITCH)) {\n\t\tif (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS,\n\t\t\t\t\t status,\n\t\t\t\t\t !(status & SDMMC_STATUS_BUSY),\n\t\t\t\t\t 10, 500 * USEC_PER_MSEC))\n\t\t\tdev_err(host->dev, \"Busy; trying anyway\\n\");\n\t}\n}\n\nstatic void mci_send_cmd(struct dw_mci_slot *slot, u32 cmd, u32 arg)\n{\n\tstruct dw_mci *host = slot->host;\n\tunsigned int cmd_status = 0;\n\n\tmci_writel(host, CMDARG, arg);\n\twmb(); /* drain writebuffer */\n\tdw_mci_wait_while_busy(host, cmd);\n\tmci_writel(host, CMD, SDMMC_CMD_START | cmd);\n\n\tif (readl_poll_timeout_atomic(host->regs + SDMMC_CMD, cmd_status,\n\t\t\t\t !(cmd_status & SDMMC_CMD_START),\n\t\t\t\t 1, 500 * USEC_PER_MSEC))\n\t\tdev_err(&slot->mmc->class_dev,\n\t\t\t\"Timeout sending command (cmd %#x arg %#x status %#x)\\n\",\n\t\t\tcmd, arg, cmd_status);\n}\n\nstatic u32 dw_mci_prepare_command(struct mmc_host *mmc, struct mmc_command *cmd)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tu32 cmdr;\n\n\tcmd->error = -EINPROGRESS;\n\tcmdr = cmd->opcode;\n\n\tif (cmd->opcode == MMC_STOP_TRANSMISSION ||\n\t cmd->opcode == MMC_GO_IDLE_STATE ||\n\t cmd->opcode == MMC_GO_INACTIVE_STATE ||\n\t (cmd->opcode == SD_IO_RW_DIRECT &&\n\t ((cmd->arg >> 9) & 0x1FFFF) == SDIO_CCCR_ABORT))\n\t\tcmdr |= SDMMC_CMD_STOP;\n\telse if (cmd->opcode != MMC_SEND_STATUS && cmd->data)\n\t\tcmdr |= SDMMC_CMD_PRV_DAT_WAIT;\n\n\tif (cmd->opcode == SD_SWITCH_VOLTAGE) {\n\t\tu32 clk_en_a;\n\n\t\t/* Special bit makes CMD11 not die */\n\t\tcmdr |= SDMMC_CMD_VOLT_SWITCH;\n\n\t\t/* Change state to continue to handle CMD11 weirdness */\n\t\tWARN_ON(slot->host->state != STATE_SENDING_CMD);\n\t\tslot->host->state = STATE_SENDING_CMD11;\n\n\t\t/*\n\t\t * We need to disable low power mode (automatic clock stop)\n\t\t * while doing voltage switch so we don't confuse the card,\n\t\t * since stopping the clock is a specific part of the UHS\n\t\t * voltage change dance.\n\t\t *\n\t\t * Note that low power mode (SDMMC_CLKEN_LOW_PWR) will be\n\t\t * unconditionally turned back on in dw_mci_setup_bus() if it's\n\t\t * ever called with a non-zero clock. That shouldn't happen\n\t\t * until the voltage change is all done.\n\t\t */\n\t\tclk_en_a = mci_readl(host, CLKENA);\n\t\tclk_en_a &= ~(SDMMC_CLKEN_LOW_PWR << slot->id);\n\t\tmci_writel(host, CLKENA, clk_en_a);\n\t\tmci_send_cmd(slot, SDMMC_CMD_UPD_CLK |\n\t\t\t SDMMC_CMD_PRV_DAT_WAIT, 0);\n\t}\n\n\tif (cmd->flags & MMC_RSP_PRESENT) {\n\t\t/* We expect a response, so set this bit */\n\t\tcmdr |= SDMMC_CMD_RESP_EXP;\n\t\tif (cmd->flags & MMC_RSP_136)\n\t\t\tcmdr |= SDMMC_CMD_RESP_LONG;\n\t}\n\n\tif (cmd->flags & MMC_RSP_CRC)\n\t\tcmdr |= SDMMC_CMD_RESP_CRC;\n\n\tif (cmd->data) {\n\t\tcmdr |= SDMMC_CMD_DAT_EXP;\n\t\tif (cmd->data->flags & MMC_DATA_WRITE)\n\t\t\tcmdr |= SDMMC_CMD_DAT_WR;\n\t}\n\n\tif (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &slot->flags))\n\t\tcmdr |= SDMMC_CMD_USE_HOLD_REG;\n\n\treturn cmdr;\n}\n\nstatic u32 dw_mci_prep_stop_abort(struct dw_mci *host, struct mmc_command *cmd)\n{\n\tstruct mmc_command *stop;\n\tu32 cmdr;\n\n\tif (!cmd->data)\n\t\treturn 0;\n\n\tstop = &host->stop_abort;\n\tcmdr = cmd->opcode;\n\tmemset(stop, 0, sizeof(struct mmc_command));\n\n\tif (cmdr == MMC_READ_SINGLE_BLOCK ||\n\t cmdr == MMC_READ_MULTIPLE_BLOCK ||\n\t cmdr == MMC_WRITE_BLOCK ||\n\t cmdr == MMC_WRITE_MULTIPLE_BLOCK ||\n\t cmdr == MMC_SEND_TUNING_BLOCK ||\n\t cmdr == MMC_SEND_TUNING_BLOCK_HS200) {\n\t\tstop->opcode = MMC_STOP_TRANSMISSION;\n\t\tstop->arg = 0;\n\t\tstop->flags = MMC_RSP_R1B | MMC_CMD_AC;\n\t} else if (cmdr == SD_IO_RW_EXTENDED) {\n\t\tstop->opcode = SD_IO_RW_DIRECT;\n\t\tstop->arg |= (1 << 31) | (0 << 28) | (SDIO_CCCR_ABORT << 9) |\n\t\t\t ((cmd->arg >> 28) & 0x7);\n\t\tstop->flags = MMC_RSP_SPI_R5 | MMC_RSP_R5 | MMC_CMD_AC;\n\t} else {\n\t\treturn 0;\n\t}\n\n\tcmdr = stop->opcode | SDMMC_CMD_STOP |\n\t\tSDMMC_CMD_RESP_CRC | SDMMC_CMD_RESP_EXP;\n\n\tif (!test_bit(DW_MMC_CARD_NO_USE_HOLD, &host->slot->flags))\n\t\tcmdr |= SDMMC_CMD_USE_HOLD_REG;\n\n\treturn cmdr;\n}\n\nstatic inline void dw_mci_set_cto(struct dw_mci *host)\n{\n\tunsigned int cto_clks;\n\tunsigned int cto_div;\n\tunsigned int cto_ms;\n\tunsigned long irqflags;\n\n\tcto_clks = mci_readl(host, TMOUT) & 0xff;\n\tcto_div = (mci_readl(host, CLKDIV) & 0xff) * 2;\n\tif (cto_div == 0)\n\t\tcto_div = 1;\n\n\tcto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * cto_clks * cto_div,\n\t\t\t\t host->bus_hz);\n\n\t/* add a bit spare time */\n\tcto_ms += 10;\n\n\t/*\n\t * The durations we're working with are fairly short so we have to be\n\t * extra careful about synchronization here. Specifically in hardware a\n\t * command timeout is _at most_ 5.1 ms, so that means we expect an\n\t * interrupt (either command done or timeout) to come rather quickly\n\t * after the mci_writel. ...but just in case we have a long interrupt\n\t * latency let's add a bit of paranoia.\n\t *\n\t * In general we'll assume that at least an interrupt will be asserted\n\t * in hardware by the time the cto_timer runs. ...and if it hasn't\n\t * been asserted in hardware by that time then we'll assume it'll never\n\t * come.\n\t */\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\tif (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))\n\t\tmod_timer(&host->cto_timer,\n\t\t\tjiffies + msecs_to_jiffies(cto_ms) + 1);\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n}\n\nstatic void dw_mci_start_command(struct dw_mci *host,\n\t\t\t\t struct mmc_command *cmd, u32 cmd_flags)\n{\n\thost->cmd = cmd;\n\tdev_vdbg(host->dev,\n\t\t \"start command: ARGR=0x%08x CMDR=0x%08x\\n\",\n\t\t cmd->arg, cmd_flags);\n\n\tmci_writel(host, CMDARG, cmd->arg);\n\twmb(); /* drain writebuffer */\n\tdw_mci_wait_while_busy(host, cmd_flags);\n\n\tmci_writel(host, CMD, cmd_flags | SDMMC_CMD_START);\n\n\t/* response expected command only */\n\tif (cmd_flags & SDMMC_CMD_RESP_EXP)\n\t\tdw_mci_set_cto(host);\n}\n\nstatic inline void send_stop_abort(struct dw_mci *host, struct mmc_data *data)\n{\n\tstruct mmc_command *stop = &host->stop_abort;\n\n\tdw_mci_start_command(host, stop, host->stop_cmdr);\n}\n\n/* DMA interface functions */\nstatic void dw_mci_stop_dma(struct dw_mci *host)\n{\n\tif (host->using_dma) {\n\t\thost->dma_ops->stop(host);\n\t\thost->dma_ops->cleanup(host);\n\t}\n\n\t/* Data transfer was stopped by the interrupt handler */\n\tset_bit(EVENT_XFER_COMPLETE, &host->pending_events);\n}\n\nstatic void dw_mci_dma_cleanup(struct dw_mci *host)\n{\n\tstruct mmc_data *data = host->data;\n\n\tif (data && data->host_cookie == COOKIE_MAPPED) {\n\t\tdma_unmap_sg(host->dev,\n\t\t\t data->sg,\n\t\t\t data->sg_len,\n\t\t\t mmc_get_dma_dir(data));\n\t\tdata->host_cookie = COOKIE_UNMAPPED;\n\t}\n}\n\nstatic void dw_mci_idmac_reset(struct dw_mci *host)\n{\n\tu32 bmod = mci_readl(host, BMOD);\n\t/* Software reset of DMA */\n\tbmod |= SDMMC_IDMAC_SWRESET;\n\tmci_writel(host, BMOD, bmod);\n}\n\nstatic void dw_mci_idmac_stop_dma(struct dw_mci *host)\n{\n\tu32 temp;\n\n\t/* Disable and reset the IDMAC interface */\n\ttemp = mci_readl(host, CTRL);\n\ttemp &= ~SDMMC_CTRL_USE_IDMAC;\n\ttemp |= SDMMC_CTRL_DMA_RESET;\n\tmci_writel(host, CTRL, temp);\n\n\t/* Stop the IDMAC running */\n\ttemp = mci_readl(host, BMOD);\n\ttemp &= ~(SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB);\n\ttemp |= SDMMC_IDMAC_SWRESET;\n\tmci_writel(host, BMOD, temp);\n}\n\nstatic void dw_mci_dmac_complete_dma(void *arg)\n{\n\tstruct dw_mci *host = arg;\n\tstruct mmc_data *data = host->data;\n\n\tdev_vdbg(host->dev, \"DMA complete\\n\");\n\n\tif ((host->use_dma == TRANS_MODE_EDMAC) &&\n\t data && (data->flags & MMC_DATA_READ))\n\t\t/* Invalidate cache after read */\n\t\tdma_sync_sg_for_cpu(mmc_dev(host->slot->mmc),\n\t\t\t\t data->sg,\n\t\t\t\t data->sg_len,\n\t\t\t\t DMA_FROM_DEVICE);\n\n\thost->dma_ops->cleanup(host);\n\n\t/*\n\t * If the card was removed, data will be NULL. No point in trying to\n\t * send the stop command or waiting for NBUSY in this case.\n\t */\n\tif (data) {\n\t\tset_bit(EVENT_XFER_COMPLETE, &host->pending_events);\n\t\ttasklet_schedule(&host->tasklet);\n\t}\n}\n\nstatic int dw_mci_idmac_init(struct dw_mci *host)\n{\n\tint i;\n\n\tif (host->dma_64bit_address == 1) {\n\t\tstruct idmac_desc_64addr *p;\n\t\t/* Number of descriptors in the ring buffer */\n\t\thost->ring_size =\n\t\t\tDESC_RING_BUF_SZ / sizeof(struct idmac_desc_64addr);\n\n\t\t/* Forward link the descriptor list */\n\t\tfor (i = 0, p = host->sg_cpu; i < host->ring_size - 1;\n\t\t\t\t\t\t\t\ti++, p++) {\n\t\t\tp->des6 = (host->sg_dma +\n\t\t\t\t\t(sizeof(struct idmac_desc_64addr) *\n\t\t\t\t\t\t\t(i + 1))) & 0xffffffff;\n\n\t\t\tp->des7 = (u64)(host->sg_dma +\n\t\t\t\t\t(sizeof(struct idmac_desc_64addr) *\n\t\t\t\t\t\t\t(i + 1))) >> 32;\n\t\t\t/* Initialize reserved and buffer size fields to \"0\" */\n\t\t\tp->des0 = 0;\n\t\t\tp->des1 = 0;\n\t\t\tp->des2 = 0;\n\t\t\tp->des3 = 0;\n\t\t}\n\n\t\t/* Set the last descriptor as the end-of-ring descriptor */\n\t\tp->des6 = host->sg_dma & 0xffffffff;\n\t\tp->des7 = (u64)host->sg_dma >> 32;\n\t\tp->des0 = IDMAC_DES0_ER;\n\n\t} else {\n\t\tstruct idmac_desc *p;\n\t\t/* Number of descriptors in the ring buffer */\n\t\thost->ring_size =\n\t\t\tDESC_RING_BUF_SZ / sizeof(struct idmac_desc);\n\n\t\t/* Forward link the descriptor list */\n\t\tfor (i = 0, p = host->sg_cpu;\n\t\t i < host->ring_size - 1;\n\t\t i++, p++) {\n\t\t\tp->des3 = cpu_to_le32(host->sg_dma +\n\t\t\t\t\t(sizeof(struct idmac_desc) * (i + 1)));\n\t\t\tp->des0 = 0;\n\t\t\tp->des1 = 0;\n\t\t}\n\n\t\t/* Set the last descriptor as the end-of-ring descriptor */\n\t\tp->des3 = cpu_to_le32(host->sg_dma);\n\t\tp->des0 = cpu_to_le32(IDMAC_DES0_ER);\n\t}\n\n\tdw_mci_idmac_reset(host);\n\n\tif (host->dma_64bit_address == 1) {\n\t\t/* Mask out interrupts - get Tx & Rx complete only */\n\t\tmci_writel(host, IDSTS64, IDMAC_INT_CLR);\n\t\tmci_writel(host, IDINTEN64, SDMMC_IDMAC_INT_NI |\n\t\t\t\tSDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI);\n\n\t\t/* Set the descriptor base address */\n\t\tmci_writel(host, DBADDRL, host->sg_dma & 0xffffffff);\n\t\tmci_writel(host, DBADDRU, (u64)host->sg_dma >> 32);\n\n\t} else {\n\t\t/* Mask out interrupts - get Tx & Rx complete only */\n\t\tmci_writel(host, IDSTS, IDMAC_INT_CLR);\n\t\tmci_writel(host, IDINTEN, SDMMC_IDMAC_INT_NI |\n\t\t\t\tSDMMC_IDMAC_INT_RI | SDMMC_IDMAC_INT_TI);\n\n\t\t/* Set the descriptor base address */\n\t\tmci_writel(host, DBADDR, host->sg_dma);\n\t}\n\n\treturn 0;\n}\n\nstatic inline int dw_mci_prepare_desc64(struct dw_mci *host,\n\t\t\t\t\t struct mmc_data *data,\n\t\t\t\t\t unsigned int sg_len)\n{\n\tunsigned int desc_len;\n\tstruct idmac_desc_64addr *desc_first, *desc_last, *desc;\n\tu32 val;\n\tint i;\n\n\tdesc_first = desc_last = desc = host->sg_cpu;\n\n\tfor (i = 0; i < sg_len; i++) {\n\t\tunsigned int length = sg_dma_len(&data->sg[i]);\n\n\t\tu64 mem_addr = sg_dma_address(&data->sg[i]);\n\n\t\tfor ( ; length ; desc++) {\n\t\t\tdesc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ?\n\t\t\t\t length : DW_MCI_DESC_DATA_LENGTH;\n\n\t\t\tlength -= desc_len;\n\n\t\t\t/*\n\t\t\t * Wait for the former clear OWN bit operation\n\t\t\t * of IDMAC to make sure that this descriptor\n\t\t\t * isn't still owned by IDMAC as IDMAC's write\n\t\t\t * ops and CPU's read ops are asynchronous.\n\t\t\t */\n\t\t\tif (readl_poll_timeout_atomic(&desc->des0, val,\n\t\t\t\t\t\t!(val & IDMAC_DES0_OWN),\n\t\t\t\t\t\t10, 100 * USEC_PER_MSEC))\n\t\t\t\tgoto err_own_bit;\n\n\t\t\t/*\n\t\t\t * Set the OWN bit and disable interrupts\n\t\t\t * for this descriptor\n\t\t\t */\n\t\t\tdesc->des0 = IDMAC_DES0_OWN | IDMAC_DES0_DIC |\n\t\t\t\t\t\tIDMAC_DES0_CH;\n\n\t\t\t/* Buffer length */\n\t\t\tIDMAC_64ADDR_SET_BUFFER1_SIZE(desc, desc_len);\n\n\t\t\t/* Physical address to DMA to/from */\n\t\t\tdesc->des4 = mem_addr & 0xffffffff;\n\t\t\tdesc->des5 = mem_addr >> 32;\n\n\t\t\t/* Update physical address for the next desc */\n\t\t\tmem_addr += desc_len;\n\n\t\t\t/* Save pointer to the last descriptor */\n\t\t\tdesc_last = desc;\n\t\t}\n\t}\n\n\t/* Set first descriptor */\n\tdesc_first->des0 |= IDMAC_DES0_FD;\n\n\t/* Set last descriptor */\n\tdesc_last->des0 &= ~(IDMAC_DES0_CH | IDMAC_DES0_DIC);\n\tdesc_last->des0 |= IDMAC_DES0_LD;\n\n\treturn 0;\nerr_own_bit:\n\t/* restore the descriptor chain as it's polluted */\n\tdev_dbg(host->dev, \"descriptor is still owned by IDMAC.\\n\");\n\tmemset(host->sg_cpu, 0, DESC_RING_BUF_SZ);\n\tdw_mci_idmac_init(host);\n\treturn -EINVAL;\n}\n\n\nstatic inline int dw_mci_prepare_desc32(struct dw_mci *host,\n\t\t\t\t\t struct mmc_data *data,\n\t\t\t\t\t unsigned int sg_len)\n{\n\tunsigned int desc_len;\n\tstruct idmac_desc *desc_first, *desc_last, *desc;\n\tu32 val;\n\tint i;\n\n\tdesc_first = desc_last = desc = host->sg_cpu;\n\n\tfor (i = 0; i < sg_len; i++) {\n\t\tunsigned int length = sg_dma_len(&data->sg[i]);\n\n\t\tu32 mem_addr = sg_dma_address(&data->sg[i]);\n\n\t\tfor ( ; length ; desc++) {\n\t\t\tdesc_len = (length <= DW_MCI_DESC_DATA_LENGTH) ?\n\t\t\t\t length : DW_MCI_DESC_DATA_LENGTH;\n\n\t\t\tlength -= desc_len;\n\n\t\t\t/*\n\t\t\t * Wait for the former clear OWN bit operation\n\t\t\t * of IDMAC to make sure that this descriptor\n\t\t\t * isn't still owned by IDMAC as IDMAC's write\n\t\t\t * ops and CPU's read ops are asynchronous.\n\t\t\t */\n\t\t\tif (readl_poll_timeout_atomic(&desc->des0, val,\n\t\t\t\t\t\t IDMAC_OWN_CLR64(val),\n\t\t\t\t\t\t 10,\n\t\t\t\t\t\t 100 * USEC_PER_MSEC))\n\t\t\t\tgoto err_own_bit;\n\n\t\t\t/*\n\t\t\t * Set the OWN bit and disable interrupts\n\t\t\t * for this descriptor\n\t\t\t */\n\t\t\tdesc->des0 = cpu_to_le32(IDMAC_DES0_OWN |\n\t\t\t\t\t\t IDMAC_DES0_DIC |\n\t\t\t\t\t\t IDMAC_DES0_CH);\n\n\t\t\t/* Buffer length */\n\t\t\tIDMAC_SET_BUFFER1_SIZE(desc, desc_len);\n\n\t\t\t/* Physical address to DMA to/from */\n\t\t\tdesc->des2 = cpu_to_le32(mem_addr);\n\n\t\t\t/* Update physical address for the next desc */\n\t\t\tmem_addr += desc_len;\n\n\t\t\t/* Save pointer to the last descriptor */\n\t\t\tdesc_last = desc;\n\t\t}\n\t}\n\n\t/* Set first descriptor */\n\tdesc_first->des0 |= cpu_to_le32(IDMAC_DES0_FD);\n\n\t/* Set last descriptor */\n\tdesc_last->des0 &= cpu_to_le32(~(IDMAC_DES0_CH |\n\t\t\t\t IDMAC_DES0_DIC));\n\tdesc_last->des0 |= cpu_to_le32(IDMAC_DES0_LD);\n\n\treturn 0;\nerr_own_bit:\n\t/* restore the descriptor chain as it's polluted */\n\tdev_dbg(host->dev, \"descriptor is still owned by IDMAC.\\n\");\n\tmemset(host->sg_cpu, 0, DESC_RING_BUF_SZ);\n\tdw_mci_idmac_init(host);\n\treturn -EINVAL;\n}\n\nstatic int dw_mci_idmac_start_dma(struct dw_mci *host, unsigned int sg_len)\n{\n\tu32 temp;\n\tint ret;\n\n\tif (host->dma_64bit_address == 1)\n\t\tret = dw_mci_prepare_desc64(host, host->data, sg_len);\n\telse\n\t\tret = dw_mci_prepare_desc32(host, host->data, sg_len);\n\n\tif (ret)\n\t\tgoto out;\n\n\t/* drain writebuffer */\n\twmb();\n\n\t/* Make sure to reset DMA in case we did PIO before this */\n\tdw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET);\n\tdw_mci_idmac_reset(host);\n\n\t/* Select IDMAC interface */\n\ttemp = mci_readl(host, CTRL);\n\ttemp |= SDMMC_CTRL_USE_IDMAC;\n\tmci_writel(host, CTRL, temp);\n\n\t/* drain writebuffer */\n\twmb();\n\n\t/* Enable the IDMAC */\n\ttemp = mci_readl(host, BMOD);\n\ttemp |= SDMMC_IDMAC_ENABLE | SDMMC_IDMAC_FB;\n\tmci_writel(host, BMOD, temp);\n\n\t/* Start it running */\n\tmci_writel(host, PLDMND, 1);\n\nout:\n\treturn ret;\n}\n\nstatic const struct dw_mci_dma_ops dw_mci_idmac_ops = {\n\t.init = dw_mci_idmac_init,\n\t.start = dw_mci_idmac_start_dma,\n\t.stop = dw_mci_idmac_stop_dma,\n\t.complete = dw_mci_dmac_complete_dma,\n\t.cleanup = dw_mci_dma_cleanup,\n};\n\nstatic void dw_mci_edmac_stop_dma(struct dw_mci *host)\n{\n\tdmaengine_terminate_async(host->dms->ch);\n}\n\nstatic int dw_mci_edmac_start_dma(struct dw_mci *host,\n\t\t\t\t\t unsigned int sg_len)\n{\n\tstruct dma_slave_config cfg;\n\tstruct dma_async_tx_descriptor *desc = NULL;\n\tstruct scatterlist *sgl = host->data->sg;\n\tstatic const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256};\n\tu32 sg_elems = host->data->sg_len;\n\tu32 fifoth_val;\n\tu32 fifo_offset = host->fifo_reg - host->regs;\n\tint ret = 0;\n\n\t/* Set external dma config: burst size, burst width */\n\tcfg.dst_addr = host->phy_regs + fifo_offset;\n\tcfg.src_addr = cfg.dst_addr;\n\tcfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;\n\tcfg.src_addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;\n\n\t/* Match burst msize with external dma config */\n\tfifoth_val = mci_readl(host, FIFOTH);\n\tcfg.dst_maxburst = mszs[(fifoth_val >> 28) & 0x7];\n\tcfg.src_maxburst = cfg.dst_maxburst;\n\n\tif (host->data->flags & MMC_DATA_WRITE)\n\t\tcfg.direction = DMA_MEM_TO_DEV;\n\telse\n\t\tcfg.direction = DMA_DEV_TO_MEM;\n\n\tret = dmaengine_slave_config(host->dms->ch, &cfg);\n\tif (ret) {\n\t\tdev_err(host->dev, \"Failed to config edmac.\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\tdesc = dmaengine_prep_slave_sg(host->dms->ch, sgl,\n\t\t\t\t sg_len, cfg.direction,\n\t\t\t\t DMA_PREP_INTERRUPT | DMA_CTRL_ACK);\n\tif (!desc) {\n\t\tdev_err(host->dev, \"Can't prepare slave sg.\\n\");\n\t\treturn -EBUSY;\n\t}\n\n\t/* Set dw_mci_dmac_complete_dma as callback */\n\tdesc->callback = dw_mci_dmac_complete_dma;\n\tdesc->callback_param = (void *)host;\n\tdmaengine_submit(desc);\n\n\t/* Flush cache before write */\n\tif (host->data->flags & MMC_DATA_WRITE)\n\t\tdma_sync_sg_for_device(mmc_dev(host->slot->mmc), sgl,\n\t\t\t\t sg_elems, DMA_TO_DEVICE);\n\n\tdma_async_issue_pending(host->dms->ch);\n\n\treturn 0;\n}\n\nstatic int dw_mci_edmac_init(struct dw_mci *host)\n{\n\t/* Request external dma channel */\n\thost->dms = kzalloc(sizeof(struct dw_mci_dma_slave), GFP_KERNEL);\n\tif (!host->dms)\n\t\treturn -ENOMEM;\n\n\thost->dms->ch = dma_request_slave_channel(host->dev, \"rx-tx\");\n\tif (!host->dms->ch) {\n\t\tdev_err(host->dev, \"Failed to get external DMA channel.\\n\");\n\t\tkfree(host->dms);\n\t\thost->dms = NULL;\n\t\treturn -ENXIO;\n\t}\n\n\treturn 0;\n}\n\nstatic void dw_mci_edmac_exit(struct dw_mci *host)\n{\n\tif (host->dms) {\n\t\tif (host->dms->ch) {\n\t\t\tdma_release_channel(host->dms->ch);\n\t\t\thost->dms->ch = NULL;\n\t\t}\n\t\tkfree(host->dms);\n\t\thost->dms = NULL;\n\t}\n}\n\nstatic const struct dw_mci_dma_ops dw_mci_edmac_ops = {\n\t.init = dw_mci_edmac_init,\n\t.exit = dw_mci_edmac_exit,\n\t.start = dw_mci_edmac_start_dma,\n\t.stop = dw_mci_edmac_stop_dma,\n\t.complete = dw_mci_dmac_complete_dma,\n\t.cleanup = dw_mci_dma_cleanup,\n};\n\nstatic int dw_mci_pre_dma_transfer(struct dw_mci *host,\n\t\t\t\t struct mmc_data *data,\n\t\t\t\t int cookie)\n{\n\tstruct scatterlist *sg;\n\tunsigned int i, sg_len;\n\n\tif (data->host_cookie == COOKIE_PRE_MAPPED)\n\t\treturn data->sg_len;\n\n\t/*\n\t * We don't do DMA on \"complex\" transfers, i.e. with\n\t * non-word-aligned buffers or lengths. Also, we don't bother\n\t * with all the DMA setup overhead for short transfers.\n\t */\n\tif (data->blocks * data->blksz < DW_MCI_DMA_THRESHOLD)\n\t\treturn -EINVAL;\n\n\tif (data->blksz & 3)\n\t\treturn -EINVAL;\n\n\tfor_each_sg(data->sg, sg, data->sg_len, i) {\n\t\tif (sg->offset & 3 || sg->length & 3)\n\t\t\treturn -EINVAL;\n\t}\n\n\tsg_len = dma_map_sg(host->dev,\n\t\t\t data->sg,\n\t\t\t data->sg_len,\n\t\t\t mmc_get_dma_dir(data));\n\tif (sg_len == 0)\n\t\treturn -EINVAL;\n\n\tdata->host_cookie = cookie;\n\n\treturn sg_len;\n}\n\nstatic void dw_mci_pre_req(struct mmc_host *mmc,\n\t\t\t struct mmc_request *mrq)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct mmc_data *data = mrq->data;\n\n\tif (!slot->host->use_dma || !data)\n\t\treturn;\n\n\t/* This data might be unmapped at this time */\n\tdata->host_cookie = COOKIE_UNMAPPED;\n\n\tif (dw_mci_pre_dma_transfer(slot->host, mrq->data,\n\t\t\t\tCOOKIE_PRE_MAPPED) < 0)\n\t\tdata->host_cookie = COOKIE_UNMAPPED;\n}\n\nstatic void dw_mci_post_req(struct mmc_host *mmc,\n\t\t\t struct mmc_request *mrq,\n\t\t\t int err)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct mmc_data *data = mrq->data;\n\n\tif (!slot->host->use_dma || !data)\n\t\treturn;\n\n\tif (data->host_cookie != COOKIE_UNMAPPED)\n\t\tdma_unmap_sg(slot->host->dev,\n\t\t\t data->sg,\n\t\t\t data->sg_len,\n\t\t\t mmc_get_dma_dir(data));\n\tdata->host_cookie = COOKIE_UNMAPPED;\n}\n\nstatic int dw_mci_get_cd(struct mmc_host *mmc)\n{\n\tint present;\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tint gpio_cd = mmc_gpio_get_cd(mmc);\n\n\t/* Use platform get_cd function, else try onboard card detect */\n\tif (((mmc->caps & MMC_CAP_NEEDS_POLL)\n\t\t\t\t|| !mmc_card_is_removable(mmc))) {\n\t\tpresent = 1;\n\n\t\tif (!test_bit(DW_MMC_CARD_PRESENT, &slot->flags)) {\n\t\t\tif (mmc->caps & MMC_CAP_NEEDS_POLL) {\n\t\t\t\tdev_info(&mmc->class_dev,\n\t\t\t\t\t\"card is polling.\\n\");\n\t\t\t} else {\n\t\t\t\tdev_info(&mmc->class_dev,\n\t\t\t\t\t\"card is non-removable.\\n\");\n\t\t\t}\n\t\t\tset_bit(DW_MMC_CARD_PRESENT, &slot->flags);\n\t\t}\n\n\t\treturn present;\n\t} else if (gpio_cd >= 0)\n\t\tpresent = gpio_cd;\n\telse\n\t\tpresent = (mci_readl(slot->host, CDETECT) & (1 << slot->id))\n\t\t\t== 0 ? 1 : 0;\n\n\tspin_lock_bh(&host->lock);\n\tif (present && !test_and_set_bit(DW_MMC_CARD_PRESENT, &slot->flags))\n\t\tdev_dbg(&mmc->class_dev, \"card is present\\n\");\n\telse if (!present &&\n\t\t\t!test_and_clear_bit(DW_MMC_CARD_PRESENT, &slot->flags))\n\t\tdev_dbg(&mmc->class_dev, \"card is not present\\n\");\n\tspin_unlock_bh(&host->lock);\n\n\treturn present;\n}\n\nstatic void dw_mci_adjust_fifoth(struct dw_mci *host, struct mmc_data *data)\n{\n\tunsigned int blksz = data->blksz;\n\tstatic const u32 mszs[] = {1, 4, 8, 16, 32, 64, 128, 256};\n\tu32 fifo_width = 1 << host->data_shift;\n\tu32 blksz_depth = blksz / fifo_width, fifoth_val;\n\tu32 msize = 0, rx_wmark = 1, tx_wmark, tx_wmark_invers;\n\tint idx = ARRAY_SIZE(mszs) - 1;\n\n\t/* pio should ship this scenario */\n\tif (!host->use_dma)\n\t\treturn;\n\n\ttx_wmark = (host->fifo_depth) / 2;\n\ttx_wmark_invers = host->fifo_depth - tx_wmark;\n\n\t/*\n\t * MSIZE is '1',\n\t * if blksz is not a multiple of the FIFO width\n\t */\n\tif (blksz % fifo_width)\n\t\tgoto done;\n\n\tdo {\n\t\tif (!((blksz_depth % mszs[idx]) ||\n\t\t (tx_wmark_invers % mszs[idx]))) {\n\t\t\tmsize = idx;\n\t\t\trx_wmark = mszs[idx] - 1;\n\t\t\tbreak;\n\t\t}\n\t} while (--idx > 0);\n\t/*\n\t * If idx is '0', it won't be tried\n\t * Thus, initial values are uesed\n\t */\ndone:\n\tfifoth_val = SDMMC_SET_FIFOTH(msize, rx_wmark, tx_wmark);\n\tmci_writel(host, FIFOTH, fifoth_val);\n}\n\nstatic void dw_mci_ctrl_thld(struct dw_mci *host, struct mmc_data *data)\n{\n\tunsigned int blksz = data->blksz;\n\tu32 blksz_depth, fifo_depth;\n\tu16 thld_size;\n\tu8 enable;\n\n\t/*\n\t * CDTHRCTL doesn't exist prior to 240A (in fact that register offset is\n\t * in the FIFO region, so we really shouldn't access it).\n\t */\n\tif (host->verid < DW_MMC_240A ||\n\t\t(host->verid < DW_MMC_280A && data->flags & MMC_DATA_WRITE))\n\t\treturn;\n\n\t/*\n\t * Card write Threshold is introduced since 2.80a\n\t * It's used when HS400 mode is enabled.\n\t */\n\tif (data->flags & MMC_DATA_WRITE &&\n\t\t!(host->timing != MMC_TIMING_MMC_HS400))\n\t\treturn;\n\n\tif (data->flags & MMC_DATA_WRITE)\n\t\tenable = SDMMC_CARD_WR_THR_EN;\n\telse\n\t\tenable = SDMMC_CARD_RD_THR_EN;\n\n\tif (host->timing != MMC_TIMING_MMC_HS200 &&\n\t host->timing != MMC_TIMING_UHS_SDR104)\n\t\tgoto disable;\n\n\tblksz_depth = blksz / (1 << host->data_shift);\n\tfifo_depth = host->fifo_depth;\n\n\tif (blksz_depth > fifo_depth)\n\t\tgoto disable;\n\n\t/*\n\t * If (blksz_depth) >= (fifo_depth >> 1), should be 'thld_size <= blksz'\n\t * If (blksz_depth) < (fifo_depth >> 1), should be thld_size = blksz\n\t * Currently just choose blksz.\n\t */\n\tthld_size = blksz;\n\tmci_writel(host, CDTHRCTL, SDMMC_SET_THLD(thld_size, enable));\n\treturn;\n\ndisable:\n\tmci_writel(host, CDTHRCTL, 0);\n}\n\nstatic int dw_mci_submit_data_dma(struct dw_mci *host, struct mmc_data *data)\n{\n\tunsigned long irqflags;\n\tint sg_len;\n\tu32 temp;\n\n\thost->using_dma = 0;\n\n\t/* If we don't have a channel, we can't do DMA */\n\tif (!host->use_dma)\n\t\treturn -ENODEV;\n\n\tsg_len = dw_mci_pre_dma_transfer(host, data, COOKIE_MAPPED);\n\tif (sg_len < 0) {\n\t\thost->dma_ops->stop(host);\n\t\treturn sg_len;\n\t}\n\n\thost->using_dma = 1;\n\n\tif (host->use_dma == TRANS_MODE_IDMAC)\n\t\tdev_vdbg(host->dev,\n\t\t\t \"sd sg_cpu: %#lx sg_dma: %#lx sg_len: %d\\n\",\n\t\t\t (unsigned long)host->sg_cpu,\n\t\t\t (unsigned long)host->sg_dma,\n\t\t\t sg_len);\n\n\t/*\n\t * Decide the MSIZE and RX/TX Watermark.\n\t * If current block size is same with previous size,\n\t * no need to update fifoth.\n\t */\n\tif (host->prev_blksz != data->blksz)\n\t\tdw_mci_adjust_fifoth(host, data);\n\n\t/* Enable the DMA interface */\n\ttemp = mci_readl(host, CTRL);\n\ttemp |= SDMMC_CTRL_DMA_ENABLE;\n\tmci_writel(host, CTRL, temp);\n\n\t/* Disable RX/TX IRQs, let DMA handle it */\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\ttemp = mci_readl(host, INTMASK);\n\ttemp &= ~(SDMMC_INT_RXDR | SDMMC_INT_TXDR);\n\tmci_writel(host, INTMASK, temp);\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\n\tif (host->dma_ops->start(host, sg_len)) {\n\t\thost->dma_ops->stop(host);\n\t\t/* We can't do DMA, try PIO for this one */\n\t\tdev_dbg(host->dev,\n\t\t\t\"%s: fall back to PIO mode for current transfer\\n\",\n\t\t\t__func__);\n\t\treturn -ENODEV;\n\t}\n\n\treturn 0;\n}\n\nstatic void dw_mci_submit_data(struct dw_mci *host, struct mmc_data *data)\n{\n\tunsigned long irqflags;\n\tint flags = SG_MITER_ATOMIC;\n\tu32 temp;\n\n\tdata->error = -EINPROGRESS;\n\n\tWARN_ON(host->data);\n\thost->sg = NULL;\n\thost->data = data;\n\n\tif (data->flags & MMC_DATA_READ)\n\t\thost->dir_status = DW_MCI_RECV_STATUS;\n\telse\n\t\thost->dir_status = DW_MCI_SEND_STATUS;\n\n\tdw_mci_ctrl_thld(host, data);\n\n\tif (dw_mci_submit_data_dma(host, data)) {\n\t\tif (host->data->flags & MMC_DATA_READ)\n\t\t\tflags |= SG_MITER_TO_SG;\n\t\telse\n\t\t\tflags |= SG_MITER_FROM_SG;\n\n\t\tsg_miter_start(&host->sg_miter, data->sg, data->sg_len, flags);\n\t\thost->sg = data->sg;\n\t\thost->part_buf_start = 0;\n\t\thost->part_buf_count = 0;\n\n\t\tmci_writel(host, RINTSTS, SDMMC_INT_TXDR | SDMMC_INT_RXDR);\n\n\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\t\ttemp = mci_readl(host, INTMASK);\n\t\ttemp |= SDMMC_INT_TXDR | SDMMC_INT_RXDR;\n\t\tmci_writel(host, INTMASK, temp);\n\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\n\t\ttemp = mci_readl(host, CTRL);\n\t\ttemp &= ~SDMMC_CTRL_DMA_ENABLE;\n\t\tmci_writel(host, CTRL, temp);\n\n\t\t/*\n\t\t * Use the initial fifoth_val for PIO mode. If wm_algined\n\t\t * is set, we set watermark same as data size.\n\t\t * If next issued data may be transfered by DMA mode,\n\t\t * prev_blksz should be invalidated.\n\t\t */\n\t\tif (host->wm_aligned)\n\t\t\tdw_mci_adjust_fifoth(host, data);\n\t\telse\n\t\t\tmci_writel(host, FIFOTH, host->fifoth_val);\n\t\thost->prev_blksz = 0;\n\t} else {\n\t\t/*\n\t\t * Keep the current block size.\n\t\t * It will be used to decide whether to update\n\t\t * fifoth register next time.\n\t\t */\n\t\thost->prev_blksz = data->blksz;\n\t}\n}\n\nstatic void dw_mci_setup_bus(struct dw_mci_slot *slot, bool force_clkinit)\n{\n\tstruct dw_mci *host = slot->host;\n\tunsigned int clock = slot->clock;\n\tu32 div;\n\tu32 clk_en_a;\n\tu32 sdmmc_cmd_bits = SDMMC_CMD_UPD_CLK | SDMMC_CMD_PRV_DAT_WAIT;\n\n\t/* We must continue to set bit 28 in CMD until the change is complete */\n\tif (host->state == STATE_WAITING_CMD11_DONE)\n\t\tsdmmc_cmd_bits |= SDMMC_CMD_VOLT_SWITCH;\n\n\tif (!clock) {\n\t\tmci_writel(host, CLKENA, 0);\n\t\tmci_send_cmd(slot, sdmmc_cmd_bits, 0);\n\t} else if (clock != host->current_speed || force_clkinit) {\n\t\tdiv = host->bus_hz / clock;\n\t\tif (host->bus_hz % clock && host->bus_hz > clock)\n\t\t\t/*\n\t\t\t * move the + 1 after the divide to prevent\n\t\t\t * over-clocking the card.\n\t\t\t */\n\t\t\tdiv += 1;\n\n\t\tdiv = (host->bus_hz != clock) ? DIV_ROUND_UP(div, 2) : 0;\n\n\t\tif ((clock != slot->__clk_old &&\n\t\t\t!test_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags)) ||\n\t\t\tforce_clkinit) {\n\t\t\t/* Silent the verbose log if calling from PM context */\n\t\t\tif (!force_clkinit)\n\t\t\t\tdev_info(&slot->mmc->class_dev,\n\t\t\t\t\t \"Bus speed (slot %d) = %dHz (slot req %dHz, actual %dHZ div = %d)\\n\",\n\t\t\t\t\t slot->id, host->bus_hz, clock,\n\t\t\t\t\t div ? ((host->bus_hz / div) >> 1) :\n\t\t\t\t\t host->bus_hz, div);\n\n\t\t\t/*\n\t\t\t * If card is polling, display the message only\n\t\t\t * one time at boot time.\n\t\t\t */\n\t\t\tif (slot->mmc->caps & MMC_CAP_NEEDS_POLL &&\n\t\t\t\t\tslot->mmc->f_min == clock)\n\t\t\t\tset_bit(DW_MMC_CARD_NEEDS_POLL, &slot->flags);\n\t\t}\n\n\t\t/* disable clock */\n\t\tmci_writel(host, CLKENA, 0);\n\t\tmci_writel(host, CLKSRC, 0);\n\n\t\t/* inform CIU */\n\t\tmci_send_cmd(slot, sdmmc_cmd_bits, 0);\n\n\t\t/* set clock to desired speed */\n\t\tmci_writel(host, CLKDIV, div);\n\n\t\t/* inform CIU */\n\t\tmci_send_cmd(slot, sdmmc_cmd_bits, 0);\n\n\t\t/* enable clock; only low power if no SDIO */\n\t\tclk_en_a = SDMMC_CLKEN_ENABLE << slot->id;\n\t\tif (!test_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags))\n\t\t\tclk_en_a |= SDMMC_CLKEN_LOW_PWR << slot->id;\n\t\tmci_writel(host, CLKENA, clk_en_a);\n\n\t\t/* inform CIU */\n\t\tmci_send_cmd(slot, sdmmc_cmd_bits, 0);\n\n\t\t/* keep the last clock value that was requested from core */\n\t\tslot->__clk_old = clock;\n\t}\n\n\thost->current_speed = clock;\n\n\t/* Set the current slot bus width */\n\tmci_writel(host, CTYPE, (slot->ctype << slot->id));\n}\n\nstatic void __dw_mci_start_request(struct dw_mci *host,\n\t\t\t\t struct dw_mci_slot *slot,\n\t\t\t\t struct mmc_command *cmd)\n{\n\tstruct mmc_request *mrq;\n\tstruct mmc_data\t*data;\n\tu32 cmdflags;\n\n\tmrq = slot->mrq;\n\n\thost->mrq = mrq;\n\n\thost->pending_events = 0;\n\thost->completed_events = 0;\n\thost->cmd_status = 0;\n\thost->data_status = 0;\n\thost->dir_status = 0;\n\n\tdata = cmd->data;\n\tif (data) {\n\t\tmci_writel(host, TMOUT, 0xFFFFFFFF);\n\t\tmci_writel(host, BYTCNT, data->blksz*data->blocks);\n\t\tmci_writel(host, BLKSIZ, data->blksz);\n\t}\n\n\tcmdflags = dw_mci_prepare_command(slot->mmc, cmd);\n\n\t/* this is the first command, send the initialization clock */\n\tif (test_and_clear_bit(DW_MMC_CARD_NEED_INIT, &slot->flags))\n\t\tcmdflags |= SDMMC_CMD_INIT;\n\n\tif (data) {\n\t\tdw_mci_submit_data(host, data);\n\t\twmb(); /* drain writebuffer */\n\t}\n\n\tdw_mci_start_command(host, cmd, cmdflags);\n\n\tif (cmd->opcode == SD_SWITCH_VOLTAGE) {\n\t\tunsigned long irqflags;\n\n\t\t/*\n\t\t * Databook says to fail after 2ms w/ no response, but evidence\n\t\t * shows that sometimes the cmd11 interrupt takes over 130ms.\n\t\t * We'll set to 500ms, plus an extra jiffy just in case jiffies\n\t\t * is just about to roll over.\n\t\t *\n\t\t * We do this whole thing under spinlock and only if the\n\t\t * command hasn't already completed (indicating the the irq\n\t\t * already ran so we don't want the timeout).\n\t\t */\n\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\t\tif (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))\n\t\t\tmod_timer(&host->cmd11_timer,\n\t\t\t\tjiffies + msecs_to_jiffies(500) + 1);\n\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\t}\n\n\thost->stop_cmdr = dw_mci_prep_stop_abort(host, cmd);\n}\n\nstatic void dw_mci_start_request(struct dw_mci *host,\n\t\t\t\t struct dw_mci_slot *slot)\n{\n\tstruct mmc_request *mrq = slot->mrq;\n\tstruct mmc_command *cmd;\n\n\tcmd = mrq->sbc ? mrq->sbc : mrq->cmd;\n\t__dw_mci_start_request(host, slot, cmd);\n}\n\n/* must be called with host->lock held */\nstatic void dw_mci_queue_request(struct dw_mci *host, struct dw_mci_slot *slot,\n\t\t\t\t struct mmc_request *mrq)\n{\n\tdev_vdbg(&slot->mmc->class_dev, \"queue request: state=%d\\n\",\n\t\t host->state);\n\n\tslot->mrq = mrq;\n\n\tif (host->state == STATE_WAITING_CMD11_DONE) {\n\t\tdev_warn(&slot->mmc->class_dev,\n\t\t\t \"Voltage change didn't complete\\n\");\n\t\t/*\n\t\t * this case isn't expected to happen, so we can\n\t\t * either crash here or just try to continue on\n\t\t * in the closest possible state\n\t\t */\n\t\thost->state = STATE_IDLE;\n\t}\n\n\tif (host->state == STATE_IDLE) {\n\t\thost->state = STATE_SENDING_CMD;\n\t\tdw_mci_start_request(host, slot);\n\t} else {\n\t\tlist_add_tail(&slot->queue_node, &host->queue);\n\t}\n}\n\nstatic void dw_mci_request(struct mmc_host *mmc, struct mmc_request *mrq)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\n\tWARN_ON(slot->mrq);\n\n\t/*\n\t * The check for card presence and queueing of the request must be\n\t * atomic, otherwise the card could be removed in between and the\n\t * request wouldn't fail until another card was inserted.\n\t */\n\n\tif (!dw_mci_get_cd(mmc)) {\n\t\tmrq->cmd->error = -ENOMEDIUM;\n\t\tmmc_request_done(mmc, mrq);\n\t\treturn;\n\t}\n\n\tspin_lock_bh(&host->lock);\n\n\tdw_mci_queue_request(host, slot, mrq);\n\n\tspin_unlock_bh(&host->lock);\n}\n\nstatic void dw_mci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tconst struct dw_mci_drv_data *drv_data = slot->host->drv_data;\n\tu32 regs;\n\tint ret;\n\n\tswitch (ios->bus_width) {\n\tcase MMC_BUS_WIDTH_4:\n\t\tslot->ctype = SDMMC_CTYPE_4BIT;\n\t\tbreak;\n\tcase MMC_BUS_WIDTH_8:\n\t\tslot->ctype = SDMMC_CTYPE_8BIT;\n\t\tbreak;\n\tdefault:\n\t\t/* set default 1 bit mode */\n\t\tslot->ctype = SDMMC_CTYPE_1BIT;\n\t}\n\n\tregs = mci_readl(slot->host, UHS_REG);\n\n\t/* DDR mode set */\n\tif (ios->timing == MMC_TIMING_MMC_DDR52 ||\n\t ios->timing == MMC_TIMING_UHS_DDR50 ||\n\t ios->timing == MMC_TIMING_MMC_HS400)\n\t\tregs |= ((0x1 << slot->id) << 16);\n\telse\n\t\tregs &= ~((0x1 << slot->id) << 16);\n\n\tmci_writel(slot->host, UHS_REG, regs);\n\tslot->host->timing = ios->timing;\n\n\t/*\n\t * Use mirror of ios->clock to prevent race with mmc\n\t * core ios update when finding the minimum.\n\t */\n\tslot->clock = ios->clock;\n\n\tif (drv_data && drv_data->set_ios)\n\t\tdrv_data->set_ios(slot->host, ios);\n\n\tswitch (ios->power_mode) {\n\tcase MMC_POWER_UP:\n\t\tif (!IS_ERR(mmc->supply.vmmc)) {\n\t\t\tret = mmc_regulator_set_ocr(mmc, mmc->supply.vmmc,\n\t\t\t\t\tios->vdd);\n\t\t\tif (ret) {\n\t\t\t\tdev_err(slot->host->dev,\n\t\t\t\t\t\"failed to enable vmmc regulator\\n\");\n\t\t\t\t/*return, if failed turn on vmmc*/\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tset_bit(DW_MMC_CARD_NEED_INIT, &slot->flags);\n\t\tregs = mci_readl(slot->host, PWREN);\n\t\tregs |= (1 << slot->id);\n\t\tmci_writel(slot->host, PWREN, regs);\n\t\tbreak;\n\tcase MMC_POWER_ON:\n\t\tif (!slot->host->vqmmc_enabled) {\n\t\t\tif (!IS_ERR(mmc->supply.vqmmc)) {\n\t\t\t\tret = regulator_enable(mmc->supply.vqmmc);\n\t\t\t\tif (ret < 0)\n\t\t\t\t\tdev_err(slot->host->dev,\n\t\t\t\t\t\t\"failed to enable vqmmc\\n\");\n\t\t\t\telse\n\t\t\t\t\tslot->host->vqmmc_enabled = true;\n\n\t\t\t} else {\n\t\t\t\t/* Keep track so we don't reset again */\n\t\t\t\tslot->host->vqmmc_enabled = true;\n\t\t\t}\n\n\t\t\t/* Reset our state machine after powering on */\n\t\t\tdw_mci_ctrl_reset(slot->host,\n\t\t\t\t\t SDMMC_CTRL_ALL_RESET_FLAGS);\n\t\t}\n\n\t\t/* Adjust clock / bus width after power is up */\n\t\tdw_mci_setup_bus(slot, false);\n\n\t\tbreak;\n\tcase MMC_POWER_OFF:\n\t\t/* Turn clock off before power goes down */\n\t\tdw_mci_setup_bus(slot, false);\n\n\t\tif (!IS_ERR(mmc->supply.vmmc))\n\t\t\tmmc_regulator_set_ocr(mmc, mmc->supply.vmmc, 0);\n\n\t\tif (!IS_ERR(mmc->supply.vqmmc) && slot->host->vqmmc_enabled)\n\t\t\tregulator_disable(mmc->supply.vqmmc);\n\t\tslot->host->vqmmc_enabled = false;\n\n\t\tregs = mci_readl(slot->host, PWREN);\n\t\tregs &= ~(1 << slot->id);\n\t\tmci_writel(slot->host, PWREN, regs);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (slot->host->state == STATE_WAITING_CMD11_DONE && ios->clock != 0)\n\t\tslot->host->state = STATE_IDLE;\n}\n\nstatic int dw_mci_card_busy(struct mmc_host *mmc)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tu32 status;\n\n\t/*\n\t * Check the busy bit which is low when DAT[3:0]\n\t * (the data lines) are 0000\n\t */\n\tstatus = mci_readl(slot->host, STATUS);\n\n\treturn !!(status & SDMMC_STATUS_BUSY);\n}\n\nstatic int dw_mci_switch_voltage(struct mmc_host *mmc, struct mmc_ios *ios)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\tu32 uhs;\n\tu32 v18 = SDMMC_UHS_18V << slot->id;\n\tint ret;\n\n\tif (drv_data && drv_data->switch_voltage)\n\t\treturn drv_data->switch_voltage(mmc, ios);\n\n\t/*\n\t * Program the voltage. Note that some instances of dw_mmc may use\n\t * the UHS_REG for this. For other instances (like exynos) the UHS_REG\n\t * does no harm but you need to set the regulator directly. Try both.\n\t */\n\tuhs = mci_readl(host, UHS_REG);\n\tif (ios->signal_voltage == MMC_SIGNAL_VOLTAGE_330)\n\t\tuhs &= ~v18;\n\telse\n\t\tuhs |= v18;\n\n\tif (!IS_ERR(mmc->supply.vqmmc)) {\n\t\tret = mmc_regulator_set_vqmmc(mmc, ios);\n\n\t\tif (ret) {\n\t\t\tdev_dbg(&mmc->class_dev,\n\t\t\t\t\t \"Regulator set error %d - %s V\\n\",\n\t\t\t\t\t ret, uhs & v18 ? \"1.8\" : \"3.3\");\n\t\t\treturn ret;\n\t\t}\n\t}\n\tmci_writel(host, UHS_REG, uhs);\n\n\treturn 0;\n}\n\nstatic int dw_mci_get_ro(struct mmc_host *mmc)\n{\n\tint read_only;\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tint gpio_ro = mmc_gpio_get_ro(mmc);\n\n\t/* Use platform get_ro function, else try on board write protect */\n\tif (gpio_ro >= 0)\n\t\tread_only = gpio_ro;\n\telse\n\t\tread_only =\n\t\t\tmci_readl(slot->host, WRTPRT) & (1 << slot->id) ? 1 : 0;\n\n\tdev_dbg(&mmc->class_dev, \"card is %s\\n\",\n\t\tread_only ? \"read-only\" : \"read-write\");\n\n\treturn read_only;\n}\n\nstatic void dw_mci_hw_reset(struct mmc_host *mmc)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tint reset;\n\n\tif (host->use_dma == TRANS_MODE_IDMAC)\n\t\tdw_mci_idmac_reset(host);\n\n\tif (!dw_mci_ctrl_reset(host, SDMMC_CTRL_DMA_RESET |\n\t\t\t\t SDMMC_CTRL_FIFO_RESET))\n\t\treturn;\n\n\t/*\n\t * According to eMMC spec, card reset procedure:\n\t * tRstW >= 1us: RST_n pulse width\n\t * tRSCA >= 200us: RST_n to Command time\n\t * tRSTH >= 1us: RST_n high period\n\t */\n\treset = mci_readl(host, RST_N);\n\treset &= ~(SDMMC_RST_HWACTIVE << slot->id);\n\tmci_writel(host, RST_N, reset);\n\tusleep_range(1, 2);\n\treset |= SDMMC_RST_HWACTIVE << slot->id;\n\tmci_writel(host, RST_N, reset);\n\tusleep_range(200, 300);\n}\n\nstatic void dw_mci_init_card(struct mmc_host *mmc, struct mmc_card *card)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\n\t/*\n\t * Low power mode will stop the card clock when idle. According to the\n\t * description of the CLKENA register we should disable low power mode\n\t * for SDIO cards if we need SDIO interrupts to work.\n\t */\n\tif (mmc->caps & MMC_CAP_SDIO_IRQ) {\n\t\tconst u32 clken_low_pwr = SDMMC_CLKEN_LOW_PWR << slot->id;\n\t\tu32 clk_en_a_old;\n\t\tu32 clk_en_a;\n\n\t\tclk_en_a_old = mci_readl(host, CLKENA);\n\n\t\tif (card->type == MMC_TYPE_SDIO ||\n\t\t card->type == MMC_TYPE_SD_COMBO) {\n\t\t\tset_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags);\n\t\t\tclk_en_a = clk_en_a_old & ~clken_low_pwr;\n\t\t} else {\n\t\t\tclear_bit(DW_MMC_CARD_NO_LOW_PWR, &slot->flags);\n\t\t\tclk_en_a = clk_en_a_old | clken_low_pwr;\n\t\t}\n\n\t\tif (clk_en_a != clk_en_a_old) {\n\t\t\tmci_writel(host, CLKENA, clk_en_a);\n\t\t\tmci_send_cmd(slot, SDMMC_CMD_UPD_CLK |\n\t\t\t\t SDMMC_CMD_PRV_DAT_WAIT, 0);\n\t\t}\n\t}\n}\n\nstatic void __dw_mci_enable_sdio_irq(struct dw_mci_slot *slot, int enb)\n{\n\tstruct dw_mci *host = slot->host;\n\tunsigned long irqflags;\n\tu32 int_mask;\n\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t/* Enable/disable Slot Specific SDIO interrupt */\n\tint_mask = mci_readl(host, INTMASK);\n\tif (enb)\n\t\tint_mask |= SDMMC_INT_SDIO(slot->sdio_id);\n\telse\n\t\tint_mask &= ~SDMMC_INT_SDIO(slot->sdio_id);\n\tmci_writel(host, INTMASK, int_mask);\n\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n}\n\nstatic void dw_mci_enable_sdio_irq(struct mmc_host *mmc, int enb)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\n\t__dw_mci_enable_sdio_irq(slot, enb);\n\n\t/* Avoid runtime suspending the device when SDIO IRQ is enabled */\n\tif (enb)\n\t\tpm_runtime_get_noresume(host->dev);\n\telse\n\t\tpm_runtime_put_noidle(host->dev);\n}\n\nstatic void dw_mci_ack_sdio_irq(struct mmc_host *mmc)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\n\t__dw_mci_enable_sdio_irq(slot, 1);\n}\n\nstatic int dw_mci_execute_tuning(struct mmc_host *mmc, u32 opcode)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\tint err = -EINVAL;\n\n\tif (drv_data && drv_data->execute_tuning)\n\t\terr = drv_data->execute_tuning(slot, opcode);\n\treturn err;\n}\n\nstatic int dw_mci_prepare_hs400_tuning(struct mmc_host *mmc,\n\t\t\t\t struct mmc_ios *ios)\n{\n\tstruct dw_mci_slot *slot = mmc_priv(mmc);\n\tstruct dw_mci *host = slot->host;\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\n\tif (drv_data && drv_data->prepare_hs400_tuning)\n\t\treturn drv_data->prepare_hs400_tuning(host, ios);\n\n\treturn 0;\n}\n\nstatic bool dw_mci_reset(struct dw_mci *host)\n{\n\tu32 flags = SDMMC_CTRL_RESET | SDMMC_CTRL_FIFO_RESET;\n\tbool ret = false;\n\tu32 status = 0;\n\n\t/*\n\t * Resetting generates a block interrupt, hence setting\n\t * the scatter-gather pointer to NULL.\n\t */\n\tif (host->sg) {\n\t\tsg_miter_stop(&host->sg_miter);\n\t\thost->sg = NULL;\n\t}\n\n\tif (host->use_dma)\n\t\tflags |= SDMMC_CTRL_DMA_RESET;\n\n\tif (dw_mci_ctrl_reset(host, flags)) {\n\t\t/*\n\t\t * In all cases we clear the RAWINTS\n\t\t * register to clear any interrupts.\n\t\t */\n\t\tmci_writel(host, RINTSTS, 0xFFFFFFFF);\n\n\t\tif (!host->use_dma) {\n\t\t\tret = true;\n\t\t\tgoto ciu_out;\n\t\t}\n\n\t\t/* Wait for dma_req to be cleared */\n\t\tif (readl_poll_timeout_atomic(host->regs + SDMMC_STATUS,\n\t\t\t\t\t status,\n\t\t\t\t\t !(status & SDMMC_STATUS_DMA_REQ),\n\t\t\t\t\t 1, 500 * USEC_PER_MSEC)) {\n\t\t\tdev_err(host->dev,\n\t\t\t\t\"%s: Timeout waiting for dma_req to be cleared\\n\",\n\t\t\t\t__func__);\n\t\t\tgoto ciu_out;\n\t\t}\n\n\t\t/* when using DMA next we reset the fifo again */\n\t\tif (!dw_mci_ctrl_reset(host, SDMMC_CTRL_FIFO_RESET))\n\t\t\tgoto ciu_out;\n\t} else {\n\t\t/* if the controller reset bit did clear, then set clock regs */\n\t\tif (!(mci_readl(host, CTRL) & SDMMC_CTRL_RESET)) {\n\t\t\tdev_err(host->dev,\n\t\t\t\t\"%s: fifo/dma reset bits didn't clear but ciu was reset, doing clock update\\n\",\n\t\t\t\t__func__);\n\t\t\tgoto ciu_out;\n\t\t}\n\t}\n\n\tif (host->use_dma == TRANS_MODE_IDMAC)\n\t\t/* It is also required that we reinit idmac */\n\t\tdw_mci_idmac_init(host);\n\n\tret = true;\n\nciu_out:\n\t/* After a CTRL reset we need to have CIU set clock registers */\n\tmci_send_cmd(host->slot, SDMMC_CMD_UPD_CLK, 0);\n\n\treturn ret;\n}\n\nstatic const struct mmc_host_ops dw_mci_ops = {\n\t.request\t\t= dw_mci_request,\n\t.pre_req\t\t= dw_mci_pre_req,\n\t.post_req\t\t= dw_mci_post_req,\n\t.set_ios\t\t= dw_mci_set_ios,\n\t.get_ro\t\t\t= dw_mci_get_ro,\n\t.get_cd\t\t\t= dw_mci_get_cd,\n\t.hw_reset = dw_mci_hw_reset,\n\t.enable_sdio_irq\t= dw_mci_enable_sdio_irq,\n\t.ack_sdio_irq\t\t= dw_mci_ack_sdio_irq,\n\t.execute_tuning\t\t= dw_mci_execute_tuning,\n\t.card_busy\t\t= dw_mci_card_busy,\n\t.start_signal_voltage_switch = dw_mci_switch_voltage,\n\t.init_card\t\t= dw_mci_init_card,\n\t.prepare_hs400_tuning\t= dw_mci_prepare_hs400_tuning,\n};\n\nstatic void dw_mci_request_end(struct dw_mci *host, struct mmc_request *mrq)\n\t__releases(&host->lock)\n\t__acquires(&host->lock)\n{\n\tstruct dw_mci_slot *slot;\n\tstruct mmc_host\t*prev_mmc = host->slot->mmc;\n\n\tWARN_ON(host->cmd || host->data);\n\n\thost->slot->mrq = NULL;\n\thost->mrq = NULL;\n\tif (!list_empty(&host->queue)) {\n\t\tslot = list_entry(host->queue.next,\n\t\t\t\t struct dw_mci_slot, queue_node);\n\t\tlist_del(&slot->queue_node);\n\t\tdev_vdbg(host->dev, \"list not empty: %s is next\\n\",\n\t\t\t mmc_hostname(slot->mmc));\n\t\thost->state = STATE_SENDING_CMD;\n\t\tdw_mci_start_request(host, slot);\n\t} else {\n\t\tdev_vdbg(host->dev, \"list empty\\n\");\n\n\t\tif (host->state == STATE_SENDING_CMD11)\n\t\t\thost->state = STATE_WAITING_CMD11_DONE;\n\t\telse\n\t\t\thost->state = STATE_IDLE;\n\t}\n\n\tspin_unlock(&host->lock);\n\tmmc_request_done(prev_mmc, mrq);\n\tspin_lock(&host->lock);\n}\n\nstatic int dw_mci_command_complete(struct dw_mci *host, struct mmc_command *cmd)\n{\n\tu32 status = host->cmd_status;\n\n\thost->cmd_status = 0;\n\n\t/* Read the response from the card (up to 16 bytes) */\n\tif (cmd->flags & MMC_RSP_PRESENT) {\n\t\tif (cmd->flags & MMC_RSP_136) {\n\t\t\tcmd->resp[3] = mci_readl(host, RESP0);\n\t\t\tcmd->resp[2] = mci_readl(host, RESP1);\n\t\t\tcmd->resp[1] = mci_readl(host, RESP2);\n\t\t\tcmd->resp[0] = mci_readl(host, RESP3);\n\t\t} else {\n\t\t\tcmd->resp[0] = mci_readl(host, RESP0);\n\t\t\tcmd->resp[1] = 0;\n\t\t\tcmd->resp[2] = 0;\n\t\t\tcmd->resp[3] = 0;\n\t\t}\n\t}\n\n\tif (status & SDMMC_INT_RTO)\n\t\tcmd->error = -ETIMEDOUT;\n\telse if ((cmd->flags & MMC_RSP_CRC) && (status & SDMMC_INT_RCRC))\n\t\tcmd->error = -EILSEQ;\n\telse if (status & SDMMC_INT_RESP_ERR)\n\t\tcmd->error = -EIO;\n\telse\n\t\tcmd->error = 0;\n\n\treturn cmd->error;\n}\n\nstatic int dw_mci_data_complete(struct dw_mci *host, struct mmc_data *data)\n{\n\tu32 status = host->data_status;\n\n\tif (status & DW_MCI_DATA_ERROR_FLAGS) {\n\t\tif (status & SDMMC_INT_DRTO) {\n\t\t\tdata->error = -ETIMEDOUT;\n\t\t} else if (status & SDMMC_INT_DCRC) {\n\t\t\tdata->error = -EILSEQ;\n\t\t} else if (status & SDMMC_INT_EBE) {\n\t\t\tif (host->dir_status ==\n\t\t\t\tDW_MCI_SEND_STATUS) {\n\t\t\t\t/*\n\t\t\t\t * No data CRC status was returned.\n\t\t\t\t * The number of bytes transferred\n\t\t\t\t * will be exaggerated in PIO mode.\n\t\t\t\t */\n\t\t\t\tdata->bytes_xfered = 0;\n\t\t\t\tdata->error = -ETIMEDOUT;\n\t\t\t} else if (host->dir_status ==\n\t\t\t\t\tDW_MCI_RECV_STATUS) {\n\t\t\t\tdata->error = -EILSEQ;\n\t\t\t}\n\t\t} else {\n\t\t\t/* SDMMC_INT_SBE is included */\n\t\t\tdata->error = -EILSEQ;\n\t\t}\n\n\t\tdev_dbg(host->dev, \"data error, status 0x%08x\\n\", status);\n\n\t\t/*\n\t\t * After an error, there may be data lingering\n\t\t * in the FIFO\n\t\t */\n\t\tdw_mci_reset(host);\n\t} else {\n\t\tdata->bytes_xfered = data->blocks * data->blksz;\n\t\tdata->error = 0;\n\t}\n\n\treturn data->error;\n}\n\nstatic void dw_mci_set_drto(struct dw_mci *host)\n{\n\tunsigned int drto_clks;\n\tunsigned int drto_div;\n\tunsigned int drto_ms;\n\tunsigned long irqflags;\n\n\tdrto_clks = mci_readl(host, TMOUT) >> 8;\n\tdrto_div = (mci_readl(host, CLKDIV) & 0xff) * 2;\n\tif (drto_div == 0)\n\t\tdrto_div = 1;\n\n\tdrto_ms = DIV_ROUND_UP_ULL((u64)MSEC_PER_SEC * drto_clks * drto_div,\n\t\t\t\t host->bus_hz);\n\n\t/* add a bit spare time */\n\tdrto_ms += 10;\n\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\tif (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events))\n\t\tmod_timer(&host->dto_timer,\n\t\t\t jiffies + msecs_to_jiffies(drto_ms));\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n}\n\nstatic bool dw_mci_clear_pending_cmd_complete(struct dw_mci *host)\n{\n\tif (!test_bit(EVENT_CMD_COMPLETE, &host->pending_events))\n\t\treturn false;\n\n\t/*\n\t * Really be certain that the timer has stopped. This is a bit of\n\t * paranoia and could only really happen if we had really bad\n\t * interrupt latency and the interrupt routine and timeout were\n\t * running concurrently so that the del_timer() in the interrupt\n\t * handler couldn't run.\n\t */\n\tWARN_ON(del_timer_sync(&host->cto_timer));\n\tclear_bit(EVENT_CMD_COMPLETE, &host->pending_events);\n\n\treturn true;\n}\n\nstatic bool dw_mci_clear_pending_data_complete(struct dw_mci *host)\n{\n\tif (!test_bit(EVENT_DATA_COMPLETE, &host->pending_events))\n\t\treturn false;\n\n\t/* Extra paranoia just like dw_mci_clear_pending_cmd_complete() */\n\tWARN_ON(del_timer_sync(&host->dto_timer));\n\tclear_bit(EVENT_DATA_COMPLETE, &host->pending_events);\n\n\treturn true;\n}\n\nstatic void dw_mci_tasklet_func(unsigned long priv)\n{\n\tstruct dw_mci *host = (struct dw_mci *)priv;\n\tstruct mmc_data\t*data;\n\tstruct mmc_command *cmd;\n\tstruct mmc_request *mrq;\n\tenum dw_mci_state state;\n\tenum dw_mci_state prev_state;\n\tunsigned int err;\n\n\tspin_lock(&host->lock);\n\n\tstate = host->state;\n\tdata = host->data;\n\tmrq = host->mrq;\n\n\tdo {\n\t\tprev_state = state;\n\n\t\tswitch (state) {\n\t\tcase STATE_IDLE:\n\t\tcase STATE_WAITING_CMD11_DONE:\n\t\t\tbreak;\n\n\t\tcase STATE_SENDING_CMD11:\n\t\tcase STATE_SENDING_CMD:\n\t\t\tif (!dw_mci_clear_pending_cmd_complete(host))\n\t\t\t\tbreak;\n\n\t\t\tcmd = host->cmd;\n\t\t\thost->cmd = NULL;\n\t\t\tset_bit(EVENT_CMD_COMPLETE, &host->completed_events);\n\t\t\terr = dw_mci_command_complete(host, cmd);\n\t\t\tif (cmd == mrq->sbc && !err) {\n\t\t\t\t__dw_mci_start_request(host, host->slot,\n\t\t\t\t\t\t mrq->cmd);\n\t\t\t\tgoto unlock;\n\t\t\t}\n\n\t\t\tif (cmd->data && err) {\n\t\t\t\t/*\n\t\t\t\t * During UHS tuning sequence, sending the stop\n\t\t\t\t * command after the response CRC error would\n\t\t\t\t * throw the system into a confused state\n\t\t\t\t * causing all future tuning phases to report\n\t\t\t\t * failure.\n\t\t\t\t *\n\t\t\t\t * In such case controller will move into a data\n\t\t\t\t * transfer state after a response error or\n\t\t\t\t * response CRC error. Let's let that finish\n\t\t\t\t * before trying to send a stop, so we'll go to\n\t\t\t\t * STATE_SENDING_DATA.\n\t\t\t\t *\n\t\t\t\t * Although letting the data transfer take place\n\t\t\t\t * will waste a bit of time (we already know\n\t\t\t\t * the command was bad), it can't cause any\n\t\t\t\t * errors since it's possible it would have\n\t\t\t\t * taken place anyway if this tasklet got\n\t\t\t\t * delayed. Allowing the transfer to take place\n\t\t\t\t * avoids races and keeps things simple.\n\t\t\t\t */\n\t\t\t\tif ((err != -ETIMEDOUT) &&\n\t\t\t\t (cmd->opcode == MMC_SEND_TUNING_BLOCK)) {\n\t\t\t\t\tstate = STATE_SENDING_DATA;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tdw_mci_stop_dma(host);\n\t\t\t\tsend_stop_abort(host, data);\n\t\t\t\tstate = STATE_SENDING_STOP;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!cmd->data || err) {\n\t\t\t\tdw_mci_request_end(host, mrq);\n\t\t\t\tgoto unlock;\n\t\t\t}\n\n\t\t\tprev_state = state = STATE_SENDING_DATA;\n\t\t\t/* fall through */\n\n\t\tcase STATE_SENDING_DATA:\n\t\t\t/*\n\t\t\t * We could get a data error and never a transfer\n\t\t\t * complete so we'd better check for it here.\n\t\t\t *\n\t\t\t * Note that we don't really care if we also got a\n\t\t\t * transfer complete; stopping the DMA and sending an\n\t\t\t * abort won't hurt.\n\t\t\t */\n\t\t\tif (test_and_clear_bit(EVENT_DATA_ERROR,\n\t\t\t\t\t &host->pending_events)) {\n\t\t\t\tdw_mci_stop_dma(host);\n\t\t\t\tif (!(host->data_status & (SDMMC_INT_DRTO |\n\t\t\t\t\t\t\t SDMMC_INT_EBE)))\n\t\t\t\t\tsend_stop_abort(host, data);\n\t\t\t\tstate = STATE_DATA_ERROR;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!test_and_clear_bit(EVENT_XFER_COMPLETE,\n\t\t\t\t\t\t&host->pending_events)) {\n\t\t\t\t/*\n\t\t\t\t * If all data-related interrupts don't come\n\t\t\t\t * within the given time in reading data state.\n\t\t\t\t */\n\t\t\t\tif (host->dir_status == DW_MCI_RECV_STATUS)\n\t\t\t\t\tdw_mci_set_drto(host);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tset_bit(EVENT_XFER_COMPLETE, &host->completed_events);\n\n\t\t\t/*\n\t\t\t * Handle an EVENT_DATA_ERROR that might have shown up\n\t\t\t * before the transfer completed. This might not have\n\t\t\t * been caught by the check above because the interrupt\n\t\t\t * could have gone off between the previous check and\n\t\t\t * the check for transfer complete.\n\t\t\t *\n\t\t\t * Technically this ought not be needed assuming we\n\t\t\t * get a DATA_COMPLETE eventually (we'll notice the\n\t\t\t * error and end the request), but it shouldn't hurt.\n\t\t\t *\n\t\t\t * This has the advantage of sending the stop command.\n\t\t\t */\n\t\t\tif (test_and_clear_bit(EVENT_DATA_ERROR,\n\t\t\t\t\t &host->pending_events)) {\n\t\t\t\tdw_mci_stop_dma(host);\n\t\t\t\tif (!(host->data_status & (SDMMC_INT_DRTO |\n\t\t\t\t\t\t\t SDMMC_INT_EBE)))\n\t\t\t\t\tsend_stop_abort(host, data);\n\t\t\t\tstate = STATE_DATA_ERROR;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev_state = state = STATE_DATA_BUSY;\n\n\t\t\t/* fall through */\n\n\t\tcase STATE_DATA_BUSY:\n\t\t\tif (!dw_mci_clear_pending_data_complete(host)) {\n\t\t\t\t/*\n\t\t\t\t * If data error interrupt comes but data over\n\t\t\t\t * interrupt doesn't come within the given time.\n\t\t\t\t * in reading data state.\n\t\t\t\t */\n\t\t\t\tif (host->dir_status == DW_MCI_RECV_STATUS)\n\t\t\t\t\tdw_mci_set_drto(host);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\thost->data = NULL;\n\t\t\tset_bit(EVENT_DATA_COMPLETE, &host->completed_events);\n\t\t\terr = dw_mci_data_complete(host, data);\n\n\t\t\tif (!err) {\n\t\t\t\tif (!data->stop || mrq->sbc) {\n\t\t\t\t\tif (mrq->sbc && data->stop)\n\t\t\t\t\t\tdata->stop->error = 0;\n\t\t\t\t\tdw_mci_request_end(host, mrq);\n\t\t\t\t\tgoto unlock;\n\t\t\t\t}\n\n\t\t\t\t/* stop command for open-ended transfer*/\n\t\t\t\tif (data->stop)\n\t\t\t\t\tsend_stop_abort(host, data);\n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * If we don't have a command complete now we'll\n\t\t\t\t * never get one since we just reset everything;\n\t\t\t\t * better end the request.\n\t\t\t\t *\n\t\t\t\t * If we do have a command complete we'll fall\n\t\t\t\t * through to the SENDING_STOP command and\n\t\t\t\t * everything will be peachy keen.\n\t\t\t\t */\n\t\t\t\tif (!test_bit(EVENT_CMD_COMPLETE,\n\t\t\t\t\t &host->pending_events)) {\n\t\t\t\t\thost->cmd = NULL;\n\t\t\t\t\tdw_mci_request_end(host, mrq);\n\t\t\t\t\tgoto unlock;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * If err has non-zero,\n\t\t\t * stop-abort command has been already issued.\n\t\t\t */\n\t\t\tprev_state = state = STATE_SENDING_STOP;\n\n\t\t\t/* fall through */\n\n\t\tcase STATE_SENDING_STOP:\n\t\t\tif (!dw_mci_clear_pending_cmd_complete(host))\n\t\t\t\tbreak;\n\n\t\t\t/* CMD error in data command */\n\t\t\tif (mrq->cmd->error && mrq->data)\n\t\t\t\tdw_mci_reset(host);\n\n\t\t\thost->cmd = NULL;\n\t\t\thost->data = NULL;\n\n\t\t\tif (!mrq->sbc && mrq->stop)\n\t\t\t\tdw_mci_command_complete(host, mrq->stop);\n\t\t\telse\n\t\t\t\thost->cmd_status = 0;\n\n\t\t\tdw_mci_request_end(host, mrq);\n\t\t\tgoto unlock;\n\n\t\tcase STATE_DATA_ERROR:\n\t\t\tif (!test_and_clear_bit(EVENT_XFER_COMPLETE,\n\t\t\t\t\t\t&host->pending_events))\n\t\t\t\tbreak;\n\n\t\t\tstate = STATE_DATA_BUSY;\n\t\t\tbreak;\n\t\t}\n\t} while (state != prev_state);\n\n\thost->state = state;\nunlock:\n\tspin_unlock(&host->lock);\n\n}\n\n/* push final bytes to part_buf, only use during push */\nstatic void dw_mci_set_part_bytes(struct dw_mci *host, void *buf, int cnt)\n{\n\tmemcpy((void *)&host->part_buf, buf, cnt);\n\thost->part_buf_count = cnt;\n}\n\n/* append bytes to part_buf, only use during push */\nstatic int dw_mci_push_part_bytes(struct dw_mci *host, void *buf, int cnt)\n{\n\tcnt = min(cnt, (1 << host->data_shift) - host->part_buf_count);\n\tmemcpy((void *)&host->part_buf + host->part_buf_count, buf, cnt);\n\thost->part_buf_count += cnt;\n\treturn cnt;\n}\n\n/* pull first bytes from part_buf, only use during pull */\nstatic int dw_mci_pull_part_bytes(struct dw_mci *host, void *buf, int cnt)\n{\n\tcnt = min_t(int, cnt, host->part_buf_count);\n\tif (cnt) {\n\t\tmemcpy(buf, (void *)&host->part_buf + host->part_buf_start,\n\t\t cnt);\n\t\thost->part_buf_count -= cnt;\n\t\thost->part_buf_start += cnt;\n\t}\n\treturn cnt;\n}\n\n/* pull final bytes from the part_buf, assuming it's just been filled */\nstatic void dw_mci_pull_final_bytes(struct dw_mci *host, void *buf, int cnt)\n{\n\tmemcpy(buf, &host->part_buf, cnt);\n\thost->part_buf_start = cnt;\n\thost->part_buf_count = (1 << host->data_shift) - cnt;\n}\n\nstatic void dw_mci_push_data16(struct dw_mci *host, void *buf, int cnt)\n{\n\tstruct mmc_data *data = host->data;\n\tint init_cnt = cnt;\n\n\t/* try and push anything in the part_buf */\n\tif (unlikely(host->part_buf_count)) {\n\t\tint len = dw_mci_push_part_bytes(host, buf, cnt);\n\n\t\tbuf += len;\n\t\tcnt -= len;\n\t\tif (host->part_buf_count == 2) {\n\t\t\tmci_fifo_writew(host->fifo_reg, host->part_buf16);\n\t\t\thost->part_buf_count = 0;\n\t\t}\n\t}\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x1)) {\n\t\twhile (cnt >= 2) {\n\t\t\tu16 aligned_buf[64];\n\t\t\tint len = min(cnt & -2, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 1;\n\t\t\tint i;\n\t\t\t/* memcpy from input buffer into aligned buffer */\n\t\t\tmemcpy(aligned_buf, buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t\t/* push data from aligned buffer into fifo */\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\tmci_fifo_writew(host->fifo_reg, aligned_buf[i]);\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu16 *pdata = buf;\n\n\t\tfor (; cnt >= 2; cnt -= 2)\n\t\t\tmci_fifo_writew(host->fifo_reg, *pdata++);\n\t\tbuf = pdata;\n\t}\n\t/* put anything remaining in the part_buf */\n\tif (cnt) {\n\t\tdw_mci_set_part_bytes(host, buf, cnt);\n\t\t /* Push data if we have reached the expected data length */\n\t\tif ((data->bytes_xfered + init_cnt) ==\n\t\t (data->blksz * data->blocks))\n\t\t\tmci_fifo_writew(host->fifo_reg, host->part_buf16);\n\t}\n}\n\nstatic void dw_mci_pull_data16(struct dw_mci *host, void *buf, int cnt)\n{\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x1)) {\n\t\twhile (cnt >= 2) {\n\t\t\t/* pull data from fifo into aligned buffer */\n\t\t\tu16 aligned_buf[64];\n\t\t\tint len = min(cnt & -2, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 1;\n\t\t\tint i;\n\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\taligned_buf[i] = mci_fifo_readw(host->fifo_reg);\n\t\t\t/* memcpy from aligned buffer into output buffer */\n\t\t\tmemcpy(buf, aligned_buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu16 *pdata = buf;\n\n\t\tfor (; cnt >= 2; cnt -= 2)\n\t\t\t*pdata++ = mci_fifo_readw(host->fifo_reg);\n\t\tbuf = pdata;\n\t}\n\tif (cnt) {\n\t\thost->part_buf16 = mci_fifo_readw(host->fifo_reg);\n\t\tdw_mci_pull_final_bytes(host, buf, cnt);\n\t}\n}\n\nstatic void dw_mci_push_data32(struct dw_mci *host, void *buf, int cnt)\n{\n\tstruct mmc_data *data = host->data;\n\tint init_cnt = cnt;\n\n\t/* try and push anything in the part_buf */\n\tif (unlikely(host->part_buf_count)) {\n\t\tint len = dw_mci_push_part_bytes(host, buf, cnt);\n\n\t\tbuf += len;\n\t\tcnt -= len;\n\t\tif (host->part_buf_count == 4) {\n\t\t\tmci_fifo_writel(host->fifo_reg,\thost->part_buf32);\n\t\t\thost->part_buf_count = 0;\n\t\t}\n\t}\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x3)) {\n\t\twhile (cnt >= 4) {\n\t\t\tu32 aligned_buf[32];\n\t\t\tint len = min(cnt & -4, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 2;\n\t\t\tint i;\n\t\t\t/* memcpy from input buffer into aligned buffer */\n\t\t\tmemcpy(aligned_buf, buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t\t/* push data from aligned buffer into fifo */\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\tmci_fifo_writel(host->fifo_reg,\taligned_buf[i]);\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu32 *pdata = buf;\n\n\t\tfor (; cnt >= 4; cnt -= 4)\n\t\t\tmci_fifo_writel(host->fifo_reg, *pdata++);\n\t\tbuf = pdata;\n\t}\n\t/* put anything remaining in the part_buf */\n\tif (cnt) {\n\t\tdw_mci_set_part_bytes(host, buf, cnt);\n\t\t /* Push data if we have reached the expected data length */\n\t\tif ((data->bytes_xfered + init_cnt) ==\n\t\t (data->blksz * data->blocks))\n\t\t\tmci_fifo_writel(host->fifo_reg, host->part_buf32);\n\t}\n}\n\nstatic void dw_mci_pull_data32(struct dw_mci *host, void *buf, int cnt)\n{\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x3)) {\n\t\twhile (cnt >= 4) {\n\t\t\t/* pull data from fifo into aligned buffer */\n\t\t\tu32 aligned_buf[32];\n\t\t\tint len = min(cnt & -4, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 2;\n\t\t\tint i;\n\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\taligned_buf[i] = mci_fifo_readl(host->fifo_reg);\n\t\t\t/* memcpy from aligned buffer into output buffer */\n\t\t\tmemcpy(buf, aligned_buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu32 *pdata = buf;\n\n\t\tfor (; cnt >= 4; cnt -= 4)\n\t\t\t*pdata++ = mci_fifo_readl(host->fifo_reg);\n\t\tbuf = pdata;\n\t}\n\tif (cnt) {\n\t\thost->part_buf32 = mci_fifo_readl(host->fifo_reg);\n\t\tdw_mci_pull_final_bytes(host, buf, cnt);\n\t}\n}\n\nstatic void dw_mci_push_data64(struct dw_mci *host, void *buf, int cnt)\n{\n\tstruct mmc_data *data = host->data;\n\tint init_cnt = cnt;\n\n\t/* try and push anything in the part_buf */\n\tif (unlikely(host->part_buf_count)) {\n\t\tint len = dw_mci_push_part_bytes(host, buf, cnt);\n\n\t\tbuf += len;\n\t\tcnt -= len;\n\n\t\tif (host->part_buf_count == 8) {\n\t\t\tmci_fifo_writeq(host->fifo_reg,\thost->part_buf);\n\t\t\thost->part_buf_count = 0;\n\t\t}\n\t}\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x7)) {\n\t\twhile (cnt >= 8) {\n\t\t\tu64 aligned_buf[16];\n\t\t\tint len = min(cnt & -8, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 3;\n\t\t\tint i;\n\t\t\t/* memcpy from input buffer into aligned buffer */\n\t\t\tmemcpy(aligned_buf, buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t\t/* push data from aligned buffer into fifo */\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\tmci_fifo_writeq(host->fifo_reg,\taligned_buf[i]);\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu64 *pdata = buf;\n\n\t\tfor (; cnt >= 8; cnt -= 8)\n\t\t\tmci_fifo_writeq(host->fifo_reg, *pdata++);\n\t\tbuf = pdata;\n\t}\n\t/* put anything remaining in the part_buf */\n\tif (cnt) {\n\t\tdw_mci_set_part_bytes(host, buf, cnt);\n\t\t/* Push data if we have reached the expected data length */\n\t\tif ((data->bytes_xfered + init_cnt) ==\n\t\t (data->blksz * data->blocks))\n\t\t\tmci_fifo_writeq(host->fifo_reg, host->part_buf);\n\t}\n}\n\nstatic void dw_mci_pull_data64(struct dw_mci *host, void *buf, int cnt)\n{\n#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS\n\tif (unlikely((unsigned long)buf & 0x7)) {\n\t\twhile (cnt >= 8) {\n\t\t\t/* pull data from fifo into aligned buffer */\n\t\t\tu64 aligned_buf[16];\n\t\t\tint len = min(cnt & -8, (int)sizeof(aligned_buf));\n\t\t\tint items = len >> 3;\n\t\t\tint i;\n\n\t\t\tfor (i = 0; i < items; ++i)\n\t\t\t\taligned_buf[i] = mci_fifo_readq(host->fifo_reg);\n\n\t\t\t/* memcpy from aligned buffer into output buffer */\n\t\t\tmemcpy(buf, aligned_buf, len);\n\t\t\tbuf += len;\n\t\t\tcnt -= len;\n\t\t}\n\t} else\n#endif\n\t{\n\t\tu64 *pdata = buf;\n\n\t\tfor (; cnt >= 8; cnt -= 8)\n\t\t\t*pdata++ = mci_fifo_readq(host->fifo_reg);\n\t\tbuf = pdata;\n\t}\n\tif (cnt) {\n\t\thost->part_buf = mci_fifo_readq(host->fifo_reg);\n\t\tdw_mci_pull_final_bytes(host, buf, cnt);\n\t}\n}\n\nstatic void dw_mci_pull_data(struct dw_mci *host, void *buf, int cnt)\n{\n\tint len;\n\n\t/* get remaining partial bytes */\n\tlen = dw_mci_pull_part_bytes(host, buf, cnt);\n\tif (unlikely(len == cnt))\n\t\treturn;\n\tbuf += len;\n\tcnt -= len;\n\n\t/* get the rest of the data */\n\thost->pull_data(host, buf, cnt);\n}\n\nstatic void dw_mci_read_data_pio(struct dw_mci *host, bool dto)\n{\n\tstruct sg_mapping_iter *sg_miter = &host->sg_miter;\n\tvoid *buf;\n\tunsigned int offset;\n\tstruct mmc_data\t*data = host->data;\n\tint shift = host->data_shift;\n\tu32 status;\n\tunsigned int len;\n\tunsigned int remain, fcnt;\n\n\tdo {\n\t\tif (!sg_miter_next(sg_miter))\n\t\t\tgoto done;\n\n\t\thost->sg = sg_miter->piter.sg;\n\t\tbuf = sg_miter->addr;\n\t\tremain = sg_miter->length;\n\t\toffset = 0;\n\n\t\tdo {\n\t\t\tfcnt = (SDMMC_GET_FCNT(mci_readl(host, STATUS))\n\t\t\t\t\t<< shift) + host->part_buf_count;\n\t\t\tlen = min(remain, fcnt);\n\t\t\tif (!len)\n\t\t\t\tbreak;\n\t\t\tdw_mci_pull_data(host, (void *)(buf + offset), len);\n\t\t\tdata->bytes_xfered += len;\n\t\t\toffset += len;\n\t\t\tremain -= len;\n\t\t} while (remain);\n\n\t\tsg_miter->consumed = offset;\n\t\tstatus = mci_readl(host, MINTSTS);\n\t\tmci_writel(host, RINTSTS, SDMMC_INT_RXDR);\n\t/* if the RXDR is ready read again */\n\t} while ((status & SDMMC_INT_RXDR) ||\n\t\t (dto && SDMMC_GET_FCNT(mci_readl(host, STATUS))));\n\n\tif (!remain) {\n\t\tif (!sg_miter_next(sg_miter))\n\t\t\tgoto done;\n\t\tsg_miter->consumed = 0;\n\t}\n\tsg_miter_stop(sg_miter);\n\treturn;\n\ndone:\n\tsg_miter_stop(sg_miter);\n\thost->sg = NULL;\n\tsmp_wmb(); /* drain writebuffer */\n\tset_bit(EVENT_XFER_COMPLETE, &host->pending_events);\n}\n\nstatic void dw_mci_write_data_pio(struct dw_mci *host)\n{\n\tstruct sg_mapping_iter *sg_miter = &host->sg_miter;\n\tvoid *buf;\n\tunsigned int offset;\n\tstruct mmc_data\t*data = host->data;\n\tint shift = host->data_shift;\n\tu32 status;\n\tunsigned int len;\n\tunsigned int fifo_depth = host->fifo_depth;\n\tunsigned int remain, fcnt;\n\n\tdo {\n\t\tif (!sg_miter_next(sg_miter))\n\t\t\tgoto done;\n\n\t\thost->sg = sg_miter->piter.sg;\n\t\tbuf = sg_miter->addr;\n\t\tremain = sg_miter->length;\n\t\toffset = 0;\n\n\t\tdo {\n\t\t\tfcnt = ((fifo_depth -\n\t\t\t\t SDMMC_GET_FCNT(mci_readl(host, STATUS)))\n\t\t\t\t\t<< shift) - host->part_buf_count;\n\t\t\tlen = min(remain, fcnt);\n\t\t\tif (!len)\n\t\t\t\tbreak;\n\t\t\thost->push_data(host, (void *)(buf + offset), len);\n\t\t\tdata->bytes_xfered += len;\n\t\t\toffset += len;\n\t\t\tremain -= len;\n\t\t} while (remain);\n\n\t\tsg_miter->consumed = offset;\n\t\tstatus = mci_readl(host, MINTSTS);\n\t\tmci_writel(host, RINTSTS, SDMMC_INT_TXDR);\n\t} while (status & SDMMC_INT_TXDR); /* if TXDR write again */\n\n\tif (!remain) {\n\t\tif (!sg_miter_next(sg_miter))\n\t\t\tgoto done;\n\t\tsg_miter->consumed = 0;\n\t}\n\tsg_miter_stop(sg_miter);\n\treturn;\n\ndone:\n\tsg_miter_stop(sg_miter);\n\thost->sg = NULL;\n\tsmp_wmb(); /* drain writebuffer */\n\tset_bit(EVENT_XFER_COMPLETE, &host->pending_events);\n}\n\nstatic void dw_mci_cmd_interrupt(struct dw_mci *host, u32 status)\n{\n\tdel_timer(&host->cto_timer);\n\n\tif (!host->cmd_status)\n\t\thost->cmd_status = status;\n\n\tsmp_wmb(); /* drain writebuffer */\n\n\tset_bit(EVENT_CMD_COMPLETE, &host->pending_events);\n\ttasklet_schedule(&host->tasklet);\n}\n\nstatic void dw_mci_handle_cd(struct dw_mci *host)\n{\n\tstruct dw_mci_slot *slot = host->slot;\n\n\tif (slot->mmc->ops->card_event)\n\t\tslot->mmc->ops->card_event(slot->mmc);\n\tmmc_detect_change(slot->mmc,\n\t\tmsecs_to_jiffies(host->pdata->detect_delay_ms));\n}\n\nstatic irqreturn_t dw_mci_interrupt(int irq, void *dev_id)\n{\n\tstruct dw_mci *host = dev_id;\n\tu32 pending;\n\tstruct dw_mci_slot *slot = host->slot;\n\tunsigned long irqflags;\n\n\tpending = mci_readl(host, MINTSTS); /* read-only mask reg */\n\n\tif (pending) {\n\t\t/* Check volt switch first, since it can look like an error */\n\t\tif ((host->state == STATE_SENDING_CMD11) &&\n\t\t (pending & SDMMC_INT_VOLT_SWITCH)) {\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_VOLT_SWITCH);\n\t\t\tpending &= ~SDMMC_INT_VOLT_SWITCH;\n\n\t\t\t/*\n\t\t\t * Hold the lock; we know cmd11_timer can't be kicked\n\t\t\t * off after the lock is released, so safe to delete.\n\t\t\t */\n\t\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\t\t\tdw_mci_cmd_interrupt(host, pending);\n\t\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\n\t\t\tdel_timer(&host->cmd11_timer);\n\t\t}\n\n\t\tif (pending & DW_MCI_CMD_ERROR_FLAGS) {\n\t\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t\t\tdel_timer(&host->cto_timer);\n\t\t\tmci_writel(host, RINTSTS, DW_MCI_CMD_ERROR_FLAGS);\n\t\t\thost->cmd_status = pending;\n\t\t\tsmp_wmb(); /* drain writebuffer */\n\t\t\tset_bit(EVENT_CMD_COMPLETE, &host->pending_events);\n\n\t\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\t\t}\n\n\t\tif (pending & DW_MCI_DATA_ERROR_FLAGS) {\n\t\t\t/* if there is an error report DATA_ERROR */\n\t\t\tmci_writel(host, RINTSTS, DW_MCI_DATA_ERROR_FLAGS);\n\t\t\thost->data_status = pending;\n\t\t\tsmp_wmb(); /* drain writebuffer */\n\t\t\tset_bit(EVENT_DATA_ERROR, &host->pending_events);\n\t\t\ttasklet_schedule(&host->tasklet);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_DATA_OVER) {\n\t\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t\t\tdel_timer(&host->dto_timer);\n\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_DATA_OVER);\n\t\t\tif (!host->data_status)\n\t\t\t\thost->data_status = pending;\n\t\t\tsmp_wmb(); /* drain writebuffer */\n\t\t\tif (host->dir_status == DW_MCI_RECV_STATUS) {\n\t\t\t\tif (host->sg != NULL)\n\t\t\t\t\tdw_mci_read_data_pio(host, true);\n\t\t\t}\n\t\t\tset_bit(EVENT_DATA_COMPLETE, &host->pending_events);\n\t\t\ttasklet_schedule(&host->tasklet);\n\n\t\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_RXDR) {\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_RXDR);\n\t\t\tif (host->dir_status == DW_MCI_RECV_STATUS && host->sg)\n\t\t\t\tdw_mci_read_data_pio(host, false);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_TXDR) {\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_TXDR);\n\t\t\tif (host->dir_status == DW_MCI_SEND_STATUS && host->sg)\n\t\t\t\tdw_mci_write_data_pio(host);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_CMD_DONE) {\n\t\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_CMD_DONE);\n\t\t\tdw_mci_cmd_interrupt(host, pending);\n\n\t\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_CD) {\n\t\t\tmci_writel(host, RINTSTS, SDMMC_INT_CD);\n\t\t\tdw_mci_handle_cd(host);\n\t\t}\n\n\t\tif (pending & SDMMC_INT_SDIO(slot->sdio_id)) {\n\t\t\tmci_writel(host, RINTSTS,\n\t\t\t\t SDMMC_INT_SDIO(slot->sdio_id));\n\t\t\t__dw_mci_enable_sdio_irq(slot, 0);\n\t\t\tsdio_signal_irq(slot->mmc);\n\t\t}\n\n\t}\n\n\tif (host->use_dma != TRANS_MODE_IDMAC)\n\t\treturn IRQ_HANDLED;\n\n\t/* Handle IDMA interrupts */\n\tif (host->dma_64bit_address == 1) {\n\t\tpending = mci_readl(host, IDSTS64);\n\t\tif (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) {\n\t\t\tmci_writel(host, IDSTS64, SDMMC_IDMAC_INT_TI |\n\t\t\t\t\t\t\tSDMMC_IDMAC_INT_RI);\n\t\t\tmci_writel(host, IDSTS64, SDMMC_IDMAC_INT_NI);\n\t\t\tif (!test_bit(EVENT_DATA_ERROR, &host->pending_events))\n\t\t\t\thost->dma_ops->complete((void *)host);\n\t\t}\n\t} else {\n\t\tpending = mci_readl(host, IDSTS);\n\t\tif (pending & (SDMMC_IDMAC_INT_TI | SDMMC_IDMAC_INT_RI)) {\n\t\t\tmci_writel(host, IDSTS, SDMMC_IDMAC_INT_TI |\n\t\t\t\t\t\t\tSDMMC_IDMAC_INT_RI);\n\t\t\tmci_writel(host, IDSTS, SDMMC_IDMAC_INT_NI);\n\t\t\tif (!test_bit(EVENT_DATA_ERROR, &host->pending_events))\n\t\t\t\thost->dma_ops->complete((void *)host);\n\t\t}\n\t}\n\n\treturn IRQ_HANDLED;\n}\n\nstatic int dw_mci_init_slot_caps(struct dw_mci_slot *slot)\n{\n\tstruct dw_mci *host = slot->host;\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\tstruct mmc_host *mmc = slot->mmc;\n\tint ctrl_id;\n\n\tif (host->pdata->caps)\n\t\tmmc->caps = host->pdata->caps;\n\n\t/*\n\t * Support MMC_CAP_ERASE by default.\n\t * It needs to use trim/discard/erase commands.\n\t */\n\tmmc->caps |= MMC_CAP_ERASE;\n\n\tif (host->pdata->pm_caps)\n\t\tmmc->pm_caps = host->pdata->pm_caps;\n\n\tif (host->dev->of_node) {\n\t\tctrl_id = of_alias_get_id(host->dev->of_node, \"mshc\");\n\t\tif (ctrl_id < 0)\n\t\t\tctrl_id = 0;\n\t} else {\n\t\tctrl_id = to_platform_device(host->dev)->id;\n\t}\n\n\tif (drv_data && drv_data->caps) {\n\t\tif (ctrl_id >= drv_data->num_caps) {\n\t\t\tdev_err(host->dev, \"invalid controller id %d\\n\",\n\t\t\t\tctrl_id);\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tmmc->caps |= drv_data->caps[ctrl_id];\n\t}\n\n\tif (host->pdata->caps2)\n\t\tmmc->caps2 = host->pdata->caps2;\n\n\tmmc->f_min = DW_MCI_FREQ_MIN;\n\tif (!mmc->f_max)\n\t\tmmc->f_max = DW_MCI_FREQ_MAX;\n\n\t/* Process SDIO IRQs through the sdio_irq_work. */\n\tif (mmc->caps & MMC_CAP_SDIO_IRQ)\n\t\tmmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;\n\n\treturn 0;\n}\n\nstatic int dw_mci_init_slot(struct dw_mci *host)\n{\n\tstruct mmc_host *mmc;\n\tstruct dw_mci_slot *slot;\n\tint ret;\n\n\tmmc = mmc_alloc_host(sizeof(struct dw_mci_slot), host->dev);\n\tif (!mmc)\n\t\treturn -ENOMEM;\n\n\tslot = mmc_priv(mmc);\n\tslot->id = 0;\n\tslot->sdio_id = host->sdio_id0 + slot->id;\n\tslot->mmc = mmc;\n\tslot->host = host;\n\thost->slot = slot;\n\n\tmmc->ops = &dw_mci_ops;\n\n\t/*if there are external regulators, get them*/\n\tret = mmc_regulator_get_supply(mmc);\n\tif (ret)\n\t\tgoto err_host_allocated;\n\n\tif (!mmc->ocr_avail)\n\t\tmmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;\n\n\tret = mmc_of_parse(mmc);\n\tif (ret)\n\t\tgoto err_host_allocated;\n\n\tret = dw_mci_init_slot_caps(slot);\n\tif (ret)\n\t\tgoto err_host_allocated;\n\n\t/* Useful defaults if platform data is unset. */\n\tif (host->use_dma == TRANS_MODE_IDMAC) {\n\t\tmmc->max_segs = host->ring_size;\n\t\tmmc->max_blk_size = 65535;\n\t\tmmc->max_seg_size = 0x1000;\n\t\tmmc->max_req_size = mmc->max_seg_size * host->ring_size;\n\t\tmmc->max_blk_count = mmc->max_req_size / 512;\n\t} else if (host->use_dma == TRANS_MODE_EDMAC) {\n\t\tmmc->max_segs = 64;\n\t\tmmc->max_blk_size = 65535;\n\t\tmmc->max_blk_count = 65535;\n\t\tmmc->max_req_size =\n\t\t\t\tmmc->max_blk_size * mmc->max_blk_count;\n\t\tmmc->max_seg_size = mmc->max_req_size;\n\t} else {\n\t\t/* TRANS_MODE_PIO */\n\t\tmmc->max_segs = 64;\n\t\tmmc->max_blk_size = 65535; /* BLKSIZ is 16 bits */\n\t\tmmc->max_blk_count = 512;\n\t\tmmc->max_req_size = mmc->max_blk_size *\n\t\t\t\t mmc->max_blk_count;\n\t\tmmc->max_seg_size = mmc->max_req_size;\n\t}\n\n\tdw_mci_get_cd(mmc);\n\n\tret = mmc_add_host(mmc);\n\tif (ret)\n\t\tgoto err_host_allocated;\n\n#if defined(CONFIG_DEBUG_FS)\n\tdw_mci_init_debugfs(slot);\n#endif\n\n\treturn 0;\n\nerr_host_allocated:\n\tmmc_free_host(mmc);\n\treturn ret;\n}\n\nstatic void dw_mci_cleanup_slot(struct dw_mci_slot *slot)\n{\n\t/* Debugfs stuff is cleaned up by mmc core */\n\tmmc_remove_host(slot->mmc);\n\tslot->host->slot = NULL;\n\tmmc_free_host(slot->mmc);\n}\n\nstatic void dw_mci_init_dma(struct dw_mci *host)\n{\n\tint addr_config;\n\tstruct device *dev = host->dev;\n\n\t/*\n\t* Check tansfer mode from HCON[17:16]\n\t* Clear the ambiguous description of dw_mmc databook:\n\t* 2b'00: No DMA Interface -> Actually means using Internal DMA block\n\t* 2b'01: DesignWare DMA Interface -> Synopsys DW-DMA block\n\t* 2b'10: Generic DMA Interface -> non-Synopsys generic DMA block\n\t* 2b'11: Non DW DMA Interface -> pio only\n\t* Compared to DesignWare DMA Interface, Generic DMA Interface has a\n\t* simpler request/acknowledge handshake mechanism and both of them\n\t* are regarded as external dma master for dw_mmc.\n\t*/\n\thost->use_dma = SDMMC_GET_TRANS_MODE(mci_readl(host, HCON));\n\tif (host->use_dma == DMA_INTERFACE_IDMA) {\n\t\thost->use_dma = TRANS_MODE_IDMAC;\n\t} else if (host->use_dma == DMA_INTERFACE_DWDMA ||\n\t\t host->use_dma == DMA_INTERFACE_GDMA) {\n\t\thost->use_dma = TRANS_MODE_EDMAC;\n\t} else {\n\t\tgoto no_dma;\n\t}\n\n\t/* Determine which DMA interface to use */\n\tif (host->use_dma == TRANS_MODE_IDMAC) {\n\t\t/*\n\t\t* Check ADDR_CONFIG bit in HCON to find\n\t\t* IDMAC address bus width\n\t\t*/\n\t\taddr_config = SDMMC_GET_ADDR_CONFIG(mci_readl(host, HCON));\n\n\t\tif (addr_config == 1) {\n\t\t\t/* host supports IDMAC in 64-bit address mode */\n\t\t\thost->dma_64bit_address = 1;\n\t\t\tdev_info(host->dev,\n\t\t\t\t \"IDMAC supports 64-bit address mode.\\n\");\n\t\t\tif (!dma_set_mask(host->dev, DMA_BIT_MASK(64)))\n\t\t\t\tdma_set_coherent_mask(host->dev,\n\t\t\t\t\t\t DMA_BIT_MASK(64));\n\t\t} else {\n\t\t\t/* host supports IDMAC in 32-bit address mode */\n\t\t\thost->dma_64bit_address = 0;\n\t\t\tdev_info(host->dev,\n\t\t\t\t \"IDMAC supports 32-bit address mode.\\n\");\n\t\t}\n\n\t\t/* Alloc memory for sg translation */\n\t\thost->sg_cpu = dmam_alloc_coherent(host->dev,\n\t\t\t\t\t\t DESC_RING_BUF_SZ,\n\t\t\t\t\t\t &host->sg_dma, GFP_KERNEL);\n\t\tif (!host->sg_cpu) {\n\t\t\tdev_err(host->dev,\n\t\t\t\t\"%s: could not alloc DMA memory\\n\",\n\t\t\t\t__func__);\n\t\t\tgoto no_dma;\n\t\t}\n\n\t\thost->dma_ops = &dw_mci_idmac_ops;\n\t\tdev_info(host->dev, \"Using internal DMA controller.\\n\");\n\t} else {\n\t\t/* TRANS_MODE_EDMAC: check dma bindings again */\n\t\tif ((device_property_read_string_array(dev, \"dma-names\",\n\t\t\t\t\t\t NULL, 0) < 0) ||\n\t\t !device_property_present(dev, \"dmas\")) {\n\t\t\tgoto no_dma;\n\t\t}\n\t\thost->dma_ops = &dw_mci_edmac_ops;\n\t\tdev_info(host->dev, \"Using external DMA controller.\\n\");\n\t}\n\n\tif (host->dma_ops->init && host->dma_ops->start &&\n\t host->dma_ops->stop && host->dma_ops->cleanup) {\n\t\tif (host->dma_ops->init(host)) {\n\t\t\tdev_err(host->dev, \"%s: Unable to initialize DMA Controller.\\n\",\n\t\t\t\t__func__);\n\t\t\tgoto no_dma;\n\t\t}\n\t} else {\n\t\tdev_err(host->dev, \"DMA initialization not found.\\n\");\n\t\tgoto no_dma;\n\t}\n\n\treturn;\n\nno_dma:\n\tdev_info(host->dev, \"Using PIO mode.\\n\");\n\thost->use_dma = TRANS_MODE_PIO;\n}\n\nstatic void dw_mci_cmd11_timer(struct timer_list *t)\n{\n\tstruct dw_mci *host = from_timer(host, t, cmd11_timer);\n\n\tif (host->state != STATE_SENDING_CMD11) {\n\t\tdev_warn(host->dev, \"Unexpected CMD11 timeout\\n\");\n\t\treturn;\n\t}\n\n\thost->cmd_status = SDMMC_INT_RTO;\n\tset_bit(EVENT_CMD_COMPLETE, &host->pending_events);\n\ttasklet_schedule(&host->tasklet);\n}\n\nstatic void dw_mci_cto_timer(struct timer_list *t)\n{\n\tstruct dw_mci *host = from_timer(host, t, cto_timer);\n\tunsigned long irqflags;\n\tu32 pending;\n\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t/*\n\t * If somehow we have very bad interrupt latency it's remotely possible\n\t * that the timer could fire while the interrupt is still pending or\n\t * while the interrupt is midway through running. Let's be paranoid\n\t * and detect those two cases. Note that this is paranoia is somewhat\n\t * justified because in this function we don't actually cancel the\n\t * pending command in the controller--we just assume it will never come.\n\t */\n\tpending = mci_readl(host, MINTSTS); /* read-only mask reg */\n\tif (pending & (DW_MCI_CMD_ERROR_FLAGS | SDMMC_INT_CMD_DONE)) {\n\t\t/* The interrupt should fire; no need to act but we can warn */\n\t\tdev_warn(host->dev, \"Unexpected interrupt latency\\n\");\n\t\tgoto exit;\n\t}\n\tif (test_bit(EVENT_CMD_COMPLETE, &host->pending_events)) {\n\t\t/* Presumably interrupt handler couldn't delete the timer */\n\t\tdev_warn(host->dev, \"CTO timeout when already completed\\n\");\n\t\tgoto exit;\n\t}\n\n\t/*\n\t * Continued paranoia to make sure we're in the state we expect.\n\t * This paranoia isn't really justified but it seems good to be safe.\n\t */\n\tswitch (host->state) {\n\tcase STATE_SENDING_CMD11:\n\tcase STATE_SENDING_CMD:\n\tcase STATE_SENDING_STOP:\n\t\t/*\n\t\t * If CMD_DONE interrupt does NOT come in sending command\n\t\t * state, we should notify the driver to terminate current\n\t\t * transfer and report a command timeout to the core.\n\t\t */\n\t\thost->cmd_status = SDMMC_INT_RTO;\n\t\tset_bit(EVENT_CMD_COMPLETE, &host->pending_events);\n\t\ttasklet_schedule(&host->tasklet);\n\t\tbreak;\n\tdefault:\n\t\tdev_warn(host->dev, \"Unexpected command timeout, state %d\\n\",\n\t\t\t host->state);\n\t\tbreak;\n\t}\n\nexit:\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n}\n\nstatic void dw_mci_dto_timer(struct timer_list *t)\n{\n\tstruct dw_mci *host = from_timer(host, t, dto_timer);\n\tunsigned long irqflags;\n\tu32 pending;\n\n\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\n\t/*\n\t * The DTO timer is much longer than the CTO timer, so it's even less\n\t * likely that we'll these cases, but it pays to be paranoid.\n\t */\n\tpending = mci_readl(host, MINTSTS); /* read-only mask reg */\n\tif (pending & SDMMC_INT_DATA_OVER) {\n\t\t/* The interrupt should fire; no need to act but we can warn */\n\t\tdev_warn(host->dev, \"Unexpected data interrupt latency\\n\");\n\t\tgoto exit;\n\t}\n\tif (test_bit(EVENT_DATA_COMPLETE, &host->pending_events)) {\n\t\t/* Presumably interrupt handler couldn't delete the timer */\n\t\tdev_warn(host->dev, \"DTO timeout when already completed\\n\");\n\t\tgoto exit;\n\t}\n\n\t/*\n\t * Continued paranoia to make sure we're in the state we expect.\n\t * This paranoia isn't really justified but it seems good to be safe.\n\t */\n\tswitch (host->state) {\n\tcase STATE_SENDING_DATA:\n\tcase STATE_DATA_BUSY:\n\t\t/*\n\t\t * If DTO interrupt does NOT come in sending data state,\n\t\t * we should notify the driver to terminate current transfer\n\t\t * and report a data timeout to the core.\n\t\t */\n\t\thost->data_status = SDMMC_INT_DRTO;\n\t\tset_bit(EVENT_DATA_ERROR, &host->pending_events);\n\t\tset_bit(EVENT_DATA_COMPLETE, &host->pending_events);\n\t\ttasklet_schedule(&host->tasklet);\n\t\tbreak;\n\tdefault:\n\t\tdev_warn(host->dev, \"Unexpected data timeout, state %d\\n\",\n\t\t\t host->state);\n\t\tbreak;\n\t}\n\nexit:\n\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n}\n\n#ifdef CONFIG_OF\nstatic struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host)\n{\n\tstruct dw_mci_board *pdata;\n\tstruct device *dev = host->dev;\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\tint ret;\n\tu32 clock_frequency;\n\n\tpdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata)\n\t\treturn ERR_PTR(-ENOMEM);\n\n\t/* find reset controller when exist */\n\tpdata->rstc = devm_reset_control_get_optional_exclusive(dev, \"reset\");\n\tif (IS_ERR(pdata->rstc)) {\n\t\tif (PTR_ERR(pdata->rstc) == -EPROBE_DEFER)\n\t\t\treturn ERR_PTR(-EPROBE_DEFER);\n\t}\n\n\tif (device_property_read_u32(dev, \"fifo-depth\", &pdata->fifo_depth))\n\t\tdev_info(dev,\n\t\t\t \"fifo-depth property not found, using value of FIFOTH register as default\\n\");\n\n\tdevice_property_read_u32(dev, \"card-detect-delay\",\n\t\t\t\t &pdata->detect_delay_ms);\n\n\tdevice_property_read_u32(dev, \"data-addr\", &host->data_addr_override);\n\n\tif (device_property_present(dev, \"fifo-watermark-aligned\"))\n\t\thost->wm_aligned = true;\n\n\tif (!device_property_read_u32(dev, \"clock-frequency\", &clock_frequency))\n\t\tpdata->bus_hz = clock_frequency;\n\n\tif (drv_data && drv_data->parse_dt) {\n\t\tret = drv_data->parse_dt(host);\n\t\tif (ret)\n\t\t\treturn ERR_PTR(ret);\n\t}\n\n\treturn pdata;\n}\n\n#else /* CONFIG_OF */\nstatic struct dw_mci_board *dw_mci_parse_dt(struct dw_mci *host)\n{\n\treturn ERR_PTR(-EINVAL);\n}\n#endif /* CONFIG_OF */\n\nstatic void dw_mci_enable_cd(struct dw_mci *host)\n{\n\tunsigned long irqflags;\n\tu32 temp;\n\n\t/*\n\t * No need for CD if all slots have a non-error GPIO\n\t * as well as broken card detection is found.\n\t */\n\tif (host->slot->mmc->caps & MMC_CAP_NEEDS_POLL)\n\t\treturn;\n\n\tif (mmc_gpio_get_cd(host->slot->mmc) < 0) {\n\t\tspin_lock_irqsave(&host->irq_lock, irqflags);\n\t\ttemp = mci_readl(host, INTMASK);\n\t\ttemp |= SDMMC_INT_CD;\n\t\tmci_writel(host, INTMASK, temp);\n\t\tspin_unlock_irqrestore(&host->irq_lock, irqflags);\n\t}\n}\n\nint dw_mci_probe(struct dw_mci *host)\n{\n\tconst struct dw_mci_drv_data *drv_data = host->drv_data;\n\tint width, i, ret = 0;\n\tu32 fifo_size;\n\n\tif (!host->pdata) {\n\t\thost->pdata = dw_mci_parse_dt(host);\n\t\tif (PTR_ERR(host->pdata) == -EPROBE_DEFER) {\n\t\t\treturn -EPROBE_DEFER;\n\t\t} else if (IS_ERR(host->pdata)) {\n\t\t\tdev_err(host->dev, \"platform data not available\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t}\n\n\thost->biu_clk = devm_clk_get(host->dev, \"biu\");\n\tif (IS_ERR(host->biu_clk)) {\n\t\tdev_dbg(host->dev, \"biu clock not available\\n\");\n\t} else {\n\t\tret = clk_prepare_enable(host->biu_clk);\n\t\tif (ret) {\n\t\t\tdev_err(host->dev, \"failed to enable biu clock\\n\");\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\thost->ciu_clk = devm_clk_get(host->dev, \"ciu\");\n\tif (IS_ERR(host->ciu_clk)) {\n\t\tdev_dbg(host->dev, \"ciu clock not available\\n\");\n\t\thost->bus_hz = host->pdata->bus_hz;\n\t} else {\n\t\tret = clk_prepare_enable(host->ciu_clk);\n\t\tif (ret) {\n\t\t\tdev_err(host->dev, \"failed to enable ciu clock\\n\");\n\t\t\tgoto err_clk_biu;\n\t\t}\n\n\t\tif (host->pdata->bus_hz) {\n\t\t\tret = clk_set_rate(host->ciu_clk, host->pdata->bus_hz);\n\t\t\tif (ret)\n\t\t\t\tdev_warn(host->dev,\n\t\t\t\t\t \"Unable to set bus rate to %uHz\\n\",\n\t\t\t\t\t host->pdata->bus_hz);\n\t\t}\n\t\thost->bus_hz = clk_get_rate(host->ciu_clk);\n\t}\n\n\tif (!host->bus_hz) {\n\t\tdev_err(host->dev,\n\t\t\t\"Platform data must supply bus speed\\n\");\n\t\tret = -ENODEV;\n\t\tgoto err_clk_ciu;\n\t}\n\n\tif (!IS_ERR(host->pdata->rstc)) {\n\t\treset_control_assert(host->pdata->rstc);\n\t\tusleep_range(10, 50);\n\t\treset_control_deassert(host->pdata->rstc);\n\t}\n\n\tif (drv_data && drv_data->init) {\n\t\tret = drv_data->init(host);\n\t\tif (ret) {\n\t\t\tdev_err(host->dev,\n\t\t\t\t\"implementation specific init failed\\n\");\n\t\t\tgoto err_clk_ciu;\n\t\t}\n\t}\n\n\ttimer_setup(&host->cmd11_timer, dw_mci_cmd11_timer, 0);\n\ttimer_setup(&host->cto_timer, dw_mci_cto_timer, 0);\n\ttimer_setup(&host->dto_timer, dw_mci_dto_timer, 0);\n\n\tspin_lock_init(&host->lock);\n\tspin_lock_init(&host->irq_lock);\n\tINIT_LIST_HEAD(&host->queue);\n\n\t/*\n\t * Get the host data width - this assumes that HCON has been set with\n\t * the correct values.\n\t */\n\ti = SDMMC_GET_HDATA_WIDTH(mci_readl(host, HCON));\n\tif (!i) {\n\t\thost->push_data = dw_mci_push_data16;\n\t\thost->pull_data = dw_mci_pull_data16;\n\t\twidth = 16;\n\t\thost->data_shift = 1;\n\t} else if (i == 2) {\n\t\thost->push_data = dw_mci_push_data64;\n\t\thost->pull_data = dw_mci_pull_data64;\n\t\twidth = 64;\n\t\thost->data_shift = 3;\n\t} else {\n\t\t/* Check for a reserved value, and warn if it is */\n\t\tWARN((i != 1),\n\t\t \"HCON reports a reserved host data width!\\n\"\n\t\t \"Defaulting to 32-bit access.\\n\");\n\t\thost->push_data = dw_mci_push_data32;\n\t\thost->pull_data = dw_mci_pull_data32;\n\t\twidth = 32;\n\t\thost->data_shift = 2;\n\t}\n\n\t/* Reset all blocks */\n\tif (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) {\n\t\tret = -ENODEV;\n\t\tgoto err_clk_ciu;\n\t}\n\n\thost->dma_ops = host->pdata->dma_ops;\n\tdw_mci_init_dma(host);\n\n\t/* Clear the interrupts for the host controller */\n\tmci_writel(host, RINTSTS, 0xFFFFFFFF);\n\tmci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */\n\n\t/* Put in max timeout */\n\tmci_writel(host, TMOUT, 0xFFFFFFFF);\n\n\t/*\n\t * FIFO threshold settings RxMark = fifo_size / 2 - 1,\n\t * Tx Mark = fifo_size / 2 DMA Size = 8\n\t */\n\tif (!host->pdata->fifo_depth) {\n\t\t/*\n\t\t * Power-on value of RX_WMark is FIFO_DEPTH-1, but this may\n\t\t * have been overwritten by the bootloader, just like we're\n\t\t * about to do, so if you know the value for your hardware, you\n\t\t * should put it in the platform data.\n\t\t */\n\t\tfifo_size = mci_readl(host, FIFOTH);\n\t\tfifo_size = 1 + ((fifo_size >> 16) & 0xfff);\n\t} else {\n\t\tfifo_size = host->pdata->fifo_depth;\n\t}\n\thost->fifo_depth = fifo_size;\n\thost->fifoth_val =\n\t\tSDMMC_SET_FIFOTH(0x2, fifo_size / 2 - 1, fifo_size / 2);\n\tmci_writel(host, FIFOTH, host->fifoth_val);\n\n\t/* disable clock to CIU */\n\tmci_writel(host, CLKENA, 0);\n\tmci_writel(host, CLKSRC, 0);\n\n\t/*\n\t * In 2.40a spec, Data offset is changed.\n\t * Need to check the version-id and set data-offset for DATA register.\n\t */\n\thost->verid = SDMMC_GET_VERID(mci_readl(host, VERID));\n\tdev_info(host->dev, \"Version ID is %04x\\n\", host->verid);\n\n\tif (host->data_addr_override)\n\t\thost->fifo_reg = host->regs + host->data_addr_override;\n\telse if (host->verid < DW_MMC_240A)\n\t\thost->fifo_reg = host->regs + DATA_OFFSET;\n\telse\n\t\thost->fifo_reg = host->regs + DATA_240A_OFFSET;\n\n\ttasklet_init(&host->tasklet, dw_mci_tasklet_func, (unsigned long)host);\n\tret = devm_request_irq(host->dev, host->irq, dw_mci_interrupt,\n\t\t\t host->irq_flags, \"dw-mci\", host);\n\tif (ret)\n\t\tgoto err_dmaunmap;\n\n\t/*\n\t * Enable interrupts for command done, data over, data empty,\n\t * receive ready and error such as transmit, receive timeout, crc error\n\t */\n\tmci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER |\n\t\t SDMMC_INT_TXDR | SDMMC_INT_RXDR |\n\t\t DW_MCI_ERROR_FLAGS);\n\t/* Enable mci interrupt */\n\tmci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE);\n\n\tdev_info(host->dev,\n\t\t \"DW MMC controller at irq %d,%d bit host data width,%u deep fifo\\n\",\n\t\t host->irq, width, fifo_size);\n\n\t/* We need at least one slot to succeed */\n\tret = dw_mci_init_slot(host);\n\tif (ret) {\n\t\tdev_dbg(host->dev, \"slot %d init failed\\n\", i);\n\t\tgoto err_dmaunmap;\n\t}\n\n\t/* Now that slots are all setup, we can enable card detect */\n\tdw_mci_enable_cd(host);\n\n\treturn 0;\n\nerr_dmaunmap:\n\tif (host->use_dma && host->dma_ops->exit)\n\t\thost->dma_ops->exit(host);\n\n\tif (!IS_ERR(host->pdata->rstc))\n\t\treset_control_assert(host->pdata->rstc);\n\nerr_clk_ciu:\n\tclk_disable_unprepare(host->ciu_clk);\n\nerr_clk_biu:\n\tclk_disable_unprepare(host->biu_clk);\n\n\treturn ret;\n}\nEXPORT_SYMBOL(dw_mci_probe);\n\nvoid dw_mci_remove(struct dw_mci *host)\n{\n\tdev_dbg(host->dev, \"remove slot\\n\");\n\tif (host->slot)\n\t\tdw_mci_cleanup_slot(host->slot);\n\n\tmci_writel(host, RINTSTS, 0xFFFFFFFF);\n\tmci_writel(host, INTMASK, 0); /* disable all mmc interrupt first */\n\n\t/* disable clock to CIU */\n\tmci_writel(host, CLKENA, 0);\n\tmci_writel(host, CLKSRC, 0);\n\n\tif (host->use_dma && host->dma_ops->exit)\n\t\thost->dma_ops->exit(host);\n\n\tif (!IS_ERR(host->pdata->rstc))\n\t\treset_control_assert(host->pdata->rstc);\n\n\tclk_disable_unprepare(host->ciu_clk);\n\tclk_disable_unprepare(host->biu_clk);\n}\nEXPORT_SYMBOL(dw_mci_remove);\n\n\n\n#ifdef CONFIG_PM\nint dw_mci_runtime_suspend(struct device *dev)\n{\n\tstruct dw_mci *host = dev_get_drvdata(dev);\n\n\tif (host->use_dma && host->dma_ops->exit)\n\t\thost->dma_ops->exit(host);\n\n\tclk_disable_unprepare(host->ciu_clk);\n\n\tif (host->slot &&\n\t (mmc_can_gpio_cd(host->slot->mmc) ||\n\t !mmc_card_is_removable(host->slot->mmc)))\n\t\tclk_disable_unprepare(host->biu_clk);\n\n\treturn 0;\n}\nEXPORT_SYMBOL(dw_mci_runtime_suspend);\n\nint dw_mci_runtime_resume(struct device *dev)\n{\n\tint ret = 0;\n\tstruct dw_mci *host = dev_get_drvdata(dev);\n\n\tif (host->slot &&\n\t (mmc_can_gpio_cd(host->slot->mmc) ||\n\t !mmc_card_is_removable(host->slot->mmc))) {\n\t\tret = clk_prepare_enable(host->biu_clk);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tret = clk_prepare_enable(host->ciu_clk);\n\tif (ret)\n\t\tgoto err;\n\n\tif (!dw_mci_ctrl_reset(host, SDMMC_CTRL_ALL_RESET_FLAGS)) {\n\t\tclk_disable_unprepare(host->ciu_clk);\n\t\tret = -ENODEV;\n\t\tgoto err;\n\t}\n\n\tif (host->use_dma && host->dma_ops->init)\n\t\thost->dma_ops->init(host);\n\n\t/*\n\t * Restore the initial value at FIFOTH register\n\t * And Invalidate the prev_blksz with zero\n\t */\n\t mci_writel(host, FIFOTH, host->fifoth_val);\n\t host->prev_blksz = 0;\n\n\t/* Put in max timeout */\n\tmci_writel(host, TMOUT, 0xFFFFFFFF);\n\n\tmci_writel(host, RINTSTS, 0xFFFFFFFF);\n\tmci_writel(host, INTMASK, SDMMC_INT_CMD_DONE | SDMMC_INT_DATA_OVER |\n\t\t SDMMC_INT_TXDR | SDMMC_INT_RXDR |\n\t\t DW_MCI_ERROR_FLAGS);\n\tmci_writel(host, CTRL, SDMMC_CTRL_INT_ENABLE);\n\n\n\tif (host->slot->mmc->pm_flags & MMC_PM_KEEP_POWER)\n\t\tdw_mci_set_ios(host->slot->mmc, &host->slot->mmc->ios);\n\n\t/* Force setup bus to guarantee available clock output */\n\tdw_mci_setup_bus(host->slot, true);\n\n\t/* Now that slots are all setup, we can enable card detect */\n\tdw_mci_enable_cd(host);\n\n\treturn 0;\n\nerr:\n\tif (host->slot &&\n\t (mmc_can_gpio_cd(host->slot->mmc) ||\n\t !mmc_card_is_removable(host->slot->mmc)))\n\t\tclk_disable_unprepare(host->biu_clk);\n\n\treturn ret;\n}\nEXPORT_SYMBOL(dw_mci_runtime_resume);\n#endif /* CONFIG_PM */\n\nstatic int __init dw_mci_init(void)\n{\n\tpr_info(\"Synopsys Designware Multimedia Card Interface Driver\\n\");\n\treturn 0;\n}\n\nstatic void __exit dw_mci_exit(void)\n{\n}\n\nmodule_init(dw_mci_init);\nmodule_exit(dw_mci_exit);\n\nMODULE_DESCRIPTION(\"DW Multimedia Card Interface driver\");\nMODULE_AUTHOR(\"NXP Semiconductor VietNam\");\nMODULE_AUTHOR(\"Imagination Technologies Ltd\");\nMODULE_LICENSE(\"GPL v2\");\n"},"repo_name":{"kind":"string","value":"raumfeld/linux-am33xx"},"path":{"kind":"string","value":"drivers/mmc/host/dw_mmc.c"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":91646,"string":"91,646"}}},{"rowIdx":115086046,"cells":{"code":{"kind":"string","value":"\n * @license LICENSE.txt\n * \n * @package QuickBooks\n * @subpackage QBXML\n */\n\n/**\n * \n */\nrequire_once 'QuickBooks.php';\n\n/**\n * \n */\nrequire_once 'QuickBooks/QBXML/Schema/Object.php';\n\n/**\n * \n */\nclass QuickBooks_QBXML_Schema_Object_PaymentMethodQueryRq extends QuickBooks_QBXML_Schema_Object\n{\n\tprotected function &_qbxmlWrapper()\n\t{\n\t\tstatic $wrapper = '';\n\t\t\n\t\treturn $wrapper;\n\t}\n\t\n\tprotected function &_dataTypePaths()\n\t{\n\t\tstatic $paths = array (\n 'ListID' => 'IDTYPE',\n 'FullName' => 'STRTYPE',\n 'MaxReturned' => 'INTTYPE',\n 'ActiveStatus' => 'ENUMTYPE',\n 'FromModifiedDate' => 'DATETIMETYPE',\n 'ToModifiedDate' => 'DATETIMETYPE',\n 'NameFilter MatchCriterion' => 'ENUMTYPE',\n 'NameFilter Name' => 'STRTYPE',\n 'NameRangeFilter FromName' => 'STRTYPE',\n 'NameRangeFilter ToName' => 'STRTYPE',\n 'PaymentMethodType' => 'ENUMTYPE',\n 'IncludeRetElement' => 'STRTYPE',\n);\n\t\t\n\t\treturn $paths;\n\t}\n\t\n\tprotected function &_maxLengthPaths()\n\t{\n\t\tstatic $paths = array (\n 'ListID' => 0,\n 'FullName' => 0,\n 'MaxReturned' => 0,\n 'ActiveStatus' => 0,\n 'FromModifiedDate' => 0,\n 'ToModifiedDate' => 0,\n 'NameFilter MatchCriterion' => 0,\n 'NameFilter Name' => 0,\n 'NameRangeFilter FromName' => 0,\n 'NameRangeFilter ToName' => 0,\n 'PaymentMethodType' => 0,\n 'IncludeRetElement' => 50,\n);\n\t\t\n\t\treturn $paths;\n\t}\n\t\n\tprotected function &_isOptionalPaths()\n\t{\n\t\tstatic $paths = array (\n 'ListID' => false,\n 'FullName' => false,\n 'MaxReturned' => true,\n 'ActiveStatus' => true,\n 'FromModifiedDate' => true,\n 'ToModifiedDate' => true,\n 'NameFilter MatchCriterion' => false,\n 'NameFilter Name' => false,\n 'NameRangeFilter FromName' => true,\n 'NameRangeFilter ToName' => true,\n 'PaymentMethodType' => true,\n 'IncludeRetElement' => true,\n);\n\t}\n\t\n\tprotected function &_sinceVersionPaths()\n\t{\n\t\tstatic $paths = array (\n 'ListID' => 999.99,\n 'FullName' => 999.99,\n 'MaxReturned' => 0,\n 'ActiveStatus' => 999.99,\n 'FromModifiedDate' => 999.99,\n 'ToModifiedDate' => 999.99,\n 'NameFilter MatchCriterion' => 999.99,\n 'NameFilter Name' => 999.99,\n 'NameRangeFilter FromName' => 999.99,\n 'NameRangeFilter ToName' => 999.99,\n 'PaymentMethodType' => 7,\n 'IncludeRetElement' => 4,\n);\n\t\t\n\t\treturn $paths;\n\t}\n\t\n\tprotected function &_isRepeatablePaths()\n\t{\n\t\tstatic $paths = array (\n 'ListID' => true,\n 'FullName' => true,\n 'MaxReturned' => false,\n 'ActiveStatus' => false,\n 'FromModifiedDate' => false,\n 'ToModifiedDate' => false,\n 'NameFilter MatchCriterion' => false,\n 'NameFilter Name' => false,\n 'NameRangeFilter FromName' => false,\n 'NameRangeFilter ToName' => false,\n 'PaymentMethodType' => true,\n 'IncludeRetElement' => true,\n);\n\t\t\t\n\t\treturn $paths;\n\t}\n\t\n\t/*\n\tabstract protected function &_inLocalePaths()\n\t{\n\t\tstatic $paths = array(\n\t\t\t'FirstName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ), \n\t\t\t'LastName' => array( 'QBD', 'QBCA', 'QBUK', 'QBAU' ),\n\t\t\t);\n\t\t\n\t\treturn $paths;\n\t}\n\t*/\n\t\n\tprotected function &_reorderPathsPaths()\n\t{\n\t\tstatic $paths = array (\n 0 => 'ListID',\n 1 => 'FullName',\n 2 => 'MaxReturned',\n 3 => 'ActiveStatus',\n 4 => 'FromModifiedDate',\n 5 => 'ToModifiedDate',\n 6 => 'NameFilter MatchCriterion',\n 7 => 'NameFilter Name',\n 8 => 'NameRangeFilter FromName',\n 9 => 'NameRangeFilter ToName',\n 10 => 'PaymentMethodType',\n 11 => 'IncludeRetElement',\n);\n\t\t\t\n\t\treturn $paths;\n\t}\n}\n\n?>"},"repo_name":{"kind":"string","value":"SayenkoDesign/selectahead"},"path":{"kind":"string","value":"wp-content/plugins/woocommerce-quickbooks-pos-2013/QuickBooks/QBXML/Schema/Object/PaymentMethodQueryRq.php"},"language":{"kind":"string","value":"PHP"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":3453,"string":"3,453"}}},{"rowIdx":115086047,"cells":{"code":{"kind":"string","value":"#ifndef __RLS_MOD_H\n#define __RLS_MOD_H\n\n#include \"../../modules/tm/tm_load.h\"\n#include \"../../lib/srdb2/db.h\"\n#include \"rl_subscription.h\"\n#include \"../dialog/dlg_mod.h\"\n#include \"rls_data.h\"\n#include \n#include \"../xcap/xcap_mod.h\"\n\nextern struct tm_binds tmb;\n\n/** min interval for subscription expiration */\nextern int rls_min_expiration;\n\n/** max interval for subscription expiration */\nextern int rls_max_expiration;\n\n/* how often test subscriptions for expiration */\nextern int rls_expiration_timer_period;\n\n/** default expiration timeout */\nextern int rls_default_expiration;\n\n/** authorization parameters */\nextern rls_auth_params_t rls_auth_params;\n\nextern int use_db;\nextern db_con_t* rls_db; /* database connection handle */\nextern db_func_t rls_dbf;\t/* database functions */\nextern dlg_func_t dlg_func;\nextern char *db_url;\nextern int reduce_xcap_needs; /* allows XCAP simulation with web server if possible */\nextern int rls_timer_interval;\n\nextern fill_xcap_params_func fill_xcap_params;\n\n/* parameters for optimizations */\nextern int max_notifications_at_once;\n\nextern int max_list_nesting_level;\n\nextern int rls_ignore_408_on_notify;\n\n#endif\n"},"repo_name":{"kind":"string","value":"foucse/kamailio"},"path":{"kind":"string","value":"obsolete/rls/rls_mod.h"},"language":{"kind":"string","value":"C"},"license":{"kind":"string","value":"gpl-2.0"},"size":{"kind":"number","value":1178,"string":"1,178"}}},{"rowIdx":115086048,"cells":{"code":{"kind":"string","value":"/*\n * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\npackage javax.swing.text;\n\nimport java.awt.Color;\nimport java.awt.Font;\nimport java.awt.font.TextAttribute;\nimport java.lang.ref.ReferenceQueue;\nimport java.lang.ref.WeakReference;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Stack;\nimport java.util.Vector;\nimport java.util.ArrayList;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.Serializable;\nimport javax.swing.event.*;\nimport javax.swing.undo.AbstractUndoableEdit;\nimport javax.swing.undo.CannotRedoException;\nimport javax.swing.undo.CannotUndoException;\nimport javax.swing.undo.UndoableEdit;\nimport javax.swing.SwingUtilities;\nimport static sun.swing.SwingUtilities2.IMPLIED_CR;\n\n/**\n * A document that can be marked up with character and paragraph\n * styles in a manner similar to the Rich Text Format. The element\n * structure for this document represents style crossings for\n * style runs. These style runs are mapped into a paragraph element\n * structure (which may reside in some other structure). The\n * style runs break at paragraph boundaries since logical styles are\n * assigned to paragraph boundaries.\n *

\n * Warning:\n * Serialized objects of this class will not be compatible with\n * future Swing releases. The current serialization support is\n * appropriate for short term storage or RMI between applications running\n * the same version of Swing. As of 1.4, support for long term storage\n * of all JavaBeans&trade;\n * has been added to the java.beans package.\n * Please see {@link java.beans.XMLEncoder}.\n *\n * @author Timothy Prinzing\n * @see Document\n * @see AbstractDocument\n */\npublic class DefaultStyledDocument extends AbstractDocument implements StyledDocument {\n\n /**\n * Constructs a styled document.\n *\n * @param c the container for the content\n * @param styles resources and style definitions which may\n * be shared across documents\n */\n public DefaultStyledDocument(Content c, StyleContext styles) {\n super(c, styles);\n listeningStyles = new Vector