repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
iAMr00t/android_kernel_lge_ls840 | include/mach-msm/include/mach/msm_iomap-8930.h | 3201 | /*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2008-2011, Code Aurora Forum. All rights reserved.
* Author: Brian Swetland <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* The MSM peripherals are spread all over across 768MB of physical
* space, which makes just having a simple IO_ADDRESS macro to slide
* them into the right virtual location rough. Instead, we will
* provide a master phys->virt mapping for peripherals here.
*
*/
#ifndef __ASM_ARCH_MSM_IOMAP_8930_H
#define __ASM_ARCH_MSM_IOMAP_8930_H
/* Physical base address and size of peripherals.
* Ordered by the virtual base addresses they will be mapped at.
*
* If you add or remove entries here, you'll want to edit the
* msm_io_desc array in arch/arm/mach-msm/io.c to reflect your
* changes.
*
*/
#define MSM8930_TMR_PHYS 0x0200A000
#define MSM8930_TMR_SIZE SZ_4K
#define MSM8930_TMR0_PHYS 0x0208A000
#define MSM8930_TMR0_SIZE SZ_4K
#define MSM8930_RPM_PHYS 0x00108000
#define MSM8930_RPM_SIZE SZ_4K
#define MSM8930_RPM_MPM_PHYS 0x00200000
#define MSM8930_RPM_MPM_SIZE SZ_4K
#define MSM8930_TCSR_PHYS 0x1A400000
#define MSM8930_TCSR_SIZE SZ_4K
#define MSM8930_APCS_GCC_PHYS 0x02011000
#define MSM8930_APCS_GCC_SIZE SZ_4K
#define MSM8930_SAW_L2_PHYS 0x02012000
#define MSM8930_SAW_L2_SIZE SZ_4K
#define MSM8930_SAW0_PHYS 0x02089000
#define MSM8930_SAW0_SIZE SZ_4K
#define MSM8930_SAW1_PHYS 0x02099000
#define MSM8930_SAW1_SIZE SZ_4K
#define MSM8930_IMEM_PHYS 0x2A03F000
#define MSM8930_IMEM_SIZE SZ_4K
#define MSM8930_ACC0_PHYS 0x02088000
#define MSM8930_ACC0_SIZE SZ_4K
#define MSM8930_ACC1_PHYS 0x02098000
#define MSM8930_ACC1_SIZE SZ_4K
#define MSM8930_QGIC_DIST_PHYS 0x02000000
#define MSM8930_QGIC_DIST_SIZE SZ_4K
#define MSM8930_QGIC_CPU_PHYS 0x02002000
#define MSM8930_QGIC_CPU_SIZE SZ_4K
#define MSM8930_CLK_CTL_PHYS 0x00900000
#define MSM8930_CLK_CTL_SIZE SZ_16K
#define MSM8930_MMSS_CLK_CTL_PHYS 0x04000000
#define MSM8930_MMSS_CLK_CTL_SIZE SZ_4K
#define MSM8930_LPASS_CLK_CTL_PHYS 0x28000000
#define MSM8930_LPASS_CLK_CTL_SIZE SZ_4K
#define MSM8930_HFPLL_PHYS 0x00903000
#define MSM8930_HFPLL_SIZE SZ_4K
#define MSM8930_TLMM_PHYS 0x00800000
#define MSM8930_TLMM_SIZE SZ_16K
#define MSM8930_DMOV_PHYS 0x18320000
#define MSM8930_DMOV_SIZE SZ_1M
#define MSM8930_SIC_NON_SECURE_PHYS 0x12100000
#define MSM8930_SIC_NON_SECURE_SIZE SZ_64K
#define MSM_GPT_BASE (MSM_TMR_BASE + 0x4)
#define MSM_DGT_BASE (MSM_TMR_BASE + 0x24)
#define MSM8930_HDMI_PHYS 0x04A00000
#define MSM8930_HDMI_SIZE SZ_4K
#ifdef CONFIG_DEBUG_MSM8930_UART
#define MSM_DEBUG_UART_BASE IOMEM(0xFA740000)
#define MSM_DEBUG_UART_PHYS 0x16440000
#endif
#define MSM8930_QFPROM_PHYS 0x00700000
#define MSM8930_QFPROM_SIZE SZ_4K
#endif
| gpl-2.0 |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/base/metrics/sample_map.h | 1962 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// SampleMap implements HistogramSamples interface. It is used by the
// SparseHistogram class to store samples.
#ifndef BASE_METRICS_SAMPLE_MAP_H_
#define BASE_METRICS_SAMPLE_MAP_H_
#include <map>
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
namespace base {
class BASE_EXPORT_PRIVATE SampleMap : public HistogramSamples {
public:
SampleMap();
~SampleMap() override;
// HistogramSamples implementation:
void Accumulate(HistogramBase::Sample value,
HistogramBase::Count count) override;
HistogramBase::Count GetCount(HistogramBase::Sample value) const override;
HistogramBase::Count TotalCount() const override;
scoped_ptr<SampleCountIterator> Iterator() const override;
protected:
bool AddSubtractImpl(
SampleCountIterator* iter,
HistogramSamples::Operator op) override; // |op| is ADD or SUBTRACT.
private:
std::map<HistogramBase::Sample, HistogramBase::Count> sample_counts_;
DISALLOW_COPY_AND_ASSIGN(SampleMap);
};
class BASE_EXPORT_PRIVATE SampleMapIterator : public SampleCountIterator {
public:
typedef std::map<HistogramBase::Sample, HistogramBase::Count>
SampleToCountMap;
explicit SampleMapIterator(const SampleToCountMap& sample_counts);
~SampleMapIterator() override;
// SampleCountIterator implementation:
bool Done() const override;
void Next() override;
void Get(HistogramBase::Sample* min,
HistogramBase::Sample* max,
HistogramBase::Count* count) const override;
private:
void SkipEmptyBuckets();
SampleToCountMap::const_iterator iter_;
const SampleToCountMap::const_iterator end_;
};
} // namespace base
#endif // BASE_METRICS_SAMPLE_MAP_H_
| mit |
Ejobs/Sylius | src/Sylius/Bundle/ResourceBundle/test/src/Tests/Configuration/ConfigurationTest.php | 1925 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Tests;
use Matthias\SymfonyConfigTest\PhpUnit\ConfigurationTestCaseTrait;
use Sylius\Bundle\ResourceBundle\DependencyInjection\Configuration;
/**
* @author Anna Walasek <[email protected]>
* @author Kamil Kokot <[email protected]>
*/
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
use ConfigurationTestCaseTrait;
/**
* @test
*/
public function it_does_not_break_if_not_customized()
{
$this->assertConfigurationIsValid(
[
[]
]
);
}
/**
* @test
*/
public function it_has_default_authorization_checker()
{
$this->assertProcessedConfigurationEquals(
[
[]
],
['authorization_checker' => 'sylius.resource_controller.authorization_checker.disabled'],
'authorization_checker'
);
}
/**
* @test
*/
public function its_authorization_checker_can_be_customized()
{
$this->assertProcessedConfigurationEquals(
[
['authorization_checker' => 'custom_service']
],
['authorization_checker' => 'custom_service'],
'authorization_checker'
);
}
/**
* @test
*/
public function its_authorization_checker_cannot_be_empty()
{
$this->assertPartialConfigurationIsInvalid(
[
['authorization_checker' => '']
],
'authorization_checker'
);
}
/**
* {@inheritdoc}
*/
protected function getConfiguration()
{
return new Configuration();
}
}
| mit |
Aldrien-/three.js | test/unit/src/helpers/PointLightHelper.tests.js | 745 | /**
* @author TristanVALCKE / https://github.com/Itee
*/
/* global QUnit */
import { PointLightHelper } from '../../../../src/helpers/PointLightHelper';
export default QUnit.module( 'Helpers', () => {
QUnit.module( 'PointLightHelper', () => {
// INHERITANCE
QUnit.todo( "Extending", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// INSTANCING
QUnit.todo( "Instancing", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// PUBLIC STUFF
QUnit.todo( "dispose", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "update", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
} );
} );
| mit |
chrisk44/android_kernel_lge_hammerhead | drivers/media/platform/msm/camera_v2/pproc/cpp/msm_cpp.h | 5681 | /* Copyright (c) 2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef __MSM_CPP_H__
#define __MSM_CPP_H__
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/list.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <media/v4l2-subdev.h>
#include "msm_sd.h"
#define MAX_ACTIVE_CPP_INSTANCE 8
#define MAX_CPP_PROCESSING_FRAME 2
#define MAX_CPP_V4l2_EVENTS 30
#define MSM_CPP_MICRO_BASE 0x4000
#define MSM_CPP_MICRO_HW_VERSION 0x0000
#define MSM_CPP_MICRO_IRQGEN_STAT 0x0004
#define MSM_CPP_MICRO_IRQGEN_CLR 0x0008
#define MSM_CPP_MICRO_IRQGEN_MASK 0x000C
#define MSM_CPP_MICRO_FIFO_TX_DATA 0x0010
#define MSM_CPP_MICRO_FIFO_TX_STAT 0x0014
#define MSM_CPP_MICRO_FIFO_RX_DATA 0x0018
#define MSM_CPP_MICRO_FIFO_RX_STAT 0x001C
#define MSM_CPP_MICRO_BOOT_START 0x0020
#define MSM_CPP_MICRO_BOOT_LDORG 0x0024
#define MSM_CPP_MICRO_CLKEN_CTL 0x0030
#define MSM_CPP_CMD_GET_BOOTLOADER_VER 0x1
#define MSM_CPP_CMD_FW_LOAD 0x2
#define MSM_CPP_CMD_EXEC_JUMP 0x3
#define MSM_CPP_CMD_RESET_HW 0x5
#define MSM_CPP_CMD_PROCESS_FRAME 0x6
#define MSM_CPP_CMD_FLUSH_STREAM 0x7
#define MSM_CPP_CMD_CFG_MEM_PARAM 0x8
#define MSM_CPP_CMD_ERROR_REQUEST 0x9
#define MSM_CPP_CMD_GET_STATUS 0xA
#define MSM_CPP_CMD_GET_FW_VER 0xB
#define MSM_CPP_MSG_ID_CMD 0x3E646D63
#define MSM_CPP_MSG_ID_OK 0x0A0A4B4F
#define MSM_CPP_MSG_ID_TRAILER 0xABCDEFAA
#define MSM_CPP_MSG_ID_JUMP_ACK 0x00000001
#define MSM_CPP_MSG_ID_FRAME_ACK 0x00000002
#define MSM_CPP_MSG_ID_FRAME_NACK 0x00000003
#define MSM_CPP_MSG_ID_FLUSH_ACK 0x00000004
#define MSM_CPP_MSG_ID_FLUSH_NACK 0x00000005
#define MSM_CPP_MSG_ID_CFG_MEM_ACK 0x00000006
#define MSM_CPP_MSG_ID_CFG_MEM_INV 0x00000007
#define MSM_CPP_MSG_ID_ERROR_STATUS 0x00000008
#define MSM_CPP_MSG_ID_INVALID_CMD 0x00000009
#define MSM_CPP_MSG_ID_GEN_STATUS 0x0000000A
#define MSM_CPP_MSG_ID_FLUSHED 0x0000000B
#define MSM_CPP_MSG_ID_FW_VER 0x0000000C
#define MSM_CPP_JUMP_ADDRESS 0x20
#define MSM_CPP_START_ADDRESS 0x0
#define MSM_CPP_END_ADDRESS 0x3F00
#define MSM_CPP_POLL_RETRIES 20
#define MSM_CPP_TASKLETQ_SIZE 16
#define MSM_CPP_TX_FIFO_LEVEL 16
struct cpp_subscribe_info {
struct v4l2_fh *vfh;
uint32_t active;
};
enum cpp_state {
CPP_STATE_BOOT,
CPP_STATE_IDLE,
CPP_STATE_ACTIVE,
CPP_STATE_OFF,
};
enum msm_queue {
MSM_CAM_Q_CTRL, /* control command or control command status */
MSM_CAM_Q_VFE_EVT, /* adsp event */
MSM_CAM_Q_VFE_MSG, /* adsp message */
MSM_CAM_Q_V4L2_REQ, /* v4l2 request */
MSM_CAM_Q_VPE_MSG, /* vpe message */
MSM_CAM_Q_PP_MSG, /* pp message */
};
struct msm_queue_cmd {
struct list_head list_config;
struct list_head list_control;
struct list_head list_frame;
struct list_head list_pict;
struct list_head list_vpe_frame;
struct list_head list_eventdata;
enum msm_queue type;
void *command;
atomic_t on_heap;
struct timespec ts;
uint32_t error_code;
uint32_t trans_code;
};
struct msm_device_queue {
struct list_head list;
spinlock_t lock;
wait_queue_head_t wait;
int max;
int len;
const char *name;
};
struct msm_cpp_tasklet_queue_cmd {
struct list_head list;
uint32_t irq_status;
uint32_t tx_fifo[MSM_CPP_TX_FIFO_LEVEL];
uint32_t tx_level;
uint8_t cmd_used;
};
struct msm_cpp_buffer_map_info_t {
unsigned long len;
unsigned long phy_addr;
struct ion_handle *ion_handle;
struct msm_cpp_buffer_info_t buff_info;
};
struct msm_cpp_buffer_map_list_t {
struct msm_cpp_buffer_map_info_t map_info;
struct list_head entry;
};
struct msm_cpp_buff_queue_info_t {
uint32_t used;
uint16_t session_id;
uint16_t stream_id;
struct list_head vb2_buff_head;
struct list_head native_buff_head;
};
struct msm_cpp_work_t {
struct work_struct my_work;
struct cpp_device *cpp_dev;
};
struct cpp_device {
struct platform_device *pdev;
struct msm_sd_subdev msm_sd;
struct v4l2_subdev subdev;
struct resource *mem;
struct resource *irq;
struct resource *io;
struct resource *vbif_mem;
struct resource *vbif_io;
struct resource *cpp_hw_mem;
void __iomem *vbif_base;
void __iomem *base;
void __iomem *cpp_hw_base;
struct clk **cpp_clk;
struct regulator *fs_cpp;
struct mutex mutex;
enum cpp_state state;
uint8_t is_firmware_loaded;
char *fw_name_bin;
struct workqueue_struct *timer_wq;
struct msm_cpp_work_t *work;
uint32_t fw_version;
int domain_num;
struct iommu_domain *domain;
struct device *iommu_ctx;
struct ion_client *client;
struct kref refcount;
/* Reusing proven tasklet from msm isp */
atomic_t irq_cnt;
uint8_t taskletq_idx;
spinlock_t tasklet_lock;
struct list_head tasklet_q;
struct tasklet_struct cpp_tasklet;
struct msm_cpp_tasklet_queue_cmd
tasklet_queue_cmd[MSM_CPP_TASKLETQ_SIZE];
struct cpp_subscribe_info cpp_subscribe_list[MAX_ACTIVE_CPP_INSTANCE];
uint32_t cpp_open_cnt;
struct cpp_hw_info hw_info;
struct msm_device_queue eventData_q; /* V4L2 Event Payload Queue */
/* Processing Queue
* store frame info for frames sent to microcontroller
*/
struct msm_device_queue processing_q;
struct msm_cpp_buff_queue_info_t *buff_queue;
uint32_t num_buffq;
struct v4l2_subdev *buf_mgr_subdev;
};
#endif /* __MSM_CPP_H__ */
| gpl-2.0 |
xinchoubiology/gcc | libstdc++-v3/testsuite/ext/mt_allocator/check_delete.cc | 1085 | // 2001-11-25 Phil Edwards <[email protected]>
//
// Copyright (C) 2001-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 20.4.1.1 allocator members
#include <cstdlib>
#include <ext/mt_allocator.h>
#include <replacement_memory_operators.h>
int main()
{
typedef __gnu_cxx::__mt_alloc<unsigned int> allocator_type;
__gnu_test::check_delete<allocator_type, false>();
return 0;
}
| gpl-2.0 |
mo-norant/FinHeartBel | website/node_modules/tslint/lib/rules/memberAccessRule.d.ts | 1404 | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as ts from "typescript";
import * as Lint from "../index";
export declare class Rule extends Lint.Rules.AbstractRule {
static metadata: Lint.IRuleMetadata;
static FAILURE_STRING_FACTORY: (memberType: string, memberName: string | undefined, publicOnly: boolean) => string;
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[];
}
export declare class MemberAccessWalker extends Lint.RuleWalker {
visitConstructorDeclaration(node: ts.ConstructorDeclaration): void;
visitMethodDeclaration(node: ts.MethodDeclaration): void;
visitPropertyDeclaration(node: ts.PropertyDeclaration): void;
visitGetAccessor(node: ts.AccessorDeclaration): void;
visitSetAccessor(node: ts.AccessorDeclaration): void;
private validateVisibilityModifiers(node);
}
| gpl-3.0 |
UK992/servo | tests/wpt/web-platform-tests/accname/name_test_case_740-manual.html | 1849 | <!doctype html>
<html>
<head>
<title>Name test case 740</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<link rel="stylesheet" href="/wai-aria/scripts/manual.css">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/wai-aria/scripts/ATTAcomm.js"></script>
<script>
setup({explicit_timeout: true, explicit_done: true });
var theTest = new ATTAcomm(
{
"steps" : [
{
"element" : "test",
"test" : {
"ATK" : [
[
"property",
"name",
"is",
"crazy Monday"
]
],
"AXAPI" : [
[
"property",
"AXDescription",
"is",
"crazy Monday"
]
],
"IAccessible2" : [
[
"property",
"accName",
"is",
"crazy Monday"
]
],
"UIA" : [
[
"property",
"Name",
"is",
"crazy Monday"
]
]
},
"title" : "step 1",
"type" : "test"
}
],
"title" : "Name test case 740"
}
) ;
</script>
</head>
<body>
<p>This test examines the ARIA properties for Name test case 740.</p>
<label for="test">
crazy
<div role="spinbutton" aria-valuetext="Monday" aria-valuemin="1" aria-valuemax="7" aria-valuenow="4">
</div>
</label>
<input type="radio" id="test"/>
<div id="manualMode"></div>
<div id="log"></div>
<div id="ATTAmessages"></div>
</body>
</html>
| mpl-2.0 |
vietpn/ghost-nodejs | node_modules/express-hbs/lib/hbs.js | 17800 | 'use strict';
var fs = require('fs');
var path = require('path');
var readdirp = require('readdirp');
var handlebars = require('handlebars');
var async = require('./async');
/**
* Regex pattern for layout directive. {{!< layout }}
*/
var layoutPattern = /{{!<\s+([A-Za-z0-9\._\-\/]+)\s*}}/;
/**
* Constructor
*/
var ExpressHbs = function() {
this.handlebars = handlebars.create();
this.SafeString = this.handlebars.SafeString;
this.Utils = this.handlebars.Utils;
this.beautify = null;
this.beautifyrc = null;
};
/**
* Defines a block into which content is inserted via `content`.
*
* @example
* In layout.hbs
*
* {{{block "pageStylesheets"}}}
*/
ExpressHbs.prototype.block = function(name) {
var val = (this.blocks[name] || []).join('\n');
// free mem
this.blocks[name] = null;
return val;
};
/**
* Defines content for a named block declared in layout.
*
* @example
*
* {{#contentFor "pageStylesheets"}}
* <link rel="stylesheet" href='{{{URL "css/style.css"}}}' />
* {{/contentFor}}
*/
ExpressHbs.prototype.content = function(name, options, context) {
var block = this.blocks[name] || (this.blocks[name] = []);
block.push(options.fn(context));
};
/**
* Returns the layout filepath given the template filename and layout used.
* Backward compatible with specifying layouts in locals like 'layouts/foo',
* but if you have specified a layoutsDir you can specify layouts in locals with just the layout name.
*
* @param {String} filename Path to template file.
* @param {String} layout Layout path.
*/
ExpressHbs.prototype.layoutPath = function(filename, layout) {
var layoutPath;
if (layout[0] === '.') {
layoutPath = path.resolve(path.dirname(filename), layout);
} else if (this.layoutsDir) {
layoutPath = path.resolve(this.layoutsDir, layout);
} else {
layoutPath = path.resolve(this.viewsDir, layout);
}
return layoutPath;
}
/**
* Find the path of the declared layout in `str`, if any
*
* @param {String} str The template string to parse
* @param {String} filename Path to template
* @returns {String|undefined} Returns the path to layout.
*/
ExpressHbs.prototype.declaredLayoutFile = function(str, filename) {
var matches = str.match(layoutPattern);
if (matches) {
var layout = matches[1];
// behave like `require`, if '.' then relative, else look in
// usual location (layoutsDir)
if (this.layoutsDir && layout[0] !== '.') {
layout = path.resolve(this.layoutsDir, layout);
}
return path.resolve(path.dirname(filename), layout);
}
};
/**
* Compiles a layout file.
*
* The function checks whether the layout file declares a parent layout.
* If it does, the parent layout is loaded recursively and checked as well
* for a parent layout, and so on, until the top layout is reached.
* All layouts are then returned as a stack to the caller via the callback.
*
* @param {String} layoutFile The path to the layout file to compile
* @param {Boolean} useCache Cache the compiled layout?
* @param {Function} cb Callback called with layouts stack
*/
ExpressHbs.prototype.cacheLayout = function(layoutFile, useCache, cb) {
var self = this;
// assume hbs extension
if (path.extname(layoutFile) === '') layoutFile += this._options.extname;
// path is relative in directive, make it absolute
var layoutTemplates = this.cache[layoutFile];
if (layoutTemplates) return cb(null, layoutTemplates);
fs.readFile(layoutFile, 'utf8', function(err, str) {
if (err) return cb(err);
// File path of eventual declared parent layout
var parentLayoutFile = self.declaredLayoutFile(str, layoutFile);
// This function returns the current layout stack to the caller
var _returnLayouts = function(layouts) {
var currentLayout;
layouts = layouts.slice(0);
currentLayout = self.compile(str, layoutFile);
layouts.push(currentLayout);
if (useCache) {
self.cache[layoutFile] = layouts.slice(0);
}
cb(null, layouts);
};
if (parentLayoutFile) {
// Recursively compile/cache parent layouts
self.cacheLayout(parentLayoutFile, useCache, function(err, parentLayouts) {
if (err) return cb(err);
_returnLayouts(parentLayouts);
});
} else {
// No parent layout: return current layout with an empty stack
_returnLayouts([]);
}
});
};
/**
* Cache partial templates found under directories configure in partialsDir.
*/
ExpressHbs.prototype.cachePartials = function(cb) {
var self = this;
if (!(this.partialsDir instanceof Array)) {
this.partialsDir = [this.partialsDir];
}
// Use to iterate all folder in series
var count = 0;
function readNext() {
readdirp({ root: self.partialsDir[count], fileFilter: '*.*' })
.on('warn', function(err) {
console.warn('Non-fatal error in express-hbs cachePartials.', err);
})
.on('error', function(err) {
console.error('Fatal error in express-hbs cachePartials', err);
return cb(err);
})
.on('data', function(entry) {
if (!entry) return;
var source = fs.readFileSync(entry.fullPath, 'utf8');
var dirname = path.dirname(entry.path);
dirname = dirname === '.' ? '' : dirname + '/';
var name = dirname + path.basename(entry.name, path.extname(entry.name));
self.registerPartial(name, source);
})
.on('end', function() {
count += 1;
// If all directories aren't read, read the next directory
if (count < self.partialsDir.length) {
readNext()
} else {
self.isPartialCachingComplete = true;
cb && cb(null, true);
}
});
}
readNext();
};
/**
* Express 3.x template engine compliance.
*
* @param {Object} options = {
* handlebars: "override handlebars",
* defaultLayout: "path to default layout",
* partialsDir: "absolute path to partials (one path or an array of paths)",
* layoutsDir: "absolute path to the layouts",
* extname: "extension to use",
* contentHelperName: "contentFor",
* blockHelperName: "block",
* beautify: "{Boolean} whether to pretty print HTML"
* }
*
*/
ExpressHbs.prototype.express3 = function(options) {
var self = this;
// Set defaults
if (!options) options = {};
if (!options.extname) options.extname = '.hbs';
if (!options.contentHelperName) options.contentHelperName = 'contentFor';
if (!options.blockHelperName) options.blockHelperName = 'block';
if (!options.templateOptions) options.templateOptions = {};
if (options.handlebars) this.handlebars = options.handlebars;
this._options = options;
if (this._options.handlebars) this.handlebars = this._options.handlebars;
if (options.i18n) {
var i18n = options.i18n;
this.handlebars.registerHelper('__', function() {
return i18n.__.apply(this, arguments);
});
this.handlebars.registerHelper('__n', function() {
return i18n.__n.apply(this, arguments);
});
}
this.handlebars.registerHelper(this._options.blockHelperName, function(name, options) {
var val = self.block(name);
if (val == '' && (typeof options.fn === 'function')) {
val = options.fn(this);
}
// blocks may have async helpers
if (val.indexOf('__aSyNcId_') >= 0) {
if (self.asyncValues) {
Object.keys(self.asyncValues).forEach(function (id) {
val = val.replace(id, self.asyncValues[id]);
val = val.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(self.asyncValues[id]));
});
}
}
return val;
});
// Pass 'this' as context of helper function to don't lose context call of helpers.
this.handlebars.registerHelper(this._options.contentHelperName, function(name, options) {
return self.content(name, options, this);
});
// Absolute path to partials directory.
this.partialsDir = this._options.partialsDir;
// Absolute path to the layouts directory
this.layoutsDir = this._options.layoutsDir;
// express passes this through _express3 func, gulp pass in an option
this.viewsDir = null
this.viewsDirOpt = this._options.viewsDir;
// Cache for templates, express 3.x doesn't do this for us
this.cache = {};
// Blocks for layouts. Is this safe? What happens if the same block is used on multiple connections?
// Isn't there a chance block and content are not in sync. The template and layout are processed asynchronously.
this.blocks = {};
// Holds the default compiled layout if specified in options configuration.
this.defaultLayoutTemplates = null;
// Keep track of if partials have been cached already or not.
this.isPartialCachingComplete = false;
return _express3.bind(this);
};
/**
* Tries to load the default layout.
*
* @param {Boolean} useCache Whether to cache.
*/
ExpressHbs.prototype.loadDefaultLayout = function(useCache, cb) {
var self = this;
if (!this._options.defaultLayout) return cb();
if (useCache && this.defaultLayoutTemplates) return cb(null, this.defaultLayoutTemplates);
this.cacheLayout(this._options.defaultLayout, useCache, function(err, templates) {
if (err) return cb(err);
self.defaultLayoutTemplates = templates.slice(0);
return cb(null, templates);
});
};
/**
* express 3.x template engine compliance
*
* @param {String} filename Full path to template.
* @param {Object} options Is the context or locals for templates. {
* {Object} settings - subset of Express settings, `settings.views` is
* the views directory
* }
* @param {Function} cb The callback expecting the rendered template as a string.
*
* @example
*
* Example options from express
*
* {
* settings: {
* 'x-powered-by': true,
* env: 'production',
* views: '/home/coder/barc/code/express-hbs/example/views',
* 'jsonp callback name': 'callback',
* 'view cache': true,
* 'view engine': 'hbs'
* },
* cache: true,
*
* // the rest are app-defined locals
* title: 'My favorite veggies',
* layout: 'layout/veggie'
* }
*/
function _express3(filename, source, options, cb) {
// console.log('filename', filename);
// console.log('options', options);
// support running as a gulp/grunt filter outside of express
if (arguments.length === 3) {
cb = options;
options = source;
source = null;
}
this.viewsDir = options.settings.views || this.viewsDirOpt;
var self = this;
/**
* Allow a layout to be declared as a handlebars comment to remain spec
* compatible with handlebars.
*
* Valid directives
*
* {{!< foo}} # foo.hbs in same directory as template
* {{!< ../layouts/default}} # default.hbs in parent layout directory
* {{!< ../layouts/default.html}} # default.html in parent layout directory
*/
function parseLayout(str, filename, cb) {
var layoutFile = self.declaredLayoutFile(str, filename);
if (layoutFile) {
self.cacheLayout(layoutFile, options.cache, cb);
} else {
cb(null, null);
}
}
/**
* Renders `template` with given `locals` and calls `cb` with the
* resulting HTML string.
*
* @param template
* @param locals
* @param cb
*/
function renderTemplate(template, locals, cb) {
var res;
try {
res = template(locals, self._options.templateOptions);
} catch (err) {
if (err.message) {
err.message = '[' + template.__filename + '] ' + err.message;
} else if (typeof err === 'string') {
err = '[' + template.__filename + '] ' + err;
}
return cb(err, null);
}
// Wait for async helpers
async.done(function (values) {
// Save for layout. Block helpers are called within layout, not in the
// current template.
self.asyncValues = values;
Object.keys(values).forEach(function (id) {
res = res.replace(id, values[id]);
res = res.replace(self.Utils.escapeExpression(id), self.Utils.escapeExpression(values[id]));
});
cb(null, res);
});
}
/**
* Renders `template` with an optional set of nested `layoutTemplates` using
* data in `locals`.
*/
function render(template, locals, layoutTemplates, cb) {
if (layoutTemplates == undefined) layoutTemplates = [];
// We'll render templates from bottom to top of the stack, each template
// being passed the rendered string of the previous ones as `body`
var i = layoutTemplates.length - 1;
var _stackRenderer = function(err, htmlStr) {
if (err) return cb(err);
if (i >= 0) {
locals.body = htmlStr;
renderTemplate(layoutTemplates[i--], locals, _stackRenderer);
} else {
cb(null, htmlStr);
}
};
// Start the rendering with the innermost page template
renderTemplate(template, locals, _stackRenderer);
}
/**
* Lazy loads js-beautify, which shouldn't be used in production env.
*/
function loadBeautify() {
if (!self.beautify) {
self.beautify = require('js-beautify').html;
var rc = path.join(process.cwd(), '.jsbeautifyrc');
if (fs.existsSync(rc)) {
self.beautifyrc = JSON.parse(fs.readFileSync(rc, 'utf8'));
}
}
}
/**
* Compiles a file into a template and a layoutTemplate, then renders it above.
*/
function compileFile(locals, cb) {
var source, info, template;
if (options.cache) {
info = self.cache[filename];
if (info) {
source = info.source;
template = info.template;
}
}
if (!info) {
source = fs.readFileSync(filename, 'utf8');
template = self.compile(source, filename);
if (options.cache) {
self.cache[filename] = { source: source, template: template };
}
}
// Try to get the layout
parseLayout(source, filename, function (err, layoutTemplates) {
if (err) return cb(err);
function renderIt(layoutTemplates) {
if (self._options.beautify) {
return render(template, locals, layoutTemplates, function(err, html) {
if (err) return cb(err);
loadBeautify();
return cb(null, self.beautify(html, self.beautifyrc));
});
} else {
return render(template, locals, layoutTemplates, cb);
}
}
// Determine which layout to use
// If options.layout is falsy, behave as if no layout should be used - suppress defaults
if ((typeof (options.layout) !== 'undefined') && !options.layout) {
renderIt(null);
} else {
// 1. Layout specified in template
if (layoutTemplates) {
renderIt(layoutTemplates);
}
// 2. Layout specified by options from render
else if ((typeof (options.layout) !== 'undefined') && options.layout) {
var layoutFile = self.layoutPath(filename, options.layout);
self.cacheLayout(layoutFile, options.cache, function (err, layoutTemplates) {
if (err) return cb(err);
renderIt(layoutTemplates);
});
}
// 3. Default layout specified when middleware was configured.
else if (self.defaultLayoutTemplates) {
renderIt(self.defaultLayoutTemplates);
}
// render without a template
else renderIt(null);
}
});
}
// kick it off by loading default template (if any)
this.loadDefaultLayout(options.cache, function(err) {
if (err) return cb(err);
// Force reloading of all partials if caching is not used. Inefficient but there
// is no loading partial event.
if (self.partialsDir && (!options.cache || !self.isPartialCachingComplete)) {
return self.cachePartials(function(err) {
if (err) return cb(err);
return compileFile(options, cb);
});
}
return compileFile(options, cb);
});
}
/**
* Expose useful methods.
*/
ExpressHbs.prototype.registerHelper = function(name, fn) {
this.handlebars.registerHelper(name, fn);
};
/**
* Registers a partial.
*
* @param {String} name The name of the partial as used in a template.
* @param {String} source String source of the partial.
*/
ExpressHbs.prototype.registerPartial = function(name, source) {
this.handlebars.registerPartial(name, this.compile(source));
};
/**
* Compiles a string.
*
* @param {String} source The source to compile.
* @param {String} filename The path used to embed into __filename for errors.
*/
ExpressHbs.prototype.compile = function(source, filename) {
// Handlebars has a bug with comment only partial causes errors. This must
// be a string so the block below can add a space.
if (typeof source !== 'string') {
throw new Error('registerPartial must be a string for empty comment workaround');
}
if (source.indexOf('}}') === source.length - 2) {
source += ' ';
}
var compiled = this.handlebars.compile(source);
if (filename) {
// track for error message
compiled.__filename = path.relative(this.viewsDir, filename).replace(path.sep, '/');
}
return compiled;
}
/**
* Registers an asynchronous helper.
*
* @param {String} name The name of the partial as used in a template.
* @param {String} fn The `function(options, cb)`
*/
ExpressHbs.prototype.registerAsyncHelper = function(name, fn) {
this.handlebars.registerHelper(name, function(context) {
return async.resolve(fn.bind(this), context);
});
};
ExpressHbs.prototype.updateTemplateOptions = function(templateOptions) {
this._options.templateOptions = templateOptions;
};
/**
* Creates a new instance of ExpressHbs.
*/
ExpressHbs.prototype.create = function() {
return new ExpressHbs();
};
module.exports = new ExpressHbs();
| mit |
krk/corefx | src/System.Net.Requests/src/System/Net/FtpWebResponse.cs | 5923 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace System.Net
{
/// <summary>
/// <para>The FtpWebResponse class contains the result of the FTP request.
/// </summary>
public class FtpWebResponse : WebResponse, IDisposable
{
internal Stream _responseStream;
private long _contentLength;
private Uri _responseUri;
private FtpStatusCode _statusCode;
private string _statusLine;
private WebHeaderCollection _ftpRequestHeaders;
private DateTime _lastModified;
private string _bannerMessage;
private string _welcomeMessage;
private string _exitMessage;
internal FtpWebResponse(Stream responseStream, long contentLength, Uri responseUri, FtpStatusCode statusCode, string statusLine, DateTime lastModified, string bannerMessage, string welcomeMessage, string exitMessage)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, contentLength, statusLine);
_responseStream = responseStream;
if (responseStream == null && contentLength < 0)
{
contentLength = 0;
}
_contentLength = contentLength;
_responseUri = responseUri;
_statusCode = statusCode;
_statusLine = statusLine;
_lastModified = lastModified;
_bannerMessage = bannerMessage;
_welcomeMessage = welcomeMessage;
_exitMessage = exitMessage;
}
internal void UpdateStatus(FtpStatusCode statusCode, string statusLine, string exitMessage)
{
_statusCode = statusCode;
_statusLine = statusLine;
_exitMessage = exitMessage;
}
public override Stream GetResponseStream()
{
Stream responseStream = null;
if (_responseStream != null)
{
responseStream = _responseStream;
}
else
{
responseStream = _responseStream = new EmptyStream();
}
return responseStream;
}
internal sealed class EmptyStream : MemoryStream
{
internal EmptyStream() : base(Array.Empty<byte>(), false)
{
}
}
internal void SetResponseStream(Stream stream)
{
if (stream == null || stream == Stream.Null || stream is EmptyStream)
return;
_responseStream = stream;
}
/// <summary>
/// <para>Closes the underlying FTP response stream, but does not close control connection</para>
/// </summary>
public override void Close()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
_responseStream?.Close();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
/// <summary>
/// <para>Queries the length of the response</para>
/// </summary>
public override long ContentLength
{
get
{
return _contentLength;
}
}
internal void SetContentLength(long value)
{
_contentLength = value;
}
public override WebHeaderCollection Headers
{
get
{
if (_ftpRequestHeaders == null)
{
lock (this)
{
if (_ftpRequestHeaders == null)
{
_ftpRequestHeaders = new WebHeaderCollection();
}
}
}
return _ftpRequestHeaders;
}
}
public override bool SupportsHeaders
{
get
{
return true;
}
}
/// <summary>
/// <para>Shows the final Uri that the FTP request ended up on</para>
/// </summary>
public override Uri ResponseUri
{
get
{
return _responseUri;
}
}
/// <summary>
/// <para>Last status code retrived</para>
/// </summary>
public FtpStatusCode StatusCode
{
get
{
return _statusCode;
}
}
/// <summary>
/// <para>Last status line retrived</para>
/// </summary>
public string StatusDescription
{
get
{
return _statusLine;
}
}
/// <summary>
/// <para>Returns last modified date time for given file (null if not relavant/avail)</para>
/// </summary>
public DateTime LastModified
{
get
{
return _lastModified;
}
}
/// <summary>
/// <para>Returns the server message sent before user credentials are sent</para>
/// </summary>
public string BannerMessage
{
get
{
return _bannerMessage;
}
}
/// <summary>
/// <para>Returns the server message sent after user credentials are sent</para>
/// </summary>
public string WelcomeMessage
{
get
{
return _welcomeMessage;
}
}
/// <summary>
/// <para>Returns the exit sent message on shutdown</para>
/// </summary>
public string ExitMessage
{
get
{
return _exitMessage;
}
}
}
}
| mit |
mathiasAichinger/fastlane_core | spec/itunes_search_api_spec.rb | 2907 | WebMock.disable_net_connect!(allow: 'coveralls.io')
# iTunes Lookup API
RSpec.configure do |config|
config.before(:each) do
# iTunes Lookup API by Apple ID
["invalid", "", 0, '284882215', ['338986109', 'FR']].each do |current|
if current.kind_of? Array
id = current[0]
country = current[1]
url = "https://itunes.apple.com/lookup?id=#{id}&country=#{country}"
body_file = "spec/responses/itunesLookup-#{id}_#{country}.json"
else
id = current
url = "https://itunes.apple.com/lookup?id=#{id}"
body_file = "spec/responses/itunesLookup-#{id}.json"
end
stub_request(:get, url).
with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).
to_return(status: 200, body: File.read(body_file), headers: {})
end
# iTunes Lookup API by App Identifier
stub_request(:get, "https://itunes.apple.com/lookup?bundleId=com.facebook.Facebook").
with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).
to_return(status: 200, body: File.read("spec/responses/itunesLookup-com.facebook.Facebook.json"), headers: {})
stub_request(:get, "https://itunes.apple.com/lookup?bundleId=net.sunapps.invalid").
with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).
to_return(status: 200, body: File.read("spec/responses/itunesLookup-net.sunapps.invalid.json"), headers: {})
end
end
describe FastlaneCore do
describe FastlaneCore::ItunesSearchApi do
it "returns nil when it could not be found" do
expect(FastlaneCore::ItunesSearchApi.fetch("invalid")).to eq(nil)
expect(FastlaneCore::ItunesSearchApi.fetch("")).to eq(nil)
expect(FastlaneCore::ItunesSearchApi.fetch(0)).to eq(nil)
end
it "returns the actual object if it could be found" do
response = FastlaneCore::ItunesSearchApi.fetch("284882215")
expect(response['kind']).to eq('software')
expect(response['supportedDevices'].count).to be > 8
expect(FastlaneCore::ItunesSearchApi.fetch_bundle_identifier("284882215")).to eq('com.facebook.Facebook')
end
it "returns the actual object if it could be found" do
response = FastlaneCore::ItunesSearchApi.fetch_by_identifier("com.facebook.Facebook")
expect(response['kind']).to eq('software')
expect(response['supportedDevices'].count).to be > 8
expect(response['trackId']).to eq(284_882_215)
end
it "can find country specific object" do
response = FastlaneCore::ItunesSearchApi.fetch(338_986_109, 'FR')
expect(response['kind']).to eq('software')
expect(response['supportedDevices'].count).to be > 8
expect(response['trackId']).to eq(338_986_109)
end
end
end
| mit |
tavaresdong/courses-notes | uw_cse333/hw/projdocs/test_tree/bash-4.2/include/shmbutil.h | 12303 | /* shmbutil.h -- utility functions for multibyte characters. */
/* Copyright (C) 2002-2004 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Bash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Bash. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined (_SH_MBUTIL_H_)
#define _SH_MBUTIL_H_
#include "stdc.h"
/* Include config.h for HANDLE_MULTIBYTE */
#include <config.h>
#if defined (HANDLE_MULTIBYTE)
#include "shmbchar.h"
extern size_t xmbsrtowcs __P((wchar_t *, const char **, size_t, mbstate_t *));
extern size_t xdupmbstowcs __P((wchar_t **, char ***, const char *));
extern size_t mbstrlen __P((const char *));
extern char *xstrchr __P((const char *, int));
#ifndef MB_INVALIDCH
#define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
#define MB_NULLWCH(x) ((x) == 0)
#endif
#define MBSLEN(s) (((s) && (s)[0]) ? ((s)[1] ? mbstrlen (s) : 1) : 0)
#define MB_STRLEN(s) ((MB_CUR_MAX > 1) ? MBSLEN (s) : STRLEN (s))
#define MBLEN(s, n) ((MB_CUR_MAX > 1) ? mblen ((s), (n)) : 1)
#define MBRLEN(s, n, p) ((MB_CUR_MAX > 1) ? mbrlen ((s), (n), (p)) : 1)
#else /* !HANDLE_MULTIBYTE */
#undef MB_LEN_MAX
#undef MB_CUR_MAX
#define MB_LEN_MAX 1
#define MB_CUR_MAX 1
#undef xstrchr
#define xstrchr(s, c) strchr(s, c)
#ifndef MB_INVALIDCH
#define MB_INVALIDCH(x) (0)
#define MB_NULLWCH(x) (0)
#endif
#define MB_STRLEN(s) (STRLEN(s))
#define MBLEN(s, n) 1
#define MBRLEN(s, n, p) 1
#ifndef wchar_t
# define wchar_t int
#endif
#endif /* !HANDLE_MULTIBYTE */
/* Declare and initialize a multibyte state. Call must be terminated
with `;'. */
#if defined (HANDLE_MULTIBYTE)
# define DECLARE_MBSTATE \
mbstate_t state; \
memset (&state, '\0', sizeof (mbstate_t))
#else
# define DECLARE_MBSTATE
#endif /* !HANDLE_MULTIBYTE */
/* Initialize or reinitialize a multibyte state named `state'. Call must be
terminated with `;'. */
#if defined (HANDLE_MULTIBYTE)
# define INITIALIZE_MBSTATE memset (&state, '\0', sizeof (mbstate_t))
#else
# define INITIALIZE_MBSTATE
#endif /* !HANDLE_MULTIBYTE */
/* Advance one (possibly multi-byte) character in string _STR of length
_STRSIZE, starting at index _I. STATE must have already been declared. */
#if defined (HANDLE_MULTIBYTE)
# define ADVANCE_CHAR(_str, _strsize, _i) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _f; \
\
_f = is_basic ((_str)[_i]); \
if (_f) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_str) + (_i), (_strsize) - (_i), &state); \
} \
\
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
(_i)++; \
} \
else if (mblength == 0) \
(_i)++; \
else \
(_i) += mblength; \
} \
else \
(_i)++; \
} \
while (0)
#else
# define ADVANCE_CHAR(_str, _strsize, _i) (_i)++
#endif /* !HANDLE_MULTIBYTE */
/* Advance one (possibly multibyte) character in the string _STR of length
_STRSIZE.
SPECIAL: assume that _STR will be incremented by 1 after this call. */
#if defined (HANDLE_MULTIBYTE)
# define ADVANCE_CHAR_P(_str, _strsize) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _f; \
\
_f = is_basic (*(_str)); \
if (_f) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_str), (_strsize), &state); \
} \
\
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
mblength = 1; \
} \
else \
(_str) += (mblength < 1) ? 0 : (mblength - 1); \
} \
} \
while (0)
#else
# define ADVANCE_CHAR_P(_str, _strsize)
#endif /* !HANDLE_MULTIBYTE */
/* Back up one (possibly multi-byte) character in string _STR of length
_STRSIZE, starting at index _I. STATE must have already been declared. */
#if defined (HANDLE_MULTIBYTE)
# define BACKUP_CHAR(_str, _strsize, _i) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _x, _p; /* _x == temp index into string, _p == prev index */ \
\
_x = _p = 0; \
while (_x < (_i)) \
{ \
state_bak = state; \
mblength = mbrlen ((_str) + (_x), (_strsize) - (_x), &state); \
\
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
_x++; \
} \
else if (mblength == 0) \
_x++; \
else \
{ \
_p = _x; /* _p == start of prev mbchar */ \
_x += mblength; \
} \
} \
(_i) = _p; \
} \
else \
(_i)--; \
} \
while (0)
#else
# define BACKUP_CHAR(_str, _strsize, _i) (_i)--
#endif /* !HANDLE_MULTIBYTE */
/* Back up one (possibly multibyte) character in the string _BASE of length
_STRSIZE starting at _STR (_BASE <= _STR <= (_BASE + _STRSIZE) ).
SPECIAL: DO NOT assume that _STR will be decremented by 1 after this call. */
#if defined (HANDLE_MULTIBYTE)
# define BACKUP_CHAR_P(_base, _strsize, _str) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
char *_x, _p; /* _x == temp pointer into string, _p == prev pointer */ \
\
_x = _p = _base; \
while (_x < (_str)) \
{ \
state_bak = state; \
mblength = mbrlen (_x, (_strsize) - _x, &state); \
\
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
_x++; \
} \
else if (mblength == 0) \
_x++; \
else \
{ \
_p = _x; /* _p == start of prev mbchar */ \
_x += mblength; \
} \
} \
(_str) = _p; \
} \
else \
(_str)--; \
} \
while (0)
#else
# define BACKUP_CHAR_P(_base, _strsize, _str) (_str)--
#endif /* !HANDLE_MULTIBYTE */
/* Copy a single character from the string _SRC to the string _DST.
_SRCEND is a pointer to the end of _SRC. */
#if defined (HANDLE_MULTIBYTE)
# define COPY_CHAR_P(_dst, _src, _srcend) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _k; \
\
_k = is_basic (*(_src)); \
if (_k) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_src), (_srcend) - (_src), &state); \
} \
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
mblength = 1; \
} \
else \
mblength = (mblength < 1) ? 1 : mblength; \
\
for (_k = 0; _k < mblength; _k++) \
*(_dst)++ = *(_src)++; \
} \
else \
*(_dst)++ = *(_src)++; \
} \
while (0)
#else
# define COPY_CHAR_P(_dst, _src, _srcend) *(_dst)++ = *(_src)++
#endif /* !HANDLE_MULTIBYTE */
/* Copy a single character from the string _SRC at index _SI to the string
_DST at index _DI. _SRCEND is a pointer to the end of _SRC. */
#if defined (HANDLE_MULTIBYTE)
# define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _k; \
\
_k = is_basic (*((_src) + (_si))); \
if (_k) \
mblength = 1; \
else \
{\
state_bak = state; \
mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src)+(_si)), &state); \
} \
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
mblength = 1; \
} \
else \
mblength = (mblength < 1) ? 1 : mblength; \
\
for (_k = 0; _k < mblength; _k++) \
_dst[_di++] = _src[_si++]; \
} \
else \
_dst[_di++] = _src[_si++]; \
} \
while (0)
#else
# define COPY_CHAR_I(_dst, _di, _src, _srcend, _si) _dst[_di++] = _src[_si++]
#endif /* !HANDLE_MULTIBYTE */
/****************************************************************
* *
* The following are only guaranteed to work in subst.c *
* *
****************************************************************/
#if defined (HANDLE_MULTIBYTE)
# define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _i; \
\
_i = is_basic (*((_src) + (_si))); \
if (_i) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_src) + (_si), (_slen) - (_si), &state); \
} \
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
mblength = 1; \
} \
else \
mblength = (mblength < 1) ? 1 : mblength; \
\
temp = xmalloc (mblength + 2); \
temp[0] = _escchar; \
for (_i = 0; _i < mblength; _i++) \
temp[_i + 1] = _src[_si++]; \
temp[mblength + 1] = '\0'; \
\
goto add_string; \
} \
else \
{ \
_dst[0] = _escchar; \
_dst[1] = _sc; \
} \
} \
while (0)
#else
# define SCOPY_CHAR_I(_dst, _escchar, _sc, _src, _si, _slen) \
_dst[0] = _escchar; \
_dst[1] = _sc
#endif /* !HANDLE_MULTIBYTE */
#if defined (HANDLE_MULTIBYTE)
# define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
mbstate_t state_bak; \
size_t mblength; \
int _i; \
\
_i = is_basic (*((_src) + (_si))); \
if (_i) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_src) + (_si), (_srcend) - ((_src) + (_si)), &state); \
} \
if (mblength == (size_t)-2 || mblength == (size_t)-1) \
{ \
state = state_bak; \
mblength = 1; \
} \
else \
mblength = (mblength < 1) ? 1 : mblength; \
\
FASTCOPY(((_src) + (_si)), (_dst), mblength); \
\
(_dst) += mblength; \
(_si) += mblength; \
} \
else \
{ \
*(_dst)++ = _src[(_si)]; \
(_si)++; \
} \
} \
while (0)
#else
# define SCOPY_CHAR_M(_dst, _src, _srcend, _si) \
*(_dst)++ = _src[(_si)]; \
(_si)++
#endif /* !HANDLE_MULTIBYTE */
#if HANDLE_MULTIBYTE
# define SADD_MBCHAR(_dst, _src, _si, _srcsize) \
do \
{ \
if (MB_CUR_MAX > 1) \
{ \
int i; \
mbstate_t state_bak; \
size_t mblength; \
\
i = is_basic (*((_src) + (_si))); \
if (i) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \
} \
if (mblength == (size_t)-1 || mblength == (size_t)-2) \
{ \
state = state_bak; \
mblength = 1; \
} \
if (mblength < 1) \
mblength = 1; \
\
_dst = (char *)xmalloc (mblength + 1); \
for (i = 0; i < mblength; i++) \
(_dst)[i] = (_src)[(_si)++]; \
(_dst)[mblength] = '\0'; \
\
goto add_string; \
} \
} \
while (0)
#else
# define SADD_MBCHAR(_dst, _src, _si, _srcsize)
#endif
/* Watch out when using this -- it's just straight textual subsitution */
#if defined (HANDLE_MULTIBYTE)
# define SADD_MBQCHAR_BODY(_dst, _src, _si, _srcsize) \
\
int i; \
mbstate_t state_bak; \
size_t mblength; \
\
i = is_basic (*((_src) + (_si))); \
if (i) \
mblength = 1; \
else \
{ \
state_bak = state; \
mblength = mbrlen ((_src) + (_si), (_srcsize) - (_si), &state); \
} \
if (mblength == (size_t)-1 || mblength == (size_t)-2) \
{ \
state = state_bak; \
mblength = 1; \
} \
if (mblength < 1) \
mblength = 1; \
\
(_dst) = (char *)xmalloc (mblength + 2); \
(_dst)[0] = CTLESC; \
for (i = 0; i < mblength; i++) \
(_dst)[i+1] = (_src)[(_si)++]; \
(_dst)[mblength+1] = '\0'; \
\
goto add_string
#endif /* HANDLE_MULTIBYTE */
#endif /* _SH_MBUTIL_H_ */
| mit |
EliteScientist/webpack | test/statsCases/import-context-filter/templates/baz.noimport.js | 38 | var baz = "baz";
export default baz;
| mit |
BTDC/coreboot | src/vendorcode/amd/agesa/f16kb/Proc/Mem/ma.h | 6015 | /* $NoKeywords:$ */
/**
* @file
*
* ma.h
*
* ARDK common header file
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: (Mem)
* @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $
*
**/
/*****************************************************************************
*
* Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ***************************************************************************
*
*/
#ifndef _MA_H_
#define _MA_H_
/*----------------------------------------------------------------------------
* Mixed (DEFINITIONS AND MACROS / TYPEDEFS, STRUCTURES, ENUMS)
*
*----------------------------------------------------------------------------
*/
/*-----------------------------------------------------------------------------
* DEFINITIONS AND MACROS
*
*-----------------------------------------------------------------------------
*/
#define MAX_CS_PER_CHANNEL 8 ///< Max CS per channel
/*----------------------------------------------------------------------------
* TYPEDEFS, STRUCTURES, ENUMS
*
*----------------------------------------------------------------------------
*/
/** MARDK Structure*/
typedef struct {
UINT16 Speed; ///< Dram speed in MHz
UINT8 Loads; ///< Number of Data Loads
UINT32 AddrTmg; ///< Address Timing value
UINT32 Odc; ///< Output Driver Compensation Value
} PSCFG_ENTRY;
/** MARDK Structure*/
typedef struct {
UINT16 Speed; ///< Dram speed in MHz
UINT8 Loads; ///< Number of Data Loads
UINT32 AddrTmg; ///< Address Timing value
UINT32 Odc; ///< Output Driver Compensation Value
UINT8 Dimms; ///< Number of Dimms
} ADV_PSCFG_ENTRY;
/** MARDK Structure for RDIMMs*/
typedef struct {
UINT16 Speed; ///< Dram speed in MHz
UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3
UINT32 AddrTmg; ///< Address Timing value
UINT16 RC2RC8; ///< RC2 and RC8 value //High byte: 1st pair value, Low byte: 2nd pair value
UINT8 Dimms; ///< Number of Dimms
} ADV_R_PSCFG_ENTRY;
/** MARDK Structure*/
typedef struct {
UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3
UINT32 PhyRODTCSLow; ///< Fn2_9C 180
UINT32 PhyRODTCSHigh; ///< Fn2_9C 181
UINT32 PhyWODTCSLow; ///< Fn2_9C 182
UINT32 PhyWODTCSHigh; ///< Fn2_9C 183
UINT8 Dimms; ///< Number of Dimms
} ADV_PSCFG_ODT_ENTRY;
/** MARDK Structure for Write Levelization ODT*/
typedef struct {
UINT16 DIMMRankType; ///< Bitmap of Ranks //Bit0-3:DIMM0(1:SR, 2:DR, 4:QR, 0:No Dimm, 0xF:Any), Bit4-7:DIMM1, Bit8-11:DIMM2, Bit12-16:DIMM3
UINT8 PhyWrLvOdt[MAX_CS_PER_CHANNEL / 2]; ///< WrLvOdt (Fn2_9C_0x08[11:8]) Value for each Dimm
UINT8 Dimms; ///< Number of Dimms
} ADV_R_PSCFG_WL_ODT_ENTRY;
/*----------------------------------------------------------------------------
* FUNCTIONS PROTOTYPE
*
*----------------------------------------------------------------------------
*/
AGESA_STATUS
MemAGetPsCfgDef (
IN OUT MEM_DATA_STRUCT *MemData,
IN UINT8 SocketID,
IN OUT CH_DEF_STRUCT *CurrentChannel
);
UINT16
MemAGetPsRankType (
IN CH_DEF_STRUCT *CurrentChannel
);
AGESA_STATUS
MemRecNGetPsCfgDef (
IN OUT MEM_DATA_STRUCT *MemData,
IN UINT8 SocketID,
IN OUT CH_DEF_STRUCT *CurrentChannel
);
UINT16
MemRecNGetPsRankType (
IN CH_DEF_STRUCT *CurrentChannel
);
AGESA_STATUS
MemRecNGetPsCfgUDIMM3Nb (
IN OUT MEM_DATA_STRUCT *MemData,
IN UINT8 SocketID,
IN OUT CH_DEF_STRUCT *CurrentChannel
);
AGESA_STATUS
MemRecNGetPsCfgSODIMM3Nb (
IN OUT MEM_DATA_STRUCT *MemData,
IN UINT8 SocketID,
IN OUT CH_DEF_STRUCT *CurrentChannel
);
AGESA_STATUS
MemRecNGetPsCfgRDIMM3Nb (
IN OUT MEM_DATA_STRUCT *MemData,
IN UINT8 SocketID,
IN OUT CH_DEF_STRUCT *CurrentChannel
);
#endif /* _MA_H_ */
| gpl-2.0 |
BTDC/coreboot | src/vendorcode/amd/agesa/f16kb/Proc/GNB/Modules/GnbPcieTrainingV2/GnbPcieTrainingV2.h | 2173 | /* $NoKeywords:$ */
/**
* @file
*
* PCIe training library
*
*
*
* @xrefitem bom "File Content Label" "Release Content"
* @e project: AGESA
* @e sub-project: GNB
* @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $
*
*/
/*
*****************************************************************************
*
* Copyright (c) 2008 - 2013, Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Advanced Micro Devices, Inc. nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ***************************************************************************
*
*/
#ifndef _GNBPCIETRAININGV2_H_
#define _GNBPCIETRAININGV2_H_
#include "PcieTrainingV2.h"
#include "PcieWorkaroundsV2.h"
#endif
| gpl-2.0 |
janrinze/loox7xxport.loox2-6-22 | scripts/kconfig/menu.c | 10632 | /*
* Copyright (C) 2002 Roman Zippel <[email protected]>
* Released under the terms of the GNU GPL v2.0.
*/
#include <stdlib.h>
#include <string.h>
#define LKC_DIRECT_LINK
#include "lkc.h"
struct menu rootmenu;
static struct menu **last_entry_ptr;
struct file *file_list;
struct file *current_file;
static void menu_warn(struct menu *menu, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s:%d:warning: ", menu->file->name, menu->lineno);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
static void prop_warn(struct property *prop, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s:%d:warning: ", prop->file->name, prop->lineno);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
}
void menu_init(void)
{
current_entry = current_menu = &rootmenu;
last_entry_ptr = &rootmenu.list;
}
void menu_add_entry(struct symbol *sym)
{
struct menu *menu;
menu = malloc(sizeof(*menu));
memset(menu, 0, sizeof(*menu));
menu->sym = sym;
menu->parent = current_menu;
menu->file = current_file;
menu->lineno = zconf_lineno();
*last_entry_ptr = menu;
last_entry_ptr = &menu->next;
current_entry = menu;
}
void menu_end_entry(void)
{
}
struct menu *menu_add_menu(void)
{
menu_end_entry();
last_entry_ptr = ¤t_entry->list;
return current_menu = current_entry;
}
void menu_end_menu(void)
{
last_entry_ptr = ¤t_menu->next;
current_menu = current_menu->parent;
}
struct expr *menu_check_dep(struct expr *e)
{
if (!e)
return e;
switch (e->type) {
case E_NOT:
e->left.expr = menu_check_dep(e->left.expr);
break;
case E_OR:
case E_AND:
e->left.expr = menu_check_dep(e->left.expr);
e->right.expr = menu_check_dep(e->right.expr);
break;
case E_SYMBOL:
/* change 'm' into 'm' && MODULES */
if (e->left.sym == &symbol_mod)
return expr_alloc_and(e, expr_alloc_symbol(modules_sym));
break;
default:
break;
}
return e;
}
void menu_add_dep(struct expr *dep)
{
current_entry->dep = expr_alloc_and(current_entry->dep, menu_check_dep(dep));
}
void menu_set_type(int type)
{
struct symbol *sym = current_entry->sym;
if (sym->type == type)
return;
if (sym->type == S_UNKNOWN) {
sym->type = type;
return;
}
menu_warn(current_entry, "type of '%s' redefined from '%s' to '%s'",
sym->name ? sym->name : "<choice>",
sym_type_name(sym->type), sym_type_name(type));
}
struct property *menu_add_prop(enum prop_type type, char *prompt, struct expr *expr, struct expr *dep)
{
struct property *prop = prop_alloc(type, current_entry->sym);
prop->menu = current_entry;
prop->expr = expr;
prop->visible.expr = menu_check_dep(dep);
if (prompt) {
if (isspace(*prompt)) {
prop_warn(prop, "leading whitespace ignored");
while (isspace(*prompt))
prompt++;
}
if (current_entry->prompt)
prop_warn(prop, "prompt redefined");
current_entry->prompt = prop;
}
prop->text = prompt;
return prop;
}
struct property *menu_add_prompt(enum prop_type type, char *prompt, struct expr *dep)
{
return menu_add_prop(type, prompt, NULL, dep);
}
void menu_add_expr(enum prop_type type, struct expr *expr, struct expr *dep)
{
menu_add_prop(type, NULL, expr, dep);
}
void menu_add_symbol(enum prop_type type, struct symbol *sym, struct expr *dep)
{
menu_add_prop(type, NULL, expr_alloc_symbol(sym), dep);
}
void menu_add_option(int token, char *arg)
{
struct property *prop;
switch (token) {
case T_OPT_MODULES:
prop = prop_alloc(P_DEFAULT, modules_sym);
prop->expr = expr_alloc_symbol(current_entry->sym);
break;
case T_OPT_DEFCONFIG_LIST:
if (!sym_defconfig_list)
sym_defconfig_list = current_entry->sym;
else if (sym_defconfig_list != current_entry->sym)
zconf_error("trying to redefine defconfig symbol");
break;
}
}
static int menu_range_valid_sym(struct symbol *sym, struct symbol *sym2)
{
return sym2->type == S_INT || sym2->type == S_HEX ||
(sym2->type == S_UNKNOWN && sym_string_valid(sym, sym2->name));
}
void sym_check_prop(struct symbol *sym)
{
struct property *prop;
struct symbol *sym2;
for (prop = sym->prop; prop; prop = prop->next) {
switch (prop->type) {
case P_DEFAULT:
if ((sym->type == S_STRING || sym->type == S_INT || sym->type == S_HEX) &&
prop->expr->type != E_SYMBOL)
prop_warn(prop,
"default for config symbol '%'"
" must be a single symbol", sym->name);
break;
case P_SELECT:
sym2 = prop_get_symbol(prop);
if (sym->type != S_BOOLEAN && sym->type != S_TRISTATE)
prop_warn(prop,
"config symbol '%s' uses select, but is "
"not boolean or tristate", sym->name);
else if (sym2->type == S_UNKNOWN)
prop_warn(prop,
"'select' used by config symbol '%s' "
"refers to undefined symbol '%s'",
sym->name, sym2->name);
else if (sym2->type != S_BOOLEAN && sym2->type != S_TRISTATE)
prop_warn(prop,
"'%s' has wrong type. 'select' only "
"accept arguments of boolean and "
"tristate type", sym2->name);
break;
case P_RANGE:
if (sym->type != S_INT && sym->type != S_HEX)
prop_warn(prop, "range is only allowed "
"for int or hex symbols");
if (!menu_range_valid_sym(sym, prop->expr->left.sym) ||
!menu_range_valid_sym(sym, prop->expr->right.sym))
prop_warn(prop, "range is invalid");
break;
default:
;
}
}
}
void menu_finalize(struct menu *parent)
{
struct menu *menu, *last_menu;
struct symbol *sym;
struct property *prop;
struct expr *parentdep, *basedep, *dep, *dep2, **ep;
sym = parent->sym;
if (parent->list) {
if (sym && sym_is_choice(sym)) {
/* find the first choice value and find out choice type */
for (menu = parent->list; menu; menu = menu->next) {
if (menu->sym) {
current_entry = parent;
menu_set_type(menu->sym->type);
current_entry = menu;
menu_set_type(sym->type);
break;
}
}
parentdep = expr_alloc_symbol(sym);
} else if (parent->prompt)
parentdep = parent->prompt->visible.expr;
else
parentdep = parent->dep;
for (menu = parent->list; menu; menu = menu->next) {
basedep = expr_transform(menu->dep);
basedep = expr_alloc_and(expr_copy(parentdep), basedep);
basedep = expr_eliminate_dups(basedep);
menu->dep = basedep;
if (menu->sym)
prop = menu->sym->prop;
else
prop = menu->prompt;
for (; prop; prop = prop->next) {
if (prop->menu != menu)
continue;
dep = expr_transform(prop->visible.expr);
dep = expr_alloc_and(expr_copy(basedep), dep);
dep = expr_eliminate_dups(dep);
if (menu->sym && menu->sym->type != S_TRISTATE)
dep = expr_trans_bool(dep);
prop->visible.expr = dep;
if (prop->type == P_SELECT) {
struct symbol *es = prop_get_symbol(prop);
es->rev_dep.expr = expr_alloc_or(es->rev_dep.expr,
expr_alloc_and(expr_alloc_symbol(menu->sym), expr_copy(dep)));
}
}
}
for (menu = parent->list; menu; menu = menu->next)
menu_finalize(menu);
} else if (sym) {
basedep = parent->prompt ? parent->prompt->visible.expr : NULL;
basedep = expr_trans_compare(basedep, E_UNEQUAL, &symbol_no);
basedep = expr_eliminate_dups(expr_transform(basedep));
last_menu = NULL;
for (menu = parent->next; menu; menu = menu->next) {
dep = menu->prompt ? menu->prompt->visible.expr : menu->dep;
if (!expr_contains_symbol(dep, sym))
break;
if (expr_depends_symbol(dep, sym))
goto next;
dep = expr_trans_compare(dep, E_UNEQUAL, &symbol_no);
dep = expr_eliminate_dups(expr_transform(dep));
dep2 = expr_copy(basedep);
expr_eliminate_eq(&dep, &dep2);
expr_free(dep);
if (!expr_is_yes(dep2)) {
expr_free(dep2);
break;
}
expr_free(dep2);
next:
menu_finalize(menu);
menu->parent = parent;
last_menu = menu;
}
if (last_menu) {
parent->list = parent->next;
parent->next = last_menu->next;
last_menu->next = NULL;
}
}
for (menu = parent->list; menu; menu = menu->next) {
if (sym && sym_is_choice(sym) && menu->sym) {
menu->sym->flags |= SYMBOL_CHOICEVAL;
if (!menu->prompt)
menu_warn(menu, "choice value must have a prompt");
for (prop = menu->sym->prop; prop; prop = prop->next) {
if (prop->type == P_PROMPT && prop->menu != menu) {
prop_warn(prop, "choice values "
"currently only support a "
"single prompt");
}
if (prop->type == P_DEFAULT)
prop_warn(prop, "defaults for choice "
"values not supported");
}
current_entry = menu;
menu_set_type(sym->type);
menu_add_symbol(P_CHOICE, sym, NULL);
prop = sym_get_choice_prop(sym);
for (ep = &prop->expr; *ep; ep = &(*ep)->left.expr)
;
*ep = expr_alloc_one(E_CHOICE, NULL);
(*ep)->right.sym = menu->sym;
}
if (menu->list && (!menu->prompt || !menu->prompt->text)) {
for (last_menu = menu->list; ; last_menu = last_menu->next) {
last_menu->parent = parent;
if (!last_menu->next)
break;
}
last_menu->next = menu->next;
menu->next = menu->list;
menu->list = NULL;
}
}
if (sym && !(sym->flags & SYMBOL_WARNED)) {
if (sym->type == S_UNKNOWN)
menu_warn(parent, "config symbol defined without type");
if (sym_is_choice(sym) && !parent->prompt)
menu_warn(parent, "choice must have a prompt");
/* Check properties connected to this symbol */
sym_check_prop(sym);
sym->flags |= SYMBOL_WARNED;
}
if (sym && !sym_is_optional(sym) && parent->prompt) {
sym->rev_dep.expr = expr_alloc_or(sym->rev_dep.expr,
expr_alloc_and(parent->prompt->visible.expr,
expr_alloc_symbol(&symbol_mod)));
}
}
bool menu_is_visible(struct menu *menu)
{
struct menu *child;
struct symbol *sym;
tristate visible;
if (!menu->prompt)
return false;
sym = menu->sym;
if (sym) {
sym_calc_value(sym);
visible = menu->prompt->visible.tri;
} else
visible = menu->prompt->visible.tri = expr_calc_value(menu->prompt->visible.expr);
if (visible != no)
return true;
if (!sym || sym_get_tristate_value(menu->sym) == no)
return false;
for (child = menu->list; child; child = child->next)
if (menu_is_visible(child))
return true;
return false;
}
const char *menu_get_prompt(struct menu *menu)
{
if (menu->prompt)
return _(menu->prompt->text);
else if (menu->sym)
return _(menu->sym->name);
return NULL;
}
struct menu *menu_get_root_menu(struct menu *menu)
{
return &rootmenu;
}
struct menu *menu_get_parent_menu(struct menu *menu)
{
enum prop_type type;
for (; menu != &rootmenu; menu = menu->parent) {
type = menu->prompt ? menu->prompt->type : 0;
if (type == P_MENU)
break;
}
return menu;
}
| gpl-2.0 |
akw28888/caf2 | drivers/misc/inv_mpu/accel/mma8450.c | 21949 | /*
$License:
Copyright (C) 2011 InvenSense Corporation, All Rights Reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
$
*/
/**
* @addtogroup ACCELDL
* @brief Provides the interface to setup and handle an accelerometer.
*
* @{
* @file mma8450.c
* @brief Accelerometer setup and handling methods for Freescale MMA8450.
*/
/* -------------------------------------------------------------------------- */
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include "mpu-dev.h"
#include <log.h>
#include <linux/mpu.h>
#include "mlsl.h"
#include "mldl_cfg.h"
#undef MPL_LOG_TAG
#define MPL_LOG_TAG "MPL-acc"
/* full scale setting - register & mask */
#define ACCEL_MMA8450_XYZ_DATA_CFG (0x16)
#define ACCEL_MMA8450_CTRL_REG1 (0x38)
#define ACCEL_MMA8450_CTRL_REG2 (0x39)
#define ACCEL_MMA8450_CTRL_REG4 (0x3B)
#define ACCEL_MMA8450_CTRL_REG5 (0x3C)
#define ACCEL_MMA8450_CTRL_REG (0x38)
#define ACCEL_MMA8450_CTRL_MASK (0x03)
#define ACCEL_MMA8450_SLEEP_MASK (0x03)
/* -------------------------------------------------------------------------- */
struct mma8450_config {
unsigned int odr;
unsigned int fsr; /** < full scale range mg */
unsigned int ths; /** < Motion no-motion thseshold mg */
unsigned int dur; /** < Motion no-motion duration ms */
unsigned char reg_ths;
unsigned char reg_dur;
unsigned char ctrl_reg1;
unsigned char irq_type;
unsigned char mot_int1_cfg;
};
struct mma8450_private_data {
struct mma8450_config suspend;
struct mma8450_config resume;
};
/* -------------------------------------------------------------------------- */
static int mma8450_set_ths(void *mlsl_handle,
struct ext_slave_platform_data *pdata,
struct mma8450_config *config,
int apply,
long ths)
{
return INV_ERROR_FEATURE_NOT_IMPLEMENTED;
}
static int mma8450_set_dur(void *mlsl_handle,
struct ext_slave_platform_data *pdata,
struct mma8450_config *config,
int apply,
long dur)
{
return INV_ERROR_FEATURE_NOT_IMPLEMENTED;
}
/**
* @brief Sets the IRQ to fire when one of the IRQ events occur.
* Threshold and duration will not be used unless the type is MOT or
* NMOT.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param pdata
* a pointer to the slave platform data.
* @param config
* configuration to apply to, suspend or resume
* @param apply
* whether to apply immediately or save the settings to be applied
* at the next resume.
* @param irq_type
* the type of IRQ. Valid values are
* - MPU_SLAVE_IRQ_TYPE_NONE
* - MPU_SLAVE_IRQ_TYPE_MOTION
* - MPU_SLAVE_IRQ_TYPE_DATA_READY
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_set_irq(void *mlsl_handle,
struct ext_slave_platform_data *pdata,
struct mma8450_config *config,
int apply,
long irq_type)
{
int result = INV_SUCCESS;
unsigned char reg1;
unsigned char reg2;
unsigned char reg3;
config->irq_type = (unsigned char)irq_type;
if (irq_type == MPU_SLAVE_IRQ_TYPE_DATA_READY) {
reg1 = 0x01;
reg2 = 0x01;
reg3 = 0x07;
} else if (irq_type == MPU_SLAVE_IRQ_TYPE_NONE) {
reg1 = 0x00;
reg2 = 0x00;
reg3 = 0x00;
} else {
return INV_ERROR_FEATURE_NOT_IMPLEMENTED;
}
if (apply) {
/* XYZ_DATA_CFG: event flag enabled on Z axis */
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_XYZ_DATA_CFG, reg3);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG4, reg1);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG5, reg2);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
}
return result;
}
/**
* @brief Set the output data rate for the particular configuration.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param pdata
* a pointer to the slave platform data.
* @param config
* Config to modify with new ODR.
* @param apply
* whether to apply immediately or save the settings to be applied
* at the next resume.
* @param odr
* Output data rate in units of 1/1000Hz (mHz).
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_set_odr(void *mlsl_handle,
struct ext_slave_platform_data *pdata,
struct mma8450_config *config,
int apply,
long odr)
{
unsigned char bits;
int result = INV_SUCCESS;
if (odr > 200000) {
config->odr = 400000;
bits = 0x00;
} else if (odr > 100000) {
config->odr = 200000;
bits = 0x04;
} else if (odr > 50000) {
config->odr = 100000;
bits = 0x08;
} else if (odr > 25000) {
config->odr = 50000;
bits = 0x0C;
} else if (odr > 12500) {
config->odr = 25000;
bits = 0x40; /* Sleep -> Auto wake mode */
} else if (odr > 1563) {
config->odr = 12500;
bits = 0x10;
} else if (odr > 0) {
config->odr = 1563;
bits = 0x14;
} else {
config->ctrl_reg1 = 0; /* Set FS1.FS2 to Standby */
config->odr = 0;
bits = 0;
}
config->ctrl_reg1 = bits | (config->ctrl_reg1 & 0x3);
if (apply) {
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1, 0);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
MPL_LOGV("ODR: %d mHz, 0x%02x\n",
config->odr, (int)config->ctrl_reg1);
}
return result;
}
/**
* @brief Set the full scale range of the accels
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param pdata
* a pointer to the slave platform data.
* @param config
* pointer to configuration.
* @param apply
* whether to apply immediately or save the settings to be applied
* at the next resume.
* @param fsr
* requested full scale range.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_set_fsr(void *mlsl_handle,
struct ext_slave_platform_data *pdata,
struct mma8450_config *config,
int apply,
long fsr)
{
unsigned char bits;
int result = INV_SUCCESS;
if (fsr <= 2000) {
bits = 0x01;
config->fsr = 2000;
} else if (fsr <= 4000) {
bits = 0x02;
config->fsr = 4000;
} else {
bits = 0x03;
config->fsr = 8000;
}
config->ctrl_reg1 = bits | (config->ctrl_reg1 & 0xFC);
if (apply) {
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1, config->ctrl_reg1);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
MPL_LOGV("FSR: %d mg\n", config->fsr);
}
return result;
}
/**
* @brief suspends the device to put it in its lowest power mode.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_suspend(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
int result;
struct mma8450_private_data *private_data = pdata->private_data;
if (private_data->suspend.fsr == 4000)
slave->range.mantissa = 4;
else if (private_data->suspend.fsr == 8000)
slave->range.mantissa = 8;
else
slave->range.mantissa = 2;
slave->range.fraction = 0;
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1, 0);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
if (private_data->suspend.ctrl_reg1) {
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1,
private_data->suspend.ctrl_reg1);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
}
result = mma8450_set_irq(mlsl_handle, pdata,
&private_data->suspend,
true, private_data->suspend.irq_type);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
return result;
}
/**
* @brief resume the device in the proper power state given the configuration
* chosen.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_resume(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
int result = INV_SUCCESS;
struct mma8450_private_data *private_data = pdata->private_data;
/* Full Scale */
if (private_data->resume.fsr == 4000)
slave->range.mantissa = 4;
else if (private_data->resume.fsr == 8000)
slave->range.mantissa = 8;
else
slave->range.mantissa = 2;
slave->range.fraction = 0;
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1, 0);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
if (private_data->resume.ctrl_reg1) {
result = inv_serial_single_write(mlsl_handle, pdata->address,
ACCEL_MMA8450_CTRL_REG1,
private_data->resume.ctrl_reg1);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
}
result = mma8450_set_irq(mlsl_handle, pdata,
&private_data->resume,
true, private_data->resume.irq_type);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
return result;
}
/**
* @brief read the sensor data from the device.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
* @param data
* a buffer to store the data read.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_read(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata, unsigned char *data)
{
int result;
unsigned char local_data[4]; /* Status register + 3 bytes data */
result = inv_serial_read(mlsl_handle, pdata->address,
0x00, sizeof(local_data), local_data);
if (result) {
LOG_RESULT_LOCATION(result);
return result;
}
memcpy(data, &local_data[1], (slave->read_len) - 1);
MPL_LOGV("Data Not Ready: %02x %02x %02x %02x\n",
local_data[0], local_data[1],
local_data[2], local_data[3]);
return result;
}
/**
* @brief one-time device driver initialization function.
* If the driver is built as a kernel module, this function will be
* called when the module is loaded in the kernel.
* If the driver is built-in in the kernel, this function will be
* called at boot time.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_init(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
struct mma8450_private_data *private_data;
private_data = (struct mma8450_private_data *)
kzalloc(sizeof(struct mma8450_private_data), GFP_KERNEL);
if (!private_data)
return INV_ERROR_MEMORY_EXAUSTED;
pdata->private_data = private_data;
mma8450_set_odr(mlsl_handle, pdata, &private_data->suspend,
false, 0);
mma8450_set_odr(mlsl_handle, pdata, &private_data->resume,
false, 200000);
mma8450_set_fsr(mlsl_handle, pdata, &private_data->suspend,
false, 2000);
mma8450_set_fsr(mlsl_handle, pdata, &private_data->resume,
false, 2000);
mma8450_set_irq(mlsl_handle, pdata, &private_data->suspend,
false,
MPU_SLAVE_IRQ_TYPE_NONE);
mma8450_set_irq(mlsl_handle, pdata, &private_data->resume,
false,
MPU_SLAVE_IRQ_TYPE_NONE);
return INV_SUCCESS;
}
/**
* @brief one-time device driver exit function.
* If the driver is built as a kernel module, this function will be
* called when the module is removed from the kernel.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_exit(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata)
{
kfree(pdata->private_data);
return INV_SUCCESS;
}
/**
* @brief device configuration facility.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
* @param data
* a pointer to the configuration data structure.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_config(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata,
struct ext_slave_config *data)
{
struct mma8450_private_data *private_data = pdata->private_data;
if (!data->data)
return INV_ERROR_INVALID_PARAMETER;
switch (data->key) {
case MPU_SLAVE_CONFIG_ODR_SUSPEND:
return mma8450_set_odr(mlsl_handle, pdata,
&private_data->suspend,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_ODR_RESUME:
return mma8450_set_odr(mlsl_handle, pdata,
&private_data->resume,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_FSR_SUSPEND:
return mma8450_set_fsr(mlsl_handle, pdata,
&private_data->suspend,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_FSR_RESUME:
return mma8450_set_fsr(mlsl_handle, pdata,
&private_data->resume,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_MOT_THS:
return mma8450_set_ths(mlsl_handle, pdata,
&private_data->suspend,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_NMOT_THS:
return mma8450_set_ths(mlsl_handle, pdata,
&private_data->resume,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_MOT_DUR:
return mma8450_set_dur(mlsl_handle, pdata,
&private_data->suspend,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_NMOT_DUR:
return mma8450_set_dur(mlsl_handle, pdata,
&private_data->resume,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_IRQ_SUSPEND:
return mma8450_set_irq(mlsl_handle, pdata,
&private_data->suspend,
data->apply,
*((long *)data->data));
case MPU_SLAVE_CONFIG_IRQ_RESUME:
return mma8450_set_irq(mlsl_handle, pdata,
&private_data->resume,
data->apply,
*((long *)data->data));
default:
LOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED);
return INV_ERROR_FEATURE_NOT_IMPLEMENTED;
};
return INV_SUCCESS;
}
/**
* @brief facility to retrieve the device configuration.
*
* @param mlsl_handle
* the handle to the serial channel the device is connected to.
* @param slave
* a pointer to the slave descriptor data structure.
* @param pdata
* a pointer to the slave platform data.
* @param data
* a pointer to store the returned configuration data structure.
*
* @return INV_SUCCESS if successful or a non-zero error code.
*/
static int mma8450_get_config(void *mlsl_handle,
struct ext_slave_descr *slave,
struct ext_slave_platform_data *pdata,
struct ext_slave_config *data)
{
struct mma8450_private_data *private_data = pdata->private_data;
if (!data->data)
return INV_ERROR_INVALID_PARAMETER;
switch (data->key) {
case MPU_SLAVE_CONFIG_ODR_SUSPEND:
(*(unsigned long *)data->data) =
(unsigned long) private_data->suspend.odr;
break;
case MPU_SLAVE_CONFIG_ODR_RESUME:
(*(unsigned long *)data->data) =
(unsigned long) private_data->resume.odr;
break;
case MPU_SLAVE_CONFIG_FSR_SUSPEND:
(*(unsigned long *)data->data) =
(unsigned long) private_data->suspend.fsr;
break;
case MPU_SLAVE_CONFIG_FSR_RESUME:
(*(unsigned long *)data->data) =
(unsigned long) private_data->resume.fsr;
break;
case MPU_SLAVE_CONFIG_MOT_THS:
(*(unsigned long *)data->data) =
(unsigned long) private_data->suspend.ths;
break;
case MPU_SLAVE_CONFIG_NMOT_THS:
(*(unsigned long *)data->data) =
(unsigned long) private_data->resume.ths;
break;
case MPU_SLAVE_CONFIG_MOT_DUR:
(*(unsigned long *)data->data) =
(unsigned long) private_data->suspend.dur;
break;
case MPU_SLAVE_CONFIG_NMOT_DUR:
(*(unsigned long *)data->data) =
(unsigned long) private_data->resume.dur;
break;
case MPU_SLAVE_CONFIG_IRQ_SUSPEND:
(*(unsigned long *)data->data) =
(unsigned long) private_data->suspend.irq_type;
break;
case MPU_SLAVE_CONFIG_IRQ_RESUME:
(*(unsigned long *)data->data) =
(unsigned long) private_data->resume.irq_type;
break;
default:
LOG_RESULT_LOCATION(INV_ERROR_FEATURE_NOT_IMPLEMENTED);
return INV_ERROR_FEATURE_NOT_IMPLEMENTED;
};
return INV_SUCCESS;
}
static struct ext_slave_descr mma8450_descr = {
.init = mma8450_init,
.exit = mma8450_exit,
.suspend = mma8450_suspend,
.resume = mma8450_resume,
.read = mma8450_read,
.config = mma8450_config,
.get_config = mma8450_get_config,
.name = "mma8450",
.type = EXT_SLAVE_TYPE_ACCEL,
.id = ACCEL_ID_MMA8450,
.read_reg = 0x00,
.read_len = 4,
.endian = EXT_SLAVE_FS8_BIG_ENDIAN,
.range = {2, 0},
.trigger = NULL,
};
static
struct ext_slave_descr *mma8450_get_slave_descr(void)
{
return &mma8450_descr;
}
/* -------------------------------------------------------------------------- */
struct mma8450_mod_private_data {
struct i2c_client *client;
struct ext_slave_platform_data *pdata;
};
static unsigned short normal_i2c[] = { I2C_CLIENT_END };
static int mma8450_mod_probe(struct i2c_client *client,
const struct i2c_device_id *devid)
{
struct ext_slave_platform_data *pdata;
struct mma8450_mod_private_data *private_data;
int result = 0;
dev_info(&client->adapter->dev, "%s: %s\n", __func__, devid->name);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
result = -ENODEV;
goto out_no_free;
}
pdata = client->dev.platform_data;
if (!pdata) {
dev_err(&client->adapter->dev,
"Missing platform data for slave %s\n", devid->name);
result = -EFAULT;
goto out_no_free;
}
private_data = kzalloc(sizeof(*private_data), GFP_KERNEL);
if (!private_data) {
result = -ENOMEM;
goto out_no_free;
}
i2c_set_clientdata(client, private_data);
private_data->client = client;
private_data->pdata = pdata;
result = inv_mpu_register_slave(THIS_MODULE, client, pdata,
mma8450_get_slave_descr);
if (result) {
dev_err(&client->adapter->dev,
"Slave registration failed: %s, %d\n",
devid->name, result);
goto out_free_memory;
}
return result;
out_free_memory:
kfree(private_data);
out_no_free:
dev_err(&client->adapter->dev, "%s failed %d\n", __func__, result);
return result;
}
static int mma8450_mod_remove(struct i2c_client *client)
{
struct mma8450_mod_private_data *private_data =
i2c_get_clientdata(client);
dev_dbg(&client->adapter->dev, "%s\n", __func__);
inv_mpu_unregister_slave(client, private_data->pdata,
mma8450_get_slave_descr);
kfree(private_data);
return 0;
}
static const struct i2c_device_id mma8450_mod_id[] = {
{ "mma8450", ACCEL_ID_MMA8450 },
{}
};
MODULE_DEVICE_TABLE(i2c, mma8450_mod_id);
static struct i2c_driver mma8450_mod_driver = {
.class = I2C_CLASS_HWMON,
.probe = mma8450_mod_probe,
.remove = mma8450_mod_remove,
.id_table = mma8450_mod_id,
.driver = {
.owner = THIS_MODULE,
.name = "mma8450_mod",
},
.address_list = normal_i2c,
};
static int __init mma8450_mod_init(void)
{
int res = i2c_add_driver(&mma8450_mod_driver);
pr_info("%s: Probe name %s\n", __func__, "mma8450_mod");
if (res)
pr_err("%s failed\n", __func__);
return res;
}
static void __exit mma8450_mod_exit(void)
{
pr_info("%s\n", __func__);
i2c_del_driver(&mma8450_mod_driver);
}
module_init(mma8450_mod_init);
module_exit(mma8450_mod_exit);
MODULE_AUTHOR("Invensense Corporation");
MODULE_DESCRIPTION("Driver to integrate MMA8450 sensor with the MPU");
MODULE_LICENSE("GPL");
MODULE_ALIAS("mma8450_mod");
/**
* @}
*/
| gpl-2.0 |
zero-ui/miniblink49 | third_party/skia/third_party/libpng/pngprefix.h | 22924 | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
* This file was created in part using the configuration script provided with
* the libpng sources. However it was missing some symbols which caused the
* linker to fail so those were added manually by scanning the library looking
* for exported symbols missing the skia_ prefix and adding them to the end of
* this file.
*
* ./third_party/externals/libpng/configure --with-libpng-prefix=skia_
*/
#define png_sRGB_table skia_png_sRGB_table
#define png_sRGB_base skia_png_sRGB_base
#define png_sRGB_delta skia_png_sRGB_delta
#define png_zstream_error skia_png_zstream_error
#define png_free_buffer_list skia_png_free_buffer_list
#define png_fixed skia_png_fixed
#define png_user_version_check skia_png_user_version_check
#define png_malloc_base skia_png_malloc_base
#define png_malloc_array skia_png_malloc_array
#define png_realloc_array skia_png_realloc_array
#define png_create_png_struct skia_png_create_png_struct
#define png_destroy_png_struct skia_png_destroy_png_struct
#define png_free_jmpbuf skia_png_free_jmpbuf
#define png_zalloc skia_png_zalloc
#define png_zfree skia_png_zfree
#define png_default_read_data skia_png_default_read_data
#define png_push_fill_buffer skia_png_push_fill_buffer
#define png_default_write_data skia_png_default_write_data
#define png_default_flush skia_png_default_flush
#define png_reset_crc skia_png_reset_crc
#define png_write_data skia_png_write_data
#define png_read_sig skia_png_read_sig
#define png_read_chunk_header skia_png_read_chunk_header
#define png_read_data skia_png_read_data
#define png_crc_read skia_png_crc_read
#define png_crc_finish skia_png_crc_finish
#define png_crc_error skia_png_crc_error
#define png_calculate_crc skia_png_calculate_crc
#define png_flush skia_png_flush
#define png_write_IHDR skia_png_write_IHDR
#define png_write_PLTE skia_png_write_PLTE
#define png_compress_IDAT skia_png_compress_IDAT
#define png_write_IEND skia_png_write_IEND
#define png_write_gAMA_fixed skia_png_write_gAMA_fixed
#define png_write_sBIT skia_png_write_sBIT
#define png_write_cHRM_fixed skia_png_write_cHRM_fixed
#define png_write_sRGB skia_png_write_sRGB
#define png_write_iCCP skia_png_write_iCCP
#define png_write_sPLT skia_png_write_sPLT
#define png_write_tRNS skia_png_write_tRNS
#define png_write_bKGD skia_png_write_bKGD
#define png_write_hIST skia_png_write_hIST
#define png_write_tEXt skia_png_write_tEXt
#define png_write_zTXt skia_png_write_zTXt
#define png_write_iTXt skia_png_write_iTXt
#define png_set_text_2 skia_png_set_text_2
#define png_write_oFFs skia_png_write_oFFs
#define png_write_pCAL skia_png_write_pCAL
#define png_write_pHYs skia_png_write_pHYs
#define png_write_tIME skia_png_write_tIME
#define png_write_sCAL_s skia_png_write_sCAL_s
#define png_write_finish_row skia_png_write_finish_row
#define png_write_start_row skia_png_write_start_row
#define png_combine_row skia_png_combine_row
#define png_do_read_interlace skia_png_do_read_interlace
#define png_do_write_interlace skia_png_do_write_interlace
#define png_read_filter_row skia_png_read_filter_row
#define png_read_filter_row_up_neon skia_png_read_filter_row_up_neon
#define png_read_filter_row_sub3_neon skia_png_read_filter_row_sub3_neon
#define png_read_filter_row_sub4_neon skia_png_read_filter_row_sub4_neon
#define png_read_filter_row_avg3_neon skia_png_read_filter_row_avg3_neon
#define png_read_filter_row_avg4_neon skia_png_read_filter_row_avg4_neon
#define png_read_filter_row_paeth3_neon skia_png_read_filter_row_paeth3_neon
#define png_read_filter_row_paeth4_neon skia_png_read_filter_row_paeth4_neon
#define png_write_find_filter skia_png_write_find_filter
#define png_read_IDAT_data skia_png_read_IDAT_data
#define png_read_finish_IDAT skia_png_read_finish_IDAT
#define png_read_finish_row skia_png_read_finish_row
#define png_read_start_row skia_png_read_start_row
#define png_read_transform_info skia_png_read_transform_info
#define png_do_read_filler skia_png_do_read_filler
#define png_do_read_swap_alpha skia_png_do_read_swap_alpha
#define png_do_write_swap_alpha skia_png_do_write_swap_alpha
#define png_do_read_invert_alpha skia_png_do_read_invert_alpha
#define png_do_write_invert_alpha skia_png_do_write_invert_alpha
#define png_do_strip_channel skia_png_do_strip_channel
#define png_do_swap skia_png_do_swap
#define png_do_packswap skia_png_do_packswap
#define png_do_rgb_to_gray skia_png_do_rgb_to_gray
#define png_do_gray_to_rgb skia_png_do_gray_to_rgb
#define png_do_unpack skia_png_do_unpack
#define png_do_unshift skia_png_do_unshift
#define png_do_invert skia_png_do_invert
#define png_do_scale_16_to_8 skia_png_do_scale_16_to_8
#define png_do_chop skia_png_do_chop
#define png_do_quantize skia_png_do_quantize
#define png_do_bgr skia_png_do_bgr
#define png_do_pack skia_png_do_pack
#define png_do_shift skia_png_do_shift
#define png_do_compose skia_png_do_compose
#define png_do_gamma skia_png_do_gamma
#define png_do_encode_alpha skia_png_do_encode_alpha
#define png_do_expand_palette skia_png_do_expand_palette
#define png_do_expand skia_png_do_expand
#define png_do_expand_16 skia_png_do_expand_16
#define png_handle_IHDR skia_png_handle_IHDR
#define png_handle_PLTE skia_png_handle_PLTE
#define png_handle_IEND skia_png_handle_IEND
#define png_handle_bKGD skia_png_handle_bKGD
#define png_handle_cHRM skia_png_handle_cHRM
#define png_handle_gAMA skia_png_handle_gAMA
#define png_handle_hIST skia_png_handle_hIST
#define png_handle_iCCP skia_png_handle_iCCP
#define png_handle_iTXt skia_png_handle_iTXt
#define png_handle_oFFs skia_png_handle_oFFs
#define png_handle_pCAL skia_png_handle_pCAL
#define png_handle_pHYs skia_png_handle_pHYs
#define png_handle_sBIT skia_png_handle_sBIT
#define png_handle_sCAL skia_png_handle_sCAL
#define png_handle_sPLT skia_png_handle_sPLT
#define png_handle_sRGB skia_png_handle_sRGB
#define png_handle_tEXt skia_png_handle_tEXt
#define png_handle_tIME skia_png_handle_tIME
#define png_handle_tRNS skia_png_handle_tRNS
#define png_handle_zTXt skia_png_handle_zTXt
#define png_check_chunk_name skia_png_check_chunk_name
#define png_handle_unknown skia_png_handle_unknown
#define png_chunk_unknown_handling skia_png_chunk_unknown_handling
#define png_do_read_transformations skia_png_do_read_transformations
#define png_do_write_transformations skia_png_do_write_transformations
#define png_init_read_transformations skia_png_init_read_transformations
#define png_push_read_chunk skia_png_push_read_chunk
#define png_push_read_sig skia_png_push_read_sig
#define png_push_check_crc skia_png_push_check_crc
#define png_push_crc_skip skia_png_push_crc_skip
#define png_push_crc_finish skia_png_push_crc_finish
#define png_push_save_buffer skia_png_push_save_buffer
#define png_push_restore_buffer skia_png_push_restore_buffer
#define png_push_read_IDAT skia_png_push_read_IDAT
#define png_process_IDAT_data skia_png_process_IDAT_data
#define png_push_process_row skia_png_push_process_row
#define png_push_handle_unknown skia_png_push_handle_unknown
#define png_push_have_info skia_png_push_have_info
#define png_push_have_end skia_png_push_have_end
#define png_push_have_row skia_png_push_have_row
#define png_push_read_end skia_png_push_read_end
#define png_process_some_data skia_png_process_some_data
#define png_read_push_finish_row skia_png_read_push_finish_row
#define png_push_handle_tEXt skia_png_push_handle_tEXt
#define png_push_read_tEXt skia_png_push_read_tEXt
#define png_push_handle_zTXt skia_png_push_handle_zTXt
#define png_push_read_zTXt skia_png_push_read_zTXt
#define png_push_handle_iTXt skia_png_push_handle_iTXt
#define png_push_read_iTXt skia_png_push_read_iTXt
#define png_do_read_intrapixel skia_png_do_read_intrapixel
#define png_do_write_intrapixel skia_png_do_write_intrapixel
#define png_colorspace_set_gamma skia_png_colorspace_set_gamma
#define png_colorspace_sync_info skia_png_colorspace_sync_info
#define png_colorspace_sync skia_png_colorspace_sync
#define png_colorspace_set_chromaticities skia_png_colorspace_set_chromaticities
#define png_colorspace_set_endpoints skia_png_colorspace_set_endpoints
#define png_colorspace_set_sRGB skia_png_colorspace_set_sRGB
#define png_colorspace_set_ICC skia_png_colorspace_set_ICC
#define png_icc_check_length skia_png_icc_check_length
#define png_icc_check_header skia_png_icc_check_header
#define png_icc_check_tag_table skia_png_icc_check_tag_table
#define png_icc_set_sRGB skia_png_icc_set_sRGB
#define png_colorspace_set_rgb_coefficients skia_png_colorspace_set_rgb_coefficients
#define png_check_IHDR skia_png_check_IHDR
#define png_do_check_palette_indexes skia_png_do_check_palette_indexes
#define png_fixed_error skia_png_fixed_error
#define png_safecat skia_png_safecat
#define png_format_number skia_png_format_number
#define png_warning_parameter skia_png_warning_parameter
#define png_warning_parameter_unsigned skia_png_warning_parameter_unsigned
#define png_warning_parameter_signed skia_png_warning_parameter_signed
#define png_formatted_warning skia_png_formatted_warning
#define png_app_warning skia_png_app_warning
#define png_app_error skia_png_app_error
#define png_chunk_report skia_png_chunk_report
#define png_ascii_from_fp skia_png_ascii_from_fp
#define png_ascii_from_fixed skia_png_ascii_from_fixed
#define png_check_fp_number skia_png_check_fp_number
#define png_check_fp_string skia_png_check_fp_string
#define png_muldiv skia_png_muldiv
#define png_muldiv_warn skia_png_muldiv_warn
#define png_reciprocal skia_png_reciprocal
#define png_reciprocal2 skia_png_reciprocal2
#define png_gamma_significant skia_png_gamma_significant
#define png_gamma_correct skia_png_gamma_correct
#define png_gamma_16bit_correct skia_png_gamma_16bit_correct
#define png_gamma_8bit_correct skia_png_gamma_8bit_correct
#define png_destroy_gamma_table skia_png_destroy_gamma_table
#define png_build_gamma_table skia_png_build_gamma_table
#define png_safe_error skia_png_safe_error
#define png_safe_warning skia_png_safe_warning
#define png_safe_execute skia_png_safe_execute
#define png_image_error skia_png_image_error
#define png_access_version_number skia_png_access_version_number
#define png_build_grayscale_palette skia_png_build_grayscale_palette
#define png_convert_to_rfc1123 skia_png_convert_to_rfc1123
#define png_convert_to_rfc1123_buffer skia_png_convert_to_rfc1123_buffer
#define png_create_info_struct skia_png_create_info_struct
#define png_data_freer skia_png_data_freer
#define png_destroy_info_struct skia_png_destroy_info_struct
#define png_free_data skia_png_free_data
#define png_get_copyright skia_png_get_copyright
#define png_get_header_ver skia_png_get_header_ver
#define png_get_header_version skia_png_get_header_version
#define png_get_io_ptr skia_png_get_io_ptr
#define png_get_libpng_ver skia_png_get_libpng_ver
#define png_handle_as_unknown skia_png_handle_as_unknown
#define png_image_free skia_png_image_free
#define png_info_init_3 skia_png_info_init_3
#define png_init_io skia_png_init_io
#define png_reset_zstream skia_png_reset_zstream
#define png_save_int_32 skia_png_save_int_32
#define png_set_option skia_png_set_option
#define png_set_sig_bytes skia_png_set_sig_bytes
#define png_sig_cmp skia_png_sig_cmp
#define png_benign_error skia_png_benign_error
#define png_chunk_benign_error skia_png_chunk_benign_error
#define png_chunk_error skia_png_chunk_error
#define png_chunk_warning skia_png_chunk_warning
#define png_error skia_png_error
#define png_get_error_ptr skia_png_get_error_ptr
#define png_longjmp skia_png_longjmp
#define png_set_error_fn skia_png_set_error_fn
#define png_set_longjmp_fn skia_png_set_longjmp_fn
#define png_warning skia_png_warning
#define png_get_bit_depth skia_png_get_bit_depth
#define png_get_bKGD skia_png_get_bKGD
#define png_get_channels skia_png_get_channels
#define png_get_cHRM skia_png_get_cHRM
#define png_get_cHRM_fixed skia_png_get_cHRM_fixed
#define png_get_cHRM_XYZ skia_png_get_cHRM_XYZ
#define png_get_cHRM_XYZ_fixed skia_png_get_cHRM_XYZ_fixed
#define png_get_chunk_cache_max skia_png_get_chunk_cache_max
#define png_get_chunk_malloc_max skia_png_get_chunk_malloc_max
#define png_get_color_type skia_png_get_color_type
#define png_get_compression_buffer_size skia_png_get_compression_buffer_size
#define png_get_compression_type skia_png_get_compression_type
#define png_get_filter_type skia_png_get_filter_type
#define png_get_gAMA skia_png_get_gAMA
#define png_get_gAMA_fixed skia_png_get_gAMA_fixed
#define png_get_hIST skia_png_get_hIST
#define png_get_iCCP skia_png_get_iCCP
#define png_get_IHDR skia_png_get_IHDR
#define png_get_image_height skia_png_get_image_height
#define png_get_image_width skia_png_get_image_width
#define png_get_interlace_type skia_png_get_interlace_type
#define png_get_io_chunk_type skia_png_get_io_chunk_type
#define png_get_io_state skia_png_get_io_state
#define png_get_oFFs skia_png_get_oFFs
#define png_get_palette_max skia_png_get_palette_max
#define png_get_pCAL skia_png_get_pCAL
#define png_get_pHYs skia_png_get_pHYs
#define png_get_pHYs_dpi skia_png_get_pHYs_dpi
#define png_get_pixel_aspect_ratio skia_png_get_pixel_aspect_ratio
#define png_get_pixel_aspect_ratio_fixed skia_png_get_pixel_aspect_ratio_fixed
#define png_get_pixels_per_inch skia_png_get_pixels_per_inch
#define png_get_pixels_per_meter skia_png_get_pixels_per_meter
#define png_get_PLTE skia_png_get_PLTE
#define png_get_rgb_to_gray_status skia_png_get_rgb_to_gray_status
#define png_get_rowbytes skia_png_get_rowbytes
#define png_get_rows skia_png_get_rows
#define png_get_sBIT skia_png_get_sBIT
#define png_get_sCAL skia_png_get_sCAL
#define png_get_sCAL_fixed skia_png_get_sCAL_fixed
#define png_get_sCAL_s skia_png_get_sCAL_s
#define png_get_signature skia_png_get_signature
#define png_get_sPLT skia_png_get_sPLT
#define png_get_sRGB skia_png_get_sRGB
#define png_get_text skia_png_get_text
#define png_get_tIME skia_png_get_tIME
#define png_get_tRNS skia_png_get_tRNS
#define png_get_unknown_chunks skia_png_get_unknown_chunks
#define png_get_user_chunk_ptr skia_png_get_user_chunk_ptr
#define png_get_user_height_max skia_png_get_user_height_max
#define png_get_user_width_max skia_png_get_user_width_max
#define png_get_valid skia_png_get_valid
#define png_get_x_offset_inches skia_png_get_x_offset_inches
#define png_get_x_offset_inches_fixed skia_png_get_x_offset_inches_fixed
#define png_get_x_offset_microns skia_png_get_x_offset_microns
#define png_get_x_offset_pixels skia_png_get_x_offset_pixels
#define png_get_x_pixels_per_inch skia_png_get_x_pixels_per_inch
#define png_get_x_pixels_per_meter skia_png_get_x_pixels_per_meter
#define png_get_y_offset_inches skia_png_get_y_offset_inches
#define png_get_y_offset_inches_fixed skia_png_get_y_offset_inches_fixed
#define png_get_y_offset_microns skia_png_get_y_offset_microns
#define png_get_y_offset_pixels skia_png_get_y_offset_pixels
#define png_get_y_pixels_per_inch skia_png_get_y_pixels_per_inch
#define png_get_y_pixels_per_meter skia_png_get_y_pixels_per_meter
#define png_calloc skia_png_calloc
#define png_free skia_png_free
#define png_free_default skia_png_free_default
#define png_get_mem_ptr skia_png_get_mem_ptr
#define png_malloc skia_png_malloc
#define png_malloc_default skia_png_malloc_default
#define png_malloc_warn skia_png_malloc_warn
#define png_set_mem_fn skia_png_set_mem_fn
#define png_get_progressive_ptr skia_png_get_progressive_ptr
#define png_process_data skia_png_process_data
#define png_process_data_pause skia_png_process_data_pause
#define png_process_data_skip skia_png_process_data_skip
#define png_progressive_combine_row skia_png_progressive_combine_row
#define png_set_progressive_read_fn skia_png_set_progressive_read_fn
#define png_create_read_struct skia_png_create_read_struct
#define png_create_read_struct_2 skia_png_create_read_struct_2
#define png_destroy_read_struct skia_png_destroy_read_struct
#define png_image_begin_read_from_file skia_png_image_begin_read_from_file
#define png_image_begin_read_from_memory skia_png_image_begin_read_from_memory
#define png_image_begin_read_from_stdio skia_png_image_begin_read_from_stdio
#define png_image_finish_read skia_png_image_finish_read
#define png_read_end skia_png_read_end
#define png_read_image skia_png_read_image
#define png_read_info skia_png_read_info
#define png_read_png skia_png_read_png
#define png_read_row skia_png_read_row
#define png_read_rows skia_png_read_rows
#define png_read_update_info skia_png_read_update_info
#define png_set_read_status_fn skia_png_set_read_status_fn
#define png_start_read_image skia_png_start_read_image
#define png_set_read_fn skia_png_set_read_fn
#define png_set_alpha_mode skia_png_set_alpha_mode
#define png_set_alpha_mode_fixed skia_png_set_alpha_mode_fixed
#define png_set_background skia_png_set_background
#define png_set_background_fixed skia_png_set_background_fixed
#define png_set_crc_action skia_png_set_crc_action
#define png_set_expand skia_png_set_expand
#define png_set_expand_16 skia_png_set_expand_16
#define png_set_expand_gray_1_2_4_to_8 skia_png_set_expand_gray_1_2_4_to_8
#define png_set_gamma skia_png_set_gamma
#define png_set_gamma_fixed skia_png_set_gamma_fixed
#define png_set_gray_to_rgb skia_png_set_gray_to_rgb
#define png_set_palette_to_rgb skia_png_set_palette_to_rgb
#define png_set_quantize skia_png_set_quantize
#define png_set_read_user_transform_fn skia_png_set_read_user_transform_fn
#define png_set_rgb_to_gray skia_png_set_rgb_to_gray
#define png_set_rgb_to_gray_fixed skia_png_set_rgb_to_gray_fixed
#define png_set_scale_16 skia_png_set_scale_16
#define png_set_strip_16 skia_png_set_strip_16
#define png_set_strip_alpha skia_png_set_strip_alpha
#define png_set_tRNS_to_alpha skia_png_set_tRNS_to_alpha
#define png_get_int_32 skia_png_get_int_32
#define png_get_uint_16 skia_png_get_uint_16
#define png_get_uint_31 skia_png_get_uint_31
#define png_get_uint_32 skia_png_get_uint_32
#define png_permit_mng_features skia_png_permit_mng_features
#define png_set_benign_errors skia_png_set_benign_errors
#define png_set_bKGD skia_png_set_bKGD
#define png_set_check_for_invalid_index skia_png_set_check_for_invalid_index
#define png_set_cHRM skia_png_set_cHRM
#define png_set_cHRM_fixed skia_png_set_cHRM_fixed
#define png_set_cHRM_XYZ skia_png_set_cHRM_XYZ
#define png_set_cHRM_XYZ_fixed skia_png_set_cHRM_XYZ_fixed
#define png_set_chunk_cache_max skia_png_set_chunk_cache_max
#define png_set_chunk_malloc_max skia_png_set_chunk_malloc_max
#define png_set_compression_buffer_size skia_png_set_compression_buffer_size
#define png_set_gAMA skia_png_set_gAMA
#define png_set_gAMA_fixed skia_png_set_gAMA_fixed
#define png_set_hIST skia_png_set_hIST
#define png_set_iCCP skia_png_set_iCCP
#define png_set_IHDR skia_png_set_IHDR
#define png_set_invalid skia_png_set_invalid
#define png_set_keep_unknown_chunks skia_png_set_keep_unknown_chunks
#define png_set_oFFs skia_png_set_oFFs
#define png_set_pCAL skia_png_set_pCAL
#define png_set_pHYs skia_png_set_pHYs
#define png_set_PLTE skia_png_set_PLTE
#define png_set_read_user_chunk_fn skia_png_set_read_user_chunk_fn
#define png_set_rows skia_png_set_rows
#define png_set_sBIT skia_png_set_sBIT
#define png_set_sCAL skia_png_set_sCAL
#define png_set_sCAL_fixed skia_png_set_sCAL_fixed
#define png_set_sCAL_s skia_png_set_sCAL_s
#define png_set_sPLT skia_png_set_sPLT
#define png_set_sRGB skia_png_set_sRGB
#define png_set_sRGB_gAMA_and_cHRM skia_png_set_sRGB_gAMA_and_cHRM
#define png_set_text skia_png_set_text
#define png_set_tIME skia_png_set_tIME
#define png_set_tRNS skia_png_set_tRNS
#define png_set_unknown_chunk_location skia_png_set_unknown_chunk_location
#define png_set_unknown_chunks skia_png_set_unknown_chunks
#define png_set_user_limits skia_png_set_user_limits
#define png_get_current_pass_number skia_png_get_current_pass_number
#define png_get_current_row_number skia_png_get_current_row_number
#define png_get_user_transform_ptr skia_png_get_user_transform_ptr
#define png_set_add_alpha skia_png_set_add_alpha
#define png_set_bgr skia_png_set_bgr
#define png_set_filler skia_png_set_filler
#define png_set_interlace_handling skia_png_set_interlace_handling
#define png_set_invert_alpha skia_png_set_invert_alpha
#define png_set_invert_mono skia_png_set_invert_mono
#define png_set_packing skia_png_set_packing
#define png_set_packswap skia_png_set_packswap
#define png_set_shift skia_png_set_shift
#define png_set_swap skia_png_set_swap
#define png_set_swap_alpha skia_png_set_swap_alpha
#define png_set_user_transform_info skia_png_set_user_transform_info
#define png_set_write_fn skia_png_set_write_fn
#define png_convert_from_struct_tm skia_png_convert_from_struct_tm
#define png_convert_from_time_t skia_png_convert_from_time_t
#define png_create_write_struct skia_png_create_write_struct
#define png_create_write_struct_2 skia_png_create_write_struct_2
#define png_destroy_write_struct skia_png_destroy_write_struct
#define png_image_write_to_file skia_png_image_write_to_file
#define png_image_write_to_stdio skia_png_image_write_to_stdio
#define png_set_compression_level skia_png_set_compression_level
#define png_set_compression_mem_level skia_png_set_compression_mem_level
#define png_set_compression_method skia_png_set_compression_method
#define png_set_compression_strategy skia_png_set_compression_strategy
#define png_set_compression_window_bits skia_png_set_compression_window_bits
#define png_set_filter skia_png_set_filter
#define png_set_filter_heuristics skia_png_set_filter_heuristics
#define png_set_filter_heuristics_fixed skia_png_set_filter_heuristics_fixed
#define png_set_flush skia_png_set_flush
#define png_set_text_compression_level skia_png_set_text_compression_level
#define png_set_text_compression_mem_level skia_png_set_text_compression_mem_level
#define png_set_text_compression_method skia_png_set_text_compression_method
#define png_set_text_compression_strategy skia_png_set_text_compression_strategy
#define png_set_text_compression_window_bits skia_png_set_text_compression_window_bits
#define png_set_write_status_fn skia_png_set_write_status_fn
#define png_set_write_user_transform_fn skia_png_set_write_user_transform_fn
#define png_write_end skia_png_write_end
#define png_write_flush skia_png_write_flush
#define png_write_image skia_png_write_image
#define png_write_info skia_png_write_info
#define png_write_info_before_PLTE skia_png_write_info_before_PLTE
#define png_write_png skia_png_write_png
#define png_write_row skia_png_write_row
#define png_write_rows skia_png_write_rows
#define png_save_uint_16 skia_png_save_uint_16
#define png_save_uint_32 skia_png_save_uint_32
#define png_write_chunk skia_png_write_chunk
#define png_write_chunk_data skia_png_write_chunk_data
#define png_write_chunk_start skia_png_write_chunk_start
#define png_write_chunk_end skia_png_write_chunk_end
#define png_write_sig skia_png_write_sig
| gpl-3.0 |
MakeHer/edx-platform | cms/static/js/views/metadata.js | 21517 | define(
[
"js/views/baseview", "underscore", "js/models/metadata", "js/views/abstract_editor",
"js/models/uploads", "js/views/uploads",
"js/models/license", "js/views/license",
"js/views/video/transcripts/metadata_videolist",
"js/views/video/translations_editor"
],
function(BaseView, _, MetadataModel, AbstractEditor, FileUpload, UploadDialog,
LicenseModel, LicenseView, VideoList, VideoTranslations) {
var Metadata = {};
Metadata.Editor = BaseView.extend({
// Model is CMS.Models.MetadataCollection,
initialize : function() {
var self = this,
counter = 0,
locator = self.$el.closest('[data-locator]').data('locator'),
courseKey = self.$el.closest('[data-course-key]').data('course-key');
this.template = this.loadTemplate('metadata-editor');
this.$el.html(this.template({numEntries: this.collection.length}));
this.collection.each(
function (model) {
var data = {
el: self.$el.find('.metadata_entry')[counter++],
courseKey: courseKey,
locator: locator,
model: model
},
conversions = {
'Select': 'Option',
'Float': 'Number',
'Integer': 'Number'
},
type = model.getType();
if (conversions[type]) {
type = conversions[type];
}
if (_.isFunction(Metadata[type])) {
new Metadata[type](data);
} else {
// Everything else is treated as GENERIC_TYPE, which uses String editor.
new Metadata.String(data);
}
});
},
/**
* Returns just the modified metadata values, in the format used to persist to the server.
*/
getModifiedMetadataValues: function () {
var modified_values = {};
this.collection.each(
function (model) {
if (model.isModified()) {
modified_values[model.getFieldName()] = model.getValue();
}
}
);
return modified_values;
},
/**
* Returns a display name for the component related to this metadata. This method looks to see
* if there is a metadata entry called 'display_name', and if so, it returns its value. If there
* is no such entry, or if display_name does not have a value set, it returns an empty string.
*/
getDisplayName: function () {
var displayName = '';
this.collection.each(
function (model) {
if (model.get('field_name') === 'display_name') {
var displayNameValue = model.get('value');
// It is possible that there is no display name value set. In that case, return empty string.
displayName = displayNameValue ? displayNameValue : '';
}
}
);
return displayName;
}
});
Metadata.VideoList = VideoList;
Metadata.VideoTranslations = VideoTranslations;
Metadata.String = AbstractEditor.extend({
events : {
"change input" : "updateModel",
"keypress .setting-input" : "showClearButton",
"click .setting-clear" : "clear"
},
templateName: "metadata-string-entry",
render: function () {
AbstractEditor.prototype.render.apply(this);
// If the model has property `non editable` equals `true`,
// the field is disabled, but user is able to clear it.
if (this.model.get('non_editable')) {
this.$el.find('#' + this.uniqueId)
.prop('readonly', true)
.addClass('is-disabled')
.attr('aria-disabled', true);
}
},
getValueFromEditor : function () {
return this.$el.find('#' + this.uniqueId).val();
},
setValueInEditor : function (value) {
this.$el.find('input').val(value);
}
});
Metadata.Number = AbstractEditor.extend({
events : {
"change input" : "updateModel",
"keypress .setting-input" : "keyPressed",
"change .setting-input" : "changed",
"click .setting-clear" : "clear"
},
render: function () {
AbstractEditor.prototype.render.apply(this);
if (!this.initialized) {
var numToString = function (val) {
return val.toFixed(4);
};
var min = "min";
var max = "max";
var step = "step";
var options = this.model.getOptions();
if (options.hasOwnProperty(min)) {
this.min = Number(options[min]);
this.$el.find('input').attr(min, numToString(this.min));
}
if (options.hasOwnProperty(max)) {
this.max = Number(options[max]);
this.$el.find('input').attr(max, numToString(this.max));
}
var stepValue = undefined;
if (options.hasOwnProperty(step)) {
// Parse step and convert to String. Polyfill doesn't like float values like ".1" (expects "0.1").
stepValue = numToString(Number(options[step]));
}
else if (this.isIntegerField()) {
stepValue = "1";
}
if (stepValue !== undefined) {
this.$el.find('input').attr(step, stepValue);
}
// Manually runs polyfill for input number types to correct for Firefox non-support.
// inputNumber will be undefined when unit test is running.
if ($.fn.inputNumber) {
this.$el.find('.setting-input-number').inputNumber();
}
this.initialized = true;
}
return this;
},
templateName: "metadata-number-entry",
getValueFromEditor : function () {
return this.$el.find('#' + this.uniqueId).val();
},
setValueInEditor : function (value) {
this.$el.find('input').val(value);
},
/**
* Returns true if this view is restricted to integers, as opposed to floating points values.
*/
isIntegerField : function () {
return this.model.getType() === 'Integer';
},
keyPressed: function (e) {
this.showClearButton();
// This first filtering if statement is take from polyfill to prevent
// non-numeric input (for browsers that don't use polyfill because they DO have a number input type).
var _ref, _ref1;
if (((_ref = e.keyCode) !== 8 && _ref !== 9 && _ref !== 35 && _ref !== 36 && _ref !== 37 && _ref !== 39) &&
((_ref1 = e.which) !== 45 && _ref1 !== 46 && _ref1 !== 48 && _ref1 !== 49 && _ref1 !== 50 && _ref1 !== 51
&& _ref1 !== 52 && _ref1 !== 53 && _ref1 !== 54 && _ref1 !== 55 && _ref1 !== 56 && _ref1 !== 57)) {
e.preventDefault();
}
// For integers, prevent decimal points.
if (this.isIntegerField() && e.keyCode === 46) {
e.preventDefault();
}
},
changed: function () {
// Limit value to the range specified by min and max (necessary for browsers that aren't using polyfill).
// Prevent integer/float fields value to be empty (set them to their defaults)
var value = this.getValueFromEditor();
if (value) {
if ((this.max !== undefined) && value > this.max) {
value = this.max;
} else if ((this.min != undefined) && value < this.min) {
value = this.min;
}
this.setValueInEditor(value);
this.updateModel();
} else {
this.clear();
}
}
});
Metadata.Option = AbstractEditor.extend({
events : {
"change select" : "updateModel",
"click .setting-clear" : "clear"
},
templateName: "metadata-option-entry",
getValueFromEditor : function () {
var selectedText = this.$el.find('#' + this.uniqueId).find(":selected").text();
var selectedValue;
_.each(this.model.getOptions(), function (modelValue) {
if (modelValue === selectedText) {
selectedValue = modelValue;
}
else if (modelValue['display_name'] === selectedText) {
selectedValue = modelValue['value'];
}
});
return selectedValue;
},
setValueInEditor : function (value) {
// Value here is the json value as used by the field. The choice may instead be showing display names.
// Find the display name matching the value passed in.
_.each(this.model.getOptions(), function (modelValue) {
if (modelValue['value'] === value) {
value = modelValue['display_name'];
}
});
this.$el.find('#' + this.uniqueId + " option").filter(function() {
return $(this).text() === value;
}).prop('selected', true);
}
});
Metadata.List = AbstractEditor.extend({
events : {
"click .setting-clear" : "clear",
"keypress .setting-input" : "showClearButton",
"change input" : "updateModel",
"input input" : "enableAdd",
"click .create-setting" : "addEntry",
"click .remove-setting" : "removeEntry"
},
templateName: "metadata-list-entry",
getValueFromEditor: function () {
return _.map(
this.$el.find('li input'),
function (ele) { return ele.value.trim(); }
).filter(_.identity);
},
setValueInEditor: function (value) {
var list = this.$el.find('ol');
list.empty();
_.each(value, function(ele, index) {
var template = _.template(
'<li class="list-settings-item">' +
'<input type="text" class="input" value="<%= ele %>">' +
'<a href="#" class="remove-action remove-setting" data-index="<%= index %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' +
'</li>'
);
list.append($(template({'ele': ele, 'index': index})));
});
},
addEntry: function(event) {
event.preventDefault();
// We don't call updateModel here since it's bound to the
// change event
var list = this.model.get('value') || [];
this.setValueInEditor(list.concat(['']));
this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true);
},
removeEntry: function(event) {
event.preventDefault();
var entry = $(event.currentTarget).siblings().val();
this.setValueInEditor(_.without(this.model.get('value'), entry));
this.updateModel();
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
},
enableAdd: function() {
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
},
clear: function() {
AbstractEditor.prototype.clear.apply(this, arguments);
if (_.isNull(this.model.getValue())) {
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
}
}
});
Metadata.RelativeTime = AbstractEditor.extend({
defaultValue: '00:00:00',
// By default max value of RelativeTime field on Backend is 23:59:59,
// that is 86399 seconds.
maxTimeInSeconds: 86399,
events: {
"focus input" : "addSelection",
"mouseup input" : "mouseUpHandler",
"change input" : "updateModel",
"keypress .setting-input" : "showClearButton" ,
"click .setting-clear" : "clear"
},
templateName: "metadata-string-entry",
getValueFromEditor: function () {
var $input = this.$el.find('#' + this.uniqueId);
return $input.val();
},
updateModel: function () {
var value = this.getValueFromEditor(),
time = this.parseRelativeTime(value);
this.model.setValue(time);
// Sometimes, `parseRelativeTime` method returns the same value for
// the different inputs. In this case, model will not be
// updated (it already has the same value) and we should
// call `render` method manually.
// Examples:
// value => 23:59:59; parseRelativeTime => 23:59:59
// value => 44:59:59; parseRelativeTime => 23:59:59
if (value !== time && !this.model.hasChanged('value')) {
this.render();
}
},
parseRelativeTime: function (value) {
// This function ensure you have two-digits
var pad = function (number) {
return (number < 10) ? "0" + number : number;
},
// Removes all white-spaces and splits by `:`.
list = value.replace(/\s+/g, '').split(':'),
seconds, date;
list = _.map(list, function(num) {
return Math.max(0, parseInt(num, 10) || 0);
}).reverse();
seconds = _.reduce(list, function(memo, num, index) {
return memo + num * Math.pow(60, index);
}, 0);
// multiply by 1000 because Date() requires milliseconds
date = new Date(Math.min(seconds, this.maxTimeInSeconds) * 1000);
return [
pad(date.getUTCHours()),
pad(date.getUTCMinutes()),
pad(date.getUTCSeconds())
].join(':');
},
setValueInEditor: function (value) {
if (!value) {
value = this.defaultValue;
}
this.$el.find('input').val(value);
},
addSelection: function (event) {
$(event.currentTarget).select();
},
mouseUpHandler: function (event) {
// Prevents default behavior to make works selection in WebKit
// browsers
event.preventDefault();
}
});
Metadata.Dict = AbstractEditor.extend({
events: {
"click .setting-clear" : "clear",
"keypress .setting-input" : "showClearButton",
"change input" : "updateModel",
"input input" : "enableAdd",
"click .create-setting" : "addEntry",
"click .remove-setting" : "removeEntry"
},
templateName: "metadata-dict-entry",
getValueFromEditor: function () {
var dict = {};
_.each(this.$el.find('li'), function(li, index) {
var key = $(li).find('.input-key').val().trim(),
value = $(li).find('.input-value').val().trim();
// Keys should be unique, so if our keys are duplicated and
// second key is empty or key and value are empty just do
// nothing. Otherwise, it'll be overwritten by the new value.
if (value === '') {
if (key === '' || key in dict) {
return false;
}
}
dict[key] = value;
});
return dict;
},
setValueInEditor: function (value) {
var list = this.$el.find('ol'),
frag = document.createDocumentFragment();
_.each(value, function(value, key) {
var template = _.template(
'<li class="list-settings-item">' +
'<input type="text" class="input input-key" value="<%= key %>">' +
'<input type="text" class="input input-value" value="<%= value %>">' +
'<a href="#" class="remove-action remove-setting" data-value="<%= value %>"><i class="icon fa fa-times-circle" aria-hidden="true"></i><span class="sr">Remove</span></a>' +
'</li>'
);
frag.appendChild($(template({'key': key, 'value': value}))[0]);
});
list.html([frag]);
},
addEntry: function(event) {
event.preventDefault();
// We don't call updateModel here since it's bound to the
// change event
var dict = $.extend(true, {}, this.model.get('value')) || {};
dict[''] = '';
this.setValueInEditor(dict);
this.$el.find('.create-setting').addClass('is-disabled').attr('aria-disabled', true);
},
removeEntry: function(event) {
event.preventDefault();
var entry = $(event.currentTarget).siblings('.input-key').val();
this.setValueInEditor(_.omit(this.model.get('value'), entry));
this.updateModel();
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
},
enableAdd: function() {
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
},
clear: function() {
AbstractEditor.prototype.clear.apply(this, arguments);
if (_.isNull(this.model.getValue())) {
this.$el.find('.create-setting').removeClass('is-disabled').attr('aria-disabled', false);
}
}
});
/**
* Provides convenient way to upload/download files in component edit.
* The editor uploads files directly to course assets and stores link
* to uploaded file.
*/
Metadata.FileUploader = AbstractEditor.extend({
events : {
"click .upload-setting" : "upload",
"click .setting-clear" : "clear"
},
templateName: "metadata-file-uploader-entry",
templateButtonsName: "metadata-file-uploader-item",
initialize: function () {
this.buttonTemplate = this.loadTemplate(this.templateButtonsName);
AbstractEditor.prototype.initialize.apply(this);
},
getValueFromEditor: function () {
return this.$('#' + this.uniqueId).val();
},
setValueInEditor: function (value) {
var html = this.buttonTemplate({
model: this.model,
uniqueId: this.uniqueId
});
this.$('#' + this.uniqueId).val(value);
this.$('.wrapper-uploader-actions').html(html);
},
upload: function (event) {
var self = this,
target = $(event.currentTarget),
url = '/assets/' + this.options.courseKey + '/',
model = new FileUpload({
title: gettext('Upload File'),
}),
view = new UploadDialog({
model: model,
url: url,
parentElement: target.closest('.xblock-editor'),
onSuccess: function (response) {
if (response['asset'] && response['asset']['url']) {
self.model.setValue(response['asset']['url']);
}
}
}).show();
event.preventDefault();
}
});
Metadata.License = AbstractEditor.extend({
initialize: function(options) {
this.licenseModel = new LicenseModel({"asString": this.model.getValue()});
this.licenseView = new LicenseView({model: this.licenseModel});
// Rerender when the license model changes
this.listenTo(this.licenseModel, 'change', this.setLicense);
this.render();
},
render: function() {
this.licenseView.render().$el.css("display", "inline");
this.licenseView.undelegateEvents();
this.$el.empty().append(this.licenseView.el);
// restore event bindings
this.licenseView.delegateEvents();
return this;
},
setLicense: function() {
this.model.setValue(this.licenseModel.toString());
this.render()
}
});
return Metadata;
});
| agpl-3.0 |
jacklicn/webm.libvpx | vp9/common/vp9_convolve.h | 1386 | /*
* Copyright (c) 2013 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef VP9_COMMON_VP9_CONVOLVE_H_
#define VP9_COMMON_VP9_CONVOLVE_H_
#include "./vpx_config.h"
#include "vpx/vpx_integer.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride,
uint8_t *dst, ptrdiff_t dst_stride,
const int16_t *filter_x, int x_step_q4,
const int16_t *filter_y, int y_step_q4,
int w, int h);
#if CONFIG_VP9_HIGHBITDEPTH
typedef void (*highbd_convolve_fn_t)(const uint8_t *src, ptrdiff_t src_stride,
uint8_t *dst, ptrdiff_t dst_stride,
const int16_t *filter_x, int x_step_q4,
const int16_t *filter_y, int y_step_q4,
int w, int h, int bd);
#endif
#ifdef __cplusplus
} // extern "C"
#endif
#endif // VP9_COMMON_VP9_CONVOLVE_H_
| bsd-3-clause |
scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-flexbox/flexbox_visibility-collapse-line-wrapping-ref.html | 463 | <!DOCTYPE html>
<title>flexbox | visibility: collapse and line wrapping</title>
<link rel="author" href="http://opera.com" title="Opera Software">
<style>
body {
margin: 0;
width: 602px;
}
div {
background: #3366cc;
border: 1px solid black;
}
div::after {
content: "";
clear: both;
display: block;
}
p {
background: #ffcc00;
margin: 1em 0;
width: 300px;
float: left;
}
</style>
<div>
<p>filler</p>
<p>filler</p>
<p>filler</p>
<p>filler</p>
</div>
| bsd-3-clause |
juanc25/proyectoFinal | app/cache/test/annotations/Proyecto-UsuarioBundle-Entity-Usuario$useLogin.cache.php | 254 | <?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";N;s:4:"type";s:6:"string";s:6:"length";i:40;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}'); | mit |
srinuvasuv/fat_free_crm | spec/controllers/entities/campaigns_controller_spec.rb | 24917 | # Copyright (c) 2008-2013 Michael Dvorkin and contributors.
#
# Fat Free CRM is freely distributable under the terms of MIT license.
# See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe CampaignsController do
def get_data_for_sidebar
@status = Setting.campaign_status.dup
end
before(:each) do
require_user
set_current_tab(:campaigns)
end
# GET /campaigns
# GET /campaigns.xml
#----------------------------------------------------------------------------
describe "responding to GET index" do
before(:each) do
get_data_for_sidebar
end
it "should expose all campaigns as @campaigns and render [index] template" do
@campaigns = [FactoryGirl.create(:campaign, user: current_user)]
get :index
expect(assigns[:campaigns]).to eq(@campaigns)
expect(response).to render_template("campaigns/index")
end
it "should collect the data for the opportunities sidebar" do
@campaigns = [FactoryGirl.create(:campaign, user: current_user)]
get :index
expect(assigns[:campaign_status_total].keys.map(&:to_sym) - (@status << :all << :other)).to eq([])
end
it "should filter out campaigns by status" do
controller.session[:campaigns_filter] = "planned,started"
@campaigns = [
FactoryGirl.create(:campaign, user: current_user, status: "started"),
FactoryGirl.create(:campaign, user: current_user, status: "planned")
]
# This one should be filtered out.
FactoryGirl.create(:campaign, user: current_user, status: "completed")
get :index
# Note: can't compare campaigns directly because of BigDecimal objects.
expect(assigns[:campaigns].size).to eq(2)
expect(assigns[:campaigns].map(&:status).sort).to eq(%w(planned started))
end
it "should perform lookup using query string" do
@first = FactoryGirl.create(:campaign, user: current_user, name: "Hello, world!")
@second = FactoryGirl.create(:campaign, user: current_user, name: "Hello again")
get :index, query: "again"
expect(assigns[:campaigns]).to eq([@second])
expect(assigns[:current_query]).to eq("again")
expect(session[:campaigns_current_query]).to eq("again")
end
describe "AJAX pagination" do
it "should pick up page number from params" do
@campaigns = [FactoryGirl.create(:campaign, user: current_user)]
xhr :get, :index, page: 42
expect(assigns[:current_page].to_i).to eq(42)
expect(assigns[:campaigns]).to eq([]) # page #42 should be empty if there's only one campaign ;-)
expect(session[:campaigns_current_page].to_i).to eq(42)
expect(response).to render_template("campaigns/index")
end
it "should pick up saved page number from session" do
session[:campaigns_current_page] = 42
@campaigns = [FactoryGirl.create(:campaign, user: current_user)]
xhr :get, :index
expect(assigns[:current_page]).to eq(42)
expect(assigns[:campaigns]).to eq([])
expect(response).to render_template("campaigns/index")
end
it "should reset current_page when query is altered" do
session[:campaigns_current_page] = 42
session[:campaigns_current_query] = "bill"
@campaigns = [FactoryGirl.create(:campaign, user: current_user)]
xhr :get, :index
expect(assigns[:current_page]).to eq(1)
expect(assigns[:campaigns]).to eq(@campaigns)
expect(response).to render_template("campaigns/index")
end
end
describe "with mime type of JSON" do
it "should render all campaigns as JSON" do
expect(@controller).to receive(:get_campaigns).and_return(@campaigns = [])
expect(@campaigns).to receive(:to_json).and_return("generated JSON")
request.env["HTTP_ACCEPT"] = "application/json"
get :index
expect(response.body).to eq("generated JSON")
end
end
describe "with mime type of XML" do
it "should render all campaigns as xml" do
expect(@controller).to receive(:get_campaigns).and_return(@campaigns = [])
expect(@campaigns).to receive(:to_xml).and_return("generated XML")
request.env["HTTP_ACCEPT"] = "application/xml"
get :index
expect(response.body).to eq("generated XML")
end
end
end
# GET /campaigns/1
# GET /campaigns/1.xml HTML
#----------------------------------------------------------------------------
describe "responding to GET show" do
describe "with mime type of HTML" do
before(:each) do
@campaign = FactoryGirl.create(:campaign, id: 42, user: current_user)
@stage = Setting.unroll(:opportunity_stage)
@comment = Comment.new
end
it "should expose the requested campaign as @campaign and render [show] template" do
get :show, id: 42
expect(assigns[:campaign]).to eq(@campaign)
expect(assigns[:stage]).to eq(@stage)
expect(assigns[:comment].attributes).to eq(@comment.attributes)
expect(response).to render_template("campaigns/show")
end
it "should update an activity when viewing the campaign" do
get :show, id: @campaign.id
expect(@campaign.versions.last.event).to eq('view')
end
end
describe "with mime type of JSON" do
it "should render the requested campaign as JSON" do
@campaign = FactoryGirl.create(:campaign, id: 42, user: current_user)
expect(Campaign).to receive(:find).and_return(@campaign)
expect(@campaign).to receive(:to_json).and_return("generated JSON")
request.env["HTTP_ACCEPT"] = "application/json"
get :show, id: 42
expect(response.body).to eq("generated JSON")
end
end
describe "with mime type of XML" do
it "should render the requested campaign as XML" do
@campaign = FactoryGirl.create(:campaign, id: 42, user: current_user)
expect(Campaign).to receive(:find).and_return(@campaign)
expect(@campaign).to receive(:to_xml).and_return("generated XML")
request.env["HTTP_ACCEPT"] = "application/xml"
get :show, id: 42
expect(response.body).to eq("generated XML")
end
end
describe "campaign got deleted or otherwise unavailable" do
it "should redirect to campaign index if the campaign got deleted" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
get :show, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response).to redirect_to(campaigns_path)
end
it "should redirect to campaign index if the campaign is protected" do
@campaign = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private")
get :show, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response).to redirect_to(campaigns_path)
end
it "should return 404 (Not Found) JSON error" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
request.env["HTTP_ACCEPT"] = "application/json"
get :show, id: @campaign.id
expect(response.code).to eq("404") # :not_found
end
it "should return 404 (Not Found) XML error" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
request.env["HTTP_ACCEPT"] = "application/xml"
get :show, id: @campaign.id
expect(response.code).to eq("404") # :not_found
end
end
end
# GET /campaigns/new
# GET /campaigns/new.xml AJAX
#----------------------------------------------------------------------------
describe "responding to GET new" do
it "should expose a new campaign as @campaign" do
@campaign = Campaign.new(user: current_user,
access: Setting.default_access)
xhr :get, :new
expect(assigns[:campaign].attributes).to eq(@campaign.attributes)
expect(response).to render_template("campaigns/new")
end
it "should create related object when necessary" do
@lead = FactoryGirl.create(:lead, id: 42)
xhr :get, :new, related: "lead_42"
expect(assigns[:lead]).to eq(@lead)
end
end
# GET /campaigns/1/edit AJAX
#----------------------------------------------------------------------------
describe "responding to GET edit" do
it "should expose the requested campaign as @campaign and render [edit] template" do
@campaign = FactoryGirl.create(:campaign, id: 42, user: current_user)
xhr :get, :edit, id: 42
expect(assigns[:campaign]).to eq(@campaign)
expect(response).to render_template("campaigns/edit")
end
it "should find previous campaign as necessary" do
@campaign = FactoryGirl.create(:campaign, id: 42)
@previous = FactoryGirl.create(:campaign, id: 99)
xhr :get, :edit, id: 42, previous: 99
expect(assigns[:campaign]).to eq(@campaign)
expect(assigns[:previous]).to eq(@previous)
end
describe "(campaign got deleted or is otherwise unavailable)" do
it "should reload current page with the flash message if the campaign got deleted" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
xhr :get, :edit, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
it "should reload current page with the flash message if the campaign is protected" do
@private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private")
xhr :get, :edit, id: @private.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
end
describe "(previous campaign got deleted or is otherwise unavailable)" do
before(:each) do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@previous = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user))
end
it "should notify the view if previous campaign got deleted" do
@previous.destroy
xhr :get, :edit, id: @campaign.id, previous: @previous.id
expect(flash[:warning]).to eq(nil) # no warning, just silently remove the div
expect(assigns[:previous]).to eq(@previous.id)
expect(response).to render_template("campaigns/edit")
end
it "should notify the view if previous campaign got protected" do
@previous.update_attribute(:access, "Private")
xhr :get, :edit, id: @campaign.id, previous: @previous.id
expect(flash[:warning]).to eq(nil)
expect(assigns[:previous]).to eq(@previous.id)
expect(response).to render_template("campaigns/edit")
end
end
end
# POST /campaigns
# POST /campaigns.xml AJAX
#----------------------------------------------------------------------------
describe "responding to POST create" do
describe "with valid params" do
it "should expose a newly created campaign as @campaign and render [create] template" do
@campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user)
allow(Campaign).to receive(:new).and_return(@campaign)
xhr :post, :create, campaign: { name: "Hello" }
expect(assigns(:campaign)).to eq(@campaign)
expect(response).to render_template("campaigns/create")
end
it "should get data to update campaign sidebar" do
@campaign = FactoryGirl.build(:campaign, name: "Hello", user: current_user)
allow(Campaign).to receive(:new).and_return(@campaign)
xhr :post, :create, campaign: { name: "Hello" }
expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess)
end
it "should reload campaigns to update pagination" do
@campaign = FactoryGirl.build(:campaign, user: current_user)
allow(Campaign).to receive(:new).and_return(@campaign)
xhr :post, :create, campaign: { name: "Hello" }
expect(assigns[:campaigns]).to eq([@campaign])
end
it "should add a new comment to the newly created campaign when specified" do
@campaign = FactoryGirl.build(:campaign, name: "Hello world", user: current_user)
allow(Campaign).to receive(:new).and_return(@campaign)
xhr :post, :create, campaign: { name: "Hello world" }, comment_body: "Awesome comment is awesome"
expect(@campaign.reload.comments.map(&:comment)).to include("Awesome comment is awesome")
end
end
describe "with invalid params" do
it "should expose a newly created but unsaved campaign as @campaign and still render [create] template" do
@campaign = FactoryGirl.build(:campaign, id: nil, name: nil, user: current_user)
allow(Campaign).to receive(:new).and_return(@campaign)
xhr :post, :create, campaign: {}
expect(assigns(:campaign)).to eq(@campaign)
expect(response).to render_template("campaigns/create")
end
end
end
# PUT /campaigns/1
# PUT /campaigns/1.xml AJAX
#----------------------------------------------------------------------------
describe "responding to PUT update" do
describe "with valid params" do
it "should update the requested campaign and render [update] template" do
@campaign = FactoryGirl.create(:campaign, id: 42, name: "Bye")
xhr :put, :update, id: 42, campaign: { name: "Hello" }
expect(@campaign.reload.name).to eq("Hello")
expect(assigns(:campaign)).to eq(@campaign)
expect(response).to render_template("campaigns/update")
end
it "should get data for campaigns sidebar when called from Campaigns index" do
@campaign = FactoryGirl.create(:campaign, id: 42)
request.env["HTTP_REFERER"] = "http://localhost/campaigns"
xhr :put, :update, id: 42, campaign: { name: "Hello" }
expect(assigns(:campaign)).to eq(@campaign)
expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess)
end
it "should update campaign permissions when sharing with specific users" do
@campaign = FactoryGirl.create(:campaign, id: 42, access: "Public")
he = FactoryGirl.create(:user, id: 7)
she = FactoryGirl.create(:user, id: 8)
xhr :put, :update, id: 42, campaign: { name: "Hello", access: "Shared", user_ids: %w(7 8) }
expect(assigns[:campaign].access).to eq("Shared")
expect(assigns[:campaign].user_ids.sort).to eq([7, 8])
end
describe "campaign got deleted or otherwise unavailable" do
it "should reload current page with the flash message if the campaign got deleted" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
xhr :put, :update, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
it "should reload current page with the flash message if the campaign is protected" do
@private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private")
xhr :put, :update, id: @private.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
end
end
describe "with invalid params" do
it "should not update the requested campaign, but still expose it as @campaign and still render [update] template" do
@campaign = FactoryGirl.create(:campaign, id: 42, name: "Hello", user: current_user)
xhr :put, :update, id: 42, campaign: { name: nil }
expect(@campaign.reload.name).to eq("Hello")
expect(assigns(:campaign)).to eq(@campaign)
expect(response).to render_template("campaigns/update")
end
end
end
# DELETE /campaigns/1
# DELETE /campaigns/1.xml AJAX
#----------------------------------------------------------------------------
describe "responding to DELETE destroy" do
before(:each) do
@campaign = FactoryGirl.create(:campaign, user: current_user)
end
describe "AJAX request" do
it "should destroy the requested campaign and render [destroy] template" do
@another_campaign = FactoryGirl.create(:campaign, user: current_user)
xhr :delete, :destroy, id: @campaign.id
expect(assigns[:campaigns]).to eq([@another_campaign])
expect { Campaign.find(@campaign.id) }.to raise_error(ActiveRecord::RecordNotFound)
expect(response).to render_template("campaigns/destroy")
end
it "should get data for campaigns sidebar" do
xhr :delete, :destroy, id: @campaign.id
expect(assigns[:campaign_status_total]).to be_instance_of(HashWithIndifferentAccess)
end
it "should try previous page and render index action if current page has no campaigns" do
session[:campaigns_current_page] = 42
xhr :delete, :destroy, id: @campaign.id
expect(session[:campaigns_current_page]).to eq(41)
expect(response).to render_template("campaigns/index")
end
it "should render index action when deleting last campaign" do
session[:campaigns_current_page] = 1
xhr :delete, :destroy, id: @campaign.id
expect(session[:campaigns_current_page]).to eq(1)
expect(response).to render_template("campaigns/index")
end
describe "campaign got deleted or otherwise unavailable" do
it "should reload current page with the flash message if the campaign got deleted" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
xhr :delete, :destroy, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
it "should reload current page with the flash message if the campaign is protected" do
@private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private")
xhr :delete, :destroy, id: @private.id
expect(flash[:warning]).not_to eq(nil)
expect(response.body).to eq("window.location.reload();")
end
end
end
describe "HTML request" do
it "should redirect to Campaigns index when a campaign gets deleted from its landing page" do
delete :destroy, id: @campaign.id
expect(flash[:notice]).not_to eq(nil)
expect(response).to redirect_to(campaigns_path)
end
it "should redirect to campaign index with the flash message is the campaign got deleted" do
@campaign = FactoryGirl.create(:campaign, user: current_user)
@campaign.destroy
delete :destroy, id: @campaign.id
expect(flash[:warning]).not_to eq(nil)
expect(response).to redirect_to(campaigns_path)
end
it "should redirect to campaign index with the flash message if the campaign is protected" do
@private = FactoryGirl.create(:campaign, user: FactoryGirl.create(:user), access: "Private")
delete :destroy, id: @private.id
expect(flash[:warning]).not_to eq(nil)
expect(response).to redirect_to(campaigns_path)
end
end
end
# PUT /campaigns/1/attach
# PUT /campaigns/1/attach.xml AJAX
#----------------------------------------------------------------------------
describe "responding to PUT attach" do
describe "tasks" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:task, asset: nil)
end
it_should_behave_like("attach")
end
describe "leads" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:lead, campaign: nil)
end
it_should_behave_like("attach")
end
describe "opportunities" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:opportunity, campaign: nil)
end
it_should_behave_like("attach")
end
end
# PUT /campaigns/1/attach
# PUT /campaigns/1/attach.xml AJAX
#----------------------------------------------------------------------------
describe "responding to PUT attach" do
describe "tasks" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:task, asset: nil)
end
it_should_behave_like("attach")
end
describe "leads" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:lead, campaign: nil)
end
it_should_behave_like("attach")
end
describe "opportunities" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:opportunity, campaign: nil)
end
it_should_behave_like("attach")
end
end
# POST /campaigns/1/discard
# POST /campaigns/1/discard.xml AJAX
#----------------------------------------------------------------------------
describe "responding to POST discard" do
describe "tasks" do
before do
@model = FactoryGirl.create(:campaign)
@attachment = FactoryGirl.create(:task, asset: @model)
end
it_should_behave_like("discard")
end
describe "leads" do
before do
@attachment = FactoryGirl.create(:lead)
@model = FactoryGirl.create(:campaign)
@model.leads << @attachment
end
it_should_behave_like("discard")
end
describe "opportunities" do
before do
@attachment = FactoryGirl.create(:opportunity)
@model = FactoryGirl.create(:campaign)
@model.opportunities << @attachment
end
it_should_behave_like("discard")
end
end
# POST /campaigns/auto_complete/query AJAX
#----------------------------------------------------------------------------
describe "responding to POST auto_complete" do
before(:each) do
@auto_complete_matches = [FactoryGirl.create(:campaign, name: "Hello World", user: current_user)]
end
it_should_behave_like("auto complete")
end
# GET /campaigns/redraw AJAX
#----------------------------------------------------------------------------
describe "responding to GET redraw" do
it "should save user selected campaign preference" do
xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name"
expect(current_user.preference[:campaigns_per_page]).to eq("42")
expect(current_user.preference[:campaigns_index_view]).to eq("brief")
expect(current_user.preference[:campaigns_sort_by]).to eq("campaigns.name ASC")
end
it "should reset current page to 1" do
xhr :get, :redraw, per_page: 42, view: "brief", sort_by: "name"
expect(session[:campaigns_current_page]).to eq(1)
end
it "should select @campaigns and render [index] template" do
@campaigns = [
FactoryGirl.create(:campaign, name: "A", user: current_user),
FactoryGirl.create(:campaign, name: "B", user: current_user)
]
xhr :get, :redraw, per_page: 1, sort_by: "name"
expect(assigns(:campaigns)).to eq([@campaigns.first])
expect(response).to render_template("campaigns/index")
end
end
# POST /campaigns/filter AJAX
#----------------------------------------------------------------------------
describe "responding to POST filter" do
it "should expose filtered campaigns as @campaigns and render [index] template" do
session[:campaigns_filter] = "planned,started"
@campaigns = [FactoryGirl.create(:campaign, status: "completed", user: current_user)]
xhr :post, :filter, status: "completed"
expect(assigns(:campaigns)).to eq(@campaigns)
expect(response).to render_template("campaigns/index")
end
it "should reset current page to 1" do
@campaigns = []
xhr :post, :filter, status: "completed"
expect(session[:campaigns_current_page]).to eq(1)
end
end
end
| mit |
koct9i/linux | arch/mips/include/asm/mach-jz4740/jz4740_fb.h | 1323 | /* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Copyright (C) 2009, Lars-Peter Clausen <[email protected]>
*/
#ifndef __ASM_MACH_JZ4740_JZ4740_FB_H__
#define __ASM_MACH_JZ4740_JZ4740_FB_H__
#include <linux/fb.h>
enum jz4740_fb_lcd_type {
JZ_LCD_TYPE_GENERIC_16_BIT = 0,
JZ_LCD_TYPE_GENERIC_18_BIT = 0 | (1 << 4),
JZ_LCD_TYPE_SPECIAL_TFT_1 = 1,
JZ_LCD_TYPE_SPECIAL_TFT_2 = 2,
JZ_LCD_TYPE_SPECIAL_TFT_3 = 3,
JZ_LCD_TYPE_NON_INTERLACED_CCIR656 = 5,
JZ_LCD_TYPE_INTERLACED_CCIR656 = 7,
JZ_LCD_TYPE_SINGLE_COLOR_STN = 8,
JZ_LCD_TYPE_SINGLE_MONOCHROME_STN = 9,
JZ_LCD_TYPE_DUAL_COLOR_STN = 10,
JZ_LCD_TYPE_DUAL_MONOCHROME_STN = 11,
JZ_LCD_TYPE_8BIT_SERIAL = 12,
};
#define JZ4740_FB_SPECIAL_TFT_CONFIG(start, stop) (((start) << 16) | (stop))
/*
* width: width of the lcd display in mm
* height: height of the lcd display in mm
* num_modes: size of modes
* modes: list of valid video modes
* bpp: bits per pixel for the lcd
* lcd_type: lcd type
*/
struct jz4740_fb_platform_data {
unsigned int width;
unsigned int height;
size_t num_modes;
struct fb_videomode *modes;
unsigned int bpp;
enum jz4740_fb_lcd_type lcd_type;
struct {
uint32_t spl;
uint32_t cls;
uint32_t ps;
uint32_t rev;
} special_tft_config;
unsigned pixclk_falling_edge:1;
unsigned date_enable_active_low:1;
};
#endif
| gpl-2.0 |
kmtoki/qmk_firmware | keyboards/oddball/v1/config.h | 1203 | /* Copyright 2020 Alexander Tulloh
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
/*
* Keyboard Matrix Assignments
*
* Change this to how you wired your keyboard
* COLS: AVR pins used for columns, left to right
* ROWS: AVR pins used for rows, top to bottom
* DIODE_DIRECTION: COL2ROW = COL = Anode (+), ROW = Cathode (-, marked on diode)
* ROW2COL = ROW = Anode (+), COL = Cathode (-, marked on diode)
*
*/
#define MATRIX_ROW_PINS { F6, B5, B6, F7 }
#define MATRIX_COL_PINS { D6, D7, B4, D3, C6, C7 }
#define UNUSED_PINS { B7, D4, D5, E6, F0, F1, F4, F5 }
| gpl-2.0 |
joglomedia/masedi.net | work/berkeley-db/docs/gsg_db_rep/CXX/bulk.html | 5739 | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Bulk Transfers</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" />
<link rel="up" href="addfeatures.html" title="Chapter 5. Additional Features" />
<link rel="prev" href="c2ctransfer.html" title="Client to Client Transfer" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Bulk Transfers</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="c2ctransfer.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5. Additional Features</th>
<td width="20%" align="right"> </td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="bulk"></a>Bulk Transfers</h2>
</div>
</div>
</div>
<p>
By default, messages are sent from the master to replicas as they are generated.
This can degrade replication performance because the various participating
environments must handle a fair amount of network I/O activity.
</p>
<p>
You can alleviate this problem by configuring your master environment for bulk
transfers. Bulk transfers simply cause replication messages to accumulate in a
buffer until a triggering event occurs. When this event occurs, the entire
contents of the buffer is sent to the replica, thereby eliminating excessive
network I/O.
</p>
<p>
Note that if you are using replica to replica transfers, then you might want any
replica that can service replication requests to also be configured for bulk
transfers.
</p>
<p>
The events that result in a bulk transfer of replication messages to a replica
will differ depending on if the transmitting environment is a master or a
replica.
</p>
<p>
If the servicing environment is a master environment, then bulk transfer
occurs when:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Bulk transfers are configured for the master environment, and
</p>
</li>
<li>
<p>
the message buffer is full or
</p>
</li>
<li>
<p>
a permanent record (for example, a transaction commit or a
checkpoint record) is placed in the buffer for the replica.
</p>
</li>
</ol>
</div>
<p>
If the servicing environment is a replica environment (that is, replica to replica
transfers are in use), then a bulk transfer occurs when:
</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>
Bulk transfers are configured for the transmitting replica, and
</p>
</li>
<li>
<p>
the message buffer is full or
</p>
</li>
<li>
<p>
the replica servicing the request is able to completely satisfy
the request with the contents of the message buffer.
</p>
</li>
</ol>
</div>
<p>
To configure bulk transfers, specify
<span>
<code class="literal">DB_REP_CONF_BULK</code> to
<code class="methodname">DbEnv::rep_set_config()</code>
and then specify <code class="literal">1</code> to the <code class="literal">onoff</code>
parameter. (Specify <code class="literal">0</code> to turn the feature off.)
</span>
</p>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="c2ctransfer.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="addfeatures.html">Up</a>
</td>
<td width="40%" align="right"> </td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Client to Client Transfer </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> </td>
</tr>
</table>
</div>
</body>
</html>
| gpl-2.0 |
wanghao-xznu/vte | testcases/third_party_suite/kexec/kexec-tools-2.0.2/kexec/arch/mips/kexec-mips.c | 3379 | /*
* kexec-mips.c - kexec for mips
* Copyright (C) 2007 Francesco Chiechi, Alessandro Rubini
* Copyright (C) 2007 Tvblob s.r.l.
*
* derived from ../ppc/kexec-mips.c
* Copyright (C) 2004, 2005 Albert Herranz
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <stddef.h>
#include <stdio.h>
#include <errno.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>
#include "../../kexec.h"
#include "../../kexec-syscall.h"
#include "kexec-mips.h"
#include <arch/options.h>
static struct memory_range memory_range[MAX_MEMORY_RANGES];
/* Return a sorted list of memory ranges. */
int get_memory_ranges(struct memory_range **range, int *ranges,
unsigned long UNUSED(kexec_flags))
{
int memory_ranges = 0;
const char iomem[] = "/proc/iomem";
char line[MAX_LINE];
FILE *fp;
unsigned long long start, end;
char *str;
int type, consumed, count;
fp = fopen(iomem, "r");
if (!fp) {
fprintf(stderr, "Cannot open %s: %s\n", iomem, strerror(errno));
return -1;
}
while (fgets(line, sizeof(line), fp) != 0) {
if (memory_ranges >= MAX_MEMORY_RANGES)
break;
count = sscanf(line, "%Lx-%Lx : %n", &start, &end, &consumed);
if (count != 2)
continue;
str = line + consumed;
end = end + 1;
if (memcmp(str, "System RAM\n", 11) == 0) {
type = RANGE_RAM;
} else if (memcmp(str, "reserved\n", 9) == 0) {
type = RANGE_RESERVED;
} else {
continue;
}
memory_range[memory_ranges].start = start;
memory_range[memory_ranges].end = end;
memory_range[memory_ranges].type = type;
memory_ranges++;
}
fclose(fp);
*range = memory_range;
*ranges = memory_ranges;
return 0;
}
struct file_type file_type[] = {
{"elf-mips", elf_mips_probe, elf_mips_load, elf_mips_usage},
};
int file_types = sizeof(file_type) / sizeof(file_type[0]);
void arch_usage(void)
{
#ifdef __mips64
fprintf(stderr, " --elf32-core-headers Prepare core headers in "
"ELF32 format\n");
#endif
}
#ifdef __mips64
struct arch_options_t arch_options = {
.core_header_type = CORE_TYPE_ELF64
};
#endif
int arch_process_options(int argc, char **argv)
{
return 0;
}
const struct arch_map_entry arches[] = {
/* For compatibility with older patches
* use KEXEC_ARCH_DEFAULT instead of KEXEC_ARCH_MIPS here.
*/
{ "mips", KEXEC_ARCH_MIPS },
{ "mips64", KEXEC_ARCH_MIPS },
{ NULL, 0 },
};
int arch_compat_trampoline(struct kexec_info *UNUSED(info))
{
return 0;
}
void arch_update_purgatory(struct kexec_info *UNUSED(info))
{
}
unsigned long virt_to_phys(unsigned long addr)
{
return addr & 0x7fffffff;
}
/*
* add_segment() should convert base to a physical address on mips,
* while the default is just to work with base as is */
void add_segment(struct kexec_info *info, const void *buf, size_t bufsz,
unsigned long base, size_t memsz)
{
add_segment_phys_virt(info, buf, bufsz, virt_to_phys(base), memsz, 1);
}
/*
* add_buffer() should convert base to a physical address on mips,
* while the default is just to work with base as is */
unsigned long add_buffer(struct kexec_info *info, const void *buf,
unsigned long bufsz, unsigned long memsz,
unsigned long buf_align, unsigned long buf_min,
unsigned long buf_max, int buf_end)
{
return add_buffer_phys_virt(info, buf, bufsz, memsz, buf_align,
buf_min, buf_max, buf_end, 1);
}
| gpl-2.0 |
cd80/UtilizedLLVM | tools/clang/test/CodeGen/capture-complex-expr-in-block.c | 710 | // RUN: %clang_cc1 %s -emit-llvm -o - -fblocks -triple x86_64-apple-darwin10 | FileCheck %s
// rdar://10033986
typedef void (^BLOCK)(void);
int main ()
{
_Complex double c;
BLOCK b = ^() {
_Complex double z;
z = z + c;
};
b();
}
// CHECK-LABEL: define internal void @__main_block_invoke
// CHECK: [[C1:%.*]] = alloca { double, double }, align 8
// CHECK: [[RP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 0
// CHECK-NEXT: [[R:%.*]] = load double, double* [[RP]]
// CHECK-NEXT: [[IP:%.*]] = getelementptr inbounds { double, double }, { double, double }* [[C1]], i32 0, i32 1
// CHECK-NEXT: [[I:%.*]] = load double, double* [[IP]]
| unlicense |
capturePointer/or-tools | documentation/reference_manual/or-tools/src/constraint_solver/globals_0x6c.html | 8677 | <!-- Good morning, Mr. Phelps. -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>or-tools/src/constraint_solver/: Class Members - Doxy</title>
<link rel="shortcut icon" href="../../../favicon.ico">
<!-- Both stylesheets are supplied by Doxygen, with maybe minor tweaks from Google. -->
<link href="../../../doxygen.css" rel="stylesheet" type="text/css">
<link href="../../../tabs.css" rel="stylesheet" type="text/css">
</head>
<body topmargin=0 leftmargin=20 bottommargin=0 rightmargin=20 marginwidth=20 marginheight=0>
<!-- Second part of the secret behind Doxy logo always having the word "Doxy" with the color of the day. -->
<style>
a.doxy_logo:hover {
background-color: #287003
}
</style>
<table width=100% cellpadding=0 cellspacing=0 border=0>
<!-- Top horizontal line with the color of the day. -->
<tr valign=top>
<td colspan=3 bgcolor=#287003 height=3></td>
</tr>
<!-- Header row with the links at the right. -->
<tr valign=top>
<td colspan=3 align=right>
<font size=-1>
Generated on: <font color=#287003><b>Thu Mar 29 07:46:58 PDT 2012</b></font>
for <b>custom file set</b>
</font>
</td>
</tr>
<!-- Header row with the logo and the search form. -->
<tr valign=top>
<!-- Logo. -->
<td align=left width=150>
<table width=150 height=54 cellpadding=0 cellspacing=0 border=0>
<tr valign=top>
<!-- First part of the secret behind Doxy logo always having the word "Doxy" with the color of the day. -->
<td bgcolor=#287003>
<a class="doxy_logo" href="../../../index.html"><img src="../../../doxy_logo.png" alt="Doxy" border=0></a>
</td>
</tr>
</table>
</td>
</tr>
<!-- Tiny vertical space below the form. -->
<tr valign=top>
<td colspan=3 height=3></td>
</tr>
</table>
<!-- Header navigation row. -->
<div class="memproto">
<table width=100% cellpadding=0 cellspacing=0 border=0>
<tr>
<td align=left style="padding-left: 20px"><font size=+1><b><tt><font color=#333333>//
<a href="../../../index.html"><font color=#287003>doxy</font></a>/</font>
<a href="../../../or-tools/index.html">or-tools</a>/
<a href="../../../or-tools/src/index.html">src</a>/
<a href="../../../or-tools/src/constraint_solver/index.html">constraint_solver</a>/
</tt></b></font>
</td>
</tr>
</table>
</div>
<br />
<!-- No subdirs found. -->
<!-- End of header. -->
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li class="current"><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_vars.html"><span>Variables</span></a></li>
<li><a href="globals_defs.html"><span>Defines</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="globals.html#index_a"><span>a</span></a></li>
<li><a href="globals_0x62.html#index_b"><span>b</span></a></li>
<li><a href="globals_0x63.html#index_c"><span>c</span></a></li>
<li><a href="globals_0x64.html#index_d"><span>d</span></a></li>
<li><a href="globals_0x65.html#index_e"><span>e</span></a></li>
<li><a href="globals_0x66.html#index_f"><span>f</span></a></li>
<li><a href="globals_0x68.html#index_h"><span>h</span></a></li>
<li><a href="globals_0x69.html#index_i"><span>i</span></a></li>
<li><a href="globals_0x6b.html#index_k"><span>k</span></a></li>
<li class="current"><a href="globals_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="globals_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="globals_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="globals_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="globals_0x70.html#index_p"><span>p</span></a></li>
<li><a href="globals_0x72.html#index_r"><span>r</span></a></li>
<li><a href="globals_0x73.html#index_s"><span>s</span></a></li>
<li><a href="globals_0x74.html#index_t"><span>t</span></a></li>
<li><a href="globals_0x75.html#index_u"><span>u</span></a></li>
<li><a href="globals_0x76.html#index_v"><span>v</span></a></li>
<li><a href="globals_0x77.html#index_w"><span>w</span></a></li>
</ul>
</div>
</div>
<div class="contents">
Here is a list of all file members with links to the files they belong to:
<p>
<h3><a class="anchor" name="index_l">- l -</a></h3><ul>
<li>last_
: <a class="el" href="constraint__solver_8cc.html#4a265269d82faeacc90eef4f9668cdbb">constraint_solver.cc</a>
, <a class="el" href="local__search_8cc.html#ce15cb86cc6195f048432fe3c9857083">local_search.cc</a>
, <a class="el" href="search_8cc.html#ce15cb86cc6195f048432fe3c9857083">search.cc</a>
<li>last_base_
: <a class="el" href="local__search_8cc.html#ffac8499a8767632743720c4c3d32115">local_search.cc</a>
<li>last_decision_
: <a class="el" href="tree__monitor_8cc.html#62099e67098897368ab69691ee56f301">tree_monitor.cc</a>
<li>last_time_delta_
: <a class="el" href="search_8cc.html#1d986b3a0535ec8217518dd4678164ba">search.cc</a>
<li>last_value_
: <a class="el" href="tree__monitor_8cc.html#7fa11d59f0ebd802fce510dcc0e11e86">tree_monitor.cc</a>
<li>last_variable_
: <a class="el" href="tree__monitor_8cc.html#dc3a742b7141c7e72d475efbd90cb83d">tree_monitor.cc</a>
<li>late_cost_
: <a class="el" href="expressions_8cc.html#a8e46190c772625168c8960dcd597918">expressions.cc</a>
<li>late_date_
: <a class="el" href="expressions_8cc.html#4834f3ce5a1ed3e970208c3274eafe71">expressions.cc</a>
<li>left_
: <a class="el" href="default__search_8cc.html#b6fe37aaf06c41be6dfaec01d28810b3">default_search.cc</a>
, <a class="el" href="expressions_8cc.html#7076deac82dc0a4df6618e6037964b0d">expressions.cc</a>
, <a class="el" href="range__cst_8cc.html#d9043b5cc6b0849d578d3e91decd673a">range_cst.cc</a>
<li>length_
: <a class="el" href="table_8cc.html#7d5350e32a84386f3508693ad02992b1">table.cc</a>
<li>limit_
: <a class="el" href="local__search_8cc.html#1c69e7dcf9d555da2ceac2a003b9e647">local_search.cc</a>
<li>limit_1_
: <a class="el" href="search_8cc.html#60b4e7c65e65cfd88aaaa2a2303ba16d">search.cc</a>
<li>limit_2_
: <a class="el" href="search_8cc.html#1b75e3a7942c823425afbadc670b866f">search.cc</a>
<li>limiter_
: <a class="el" href="search_8cc.html#21fbf59b6ca09e01c1568e774a9f4a1e">search.cc</a>
<li>loads_
: <a class="el" href="pack_8cc.html#aea3cda9f7389374c313391aa065589d">pack.cc</a>
<li>ls_operator_
: <a class="el" href="local__search_8cc.html#1b511506766ee2e09a27e61830c13347">local_search.cc</a>
<li>lt_tree_
: <a class="el" href="resource_8cc.html#27d3bf892939e964a3e650ab1a8f822d">resource.cc</a>
</ul>
</div>
<!-- Start of footer. -->
<table width=100% cellpadding=0 cellspacing=0 border=0>
<tr valign=top>
<td colspan=2 height=10></td>
</tr>
<tr valign=top>
<td colspan=2 bgcolor=#287003 height=3></td>
</tr>
</table>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br />
</body>
</html>
| apache-2.0 |
danalec/dotfiles | sublime/.config/sublime-text-3/Packages/anaconda_php/plugin/handlers_php/linting/phpcs/CodeSniffer/Standards/PEAR/Tests/Formatting/MultiLineAssignmentUnitTest.php | 1893 | <?php
/**
* Unit test class for the MultiLineAssignment sniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Unit test class for the MultiLineAssignment sniff.
*
* A sniff unit test checks a .inc file for expected violations of a single
* coding standard. Expected errors and warnings are stored in this class.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PEAR_Tests_Formatting_MultiLineAssignmentUnitTest extends AbstractSniffUnitTest
{
/**
* Returns the lines where errors should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of errors that should occur on that line.
*
* @return array<int, int>
*/
public function getErrorList()
{
return array(
3 => 1,
6 => 1,
8 => 1,
);
}//end getErrorList()
/**
* Returns the lines where warnings should occur.
*
* The key of the array should represent the line number and the value
* should represent the number of warnings that should occur on that line.
*
* @return array<int, int>
*/
public function getWarningList()
{
return array();
}//end getWarningList()
}//end class
?>
| mit |
lxl1140989/dmsdk | uboot/u-boot-dm6291/arch/mips/lib/bootm.c | 4774 | /*
* (C) Copyright 2003
* Wolfgang Denk, DENX Software Engineering, [email protected].
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <common.h>
#include <command.h>
#include <image.h>
#include <u-boot/zlib.h>
#include <asm/byteorder.h>
#include <asm/addrspace.h>
DECLARE_GLOBAL_DATA_PTR;
#define LINUX_MAX_ENVS 256
#define LINUX_MAX_ARGS 256
static int linux_argc;
static char **linux_argv;
static char **linux_env;
static char *linux_env_p;
static int linux_env_idx;
static void linux_params_init(ulong start, char *commandline);
static void linux_env_set(char *env_name, char *env_val);
static void boot_prep_linux(bootm_headers_t *images)
{
char *commandline = getenv("bootargs");
char env_buf[12];
char *cp;
linux_params_init(UNCACHED_SDRAM(gd->bd->bi_boot_params), commandline);
#ifdef CONFIG_MEMSIZE_IN_BYTES
sprintf(env_buf, "%lu", (ulong)gd->ram_size);
debug("## Giving linux memsize in bytes, %lu\n", (ulong)gd->ram_size);
#else
sprintf(env_buf, "%lu", (ulong)(gd->ram_size >> 20));
debug("## Giving linux memsize in MB, %lu\n",
(ulong)(gd->ram_size >> 20));
#endif /* CONFIG_MEMSIZE_IN_BYTES */
linux_env_set("memsize", env_buf);
sprintf(env_buf, "0x%08X", (uint) UNCACHED_SDRAM(images->rd_start));
linux_env_set("initrd_start", env_buf);
sprintf(env_buf, "0x%X", (uint) (images->rd_end - images->rd_start));
linux_env_set("initrd_size", env_buf);
sprintf(env_buf, "0x%08X", (uint) (gd->bd->bi_flashstart));
linux_env_set("flash_start", env_buf);
sprintf(env_buf, "0x%X", (uint) (gd->bd->bi_flashsize));
linux_env_set("flash_size", env_buf);
cp = getenv("ethaddr");
if (cp)
linux_env_set("ethaddr", cp);
cp = getenv("eth1addr");
if (cp)
linux_env_set("eth1addr", cp);
}
static void boot_jump_linux(bootm_headers_t *images)
{
void (*theKernel) (int, char **, char **, int *);
/* find kernel entry point */
theKernel = (void (*)(int, char **, char **, int *))images->ep;
debug("## Transferring control to Linux (at address %08lx) ...\n",
(ulong) theKernel);
bootstage_mark(BOOTSTAGE_ID_RUN_OS);
/* we assume that the kernel is in place */
printf("\nStarting kernel ...\n\n");
theKernel(linux_argc, linux_argv, linux_env, 0);
}
int do_bootm_linux(int flag, int argc, char * const argv[],
bootm_headers_t *images)
{
/* No need for those on MIPS */
if (flag & BOOTM_STATE_OS_BD_T || flag & BOOTM_STATE_OS_CMDLINE)
return -1;
if (flag & BOOTM_STATE_OS_PREP) {
boot_prep_linux(images);
return 0;
}
if (flag & BOOTM_STATE_OS_GO) {
boot_jump_linux(images);
return 0;
}
boot_prep_linux(images);
boot_jump_linux(images);
/* does not return */
return 1;
}
static void linux_params_init(ulong start, char *line)
{
char *next, *quote, *argp;
linux_argc = 1;
linux_argv = (char **) start;
linux_argv[0] = 0;
argp = (char *) (linux_argv + LINUX_MAX_ARGS);
next = line;
while (line && *line && linux_argc < LINUX_MAX_ARGS) {
quote = strchr(line, '"');
next = strchr(line, ' ');
while (next && quote && quote < next) {
/* we found a left quote before the next blank
* now we have to find the matching right quote
*/
next = strchr(quote + 1, '"');
if (next) {
quote = strchr(next + 1, '"');
next = strchr(next + 1, ' ');
}
}
if (!next)
next = line + strlen(line);
linux_argv[linux_argc] = argp;
memcpy(argp, line, next - line);
argp[next - line] = 0;
argp += next - line + 1;
linux_argc++;
if (*next)
next++;
line = next;
}
linux_env = (char **) (((ulong) argp + 15) & ~15);
linux_env[0] = 0;
linux_env_p = (char *) (linux_env + LINUX_MAX_ENVS);
linux_env_idx = 0;
}
static void linux_env_set(char *env_name, char *env_val)
{
if (linux_env_idx < LINUX_MAX_ENVS - 1) {
linux_env[linux_env_idx] = linux_env_p;
strcpy(linux_env_p, env_name);
linux_env_p += strlen(env_name);
strcpy(linux_env_p, "=");
linux_env_p += 1;
strcpy(linux_env_p, env_val);
linux_env_p += strlen(env_val);
linux_env_p++;
linux_env[++linux_env_idx] = 0;
}
}
| gpl-2.0 |
sarahkpeck/it-starts-with | wp-content/plugins/yet-another-related-posts-plugin/includes/yarpp_options.php | 5985 | <?php
global $wpdb, $wp_version, $yarpp;
/* Enforce YARPP setup: */
$yarpp->enforce();
if(!$yarpp->enabled() && !$yarpp->activate()) {
echo '<div class="updated">'.__('The YARPP database has an error which could not be fixed.','yarpp').'</div>';
}
/* Check to see that templates are in the right place */
if (!$yarpp->diagnostic_custom_templates()) {
$template_option = yarpp_get_option('template');
if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('template', false);
$template_option = yarpp_get_option('rss_template');
if ($template_option !== false && $template_option !== 'thumbnails') yarpp_set_option('rss_template', false);
}
/**
* @since 3.3 Move version checking here, in PHP.
*/
if (current_user_can('update_plugins')) {
$yarpp_version_info = $yarpp->version_info();
/*
* These strings are not localizable, as long as the plugin data on wordpress.org cannot be.
*/
$slug = 'yet-another-related-posts-plugin';
$plugin_name = 'Yet Another Related Posts Plugin';
$file = basename(YARPP_DIR).'/yarpp.php';
if ($yarpp_version_info['result'] === 'new') {
/* Make sure the update system is aware of this version. */
$current = get_site_transient('update_plugins');
if (!isset($current->response[$file])) {
delete_site_transient('update_plugins');
wp_update_plugins();
}
echo '<div class="updated"><p>';
$details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin='.$slug.'&TB_iframe=true&width=600&height=800');
printf(
__(
'There is a new version of %1$s available.'.
'<a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>'.
'or <a href="%5$s">update automatically</a>.', 'yarpp'),
$plugin_name,
esc_url($details_url),
esc_attr($plugin_name),
$yarpp_version_info['current']['version'],
wp_nonce_url( self_admin_url('update.php?action=upgrade-plugin&plugin=').$file, 'upgrade-plugin_'.$file)
);
echo '</p></div>';
} else if ($yarpp_version_info['result'] === 'newbeta') {
echo '<div class="updated"><p>';
printf(
__(
"There is a new beta (%s) of Yet Another Related Posts Plugin. ".
"You can <a href=\"%s\">download it here</a> at your own risk.", "yarpp"),
$yarpp_version_info['beta']['version'],
$yarpp_version_info['beta']['url']
);
echo '</p></div>';
}
}
/* MyISAM Check */
include 'yarpp_myisam_notice.php';
/* This is not a yarpp pluging update, it is an yarpp option update */
if (isset($_POST['update_yarpp'])) {
$new_options = array();
foreach ($yarpp->default_options as $option => $default) {
if ( is_bool($default) )
$new_options[$option] = isset($_POST[$option]);
if ( (is_string($default) || is_int($default)) &&
isset($_POST[$option]) && is_string($_POST[$option]) )
$new_options[$option] = stripslashes($_POST[$option]);
}
if ( isset($_POST['weight']) ) {
$new_options['weight'] = array();
$new_options['require_tax'] = array();
foreach ( (array) $_POST['weight'] as $key => $value) {
if ( $value == 'consider' )
$new_options['weight'][$key] = 1;
if ( $value == 'consider_extra' )
$new_options['weight'][$key] = YARPP_EXTRA_WEIGHT;
}
foreach ( (array) $_POST['weight']['tax'] as $tax => $value) {
if ( $value == 'consider' )
$new_options['weight']['tax'][$tax] = 1;
if ( $value == 'consider_extra' )
$new_options['weight']['tax'][$tax] = YARPP_EXTRA_WEIGHT;
if ( $value == 'require_one' ) {
$new_options['weight']['tax'][$tax] = 1;
$new_options['require_tax'][$tax] = 1;
}
if ( $value == 'require_more' ) {
$new_options['weight']['tax'][$tax] = 1;
$new_options['require_tax'][$tax] = 2;
}
}
}
if ( isset( $_POST['auto_display_post_types'] ) ) {
$new_options['auto_display_post_types'] = array_keys( $_POST['auto_display_post_types'] );
} else {
$new_options['auto_display_post_types'] = array();
}
$new_options['recent'] = isset($_POST['recent_only']) ?
$_POST['recent_number'] . ' ' . $_POST['recent_units'] : false;
if ( isset($_POST['exclude']) )
$new_options['exclude'] = implode(',',array_keys($_POST['exclude']));
else
$new_options['exclude'] = '';
$new_options['template'] = $_POST['use_template'] == 'custom' ? $_POST['template_file'] :
( $_POST['use_template'] == 'thumbnails' ? 'thumbnails' : false );
$new_options['rss_template'] = $_POST['rss_use_template'] == 'custom' ? $_POST['rss_template_file'] :
( $_POST['rss_use_template'] == 'thumbnails' ? 'thumbnails' : false );
$new_options = apply_filters( 'yarpp_settings_save', $new_options );
yarpp_set_option($new_options);
echo '<div class="updated fade"><p>'.__('Options saved!','yarpp').'</p></div>';
}
wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
wp_nonce_field('yarpp_display_demo', 'yarpp_display_demo-nonce', false);
wp_nonce_field('yarpp_display_exclude_terms', 'yarpp_display_exclude_terms-nonce', false);
wp_nonce_field('yarpp_optin_data', 'yarpp_optin_data-nonce', false);
wp_nonce_field('yarpp_set_display_code', 'yarpp_set_display_code-nonce', false);
if (!count($yarpp->admin->get_templates()) && $yarpp->admin->can_copy_templates()) {
wp_nonce_field('yarpp_copy_templates', 'yarpp_copy_templates-nonce', false);
}
include(YARPP_DIR.'/includes/phtmls/yarpp_options.phtml'); | gpl-2.0 |
gh1026/linux-3.4 | modules/mali/DX910-SW-99002-r3p2-01rel3/driver/src/devicedrv/mali/Makefile | 3987 | #
# Copyright (C) 2010-2013 ARM Limited. All rights reserved.
#
# This program is free software and is provided to you under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.
#
# A copy of the licence is included with the program, and can also be obtained from Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
USE_UMPV2=0
USING_PROFILING ?= 1
USING_INTERNAL_PROFILING ?= 0
MALI_DMA_BUF_MAP_ON_ATTACH ?= 1
# The Makefile sets up "arch" based on the CONFIG, creates the version info
# string and the __malidrv_build_info.c file, and then call the Linux build
# system to actually build the driver. After that point the Kbuild file takes
# over.
# set up defaults if not defined by the user
ARCH ?= arm
OSKOS=linux
FILES_PREFIX=
check_cc2 = \
$(shell if $(1) -S -o /dev/null -xc /dev/null > /dev/null 2>&1; \
then \
echo "$(2)"; \
else \
echo "$(3)"; \
fi ;)
# This conditional makefile exports the global definition ARM_INTERNAL_BUILD. Customer releases will not include arm_internal.mak
-include ../../../arm_internal.mak
# Give warning of old config parameters are used
ifneq ($(CONFIG),)
$(warning "You have specified the CONFIG variable which is no longer in used. Use TARGET_PLATFORM instead.")
endif
ifneq ($(CPU),)
$(warning "You have specified the CPU variable which is no longer in used. Use TARGET_PLATFORM instead.")
endif
# Include the mapping between TARGET_PLATFORM and KDIR + MALI_PLATFORM
-include MALI_CONFIGURATION
export KDIR ?= $(KDIR-$(TARGET_PLATFORM))
export MALI_PLATFORM ?= $(MALI_PLATFORM-$(TARGET_PLATFORM))
ifneq ($(TARGET_PLATFORM),)
ifeq ($(MALI_PLATFORM),)
$(error "Invalid TARGET_PLATFORM: $(TARGET_PLATFORM)")
endif
endif
# validate lookup result
ifeq ($(KDIR),)
$(error No KDIR found for platform $(TARGET_PLATFORM))
endif
ifeq ($(USING_UMP),1)
export CONFIG_MALI400_UMP=y
export EXTRA_DEFINES += -DCONFIG_MALI400_UMP=1
ifeq ($(USE_UMPV2),1)
UMP_SYMVERS_FILE ?= ../umpv2/Module.symvers
else
UMP_SYMVERS_FILE ?= ../ump/Module.symvers
endif
KBUILD_EXTRA_SYMBOLS = $(realpath $(UMP_SYMVERS_FILE))
$(warning $(KBUILD_EXTRA_SYMBOLS))
endif
# Define host system directory
KDIR-$(shell uname -m):=/lib/modules/$(shell uname -r)/build
include $(KDIR)/.config
ifeq ($(ARCH), arm)
# when compiling for ARM we're cross compiling
export CROSS_COMPILE ?= $(call check_cc2, arm-linux-gnueabi-gcc, arm-linux-gnueabi-, arm-none-linux-gnueabi-)
endif
# report detected/selected settings
ifdef ARM_INTERNAL_BUILD
$(warning TARGET_PLATFORM $(TARGET_PLATFORM))
$(warning KDIR $(KDIR))
$(warning MALI_PLATFORM $(MALI_PLATFORM))
endif
# Set up build config
export CONFIG_MALI400=m
ifneq ($(MALI_PLATFORM),)
export EXTRA_DEFINES += -DMALI_FAKE_PLATFORM_DEVICE=1
export MALI_PLATFORM_FILES = $(wildcard platform/$(MALI_PLATFORM)/*.c)
endif
ifeq ($(USING_PROFILING),1)
ifeq ($(CONFIG_TRACEPOINTS),)
$(warning CONFIG_TRACEPOINTS reqired for profiling)
else
export CONFIG_MALI400_PROFILING=y
export EXTRA_DEFINES += -DCONFIG_MALI400_PROFILING=1
ifeq ($(USING_INTERNAL_PROFILING),1)
export CONFIG_MALI400_INTERNAL_PROFILING=y
export EXTRA_DEFINES += -DCONFIG_MALI400_INTERNAL_PROFILING=1
endif
endif
endif
ifeq ($(MALI_DMA_BUF_MAP_ON_ATTACH),1)
export CONFIG_MALI_DMA_BUF_MAP_ON_ATTACH=y
export EXTRA_DEFINES += -DCONFIG_MALI_DMA_BUF_MAP_ON_ATTACH
endif
ifeq ($(MALI_SHARED_INTERRUPTS),1)
export CONFIG_MALI_SHARED_INTERRUPTS=y
export EXTRA_DEFINES += -DCONFIG_MALI_SHARED_INTERRUPTS
endif
ifneq ($(BUILD),release)
export CONFIG_MALI400_DEBUG=y
endif
all: $(UMP_SYMVERS_FILE)
$(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) modules
@rm $(FILES_PREFIX)__malidrv_build_info.c $(FILES_PREFIX)__malidrv_build_info.o
clean:
$(MAKE) ARCH=$(ARCH) -C $(KDIR) M=$(CURDIR) clean
kernelrelease:
$(MAKE) ARCH=$(ARCH) -C $(KDIR) kernelrelease
export CONFIG KBUILD_EXTRA_SYMBOLS
| gpl-2.0 |
raumfeld/linux-am33xx | drivers/net/ethernet/hisilicon/hns3/hns3vf/hclgevf_cmd.h | 6156 | /* SPDX-License-Identifier: GPL-2.0+ */
/* Copyright (c) 2016-2017 Hisilicon Limited. */
#ifndef __HCLGEVF_CMD_H
#define __HCLGEVF_CMD_H
#include <linux/io.h>
#include <linux/types.h>
#include "hnae3.h"
#define HCLGEVF_CMDQ_TX_TIMEOUT 30000
#define HCLGEVF_CMDQ_RX_INVLD_B 0
#define HCLGEVF_CMDQ_RX_OUTVLD_B 1
struct hclgevf_hw;
struct hclgevf_dev;
struct hclgevf_desc {
__le16 opcode;
__le16 flag;
__le16 retval;
__le16 rsv;
__le32 data[6];
};
struct hclgevf_desc_cb {
dma_addr_t dma;
void *va;
u32 length;
};
struct hclgevf_cmq_ring {
dma_addr_t desc_dma_addr;
struct hclgevf_desc *desc;
struct hclgevf_desc_cb *desc_cb;
struct hclgevf_dev *dev;
u32 head;
u32 tail;
u16 buf_size;
u16 desc_num;
int next_to_use;
int next_to_clean;
u8 flag;
spinlock_t lock; /* Command queue lock */
};
enum hclgevf_cmd_return_status {
HCLGEVF_CMD_EXEC_SUCCESS = 0,
HCLGEVF_CMD_NO_AUTH = 1,
HCLGEVF_CMD_NOT_EXEC = 2,
HCLGEVF_CMD_QUEUE_FULL = 3,
};
enum hclgevf_cmd_status {
HCLGEVF_STATUS_SUCCESS = 0,
HCLGEVF_ERR_CSQ_FULL = -1,
HCLGEVF_ERR_CSQ_TIMEOUT = -2,
HCLGEVF_ERR_CSQ_ERROR = -3
};
struct hclgevf_cmq {
struct hclgevf_cmq_ring csq;
struct hclgevf_cmq_ring crq;
u16 tx_timeout; /* Tx timeout */
enum hclgevf_cmd_status last_status;
};
#define HCLGEVF_CMD_FLAG_IN_VALID_SHIFT 0
#define HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT 1
#define HCLGEVF_CMD_FLAG_NEXT_SHIFT 2
#define HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT 3
#define HCLGEVF_CMD_FLAG_NO_INTR_SHIFT 4
#define HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT 5
#define HCLGEVF_CMD_FLAG_IN BIT(HCLGEVF_CMD_FLAG_IN_VALID_SHIFT)
#define HCLGEVF_CMD_FLAG_OUT BIT(HCLGEVF_CMD_FLAG_OUT_VALID_SHIFT)
#define HCLGEVF_CMD_FLAG_NEXT BIT(HCLGEVF_CMD_FLAG_NEXT_SHIFT)
#define HCLGEVF_CMD_FLAG_WR BIT(HCLGEVF_CMD_FLAG_WR_OR_RD_SHIFT)
#define HCLGEVF_CMD_FLAG_NO_INTR BIT(HCLGEVF_CMD_FLAG_NO_INTR_SHIFT)
#define HCLGEVF_CMD_FLAG_ERR_INTR BIT(HCLGEVF_CMD_FLAG_ERR_INTR_SHIFT)
enum hclgevf_opcode_type {
/* Generic command */
HCLGEVF_OPC_QUERY_FW_VER = 0x0001,
/* TQP command */
HCLGEVF_OPC_QUERY_TX_STATUS = 0x0B03,
HCLGEVF_OPC_QUERY_RX_STATUS = 0x0B13,
HCLGEVF_OPC_CFG_COM_TQP_QUEUE = 0x0B20,
/* RSS cmd */
HCLGEVF_OPC_RSS_GENERIC_CONFIG = 0x0D01,
HCLGEVF_OPC_RSS_INDIR_TABLE = 0x0D07,
HCLGEVF_OPC_RSS_TC_MODE = 0x0D08,
/* Mailbox cmd */
HCLGEVF_OPC_MBX_VF_TO_PF = 0x2001,
};
#define HCLGEVF_TQP_REG_OFFSET 0x80000
#define HCLGEVF_TQP_REG_SIZE 0x200
struct hclgevf_tqp_map {
__le16 tqp_id; /* Absolute tqp id for in this pf */
u8 tqp_vf; /* VF id */
#define HCLGEVF_TQP_MAP_TYPE_PF 0
#define HCLGEVF_TQP_MAP_TYPE_VF 1
#define HCLGEVF_TQP_MAP_TYPE_B 0
#define HCLGEVF_TQP_MAP_EN_B 1
u8 tqp_flag; /* Indicate it's pf or vf tqp */
__le16 tqp_vid; /* Virtual id in this pf/vf */
u8 rsv[18];
};
#define HCLGEVF_VECTOR_ELEMENTS_PER_CMD 10
enum hclgevf_int_type {
HCLGEVF_INT_TX = 0,
HCLGEVF_INT_RX,
HCLGEVF_INT_EVENT,
};
struct hclgevf_ctrl_vector_chain {
u8 int_vector_id;
u8 int_cause_num;
#define HCLGEVF_INT_TYPE_S 0
#define HCLGEVF_INT_TYPE_M 0x3
#define HCLGEVF_TQP_ID_S 2
#define HCLGEVF_TQP_ID_M (0x3fff << HCLGEVF_TQP_ID_S)
__le16 tqp_type_and_id[HCLGEVF_VECTOR_ELEMENTS_PER_CMD];
u8 vfid;
u8 resv;
};
struct hclgevf_query_version_cmd {
__le32 firmware;
__le32 firmware_rsv[5];
};
#define HCLGEVF_RSS_HASH_KEY_OFFSET 4
#define HCLGEVF_RSS_HASH_KEY_NUM 16
struct hclgevf_rss_config_cmd {
u8 hash_config;
u8 rsv[7];
u8 hash_key[HCLGEVF_RSS_HASH_KEY_NUM];
};
struct hclgevf_rss_input_tuple_cmd {
u8 ipv4_tcp_en;
u8 ipv4_udp_en;
u8 ipv4_stcp_en;
u8 ipv4_fragment_en;
u8 ipv6_tcp_en;
u8 ipv6_udp_en;
u8 ipv6_stcp_en;
u8 ipv6_fragment_en;
u8 rsv[16];
};
#define HCLGEVF_RSS_CFG_TBL_SIZE 16
struct hclgevf_rss_indirection_table_cmd {
u16 start_table_index;
u16 rss_set_bitmap;
u8 rsv[4];
u8 rss_result[HCLGEVF_RSS_CFG_TBL_SIZE];
};
#define HCLGEVF_RSS_TC_OFFSET_S 0
#define HCLGEVF_RSS_TC_OFFSET_M (0x3ff << HCLGEVF_RSS_TC_OFFSET_S)
#define HCLGEVF_RSS_TC_SIZE_S 12
#define HCLGEVF_RSS_TC_SIZE_M (0x7 << HCLGEVF_RSS_TC_SIZE_S)
#define HCLGEVF_RSS_TC_VALID_B 15
#define HCLGEVF_MAX_TC_NUM 8
struct hclgevf_rss_tc_mode_cmd {
u16 rss_tc_mode[HCLGEVF_MAX_TC_NUM];
u8 rsv[8];
};
#define HCLGEVF_LINK_STS_B 0
#define HCLGEVF_LINK_STATUS BIT(HCLGEVF_LINK_STS_B)
struct hclgevf_link_status_cmd {
u8 status;
u8 rsv[23];
};
#define HCLGEVF_RING_ID_MASK 0x3ff
#define HCLGEVF_TQP_ENABLE_B 0
struct hclgevf_cfg_com_tqp_queue_cmd {
__le16 tqp_id;
__le16 stream_id;
u8 enable;
u8 rsv[19];
};
struct hclgevf_cfg_tx_queue_pointer_cmd {
__le16 tqp_id;
__le16 tx_tail;
__le16 tx_head;
__le16 fbd_num;
__le16 ring_offset;
u8 rsv[14];
};
#define HCLGEVF_TYPE_CRQ 0
#define HCLGEVF_TYPE_CSQ 1
#define HCLGEVF_NIC_CSQ_BASEADDR_L_REG 0x27000
#define HCLGEVF_NIC_CSQ_BASEADDR_H_REG 0x27004
#define HCLGEVF_NIC_CSQ_DEPTH_REG 0x27008
#define HCLGEVF_NIC_CSQ_TAIL_REG 0x27010
#define HCLGEVF_NIC_CSQ_HEAD_REG 0x27014
#define HCLGEVF_NIC_CRQ_BASEADDR_L_REG 0x27018
#define HCLGEVF_NIC_CRQ_BASEADDR_H_REG 0x2701c
#define HCLGEVF_NIC_CRQ_DEPTH_REG 0x27020
#define HCLGEVF_NIC_CRQ_TAIL_REG 0x27024
#define HCLGEVF_NIC_CRQ_HEAD_REG 0x27028
#define HCLGEVF_NIC_CMQ_EN_B 16
#define HCLGEVF_NIC_CMQ_ENABLE BIT(HCLGEVF_NIC_CMQ_EN_B)
#define HCLGEVF_NIC_CMQ_DESC_NUM 1024
#define HCLGEVF_NIC_CMQ_DESC_NUM_S 3
#define HCLGEVF_NIC_CMDQ_INT_SRC_REG 0x27100
static inline void hclgevf_write_reg(void __iomem *base, u32 reg, u32 value)
{
writel(value, base + reg);
}
static inline u32 hclgevf_read_reg(u8 __iomem *base, u32 reg)
{
u8 __iomem *reg_addr = READ_ONCE(base);
return readl(reg_addr + reg);
}
#define hclgevf_write_dev(a, reg, value) \
hclgevf_write_reg((a)->io_base, (reg), (value))
#define hclgevf_read_dev(a, reg) \
hclgevf_read_reg((a)->io_base, (reg))
#define HCLGEVF_SEND_SYNC(flag) \
((flag) & HCLGEVF_CMD_FLAG_NO_INTR)
int hclgevf_cmd_init(struct hclgevf_dev *hdev);
void hclgevf_cmd_uninit(struct hclgevf_dev *hdev);
int hclgevf_cmd_send(struct hclgevf_hw *hw, struct hclgevf_desc *desc, int num);
void hclgevf_cmd_setup_basic_desc(struct hclgevf_desc *desc,
enum hclgevf_opcode_type opcode,
bool is_read);
#endif
| gpl-2.0 |
selmentdev/selment-toolchain | source/gcc-latest/gcc/testsuite/gcc.target/arm/neon/vmaxQs32.c | 584 | /* Test the `vmaxQs32' ARM Neon intrinsic. */
/* This file was autogenerated by neon-testgen. */
/* { dg-do assemble } */
/* { dg-require-effective-target arm_neon_ok } */
/* { dg-options "-save-temps -O0" } */
/* { dg-add-options arm_neon } */
#include "arm_neon.h"
void test_vmaxQs32 (void)
{
int32x4_t out_int32x4_t;
int32x4_t arg0_int32x4_t;
int32x4_t arg1_int32x4_t;
out_int32x4_t = vmaxq_s32 (arg0_int32x4_t, arg1_int32x4_t);
}
/* { dg-final { scan-assembler "vmax\.s32\[ \]+\[qQ\]\[0-9\]+, \[qQ\]\[0-9\]+, \[qQ\]\[0-9\]+!?\(\[ \]+@\[a-zA-Z0-9 \]+\)?\n" } } */
| gpl-3.0 |
anthgur/servo | tests/wpt/web-platform-tests/tools/third_party/pytest/_pytest/junitxml.py | 15681 | """
report test results in JUnit-XML format,
for use with Jenkins and build integration servers.
Based on initial code from Ross Lawley.
Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/
src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
"""
from __future__ import absolute_import, division, print_function
import functools
import py
import os
import re
import sys
import time
import pytest
from _pytest import nodes
from _pytest.config import filename_arg
# Python 2.X and 3.X compatibility
if sys.version_info[0] < 3:
from codecs import open
else:
unichr = chr
unicode = str
long = int
class Junit(py.xml.Namespace):
pass
# We need to get the subset of the invalid unicode ranges according to
# XML 1.0 which are valid in this python build. Hence we calculate
# this dynamically instead of hardcoding it. The spec range of valid
# chars is: Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD]
# | [#x10000-#x10FFFF]
_legal_chars = (0x09, 0x0A, 0x0d)
_legal_ranges = (
(0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF),
)
_legal_xml_re = [
unicode("%s-%s") % (unichr(low), unichr(high))
for (low, high) in _legal_ranges if low < sys.maxunicode
]
_legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re
illegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re))
del _legal_chars
del _legal_ranges
del _legal_xml_re
_py_ext_re = re.compile(r"\.py$")
def bin_xml_escape(arg):
def repl(matchobj):
i = ord(matchobj.group())
if i <= 0xFF:
return unicode('#x%02X') % i
else:
return unicode('#x%04X') % i
return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
class _NodeReporter(object):
def __init__(self, nodeid, xml):
self.id = nodeid
self.xml = xml
self.add_stats = self.xml.add_stats
self.duration = 0
self.properties = []
self.nodes = []
self.testcase = None
self.attrs = {}
def append(self, node):
self.xml.add_stats(type(node).__name__)
self.nodes.append(node)
def add_property(self, name, value):
self.properties.append((str(name), bin_xml_escape(value)))
def make_properties_node(self):
"""Return a Junit node containing custom properties, if any.
"""
if self.properties:
return Junit.properties([
Junit.property(name=name, value=value)
for name, value in self.properties
])
return ''
def record_testreport(self, testreport):
assert not self.testcase
names = mangle_test_address(testreport.nodeid)
classnames = names[:-1]
if self.xml.prefix:
classnames.insert(0, self.xml.prefix)
attrs = {
"classname": ".".join(classnames),
"name": bin_xml_escape(names[-1]),
"file": testreport.location[0],
}
if testreport.location[1] is not None:
attrs["line"] = testreport.location[1]
if hasattr(testreport, "url"):
attrs["url"] = testreport.url
self.attrs = attrs
def to_xml(self):
testcase = Junit.testcase(time=self.duration, **self.attrs)
testcase.append(self.make_properties_node())
for node in self.nodes:
testcase.append(node)
return testcase
def _add_simple(self, kind, message, data=None):
data = bin_xml_escape(data)
node = kind(data, message=message)
self.append(node)
def write_captured_output(self, report):
for capname in ('out', 'err'):
content = getattr(report, 'capstd' + capname)
if content:
tag = getattr(Junit, 'system-' + capname)
self.append(tag(bin_xml_escape(content)))
def append_pass(self, report):
self.add_stats('passed')
def append_failure(self, report):
# msg = str(report.longrepr.reprtraceback.extraline)
if hasattr(report, "wasxfail"):
self._add_simple(
Junit.skipped,
"xfail-marked test passes unexpectedly")
else:
if hasattr(report.longrepr, "reprcrash"):
message = report.longrepr.reprcrash.message
elif isinstance(report.longrepr, (unicode, str)):
message = report.longrepr
else:
message = str(report.longrepr)
message = bin_xml_escape(message)
fail = Junit.failure(message=message)
fail.append(bin_xml_escape(report.longrepr))
self.append(fail)
def append_collect_error(self, report):
# msg = str(report.longrepr.reprtraceback.extraline)
self.append(Junit.error(bin_xml_escape(report.longrepr),
message="collection failure"))
def append_collect_skipped(self, report):
self._add_simple(
Junit.skipped, "collection skipped", report.longrepr)
def append_error(self, report):
if getattr(report, 'when', None) == 'teardown':
msg = "test teardown failure"
else:
msg = "test setup failure"
self._add_simple(
Junit.error, msg, report.longrepr)
def append_skipped(self, report):
if hasattr(report, "wasxfail"):
self._add_simple(
Junit.skipped, "expected test failure", report.wasxfail
)
else:
filename, lineno, skipreason = report.longrepr
if skipreason.startswith("Skipped: "):
skipreason = bin_xml_escape(skipreason[9:])
self.append(
Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason),
type="pytest.skip",
message=skipreason))
self.write_captured_output(report)
def finalize(self):
data = self.to_xml().unicode(indent=0)
self.__dict__.clear()
self.to_xml = lambda: py.xml.raw(data)
@pytest.fixture
def record_xml_property(request):
"""Add extra xml properties to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being automatically
xml-encoded.
"""
request.node.warn(
code='C3',
message='record_xml_property is an experimental feature',
)
xml = getattr(request.config, "_xml", None)
if xml is not None:
node_reporter = xml.node_reporter(request.node.nodeid)
return node_reporter.add_property
else:
def add_property_noop(name, value):
pass
return add_property_noop
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting")
group.addoption(
'--junitxml', '--junit-xml',
action="store",
dest="xmlpath",
metavar="path",
type=functools.partial(filename_arg, optname="--junitxml"),
default=None,
help="create junit-xml style report file at given path.")
group.addoption(
'--junitprefix', '--junit-prefix',
action="store",
metavar="str",
default=None,
help="prepend prefix to classnames in junit-xml output")
parser.addini("junit_suite_name", "Test suite name for JUnit report", default="pytest")
def pytest_configure(config):
xmlpath = config.option.xmlpath
# prevent opening xmllog on slave nodes (xdist)
if xmlpath and not hasattr(config, 'slaveinput'):
config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini("junit_suite_name"))
config.pluginmanager.register(config._xml)
def pytest_unconfigure(config):
xml = getattr(config, '_xml', None)
if xml:
del config._xml
config.pluginmanager.unregister(xml)
def mangle_test_address(address):
path, possible_open_bracket, params = address.partition('[')
names = path.split("::")
try:
names.remove('()')
except ValueError:
pass
# convert file path to dotted path
names[0] = names[0].replace(nodes.SEP, '.')
names[0] = _py_ext_re.sub("", names[0])
# put any params back
names[-1] += possible_open_bracket + params
return names
class LogXML(object):
def __init__(self, logfile, prefix, suite_name="pytest"):
logfile = os.path.expanduser(os.path.expandvars(logfile))
self.logfile = os.path.normpath(os.path.abspath(logfile))
self.prefix = prefix
self.suite_name = suite_name
self.stats = dict.fromkeys([
'error',
'passed',
'failure',
'skipped',
], 0)
self.node_reporters = {} # nodeid -> _NodeReporter
self.node_reporters_ordered = []
self.global_properties = []
# List of reports that failed on call but teardown is pending.
self.open_reports = []
self.cnt_double_fail_tests = 0
def finalize(self, report):
nodeid = getattr(report, 'nodeid', report)
# local hack to handle xdist report order
slavenode = getattr(report, 'node', None)
reporter = self.node_reporters.pop((nodeid, slavenode))
if reporter is not None:
reporter.finalize()
def node_reporter(self, report):
nodeid = getattr(report, 'nodeid', report)
# local hack to handle xdist report order
slavenode = getattr(report, 'node', None)
key = nodeid, slavenode
if key in self.node_reporters:
# TODO: breasks for --dist=each
return self.node_reporters[key]
reporter = _NodeReporter(nodeid, self)
self.node_reporters[key] = reporter
self.node_reporters_ordered.append(reporter)
return reporter
def add_stats(self, key):
if key in self.stats:
self.stats[key] += 1
def _opentestcase(self, report):
reporter = self.node_reporter(report)
reporter.record_testreport(report)
return reporter
def pytest_runtest_logreport(self, report):
"""handle a setup/call/teardown report, generating the appropriate
xml tags as necessary.
note: due to plugins like xdist, this hook may be called in interlaced
order with reports from other nodes. for example:
usual call order:
-> setup node1
-> call node1
-> teardown node1
-> setup node2
-> call node2
-> teardown node2
possible call order in xdist:
-> setup node1
-> call node1
-> setup node2
-> call node2
-> teardown node2
-> teardown node1
"""
close_report = None
if report.passed:
if report.when == "call": # ignore setup/teardown
reporter = self._opentestcase(report)
reporter.append_pass(report)
elif report.failed:
if report.when == "teardown":
# The following vars are needed when xdist plugin is used
report_wid = getattr(report, "worker_id", None)
report_ii = getattr(report, "item_index", None)
close_report = next(
(rep for rep in self.open_reports
if (rep.nodeid == report.nodeid and
getattr(rep, "item_index", None) == report_ii and
getattr(rep, "worker_id", None) == report_wid
)
), None)
if close_report:
# We need to open new testcase in case we have failure in
# call and error in teardown in order to follow junit
# schema
self.finalize(close_report)
self.cnt_double_fail_tests += 1
reporter = self._opentestcase(report)
if report.when == "call":
reporter.append_failure(report)
self.open_reports.append(report)
else:
reporter.append_error(report)
elif report.skipped:
reporter = self._opentestcase(report)
reporter.append_skipped(report)
self.update_testcase_duration(report)
if report.when == "teardown":
reporter = self._opentestcase(report)
reporter.write_captured_output(report)
self.finalize(report)
report_wid = getattr(report, "worker_id", None)
report_ii = getattr(report, "item_index", None)
close_report = next(
(rep for rep in self.open_reports
if (rep.nodeid == report.nodeid and
getattr(rep, "item_index", None) == report_ii and
getattr(rep, "worker_id", None) == report_wid
)
), None)
if close_report:
self.open_reports.remove(close_report)
def update_testcase_duration(self, report):
"""accumulates total duration for nodeid from given report and updates
the Junit.testcase with the new total if already created.
"""
reporter = self.node_reporter(report)
reporter.duration += getattr(report, 'duration', 0.0)
def pytest_collectreport(self, report):
if not report.passed:
reporter = self._opentestcase(report)
if report.failed:
reporter.append_collect_error(report)
else:
reporter.append_collect_skipped(report)
def pytest_internalerror(self, excrepr):
reporter = self.node_reporter('internal')
reporter.attrs.update(classname="pytest", name='internal')
reporter._add_simple(Junit.error, 'internal error', excrepr)
def pytest_sessionstart(self):
self.suite_start_time = time.time()
def pytest_sessionfinish(self):
dirname = os.path.dirname(os.path.abspath(self.logfile))
if not os.path.isdir(dirname):
os.makedirs(dirname)
logfile = open(self.logfile, 'w', encoding='utf-8')
suite_stop_time = time.time()
suite_time_delta = suite_stop_time - self.suite_start_time
numtests = (self.stats['passed'] + self.stats['failure'] +
self.stats['skipped'] + self.stats['error'] -
self.cnt_double_fail_tests)
logfile.write('<?xml version="1.0" encoding="utf-8"?>')
logfile.write(Junit.testsuite(
self._get_global_properties_node(),
[x.to_xml() for x in self.node_reporters_ordered],
name=self.suite_name,
errors=self.stats['error'],
failures=self.stats['failure'],
skips=self.stats['skipped'],
tests=numtests,
time="%.3f" % suite_time_delta, ).unicode(indent=0))
logfile.close()
def pytest_terminal_summary(self, terminalreporter):
terminalreporter.write_sep("-",
"generated xml file: %s" % (self.logfile))
def add_global_property(self, name, value):
self.global_properties.append((str(name), bin_xml_escape(value)))
def _get_global_properties_node(self):
"""Return a Junit node containing custom properties, if any.
"""
if self.global_properties:
return Junit.properties(
[
Junit.property(name=name, value=value)
for name, value in self.global_properties
]
)
return ''
| mpl-2.0 |
js0701/chromium-crosswalk | third_party/WebKit/LayoutTests/http/tests/security/cookies/base-about-blank.html | 842 | <html>
<head>
<script>
if (window.testRunner) {
testRunner.dumpAsText();
testRunner.waitUntilDone();
}
document.cookie = "secret=PASS";
function log(msg) {
var line = document.createElement("div");
line.appendChild(document.createTextNode(msg));
document.getElementById("console").appendChild(line);
}
function runTest() {
log("Running test.");
frames[1].document.open();
log(frames[1].document.cookie);
frames[1].document.close();
log("Test complete.");
if (window.testRunner)
testRunner.notifyDone();
}
</script>
<base href="http://localhost:8000/security/cookies/resources/set-a-cookie.html">
</head>
<body>
<iframe
onload="runTest()"
src="http://localhost:8000/security/cookies/resources/set-a-cookie.html">
</iframe>
<iframe></iframe>
<div id="console"></div>
</body>
</html>
| bsd-3-clause |
froala/cdnjs | ajax/libs/timeago.js/2.0.0/timeago.js | 8824 | /**
* Copyright (c) 2016 hustcc
* License: MIT
* https://github.com/hustcc/timeago.js
**/
/* jshint expr: true */
!function (root, factory) {
if (typeof module === 'object' && module.exports)
module.exports = factory(root);
else
root.timeago = factory(root);
}(typeof window !== 'undefined' ? window : this,
function () {
var cnt = 0, // the timer counter, for timer key
indexMapEn = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year'],
indexMapZh = ['秒', '分钟', '小时', '天', '周', '月', '年'],
// build-in locales: en & zh_CN
locales = {
'en': function(number, index) {
if (index === 0) return ['just now', 'a while'];
else {
var unit = indexMapEn[parseInt(index / 2)];
if (number > 1) unit += 's';
return [number + ' ' + unit + ' ago', 'in ' + number + ' ' + unit];
}
},
'zh_CN': function(number, index) {
if (index === 0) return ['刚刚', '片刻后'];
else {
var unit = indexMapZh[parseInt(index / 2)];
return [number + unit + '前', number + unit + '后'];
}
}
},
// second, minute, hour, day, week, month, year(365 days)
SEC_ARRAY = [60, 60, 24, 7, 365/7/12, 12],
SEC_ARRAY_LEN = 6,
ATTR_DATETIME = 'datetime';
/**
* timeago: the function to get `timeago` instance.
* - nowDate: the relative date, default is new Date().
* - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you.
*
* How to use it?
* var timeagoLib = require('timeago.js');
* var timeago = timeagoLib(); // all use default.
* var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.
* var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`.
* var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前.
**/
function timeago(nowDate, defaultLocale) {
var timers = {}; // real-time render timers
// if do not set the defaultLocale, set it with `en`
if (! defaultLocale) defaultLocale = 'en'; // use default build-in locale
// calculate the diff second between date to be formated an now date.
function diffSec(date) {
var now = new Date();
if (nowDate) now = toDate(nowDate);
return (now - toDate(date)) / 1000;
}
// format the diff second to *** time ago, with setting locale
function formatDiff(diff, locale) {
if (! locales[locale]) locale = defaultLocale;
var i = 0;
agoin = diff < 0 ? 1 : 0, // timein or timeago
diff = Math.abs(diff);
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {
diff /= SEC_ARRAY[i];
}
diff = toInt(diff);
i *= 2;
if (diff > (i === 0 ? 9 : 1)) i += 1;
return locales[locale](diff, i)[agoin].replace('%s', diff);
}
/**
* format: format the date to *** time ago, with setting or default locale
* - date: the date / string / timestamp to be formated
* - locale: the formated string's locale name, e.g. en / zh_CN
*
* How to use it?
* var timeago = require('timeago.js')();
* timeago.format(new Date(), 'pl'); // Date instance
* timeago.format('2016-09-10', 'fr'); // formated date string
* timeago.format(1473473400269); // timestamp with ms
**/
this.format = function(date, locale) {
return formatDiff(diffSec(date), locale);
};
// format Date / string / timestamp to Date instance.
function toDate(input) {
if (input instanceof Date) {
return input;
} else if (!isNaN(input)) {
return new Date(toInt(input));
} else if (/^\d+$/.test(input)) {
return new Date(toInt(input, 10));
} else {
var s = (input || '').trim();
s = s.replace(/\.\d+/, '') // remove milliseconds
.replace(/-/, '/').replace(/-/, '/')
.replace(/T/, ' ').replace(/Z/, ' UTC')
.replace(/([\+\-]\d\d)\:?(\d\d)/, ' $1$2'); // -04:00 -> -0400
return new Date(s);
}
}
// change f into int, remove Decimal. just for code compression
function toInt(f) {
return parseInt(f);
}
// function leftSec(diff, unit) {
// diff = diff % unit;
// diff = diff ? unit - diff : unit;
// return Math.ceil(diff);
// }
/**
* nextInterval: calculate the next interval time.
* - diff: the diff sec between now and date to be formated.
*
* What's the meaning?
* diff = 61 then return 59
* diff = 3601 (an hour + 1 second), then return 3599
* make the interval with high performace.
**/
// this.nextInterval = function(diff) { // for dev test
function nextInterval(diff) {
var rst = 1, i = 0, d = diff;
for (; diff >= SEC_ARRAY[i] && i < SEC_ARRAY_LEN; i++) {
diff /= SEC_ARRAY[i];
rst *= SEC_ARRAY[i];
}
// return leftSec(d, rst);
d = d % rst;
d = d ? rst - d : rst;
return Math.ceil(d);
// }; // for dev test
}
// what the timer will do
function doRender(node, date, locale, cnt) {
var diff = diffSec(date);
node.innerHTML = formatDiff(diff, locale);
// waiting %s seconds, do the next render
timers['k' + cnt] = setTimeout(function() {
doRender(node, date, locale, cnt);
}, nextInterval(diff) * 1000);
}
// get the datetime attribute, jQuery and DOM
function getDateAttr(node) {
if (node.getAttribute) return node.getAttribute(ATTR_DATETIME);
if(node.attr) return node.attr(ATTR_DATETIME);
}
/**
* render: render the DOM real-time.
* - nodes: which nodes will be rendered.
* - locale: the locale name used to format date.
*
* How to use it?
* var timeago = new require('timeago.js')();
* // 1. javascript selector
* timeago.render(document.querySelectorAll('.need_to_be_rendered'));
* // 2. use jQuery selector
* timeago.render($('.need_to_be_rendered'), 'pl');
*
* Notice: please be sure the dom has attribute `datetime`.
**/
this.render = function(nodes, locale) {
if (nodes.length === undefined) nodes = [nodes];
for (var i = 0; i < nodes.length; i++) {
doRender(nodes[i], getDateAttr(nodes[i]), locale, ++ cnt); // render item
}
};
/**
* cancel: cancel all the timers which are doing real-time render.
*
* How to use it?
* var timeago = new require('timeago.js')();
* timeago.render(document.querySelectorAll('.need_to_be_rendered'));
* timeago.cancel(); // will stop all the timer, stop render in real time.
**/
this.cancel = function() {
for (var key in timers) {
clearTimeout(timers[key]);
}
timers = {};
};
/**
* setLocale: set the default locale name.
*
* How to use it?
* var timeago = require('timeago.js');
* timeago = new timeago();
* timeago.setLocale('fr');
**/
this.setLocale = function(locale) {
defaultLocale = locale;
};
return this;
}
/**
* timeago: the function to get `timeago` instance.
* - nowDate: the relative date, default is new Date().
* - defaultLocale: the default locale, default is en. if your set it, then the `locale` parameter of format is not needed of you.
*
* How to use it?
* var timeagoLib = require('timeago.js');
* var timeago = timeagoLib(); // all use default.
* var timeago = timeagoLib('2016-09-10'); // the relative date is 2016-09-10, so the 2016-09-11 will be 1 day ago.
* var timeago = timeagoLib(null, 'zh_CN'); // set default locale is `zh_CN`.
* var timeago = timeagoLib('2016-09-10', 'zh_CN'); // the relative date is 2016-09-10, and locale is zh_CN, so the 2016-09-11 will be 1天前.
**/
function timeagoFactory(nowDate, defaultLocale) {
return new timeago(nowDate, defaultLocale);
}
/**
* register: register a new language locale
* - locale: locale name, e.g. en / zh_CN, notice the standard.
* - localeFunc: the locale process function
*
* How to use it?
* var timeagoLib = require('timeago.js');
*
* timeagoLib.register('the locale name', the_locale_func);
* // or
* timeagoLib.register('pl', require('timeago.js/locales/pl'));
**/
timeagoFactory.register = function(locale, localeFunc) {
locales[locale] = localeFunc;
};
return timeagoFactory;
}); | mit |
bas-t/linux_media | drivers/net/ethernet/mellanox/mlxsw/cmd.h | 40398 | /*
* drivers/net/ethernet/mellanox/mlxsw/cmd.h
* Copyright (c) 2015 Mellanox Technologies. All rights reserved.
* Copyright (c) 2015 Jiri Pirko <[email protected]>
* Copyright (c) 2015 Ido Schimmel <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _MLXSW_CMD_H
#define _MLXSW_CMD_H
#include "item.h"
#define MLXSW_CMD_MBOX_SIZE 4096
static inline char *mlxsw_cmd_mbox_alloc(void)
{
return kzalloc(MLXSW_CMD_MBOX_SIZE, GFP_KERNEL);
}
static inline void mlxsw_cmd_mbox_free(char *mbox)
{
kfree(mbox);
}
static inline void mlxsw_cmd_mbox_zero(char *mbox)
{
memset(mbox, 0, MLXSW_CMD_MBOX_SIZE);
}
struct mlxsw_core;
int mlxsw_cmd_exec(struct mlxsw_core *mlxsw_core, u16 opcode, u8 opcode_mod,
u32 in_mod, bool out_mbox_direct,
char *in_mbox, size_t in_mbox_size,
char *out_mbox, size_t out_mbox_size);
static inline int mlxsw_cmd_exec_in(struct mlxsw_core *mlxsw_core, u16 opcode,
u8 opcode_mod, u32 in_mod, char *in_mbox,
size_t in_mbox_size)
{
return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false,
in_mbox, in_mbox_size, NULL, 0);
}
static inline int mlxsw_cmd_exec_out(struct mlxsw_core *mlxsw_core, u16 opcode,
u8 opcode_mod, u32 in_mod,
bool out_mbox_direct,
char *out_mbox, size_t out_mbox_size)
{
return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod,
out_mbox_direct, NULL, 0,
out_mbox, out_mbox_size);
}
static inline int mlxsw_cmd_exec_none(struct mlxsw_core *mlxsw_core, u16 opcode,
u8 opcode_mod, u32 in_mod)
{
return mlxsw_cmd_exec(mlxsw_core, opcode, opcode_mod, in_mod, false,
NULL, 0, NULL, 0);
}
enum mlxsw_cmd_opcode {
MLXSW_CMD_OPCODE_QUERY_FW = 0x004,
MLXSW_CMD_OPCODE_QUERY_BOARDINFO = 0x006,
MLXSW_CMD_OPCODE_QUERY_AQ_CAP = 0x003,
MLXSW_CMD_OPCODE_MAP_FA = 0xFFF,
MLXSW_CMD_OPCODE_UNMAP_FA = 0xFFE,
MLXSW_CMD_OPCODE_CONFIG_PROFILE = 0x100,
MLXSW_CMD_OPCODE_ACCESS_REG = 0x040,
MLXSW_CMD_OPCODE_SW2HW_DQ = 0x201,
MLXSW_CMD_OPCODE_HW2SW_DQ = 0x202,
MLXSW_CMD_OPCODE_2ERR_DQ = 0x01E,
MLXSW_CMD_OPCODE_QUERY_DQ = 0x022,
MLXSW_CMD_OPCODE_SW2HW_CQ = 0x016,
MLXSW_CMD_OPCODE_HW2SW_CQ = 0x017,
MLXSW_CMD_OPCODE_QUERY_CQ = 0x018,
MLXSW_CMD_OPCODE_SW2HW_EQ = 0x013,
MLXSW_CMD_OPCODE_HW2SW_EQ = 0x014,
MLXSW_CMD_OPCODE_QUERY_EQ = 0x015,
MLXSW_CMD_OPCODE_QUERY_RESOURCES = 0x101,
};
static inline const char *mlxsw_cmd_opcode_str(u16 opcode)
{
switch (opcode) {
case MLXSW_CMD_OPCODE_QUERY_FW:
return "QUERY_FW";
case MLXSW_CMD_OPCODE_QUERY_BOARDINFO:
return "QUERY_BOARDINFO";
case MLXSW_CMD_OPCODE_QUERY_AQ_CAP:
return "QUERY_AQ_CAP";
case MLXSW_CMD_OPCODE_MAP_FA:
return "MAP_FA";
case MLXSW_CMD_OPCODE_UNMAP_FA:
return "UNMAP_FA";
case MLXSW_CMD_OPCODE_CONFIG_PROFILE:
return "CONFIG_PROFILE";
case MLXSW_CMD_OPCODE_ACCESS_REG:
return "ACCESS_REG";
case MLXSW_CMD_OPCODE_SW2HW_DQ:
return "SW2HW_DQ";
case MLXSW_CMD_OPCODE_HW2SW_DQ:
return "HW2SW_DQ";
case MLXSW_CMD_OPCODE_2ERR_DQ:
return "2ERR_DQ";
case MLXSW_CMD_OPCODE_QUERY_DQ:
return "QUERY_DQ";
case MLXSW_CMD_OPCODE_SW2HW_CQ:
return "SW2HW_CQ";
case MLXSW_CMD_OPCODE_HW2SW_CQ:
return "HW2SW_CQ";
case MLXSW_CMD_OPCODE_QUERY_CQ:
return "QUERY_CQ";
case MLXSW_CMD_OPCODE_SW2HW_EQ:
return "SW2HW_EQ";
case MLXSW_CMD_OPCODE_HW2SW_EQ:
return "HW2SW_EQ";
case MLXSW_CMD_OPCODE_QUERY_EQ:
return "QUERY_EQ";
case MLXSW_CMD_OPCODE_QUERY_RESOURCES:
return "QUERY_RESOURCES";
default:
return "*UNKNOWN*";
}
}
enum mlxsw_cmd_status {
/* Command execution succeeded. */
MLXSW_CMD_STATUS_OK = 0x00,
/* Internal error (e.g. bus error) occurred while processing command. */
MLXSW_CMD_STATUS_INTERNAL_ERR = 0x01,
/* Operation/command not supported or opcode modifier not supported. */
MLXSW_CMD_STATUS_BAD_OP = 0x02,
/* Parameter not supported, parameter out of range. */
MLXSW_CMD_STATUS_BAD_PARAM = 0x03,
/* System was not enabled or bad system state. */
MLXSW_CMD_STATUS_BAD_SYS_STATE = 0x04,
/* Attempt to access reserved or unallocated resource, or resource in
* inappropriate ownership.
*/
MLXSW_CMD_STATUS_BAD_RESOURCE = 0x05,
/* Requested resource is currently executing a command. */
MLXSW_CMD_STATUS_RESOURCE_BUSY = 0x06,
/* Required capability exceeds device limits. */
MLXSW_CMD_STATUS_EXCEED_LIM = 0x08,
/* Resource is not in the appropriate state or ownership. */
MLXSW_CMD_STATUS_BAD_RES_STATE = 0x09,
/* Index out of range (might be beyond table size or attempt to
* access a reserved resource).
*/
MLXSW_CMD_STATUS_BAD_INDEX = 0x0A,
/* NVMEM checksum/CRC failed. */
MLXSW_CMD_STATUS_BAD_NVMEM = 0x0B,
/* Bad management packet (silently discarded). */
MLXSW_CMD_STATUS_BAD_PKT = 0x30,
};
static inline const char *mlxsw_cmd_status_str(u8 status)
{
switch (status) {
case MLXSW_CMD_STATUS_OK:
return "OK";
case MLXSW_CMD_STATUS_INTERNAL_ERR:
return "INTERNAL_ERR";
case MLXSW_CMD_STATUS_BAD_OP:
return "BAD_OP";
case MLXSW_CMD_STATUS_BAD_PARAM:
return "BAD_PARAM";
case MLXSW_CMD_STATUS_BAD_SYS_STATE:
return "BAD_SYS_STATE";
case MLXSW_CMD_STATUS_BAD_RESOURCE:
return "BAD_RESOURCE";
case MLXSW_CMD_STATUS_RESOURCE_BUSY:
return "RESOURCE_BUSY";
case MLXSW_CMD_STATUS_EXCEED_LIM:
return "EXCEED_LIM";
case MLXSW_CMD_STATUS_BAD_RES_STATE:
return "BAD_RES_STATE";
case MLXSW_CMD_STATUS_BAD_INDEX:
return "BAD_INDEX";
case MLXSW_CMD_STATUS_BAD_NVMEM:
return "BAD_NVMEM";
case MLXSW_CMD_STATUS_BAD_PKT:
return "BAD_PKT";
default:
return "*UNKNOWN*";
}
}
/* QUERY_FW - Query Firmware
* -------------------------
* OpMod == 0, INMmod == 0
* -----------------------
* The QUERY_FW command retrieves information related to firmware, command
* interface version and the amount of resources that should be allocated to
* the firmware.
*/
static inline int mlxsw_cmd_query_fw(struct mlxsw_core *mlxsw_core,
char *out_mbox)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_FW,
0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_query_fw_fw_pages
* Amount of physical memory to be allocatedfor firmware usage in 4KB pages.
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_pages, 0x00, 16, 16);
/* cmd_mbox_query_fw_fw_rev_major
* Firmware Revision - Major
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_major, 0x00, 0, 16);
/* cmd_mbox_query_fw_fw_rev_subminor
* Firmware Sub-minor version (Patch level)
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_subminor, 0x04, 16, 16);
/* cmd_mbox_query_fw_fw_rev_minor
* Firmware Revision - Minor
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_rev_minor, 0x04, 0, 16);
/* cmd_mbox_query_fw_core_clk
* Internal Clock Frequency (in MHz)
*/
MLXSW_ITEM32(cmd_mbox, query_fw, core_clk, 0x08, 16, 16);
/* cmd_mbox_query_fw_cmd_interface_rev
* Command Interface Interpreter Revision ID. This number is bumped up
* every time a non-backward-compatible change is done for the command
* interface. The current cmd_interface_rev is 1.
*/
MLXSW_ITEM32(cmd_mbox, query_fw, cmd_interface_rev, 0x08, 0, 16);
/* cmd_mbox_query_fw_dt
* If set, Debug Trace is supported
*/
MLXSW_ITEM32(cmd_mbox, query_fw, dt, 0x0C, 31, 1);
/* cmd_mbox_query_fw_api_version
* Indicates the version of the API, to enable software querying
* for compatibility. The current api_version is 1.
*/
MLXSW_ITEM32(cmd_mbox, query_fw, api_version, 0x0C, 0, 16);
/* cmd_mbox_query_fw_fw_hour
* Firmware timestamp - hour
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_hour, 0x10, 24, 8);
/* cmd_mbox_query_fw_fw_minutes
* Firmware timestamp - minutes
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_minutes, 0x10, 16, 8);
/* cmd_mbox_query_fw_fw_seconds
* Firmware timestamp - seconds
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_seconds, 0x10, 8, 8);
/* cmd_mbox_query_fw_fw_year
* Firmware timestamp - year
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_year, 0x14, 16, 16);
/* cmd_mbox_query_fw_fw_month
* Firmware timestamp - month
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_month, 0x14, 8, 8);
/* cmd_mbox_query_fw_fw_day
* Firmware timestamp - day
*/
MLXSW_ITEM32(cmd_mbox, query_fw, fw_day, 0x14, 0, 8);
/* cmd_mbox_query_fw_clr_int_base_offset
* Clear Interrupt register's offset from clr_int_bar register
* in PCI address space.
*/
MLXSW_ITEM64(cmd_mbox, query_fw, clr_int_base_offset, 0x20, 0, 64);
/* cmd_mbox_query_fw_clr_int_bar
* PCI base address register (BAR) where clr_int register is located.
* 00 - BAR 0-1 (64 bit BAR)
*/
MLXSW_ITEM32(cmd_mbox, query_fw, clr_int_bar, 0x28, 30, 2);
/* cmd_mbox_query_fw_error_buf_offset
* Read Only buffer for internal error reports of offset
* from error_buf_bar register in PCI address space).
*/
MLXSW_ITEM64(cmd_mbox, query_fw, error_buf_offset, 0x30, 0, 64);
/* cmd_mbox_query_fw_error_buf_size
* Internal error buffer size in DWORDs
*/
MLXSW_ITEM32(cmd_mbox, query_fw, error_buf_size, 0x38, 0, 32);
/* cmd_mbox_query_fw_error_int_bar
* PCI base address register (BAR) where error buffer
* register is located.
* 00 - BAR 0-1 (64 bit BAR)
*/
MLXSW_ITEM32(cmd_mbox, query_fw, error_int_bar, 0x3C, 30, 2);
/* cmd_mbox_query_fw_doorbell_page_offset
* Offset of the doorbell page
*/
MLXSW_ITEM64(cmd_mbox, query_fw, doorbell_page_offset, 0x40, 0, 64);
/* cmd_mbox_query_fw_doorbell_page_bar
* PCI base address register (BAR) of the doorbell page
* 00 - BAR 0-1 (64 bit BAR)
*/
MLXSW_ITEM32(cmd_mbox, query_fw, doorbell_page_bar, 0x48, 30, 2);
/* QUERY_BOARDINFO - Query Board Information
* -----------------------------------------
* OpMod == 0 (N/A), INMmod == 0 (N/A)
* -----------------------------------
* The QUERY_BOARDINFO command retrieves adapter specific parameters.
*/
static inline int mlxsw_cmd_boardinfo(struct mlxsw_core *mlxsw_core,
char *out_mbox)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_BOARDINFO,
0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_boardinfo_intapin
* When PCIe interrupt messages are being used, this value is used for clearing
* an interrupt. When using MSI-X, this register is not used.
*/
MLXSW_ITEM32(cmd_mbox, boardinfo, intapin, 0x10, 24, 8);
/* cmd_mbox_boardinfo_vsd_vendor_id
* PCISIG Vendor ID (www.pcisig.com/membership/vid_search) of the vendor
* specifying/formatting the VSD. The vsd_vendor_id identifies the management
* domain of the VSD/PSID data. Different vendors may choose different VSD/PSID
* format and encoding as long as they use their assigned vsd_vendor_id.
*/
MLXSW_ITEM32(cmd_mbox, boardinfo, vsd_vendor_id, 0x1C, 0, 16);
/* cmd_mbox_boardinfo_vsd
* Vendor Specific Data. The VSD string that is burnt to the Flash
* with the firmware.
*/
#define MLXSW_CMD_BOARDINFO_VSD_LEN 208
MLXSW_ITEM_BUF(cmd_mbox, boardinfo, vsd, 0x20, MLXSW_CMD_BOARDINFO_VSD_LEN);
/* cmd_mbox_boardinfo_psid
* The PSID field is a 16-ascii (byte) character string which acts as
* the board ID. The PSID format is used in conjunction with
* Mellanox vsd_vendor_id (15B3h).
*/
#define MLXSW_CMD_BOARDINFO_PSID_LEN 16
MLXSW_ITEM_BUF(cmd_mbox, boardinfo, psid, 0xF0, MLXSW_CMD_BOARDINFO_PSID_LEN);
/* QUERY_AQ_CAP - Query Asynchronous Queues Capabilities
* -----------------------------------------------------
* OpMod == 0 (N/A), INMmod == 0 (N/A)
* -----------------------------------
* The QUERY_AQ_CAP command returns the device asynchronous queues
* capabilities supported.
*/
static inline int mlxsw_cmd_query_aq_cap(struct mlxsw_core *mlxsw_core,
char *out_mbox)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_AQ_CAP,
0, 0, false, out_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_query_aq_cap_log_max_sdq_sz
* Log (base 2) of max WQEs allowed on SDQ.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_sdq_sz, 0x00, 24, 8);
/* cmd_mbox_query_aq_cap_max_num_sdqs
* Maximum number of SDQs.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_sdqs, 0x00, 0, 8);
/* cmd_mbox_query_aq_cap_log_max_rdq_sz
* Log (base 2) of max WQEs allowed on RDQ.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_rdq_sz, 0x04, 24, 8);
/* cmd_mbox_query_aq_cap_max_num_rdqs
* Maximum number of RDQs.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_rdqs, 0x04, 0, 8);
/* cmd_mbox_query_aq_cap_log_max_cq_sz
* Log (base 2) of max CQEs allowed on CQ.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_cq_sz, 0x08, 24, 8);
/* cmd_mbox_query_aq_cap_max_num_cqs
* Maximum number of CQs.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_cqs, 0x08, 0, 8);
/* cmd_mbox_query_aq_cap_log_max_eq_sz
* Log (base 2) of max EQEs allowed on EQ.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, log_max_eq_sz, 0x0C, 24, 8);
/* cmd_mbox_query_aq_cap_max_num_eqs
* Maximum number of EQs.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_num_eqs, 0x0C, 0, 8);
/* cmd_mbox_query_aq_cap_max_sg_sq
* The maximum S/G list elements in an DSQ. DSQ must not contain
* more S/G entries than indicated here.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_sq, 0x10, 8, 8);
/* cmd_mbox_query_aq_cap_
* The maximum S/G list elements in an DRQ. DRQ must not contain
* more S/G entries than indicated here.
*/
MLXSW_ITEM32(cmd_mbox, query_aq_cap, max_sg_rq, 0x10, 0, 8);
/* MAP_FA - Map Firmware Area
* --------------------------
* OpMod == 0 (N/A), INMmod == Number of VPM entries
* -------------------------------------------------
* The MAP_FA command passes physical pages to the switch. These pages
* are used to store the device firmware. MAP_FA can be executed multiple
* times until all the firmware area is mapped (the size that should be
* mapped is retrieved through the QUERY_FW command). All required pages
* must be mapped to finish the initialization phase. Physical memory
* passed in this command must be pinned.
*/
#define MLXSW_CMD_MAP_FA_VPM_ENTRIES_MAX 32
static inline int mlxsw_cmd_map_fa(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 vpm_entries_count)
{
return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_MAP_FA,
0, vpm_entries_count,
in_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_map_fa_pa
* Physical Address.
*/
MLXSW_ITEM64_INDEXED(cmd_mbox, map_fa, pa, 0x00, 12, 52, 0x08, 0x00, true);
/* cmd_mbox_map_fa_log2size
* Log (base 2) of the size in 4KB pages of the physical and contiguous memory
* that starts at PA_L/H.
*/
MLXSW_ITEM32_INDEXED(cmd_mbox, map_fa, log2size, 0x00, 0, 5, 0x08, 0x04, false);
/* UNMAP_FA - Unmap Firmware Area
* ------------------------------
* OpMod == 0 (N/A), INMmod == 0 (N/A)
* -----------------------------------
* The UNMAP_FA command unload the firmware and unmaps all the
* firmware area. After this command is completed the device will not access
* the pages that were mapped to the firmware area. After executing UNMAP_FA
* command, software reset must be done prior to execution of MAP_FW command.
*/
static inline int mlxsw_cmd_unmap_fa(struct mlxsw_core *mlxsw_core)
{
return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_UNMAP_FA, 0, 0);
}
/* QUERY_RESOURCES - Query chip resources
* --------------------------------------
* OpMod == 0 (N/A) , INMmod is index
* ----------------------------------
* The QUERY_RESOURCES command retrieves information related to chip resources
* by resource ID. Every command returns 32 entries. INmod is being use as base.
* for example, index 1 will return entries 32-63. When the tables end and there
* are no more sources in the table, will return resource id 0xFFF to indicate
* it.
*/
#define MLXSW_CMD_QUERY_RESOURCES_TABLE_END_ID 0xffff
#define MLXSW_CMD_QUERY_RESOURCES_MAX_QUERIES 100
#define MLXSW_CMD_QUERY_RESOURCES_PER_QUERY 32
static inline int mlxsw_cmd_query_resources(struct mlxsw_core *mlxsw_core,
char *out_mbox, int index)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_RESOURCES,
0, index, false, out_mbox,
MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_query_resource_id
* The resource id. 0xFFFF indicates table's end.
*/
MLXSW_ITEM32_INDEXED(cmd_mbox, query_resource, id, 0x00, 16, 16, 0x8, 0, false);
/* cmd_mbox_query_resource_data
* The resource
*/
MLXSW_ITEM64_INDEXED(cmd_mbox, query_resource, data,
0x00, 0, 40, 0x8, 0, false);
/* CONFIG_PROFILE (Set) - Configure Switch Profile
* ------------------------------
* OpMod == 1 (Set), INMmod == 0 (N/A)
* -----------------------------------
* The CONFIG_PROFILE command sets the switch profile. The command can be
* executed on the device only once at startup in order to allocate and
* configure all switch resources and prepare it for operational mode.
* It is not possible to change the device profile after the chip is
* in operational mode.
* Failure of the CONFIG_PROFILE command leaves the hardware in an indeterminate
* state therefore it is required to perform software reset to the device
* following an unsuccessful completion of the command. It is required
* to perform software reset to the device to change an existing profile.
*/
static inline int mlxsw_cmd_config_profile_set(struct mlxsw_core *mlxsw_core,
char *in_mbox)
{
return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_CONFIG_PROFILE,
1, 0, in_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_config_profile_set_max_vepa_channels
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_vepa_channels, 0x0C, 0, 1);
/* cmd_mbox_config_profile_set_max_lag
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_lag, 0x0C, 1, 1);
/* cmd_mbox_config_profile_set_max_port_per_lag
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_port_per_lag, 0x0C, 2, 1);
/* cmd_mbox_config_profile_set_max_mid
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_mid, 0x0C, 3, 1);
/* cmd_mbox_config_profile_set_max_pgt
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_pgt, 0x0C, 4, 1);
/* cmd_mbox_config_profile_set_max_system_port
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_system_port, 0x0C, 5, 1);
/* cmd_mbox_config_profile_set_max_vlan_groups
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_vlan_groups, 0x0C, 6, 1);
/* cmd_mbox_config_profile_set_max_regions
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_regions, 0x0C, 7, 1);
/* cmd_mbox_config_profile_set_flood_mode
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_flood_mode, 0x0C, 8, 1);
/* cmd_mbox_config_profile_set_max_flood_tables
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_flood_tables, 0x0C, 9, 1);
/* cmd_mbox_config_profile_set_max_ib_mc
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_ib_mc, 0x0C, 12, 1);
/* cmd_mbox_config_profile_set_max_pkey
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_max_pkey, 0x0C, 13, 1);
/* cmd_mbox_config_profile_set_adaptive_routing_group_cap
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile,
set_adaptive_routing_group_cap, 0x0C, 14, 1);
/* cmd_mbox_config_profile_set_ar_sec
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_ar_sec, 0x0C, 15, 1);
/* cmd_mbox_config_set_kvd_linear_size
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_linear_size, 0x0C, 24, 1);
/* cmd_mbox_config_set_kvd_hash_single_size
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_single_size, 0x0C, 25, 1);
/* cmd_mbox_config_set_kvd_hash_double_size
* Capability bit. Setting a bit to 1 configures the profile
* according to the mailbox contents.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, set_kvd_hash_double_size, 0x0C, 26, 1);
/* cmd_mbox_config_profile_max_vepa_channels
* Maximum number of VEPA channels per port (0 through 16)
* 0 - multi-channel VEPA is disabled
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_vepa_channels, 0x10, 0, 8);
/* cmd_mbox_config_profile_max_lag
* Maximum number of LAG IDs requested.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_lag, 0x14, 0, 16);
/* cmd_mbox_config_profile_max_port_per_lag
* Maximum number of ports per LAG requested.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_port_per_lag, 0x18, 0, 16);
/* cmd_mbox_config_profile_max_mid
* Maximum Multicast IDs.
* Multicast IDs are allocated from 0 to max_mid-1
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_mid, 0x1C, 0, 16);
/* cmd_mbox_config_profile_max_pgt
* Maximum records in the Port Group Table per Switch Partition.
* Port Group Table indexes are from 0 to max_pgt-1
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_pgt, 0x20, 0, 16);
/* cmd_mbox_config_profile_max_system_port
* The maximum number of system ports that can be allocated.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_system_port, 0x24, 0, 16);
/* cmd_mbox_config_profile_max_vlan_groups
* Maximum number VLAN Groups for VLAN binding.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_vlan_groups, 0x28, 0, 12);
/* cmd_mbox_config_profile_max_regions
* Maximum number of TCAM Regions.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_regions, 0x2C, 0, 16);
/* cmd_mbox_config_profile_max_flood_tables
* Maximum number of single-entry flooding tables. Different flooding tables
* can be associated with different packet types.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_flood_tables, 0x30, 16, 4);
/* cmd_mbox_config_profile_max_vid_flood_tables
* Maximum number of per-vid flooding tables. Flooding tables are associated
* to the different packet types for the different switch partitions.
* Table size is 4K entries covering all VID space.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_vid_flood_tables, 0x30, 8, 4);
/* cmd_mbox_config_profile_flood_mode
* Flooding mode to use.
* 0-2 - Backward compatible modes for SwitchX devices.
* 3 - Mixed mode, where:
* max_flood_tables indicates the number of single-entry tables.
* max_vid_flood_tables indicates the number of per-VID tables.
* max_fid_offset_flood_tables indicates the number of FID-offset tables.
* max_fid_flood_tables indicates the number of per-FID tables.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, flood_mode, 0x30, 0, 2);
/* cmd_mbox_config_profile_max_fid_offset_flood_tables
* Maximum number of FID-offset flooding tables.
*/
MLXSW_ITEM32(cmd_mbox, config_profile,
max_fid_offset_flood_tables, 0x34, 24, 4);
/* cmd_mbox_config_profile_fid_offset_flood_table_size
* The size (number of entries) of each FID-offset flood table.
*/
MLXSW_ITEM32(cmd_mbox, config_profile,
fid_offset_flood_table_size, 0x34, 0, 16);
/* cmd_mbox_config_profile_max_fid_flood_tables
* Maximum number of per-FID flooding tables.
*
* Note: This flooding tables cover special FIDs only (vFIDs), starting at
* FID value 4K and higher.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_fid_flood_tables, 0x38, 24, 4);
/* cmd_mbox_config_profile_fid_flood_table_size
* The size (number of entries) of each per-FID table.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, fid_flood_table_size, 0x38, 0, 16);
/* cmd_mbox_config_profile_max_ib_mc
* Maximum number of multicast FDB records for InfiniBand
* FDB (in 512 chunks) per InfiniBand switch partition.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_ib_mc, 0x40, 0, 15);
/* cmd_mbox_config_profile_max_pkey
* Maximum per port PKEY table size (for PKEY enforcement)
*/
MLXSW_ITEM32(cmd_mbox, config_profile, max_pkey, 0x44, 0, 15);
/* cmd_mbox_config_profile_ar_sec
* Primary/secondary capability
* Describes the number of adaptive routing sub-groups
* 0 - disable primary/secondary (single group)
* 1 - enable primary/secondary (2 sub-groups)
* 2 - 3 sub-groups: Not supported in SwitchX, SwitchX-2
* 3 - 4 sub-groups: Not supported in SwitchX, SwitchX-2
*/
MLXSW_ITEM32(cmd_mbox, config_profile, ar_sec, 0x4C, 24, 2);
/* cmd_mbox_config_profile_adaptive_routing_group_cap
* Adaptive Routing Group Capability. Indicates the number of AR groups
* supported. Note that when Primary/secondary is enabled, each
* primary/secondary couple consumes 2 adaptive routing entries.
*/
MLXSW_ITEM32(cmd_mbox, config_profile, adaptive_routing_group_cap, 0x4C, 0, 16);
/* cmd_mbox_config_profile_arn
* Adaptive Routing Notification Enable
* Not supported in SwitchX, SwitchX-2
*/
MLXSW_ITEM32(cmd_mbox, config_profile, arn, 0x50, 31, 1);
/* cmd_mbox_config_kvd_linear_size
* KVD Linear Size
* Valid for Spectrum only
* Allowed values are 128*N where N=0 or higher
*/
MLXSW_ITEM32(cmd_mbox, config_profile, kvd_linear_size, 0x54, 0, 24);
/* cmd_mbox_config_kvd_hash_single_size
* KVD Hash single-entries size
* Valid for Spectrum only
* Allowed values are 128*N where N=0 or higher
* Must be greater or equal to cap_min_kvd_hash_single_size
* Must be smaller or equal to cap_kvd_size - kvd_linear_size
*/
MLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_single_size, 0x58, 0, 24);
/* cmd_mbox_config_kvd_hash_double_size
* KVD Hash double-entries size (units of single-size entries)
* Valid for Spectrum only
* Allowed values are 128*N where N=0 or higher
* Must be either 0 or greater or equal to cap_min_kvd_hash_double_size
* Must be smaller or equal to cap_kvd_size - kvd_linear_size
*/
MLXSW_ITEM32(cmd_mbox, config_profile, kvd_hash_double_size, 0x5C, 0, 24);
/* cmd_mbox_config_profile_swid_config_mask
* Modify Switch Partition Configuration mask. When set, the configu-
* ration value for the Switch Partition are taken from the mailbox.
* When clear, the current configuration values are used.
* Bit 0 - set type
* Bit 1 - properties
* Other - reserved
*/
MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_mask,
0x60, 24, 8, 0x08, 0x00, false);
/* cmd_mbox_config_profile_swid_config_type
* Switch Partition type.
* 0000 - disabled (Switch Partition does not exist)
* 0001 - InfiniBand
* 0010 - Ethernet
* 1000 - router port (SwitchX-2 only)
* Other - reserved
*/
MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_type,
0x60, 20, 4, 0x08, 0x00, false);
/* cmd_mbox_config_profile_swid_config_properties
* Switch Partition properties.
*/
MLXSW_ITEM32_INDEXED(cmd_mbox, config_profile, swid_config_properties,
0x60, 0, 8, 0x08, 0x00, false);
/* ACCESS_REG - Access EMAD Supported Register
* ----------------------------------
* OpMod == 0 (N/A), INMmod == 0 (N/A)
* -------------------------------------
* The ACCESS_REG command supports accessing device registers. This access
* is mainly used for bootstrapping.
*/
static inline int mlxsw_cmd_access_reg(struct mlxsw_core *mlxsw_core,
char *in_mbox, char *out_mbox)
{
return mlxsw_cmd_exec(mlxsw_core, MLXSW_CMD_OPCODE_ACCESS_REG,
0, 0, false, in_mbox, MLXSW_CMD_MBOX_SIZE,
out_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* SW2HW_DQ - Software to Hardware DQ
* ----------------------------------
* OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)
* INMmod == DQ number
* ----------------------------------------------
* The SW2HW_DQ command transitions a descriptor queue from software to
* hardware ownership. The command enables posting WQEs and ringing DoorBells
* on the descriptor queue.
*/
static inline int __mlxsw_cmd_sw2hw_dq(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 dq_number,
u8 opcode_mod)
{
return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_DQ,
opcode_mod, dq_number,
in_mbox, MLXSW_CMD_MBOX_SIZE);
}
enum {
MLXSW_CMD_OPCODE_MOD_SDQ = 0,
MLXSW_CMD_OPCODE_MOD_RDQ = 1,
};
static inline int mlxsw_cmd_sw2hw_sdq(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 dq_number)
{
return __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number,
MLXSW_CMD_OPCODE_MOD_SDQ);
}
static inline int mlxsw_cmd_sw2hw_rdq(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 dq_number)
{
return __mlxsw_cmd_sw2hw_dq(mlxsw_core, in_mbox, dq_number,
MLXSW_CMD_OPCODE_MOD_RDQ);
}
/* cmd_mbox_sw2hw_dq_cq
* Number of the CQ that this Descriptor Queue reports completions to.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_dq, cq, 0x00, 24, 8);
/* cmd_mbox_sw2hw_dq_sdq_tclass
* SDQ: CPU Egress TClass
* RDQ: Reserved
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_dq, sdq_tclass, 0x00, 16, 6);
/* cmd_mbox_sw2hw_dq_log2_dq_sz
* Log (base 2) of the Descriptor Queue size in 4KB pages.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_dq, log2_dq_sz, 0x00, 0, 6);
/* cmd_mbox_sw2hw_dq_pa
* Physical Address.
*/
MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_dq, pa, 0x10, 12, 52, 0x08, 0x00, true);
/* HW2SW_DQ - Hardware to Software DQ
* ----------------------------------
* OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)
* INMmod == DQ number
* ----------------------------------------------
* The HW2SW_DQ command transitions a descriptor queue from hardware to
* software ownership. Incoming packets on the DQ are silently discarded,
* SW should not post descriptors on nonoperational DQs.
*/
static inline int __mlxsw_cmd_hw2sw_dq(struct mlxsw_core *mlxsw_core,
u32 dq_number, u8 opcode_mod)
{
return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_DQ,
opcode_mod, dq_number);
}
static inline int mlxsw_cmd_hw2sw_sdq(struct mlxsw_core *mlxsw_core,
u32 dq_number)
{
return __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number,
MLXSW_CMD_OPCODE_MOD_SDQ);
}
static inline int mlxsw_cmd_hw2sw_rdq(struct mlxsw_core *mlxsw_core,
u32 dq_number)
{
return __mlxsw_cmd_hw2sw_dq(mlxsw_core, dq_number,
MLXSW_CMD_OPCODE_MOD_RDQ);
}
/* 2ERR_DQ - To Error DQ
* ---------------------
* OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)
* INMmod == DQ number
* ----------------------------------------------
* The 2ERR_DQ command transitions the DQ into the error state from the state
* in which it has been. While the command is executed, some in-process
* descriptors may complete. Once the DQ transitions into the error state,
* if there are posted descriptors on the RDQ/SDQ, the hardware writes
* a completion with error (flushed) for all descriptors posted in the RDQ/SDQ.
* When the command is completed successfully, the DQ is already in
* the error state.
*/
static inline int __mlxsw_cmd_2err_dq(struct mlxsw_core *mlxsw_core,
u32 dq_number, u8 opcode_mod)
{
return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ,
opcode_mod, dq_number);
}
static inline int mlxsw_cmd_2err_sdq(struct mlxsw_core *mlxsw_core,
u32 dq_number)
{
return __mlxsw_cmd_2err_dq(mlxsw_core, dq_number,
MLXSW_CMD_OPCODE_MOD_SDQ);
}
static inline int mlxsw_cmd_2err_rdq(struct mlxsw_core *mlxsw_core,
u32 dq_number)
{
return __mlxsw_cmd_2err_dq(mlxsw_core, dq_number,
MLXSW_CMD_OPCODE_MOD_RDQ);
}
/* QUERY_DQ - Query DQ
* ---------------------
* OpMod == 0 (send DQ) / OpMod == 1 (receive DQ)
* INMmod == DQ number
* ----------------------------------------------
* The QUERY_DQ command retrieves a snapshot of DQ parameters from the hardware.
*
* Note: Output mailbox has the same format as SW2HW_DQ.
*/
static inline int __mlxsw_cmd_query_dq(struct mlxsw_core *mlxsw_core,
char *out_mbox, u32 dq_number,
u8 opcode_mod)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_2ERR_DQ,
opcode_mod, dq_number, false,
out_mbox, MLXSW_CMD_MBOX_SIZE);
}
static inline int mlxsw_cmd_query_sdq(struct mlxsw_core *mlxsw_core,
char *out_mbox, u32 dq_number)
{
return __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number,
MLXSW_CMD_OPCODE_MOD_SDQ);
}
static inline int mlxsw_cmd_query_rdq(struct mlxsw_core *mlxsw_core,
char *out_mbox, u32 dq_number)
{
return __mlxsw_cmd_query_dq(mlxsw_core, out_mbox, dq_number,
MLXSW_CMD_OPCODE_MOD_RDQ);
}
/* SW2HW_CQ - Software to Hardware CQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == CQ number
* -------------------------------------
* The SW2HW_CQ command transfers ownership of a CQ context entry from software
* to hardware. The command takes the CQ context entry from the input mailbox
* and stores it in the CQC in the ownership of the hardware. The command fails
* if the requested CQC entry is already in the ownership of the hardware.
*/
static inline int mlxsw_cmd_sw2hw_cq(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 cq_number)
{
return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_CQ,
0, cq_number, in_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_sw2hw_cq_cv
* CQE Version.
* 0 - CQE Version 0, 1 - CQE Version 1
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, cv, 0x00, 28, 4);
/* cmd_mbox_sw2hw_cq_c_eqn
* Event Queue this CQ reports completion events to.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, c_eqn, 0x00, 24, 1);
/* cmd_mbox_sw2hw_cq_oi
* When set, overrun ignore is enabled. When set, updates of
* CQ consumer counter (poll for completion) or Request completion
* notifications (Arm CQ) DoorBells should not be rung on that CQ.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, oi, 0x00, 12, 1);
/* cmd_mbox_sw2hw_cq_st
* Event delivery state machine
* 0x0 - FIRED
* 0x1 - ARMED (Request for Notification)
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, st, 0x00, 8, 1);
/* cmd_mbox_sw2hw_cq_log_cq_size
* Log (base 2) of the CQ size (in entries).
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, log_cq_size, 0x00, 0, 4);
/* cmd_mbox_sw2hw_cq_producer_counter
* Producer Counter. The counter is incremented for each CQE that is
* written by the HW to the CQ.
* Maintained by HW (valid for the QUERY_CQ command only)
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_cq, producer_counter, 0x04, 0, 16);
/* cmd_mbox_sw2hw_cq_pa
* Physical Address.
*/
MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_cq, pa, 0x10, 11, 53, 0x08, 0x00, true);
/* HW2SW_CQ - Hardware to Software CQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == CQ number
* -------------------------------------
* The HW2SW_CQ command transfers ownership of a CQ context entry from hardware
* to software. The CQC entry is invalidated as a result of this command.
*/
static inline int mlxsw_cmd_hw2sw_cq(struct mlxsw_core *mlxsw_core,
u32 cq_number)
{
return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_CQ,
0, cq_number);
}
/* QUERY_CQ - Query CQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == CQ number
* -------------------------------------
* The QUERY_CQ command retrieves a snapshot of the current CQ context entry.
* The command stores the snapshot in the output mailbox in the software format.
* Note that the CQ context state and values are not affected by the QUERY_CQ
* command. The QUERY_CQ command is for debug purposes only.
*
* Note: Output mailbox has the same format as SW2HW_CQ.
*/
static inline int mlxsw_cmd_query_cq(struct mlxsw_core *mlxsw_core,
char *out_mbox, u32 cq_number)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_CQ,
0, cq_number, false,
out_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* SW2HW_EQ - Software to Hardware EQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == EQ number
* -------------------------------------
* The SW2HW_EQ command transfers ownership of an EQ context entry from software
* to hardware. The command takes the EQ context entry from the input mailbox
* and stores it in the EQC in the ownership of the hardware. The command fails
* if the requested EQC entry is already in the ownership of the hardware.
*/
static inline int mlxsw_cmd_sw2hw_eq(struct mlxsw_core *mlxsw_core,
char *in_mbox, u32 eq_number)
{
return mlxsw_cmd_exec_in(mlxsw_core, MLXSW_CMD_OPCODE_SW2HW_EQ,
0, eq_number, in_mbox, MLXSW_CMD_MBOX_SIZE);
}
/* cmd_mbox_sw2hw_eq_int_msix
* When set, MSI-X cycles will be generated by this EQ.
* When cleared, an interrupt will be generated by this EQ.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_eq, int_msix, 0x00, 24, 1);
/* cmd_mbox_sw2hw_eq_int_oi
* When set, overrun ignore is enabled.
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_eq, oi, 0x00, 12, 1);
/* cmd_mbox_sw2hw_eq_int_st
* Event delivery state machine
* 0x0 - FIRED
* 0x1 - ARMED (Request for Notification)
* 0x11 - Always ARMED
* other - reserved
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_eq, st, 0x00, 8, 2);
/* cmd_mbox_sw2hw_eq_int_log_eq_size
* Log (base 2) of the EQ size (in entries).
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_eq, log_eq_size, 0x00, 0, 4);
/* cmd_mbox_sw2hw_eq_int_producer_counter
* Producer Counter. The counter is incremented for each EQE that is written
* by the HW to the EQ.
* Maintained by HW (valid for the QUERY_EQ command only)
*/
MLXSW_ITEM32(cmd_mbox, sw2hw_eq, producer_counter, 0x04, 0, 16);
/* cmd_mbox_sw2hw_eq_int_pa
* Physical Address.
*/
MLXSW_ITEM64_INDEXED(cmd_mbox, sw2hw_eq, pa, 0x10, 11, 53, 0x08, 0x00, true);
/* HW2SW_EQ - Hardware to Software EQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == EQ number
* -------------------------------------
*/
static inline int mlxsw_cmd_hw2sw_eq(struct mlxsw_core *mlxsw_core,
u32 eq_number)
{
return mlxsw_cmd_exec_none(mlxsw_core, MLXSW_CMD_OPCODE_HW2SW_EQ,
0, eq_number);
}
/* QUERY_EQ - Query EQ
* ----------------------------------
* OpMod == 0 (N/A), INMmod == EQ number
* -------------------------------------
*
* Note: Output mailbox has the same format as SW2HW_EQ.
*/
static inline int mlxsw_cmd_query_eq(struct mlxsw_core *mlxsw_core,
char *out_mbox, u32 eq_number)
{
return mlxsw_cmd_exec_out(mlxsw_core, MLXSW_CMD_OPCODE_QUERY_EQ,
0, eq_number, false,
out_mbox, MLXSW_CMD_MBOX_SIZE);
}
#endif
| gpl-2.0 |
imoseyon/leanKernel-d2vzw | drivers/media/video/msm_apexq/msm_mctl.c | 44450 | /* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/ioctl.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <linux/proc_fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <linux/android_pmem.h>
#include "msm.h"
#include "msm_csid.h"
#include "msm_csic.h"
#include "msm_csiphy.h"
#include "msm_ispif.h"
#include "msm_sensor.h"
#ifdef CONFIG_MSM_CAMERA_DEBUG
#define D(fmt, args...) pr_debug("msm_mctl: " fmt, ##args)
#else
#define D(fmt, args...) do {} while (0)
#endif
#define MSM_V4L2_SWFI_LATENCY 3
/* VFE required buffer number for streaming */
static struct msm_isp_color_fmt msm_isp_formats[] = {
{
.name = "NV12YUV",
.depth = 12,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV12,
.pxlcode = V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV21YUV",
.depth = 12,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV21,
.pxlcode = V4L2_MBUS_FMT_YUYV8_2X8, /* YUV sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV12BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV12,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV21BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV21,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV16BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV16,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV61BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV61,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "NV21BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_NV21,
.pxlcode = V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "YU12BAYER",
.depth = 8,
.bitsperpxl = 8,
.fourcc = V4L2_PIX_FMT_YUV420M,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "RAWBAYER",
.depth = 10,
.bitsperpxl = 10,
.fourcc = V4L2_PIX_FMT_SBGGR10,
.pxlcode = V4L2_MBUS_FMT_SBGGR10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
{
.name = "RAWBAYER",
.depth = 10,
.bitsperpxl = 10,
.fourcc = V4L2_PIX_FMT_SBGGR10,
.pxlcode = V4L2_MBUS_FMT_SGRBG10_1X10, /* Bayer sensor */
.colorspace = V4L2_COLORSPACE_JPEG,
},
};
/*
* V4l2 subdevice operations
*/
static int mctl_subdev_log_status(struct v4l2_subdev *sd)
{
return -EINVAL;
}
static long mctl_subdev_ioctl(struct v4l2_subdev *sd,
unsigned int cmd, void *arg)
{
struct msm_cam_media_controller *pmctl = NULL;
if (!sd) {
pr_err("%s: param is NULL", __func__);
return -EINVAL;
} else
pmctl = (struct msm_cam_media_controller *)
v4l2_get_subdevdata(sd);
return -EINVAL;
}
static int mctl_subdev_g_mbus_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
return -EINVAL;
}
static struct v4l2_subdev_core_ops mctl_subdev_core_ops = {
.log_status = mctl_subdev_log_status,
.ioctl = mctl_subdev_ioctl,
};
static struct v4l2_subdev_video_ops mctl_subdev_video_ops = {
.g_mbus_fmt = mctl_subdev_g_mbus_fmt,
};
static struct v4l2_subdev_ops mctl_subdev_ops = {
.core = &mctl_subdev_core_ops,
.video = &mctl_subdev_video_ops,
};
static int msm_get_sensor_info(struct msm_sync *sync,
void __user *arg)
{
int rc = 0;
struct msm_camsensor_info info;
struct msm_camera_sensor_info *sdata;
if (copy_from_user(&info,
arg,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_FROM_USER();
return -EFAULT;
}
sdata = sync->sdata;
D("%s: sensor_name %s\n", __func__, sdata->sensor_name);
memcpy(&info.name[0], sdata->sensor_name, MAX_SENSOR_NAME);
info.flash_enabled = sdata->flash_data->flash_type !=
MSM_CAMERA_FLASH_NONE;
/* copy back to user space */
if (copy_to_user((void *)arg,
&info,
sizeof(struct msm_camsensor_info))) {
ERR_COPY_TO_USER();
rc = -EFAULT;
}
return rc;
}
/* called by other subdev to notify any changes*/
static int msm_mctl_notify(struct msm_cam_media_controller *p_mctl,
unsigned int notification, void *arg)
{
int rc = -EINVAL;
struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);
struct msm_camera_sensor_info *sinfo =
(struct msm_camera_sensor_info *) s_ctrl->sensordata;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
uint8_t csid_core = camdev->csid_core;
switch (notification) {
case NOTIFY_CID_CHANGE:
/* reconfig the ISPIF*/
if (p_mctl->ispif_sdev) {
struct msm_ispif_params_list ispif_params;
ispif_params.len = 1;
ispif_params.params[0].intftype = PIX0;
ispif_params.params[0].cid_mask = 0x0001;
ispif_params.params[0].csid = csid_core;
rc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,
VIDIOC_MSM_ISPIF_CFG, &ispif_params);
if (rc < 0)
return rc;
}
break;
case NOTIFY_ISPIF_STREAM:
/* call ISPIF stream on/off */
rc = v4l2_subdev_call(p_mctl->ispif_sdev, video,
s_stream, (int)arg);
if (rc < 0)
return rc;
break;
case NOTIFY_ISP_MSG_EVT:
case NOTIFY_VFE_MSG_OUT:
case NOTIFY_VFE_MSG_STATS:
case NOTIFY_VFE_MSG_COMP_STATS:
case NOTIFY_VFE_BUF_EVT:
case NOTIFY_VFE_BUF_FREE_EVT:
if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) {
rc = p_mctl->isp_sdev->isp_notify(
p_mctl->isp_sdev->sd, notification, arg);
}
break;
case NOTIFY_VPE_MSG_EVT:
if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_notify) {
rc = p_mctl->isp_sdev->isp_notify(
p_mctl->isp_sdev->sd_vpe, notification, arg);
}
break;
case NOTIFY_PCLK_CHANGE:
rc = v4l2_subdev_call(p_mctl->isp_sdev->sd, video,
s_crystal_freq, *(uint32_t *)arg, 0);
break;
case NOTIFY_CSIPHY_CFG:
rc = v4l2_subdev_call(p_mctl->csiphy_sdev,
core, ioctl, VIDIOC_MSM_CSIPHY_CFG, arg);
break;
case NOTIFY_CSID_CFG:
rc = v4l2_subdev_call(p_mctl->csid_sdev,
core, ioctl, VIDIOC_MSM_CSID_CFG, arg);
break;
case NOTIFY_CSIC_CFG:
rc = v4l2_subdev_call(p_mctl->csic_sdev,
core, ioctl, VIDIOC_MSM_CSIC_CFG, arg);
break;
default:
break;
}
return rc;
}
static int msm_mctl_set_vfe_output_mode(struct msm_cam_media_controller
*p_mctl, void __user *arg)
{
int rc = 0;
if (copy_from_user(&p_mctl->vfe_output_mode,
(void __user *)arg, sizeof(p_mctl->vfe_output_mode))) {
pr_err("%s Copy from user failed ", __func__);
rc = -EFAULT;
} else {
pr_info("%s: mctl=0x%p, vfe output mode =0x%x",
__func__, p_mctl, p_mctl->vfe_output_mode);
}
return rc;
}
/* called by the server or the config nodes to handle user space
commands*/
static int msm_mctl_cmd(struct msm_cam_media_controller *p_mctl,
unsigned int cmd, unsigned long arg)
{
int rc = -EINVAL;
void __user *argp = (void __user *)arg;
if (!p_mctl) {
pr_err("%s: param is NULL", __func__);
return -EINVAL;
}
D("%s:%d: cmd %d\n", __func__, __LINE__, cmd);
/* ... call sensor, ISPIF or VEF subdev*/
switch (cmd) {
/* sensor config*/
case MSM_CAM_IOCTL_GET_SENSOR_INFO:
rc = msm_get_sensor_info(&p_mctl->sync, argp);
break;
case MSM_CAM_IOCTL_SENSOR_IO_CFG:
printk(KERN_DEBUG "MSM_CAM_IOCTL_SENSOR_IO_CFG\n");
rc = v4l2_subdev_call(p_mctl->sensor_sdev,
core, ioctl, VIDIOC_MSM_SENSOR_CFG, argp);
break;
case MSM_CAM_IOCTL_SENSOR_V4l2_S_CTRL: {
struct v4l2_control v4l2_ctrl;
CDBG("subdev call\n");
if (copy_from_user(&v4l2_ctrl,
(void *)argp,
sizeof(struct v4l2_control))) {
CDBG("copy fail\n");
return -EFAULT;
}
CDBG("subdev call ok\n");
rc = v4l2_subdev_call(p_mctl->sensor_sdev,
core, s_ctrl, &v4l2_ctrl);
break;
}
case MSM_CAM_IOCTL_SENSOR_V4l2_QUERY_CTRL: {
struct v4l2_queryctrl v4l2_qctrl;
CDBG("query called\n");
if (copy_from_user(&v4l2_qctrl,
(void *)argp,
sizeof(struct v4l2_queryctrl))) {
CDBG("copy fail\n");
rc = -EFAULT;
break;
}
rc = v4l2_subdev_call(p_mctl->sensor_sdev,
core, queryctrl, &v4l2_qctrl);
if (rc < 0) {
rc = -EFAULT;
break;
}
if (copy_to_user((void *)argp,
&v4l2_qctrl,
sizeof(struct v4l2_queryctrl))) {
rc = -EFAULT;
}
break;
}
case MSM_CAM_IOCTL_ACTUATOR_IO_CFG: {
struct msm_actuator_cfg_data act_data;
if (p_mctl->sync.actctrl.a_config) {
rc = p_mctl->sync.actctrl.a_config(argp);
} else {
rc = copy_from_user(
&act_data,
(void *)argp,
sizeof(struct msm_actuator_cfg_data));
if (rc != 0) {
rc = -EFAULT;
break;
}
act_data.is_af_supported = 0;
rc = copy_to_user((void *)argp,
&act_data,
sizeof(struct msm_actuator_cfg_data));
if (rc != 0) {
rc = -EFAULT;
break;
}
}
break;
}
case MSM_CAM_IOCTL_GET_KERNEL_SYSTEM_TIME: {
struct timeval timestamp;
if (copy_from_user(×tamp, argp, sizeof(timestamp))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else {
msm_mctl_gettimeofday(×tamp);
rc = copy_to_user((void *)argp,
×tamp, sizeof(timestamp));
}
break;
}
case MSM_CAM_IOCTL_FLASH_CTRL: {
struct flash_ctrl_data flash_info;
if (copy_from_user(&flash_info, argp, sizeof(flash_info))) {
ERR_COPY_FROM_USER();
rc = -EFAULT;
} else {
rc = msm_flash_ctrl(p_mctl->sync.sdata, &flash_info);
}
break;
}
case MSM_CAM_IOCTL_PICT_PP:
rc = msm_mctl_set_pp_key(p_mctl, (void __user *)arg);
break;
case MSM_CAM_IOCTL_PICT_PP_DIVERT_DONE:
rc = msm_mctl_pp_divert_done(p_mctl, (void __user *)arg);
break;
case MSM_CAM_IOCTL_PICT_PP_DONE:
rc = msm_mctl_pp_done(p_mctl, (void __user *)arg);
break;
case MSM_CAM_IOCTL_MCTL_POST_PROC:
rc = msm_mctl_pp_ioctl(p_mctl, cmd, arg);
break;
case MSM_CAM_IOCTL_RESERVE_FREE_FRAME:
rc = msm_mctl_pp_reserve_free_frame(p_mctl,
(void __user *)arg);
break;
case MSM_CAM_IOCTL_RELEASE_FREE_FRAME:
rc = msm_mctl_pp_release_free_frame(p_mctl,
(void __user *)arg);
break;
case MSM_CAM_IOCTL_SET_VFE_OUTPUT_TYPE:
rc = msm_mctl_set_vfe_output_mode(p_mctl,
(void __user *)arg);
break;
case MSM_CAM_IOCTL_MCTL_DIVERT_DONE:
rc = msm_mctl_pp_mctl_divert_done(p_mctl,
(void __user *)arg);
break;
/* ISFIF config*/
default:
/* ISP config*/
D("%s:%d: go to default. Calling msm_isp_config\n",
__func__, __LINE__);
rc = p_mctl->isp_sdev->isp_config(p_mctl, cmd, arg);
break;
}
D("%s: !!! cmd = %d, rc = %d\n",
__func__, _IOC_NR(cmd), rc);
return rc;
}
static int msm_mctl_subdev_match_core(struct device *dev, void *data)
{
int core_index = (int)data;
struct platform_device *pdev = to_platform_device(dev);
if (pdev->id == core_index)
return 1;
else
return 0;
}
static int msm_mctl_register_subdevs(struct msm_cam_media_controller *p_mctl,
int core_index)
{
struct device_driver *driver;
struct device *dev;
int rc = -ENODEV;
struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);
struct msm_camera_sensor_info *sinfo =
(struct msm_camera_sensor_info *) s_ctrl->sensordata;
struct msm_camera_device_platform_data *pdata = sinfo->pdata;
if (pdata->is_csiphy) {
/* register csiphy subdev */
driver = driver_find(MSM_CSIPHY_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, (void *)core_index,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->csiphy_sdev = dev_get_drvdata(dev);
// put_driver(driver);
}
/* if (pdata->is_csic) {
/ * register csic subdev * /
driver = driver_find(MSM_CSIC_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, (void *)core_index,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->csic_sdev = dev_get_drvdata(dev);
// put_driver(driver);
}
*/
if (pdata->is_csid) {
/* register csid subdev */
driver = driver_find(MSM_CSID_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, (void *)core_index,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->csid_sdev = dev_get_drvdata(dev);
// put_driver(driver);
}
if (pdata->is_ispif) {
/* register ispif subdev */
driver = driver_find(MSM_ISPIF_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, 0,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->ispif_sdev = dev_get_drvdata(dev);
// put_driver(driver);
}
/* register vfe subdev */
driver = driver_find(MSM_VFE_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, 0,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->isp_sdev->sd = dev_get_drvdata(dev);
// put_driver(driver);
if (pdata->is_vpe) {
/* register vfe subdev */
driver = driver_find(MSM_VPE_DRV_NAME, &platform_bus_type);
if (!driver)
goto out;
dev = driver_find_device(driver, NULL, 0,
msm_mctl_subdev_match_core);
if (!dev)
goto out_put_driver;
p_mctl->isp_sdev->sd_vpe = dev_get_drvdata(dev);
// put_driver(driver);
}
rc = 0;
/* register gemini subdev */
driver = driver_find(MSM_GEMINI_DRV_NAME, &platform_bus_type);
if (!driver) {
pr_err("%s:%d:Gemini: Failure: goto out\n",
__func__, __LINE__);
goto out;
}
pr_debug("%s:%d:Gemini: driver_find_device Gemini driver 0x%x\n",
__func__, __LINE__, (uint32_t)driver);
dev = driver_find_device(driver, NULL, NULL,
msm_mctl_subdev_match_core);
if (!dev) {
pr_err("%s:%d:Gemini: Failure goto out_put_driver\n",
__func__, __LINE__);
goto out_put_driver;
}
p_mctl->gemini_sdev = dev_get_drvdata(dev);
pr_debug("%s:%d:Gemini: After dev_get_drvdata gemini_sdev=0x%x\n",
__func__, __LINE__, (uint32_t)p_mctl->gemini_sdev);
if (p_mctl->gemini_sdev == NULL) {
pr_err("%s:%d:Gemini: Failure gemini_sdev is null\n",
__func__, __LINE__);
goto out_put_driver;
}
rc = 0;
return rc;
out_put_driver:
//put_driver(driver);
out:
return rc;
}
static int msm_mctl_open(struct msm_cam_media_controller *p_mctl,
const char *const apps_id)
{
int rc = 0;
struct msm_sync *sync = NULL;
struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);
struct msm_camera_sensor_info *sinfo =
(struct msm_camera_sensor_info *) s_ctrl->sensordata;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
uint8_t csid_core;
D("%s\n", __func__);
if (!p_mctl) {
pr_err("%s: param is NULL", __func__);
return -EINVAL;
}
/* msm_sync_init() muct be called before*/
sync = &(p_mctl->sync);
mutex_lock(&sync->lock);
/* open sub devices - once only*/
if (!sync->opencnt) {
uint32_t csid_version;
wake_lock(&sync->wake_lock);
csid_core = camdev->csid_core;
rc = msm_mctl_register_subdevs(p_mctl, csid_core);
if (rc < 0) {
pr_err("%s: msm_mctl_register_subdevs failed:%d\n",
__func__, rc);
goto register_sdev_failed;
}
/* then sensor - move sub dev later*/
rc = v4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 1);
if (rc < 0) {
pr_err("%s: isp init failed: %d\n", __func__, rc);
goto msm_open_done;
}
if (sync->actctrl.a_power_up)
rc = sync->actctrl.a_power_up(
sync->sdata->actuator_info);
if (rc < 0) {
pr_err("%s: act power failed:%d\n", __func__, rc);
goto msm_open_done;
}
if (camdev->is_csiphy) {
rc = v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,
VIDIOC_MSM_CSIPHY_INIT, NULL);
if (rc < 0) {
pr_err("%s: csiphy initialization failed %d\n",
__func__, rc);
goto csiphy_init_failed;
}
}
if (camdev->is_csid) {
rc = v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,
VIDIOC_MSM_CSID_INIT, &csid_version);
if (rc < 0) {
pr_err("%s: csid initialization failed %d\n",
__func__, rc);
goto csid_init_failed;
}
}
/* if (camdev->is_csic) {
rc = v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,
VIDIOC_MSM_CSIC_INIT, &csid_version);
if (rc < 0) {
pr_err("%s: csic initialization failed %d\n",
__func__, rc);
goto csic_init_failed;
}
}
*/
/* ISP first*/
if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_open)
rc = p_mctl->isp_sdev->isp_open(
p_mctl->isp_sdev->sd,
p_mctl->isp_sdev->sd_vpe,
p_mctl->gemini_sdev,
sync);
if (rc < 0) {
pr_err("%s: isp init failed: %d\n", __func__, rc);
goto isp_open_failed;
}
if (camdev->is_ispif) {
rc = v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,
VIDIOC_MSM_ISPIF_INIT, &csid_version);
if (rc < 0) {
pr_err("%s: ispif initialization failed %d\n",
__func__, rc);
goto ispif_init_failed;
}
}
if (camdev->is_ispif) {
pm_qos_add_request(p_mctl->pm_qos_req_list,
PM_QOS_CPU_DMA_LATENCY,
PM_QOS_DEFAULT_VALUE);
pm_qos_update_request(p_mctl->pm_qos_req_list,
MSM_V4L2_SWFI_LATENCY);
}
sync->apps_id = apps_id;
sync->opencnt++;
} else {
D("%s: camera is already open", __func__);
}
mutex_unlock(&sync->lock);
return rc;
ispif_init_failed:
if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release)
p_mctl->isp_sdev->isp_release(&p_mctl->sync,
p_mctl->gemini_sdev);
isp_open_failed:
/* if (camdev->is_csic)
if (v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,
VIDIOC_MSM_CSIC_RELEASE, NULL) < 0)
pr_err("%s: csic release failed %d\n", __func__, rc);
csic_init_failed:*/
if (camdev->is_csid)
if (v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,
VIDIOC_MSM_CSID_RELEASE, NULL) < 0)
pr_err("%s: csid release failed %d\n", __func__, rc);
csid_init_failed:
if (camdev->is_csiphy)
if (v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,
VIDIOC_MSM_CSIPHY_RELEASE, NULL) < 0)
pr_err("%s: csiphy release failed %d\n", __func__, rc);
csiphy_init_failed:
if (p_mctl->sync.actctrl.a_power_down)
p_mctl->sync.actctrl.a_power_down(
p_mctl->sync.sdata->actuator_info);
register_sdev_failed:
msm_open_done:
wake_unlock(&p_mctl->sync.wake_lock);
mutex_unlock(&sync->lock);
return rc;
}
static int msm_mctl_release(struct msm_cam_media_controller *p_mctl)
{
int rc = 0;
struct msm_sensor_ctrl_t *s_ctrl = get_sctrl(p_mctl->sensor_sdev);
struct msm_camera_sensor_info *sinfo =
(struct msm_camera_sensor_info *) s_ctrl->sensordata;
struct msm_camera_device_platform_data *camdev = sinfo->pdata;
v4l2_subdev_call(p_mctl->sensor_sdev, core, ioctl,
VIDIOC_MSM_SENSOR_RELEASE, NULL);
if (camdev->is_ispif) {
v4l2_subdev_call(p_mctl->ispif_sdev, core, ioctl,
VIDIOC_MSM_ISPIF_RELEASE, NULL);
}
/* if (camdev->is_csic) {
v4l2_subdev_call(p_mctl->csic_sdev, core, ioctl,
VIDIOC_MSM_CSIC_RELEASE, NULL);
}
*/
if (p_mctl->isp_sdev && p_mctl->isp_sdev->isp_release)
p_mctl->isp_sdev->isp_release(&p_mctl->sync,
p_mctl->gemini_sdev);
if (camdev->is_csid) {
v4l2_subdev_call(p_mctl->csid_sdev, core, ioctl,
VIDIOC_MSM_CSID_RELEASE, NULL);
}
if (camdev->is_csiphy) {
v4l2_subdev_call(p_mctl->csiphy_sdev, core, ioctl,
VIDIOC_MSM_CSIPHY_RELEASE, NULL);
}
if (camdev->is_ispif) {
pm_qos_update_request(p_mctl->pm_qos_req_list,
PM_QOS_DEFAULT_VALUE);
pm_qos_remove_request(p_mctl->pm_qos_req_list);
}
if (p_mctl->sync.actctrl.a_power_down)
p_mctl->sync.actctrl.a_power_down(
p_mctl->sync.sdata->actuator_info);
v4l2_subdev_call(p_mctl->sensor_sdev, core, s_power, 0);
wake_unlock(&p_mctl->sync.wake_lock);
return rc;
}
int msm_mctl_init_user_formats(struct msm_cam_v4l2_device *pcam)
{
struct v4l2_subdev *sd = pcam->mctl.sensor_sdev;
enum v4l2_mbus_pixelcode pxlcode;
int numfmt_sensor = 0;
int numfmt = 0;
int rc = 0;
int i, j;
D("%s\n", __func__);
while (!v4l2_subdev_call(sd, video, enum_mbus_fmt, numfmt_sensor,
&pxlcode))
numfmt_sensor++;
D("%s, numfmt_sensor = %d\n", __func__, numfmt_sensor);
if (!numfmt_sensor)
return -ENXIO;
pcam->usr_fmts = vmalloc(numfmt_sensor * ARRAY_SIZE(msm_isp_formats) *
sizeof(struct msm_isp_color_fmt));
if (!pcam->usr_fmts)
return -ENOMEM;
/* from sensor to ISP.. fill the data structure */
for (i = 0; i < numfmt_sensor; i++) {
rc = v4l2_subdev_call(sd, video, enum_mbus_fmt, i, &pxlcode);
D("rc is %d\n", rc);
if (rc < 0) {
vfree(pcam->usr_fmts);
return rc;
}
for (j = 0; j < ARRAY_SIZE(msm_isp_formats); j++) {
/* find the corresponding format */
if (pxlcode == msm_isp_formats[j].pxlcode) {
pcam->usr_fmts[numfmt] = msm_isp_formats[j];
D("pcam->usr_fmts=0x%x\n", (u32)pcam->usr_fmts);
D("format pxlcode 0x%x (0x%x) found\n",
pcam->usr_fmts[numfmt].pxlcode,
pcam->usr_fmts[numfmt].fourcc);
numfmt++;
}
}
}
pcam->num_fmts = numfmt;
if (numfmt == 0) {
pr_err("%s: No supported formats.\n", __func__);
vfree(pcam->usr_fmts);
return -EINVAL;
}
D("Found %d supported formats.\n", pcam->num_fmts);
/* set the default pxlcode, in any case, it will be set through
* setfmt */
return 0;
}
/* this function plug in the implementation of a v4l2_subdev */
int msm_mctl_init_module(struct msm_cam_v4l2_device *pcam)
{
struct msm_cam_media_controller *pmctl = NULL;
D("%s\n", __func__);
if (!pcam) {
pr_err("%s: param is NULL", __func__);
return -EINVAL;
} else
pmctl = &pcam->mctl;
pmctl->sync.opencnt = 0;
/* init module operations*/
pmctl->mctl_open = msm_mctl_open;
pmctl->mctl_cmd = msm_mctl_cmd;
pmctl->mctl_notify = msm_mctl_notify;
pmctl->mctl_release = msm_mctl_release;
/* init mctl buf */
msm_mctl_buf_init(pcam);
memset(&pmctl->pp_info, 0, sizeof(pmctl->pp_info));
pmctl->vfe_output_mode = 0;
spin_lock_init(&pmctl->pp_info.lock);
/* init sub device*/
v4l2_subdev_init(&(pmctl->mctl_sdev), &mctl_subdev_ops);
v4l2_set_subdevdata(&(pmctl->mctl_sdev), pmctl);
return 0;
}
/* mctl node v4l2_file_operations */
static int msm_mctl_dev_open(struct file *f)
{
int rc = -EINVAL, i;
/* get the video device */
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
struct msm_cam_v4l2_dev_inst *pcam_inst;
pr_err("%s : E ", __func__);
if (!pcam) {
pr_err("%s NULL pointer passed in!\n", __func__);
return rc;
}
mutex_lock(&pcam->mctl_node.dev_lock);
for (i = 0; i < MSM_DEV_INST_MAX; i++) {
if (pcam->mctl_node.dev_inst[i] == NULL)
break;
}
/* if no instance is available, return error */
if (i == MSM_DEV_INST_MAX) {
mutex_unlock(&pcam->mctl_node.dev_lock);
return rc;
}
pcam_inst = kzalloc(sizeof(struct msm_cam_v4l2_dev_inst), GFP_KERNEL);
if (!pcam_inst) {
mutex_unlock(&pcam->mctl_node.dev_lock);
return rc;
}
pcam_inst->sensor_pxlcode = pcam->usr_fmts[0].pxlcode;
pcam_inst->my_index = i;
pcam_inst->pcam = pcam;
pcam->mctl_node.dev_inst[i] = pcam_inst;
D("%s pcam_inst %p my_index = %d\n", __func__,
pcam_inst, pcam_inst->my_index);
D("%s for %s\n", __func__, pcam->pdev->name);
rc = msm_setup_v4l2_event_queue(&pcam_inst->eventHandle,
pcam->mctl_node.pvdev);
if (rc < 0) {
mutex_unlock(&pcam->mctl_node.dev_lock);
return rc;
}
pcam_inst->vbqueue_initialized = 0;
kref_get(&pcam->mctl.refcount);
f->private_data = &pcam_inst->eventHandle;
D("f->private_data = 0x%x, pcam = 0x%x\n",
(u32)f->private_data, (u32)pcam_inst);
mutex_unlock(&pcam->mctl_node.dev_lock);
D("%s : X ", __func__);
return rc;
}
static unsigned int msm_mctl_dev_poll(struct file *f,
struct poll_table_struct *wait)
{
int rc = 0;
struct msm_cam_v4l2_device *pcam;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
pcam = pcam_inst->pcam;
D("%s : E pcam_inst = %p", __func__, pcam_inst);
if (!pcam) {
pr_err("%s NULL pointer of camera device!\n", __func__);
return -EINVAL;
}
poll_wait(f, &(pcam_inst->eventHandle.wait), wait);
if (v4l2_event_pending(&pcam_inst->eventHandle)) {
rc |= POLLPRI;
D("%s Event available on mctl node ", __func__);
}
D("%s poll on vb2\n", __func__);
if (!pcam_inst->vid_bufq.streaming) {
D("%s vid_bufq.streaming is off, inst=0x%x\n",
__func__, (u32)pcam_inst);
return rc;
}
rc |= vb2_poll(&pcam_inst->vid_bufq, f, wait);
D("%s : X ", __func__);
return rc;
}
static int msm_mctl_dev_close(struct file *f)
{
int rc = 0;
struct msm_cam_v4l2_device *pcam;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
pcam = pcam_inst->pcam;
pr_err("%s : E ", __func__);
if (!pcam) {
pr_err("%s NULL pointer of camera device!\n", __func__);
return -EINVAL;
}
mutex_lock(&pcam->mctl_node.dev_lock);
pcam_inst->streamon = 0;
pcam->mctl_node.dev_inst_map[pcam_inst->image_mode] = NULL;
if (pcam_inst->vbqueue_initialized)
vb2_queue_release(&pcam_inst->vid_bufq);
D("%s Closing down instance %p ", __func__, pcam_inst);
pcam->mctl_node.dev_inst[pcam_inst->my_index] = NULL;
v4l2_fh_del(&pcam_inst->eventHandle);
v4l2_fh_exit(&pcam_inst->eventHandle);
kfree(pcam_inst);
kref_put(&pcam->mctl.refcount, msm_release_ion_client);
f->private_data = NULL;
mutex_unlock(&pcam->mctl_node.dev_lock);
D("%s : X ", __func__);
return rc;
}
static struct v4l2_file_operations g_msm_mctl_fops = {
.owner = THIS_MODULE,
.open = msm_mctl_dev_open,
.poll = msm_mctl_dev_poll,
.release = msm_mctl_dev_close,
.unlocked_ioctl = video_ioctl2,
};
/*
*
* implementation of mctl node v4l2_ioctl_ops
*
*/
static int msm_mctl_v4l2_querycap(struct file *f, void *pctx,
struct v4l2_capability *pcaps)
{
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
strlcpy(pcaps->driver, pcam->pdev->name, sizeof(pcaps->driver));
pcaps->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
return 0;
}
static int msm_mctl_v4l2_queryctrl(struct file *f, void *pctx,
struct v4l2_queryctrl *pqctrl)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_g_ctrl(struct file *f, void *pctx,
struct v4l2_control *c)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_s_ctrl(struct file *f, void *pctx,
struct v4l2_control *ctrl)
{
int rc = 0;
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
mutex_lock(&pcam->mctl_node.dev_lock);
if (ctrl->id == MSM_V4L2_PID_PP_PLANE_INFO) {
if (copy_from_user(&pcam_inst->plane_info,
(void *)ctrl->value,
sizeof(struct img_plane_info))) {
pr_err("%s inst %p Copying plane_info failed ",
__func__, pcam_inst);
rc = -EFAULT;
}
D("%s inst %p got plane info: num_planes = %d,"
"plane size = %ld %ld ", __func__, pcam_inst,
pcam_inst->plane_info.num_planes,
pcam_inst->plane_info.plane[0].size,
pcam_inst->plane_info.plane[1].size);
} else
pr_err("%s Unsupported S_CTRL Value ", __func__);
mutex_unlock(&pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_reqbufs(struct file *f, void *pctx,
struct v4l2_requestbuffers *pb)
{
int rc = 0, i, j;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
rc = vb2_reqbufs(&pcam_inst->vid_bufq, pb);
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
if (rc < 0) {
pr_err("%s reqbufs failed %d ", __func__, rc);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
if (!pb->count) {
/* Deallocation. free buf_offset array */
D("%s Inst %p freeing buffer offsets array",
__func__, pcam_inst);
for (j = 0 ; j < pcam_inst->buf_count ; j++)
kfree(pcam_inst->buf_offset[j]);
kfree(pcam_inst->buf_offset);
pcam_inst->buf_offset = NULL;
/* If the userspace has deallocated all the
* buffers, then release the vb2 queue */
if (pcam_inst->vbqueue_initialized) {
vb2_queue_release(&pcam_inst->vid_bufq);
pcam_inst->vbqueue_initialized = 0;
}
} else {
D("%s Inst %p Allocating buf_offset array",
__func__, pcam_inst);
/* Allocation. allocate buf_offset array */
pcam_inst->buf_offset = (struct msm_cam_buf_offset **)
kzalloc(pb->count * sizeof(struct msm_cam_buf_offset *),
GFP_KERNEL);
if (!pcam_inst->buf_offset) {
pr_err("%s out of memory ", __func__);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -ENOMEM;
}
for (i = 0; i < pb->count; i++) {
pcam_inst->buf_offset[i] =
kzalloc(sizeof(struct msm_cam_buf_offset) *
pcam_inst->plane_info.num_planes, GFP_KERNEL);
if (!pcam_inst->buf_offset[i]) {
pr_err("%s out of memory ", __func__);
for (j = i-1 ; j >= 0; j--)
kfree(pcam_inst->buf_offset[j]);
kfree(pcam_inst->buf_offset);
pcam_inst->buf_offset = NULL;
mutex_unlock(
&pcam_inst->pcam->mctl_node.dev_lock);
return -ENOMEM;
}
}
}
pcam_inst->buf_count = pb->count;
D("%s inst %p, buf count %d ", __func__,
pcam_inst, pcam_inst->buf_count);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_querybuf(struct file *f, void *pctx,
struct v4l2_buffer *pb)
{
/* get the video device */
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return vb2_querybuf(&pcam_inst->vid_bufq, pb);
}
static int msm_mctl_v4l2_qbuf(struct file *f, void *pctx,
struct v4l2_buffer *pb)
{
int rc = 0, i = 0;
/* get the camera device */
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s Inst = %p\n", __func__, pcam_inst);
WARN_ON(pctx != f->private_data);
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
if (!pcam_inst->buf_offset) {
pr_err("%s Buffer is already released. Returning. ", __func__);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -EINVAL;
}
if (pb->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
/* Reject the buffer if planes array was not allocated */
if (pb->m.planes == NULL) {
pr_err("%s Planes array is null ", __func__);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -EINVAL;
}
for (i = 0; i < pcam_inst->plane_info.num_planes; i++) {
D("%s stored offsets for plane %d as"
"addr offset %d, data offset %d",
__func__, i, pb->m.planes[i].reserved[0],
pb->m.planes[i].data_offset);
pcam_inst->buf_offset[pb->index][i].data_offset =
pb->m.planes[i].data_offset;
pcam_inst->buf_offset[pb->index][i].addr_offset =
pb->m.planes[i].reserved[0];
}
} else {
D("%s stored reserved info %d", __func__, pb->reserved);
pcam_inst->buf_offset[pb->index][0].addr_offset = pb->reserved;
}
rc = vb2_qbuf(&pcam_inst->vid_bufq, pb);
D("%s, videobuf_qbuf returns %d\n", __func__, rc);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_dqbuf(struct file *f, void *pctx,
struct v4l2_buffer *pb)
{
int rc = 0;
/* get the camera device */
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
rc = vb2_dqbuf(&pcam_inst->vid_bufq, pb, f->f_flags & O_NONBLOCK);
D("%s, videobuf_dqbuf returns %d\n", __func__, rc);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_streamon(struct file *f, void *pctx,
enum v4l2_buf_type buf_type)
{
int rc = 0;
/* get the camera device */
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s Inst %p\n", __func__, pcam_inst);
WARN_ON(pctx != f->private_data);
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
if ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&
(buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) {
pr_err("%s Invalid buffer type ", __func__);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -EINVAL;
}
D("%s Calling videobuf_streamon", __func__);
/* if HW streaming on is successful, start buffer streaming */
rc = vb2_streamon(&pcam_inst->vid_bufq, buf_type);
D("%s, videobuf_streamon returns %d\n", __func__, rc);
/* turn HW (VFE/sensor) streaming */
pcam_inst->streamon = 1;
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
D("%s rc = %d\n", __func__, rc);
return rc;
}
static int msm_mctl_v4l2_streamoff(struct file *f, void *pctx,
enum v4l2_buf_type buf_type)
{
int rc = 0;
/* get the camera device */
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s Inst %p\n", __func__, pcam_inst);
WARN_ON(pctx != f->private_data);
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
if ((buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&
(buf_type != V4L2_BUF_TYPE_VIDEO_CAPTURE)) {
pr_err("%s Invalid buffer type ", __func__);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -EINVAL;
}
/* first turn of HW (VFE/sensor) streaming so that buffers are
not in use when we free the buffers */
pcam_inst->streamon = 0;
/* stop buffer streaming */
rc = vb2_streamoff(&pcam_inst->vid_bufq, buf_type);
D("%s, videobuf_streamoff returns %d\n", __func__, rc);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_enum_fmt_cap(struct file *f, void *pctx,
struct v4l2_fmtdesc *pfmtdesc)
{
/* get the video device */
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
const struct msm_isp_color_fmt *isp_fmt;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
if ((pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) &&
(pfmtdesc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE))
return -EINVAL;
if (pfmtdesc->index >= pcam->num_fmts)
return -EINVAL;
isp_fmt = &pcam->usr_fmts[pfmtdesc->index];
if (isp_fmt->name)
strlcpy(pfmtdesc->description, isp_fmt->name,
sizeof(pfmtdesc->description));
pfmtdesc->pixelformat = isp_fmt->fourcc;
D("%s: [%d] 0x%x, %s\n", __func__, pfmtdesc->index,
isp_fmt->fourcc, isp_fmt->name);
return 0;
}
static int msm_mctl_v4l2_g_fmt_cap(struct file *f,
void *pctx, struct v4l2_format *pfmt)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
if (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
return rc;
}
static int msm_mctl_v4l2_g_fmt_cap_mplane(struct file *f,
void *pctx, struct v4l2_format *pfmt)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
if (pfmt->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)
return -EINVAL;
return rc;
}
/* This function will readjust the format parameters based in HW
capabilities. Called by s_fmt_cap
*/
static int msm_mctl_v4l2_try_fmt_cap(struct file *f, void *pctx,
struct v4l2_format *pfmt)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_try_fmt_cap_mplane(struct file *f, void *pctx,
struct v4l2_format *pfmt)
{
int rc = 0;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
/* This function will reconfig the v4l2 driver and HW device, it should be
called after the streaming is stopped.
*/
static int msm_mctl_v4l2_s_fmt_cap(struct file *f, void *pctx,
struct v4l2_format *pfmt)
{
int rc = 0;
/* get the video device */
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s\n", __func__);
D("%s, inst=0x%x,idx=%d,priv = 0x%p\n",
__func__, (u32)pcam_inst, pcam_inst->my_index,
(void *)pfmt->fmt.pix.priv);
WARN_ON(pctx != f->private_data);
if (!pcam_inst->vbqueue_initialized) {
pcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq,
V4L2_BUF_TYPE_VIDEO_CAPTURE);
pcam_inst->vbqueue_initialized = 1;
}
return rc;
}
static int msm_mctl_v4l2_s_fmt_cap_mplane(struct file *f, void *pctx,
struct v4l2_format *pfmt)
{
int rc = 0, i;
struct msm_cam_v4l2_device *pcam = video_drvdata(f);
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s Inst %p vbqueue %d\n", __func__,
pcam_inst, pcam_inst->vbqueue_initialized);
WARN_ON(pctx != f->private_data);
if (!pcam_inst->vbqueue_initialized) {
pcam->mctl.mctl_vbqueue_init(pcam_inst, &pcam_inst->vid_bufq,
V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
pcam_inst->vbqueue_initialized = 1;
}
for (i = 0; i < pcam->num_fmts; i++)
if (pcam->usr_fmts[i].fourcc == pfmt->fmt.pix_mp.pixelformat)
break;
if (i == pcam->num_fmts) {
pr_err("%s: User requested pixelformat %x not supported\n",
__func__, pfmt->fmt.pix_mp.pixelformat);
return -EINVAL;
}
pcam_inst->vid_fmt = *pfmt;
pcam_inst->sensor_pxlcode =
pcam->usr_fmts[i].pxlcode;
D("%s: inst=%p, width=%d, heigth=%d\n",
__func__, pcam_inst,
pcam_inst->vid_fmt.fmt.pix_mp.width,
pcam_inst->vid_fmt.fmt.pix_mp.height);
return rc;
}
static int msm_mctl_v4l2_g_jpegcomp(struct file *f, void *pctx,
struct v4l2_jpegcompression *pcomp)
{
int rc = -EINVAL;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_s_jpegcomp(struct file *f, void *pctx,
struct v4l2_jpegcompression *pcomp)
{
int rc = -EINVAL;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_g_crop(struct file *f, void *pctx,
struct v4l2_crop *crop)
{
int rc = -EINVAL;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
static int msm_mctl_v4l2_s_crop(struct file *f, void *pctx,
struct v4l2_crop *a)
{
int rc = -EINVAL;
D("%s\n", __func__);
WARN_ON(pctx != f->private_data);
return rc;
}
/* Stream type-dependent parameter ioctls */
static int msm_mctl_v4l2_g_parm(struct file *f, void *pctx,
struct v4l2_streamparm *a)
{
int rc = -EINVAL;
return rc;
}
static int msm_mctl_vidbuf_get_path(u32 extendedmode)
{
switch (extendedmode) {
case MSM_V4L2_EXT_CAPTURE_MODE_THUMBNAIL:
return OUTPUT_TYPE_T;
case MSM_V4L2_EXT_CAPTURE_MODE_MAIN:
return OUTPUT_TYPE_S;
case MSM_V4L2_EXT_CAPTURE_MODE_VIDEO:
return OUTPUT_TYPE_V;
case MSM_V4L2_EXT_CAPTURE_MODE_DEFAULT:
case MSM_V4L2_EXT_CAPTURE_MODE_PREVIEW:
default:
return OUTPUT_TYPE_P;
}
}
static int msm_mctl_v4l2_s_parm(struct file *f, void *pctx,
struct v4l2_streamparm *a)
{
int rc = 0;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst = container_of(f->private_data,
struct msm_cam_v4l2_dev_inst, eventHandle);
pcam_inst->image_mode = a->parm.capture.extendedmode;
mutex_lock(&pcam_inst->pcam->mctl_node.dev_lock);
if (pcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode]) {
pr_err("%s Stream type %d already used.",
__func__, pcam_inst->image_mode);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return -EBUSY;
}
pcam_inst->pcam->mctl_node.dev_inst_map[pcam_inst->image_mode] =
pcam_inst;
pcam_inst->path = msm_mctl_vidbuf_get_path(pcam_inst->image_mode);
D("%s path=%d, image mode = %d rc=%d\n", __func__,
pcam_inst->path, pcam_inst->image_mode, rc);
mutex_unlock(&pcam_inst->pcam->mctl_node.dev_lock);
return rc;
}
static int msm_mctl_v4l2_subscribe_event(struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
int rc = 0;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst =
(struct msm_cam_v4l2_dev_inst *)container_of(fh,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s:fh = 0x%x, type = 0x%x\n", __func__, (u32)fh, sub->type);
if (sub->type == V4L2_EVENT_ALL)
sub->type = V4L2_EVENT_PRIVATE_START+MSM_CAM_APP_NOTIFY_EVENT;
rc = v4l2_event_subscribe(fh, sub, 30);
if (rc < 0)
pr_err("%s: failed for evtType = 0x%x, rc = %d\n",
__func__, sub->type, rc);
return rc;
}
static int msm_mctl_v4l2_unsubscribe_event(struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
int rc = 0;
struct msm_cam_v4l2_dev_inst *pcam_inst;
pcam_inst =
(struct msm_cam_v4l2_dev_inst *)container_of(fh,
struct msm_cam_v4l2_dev_inst, eventHandle);
D("%s: fh = 0x%x\n", __func__, (u32)fh);
rc = v4l2_event_unsubscribe(fh, sub);
D("%s: rc = %d\n", __func__, rc);
return rc;
}
/* mctl node v4l2_ioctl_ops */
static const struct v4l2_ioctl_ops g_msm_mctl_ioctl_ops = {
.vidioc_querycap = msm_mctl_v4l2_querycap,
.vidioc_s_crop = msm_mctl_v4l2_s_crop,
.vidioc_g_crop = msm_mctl_v4l2_g_crop,
.vidioc_queryctrl = msm_mctl_v4l2_queryctrl,
.vidioc_g_ctrl = msm_mctl_v4l2_g_ctrl,
.vidioc_s_ctrl = msm_mctl_v4l2_s_ctrl,
.vidioc_reqbufs = msm_mctl_v4l2_reqbufs,
.vidioc_querybuf = msm_mctl_v4l2_querybuf,
.vidioc_qbuf = msm_mctl_v4l2_qbuf,
.vidioc_dqbuf = msm_mctl_v4l2_dqbuf,
.vidioc_streamon = msm_mctl_v4l2_streamon,
.vidioc_streamoff = msm_mctl_v4l2_streamoff,
/* format ioctls */
.vidioc_enum_fmt_vid_cap = msm_mctl_v4l2_enum_fmt_cap,
.vidioc_enum_fmt_vid_cap_mplane = msm_mctl_v4l2_enum_fmt_cap,
.vidioc_try_fmt_vid_cap = msm_mctl_v4l2_try_fmt_cap,
.vidioc_try_fmt_vid_cap_mplane = msm_mctl_v4l2_try_fmt_cap_mplane,
.vidioc_g_fmt_vid_cap = msm_mctl_v4l2_g_fmt_cap,
.vidioc_g_fmt_vid_cap_mplane = msm_mctl_v4l2_g_fmt_cap_mplane,
.vidioc_s_fmt_vid_cap = msm_mctl_v4l2_s_fmt_cap,
.vidioc_s_fmt_vid_cap_mplane = msm_mctl_v4l2_s_fmt_cap_mplane,
.vidioc_g_jpegcomp = msm_mctl_v4l2_g_jpegcomp,
.vidioc_s_jpegcomp = msm_mctl_v4l2_s_jpegcomp,
/* Stream type-dependent parameter ioctls */
.vidioc_g_parm = msm_mctl_v4l2_g_parm,
.vidioc_s_parm = msm_mctl_v4l2_s_parm,
/* event subscribe/unsubscribe */
.vidioc_subscribe_event = msm_mctl_v4l2_subscribe_event,
.vidioc_unsubscribe_event = msm_mctl_v4l2_unsubscribe_event,
};
int msm_setup_mctl_node(struct msm_cam_v4l2_device *pcam)
{
int rc = -EINVAL;
struct video_device *pvdev = NULL;
struct i2c_client *client = v4l2_get_subdevdata(pcam->mctl.sensor_sdev);
D("%s\n", __func__);
/* first register the v4l2 device */
pcam->mctl_node.v4l2_dev.dev = &client->dev;
rc = v4l2_device_register(pcam->mctl_node.v4l2_dev.dev,
&pcam->mctl_node.v4l2_dev);
if (rc < 0)
return -EINVAL;
/* else
pcam->v4l2_dev.notify = msm_cam_v4l2_subdev_notify; */
/* now setup video device */
pvdev = video_device_alloc();
if (pvdev == NULL) {
pr_err("%s: video_device_alloc failed\n", __func__);
return rc;
}
/* init video device's driver interface */
D("sensor name = %s, sizeof(pvdev->name)=%d\n",
pcam->mctl.sensor_sdev->name, sizeof(pvdev->name));
/* device info - strlcpy is safer than strncpy but
only if architecture supports*/
strlcpy(pvdev->name, pcam->mctl.sensor_sdev->name,
sizeof(pvdev->name));
pvdev->release = video_device_release;
pvdev->fops = &g_msm_mctl_fops;
pvdev->ioctl_ops = &g_msm_mctl_ioctl_ops;
pvdev->minor = -1;
pvdev->vfl_type = 1;
/* register v4l2 video device to kernel as /dev/videoXX */
D("%s video_register_device\n", __func__);
rc = video_register_device(pvdev,
VFL_TYPE_GRABBER,
-1);
if (rc) {
pr_err("%s: video_register_device failed\n", __func__);
goto reg_fail;
}
D("%s: video device registered as /dev/video%d\n",
__func__, pvdev->num);
/* connect pcam and mctl video dev to each other */
pcam->mctl_node.pvdev = pvdev;
video_set_drvdata(pcam->mctl_node.pvdev, pcam);
return rc ;
reg_fail:
video_device_release(pvdev);
v4l2_device_unregister(&pcam->mctl_node.v4l2_dev);
pcam->mctl_node.v4l2_dev.dev = NULL;
return rc;
}
| gpl-2.0 |
akosyakov/intellij-community | platform/usageView/src/com/intellij/usages/impl/GroupNode.java | 11143 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.usages.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.usages.Usage;
import com.intellij.usages.UsageGroup;
import com.intellij.usages.UsageView;
import com.intellij.usages.rules.MergeableUsage;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import java.util.*;
/**
* @author max
*/
public class GroupNode extends Node implements Navigatable, Comparable<GroupNode> {
private static final NodeComparator COMPARATOR = new NodeComparator();
private final Object lock = new Object();
private final UsageGroup myGroup;
private final int myRuleIndex;
private final Map<UsageGroup, GroupNode> mySubgroupNodes = new THashMap<UsageGroup, GroupNode>();
private final List<UsageNode> myUsageNodes = new SmartList<UsageNode>();
@NotNull private final UsageViewTreeModelBuilder myUsageTreeModel;
private volatile int myRecursiveUsageCount = 0;
public GroupNode(@Nullable UsageGroup group, int ruleIndex, @NotNull UsageViewTreeModelBuilder treeModel) {
super(treeModel);
myUsageTreeModel = treeModel;
setUserObject(group);
myGroup = group;
myRuleIndex = ruleIndex;
}
@Override
protected void updateNotify() {
if (myGroup != null) {
myGroup.update();
}
}
public String toString() {
String result = "";
if (myGroup != null) result = myGroup.getText(null);
if (children == null) {
return result;
}
return result + children.subList(0, Math.min(10, children.size())).toString();
}
public GroupNode addGroup(@NotNull UsageGroup group, int ruleIndex, @NotNull Consumer<Runnable> edtQueue) {
synchronized (lock) {
GroupNode node = mySubgroupNodes.get(group);
if (node == null) {
final GroupNode node1 = node = new GroupNode(group, ruleIndex, getBuilder());
mySubgroupNodes.put(group, node);
addNode(node1, edtQueue);
}
return node;
}
}
void addNode(@NotNull final DefaultMutableTreeNode node, @NotNull Consumer<Runnable> edtQueue) {
if (!getBuilder().isDetachedMode()) {
edtQueue.consume(new Runnable() {
@Override
public void run() {
myTreeModel.insertNodeInto(node, GroupNode.this, getNodeInsertionIndex(node));
}
});
}
}
private UsageViewTreeModelBuilder getBuilder() {
return (UsageViewTreeModelBuilder)myTreeModel;
}
@Override
public void removeAllChildren() {
synchronized (lock) {
ApplicationManager.getApplication().assertIsDispatchThread();
super.removeAllChildren();
mySubgroupNodes.clear();
myRecursiveUsageCount = 0;
myUsageNodes.clear();
}
myTreeModel.reload(this);
}
@Nullable UsageNode tryMerge(@NotNull Usage usage) {
if (!(usage instanceof MergeableUsage)) return null;
MergeableUsage mergeableUsage = (MergeableUsage)usage;
for (UsageNode node : myUsageNodes) {
Usage original = node.getUsage();
if (original == mergeableUsage) {
// search returned duplicate usage, ignore
return node;
}
if (original instanceof MergeableUsage) {
if (((MergeableUsage)original).merge(mergeableUsage)) return node;
}
}
return null;
}
public boolean removeUsage(@NotNull UsageNode usage) {
ApplicationManager.getApplication().assertIsDispatchThread();
final Collection<GroupNode> groupNodes = mySubgroupNodes.values();
for(Iterator<GroupNode> iterator = groupNodes.iterator();iterator.hasNext();) {
final GroupNode groupNode = iterator.next();
if(groupNode.removeUsage(usage)) {
doUpdate();
if (groupNode.getRecursiveUsageCount() == 0) {
myTreeModel.removeNodeFromParent(groupNode);
iterator.remove();
}
return true;
}
}
boolean removed;
synchronized (lock) {
removed = myUsageNodes.remove(usage);
}
if (removed) {
doUpdate();
return true;
}
return false;
}
public boolean removeUsagesBulk(@NotNull Set<UsageNode> usages) {
boolean removed;
synchronized (lock) {
removed = myUsageNodes.removeAll(usages);
}
Collection<GroupNode> groupNodes = mySubgroupNodes.values();
for (Iterator<GroupNode> iterator = groupNodes.iterator(); iterator.hasNext(); ) {
GroupNode groupNode = iterator.next();
if (groupNode.removeUsagesBulk(usages)) {
if (groupNode.getRecursiveUsageCount() == 0) {
MutableTreeNode parent = (MutableTreeNode)groupNode.getParent();
int childIndex = parent.getIndex(groupNode);
if (childIndex != -1) {
parent.remove(childIndex);
}
iterator.remove();
}
removed = true;
}
}
if (removed) {
--myRecursiveUsageCount;
}
return removed;
}
private void doUpdate() {
ApplicationManager.getApplication().assertIsDispatchThread();
--myRecursiveUsageCount;
myTreeModel.nodeChanged(this);
}
public UsageNode addUsage(@NotNull Usage usage, @NotNull Consumer<Runnable> edtQueue) {
final UsageNode node;
synchronized (lock) {
if (myUsageTreeModel.isFilterDuplicatedLine()) {
UsageNode mergedWith = tryMerge(usage);
if (mergedWith != null) {
return mergedWith;
}
}
node = new UsageNode(usage, getBuilder());
myUsageNodes.add(node);
}
if (!getBuilder().isDetachedMode()) {
edtQueue.consume(new Runnable() {
@Override
public void run() {
myTreeModel.insertNodeInto(node, GroupNode.this, getNodeIndex(node));
incrementUsageCount();
}
});
}
return node;
}
private int getNodeIndex(@NotNull UsageNode node) {
int index = indexedBinarySearch(node);
return index >= 0 ? index : -index-1;
}
private int indexedBinarySearch(@NotNull UsageNode key) {
int low = 0;
int high = getChildCount() - 1;
while (low <= high) {
int mid = (low + high) / 2;
TreeNode treeNode = getChildAt(mid);
int cmp;
if (treeNode instanceof UsageNode) {
UsageNode midVal = (UsageNode)treeNode;
cmp = midVal.compareTo(key);
}
else {
cmp = -1;
}
if (cmp < 0) {
low = mid + 1;
}
else if (cmp > 0) {
high = mid - 1;
}
else {
return mid; // key found
}
}
return -(low + 1); // key not found
}
private void incrementUsageCount() {
GroupNode groupNode = this;
while (true) {
groupNode.myRecursiveUsageCount++;
final GroupNode node = groupNode;
myTreeModel.nodeChanged(node);
TreeNode parent = groupNode.getParent();
if (!(parent instanceof GroupNode)) return;
groupNode = (GroupNode)parent;
}
}
@Override
public String tree2string(int indent, String lineSeparator) {
StringBuffer result = new StringBuffer();
StringUtil.repeatSymbol(result, ' ', indent);
if (myGroup != null) result.append(myGroup.toString());
result.append("[");
result.append(lineSeparator);
Enumeration enumeration = children();
while (enumeration.hasMoreElements()) {
Node node = (Node)enumeration.nextElement();
result.append(node.tree2string(indent + 4, lineSeparator));
result.append(lineSeparator);
}
StringUtil.repeatSymbol(result, ' ', indent);
result.append("]");
result.append(lineSeparator);
return result.toString();
}
@Override
protected boolean isDataValid() {
return myGroup == null || myGroup.isValid();
}
@Override
protected boolean isDataReadOnly() {
Enumeration enumeration = children();
while (enumeration.hasMoreElements()) {
Object element = enumeration.nextElement();
if (element instanceof Node && ((Node)element).isReadOnly()) return true;
}
return false;
}
private int getNodeInsertionIndex(@NotNull DefaultMutableTreeNode node) {
Enumeration children = children();
int idx = 0;
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode)children.nextElement();
if (COMPARATOR.compare(child, node) >= 0) break;
idx++;
}
return idx;
}
private static class NodeComparator implements Comparator<DefaultMutableTreeNode> {
private static int getClassIndex(DefaultMutableTreeNode node) {
if (node instanceof UsageNode) return 3;
if (node instanceof GroupNode) return 2;
if (node instanceof UsageTargetNode) return 1;
return 0;
}
@Override
public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) {
int classIdx1 = getClassIndex(n1);
int classIdx2 = getClassIndex(n2);
if (classIdx1 != classIdx2) return classIdx1 - classIdx2;
if (classIdx1 == 2) return ((GroupNode)n1).compareTo((GroupNode)n2);
return 0;
}
}
@Override
public int compareTo(@NotNull GroupNode groupNode) {
if (myRuleIndex == groupNode.myRuleIndex) {
return myGroup.compareTo(groupNode.myGroup);
}
return myRuleIndex - groupNode.myRuleIndex;
}
public UsageGroup getGroup() {
return myGroup;
}
public int getRecursiveUsageCount() {
return myRecursiveUsageCount;
}
@Override
public void navigate(boolean requestFocus) {
if (myGroup != null) {
myGroup.navigate(requestFocus);
}
}
@Override
public boolean canNavigate() {
return myGroup != null && myGroup.canNavigate();
}
@Override
public boolean canNavigateToSource() {
return myGroup != null && myGroup.canNavigateToSource();
}
@Override
protected boolean isDataExcluded() {
Enumeration enumeration = children();
while (enumeration.hasMoreElements()) {
Node node = (Node)enumeration.nextElement();
if (!node.isExcluded()) return false;
}
return true;
}
@Override
protected String getText(@NotNull UsageView view) {
return myGroup.getText(view);
}
@NotNull
public Collection<GroupNode> getSubGroups() {
return mySubgroupNodes.values();
}
@NotNull
public Collection<UsageNode> getUsageNodes() {
return myUsageNodes;
}
}
| apache-2.0 |
domenicbove/origin | pkg/client/testclient/fake_templates.go | 2068 | package testclient
import (
ktestclient "k8s.io/kubernetes/pkg/client/testclient"
"k8s.io/kubernetes/pkg/fields"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/watch"
templateapi "github.com/openshift/origin/pkg/template/api"
)
// FakeTemplates implements TemplateInterface. Meant to be embedded into a struct to get a default
// implementation. This makes faking out just the methods you want to test easier.
type FakeTemplates struct {
Fake *Fake
Namespace string
}
func (c *FakeTemplates) Get(name string) (*templateapi.Template, error) {
obj, err := c.Fake.Invokes(ktestclient.NewGetAction("templates", c.Namespace, name), &templateapi.Template{})
if obj == nil {
return nil, err
}
return obj.(*templateapi.Template), err
}
func (c *FakeTemplates) List(label labels.Selector, field fields.Selector) (*templateapi.TemplateList, error) {
obj, err := c.Fake.Invokes(ktestclient.NewListAction("templates", c.Namespace, label, field), &templateapi.TemplateList{})
if obj == nil {
return nil, err
}
return obj.(*templateapi.TemplateList), err
}
func (c *FakeTemplates) Create(inObj *templateapi.Template) (*templateapi.Template, error) {
obj, err := c.Fake.Invokes(ktestclient.NewCreateAction("templates", c.Namespace, inObj), inObj)
if obj == nil {
return nil, err
}
return obj.(*templateapi.Template), err
}
func (c *FakeTemplates) Update(inObj *templateapi.Template) (*templateapi.Template, error) {
obj, err := c.Fake.Invokes(ktestclient.NewUpdateAction("templates", c.Namespace, inObj), inObj)
if obj == nil {
return nil, err
}
return obj.(*templateapi.Template), err
}
func (c *FakeTemplates) Delete(name string) error {
_, err := c.Fake.Invokes(ktestclient.NewDeleteAction("templates", c.Namespace, name), &templateapi.Template{})
return err
}
func (c *FakeTemplates) Watch(label labels.Selector, field fields.Selector, resourceVersion string) (watch.Interface, error) {
c.Fake.Invokes(ktestclient.NewWatchAction("templates", c.Namespace, label, field, resourceVersion), nil)
return c.Fake.Watch, nil
}
| apache-2.0 |
Rogerlin2013/actor-platform | actor-apps/core/src/main/java/im/actor/model/api/rpc/RequestSendMessage.java | 2557 | package im.actor.model.api.rpc;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import im.actor.model.droidkit.bser.Bser;
import im.actor.model.droidkit.bser.BserParser;
import im.actor.model.droidkit.bser.BserObject;
import im.actor.model.droidkit.bser.BserValues;
import im.actor.model.droidkit.bser.BserWriter;
import im.actor.model.droidkit.bser.DataInput;
import im.actor.model.droidkit.bser.DataOutput;
import im.actor.model.droidkit.bser.util.SparseArray;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import static im.actor.model.droidkit.bser.Utils.*;
import java.io.IOException;
import im.actor.model.network.parser.*;
import java.util.List;
import java.util.ArrayList;
import im.actor.model.api.*;
public class RequestSendMessage extends Request<ResponseSeqDate> {
public static final int HEADER = 0x5c;
public static RequestSendMessage fromBytes(byte[] data) throws IOException {
return Bser.parse(new RequestSendMessage(), data);
}
private OutPeer peer;
private long rid;
private Message message;
public RequestSendMessage(@NotNull OutPeer peer, long rid, @NotNull Message message) {
this.peer = peer;
this.rid = rid;
this.message = message;
}
public RequestSendMessage() {
}
@NotNull
public OutPeer getPeer() {
return this.peer;
}
public long getRid() {
return this.rid;
}
@NotNull
public Message getMessage() {
return this.message;
}
@Override
public void parse(BserValues values) throws IOException {
this.peer = values.getObj(1, new OutPeer());
this.rid = values.getLong(3);
this.message = Message.fromBytes(values.getBytes(4));
}
@Override
public void serialize(BserWriter writer) throws IOException {
if (this.peer == null) {
throw new IOException();
}
writer.writeObject(1, this.peer);
writer.writeLong(3, this.rid);
if (this.message == null) {
throw new IOException();
}
writer.writeBytes(4, this.message.buildContainer());
}
@Override
public String toString() {
String res = "rpc SendMessage{";
res += "peer=" + this.peer;
res += ", rid=" + this.rid;
res += ", message=" + this.message;
res += "}";
return res;
}
@Override
public int getHeaderKey() {
return HEADER;
}
}
| mit |
peterwillcn/mongoid | spec/mongoid/relations/referenced/in_spec.rb | 30037 | require "spec_helper"
describe Mongoid::Relations::Referenced::In do
let(:person) do
Person.create
end
describe "#=" do
context "when the relation is named target" do
let(:target) do
User.new
end
context "when the relation is referenced from an embeds many" do
context "when setting via create" do
let(:service) do
person.services.create(target: target)
end
it "sets the target relation" do
service.target.should eq(target)
end
end
end
end
context "when the inverse relation has no reference defined" do
let(:agent) do
Agent.new(title: "007")
end
let(:game) do
Game.new(name: "Donkey Kong")
end
before do
agent.game = game
end
it "sets the relation" do
agent.game.should eq(game)
end
it "sets the foreign_key" do
agent.game_id.should eq(game.id)
end
end
context "when referencing a document from an embedded document" do
let(:person) do
Person.create
end
let(:address) do
person.addresses.create(street: "Wienerstr")
end
let(:account) do
Account.create(name: "1", number: 1000000)
end
before do
address.account = account
end
it "sets the relation" do
address.account.should eq(account)
end
it "does not erase the metadata" do
address.metadata.should_not be_nil
end
it "allows saving of the embedded document" do
address.save.should be_true
end
end
context "when the parent is a references one" do
context "when the relation is not polymorphic" do
context "when the child is a new record" do
let(:person) do
Person.new
end
let(:game) do
Game.new
end
before do
game.person = person
end
it "sets the target of the relation" do
game.person.target.should eq(person)
end
it "sets the foreign key on the relation" do
game.person_id.should eq(person.id)
end
it "sets the base on the inverse relation" do
person.game.should eq(game)
end
it "sets the same instance on the inverse relation" do
person.game.should eql(game)
end
it "does not save the target" do
person.should_not be_persisted
end
end
context "when the child is not a new record" do
let(:person) do
Person.new
end
let(:game) do
Game.create
end
before do
game.person = person
end
it "sets the target of the relation" do
game.person.target.should eq(person)
end
it "sets the foreign key of the relation" do
game.person_id.should eq(person.id)
end
it "sets the base on the inverse relation" do
person.game.should eq(game)
end
it "sets the same instance on the inverse relation" do
person.game.should eql(game)
end
it "does not saves the target" do
person.should_not be_persisted
end
end
end
context "when the relation is not polymorphic" do
context "when the child is a new record" do
let(:bar) do
Bar.new
end
let(:rating) do
Rating.new
end
before do
rating.ratable = bar
end
it "sets the target of the relation" do
rating.ratable.target.should eq(bar)
end
it "sets the foreign key on the relation" do
rating.ratable_id.should eq(bar.id)
end
it "sets the base on the inverse relation" do
bar.rating.should eq(rating)
end
it "sets the same instance on the inverse relation" do
bar.rating.should eql(rating)
end
it "does not save the target" do
bar.should_not be_persisted
end
end
context "when the child is not a new record" do
let(:bar) do
Bar.new
end
let(:rating) do
Rating.create
end
before do
rating.ratable = bar
end
it "sets the target of the relation" do
rating.ratable.target.should eq(bar)
end
it "sets the foreign key of the relation" do
rating.ratable_id.should eq(bar.id)
end
it "sets the base on the inverse relation" do
bar.rating.should eq(rating)
end
it "sets the same instance on the inverse relation" do
bar.rating.should eql(rating)
end
it "does not saves the target" do
bar.should_not be_persisted
end
end
end
end
context "when the parent is a references many" do
context "when the relation is not polymorphic" do
context "when the child is a new record" do
let(:person) do
Person.new
end
let(:post) do
Post.new
end
before do
post.person = person
end
it "sets the target of the relation" do
post.person.target.should eq(person)
end
it "sets the foreign key on the relation" do
post.person_id.should eq(person.id)
end
it "does not save the target" do
person.should_not be_persisted
end
end
context "when the child is not a new record" do
let(:person) do
Person.new
end
let(:post) do
Post.create
end
before do
post.person = person
end
it "sets the target of the relation" do
post.person.target.should eq(person)
end
it "sets the foreign key of the relation" do
post.person_id.should eq(person.id)
end
it "does not saves the target" do
person.should_not be_persisted
end
end
end
context "when the relation is polymorphic" do
context "when multiple relations against the same class exist" do
let(:face) do
Face.new
end
let(:eye) do
Eye.new
end
it "raises an error" do
expect {
eye.eyeable = face
}.to raise_error(Mongoid::Errors::InvalidSetPolymorphicRelation)
end
end
context "when one relation against the same class exists" do
context "when the child is a new record" do
let(:movie) do
Movie.new
end
let(:rating) do
Rating.new
end
before do
rating.ratable = movie
end
it "sets the target of the relation" do
rating.ratable.target.should eq(movie)
end
it "sets the foreign key on the relation" do
rating.ratable_id.should eq(movie.id)
end
it "does not save the target" do
movie.should_not be_persisted
end
end
context "when the child is not a new record" do
let(:movie) do
Movie.new
end
let(:rating) do
Rating.create
end
before do
rating.ratable = movie
end
it "sets the target of the relation" do
rating.ratable.target.should eq(movie)
end
it "sets the foreign key of the relation" do
rating.ratable_id.should eq(movie.id)
end
it "does not saves the target" do
movie.should_not be_persisted
end
end
end
end
end
end
describe "#= nil" do
context "when dependent is destroy" do
let(:account) do
Account.create
end
let(:drug) do
Drug.create
end
let(:person) do
Person.create
end
context "when relation is has_one" do
before do
Account.belongs_to :person, dependent: :destroy
Person.has_one :account
person.account = account
person.save
end
after :all do
Account.belongs_to :person, dependent: :nullify
Person.has_one :account, validate: false
end
context "when parent exists" do
context "when child is destroyed" do
before do
account.delete
end
it "deletes child" do
account.should be_destroyed
end
it "deletes parent" do
person.should be_destroyed
end
end
end
end
context "when relation is has_many" do
before do
Drug.belongs_to :person, dependent: :destroy
Person.has_many :drugs
person.drugs = [drug]
person.save
end
after :all do
Drug.belongs_to :person, dependent: :nullify
Person.has_many :drugs, validate: false
end
context "when parent exists" do
context "when child is destroyed" do
before do
drug.delete
end
it "deletes child" do
drug.should be_destroyed
end
it "deletes parent" do
person.should be_destroyed
end
end
end
end
end
context "when dependent is delete" do
let(:account) do
Account.create
end
let(:drug) do
Drug.create
end
let(:person) do
Person.create
end
context "when relation is has_one" do
before do
Account.belongs_to :person, dependent: :delete
Person.has_one :account
person.account = account
person.save
end
after :all do
Account.belongs_to :person, dependent: :nullify
Person.has_one :account, validate: false
end
context "when parent is persisted" do
context "when child is deleted" do
before do
account.delete
end
it "deletes child" do
account.should be_destroyed
end
it "deletes parent" do
person.should be_destroyed
end
end
end
end
context "when relation is has_many" do
before do
Drug.belongs_to :person, dependent: :delete
Person.has_many :drugs
person.drugs = [drug]
person.save
end
after :all do
Drug.belongs_to :person, dependent: :nullify
Person.has_many :drugs, validate: false
end
context "when parent exists" do
context "when child is destroyed" do
before do
drug.delete
end
it "deletes child" do
drug.should be_destroyed
end
it "deletes parent" do
person.should be_destroyed
end
end
end
end
end
context "when dependent is nullify" do
let(:account) do
Account.create
end
let(:drug) do
Drug.create
end
let(:person) do
Person.create
end
context "when relation is has_one" do
before do
Account.belongs_to :person, dependent: :nullify
Person.has_one :account
person.account = account
person.save
end
context "when parent is persisted" do
context "when child is deleted" do
before do
account.delete
end
it "deletes child" do
account.should be_destroyed
end
it "doesn't delete parent" do
person.should_not be_destroyed
end
it "removes the link" do
person.account.should be_nil
end
end
end
end
context "when relation is has_many" do
before do
Drug.belongs_to :person, dependent: :nullify
Person.has_many :drugs
person.drugs = [drug]
person.save
end
context "when parent exists" do
context "when child is destroyed" do
before do
drug.delete
end
it "deletes child" do
drug.should be_destroyed
end
it "doesn't deletes parent" do
person.should_not be_destroyed
end
it "removes the link" do
person.drugs.should eq([])
end
end
end
end
end
context "when the inverse relation has no reference defined" do
let(:agent) do
Agent.new(title: "007")
end
let(:game) do
Game.new(name: "Donkey Kong")
end
before do
agent.game = game
agent.game = nil
end
it "removes the relation" do
agent.game.should be_nil
end
it "removes the foreign_key" do
agent.game_id.should be_nil
end
end
context "when the parent is a references one" do
context "when the relation is not polymorphic" do
context "when the parent is a new record" do
let(:person) do
Person.new
end
let(:game) do
Game.new
end
before do
game.person = person
game.person = nil
end
it "sets the relation to nil" do
game.person.should be_nil
end
it "removed the inverse relation" do
person.game.should be_nil
end
it "removes the foreign key value" do
game.person_id.should be_nil
end
end
context "when the parent is not a new record" do
let(:person) do
Person.create
end
let(:game) do
Game.create
end
before do
game.person = person
game.person = nil
end
it "sets the relation to nil" do
game.person.should be_nil
end
it "removed the inverse relation" do
person.game.should be_nil
end
it "removes the foreign key value" do
game.person_id.should be_nil
end
it "does not delete the child" do
game.should_not be_destroyed
end
end
end
context "when the relation is polymorphic" do
context "when multiple relations against the same class exist" do
context "when the parent is a new record" do
let(:face) do
Face.new
end
let(:eye) do
Eye.new
end
before do
face.left_eye = eye
eye.eyeable = nil
end
it "sets the relation to nil" do
eye.eyeable.should be_nil
end
it "removed the inverse relation" do
face.left_eye.should be_nil
end
it "removes the foreign key value" do
eye.eyeable_id.should be_nil
end
end
context "when the parent is not a new record" do
let(:face) do
Face.new
end
let(:eye) do
Eye.create
end
before do
face.left_eye = eye
eye.eyeable = nil
end
it "sets the relation to nil" do
eye.eyeable.should be_nil
end
it "removed the inverse relation" do
face.left_eye.should be_nil
end
it "removes the foreign key value" do
eye.eyeable_id.should be_nil
end
end
end
context "when one relation against the same class exists" do
context "when the parent is a new record" do
let(:bar) do
Bar.new
end
let(:rating) do
Rating.new
end
before do
rating.ratable = bar
rating.ratable = nil
end
it "sets the relation to nil" do
rating.ratable.should be_nil
end
it "removed the inverse relation" do
bar.rating.should be_nil
end
it "removes the foreign key value" do
rating.ratable_id.should be_nil
end
end
context "when the parent is not a new record" do
let(:bar) do
Bar.new
end
let(:rating) do
Rating.create
end
before do
rating.ratable = bar
rating.ratable = nil
end
it "sets the relation to nil" do
rating.ratable.should be_nil
end
it "removed the inverse relation" do
bar.rating.should be_nil
end
it "removes the foreign key value" do
rating.ratable_id.should be_nil
end
end
end
end
end
context "when the parent is a references many" do
context "when the relation is not polymorphic" do
context "when the parent is a new record" do
let(:person) do
Person.new
end
let(:post) do
Post.new
end
before do
post.person = person
post.person = nil
end
it "sets the relation to nil" do
post.person.should be_nil
end
it "removed the inverse relation" do
person.posts.should be_empty
end
it "removes the foreign key value" do
post.person_id.should be_nil
end
end
context "when the parent is not a new record" do
let(:person) do
Person.new
end
let(:post) do
Post.create
end
before do
post.person = person
post.person = nil
end
it "sets the relation to nil" do
post.person.should be_nil
end
it "removed the inverse relation" do
person.posts.should be_empty
end
it "removes the foreign key value" do
post.person_id.should be_nil
end
end
end
context "when the relation is polymorphic" do
context "when the parent is a new record" do
let(:movie) do
Movie.new
end
let(:rating) do
Rating.new
end
before do
rating.ratable = movie
rating.ratable = nil
end
it "sets the relation to nil" do
rating.ratable.should be_nil
end
it "removed the inverse relation" do
movie.ratings.should be_empty
end
it "removes the foreign key value" do
rating.ratable_id.should be_nil
end
end
context "when the parent is not a new record" do
let(:movie) do
Movie.new
end
let(:rating) do
Rating.create
end
before do
rating.ratable = movie
rating.ratable = nil
end
it "sets the relation to nil" do
rating.ratable.should be_nil
end
it "removed the inverse relation" do
movie.ratings.should be_empty
end
it "removes the foreign key value" do
rating.ratable_id.should be_nil
end
end
end
end
end
describe ".builder" do
let(:builder_klass) do
Mongoid::Relations::Builders::Referenced::In
end
let(:document) do
stub
end
let(:metadata) do
stub(extension?: false)
end
it "returns the embedded in builder" do
described_class.builder(nil, metadata, document).should
be_a_kind_of(builder_klass)
end
end
describe ".eager_load" do
before do
Mongoid.identity_map_enabled = true
end
after do
Mongoid.identity_map_enabled = false
end
context "when the relation is not polymorphic" do
let!(:person) do
Person.create
end
let!(:post) do
person.posts.create(title: "testing")
end
let(:metadata) do
Post.relations["person"]
end
let(:eager) do
described_class.eager_load(metadata, Post.all)
end
let!(:map) do
Mongoid::IdentityMap.get(Person, person.id)
end
it "puts the document in the identity map" do
map.should eq(person)
end
end
context "when the relation is polymorphic" do
let(:metadata) do
Rating.relations["ratable"]
end
it "raises an error" do
expect {
described_class.eager_load(metadata, Rating.all)
}.to raise_error(Mongoid::Errors::EagerLoad)
end
end
context "when the ids has been duplicated" do
let!(:person) do
Person.create
end
let!(:posts) do
2.times {|i| person.posts.create(title: "testing#{i}") }
person.posts
end
let(:metadata) do
Post.relations["person"]
end
let(:eager) do
described_class.eager_load(metadata, posts.map(&:person_id))
end
it "duplication should be removed" do
eager.count.should eq(1)
end
end
end
describe ".embedded?" do
it "returns false" do
described_class.should_not be_embedded
end
end
describe ".foreign_key_suffix" do
it "returns _id" do
described_class.foreign_key_suffix.should eq("_id")
end
end
describe ".macro" do
it "returns belongs_to" do
described_class.macro.should eq(:belongs_to)
end
end
describe "#respond_to?" do
let(:person) do
Person.new
end
let(:game) do
person.build_game(name: "Tron")
end
let(:document) do
game.person
end
Mongoid::Document.public_instance_methods(true).each do |method|
context "when checking #{method}" do
it "returns true" do
document.respond_to?(method).should be_true
end
end
end
end
describe ".stores_foreign_key?" do
it "returns true" do
described_class.stores_foreign_key?.should be_true
end
end
describe ".valid_options" do
it "returns the valid options" do
described_class.valid_options.should eq(
[ :autobuild, :autosave, :dependent, :foreign_key, :index, :polymorphic, :touch ]
)
end
end
describe ".validation_default" do
it "returns false" do
described_class.validation_default.should be_false
end
end
context "when the relation is self referencing" do
let(:game_one) do
Game.new(name: "Diablo")
end
let(:game_two) do
Game.new(name: "Warcraft")
end
context "when setting the parent" do
before do
game_one.parent = game_two
end
it "sets the parent" do
game_one.parent.should eq(game_two)
end
it "does not set the parent recursively" do
game_two.parent.should be_nil
end
end
end
context "when the relation belongs to a has many and has one" do
before(:all) do
class A
include Mongoid::Document
has_many :bs, inverse_of: :a
end
class B
include Mongoid::Document
belongs_to :a, inverse_of: :bs
belongs_to :c, inverse_of: :b
end
class C
include Mongoid::Document
has_one :b, inverse_of: :c
end
end
after(:all) do
Object.send(:remove_const, :A)
Object.send(:remove_const, :B)
Object.send(:remove_const, :C)
end
context "when setting the has one" do
let(:a) do
A.new
end
let(:b) do
B.new
end
let(:c) do
C.new
end
before do
b.c = c
end
context "when subsequently setting the has many" do
before do
b.a = a
end
context "when setting the has one again" do
before do
b.c = c
end
it "allows the reset of the has one" do
b.c.should eq(c)
end
end
end
end
end
context "when replacing the relation with another" do
let!(:person) do
Person.create
end
let!(:post) do
Post.create(title: "test")
end
let!(:game) do
person.create_game(name: "Tron")
end
before do
post.person = game.person
post.save
end
it "clones the relation" do
post.person.should eq(person)
end
it "sets the foreign key" do
post.person_id.should eq(person.id)
end
it "does not remove the previous relation" do
game.person.should eq(person)
end
it "does not remove the previous foreign key" do
game.person_id.should eq(person.id)
end
context "when reloading" do
before do
post.reload
game.reload
end
it "persists the relation" do
post.reload.person.should eq(person)
end
it "persists the foreign key" do
post.reload.person_id.should eq(game.person_id)
end
it "does not remove the previous relation" do
game.person.should eq(person)
end
it "does not remove the previous foreign key" do
game.person_id.should eq(person.id)
end
end
end
context "when the document belongs to a has one and has many" do
let(:movie) do
Movie.create(name: "Infernal Affairs")
end
let(:account) do
Account.create(name: "Leung")
end
context "when creating the document" do
let(:comment) do
Comment.create(movie: movie, account: account)
end
it "sets the correct has one" do
comment.account.should eq(account)
end
it "sets the correct has many" do
comment.movie.should eq(movie)
end
end
end
context "when reloading the relation" do
let!(:person_one) do
Person.create
end
let!(:person_two) do
Person.create(title: "Sir")
end
let!(:game) do
Game.create(name: "Starcraft 2")
end
before do
game.person = person_one
game.save
end
context "when the relation references the same document" do
before do
Person.collection.find({ _id: person_one.id }).
update({ "$set" => { title: "Madam" }})
end
let(:reloaded) do
game.person(true)
end
it "reloads the document from the database" do
reloaded.title.should eq("Madam")
end
it "sets a new document instance" do
reloaded.should_not equal(person_one)
end
end
context "when the relation references a different document" do
before do
game.person_id = person_two.id
game.save
end
let(:reloaded) do
game.person(true)
end
it "reloads the new document from the database" do
reloaded.title.should eq("Sir")
end
it "sets a new document instance" do
reloaded.should_not equal(person_one)
end
end
end
context "when the parent and child are persisted" do
context "when the identity map is enabled" do
before do
Mongoid.identity_map_enabled = true
end
after do
Mongoid.identity_map_enabled = false
end
let(:series) do
Series.create
end
let!(:book_one) do
series.books.create
end
let!(:book_two) do
series.books.create
end
let(:id) do
Book.first.id
end
context "when asking for the inverse multiple times" do
before do
Book.find(id).series.books.to_a
end
it "does not append and save duplicate docs" do
Book.find(id).series.books.to_a.length.should eq(2)
end
it "returns the same documents from the map" do
Book.find(id).should equal(Book.find(id))
end
end
end
end
context "when creating with a reference to an integer id parent" do
let!(:jar) do
Jar.create do |doc|
doc._id = 1
end
end
let(:cookie) do
Cookie.create(jar_id: "1")
end
it "allows strings to be passed as the id" do
cookie.jar.should eq(jar)
end
it "persists the relation" do
cookie.reload.jar.should eq(jar)
end
end
context "when setting the relation via the foreign key" do
context "when the relation exists" do
let!(:person_one) do
Person.create
end
let!(:person_two) do
Person.create
end
let!(:game) do
Game.create(person: person_one)
end
before do
game.person_id = person_two.id
end
it "sets the new document on the relation" do
game.person.should eq(person_two)
end
end
end
end
| mit |
ptoonen/corefx | src/Common/src/System/Net/Security/CertificateValidation.Unix.cs | 2411 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
internal static class CertificateValidation
{
private static readonly IdnMapping s_idnMapping = new IdnMapping();
internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName)
{
SslPolicyErrors errors = chain.Build(remoteCertificate) ?
SslPolicyErrors.None :
SslPolicyErrors.RemoteCertificateChainErrors;
if (!checkCertName)
{
return errors;
}
if (string.IsNullOrEmpty(hostName))
{
return errors | SslPolicyErrors.RemoteCertificateNameMismatch;
}
int hostNameMatch;
using (SafeX509Handle certHandle = Interop.Crypto.X509UpRef(remoteCertificate.Handle))
{
IPAddress hostnameAsIp;
if (IPAddress.TryParse(hostName, out hostnameAsIp))
{
byte[] addressBytes = hostnameAsIp.GetAddressBytes();
hostNameMatch = Interop.Crypto.CheckX509IpAddress(certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length);
}
else
{
// The IdnMapping converts Unicode input into the IDNA punycode sequence.
// It also does host case normalization. The bypass logic would be something
// like "all characters being within [a-z0-9.-]+"
string matchName = s_idnMapping.GetAscii(hostName);
hostNameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length);
}
}
Debug.Assert(hostNameMatch == 0 || hostNameMatch == 1, $"Expected 0 or 1 from CheckX509Hostname, got {hostNameMatch}");
return hostNameMatch == 1 ?
errors :
errors | SslPolicyErrors.RemoteCertificateNameMismatch;
}
}
}
| mit |
c0d3z3r0/linux-rockchip | drivers/iio/buffer/industrialio-buffer-dma.c | 21128 | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright 2013-2015 Analog Devices Inc.
* Author: Lars-Peter Clausen <[email protected]>
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/poll.h>
#include <linux/iio/buffer.h>
#include <linux/iio/buffer_impl.h>
#include <linux/iio/buffer-dma.h>
#include <linux/dma-mapping.h>
#include <linux/sizes.h>
/*
* For DMA buffers the storage is sub-divided into so called blocks. Each block
* has its own memory buffer. The size of the block is the granularity at which
* memory is exchanged between the hardware and the application. Increasing the
* basic unit of data exchange from one sample to one block decreases the
* management overhead that is associated with each sample. E.g. if we say the
* management overhead for one exchange is x and the unit of exchange is one
* sample the overhead will be x for each sample. Whereas when using a block
* which contains n samples the overhead per sample is reduced to x/n. This
* allows to achieve much higher samplerates than what can be sustained with
* the one sample approach.
*
* Blocks are exchanged between the DMA controller and the application via the
* means of two queues. The incoming queue and the outgoing queue. Blocks on the
* incoming queue are waiting for the DMA controller to pick them up and fill
* them with data. Block on the outgoing queue have been filled with data and
* are waiting for the application to dequeue them and read the data.
*
* A block can be in one of the following states:
* * Owned by the application. In this state the application can read data from
* the block.
* * On the incoming list: Blocks on the incoming list are queued up to be
* processed by the DMA controller.
* * Owned by the DMA controller: The DMA controller is processing the block
* and filling it with data.
* * On the outgoing list: Blocks on the outgoing list have been successfully
* processed by the DMA controller and contain data. They can be dequeued by
* the application.
* * Dead: A block that is dead has been marked as to be freed. It might still
* be owned by either the application or the DMA controller at the moment.
* But once they are done processing it instead of going to either the
* incoming or outgoing queue the block will be freed.
*
* In addition to this blocks are reference counted and the memory associated
* with both the block structure as well as the storage memory for the block
* will be freed when the last reference to the block is dropped. This means a
* block must not be accessed without holding a reference.
*
* The iio_dma_buffer implementation provides a generic infrastructure for
* managing the blocks.
*
* A driver for a specific piece of hardware that has DMA capabilities need to
* implement the submit() callback from the iio_dma_buffer_ops structure. This
* callback is supposed to initiate the DMA transfer copying data from the
* converter to the memory region of the block. Once the DMA transfer has been
* completed the driver must call iio_dma_buffer_block_done() for the completed
* block.
*
* Prior to this it must set the bytes_used field of the block contains
* the actual number of bytes in the buffer. Typically this will be equal to the
* size of the block, but if the DMA hardware has certain alignment requirements
* for the transfer length it might choose to use less than the full size. In
* either case it is expected that bytes_used is a multiple of the bytes per
* datum, i.e. the block must not contain partial samples.
*
* The driver must call iio_dma_buffer_block_done() for each block it has
* received through its submit_block() callback, even if it does not actually
* perform a DMA transfer for the block, e.g. because the buffer was disabled
* before the block transfer was started. In this case it should set bytes_used
* to 0.
*
* In addition it is recommended that a driver implements the abort() callback.
* It will be called when the buffer is disabled and can be used to cancel
* pending and stop active transfers.
*
* The specific driver implementation should use the default callback
* implementations provided by this module for the iio_buffer_access_funcs
* struct. It may overload some callbacks with custom variants if the hardware
* has special requirements that are not handled by the generic functions. If a
* driver chooses to overload a callback it has to ensure that the generic
* callback is called from within the custom callback.
*/
static void iio_buffer_block_release(struct kref *kref)
{
struct iio_dma_buffer_block *block = container_of(kref,
struct iio_dma_buffer_block, kref);
WARN_ON(block->state != IIO_BLOCK_STATE_DEAD);
dma_free_coherent(block->queue->dev, PAGE_ALIGN(block->size),
block->vaddr, block->phys_addr);
iio_buffer_put(&block->queue->buffer);
kfree(block);
}
static void iio_buffer_block_get(struct iio_dma_buffer_block *block)
{
kref_get(&block->kref);
}
static void iio_buffer_block_put(struct iio_dma_buffer_block *block)
{
kref_put(&block->kref, iio_buffer_block_release);
}
/*
* dma_free_coherent can sleep, hence we need to take some special care to be
* able to drop a reference from an atomic context.
*/
static LIST_HEAD(iio_dma_buffer_dead_blocks);
static DEFINE_SPINLOCK(iio_dma_buffer_dead_blocks_lock);
static void iio_dma_buffer_cleanup_worker(struct work_struct *work)
{
struct iio_dma_buffer_block *block, *_block;
LIST_HEAD(block_list);
spin_lock_irq(&iio_dma_buffer_dead_blocks_lock);
list_splice_tail_init(&iio_dma_buffer_dead_blocks, &block_list);
spin_unlock_irq(&iio_dma_buffer_dead_blocks_lock);
list_for_each_entry_safe(block, _block, &block_list, head)
iio_buffer_block_release(&block->kref);
}
static DECLARE_WORK(iio_dma_buffer_cleanup_work, iio_dma_buffer_cleanup_worker);
static void iio_buffer_block_release_atomic(struct kref *kref)
{
struct iio_dma_buffer_block *block;
unsigned long flags;
block = container_of(kref, struct iio_dma_buffer_block, kref);
spin_lock_irqsave(&iio_dma_buffer_dead_blocks_lock, flags);
list_add_tail(&block->head, &iio_dma_buffer_dead_blocks);
spin_unlock_irqrestore(&iio_dma_buffer_dead_blocks_lock, flags);
schedule_work(&iio_dma_buffer_cleanup_work);
}
/*
* Version of iio_buffer_block_put() that can be called from atomic context
*/
static void iio_buffer_block_put_atomic(struct iio_dma_buffer_block *block)
{
kref_put(&block->kref, iio_buffer_block_release_atomic);
}
static struct iio_dma_buffer_queue *iio_buffer_to_queue(struct iio_buffer *buf)
{
return container_of(buf, struct iio_dma_buffer_queue, buffer);
}
static struct iio_dma_buffer_block *iio_dma_buffer_alloc_block(
struct iio_dma_buffer_queue *queue, size_t size)
{
struct iio_dma_buffer_block *block;
block = kzalloc(sizeof(*block), GFP_KERNEL);
if (!block)
return NULL;
block->vaddr = dma_alloc_coherent(queue->dev, PAGE_ALIGN(size),
&block->phys_addr, GFP_KERNEL);
if (!block->vaddr) {
kfree(block);
return NULL;
}
block->size = size;
block->state = IIO_BLOCK_STATE_DEQUEUED;
block->queue = queue;
INIT_LIST_HEAD(&block->head);
kref_init(&block->kref);
iio_buffer_get(&queue->buffer);
return block;
}
static void _iio_dma_buffer_block_done(struct iio_dma_buffer_block *block)
{
struct iio_dma_buffer_queue *queue = block->queue;
/*
* The buffer has already been freed by the application, just drop the
* reference.
*/
if (block->state != IIO_BLOCK_STATE_DEAD) {
block->state = IIO_BLOCK_STATE_DONE;
list_add_tail(&block->head, &queue->outgoing);
}
}
/**
* iio_dma_buffer_block_done() - Indicate that a block has been completed
* @block: The completed block
*
* Should be called when the DMA controller has finished handling the block to
* pass back ownership of the block to the queue.
*/
void iio_dma_buffer_block_done(struct iio_dma_buffer_block *block)
{
struct iio_dma_buffer_queue *queue = block->queue;
unsigned long flags;
spin_lock_irqsave(&queue->list_lock, flags);
_iio_dma_buffer_block_done(block);
spin_unlock_irqrestore(&queue->list_lock, flags);
iio_buffer_block_put_atomic(block);
wake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM);
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_block_done);
/**
* iio_dma_buffer_block_list_abort() - Indicate that a list block has been
* aborted
* @queue: Queue for which to complete blocks.
* @list: List of aborted blocks. All blocks in this list must be from @queue.
*
* Typically called from the abort() callback after the DMA controller has been
* stopped. This will set bytes_used to 0 for each block in the list and then
* hand the blocks back to the queue.
*/
void iio_dma_buffer_block_list_abort(struct iio_dma_buffer_queue *queue,
struct list_head *list)
{
struct iio_dma_buffer_block *block, *_block;
unsigned long flags;
spin_lock_irqsave(&queue->list_lock, flags);
list_for_each_entry_safe(block, _block, list, head) {
list_del(&block->head);
block->bytes_used = 0;
_iio_dma_buffer_block_done(block);
iio_buffer_block_put_atomic(block);
}
spin_unlock_irqrestore(&queue->list_lock, flags);
wake_up_interruptible_poll(&queue->buffer.pollq, EPOLLIN | EPOLLRDNORM);
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_block_list_abort);
static bool iio_dma_block_reusable(struct iio_dma_buffer_block *block)
{
/*
* If the core owns the block it can be re-used. This should be the
* default case when enabling the buffer, unless the DMA controller does
* not support abort and has not given back the block yet.
*/
switch (block->state) {
case IIO_BLOCK_STATE_DEQUEUED:
case IIO_BLOCK_STATE_QUEUED:
case IIO_BLOCK_STATE_DONE:
return true;
default:
return false;
}
}
/**
* iio_dma_buffer_request_update() - DMA buffer request_update callback
* @buffer: The buffer which to request an update
*
* Should be used as the iio_dma_buffer_request_update() callback for
* iio_buffer_access_ops struct for DMA buffers.
*/
int iio_dma_buffer_request_update(struct iio_buffer *buffer)
{
struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);
struct iio_dma_buffer_block *block;
bool try_reuse = false;
size_t size;
int ret = 0;
int i;
/*
* Split the buffer into two even parts. This is used as a double
* buffering scheme with usually one block at a time being used by the
* DMA and the other one by the application.
*/
size = DIV_ROUND_UP(queue->buffer.bytes_per_datum *
queue->buffer.length, 2);
mutex_lock(&queue->lock);
/* Allocations are page aligned */
if (PAGE_ALIGN(queue->fileio.block_size) == PAGE_ALIGN(size))
try_reuse = true;
queue->fileio.block_size = size;
queue->fileio.active_block = NULL;
spin_lock_irq(&queue->list_lock);
for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {
block = queue->fileio.blocks[i];
/* If we can't re-use it free it */
if (block && (!iio_dma_block_reusable(block) || !try_reuse))
block->state = IIO_BLOCK_STATE_DEAD;
}
/*
* At this point all blocks are either owned by the core or marked as
* dead. This means we can reset the lists without having to fear
* corrution.
*/
INIT_LIST_HEAD(&queue->outgoing);
spin_unlock_irq(&queue->list_lock);
INIT_LIST_HEAD(&queue->incoming);
for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {
if (queue->fileio.blocks[i]) {
block = queue->fileio.blocks[i];
if (block->state == IIO_BLOCK_STATE_DEAD) {
/* Could not reuse it */
iio_buffer_block_put(block);
block = NULL;
} else {
block->size = size;
}
} else {
block = NULL;
}
if (!block) {
block = iio_dma_buffer_alloc_block(queue, size);
if (!block) {
ret = -ENOMEM;
goto out_unlock;
}
queue->fileio.blocks[i] = block;
}
block->state = IIO_BLOCK_STATE_QUEUED;
list_add_tail(&block->head, &queue->incoming);
}
out_unlock:
mutex_unlock(&queue->lock);
return ret;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_request_update);
static void iio_dma_buffer_submit_block(struct iio_dma_buffer_queue *queue,
struct iio_dma_buffer_block *block)
{
int ret;
/*
* If the hardware has already been removed we put the block into
* limbo. It will neither be on the incoming nor outgoing list, nor will
* it ever complete. It will just wait to be freed eventually.
*/
if (!queue->ops)
return;
block->state = IIO_BLOCK_STATE_ACTIVE;
iio_buffer_block_get(block);
ret = queue->ops->submit(queue, block);
if (ret) {
/*
* This is a bit of a problem and there is not much we can do
* other then wait for the buffer to be disabled and re-enabled
* and try again. But it should not really happen unless we run
* out of memory or something similar.
*
* TODO: Implement support in the IIO core to allow buffers to
* notify consumers that something went wrong and the buffer
* should be disabled.
*/
iio_buffer_block_put(block);
}
}
/**
* iio_dma_buffer_enable() - Enable DMA buffer
* @buffer: IIO buffer to enable
* @indio_dev: IIO device the buffer is attached to
*
* Needs to be called when the device that the buffer is attached to starts
* sampling. Typically should be the iio_buffer_access_ops enable callback.
*
* This will allocate the DMA buffers and start the DMA transfers.
*/
int iio_dma_buffer_enable(struct iio_buffer *buffer,
struct iio_dev *indio_dev)
{
struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);
struct iio_dma_buffer_block *block, *_block;
mutex_lock(&queue->lock);
queue->active = true;
list_for_each_entry_safe(block, _block, &queue->incoming, head) {
list_del(&block->head);
iio_dma_buffer_submit_block(queue, block);
}
mutex_unlock(&queue->lock);
return 0;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_enable);
/**
* iio_dma_buffer_disable() - Disable DMA buffer
* @buffer: IIO DMA buffer to disable
* @indio_dev: IIO device the buffer is attached to
*
* Needs to be called when the device that the buffer is attached to stops
* sampling. Typically should be the iio_buffer_access_ops disable callback.
*/
int iio_dma_buffer_disable(struct iio_buffer *buffer,
struct iio_dev *indio_dev)
{
struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);
mutex_lock(&queue->lock);
queue->active = false;
if (queue->ops && queue->ops->abort)
queue->ops->abort(queue);
mutex_unlock(&queue->lock);
return 0;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_disable);
static void iio_dma_buffer_enqueue(struct iio_dma_buffer_queue *queue,
struct iio_dma_buffer_block *block)
{
if (block->state == IIO_BLOCK_STATE_DEAD) {
iio_buffer_block_put(block);
} else if (queue->active) {
iio_dma_buffer_submit_block(queue, block);
} else {
block->state = IIO_BLOCK_STATE_QUEUED;
list_add_tail(&block->head, &queue->incoming);
}
}
static struct iio_dma_buffer_block *iio_dma_buffer_dequeue(
struct iio_dma_buffer_queue *queue)
{
struct iio_dma_buffer_block *block;
spin_lock_irq(&queue->list_lock);
block = list_first_entry_or_null(&queue->outgoing, struct
iio_dma_buffer_block, head);
if (block != NULL) {
list_del(&block->head);
block->state = IIO_BLOCK_STATE_DEQUEUED;
}
spin_unlock_irq(&queue->list_lock);
return block;
}
/**
* iio_dma_buffer_read() - DMA buffer read callback
* @buffer: Buffer to read form
* @n: Number of bytes to read
* @user_buffer: Userspace buffer to copy the data to
*
* Should be used as the read callback for iio_buffer_access_ops
* struct for DMA buffers.
*/
int iio_dma_buffer_read(struct iio_buffer *buffer, size_t n,
char __user *user_buffer)
{
struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buffer);
struct iio_dma_buffer_block *block;
int ret;
if (n < buffer->bytes_per_datum)
return -EINVAL;
mutex_lock(&queue->lock);
if (!queue->fileio.active_block) {
block = iio_dma_buffer_dequeue(queue);
if (block == NULL) {
ret = 0;
goto out_unlock;
}
queue->fileio.pos = 0;
queue->fileio.active_block = block;
} else {
block = queue->fileio.active_block;
}
n = rounddown(n, buffer->bytes_per_datum);
if (n > block->bytes_used - queue->fileio.pos)
n = block->bytes_used - queue->fileio.pos;
if (copy_to_user(user_buffer, block->vaddr + queue->fileio.pos, n)) {
ret = -EFAULT;
goto out_unlock;
}
queue->fileio.pos += n;
if (queue->fileio.pos == block->bytes_used) {
queue->fileio.active_block = NULL;
iio_dma_buffer_enqueue(queue, block);
}
ret = n;
out_unlock:
mutex_unlock(&queue->lock);
return ret;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_read);
/**
* iio_dma_buffer_data_available() - DMA buffer data_available callback
* @buf: Buffer to check for data availability
*
* Should be used as the data_available callback for iio_buffer_access_ops
* struct for DMA buffers.
*/
size_t iio_dma_buffer_data_available(struct iio_buffer *buf)
{
struct iio_dma_buffer_queue *queue = iio_buffer_to_queue(buf);
struct iio_dma_buffer_block *block;
size_t data_available = 0;
/*
* For counting the available bytes we'll use the size of the block not
* the number of actual bytes available in the block. Otherwise it is
* possible that we end up with a value that is lower than the watermark
* but won't increase since all blocks are in use.
*/
mutex_lock(&queue->lock);
if (queue->fileio.active_block)
data_available += queue->fileio.active_block->size;
spin_lock_irq(&queue->list_lock);
list_for_each_entry(block, &queue->outgoing, head)
data_available += block->size;
spin_unlock_irq(&queue->list_lock);
mutex_unlock(&queue->lock);
return data_available;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_data_available);
/**
* iio_dma_buffer_set_bytes_per_datum() - DMA buffer set_bytes_per_datum callback
* @buffer: Buffer to set the bytes-per-datum for
* @bpd: The new bytes-per-datum value
*
* Should be used as the set_bytes_per_datum callback for iio_buffer_access_ops
* struct for DMA buffers.
*/
int iio_dma_buffer_set_bytes_per_datum(struct iio_buffer *buffer, size_t bpd)
{
buffer->bytes_per_datum = bpd;
return 0;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_set_bytes_per_datum);
/**
* iio_dma_buffer_set_length - DMA buffer set_length callback
* @buffer: Buffer to set the length for
* @length: The new buffer length
*
* Should be used as the set_length callback for iio_buffer_access_ops
* struct for DMA buffers.
*/
int iio_dma_buffer_set_length(struct iio_buffer *buffer, unsigned int length)
{
/* Avoid an invalid state */
if (length < 2)
length = 2;
buffer->length = length;
buffer->watermark = length / 2;
return 0;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_set_length);
/**
* iio_dma_buffer_init() - Initialize DMA buffer queue
* @queue: Buffer to initialize
* @dev: DMA device
* @ops: DMA buffer queue callback operations
*
* The DMA device will be used by the queue to do DMA memory allocations. So it
* should refer to the device that will perform the DMA to ensure that
* allocations are done from a memory region that can be accessed by the device.
*/
int iio_dma_buffer_init(struct iio_dma_buffer_queue *queue,
struct device *dev, const struct iio_dma_buffer_ops *ops)
{
iio_buffer_init(&queue->buffer);
queue->buffer.length = PAGE_SIZE;
queue->buffer.watermark = queue->buffer.length / 2;
queue->dev = dev;
queue->ops = ops;
INIT_LIST_HEAD(&queue->incoming);
INIT_LIST_HEAD(&queue->outgoing);
mutex_init(&queue->lock);
spin_lock_init(&queue->list_lock);
return 0;
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_init);
/**
* iio_dma_buffer_exit() - Cleanup DMA buffer queue
* @queue: Buffer to cleanup
*
* After this function has completed it is safe to free any resources that are
* associated with the buffer and are accessed inside the callback operations.
*/
void iio_dma_buffer_exit(struct iio_dma_buffer_queue *queue)
{
unsigned int i;
mutex_lock(&queue->lock);
spin_lock_irq(&queue->list_lock);
for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {
if (!queue->fileio.blocks[i])
continue;
queue->fileio.blocks[i]->state = IIO_BLOCK_STATE_DEAD;
}
INIT_LIST_HEAD(&queue->outgoing);
spin_unlock_irq(&queue->list_lock);
INIT_LIST_HEAD(&queue->incoming);
for (i = 0; i < ARRAY_SIZE(queue->fileio.blocks); i++) {
if (!queue->fileio.blocks[i])
continue;
iio_buffer_block_put(queue->fileio.blocks[i]);
queue->fileio.blocks[i] = NULL;
}
queue->fileio.active_block = NULL;
queue->ops = NULL;
mutex_unlock(&queue->lock);
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_exit);
/**
* iio_dma_buffer_release() - Release final buffer resources
* @queue: Buffer to release
*
* Frees resources that can't yet be freed in iio_dma_buffer_exit(). Should be
* called in the buffers release callback implementation right before freeing
* the memory associated with the buffer.
*/
void iio_dma_buffer_release(struct iio_dma_buffer_queue *queue)
{
mutex_destroy(&queue->lock);
}
EXPORT_SYMBOL_GPL(iio_dma_buffer_release);
MODULE_AUTHOR("Lars-Peter Clausen <[email protected]>");
MODULE_DESCRIPTION("DMA buffer for the IIO framework");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
raj-bhatia/grooveip-ios-public | submodules/externals/opencore-amr/opencore/codecs_v2/audio/gsm_amr/amr_wb/dec/src/q_gain2_tab.cpp | 5030 | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.173
ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
Available from http://www.3gpp.org
(C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
#include "qisf_ns.h"
/*
* Tables for function q_gain2()
*
* g_pitch(Q14), g_code(Q11)
*
* pitch gain are ordered in table to reduce complexity
* during quantization of gains.
*/
const int16 t_qua_gain6b[NB_QUA_GAIN6B*2] =
{
1566, 1332,
1577, 3557,
3071, 6490,
4193, 10163,
4496, 2534,
5019, 4488,
5586, 15614,
5725, 1422,
6453, 580,
6724, 6831,
7657, 3527,
8072, 2099,
8232, 5319,
8827, 8775,
9740, 2868,
9856, 1465,
10087, 12488,
10241, 4453,
10859, 6618,
11321, 3587,
11417, 1800,
11643, 2428,
11718, 988,
12312, 5093,
12523, 8413,
12574, 26214,
12601, 3396,
13172, 1623,
13285, 2423,
13418, 6087,
13459, 12810,
13656, 3607,
14111, 4521,
14144, 1229,
14425, 1871,
14431, 7234,
14445, 2834,
14628, 10036,
14860, 17496,
15161, 3629,
15209, 5819,
15299, 2256,
15518, 4722,
15663, 1060,
15759, 7972,
15939, 11964,
16020, 2996,
16086, 1707,
16521, 4254,
16576, 6224,
16894, 2380,
16906, 681,
17213, 8406,
17610, 3418,
17895, 5269,
18168, 11748,
18230, 1575,
18607, 32767,
18728, 21684,
19137, 2543,
19422, 6577,
19446, 4097,
19450, 9056,
20371, 14885
};
const int16 t_qua_gain7b[NB_QUA_GAIN7B*2] =
{
204, 441,
464, 1977,
869, 1077,
1072, 3062,
1281, 4759,
1647, 1539,
1845, 7020,
1853, 634,
1995, 2336,
2351, 15400,
2661, 1165,
2702, 3900,
2710, 10133,
3195, 1752,
3498, 2624,
3663, 849,
3984, 5697,
4214, 3399,
4415, 1304,
4695, 2056,
5376, 4558,
5386, 676,
5518, 23554,
5567, 7794,
5644, 3061,
5672, 1513,
5957, 2338,
6533, 1060,
6804, 5998,
6820, 1767,
6937, 3837,
7277, 414,
7305, 2665,
7466, 11304,
7942, 794,
8007, 1982,
8007, 1366,
8326, 3105,
8336, 4810,
8708, 7954,
8989, 2279,
9031, 1055,
9247, 3568,
9283, 1631,
9654, 6311,
9811, 2605,
10120, 683,
10143, 4179,
10245, 1946,
10335, 1218,
10468, 9960,
10651, 3000,
10951, 1530,
10969, 5290,
11203, 2305,
11325, 3562,
11771, 6754,
11839, 1849,
11941, 4495,
11954, 1298,
11975, 15223,
11977, 883,
11986, 2842,
12438, 2141,
12593, 3665,
12636, 8367,
12658, 1594,
12886, 2628,
12984, 4942,
13146, 1115,
13224, 524,
13341, 3163,
13399, 1923,
13549, 5961,
13606, 1401,
13655, 2399,
13782, 3909,
13868, 10923,
14226, 1723,
14232, 2939,
14278, 7528,
14439, 4598,
14451, 984,
14458, 2265,
14792, 1403,
14818, 3445,
14899, 5709,
15017, 15362,
15048, 1946,
15069, 2655,
15405, 9591,
15405, 4079,
15570, 7183,
15687, 2286,
15691, 1624,
15699, 3068,
15772, 5149,
15868, 1205,
15970, 696,
16249, 3584,
16338, 1917,
16424, 2560,
16483, 4438,
16529, 6410,
16620, 11966,
16839, 8780,
17030, 3050,
17033, 18325,
17092, 1568,
17123, 5197,
17351, 2113,
17374, 980,
17566, 26214,
17609, 3912,
17639, 32767,
18151, 7871,
18197, 2516,
18202, 5649,
18679, 3283,
18930, 1370,
19271, 13757,
19317, 4120,
19460, 1973,
19654, 10018,
19764, 6792,
19912, 5135,
20040, 2841,
21234, 19833
};
| gpl-2.0 |
tprrt/linux-stable | arch/powerpc/kernel/signal_64.c | 30604 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* PowerPC version
* Copyright (C) 1995-1996 Gary Thomas ([email protected])
*
* Derived from "arch/i386/kernel/signal.c"
* Copyright (C) 1991, 1992 Linus Torvalds
* 1997-11-28 Modified for POSIX.1b signals by Richard Henderson
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/elf.h>
#include <linux/ptrace.h>
#include <linux/ratelimit.h>
#include <linux/syscalls.h>
#include <linux/pagemap.h>
#include <asm/sigcontext.h>
#include <asm/ucontext.h>
#include <linux/uaccess.h>
#include <asm/unistd.h>
#include <asm/cacheflush.h>
#include <asm/syscalls.h>
#include <asm/vdso.h>
#include <asm/switch_to.h>
#include <asm/tm.h>
#include <asm/asm-prototypes.h>
#include "signal.h"
#define GP_REGS_SIZE min(sizeof(elf_gregset_t), sizeof(struct pt_regs))
#define FP_REGS_SIZE sizeof(elf_fpregset_t)
#define TRAMP_TRACEBACK 4
#define TRAMP_SIZE 7
/*
* When we have signals to deliver, we set up on the user stack,
* going down from the original stack pointer:
* 1) a rt_sigframe struct which contains the ucontext
* 2) a gap of __SIGNAL_FRAMESIZE bytes which acts as a dummy caller
* frame for the signal handler.
*/
struct rt_sigframe {
/* sys_rt_sigreturn requires the ucontext be the first field */
struct ucontext uc;
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
struct ucontext uc_transact;
#endif
unsigned long _unused[2];
unsigned int tramp[TRAMP_SIZE];
struct siginfo __user *pinfo;
void __user *puc;
struct siginfo info;
/* New 64 bit little-endian ABI allows redzone of 512 bytes below sp */
char abigap[USER_REDZONE_SIZE];
} __attribute__ ((aligned (16)));
/*
* This computes a quad word aligned pointer inside the vmx_reserve array
* element. For historical reasons sigcontext might not be quad word aligned,
* but the location we write the VMX regs to must be. See the comment in
* sigcontext for more detail.
*/
#ifdef CONFIG_ALTIVEC
static elf_vrreg_t __user *sigcontext_vmx_regs(struct sigcontext __user *sc)
{
return (elf_vrreg_t __user *) (((unsigned long)sc->vmx_reserve + 15) & ~0xful);
}
#endif
static void prepare_setup_sigcontext(struct task_struct *tsk)
{
#ifdef CONFIG_ALTIVEC
/* save altivec registers */
if (tsk->thread.used_vr)
flush_altivec_to_thread(tsk);
if (cpu_has_feature(CPU_FTR_ALTIVEC))
tsk->thread.vrsave = mfspr(SPRN_VRSAVE);
#endif /* CONFIG_ALTIVEC */
flush_fp_to_thread(tsk);
#ifdef CONFIG_VSX
if (tsk->thread.used_vsr)
flush_vsx_to_thread(tsk);
#endif /* CONFIG_VSX */
}
/*
* Set up the sigcontext for the signal frame.
*/
#define unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region, label)\
do { \
if (__unsafe_setup_sigcontext(sc, tsk, signr, set, handler, ctx_has_vsx_region))\
goto label; \
} while (0)
static long notrace __unsafe_setup_sigcontext(struct sigcontext __user *sc,
struct task_struct *tsk, int signr, sigset_t *set,
unsigned long handler, int ctx_has_vsx_region)
{
/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the
* process never used altivec yet (MSR_VEC is zero in pt_regs of
* the context). This is very important because we must ensure we
* don't lose the VRSAVE content that may have been set prior to
* the process doing its first vector operation
* Userland shall check AT_HWCAP to know whether it can rely on the
* v_regs pointer or not
*/
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);
#endif
struct pt_regs *regs = tsk->thread.regs;
unsigned long msr = regs->msr;
/* Force usr to alway see softe as 1 (interrupts enabled) */
unsigned long softe = 0x1;
BUG_ON(tsk != current);
#ifdef CONFIG_ALTIVEC
unsafe_put_user(v_regs, &sc->v_regs, efault_out);
/* save altivec registers */
if (tsk->thread.used_vr) {
/* Copy 33 vec registers (vr0..31 and vscr) to the stack */
unsafe_copy_to_user(v_regs, &tsk->thread.vr_state,
33 * sizeof(vector128), efault_out);
/* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg)
* contains valid data.
*/
msr |= MSR_VEC;
}
/* We always copy to/from vrsave, it's 0 if we don't have or don't
* use altivec.
*/
unsafe_put_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out);
#else /* CONFIG_ALTIVEC */
unsafe_put_user(0, &sc->v_regs, efault_out);
#endif /* CONFIG_ALTIVEC */
/* copy fpr regs and fpscr */
unsafe_copy_fpr_to_user(&sc->fp_regs, tsk, efault_out);
/*
* Clear the MSR VSX bit to indicate there is no valid state attached
* to this context, except in the specific case below where we set it.
*/
msr &= ~MSR_VSX;
#ifdef CONFIG_VSX
/*
* Copy VSX low doubleword to local buffer for formatting,
* then out to userspace. Update v_regs to point after the
* VMX data.
*/
if (tsk->thread.used_vsr && ctx_has_vsx_region) {
v_regs += ELF_NVRREG;
unsafe_copy_vsx_to_user(v_regs, tsk, efault_out);
/* set MSR_VSX in the MSR value in the frame to
* indicate that sc->vs_reg) contains valid data.
*/
msr |= MSR_VSX;
}
#endif /* CONFIG_VSX */
unsafe_put_user(&sc->gp_regs, &sc->regs, efault_out);
unsafe_copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE, efault_out);
unsafe_put_user(msr, &sc->gp_regs[PT_MSR], efault_out);
unsafe_put_user(softe, &sc->gp_regs[PT_SOFTE], efault_out);
unsafe_put_user(signr, &sc->signal, efault_out);
unsafe_put_user(handler, &sc->handler, efault_out);
if (set != NULL)
unsafe_put_user(set->sig[0], &sc->oldmask, efault_out);
return 0;
efault_out:
return -EFAULT;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/*
* As above, but Transactional Memory is in use, so deliver sigcontexts
* containing checkpointed and transactional register states.
*
* To do this, we treclaim (done before entering here) to gather both sets of
* registers and set up the 'normal' sigcontext registers with rolled-back
* register values such that a simple signal handler sees a correct
* checkpointed register state. If interested, a TM-aware sighandler can
* examine the transactional registers in the 2nd sigcontext to determine the
* real origin of the signal.
*/
static long setup_tm_sigcontexts(struct sigcontext __user *sc,
struct sigcontext __user *tm_sc,
struct task_struct *tsk,
int signr, sigset_t *set, unsigned long handler,
unsigned long msr)
{
/* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the
* process never used altivec yet (MSR_VEC is zero in pt_regs of
* the context). This is very important because we must ensure we
* don't lose the VRSAVE content that may have been set prior to
* the process doing its first vector operation
* Userland shall check AT_HWCAP to know wether it can rely on the
* v_regs pointer or not.
*/
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc);
elf_vrreg_t __user *tm_v_regs = sigcontext_vmx_regs(tm_sc);
#endif
struct pt_regs *regs = tsk->thread.regs;
long err = 0;
BUG_ON(tsk != current);
BUG_ON(!MSR_TM_ACTIVE(msr));
WARN_ON(tm_suspend_disabled);
/* Restore checkpointed FP, VEC, and VSX bits from ckpt_regs as
* it contains the correct FP, VEC, VSX state after we treclaimed
* the transaction and giveup_all() was called on reclaiming.
*/
msr |= tsk->thread.ckpt_regs.msr & (MSR_FP | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __put_user(v_regs, &sc->v_regs);
err |= __put_user(tm_v_regs, &tm_sc->v_regs);
/* save altivec registers */
if (tsk->thread.used_vr) {
/* Copy 33 vec registers (vr0..31 and vscr) to the stack */
err |= __copy_to_user(v_regs, &tsk->thread.ckvr_state,
33 * sizeof(vector128));
/* If VEC was enabled there are transactional VRs valid too,
* else they're a copy of the checkpointed VRs.
*/
if (msr & MSR_VEC)
err |= __copy_to_user(tm_v_regs,
&tsk->thread.vr_state,
33 * sizeof(vector128));
else
err |= __copy_to_user(tm_v_regs,
&tsk->thread.ckvr_state,
33 * sizeof(vector128));
/* set MSR_VEC in the MSR value in the frame to indicate
* that sc->v_reg contains valid data.
*/
msr |= MSR_VEC;
}
/* We always copy to/from vrsave, it's 0 if we don't have or don't
* use altivec.
*/
if (cpu_has_feature(CPU_FTR_ALTIVEC))
tsk->thread.ckvrsave = mfspr(SPRN_VRSAVE);
err |= __put_user(tsk->thread.ckvrsave, (u32 __user *)&v_regs[33]);
if (msr & MSR_VEC)
err |= __put_user(tsk->thread.vrsave,
(u32 __user *)&tm_v_regs[33]);
else
err |= __put_user(tsk->thread.ckvrsave,
(u32 __user *)&tm_v_regs[33]);
#else /* CONFIG_ALTIVEC */
err |= __put_user(0, &sc->v_regs);
err |= __put_user(0, &tm_sc->v_regs);
#endif /* CONFIG_ALTIVEC */
/* copy fpr regs and fpscr */
err |= copy_ckfpr_to_user(&sc->fp_regs, tsk);
if (msr & MSR_FP)
err |= copy_fpr_to_user(&tm_sc->fp_regs, tsk);
else
err |= copy_ckfpr_to_user(&tm_sc->fp_regs, tsk);
#ifdef CONFIG_VSX
/*
* Copy VSX low doubleword to local buffer for formatting,
* then out to userspace. Update v_regs to point after the
* VMX data.
*/
if (tsk->thread.used_vsr) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_ckvsx_to_user(v_regs, tsk);
if (msr & MSR_VSX)
err |= copy_vsx_to_user(tm_v_regs, tsk);
else
err |= copy_ckvsx_to_user(tm_v_regs, tsk);
/* set MSR_VSX in the MSR value in the frame to
* indicate that sc->vs_reg) contains valid data.
*/
msr |= MSR_VSX;
}
#endif /* CONFIG_VSX */
err |= __put_user(&sc->gp_regs, &sc->regs);
err |= __put_user(&tm_sc->gp_regs, &tm_sc->regs);
err |= __copy_to_user(&tm_sc->gp_regs, regs, GP_REGS_SIZE);
err |= __copy_to_user(&sc->gp_regs,
&tsk->thread.ckpt_regs, GP_REGS_SIZE);
err |= __put_user(msr, &tm_sc->gp_regs[PT_MSR]);
err |= __put_user(msr, &sc->gp_regs[PT_MSR]);
err |= __put_user(signr, &sc->signal);
err |= __put_user(handler, &sc->handler);
if (set != NULL)
err |= __put_user(set->sig[0], &sc->oldmask);
return err;
}
#endif
/*
* Restore the sigcontext from the signal frame.
*/
#define unsafe_restore_sigcontext(tsk, set, sig, sc, label) do { \
if (__unsafe_restore_sigcontext(tsk, set, sig, sc)) \
goto label; \
} while (0)
static long notrace __unsafe_restore_sigcontext(struct task_struct *tsk, sigset_t *set,
int sig, struct sigcontext __user *sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs;
#endif
unsigned long save_r13 = 0;
unsigned long msr;
struct pt_regs *regs = tsk->thread.regs;
#ifdef CONFIG_VSX
int i;
#endif
BUG_ON(tsk != current);
/* If this is not a signal return, we preserve the TLS in r13 */
if (!sig)
save_r13 = regs->gpr[13];
/* copy the GPRs */
unsafe_copy_from_user(regs->gpr, sc->gp_regs, sizeof(regs->gpr), efault_out);
unsafe_get_user(regs->nip, &sc->gp_regs[PT_NIP], efault_out);
/* get MSR separately, transfer the LE bit if doing signal return */
unsafe_get_user(msr, &sc->gp_regs[PT_MSR], efault_out);
if (sig)
regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE));
unsafe_get_user(regs->orig_gpr3, &sc->gp_regs[PT_ORIG_R3], efault_out);
unsafe_get_user(regs->ctr, &sc->gp_regs[PT_CTR], efault_out);
unsafe_get_user(regs->link, &sc->gp_regs[PT_LNK], efault_out);
unsafe_get_user(regs->xer, &sc->gp_regs[PT_XER], efault_out);
unsafe_get_user(regs->ccr, &sc->gp_regs[PT_CCR], efault_out);
/* Don't allow userspace to set SOFTE */
set_trap_norestart(regs);
unsafe_get_user(regs->dar, &sc->gp_regs[PT_DAR], efault_out);
unsafe_get_user(regs->dsisr, &sc->gp_regs[PT_DSISR], efault_out);
unsafe_get_user(regs->result, &sc->gp_regs[PT_RESULT], efault_out);
if (!sig)
regs->gpr[13] = save_r13;
if (set != NULL)
unsafe_get_user(set->sig[0], &sc->oldmask, efault_out);
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into tsk->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX));
#ifdef CONFIG_ALTIVEC
unsafe_get_user(v_regs, &sc->v_regs, efault_out);
if (v_regs && !access_ok(v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && (msr & MSR_VEC) != 0) {
unsafe_copy_from_user(&tsk->thread.vr_state, v_regs,
33 * sizeof(vector128), efault_out);
tsk->thread.used_vr = true;
} else if (tsk->thread.used_vr) {
memset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL)
unsafe_get_user(tsk->thread.vrsave, (u32 __user *)&v_regs[33], efault_out);
else
tsk->thread.vrsave = 0;
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, tsk->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
unsafe_copy_fpr_from_user(tsk, &sc->fp_regs, efault_out);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
v_regs += ELF_NVRREG;
if ((msr & MSR_VSX) != 0) {
unsafe_copy_vsx_from_user(tsk, v_regs, efault_out);
tsk->thread.used_vsr = true;
} else {
for (i = 0; i < 32 ; i++)
tsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
}
#endif
return 0;
efault_out:
return -EFAULT;
}
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/*
* Restore the two sigcontexts from the frame of a transactional processes.
*/
static long restore_tm_sigcontexts(struct task_struct *tsk,
struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs, *tm_v_regs;
#endif
unsigned long err = 0;
unsigned long msr;
struct pt_regs *regs = tsk->thread.regs;
#ifdef CONFIG_VSX
int i;
#endif
BUG_ON(tsk != current);
if (tm_suspend_disabled)
return -EINVAL;
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));
err |= __copy_from_user(&tsk->thread.ckpt_regs, sc->gp_regs,
sizeof(regs->gpr));
/*
* TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.
* TEXASR was set by the signal delivery reclaim, as was TFIAR.
* Users doing anything abhorrent like thread-switching w/ signals for
* TM-Suspended code will have to back TEXASR/TFIAR up themselves.
* For the case of getting a signal and simply returning from it,
* we don't need to re-copy them here.
*/
err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);
err |= __get_user(tsk->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
/* Don't allow reserved mode. */
if (MSR_TM_RESV(msr))
return -EINVAL;
/* pull in MSR LE from user context */
regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (msr & MSR_LE));
/* The following non-GPR non-FPR non-VR state is also checkpointed: */
err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);
err |= __get_user(tsk->thread.ckpt_regs.ctr,
&sc->gp_regs[PT_CTR]);
err |= __get_user(tsk->thread.ckpt_regs.link,
&sc->gp_regs[PT_LNK]);
err |= __get_user(tsk->thread.ckpt_regs.xer,
&sc->gp_regs[PT_XER]);
err |= __get_user(tsk->thread.ckpt_regs.ccr,
&sc->gp_regs[PT_CCR]);
/* Don't allow userspace to set SOFTE */
set_trap_norestart(regs);
/* These regs are not checkpointed; they can go in 'regs'. */
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into tsk->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs_set_return_msr(regs, regs->msr & ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX));
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
err |= __get_user(tm_v_regs, &tm_sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(v_regs, 34 * sizeof(vector128)))
return -EFAULT;
if (tm_v_regs && !access_ok(tm_v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {
err |= __copy_from_user(&tsk->thread.ckvr_state, v_regs,
33 * sizeof(vector128));
err |= __copy_from_user(&tsk->thread.vr_state, tm_v_regs,
33 * sizeof(vector128));
current->thread.used_vr = true;
}
else if (tsk->thread.used_vr) {
memset(&tsk->thread.vr_state, 0, 33 * sizeof(vector128));
memset(&tsk->thread.ckvr_state, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL && tm_v_regs != NULL) {
err |= __get_user(tsk->thread.ckvrsave,
(u32 __user *)&v_regs[33]);
err |= __get_user(tsk->thread.vrsave,
(u32 __user *)&tm_v_regs[33]);
}
else {
tsk->thread.vrsave = 0;
tsk->thread.ckvrsave = 0;
}
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, tsk->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(tsk, &tm_sc->fp_regs);
err |= copy_ckfpr_from_user(tsk, &sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
if (v_regs && ((msr & MSR_VSX) != 0)) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_from_user(tsk, tm_v_regs);
err |= copy_ckvsx_from_user(tsk, v_regs);
tsk->thread.used_vsr = true;
} else {
for (i = 0; i < 32 ; i++) {
tsk->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
tsk->thread.ckfp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
}
}
#endif
tm_enable();
/* Make sure the transaction is marked as failed */
tsk->thread.tm_texasr |= TEXASR_FS;
/*
* Disabling preemption, since it is unsafe to be preempted
* with MSR[TS] set without recheckpointing.
*/
preempt_disable();
/* pull in MSR TS bits from user context */
regs_set_return_msr(regs, regs->msr | (msr & MSR_TS_MASK));
/*
* Ensure that TM is enabled in regs->msr before we leave the signal
* handler. It could be the case that (a) user disabled the TM bit
* through the manipulation of the MSR bits in uc_mcontext or (b) the
* TM bit was disabled because a sufficient number of context switches
* happened whilst in the signal handler and load_tm overflowed,
* disabling the TM bit. In either case we can end up with an illegal
* TM state leading to a TM Bad Thing when we return to userspace.
*
* CAUTION:
* After regs->MSR[TS] being updated, make sure that get_user(),
* put_user() or similar functions are *not* called. These
* functions can generate page faults which will cause the process
* to be de-scheduled with MSR[TS] set but without calling
* tm_recheckpoint(). This can cause a bug.
*/
regs_set_return_msr(regs, regs->msr | MSR_TM);
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(&tsk->thread);
msr_check_and_set(msr & (MSR_FP | MSR_VEC));
if (msr & MSR_FP) {
load_fp_state(&tsk->thread.fp_state);
regs_set_return_msr(regs, regs->msr | (MSR_FP | tsk->thread.fpexc_mode));
}
if (msr & MSR_VEC) {
load_vr_state(&tsk->thread.vr_state);
regs_set_return_msr(regs, regs->msr | MSR_VEC);
}
preempt_enable();
return err;
}
#else /* !CONFIG_PPC_TRANSACTIONAL_MEM */
static long restore_tm_sigcontexts(struct task_struct *tsk, struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
return -EINVAL;
}
#endif
/*
* Setup the trampoline code on the stack
*/
static long setup_trampoline(unsigned int syscall, unsigned int __user *tramp)
{
int i;
long err = 0;
/* Call the handler and pop the dummy stackframe*/
err |= __put_user(PPC_RAW_BCTRL(), &tramp[0]);
err |= __put_user(PPC_RAW_ADDI(_R1, _R1, __SIGNAL_FRAMESIZE), &tramp[1]);
err |= __put_user(PPC_RAW_LI(_R0, syscall), &tramp[2]);
err |= __put_user(PPC_RAW_SC(), &tramp[3]);
/* Minimal traceback info */
for (i=TRAMP_TRACEBACK; i < TRAMP_SIZE ;i++)
err |= __put_user(0, &tramp[i]);
if (!err)
flush_icache_range((unsigned long) &tramp[0],
(unsigned long) &tramp[TRAMP_SIZE]);
return err;
}
/*
* Userspace code may pass a ucontext which doesn't include VSX added
* at the end. We need to check for this case.
*/
#define UCONTEXTSIZEWITHOUTVSX \
(sizeof(struct ucontext) - 32*sizeof(long))
/*
* Handle {get,set,swap}_context operations
*/
SYSCALL_DEFINE3(swapcontext, struct ucontext __user *, old_ctx,
struct ucontext __user *, new_ctx, long, ctx_size)
{
sigset_t set;
unsigned long new_msr = 0;
int ctx_has_vsx_region = 0;
if (new_ctx &&
get_user(new_msr, &new_ctx->uc_mcontext.gp_regs[PT_MSR]))
return -EFAULT;
/*
* Check that the context is not smaller than the original
* size (with VMX but without VSX)
*/
if (ctx_size < UCONTEXTSIZEWITHOUTVSX)
return -EINVAL;
/*
* If the new context state sets the MSR VSX bits but
* it doesn't provide VSX state.
*/
if ((ctx_size < sizeof(struct ucontext)) &&
(new_msr & MSR_VSX))
return -EINVAL;
/* Does the context have enough room to store VSX data? */
if (ctx_size >= sizeof(struct ucontext))
ctx_has_vsx_region = 1;
if (old_ctx != NULL) {
prepare_setup_sigcontext(current);
if (!user_write_access_begin(old_ctx, ctx_size))
return -EFAULT;
unsafe_setup_sigcontext(&old_ctx->uc_mcontext, current, 0, NULL,
0, ctx_has_vsx_region, efault_out);
unsafe_copy_to_user(&old_ctx->uc_sigmask, ¤t->blocked,
sizeof(sigset_t), efault_out);
user_write_access_end();
}
if (new_ctx == NULL)
return 0;
if (!access_ok(new_ctx, ctx_size) ||
fault_in_pages_readable((u8 __user *)new_ctx, ctx_size))
return -EFAULT;
/*
* If we get a fault copying the context into the kernel's
* image of the user's registers, we can't just return -EFAULT
* because the user's registers will be corrupted. For instance
* the NIP value may have been updated but not some of the
* other registers. Given that we have done the access_ok
* and successfully read the first and last bytes of the region
* above, this should only happen in an out-of-memory situation
* or if another thread unmaps the region containing the context.
* We kill the task with a SIGSEGV in this situation.
*/
if (__get_user_sigset(&set, &new_ctx->uc_sigmask))
do_exit(SIGSEGV);
set_current_blocked(&set);
if (!user_read_access_begin(new_ctx, ctx_size))
return -EFAULT;
if (__unsafe_restore_sigcontext(current, NULL, 0, &new_ctx->uc_mcontext)) {
user_read_access_end();
do_exit(SIGSEGV);
}
user_read_access_end();
/* This returns like rt_sigreturn */
set_thread_flag(TIF_RESTOREALL);
return 0;
efault_out:
user_write_access_end();
return -EFAULT;
}
/*
* Do a signal return; undo the signal stack.
*/
SYSCALL_DEFINE0(rt_sigreturn)
{
struct pt_regs *regs = current_pt_regs();
struct ucontext __user *uc = (struct ucontext __user *)regs->gpr[1];
sigset_t set;
unsigned long msr;
/* Always make any pending restarted system calls return -EINTR */
current->restart_block.fn = do_no_restart_syscall;
if (!access_ok(uc, sizeof(*uc)))
goto badframe;
if (__get_user_sigset(&set, &uc->uc_sigmask))
goto badframe;
set_current_blocked(&set);
if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM)) {
/*
* If there is a transactional state then throw it away.
* The purpose of a sigreturn is to destroy all traces of the
* signal frame, this includes any transactional state created
* within in. We only check for suspended as we can never be
* active in the kernel, we are active, there is nothing better to
* do than go ahead and Bad Thing later.
* The cause is not important as there will never be a
* recheckpoint so it's not user visible.
*/
if (MSR_TM_SUSPENDED(mfmsr()))
tm_reclaim_current(0);
/*
* Disable MSR[TS] bit also, so, if there is an exception in the
* code below (as a page fault in copy_ckvsx_to_user()), it does
* not recheckpoint this task if there was a context switch inside
* the exception.
*
* A major page fault can indirectly call schedule(). A reschedule
* process in the middle of an exception can have a side effect
* (Changing the CPU MSR[TS] state), since schedule() is called
* with the CPU MSR[TS] disable and returns with MSR[TS]=Suspended
* (switch_to() calls tm_recheckpoint() for the 'new' process). In
* this case, the process continues to be the same in the CPU, but
* the CPU state just changed.
*
* This can cause a TM Bad Thing, since the MSR in the stack will
* have the MSR[TS]=0, and this is what will be used to RFID.
*
* Clearing MSR[TS] state here will avoid a recheckpoint if there
* is any process reschedule in kernel space. The MSR[TS] state
* does not need to be saved also, since it will be replaced with
* the MSR[TS] that came from user context later, at
* restore_tm_sigcontexts.
*/
regs_set_return_msr(regs, regs->msr & ~MSR_TS_MASK);
if (__get_user(msr, &uc->uc_mcontext.gp_regs[PT_MSR]))
goto badframe;
}
if (IS_ENABLED(CONFIG_PPC_TRANSACTIONAL_MEM) && MSR_TM_ACTIVE(msr)) {
/* We recheckpoint on return. */
struct ucontext __user *uc_transact;
/* Trying to start TM on non TM system */
if (!cpu_has_feature(CPU_FTR_TM))
goto badframe;
if (__get_user(uc_transact, &uc->uc_link))
goto badframe;
if (restore_tm_sigcontexts(current, &uc->uc_mcontext,
&uc_transact->uc_mcontext))
goto badframe;
} else {
/*
* Fall through, for non-TM restore
*
* Unset MSR[TS] on the thread regs since MSR from user
* context does not have MSR active, and recheckpoint was
* not called since restore_tm_sigcontexts() was not called
* also.
*
* If not unsetting it, the code can RFID to userspace with
* MSR[TS] set, but without CPU in the proper state,
* causing a TM bad thing.
*/
regs_set_return_msr(current->thread.regs,
current->thread.regs->msr & ~MSR_TS_MASK);
if (!user_read_access_begin(&uc->uc_mcontext, sizeof(uc->uc_mcontext)))
goto badframe;
unsafe_restore_sigcontext(current, NULL, 1, &uc->uc_mcontext,
badframe_block);
user_read_access_end();
}
if (restore_altstack(&uc->uc_stack))
goto badframe;
set_thread_flag(TIF_RESTOREALL);
return 0;
badframe_block:
user_read_access_end();
badframe:
signal_fault(current, regs, "rt_sigreturn", uc);
force_sig(SIGSEGV);
return 0;
}
int handle_rt_signal64(struct ksignal *ksig, sigset_t *set,
struct task_struct *tsk)
{
struct rt_sigframe __user *frame;
unsigned long newsp = 0;
long err = 0;
struct pt_regs *regs = tsk->thread.regs;
/* Save the thread's msr before get_tm_stackpointer() changes it */
unsigned long msr = regs->msr;
frame = get_sigframe(ksig, tsk, sizeof(*frame), 0);
/*
* This only applies when calling unsafe_setup_sigcontext() and must be
* called before opening the uaccess window.
*/
if (!MSR_TM_ACTIVE(msr))
prepare_setup_sigcontext(tsk);
if (!user_write_access_begin(frame, sizeof(*frame)))
goto badframe;
unsafe_put_user(&frame->info, &frame->pinfo, badframe_block);
unsafe_put_user(&frame->uc, &frame->puc, badframe_block);
/* Create the ucontext. */
unsafe_put_user(0, &frame->uc.uc_flags, badframe_block);
unsafe_save_altstack(&frame->uc.uc_stack, regs->gpr[1], badframe_block);
if (MSR_TM_ACTIVE(msr)) {
#ifdef CONFIG_PPC_TRANSACTIONAL_MEM
/* The ucontext_t passed to userland points to the second
* ucontext_t (for transactional state) with its uc_link ptr.
*/
unsafe_put_user(&frame->uc_transact, &frame->uc.uc_link, badframe_block);
user_write_access_end();
err |= setup_tm_sigcontexts(&frame->uc.uc_mcontext,
&frame->uc_transact.uc_mcontext,
tsk, ksig->sig, NULL,
(unsigned long)ksig->ka.sa.sa_handler,
msr);
if (!user_write_access_begin(&frame->uc.uc_sigmask,
sizeof(frame->uc.uc_sigmask)))
goto badframe;
#endif
} else {
unsafe_put_user(0, &frame->uc.uc_link, badframe_block);
unsafe_setup_sigcontext(&frame->uc.uc_mcontext, tsk, ksig->sig,
NULL, (unsigned long)ksig->ka.sa.sa_handler,
1, badframe_block);
}
unsafe_copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set), badframe_block);
user_write_access_end();
/* Save the siginfo outside of the unsafe block. */
if (copy_siginfo_to_user(&frame->info, &ksig->info))
goto badframe;
/* Make sure signal handler doesn't get spurious FP exceptions */
tsk->thread.fp_state.fpscr = 0;
/* Set up to return from userspace. */
if (tsk->mm->context.vdso) {
regs_set_return_ip(regs, VDSO64_SYMBOL(tsk->mm->context.vdso, sigtramp_rt64));
} else {
err |= setup_trampoline(__NR_rt_sigreturn, &frame->tramp[0]);
if (err)
goto badframe;
regs_set_return_ip(regs, (unsigned long) &frame->tramp[0]);
}
/* Allocate a dummy caller frame for the signal handler. */
newsp = ((unsigned long)frame) - __SIGNAL_FRAMESIZE;
err |= put_user(regs->gpr[1], (unsigned long __user *)newsp);
/* Set up "regs" so we "return" to the signal handler. */
if (is_elf2_task()) {
regs->ctr = (unsigned long) ksig->ka.sa.sa_handler;
regs->gpr[12] = regs->ctr;
} else {
/* Handler is *really* a pointer to the function descriptor for
* the signal routine. The first entry in the function
* descriptor is the entry address of signal and the second
* entry is the TOC value we need to use.
*/
func_descr_t __user *funct_desc_ptr =
(func_descr_t __user *) ksig->ka.sa.sa_handler;
err |= get_user(regs->ctr, &funct_desc_ptr->entry);
err |= get_user(regs->gpr[2], &funct_desc_ptr->toc);
}
/* enter the signal handler in native-endian mode */
regs_set_return_msr(regs, (regs->msr & ~MSR_LE) | (MSR_KERNEL & MSR_LE));
regs->gpr[1] = newsp;
regs->gpr[3] = ksig->sig;
regs->result = 0;
if (ksig->ka.sa.sa_flags & SA_SIGINFO) {
regs->gpr[4] = (unsigned long)&frame->info;
regs->gpr[5] = (unsigned long)&frame->uc;
regs->gpr[6] = (unsigned long) frame;
} else {
regs->gpr[4] = (unsigned long)&frame->uc.uc_mcontext;
}
if (err)
goto badframe;
return 0;
badframe_block:
user_write_access_end();
badframe:
signal_fault(current, regs, "handle_rt_signal64", frame);
return 1;
}
| gpl-2.0 |
rohlandm/servo | components/script/dom/htmlareaelement.rs | 2237 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::reflector::Reflectable;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use std::default::Default;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableHeap<JS<DOMTokenList>>,
}
impl HTMLAreaElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAreaElement> {
let element = HTMLAreaElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)
}
}
impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("rel") => AttrValue::from_serialized_tokenlist(value),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &atom!("rel"))
})
}
}
| mpl-2.0 |
gkneighb/insoshi | vendor/plugins/will_paginate/lib/will_paginate/finder.rb | 10582 | require 'will_paginate/core_ext'
module WillPaginate
# A mixin for ActiveRecord::Base. Provides +per_page+ class method
# and hooks things up to provide paginating finders.
#
# Find out more in WillPaginate::Finder::ClassMethods
#
module Finder
def self.included(base)
base.extend ClassMethods
class << base
alias_method_chain :method_missing, :paginate
# alias_method_chain :find_every, :paginate
define_method(:per_page) { 30 } unless respond_to?(:per_page)
end
end
# = Paginating finders for ActiveRecord models
#
# WillPaginate adds +paginate+, +per_page+ and other methods to
# ActiveRecord::Base class methods and associations. It also hooks into
# +method_missing+ to intercept pagination calls to dynamic finders such as
# +paginate_by_user_id+ and translate them to ordinary finders
# (+find_all_by_user_id+ in this case).
#
# In short, paginating finders are equivalent to ActiveRecord finders; the
# only difference is that we start with "paginate" instead of "find" and
# that <tt>:page</tt> is required parameter:
#
# @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
#
# In paginating finders, "all" is implicit. There is no sense in paginating
# a single record, right? So, you can drop the <tt>:all</tt> argument:
#
# Post.paginate(...) => Post.find :all
# Post.paginate_all_by_something => Post.find_all_by_something
# Post.paginate_by_something => Post.find_all_by_something
#
# == The importance of the <tt>:order</tt> parameter
#
# In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for
# the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since
# pagination only makes sense with ordered sets. Without the <tt>ORDER
# BY</tt> clause, databases aren't required to do consistent ordering when
# performing <tt>SELECT</tt> queries; this is especially true for
# PostgreSQL.
#
# Therefore, make sure you are doing ordering on a column that makes the
# most sense in the current context. Make that obvious to the user, also.
# For perfomance reasons you will also want to add an index to that column.
module ClassMethods
# This is the main paginating finder.
#
# == Special parameters for paginating finders
# * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil
# * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden)
# * <tt>:total_entries</tt> -- use only if you manually count total entries
# * <tt>:count</tt> -- additional options that are passed on to +count+
# * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find")
#
# All other options (+conditions+, +order+, ...) are forwarded to +find+
# and +count+ calls.
def paginate(*args, &block)
options = args.pop
page, per_page, total_entries = wp_parse_options(options)
finder = (options[:finder] || 'find').to_s
if finder == 'find'
# an array of IDs may have been given:
total_entries ||= (Array === args.first and args.first.size)
# :all is implicit
args.unshift(:all) if args.empty?
end
WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
count_options = options.except :page, :per_page, :total_entries, :finder
find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page)
args << find_options
# @options_from_last_find = nil
pager.replace send(finder, *args, &block)
# magic counting for user convenience:
pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries
end
end
# Iterates through all records by loading one page at a time. This is useful
# for migrations or any other use case where you don't want to load all the
# records in memory at once.
#
# It uses +paginate+ internally; therefore it accepts all of its options.
# You can specify a starting page with <tt>:page</tt> (default is 1). Default
# <tt>:order</tt> is <tt>"id"</tt>, override if necessary.
#
# See http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord where
# Jamis Buck describes this and also uses a more efficient way for MySQL.
def paginated_each(options = {}, &block)
options = { :order => 'id', :page => 1 }.merge options
options[:page] = options[:page].to_i
options[:total_entries] = 0 # skip the individual count queries
total = 0
begin
collection = paginate(options)
total += collection.each(&block).size
options[:page] += 1
end until collection.size < collection.per_page
total
end
# Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
# based on the params otherwise used by paginating finds: +page+ and
# +per_page+.
#
# Example:
#
# @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
# :page => params[:page], :per_page => 3
#
# A query for counting rows will automatically be generated if you don't
# supply <tt>:total_entries</tt>. If you experience problems with this
# generated SQL, you might want to perform the count manually in your
# application.
#
def paginate_by_sql(sql, options)
WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|
query = sanitize_sql(sql)
original_query = query.dup
# add limit, offset
add_limit! query, :offset => pager.offset, :limit => pager.per_page
# perfom the find
pager.replace find_by_sql(query)
unless pager.total_entries
count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, ''
count_query = "SELECT COUNT(*) FROM (#{count_query})"
unless ['oracle', 'oci'].include?(self.connection.adapter_name.downcase)
count_query << ' AS count_table'
end
# perform the count query
pager.total_entries = count_by_sql(count_query)
end
end
end
def respond_to?(method, include_priv = false) #:nodoc:
case method.to_sym
when :paginate, :paginate_by_sql
true
else
super(method.to_s.sub(/^paginate/, 'find'), include_priv)
end
end
protected
def method_missing_with_paginate(method, *args, &block) #:nodoc:
# did somebody tried to paginate? if not, let them be
unless method.to_s.index('paginate') == 0
return method_missing_without_paginate(method, *args, &block)
end
# paginate finders are really just find_* with limit and offset
finder = method.to_s.sub('paginate', 'find')
finder.sub!('find', 'find_all') if finder.index('find_by_') == 0
options = args.pop
raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
options = options.dup
options[:finder] = finder
args << options
paginate(*args, &block)
end
# Does the not-so-trivial job of finding out the total number of entries
# in the database. It relies on the ActiveRecord +count+ method.
def wp_count(options, args, finder)
excludees = [:count, :order, :limit, :offset, :readonly]
unless options[:select] and options[:select] =~ /^\s*DISTINCT\b/i
excludees << :select # only exclude the select param if it doesn't begin with DISTINCT
end
# count expects (almost) the same options as find
count_options = options.except *excludees
# merge the hash found in :count
# this allows you to specify :select, :order, or anything else just for the count query
count_options.update options[:count] if options[:count]
# we may be in a model or an association proxy
klass = (@owner and @reflection) ? @reflection.klass : self
# forget about includes if they are irrelevant (Rails 2.1)
if count_options[:include] and
klass.private_methods.include?('references_eager_loaded_tables?') and
!klass.send(:references_eager_loaded_tables?, count_options)
count_options.delete :include
end
# we may have to scope ...
counter = Proc.new { count(count_options) }
count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with'))
# scope_out adds a 'with_finder' method which acts like with_scope, if it's present
# then execute the count with the scoping provided by the with_finder
send(scoper, &counter)
elsif match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder)
# extract conditions from calls like "paginate_by_foo_and_bar"
attribute_names = extract_attribute_names_from_match(match)
conditions = construct_attributes_from_arguments(attribute_names, args)
with_scope(:find => { :conditions => conditions }, &counter)
else
counter.call
end
count.respond_to?(:length) ? count.length : count
end
def wp_parse_options(options) #:nodoc:
raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
options = options.symbolize_keys
raise ArgumentError, ':page parameter required' unless options.key? :page
if options[:count] and options[:total_entries]
raise ArgumentError, ':count and :total_entries are mutually exclusive'
end
page = options[:page] || 1
per_page = options[:per_page] || self.per_page
total = options[:total_entries]
[page, per_page, total]
end
private
# def find_every_with_paginate(options)
# @options_from_last_find = options
# find_every_without_paginate(options)
# end
end
end
end
| agpl-3.0 |
julien3/vertxbuspp | vertxbuspp/asio/include/asio/basic_serial_port.hpp | 24579 | //
// basic_serial_port.hpp
// ~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_BASIC_SERIAL_PORT_HPP
#define ASIO_BASIC_SERIAL_PORT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_SERIAL_PORT) \
|| defined(GENERATING_DOCUMENTATION)
#include <string>
#include "asio/basic_io_object.hpp"
#include "asio/detail/handler_type_requirements.hpp"
#include "asio/detail/throw_error.hpp"
#include "asio/error.hpp"
#include "asio/serial_port_base.hpp"
#include "asio/serial_port_service.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
/// Provides serial port functionality.
/**
* The basic_serial_port class template provides functionality that is common
* to all serial ports.
*
* @par Thread Safety
* @e Distinct @e objects: Safe.@n
* @e Shared @e objects: Unsafe.
*/
template <typename SerialPortService = serial_port_service>
class basic_serial_port
: public basic_io_object<SerialPortService>,
public serial_port_base
{
public:
/// (Deprecated: Use native_handle_type.) The native representation of a
/// serial port.
typedef typename SerialPortService::native_handle_type native_type;
/// The native representation of a serial port.
typedef typename SerialPortService::native_handle_type native_handle_type;
/// A basic_serial_port is always the lowest layer.
typedef basic_serial_port<SerialPortService> lowest_layer_type;
/// Construct a basic_serial_port without opening it.
/**
* This constructor creates a serial port without opening it.
*
* @param io_service The io_service object that the serial port will use to
* dispatch handlers for any asynchronous operations performed on the port.
*/
explicit basic_serial_port(asio::io_service& io_service)
: basic_io_object<SerialPortService>(io_service)
{
}
/// Construct and open a basic_serial_port.
/**
* This constructor creates and opens a serial port for the specified device
* name.
*
* @param io_service The io_service object that the serial port will use to
* dispatch handlers for any asynchronous operations performed on the port.
*
* @param device The platform-specific device name for this serial
* port.
*/
explicit basic_serial_port(asio::io_service& io_service,
const char* device)
: basic_io_object<SerialPortService>(io_service)
{
asio::error_code ec;
this->get_service().open(this->get_implementation(), device, ec);
asio::detail::throw_error(ec, "open");
}
/// Construct and open a basic_serial_port.
/**
* This constructor creates and opens a serial port for the specified device
* name.
*
* @param io_service The io_service object that the serial port will use to
* dispatch handlers for any asynchronous operations performed on the port.
*
* @param device The platform-specific device name for this serial
* port.
*/
explicit basic_serial_port(asio::io_service& io_service,
const std::string& device)
: basic_io_object<SerialPortService>(io_service)
{
asio::error_code ec;
this->get_service().open(this->get_implementation(), device, ec);
asio::detail::throw_error(ec, "open");
}
/// Construct a basic_serial_port on an existing native serial port.
/**
* This constructor creates a serial port object to hold an existing native
* serial port.
*
* @param io_service The io_service object that the serial port will use to
* dispatch handlers for any asynchronous operations performed on the port.
*
* @param native_serial_port A native serial port.
*
* @throws asio::system_error Thrown on failure.
*/
basic_serial_port(asio::io_service& io_service,
const native_handle_type& native_serial_port)
: basic_io_object<SerialPortService>(io_service)
{
asio::error_code ec;
this->get_service().assign(this->get_implementation(),
native_serial_port, ec);
asio::detail::throw_error(ec, "assign");
}
#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move-construct a basic_serial_port from another.
/**
* This constructor moves a serial port from one object to another.
*
* @param other The other basic_serial_port object from which the move will
* occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_serial_port(io_service&) constructor.
*/
basic_serial_port(basic_serial_port&& other)
: basic_io_object<SerialPortService>(
ASIO_MOVE_CAST(basic_serial_port)(other))
{
}
/// Move-assign a basic_serial_port from another.
/**
* This assignment operator moves a serial port from one object to another.
*
* @param other The other basic_serial_port object from which the move will
* occur.
*
* @note Following the move, the moved-from object is in the same state as if
* constructed using the @c basic_serial_port(io_service&) constructor.
*/
basic_serial_port& operator=(basic_serial_port&& other)
{
basic_io_object<SerialPortService>::operator=(
ASIO_MOVE_CAST(basic_serial_port)(other));
return *this;
}
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Get a reference to the lowest layer.
/**
* This function returns a reference to the lowest layer in a stack of
* layers. Since a basic_serial_port cannot contain any further layers, it
* simply returns a reference to itself.
*
* @return A reference to the lowest layer in the stack of layers. Ownership
* is not transferred to the caller.
*/
lowest_layer_type& lowest_layer()
{
return *this;
}
/// Get a const reference to the lowest layer.
/**
* This function returns a const reference to the lowest layer in a stack of
* layers. Since a basic_serial_port cannot contain any further layers, it
* simply returns a reference to itself.
*
* @return A const reference to the lowest layer in the stack of layers.
* Ownership is not transferred to the caller.
*/
const lowest_layer_type& lowest_layer() const
{
return *this;
}
/// Open the serial port using the specified device name.
/**
* This function opens the serial port for the specified device name.
*
* @param device The platform-specific device name.
*
* @throws asio::system_error Thrown on failure.
*/
void open(const std::string& device)
{
asio::error_code ec;
this->get_service().open(this->get_implementation(), device, ec);
asio::detail::throw_error(ec, "open");
}
/// Open the serial port using the specified device name.
/**
* This function opens the serial port using the given platform-specific
* device name.
*
* @param device The platform-specific device name.
*
* @param ec Set the indicate what error occurred, if any.
*/
asio::error_code open(const std::string& device,
asio::error_code& ec)
{
return this->get_service().open(this->get_implementation(), device, ec);
}
/// Assign an existing native serial port to the serial port.
/*
* This function opens the serial port to hold an existing native serial port.
*
* @param native_serial_port A native serial port.
*
* @throws asio::system_error Thrown on failure.
*/
void assign(const native_handle_type& native_serial_port)
{
asio::error_code ec;
this->get_service().assign(this->get_implementation(),
native_serial_port, ec);
asio::detail::throw_error(ec, "assign");
}
/// Assign an existing native serial port to the serial port.
/*
* This function opens the serial port to hold an existing native serial port.
*
* @param native_serial_port A native serial port.
*
* @param ec Set to indicate what error occurred, if any.
*/
asio::error_code assign(const native_handle_type& native_serial_port,
asio::error_code& ec)
{
return this->get_service().assign(this->get_implementation(),
native_serial_port, ec);
}
/// Determine whether the serial port is open.
bool is_open() const
{
return this->get_service().is_open(this->get_implementation());
}
/// Close the serial port.
/**
* This function is used to close the serial port. Any asynchronous read or
* write operations will be cancelled immediately, and will complete with the
* asio::error::operation_aborted error.
*
* @throws asio::system_error Thrown on failure.
*/
void close()
{
asio::error_code ec;
this->get_service().close(this->get_implementation(), ec);
asio::detail::throw_error(ec, "close");
}
/// Close the serial port.
/**
* This function is used to close the serial port. Any asynchronous read or
* write operations will be cancelled immediately, and will complete with the
* asio::error::operation_aborted error.
*
* @param ec Set to indicate what error occurred, if any.
*/
asio::error_code close(asio::error_code& ec)
{
return this->get_service().close(this->get_implementation(), ec);
}
/// (Deprecated: Use native_handle().) Get the native serial port
/// representation.
/**
* This function may be used to obtain the underlying representation of the
* serial port. This is intended to allow access to native serial port
* functionality that is not otherwise provided.
*/
native_type native()
{
return this->get_service().native_handle(this->get_implementation());
}
/// Get the native serial port representation.
/**
* This function may be used to obtain the underlying representation of the
* serial port. This is intended to allow access to native serial port
* functionality that is not otherwise provided.
*/
native_handle_type native_handle()
{
return this->get_service().native_handle(this->get_implementation());
}
/// Cancel all asynchronous operations associated with the serial port.
/**
* This function causes all outstanding asynchronous read or write operations
* to finish immediately, and the handlers for cancelled operations will be
* passed the asio::error::operation_aborted error.
*
* @throws asio::system_error Thrown on failure.
*/
void cancel()
{
asio::error_code ec;
this->get_service().cancel(this->get_implementation(), ec);
asio::detail::throw_error(ec, "cancel");
}
/// Cancel all asynchronous operations associated with the serial port.
/**
* This function causes all outstanding asynchronous read or write operations
* to finish immediately, and the handlers for cancelled operations will be
* passed the asio::error::operation_aborted error.
*
* @param ec Set to indicate what error occurred, if any.
*/
asio::error_code cancel(asio::error_code& ec)
{
return this->get_service().cancel(this->get_implementation(), ec);
}
/// Send a break sequence to the serial port.
/**
* This function causes a break sequence of platform-specific duration to be
* sent out the serial port.
*
* @throws asio::system_error Thrown on failure.
*/
void send_break()
{
asio::error_code ec;
this->get_service().send_break(this->get_implementation(), ec);
asio::detail::throw_error(ec, "send_break");
}
/// Send a break sequence to the serial port.
/**
* This function causes a break sequence of platform-specific duration to be
* sent out the serial port.
*
* @param ec Set to indicate what error occurred, if any.
*/
asio::error_code send_break(asio::error_code& ec)
{
return this->get_service().send_break(this->get_implementation(), ec);
}
/// Set an option on the serial port.
/**
* This function is used to set an option on the serial port.
*
* @param option The option value to be set on the serial port.
*
* @throws asio::system_error Thrown on failure.
*
* @sa SettableSerialPortOption @n
* asio::serial_port_base::baud_rate @n
* asio::serial_port_base::flow_control @n
* asio::serial_port_base::parity @n
* asio::serial_port_base::stop_bits @n
* asio::serial_port_base::character_size
*/
template <typename SettableSerialPortOption>
void set_option(const SettableSerialPortOption& option)
{
asio::error_code ec;
this->get_service().set_option(this->get_implementation(), option, ec);
asio::detail::throw_error(ec, "set_option");
}
/// Set an option on the serial port.
/**
* This function is used to set an option on the serial port.
*
* @param option The option value to be set on the serial port.
*
* @param ec Set to indicate what error occurred, if any.
*
* @sa SettableSerialPortOption @n
* asio::serial_port_base::baud_rate @n
* asio::serial_port_base::flow_control @n
* asio::serial_port_base::parity @n
* asio::serial_port_base::stop_bits @n
* asio::serial_port_base::character_size
*/
template <typename SettableSerialPortOption>
asio::error_code set_option(const SettableSerialPortOption& option,
asio::error_code& ec)
{
return this->get_service().set_option(
this->get_implementation(), option, ec);
}
/// Get an option from the serial port.
/**
* This function is used to get the current value of an option on the serial
* port.
*
* @param option The option value to be obtained from the serial port.
*
* @throws asio::system_error Thrown on failure.
*
* @sa GettableSerialPortOption @n
* asio::serial_port_base::baud_rate @n
* asio::serial_port_base::flow_control @n
* asio::serial_port_base::parity @n
* asio::serial_port_base::stop_bits @n
* asio::serial_port_base::character_size
*/
template <typename GettableSerialPortOption>
void get_option(GettableSerialPortOption& option)
{
asio::error_code ec;
this->get_service().get_option(this->get_implementation(), option, ec);
asio::detail::throw_error(ec, "get_option");
}
/// Get an option from the serial port.
/**
* This function is used to get the current value of an option on the serial
* port.
*
* @param option The option value to be obtained from the serial port.
*
* @param ec Set to indicate what error occured, if any.
*
* @sa GettableSerialPortOption @n
* asio::serial_port_base::baud_rate @n
* asio::serial_port_base::flow_control @n
* asio::serial_port_base::parity @n
* asio::serial_port_base::stop_bits @n
* asio::serial_port_base::character_size
*/
template <typename GettableSerialPortOption>
asio::error_code get_option(GettableSerialPortOption& option,
asio::error_code& ec)
{
return this->get_service().get_option(
this->get_implementation(), option, ec);
}
/// Write some data to the serial port.
/**
* This function is used to write data to the serial port. The function call
* will block until one or more bytes of the data has been written
* successfully, or until an error occurs.
*
* @param buffers One or more data buffers to be written to the serial port.
*
* @returns The number of bytes written.
*
* @throws asio::system_error Thrown on failure. An error code of
* asio::error::eof indicates that the connection was closed by the
* peer.
*
* @note The write_some operation may not transmit all of the data to the
* peer. Consider using the @ref write function if you need to ensure that
* all data is written before the blocking operation completes.
*
* @par Example
* To write a single data buffer use the @ref buffer function as follows:
* @code
* serial_port.write_some(asio::buffer(data, size));
* @endcode
* See the @ref buffer documentation for information on writing multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers)
{
asio::error_code ec;
std::size_t s = this->get_service().write_some(
this->get_implementation(), buffers, ec);
asio::detail::throw_error(ec, "write_some");
return s;
}
/// Write some data to the serial port.
/**
* This function is used to write data to the serial port. The function call
* will block until one or more bytes of the data has been written
* successfully, or until an error occurs.
*
* @param buffers One or more data buffers to be written to the serial port.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes written. Returns 0 if an error occurred.
*
* @note The write_some operation may not transmit all of the data to the
* peer. Consider using the @ref write function if you need to ensure that
* all data is written before the blocking operation completes.
*/
template <typename ConstBufferSequence>
std::size_t write_some(const ConstBufferSequence& buffers,
asio::error_code& ec)
{
return this->get_service().write_some(
this->get_implementation(), buffers, ec);
}
/// Start an asynchronous write.
/**
* This function is used to asynchronously write data to the serial port.
* The function call always returns immediately.
*
* @param buffers One or more data buffers to be written to the serial port.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the write operation completes.
* Copies will be made of the handler as required. The function signature of
* the handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes written.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation
* of the handler will be performed in a manner equivalent to using
* asio::io_service::post().
*
* @note The write operation may not transmit all of the data to the peer.
* Consider using the @ref async_write function if you need to ensure that all
* data is written before the asynchronous operation completes.
*
* @par Example
* To write a single data buffer use the @ref buffer function as follows:
* @code
* serial_port.async_write_some(asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on writing multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename ConstBufferSequence, typename WriteHandler>
ASIO_INITFN_RESULT_TYPE(WriteHandler,
void (asio::error_code, std::size_t))
async_write_some(const ConstBufferSequence& buffers,
ASIO_MOVE_ARG(WriteHandler) handler)
{
// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a WriteHandler.
ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check;
return this->get_service().async_write_some(this->get_implementation(),
buffers, ASIO_MOVE_CAST(WriteHandler)(handler));
}
/// Read some data from the serial port.
/**
* This function is used to read data from the serial port. The function
* call will block until one or more bytes of data has been read successfully,
* or until an error occurs.
*
* @param buffers One or more buffers into which the data will be read.
*
* @returns The number of bytes read.
*
* @throws asio::system_error Thrown on failure. An error code of
* asio::error::eof indicates that the connection was closed by the
* peer.
*
* @note The read_some operation may not read all of the requested number of
* bytes. Consider using the @ref read function if you need to ensure that
* the requested amount of data is read before the blocking operation
* completes.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* serial_port.read_some(asio::buffer(data, size));
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers)
{
asio::error_code ec;
std::size_t s = this->get_service().read_some(
this->get_implementation(), buffers, ec);
asio::detail::throw_error(ec, "read_some");
return s;
}
/// Read some data from the serial port.
/**
* This function is used to read data from the serial port. The function
* call will block until one or more bytes of data has been read successfully,
* or until an error occurs.
*
* @param buffers One or more buffers into which the data will be read.
*
* @param ec Set to indicate what error occurred, if any.
*
* @returns The number of bytes read. Returns 0 if an error occurred.
*
* @note The read_some operation may not read all of the requested number of
* bytes. Consider using the @ref read function if you need to ensure that
* the requested amount of data is read before the blocking operation
* completes.
*/
template <typename MutableBufferSequence>
std::size_t read_some(const MutableBufferSequence& buffers,
asio::error_code& ec)
{
return this->get_service().read_some(
this->get_implementation(), buffers, ec);
}
/// Start an asynchronous read.
/**
* This function is used to asynchronously read data from the serial port.
* The function call always returns immediately.
*
* @param buffers One or more buffers into which the data will be read.
* Although the buffers object may be copied as necessary, ownership of the
* underlying memory blocks is retained by the caller, which must guarantee
* that they remain valid until the handler is called.
*
* @param handler The handler to be called when the read operation completes.
* Copies will be made of the handler as required. The function signature of
* the handler must be:
* @code void handler(
* const asio::error_code& error, // Result of operation.
* std::size_t bytes_transferred // Number of bytes read.
* ); @endcode
* Regardless of whether the asynchronous operation completes immediately or
* not, the handler will not be invoked from within this function. Invocation
* of the handler will be performed in a manner equivalent to using
* asio::io_service::post().
*
* @note The read operation may not read all of the requested number of bytes.
* Consider using the @ref async_read function if you need to ensure that the
* requested amount of data is read before the asynchronous operation
* completes.
*
* @par Example
* To read into a single data buffer use the @ref buffer function as follows:
* @code
* serial_port.async_read_some(asio::buffer(data, size), handler);
* @endcode
* See the @ref buffer documentation for information on reading into multiple
* buffers in one go, and how to use it with arrays, boost::array or
* std::vector.
*/
template <typename MutableBufferSequence, typename ReadHandler>
ASIO_INITFN_RESULT_TYPE(ReadHandler,
void (asio::error_code, std::size_t))
async_read_some(const MutableBufferSequence& buffers,
ASIO_MOVE_ARG(ReadHandler) handler)
{
// If you get an error on the following line it means that your handler does
// not meet the documented type requirements for a ReadHandler.
ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check;
return this->get_service().async_read_some(this->get_implementation(),
buffers, ASIO_MOVE_CAST(ReadHandler)(handler));
}
};
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_SERIAL_PORT)
// || defined(GENERATING_DOCUMENTATION)
#endif // ASIO_BASIC_SERIAL_PORT_HPP
| apache-2.0 |
jmandawg/camel | components/camel-test-spring/src/main/java/org/apache/camel/test/spring/CamelSpringDelegatingTestContextLoader.java | 5252 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.spring;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.spring.SpringCamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.support.DelegatingSmartContextLoader;
/**
* CamelSpringDelegatingTestContextLoader which fixes issues in Camel's JavaConfigContextLoader. (adds support for Camel's test annotations)
* <br>
* <em>This loader can handle either classes or locations for configuring the context.</em>
* <br>
* NOTE: This TestContextLoader doesn't support the annotation of ExcludeRoutes now.
*/
public class CamelSpringDelegatingTestContextLoader extends DelegatingSmartContextLoader {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
Class<?> testClass = getTestClass();
if (logger.isDebugEnabled()) {
logger.debug("Loading ApplicationContext for merged context configuration [{}].", mergedConfig);
}
// Pre CamelContext(s) instantiation setup
CamelAnnotationsHandler.handleDisableJmx(null, testClass);
try {
SpringCamelContext.setNoStart(true);
System.setProperty("skipStartingCamelContext", "true");
ConfigurableApplicationContext context = (ConfigurableApplicationContext) super.loadContext(mergedConfig);
SpringCamelContext.setNoStart(false);
System.clearProperty("skipStartingCamelContext");
return loadContext(context, testClass);
} finally {
cleanup(testClass);
}
}
/**
* Performs the bulk of the Spring application context loading/customization.
*
* @param context the partially configured context. The context should have the bean definitions loaded, but nothing else.
* @param testClass the test class being executed
* @return the initialized (refreshed) Spring application context
*
* @throws Exception if there is an error during initialization/customization
*/
public ApplicationContext loadContext(ConfigurableApplicationContext context, Class<?> testClass)
throws Exception {
AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) context);
// Post CamelContext(s) instantiation but pre CamelContext(s) start setup
CamelAnnotationsHandler.handleProvidesBreakpoint(context, testClass);
CamelAnnotationsHandler.handleShutdownTimeout(context, testClass);
CamelAnnotationsHandler.handleMockEndpoints(context, testClass);
CamelAnnotationsHandler.handleMockEndpointsAndSkip(context, testClass);
CamelAnnotationsHandler.handleUseOverridePropertiesWithPropertiesComponent(context, testClass);
// CamelContext(s) startup
CamelAnnotationsHandler.handleCamelContextStartup(context, testClass);
return context;
}
/**
* Cleanup/restore global state to defaults / pre-test values after the test setup
* is complete.
*
* @param testClass the test class being executed
*/
protected void cleanup(Class<?> testClass) {
SpringCamelContext.setNoStart(false);
if (testClass.isAnnotationPresent(DisableJmx.class)) {
if (CamelSpringTestHelper.getOriginalJmxDisabled() == null) {
System.clearProperty(JmxSystemPropertyKeys.DISABLED);
} else {
System.setProperty(JmxSystemPropertyKeys.DISABLED,
CamelSpringTestHelper.getOriginalJmxDisabled());
}
}
}
/**
* Returns the class under test in order to enable inspection of annotations while the
* Spring context is being created.
*
* @return the test class that is being executed
* @see CamelSpringTestHelper
*/
protected Class<?> getTestClass() {
return CamelSpringTestHelper.getTestClass();
}
} | apache-2.0 |
stardog-union/stardog-graviton | vendor/github.com/mitchellh/packer/builder/azure/arm/openssh_key_pair_test.go | 980 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See the LICENSE file in builder/azure for license information.
package arm
import (
"golang.org/x/crypto/ssh"
"testing"
)
func TestFart(t *testing.T) {
}
func TestAuthorizedKeyShouldParse(t *testing.T) {
testSubject, err := NewOpenSshKeyPairWithSize(512)
if err != nil {
t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err)
}
authorizedKey := testSubject.AuthorizedKey()
_, _, _, _, err = ssh.ParseAuthorizedKey([]byte(authorizedKey))
if err != nil {
t.Fatalf("Failed to parse the authorized key, err=%s", err)
}
}
func TestPrivateKeyShouldParse(t *testing.T) {
testSubject, err := NewOpenSshKeyPairWithSize(512)
if err != nil {
t.Fatalf("Failed to create a new OpenSSH key pair, err=%s.", err)
}
_, err = ssh.ParsePrivateKey([]byte(testSubject.PrivateKey()))
if err != nil {
t.Fatalf("Failed to parse the private key, err=%s\n", err)
}
}
| apache-2.0 |
mkumatag/origin | vendor/k8s.io/kubernetes/cluster/restore-from-backup.sh | 9389 | #!/usr/bin/env bash
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script performs disaster recovery of etcd from the backup data.
# Assumptions:
# - backup was done using etcdctl command:
# a) in case of etcd2
# $ etcdctl backup --data-dir=<dir>
# produced .snap and .wal files
# b) in case of etcd3
# $ etcdctl --endpoints=<address> snapshot save
# produced .db file
# - version.txt file is in the current directory (if it isn't it will be
# defaulted to "3.0.17/etcd3"). Based on this file, the script will
# decide to which version we are restoring (procedures are different
# for etcd2 and etcd3).
# - in case of etcd2 - *.snap and *.wal files are in current directory
# - in case of etcd3 - *.db file is in the current directory
# - the script is run as root
# - for event etcd, we only support clearing it - to do it, you need to
# set RESET_EVENT_ETCD=true env var.
set -o errexit
set -o nounset
set -o pipefail
# Version file contains information about current version in the format:
# <etcd binary version>/<etcd api mode> (e.g. "3.0.12/etcd3").
#
# If the file doesn't exist we assume "3.0.17/etcd3" configuration is
# the current one and create a file with such configuration.
# The restore procedure is chosen based on this information.
VERSION_FILE="version.txt"
# Make it possible to overwrite version file (or default version)
# with VERSION_CONTENTS env var.
if [ -n "${VERSION_CONTENTS:-}" ]; then
echo "${VERSION_CONTENTS}" > "${VERSION_FILE}"
fi
if [ ! -f "${VERSION_FILE}" ]; then
echo "3.0.17/etcd3" > "${VERSION_FILE}"
fi
VERSION_CONTENTS="$(cat ${VERSION_FILE})"
ETCD_VERSION="$(echo "$VERSION_CONTENTS" | cut -d '/' -f 1)"
ETCD_API="$(echo "$VERSION_CONTENTS" | cut -d '/' -f 2)"
# Name is used only in case of etcd3 mode, to appropriate set the metadata
# for the etcd data.
# NOTE: NAME HAS TO BE EQUAL TO WHAT WE USE IN --name flag when starting etcd.
NAME="${NAME:-etcd-$(hostname)}"
INITIAL_CLUSTER="${INITIAL_CLUSTER:-${NAME}=http://localhost:2380}"
INITIAL_ADVERTISE_PEER_URLS="${INITIAL_ADVERTISE_PEER_URLS:-http://localhost:2380}"
# Port on which etcd is exposed.
etcd_port=2379
event_etcd_port=4002
# Wait until both etcd instances are up
wait_for_etcd_up() {
port=$1
# TODO: As of 3.0.x etcd versions, all 2.* and 3.* versions return
# {"health": "true"} on /health endpoint in healthy case.
# However, we should come with a regex for it to avoid future break.
health_ok="{\"health\": \"true\"}"
for _ in $(seq 120); do
# TODO: Is it enough to look into /health endpoint?
health=$(curl --silent "http://127.0.0.1:${port}/health")
if [ "${health}" == "${health_ok}" ]; then
return 0
fi
sleep 1
done
return 1
}
# Wait until apiserver is up.
wait_for_cluster_healthy() {
for _ in $(seq 120); do
cs_status=$(kubectl get componentstatuses -o template --template='{{range .items}}{{with index .conditions 0}}{{.type}}:{{.status}}{{end}}{{"\n"}}{{end}}') || true
componentstatuses=$(echo "${cs_status}" | grep -c 'Healthy:') || true
healthy=$(echo "${cs_status}" | grep -c 'Healthy:True') || true
if [ "${componentstatuses}" -eq "${healthy}" ]; then
return 0
fi
sleep 1
done
return 1
}
# Wait until etcd and apiserver pods are down.
wait_for_etcd_and_apiserver_down() {
for _ in $(seq 120); do
etcd=$(docker ps | grep -c etcd-server)
apiserver=$(docker ps | grep -c apiserver)
# TODO: Theoretically it is possible, that apiserver and or etcd
# are currently down, but Kubelet is now restarting them and they
# will reappear again. We should avoid it.
if [ "${etcd}" -eq "0" ] && [ "${apiserver}" -eq "0" ]; then
return 0
fi
sleep 1
done
return 1
}
# Move the manifest files to stop etcd and kube-apiserver
# while we swap the data out from under them.
MANIFEST_DIR="/etc/kubernetes/manifests"
MANIFEST_BACKUP_DIR="/etc/kubernetes/manifests-backups"
mkdir -p "${MANIFEST_BACKUP_DIR}"
echo "Moving etcd(s) & apiserver manifest files to ${MANIFEST_BACKUP_DIR}"
# If those files were already moved (e.g. during previous
# try of backup) don't fail on it.
mv "${MANIFEST_DIR}/kube-apiserver.manifest" "${MANIFEST_BACKUP_DIR}" || true
mv "${MANIFEST_DIR}/etcd.manifest" "${MANIFEST_BACKUP_DIR}" || true
mv "${MANIFEST_DIR}/etcd-events.manifest" "${MANIFEST_BACKUP_DIR}" || true
# Wait for the pods to be stopped
echo "Waiting for etcd and kube-apiserver to be down"
if ! wait_for_etcd_and_apiserver_down; then
# Couldn't kill etcd and apiserver.
echo "Downing etcd and apiserver failed"
exit 1
fi
read -rsp $'Press enter when all etcd instances are down...\n'
# Create the sort of directory structure that etcd expects.
# If this directory already exists, remove it.
BACKUP_DIR="/var/tmp/backup"
rm -rf "${BACKUP_DIR}"
if [ "${ETCD_API}" == "etcd2" ]; then
echo "Preparing etcd backup data for restore"
# In v2 mode, we simply copy both snap and wal files to a newly created
# directory. After that, we start etcd with --force-new-cluster option
# that (according to the etcd documentation) is required to recover from
# a backup.
echo "Copying data to ${BACKUP_DIR} and restoring there"
mkdir -p "${BACKUP_DIR}/member/snap"
mkdir -p "${BACKUP_DIR}/member/wal"
# If the cluster is relatively new, there can be no .snap file.
mv ./*.snap "${BACKUP_DIR}/member/snap/" || true
mv ./*.wal "${BACKUP_DIR}/member/wal/"
# TODO(jsz): This won't work with HA setups (e.g. do we need to set --name flag)?
echo "Starting etcd ${ETCD_VERSION} to restore data"
if ! image=$(docker run -d -v ${BACKUP_DIR}:/var/etcd/data \
--net=host -p ${etcd_port}:${etcd_port} \
"k8s.gcr.io/etcd:${ETCD_VERSION}" /bin/sh -c \
"/usr/local/bin/etcd --data-dir /var/etcd/data --force-new-cluster"); then
echo "Docker container didn't started correctly"
exit 1
fi
echo "Container ${image} created, waiting for etcd to report as healthy"
if ! wait_for_etcd_up "${etcd_port}"; then
echo "Etcd didn't come back correctly"
exit 1
fi
# Kill that etcd instance.
echo "Etcd healthy - killing ${image} container"
docker kill "${image}"
elif [ "${ETCD_API}" == "etcd3" ]; then
echo "Preparing etcd snapshot for restore"
mkdir -p "${BACKUP_DIR}"
echo "Copying data to ${BACKUP_DIR} and restoring there"
number_files=$(find . -maxdepth 1 -type f -name "*.db" | wc -l)
if [ "${number_files}" -ne "1" ]; then
echo "Incorrect number of *.db files - expected 1"
exit 1
fi
mv ./*.db "${BACKUP_DIR}/"
snapshot="$(ls ${BACKUP_DIR})"
# Run etcdctl snapshot restore command and wait until it is finished.
# setting with --name in the etcd manifest file and then it seems to work.
if ! docker run -v ${BACKUP_DIR}:/var/tmp/backup --env ETCDCTL_API=3 \
"k8s.gcr.io/etcd:${ETCD_VERSION}" /bin/sh -c \
"/usr/local/bin/etcdctl snapshot restore ${BACKUP_DIR}/${snapshot} --name ${NAME} --initial-cluster ${INITIAL_CLUSTER} --initial-advertise-peer-urls ${INITIAL_ADVERTISE_PEER_URLS}; mv /${NAME}.etcd/member /var/tmp/backup/"; then
echo "Docker container didn't started correctly"
exit 1
fi
rm -f "${BACKUP_DIR}/${snapshot}"
fi
# Also copy version.txt file.
cp "${VERSION_FILE}" "${BACKUP_DIR}"
export MNT_DISK="/mnt/disks/master-pd"
# Save the corrupted data (clean directory if it is already non-empty).
rm -rf "${MNT_DISK}/var/etcd-corrupted"
mkdir -p "${MNT_DISK}/var/etcd-corrupted"
echo "Saving corrupted data to ${MNT_DISK}/var/etcd-corrupted"
mv /var/etcd/data "${MNT_DISK}/var/etcd-corrupted"
# Replace the corrupted data dir with the restored data.
echo "Copying restored data to /var/etcd/data"
mv "${BACKUP_DIR}" /var/etcd/data
if [ "${RESET_EVENT_ETCD:-}" == "true" ]; then
echo "Removing event-etcd corrupted data"
EVENTS_CORRUPTED_DIR="${MNT_DISK}/var/etcd-events-corrupted"
# Save the corrupted data (clean directory if it is already non-empty).
rm -rf "${EVENTS_CORRUPTED_DIR}"
mkdir -p "${EVENTS_CORRUPTED_DIR}"
mv /var/etcd/data-events "${EVENTS_CORRUPTED_DIR}"
fi
# Start etcd and kube-apiserver again.
echo "Restarting etcd and apiserver from restored snapshot"
mv "${MANIFEST_BACKUP_DIR}"/* "${MANIFEST_DIR}/"
rm -rf "${MANIFEST_BACKUP_DIR}"
# Verify that etcd is back.
echo "Waiting for etcd to come back"
if ! wait_for_etcd_up "${etcd_port}"; then
echo "Etcd didn't come back correctly"
exit 1
fi
# Verify that event etcd is back.
echo "Waiting for event etcd to come back"
if ! wait_for_etcd_up "${event_etcd_port}"; then
echo "Event etcd didn't come back correctly"
exit 1
fi
# Verify that kube-apiserver is back and cluster is healthy.
echo "Waiting for apiserver to come back"
if ! wait_for_cluster_healthy; then
echo "Apiserver didn't come back correctly"
exit 1
fi
echo "Cluster successfully restored!"
| apache-2.0 |
shahata/angular | modules/angular2/src/core/render/dom/compiler/property_binding_parser.ts | 4415 | import {isPresent, RegExpWrapper, StringWrapper} from 'angular2/src/core/facade/lang';
import {MapWrapper} from 'angular2/src/core/facade/collection';
import {Parser} from 'angular2/src/core/change_detection/change_detection';
import {CompileStep} from './compile_step';
import {CompileElement} from './compile_element';
import {CompileControl} from './compile_control';
import {dashCaseToCamelCase} from '../util';
// Group 1 = "bind-"
// Group 2 = "var-" or "#"
// Group 3 = "on-"
// Group 4 = "bindon-"
// Group 5 = the identifier after "bind-", "var-/#", or "on-"
// Group 6 = identifier inside [()]
// Group 7 = identifier inside []
// Group 8 = identifier inside ()
var BIND_NAME_REGEXP =
/^(?:(?:(?:(bind-)|(var-|#)|(on-)|(bindon-))(.+))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/g;
/**
* Parses the property bindings on a single element.
*/
export class PropertyBindingParser implements CompileStep {
constructor(private _parser: Parser) {}
processStyle(style: string): string { return style; }
processElement(parent: CompileElement, current: CompileElement, control: CompileControl) {
var attrs = current.attrs();
var newAttrs = new Map();
MapWrapper.forEach(attrs, (attrValue, attrName) => {
attrName = this._normalizeAttributeName(attrName);
var bindParts = RegExpWrapper.firstMatch(BIND_NAME_REGEXP, attrName);
if (isPresent(bindParts)) {
if (isPresent(bindParts[1])) { // match: bind-prop
this._bindProperty(bindParts[5], attrValue, current, newAttrs);
} else if (isPresent(
bindParts[2])) { // match: var-name / var-name="iden" / #name / #name="iden"
var identifier = bindParts[5];
var value = attrValue == '' ? '\$implicit' : attrValue;
this._bindVariable(identifier, value, current, newAttrs);
} else if (isPresent(bindParts[3])) { // match: on-event
this._bindEvent(bindParts[5], attrValue, current, newAttrs);
} else if (isPresent(bindParts[4])) { // match: bindon-prop
this._bindProperty(bindParts[5], attrValue, current, newAttrs);
this._bindAssignmentEvent(bindParts[5], attrValue, current, newAttrs);
} else if (isPresent(bindParts[6])) { // match: [(expr)]
this._bindProperty(bindParts[6], attrValue, current, newAttrs);
this._bindAssignmentEvent(bindParts[6], attrValue, current, newAttrs);
} else if (isPresent(bindParts[7])) { // match: [expr]
this._bindProperty(bindParts[7], attrValue, current, newAttrs);
} else if (isPresent(bindParts[8])) { // match: (event)
this._bindEvent(bindParts[8], attrValue, current, newAttrs);
}
} else {
var expr = this._parser.parseInterpolation(attrValue, current.elementDescription);
if (isPresent(expr)) {
this._bindPropertyAst(attrName, expr, current, newAttrs);
}
}
});
MapWrapper.forEach(newAttrs, (attrValue, attrName) => { attrs.set(attrName, attrValue); });
}
_normalizeAttributeName(attrName: string): string {
return StringWrapper.startsWith(attrName, 'data-') ? StringWrapper.substring(attrName, 5) :
attrName;
}
_bindVariable(identifier, value, current: CompileElement, newAttrs: Map<any, any>) {
current.bindElement().bindVariable(dashCaseToCamelCase(identifier), value);
newAttrs.set(identifier, value);
}
_bindProperty(name, expression, current: CompileElement, newAttrs) {
this._bindPropertyAst(name, this._parser.parseBinding(expression, current.elementDescription),
current, newAttrs);
}
_bindPropertyAst(name, ast, current: CompileElement, newAttrs: Map<any, any>) {
var binder = current.bindElement();
binder.bindProperty(dashCaseToCamelCase(name), ast);
newAttrs.set(name, ast.source);
}
_bindAssignmentEvent(name, expression, current: CompileElement, newAttrs) {
this._bindEvent(name, `${expression}=$event`, current, newAttrs);
}
_bindEvent(name, expression, current: CompileElement, newAttrs) {
current.bindElement().bindEvent(
dashCaseToCamelCase(name),
this._parser.parseAction(expression, current.elementDescription));
// Don't detect directives for event names for now,
// so don't add the event name to the CompileElement.attrs
}
}
| apache-2.0 |
smmribeiro/intellij-community | java/java-tests/testData/codeInsight/completion/normal/MethodCallAfterFinally.java | 87 | public class Test {
void fooBarGoo() {
try {}
finally {}
fbg<caret>
}
} | apache-2.0 |
js0701/chromium-crosswalk | third_party/WebKit/LayoutTests/compositing/reflections/nested-reflection-transformed.html | 959 | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.outer {
width: 120px;
height: 230px;
margin: 20px;
border: 1px solid black;
-webkit-box-reflect: right 10px;
}
.inner {
margin: 10px;
width: 100px;
height: 100px;
background-color: green;
text-align: center;
font-size: 50pt;
-webkit-box-reflect: below 10px;
}
.composited {
transform: translateZ(0);
}
</style>
<script type="text/javascript" charset="utf-8">
function doTest()
{
document.getElementById('inner').style.webkitTransform = 'rotate(10deg)';
}
window.addEventListener('load', doTest, false);
</script>
</head>
<body>
<p>Test transform change on reflected elements. Left and right side should be symmetrical.</p>
<div class="outer composited">
<div id="inner" class="inner composited">
1
</div>
</div>
</body>
</html>
| bsd-3-clause |
phstc/sshp | vendor/ruby/1.9.1/gems/pry-0.9.12.2/spec/fixtures/candidate_helper2.rb | 70 | # rank 1
class CandidateTest
def test4
end
def test5
end
end
| mit |
sigma-random/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/net/mac80211/wme.c | 3394 | /*
* Copyright 2004, Instant802 Networks, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/types.h>
#include <net/ip.h>
#include <net/pkt_sched.h>
#include <net/mac80211.h>
#include "ieee80211_i.h"
#include "wme.h"
/* Default mapping in classifier to work with default
* queue setup.
*/
const int ieee802_1d_to_ac[8] = { 2, 3, 3, 2, 1, 1, 0, 0 };
static int wme_downgrade_ac(struct sk_buff *skb)
{
switch (skb->priority) {
case 6:
case 7:
skb->priority = 5; /* VO -> VI */
return 0;
case 4:
case 5:
skb->priority = 3; /* VI -> BE */
return 0;
case 0:
case 3:
skb->priority = 2; /* BE -> BK */
return 0;
default:
return -1;
}
}
/* Indicate which queue to use. */
u16 ieee80211_select_queue(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb)
{
struct ieee80211_local *local = sdata->local;
struct sta_info *sta = NULL;
u32 sta_flags = 0;
const u8 *ra = NULL;
bool qos = false;
if (local->hw.queues < 4 || skb->len < 6) {
skb->priority = 0; /* required for correct WPA/11i MIC */
return min_t(u16, local->hw.queues - 1,
ieee802_1d_to_ac[skb->priority]);
}
rcu_read_lock();
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP_VLAN:
rcu_read_lock();
sta = rcu_dereference(sdata->u.vlan.sta);
if (sta)
sta_flags = get_sta_flags(sta);
rcu_read_unlock();
if (sta)
break;
case NL80211_IFTYPE_AP:
ra = skb->data;
break;
case NL80211_IFTYPE_WDS:
ra = sdata->u.wds.remote_addr;
break;
#ifdef CONFIG_MAC80211_MESH
case NL80211_IFTYPE_MESH_POINT:
break;
#endif
case NL80211_IFTYPE_STATION:
ra = sdata->u.mgd.bssid;
break;
case NL80211_IFTYPE_ADHOC:
ra = skb->data;
break;
default:
break;
}
if (!sta && ra && !is_multicast_ether_addr(ra)) {
sta = sta_info_get(sdata, ra);
if (sta)
sta_flags = get_sta_flags(sta);
}
if (sta_flags & WLAN_STA_WME)
qos = true;
rcu_read_unlock();
if (!qos) {
skb->priority = 0; /* required for correct WPA/11i MIC */
return ieee802_1d_to_ac[skb->priority];
}
/* use the data classifier to determine what 802.1d tag the
* data frame has */
skb->priority = cfg80211_classify8021d(skb);
return ieee80211_downgrade_queue(local, skb);
}
u16 ieee80211_downgrade_queue(struct ieee80211_local *local,
struct sk_buff *skb)
{
/* in case we are a client verify acm is not set for this ac */
while (unlikely(local->wmm_acm & BIT(skb->priority))) {
if (wme_downgrade_ac(skb)) {
break;
}
}
/* look up which queue to use for frames with this 1d tag */
return ieee802_1d_to_ac[skb->priority];
}
void ieee80211_set_qos_hdr(struct ieee80211_local *local, struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (void *)skb->data;
/* Fill in the QoS header if there is one. */
if (ieee80211_is_data_qos(hdr->frame_control)) {
u8 *p = ieee80211_get_qos_ctl(hdr);
u8 ack_policy = 0, tid;
tid = skb->priority & IEEE80211_QOS_CTL_TAG1D_MASK;
if (unlikely(local->wifi_wme_noack_test))
ack_policy |= QOS_CONTROL_ACK_POLICY_NOACK <<
QOS_CONTROL_ACK_POLICY_SHIFT;
/* qos header is 2 bytes, second reserved */
*p++ = ack_policy | tid;
*p = 0;
}
}
| gpl-2.0 |
wkritzinger/asuswrt-merlin | release/src-rt-7.x.main/src/linux/linux-2.6.36/drivers/media/common/tuners/tuner-xc2028.h | 1827 | /* tuner-xc2028
*
* Copyright (c) 2007-2008 Mauro Carvalho Chehab ([email protected])
* This code is placed under the terms of the GNU General Public License v2
*/
#ifndef __TUNER_XC2028_H__
#define __TUNER_XC2028_H__
#include "dvb_frontend.h"
#define XC2028_DEFAULT_FIRMWARE "xc3028-v27.fw"
#define XC3028L_DEFAULT_FIRMWARE "xc3028L-v36.fw"
/* Dmoduler IF (kHz) */
#define XC3028_FE_DEFAULT 0 /* Don't load SCODE */
#define XC3028_FE_LG60 6000
#define XC3028_FE_ATI638 6380
#define XC3028_FE_OREN538 5380
#define XC3028_FE_OREN36 3600
#define XC3028_FE_TOYOTA388 3880
#define XC3028_FE_TOYOTA794 7940
#define XC3028_FE_DIBCOM52 5200
#define XC3028_FE_ZARLINK456 4560
#define XC3028_FE_CHINA 5200
enum firmware_type {
XC2028_AUTO = 0, /* By default, auto-detects */
XC2028_D2633,
XC2028_D2620,
};
struct xc2028_ctrl {
char *fname;
int max_len;
int msleep;
unsigned int scode_table;
unsigned int mts :1;
unsigned int input1:1;
unsigned int vhfbw7:1;
unsigned int uhfbw8:1;
unsigned int disable_power_mgmt:1;
unsigned int read_not_reliable:1;
unsigned int demod;
enum firmware_type type:2;
};
struct xc2028_config {
struct i2c_adapter *i2c_adap;
u8 i2c_addr;
struct xc2028_ctrl *ctrl;
};
/* xc2028 commands for callback */
#define XC2028_TUNER_RESET 0
#define XC2028_RESET_CLK 1
#if defined(CONFIG_MEDIA_TUNER_XC2028) || (defined(CONFIG_MEDIA_TUNER_XC2028_MODULE) && \
defined(MODULE))
extern struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,
struct xc2028_config *cfg);
#else
static inline struct dvb_frontend *xc2028_attach(struct dvb_frontend *fe,
struct xc2028_config *cfg)
{
printk(KERN_INFO "%s: not probed - driver disabled by Kconfig\n",
__func__);
return NULL;
}
#endif
#endif /* __TUNER_XC2028_H__ */
| gpl-2.0 |
nazgee/igep-kernel | drivers/net/wireless/hostap/hostap_cs.c | 18243 | #define PRISM2_PCCARD
#include <linux/module.h>
#include <linux/init.h>
#include <linux/if.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/timer.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/workqueue.h>
#include <linux/wireless.h>
#include <net/iw_handler.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include <asm/io.h>
#include "hostap_wlan.h"
static char *dev_info = "hostap_cs";
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("Support for Intersil Prism2-based 802.11 wireless LAN "
"cards (PC Card).");
MODULE_SUPPORTED_DEVICE("Intersil Prism2-based WLAN cards (PC Card)");
MODULE_LICENSE("GPL");
static int ignore_cis_vcc;
module_param(ignore_cis_vcc, int, 0444);
MODULE_PARM_DESC(ignore_cis_vcc, "Ignore broken CIS VCC entry");
/* struct local_info::hw_priv */
struct hostap_cs_priv {
struct pcmcia_device *link;
int sandisk_connectplus;
};
#ifdef PRISM2_IO_DEBUG
static inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v);
outb(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u8 hfa384x_inb_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u8 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inb(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v);
outw(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u16 hfa384x_inw_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u16 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inw(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outsw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc);
outsw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline void hfa384x_insw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc);
insw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
#define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v))
#define HFA384X_INB(a) hfa384x_inb_debug(dev, (a))
#define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v))
#define HFA384X_INW(a) hfa384x_inw_debug(dev, (a))
#define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc))
#define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc))
#else /* PRISM2_IO_DEBUG */
#define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a))
#define HFA384X_INB(a) inb(dev->base_addr + (a))
#define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a))
#define HFA384X_INW(a) inw(dev->base_addr + (a))
#define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc)
#define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc)
#endif /* PRISM2_IO_DEBUG */
static int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf,
int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_INSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
*((char *) pos) = HFA384X_INB(d_off);
return 0;
}
static int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_OUTSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
HFA384X_OUTB(*((char *) pos), d_off);
return 0;
}
/* FIX: This might change at some point.. */
#include "hostap_hw.c"
static void prism2_detach(struct pcmcia_device *p_dev);
static void prism2_release(u_long arg);
static int prism2_config(struct pcmcia_device *link);
static int prism2_pccard_card_present(local_info_t *local)
{
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (hw_priv != NULL && hw_priv->link != NULL && pcmcia_dev_present(hw_priv->link))
return 1;
return 0;
}
/*
* SanDisk CompactFlash WLAN Flashcard - Product Manual v1.0
* Document No. 20-10-00058, January 2004
* http://www.sandisk.com/pdf/industrial/ProdManualCFWLANv1.0.pdf
*/
#define SANDISK_WLAN_ACTIVATION_OFF 0x40
#define SANDISK_HCR_OFF 0x42
static void sandisk_set_iobase(local_info_t *local)
{
int res;
struct hostap_cs_priv *hw_priv = local->hw_priv;
res = pcmcia_write_config_byte(hw_priv->link, 0x10,
hw_priv->link->resource[0]->start & 0x00ff);
if (res != 0) {
printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 0 -"
" res=%d\n", res);
}
udelay(10);
res = pcmcia_write_config_byte(hw_priv->link, 0x12,
(hw_priv->link->resource[0]->start >> 8) & 0x00ff);
if (res != 0) {
printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 1 -"
" res=%d\n", res);
}
}
static void sandisk_write_hcr(local_info_t *local, int hcr)
{
struct net_device *dev = local->dev;
int i;
HFA384X_OUTB(0x80, SANDISK_WLAN_ACTIVATION_OFF);
udelay(50);
for (i = 0; i < 10; i++) {
HFA384X_OUTB(hcr, SANDISK_HCR_OFF);
}
udelay(55);
HFA384X_OUTB(0x45, SANDISK_WLAN_ACTIVATION_OFF);
}
static int sandisk_enable_wireless(struct net_device *dev)
{
int res, ret = 0;
struct hostap_interface *iface = netdev_priv(dev);
local_info_t *local = iface->local;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (resource_size(hw_priv->link->resource[0]) < 0x42) {
/* Not enough ports to be SanDisk multi-function card */
ret = -ENODEV;
goto done;
}
if (hw_priv->link->manf_id != 0xd601 || hw_priv->link->card_id != 0x0101) {
/* No SanDisk manfid found */
ret = -ENODEV;
goto done;
}
if (hw_priv->link->socket->functions < 2) {
/* No multi-function links found */
ret = -ENODEV;
goto done;
}
printk(KERN_DEBUG "%s: Multi-function SanDisk ConnectPlus detected"
" - using vendor-specific initialization\n", dev->name);
hw_priv->sandisk_connectplus = 1;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n",
dev->name, res);
goto done;
}
mdelay(5);
/*
* Do not enable interrupts here to avoid some bogus events. Interrupts
* will be enabled during the first cor_sreset call.
*/
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
(COR_LEVEL_REQ | 0x8 | COR_ADDR_DECODE |
COR_FUNC_ENA));
if (res != 0) {
printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n",
dev->name, res);
goto done;
}
mdelay(5);
sandisk_set_iobase(local);
HFA384X_OUTB(0xc5, SANDISK_WLAN_ACTIVATION_OFF);
udelay(10);
HFA384X_OUTB(0x4b, SANDISK_WLAN_ACTIVATION_OFF);
udelay(10);
done:
return ret;
}
static void prism2_pccard_cor_sreset(local_info_t *local)
{
int res;
u8 val;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (!prism2_pccard_card_present(local))
return;
res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 1 (%d)\n",
res);
return;
}
printk(KERN_DEBUG "prism2_pccard_cor_sreset: original COR %02x\n",
val);
val |= COR_SOFT_RESET;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 2 (%d)\n",
res);
return;
}
mdelay(hw_priv->sandisk_connectplus ? 5 : 2);
val &= ~COR_SOFT_RESET;
if (hw_priv->sandisk_connectplus)
val |= COR_IREQ_ENA;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 3 (%d)\n",
res);
return;
}
mdelay(hw_priv->sandisk_connectplus ? 5 : 2);
if (hw_priv->sandisk_connectplus)
sandisk_set_iobase(local);
}
static void prism2_pccard_genesis_reset(local_info_t *local, int hcr)
{
int res;
u8 old_cor;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (!prism2_pccard_card_present(local))
return;
if (hw_priv->sandisk_connectplus) {
sandisk_write_hcr(local, hcr);
return;
}
res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &old_cor);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 1 "
"(%d)\n", res);
return;
}
printk(KERN_DEBUG "prism2_pccard_genesis_sreset: original COR %02x\n",
old_cor);
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
old_cor | COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 2 "
"(%d)\n", res);
return;
}
mdelay(10);
/* Setup Genesis mode */
res = pcmcia_write_config_byte(hw_priv->link, CISREG_CCSR, hcr);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 3 "
"(%d)\n", res);
return;
}
mdelay(10);
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
old_cor & ~COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 4 "
"(%d)\n", res);
return;
}
mdelay(10);
}
static struct prism2_helper_functions prism2_pccard_funcs =
{
.card_present = prism2_pccard_card_present,
.cor_sreset = prism2_pccard_cor_sreset,
.genesis_reset = prism2_pccard_genesis_reset,
.hw_type = HOSTAP_HW_PCCARD,
};
/* allocate local data and register with CardServices
* initialize dev_link structure, but do not configure the card yet */
static int hostap_cs_probe(struct pcmcia_device *p_dev)
{
int ret;
PDEBUG(DEBUG_HW, "%s: setting Vcc=33 (constant)\n", dev_info);
ret = prism2_config(p_dev);
if (ret) {
PDEBUG(DEBUG_EXTRA, "prism2_config() failed\n");
}
return ret;
}
static void prism2_detach(struct pcmcia_device *link)
{
PDEBUG(DEBUG_FLOW, "prism2_detach\n");
prism2_release((u_long)link);
/* release net devices */
if (link->priv) {
struct hostap_cs_priv *hw_priv;
struct net_device *dev;
struct hostap_interface *iface;
dev = link->priv;
iface = netdev_priv(dev);
hw_priv = iface->local->hw_priv;
prism2_free_local_data(dev);
kfree(hw_priv);
}
}
static int prism2_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
if (p_dev->config_index == 0)
return -EINVAL;
return pcmcia_request_io(p_dev);
}
static int prism2_config(struct pcmcia_device *link)
{
struct net_device *dev;
struct hostap_interface *iface;
local_info_t *local;
int ret = 1;
struct hostap_cs_priv *hw_priv;
unsigned long flags;
PDEBUG(DEBUG_FLOW, "prism2_config()\n");
hw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL);
if (hw_priv == NULL) {
ret = -ENOMEM;
goto failed;
}
/* Look for an appropriate configuration table entry in the CIS */
link->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_AUDIO |
CONF_AUTO_CHECK_VCC | CONF_AUTO_SET_IO | CONF_ENABLE_IRQ;
if (ignore_cis_vcc)
link->config_flags &= ~CONF_AUTO_CHECK_VCC;
ret = pcmcia_loop_config(link, prism2_config_check, NULL);
if (ret) {
if (!ignore_cis_vcc)
printk(KERN_ERR "GetNextTuple(): No matching "
"CIS configuration. Maybe you need the "
"ignore_cis_vcc=1 parameter.\n");
goto failed;
}
/* Need to allocate net_device before requesting IRQ handler */
dev = prism2_init_local_data(&prism2_pccard_funcs, 0,
&link->dev);
if (dev == NULL)
goto failed;
link->priv = dev;
iface = netdev_priv(dev);
local = iface->local;
local->hw_priv = hw_priv;
hw_priv->link = link;
/*
* Make sure the IRQ handler cannot proceed until at least
* dev->base_addr is initialized.
*/
spin_lock_irqsave(&local->irq_init_lock, flags);
ret = pcmcia_request_irq(link, prism2_interrupt);
if (ret)
goto failed_unlock;
ret = pcmcia_enable_device(link);
if (ret)
goto failed_unlock;
dev->irq = link->irq;
dev->base_addr = link->resource[0]->start;
spin_unlock_irqrestore(&local->irq_init_lock, flags);
local->shutdown = 0;
sandisk_enable_wireless(dev);
ret = prism2_hw_config(dev, 1);
if (!ret)
ret = hostap_hw_ready(dev);
return ret;
failed_unlock:
spin_unlock_irqrestore(&local->irq_init_lock, flags);
failed:
kfree(hw_priv);
prism2_release((u_long)link);
return ret;
}
static void prism2_release(u_long arg)
{
struct pcmcia_device *link = (struct pcmcia_device *)arg;
PDEBUG(DEBUG_FLOW, "prism2_release\n");
if (link->priv) {
struct net_device *dev = link->priv;
struct hostap_interface *iface;
iface = netdev_priv(dev);
prism2_hw_shutdown(dev, 0);
iface->local->shutdown = 1;
}
pcmcia_disable_device(link);
PDEBUG(DEBUG_FLOW, "release - done\n");
}
static int hostap_cs_suspend(struct pcmcia_device *link)
{
struct net_device *dev = (struct net_device *) link->priv;
int dev_open = 0;
struct hostap_interface *iface = NULL;
if (!dev)
return -ENODEV;
iface = netdev_priv(dev);
PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_SUSPEND\n", dev_info);
if (iface && iface->local)
dev_open = iface->local->num_dev_open > 0;
if (dev_open) {
netif_stop_queue(dev);
netif_device_detach(dev);
}
prism2_suspend(dev);
return 0;
}
static int hostap_cs_resume(struct pcmcia_device *link)
{
struct net_device *dev = (struct net_device *) link->priv;
int dev_open = 0;
struct hostap_interface *iface = NULL;
if (!dev)
return -ENODEV;
iface = netdev_priv(dev);
PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_RESUME\n", dev_info);
if (iface && iface->local)
dev_open = iface->local->num_dev_open > 0;
prism2_hw_shutdown(dev, 1);
prism2_hw_config(dev, dev_open ? 0 : 1);
if (dev_open) {
netif_device_attach(dev);
netif_start_queue(dev);
}
return 0;
}
static struct pcmcia_device_id hostap_cs_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7100),
PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7300),
PCMCIA_DEVICE_MANF_CARD(0x0101, 0x0777),
PCMCIA_DEVICE_MANF_CARD(0x0126, 0x8000),
PCMCIA_DEVICE_MANF_CARD(0x0138, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x01bf, 0x3301),
PCMCIA_DEVICE_MANF_CARD(0x0250, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x026f, 0x030b),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1612),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1613),
PCMCIA_DEVICE_MANF_CARD(0x028a, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x02aa, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x02d2, 0x0001),
PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x0001),
PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x7300),
/* PCMCIA_DEVICE_MANF_CARD(0xc00f, 0x0000), conflict with pcnet_cs */
PCMCIA_DEVICE_MANF_CARD(0xc250, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0005),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0010),
PCMCIA_DEVICE_MANF_CARD(0x0126, 0x0002),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0xd601, 0x0005, "ADLINK 345 CF",
0x2d858104),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "INTERSIL",
0x74c5e40d),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "Intersil",
0x4b801a17),
PCMCIA_MFC_DEVICE_PROD_ID12(0, "SanDisk", "ConnectPlus",
0x7a954bd9, 0x74be00c6),
PCMCIA_DEVICE_PROD_ID123(
"Addtron", "AWP-100 Wireless PCMCIA", "Version 01.02",
0xe6ec52ce, 0x08649af2, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"D", "Link DWL-650 11Mbps WLAN Card", "Version 01.02",
0x71b18589, 0xb6f1b0ab, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"Instant Wireless ", " Network PC CARD", "Version 01.02",
0x11d901af, 0x6e9bd926, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"SMC", "SMC2632W", "Version 01.02",
0xc4f8b18b, 0x474a1f2a, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID12("BUFFALO", "WLI-CF-S11G",
0x2decece3, 0x82067c18),
PCMCIA_DEVICE_PROD_ID12("Compaq", "WL200_11Mbps_Wireless_PCI_Card",
0x54f7c49c, 0x15a75e5b),
PCMCIA_DEVICE_PROD_ID12("INTERSIL", "HFA384x/IEEE",
0x74c5e40d, 0xdb472a18),
PCMCIA_DEVICE_PROD_ID12("Linksys", "Wireless CompactFlash Card",
0x0733cc81, 0x0c52f395),
PCMCIA_DEVICE_PROD_ID12(
"ZoomAir 11Mbps High", "Rate wireless Networking",
0x273fe3db, 0x32a1eaee),
PCMCIA_DEVICE_PROD_ID123(
"Pretec", "CompactWLAN Card 802.11b", "2.5",
0x1cadd3e5, 0xe697636c, 0x7a5bfcf1),
PCMCIA_DEVICE_PROD_ID123(
"U.S. Robotics", "IEEE 802.11b PC-CARD", "Version 01.02",
0xc7b8df9d, 0x1700d087, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"Allied Telesyn", "AT-WCL452 Wireless PCMCIA Radio",
"Ver. 1.00",
0x5cd01705, 0x4271660f, 0x9d08ee12),
PCMCIA_DEVICE_PROD_ID123(
"Wireless LAN" , "11Mbps PC Card", "Version 01.02",
0x4b8870ff, 0x70e946d1, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID3("HFA3863", 0x355cb092),
PCMCIA_DEVICE_PROD_ID3("ISL37100P", 0x630d52b2),
PCMCIA_DEVICE_PROD_ID3("ISL37101P-10", 0xdd97a26b),
PCMCIA_DEVICE_PROD_ID3("ISL37300P", 0xc9049a39),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, hostap_cs_ids);
static struct pcmcia_driver hostap_driver = {
.name = "hostap_cs",
.probe = hostap_cs_probe,
.remove = prism2_detach,
.owner = THIS_MODULE,
.id_table = hostap_cs_ids,
.suspend = hostap_cs_suspend,
.resume = hostap_cs_resume,
};
static int __init init_prism2_pccard(void)
{
return pcmcia_register_driver(&hostap_driver);
}
static void __exit exit_prism2_pccard(void)
{
pcmcia_unregister_driver(&hostap_driver);
}
module_init(init_prism2_pccard);
module_exit(exit_prism2_pccard);
| gpl-2.0 |
hassanibi/erpnext | erpnext/patches/v6_2/remove_newsletter_duplicates.py | 407 | import frappe
def execute():
duplicates = frappe.db.sql("""select email_group, email, count(name)
from `tabEmail Group Member`
group by email_group, email
having count(name) > 1""")
# delete all duplicates except 1
for email_group, email, count in duplicates:
frappe.db.sql("""delete from `tabEmail Group Member`
where email_group=%s and email=%s limit %s""", (email_group, email, count-1))
| gpl-3.0 |
rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/rxjs/_esm2015/operators/sequenceEqual.js | 4896 | import { Subscriber } from '../Subscriber';
import { tryCatch } from '../util/tryCatch';
import { errorObject } from '../util/errorObject';
/**
* Compares all values of two observables in sequence using an optional comparor function
* and returns an observable of a single boolean value representing whether or not the two sequences
* are equal.
*
* <span class="informal">Checks to see of all values emitted by both observables are equal, in order.</span>
*
* <img src="./img/sequenceEqual.png" width="100%">
*
* `sequenceEqual` subscribes to two observables and buffers incoming values from each observable. Whenever either
* observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom
* up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the
* observables completes, the operator will wait for the other observable to complete; If the other
* observable emits before completing, the returned observable will emit `false` and complete. If one observable never
* completes or emits after the other complets, the returned observable will never complete.
*
* @example <caption>figure out if the Konami code matches</caption>
* var code = Rx.Observable.from([
* "ArrowUp",
* "ArrowUp",
* "ArrowDown",
* "ArrowDown",
* "ArrowLeft",
* "ArrowRight",
* "ArrowLeft",
* "ArrowRight",
* "KeyB",
* "KeyA",
* "Enter" // no start key, clearly.
* ]);
*
* var keys = Rx.Observable.fromEvent(document, 'keyup')
* .map(e => e.code);
* var matches = keys.bufferCount(11, 1)
* .mergeMap(
* last11 =>
* Rx.Observable.from(last11)
* .sequenceEqual(code)
* );
* matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));
*
* @see {@link combineLatest}
* @see {@link zip}
* @see {@link withLatestFrom}
*
* @param {Observable} compareTo The observable sequence to compare the source sequence to.
* @param {function} [comparor] An optional function to compare each value pair
* @return {Observable} An Observable of a single boolean value representing whether or not
* the values emitted by both observables were equal in sequence.
* @method sequenceEqual
* @owner Observable
*/
export function sequenceEqual(compareTo, comparor) {
return (source) => source.lift(new SequenceEqualOperator(compareTo, comparor));
}
export class SequenceEqualOperator {
constructor(compareTo, comparor) {
this.compareTo = compareTo;
this.comparor = comparor;
}
call(subscriber, source) {
return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparor));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class SequenceEqualSubscriber extends Subscriber {
constructor(destination, compareTo, comparor) {
super(destination);
this.compareTo = compareTo;
this.comparor = comparor;
this._a = [];
this._b = [];
this._oneComplete = false;
this.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, this)));
}
_next(value) {
if (this._oneComplete && this._b.length === 0) {
this.emit(false);
}
else {
this._a.push(value);
this.checkValues();
}
}
_complete() {
if (this._oneComplete) {
this.emit(this._a.length === 0 && this._b.length === 0);
}
else {
this._oneComplete = true;
}
}
checkValues() {
const { _a, _b, comparor } = this;
while (_a.length > 0 && _b.length > 0) {
let a = _a.shift();
let b = _b.shift();
let areEqual = false;
if (comparor) {
areEqual = tryCatch(comparor)(a, b);
if (areEqual === errorObject) {
this.destination.error(errorObject.e);
}
}
else {
areEqual = a === b;
}
if (!areEqual) {
this.emit(false);
}
}
}
emit(value) {
const { destination } = this;
destination.next(value);
destination.complete();
}
nextB(value) {
if (this._oneComplete && this._a.length === 0) {
this.emit(false);
}
else {
this._b.push(value);
this.checkValues();
}
}
}
class SequenceEqualCompareToSubscriber extends Subscriber {
constructor(destination, parent) {
super(destination);
this.parent = parent;
}
_next(value) {
this.parent.nextB(value);
}
_error(err) {
this.parent.error(err);
}
_complete() {
this.parent._complete();
}
}
//# sourceMappingURL=sequenceEqual.js.map | apache-2.0 |
wjiangjay/origin | vendor/k8s.io/kubernetes/pkg/volume/aws_ebs/aws_ebs_block.go | 6460 | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package aws_ebs
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"github.com/golang/glog"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/kubernetes/pkg/cloudprovider/providers/aws"
"k8s.io/kubernetes/pkg/util/mount"
kstrings "k8s.io/kubernetes/pkg/util/strings"
"k8s.io/kubernetes/pkg/volume"
"k8s.io/kubernetes/pkg/volume/util"
"k8s.io/kubernetes/pkg/volume/util/volumepathhandler"
)
var _ volume.VolumePlugin = &awsElasticBlockStorePlugin{}
var _ volume.PersistentVolumePlugin = &awsElasticBlockStorePlugin{}
var _ volume.BlockVolumePlugin = &awsElasticBlockStorePlugin{}
var _ volume.DeletableVolumePlugin = &awsElasticBlockStorePlugin{}
var _ volume.ProvisionableVolumePlugin = &awsElasticBlockStorePlugin{}
func (plugin *awsElasticBlockStorePlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) {
pluginDir := plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName)
blkutil := volumepathhandler.NewBlockVolumePathHandler()
globalMapPathUUID, err := blkutil.FindGlobalMapPathUUIDFromPod(pluginDir, mapPath, podUID)
if err != nil {
return nil, err
}
glog.V(5).Infof("globalMapPathUUID: %s", globalMapPathUUID)
globalMapPath := filepath.Dir(globalMapPathUUID)
if len(globalMapPath) <= 1 {
return nil, fmt.Errorf("failed to get volume plugin information from globalMapPathUUID: %v", globalMapPathUUID)
}
return getVolumeSpecFromGlobalMapPath(globalMapPath)
}
func getVolumeSpecFromGlobalMapPath(globalMapPath string) (*volume.Spec, error) {
// Get volume spec information from globalMapPath
// globalMapPath example:
// plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumeID}
// plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX
vID := filepath.Base(globalMapPath)
if len(vID) <= 1 {
return nil, fmt.Errorf("failed to get volumeID from global path=%s", globalMapPath)
}
if !strings.Contains(vID, "vol-") {
return nil, fmt.Errorf("failed to get volumeID from global path=%s, invalid volumeID format = %s", globalMapPath, vID)
}
block := v1.PersistentVolumeBlock
awsVolume := &v1.PersistentVolume{
Spec: v1.PersistentVolumeSpec{
PersistentVolumeSource: v1.PersistentVolumeSource{
AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{
VolumeID: vID,
},
},
VolumeMode: &block,
},
}
return volume.NewSpecFromPersistentVolume(awsVolume, true), nil
}
// NewBlockVolumeMapper creates a new volume.BlockVolumeMapper from an API specification.
func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeMapper(spec *volume.Spec, pod *v1.Pod, _ volume.VolumeOptions) (volume.BlockVolumeMapper, error) {
// If this is called via GenerateUnmapDeviceFunc(), pod is nil.
// Pass empty string as dummy uid since uid isn't used in the case.
var uid types.UID
if pod != nil {
uid = pod.UID
}
return plugin.newBlockVolumeMapperInternal(spec, uid, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))
}
func (plugin *awsElasticBlockStorePlugin) newBlockVolumeMapperInternal(spec *volume.Spec, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeMapper, error) {
ebs, readOnly, err := getVolumeSource(spec)
if err != nil {
return nil, err
}
volumeID := aws.KubernetesVolumeID(ebs.VolumeID)
partition := ""
if ebs.Partition != 0 {
partition = strconv.Itoa(int(ebs.Partition))
}
return &awsElasticBlockStoreMapper{
awsElasticBlockStore: &awsElasticBlockStore{
podUID: podUID,
volName: spec.Name(),
volumeID: volumeID,
partition: partition,
manager: manager,
mounter: mounter,
plugin: plugin,
},
readOnly: readOnly}, nil
}
func (plugin *awsElasticBlockStorePlugin) NewBlockVolumeUnmapper(volName string, podUID types.UID) (volume.BlockVolumeUnmapper, error) {
return plugin.newUnmapperInternal(volName, podUID, &AWSDiskUtil{}, plugin.host.GetMounter(plugin.GetPluginName()))
}
func (plugin *awsElasticBlockStorePlugin) newUnmapperInternal(volName string, podUID types.UID, manager ebsManager, mounter mount.Interface) (volume.BlockVolumeUnmapper, error) {
return &awsElasticBlockStoreUnmapper{
awsElasticBlockStore: &awsElasticBlockStore{
podUID: podUID,
volName: volName,
manager: manager,
mounter: mounter,
plugin: plugin,
}}, nil
}
func (c *awsElasticBlockStoreUnmapper) TearDownDevice(mapPath, devicePath string) error {
return nil
}
type awsElasticBlockStoreUnmapper struct {
*awsElasticBlockStore
}
var _ volume.BlockVolumeUnmapper = &awsElasticBlockStoreUnmapper{}
type awsElasticBlockStoreMapper struct {
*awsElasticBlockStore
readOnly bool
}
var _ volume.BlockVolumeMapper = &awsElasticBlockStoreMapper{}
func (b *awsElasticBlockStoreMapper) SetUpDevice() (string, error) {
return "", nil
}
func (b *awsElasticBlockStoreMapper) MapDevice(devicePath, globalMapPath, volumeMapPath, volumeMapName string, podUID types.UID) error {
return util.MapBlockVolume(devicePath, globalMapPath, volumeMapPath, volumeMapName, podUID)
}
// GetGlobalMapPath returns global map path and error
// path: plugins/kubernetes.io/{PluginName}/volumeDevices/volumeID
// plugins/kubernetes.io/aws-ebs/volumeDevices/vol-XXXXXX
func (ebs *awsElasticBlockStore) GetGlobalMapPath(spec *volume.Spec) (string, error) {
volumeSource, _, err := getVolumeSource(spec)
if err != nil {
return "", err
}
return filepath.Join(ebs.plugin.host.GetVolumeDevicePluginDir(awsElasticBlockStorePluginName), string(volumeSource.VolumeID)), nil
}
// GetPodDeviceMapPath returns pod device map path and volume name
// path: pods/{podUid}/volumeDevices/kubernetes.io~aws
func (ebs *awsElasticBlockStore) GetPodDeviceMapPath() (string, string) {
name := awsElasticBlockStorePluginName
return ebs.plugin.host.GetPodVolumeDeviceDir(ebs.podUID, kstrings.EscapeQualifiedNameForDisk(name)), ebs.volName
}
| apache-2.0 |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/core/common_runtime/session_factory.cc | 4469 | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/session_factory.h"
#include <unordered_map>
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/config.pb_text.h"
#include "tensorflow/core/public/session_options.h"
namespace tensorflow {
namespace {
static mutex* get_session_factory_lock() {
static mutex session_factory_lock;
return &session_factory_lock;
}
typedef std::unordered_map<string, SessionFactory*> SessionFactories;
SessionFactories* session_factories() {
static SessionFactories* factories = new SessionFactories;
return factories;
}
} // namespace
void SessionFactory::Register(const string& runtime_type,
SessionFactory* factory) {
mutex_lock l(*get_session_factory_lock());
if (!session_factories()->insert({runtime_type, factory}).second) {
LOG(ERROR) << "Two session factories are being registered "
<< "under" << runtime_type;
}
}
namespace {
const string RegisteredFactoriesErrorMessageLocked() {
std::vector<string> factory_types;
for (const auto& session_factory : *session_factories()) {
factory_types.push_back(session_factory.first);
}
return strings::StrCat("Registered factories are {",
str_util::Join(factory_types, ", "), "}.");
}
string SessionOptionsToString(const SessionOptions& options) {
return strings::StrCat("target: \"", options.target, "\" config: ",
ProtoShortDebugString(options.config));
}
} // namespace
Status SessionFactory::GetFactory(const SessionOptions& options,
SessionFactory** out_factory) {
mutex_lock l(*get_session_factory_lock()); // could use reader lock
std::vector<std::pair<string, SessionFactory*>> candidate_factories;
for (const auto& session_factory : *session_factories()) {
if (session_factory.second->AcceptsOptions(options)) {
VLOG(2) << "SessionFactory type " << session_factory.first
<< " accepts target: " << options.target;
candidate_factories.push_back(session_factory);
} else {
VLOG(2) << "SessionFactory type " << session_factory.first
<< " does not accept target: " << options.target;
}
}
if (candidate_factories.size() == 1) {
*out_factory = candidate_factories[0].second;
return Status::OK();
} else if (candidate_factories.size() > 1) {
// NOTE(mrry): This implementation assumes that the domains (in
// terms of acceptable SessionOptions) of the registered
// SessionFactory implementations do not overlap. This is fine for
// now, but we may need an additional way of distinguishing
// different runtimes (such as an additional session option) if
// the number of sessions grows.
// TODO(mrry): Consider providing a system-default fallback option
// in this case.
std::vector<string> factory_types;
factory_types.reserve(candidate_factories.size());
for (const auto& candidate_factory : candidate_factories) {
factory_types.push_back(candidate_factory.first);
}
return errors::Internal(
"Multiple session factories registered for the given session "
"options: {",
SessionOptionsToString(options), "} Candidate factories are {",
str_util::Join(factory_types, ", "), "}. ",
RegisteredFactoriesErrorMessageLocked());
} else {
return errors::NotFound(
"No session factory registered for the given session options: {",
SessionOptionsToString(options), "} ",
RegisteredFactoriesErrorMessageLocked());
}
}
} // namespace tensorflow
| apache-2.0 |
Nepomuceno/azure-xplat-cli | test/hdinsight/unit-list-command.js | 2528 | //
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
var mocha = require('mocha');
var should = require('should');
var sinon = require('sinon');
var _ = require('underscore');
// Test includes
var testutil = require('../util/util');
// Lib includes
var util = testutil.libRequire('util/utils');
var GetCommand = require('./util-GetCommand.js');
describe('HDInsight list command (under unit test)', function() {
after(function (done) {
done();
});
// NOTE: To Do, we should actually create new accounts for our tests
// So that we can work on any existing subscription.
before (function (done) {
done();
});
it('should call startProgress with the correct statement', function(done) {
var command = new GetCommand();
command.hdinsight.listClustersCommand.should.not.equal(null);
command.hdinsight.listClustersCommand({}, _);
command.user.startProgress.firstCall.args[0].should.be.equal('Getting HDInsight servers');
done();
});
it('should call listClusters with the supplied subscriptionId (when none is supplied)', function(done) {
var command = new GetCommand();
command.hdinsight.listClustersCommand.should.not.equal(null);
command.hdinsight.listClustersCommand({}, _);
command.processor.listClusters.firstCall.should.not.equal(null);
(command.processor.listClusters.firstCall.args[0] === undefined).should.equal(true);
done();
});
it('should call listClusters with the supplied subscriptionId (when one is supplied)', function(done) {
var command = new GetCommand();
command.hdinsight.listClustersCommand.should.not.equal(null);
command.hdinsight.listClustersCommand({ subscription: 'test1' }, _);
command.processor.listClusters.firstCall.should.not.equal(null);
command.processor.listClusters.firstCall.args[0].should.not.equal(null);
command.processor.listClusters.firstCall.args[0].should.be.equal('test1');
done();
});
}); | apache-2.0 |
ggsamsa/sched_casio | drivers/net/qlcnic/qlcnic_hw.c | 33431 | /*
* Copyright (C) 2009 - QLogic Corporation.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* The full GNU General Public License is included in this distribution
* in the file called "COPYING".
*
*/
#include "qlcnic.h"
#include <linux/slab.h>
#include <net/ip.h>
#define MASK(n) ((1ULL<<(n))-1)
#define OCM_WIN_P3P(addr) (addr & 0xffc0000)
#define GET_MEM_OFFS_2M(addr) (addr & MASK(18))
#define CRB_BLK(off) ((off >> 20) & 0x3f)
#define CRB_SUBBLK(off) ((off >> 16) & 0xf)
#define CRB_WINDOW_2M (0x130060)
#define CRB_HI(off) ((crb_hub_agt[CRB_BLK(off)] << 20) | ((off) & 0xf0000))
#define CRB_INDIRECT_2M (0x1e0000UL)
#ifndef readq
static inline u64 readq(void __iomem *addr)
{
return readl(addr) | (((u64) readl(addr + 4)) << 32LL);
}
#endif
#ifndef writeq
static inline void writeq(u64 val, void __iomem *addr)
{
writel(((u32) (val)), (addr));
writel(((u32) (val >> 32)), (addr + 4));
}
#endif
#define ADDR_IN_RANGE(addr, low, high) \
(((addr) < (high)) && ((addr) >= (low)))
#define PCI_OFFSET_FIRST_RANGE(adapter, off) \
((adapter)->ahw.pci_base0 + (off))
static void __iomem *pci_base_offset(struct qlcnic_adapter *adapter,
unsigned long off)
{
if (ADDR_IN_RANGE(off, FIRST_PAGE_GROUP_START, FIRST_PAGE_GROUP_END))
return PCI_OFFSET_FIRST_RANGE(adapter, off);
return NULL;
}
static const struct crb_128M_2M_block_map
crb_128M_2M_map[64] __cacheline_aligned_in_smp = {
{{{0, 0, 0, 0} } }, /* 0: PCI */
{{{1, 0x0100000, 0x0102000, 0x120000}, /* 1: PCIE */
{1, 0x0110000, 0x0120000, 0x130000},
{1, 0x0120000, 0x0122000, 0x124000},
{1, 0x0130000, 0x0132000, 0x126000},
{1, 0x0140000, 0x0142000, 0x128000},
{1, 0x0150000, 0x0152000, 0x12a000},
{1, 0x0160000, 0x0170000, 0x110000},
{1, 0x0170000, 0x0172000, 0x12e000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x01e0000, 0x01e0800, 0x122000},
{0, 0x0000000, 0x0000000, 0x000000} } },
{{{1, 0x0200000, 0x0210000, 0x180000} } },/* 2: MN */
{{{0, 0, 0, 0} } }, /* 3: */
{{{1, 0x0400000, 0x0401000, 0x169000} } },/* 4: P2NR1 */
{{{1, 0x0500000, 0x0510000, 0x140000} } },/* 5: SRE */
{{{1, 0x0600000, 0x0610000, 0x1c0000} } },/* 6: NIU */
{{{1, 0x0700000, 0x0704000, 0x1b8000} } },/* 7: QM */
{{{1, 0x0800000, 0x0802000, 0x170000}, /* 8: SQM0 */
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x08f0000, 0x08f2000, 0x172000} } },
{{{1, 0x0900000, 0x0902000, 0x174000}, /* 9: SQM1*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x09f0000, 0x09f2000, 0x176000} } },
{{{0, 0x0a00000, 0x0a02000, 0x178000}, /* 10: SQM2*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x0af0000, 0x0af2000, 0x17a000} } },
{{{0, 0x0b00000, 0x0b02000, 0x17c000}, /* 11: SQM3*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x0bf0000, 0x0bf2000, 0x17e000} } },
{{{1, 0x0c00000, 0x0c04000, 0x1d4000} } },/* 12: I2Q */
{{{1, 0x0d00000, 0x0d04000, 0x1a4000} } },/* 13: TMR */
{{{1, 0x0e00000, 0x0e04000, 0x1a0000} } },/* 14: ROMUSB */
{{{1, 0x0f00000, 0x0f01000, 0x164000} } },/* 15: PEG4 */
{{{0, 0x1000000, 0x1004000, 0x1a8000} } },/* 16: XDMA */
{{{1, 0x1100000, 0x1101000, 0x160000} } },/* 17: PEG0 */
{{{1, 0x1200000, 0x1201000, 0x161000} } },/* 18: PEG1 */
{{{1, 0x1300000, 0x1301000, 0x162000} } },/* 19: PEG2 */
{{{1, 0x1400000, 0x1401000, 0x163000} } },/* 20: PEG3 */
{{{1, 0x1500000, 0x1501000, 0x165000} } },/* 21: P2ND */
{{{1, 0x1600000, 0x1601000, 0x166000} } },/* 22: P2NI */
{{{0, 0, 0, 0} } }, /* 23: */
{{{0, 0, 0, 0} } }, /* 24: */
{{{0, 0, 0, 0} } }, /* 25: */
{{{0, 0, 0, 0} } }, /* 26: */
{{{0, 0, 0, 0} } }, /* 27: */
{{{0, 0, 0, 0} } }, /* 28: */
{{{1, 0x1d00000, 0x1d10000, 0x190000} } },/* 29: MS */
{{{1, 0x1e00000, 0x1e01000, 0x16a000} } },/* 30: P2NR2 */
{{{1, 0x1f00000, 0x1f10000, 0x150000} } },/* 31: EPG */
{{{0} } }, /* 32: PCI */
{{{1, 0x2100000, 0x2102000, 0x120000}, /* 33: PCIE */
{1, 0x2110000, 0x2120000, 0x130000},
{1, 0x2120000, 0x2122000, 0x124000},
{1, 0x2130000, 0x2132000, 0x126000},
{1, 0x2140000, 0x2142000, 0x128000},
{1, 0x2150000, 0x2152000, 0x12a000},
{1, 0x2160000, 0x2170000, 0x110000},
{1, 0x2170000, 0x2172000, 0x12e000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000} } },
{{{1, 0x2200000, 0x2204000, 0x1b0000} } },/* 34: CAM */
{{{0} } }, /* 35: */
{{{0} } }, /* 36: */
{{{0} } }, /* 37: */
{{{0} } }, /* 38: */
{{{0} } }, /* 39: */
{{{1, 0x2800000, 0x2804000, 0x1a4000} } },/* 40: TMR */
{{{1, 0x2900000, 0x2901000, 0x16b000} } },/* 41: P2NR3 */
{{{1, 0x2a00000, 0x2a00400, 0x1ac400} } },/* 42: RPMX1 */
{{{1, 0x2b00000, 0x2b00400, 0x1ac800} } },/* 43: RPMX2 */
{{{1, 0x2c00000, 0x2c00400, 0x1acc00} } },/* 44: RPMX3 */
{{{1, 0x2d00000, 0x2d00400, 0x1ad000} } },/* 45: RPMX4 */
{{{1, 0x2e00000, 0x2e00400, 0x1ad400} } },/* 46: RPMX5 */
{{{1, 0x2f00000, 0x2f00400, 0x1ad800} } },/* 47: RPMX6 */
{{{1, 0x3000000, 0x3000400, 0x1adc00} } },/* 48: RPMX7 */
{{{0, 0x3100000, 0x3104000, 0x1a8000} } },/* 49: XDMA */
{{{1, 0x3200000, 0x3204000, 0x1d4000} } },/* 50: I2Q */
{{{1, 0x3300000, 0x3304000, 0x1a0000} } },/* 51: ROMUSB */
{{{0} } }, /* 52: */
{{{1, 0x3500000, 0x3500400, 0x1ac000} } },/* 53: RPMX0 */
{{{1, 0x3600000, 0x3600400, 0x1ae000} } },/* 54: RPMX8 */
{{{1, 0x3700000, 0x3700400, 0x1ae400} } },/* 55: RPMX9 */
{{{1, 0x3800000, 0x3804000, 0x1d0000} } },/* 56: OCM0 */
{{{1, 0x3900000, 0x3904000, 0x1b4000} } },/* 57: CRYPTO */
{{{1, 0x3a00000, 0x3a04000, 0x1d8000} } },/* 58: SMB */
{{{0} } }, /* 59: I2C0 */
{{{0} } }, /* 60: I2C1 */
{{{1, 0x3d00000, 0x3d04000, 0x1d8000} } },/* 61: LPC */
{{{1, 0x3e00000, 0x3e01000, 0x167000} } },/* 62: P2NC */
{{{1, 0x3f00000, 0x3f01000, 0x168000} } } /* 63: P2NR0 */
};
/*
* top 12 bits of crb internal address (hub, agent)
*/
static const unsigned crb_hub_agt[64] = {
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PS,
QLCNIC_HW_CRB_HUB_AGT_ADR_MN,
QLCNIC_HW_CRB_HUB_AGT_ADR_MS,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SRE,
QLCNIC_HW_CRB_HUB_AGT_ADR_NIU,
QLCNIC_HW_CRB_HUB_AGT_ADR_QMN,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN1,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN2,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN3,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,
QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,
QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN4,
QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN1,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN2,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN3,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGND,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGNI,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS1,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS2,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS3,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGSI,
QLCNIC_HW_CRB_HUB_AGT_ADR_SN,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_EG,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PS,
QLCNIC_HW_CRB_HUB_AGT_ADR_CAM,
0,
0,
0,
0,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX1,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX2,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX3,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX4,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX5,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX6,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX7,
QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,
QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX8,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX9,
QLCNIC_HW_CRB_HUB_AGT_ADR_OCM0,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SMB,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2C0,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2C1,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGNC,
0,
};
/* PCI Windowing for DDR regions. */
#define QLCNIC_PCIE_SEM_TIMEOUT 10000
int
qlcnic_pcie_sem_lock(struct qlcnic_adapter *adapter, int sem, u32 id_reg)
{
int done = 0, timeout = 0;
while (!done) {
done = QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_LOCK(sem)));
if (done == 1)
break;
if (++timeout >= QLCNIC_PCIE_SEM_TIMEOUT)
return -EIO;
msleep(1);
}
if (id_reg)
QLCWR32(adapter, id_reg, adapter->portnum);
return 0;
}
void
qlcnic_pcie_sem_unlock(struct qlcnic_adapter *adapter, int sem)
{
QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_UNLOCK(sem)));
}
static int
qlcnic_send_cmd_descs(struct qlcnic_adapter *adapter,
struct cmd_desc_type0 *cmd_desc_arr, int nr_desc)
{
u32 i, producer, consumer;
struct qlcnic_cmd_buffer *pbuf;
struct cmd_desc_type0 *cmd_desc;
struct qlcnic_host_tx_ring *tx_ring;
i = 0;
if (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC)
return -EIO;
tx_ring = adapter->tx_ring;
__netif_tx_lock_bh(tx_ring->txq);
producer = tx_ring->producer;
consumer = tx_ring->sw_consumer;
if (nr_desc >= qlcnic_tx_avail(tx_ring)) {
netif_tx_stop_queue(tx_ring->txq);
__netif_tx_unlock_bh(tx_ring->txq);
adapter->stats.xmit_off++;
return -EBUSY;
}
do {
cmd_desc = &cmd_desc_arr[i];
pbuf = &tx_ring->cmd_buf_arr[producer];
pbuf->skb = NULL;
pbuf->frag_count = 0;
memcpy(&tx_ring->desc_head[producer],
&cmd_desc_arr[i], sizeof(struct cmd_desc_type0));
producer = get_next_index(producer, tx_ring->num_desc);
i++;
} while (i != nr_desc);
tx_ring->producer = producer;
qlcnic_update_cmd_producer(adapter, tx_ring);
__netif_tx_unlock_bh(tx_ring->txq);
return 0;
}
static int
qlcnic_sre_macaddr_change(struct qlcnic_adapter *adapter, u8 *addr,
unsigned op)
{
struct qlcnic_nic_req req;
struct qlcnic_mac_req *mac_req;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_REQUEST << 23);
word = QLCNIC_MAC_EVENT | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
mac_req = (struct qlcnic_mac_req *)&req.words[0];
mac_req->op = op;
memcpy(mac_req->mac_addr, addr, 6);
return qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
}
static int qlcnic_nic_add_mac(struct qlcnic_adapter *adapter, u8 *addr)
{
struct list_head *head;
struct qlcnic_mac_list_s *cur;
/* look up if already exists */
list_for_each(head, &adapter->mac_list) {
cur = list_entry(head, struct qlcnic_mac_list_s, list);
if (memcmp(addr, cur->mac_addr, ETH_ALEN) == 0)
return 0;
}
cur = kzalloc(sizeof(struct qlcnic_mac_list_s), GFP_ATOMIC);
if (cur == NULL) {
dev_err(&adapter->netdev->dev,
"failed to add mac address filter\n");
return -ENOMEM;
}
memcpy(cur->mac_addr, addr, ETH_ALEN);
list_add_tail(&cur->list, &adapter->mac_list);
return qlcnic_sre_macaddr_change(adapter,
cur->mac_addr, QLCNIC_MAC_ADD);
}
void qlcnic_set_multi(struct net_device *netdev)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
struct dev_mc_list *mc_ptr;
u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
u32 mode = VPORT_MISS_MODE_DROP;
if (adapter->is_up != QLCNIC_ADAPTER_UP_MAGIC)
return;
qlcnic_nic_add_mac(adapter, adapter->mac_addr);
qlcnic_nic_add_mac(adapter, bcast_addr);
if (netdev->flags & IFF_PROMISC) {
mode = VPORT_MISS_MODE_ACCEPT_ALL;
goto send_fw_cmd;
}
if ((netdev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(netdev) > adapter->max_mc_count)) {
mode = VPORT_MISS_MODE_ACCEPT_MULTI;
goto send_fw_cmd;
}
if (!netdev_mc_empty(netdev)) {
netdev_for_each_mc_addr(mc_ptr, netdev) {
qlcnic_nic_add_mac(adapter, mc_ptr->dmi_addr);
}
}
send_fw_cmd:
qlcnic_nic_set_promisc(adapter, mode);
}
int qlcnic_nic_set_promisc(struct qlcnic_adapter *adapter, u32 mode)
{
struct qlcnic_nic_req req;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_PROXY_SET_VPORT_MISS_MODE |
((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(mode);
return qlcnic_send_cmd_descs(adapter,
(struct cmd_desc_type0 *)&req, 1);
}
void qlcnic_free_mac_list(struct qlcnic_adapter *adapter)
{
struct qlcnic_mac_list_s *cur;
struct list_head *head = &adapter->mac_list;
while (!list_empty(head)) {
cur = list_entry(head->next, struct qlcnic_mac_list_s, list);
qlcnic_sre_macaddr_change(adapter,
cur->mac_addr, QLCNIC_MAC_DEL);
list_del(&cur->list);
kfree(cur);
}
}
#define QLCNIC_CONFIG_INTR_COALESCE 3
/*
* Send the interrupt coalescing parameter set by ethtool to the card.
*/
int qlcnic_config_intr_coalesce(struct qlcnic_adapter *adapter)
{
struct qlcnic_nic_req req;
u64 word[6];
int rv, i;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word[0] = QLCNIC_CONFIG_INTR_COALESCE | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word[0]);
memcpy(&word[0], &adapter->coal, sizeof(adapter->coal));
for (i = 0; i < 6; i++)
req.words[i] = cpu_to_le64(word[i]);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send interrupt coalescing parameters\n");
return rv;
}
int qlcnic_config_hw_lro(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
if ((adapter->flags & QLCNIC_LRO_ENABLED) == enable)
return 0;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_HW_LRO | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send configure hw lro request\n");
adapter->flags ^= QLCNIC_LRO_ENABLED;
return rv;
}
int qlcnic_config_bridged_mode(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
if (!!(adapter->flags & QLCNIC_BRIDGE_ENABLED) == enable)
return 0;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_BRIDGING |
((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send configure bridge mode request\n");
adapter->flags ^= QLCNIC_BRIDGE_ENABLED;
return rv;
}
#define RSS_HASHTYPE_IP_TCP 0x3
int qlcnic_config_rss(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int i, rv;
const u64 key[] = { 0xbeac01fa6a42b73bULL, 0x8030f20c77cb2da3ULL,
0xae7b30b4d0ca2bcbULL, 0x43a38fb04167253dULL,
0x255b0ec26d5a56daULL };
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_RSS | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
/*
* RSS request:
* bits 3-0: hash_method
* 5-4: hash_type_ipv4
* 7-6: hash_type_ipv6
* 8: enable
* 9: use indirection table
* 47-10: reserved
* 63-48: indirection table mask
*/
word = ((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 4) |
((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 6) |
((u64)(enable & 0x1) << 8) |
((0x7ULL) << 48);
req.words[0] = cpu_to_le64(word);
for (i = 0; i < 5; i++)
req.words[i+1] = cpu_to_le64(key[i]);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev, "could not configure RSS\n");
return rv;
}
int qlcnic_config_ipaddr(struct qlcnic_adapter *adapter, u32 ip, int cmd)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_IPADDR | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(cmd);
req.words[1] = cpu_to_le64(ip);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not notify %s IP 0x%x reuqest\n",
(cmd == QLCNIC_IP_UP) ? "Add" : "Remove", ip);
return rv;
}
int qlcnic_linkevent_request(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_GET_LINKEVENT | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable | (enable << 8));
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not configure link notification\n");
return rv;
}
int qlcnic_send_lro_cleanup(struct qlcnic_adapter *adapter)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_LRO_REQUEST |
((u64)adapter->portnum << 16) |
((u64)QLCNIC_LRO_REQUEST_CLEANUP << 56) ;
req.req_hdr = cpu_to_le64(word);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not cleanup lro flows\n");
return rv;
}
/*
* qlcnic_change_mtu - Change the Maximum Transfer Unit
* @returns 0 on success, negative on failure
*/
int qlcnic_change_mtu(struct net_device *netdev, int mtu)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
int rc = 0;
if (mtu > P3_MAX_MTU) {
dev_err(&adapter->netdev->dev, "mtu > %d bytes unsupported\n",
P3_MAX_MTU);
return -EINVAL;
}
rc = qlcnic_fw_cmd_set_mtu(adapter, mtu);
if (!rc)
netdev->mtu = mtu;
return rc;
}
int qlcnic_get_mac_addr(struct qlcnic_adapter *adapter, u64 *mac)
{
u32 crbaddr, mac_hi, mac_lo;
int pci_func = adapter->ahw.pci_func;
crbaddr = CRB_MAC_BLOCK_START +
(4 * ((pci_func/2) * 3)) + (4 * (pci_func & 1));
mac_lo = QLCRD32(adapter, crbaddr);
mac_hi = QLCRD32(adapter, crbaddr+4);
if (pci_func & 1)
*mac = le64_to_cpu((mac_lo >> 16) | ((u64)mac_hi << 16));
else
*mac = le64_to_cpu((u64)mac_lo | ((u64)mac_hi << 32));
return 0;
}
/*
* Changes the CRB window to the specified window.
*/
/* Returns < 0 if off is not valid,
* 1 if window access is needed. 'off' is set to offset from
* CRB space in 128M pci map
* 0 if no window access is needed. 'off' is set to 2M addr
* In: 'off' is offset from base in 128M pci map
*/
static int
qlcnic_pci_get_crb_addr_2M(struct qlcnic_adapter *adapter,
ulong off, void __iomem **addr)
{
const struct crb_128M_2M_sub_block_map *m;
if ((off >= QLCNIC_CRB_MAX) || (off < QLCNIC_PCI_CRBSPACE))
return -EINVAL;
off -= QLCNIC_PCI_CRBSPACE;
/*
* Try direct map
*/
m = &crb_128M_2M_map[CRB_BLK(off)].sub_block[CRB_SUBBLK(off)];
if (m->valid && (m->start_128M <= off) && (m->end_128M > off)) {
*addr = adapter->ahw.pci_base0 + m->start_2M +
(off - m->start_128M);
return 0;
}
/*
* Not in direct map, use crb window
*/
*addr = adapter->ahw.pci_base0 + CRB_INDIRECT_2M + (off & MASK(16));
return 1;
}
/*
* In: 'off' is offset from CRB space in 128M pci map
* Out: 'off' is 2M pci map addr
* side effect: lock crb window
*/
static void
qlcnic_pci_set_crbwindow_2M(struct qlcnic_adapter *adapter, ulong off)
{
u32 window;
void __iomem *addr = adapter->ahw.pci_base0 + CRB_WINDOW_2M;
off -= QLCNIC_PCI_CRBSPACE;
window = CRB_HI(off);
if (adapter->ahw.crb_win == window)
return;
writel(window, addr);
if (readl(addr) != window) {
if (printk_ratelimit())
dev_warn(&adapter->pdev->dev,
"failed to set CRB window to %d off 0x%lx\n",
window, off);
}
adapter->ahw.crb_win = window;
}
int
qlcnic_hw_write_wx_2M(struct qlcnic_adapter *adapter, ulong off, u32 data)
{
unsigned long flags;
int rv;
void __iomem *addr = NULL;
rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);
if (rv == 0) {
writel(data, addr);
return 0;
}
if (rv > 0) {
/* indirect access */
write_lock_irqsave(&adapter->ahw.crb_lock, flags);
crb_win_lock(adapter);
qlcnic_pci_set_crbwindow_2M(adapter, off);
writel(data, addr);
crb_win_unlock(adapter);
write_unlock_irqrestore(&adapter->ahw.crb_lock, flags);
return 0;
}
dev_err(&adapter->pdev->dev,
"%s: invalid offset: 0x%016lx\n", __func__, off);
dump_stack();
return -EIO;
}
u32
qlcnic_hw_read_wx_2M(struct qlcnic_adapter *adapter, ulong off)
{
unsigned long flags;
int rv;
u32 data;
void __iomem *addr = NULL;
rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);
if (rv == 0)
return readl(addr);
if (rv > 0) {
/* indirect access */
write_lock_irqsave(&adapter->ahw.crb_lock, flags);
crb_win_lock(adapter);
qlcnic_pci_set_crbwindow_2M(adapter, off);
data = readl(addr);
crb_win_unlock(adapter);
write_unlock_irqrestore(&adapter->ahw.crb_lock, flags);
return data;
}
dev_err(&adapter->pdev->dev,
"%s: invalid offset: 0x%016lx\n", __func__, off);
dump_stack();
return -1;
}
void __iomem *
qlcnic_get_ioaddr(struct qlcnic_adapter *adapter, u32 offset)
{
void __iomem *addr = NULL;
WARN_ON(qlcnic_pci_get_crb_addr_2M(adapter, offset, &addr));
return addr;
}
static int
qlcnic_pci_set_window_2M(struct qlcnic_adapter *adapter,
u64 addr, u32 *start)
{
u32 window;
struct pci_dev *pdev = adapter->pdev;
if ((addr & 0x00ff800) == 0xff800) {
if (printk_ratelimit())
dev_warn(&pdev->dev, "QM access not handled\n");
return -EIO;
}
window = OCM_WIN_P3P(addr);
writel(window, adapter->ahw.ocm_win_crb);
/* read back to flush */
readl(adapter->ahw.ocm_win_crb);
adapter->ahw.ocm_win = window;
*start = QLCNIC_PCI_OCM0_2M + GET_MEM_OFFS_2M(addr);
return 0;
}
static int
qlcnic_pci_mem_access_direct(struct qlcnic_adapter *adapter, u64 off,
u64 *data, int op)
{
void __iomem *addr, *mem_ptr = NULL;
resource_size_t mem_base;
int ret;
u32 start;
mutex_lock(&adapter->ahw.mem_lock);
ret = qlcnic_pci_set_window_2M(adapter, off, &start);
if (ret != 0)
goto unlock;
addr = pci_base_offset(adapter, start);
if (addr)
goto noremap;
mem_base = pci_resource_start(adapter->pdev, 0) + (start & PAGE_MASK);
mem_ptr = ioremap(mem_base, PAGE_SIZE);
if (mem_ptr == NULL) {
ret = -EIO;
goto unlock;
}
addr = mem_ptr + (start & (PAGE_SIZE - 1));
noremap:
if (op == 0) /* read */
*data = readq(addr);
else /* write */
writeq(*data, addr);
unlock:
mutex_unlock(&adapter->ahw.mem_lock);
if (mem_ptr)
iounmap(mem_ptr);
return ret;
}
#define MAX_CTL_CHECK 1000
int
qlcnic_pci_mem_write_2M(struct qlcnic_adapter *adapter,
u64 off, u64 data)
{
int i, j, ret;
u32 temp, off8;
u64 stride;
void __iomem *mem_crb;
/* Only 64-bit aligned access */
if (off & 7)
return -EIO;
/* P3 onward, test agent base for MIU and SIU is same */
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,
QLCNIC_ADDR_QDR_NET_MAX_P3)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX))
return qlcnic_pci_mem_access_direct(adapter, off, &data, 1);
return -EIO;
correct:
stride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8;
off8 = off & ~(stride-1);
mutex_lock(&adapter->ahw.mem_lock);
writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));
writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));
i = 0;
if (stride == 16) {
writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE),
(mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
ret = -EIO;
goto done;
}
i = (off & 0xf) ? 0 : 2;
writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i)),
mem_crb + MIU_TEST_AGT_WRDATA(i));
writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i+1)),
mem_crb + MIU_TEST_AGT_WRDATA(i+1));
i = (off & 0xf) ? 2 : 0;
}
writel(data & 0xffffffff,
mem_crb + MIU_TEST_AGT_WRDATA(i));
writel((data >> 32) & 0xffffffff,
mem_crb + MIU_TEST_AGT_WRDATA(i+1));
writel((TA_CTL_ENABLE | TA_CTL_WRITE), (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE | TA_CTL_WRITE),
(mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
if (printk_ratelimit())
dev_err(&adapter->pdev->dev,
"failed to write through agent\n");
ret = -EIO;
} else
ret = 0;
done:
mutex_unlock(&adapter->ahw.mem_lock);
return ret;
}
int
qlcnic_pci_mem_read_2M(struct qlcnic_adapter *adapter,
u64 off, u64 *data)
{
int j, ret;
u32 temp, off8;
u64 val, stride;
void __iomem *mem_crb;
/* Only 64-bit aligned access */
if (off & 7)
return -EIO;
/* P3 onward, test agent base for MIU and SIU is same */
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,
QLCNIC_ADDR_QDR_NET_MAX_P3)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX)) {
return qlcnic_pci_mem_access_direct(adapter,
off, data, 0);
}
return -EIO;
correct:
stride = QLCNIC_IS_REVISION_P3P(adapter->ahw.revision_id) ? 16 : 8;
off8 = off & ~(stride-1);
mutex_lock(&adapter->ahw.mem_lock);
writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));
writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));
writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE), (mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
if (printk_ratelimit())
dev_err(&adapter->pdev->dev,
"failed to read through agent\n");
ret = -EIO;
} else {
off8 = MIU_TEST_AGT_RDDATA_LO;
if ((stride == 16) && (off & 0xf))
off8 = MIU_TEST_AGT_RDDATA_UPPER_LO;
temp = readl(mem_crb + off8 + 4);
val = (u64)temp << 32;
val |= readl(mem_crb + off8);
*data = val;
ret = 0;
}
mutex_unlock(&adapter->ahw.mem_lock);
return ret;
}
int qlcnic_get_board_info(struct qlcnic_adapter *adapter)
{
int offset, board_type, magic;
struct pci_dev *pdev = adapter->pdev;
offset = QLCNIC_FW_MAGIC_OFFSET;
if (qlcnic_rom_fast_read(adapter, offset, &magic))
return -EIO;
if (magic != QLCNIC_BDINFO_MAGIC) {
dev_err(&pdev->dev, "invalid board config, magic=%08x\n",
magic);
return -EIO;
}
offset = QLCNIC_BRDTYPE_OFFSET;
if (qlcnic_rom_fast_read(adapter, offset, &board_type))
return -EIO;
adapter->ahw.board_type = board_type;
if (board_type == QLCNIC_BRDTYPE_P3_4_GB_MM) {
u32 gpio = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_PAD_GPIO_I);
if ((gpio & 0x8000) == 0)
board_type = QLCNIC_BRDTYPE_P3_10G_TP;
}
switch (board_type) {
case QLCNIC_BRDTYPE_P3_HMEZ:
case QLCNIC_BRDTYPE_P3_XG_LOM:
case QLCNIC_BRDTYPE_P3_10G_CX4:
case QLCNIC_BRDTYPE_P3_10G_CX4_LP:
case QLCNIC_BRDTYPE_P3_IMEZ:
case QLCNIC_BRDTYPE_P3_10G_SFP_PLUS:
case QLCNIC_BRDTYPE_P3_10G_SFP_CT:
case QLCNIC_BRDTYPE_P3_10G_SFP_QT:
case QLCNIC_BRDTYPE_P3_10G_XFP:
case QLCNIC_BRDTYPE_P3_10000_BASE_T:
adapter->ahw.port_type = QLCNIC_XGBE;
break;
case QLCNIC_BRDTYPE_P3_REF_QG:
case QLCNIC_BRDTYPE_P3_4_GB:
case QLCNIC_BRDTYPE_P3_4_GB_MM:
adapter->ahw.port_type = QLCNIC_GBE;
break;
case QLCNIC_BRDTYPE_P3_10G_TP:
adapter->ahw.port_type = (adapter->portnum < 2) ?
QLCNIC_XGBE : QLCNIC_GBE;
break;
default:
dev_err(&pdev->dev, "unknown board type %x\n", board_type);
adapter->ahw.port_type = QLCNIC_XGBE;
break;
}
return 0;
}
int
qlcnic_wol_supported(struct qlcnic_adapter *adapter)
{
u32 wol_cfg;
wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG_NV);
if (wol_cfg & (1UL << adapter->portnum)) {
wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG);
if (wol_cfg & (1 << adapter->portnum))
return 1;
}
return 0;
}
int qlcnic_config_led(struct qlcnic_adapter *adapter, u32 state, u32 rate)
{
struct qlcnic_nic_req req;
int rv;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_LED | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64((u64)rate << 32);
req.words[1] = cpu_to_le64(state);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv)
dev_err(&adapter->pdev->dev, "LED configuration failed.\n");
return rv;
}
static int qlcnic_set_fw_loopback(struct qlcnic_adapter *adapter, u32 flag)
{
struct qlcnic_nic_req req;
int rv;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_LOOPBACK |
((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(flag);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv)
dev_err(&adapter->pdev->dev,
"%sting loopback mode failed.\n",
flag ? "Set" : "Reset");
return rv;
}
int qlcnic_set_ilb_mode(struct qlcnic_adapter *adapter)
{
if (qlcnic_set_fw_loopback(adapter, 1))
return -EIO;
if (qlcnic_nic_set_promisc(adapter,
VPORT_MISS_MODE_ACCEPT_ALL)) {
qlcnic_set_fw_loopback(adapter, 0);
return -EIO;
}
msleep(1000);
return 0;
}
void qlcnic_clear_ilb_mode(struct qlcnic_adapter *adapter)
{
int mode = VPORT_MISS_MODE_DROP;
struct net_device *netdev = adapter->netdev;
qlcnic_set_fw_loopback(adapter, 0);
if (netdev->flags & IFF_PROMISC)
mode = VPORT_MISS_MODE_ACCEPT_ALL;
else if (netdev->flags & IFF_ALLMULTI)
mode = VPORT_MISS_MODE_ACCEPT_MULTI;
qlcnic_nic_set_promisc(adapter, mode);
}
| gpl-2.0 |
GuillaumeSeren/linux | drivers/mfd/da9063-i2c.c | 15634 | // SPDX-License-Identifier: GPL-2.0+
/* I2C support for Dialog DA9063
*
* Copyright 2012 Dialog Semiconductor Ltd.
* Copyright 2013 Philipp Zabel, Pengutronix
*
* Author: Krystian Garbaciak, Dialog Semiconductor
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/mfd/core.h>
#include <linux/mfd/da9063/core.h>
#include <linux/mfd/da9063/registers.h>
#include <linux/of.h>
#include <linux/regulator/of_regulator.h>
/*
* Raw I2C access required for just accessing chip and variant info before we
* know which device is present. The info read from the device using this
* approach is then used to select the correct regmap tables.
*/
#define DA9063_REG_PAGE_SIZE 0x100
#define DA9063_REG_PAGED_ADDR_MASK 0xFF
enum da9063_page_sel_buf_fmt {
DA9063_PAGE_SEL_BUF_PAGE_REG = 0,
DA9063_PAGE_SEL_BUF_PAGE_VAL,
DA9063_PAGE_SEL_BUF_SIZE,
};
enum da9063_paged_read_msgs {
DA9063_PAGED_READ_MSG_PAGE_SEL = 0,
DA9063_PAGED_READ_MSG_REG_SEL,
DA9063_PAGED_READ_MSG_DATA,
DA9063_PAGED_READ_MSG_CNT,
};
static int da9063_i2c_blockreg_read(struct i2c_client *client, u16 addr,
u8 *buf, int count)
{
struct i2c_msg xfer[DA9063_PAGED_READ_MSG_CNT];
u8 page_sel_buf[DA9063_PAGE_SEL_BUF_SIZE];
u8 page_num, paged_addr;
int ret;
/* Determine page info based on register address */
page_num = (addr / DA9063_REG_PAGE_SIZE);
if (page_num > 1) {
dev_err(&client->dev, "Invalid register address provided\n");
return -EINVAL;
}
paged_addr = (addr % DA9063_REG_PAGE_SIZE) & DA9063_REG_PAGED_ADDR_MASK;
page_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_REG] = DA9063_REG_PAGE_CON;
page_sel_buf[DA9063_PAGE_SEL_BUF_PAGE_VAL] =
(page_num << DA9063_I2C_PAGE_SEL_SHIFT) & DA9063_REG_PAGE_MASK;
/* Write reg address, page selection */
xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].addr = client->addr;
xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].flags = 0;
xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].len = DA9063_PAGE_SEL_BUF_SIZE;
xfer[DA9063_PAGED_READ_MSG_PAGE_SEL].buf = page_sel_buf;
/* Select register address */
xfer[DA9063_PAGED_READ_MSG_REG_SEL].addr = client->addr;
xfer[DA9063_PAGED_READ_MSG_REG_SEL].flags = 0;
xfer[DA9063_PAGED_READ_MSG_REG_SEL].len = sizeof(paged_addr);
xfer[DA9063_PAGED_READ_MSG_REG_SEL].buf = &paged_addr;
/* Read data */
xfer[DA9063_PAGED_READ_MSG_DATA].addr = client->addr;
xfer[DA9063_PAGED_READ_MSG_DATA].flags = I2C_M_RD;
xfer[DA9063_PAGED_READ_MSG_DATA].len = count;
xfer[DA9063_PAGED_READ_MSG_DATA].buf = buf;
ret = i2c_transfer(client->adapter, xfer, DA9063_PAGED_READ_MSG_CNT);
if (ret < 0) {
dev_err(&client->dev, "Paged block read failed: %d\n", ret);
return ret;
}
if (ret != DA9063_PAGED_READ_MSG_CNT) {
dev_err(&client->dev, "Paged block read failed to complete\n");
return -EIO;
}
return 0;
}
enum {
DA9063_DEV_ID_REG = 0,
DA9063_VAR_ID_REG,
DA9063_CHIP_ID_REGS,
};
static int da9063_get_device_type(struct i2c_client *i2c, struct da9063 *da9063)
{
u8 buf[DA9063_CHIP_ID_REGS];
int ret;
ret = da9063_i2c_blockreg_read(i2c, DA9063_REG_DEVICE_ID, buf,
DA9063_CHIP_ID_REGS);
if (ret)
return ret;
if (buf[DA9063_DEV_ID_REG] != PMIC_CHIP_ID_DA9063) {
dev_err(da9063->dev,
"Invalid chip device ID: 0x%02x\n",
buf[DA9063_DEV_ID_REG]);
return -ENODEV;
}
dev_info(da9063->dev,
"Device detected (chip-ID: 0x%02X, var-ID: 0x%02X)\n",
buf[DA9063_DEV_ID_REG], buf[DA9063_VAR_ID_REG]);
da9063->variant_code =
(buf[DA9063_VAR_ID_REG] & DA9063_VARIANT_ID_MRC_MASK)
>> DA9063_VARIANT_ID_MRC_SHIFT;
return 0;
}
/*
* Variant specific regmap configs
*/
static const struct regmap_range da9063_ad_readable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_AD_REG_SECOND_D),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_AD_REG_GP_ID_19),
regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),
};
static const struct regmap_range da9063_ad_writeable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),
regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),
regmap_reg_range(DA9063_REG_COUNT_S, DA9063_AD_REG_ALARM_Y),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_AD_REG_MON_REG_4),
regmap_reg_range(DA9063_AD_REG_GP_ID_0, DA9063_AD_REG_GP_ID_19),
};
static const struct regmap_range da9063_ad_volatile_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),
regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),
regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),
regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),
regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),
regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_AD_REG_SECOND_D),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),
regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),
regmap_reg_range(DA9063_AD_REG_MON_REG_5, DA9063_AD_REG_MON_REG_6),
};
static const struct regmap_access_table da9063_ad_readable_table = {
.yes_ranges = da9063_ad_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_ad_readable_ranges),
};
static const struct regmap_access_table da9063_ad_writeable_table = {
.yes_ranges = da9063_ad_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_ad_writeable_ranges),
};
static const struct regmap_access_table da9063_ad_volatile_table = {
.yes_ranges = da9063_ad_volatile_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_ad_volatile_ranges),
};
static const struct regmap_range da9063_bb_readable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19),
regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),
};
static const struct regmap_range da9063_bb_writeable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),
regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),
regmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),
regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19),
};
static const struct regmap_range da9063_bb_da_volatile_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),
regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),
regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),
regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),
regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),
regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_BB_REG_SECOND_D),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),
regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),
regmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6),
};
static const struct regmap_access_table da9063_bb_readable_table = {
.yes_ranges = da9063_bb_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_bb_readable_ranges),
};
static const struct regmap_access_table da9063_bb_writeable_table = {
.yes_ranges = da9063_bb_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_bb_writeable_ranges),
};
static const struct regmap_access_table da9063_bb_da_volatile_table = {
.yes_ranges = da9063_bb_da_volatile_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_bb_da_volatile_ranges),
};
static const struct regmap_range da9063l_bb_readable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_19),
regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),
};
static const struct regmap_range da9063l_bb_writeable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),
regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),
regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_19),
};
static const struct regmap_range da9063l_bb_da_volatile_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_EVENT_D),
regmap_reg_range(DA9063_REG_CONTROL_A, DA9063_REG_CONTROL_B),
regmap_reg_range(DA9063_REG_CONTROL_E, DA9063_REG_CONTROL_F),
regmap_reg_range(DA9063_REG_BCORE2_CONT, DA9063_REG_LDO11_CONT),
regmap_reg_range(DA9063_REG_DVC_1, DA9063_REG_ADC_MAN),
regmap_reg_range(DA9063_REG_ADC_RES_L, DA9063_REG_MON_A10_RES),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_SEQ),
regmap_reg_range(DA9063_REG_EN_32K, DA9063_REG_EN_32K),
regmap_reg_range(DA9063_BB_REG_MON_REG_5, DA9063_BB_REG_MON_REG_6),
};
static const struct regmap_access_table da9063l_bb_readable_table = {
.yes_ranges = da9063l_bb_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063l_bb_readable_ranges),
};
static const struct regmap_access_table da9063l_bb_writeable_table = {
.yes_ranges = da9063l_bb_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063l_bb_writeable_ranges),
};
static const struct regmap_access_table da9063l_bb_da_volatile_table = {
.yes_ranges = da9063l_bb_da_volatile_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063l_bb_da_volatile_ranges),
};
static const struct regmap_range da9063_da_readable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_BB_REG_SECOND_D),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11),
regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),
};
static const struct regmap_range da9063_da_writeable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),
regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),
regmap_reg_range(DA9063_REG_COUNT_S, DA9063_BB_REG_ALARM_Y),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),
regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11),
};
static const struct regmap_access_table da9063_da_readable_table = {
.yes_ranges = da9063_da_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_da_readable_ranges),
};
static const struct regmap_access_table da9063_da_writeable_table = {
.yes_ranges = da9063_da_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063_da_writeable_ranges),
};
static const struct regmap_range da9063l_da_readable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_MON_A10_RES),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_T_OFFSET, DA9063_BB_REG_GP_ID_11),
regmap_reg_range(DA9063_REG_DEVICE_ID, DA9063_REG_VARIANT_ID),
};
static const struct regmap_range da9063l_da_writeable_ranges[] = {
regmap_reg_range(DA9063_REG_PAGE_CON, DA9063_REG_PAGE_CON),
regmap_reg_range(DA9063_REG_FAULT_LOG, DA9063_REG_VSYS_MON),
regmap_reg_range(DA9063_REG_SEQ, DA9063_REG_ID_32_31),
regmap_reg_range(DA9063_REG_SEQ_A, DA9063_REG_AUTO3_LOW),
regmap_reg_range(DA9063_REG_CONFIG_I, DA9063_BB_REG_MON_REG_4),
regmap_reg_range(DA9063_BB_REG_GP_ID_0, DA9063_BB_REG_GP_ID_11),
};
static const struct regmap_access_table da9063l_da_readable_table = {
.yes_ranges = da9063l_da_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063l_da_readable_ranges),
};
static const struct regmap_access_table da9063l_da_writeable_table = {
.yes_ranges = da9063l_da_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(da9063l_da_writeable_ranges),
};
static const struct regmap_range_cfg da9063_range_cfg[] = {
{
.range_min = DA9063_REG_PAGE_CON,
.range_max = DA9063_REG_CONFIG_ID,
.selector_reg = DA9063_REG_PAGE_CON,
.selector_mask = 1 << DA9063_I2C_PAGE_SEL_SHIFT,
.selector_shift = DA9063_I2C_PAGE_SEL_SHIFT,
.window_start = 0,
.window_len = 256,
}
};
static struct regmap_config da9063_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.ranges = da9063_range_cfg,
.num_ranges = ARRAY_SIZE(da9063_range_cfg),
.max_register = DA9063_REG_CONFIG_ID,
.cache_type = REGCACHE_RBTREE,
};
static const struct of_device_id da9063_dt_ids[] = {
{ .compatible = "dlg,da9063", },
{ .compatible = "dlg,da9063l", },
{ }
};
MODULE_DEVICE_TABLE(of, da9063_dt_ids);
static int da9063_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct da9063 *da9063;
int ret;
da9063 = devm_kzalloc(&i2c->dev, sizeof(struct da9063), GFP_KERNEL);
if (da9063 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, da9063);
da9063->dev = &i2c->dev;
da9063->chip_irq = i2c->irq;
da9063->type = id->driver_data;
ret = da9063_get_device_type(i2c, da9063);
if (ret)
return ret;
switch (da9063->type) {
case PMIC_TYPE_DA9063:
switch (da9063->variant_code) {
case PMIC_DA9063_AD:
da9063_regmap_config.rd_table =
&da9063_ad_readable_table;
da9063_regmap_config.wr_table =
&da9063_ad_writeable_table;
da9063_regmap_config.volatile_table =
&da9063_ad_volatile_table;
break;
case PMIC_DA9063_BB:
case PMIC_DA9063_CA:
da9063_regmap_config.rd_table =
&da9063_bb_readable_table;
da9063_regmap_config.wr_table =
&da9063_bb_writeable_table;
da9063_regmap_config.volatile_table =
&da9063_bb_da_volatile_table;
break;
case PMIC_DA9063_DA:
da9063_regmap_config.rd_table =
&da9063_da_readable_table;
da9063_regmap_config.wr_table =
&da9063_da_writeable_table;
da9063_regmap_config.volatile_table =
&da9063_bb_da_volatile_table;
break;
default:
dev_err(da9063->dev,
"Chip variant not supported for DA9063\n");
return -ENODEV;
}
break;
case PMIC_TYPE_DA9063L:
switch (da9063->variant_code) {
case PMIC_DA9063_BB:
case PMIC_DA9063_CA:
da9063_regmap_config.rd_table =
&da9063l_bb_readable_table;
da9063_regmap_config.wr_table =
&da9063l_bb_writeable_table;
da9063_regmap_config.volatile_table =
&da9063l_bb_da_volatile_table;
break;
case PMIC_DA9063_DA:
da9063_regmap_config.rd_table =
&da9063l_da_readable_table;
da9063_regmap_config.wr_table =
&da9063l_da_writeable_table;
da9063_regmap_config.volatile_table =
&da9063l_bb_da_volatile_table;
break;
default:
dev_err(da9063->dev,
"Chip variant not supported for DA9063L\n");
return -ENODEV;
}
break;
default:
dev_err(da9063->dev, "Chip type not supported\n");
return -ENODEV;
}
da9063->regmap = devm_regmap_init_i2c(i2c, &da9063_regmap_config);
if (IS_ERR(da9063->regmap)) {
ret = PTR_ERR(da9063->regmap);
dev_err(da9063->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
return da9063_device_init(da9063, i2c->irq);
}
static const struct i2c_device_id da9063_i2c_id[] = {
{ "da9063", PMIC_TYPE_DA9063 },
{ "da9063l", PMIC_TYPE_DA9063L },
{},
};
MODULE_DEVICE_TABLE(i2c, da9063_i2c_id);
static struct i2c_driver da9063_i2c_driver = {
.driver = {
.name = "da9063",
.of_match_table = da9063_dt_ids,
},
.probe = da9063_i2c_probe,
.id_table = da9063_i2c_id,
};
module_i2c_driver(da9063_i2c_driver);
| gpl-2.0 |
queirozfcom/elasticsearch | core/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalTerms.java | 10492 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.terms;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.search.aggregations.AggregationExecutionException;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregations;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.support.format.ValueFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
*
*/
public abstract class InternalTerms<A extends InternalTerms, B extends InternalTerms.Bucket> extends InternalMultiBucketAggregation<A, B>
implements Terms, ToXContent, Streamable {
protected static final String DOC_COUNT_ERROR_UPPER_BOUND_FIELD_NAME = "doc_count_error_upper_bound";
protected static final String SUM_OF_OTHER_DOC_COUNTS = "sum_other_doc_count";
public static abstract class Bucket extends Terms.Bucket {
long bucketOrd;
protected long docCount;
protected long docCountError;
protected InternalAggregations aggregations;
protected boolean showDocCountError;
transient final ValueFormatter formatter;
protected Bucket(ValueFormatter formatter, boolean showDocCountError) {
// for serialization
this.showDocCountError = showDocCountError;
this.formatter = formatter;
}
protected Bucket(long docCount, InternalAggregations aggregations, boolean showDocCountError, long docCountError,
ValueFormatter formatter) {
this(formatter, showDocCountError);
this.docCount = docCount;
this.aggregations = aggregations;
this.docCountError = docCountError;
}
@Override
public long getDocCount() {
return docCount;
}
@Override
public long getDocCountError() {
if (!showDocCountError) {
throw new IllegalStateException("show_terms_doc_count_error is false");
}
return docCountError;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
abstract Bucket newBucket(long docCount, InternalAggregations aggs, long docCountError);
public Bucket reduce(List<? extends Bucket> buckets, ReduceContext context) {
long docCount = 0;
long docCountError = 0;
List<InternalAggregations> aggregationsList = new ArrayList<>(buckets.size());
for (Bucket bucket : buckets) {
docCount += bucket.docCount;
if (docCountError != -1) {
if (bucket.docCountError == -1) {
docCountError = -1;
} else {
docCountError += bucket.docCountError;
}
}
aggregationsList.add(bucket.aggregations);
}
InternalAggregations aggs = InternalAggregations.reduce(aggregationsList, context);
return newBucket(docCount, aggs, docCountError);
}
}
protected Terms.Order order;
protected int requiredSize;
protected int shardSize;
protected long minDocCount;
protected List<? extends Bucket> buckets;
protected Map<String, Bucket> bucketMap;
protected long docCountError;
protected boolean showTermDocCountError;
protected long otherDocCount;
protected InternalTerms() {} // for serialization
protected InternalTerms(String name, Terms.Order order, int requiredSize, int shardSize, long minDocCount,
List<? extends Bucket> buckets, boolean showTermDocCountError, long docCountError, long otherDocCount, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) {
super(name, pipelineAggregators, metaData);
this.order = order;
this.requiredSize = requiredSize;
this.shardSize = shardSize;
this.minDocCount = minDocCount;
this.buckets = buckets;
this.showTermDocCountError = showTermDocCountError;
this.docCountError = docCountError;
this.otherDocCount = otherDocCount;
}
@Override
public List<Terms.Bucket> getBuckets() {
Object o = buckets;
return (List<Terms.Bucket>) o;
}
@Override
public Terms.Bucket getBucketByKey(String term) {
if (bucketMap == null) {
bucketMap = Maps.newHashMapWithExpectedSize(buckets.size());
for (Bucket bucket : buckets) {
bucketMap.put(bucket.getKeyAsString(), bucket);
}
}
return bucketMap.get(term);
}
@Override
public long getDocCountError() {
return docCountError;
}
@Override
public long getSumOfOtherDocCounts() {
return otherDocCount;
}
@Override
public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
Multimap<Object, InternalTerms.Bucket> buckets = ArrayListMultimap.create();
long sumDocCountError = 0;
long otherDocCount = 0;
InternalTerms<A, B> referenceTerms = null;
for (InternalAggregation aggregation : aggregations) {
InternalTerms<A, B> terms = (InternalTerms<A, B>) aggregation;
if (referenceTerms == null && !terms.getClass().equals(UnmappedTerms.class)) {
referenceTerms = (InternalTerms<A, B>) aggregation;
}
if (referenceTerms != null &&
!referenceTerms.getClass().equals(terms.getClass()) &&
!terms.getClass().equals(UnmappedTerms.class)) {
// control gets into this loop when the same field name against which the query is executed
// is of different types in different indices.
throw new AggregationExecutionException("Merging/Reducing the aggregations failed " +
"when computing the aggregation [ Name: " +
referenceTerms.getName() + ", Type: " +
referenceTerms.type() + " ]" + " because: " +
"the field you gave in the aggregation query " +
"existed as two different types " +
"in two different indices");
}
otherDocCount += terms.getSumOfOtherDocCounts();
final long thisAggDocCountError;
if (terms.buckets.size() < this.shardSize || this.order == InternalOrder.TERM_ASC || this.order == InternalOrder.TERM_DESC) {
thisAggDocCountError = 0;
} else if (InternalOrder.isCountDesc(this.order)) {
thisAggDocCountError = terms.buckets.get(terms.buckets.size() - 1).docCount;
} else {
thisAggDocCountError = -1;
}
if (sumDocCountError != -1) {
if (thisAggDocCountError == -1) {
sumDocCountError = -1;
} else {
sumDocCountError += thisAggDocCountError;
}
}
terms.docCountError = thisAggDocCountError;
for (Bucket bucket : terms.buckets) {
bucket.docCountError = thisAggDocCountError;
buckets.put(bucket.getKey(), bucket);
}
}
final int size = Math.min(requiredSize, buckets.size());
BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null));
for (Collection<Bucket> l : buckets.asMap().values()) {
List<Bucket> sameTermBuckets = (List<Bucket>) l; // cast is ok according to javadocs
final Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext);
if (b.docCountError != -1) {
if (sumDocCountError == -1) {
b.docCountError = -1;
} else {
b.docCountError = sumDocCountError - b.docCountError;
}
}
if (b.docCount >= minDocCount) {
Terms.Bucket removed = ordered.insertWithOverflow(b);
if (removed != null) {
otherDocCount += removed.getDocCount();
}
}
}
Bucket[] list = new Bucket[ordered.size()];
for (int i = ordered.size() - 1; i >= 0; i--) {
list[i] = (Bucket) ordered.pop();
}
long docCountError;
if (sumDocCountError == -1) {
docCountError = -1;
} else {
docCountError = aggregations.size() == 1 ? 0 : sumDocCountError;
}
return create(name, Arrays.asList(list), docCountError, otherDocCount, this);
}
protected abstract A create(String name, List<InternalTerms.Bucket> buckets, long docCountError, long otherDocCount,
InternalTerms prototype);
}
| apache-2.0 |
dmirubtsov/k8s-executor | vendor/k8s.io/kubernetes/vendor/github.com/google/cadvisor/info/v2/conversion.go | 7941 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v2
import (
"fmt"
"time"
"github.com/golang/glog"
"github.com/google/cadvisor/info/v1"
)
func machineFsStatsFromV1(fsStats []v1.FsStats) []MachineFsStats {
var result []MachineFsStats
for _, stat := range fsStats {
readDuration := time.Millisecond * time.Duration(stat.ReadTime)
writeDuration := time.Millisecond * time.Duration(stat.WriteTime)
ioDuration := time.Millisecond * time.Duration(stat.IoTime)
weightedDuration := time.Millisecond * time.Duration(stat.WeightedIoTime)
result = append(result, MachineFsStats{
Device: stat.Device,
Type: stat.Type,
Capacity: &stat.Limit,
Usage: &stat.Usage,
Available: &stat.Available,
InodesFree: &stat.InodesFree,
DiskStats: DiskStats{
ReadsCompleted: &stat.ReadsCompleted,
ReadsMerged: &stat.ReadsMerged,
SectorsRead: &stat.SectorsRead,
ReadDuration: &readDuration,
WritesCompleted: &stat.WritesCompleted,
WritesMerged: &stat.WritesMerged,
SectorsWritten: &stat.SectorsWritten,
WriteDuration: &writeDuration,
IoInProgress: &stat.IoInProgress,
IoDuration: &ioDuration,
WeightedIoDuration: &weightedDuration,
},
})
}
return result
}
func MachineStatsFromV1(cont *v1.ContainerInfo) []MachineStats {
var stats []MachineStats
var last *v1.ContainerStats
for _, val := range cont.Stats {
stat := MachineStats{
Timestamp: val.Timestamp,
}
if cont.Spec.HasCpu {
stat.Cpu = &val.Cpu
cpuInst, err := InstCpuStats(last, val)
if err != nil {
glog.Warningf("Could not get instant cpu stats: %v", err)
} else {
stat.CpuInst = cpuInst
}
last = val
}
if cont.Spec.HasMemory {
stat.Memory = &val.Memory
}
if cont.Spec.HasNetwork {
stat.Network = &NetworkStats{
// FIXME: Use reflection instead.
Tcp: TcpStat(val.Network.Tcp),
Tcp6: TcpStat(val.Network.Tcp6),
Interfaces: val.Network.Interfaces,
}
}
if cont.Spec.HasFilesystem {
stat.Filesystem = machineFsStatsFromV1(val.Filesystem)
}
// TODO(rjnagal): Handle load stats.
stats = append(stats, stat)
}
return stats
}
func ContainerStatsFromV1(spec *v1.ContainerSpec, stats []*v1.ContainerStats) []*ContainerStats {
newStats := make([]*ContainerStats, 0, len(stats))
var last *v1.ContainerStats
for _, val := range stats {
stat := &ContainerStats{
Timestamp: val.Timestamp,
}
if spec.HasCpu {
stat.Cpu = &val.Cpu
cpuInst, err := InstCpuStats(last, val)
if err != nil {
glog.Warningf("Could not get instant cpu stats: %v", err)
} else {
stat.CpuInst = cpuInst
}
last = val
}
if spec.HasMemory {
stat.Memory = &val.Memory
}
if spec.HasNetwork {
// TODO: Handle TcpStats
stat.Network = &NetworkStats{
Interfaces: val.Network.Interfaces,
}
}
if spec.HasFilesystem {
if len(val.Filesystem) == 1 {
stat.Filesystem = &FilesystemStats{
TotalUsageBytes: &val.Filesystem[0].Usage,
BaseUsageBytes: &val.Filesystem[0].BaseUsage,
}
} else if len(val.Filesystem) > 1 {
// Cannot handle multiple devices per container.
glog.V(2).Infof("failed to handle multiple devices for container. Skipping Filesystem stats")
}
}
if spec.HasDiskIo {
stat.DiskIo = &val.DiskIo
}
if spec.HasCustomMetrics {
stat.CustomMetrics = val.CustomMetrics
}
// TODO(rjnagal): Handle load stats.
newStats = append(newStats, stat)
}
return newStats
}
func DeprecatedStatsFromV1(cont *v1.ContainerInfo) []DeprecatedContainerStats {
stats := make([]DeprecatedContainerStats, 0, len(cont.Stats))
var last *v1.ContainerStats
for _, val := range cont.Stats {
stat := DeprecatedContainerStats{
Timestamp: val.Timestamp,
HasCpu: cont.Spec.HasCpu,
HasMemory: cont.Spec.HasMemory,
HasNetwork: cont.Spec.HasNetwork,
HasFilesystem: cont.Spec.HasFilesystem,
HasDiskIo: cont.Spec.HasDiskIo,
HasCustomMetrics: cont.Spec.HasCustomMetrics,
}
if stat.HasCpu {
stat.Cpu = val.Cpu
cpuInst, err := InstCpuStats(last, val)
if err != nil {
glog.Warningf("Could not get instant cpu stats: %v", err)
} else {
stat.CpuInst = cpuInst
}
last = val
}
if stat.HasMemory {
stat.Memory = val.Memory
}
if stat.HasNetwork {
stat.Network.Interfaces = val.Network.Interfaces
}
if stat.HasFilesystem {
stat.Filesystem = val.Filesystem
}
if stat.HasDiskIo {
stat.DiskIo = val.DiskIo
}
if stat.HasCustomMetrics {
stat.CustomMetrics = val.CustomMetrics
}
// TODO(rjnagal): Handle load stats.
stats = append(stats, stat)
}
return stats
}
func InstCpuStats(last, cur *v1.ContainerStats) (*CpuInstStats, error) {
if last == nil {
return nil, nil
}
if !cur.Timestamp.After(last.Timestamp) {
return nil, fmt.Errorf("container stats move backwards in time")
}
if len(last.Cpu.Usage.PerCpu) != len(cur.Cpu.Usage.PerCpu) {
return nil, fmt.Errorf("different number of cpus")
}
timeDelta := cur.Timestamp.Sub(last.Timestamp)
if timeDelta <= 100*time.Millisecond {
return nil, fmt.Errorf("time delta unexpectedly small")
}
// Nanoseconds to gain precision and avoid having zero seconds if the
// difference between the timestamps is just under a second
timeDeltaNs := uint64(timeDelta.Nanoseconds())
convertToRate := func(lastValue, curValue uint64) (uint64, error) {
if curValue < lastValue {
return 0, fmt.Errorf("cumulative stats decrease")
}
valueDelta := curValue - lastValue
// Use float64 to keep precision
return uint64(float64(valueDelta) / float64(timeDeltaNs) * 1e9), nil
}
total, err := convertToRate(last.Cpu.Usage.Total, cur.Cpu.Usage.Total)
if err != nil {
return nil, err
}
percpu := make([]uint64, len(last.Cpu.Usage.PerCpu))
for i := range percpu {
var err error
percpu[i], err = convertToRate(last.Cpu.Usage.PerCpu[i], cur.Cpu.Usage.PerCpu[i])
if err != nil {
return nil, err
}
}
user, err := convertToRate(last.Cpu.Usage.User, cur.Cpu.Usage.User)
if err != nil {
return nil, err
}
system, err := convertToRate(last.Cpu.Usage.System, cur.Cpu.Usage.System)
if err != nil {
return nil, err
}
return &CpuInstStats{
Usage: CpuInstUsage{
Total: total,
PerCpu: percpu,
User: user,
System: system,
},
}, nil
}
// Get V2 container spec from v1 container info.
func ContainerSpecFromV1(specV1 *v1.ContainerSpec, aliases []string, namespace string) ContainerSpec {
specV2 := ContainerSpec{
CreationTime: specV1.CreationTime,
HasCpu: specV1.HasCpu,
HasMemory: specV1.HasMemory,
HasFilesystem: specV1.HasFilesystem,
HasNetwork: specV1.HasNetwork,
HasDiskIo: specV1.HasDiskIo,
HasCustomMetrics: specV1.HasCustomMetrics,
Image: specV1.Image,
Labels: specV1.Labels,
}
if specV1.HasCpu {
specV2.Cpu.Limit = specV1.Cpu.Limit
specV2.Cpu.MaxLimit = specV1.Cpu.MaxLimit
specV2.Cpu.Mask = specV1.Cpu.Mask
}
if specV1.HasMemory {
specV2.Memory.Limit = specV1.Memory.Limit
specV2.Memory.Reservation = specV1.Memory.Reservation
specV2.Memory.SwapLimit = specV1.Memory.SwapLimit
}
if specV1.HasCustomMetrics {
specV2.CustomMetrics = specV1.CustomMetrics
}
specV2.Aliases = aliases
specV2.Namespace = namespace
return specV2
}
| apache-2.0 |
luciancrasovan/amphtml | examples/beopinion.amp.html | 4630 | <!doctype html>
<html ⚡>
<head>
<meta charset="utf-8">
<title>BeOpinion examples</title>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>
<link rel="canonical" href="https://www.example.com/url/to/full/document.html">
<script async custom-element="amp-beopinion" src="https://cdn.ampproject.org/v0/amp-beopinion-0.1.js"></script>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
<h2>BeOpinion</h2>
<h3>Simple Question</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c383c46e0fb00017ef05a">
</amp-beopinion>
<h3>Question with Tweet</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c504fc9e77c00018d1f1a">
</amp-beopinion>
<h3>Question with Instagram post</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c50a646e0fb00018039df">
</amp-beopinion>
<h3>Question with YouTube video</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8d4f0046e0fb00018bc17d">
</amp-beopinion>
<h3>Question with Dailymotion video</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8d7fddc9e77c00019c3f72">
</amp-beopinion>
<h3>Question with custom video</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c5232c9e77c00018d3a3d">
</amp-beopinion>
<h3>Survey</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c3b69c9e77c00018bffeb">
</amp-beopinion>
<h3>Quiz</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c3d1246e0fb00017f2f47">
</amp-beopinion>
<h3>Personality test</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c3ed0c9e77c00018c2d81">
</amp-beopinion>
<h3>Form</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c3f62c9e77c00018c35dc">
</amp-beopinion>
<h3>Game</h3>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8c41c846e0fb00017f7093">
</amp-beopinion>
<h2>Intentionally non-existing content</h2>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="aaaaaaaaaaaaaaaaaaaaaaaa">
</amp-beopinion>
<h2>Unpublished content</h2>
<amp-beopinion width="375" height="1"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8afe1746e0fb00017282f7">
</amp-beopinion>
<h2>Unpublished content (with fallback)</h2>
<amp-beopinion width="375" height="100"
layout="responsive"
data-account="5a8af83d46e0fb0001720141"
data-content="5a8afe1746e0fb00017282f7">
<div fallback>
An error occurred while retrieving the content. It might have been deleted.
</div>
</amp-beopinion>
<h2>Ad</h2>
<amp-ad width="300" height="1"
type="beopinion"
layout="responsive"
data-name="slot_0"
data-my-content="0"
data-account="5a8af83d46e0fb0001720141">
</amp-ad>
</body>
</html>
| apache-2.0 |
adouble42/nemesis-current | wxWidgets-3.1.0/include/wx/bmpbuttn.h | 4285 | /////////////////////////////////////////////////////////////////////////////
// Name: wx/bmpbuttn.h
// Purpose: wxBitmapButton class interface
// Author: Vadim Zeitlin
// Modified by:
// Created: 25.08.00
// Copyright: (c) 2000 Vadim Zeitlin
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifndef _WX_BMPBUTTON_H_BASE_
#define _WX_BMPBUTTON_H_BASE_
#include "wx/defs.h"
#if wxUSE_BMPBUTTON
#include "wx/button.h"
// FIXME: right now only wxMSW, wxGTK and wxOSX implement bitmap support in wxButton
// itself, this shouldn't be used for the other platforms neither
// when all of them do it
#if (defined(__WXMSW__) || defined(__WXGTK20__) || defined(__WXOSX__) || defined(__WXQT__)) && !defined(__WXUNIVERSAL__)
#define wxHAS_BUTTON_BITMAP
#endif
class WXDLLIMPEXP_FWD_CORE wxBitmapButton;
// ----------------------------------------------------------------------------
// wxBitmapButton: a button which shows bitmaps instead of the usual string.
// It has different bitmaps for different states (focused/disabled/pressed)
// ----------------------------------------------------------------------------
class WXDLLIMPEXP_CORE wxBitmapButtonBase : public wxButton
{
public:
wxBitmapButtonBase()
{
#ifndef wxHAS_BUTTON_BITMAP
m_marginX =
m_marginY = 0;
#endif // wxHAS_BUTTON_BITMAP
}
bool Create(wxWindow *parent,
wxWindowID winid,
const wxPoint& pos,
const wxSize& size,
long style,
const wxValidator& validator,
const wxString& name)
{
// We use wxBU_NOTEXT to let the base class Create() know that we are
// not going to show the label: this is a hack needed for wxGTK where
// we can show both label and bitmap only with GTK 2.6+ but we always
// can show just one of them and this style allows us to choose which
// one we need.
//
// And we also use wxBU_EXACTFIT to avoid being resized up to the
// standard button size as this doesn't make sense for bitmap buttons
// which are not standard anyhow and should fit their bitmap size.
return wxButton::Create(parent, winid, "",
pos, size,
style | wxBU_NOTEXT | wxBU_EXACTFIT,
validator, name);
}
// Special creation function for a standard "Close" bitmap. It allows to
// simply create a close button with the image appropriate for the current
// platform.
static wxBitmapButton* NewCloseButton(wxWindow* parent, wxWindowID winid);
// set/get the margins around the button
virtual void SetMargins(int x, int y)
{
DoSetBitmapMargins(x, y);
}
int GetMarginX() const { return DoGetBitmapMargins().x; }
int GetMarginY() const { return DoGetBitmapMargins().y; }
protected:
#ifndef wxHAS_BUTTON_BITMAP
// function called when any of the bitmaps changes
virtual void OnSetBitmap() { InvalidateBestSize(); Refresh(); }
virtual wxBitmap DoGetBitmap(State which) const { return m_bitmaps[which]; }
virtual void DoSetBitmap(const wxBitmap& bitmap, State which)
{ m_bitmaps[which] = bitmap; OnSetBitmap(); }
virtual wxSize DoGetBitmapMargins() const
{
return wxSize(m_marginX, m_marginY);
}
virtual void DoSetBitmapMargins(int x, int y)
{
m_marginX = x;
m_marginY = y;
}
// the bitmaps for various states
wxBitmap m_bitmaps[State_Max];
// the margins around the bitmap
int m_marginX,
m_marginY;
#endif // !wxHAS_BUTTON_BITMAP
wxDECLARE_NO_COPY_CLASS(wxBitmapButtonBase);
};
#if defined(__WXUNIVERSAL__)
#include "wx/univ/bmpbuttn.h"
#elif defined(__WXMSW__)
#include "wx/msw/bmpbuttn.h"
#elif defined(__WXMOTIF__)
#include "wx/motif/bmpbuttn.h"
#elif defined(__WXGTK20__)
#include "wx/gtk/bmpbuttn.h"
#elif defined(__WXGTK__)
#include "wx/gtk1/bmpbuttn.h"
#elif defined(__WXMAC__)
#include "wx/osx/bmpbuttn.h"
#elif defined(__WXQT__)
#include "wx/qt/bmpbuttn.h"
#endif
#endif // wxUSE_BMPBUTTON
#endif // _WX_BMPBUTTON_H_BASE_
| bsd-2-clause |
CTSRD-SOAAP/chromium-42.0.2311.135 | content/renderer/media/webrtc/peer_connection_dependency_factory_unittest.cc | 1157 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
#include "content/renderer/media/mock_web_rtc_peer_connection_handler_client.h"
#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/WebRTCPeerConnectionHandler.h"
namespace content {
class PeerConnectionDependencyFactoryTest : public ::testing::Test {
public:
void SetUp() override {
dependency_factory_.reset(new MockPeerConnectionDependencyFactory());
}
protected:
base::MessageLoop message_loop_;
scoped_ptr<MockPeerConnectionDependencyFactory> dependency_factory_;
};
TEST_F(PeerConnectionDependencyFactoryTest, CreateRTCPeerConnectionHandler) {
MockWebRTCPeerConnectionHandlerClient client_jsep;
scoped_ptr<blink::WebRTCPeerConnectionHandler> pc_handler(
dependency_factory_->CreateRTCPeerConnectionHandler(&client_jsep));
EXPECT_TRUE(pc_handler.get() != NULL);
}
} // namespace content
| bsd-3-clause |
jallen93/linux-vnic-dbg | drivers/spi/spi-davinci.c | 28957 | /*
* Copyright (C) 2009 Texas Instruments.
* Copyright (C) 2010 EF Johnson Technologies
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/dmaengine.h>
#include <linux/dma-mapping.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_bitbang.h>
#include <linux/slab.h>
#include <linux/platform_data/spi-davinci.h>
#define CS_DEFAULT 0xFF
#define SPIFMT_PHASE_MASK BIT(16)
#define SPIFMT_POLARITY_MASK BIT(17)
#define SPIFMT_DISTIMER_MASK BIT(18)
#define SPIFMT_SHIFTDIR_MASK BIT(20)
#define SPIFMT_WAITENA_MASK BIT(21)
#define SPIFMT_PARITYENA_MASK BIT(22)
#define SPIFMT_ODD_PARITY_MASK BIT(23)
#define SPIFMT_WDELAY_MASK 0x3f000000u
#define SPIFMT_WDELAY_SHIFT 24
#define SPIFMT_PRESCALE_SHIFT 8
/* SPIPC0 */
#define SPIPC0_DIFUN_MASK BIT(11) /* MISO */
#define SPIPC0_DOFUN_MASK BIT(10) /* MOSI */
#define SPIPC0_CLKFUN_MASK BIT(9) /* CLK */
#define SPIPC0_SPIENA_MASK BIT(8) /* nREADY */
#define SPIINT_MASKALL 0x0101035F
#define SPIINT_MASKINT 0x0000015F
#define SPI_INTLVL_1 0x000001FF
#define SPI_INTLVL_0 0x00000000
/* SPIDAT1 (upper 16 bit defines) */
#define SPIDAT1_CSHOLD_MASK BIT(12)
#define SPIDAT1_WDEL BIT(10)
/* SPIGCR1 */
#define SPIGCR1_CLKMOD_MASK BIT(1)
#define SPIGCR1_MASTER_MASK BIT(0)
#define SPIGCR1_POWERDOWN_MASK BIT(8)
#define SPIGCR1_LOOPBACK_MASK BIT(16)
#define SPIGCR1_SPIENA_MASK BIT(24)
/* SPIBUF */
#define SPIBUF_TXFULL_MASK BIT(29)
#define SPIBUF_RXEMPTY_MASK BIT(31)
/* SPIDELAY */
#define SPIDELAY_C2TDELAY_SHIFT 24
#define SPIDELAY_C2TDELAY_MASK (0xFF << SPIDELAY_C2TDELAY_SHIFT)
#define SPIDELAY_T2CDELAY_SHIFT 16
#define SPIDELAY_T2CDELAY_MASK (0xFF << SPIDELAY_T2CDELAY_SHIFT)
#define SPIDELAY_T2EDELAY_SHIFT 8
#define SPIDELAY_T2EDELAY_MASK (0xFF << SPIDELAY_T2EDELAY_SHIFT)
#define SPIDELAY_C2EDELAY_SHIFT 0
#define SPIDELAY_C2EDELAY_MASK 0xFF
/* Error Masks */
#define SPIFLG_DLEN_ERR_MASK BIT(0)
#define SPIFLG_TIMEOUT_MASK BIT(1)
#define SPIFLG_PARERR_MASK BIT(2)
#define SPIFLG_DESYNC_MASK BIT(3)
#define SPIFLG_BITERR_MASK BIT(4)
#define SPIFLG_OVRRUN_MASK BIT(6)
#define SPIFLG_BUF_INIT_ACTIVE_MASK BIT(24)
#define SPIFLG_ERROR_MASK (SPIFLG_DLEN_ERR_MASK \
| SPIFLG_TIMEOUT_MASK | SPIFLG_PARERR_MASK \
| SPIFLG_DESYNC_MASK | SPIFLG_BITERR_MASK \
| SPIFLG_OVRRUN_MASK)
#define SPIINT_DMA_REQ_EN BIT(16)
/* SPI Controller registers */
#define SPIGCR0 0x00
#define SPIGCR1 0x04
#define SPIINT 0x08
#define SPILVL 0x0c
#define SPIFLG 0x10
#define SPIPC0 0x14
#define SPIDAT1 0x3c
#define SPIBUF 0x40
#define SPIDELAY 0x48
#define SPIDEF 0x4c
#define SPIFMT0 0x50
/* SPI Controller driver's private data. */
struct davinci_spi {
struct spi_bitbang bitbang;
struct clk *clk;
u8 version;
resource_size_t pbase;
void __iomem *base;
u32 irq;
struct completion done;
const void *tx;
void *rx;
int rcount;
int wcount;
struct dma_chan *dma_rx;
struct dma_chan *dma_tx;
struct davinci_spi_platform_data pdata;
void (*get_rx)(u32 rx_data, struct davinci_spi *);
u32 (*get_tx)(struct davinci_spi *);
u8 *bytes_per_word;
u8 prescaler_limit;
};
static struct davinci_spi_config davinci_spi_default_cfg;
static void davinci_spi_rx_buf_u8(u32 data, struct davinci_spi *dspi)
{
if (dspi->rx) {
u8 *rx = dspi->rx;
*rx++ = (u8)data;
dspi->rx = rx;
}
}
static void davinci_spi_rx_buf_u16(u32 data, struct davinci_spi *dspi)
{
if (dspi->rx) {
u16 *rx = dspi->rx;
*rx++ = (u16)data;
dspi->rx = rx;
}
}
static u32 davinci_spi_tx_buf_u8(struct davinci_spi *dspi)
{
u32 data = 0;
if (dspi->tx) {
const u8 *tx = dspi->tx;
data = *tx++;
dspi->tx = tx;
}
return data;
}
static u32 davinci_spi_tx_buf_u16(struct davinci_spi *dspi)
{
u32 data = 0;
if (dspi->tx) {
const u16 *tx = dspi->tx;
data = *tx++;
dspi->tx = tx;
}
return data;
}
static inline void set_io_bits(void __iomem *addr, u32 bits)
{
u32 v = ioread32(addr);
v |= bits;
iowrite32(v, addr);
}
static inline void clear_io_bits(void __iomem *addr, u32 bits)
{
u32 v = ioread32(addr);
v &= ~bits;
iowrite32(v, addr);
}
/*
* Interface to control the chip select signal
*/
static void davinci_spi_chipselect(struct spi_device *spi, int value)
{
struct davinci_spi *dspi;
struct davinci_spi_platform_data *pdata;
struct davinci_spi_config *spicfg = spi->controller_data;
u8 chip_sel = spi->chip_select;
u16 spidat1 = CS_DEFAULT;
dspi = spi_master_get_devdata(spi->master);
pdata = &dspi->pdata;
/* program delay transfers if tx_delay is non zero */
if (spicfg->wdelay)
spidat1 |= SPIDAT1_WDEL;
/*
* Board specific chip select logic decides the polarity and cs
* line for the controller
*/
if (spi->cs_gpio >= 0) {
if (value == BITBANG_CS_ACTIVE)
gpio_set_value(spi->cs_gpio, spi->mode & SPI_CS_HIGH);
else
gpio_set_value(spi->cs_gpio,
!(spi->mode & SPI_CS_HIGH));
} else {
if (value == BITBANG_CS_ACTIVE) {
spidat1 |= SPIDAT1_CSHOLD_MASK;
spidat1 &= ~(0x1 << chip_sel);
}
}
iowrite16(spidat1, dspi->base + SPIDAT1 + 2);
}
/**
* davinci_spi_get_prescale - Calculates the correct prescale value
* @maxspeed_hz: the maximum rate the SPI clock can run at
*
* This function calculates the prescale value that generates a clock rate
* less than or equal to the specified maximum.
*
* Returns: calculated prescale value for easy programming into SPI registers
* or negative error number if valid prescalar cannot be updated.
*/
static inline int davinci_spi_get_prescale(struct davinci_spi *dspi,
u32 max_speed_hz)
{
int ret;
/* Subtract 1 to match what will be programmed into SPI register. */
ret = DIV_ROUND_UP(clk_get_rate(dspi->clk), max_speed_hz) - 1;
if (ret < dspi->prescaler_limit || ret > 255)
return -EINVAL;
return ret;
}
/**
* davinci_spi_setup_transfer - This functions will determine transfer method
* @spi: spi device on which data transfer to be done
* @t: spi transfer in which transfer info is filled
*
* This function determines data transfer method (8/16/32 bit transfer).
* It will also set the SPI Clock Control register according to
* SPI slave device freq.
*/
static int davinci_spi_setup_transfer(struct spi_device *spi,
struct spi_transfer *t)
{
struct davinci_spi *dspi;
struct davinci_spi_config *spicfg;
u8 bits_per_word = 0;
u32 hz = 0, spifmt = 0;
int prescale;
dspi = spi_master_get_devdata(spi->master);
spicfg = spi->controller_data;
if (!spicfg)
spicfg = &davinci_spi_default_cfg;
if (t) {
bits_per_word = t->bits_per_word;
hz = t->speed_hz;
}
/* if bits_per_word is not set then set it default */
if (!bits_per_word)
bits_per_word = spi->bits_per_word;
/*
* Assign function pointer to appropriate transfer method
* 8bit, 16bit or 32bit transfer
*/
if (bits_per_word <= 8) {
dspi->get_rx = davinci_spi_rx_buf_u8;
dspi->get_tx = davinci_spi_tx_buf_u8;
dspi->bytes_per_word[spi->chip_select] = 1;
} else {
dspi->get_rx = davinci_spi_rx_buf_u16;
dspi->get_tx = davinci_spi_tx_buf_u16;
dspi->bytes_per_word[spi->chip_select] = 2;
}
if (!hz)
hz = spi->max_speed_hz;
/* Set up SPIFMTn register, unique to this chipselect. */
prescale = davinci_spi_get_prescale(dspi, hz);
if (prescale < 0)
return prescale;
spifmt = (prescale << SPIFMT_PRESCALE_SHIFT) | (bits_per_word & 0x1f);
if (spi->mode & SPI_LSB_FIRST)
spifmt |= SPIFMT_SHIFTDIR_MASK;
if (spi->mode & SPI_CPOL)
spifmt |= SPIFMT_POLARITY_MASK;
if (!(spi->mode & SPI_CPHA))
spifmt |= SPIFMT_PHASE_MASK;
/*
* Assume wdelay is used only on SPI peripherals that has this field
* in SPIFMTn register and when it's configured from board file or DT.
*/
if (spicfg->wdelay)
spifmt |= ((spicfg->wdelay << SPIFMT_WDELAY_SHIFT)
& SPIFMT_WDELAY_MASK);
/*
* Version 1 hardware supports two basic SPI modes:
* - Standard SPI mode uses 4 pins, with chipselect
* - 3 pin SPI is a 4 pin variant without CS (SPI_NO_CS)
* (distinct from SPI_3WIRE, with just one data wire;
* or similar variants without MOSI or without MISO)
*
* Version 2 hardware supports an optional handshaking signal,
* so it can support two more modes:
* - 5 pin SPI variant is standard SPI plus SPI_READY
* - 4 pin with enable is (SPI_READY | SPI_NO_CS)
*/
if (dspi->version == SPI_VERSION_2) {
u32 delay = 0;
if (spicfg->odd_parity)
spifmt |= SPIFMT_ODD_PARITY_MASK;
if (spicfg->parity_enable)
spifmt |= SPIFMT_PARITYENA_MASK;
if (spicfg->timer_disable) {
spifmt |= SPIFMT_DISTIMER_MASK;
} else {
delay |= (spicfg->c2tdelay << SPIDELAY_C2TDELAY_SHIFT)
& SPIDELAY_C2TDELAY_MASK;
delay |= (spicfg->t2cdelay << SPIDELAY_T2CDELAY_SHIFT)
& SPIDELAY_T2CDELAY_MASK;
}
if (spi->mode & SPI_READY) {
spifmt |= SPIFMT_WAITENA_MASK;
delay |= (spicfg->t2edelay << SPIDELAY_T2EDELAY_SHIFT)
& SPIDELAY_T2EDELAY_MASK;
delay |= (spicfg->c2edelay << SPIDELAY_C2EDELAY_SHIFT)
& SPIDELAY_C2EDELAY_MASK;
}
iowrite32(delay, dspi->base + SPIDELAY);
}
iowrite32(spifmt, dspi->base + SPIFMT0);
return 0;
}
static int davinci_spi_of_setup(struct spi_device *spi)
{
struct davinci_spi_config *spicfg = spi->controller_data;
struct device_node *np = spi->dev.of_node;
u32 prop;
if (spicfg == NULL && np) {
spicfg = kzalloc(sizeof(*spicfg), GFP_KERNEL);
if (!spicfg)
return -ENOMEM;
*spicfg = davinci_spi_default_cfg;
/* override with dt configured values */
if (!of_property_read_u32(np, "ti,spi-wdelay", &prop))
spicfg->wdelay = (u8)prop;
spi->controller_data = spicfg;
}
return 0;
}
/**
* davinci_spi_setup - This functions will set default transfer method
* @spi: spi device on which data transfer to be done
*
* This functions sets the default transfer method.
*/
static int davinci_spi_setup(struct spi_device *spi)
{
int retval = 0;
struct davinci_spi *dspi;
struct davinci_spi_platform_data *pdata;
struct spi_master *master = spi->master;
struct device_node *np = spi->dev.of_node;
bool internal_cs = true;
dspi = spi_master_get_devdata(spi->master);
pdata = &dspi->pdata;
if (!(spi->mode & SPI_NO_CS)) {
if (np && (master->cs_gpios != NULL) && (spi->cs_gpio >= 0)) {
retval = gpio_direction_output(
spi->cs_gpio, !(spi->mode & SPI_CS_HIGH));
internal_cs = false;
} else if (pdata->chip_sel &&
spi->chip_select < pdata->num_chipselect &&
pdata->chip_sel[spi->chip_select] != SPI_INTERN_CS) {
spi->cs_gpio = pdata->chip_sel[spi->chip_select];
retval = gpio_direction_output(
spi->cs_gpio, !(spi->mode & SPI_CS_HIGH));
internal_cs = false;
}
if (retval) {
dev_err(&spi->dev, "GPIO %d setup failed (%d)\n",
spi->cs_gpio, retval);
return retval;
}
if (internal_cs)
set_io_bits(dspi->base + SPIPC0, 1 << spi->chip_select);
}
if (spi->mode & SPI_READY)
set_io_bits(dspi->base + SPIPC0, SPIPC0_SPIENA_MASK);
if (spi->mode & SPI_LOOP)
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK);
else
clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_LOOPBACK_MASK);
return davinci_spi_of_setup(spi);
}
static void davinci_spi_cleanup(struct spi_device *spi)
{
struct davinci_spi_config *spicfg = spi->controller_data;
spi->controller_data = NULL;
if (spi->dev.of_node)
kfree(spicfg);
}
static int davinci_spi_check_error(struct davinci_spi *dspi, int int_status)
{
struct device *sdev = dspi->bitbang.master->dev.parent;
if (int_status & SPIFLG_TIMEOUT_MASK) {
dev_err(sdev, "SPI Time-out Error\n");
return -ETIMEDOUT;
}
if (int_status & SPIFLG_DESYNC_MASK) {
dev_err(sdev, "SPI Desynchronization Error\n");
return -EIO;
}
if (int_status & SPIFLG_BITERR_MASK) {
dev_err(sdev, "SPI Bit error\n");
return -EIO;
}
if (dspi->version == SPI_VERSION_2) {
if (int_status & SPIFLG_DLEN_ERR_MASK) {
dev_err(sdev, "SPI Data Length Error\n");
return -EIO;
}
if (int_status & SPIFLG_PARERR_MASK) {
dev_err(sdev, "SPI Parity Error\n");
return -EIO;
}
if (int_status & SPIFLG_OVRRUN_MASK) {
dev_err(sdev, "SPI Data Overrun error\n");
return -EIO;
}
if (int_status & SPIFLG_BUF_INIT_ACTIVE_MASK) {
dev_err(sdev, "SPI Buffer Init Active\n");
return -EBUSY;
}
}
return 0;
}
/**
* davinci_spi_process_events - check for and handle any SPI controller events
* @dspi: the controller data
*
* This function will check the SPIFLG register and handle any events that are
* detected there
*/
static int davinci_spi_process_events(struct davinci_spi *dspi)
{
u32 buf, status, errors = 0, spidat1;
buf = ioread32(dspi->base + SPIBUF);
if (dspi->rcount > 0 && !(buf & SPIBUF_RXEMPTY_MASK)) {
dspi->get_rx(buf & 0xFFFF, dspi);
dspi->rcount--;
}
status = ioread32(dspi->base + SPIFLG);
if (unlikely(status & SPIFLG_ERROR_MASK)) {
errors = status & SPIFLG_ERROR_MASK;
goto out;
}
if (dspi->wcount > 0 && !(buf & SPIBUF_TXFULL_MASK)) {
spidat1 = ioread32(dspi->base + SPIDAT1);
dspi->wcount--;
spidat1 &= ~0xFFFF;
spidat1 |= 0xFFFF & dspi->get_tx(dspi);
iowrite32(spidat1, dspi->base + SPIDAT1);
}
out:
return errors;
}
static void davinci_spi_dma_rx_callback(void *data)
{
struct davinci_spi *dspi = (struct davinci_spi *)data;
dspi->rcount = 0;
if (!dspi->wcount && !dspi->rcount)
complete(&dspi->done);
}
static void davinci_spi_dma_tx_callback(void *data)
{
struct davinci_spi *dspi = (struct davinci_spi *)data;
dspi->wcount = 0;
if (!dspi->wcount && !dspi->rcount)
complete(&dspi->done);
}
/**
* davinci_spi_bufs - functions which will handle transfer data
* @spi: spi device on which data transfer to be done
* @t: spi transfer in which transfer info is filled
*
* This function will put data to be transferred into data register
* of SPI controller and then wait until the completion will be marked
* by the IRQ Handler.
*/
static int davinci_spi_bufs(struct spi_device *spi, struct spi_transfer *t)
{
struct davinci_spi *dspi;
int data_type, ret = -ENOMEM;
u32 tx_data, spidat1;
u32 errors = 0;
struct davinci_spi_config *spicfg;
struct davinci_spi_platform_data *pdata;
unsigned uninitialized_var(rx_buf_count);
void *dummy_buf = NULL;
struct scatterlist sg_rx, sg_tx;
dspi = spi_master_get_devdata(spi->master);
pdata = &dspi->pdata;
spicfg = (struct davinci_spi_config *)spi->controller_data;
if (!spicfg)
spicfg = &davinci_spi_default_cfg;
/* convert len to words based on bits_per_word */
data_type = dspi->bytes_per_word[spi->chip_select];
dspi->tx = t->tx_buf;
dspi->rx = t->rx_buf;
dspi->wcount = t->len / data_type;
dspi->rcount = dspi->wcount;
spidat1 = ioread32(dspi->base + SPIDAT1);
clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK);
reinit_completion(&dspi->done);
if (spicfg->io_type == SPI_IO_TYPE_INTR)
set_io_bits(dspi->base + SPIINT, SPIINT_MASKINT);
if (spicfg->io_type != SPI_IO_TYPE_DMA) {
/* start the transfer */
dspi->wcount--;
tx_data = dspi->get_tx(dspi);
spidat1 &= 0xFFFF0000;
spidat1 |= tx_data & 0xFFFF;
iowrite32(spidat1, dspi->base + SPIDAT1);
} else {
struct dma_slave_config dma_rx_conf = {
.direction = DMA_DEV_TO_MEM,
.src_addr = (unsigned long)dspi->pbase + SPIBUF,
.src_addr_width = data_type,
.src_maxburst = 1,
};
struct dma_slave_config dma_tx_conf = {
.direction = DMA_MEM_TO_DEV,
.dst_addr = (unsigned long)dspi->pbase + SPIDAT1,
.dst_addr_width = data_type,
.dst_maxburst = 1,
};
struct dma_async_tx_descriptor *rxdesc;
struct dma_async_tx_descriptor *txdesc;
void *buf;
dummy_buf = kzalloc(t->len, GFP_KERNEL);
if (!dummy_buf)
goto err_alloc_dummy_buf;
dmaengine_slave_config(dspi->dma_rx, &dma_rx_conf);
dmaengine_slave_config(dspi->dma_tx, &dma_tx_conf);
sg_init_table(&sg_rx, 1);
if (!t->rx_buf)
buf = dummy_buf;
else
buf = t->rx_buf;
t->rx_dma = dma_map_single(&spi->dev, buf,
t->len, DMA_FROM_DEVICE);
if (dma_mapping_error(&spi->dev, !t->rx_dma)) {
ret = -EFAULT;
goto err_rx_map;
}
sg_dma_address(&sg_rx) = t->rx_dma;
sg_dma_len(&sg_rx) = t->len;
sg_init_table(&sg_tx, 1);
if (!t->tx_buf)
buf = dummy_buf;
else
buf = (void *)t->tx_buf;
t->tx_dma = dma_map_single(&spi->dev, buf,
t->len, DMA_TO_DEVICE);
if (dma_mapping_error(&spi->dev, t->tx_dma)) {
ret = -EFAULT;
goto err_tx_map;
}
sg_dma_address(&sg_tx) = t->tx_dma;
sg_dma_len(&sg_tx) = t->len;
rxdesc = dmaengine_prep_slave_sg(dspi->dma_rx,
&sg_rx, 1, DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!rxdesc)
goto err_desc;
txdesc = dmaengine_prep_slave_sg(dspi->dma_tx,
&sg_tx, 1, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!txdesc)
goto err_desc;
rxdesc->callback = davinci_spi_dma_rx_callback;
rxdesc->callback_param = (void *)dspi;
txdesc->callback = davinci_spi_dma_tx_callback;
txdesc->callback_param = (void *)dspi;
if (pdata->cshold_bug)
iowrite16(spidat1 >> 16, dspi->base + SPIDAT1 + 2);
dmaengine_submit(rxdesc);
dmaengine_submit(txdesc);
dma_async_issue_pending(dspi->dma_rx);
dma_async_issue_pending(dspi->dma_tx);
set_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN);
}
/* Wait for the transfer to complete */
if (spicfg->io_type != SPI_IO_TYPE_POLL) {
if (wait_for_completion_timeout(&dspi->done, HZ) == 0)
errors = SPIFLG_TIMEOUT_MASK;
} else {
while (dspi->rcount > 0 || dspi->wcount > 0) {
errors = davinci_spi_process_events(dspi);
if (errors)
break;
cpu_relax();
}
}
clear_io_bits(dspi->base + SPIINT, SPIINT_MASKALL);
if (spicfg->io_type == SPI_IO_TYPE_DMA) {
clear_io_bits(dspi->base + SPIINT, SPIINT_DMA_REQ_EN);
dma_unmap_single(&spi->dev, t->rx_dma,
t->len, DMA_FROM_DEVICE);
dma_unmap_single(&spi->dev, t->tx_dma,
t->len, DMA_TO_DEVICE);
kfree(dummy_buf);
}
clear_io_bits(dspi->base + SPIGCR1, SPIGCR1_SPIENA_MASK);
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);
/*
* Check for bit error, desync error,parity error,timeout error and
* receive overflow errors
*/
if (errors) {
ret = davinci_spi_check_error(dspi, errors);
WARN(!ret, "%s: error reported but no error found!\n",
dev_name(&spi->dev));
return ret;
}
if (dspi->rcount != 0 || dspi->wcount != 0) {
dev_err(&spi->dev, "SPI data transfer error\n");
return -EIO;
}
return t->len;
err_desc:
dma_unmap_single(&spi->dev, t->tx_dma, t->len, DMA_TO_DEVICE);
err_tx_map:
dma_unmap_single(&spi->dev, t->rx_dma, t->len, DMA_FROM_DEVICE);
err_rx_map:
kfree(dummy_buf);
err_alloc_dummy_buf:
return ret;
}
/**
* dummy_thread_fn - dummy thread function
* @irq: IRQ number for this SPI Master
* @context_data: structure for SPI Master controller davinci_spi
*
* This is to satisfy the request_threaded_irq() API so that the irq
* handler is called in interrupt context.
*/
static irqreturn_t dummy_thread_fn(s32 irq, void *data)
{
return IRQ_HANDLED;
}
/**
* davinci_spi_irq - Interrupt handler for SPI Master Controller
* @irq: IRQ number for this SPI Master
* @context_data: structure for SPI Master controller davinci_spi
*
* ISR will determine that interrupt arrives either for READ or WRITE command.
* According to command it will do the appropriate action. It will check
* transfer length and if it is not zero then dispatch transfer command again.
* If transfer length is zero then it will indicate the COMPLETION so that
* davinci_spi_bufs function can go ahead.
*/
static irqreturn_t davinci_spi_irq(s32 irq, void *data)
{
struct davinci_spi *dspi = data;
int status;
status = davinci_spi_process_events(dspi);
if (unlikely(status != 0))
clear_io_bits(dspi->base + SPIINT, SPIINT_MASKINT);
if ((!dspi->rcount && !dspi->wcount) || status)
complete(&dspi->done);
return IRQ_HANDLED;
}
static int davinci_spi_request_dma(struct davinci_spi *dspi)
{
struct device *sdev = dspi->bitbang.master->dev.parent;
dspi->dma_rx = dma_request_chan(sdev, "rx");
if (IS_ERR(dspi->dma_rx))
return PTR_ERR(dspi->dma_rx);
dspi->dma_tx = dma_request_chan(sdev, "tx");
if (IS_ERR(dspi->dma_tx)) {
dma_release_channel(dspi->dma_rx);
return PTR_ERR(dspi->dma_tx);
}
return 0;
}
#if defined(CONFIG_OF)
/* OF SPI data structure */
struct davinci_spi_of_data {
u8 version;
u8 prescaler_limit;
};
static const struct davinci_spi_of_data dm6441_spi_data = {
.version = SPI_VERSION_1,
.prescaler_limit = 2,
};
static const struct davinci_spi_of_data da830_spi_data = {
.version = SPI_VERSION_2,
.prescaler_limit = 2,
};
static const struct davinci_spi_of_data keystone_spi_data = {
.version = SPI_VERSION_1,
.prescaler_limit = 0,
};
static const struct of_device_id davinci_spi_of_match[] = {
{
.compatible = "ti,dm6441-spi",
.data = &dm6441_spi_data,
},
{
.compatible = "ti,da830-spi",
.data = &da830_spi_data,
},
{
.compatible = "ti,keystone-spi",
.data = &keystone_spi_data,
},
{ },
};
MODULE_DEVICE_TABLE(of, davinci_spi_of_match);
/**
* spi_davinci_get_pdata - Get platform data from DTS binding
* @pdev: ptr to platform data
* @dspi: ptr to driver data
*
* Parses and populates pdata in dspi from device tree bindings.
*
* NOTE: Not all platform data params are supported currently.
*/
static int spi_davinci_get_pdata(struct platform_device *pdev,
struct davinci_spi *dspi)
{
struct device_node *node = pdev->dev.of_node;
struct davinci_spi_of_data *spi_data;
struct davinci_spi_platform_data *pdata;
unsigned int num_cs, intr_line = 0;
const struct of_device_id *match;
pdata = &dspi->pdata;
match = of_match_device(davinci_spi_of_match, &pdev->dev);
if (!match)
return -ENODEV;
spi_data = (struct davinci_spi_of_data *)match->data;
pdata->version = spi_data->version;
pdata->prescaler_limit = spi_data->prescaler_limit;
/*
* default num_cs is 1 and all chipsel are internal to the chip
* indicated by chip_sel being NULL or cs_gpios being NULL or
* set to -ENOENT. num-cs includes internal as well as gpios.
* indicated by chip_sel being NULL. GPIO based CS is not
* supported yet in DT bindings.
*/
num_cs = 1;
of_property_read_u32(node, "num-cs", &num_cs);
pdata->num_chipselect = num_cs;
of_property_read_u32(node, "ti,davinci-spi-intr-line", &intr_line);
pdata->intr_line = intr_line;
return 0;
}
#else
static struct davinci_spi_platform_data
*spi_davinci_get_pdata(struct platform_device *pdev,
struct davinci_spi *dspi)
{
return -ENODEV;
}
#endif
/**
* davinci_spi_probe - probe function for SPI Master Controller
* @pdev: platform_device structure which contains plateform specific data
*
* According to Linux Device Model this function will be invoked by Linux
* with platform_device struct which contains the device specific info.
* This function will map the SPI controller's memory, register IRQ,
* Reset SPI controller and setting its registers to default value.
* It will invoke spi_bitbang_start to create work queue so that client driver
* can register transfer method to work queue.
*/
static int davinci_spi_probe(struct platform_device *pdev)
{
struct spi_master *master;
struct davinci_spi *dspi;
struct davinci_spi_platform_data *pdata;
struct resource *r;
int ret = 0;
u32 spipc0;
master = spi_alloc_master(&pdev->dev, sizeof(struct davinci_spi));
if (master == NULL) {
ret = -ENOMEM;
goto err;
}
platform_set_drvdata(pdev, master);
dspi = spi_master_get_devdata(master);
if (dev_get_platdata(&pdev->dev)) {
pdata = dev_get_platdata(&pdev->dev);
dspi->pdata = *pdata;
} else {
/* update dspi pdata with that from the DT */
ret = spi_davinci_get_pdata(pdev, dspi);
if (ret < 0)
goto free_master;
}
/* pdata in dspi is now updated and point pdata to that */
pdata = &dspi->pdata;
dspi->bytes_per_word = devm_kzalloc(&pdev->dev,
sizeof(*dspi->bytes_per_word) *
pdata->num_chipselect, GFP_KERNEL);
if (dspi->bytes_per_word == NULL) {
ret = -ENOMEM;
goto free_master;
}
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (r == NULL) {
ret = -ENOENT;
goto free_master;
}
dspi->pbase = r->start;
dspi->base = devm_ioremap_resource(&pdev->dev, r);
if (IS_ERR(dspi->base)) {
ret = PTR_ERR(dspi->base);
goto free_master;
}
ret = platform_get_irq(pdev, 0);
if (ret == 0)
ret = -EINVAL;
if (ret < 0)
goto free_master;
dspi->irq = ret;
ret = devm_request_threaded_irq(&pdev->dev, dspi->irq, davinci_spi_irq,
dummy_thread_fn, 0, dev_name(&pdev->dev), dspi);
if (ret)
goto free_master;
dspi->bitbang.master = master;
dspi->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(dspi->clk)) {
ret = -ENODEV;
goto free_master;
}
clk_prepare_enable(dspi->clk);
master->dev.of_node = pdev->dev.of_node;
master->bus_num = pdev->id;
master->num_chipselect = pdata->num_chipselect;
master->bits_per_word_mask = SPI_BPW_RANGE_MASK(2, 16);
master->setup = davinci_spi_setup;
master->cleanup = davinci_spi_cleanup;
dspi->bitbang.chipselect = davinci_spi_chipselect;
dspi->bitbang.setup_transfer = davinci_spi_setup_transfer;
dspi->prescaler_limit = pdata->prescaler_limit;
dspi->version = pdata->version;
dspi->bitbang.flags = SPI_NO_CS | SPI_LSB_FIRST | SPI_LOOP;
if (dspi->version == SPI_VERSION_2)
dspi->bitbang.flags |= SPI_READY;
if (pdev->dev.of_node) {
int i;
for (i = 0; i < pdata->num_chipselect; i++) {
int cs_gpio = of_get_named_gpio(pdev->dev.of_node,
"cs-gpios", i);
if (cs_gpio == -EPROBE_DEFER) {
ret = cs_gpio;
goto free_clk;
}
if (gpio_is_valid(cs_gpio)) {
ret = devm_gpio_request(&pdev->dev, cs_gpio,
dev_name(&pdev->dev));
if (ret)
goto free_clk;
}
}
}
dspi->bitbang.txrx_bufs = davinci_spi_bufs;
ret = davinci_spi_request_dma(dspi);
if (ret == -EPROBE_DEFER) {
goto free_clk;
} else if (ret) {
dev_info(&pdev->dev, "DMA is not supported (%d)\n", ret);
dspi->dma_rx = NULL;
dspi->dma_tx = NULL;
}
dspi->get_rx = davinci_spi_rx_buf_u8;
dspi->get_tx = davinci_spi_tx_buf_u8;
init_completion(&dspi->done);
/* Reset In/OUT SPI module */
iowrite32(0, dspi->base + SPIGCR0);
udelay(100);
iowrite32(1, dspi->base + SPIGCR0);
/* Set up SPIPC0. CS and ENA init is done in davinci_spi_setup */
spipc0 = SPIPC0_DIFUN_MASK | SPIPC0_DOFUN_MASK | SPIPC0_CLKFUN_MASK;
iowrite32(spipc0, dspi->base + SPIPC0);
if (pdata->intr_line)
iowrite32(SPI_INTLVL_1, dspi->base + SPILVL);
else
iowrite32(SPI_INTLVL_0, dspi->base + SPILVL);
iowrite32(CS_DEFAULT, dspi->base + SPIDEF);
/* master mode default */
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_CLKMOD_MASK);
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_MASTER_MASK);
set_io_bits(dspi->base + SPIGCR1, SPIGCR1_POWERDOWN_MASK);
ret = spi_bitbang_start(&dspi->bitbang);
if (ret)
goto free_dma;
dev_info(&pdev->dev, "Controller at 0x%p\n", dspi->base);
return ret;
free_dma:
if (dspi->dma_rx) {
dma_release_channel(dspi->dma_rx);
dma_release_channel(dspi->dma_tx);
}
free_clk:
clk_disable_unprepare(dspi->clk);
free_master:
spi_master_put(master);
err:
return ret;
}
/**
* davinci_spi_remove - remove function for SPI Master Controller
* @pdev: platform_device structure which contains plateform specific data
*
* This function will do the reverse action of davinci_spi_probe function
* It will free the IRQ and SPI controller's memory region.
* It will also call spi_bitbang_stop to destroy the work queue which was
* created by spi_bitbang_start.
*/
static int davinci_spi_remove(struct platform_device *pdev)
{
struct davinci_spi *dspi;
struct spi_master *master;
master = platform_get_drvdata(pdev);
dspi = spi_master_get_devdata(master);
spi_bitbang_stop(&dspi->bitbang);
clk_disable_unprepare(dspi->clk);
spi_master_put(master);
if (dspi->dma_rx) {
dma_release_channel(dspi->dma_rx);
dma_release_channel(dspi->dma_tx);
}
return 0;
}
static struct platform_driver davinci_spi_driver = {
.driver = {
.name = "spi_davinci",
.of_match_table = of_match_ptr(davinci_spi_of_match),
},
.probe = davinci_spi_probe,
.remove = davinci_spi_remove,
};
module_platform_driver(davinci_spi_driver);
MODULE_DESCRIPTION("TI DaVinci SPI Master Controller Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/browser/ui/views/app_list/win/app_list_controller_delegate_win.h | 1077 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_
#define CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_
#include "chrome/browser/ui/app_list/app_list_controller_delegate_views.h"
// Windows specific configuration and behaviour for the AppList.
class AppListControllerDelegateWin : public AppListControllerDelegateViews {
public:
explicit AppListControllerDelegateWin(AppListServiceViews* service);
virtual ~AppListControllerDelegateWin();
// AppListControllerDelegate overrides:
virtual bool ForceNativeDesktop() const OVERRIDE;
virtual gfx::ImageSkia GetWindowIcon() OVERRIDE;
private:
// AppListcontrollerDelegateImpl:
virtual void FillLaunchParams(AppLaunchParams* params) OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(AppListControllerDelegateWin);
};
#endif // CHROME_BROWSER_UI_VIEWS_APP_LIST_WIN_APP_LIST_CONTROLLER_DELEGATE_WIN_H_
| gpl-3.0 |
bonzini/seabios | src/cdrom.c | 9412 | // Support for booting from cdroms (the "El Torito" spec).
//
// Copyright (C) 2008,2009 Kevin O'Connor <[email protected]>
// Copyright (C) 2002 MandrakeSoft S.A.
//
// This file may be distributed under the terms of the GNU LGPLv3 license.
#include "disk.h" // cdrom_13
#include "util.h" // memset
#include "bregs.h" // struct bregs
#include "biosvar.h" // GET_EBDA
#include "ata.h" // ATA_CMD_REQUEST_SENSE
#include "blockcmd.h" // CDB_CMD_REQUEST_SENSE
/****************************************************************
* CD emulation
****************************************************************/
struct drive_s *cdemu_drive_gf VAR16VISIBLE;
static int
cdemu_read(struct disk_op_s *op)
{
u16 ebda_seg = get_ebda_seg();
struct drive_s *drive_g;
drive_g = GLOBALFLAT2GLOBAL(GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf));
struct disk_op_s dop;
dop.drive_g = drive_g;
dop.command = op->command;
dop.lba = GET_EBDA2(ebda_seg, cdemu.ilba) + op->lba / 4;
int count = op->count;
op->count = 0;
u8 *cdbuf_fl = GET_GLOBAL(bounce_buf_fl);
if (op->lba & 3) {
// Partial read of first block.
dop.count = 1;
dop.buf_fl = cdbuf_fl;
int ret = process_op(&dop);
if (ret)
return ret;
u8 thiscount = 4 - (op->lba & 3);
if (thiscount > count)
thiscount = count;
count -= thiscount;
memcpy_fl(op->buf_fl, cdbuf_fl + (op->lba & 3) * 512, thiscount * 512);
op->buf_fl += thiscount * 512;
op->count += thiscount;
dop.lba++;
}
if (count > 3) {
// Read n number of regular blocks.
dop.count = count / 4;
dop.buf_fl = op->buf_fl;
int ret = process_op(&dop);
op->count += dop.count * 4;
if (ret)
return ret;
u8 thiscount = count & ~3;
count &= 3;
op->buf_fl += thiscount * 512;
dop.lba += thiscount / 4;
}
if (count) {
// Partial read on last block.
dop.count = 1;
dop.buf_fl = cdbuf_fl;
int ret = process_op(&dop);
if (ret)
return ret;
u8 thiscount = count;
memcpy_fl(op->buf_fl, cdbuf_fl, thiscount * 512);
op->count += thiscount;
}
return DISK_RET_SUCCESS;
}
int
process_cdemu_op(struct disk_op_s *op)
{
if (!CONFIG_CDROM_EMU)
return 0;
switch (op->command) {
case CMD_READ:
return cdemu_read(op);
case CMD_WRITE:
case CMD_FORMAT:
return DISK_RET_EWRITEPROTECT;
case CMD_VERIFY:
case CMD_RESET:
case CMD_SEEK:
case CMD_ISREADY:
return DISK_RET_SUCCESS;
default:
op->count = 0;
return DISK_RET_EPARAM;
}
}
void
cdemu_setup(void)
{
if (!CONFIG_CDROM_EMU)
return;
if (!CDCount)
return;
if (bounce_buf_init() < 0)
return;
struct drive_s *drive_g = malloc_fseg(sizeof(*drive_g));
if (!drive_g) {
warn_noalloc();
free(drive_g);
return;
}
cdemu_drive_gf = drive_g;
memset(drive_g, 0, sizeof(*drive_g));
drive_g->type = DTYPE_CDEMU;
drive_g->blksize = DISK_SECTOR_SIZE;
drive_g->sectors = (u64)-1;
}
struct eltorito_s {
u8 size;
u8 media;
u8 emulated_drive;
u8 controller_index;
u32 ilba;
u16 device_spec;
u16 buffer_segment;
u16 load_segment;
u16 sector_count;
u8 cylinders;
u8 sectors;
u8 heads;
};
#define SET_INT13ET(regs,var,val) \
SET_FARVAR((regs)->ds, ((struct eltorito_s*)((regs)->si+0))->var, (val))
// ElTorito - Terminate disk emu
void
cdemu_134b(struct bregs *regs)
{
// FIXME ElTorito Hardcoded
u16 ebda_seg = get_ebda_seg();
SET_INT13ET(regs, size, 0x13);
SET_INT13ET(regs, media, GET_EBDA2(ebda_seg, cdemu.media));
SET_INT13ET(regs, emulated_drive
, GET_EBDA2(ebda_seg, cdemu.emulated_extdrive));
struct drive_s *drive_gf = GET_EBDA2(ebda_seg, cdemu.emulated_drive_gf);
u8 cntl_id = 0;
if (drive_gf)
cntl_id = GET_GLOBALFLAT(drive_gf->cntl_id);
SET_INT13ET(regs, controller_index, cntl_id / 2);
SET_INT13ET(regs, device_spec, cntl_id % 2);
SET_INT13ET(regs, ilba, GET_EBDA2(ebda_seg, cdemu.ilba));
SET_INT13ET(regs, buffer_segment, GET_EBDA2(ebda_seg, cdemu.buffer_segment));
SET_INT13ET(regs, load_segment, GET_EBDA2(ebda_seg, cdemu.load_segment));
SET_INT13ET(regs, sector_count, GET_EBDA2(ebda_seg, cdemu.sector_count));
SET_INT13ET(regs, cylinders, GET_EBDA2(ebda_seg, cdemu.lchs.cylinders));
SET_INT13ET(regs, sectors, GET_EBDA2(ebda_seg, cdemu.lchs.spt));
SET_INT13ET(regs, heads, GET_EBDA2(ebda_seg, cdemu.lchs.heads));
// If we have to terminate emulation
if (regs->al == 0x00) {
// FIXME ElTorito Various. Should be handled accordingly to spec
SET_EBDA2(ebda_seg, cdemu.active, 0x00); // bye bye
// XXX - update floppy/hd count.
}
disk_ret(regs, DISK_RET_SUCCESS);
}
/****************************************************************
* CD booting
****************************************************************/
int
cdrom_boot(struct drive_s *drive_g)
{
struct disk_op_s dop;
int cdid = getDriveId(EXTTYPE_CD, drive_g);
memset(&dop, 0, sizeof(dop));
dop.drive_g = drive_g;
if (!dop.drive_g || cdid < 0)
return 1;
int ret = scsi_is_ready(&dop);
if (ret)
dprintf(1, "scsi_is_ready returned %d\n", ret);
// Read the Boot Record Volume Descriptor
u8 buffer[2048];
dop.lba = 0x11;
dop.count = 1;
dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);
ret = cdb_read(&dop);
if (ret)
return 3;
// Validity checks
if (buffer[0])
return 4;
if (strcmp((char*)&buffer[1], "CD001\001EL TORITO SPECIFICATION") != 0)
return 5;
// ok, now we calculate the Boot catalog address
u32 lba = *(u32*)&buffer[0x47];
// And we read the Boot Catalog
dop.lba = lba;
dop.count = 1;
ret = cdb_read(&dop);
if (ret)
return 7;
// Validation entry
if (buffer[0x00] != 0x01)
return 8; // Header
if (buffer[0x01] != 0x00)
return 9; // Platform
if (buffer[0x1E] != 0x55)
return 10; // key 1
if (buffer[0x1F] != 0xAA)
return 10; // key 2
// Initial/Default Entry
if (buffer[0x20] != 0x88)
return 11; // Bootable
u16 ebda_seg = get_ebda_seg();
u8 media = buffer[0x21];
SET_EBDA2(ebda_seg, cdemu.media, media);
SET_EBDA2(ebda_seg, cdemu.emulated_drive_gf, dop.drive_g);
u16 boot_segment = *(u16*)&buffer[0x22];
if (!boot_segment)
boot_segment = 0x07C0;
SET_EBDA2(ebda_seg, cdemu.load_segment, boot_segment);
SET_EBDA2(ebda_seg, cdemu.buffer_segment, 0x0000);
u16 nbsectors = *(u16*)&buffer[0x26];
SET_EBDA2(ebda_seg, cdemu.sector_count, nbsectors);
lba = *(u32*)&buffer[0x28];
SET_EBDA2(ebda_seg, cdemu.ilba, lba);
// And we read the image in memory
dop.lba = lba;
dop.count = DIV_ROUND_UP(nbsectors, 4);
dop.buf_fl = MAKE_FLATPTR(boot_segment, 0);
ret = cdb_read(&dop);
if (ret)
return 12;
if (media == 0) {
// No emulation requested - return success.
SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, EXTSTART_CD + cdid);
return 0;
}
// Emulation of a floppy/harddisk requested
if (! CONFIG_CDROM_EMU || !cdemu_drive_gf)
return 13;
// Set emulated drive id and increase bios installed hardware
// number of devices
if (media < 4) {
// Floppy emulation
SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x00);
// XXX - get and set actual floppy count.
SETBITS_BDA(equipment_list_flags, 0x41);
switch (media) {
case 0x01: // 1.2M floppy
SET_EBDA2(ebda_seg, cdemu.lchs.spt, 15);
SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);
SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);
break;
case 0x02: // 1.44M floppy
SET_EBDA2(ebda_seg, cdemu.lchs.spt, 18);
SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);
SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);
break;
case 0x03: // 2.88M floppy
SET_EBDA2(ebda_seg, cdemu.lchs.spt, 36);
SET_EBDA2(ebda_seg, cdemu.lchs.cylinders, 80);
SET_EBDA2(ebda_seg, cdemu.lchs.heads, 2);
break;
}
} else {
// Harddrive emulation
SET_EBDA2(ebda_seg, cdemu.emulated_extdrive, 0x80);
SET_BDA(hdcount, GET_BDA(hdcount) + 1);
// Peak at partition table to get chs.
struct mbr_s *mbr = (void*)0;
u8 sptcyl = GET_FARVAR(boot_segment, mbr->partitions[0].last.sptcyl);
u8 cyllow = GET_FARVAR(boot_segment, mbr->partitions[0].last.cyllow);
u8 heads = GET_FARVAR(boot_segment, mbr->partitions[0].last.heads);
SET_EBDA2(ebda_seg, cdemu.lchs.spt, sptcyl & 0x3f);
SET_EBDA2(ebda_seg, cdemu.lchs.cylinders
, ((sptcyl<<2)&0x300) + cyllow + 1);
SET_EBDA2(ebda_seg, cdemu.lchs.heads, heads + 1);
}
// everything is ok, so from now on, the emulation is active
SET_EBDA2(ebda_seg, cdemu.active, 0x01);
dprintf(6, "cdemu media=%d\n", media);
return 0;
}
| gpl-3.0 |
gnubila-france/linuxbrew | Library/Formula/gst-plugins-ugly.rb | 2650 | class GstPluginsUgly < Formula
desc "GStreamer plugins (well-supported, possibly problematic for distributors)"
homepage "https://gstreamer.freedesktop.org/"
url "https://gstreamer.freedesktop.org/src/gst-plugins-ugly/gst-plugins-ugly-1.8.0.tar.xz"
sha256 "53657ffb7d49ddc4ae40e3f52e56165db4c06eb016891debe2b6c0e9f134eb8c"
bottle do
sha256 "de81ae62cc34b67d54cb632dce97fb108e4dff3cf839cf99703c23415e64fa8b" => :el_capitan
sha256 "5b471670878ccc08926394d973d3ddb5904921e7739ef11bb0f4fe3c67b77f09" => :yosemite
sha256 "32c4fc7c2fa4a60390f4346f69b9f4d1bf3a260c94400319d122d2b4c634d5ad" => :mavericks
end
head do
url "https://anongit.freedesktop.org/git/gstreamer/gst-plugins-ugly.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "gst-plugins-base"
# The set of optional dependencies is based on the intersection of
# gst-plugins-ugly-0.10.17/REQUIREMENTS and Homebrew formulae
depends_on "dirac" => :optional
depends_on "mad" => :optional
depends_on "jpeg" => :optional
depends_on "libvorbis" => :optional
depends_on "cdparanoia" => :optional
depends_on "lame" => :optional
depends_on "two-lame" => :optional
depends_on "libshout" => :optional
depends_on "aalib" => :optional
depends_on "libcaca" => :optional
depends_on "libdvdread" => :optional
depends_on "libmpeg2" => :optional
depends_on "a52dec" => :optional
depends_on "liboil" => :optional
depends_on "flac" => :optional
depends_on "gtk+" => :optional
depends_on "pango" => :optional
depends_on "theora" => :optional
depends_on "libmms" => :optional
depends_on "x264" => :optional
depends_on "opencore-amr" => :optional
# Does not work with libcdio 0.9
def install
args = %W[
--prefix=#{prefix}
--mandir=#{man}
--disable-debug
--disable-dependency-tracking
]
if build.head?
ENV["NOCONFIGURE"] = "yes"
system "./autogen.sh"
end
if build.with? "opencore-amr"
# Fixes build error, missing includes.
# https://github.com/Homebrew/homebrew/issues/14078
nbcflags = `pkg-config --cflags opencore-amrnb`.chomp
wbcflags = `pkg-config --cflags opencore-amrwb`.chomp
ENV["AMRNB_CFLAGS"] = nbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrnb"
ENV["AMRWB_CFLAGS"] = wbcflags + "-I#{HOMEBREW_PREFIX}/include/opencore-amrwb"
else
args << "--disable-amrnb" << "--disable-amrwb"
end
system "./configure", *args
system "make"
system "make", "install"
end
end
| bsd-2-clause |
wastrachan/homebrew-cask | Casks/netbeans-java-se.rb | 426 | cask 'netbeans-java-se' do
version '8.2'
sha256 '91652f03d8abba0ae9d76a612ed909c9f82e4f138cbd510f5d3679280323011b'
url "https://download.netbeans.org/netbeans/#{version}/final/bundles/netbeans-#{version}-javase-macosx.dmg"
name 'NetBeans IDE for Java SE'
homepage 'https://netbeans.org/'
pkg "NetBeans #{version}.pkg"
uninstall pkgutil: 'org.netbeans.ide.*',
delete: '/Applications/NetBeans'
end
| bsd-2-clause |
go2ev-devteam/Gplus_2159_0801 | openplatform/sdk/os/kernel-2.6.32/drivers/usb/misc/idmouse.c | 12143 | /* Siemens ID Mouse driver v0.6
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
Copyright (C) 2004-5 by Florian 'Floe' Echtler <[email protected]>
and Andreas 'ad' Deresch <[email protected]>
Derived from the USB Skeleton driver 1.1,
Copyright (C) 2003 Greg Kroah-Hartman ([email protected])
Additional information provided by Martin Reising
<[email protected]>
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/usb.h>
/* image constants */
#define WIDTH 225
#define HEIGHT 289
#define HEADER "P5 225 289 255 "
#define IMGSIZE ((WIDTH * HEIGHT) + sizeof(HEADER)-1)
/* version information */
#define DRIVER_VERSION "0.6"
#define DRIVER_SHORT "idmouse"
#define DRIVER_AUTHOR "Florian 'Floe' Echtler <[email protected]>"
#define DRIVER_DESC "Siemens ID Mouse FingerTIP Sensor Driver"
/* minor number for misc USB devices */
#define USB_IDMOUSE_MINOR_BASE 132
/* vendor and device IDs */
#define ID_SIEMENS 0x0681
#define ID_IDMOUSE 0x0005
#define ID_CHERRY 0x0010
/* device ID table */
static struct usb_device_id idmouse_table[] = {
{USB_DEVICE(ID_SIEMENS, ID_IDMOUSE)}, /* Siemens ID Mouse (Professional) */
{USB_DEVICE(ID_SIEMENS, ID_CHERRY )}, /* Cherry FingerTIP ID Board */
{} /* terminating null entry */
};
/* sensor commands */
#define FTIP_RESET 0x20
#define FTIP_ACQUIRE 0x21
#define FTIP_RELEASE 0x22
#define FTIP_BLINK 0x23 /* LSB of value = blink pulse width */
#define FTIP_SCROLL 0x24
#define ftip_command(dev, command, value, index) \
usb_control_msg (dev->udev, usb_sndctrlpipe (dev->udev, 0), command, \
USB_TYPE_VENDOR | USB_RECIP_ENDPOINT | USB_DIR_OUT, value, index, NULL, 0, 1000)
MODULE_DEVICE_TABLE(usb, idmouse_table);
static DEFINE_MUTEX(open_disc_mutex);
/* structure to hold all of our device specific stuff */
struct usb_idmouse {
struct usb_device *udev; /* save off the usb device pointer */
struct usb_interface *interface; /* the interface for this device */
unsigned char *bulk_in_buffer; /* the buffer to receive data */
size_t bulk_in_size; /* the maximum bulk packet size */
size_t orig_bi_size; /* same as above, but reported by the device */
__u8 bulk_in_endpointAddr; /* the address of the bulk in endpoint */
int open; /* if the port is open or not */
int present; /* if the device is not disconnected */
struct mutex lock; /* locks this structure */
};
/* local function prototypes */
static ssize_t idmouse_read(struct file *file, char __user *buffer,
size_t count, loff_t * ppos);
static int idmouse_open(struct inode *inode, struct file *file);
static int idmouse_release(struct inode *inode, struct file *file);
static int idmouse_probe(struct usb_interface *interface,
const struct usb_device_id *id);
static void idmouse_disconnect(struct usb_interface *interface);
static int idmouse_suspend(struct usb_interface *intf, pm_message_t message);
static int idmouse_resume(struct usb_interface *intf);
/* file operation pointers */
static const struct file_operations idmouse_fops = {
.owner = THIS_MODULE,
.read = idmouse_read,
.open = idmouse_open,
.release = idmouse_release,
};
/* class driver information */
static struct usb_class_driver idmouse_class = {
.name = "idmouse%d",
.fops = &idmouse_fops,
.minor_base = USB_IDMOUSE_MINOR_BASE,
};
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver idmouse_driver = {
.name = DRIVER_SHORT,
.probe = idmouse_probe,
.disconnect = idmouse_disconnect,
.suspend = idmouse_suspend,
.resume = idmouse_resume,
.reset_resume = idmouse_resume,
.id_table = idmouse_table,
.supports_autosuspend = 1,
};
static int idmouse_create_image(struct usb_idmouse *dev)
{
int bytes_read;
int bulk_read;
int result;
memcpy(dev->bulk_in_buffer, HEADER, sizeof(HEADER)-1);
bytes_read = sizeof(HEADER)-1;
/* reset the device and set a fast blink rate */
result = ftip_command(dev, FTIP_RELEASE, 0, 0);
if (result < 0)
goto reset;
result = ftip_command(dev, FTIP_BLINK, 1, 0);
if (result < 0)
goto reset;
/* initialize the sensor - sending this command twice */
/* significantly reduces the rate of failed reads */
result = ftip_command(dev, FTIP_ACQUIRE, 0, 0);
if (result < 0)
goto reset;
result = ftip_command(dev, FTIP_ACQUIRE, 0, 0);
if (result < 0)
goto reset;
/* start the readout - sending this command twice */
/* presumably enables the high dynamic range mode */
result = ftip_command(dev, FTIP_RESET, 0, 0);
if (result < 0)
goto reset;
result = ftip_command(dev, FTIP_RESET, 0, 0);
if (result < 0)
goto reset;
/* loop over a blocking bulk read to get data from the device */
while (bytes_read < IMGSIZE) {
result = usb_bulk_msg (dev->udev,
usb_rcvbulkpipe (dev->udev, dev->bulk_in_endpointAddr),
dev->bulk_in_buffer + bytes_read,
dev->bulk_in_size, &bulk_read, 5000);
if (result < 0) {
/* Maybe this error was caused by the increased packet size? */
/* Reset to the original value and tell userspace to retry. */
if (dev->bulk_in_size != dev->orig_bi_size) {
dev->bulk_in_size = dev->orig_bi_size;
result = -EAGAIN;
}
break;
}
if (signal_pending(current)) {
result = -EINTR;
break;
}
bytes_read += bulk_read;
}
/* reset the device */
reset:
ftip_command(dev, FTIP_RELEASE, 0, 0);
/* check for valid image */
/* right border should be black (0x00) */
for (bytes_read = sizeof(HEADER)-1 + WIDTH-1; bytes_read < IMGSIZE; bytes_read += WIDTH)
if (dev->bulk_in_buffer[bytes_read] != 0x00)
return -EAGAIN;
/* lower border should be white (0xFF) */
for (bytes_read = IMGSIZE-WIDTH; bytes_read < IMGSIZE-1; bytes_read++)
if (dev->bulk_in_buffer[bytes_read] != 0xFF)
return -EAGAIN;
/* should be IMGSIZE == 65040 */
dbg("read %d bytes fingerprint data", bytes_read);
return result;
}
/* PM operations are nops as this driver does IO only during open() */
static int idmouse_suspend(struct usb_interface *intf, pm_message_t message)
{
return 0;
}
static int idmouse_resume(struct usb_interface *intf)
{
return 0;
}
static inline void idmouse_delete(struct usb_idmouse *dev)
{
kfree(dev->bulk_in_buffer);
kfree(dev);
}
static int idmouse_open(struct inode *inode, struct file *file)
{
struct usb_idmouse *dev;
struct usb_interface *interface;
int result;
/* get the interface from minor number and driver information */
interface = usb_find_interface (&idmouse_driver, iminor (inode));
if (!interface)
return -ENODEV;
mutex_lock(&open_disc_mutex);
/* get the device information block from the interface */
dev = usb_get_intfdata(interface);
if (!dev) {
mutex_unlock(&open_disc_mutex);
return -ENODEV;
}
/* lock this device */
mutex_lock(&dev->lock);
mutex_unlock(&open_disc_mutex);
/* check if already open */
if (dev->open) {
/* already open, so fail */
result = -EBUSY;
} else {
/* create a new image and check for success */
result = usb_autopm_get_interface(interface);
if (result)
goto error;
result = idmouse_create_image (dev);
if (result)
goto error;
usb_autopm_put_interface(interface);
/* increment our usage count for the driver */
++dev->open;
/* save our object in the file's private structure */
file->private_data = dev;
}
error:
/* unlock this device */
mutex_unlock(&dev->lock);
return result;
}
static int idmouse_release(struct inode *inode, struct file *file)
{
struct usb_idmouse *dev;
dev = file->private_data;
if (dev == NULL)
return -ENODEV;
mutex_lock(&open_disc_mutex);
/* lock our device */
mutex_lock(&dev->lock);
/* are we really open? */
if (dev->open <= 0) {
mutex_unlock(&dev->lock);
mutex_unlock(&open_disc_mutex);
return -ENODEV;
}
--dev->open;
if (!dev->present) {
/* the device was unplugged before the file was released */
mutex_unlock(&dev->lock);
mutex_unlock(&open_disc_mutex);
idmouse_delete(dev);
} else {
mutex_unlock(&dev->lock);
mutex_unlock(&open_disc_mutex);
}
return 0;
}
static ssize_t idmouse_read(struct file *file, char __user *buffer, size_t count,
loff_t * ppos)
{
struct usb_idmouse *dev = file->private_data;
int result;
/* lock this object */
mutex_lock(&dev->lock);
/* verify that the device wasn't unplugged */
if (!dev->present) {
mutex_unlock(&dev->lock);
return -ENODEV;
}
result = simple_read_from_buffer(buffer, count, ppos,
dev->bulk_in_buffer, IMGSIZE);
/* unlock the device */
mutex_unlock(&dev->lock);
return result;
}
static int idmouse_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_idmouse *dev;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int result;
/* check if we have gotten the data or the hid interface */
iface_desc = &interface->altsetting[0];
if (iface_desc->desc.bInterfaceClass != 0x0A)
return -ENODEV;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL)
return -ENOMEM;
mutex_init(&dev->lock);
dev->udev = udev;
dev->interface = interface;
/* set up the endpoint information - use only the first bulk-in endpoint */
endpoint = &iface_desc->endpoint[0].desc;
if (!dev->bulk_in_endpointAddr && usb_endpoint_is_bulk_in(endpoint)) {
/* we found a bulk in endpoint */
dev->orig_bi_size = le16_to_cpu(endpoint->wMaxPacketSize);
dev->bulk_in_size = 0x200; /* works _much_ faster */
dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
dev->bulk_in_buffer =
kmalloc(IMGSIZE + dev->bulk_in_size, GFP_KERNEL);
if (!dev->bulk_in_buffer) {
err("Unable to allocate input buffer.");
idmouse_delete(dev);
return -ENOMEM;
}
}
if (!(dev->bulk_in_endpointAddr)) {
err("Unable to find bulk-in endpoint.");
idmouse_delete(dev);
return -ENODEV;
}
/* allow device read, write and ioctl */
dev->present = 1;
/* we can register the device now, as it is ready */
usb_set_intfdata(interface, dev);
result = usb_register_dev(interface, &idmouse_class);
if (result) {
/* something prevented us from registering this device */
err("Unble to allocate minor number.");
usb_set_intfdata(interface, NULL);
idmouse_delete(dev);
return result;
}
/* be noisy */
dev_info(&interface->dev,"%s now attached\n",DRIVER_DESC);
return 0;
}
static void idmouse_disconnect(struct usb_interface *interface)
{
struct usb_idmouse *dev;
/* get device structure */
dev = usb_get_intfdata(interface);
/* give back our minor */
usb_deregister_dev(interface, &idmouse_class);
mutex_lock(&open_disc_mutex);
usb_set_intfdata(interface, NULL);
/* lock the device */
mutex_lock(&dev->lock);
mutex_unlock(&open_disc_mutex);
/* prevent device read, write and ioctl */
dev->present = 0;
/* if the device is opened, idmouse_release will clean this up */
if (!dev->open) {
mutex_unlock(&dev->lock);
idmouse_delete(dev);
} else {
/* unlock */
mutex_unlock(&dev->lock);
}
dev_info(&interface->dev, "disconnected\n");
}
static int __init usb_idmouse_init(void)
{
int result;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
/* register this driver with the USB subsystem */
result = usb_register(&idmouse_driver);
if (result)
err("Unable to register device (error %d).", result);
return result;
}
static void __exit usb_idmouse_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&idmouse_driver);
}
module_init(usb_idmouse_init);
module_exit(usb_idmouse_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Roquet87/SIGESRHI | vendor/apy/datagrid-bundle/APY/DataGridBundle/Resources/doc/columns_configuration/filters/input_filter.md | 532 | Input filter
============
This type of filter displays an input field.
A second input field is displayed if you select a range operator (between).
The two input fields are disabled if you select the `Is defined` and `Is not defined` operators.
### Additionnal attributes for a column annotation for a property
|Attribute|Type|Default value|Possible values|Description|
|:--:|:--|:--|:--|:--|
|inputType|string|text||Define the type of inputs. See [HTML5 input types](http://www.w3schools.com/html5/html5_form_input_types.asp)|
| mit |
koct9i/linux | arch/x86/kernel/head64.c | 13218 | // SPDX-License-Identifier: GPL-2.0
/*
* prepare to run common code
*
* Copyright (C) 2000 Andrea Arcangeli <[email protected]> SuSE
*/
#define DISABLE_BRANCH_PROFILING
/* cpu_feature_enabled() cannot be used this early */
#define USE_EARLY_PGTABLE_L5
#include <linux/init.h>
#include <linux/linkage.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/percpu.h>
#include <linux/start_kernel.h>
#include <linux/io.h>
#include <linux/memblock.h>
#include <linux/mem_encrypt.h>
#include <asm/processor.h>
#include <asm/proto.h>
#include <asm/smp.h>
#include <asm/setup.h>
#include <asm/desc.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include <asm/sections.h>
#include <asm/kdebug.h>
#include <asm/e820/api.h>
#include <asm/bios_ebda.h>
#include <asm/bootparam_utils.h>
#include <asm/microcode.h>
#include <asm/kasan.h>
#include <asm/fixmap.h>
/*
* Manage page tables very early on.
*/
extern pmd_t early_dynamic_pgts[EARLY_DYNAMIC_PAGE_TABLES][PTRS_PER_PMD];
static unsigned int __initdata next_early_pgt;
pmdval_t early_pmd_flags = __PAGE_KERNEL_LARGE & ~(_PAGE_GLOBAL | _PAGE_NX);
#ifdef CONFIG_X86_5LEVEL
unsigned int __pgtable_l5_enabled __ro_after_init;
unsigned int pgdir_shift __ro_after_init = 39;
EXPORT_SYMBOL(pgdir_shift);
unsigned int ptrs_per_p4d __ro_after_init = 1;
EXPORT_SYMBOL(ptrs_per_p4d);
#endif
#ifdef CONFIG_DYNAMIC_MEMORY_LAYOUT
unsigned long page_offset_base __ro_after_init = __PAGE_OFFSET_BASE_L4;
EXPORT_SYMBOL(page_offset_base);
unsigned long vmalloc_base __ro_after_init = __VMALLOC_BASE_L4;
EXPORT_SYMBOL(vmalloc_base);
unsigned long vmemmap_base __ro_after_init = __VMEMMAP_BASE_L4;
EXPORT_SYMBOL(vmemmap_base);
#endif
#define __head __section(.head.text)
static void __head *fixup_pointer(void *ptr, unsigned long physaddr)
{
return ptr - (void *)_text + (void *)physaddr;
}
static unsigned long __head *fixup_long(void *ptr, unsigned long physaddr)
{
return fixup_pointer(ptr, physaddr);
}
#ifdef CONFIG_X86_5LEVEL
static unsigned int __head *fixup_int(void *ptr, unsigned long physaddr)
{
return fixup_pointer(ptr, physaddr);
}
static bool __head check_la57_support(unsigned long physaddr)
{
/*
* 5-level paging is detected and enabled at kernel decomression
* stage. Only check if it has been enabled there.
*/
if (!(native_read_cr4() & X86_CR4_LA57))
return false;
*fixup_int(&__pgtable_l5_enabled, physaddr) = 1;
*fixup_int(&pgdir_shift, physaddr) = 48;
*fixup_int(&ptrs_per_p4d, physaddr) = 512;
*fixup_long(&page_offset_base, physaddr) = __PAGE_OFFSET_BASE_L5;
*fixup_long(&vmalloc_base, physaddr) = __VMALLOC_BASE_L5;
*fixup_long(&vmemmap_base, physaddr) = __VMEMMAP_BASE_L5;
return true;
}
#else
static bool __head check_la57_support(unsigned long physaddr)
{
return false;
}
#endif
/* Code in __startup_64() can be relocated during execution, but the compiler
* doesn't have to generate PC-relative relocations when accessing globals from
* that function. Clang actually does not generate them, which leads to
* boot-time crashes. To work around this problem, every global pointer must
* be adjusted using fixup_pointer().
*/
unsigned long __head __startup_64(unsigned long physaddr,
struct boot_params *bp)
{
unsigned long vaddr, vaddr_end;
unsigned long load_delta, *p;
unsigned long pgtable_flags;
pgdval_t *pgd;
p4dval_t *p4d;
pudval_t *pud;
pmdval_t *pmd, pmd_entry;
pteval_t *mask_ptr;
bool la57;
int i;
unsigned int *next_pgt_ptr;
la57 = check_la57_support(physaddr);
/* Is the address too large? */
if (physaddr >> MAX_PHYSMEM_BITS)
for (;;);
/*
* Compute the delta between the address I am compiled to run at
* and the address I am actually running at.
*/
load_delta = physaddr - (unsigned long)(_text - __START_KERNEL_map);
/* Is the address not 2M aligned? */
if (load_delta & ~PMD_PAGE_MASK)
for (;;);
/* Activate Secure Memory Encryption (SME) if supported and enabled */
sme_enable(bp);
/* Include the SME encryption mask in the fixup value */
load_delta += sme_get_me_mask();
/* Fixup the physical addresses in the page table */
pgd = fixup_pointer(&early_top_pgt, physaddr);
p = pgd + pgd_index(__START_KERNEL_map);
if (la57)
*p = (unsigned long)level4_kernel_pgt;
else
*p = (unsigned long)level3_kernel_pgt;
*p += _PAGE_TABLE_NOENC - __START_KERNEL_map + load_delta;
if (la57) {
p4d = fixup_pointer(&level4_kernel_pgt, physaddr);
p4d[511] += load_delta;
}
pud = fixup_pointer(&level3_kernel_pgt, physaddr);
pud[510] += load_delta;
pud[511] += load_delta;
pmd = fixup_pointer(level2_fixmap_pgt, physaddr);
for (i = FIXMAP_PMD_TOP; i > FIXMAP_PMD_TOP - FIXMAP_PMD_NUM; i--)
pmd[i] += load_delta;
/*
* Set up the identity mapping for the switchover. These
* entries should *NOT* have the global bit set! This also
* creates a bunch of nonsense entries but that is fine --
* it avoids problems around wraparound.
*/
next_pgt_ptr = fixup_pointer(&next_early_pgt, physaddr);
pud = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr);
pmd = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++], physaddr);
pgtable_flags = _KERNPG_TABLE_NOENC + sme_get_me_mask();
if (la57) {
p4d = fixup_pointer(early_dynamic_pgts[(*next_pgt_ptr)++],
physaddr);
i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;
pgd[i + 0] = (pgdval_t)p4d + pgtable_flags;
pgd[i + 1] = (pgdval_t)p4d + pgtable_flags;
i = physaddr >> P4D_SHIFT;
p4d[(i + 0) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;
p4d[(i + 1) % PTRS_PER_P4D] = (pgdval_t)pud + pgtable_flags;
} else {
i = (physaddr >> PGDIR_SHIFT) % PTRS_PER_PGD;
pgd[i + 0] = (pgdval_t)pud + pgtable_flags;
pgd[i + 1] = (pgdval_t)pud + pgtable_flags;
}
i = physaddr >> PUD_SHIFT;
pud[(i + 0) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;
pud[(i + 1) % PTRS_PER_PUD] = (pudval_t)pmd + pgtable_flags;
pmd_entry = __PAGE_KERNEL_LARGE_EXEC & ~_PAGE_GLOBAL;
/* Filter out unsupported __PAGE_KERNEL_* bits: */
mask_ptr = fixup_pointer(&__supported_pte_mask, physaddr);
pmd_entry &= *mask_ptr;
pmd_entry += sme_get_me_mask();
pmd_entry += physaddr;
for (i = 0; i < DIV_ROUND_UP(_end - _text, PMD_SIZE); i++) {
int idx = i + (physaddr >> PMD_SHIFT);
pmd[idx % PTRS_PER_PMD] = pmd_entry + i * PMD_SIZE;
}
/*
* Fixup the kernel text+data virtual addresses. Note that
* we might write invalid pmds, when the kernel is relocated
* cleanup_highmap() fixes this up along with the mappings
* beyond _end.
*/
pmd = fixup_pointer(level2_kernel_pgt, physaddr);
for (i = 0; i < PTRS_PER_PMD; i++) {
if (pmd[i] & _PAGE_PRESENT)
pmd[i] += load_delta;
}
/*
* Fixup phys_base - remove the memory encryption mask to obtain
* the true physical address.
*/
*fixup_long(&phys_base, physaddr) += load_delta - sme_get_me_mask();
/* Encrypt the kernel and related (if SME is active) */
sme_encrypt_kernel(bp);
/*
* Clear the memory encryption mask from the .bss..decrypted section.
* The bss section will be memset to zero later in the initialization so
* there is no need to zero it after changing the memory encryption
* attribute.
*/
if (mem_encrypt_active()) {
vaddr = (unsigned long)__start_bss_decrypted;
vaddr_end = (unsigned long)__end_bss_decrypted;
for (; vaddr < vaddr_end; vaddr += PMD_SIZE) {
i = pmd_index(vaddr);
pmd[i] -= sme_get_me_mask();
}
}
/*
* Return the SME encryption mask (if SME is active) to be used as a
* modifier for the initial pgdir entry programmed into CR3.
*/
return sme_get_me_mask();
}
unsigned long __startup_secondary_64(void)
{
/*
* Return the SME encryption mask (if SME is active) to be used as a
* modifier for the initial pgdir entry programmed into CR3.
*/
return sme_get_me_mask();
}
/* Wipe all early page tables except for the kernel symbol map */
static void __init reset_early_page_tables(void)
{
memset(early_top_pgt, 0, sizeof(pgd_t)*(PTRS_PER_PGD-1));
next_early_pgt = 0;
write_cr3(__sme_pa_nodebug(early_top_pgt));
}
/* Create a new PMD entry */
int __init __early_make_pgtable(unsigned long address, pmdval_t pmd)
{
unsigned long physaddr = address - __PAGE_OFFSET;
pgdval_t pgd, *pgd_p;
p4dval_t p4d, *p4d_p;
pudval_t pud, *pud_p;
pmdval_t *pmd_p;
/* Invalid address or early pgt is done ? */
if (physaddr >= MAXMEM || read_cr3_pa() != __pa_nodebug(early_top_pgt))
return -1;
again:
pgd_p = &early_top_pgt[pgd_index(address)].pgd;
pgd = *pgd_p;
/*
* The use of __START_KERNEL_map rather than __PAGE_OFFSET here is
* critical -- __PAGE_OFFSET would point us back into the dynamic
* range and we might end up looping forever...
*/
if (!pgtable_l5_enabled())
p4d_p = pgd_p;
else if (pgd)
p4d_p = (p4dval_t *)((pgd & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
else {
if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
reset_early_page_tables();
goto again;
}
p4d_p = (p4dval_t *)early_dynamic_pgts[next_early_pgt++];
memset(p4d_p, 0, sizeof(*p4d_p) * PTRS_PER_P4D);
*pgd_p = (pgdval_t)p4d_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
}
p4d_p += p4d_index(address);
p4d = *p4d_p;
if (p4d)
pud_p = (pudval_t *)((p4d & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
else {
if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
reset_early_page_tables();
goto again;
}
pud_p = (pudval_t *)early_dynamic_pgts[next_early_pgt++];
memset(pud_p, 0, sizeof(*pud_p) * PTRS_PER_PUD);
*p4d_p = (p4dval_t)pud_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
}
pud_p += pud_index(address);
pud = *pud_p;
if (pud)
pmd_p = (pmdval_t *)((pud & PTE_PFN_MASK) + __START_KERNEL_map - phys_base);
else {
if (next_early_pgt >= EARLY_DYNAMIC_PAGE_TABLES) {
reset_early_page_tables();
goto again;
}
pmd_p = (pmdval_t *)early_dynamic_pgts[next_early_pgt++];
memset(pmd_p, 0, sizeof(*pmd_p) * PTRS_PER_PMD);
*pud_p = (pudval_t)pmd_p - __START_KERNEL_map + phys_base + _KERNPG_TABLE;
}
pmd_p[pmd_index(address)] = pmd;
return 0;
}
int __init early_make_pgtable(unsigned long address)
{
unsigned long physaddr = address - __PAGE_OFFSET;
pmdval_t pmd;
pmd = (physaddr & PMD_MASK) + early_pmd_flags;
return __early_make_pgtable(address, pmd);
}
/* Don't add a printk in there. printk relies on the PDA which is not initialized
yet. */
static void __init clear_bss(void)
{
memset(__bss_start, 0,
(unsigned long) __bss_stop - (unsigned long) __bss_start);
}
static unsigned long get_cmd_line_ptr(void)
{
unsigned long cmd_line_ptr = boot_params.hdr.cmd_line_ptr;
cmd_line_ptr |= (u64)boot_params.ext_cmd_line_ptr << 32;
return cmd_line_ptr;
}
static void __init copy_bootdata(char *real_mode_data)
{
char * command_line;
unsigned long cmd_line_ptr;
/*
* If SME is active, this will create decrypted mappings of the
* boot data in advance of the copy operations.
*/
sme_map_bootdata(real_mode_data);
memcpy(&boot_params, real_mode_data, sizeof(boot_params));
sanitize_boot_params(&boot_params);
cmd_line_ptr = get_cmd_line_ptr();
if (cmd_line_ptr) {
command_line = __va(cmd_line_ptr);
memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE);
}
/*
* The old boot data is no longer needed and won't be reserved,
* freeing up that memory for use by the system. If SME is active,
* we need to remove the mappings that were created so that the
* memory doesn't remain mapped as decrypted.
*/
sme_unmap_bootdata(real_mode_data);
}
asmlinkage __visible void __init x86_64_start_kernel(char * real_mode_data)
{
/*
* Build-time sanity checks on the kernel image and module
* area mappings. (these are purely build-time and produce no code)
*/
BUILD_BUG_ON(MODULES_VADDR < __START_KERNEL_map);
BUILD_BUG_ON(MODULES_VADDR - __START_KERNEL_map < KERNEL_IMAGE_SIZE);
BUILD_BUG_ON(MODULES_LEN + KERNEL_IMAGE_SIZE > 2*PUD_SIZE);
BUILD_BUG_ON((__START_KERNEL_map & ~PMD_MASK) != 0);
BUILD_BUG_ON((MODULES_VADDR & ~PMD_MASK) != 0);
BUILD_BUG_ON(!(MODULES_VADDR > __START_KERNEL));
MAYBE_BUILD_BUG_ON(!(((MODULES_END - 1) & PGDIR_MASK) ==
(__START_KERNEL & PGDIR_MASK)));
BUILD_BUG_ON(__fix_to_virt(__end_of_fixed_addresses) <= MODULES_END);
cr4_init_shadow();
/* Kill off the identity-map trampoline */
reset_early_page_tables();
clear_bss();
clear_page(init_top_pgt);
/*
* SME support may update early_pmd_flags to include the memory
* encryption mask, so it needs to be called before anything
* that may generate a page fault.
*/
sme_early_init();
kasan_early_init();
idt_setup_early_handler();
copy_bootdata(__va(real_mode_data));
/*
* Load microcode early on BSP.
*/
load_ucode_bsp();
/* set init_top_pgt kernel high mapping*/
init_top_pgt[511] = early_top_pgt[511];
x86_64_start_reservations(real_mode_data);
}
void __init x86_64_start_reservations(char *real_mode_data)
{
/* version is always not zero if it is copied */
if (!boot_params.hdr.version)
copy_bootdata(__va(real_mode_data));
x86_early_init_platform_quirks();
switch (boot_params.hdr.hardware_subarch) {
case X86_SUBARCH_INTEL_MID:
x86_intel_mid_early_setup();
break;
default:
break;
}
start_kernel();
}
| gpl-2.0 |
Webee-IOT/webee210-linux-kernel-3.8 | net/sctp/associola.c | 48370 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This file is part of the SCTP kernel implementation
*
* This module provides the abstraction for an SCTP association.
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <[email protected]>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <[email protected]>
* Karl Knutson <[email protected]>
* Jon Grimm <[email protected]>
* Xingang Guo <[email protected]>
* Hui Huang <[email protected]>
* Sridhar Samudrala <[email protected]>
* Daisy Chang <[email protected]>
* Ryan Layer <[email protected]>
* Kevin Gao <[email protected]>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <net/ipv6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal functions. */
static void sctp_assoc_bh_rcv(struct work_struct *work);
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc);
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc);
/* Keep track of the new idr low so that we don't re-use association id
* numbers too fast. It is protected by they idr spin lock is in the
* range of 1 - INT_MAX.
*/
static u32 idr_low = 1;
/* 1st Level Abstractions. */
/* Initialize a new association from provided memory. */
static struct sctp_association *sctp_association_init(struct sctp_association *asoc,
const struct sctp_endpoint *ep,
const struct sock *sk,
sctp_scope_t scope,
gfp_t gfp)
{
struct net *net = sock_net(sk);
struct sctp_sock *sp;
int i;
sctp_paramhdr_t *p;
int err;
/* Retrieve the SCTP per socket area. */
sp = sctp_sk((struct sock *)sk);
/* Discarding const is appropriate here. */
asoc->ep = (struct sctp_endpoint *)ep;
sctp_endpoint_hold(asoc->ep);
/* Hold the sock. */
asoc->base.sk = (struct sock *)sk;
sock_hold(asoc->base.sk);
/* Initialize the common base substructure. */
asoc->base.type = SCTP_EP_TYPE_ASSOCIATION;
/* Initialize the object handling fields. */
atomic_set(&asoc->base.refcnt, 1);
asoc->base.dead = 0;
asoc->base.malloced = 0;
/* Initialize the bind addr area. */
sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port);
asoc->state = SCTP_STATE_CLOSED;
/* Set these values from the socket values, a conversion between
* millsecons to seconds/microseconds must also be done.
*/
asoc->cookie_life.tv_sec = sp->assocparams.sasoc_cookie_life / 1000;
asoc->cookie_life.tv_usec = (sp->assocparams.sasoc_cookie_life % 1000)
* 1000;
asoc->frag_point = 0;
asoc->user_frag = sp->user_frag;
/* Set the association max_retrans and RTO values from the
* socket values.
*/
asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt;
asoc->pf_retrans = net->sctp.pf_retrans;
asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial);
asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max);
asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min);
asoc->overall_error_count = 0;
/* Initialize the association's heartbeat interval based on the
* sock configured value.
*/
asoc->hbinterval = msecs_to_jiffies(sp->hbinterval);
/* Initialize path max retrans value. */
asoc->pathmaxrxt = sp->pathmaxrxt;
/* Initialize default path MTU. */
asoc->pathmtu = sp->pathmtu;
/* Set association default SACK delay */
asoc->sackdelay = msecs_to_jiffies(sp->sackdelay);
asoc->sackfreq = sp->sackfreq;
/* Set the association default flags controlling
* Heartbeat, SACK delay, and Path MTU Discovery.
*/
asoc->param_flags = sp->param_flags;
/* Initialize the maximum mumber of new data packets that can be sent
* in a burst.
*/
asoc->max_burst = sp->max_burst;
/* initialize association timers */
asoc->timeouts[SCTP_EVENT_TIMEOUT_NONE] = 0;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T3_RTX] = 0;
asoc->timeouts[SCTP_EVENT_TIMEOUT_T4_RTO] = 0;
/* sctpimpguide Section 2.12.2
* If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the
* recommended value of 5 times 'RTO.Max'.
*/
asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]
= 5 * asoc->rto_max;
asoc->timeouts[SCTP_EVENT_TIMEOUT_HEARTBEAT] = 0;
asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay;
asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] =
min_t(unsigned long, sp->autoclose, net->sctp.max_autoclose) * HZ;
/* Initializes the timers */
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i)
setup_timer(&asoc->timers[i], sctp_timer_events[i],
(unsigned long)asoc);
/* Pull default initialization values from the sock options.
* Note: This assumes that the values have already been
* validated in the sock.
*/
asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams;
asoc->c.sinit_num_ostreams = sp->initmsg.sinit_num_ostreams;
asoc->max_init_attempts = sp->initmsg.sinit_max_attempts;
asoc->max_init_timeo =
msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo);
/* Allocate storage for the ssnmap after the inbound and outbound
* streams have been negotiated during Init.
*/
asoc->ssnmap = NULL;
/* Set the local window size for receive.
* This is also the rcvbuf space per association.
* RFC 6 - A SCTP receiver MUST be able to receive a minimum of
* 1500 bytes in one SCTP packet.
*/
if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW)
asoc->rwnd = SCTP_DEFAULT_MINWINDOW;
else
asoc->rwnd = sk->sk_rcvbuf/2;
asoc->a_rwnd = asoc->rwnd;
asoc->rwnd_over = 0;
asoc->rwnd_press = 0;
/* Use my own max window until I learn something better. */
asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW;
/* Set the sndbuf size for transmit. */
asoc->sndbuf_used = 0;
/* Initialize the receive memory counter */
atomic_set(&asoc->rmem_alloc, 0);
init_waitqueue_head(&asoc->wait);
asoc->c.my_vtag = sctp_generate_tag(ep);
asoc->peer.i.init_tag = 0; /* INIT needs a vtag of 0. */
asoc->c.peer_vtag = 0;
asoc->c.my_ttag = 0;
asoc->c.peer_ttag = 0;
asoc->c.my_port = ep->base.bind_addr.port;
asoc->c.initial_tsn = sctp_generate_tsn(ep);
asoc->next_tsn = asoc->c.initial_tsn;
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
asoc->highest_sacked = asoc->ctsn_ack_point;
asoc->last_cwr_tsn = asoc->ctsn_ack_point;
asoc->unack_data = 0;
/* ADDIP Section 4.1 Asconf Chunk Procedures
*
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do the following:
* ...
* A2) a serial number should be assigned to the chunk. The serial
* number SHOULD be a monotonically increasing number. The serial
* numbers SHOULD be initialized at the start of the
* association to the same value as the initial TSN.
*/
asoc->addip_serial = asoc->c.initial_tsn;
INIT_LIST_HEAD(&asoc->addip_chunk_list);
INIT_LIST_HEAD(&asoc->asconf_ack_list);
/* Make an empty list of remote transport addresses. */
INIT_LIST_HEAD(&asoc->peer.transport_addr_list);
asoc->peer.transport_count = 0;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* After the reception of the first data chunk in an
* association the endpoint must immediately respond with a
* sack to acknowledge the data chunk. Subsequent
* acknowledgements should be done as described in Section
* 6.2.
*
* [We implement this by telling a new association that it
* already received one packet.]
*/
asoc->peer.sack_needed = 1;
asoc->peer.sack_cnt = 0;
asoc->peer.sack_generation = 1;
/* Assume that the peer will tell us if he recognizes ASCONF
* as part of INIT exchange.
* The sctp_addip_noauth option is there for backward compatibilty
* and will revert old behavior.
*/
asoc->peer.asconf_capable = 0;
if (net->sctp.addip_noauth)
asoc->peer.asconf_capable = 1;
asoc->asconf_addr_del_pending = NULL;
asoc->src_out_of_asoc_ok = 0;
asoc->new_transport = NULL;
/* Create an input queue. */
sctp_inq_init(&asoc->base.inqueue);
sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv);
/* Create an output queue. */
sctp_outq_init(asoc, &asoc->outqueue);
if (!sctp_ulpq_init(&asoc->ulpq, asoc))
goto fail_init;
memset(&asoc->peer.tsn_map, 0, sizeof(struct sctp_tsnmap));
asoc->need_ecne = 0;
asoc->assoc_id = 0;
/* Assume that peer would support both address types unless we are
* told otherwise.
*/
asoc->peer.ipv4_address = 1;
if (asoc->base.sk->sk_family == PF_INET6)
asoc->peer.ipv6_address = 1;
INIT_LIST_HEAD(&asoc->asocs);
asoc->autoclose = sp->autoclose;
asoc->default_stream = sp->default_stream;
asoc->default_ppid = sp->default_ppid;
asoc->default_flags = sp->default_flags;
asoc->default_context = sp->default_context;
asoc->default_timetolive = sp->default_timetolive;
asoc->default_rcv_context = sp->default_rcv_context;
/* SCTP_GET_ASSOC_STATS COUNTERS */
memset(&asoc->stats, 0, sizeof(struct sctp_priv_assoc_stats));
/* AUTH related initializations */
INIT_LIST_HEAD(&asoc->endpoint_shared_keys);
err = sctp_auth_asoc_copy_shkeys(ep, asoc, gfp);
if (err)
goto fail_init;
asoc->active_key_id = ep->active_key_id;
asoc->asoc_shared_key = NULL;
asoc->default_hmac_id = 0;
/* Save the hmacs and chunks list into this association */
if (ep->auth_hmacs_list)
memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list,
ntohs(ep->auth_hmacs_list->param_hdr.length));
if (ep->auth_chunk_list)
memcpy(asoc->c.auth_chunks, ep->auth_chunk_list,
ntohs(ep->auth_chunk_list->param_hdr.length));
/* Get the AUTH random number for this association */
p = (sctp_paramhdr_t *)asoc->c.auth_random;
p->type = SCTP_PARAM_RANDOM;
p->length = htons(sizeof(sctp_paramhdr_t) + SCTP_AUTH_RANDOM_LENGTH);
get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH);
return asoc;
fail_init:
sctp_endpoint_put(asoc->ep);
sock_put(asoc->base.sk);
return NULL;
}
/* Allocate and initialize a new association */
struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep,
const struct sock *sk,
sctp_scope_t scope,
gfp_t gfp)
{
struct sctp_association *asoc;
asoc = t_new(struct sctp_association, gfp);
if (!asoc)
goto fail;
if (!sctp_association_init(asoc, ep, sk, scope, gfp))
goto fail_init;
asoc->base.malloced = 1;
SCTP_DBG_OBJCNT_INC(assoc);
SCTP_DEBUG_PRINTK("Created asoc %p\n", asoc);
return asoc;
fail_init:
kfree(asoc);
fail:
return NULL;
}
/* Free this association if possible. There may still be users, so
* the actual deallocation may be delayed.
*/
void sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!asoc->temp) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = 1;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (timer_pending(&asoc->timers[i]) &&
del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
/* Cleanup and free up an association. */
static void sctp_association_destroy(struct sctp_association *asoc)
{
SCTP_ASSERT(asoc->base.dead, "Assoc is not dead", return);
sctp_endpoint_put(asoc->ep);
sock_put(asoc->base.sk);
if (asoc->assoc_id != 0) {
spin_lock_bh(&sctp_assocs_id_lock);
idr_remove(&sctp_assocs_id, asoc->assoc_id);
spin_unlock_bh(&sctp_assocs_id_lock);
}
WARN_ON(atomic_read(&asoc->rmem_alloc));
if (asoc->base.malloced) {
kfree(asoc);
SCTP_DBG_OBJCNT_DEC(assoc);
}
}
/* Change the primary destination address for the peer. */
void sctp_assoc_set_primary(struct sctp_association *asoc,
struct sctp_transport *transport)
{
int changeover = 0;
/* it's a changeover only if we already have a primary path
* that we are changing
*/
if (asoc->peer.primary_path != NULL &&
asoc->peer.primary_path != transport)
changeover = 1 ;
asoc->peer.primary_path = transport;
/* Set a default msg_name for events. */
memcpy(&asoc->peer.primary_addr, &transport->ipaddr,
sizeof(union sctp_addr));
/* If the primary path is changing, assume that the
* user wants to use this new path.
*/
if ((transport->state == SCTP_ACTIVE) ||
(transport->state == SCTP_UNKNOWN))
asoc->peer.active_path = transport;
/*
* SFR-CACC algorithm:
* Upon the receipt of a request to change the primary
* destination address, on the data structure for the new
* primary destination, the sender MUST do the following:
*
* 1) If CHANGEOVER_ACTIVE is set, then there was a switch
* to this destination address earlier. The sender MUST set
* CYCLING_CHANGEOVER to indicate that this switch is a
* double switch to the same destination address.
*
* Really, only bother is we have data queued or outstanding on
* the association.
*/
if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen)
return;
if (transport->cacc.changeover_active)
transport->cacc.cycling_changeover = changeover;
/* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that
* a changeover has occurred.
*/
transport->cacc.changeover_active = changeover;
/* 3) The sender MUST store the next TSN to be sent in
* next_tsn_at_change.
*/
transport->cacc.next_tsn_at_change = asoc->next_tsn;
}
/* Remove a transport from an association. */
void sctp_assoc_rm_peer(struct sctp_association *asoc,
struct sctp_transport *peer)
{
struct list_head *pos;
struct sctp_transport *transport;
SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_rm_peer:association %p addr: ",
" port: %d\n",
asoc,
(&peer->ipaddr),
ntohs(peer->ipaddr.v4.sin_port));
/* If we are to remove the current retran_path, update it
* to the next peer before removing this peer from the list.
*/
if (asoc->peer.retran_path == peer)
sctp_assoc_update_retran_path(asoc);
/* Remove this peer from the list. */
list_del_rcu(&peer->transports);
/* Get the first transport of asoc. */
pos = asoc->peer.transport_addr_list.next;
transport = list_entry(pos, struct sctp_transport, transports);
/* Update any entries that match the peer to be deleted. */
if (asoc->peer.primary_path == peer)
sctp_assoc_set_primary(asoc, transport);
if (asoc->peer.active_path == peer)
asoc->peer.active_path = transport;
if (asoc->peer.retran_path == peer)
asoc->peer.retran_path = transport;
if (asoc->peer.last_data_from == peer)
asoc->peer.last_data_from = transport;
/* If we remove the transport an INIT was last sent to, set it to
* NULL. Combined with the update of the retran path above, this
* will cause the next INIT to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->init_last_sent_to == peer)
asoc->init_last_sent_to = NULL;
/* If we remove the transport an SHUTDOWN was last sent to, set it
* to NULL. Combined with the update of the retran path above, this
* will cause the next SHUTDOWN to be sent to the next available
* transport, maintaining the cycle.
*/
if (asoc->shutdown_last_sent_to == peer)
asoc->shutdown_last_sent_to = NULL;
/* If we remove the transport an ASCONF was last sent to, set it to
* NULL.
*/
if (asoc->addip_last_asconf &&
asoc->addip_last_asconf->transport == peer)
asoc->addip_last_asconf->transport = NULL;
/* If we have something on the transmitted list, we have to
* save it off. The best place is the active path.
*/
if (!list_empty(&peer->transmitted)) {
struct sctp_transport *active = asoc->peer.active_path;
struct sctp_chunk *ch;
/* Reset the transport of each chunk on this list */
list_for_each_entry(ch, &peer->transmitted,
transmitted_list) {
ch->transport = NULL;
ch->rtt_in_progress = 0;
}
list_splice_tail_init(&peer->transmitted,
&active->transmitted);
/* Start a T3 timer here in case it wasn't running so
* that these migrated packets have a chance to get
* retrnasmitted.
*/
if (!timer_pending(&active->T3_rtx_timer))
if (!mod_timer(&active->T3_rtx_timer,
jiffies + active->rto))
sctp_transport_hold(active);
}
asoc->peer.transport_count--;
sctp_transport_free(peer);
}
/* Add a transport address to an association. */
struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc,
const union sctp_addr *addr,
const gfp_t gfp,
const int peer_state)
{
struct net *net = sock_net(asoc->base.sk);
struct sctp_transport *peer;
struct sctp_sock *sp;
unsigned short port;
sp = sctp_sk(asoc->base.sk);
/* AF_INET and AF_INET6 share common port field. */
port = ntohs(addr->v4.sin_port);
SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_add_peer:association %p addr: ",
" port: %d state:%d\n",
asoc,
addr,
port,
peer_state);
/* Set the port if it has not been set yet. */
if (0 == asoc->peer.port)
asoc->peer.port = port;
/* Check to see if this is a duplicate. */
peer = sctp_assoc_lookup_paddr(asoc, addr);
if (peer) {
/* An UNKNOWN state is only set on transports added by
* user in sctp_connectx() call. Such transports should be
* considered CONFIRMED per RFC 4960, Section 5.4.
*/
if (peer->state == SCTP_UNKNOWN) {
peer->state = SCTP_ACTIVE;
}
return peer;
}
peer = sctp_transport_new(net, addr, gfp);
if (!peer)
return NULL;
sctp_transport_set_owner(peer, asoc);
/* Initialize the peer's heartbeat interval based on the
* association configured value.
*/
peer->hbinterval = asoc->hbinterval;
/* Set the path max_retrans. */
peer->pathmaxrxt = asoc->pathmaxrxt;
/* And the partial failure retrnas threshold */
peer->pf_retrans = asoc->pf_retrans;
/* Initialize the peer's SACK delay timeout based on the
* association configured value.
*/
peer->sackdelay = asoc->sackdelay;
peer->sackfreq = asoc->sackfreq;
/* Enable/disable heartbeat, SACK delay, and path MTU discovery
* based on association setting.
*/
peer->param_flags = asoc->param_flags;
sctp_transport_route(peer, NULL, sp);
/* Initialize the pmtu of the transport. */
if (peer->param_flags & SPP_PMTUD_DISABLE) {
if (asoc->pathmtu)
peer->pathmtu = asoc->pathmtu;
else
peer->pathmtu = SCTP_DEFAULT_MAXSEGMENT;
}
/* If this is the first transport addr on this association,
* initialize the association PMTU to the peer's PMTU.
* If not and the current association PMTU is higher than the new
* peer's PMTU, reset the association PMTU to the new peer's PMTU.
*/
if (asoc->pathmtu)
asoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu);
else
asoc->pathmtu = peer->pathmtu;
SCTP_DEBUG_PRINTK("sctp_assoc_add_peer:association %p PMTU set to "
"%d\n", asoc, asoc->pathmtu);
peer->pmtu_pending = 0;
asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
/* The asoc->peer.port might not be meaningful yet, but
* initialize the packet structure anyway.
*/
sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port,
asoc->peer.port);
/* 7.2.1 Slow-Start
*
* o The initial cwnd before DATA transmission or after a sufficiently
* long idle period MUST be set to
* min(4*MTU, max(2*MTU, 4380 bytes))
*
* o The initial value of ssthresh MAY be arbitrarily high
* (for example, implementations MAY use the size of the
* receiver advertised window).
*/
peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));
/* At this point, we may not have the receiver's advertised window,
* so initialize ssthresh to the default value and it will be set
* later when we process the INIT.
*/
peer->ssthresh = SCTP_DEFAULT_MAXWINDOW;
peer->partial_bytes_acked = 0;
peer->flight_size = 0;
peer->burst_limited = 0;
/* Set the transport's RTO.initial value */
peer->rto = asoc->rto_initial;
sctp_max_rto(asoc, peer);
/* Set the peer's active state. */
peer->state = peer_state;
/* Attach the remote transport to our asoc. */
list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list);
asoc->peer.transport_count++;
/* If we do not yet have a primary path, set one. */
if (!asoc->peer.primary_path) {
sctp_assoc_set_primary(asoc, peer);
asoc->peer.retran_path = peer;
}
if (asoc->peer.active_path == asoc->peer.retran_path &&
peer->state != SCTP_UNCONFIRMED) {
asoc->peer.retran_path = peer;
}
return peer;
}
/* Delete a transport address from an association. */
void sctp_assoc_del_peer(struct sctp_association *asoc,
const union sctp_addr *addr)
{
struct list_head *pos;
struct list_head *temp;
struct sctp_transport *transport;
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
if (sctp_cmp_addr_exact(addr, &transport->ipaddr)) {
/* Do book keeping for removing the peer and free it. */
sctp_assoc_rm_peer(asoc, transport);
break;
}
}
}
/* Lookup a transport by address. */
struct sctp_transport *sctp_assoc_lookup_paddr(
const struct sctp_association *asoc,
const union sctp_addr *address)
{
struct sctp_transport *t;
/* Cycle through all transports searching for a peer address. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (sctp_cmp_addr_exact(address, &t->ipaddr))
return t;
}
return NULL;
}
/* Remove all transports except a give one */
void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc,
struct sctp_transport *primary)
{
struct sctp_transport *temp;
struct sctp_transport *t;
list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list,
transports) {
/* if the current transport is not the primary one, delete it */
if (t != primary)
sctp_assoc_rm_peer(asoc, t);
}
}
/* Engage in transport control operations.
* Mark the transport up or down and send a notification to the user.
* Select and update the new active and retran paths.
*/
void sctp_assoc_control_transport(struct sctp_association *asoc,
struct sctp_transport *transport,
sctp_transport_cmd_t command,
sctp_sn_error_t error)
{
struct sctp_transport *t = NULL;
struct sctp_transport *first;
struct sctp_transport *second;
struct sctp_ulpevent *event;
struct sockaddr_storage addr;
int spc_state = 0;
bool ulp_notify = true;
/* Record the transition on the transport. */
switch (command) {
case SCTP_TRANSPORT_UP:
/* If we are moving from UNCONFIRMED state due
* to heartbeat success, report the SCTP_ADDR_CONFIRMED
* state to the user, otherwise report SCTP_ADDR_AVAILABLE.
*/
if (SCTP_UNCONFIRMED == transport->state &&
SCTP_HEARTBEAT_SUCCESS == error)
spc_state = SCTP_ADDR_CONFIRMED;
else
spc_state = SCTP_ADDR_AVAILABLE;
/* Don't inform ULP about transition from PF to
* active state and set cwnd to 1, see SCTP
* Quick failover draft section 5.1, point 5
*/
if (transport->state == SCTP_PF) {
ulp_notify = false;
transport->cwnd = 1;
}
transport->state = SCTP_ACTIVE;
break;
case SCTP_TRANSPORT_DOWN:
/* If the transport was never confirmed, do not transition it
* to inactive state. Also, release the cached route since
* there may be a better route next time.
*/
if (transport->state != SCTP_UNCONFIRMED)
transport->state = SCTP_INACTIVE;
else {
dst_release(transport->dst);
transport->dst = NULL;
}
spc_state = SCTP_ADDR_UNREACHABLE;
break;
case SCTP_TRANSPORT_PF:
transport->state = SCTP_PF;
ulp_notify = false;
break;
default:
return;
}
/* Generate and send a SCTP_PEER_ADDR_CHANGE notification to the
* user.
*/
if (ulp_notify) {
memset(&addr, 0, sizeof(struct sockaddr_storage));
memcpy(&addr, &transport->ipaddr,
transport->af_specific->sockaddr_len);
event = sctp_ulpevent_make_peer_addr_change(asoc, &addr,
0, spc_state, error, GFP_ATOMIC);
if (event)
sctp_ulpq_tail_event(&asoc->ulpq, event);
}
/* Select new active and retran paths. */
/* Look for the two most recently used active transports.
*
* This code produces the wrong ordering whenever jiffies
* rolls over, but we still get usable transports, so we don't
* worry about it.
*/
first = NULL; second = NULL;
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if ((t->state == SCTP_INACTIVE) ||
(t->state == SCTP_UNCONFIRMED) ||
(t->state == SCTP_PF))
continue;
if (!first || t->last_time_heard > first->last_time_heard) {
second = first;
first = t;
}
if (!second || t->last_time_heard > second->last_time_heard)
second = t;
}
/* RFC 2960 6.4 Multi-Homed SCTP Endpoints
*
* By default, an endpoint should always transmit to the
* primary path, unless the SCTP user explicitly specifies the
* destination transport address (and possibly source
* transport address) to use.
*
* [If the primary is active but not most recent, bump the most
* recently used transport.]
*/
if (((asoc->peer.primary_path->state == SCTP_ACTIVE) ||
(asoc->peer.primary_path->state == SCTP_UNKNOWN)) &&
first != asoc->peer.primary_path) {
second = first;
first = asoc->peer.primary_path;
}
/* If we failed to find a usable transport, just camp on the
* primary, even if it is inactive.
*/
if (!first) {
first = asoc->peer.primary_path;
second = asoc->peer.primary_path;
}
/* Set the active and retran transports. */
asoc->peer.active_path = first;
asoc->peer.retran_path = second;
}
/* Hold a reference to an association. */
void sctp_association_hold(struct sctp_association *asoc)
{
atomic_inc(&asoc->base.refcnt);
}
/* Release a reference to an association and cleanup
* if there are no more references.
*/
void sctp_association_put(struct sctp_association *asoc)
{
if (atomic_dec_and_test(&asoc->base.refcnt))
sctp_association_destroy(asoc);
}
/* Allocate the next TSN, Transmission Sequence Number, for the given
* association.
*/
__u32 sctp_association_get_next_tsn(struct sctp_association *asoc)
{
/* From Section 1.6 Serial Number Arithmetic:
* Transmission Sequence Numbers wrap around when they reach
* 2**32 - 1. That is, the next TSN a DATA chunk MUST use
* after transmitting TSN = 2*32 - 1 is TSN = 0.
*/
__u32 retval = asoc->next_tsn;
asoc->next_tsn++;
asoc->unack_data++;
return retval;
}
/* Compare two addresses to see if they match. Wildcard addresses
* only match themselves.
*/
int sctp_cmp_addr_exact(const union sctp_addr *ss1,
const union sctp_addr *ss2)
{
struct sctp_af *af;
af = sctp_get_af_specific(ss1->sa.sa_family);
if (unlikely(!af))
return 0;
return af->cmp_addr(ss1, ss2);
}
/* Return an ecne chunk to get prepended to a packet.
* Note: We are sly and return a shared, prealloced chunk. FIXME:
* No we don't, but we could/should.
*/
struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc)
{
struct sctp_chunk *chunk;
/* Send ECNE if needed.
* Not being able to allocate a chunk here is not deadly.
*/
if (asoc->need_ecne)
chunk = sctp_make_ecne(asoc, asoc->last_ecne_tsn);
else
chunk = NULL;
return chunk;
}
/*
* Find which transport this TSN was sent on.
*/
struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc,
__u32 tsn)
{
struct sctp_transport *active;
struct sctp_transport *match;
struct sctp_transport *transport;
struct sctp_chunk *chunk;
__be32 key = htonl(tsn);
match = NULL;
/*
* FIXME: In general, find a more efficient data structure for
* searching.
*/
/*
* The general strategy is to search each transport's transmitted
* list. Return which transport this TSN lives on.
*
* Let's be hopeful and check the active_path first.
* Another optimization would be to know if there is only one
* outbound path and not have to look for the TSN at all.
*
*/
active = asoc->peer.active_path;
list_for_each_entry(chunk, &active->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = active;
goto out;
}
}
/* If not found, go search all the other transports. */
list_for_each_entry(transport, &asoc->peer.transport_addr_list,
transports) {
if (transport == active)
break;
list_for_each_entry(chunk, &transport->transmitted,
transmitted_list) {
if (key == chunk->subh.data_hdr->tsn) {
match = transport;
goto out;
}
}
}
out:
return match;
}
/* Is this the association we are looking for? */
struct sctp_transport *sctp_assoc_is_match(struct sctp_association *asoc,
struct net *net,
const union sctp_addr *laddr,
const union sctp_addr *paddr)
{
struct sctp_transport *transport;
if ((htons(asoc->base.bind_addr.port) == laddr->v4.sin_port) &&
(htons(asoc->peer.port) == paddr->v4.sin_port) &&
net_eq(sock_net(asoc->base.sk), net)) {
transport = sctp_assoc_lookup_paddr(asoc, paddr);
if (!transport)
goto out;
if (sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
sctp_sk(asoc->base.sk)))
goto out;
}
transport = NULL;
out:
return transport;
}
/* Do delayed input processing. This is scheduled by sctp_rcv(). */
static void sctp_assoc_bh_rcv(struct work_struct *work)
{
struct sctp_association *asoc =
container_of(work, struct sctp_association,
base.inqueue.immediate);
struct net *net = sock_net(asoc->base.sk);
struct sctp_endpoint *ep;
struct sctp_chunk *chunk;
struct sctp_inq *inqueue;
int state;
sctp_subtype_t subtype;
int error = 0;
/* The association should be held so we should be safe. */
ep = asoc->ep;
inqueue = &asoc->base.inqueue;
sctp_association_hold(asoc);
while (NULL != (chunk = sctp_inq_pop(inqueue))) {
state = asoc->state;
subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);
/* SCTP-AUTH, Section 6.3:
* The receiver has a list of chunk types which it expects
* to be received only after an AUTH-chunk. This list has
* been sent to the peer during the association setup. It
* MUST silently discard these chunks if they are not placed
* after an AUTH chunk in the packet.
*/
if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)
continue;
/* Remember where the last DATA chunk came from so we
* know where to send the SACK.
*/
if (sctp_chunk_is_data(chunk))
asoc->peer.last_data_from = chunk->transport;
else {
SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS);
asoc->stats.ictrlchunks++;
if (chunk->chunk_hdr->type == SCTP_CID_SACK)
asoc->stats.isacks++;
}
if (chunk->transport)
chunk->transport->last_time_heard = jiffies;
/* Run through the state machine. */
error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype,
state, ep, asoc, chunk, GFP_ATOMIC);
/* Check to see if the association is freed in response to
* the incoming chunk. If so, get out of the while loop.
*/
if (asoc->base.dead)
break;
/* If there is an error on chunk, discard this packet. */
if (error && chunk)
chunk->pdiscard = 1;
}
sctp_association_put(asoc);
}
/* This routine moves an association from its old sk to a new sk. */
void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk)
{
struct sctp_sock *newsp = sctp_sk(newsk);
struct sock *oldsk = assoc->base.sk;
/* Delete the association from the old endpoint's list of
* associations.
*/
list_del_init(&assoc->asocs);
/* Decrement the backlog value for a TCP-style socket. */
if (sctp_style(oldsk, TCP))
oldsk->sk_ack_backlog--;
/* Release references to the old endpoint and the sock. */
sctp_endpoint_put(assoc->ep);
sock_put(assoc->base.sk);
/* Get a reference to the new endpoint. */
assoc->ep = newsp->ep;
sctp_endpoint_hold(assoc->ep);
/* Get a reference to the new sock. */
assoc->base.sk = newsk;
sock_hold(assoc->base.sk);
/* Add the association to the new endpoint's list of associations. */
sctp_endpoint_add_asoc(newsp->ep, assoc);
}
/* Update an association (possibly from unexpected COOKIE-ECHO processing). */
void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new assocaitions
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
/* Update the retran path for sending a retransmitted packet.
* Round-robin through the active transports, else round-robin
* through the inactive transports as this is the next best thing
* we can try.
*/
void sctp_assoc_update_retran_path(struct sctp_association *asoc)
{
struct sctp_transport *t, *next;
struct list_head *head = &asoc->peer.transport_addr_list;
struct list_head *pos;
if (asoc->peer.transport_count == 1)
return;
/* Find the next transport in a round-robin fashion. */
t = asoc->peer.retran_path;
pos = &t->transports;
next = NULL;
while (1) {
/* Skip the head. */
if (pos->next == head)
pos = head->next;
else
pos = pos->next;
t = list_entry(pos, struct sctp_transport, transports);
/* We have exhausted the list, but didn't find any
* other active transports. If so, use the next
* transport.
*/
if (t == asoc->peer.retran_path) {
t = next;
break;
}
/* Try to find an active transport. */
if ((t->state == SCTP_ACTIVE) ||
(t->state == SCTP_UNKNOWN)) {
break;
} else {
/* Keep track of the next transport in case
* we don't find any active transport.
*/
if (t->state != SCTP_UNCONFIRMED && !next)
next = t;
}
}
if (t)
asoc->peer.retran_path = t;
else
t = asoc->peer.retran_path;
SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_update_retran_path:association"
" %p addr: ",
" port: %d\n",
asoc,
(&t->ipaddr),
ntohs(t->ipaddr.v4.sin_port));
}
/* Choose the transport for sending retransmit packet. */
struct sctp_transport *sctp_assoc_choose_alter_transport(
struct sctp_association *asoc, struct sctp_transport *last_sent_to)
{
/* If this is the first time packet is sent, use the active path,
* else use the retran path. If the last packet was sent over the
* retran path, update the retran path and use it.
*/
if (!last_sent_to)
return asoc->peer.active_path;
else {
if (last_sent_to == asoc->peer.retran_path)
sctp_assoc_update_retran_path(asoc);
return asoc->peer.retran_path;
}
}
/* Update the association's pmtu and frag_point by going through all the
* transports. This routine is called when a transport's PMTU has changed.
*/
void sctp_assoc_sync_pmtu(struct sock *sk, struct sctp_association *asoc)
{
struct sctp_transport *t;
__u32 pmtu = 0;
if (!asoc)
return;
/* Get the lowest pmtu of all the transports. */
list_for_each_entry(t, &asoc->peer.transport_addr_list,
transports) {
if (t->pmtu_pending && t->dst) {
sctp_transport_update_pmtu(sk, t, dst_mtu(t->dst));
t->pmtu_pending = 0;
}
if (!pmtu || (t->pathmtu < pmtu))
pmtu = t->pathmtu;
}
if (pmtu) {
asoc->pathmtu = pmtu;
asoc->frag_point = sctp_frag_point(asoc, pmtu);
}
SCTP_DEBUG_PRINTK("%s: asoc:%p, pmtu:%d, frag_point:%d\n",
__func__, asoc, asoc->pathmtu, asoc->frag_point);
}
/* Should we send a SACK to update our peer? */
static inline int sctp_peer_needs_update(struct sctp_association *asoc)
{
struct net *net = sock_net(asoc->base.sk);
switch (asoc->state) {
case SCTP_STATE_ESTABLISHED:
case SCTP_STATE_SHUTDOWN_PENDING:
case SCTP_STATE_SHUTDOWN_RECEIVED:
case SCTP_STATE_SHUTDOWN_SENT:
if ((asoc->rwnd > asoc->a_rwnd) &&
((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32,
(asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift),
asoc->pathmtu)))
return 1;
break;
default:
break;
}
return 0;
}
/* Increase asoc's rwnd by len and send any window update SACK if needed. */
void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len)
{
struct sctp_chunk *sack;
struct timer_list *timer;
if (asoc->rwnd_over) {
if (asoc->rwnd_over >= len) {
asoc->rwnd_over -= len;
} else {
asoc->rwnd += (len - asoc->rwnd_over);
asoc->rwnd_over = 0;
}
} else {
asoc->rwnd += len;
}
/* If we had window pressure, start recovering it
* once our rwnd had reached the accumulated pressure
* threshold. The idea is to recover slowly, but up
* to the initial advertised window.
*/
if (asoc->rwnd_press && asoc->rwnd >= asoc->rwnd_press) {
int change = min(asoc->pathmtu, asoc->rwnd_press);
asoc->rwnd += change;
asoc->rwnd_press -= change;
}
SCTP_DEBUG_PRINTK("%s: asoc %p rwnd increased by %d to (%u, %u) "
"- %u\n", __func__, asoc, len, asoc->rwnd,
asoc->rwnd_over, asoc->a_rwnd);
/* Send a window update SACK if the rwnd has increased by at least the
* minimum of the association's PMTU and half of the receive buffer.
* The algorithm used is similar to the one described in
* Section 4.2.3.3 of RFC 1122.
*/
if (sctp_peer_needs_update(asoc)) {
asoc->a_rwnd = asoc->rwnd;
SCTP_DEBUG_PRINTK("%s: Sending window update SACK- asoc: %p "
"rwnd: %u a_rwnd: %u\n", __func__,
asoc, asoc->rwnd, asoc->a_rwnd);
sack = sctp_make_sack(asoc);
if (!sack)
return;
asoc->peer.sack_needed = 0;
sctp_outq_tail(&asoc->outqueue, sack);
/* Stop the SACK timer. */
timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
if (timer_pending(timer) && del_timer(timer))
sctp_association_put(asoc);
}
}
/* Decrease asoc's rwnd by len. */
void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len)
{
int rx_count;
int over = 0;
SCTP_ASSERT(asoc->rwnd, "rwnd zero", return);
SCTP_ASSERT(!asoc->rwnd_over, "rwnd_over not zero", return);
if (asoc->ep->rcvbuf_policy)
rx_count = atomic_read(&asoc->rmem_alloc);
else
rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);
/* If we've reached or overflowed our receive buffer, announce
* a 0 rwnd if rwnd would still be positive. Store the
* the pottential pressure overflow so that the window can be restored
* back to original value.
*/
if (rx_count >= asoc->base.sk->sk_rcvbuf)
over = 1;
if (asoc->rwnd >= len) {
asoc->rwnd -= len;
if (over) {
asoc->rwnd_press += asoc->rwnd;
asoc->rwnd = 0;
}
} else {
asoc->rwnd_over = len - asoc->rwnd;
asoc->rwnd = 0;
}
SCTP_DEBUG_PRINTK("%s: asoc %p rwnd decreased by %d to (%u, %u, %u)\n",
__func__, asoc, len, asoc->rwnd,
asoc->rwnd_over, asoc->rwnd_press);
}
/* Build the bind address list for the association based on info from the
* local endpoint and the remote peer.
*/
int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc,
sctp_scope_t scope, gfp_t gfp)
{
int flags;
/* Use scoping rules to determine the subset of addresses from
* the endpoint.
*/
flags = (PF_INET6 == asoc->base.sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0;
if (asoc->peer.ipv4_address)
flags |= SCTP_ADDR4_PEERSUPP;
if (asoc->peer.ipv6_address)
flags |= SCTP_ADDR6_PEERSUPP;
return sctp_bind_addr_copy(sock_net(asoc->base.sk),
&asoc->base.bind_addr,
&asoc->ep->base.bind_addr,
scope, gfp, flags);
}
/* Build the association's bind address list from the cookie. */
int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc,
struct sctp_cookie *cookie,
gfp_t gfp)
{
int var_size2 = ntohs(cookie->peer_init->chunk_hdr.length);
int var_size3 = cookie->raw_addr_list_len;
__u8 *raw = (__u8 *)cookie->peer_init + var_size2;
return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3,
asoc->ep->base.bind_addr.port, gfp);
}
/* Lookup laddr in the bind address list of an association. */
int sctp_assoc_lookup_laddr(struct sctp_association *asoc,
const union sctp_addr *laddr)
{
int found = 0;
if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) &&
sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
sctp_sk(asoc->base.sk)))
found = 1;
return found;
}
/* Set an association id for a given association */
int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp)
{
int assoc_id;
int error = 0;
/* If the id is already assigned, keep it. */
if (asoc->assoc_id)
return error;
retry:
if (unlikely(!idr_pre_get(&sctp_assocs_id, gfp)))
return -ENOMEM;
spin_lock_bh(&sctp_assocs_id_lock);
error = idr_get_new_above(&sctp_assocs_id, (void *)asoc,
idr_low, &assoc_id);
if (!error) {
idr_low = assoc_id + 1;
if (idr_low == INT_MAX)
idr_low = 1;
}
spin_unlock_bh(&sctp_assocs_id_lock);
if (error == -EAGAIN)
goto retry;
else if (error)
return error;
asoc->assoc_id = (sctp_assoc_t) assoc_id;
return error;
}
/* Free the ASCONF queue */
static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc)
{
struct sctp_chunk *asconf;
struct sctp_chunk *tmp;
list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) {
list_del_init(&asconf->list);
sctp_chunk_free(asconf);
}
}
/* Free asconf_ack cache */
static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Clean up the ASCONF_ACK queue */
void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc)
{
struct sctp_chunk *ack;
struct sctp_chunk *tmp;
/* We can remove all the entries from the queue up to
* the "Peer-Sequence-Number".
*/
list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
transmitted_list) {
if (ack->subh.addip_hdr->serial ==
htonl(asoc->peer.addip_serial))
break;
list_del_init(&ack->transmitted_list);
sctp_chunk_free(ack);
}
}
/* Find the ASCONF_ACK whose serial number matches ASCONF */
struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
const struct sctp_association *asoc,
__be32 serial)
{
struct sctp_chunk *ack;
/* Walk through the list of cached ASCONF-ACKs and find the
* ack chunk whose serial number matches that of the request.
*/
list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
if (ack->subh.addip_hdr->serial == serial) {
sctp_chunk_hold(ack);
return ack;
}
}
return NULL;
}
void sctp_asconf_queue_teardown(struct sctp_association *asoc)
{
/* Free any cached ASCONF_ACK chunk. */
sctp_assoc_free_asconf_acks(asoc);
/* Free the ASCONF queue. */
sctp_assoc_free_asconf_queue(asoc);
/* Free any cached ASCONF chunk. */
if (asoc->addip_last_asconf)
sctp_chunk_free(asoc->addip_last_asconf);
}
| gpl-2.0 |
drthomas21/WordPress_Tutorial | wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/Dataproc/DataprocEmpty.php | 667 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_Dataproc_DataprocEmpty extends Google_Model
{
}
| apache-2.0 |
drthomas21/WordPress_Tutorial | wordpress_htdocs/wp-content/plugins/swg-youtube-vids/vendor/google/apiclient-services/src/Google/Service/DoubleClickBidManager/QueryMetadata.php | 3146 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_DoubleClickBidManager_QueryMetadata extends Google_Collection
{
protected $collection_key = 'shareEmailAddress';
public $dataRange;
public $format;
public $googleCloudStoragePathForLatestReport;
public $googleDrivePathForLatestReport;
public $latestReportRunTimeMs;
public $locale;
public $reportCount;
public $running;
public $sendNotification;
public $shareEmailAddress;
public $title;
public function setDataRange($dataRange)
{
$this->dataRange = $dataRange;
}
public function getDataRange()
{
return $this->dataRange;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
public function setGoogleCloudStoragePathForLatestReport($googleCloudStoragePathForLatestReport)
{
$this->googleCloudStoragePathForLatestReport = $googleCloudStoragePathForLatestReport;
}
public function getGoogleCloudStoragePathForLatestReport()
{
return $this->googleCloudStoragePathForLatestReport;
}
public function setGoogleDrivePathForLatestReport($googleDrivePathForLatestReport)
{
$this->googleDrivePathForLatestReport = $googleDrivePathForLatestReport;
}
public function getGoogleDrivePathForLatestReport()
{
return $this->googleDrivePathForLatestReport;
}
public function setLatestReportRunTimeMs($latestReportRunTimeMs)
{
$this->latestReportRunTimeMs = $latestReportRunTimeMs;
}
public function getLatestReportRunTimeMs()
{
return $this->latestReportRunTimeMs;
}
public function setLocale($locale)
{
$this->locale = $locale;
}
public function getLocale()
{
return $this->locale;
}
public function setReportCount($reportCount)
{
$this->reportCount = $reportCount;
}
public function getReportCount()
{
return $this->reportCount;
}
public function setRunning($running)
{
$this->running = $running;
}
public function getRunning()
{
return $this->running;
}
public function setSendNotification($sendNotification)
{
$this->sendNotification = $sendNotification;
}
public function getSendNotification()
{
return $this->sendNotification;
}
public function setShareEmailAddress($shareEmailAddress)
{
$this->shareEmailAddress = $shareEmailAddress;
}
public function getShareEmailAddress()
{
return $this->shareEmailAddress;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
| apache-2.0 |
samthor/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentEP.java | 3337 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.PluginAware;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.util.NotNullFunction;
import com.intellij.util.pico.ConstructorInjectionComponentAdapter;
import com.intellij.util.xmlb.annotations.Attribute;
import org.jetbrains.annotations.Nullable;
/**
* @author yole
*/
public class ChangesViewContentEP implements PluginAware {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ui.ChangesViewContentEP");
public static final ExtensionPointName<ChangesViewContentEP> EP_NAME = new ExtensionPointName<ChangesViewContentEP>("com.intellij.changesViewContent");
@Attribute("tabName")
public String tabName;
@Attribute("className")
public String className;
@Attribute("predicateClassName")
public String predicateClassName;
private PluginDescriptor myPluginDescriptor;
private ChangesViewContentProvider myInstance;
public void setPluginDescriptor(PluginDescriptor pluginDescriptor) {
myPluginDescriptor = pluginDescriptor;
}
public String getTabName() {
return tabName;
}
public void setTabName(final String tabName) {
this.tabName = tabName;
}
public String getClassName() {
return className;
}
public void setClassName(final String className) {
this.className = className;
}
public String getPredicateClassName() {
return predicateClassName;
}
public void setPredicateClassName(final String predicateClassName) {
this.predicateClassName = predicateClassName;
}
public ChangesViewContentProvider getInstance(Project project) {
if (myInstance == null) {
myInstance = (ChangesViewContentProvider) newClassInstance(project, className);
}
return myInstance;
}
@Nullable
public NotNullFunction<Project, Boolean> newPredicateInstance(Project project) {
//noinspection unchecked
return predicateClassName != null ? (NotNullFunction<Project, Boolean>)newClassInstance(project, predicateClassName) : null;
}
private Object newClassInstance(final Project project, final String className) {
try {
final Class<?> aClass = Class.forName(className, true,
myPluginDescriptor == null ? getClass().getClassLoader() : myPluginDescriptor.getPluginClassLoader());
return new ConstructorInjectionComponentAdapter(className, aClass).getComponentInstance(project.getPicoContainer());
}
catch(Exception e) {
LOG.error(e);
return null;
}
}
}
| apache-2.0 |
cymcsg/UltimateAndroid | deprecated/UltimateAndroidNormal/DemoOfUI/src/com/marshalchen/common/demoofui/showcaseview/legacy/MultipleShowcaseSampleActivity.java | 2332 | package com.marshalchen.common.demoofui.showcaseview.legacy;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.marshalchen.common.demoofui.R;
public class MultipleShowcaseSampleActivity extends Activity {
private static final float SHOWCASE_KITTEN_SCALE = 1.2f;
private static final float SHOWCASE_LIKE_SCALE = 0.5f;
//ShowcaseViews mViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showcase_activity_sample_legacy);
findViewById(R.id.buttonLike).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "like_message", Toast.LENGTH_SHORT).show();
}
});
//mOptions.block = false;
// mViews = new ShowcaseViews(this,
// new ShowcaseViews.OnShowcaseAcknowledged() {
// @Override
// public void onShowCaseAcknowledged(ShowcaseView showcaseView) {
// Toast.makeText(MultipleShowcaseSampleActivity.this, R.string.dismissed_message, Toast.LENGTH_SHORT).show();
// }
// });
// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.image,
// R.string.showcase_image_title,
// R.string.showcase_image_message,
// SHOWCASE_KITTEN_SCALE));
// mViews.addView( new ShowcaseViews.ItemViewProperties(R.id.buttonLike,
// R.string.showcase_like_title,
// R.string.showcase_like_message,
// SHOWCASE_LIKE_SCALE));
// mViews.show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
enableUp();
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void enableUp() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
diogocs1/comps | web/addons/sale_layout/models/sale_layout.py | 4907 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv, fields
from itertools import groupby
def grouplines(self, ordered_lines, sortkey):
"""Return lines from a specified invoice or sale order grouped by category"""
grouped_lines = []
for key, valuesiter in groupby(ordered_lines, sortkey):
group = {}
group['category'] = key
group['lines'] = list(v for v in valuesiter)
if 'subtotal' in key and key.subtotal is True:
group['subtotal'] = sum(line.price_subtotal for line in group['lines'])
grouped_lines.append(group)
return grouped_lines
class SaleLayoutCategory(osv.Model):
_name = 'sale_layout.category'
_order = 'sequence'
_columns = {
'name': fields.char('Name', required=True),
'sequence': fields.integer('Sequence', required=True),
'subtotal': fields.boolean('Add subtotal'),
'separator': fields.boolean('Add separator'),
'pagebreak': fields.boolean('Add pagebreak')
}
_defaults = {
'subtotal': True,
'separator': True,
'pagebreak': False,
'sequence': 10
}
class AccountInvoice(osv.Model):
_inherit = 'account.invoice'
def sale_layout_lines(self, cr, uid, ids, invoice_id=None, context=None):
"""
Returns invoice lines from a specified invoice ordered by
sale_layout_category sequence. Used in sale_layout module.
:Parameters:
-'invoice_id' (int): specify the concerned invoice.
"""
ordered_lines = self.browse(cr, uid, invoice_id, context=context).invoice_line
# We chose to group first by category model and, if not present, by invoice name
sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else ''
return grouplines(self, ordered_lines, sortkey)
import openerp
class AccountInvoiceLine(osv.Model):
_inherit = 'account.invoice.line'
_order = 'invoice_id, categ_sequence, sequence, id'
sale_layout_cat_id = openerp.fields.Many2one('sale_layout.category', string='Section')
categ_sequence = openerp.fields.Integer(related='sale_layout_cat_id.sequence',
string='Layout Sequence', store=True)
class SaleOrder(osv.Model):
_inherit = 'sale.order'
def sale_layout_lines(self, cr, uid, ids, order_id=None, context=None):
"""
Returns order lines from a specified sale ordered by
sale_layout_category sequence. Used in sale_layout module.
:Parameters:
-'order_id' (int): specify the concerned sale order.
"""
ordered_lines = self.browse(cr, uid, order_id, context=context).order_line
sortkey = lambda x: x.sale_layout_cat_id if x.sale_layout_cat_id else ''
return grouplines(self, ordered_lines, sortkey)
class SaleOrderLine(osv.Model):
_inherit = 'sale.order.line'
_columns = {
'sale_layout_cat_id': fields.many2one('sale_layout.category',
string='Section'),
'categ_sequence': fields.related('sale_layout_cat_id',
'sequence', type='integer',
string='Layout Sequence', store=True)
# Store is intentionally set in order to keep the "historic" order.
}
_order = 'order_id, categ_sequence, sequence, id'
def _prepare_order_line_invoice_line(self, cr, uid, line, account_id=False, context=None):
"""Save the layout when converting to an invoice line."""
invoice_vals = super(SaleOrderLine, self)._prepare_order_line_invoice_line(cr, uid, line, account_id=account_id, context=context)
if line.sale_layout_cat_id:
invoice_vals['sale_layout_cat_id'] = line.sale_layout_cat_id.id
if line.categ_sequence:
invoice_vals['categ_sequence'] = line.categ_sequence
return invoice_vals
| apache-2.0 |
vongalpha/origin | Godeps/_workspace/src/k8s.io/kubernetes/docs/user-guide/connecting-applications.md | 17365 | <!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
<strong>
The latest 1.0.x release of this document can be found
[here](http://releases.k8s.io/release-1.0/docs/user-guide/connecting-applications.md).
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
# Kubernetes User Guide: Managing Applications: Connecting applications
**Table of Contents**
<!-- BEGIN MUNGE: GENERATED_TOC -->
- [Kubernetes User Guide: Managing Applications: Connecting applications](#kubernetes-user-guide-managing-applications-connecting-applications)
- [The Kubernetes model for connecting containers](#the-kubernetes-model-for-connecting-containers)
- [Exposing pods to the cluster](#exposing-pods-to-the-cluster)
- [Creating a Service](#creating-a-service)
- [Accessing the Service](#accessing-the-service)
- [Environment Variables](#environment-variables)
- [DNS](#dns)
- [Securing the Service](#securing-the-service)
- [Exposing the Service](#exposing-the-service)
- [What's next?](#whats-next)
<!-- END MUNGE: GENERATED_TOC -->
# The Kubernetes model for connecting containers
Now that you have a continuously running, replicated application you can expose it on a network. Before discussing the Kubernetes approach to networking, it is worthwhile to contrast it with the "normal" way networking works with Docker.
By default, Docker uses host-private networking, so containers can talk to other containers only if they are on the same machine. In order for Docker containers to communicate across nodes, they must be allocated ports on the machine's own IP address, which are then forwarded or proxied to the containers. This obviously means that containers must either coordinate which ports they use very carefully or else be allocated ports dynamically.
Coordinating ports across multiple developers is very difficult to do at scale and exposes users to cluster-level issues outside of their control. Kubernetes assumes that pods can communicate with other pods, regardless of which host they land on. We give every pod its own cluster-private-IP address so you do not need to explicitly create links between pods or mapping container ports to host ports. This means that containers within a Pod can all reach each other’s ports on localhost, and all pods in a cluster can see each other without NAT. The rest of this document will elaborate on how you can run reliable services on such a networking model.
This guide uses a simple nginx server to demonstrate proof of concept. The same principles are embodied in a more complete [Jenkins CI application](http://blog.kubernetes.io/2015/07/strong-simple-ssl-for-kubernetes.html).
## Exposing pods to the cluster
We did this in a previous example, but lets do it once again and focus on the networking perspective. Create an nginx pod, and note that it has a container port specification:
```yaml
$ cat nginxrc.yaml
apiVersion: v1
kind: ReplicationController
metadata:
name: my-nginx
spec:
replicas: 2
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
```
This makes it accessible from any node in your cluster. Check the nodes the pod is running on:
```console
$ kubectl create -f ./nginxrc.yaml
$ kubectl get pods -l app=nginx -o wide
my-nginx-6isf4 1/1 Running 0 2h e2e-test-beeps-minion-93ly
my-nginx-t26zt 1/1 Running 0 2h e2e-test-beeps-minion-93ly
```
Check your pods' IPs:
```console
$ kubectl get pods -l app=nginx -o json | grep podIP
"podIP": "10.245.0.15",
"podIP": "10.245.0.14",
```
You should be able to ssh into any node in your cluster and curl both IPs. Note that the containers are *not* using port 80 on the node, nor are there any special NAT rules to route traffic to the pod. This means you can run multiple nginx pods on the same node all using the same containerPort and access them from any other pod or node in your cluster using IP. Like Docker, ports can still be published to the host node's interface(s), but the need for this is radically diminished because of the networking model.
You can read more about [how we achieve this](../admin/networking.md#how-to-achieve-this) if you’re curious.
## Creating a Service
So we have pods running nginx in a flat, cluster wide, address space. In theory, you could talk to these pods directly, but what happens when a node dies? The pods die with it, and the replication controller will create new ones, with different IPs. This is the problem a Service solves.
A Kubernetes Service is an abstraction which defines a logical set of Pods running somewhere in your cluster, that all provide the same functionality. When created, each Service is assigned a unique IP address (also called clusterIP). This address is tied to the lifespan of the Service, and will not change while the Service is alive. Pods can be configured to talk to the Service, and know that communication to the Service will be automatically load-balanced out to some pod that is a member of the Service.
You can create a Service for your 2 nginx replicas with the following yaml:
```yaml
$ cat nginxsvc.yaml
apiVersion: v1
kind: Service
metadata:
name: nginxsvc
labels:
app: nginx
spec:
ports:
- port: 80
protocol: TCP
selector:
app: nginx
```
This specification will create a Service which targets TCP port 80 on any Pod with the `app=nginx` label, and expose it on an abstracted Service port (`targetPort`: is the port the container accepts traffic on, `port`: is the abstracted Service port, which can be any port other pods use to access the Service). View [service API object](https://htmlpreview.github.io/?https://k8s.io/kubernetes/HEAD/docs/api-reference/definitions.html#_v1_service) to see the list of supported fields in service definition.
Check your Service:
```console
$ kubectl get svc
NAME LABELS SELECTOR IP(S) PORT(S)
nginxsvc app=nginx app=nginx 10.0.116.146 80/TCP
```
As mentioned previously, a Service is backed by a group of pods. These pods are exposed through `endpoints`. The Service's selector will be evaluated continuously and the results will be POSTed to an Endpoints object also named `nginxsvc`. When a pod dies, it is automatically removed from the endpoints, and new pods matching the Service’s selector will automatically get added to the endpoints. Check the endpoints, and note that the IPs are the same as the pods created in the first step:
```console
$ kubectl describe svc nginxsvc
Name: nginxsvc
Namespace: default
Labels: app=nginx
Selector: app=nginx
Type: ClusterIP
IP: 10.0.116.146
Port: <unnamed> 80/TCP
Endpoints: 10.245.0.14:80,10.245.0.15:80
Session Affinity: None
No events.
$ kubectl get ep
NAME ENDPOINTS
nginxsvc 10.245.0.14:80,10.245.0.15:80
```
You should now be able to curl the nginx Service on `10.0.116.146:80` from any node in your cluster. Note that the Service IP is completely virtual, it never hits the wire, if you’re curious about how this works you can read more about the [service proxy](services.md#virtual-ips-and-service-proxies).
## Accessing the Service
Kubernetes supports 2 primary modes of finding a Service - environment variables and DNS. The former works out of the box while the latter requires the [kube-dns cluster addon](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md).
### Environment Variables
When a Pod is run on a Node, the kubelet adds a set of environment variables for each active Service. This introduces an ordering problem. To see why, inspect the environment of your running nginx pods:
```console
$ kubectl exec my-nginx-6isf4 -- printenv | grep SERVICE
KUBERNETES_SERVICE_HOST=10.0.0.1
KUBERNETES_SERVICE_PORT=443
```
Note there’s no mention of your Service. This is because you created the replicas before the Service. Another disadvantage of doing this is that the scheduler might put both pods on the same machine, which will take your entire Service down if it dies. We can do this the right way by killing the 2 pods and waiting for the replication controller to recreate them. This time around the Service exists *before* the replicas. This will given you scheduler level Service spreading of your pods (provided all your nodes have equal capacity), as well as the right environment variables:
```console
$ kubectl scale rc my-nginx --replicas=0; kubectl scale rc my-nginx --replicas=2;
$ kubectl get pods -l app=nginx -o wide
NAME READY STATUS RESTARTS AGE NODE
my-nginx-5j8ok 1/1 Running 0 2m node1
my-nginx-90vaf 1/1 Running 0 2m node2
$ kubectl exec my-nginx-5j8ok -- printenv | grep SERVICE
KUBERNETES_SERVICE_PORT=443
NGINXSVC_SERVICE_HOST=10.0.116.146
KUBERNETES_SERVICE_HOST=10.0.0.1
NGINXSVC_SERVICE_PORT=80
```
### DNS
Kubernetes offers a DNS cluster addon Service that uses skydns to automatically assign dns names to other Services. You can check if it’s running on your cluster:
```console
$ kubectl get services kube-dns --namespace=kube-system
NAME LABELS SELECTOR IP(S) PORT(S)
kube-dns <none> k8s-app=kube-dns 10.0.0.10 53/UDP
53/TCP
```
If it isn’t running, you can [enable it](http://releases.k8s.io/HEAD/cluster/addons/dns/README.md#how-do-i-configure-it). The rest of this section will assume you have a Service with a long lived IP (nginxsvc), and a dns server that has assigned a name to that IP (the kube-dns cluster addon), so you can talk to the Service from any pod in your cluster using standard methods (e.g. gethostbyname). Let’s create another pod to test this:
```yaml
$ cat curlpod.yaml
apiVersion: v1
kind: Pod
metadata:
name: curlpod
spec:
containers:
- image: radial/busyboxplus:curl
command:
- sleep
- "3600"
imagePullPolicy: IfNotPresent
name: curlcontainer
restartPolicy: Always
```
And perform a lookup of the nginx Service
```console
$ kubectl create -f ./curlpod.yaml
default/curlpod
$ kubectl get pods curlpod
NAME READY STATUS RESTARTS AGE
curlpod 1/1 Running 0 18s
$ kubectl exec curlpod -- nslookup nginxsvc
Server: 10.0.0.10
Address 1: 10.0.0.10
Name: nginxsvc
Address 1: 10.0.116.146
```
## Securing the Service
Till now we have only accessed the nginx server from within the cluster. Before exposing the Service to the internet, you want to make sure the communication channel is secure. For this, you will need:
* Self signed certificates for https (unless you already have an identitiy certificate)
* An nginx server configured to use the cretificates
* A [secret](secrets.md) that makes the certificates accessible to pods
You can acquire all these from the [nginx https example](../../examples/https-nginx/README.md), in short:
```console
$ make keys secret KEY=/tmp/nginx.key CERT=/tmp/nginx.crt SECRET=/tmp/secret.json
$ kubectl create -f /tmp/secret.json
secrets/nginxsecret
$ kubectl get secrets
NAME TYPE DATA
default-token-il9rc kubernetes.io/service-account-token 1
nginxsecret Opaque 2
```
Now modify your nginx replicas to start a https server using the certificate in the secret, and the Service, to expose both ports (80 and 443):
```yaml
$ cat nginx-app.yaml
apiVersion: v1
kind: Service
metadata:
name: nginxsvc
labels:
app: nginx
spec:
type: NodePort
ports:
- port: 8080
targetPort: 80
protocol: TCP
name: http
- port: 443
protocol: TCP
name: https
selector:
app: nginx
---
apiVersion: v1
kind: ReplicationController
metadata:
name: my-nginx
spec:
replicas: 1
template:
metadata:
labels:
app: nginx
spec:
volumes:
- name: secret-volume
secret:
secretName: nginxsecret
containers:
- name: nginxhttps
image: bprashanth/nginxhttps:1.0
ports:
- containerPort: 443
- containerPort: 80
volumeMounts:
- mountPath: /etc/nginx/ssl
name: secret-volume
```
Noteworthy points about the nginx-app manifest:
- It contains both rc and service specification in the same file
- The [nginx server](../../examples/https-nginx/default.conf) serves http traffic on port 80 and https traffic on 443, and nginx Service exposes both ports.
- Each container has access to the keys through a volume mounted at /etc/nginx/ssl. This is setup *before* the nginx server is started.
```console
$ kubectl delete rc,svc -l app=nginx; kubectl create -f ./nginx-app.yaml
replicationcontrollers/my-nginx
services/nginxsvc
services/nginxsvc
replicationcontrollers/my-nginx
```
At this point you can reach the nginx server from any node.
```console
$ kubectl get pods -o json | grep -i podip
"podIP": "10.1.0.80",
node $ curl -k https://10.1.0.80
...
<h1>Welcome to nginx!</h1>
```
Note how we supplied the `-k` parameter to curl in the last step, this is because we don't know anything about the pods running nginx at certificate generation time,
so we have to tell curl to ignore the CName mismatch. By creating a Service we linked the CName used in the certificate with the actual DNS name used by pods during Service lookup.
Lets test this from a pod (the same secret is being reused for simplicity, the pod only needs nginx.crt to access the Service):
```console
$ cat curlpod.yaml
vapiVersion: v1
kind: ReplicationController
metadata:
name: curlrc
spec:
replicas: 1
template:
metadata:
labels:
app: curlpod
spec:
volumes:
- name: secret-volume
secret:
secretName: nginxsecret
containers:
- name: curlpod
command:
- sh
- -c
- while true; do sleep 1; done
image: radial/busyboxplus:curl
volumeMounts:
- mountPath: /etc/nginx/ssl
name: secret-volume
$ kubectl create -f ./curlpod.yaml
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
curlpod 1/1 Running 0 2m
my-nginx-7006w 1/1 Running 0 24m
$ kubectl exec curlpod -- curl https://nginxsvc --cacert /etc/nginx/ssl/nginx.crt
...
<title>Welcome to nginx!</title>
...
```
## Exposing the Service
For some parts of your applications you may want to expose a Service onto an external IP address. Kubernetes supports two ways of doing this: NodePorts and LoadBalancers. The Service created in the last section already used `NodePort`, so your nginx https replica is ready to serve traffic on the internet if your node has a public IP.
```console
$ kubectl get svc nginxsvc -o json | grep -i nodeport -C 5
{
"name": "http",
"protocol": "TCP",
"port": 80,
"targetPort": 80,
"nodePort": 32188
},
{
"name": "https",
"protocol": "TCP",
"port": 443,
"targetPort": 443,
"nodePort": 30645
}
$ kubectl get nodes -o json | grep ExternalIP -C 2
{
"type": "ExternalIP",
"address": "104.197.63.17"
}
--
},
{
"type": "ExternalIP",
"address": "104.154.89.170"
}
$ curl https://104.197.63.17:30645 -k
...
<h1>Welcome to nginx!</h1>
```
Lets now recreate the Service to use a cloud load balancer, just change the `Type` of Service in the nginx-app.yaml from `NodePort` to `LoadBalancer`:
```console
$ kubectl delete rc, svc -l app=nginx
$ kubectl create -f ./nginx-app.yaml
$ kubectl get svc -o json | grep -i ingress -A 5
"ingress": [
{
"ip": "104.197.68.43"
}
]
}
$ curl https://104.197.68.43 -k
...
<title>Welcome to nginx!</title>
```
## What's next?
[Learn about more Kubernetes features that will help you run containers reliably in production.](production-pods.md)
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[]()
<!-- END MUNGE: GENERATED_ANALYTICS -->
| apache-2.0 |
valery-barysok/Apktool | brut.apktool.smali/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/DexBackedDexFile.java | 10213 | /*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.dexbacked;
import com.google.common.io.ByteStreams;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.raw.*;
import org.jf.dexlib2.dexbacked.util.FixedSizeSet;
import org.jf.dexlib2.iface.DexFile;
import org.jf.util.ExceptionWithContext;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
public class DexBackedDexFile extends BaseDexBuffer implements DexFile {
private final Opcodes opcodes;
private final int stringCount;
private final int stringStartOffset;
private final int typeCount;
private final int typeStartOffset;
private final int protoCount;
private final int protoStartOffset;
private final int fieldCount;
private final int fieldStartOffset;
private final int methodCount;
private final int methodStartOffset;
private final int classCount;
private final int classStartOffset;
private DexBackedDexFile(Opcodes opcodes, @Nonnull byte[] buf, int offset, boolean verifyMagic) {
super(buf);
this.opcodes = opcodes;
if (verifyMagic) {
verifyMagicAndByteOrder(buf, offset);
}
stringCount = readSmallUint(HeaderItem.STRING_COUNT_OFFSET);
stringStartOffset = readSmallUint(HeaderItem.STRING_START_OFFSET);
typeCount = readSmallUint(HeaderItem.TYPE_COUNT_OFFSET);
typeStartOffset = readSmallUint(HeaderItem.TYPE_START_OFFSET);
protoCount = readSmallUint(HeaderItem.PROTO_COUNT_OFFSET);
protoStartOffset = readSmallUint(HeaderItem.PROTO_START_OFFSET);
fieldCount = readSmallUint(HeaderItem.FIELD_COUNT_OFFSET);
fieldStartOffset = readSmallUint(HeaderItem.FIELD_START_OFFSET);
methodCount = readSmallUint(HeaderItem.METHOD_COUNT_OFFSET);
methodStartOffset = readSmallUint(HeaderItem.METHOD_START_OFFSET);
classCount = readSmallUint(HeaderItem.CLASS_COUNT_OFFSET);
classStartOffset = readSmallUint(HeaderItem.CLASS_START_OFFSET);
}
public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull BaseDexBuffer buf) {
this(opcodes, buf.buf);
}
public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf, int offset) {
this(opcodes, buf, offset, false);
}
public DexBackedDexFile(@Nonnull Opcodes opcodes, @Nonnull byte[] buf) {
this(opcodes, buf, 0, true);
}
public static DexBackedDexFile fromInputStream(@Nonnull Opcodes opcodes, @Nonnull InputStream is)
throws IOException {
if (!is.markSupported()) {
throw new IllegalArgumentException("InputStream must support mark");
}
is.mark(44);
byte[] partialHeader = new byte[44];
try {
ByteStreams.readFully(is, partialHeader);
} catch (EOFException ex) {
throw new NotADexFile("File is too short");
} finally {
is.reset();
}
verifyMagicAndByteOrder(partialHeader, 0);
byte[] buf = ByteStreams.toByteArray(is);
return new DexBackedDexFile(opcodes, buf, 0, false);
}
public Opcodes getOpcodes() {
return opcodes;
}
public boolean isOdexFile() {
return false;
}
@Nonnull
@Override
public Set<? extends DexBackedClassDef> getClasses() {
return new FixedSizeSet<DexBackedClassDef>() {
@Nonnull
@Override
public DexBackedClassDef readItem(int index) {
return new DexBackedClassDef(DexBackedDexFile.this, getClassDefItemOffset(index));
}
@Override
public int size() {
return classCount;
}
};
}
private static void verifyMagicAndByteOrder(@Nonnull byte[] buf, int offset) {
if (!HeaderItem.verifyMagic(buf, offset)) {
StringBuilder sb = new StringBuilder("Invalid magic value:");
for (int i=0; i<8; i++) {
sb.append(String.format(" %02x", buf[i]));
}
throw new NotADexFile(sb.toString());
}
int endian = HeaderItem.getEndian(buf, offset);
if (endian == HeaderItem.BIG_ENDIAN_TAG) {
throw new ExceptionWithContext("Big endian dex files are not currently supported");
}
if (endian != HeaderItem.LITTLE_ENDIAN_TAG) {
throw new ExceptionWithContext("Invalid endian tag: 0x%x", endian);
}
}
public int getStringIdItemOffset(int stringIndex) {
if (stringIndex < 0 || stringIndex >= stringCount) {
throw new InvalidItemIndex(stringIndex, "String index out of bounds: %d", stringIndex);
}
return stringStartOffset + stringIndex*StringIdItem.ITEM_SIZE;
}
public int getTypeIdItemOffset(int typeIndex) {
if (typeIndex < 0 || typeIndex >= typeCount) {
throw new InvalidItemIndex(typeIndex, "Type index out of bounds: %d", typeIndex);
}
return typeStartOffset + typeIndex*TypeIdItem.ITEM_SIZE;
}
public int getFieldIdItemOffset(int fieldIndex) {
if (fieldIndex < 0 || fieldIndex >= fieldCount) {
throw new InvalidItemIndex(fieldIndex, "Field index out of bounds: %d", fieldIndex);
}
return fieldStartOffset + fieldIndex*FieldIdItem.ITEM_SIZE;
}
public int getMethodIdItemOffset(int methodIndex) {
if (methodIndex < 0 || methodIndex >= methodCount) {
throw new InvalidItemIndex(methodIndex, "Method index out of bounds: %d", methodIndex);
}
return methodStartOffset + methodIndex*MethodIdItem.ITEM_SIZE;
}
public int getProtoIdItemOffset(int protoIndex) {
if (protoIndex < 0 || protoIndex >= protoCount) {
throw new InvalidItemIndex(protoIndex, "Proto index out of bounds: %d", protoIndex);
}
return protoStartOffset + protoIndex*ProtoIdItem.ITEM_SIZE;
}
public int getClassDefItemOffset(int classIndex) {
if (classIndex < 0 || classIndex >= classCount) {
throw new InvalidItemIndex(classIndex, "Class index out of bounds: %d", classIndex);
}
return classStartOffset + classIndex*ClassDefItem.ITEM_SIZE;
}
public int getClassCount() {
return classCount;
}
public int getStringCount() {
return stringCount;
}
public int getTypeCount() {
return typeCount;
}
public int getProtoCount() {
return protoCount;
}
public int getFieldCount() {
return fieldCount;
}
public int getMethodCount() {
return methodCount;
}
@Nonnull
public String getString(int stringIndex) {
int stringOffset = getStringIdItemOffset(stringIndex);
int stringDataOffset = readSmallUint(stringOffset);
DexReader reader = readerAt(stringDataOffset);
int utf16Length = reader.readSmallUleb128();
return reader.readString(utf16Length);
}
@Nullable
public String getOptionalString(int stringIndex) {
if (stringIndex == -1) {
return null;
}
return getString(stringIndex);
}
@Nonnull
public String getType(int typeIndex) {
int typeOffset = getTypeIdItemOffset(typeIndex);
int stringIndex = readSmallUint(typeOffset);
return getString(stringIndex);
}
@Nullable
public String getOptionalType(int typeIndex) {
if (typeIndex == -1) {
return null;
}
return getType(typeIndex);
}
@Override
@Nonnull
public DexReader readerAt(int offset) {
return new DexReader(this, offset);
}
public static class NotADexFile extends RuntimeException {
public NotADexFile() {
}
public NotADexFile(Throwable cause) {
super(cause);
}
public NotADexFile(String message) {
super(message);
}
public NotADexFile(String message, Throwable cause) {
super(message, cause);
}
}
public static class InvalidItemIndex extends ExceptionWithContext {
private final int itemIndex;
public InvalidItemIndex(int itemIndex) {
super("");
this.itemIndex = itemIndex;
}
public InvalidItemIndex(int itemIndex, String message, Object... formatArgs) {
super(message, formatArgs);
this.itemIndex = itemIndex;
}
public int getInvalidIndex() {
return itemIndex;
}
}
}
| apache-2.0 |
KOala888/GB_kernel | linux_kernel_galaxyplayer-master/fs/cachefiles/internal.h | 11228 | /* General netfs cache on cache files internal defs
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells ([email protected])
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/fscache-cache.h>
#include <linux/timer.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/security.h>
struct cachefiles_cache;
struct cachefiles_object;
extern unsigned cachefiles_debug;
#define CACHEFILES_DEBUG_KENTER 1
#define CACHEFILES_DEBUG_KLEAVE 2
#define CACHEFILES_DEBUG_KDEBUG 4
/*
* node records
*/
struct cachefiles_object {
struct fscache_object fscache; /* fscache handle */
struct cachefiles_lookup_data *lookup_data; /* cached lookup data */
struct dentry *dentry; /* the file/dir representing this object */
struct dentry *backer; /* backing file */
loff_t i_size; /* object size */
unsigned long flags;
#define CACHEFILES_OBJECT_ACTIVE 0 /* T if marked active */
#define CACHEFILES_OBJECT_BURIED 1 /* T if preemptively buried */
atomic_t usage; /* object usage count */
uint8_t type; /* object type */
uint8_t new; /* T if object new */
spinlock_t work_lock;
struct rb_node active_node; /* link in active tree (dentry is key) */
};
extern struct kmem_cache *cachefiles_object_jar;
/*
* Cache files cache definition
*/
struct cachefiles_cache {
struct fscache_cache cache; /* FS-Cache record */
struct vfsmount *mnt; /* mountpoint holding the cache */
struct dentry *graveyard; /* directory into which dead objects go */
struct file *cachefilesd; /* manager daemon handle */
const struct cred *cache_cred; /* security override for accessing cache */
struct mutex daemon_mutex; /* command serialisation mutex */
wait_queue_head_t daemon_pollwq; /* poll waitqueue for daemon */
struct rb_root active_nodes; /* active nodes (can't be culled) */
rwlock_t active_lock; /* lock for active_nodes */
atomic_t gravecounter; /* graveyard uniquifier */
unsigned frun_percent; /* when to stop culling (% files) */
unsigned fcull_percent; /* when to start culling (% files) */
unsigned fstop_percent; /* when to stop allocating (% files) */
unsigned brun_percent; /* when to stop culling (% blocks) */
unsigned bcull_percent; /* when to start culling (% blocks) */
unsigned bstop_percent; /* when to stop allocating (% blocks) */
unsigned bsize; /* cache's block size */
unsigned bshift; /* min(ilog2(PAGE_SIZE / bsize), 0) */
uint64_t frun; /* when to stop culling */
uint64_t fcull; /* when to start culling */
uint64_t fstop; /* when to stop allocating */
sector_t brun; /* when to stop culling */
sector_t bcull; /* when to start culling */
sector_t bstop; /* when to stop allocating */
unsigned long flags;
#define CACHEFILES_READY 0 /* T if cache prepared */
#define CACHEFILES_DEAD 1 /* T if cache dead */
#define CACHEFILES_CULLING 2 /* T if cull engaged */
#define CACHEFILES_STATE_CHANGED 3 /* T if state changed (poll trigger) */
char *rootdirname; /* name of cache root directory */
char *secctx; /* LSM security context */
char *tag; /* cache binding tag */
};
/*
* backing file read tracking
*/
struct cachefiles_one_read {
wait_queue_t monitor; /* link into monitored waitqueue */
struct page *back_page; /* backing file page we're waiting for */
struct page *netfs_page; /* netfs page we're going to fill */
struct fscache_retrieval *op; /* retrieval op covering this */
struct list_head op_link; /* link in op's todo list */
};
/*
* backing file write tracking
*/
struct cachefiles_one_write {
struct page *netfs_page; /* netfs page to copy */
struct cachefiles_object *object;
struct list_head obj_link; /* link in object's lists */
fscache_rw_complete_t end_io_func;
void *context;
};
/*
* auxiliary data xattr buffer
*/
struct cachefiles_xattr {
uint16_t len;
uint8_t type;
uint8_t data[];
};
/*
* note change of state for daemon
*/
static inline void cachefiles_state_changed(struct cachefiles_cache *cache)
{
set_bit(CACHEFILES_STATE_CHANGED, &cache->flags);
wake_up_all(&cache->daemon_pollwq);
}
/*
* bind.c
*/
extern int cachefiles_daemon_bind(struct cachefiles_cache *cache, char *args);
extern void cachefiles_daemon_unbind(struct cachefiles_cache *cache);
/*
* daemon.c
*/
extern const struct file_operations cachefiles_daemon_fops;
extern int cachefiles_has_space(struct cachefiles_cache *cache,
unsigned fnr, unsigned bnr);
/*
* interface.c
*/
extern const struct fscache_cache_ops cachefiles_cache_ops;
/*
* key.c
*/
extern char *cachefiles_cook_key(const u8 *raw, int keylen, uint8_t type);
/*
* namei.c
*/
extern int cachefiles_delete_object(struct cachefiles_cache *cache,
struct cachefiles_object *object);
extern int cachefiles_walk_to_object(struct cachefiles_object *parent,
struct cachefiles_object *object,
const char *key,
struct cachefiles_xattr *auxdata);
extern struct dentry *cachefiles_get_directory(struct cachefiles_cache *cache,
struct dentry *dir,
const char *name);
extern int cachefiles_cull(struct cachefiles_cache *cache, struct dentry *dir,
char *filename);
extern int cachefiles_check_in_use(struct cachefiles_cache *cache,
struct dentry *dir, char *filename);
/*
* proc.c
*/
#ifdef CONFIG_CACHEFILES_HISTOGRAM
extern atomic_t cachefiles_lookup_histogram[HZ];
extern atomic_t cachefiles_mkdir_histogram[HZ];
extern atomic_t cachefiles_create_histogram[HZ];
extern int __init cachefiles_proc_init(void);
extern void cachefiles_proc_cleanup(void);
static inline
void cachefiles_hist(atomic_t histogram[], unsigned long start_jif)
{
unsigned long jif = jiffies - start_jif;
if (jif >= HZ)
jif = HZ - 1;
atomic_inc(&histogram[jif]);
}
#else
#define cachefiles_proc_init() (0)
#define cachefiles_proc_cleanup() do {} while (0)
#define cachefiles_hist(hist, start_jif) do {} while (0)
#endif
/*
* rdwr.c
*/
extern int cachefiles_read_or_alloc_page(struct fscache_retrieval *,
struct page *, gfp_t);
extern int cachefiles_read_or_alloc_pages(struct fscache_retrieval *,
struct list_head *, unsigned *,
gfp_t);
extern int cachefiles_allocate_page(struct fscache_retrieval *, struct page *,
gfp_t);
extern int cachefiles_allocate_pages(struct fscache_retrieval *,
struct list_head *, unsigned *, gfp_t);
extern int cachefiles_write_page(struct fscache_storage *, struct page *);
extern void cachefiles_uncache_page(struct fscache_object *, struct page *);
/*
* security.c
*/
extern int cachefiles_get_security_ID(struct cachefiles_cache *cache);
extern int cachefiles_determine_cache_security(struct cachefiles_cache *cache,
struct dentry *root,
const struct cred **_saved_cred);
static inline void cachefiles_begin_secure(struct cachefiles_cache *cache,
const struct cred **_saved_cred)
{
*_saved_cred = override_creds(cache->cache_cred);
}
static inline void cachefiles_end_secure(struct cachefiles_cache *cache,
const struct cred *saved_cred)
{
revert_creds(saved_cred);
}
/*
* xattr.c
*/
extern int cachefiles_check_object_type(struct cachefiles_object *object);
extern int cachefiles_set_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata);
extern int cachefiles_update_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata);
extern int cachefiles_check_object_xattr(struct cachefiles_object *object,
struct cachefiles_xattr *auxdata);
extern int cachefiles_remove_object_xattr(struct cachefiles_cache *cache,
struct dentry *dentry);
/*
* error handling
*/
#define kerror(FMT, ...) printk(KERN_ERR "CacheFiles: "FMT"\n", ##__VA_ARGS__)
#define cachefiles_io_error(___cache, FMT, ...) \
do { \
kerror("I/O Error: " FMT, ##__VA_ARGS__); \
fscache_io_error(&(___cache)->cache); \
set_bit(CACHEFILES_DEAD, &(___cache)->flags); \
} while (0)
#define cachefiles_io_error_obj(object, FMT, ...) \
do { \
struct cachefiles_cache *___cache; \
\
___cache = container_of((object)->fscache.cache, \
struct cachefiles_cache, cache); \
cachefiles_io_error(___cache, FMT, ##__VA_ARGS__); \
} while (0)
/*
* debug tracing
*/
#define dbgprintk(FMT, ...) \
printk(KERN_DEBUG "[%-6.6s] "FMT"\n", current->comm, ##__VA_ARGS__)
/* make sure we maintain the format strings, even when debugging is disabled */
static inline void _dbprintk(const char *fmt, ...)
__attribute__((format(printf, 1, 2)));
static inline void _dbprintk(const char *fmt, ...)
{
}
#define kenter(FMT, ...) dbgprintk("==> %s("FMT")", __func__, ##__VA_ARGS__)
#define kleave(FMT, ...) dbgprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__)
#define kdebug(FMT, ...) dbgprintk(FMT, ##__VA_ARGS__)
#if defined(__KDEBUG)
#define _enter(FMT, ...) kenter(FMT, ##__VA_ARGS__)
#define _leave(FMT, ...) kleave(FMT, ##__VA_ARGS__)
#define _debug(FMT, ...) kdebug(FMT, ##__VA_ARGS__)
#elif defined(CONFIG_CACHEFILES_DEBUG)
#define _enter(FMT, ...) \
do { \
if (cachefiles_debug & CACHEFILES_DEBUG_KENTER) \
kenter(FMT, ##__VA_ARGS__); \
} while (0)
#define _leave(FMT, ...) \
do { \
if (cachefiles_debug & CACHEFILES_DEBUG_KLEAVE) \
kleave(FMT, ##__VA_ARGS__); \
} while (0)
#define _debug(FMT, ...) \
do { \
if (cachefiles_debug & CACHEFILES_DEBUG_KDEBUG) \
kdebug(FMT, ##__VA_ARGS__); \
} while (0)
#else
#define _enter(FMT, ...) _dbprintk("==> %s("FMT")", __func__, ##__VA_ARGS__)
#define _leave(FMT, ...) _dbprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__)
#define _debug(FMT, ...) _dbprintk(FMT, ##__VA_ARGS__)
#endif
#if 1 /* defined(__KDEBUGALL) */
#define ASSERT(X) \
do { \
if (unlikely(!(X))) { \
printk(KERN_ERR "\n"); \
printk(KERN_ERR "CacheFiles: Assertion failed\n"); \
BUG(); \
} \
} while (0)
#define ASSERTCMP(X, OP, Y) \
do { \
if (unlikely(!((X) OP (Y)))) { \
printk(KERN_ERR "\n"); \
printk(KERN_ERR "CacheFiles: Assertion failed\n"); \
printk(KERN_ERR "%lx " #OP " %lx is false\n", \
(unsigned long)(X), (unsigned long)(Y)); \
BUG(); \
} \
} while (0)
#define ASSERTIF(C, X) \
do { \
if (unlikely((C) && !(X))) { \
printk(KERN_ERR "\n"); \
printk(KERN_ERR "CacheFiles: Assertion failed\n"); \
BUG(); \
} \
} while (0)
#define ASSERTIFCMP(C, X, OP, Y) \
do { \
if (unlikely((C) && !((X) OP (Y)))) { \
printk(KERN_ERR "\n"); \
printk(KERN_ERR "CacheFiles: Assertion failed\n"); \
printk(KERN_ERR "%lx " #OP " %lx is false\n", \
(unsigned long)(X), (unsigned long)(Y)); \
BUG(); \
} \
} while (0)
#else
#define ASSERT(X) do {} while (0)
#define ASSERTCMP(X, OP, Y) do {} while (0)
#define ASSERTIF(C, X) do {} while (0)
#define ASSERTIFCMP(C, X, OP, Y) do {} while (0)
#endif
| gpl-2.0 |
sreym/cdnjs | ajax/libs/pdf.js/1.3.177/pdf.js | 313996 | /* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint globalstrict: false */
/* umdutils ignore */
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define('pdfjs-dist/build/pdf', ['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.pdfjsDistBuildPdf = {}));
}
}(this, function (exports) {
// Use strict in our context only - users might not want it
'use strict';
var pdfjsVersion = '1.3.177';
var pdfjsBuild = '51b59bc';
var pdfjsFilePath =
typeof document !== 'undefined' && document.currentScript ?
document.currentScript.src : null;
var pdfjsLibs = {};
(function pdfjsWrapper() {
(function (root, factory) {
{
factory((root.pdfjsSharedGlobal = {}));
}
}(this, function (exports) {
var globalScope = (typeof window !== 'undefined') ? window :
(typeof global !== 'undefined') ? global :
(typeof self !== 'undefined') ? self : this;
var isWorker = (typeof window === 'undefined');
// The global PDFJS object exposes the API
// In production, it will be declared outside a global wrapper
// In development, it will be declared here
if (!globalScope.PDFJS) {
globalScope.PDFJS = {};
}
if (typeof pdfjsVersion !== 'undefined') {
globalScope.PDFJS.version = pdfjsVersion;
}
if (typeof pdfjsVersion !== 'undefined') {
globalScope.PDFJS.build = pdfjsBuild;
}
globalScope.PDFJS.pdfBug = false;
exports.globalScope = globalScope;
exports.isWorker = isWorker;
exports.PDFJS = globalScope.PDFJS;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedGlobal);
}
}(this, function (exports, sharedGlobal) {
var PDFJS = sharedGlobal.PDFJS;
/**
* Optimised CSS custom property getter/setter.
* @class
*/
var CustomStyle = (function CustomStyleClosure() {
// As noted on: http://www.zachstronaut.com/posts/2009/02/17/
// animate-css-transforms-firefox-webkit.html
// in some versions of IE9 it is critical that ms appear in this list
// before Moz
var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
var _cache = {};
function CustomStyle() {}
CustomStyle.getProp = function get(propName, element) {
// check cache only when no element is given
if (arguments.length === 1 && typeof _cache[propName] === 'string') {
return _cache[propName];
}
element = element || document.documentElement;
var style = element.style, prefixed, uPropName;
// test standard property first
if (typeof style[propName] === 'string') {
return (_cache[propName] = propName);
}
// capitalize
uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
// test vendor specific properties
for (var i = 0, l = prefixes.length; i < l; i++) {
prefixed = prefixes[i] + uPropName;
if (typeof style[prefixed] === 'string') {
return (_cache[propName] = prefixed);
}
}
//if all fails then set to undefined
return (_cache[propName] = 'undefined');
};
CustomStyle.setProp = function set(propName, element, str) {
var prop = this.getProp(propName);
if (prop !== 'undefined') {
element.style[prop] = str;
}
};
return CustomStyle;
})();
PDFJS.CustomStyle = CustomStyle;
exports.CustomStyle = CustomStyle;
}));
(function (root, factory) {
{
factory((root.pdfjsSharedUtil = {}), root.pdfjsSharedGlobal);
}
}(this, function (exports, sharedGlobal) {
var PDFJS = sharedGlobal.PDFJS;
var globalScope = sharedGlobal.globalScope;
var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
var TextRenderingMode = {
FILL: 0,
STROKE: 1,
FILL_STROKE: 2,
INVISIBLE: 3,
FILL_ADD_TO_PATH: 4,
STROKE_ADD_TO_PATH: 5,
FILL_STROKE_ADD_TO_PATH: 6,
ADD_TO_PATH: 7,
FILL_STROKE_MASK: 3,
ADD_TO_PATH_FLAG: 4
};
var ImageKind = {
GRAYSCALE_1BPP: 1,
RGB_24BPP: 2,
RGBA_32BPP: 3
};
var AnnotationType = {
TEXT: 1,
LINK: 2,
FREETEXT: 3,
LINE: 4,
SQUARE: 5,
CIRCLE: 6,
POLYGON: 7,
POLYLINE: 8,
HIGHLIGHT: 9,
UNDERLINE: 10,
SQUIGGLY: 11,
STRIKEOUT: 12,
STAMP: 13,
CARET: 14,
INK: 15,
POPUP: 16,
FILEATTACHMENT: 17,
SOUND: 18,
MOVIE: 19,
WIDGET: 20,
SCREEN: 21,
PRINTERMARK: 22,
TRAPNET: 23,
WATERMARK: 24,
THREED: 25,
REDACT: 26
};
var AnnotationFlag = {
INVISIBLE: 0x01,
HIDDEN: 0x02,
PRINT: 0x04,
NOZOOM: 0x08,
NOROTATE: 0x10,
NOVIEW: 0x20,
READONLY: 0x40,
LOCKED: 0x80,
TOGGLENOVIEW: 0x100,
LOCKEDCONTENTS: 0x200
};
var AnnotationBorderStyleType = {
SOLID: 1,
DASHED: 2,
BEVELED: 3,
INSET: 4,
UNDERLINE: 5
};
var StreamType = {
UNKNOWN: 0,
FLATE: 1,
LZW: 2,
DCT: 3,
JPX: 4,
JBIG: 5,
A85: 6,
AHX: 7,
CCF: 8,
RL: 9
};
var FontType = {
UNKNOWN: 0,
TYPE1: 1,
TYPE1C: 2,
CIDFONTTYPE0: 3,
CIDFONTTYPE0C: 4,
TRUETYPE: 5,
CIDFONTTYPE2: 6,
TYPE3: 7,
OPENTYPE: 8,
TYPE0: 9,
MMTYPE1: 10
};
PDFJS.VERBOSITY_LEVELS = {
errors: 0,
warnings: 1,
infos: 5
};
// All the possible operations for an operator list.
var OPS = PDFJS.OPS = {
// Intentionally start from 1 so it is easy to spot bad operators that will be
// 0's.
dependency: 1,
setLineWidth: 2,
setLineCap: 3,
setLineJoin: 4,
setMiterLimit: 5,
setDash: 6,
setRenderingIntent: 7,
setFlatness: 8,
setGState: 9,
save: 10,
restore: 11,
transform: 12,
moveTo: 13,
lineTo: 14,
curveTo: 15,
curveTo2: 16,
curveTo3: 17,
closePath: 18,
rectangle: 19,
stroke: 20,
closeStroke: 21,
fill: 22,
eoFill: 23,
fillStroke: 24,
eoFillStroke: 25,
closeFillStroke: 26,
closeEOFillStroke: 27,
endPath: 28,
clip: 29,
eoClip: 30,
beginText: 31,
endText: 32,
setCharSpacing: 33,
setWordSpacing: 34,
setHScale: 35,
setLeading: 36,
setFont: 37,
setTextRenderingMode: 38,
setTextRise: 39,
moveText: 40,
setLeadingMoveText: 41,
setTextMatrix: 42,
nextLine: 43,
showText: 44,
showSpacedText: 45,
nextLineShowText: 46,
nextLineSetSpacingShowText: 47,
setCharWidth: 48,
setCharWidthAndBounds: 49,
setStrokeColorSpace: 50,
setFillColorSpace: 51,
setStrokeColor: 52,
setStrokeColorN: 53,
setFillColor: 54,
setFillColorN: 55,
setStrokeGray: 56,
setFillGray: 57,
setStrokeRGBColor: 58,
setFillRGBColor: 59,
setStrokeCMYKColor: 60,
setFillCMYKColor: 61,
shadingFill: 62,
beginInlineImage: 63,
beginImageData: 64,
endInlineImage: 65,
paintXObject: 66,
markPoint: 67,
markPointProps: 68,
beginMarkedContent: 69,
beginMarkedContentProps: 70,
endMarkedContent: 71,
beginCompat: 72,
endCompat: 73,
paintFormXObjectBegin: 74,
paintFormXObjectEnd: 75,
beginGroup: 76,
endGroup: 77,
beginAnnotations: 78,
endAnnotations: 79,
beginAnnotation: 80,
endAnnotation: 81,
paintJpegXObject: 82,
paintImageMaskXObject: 83,
paintImageMaskXObjectGroup: 84,
paintImageXObject: 85,
paintInlineImageXObject: 86,
paintInlineImageXObjectGroup: 87,
paintImageXObjectRepeat: 88,
paintImageMaskXObjectRepeat: 89,
paintSolidColorImageMask: 90,
constructPath: 91
};
// A notice for devs. These are good for things that are helpful to devs, such
// as warning that Workers were disabled, which is important to devs but not
// end users.
function info(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
console.log('Info: ' + msg);
}
}
// Non-fatal warnings.
function warn(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
console.log('Warning: ' + msg);
}
}
// Deprecated API function -- treated as warnings.
function deprecated(details) {
warn('Deprecated API usage: ' + details);
}
// Fatal errors that should trigger the fallback UI and halt execution by
// throwing an exception.
function error(msg) {
if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
console.log('Error: ' + msg);
console.log(backtrace());
}
throw new Error(msg);
}
function backtrace() {
try {
throw new Error();
} catch (e) {
return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
}
}
function assert(cond, msg) {
if (!cond) {
error(msg);
}
}
var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
unknown: 'unknown',
forms: 'forms',
javaScript: 'javaScript',
smask: 'smask',
shadingPattern: 'shadingPattern',
font: 'font'
};
// Combines two URLs. The baseUrl shall be absolute URL. If the url is an
// absolute URL, it will be returned as is.
function combineUrl(baseUrl, url) {
if (!url) {
return baseUrl;
}
if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
return url;
}
var i;
if (url.charAt(0) === '/') {
// absolute path
i = baseUrl.indexOf('://');
if (url.charAt(1) === '/') {
++i;
} else {
i = baseUrl.indexOf('/', i + 3);
}
return baseUrl.substring(0, i) + url;
} else {
// relative path
var pathLength = baseUrl.length;
i = baseUrl.lastIndexOf('#');
pathLength = i >= 0 ? i : pathLength;
i = baseUrl.lastIndexOf('?', pathLength);
pathLength = i >= 0 ? i : pathLength;
var prefixLength = baseUrl.lastIndexOf('/', pathLength);
return baseUrl.substring(0, prefixLength + 1) + url;
}
}
// Validates if URL is safe and allowed, e.g. to avoid XSS.
function isValidUrl(url, allowRelative) {
if (!url) {
return false;
}
// RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
if (!protocol) {
return allowRelative;
}
protocol = protocol[0].toLowerCase();
switch (protocol) {
case 'http':
case 'https':
case 'ftp':
case 'mailto':
case 'tel':
return true;
default:
return false;
}
}
PDFJS.isValidUrl = isValidUrl;
function shadow(obj, prop, value) {
Object.defineProperty(obj, prop, { value: value,
enumerable: true,
configurable: true,
writable: false });
return value;
}
PDFJS.shadow = shadow;
var LinkTarget = PDFJS.LinkTarget = {
NONE: 0, // Default value.
SELF: 1,
BLANK: 2,
PARENT: 3,
TOP: 4,
};
var LinkTargetStringMap = [
'',
'_self',
'_blank',
'_parent',
'_top'
];
function isExternalLinkTargetSet() {
if (PDFJS.openExternalLinksInNewWindow) {
deprecated('PDFJS.openExternalLinksInNewWindow, please use ' +
'"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
if (PDFJS.externalLinkTarget === LinkTarget.NONE) {
PDFJS.externalLinkTarget = LinkTarget.BLANK;
}
// Reset the deprecated parameter, to suppress further warnings.
PDFJS.openExternalLinksInNewWindow = false;
}
switch (PDFJS.externalLinkTarget) {
case LinkTarget.NONE:
return false;
case LinkTarget.SELF:
case LinkTarget.BLANK:
case LinkTarget.PARENT:
case LinkTarget.TOP:
return true;
}
warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget);
// Reset the external link target, to suppress further warnings.
PDFJS.externalLinkTarget = LinkTarget.NONE;
return false;
}
PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet;
var PasswordResponses = PDFJS.PasswordResponses = {
NEED_PASSWORD: 1,
INCORRECT_PASSWORD: 2
};
var PasswordException = (function PasswordExceptionClosure() {
function PasswordException(msg, code) {
this.name = 'PasswordException';
this.message = msg;
this.code = code;
}
PasswordException.prototype = new Error();
PasswordException.constructor = PasswordException;
return PasswordException;
})();
PDFJS.PasswordException = PasswordException;
var UnknownErrorException = (function UnknownErrorExceptionClosure() {
function UnknownErrorException(msg, details) {
this.name = 'UnknownErrorException';
this.message = msg;
this.details = details;
}
UnknownErrorException.prototype = new Error();
UnknownErrorException.constructor = UnknownErrorException;
return UnknownErrorException;
})();
PDFJS.UnknownErrorException = UnknownErrorException;
var InvalidPDFException = (function InvalidPDFExceptionClosure() {
function InvalidPDFException(msg) {
this.name = 'InvalidPDFException';
this.message = msg;
}
InvalidPDFException.prototype = new Error();
InvalidPDFException.constructor = InvalidPDFException;
return InvalidPDFException;
})();
PDFJS.InvalidPDFException = InvalidPDFException;
var MissingPDFException = (function MissingPDFExceptionClosure() {
function MissingPDFException(msg) {
this.name = 'MissingPDFException';
this.message = msg;
}
MissingPDFException.prototype = new Error();
MissingPDFException.constructor = MissingPDFException;
return MissingPDFException;
})();
PDFJS.MissingPDFException = MissingPDFException;
var UnexpectedResponseException =
(function UnexpectedResponseExceptionClosure() {
function UnexpectedResponseException(msg, status) {
this.name = 'UnexpectedResponseException';
this.message = msg;
this.status = status;
}
UnexpectedResponseException.prototype = new Error();
UnexpectedResponseException.constructor = UnexpectedResponseException;
return UnexpectedResponseException;
})();
PDFJS.UnexpectedResponseException = UnexpectedResponseException;
var NotImplementedException = (function NotImplementedExceptionClosure() {
function NotImplementedException(msg) {
this.message = msg;
}
NotImplementedException.prototype = new Error();
NotImplementedException.prototype.name = 'NotImplementedException';
NotImplementedException.constructor = NotImplementedException;
return NotImplementedException;
})();
var MissingDataException = (function MissingDataExceptionClosure() {
function MissingDataException(begin, end) {
this.begin = begin;
this.end = end;
this.message = 'Missing data [' + begin + ', ' + end + ')';
}
MissingDataException.prototype = new Error();
MissingDataException.prototype.name = 'MissingDataException';
MissingDataException.constructor = MissingDataException;
return MissingDataException;
})();
var XRefParseException = (function XRefParseExceptionClosure() {
function XRefParseException(msg) {
this.message = msg;
}
XRefParseException.prototype = new Error();
XRefParseException.prototype.name = 'XRefParseException';
XRefParseException.constructor = XRefParseException;
return XRefParseException;
})();
var NullCharactersRegExp = /\x00/g;
function removeNullCharacters(str) {
if (typeof str !== 'string') {
warn('The argument for removeNullCharacters must be a string.');
return str;
}
return str.replace(NullCharactersRegExp, '');
}
PDFJS.removeNullCharacters = removeNullCharacters;
function bytesToString(bytes) {
assert(bytes !== null && typeof bytes === 'object' &&
bytes.length !== undefined, 'Invalid argument for bytesToString');
var length = bytes.length;
var MAX_ARGUMENT_COUNT = 8192;
if (length < MAX_ARGUMENT_COUNT) {
return String.fromCharCode.apply(null, bytes);
}
var strBuf = [];
for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
var chunk = bytes.subarray(i, chunkEnd);
strBuf.push(String.fromCharCode.apply(null, chunk));
}
return strBuf.join('');
}
function stringToBytes(str) {
assert(typeof str === 'string', 'Invalid argument for stringToBytes');
var length = str.length;
var bytes = new Uint8Array(length);
for (var i = 0; i < length; ++i) {
bytes[i] = str.charCodeAt(i) & 0xFF;
}
return bytes;
}
function string32(value) {
return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
(value >> 8) & 0xff, value & 0xff);
}
function log2(x) {
var n = 1, i = 0;
while (x > n) {
n <<= 1;
i++;
}
return i;
}
function readInt8(data, start) {
return (data[start] << 24) >> 24;
}
function readUint16(data, offset) {
return (data[offset] << 8) | data[offset + 1];
}
function readUint32(data, offset) {
return ((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]) >>> 0;
}
// Lazy test the endianness of the platform
// NOTE: This will be 'true' for simulated TypedArrays
function isLittleEndian() {
var buffer8 = new Uint8Array(2);
buffer8[0] = 1;
var buffer16 = new Uint16Array(buffer8.buffer);
return (buffer16[0] === 1);
}
Object.defineProperty(PDFJS, 'isLittleEndian', {
configurable: true,
get: function PDFJS_isLittleEndian() {
return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
}
});
// Lazy test if the userAgent support CanvasTypedArrays
function hasCanvasTypedArrays() {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
var imageData = ctx.createImageData(1, 1);
return (typeof imageData.data.buffer !== 'undefined');
}
Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
configurable: true,
get: function PDFJS_hasCanvasTypedArrays() {
return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
}
});
var Uint32ArrayView = (function Uint32ArrayViewClosure() {
function Uint32ArrayView(buffer, length) {
this.buffer = buffer;
this.byteLength = buffer.length;
this.length = length === undefined ? (this.byteLength >> 2) : length;
ensureUint32ArrayViewProps(this.length);
}
Uint32ArrayView.prototype = Object.create(null);
var uint32ArrayViewSetters = 0;
function createUint32ArrayProp(index) {
return {
get: function () {
var buffer = this.buffer, offset = index << 2;
return (buffer[offset] | (buffer[offset + 1] << 8) |
(buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
},
set: function (value) {
var buffer = this.buffer, offset = index << 2;
buffer[offset] = value & 255;
buffer[offset + 1] = (value >> 8) & 255;
buffer[offset + 2] = (value >> 16) & 255;
buffer[offset + 3] = (value >>> 24) & 255;
}
};
}
function ensureUint32ArrayViewProps(length) {
while (uint32ArrayViewSetters < length) {
Object.defineProperty(Uint32ArrayView.prototype,
uint32ArrayViewSetters,
createUint32ArrayProp(uint32ArrayViewSetters));
uint32ArrayViewSetters++;
}
}
return Uint32ArrayView;
})();
exports.Uint32ArrayView = Uint32ArrayView;
var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
var Util = PDFJS.Util = (function UtilClosure() {
function Util() {}
var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
// makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
// creating many intermediate strings.
Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
rgbBuf[1] = r;
rgbBuf[3] = g;
rgbBuf[5] = b;
return rgbBuf.join('');
};
// Concatenates two transformation matrices together and returns the result.
Util.transform = function Util_transform(m1, m2) {
return [
m1[0] * m2[0] + m1[2] * m2[1],
m1[1] * m2[0] + m1[3] * m2[1],
m1[0] * m2[2] + m1[2] * m2[3],
m1[1] * m2[2] + m1[3] * m2[3],
m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
];
};
// For 2d affine transforms
Util.applyTransform = function Util_applyTransform(p, m) {
var xt = p[0] * m[0] + p[1] * m[2] + m[4];
var yt = p[0] * m[1] + p[1] * m[3] + m[5];
return [xt, yt];
};
Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
var d = m[0] * m[3] - m[1] * m[2];
var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
return [xt, yt];
};
// Applies the transform to the rectangle and finds the minimum axially
// aligned bounding box.
Util.getAxialAlignedBoundingBox =
function Util_getAxialAlignedBoundingBox(r, m) {
var p1 = Util.applyTransform(r, m);
var p2 = Util.applyTransform(r.slice(2, 4), m);
var p3 = Util.applyTransform([r[0], r[3]], m);
var p4 = Util.applyTransform([r[2], r[1]], m);
return [
Math.min(p1[0], p2[0], p3[0], p4[0]),
Math.min(p1[1], p2[1], p3[1], p4[1]),
Math.max(p1[0], p2[0], p3[0], p4[0]),
Math.max(p1[1], p2[1], p3[1], p4[1])
];
};
Util.inverseTransform = function Util_inverseTransform(m) {
var d = m[0] * m[3] - m[1] * m[2];
return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
(m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
};
// Apply a generic 3d matrix M on a 3-vector v:
// | a b c | | X |
// | d e f | x | Y |
// | g h i | | Z |
// M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
// with v as [X,Y,Z]
Util.apply3dTransform = function Util_apply3dTransform(m, v) {
return [
m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
];
};
// This calculation uses Singular Value Decomposition.
// The SVD can be represented with formula A = USV. We are interested in the
// matrix S here because it represents the scale values.
Util.singularValueDecompose2dScale =
function Util_singularValueDecompose2dScale(m) {
var transpose = [m[0], m[2], m[1], m[3]];
// Multiply matrix m with its transpose.
var a = m[0] * transpose[0] + m[1] * transpose[2];
var b = m[0] * transpose[1] + m[1] * transpose[3];
var c = m[2] * transpose[0] + m[3] * transpose[2];
var d = m[2] * transpose[1] + m[3] * transpose[3];
// Solve the second degree polynomial to get roots.
var first = (a + d) / 2;
var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
var sx = first + second || 1;
var sy = first - second || 1;
// Scale values are the square roots of the eigenvalues.
return [Math.sqrt(sx), Math.sqrt(sy)];
};
// Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
// For coordinate systems whose origin lies in the bottom-left, this
// means normalization to (BL,TR) ordering. For systems with origin in the
// top-left, this means (TL,BR) ordering.
Util.normalizeRect = function Util_normalizeRect(rect) {
var r = rect.slice(0); // clone rect
if (rect[0] > rect[2]) {
r[0] = rect[2];
r[2] = rect[0];
}
if (rect[1] > rect[3]) {
r[1] = rect[3];
r[3] = rect[1];
}
return r;
};
// Returns a rectangle [x1, y1, x2, y2] corresponding to the
// intersection of rect1 and rect2. If no intersection, returns 'false'
// The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
Util.intersect = function Util_intersect(rect1, rect2) {
function compare(a, b) {
return a - b;
}
// Order points along the axes
var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
result = [];
rect1 = Util.normalizeRect(rect1);
rect2 = Util.normalizeRect(rect2);
// X: first and second points belong to different rectangles?
if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
(orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
// Intersection must be between second and third points
result[0] = orderedX[1];
result[2] = orderedX[2];
} else {
return false;
}
// Y: first and second points belong to different rectangles?
if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
(orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
// Intersection must be between second and third points
result[1] = orderedY[1];
result[3] = orderedY[2];
} else {
return false;
}
return result;
};
Util.sign = function Util_sign(num) {
return num < 0 ? -1 : 1;
};
Util.appendToArray = function Util_appendToArray(arr1, arr2) {
Array.prototype.push.apply(arr1, arr2);
};
Util.prependToArray = function Util_prependToArray(arr1, arr2) {
Array.prototype.unshift.apply(arr1, arr2);
};
Util.extendObj = function extendObj(obj1, obj2) {
for (var key in obj2) {
obj1[key] = obj2[key];
}
};
Util.getInheritableProperty = function Util_getInheritableProperty(dict,
name) {
while (dict && !dict.has(name)) {
dict = dict.get('Parent');
}
if (!dict) {
return null;
}
return dict.get(name);
};
Util.inherit = function Util_inherit(sub, base, prototype) {
sub.prototype = Object.create(base.prototype);
sub.prototype.constructor = sub;
for (var prop in prototype) {
sub.prototype[prop] = prototype[prop];
}
};
Util.loadScript = function Util_loadScript(src, callback) {
var script = document.createElement('script');
var loaded = false;
script.setAttribute('src', src);
if (callback) {
script.onload = function() {
if (!loaded) {
callback();
}
loaded = true;
};
}
document.getElementsByTagName('head')[0].appendChild(script);
};
return Util;
})();
/**
* PDF page viewport created based on scale, rotation and offset.
* @class
* @alias PDFJS.PageViewport
*/
var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
/**
* @constructor
* @private
* @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
* @param scale {number} scale of the viewport.
* @param rotation {number} rotations of the viewport in degrees.
* @param offsetX {number} offset X
* @param offsetY {number} offset Y
* @param dontFlip {boolean} if true, axis Y will not be flipped.
*/
function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
this.viewBox = viewBox;
this.scale = scale;
this.rotation = rotation;
this.offsetX = offsetX;
this.offsetY = offsetY;
// creating transform to convert pdf coordinate system to the normal
// canvas like coordinates taking in account scale and rotation
var centerX = (viewBox[2] + viewBox[0]) / 2;
var centerY = (viewBox[3] + viewBox[1]) / 2;
var rotateA, rotateB, rotateC, rotateD;
rotation = rotation % 360;
rotation = rotation < 0 ? rotation + 360 : rotation;
switch (rotation) {
case 180:
rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
break;
case 90:
rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
break;
case 270:
rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
break;
//case 0:
default:
rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
break;
}
if (dontFlip) {
rotateC = -rotateC; rotateD = -rotateD;
}
var offsetCanvasX, offsetCanvasY;
var width, height;
if (rotateA === 0) {
offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
width = Math.abs(viewBox[3] - viewBox[1]) * scale;
height = Math.abs(viewBox[2] - viewBox[0]) * scale;
} else {
offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
width = Math.abs(viewBox[2] - viewBox[0]) * scale;
height = Math.abs(viewBox[3] - viewBox[1]) * scale;
}
// creating transform for the following operations:
// translate(-centerX, -centerY), rotate and flip vertically,
// scale, and translate(offsetCanvasX, offsetCanvasY)
this.transform = [
rotateA * scale,
rotateB * scale,
rotateC * scale,
rotateD * scale,
offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
];
this.width = width;
this.height = height;
this.fontScale = scale;
}
PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
/**
* Clones viewport with additional properties.
* @param args {Object} (optional) If specified, may contain the 'scale' or
* 'rotation' properties to override the corresponding properties in
* the cloned viewport.
* @returns {PDFJS.PageViewport} Cloned viewport.
*/
clone: function PageViewPort_clone(args) {
args = args || {};
var scale = 'scale' in args ? args.scale : this.scale;
var rotation = 'rotation' in args ? args.rotation : this.rotation;
return new PageViewport(this.viewBox.slice(), scale, rotation,
this.offsetX, this.offsetY, args.dontFlip);
},
/**
* Converts PDF point to the viewport coordinates. For examples, useful for
* converting PDF location into canvas pixel coordinates.
* @param x {number} X coordinate.
* @param y {number} Y coordinate.
* @returns {Object} Object that contains 'x' and 'y' properties of the
* point in the viewport coordinate space.
* @see {@link convertToPdfPoint}
* @see {@link convertToViewportRectangle}
*/
convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
return Util.applyTransform([x, y], this.transform);
},
/**
* Converts PDF rectangle to the viewport coordinates.
* @param rect {Array} xMin, yMin, xMax and yMax coordinates.
* @returns {Array} Contains corresponding coordinates of the rectangle
* in the viewport coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToViewportRectangle:
function PageViewport_convertToViewportRectangle(rect) {
var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
var br = Util.applyTransform([rect[2], rect[3]], this.transform);
return [tl[0], tl[1], br[0], br[1]];
},
/**
* Converts viewport coordinates to the PDF location. For examples, useful
* for converting canvas pixel location into PDF one.
* @param x {number} X coordinate.
* @param y {number} Y coordinate.
* @returns {Object} Object that contains 'x' and 'y' properties of the
* point in the PDF coordinate space.
* @see {@link convertToViewportPoint}
*/
convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
return Util.applyInverseTransform([x, y], this.transform);
}
};
return PageViewport;
})();
var PDFStringTranslateTable = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
];
function stringToPDFString(str) {
var i, n = str.length, strBuf = [];
if (str[0] === '\xFE' && str[1] === '\xFF') {
// UTF16BE BOM
for (i = 2; i < n; i += 2) {
strBuf.push(String.fromCharCode(
(str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
}
} else {
for (i = 0; i < n; ++i) {
var code = PDFStringTranslateTable[str.charCodeAt(i)];
strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
}
}
return strBuf.join('');
}
function stringToUTF8String(str) {
return decodeURIComponent(escape(str));
}
function utf8StringToString(str) {
return unescape(encodeURIComponent(str));
}
function isEmptyObj(obj) {
for (var key in obj) {
return false;
}
return true;
}
function isBool(v) {
return typeof v === 'boolean';
}
function isInt(v) {
return typeof v === 'number' && ((v | 0) === v);
}
function isNum(v) {
return typeof v === 'number';
}
function isString(v) {
return typeof v === 'string';
}
function isArray(v) {
return v instanceof Array;
}
function isArrayBuffer(v) {
return typeof v === 'object' && v !== null && v.byteLength !== undefined;
}
/**
* Promise Capability object.
*
* @typedef {Object} PromiseCapability
* @property {Promise} promise - A promise object.
* @property {function} resolve - Fullfills the promise.
* @property {function} reject - Rejects the promise.
*/
/**
* Creates a promise capability object.
* @alias PDFJS.createPromiseCapability
*
* @return {PromiseCapability} A capability object contains:
* - a Promise, resolve and reject methods.
*/
function createPromiseCapability() {
var capability = {};
capability.promise = new Promise(function (resolve, reject) {
capability.resolve = resolve;
capability.reject = reject;
});
return capability;
}
PDFJS.createPromiseCapability = createPromiseCapability;
/**
* Polyfill for Promises:
* The following promise implementation tries to generally implement the
* Promise/A+ spec. Some notable differences from other promise libaries are:
* - There currently isn't a seperate deferred and promise object.
* - Unhandled rejections eventually show an error if they aren't handled.
*
* Based off of the work in:
* https://bugzilla.mozilla.org/show_bug.cgi?id=810490
*/
(function PromiseClosure() {
if (globalScope.Promise) {
// Promises existing in the DOM/Worker, checking presence of all/resolve
if (typeof globalScope.Promise.all !== 'function') {
globalScope.Promise.all = function (iterable) {
var count = 0, results = [], resolve, reject;
var promise = new globalScope.Promise(function (resolve_, reject_) {
resolve = resolve_;
reject = reject_;
});
iterable.forEach(function (p, i) {
count++;
p.then(function (result) {
results[i] = result;
count--;
if (count === 0) {
resolve(results);
}
}, reject);
});
if (count === 0) {
resolve(results);
}
return promise;
};
}
if (typeof globalScope.Promise.resolve !== 'function') {
globalScope.Promise.resolve = function (value) {
return new globalScope.Promise(function (resolve) { resolve(value); });
};
}
if (typeof globalScope.Promise.reject !== 'function') {
globalScope.Promise.reject = function (reason) {
return new globalScope.Promise(function (resolve, reject) {
reject(reason);
});
};
}
if (typeof globalScope.Promise.prototype.catch !== 'function') {
globalScope.Promise.prototype.catch = function (onReject) {
return globalScope.Promise.prototype.then(undefined, onReject);
};
}
return;
}
var STATUS_PENDING = 0;
var STATUS_RESOLVED = 1;
var STATUS_REJECTED = 2;
// In an attempt to avoid silent exceptions, unhandled rejections are
// tracked and if they aren't handled in a certain amount of time an
// error is logged.
var REJECTION_TIMEOUT = 500;
var HandlerManager = {
handlers: [],
running: false,
unhandledRejections: [],
pendingRejectionCheck: false,
scheduleHandlers: function scheduleHandlers(promise) {
if (promise._status === STATUS_PENDING) {
return;
}
this.handlers = this.handlers.concat(promise._handlers);
promise._handlers = [];
if (this.running) {
return;
}
this.running = true;
setTimeout(this.runHandlers.bind(this), 0);
},
runHandlers: function runHandlers() {
var RUN_TIMEOUT = 1; // ms
var timeoutAt = Date.now() + RUN_TIMEOUT;
while (this.handlers.length > 0) {
var handler = this.handlers.shift();
var nextStatus = handler.thisPromise._status;
var nextValue = handler.thisPromise._value;
try {
if (nextStatus === STATUS_RESOLVED) {
if (typeof handler.onResolve === 'function') {
nextValue = handler.onResolve(nextValue);
}
} else if (typeof handler.onReject === 'function') {
nextValue = handler.onReject(nextValue);
nextStatus = STATUS_RESOLVED;
if (handler.thisPromise._unhandledRejection) {
this.removeUnhandeledRejection(handler.thisPromise);
}
}
} catch (ex) {
nextStatus = STATUS_REJECTED;
nextValue = ex;
}
handler.nextPromise._updateStatus(nextStatus, nextValue);
if (Date.now() >= timeoutAt) {
break;
}
}
if (this.handlers.length > 0) {
setTimeout(this.runHandlers.bind(this), 0);
return;
}
this.running = false;
},
addUnhandledRejection: function addUnhandledRejection(promise) {
this.unhandledRejections.push({
promise: promise,
time: Date.now()
});
this.scheduleRejectionCheck();
},
removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
promise._unhandledRejection = false;
for (var i = 0; i < this.unhandledRejections.length; i++) {
if (this.unhandledRejections[i].promise === promise) {
this.unhandledRejections.splice(i);
i--;
}
}
},
scheduleRejectionCheck: function scheduleRejectionCheck() {
if (this.pendingRejectionCheck) {
return;
}
this.pendingRejectionCheck = true;
setTimeout(function rejectionCheck() {
this.pendingRejectionCheck = false;
var now = Date.now();
for (var i = 0; i < this.unhandledRejections.length; i++) {
if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
var unhandled = this.unhandledRejections[i].promise._value;
var msg = 'Unhandled rejection: ' + unhandled;
if (unhandled.stack) {
msg += '\n' + unhandled.stack;
}
warn(msg);
this.unhandledRejections.splice(i);
i--;
}
}
if (this.unhandledRejections.length) {
this.scheduleRejectionCheck();
}
}.bind(this), REJECTION_TIMEOUT);
}
};
function Promise(resolver) {
this._status = STATUS_PENDING;
this._handlers = [];
try {
resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
} catch (e) {
this._reject(e);
}
}
/**
* Builds a promise that is resolved when all the passed in promises are
* resolved.
* @param {array} array of data and/or promises to wait for.
* @return {Promise} New dependant promise.
*/
Promise.all = function Promise_all(promises) {
var resolveAll, rejectAll;
var deferred = new Promise(function (resolve, reject) {
resolveAll = resolve;
rejectAll = reject;
});
var unresolved = promises.length;
var results = [];
if (unresolved === 0) {
resolveAll(results);
return deferred;
}
function reject(reason) {
if (deferred._status === STATUS_REJECTED) {
return;
}
results = [];
rejectAll(reason);
}
for (var i = 0, ii = promises.length; i < ii; ++i) {
var promise = promises[i];
var resolve = (function(i) {
return function(value) {
if (deferred._status === STATUS_REJECTED) {
return;
}
results[i] = value;
unresolved--;
if (unresolved === 0) {
resolveAll(results);
}
};
})(i);
if (Promise.isPromise(promise)) {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
return deferred;
};
/**
* Checks if the value is likely a promise (has a 'then' function).
* @return {boolean} true if value is thenable
*/
Promise.isPromise = function Promise_isPromise(value) {
return value && typeof value.then === 'function';
};
/**
* Creates resolved promise
* @param value resolve value
* @returns {Promise}
*/
Promise.resolve = function Promise_resolve(value) {
return new Promise(function (resolve) { resolve(value); });
};
/**
* Creates rejected promise
* @param reason rejection value
* @returns {Promise}
*/
Promise.reject = function Promise_reject(reason) {
return new Promise(function (resolve, reject) { reject(reason); });
};
Promise.prototype = {
_status: null,
_value: null,
_handlers: null,
_unhandledRejection: null,
_updateStatus: function Promise__updateStatus(status, value) {
if (this._status === STATUS_RESOLVED ||
this._status === STATUS_REJECTED) {
return;
}
if (status === STATUS_RESOLVED &&
Promise.isPromise(value)) {
value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
this._updateStatus.bind(this, STATUS_REJECTED));
return;
}
this._status = status;
this._value = value;
if (status === STATUS_REJECTED && this._handlers.length === 0) {
this._unhandledRejection = true;
HandlerManager.addUnhandledRejection(this);
}
HandlerManager.scheduleHandlers(this);
},
_resolve: function Promise_resolve(value) {
this._updateStatus(STATUS_RESOLVED, value);
},
_reject: function Promise_reject(reason) {
this._updateStatus(STATUS_REJECTED, reason);
},
then: function Promise_then(onResolve, onReject) {
var nextPromise = new Promise(function (resolve, reject) {
this.resolve = resolve;
this.reject = reject;
});
this._handlers.push({
thisPromise: this,
onResolve: onResolve,
onReject: onReject,
nextPromise: nextPromise
});
HandlerManager.scheduleHandlers(this);
return nextPromise;
},
catch: function Promise_catch(onReject) {
return this.then(undefined, onReject);
}
};
globalScope.Promise = Promise;
})();
var StatTimer = (function StatTimerClosure() {
function rpad(str, pad, length) {
while (str.length < length) {
str += pad;
}
return str;
}
function StatTimer() {
this.started = {};
this.times = [];
this.enabled = true;
}
StatTimer.prototype = {
time: function StatTimer_time(name) {
if (!this.enabled) {
return;
}
if (name in this.started) {
warn('Timer is already running for ' + name);
}
this.started[name] = Date.now();
},
timeEnd: function StatTimer_timeEnd(name) {
if (!this.enabled) {
return;
}
if (!(name in this.started)) {
warn('Timer has not been started for ' + name);
}
this.times.push({
'name': name,
'start': this.started[name],
'end': Date.now()
});
// Remove timer from started so it can be called again.
delete this.started[name];
},
toString: function StatTimer_toString() {
var i, ii;
var times = this.times;
var out = '';
// Find the longest name for padding purposes.
var longest = 0;
for (i = 0, ii = times.length; i < ii; ++i) {
var name = times[i]['name'];
if (name.length > longest) {
longest = name.length;
}
}
for (i = 0, ii = times.length; i < ii; ++i) {
var span = times[i];
var duration = span.end - span.start;
out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
}
return out;
}
};
return StatTimer;
})();
PDFJS.createBlob = function createBlob(data, contentType) {
if (typeof Blob !== 'undefined') {
return new Blob([data], { type: contentType });
}
// Blob builder is deprecated in FF14 and removed in FF18.
var bb = new MozBlobBuilder();
bb.append(data);
return bb.getBlob(contentType);
};
PDFJS.createObjectURL = (function createObjectURLClosure() {
// Blob/createObjectURL is not available, falling back to data schema.
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
return function createObjectURL(data, contentType) {
if (!PDFJS.disableCreateObjectURL &&
typeof URL !== 'undefined' && URL.createObjectURL) {
var blob = PDFJS.createBlob(data, contentType);
return URL.createObjectURL(blob);
}
var buffer = 'data:' + contentType + ';base64,';
for (var i = 0, ii = data.length; i < ii; i += 3) {
var b1 = data[i] & 0xFF;
var b2 = data[i + 1] & 0xFF;
var b3 = data[i + 2] & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
}
return buffer;
};
})();
function MessageHandler(sourceName, targetName, comObj) {
this.sourceName = sourceName;
this.targetName = targetName;
this.comObj = comObj;
this.callbackIndex = 1;
this.postMessageTransfers = true;
var callbacksCapabilities = this.callbacksCapabilities = {};
var ah = this.actionHandler = {};
this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
var data = event.data;
if (data.targetName !== this.sourceName) {
return;
}
if (data.isReply) {
var callbackId = data.callbackId;
if (data.callbackId in callbacksCapabilities) {
var callback = callbacksCapabilities[callbackId];
delete callbacksCapabilities[callbackId];
if ('error' in data) {
callback.reject(data.error);
} else {
callback.resolve(data.data);
}
} else {
error('Cannot resolve callback ' + callbackId);
}
} else if (data.action in ah) {
var action = ah[data.action];
if (data.callbackId) {
var sourceName = this.sourceName;
var targetName = data.sourceName;
Promise.resolve().then(function () {
return action[0].call(action[1], data.data);
}).then(function (result) {
comObj.postMessage({
sourceName: sourceName,
targetName: targetName,
isReply: true,
callbackId: data.callbackId,
data: result
});
}, function (reason) {
if (reason instanceof Error) {
// Serialize error to avoid "DataCloneError"
reason = reason + '';
}
comObj.postMessage({
sourceName: sourceName,
targetName: targetName,
isReply: true,
callbackId: data.callbackId,
error: reason
});
});
} else {
action[0].call(action[1], data.data);
}
} else {
error('Unknown action from worker: ' + data.action);
}
}.bind(this);
comObj.addEventListener('message', this._onComObjOnMessage);
}
MessageHandler.prototype = {
on: function messageHandlerOn(actionName, handler, scope) {
var ah = this.actionHandler;
if (ah[actionName]) {
error('There is already an actionName called "' + actionName + '"');
}
ah[actionName] = [handler, scope];
},
/**
* Sends a message to the comObj to invoke the action with the supplied data.
* @param {String} actionName Action to call.
* @param {JSON} data JSON data to send.
* @param {Array} [transfers] Optional list of transfers/ArrayBuffers
*/
send: function messageHandlerSend(actionName, data, transfers) {
var message = {
sourceName: this.sourceName,
targetName: this.targetName,
action: actionName,
data: data
};
this.postMessage(message, transfers);
},
/**
* Sends a message to the comObj to invoke the action with the supplied data.
* Expects that other side will callback with the response.
* @param {String} actionName Action to call.
* @param {JSON} data JSON data to send.
* @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
* @returns {Promise} Promise to be resolved with response data.
*/
sendWithPromise:
function messageHandlerSendWithPromise(actionName, data, transfers) {
var callbackId = this.callbackIndex++;
var message = {
sourceName: this.sourceName,
targetName: this.targetName,
action: actionName,
data: data,
callbackId: callbackId
};
var capability = createPromiseCapability();
this.callbacksCapabilities[callbackId] = capability;
try {
this.postMessage(message, transfers);
} catch (e) {
capability.reject(e);
}
return capability.promise;
},
/**
* Sends raw message to the comObj.
* @private
* @param message {Object} Raw message.
* @param transfers List of transfers/ArrayBuffers, or undefined.
*/
postMessage: function (message, transfers) {
if (transfers && this.postMessageTransfers) {
this.comObj.postMessage(message, transfers);
} else {
this.comObj.postMessage(message);
}
},
destroy: function () {
this.comObj.removeEventListener('message', this._onComObjOnMessage);
}
};
function loadJpegStream(id, imageUrl, objs) {
var img = new Image();
img.onload = (function loadJpegStream_onloadClosure() {
objs.resolve(id, img);
});
img.onerror = (function loadJpegStream_onerrorClosure() {
objs.resolve(id, null);
warn('Error during JPEG image loading');
});
img.src = imageUrl;
}
exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
exports.OPS = OPS;
exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
exports.AnnotationFlag = AnnotationFlag;
exports.AnnotationType = AnnotationType;
exports.FontType = FontType;
exports.ImageKind = ImageKind;
exports.InvalidPDFException = InvalidPDFException;
exports.LinkTarget = LinkTarget;
exports.LinkTargetStringMap = LinkTargetStringMap;
exports.MessageHandler = MessageHandler;
exports.MissingDataException = MissingDataException;
exports.MissingPDFException = MissingPDFException;
exports.NotImplementedException = NotImplementedException;
exports.PasswordException = PasswordException;
exports.PasswordResponses = PasswordResponses;
exports.StatTimer = StatTimer;
exports.StreamType = StreamType;
exports.TextRenderingMode = TextRenderingMode;
exports.UnexpectedResponseException = UnexpectedResponseException;
exports.UnknownErrorException = UnknownErrorException;
exports.Util = Util;
exports.XRefParseException = XRefParseException;
exports.assert = assert;
exports.bytesToString = bytesToString;
exports.combineUrl = combineUrl;
exports.createPromiseCapability = createPromiseCapability;
exports.deprecated = deprecated;
exports.error = error;
exports.info = info;
exports.isArray = isArray;
exports.isArrayBuffer = isArrayBuffer;
exports.isBool = isBool;
exports.isEmptyObj = isEmptyObj;
exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
exports.isInt = isInt;
exports.isNum = isNum;
exports.isString = isString;
exports.isValidUrl = isValidUrl;
exports.loadJpegStream = loadJpegStream;
exports.log2 = log2;
exports.readInt8 = readInt8;
exports.readUint16 = readUint16;
exports.readUint32 = readUint32;
exports.removeNullCharacters = removeNullCharacters;
exports.shadow = shadow;
exports.string32 = string32;
exports.stringToBytes = stringToBytes;
exports.stringToPDFString = stringToPDFString;
exports.stringToUTF8String = stringToUTF8String;
exports.utf8StringToString = utf8StringToString;
exports.warn = warn;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayDOMUtils);
}
}(this, function (exports, sharedUtil, displayDOMUtils) {
var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
var AnnotationType = sharedUtil.AnnotationType;
var Util = sharedUtil.Util;
var isExternalLinkTargetSet = sharedUtil.isExternalLinkTargetSet;
var LinkTargetStringMap = sharedUtil.LinkTargetStringMap;
var removeNullCharacters = sharedUtil.removeNullCharacters;
var warn = sharedUtil.warn;
var CustomStyle = displayDOMUtils.CustomStyle;
/**
* @typedef {Object} AnnotationElementParameters
* @property {Object} data
* @property {HTMLDivElement} layer
* @property {PDFPage} page
* @property {PageViewport} viewport
* @property {IPDFLinkService} linkService
*/
/**
* @class
* @alias AnnotationElementFactory
*/
function AnnotationElementFactory() {}
AnnotationElementFactory.prototype =
/** @lends AnnotationElementFactory.prototype */ {
/**
* @param {AnnotationElementParameters} parameters
* @returns {AnnotationElement}
*/
create: function AnnotationElementFactory_create(parameters) {
var subtype = parameters.data.annotationType;
switch (subtype) {
case AnnotationType.LINK:
return new LinkAnnotationElement(parameters);
case AnnotationType.TEXT:
return new TextAnnotationElement(parameters);
case AnnotationType.WIDGET:
return new WidgetAnnotationElement(parameters);
case AnnotationType.POPUP:
return new PopupAnnotationElement(parameters);
case AnnotationType.HIGHLIGHT:
return new HighlightAnnotationElement(parameters);
case AnnotationType.UNDERLINE:
return new UnderlineAnnotationElement(parameters);
case AnnotationType.SQUIGGLY:
return new SquigglyAnnotationElement(parameters);
case AnnotationType.STRIKEOUT:
return new StrikeOutAnnotationElement(parameters);
default:
throw new Error('Unimplemented annotation type "' + subtype + '"');
}
}
};
/**
* @class
* @alias AnnotationElement
*/
var AnnotationElement = (function AnnotationElementClosure() {
function AnnotationElement(parameters) {
this.data = parameters.data;
this.layer = parameters.layer;
this.page = parameters.page;
this.viewport = parameters.viewport;
this.linkService = parameters.linkService;
this.container = this._createContainer();
}
AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ {
/**
* Create an empty container for the annotation's HTML element.
*
* @private
* @memberof AnnotationElement
* @returns {HTMLSectionElement}
*/
_createContainer: function AnnotationElement_createContainer() {
var data = this.data, page = this.page, viewport = this.viewport;
var container = document.createElement('section');
var width = data.rect[2] - data.rect[0];
var height = data.rect[3] - data.rect[1];
container.setAttribute('data-annotation-id', data.id);
// Do *not* modify `data.rect`, since that will corrupt the annotation
// position on subsequent calls to `_createContainer` (see issue 6804).
var rect = Util.normalizeRect([
data.rect[0],
page.view[3] - data.rect[1] + page.view[1],
data.rect[2],
page.view[3] - data.rect[3] + page.view[1]
]);
CustomStyle.setProp('transform', container,
'matrix(' + viewport.transform.join(',') + ')');
CustomStyle.setProp('transformOrigin', container,
-rect[0] + 'px ' + -rect[1] + 'px');
if (data.borderStyle.width > 0) {
container.style.borderWidth = data.borderStyle.width + 'px';
if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
// Underline styles only have a bottom border, so we do not need
// to adjust for all borders. This yields a similar result as
// Adobe Acrobat/Reader.
width = width - 2 * data.borderStyle.width;
height = height - 2 * data.borderStyle.width;
}
var horizontalRadius = data.borderStyle.horizontalCornerRadius;
var verticalRadius = data.borderStyle.verticalCornerRadius;
if (horizontalRadius > 0 || verticalRadius > 0) {
var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
CustomStyle.setProp('borderRadius', container, radius);
}
switch (data.borderStyle.style) {
case AnnotationBorderStyleType.SOLID:
container.style.borderStyle = 'solid';
break;
case AnnotationBorderStyleType.DASHED:
container.style.borderStyle = 'dashed';
break;
case AnnotationBorderStyleType.BEVELED:
warn('Unimplemented border style: beveled');
break;
case AnnotationBorderStyleType.INSET:
warn('Unimplemented border style: inset');
break;
case AnnotationBorderStyleType.UNDERLINE:
container.style.borderBottomStyle = 'solid';
break;
default:
break;
}
if (data.color) {
container.style.borderColor =
Util.makeCssRgb(data.color[0] | 0,
data.color[1] | 0,
data.color[2] | 0);
} else {
// Transparent (invisible) border, so do not draw it at all.
container.style.borderWidth = 0;
}
}
container.style.left = rect[0] + 'px';
container.style.top = rect[1] + 'px';
container.style.width = width + 'px';
container.style.height = height + 'px';
return container;
},
/**
* Render the annotation's HTML element in the empty container.
*
* @public
* @memberof AnnotationElement
*/
render: function AnnotationElement_render() {
throw new Error('Abstract method AnnotationElement.render called');
}
};
return AnnotationElement;
})();
/**
* @class
* @alias LinkAnnotationElement
*/
var LinkAnnotationElement = (function LinkAnnotationElementClosure() {
function LinkAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(LinkAnnotationElement, AnnotationElement, {
/**
* Render the link annotation's HTML element in the empty container.
*
* @public
* @memberof LinkAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function LinkAnnotationElement_render() {
this.container.className = 'linkAnnotation';
var link = document.createElement('a');
link.href = link.title = (this.data.url ?
removeNullCharacters(this.data.url) : '');
if (this.data.url && isExternalLinkTargetSet()) {
link.target = LinkTargetStringMap[PDFJS.externalLinkTarget];
}
// Strip referrer from the URL.
if (this.data.url) {
link.rel = PDFJS.externalLinkRel;
}
if (!this.data.url) {
if (this.data.action) {
this._bindNamedAction(link, this.data.action);
} else {
this._bindLink(link, ('dest' in this.data) ? this.data.dest : null);
}
}
this.container.appendChild(link);
return this.container;
},
/**
* Bind internal links to the link element.
*
* @private
* @param {Object} link
* @param {Object} destination
* @memberof LinkAnnotationElement
*/
_bindLink: function LinkAnnotationElement_bindLink(link, destination) {
var self = this;
link.href = this.linkService.getDestinationHash(destination);
link.onclick = function() {
if (destination) {
self.linkService.navigateTo(destination);
}
return false;
};
if (destination) {
link.className = 'internalLink';
}
},
/**
* Bind named actions to the link element.
*
* @private
* @param {Object} link
* @param {Object} action
* @memberof LinkAnnotationElement
*/
_bindNamedAction:
function LinkAnnotationElement_bindNamedAction(link, action) {
var self = this;
link.href = this.linkService.getAnchorUrl('');
link.onclick = function() {
self.linkService.executeNamedAction(action);
return false;
};
link.className = 'internalLink';
}
});
return LinkAnnotationElement;
})();
/**
* @class
* @alias TextAnnotationElement
*/
var TextAnnotationElement = (function TextAnnotationElementClosure() {
function TextAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(TextAnnotationElement, AnnotationElement, {
/**
* Render the text annotation's HTML element in the empty container.
*
* @public
* @memberof TextAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function TextAnnotationElement_render() {
this.container.className = 'textAnnotation';
var image = document.createElement('img');
image.style.height = this.container.style.height;
image.style.width = this.container.style.width;
image.src = PDFJS.imageResourcesPath + 'annotation-' +
this.data.name.toLowerCase() + '.svg';
image.alt = '[{{type}} Annotation]';
image.dataset.l10nId = 'text_annotation_type';
image.dataset.l10nArgs = JSON.stringify({type: this.data.name});
if (!this.data.hasPopup) {
var popupElement = new PopupElement({
container: this.container,
trigger: image,
color: this.data.color,
title: this.data.title,
contents: this.data.contents,
hideWrapper: true
});
var popup = popupElement.render();
// Position the popup next to the Text annotation's container.
popup.style.left = image.style.width;
this.container.appendChild(popup);
}
this.container.appendChild(image);
return this.container;
}
});
return TextAnnotationElement;
})();
/**
* @class
* @alias WidgetAnnotationElement
*/
var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() {
function WidgetAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(WidgetAnnotationElement, AnnotationElement, {
/**
* Render the widget annotation's HTML element in the empty container.
*
* @public
* @memberof WidgetAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function WidgetAnnotationElement_render() {
var content = document.createElement('div');
content.textContent = this.data.fieldValue;
var textAlignment = this.data.textAlignment;
content.style.textAlign = ['left', 'center', 'right'][textAlignment];
content.style.verticalAlign = 'middle';
content.style.display = 'table-cell';
var font = (this.data.fontRefName ?
this.page.commonObjs.getData(this.data.fontRefName) : null);
this._setTextStyle(content, font);
this.container.appendChild(content);
return this.container;
},
/**
* Apply text styles to the text in the element.
*
* @private
* @param {HTMLDivElement} element
* @param {Object} font
* @memberof WidgetAnnotationElement
*/
_setTextStyle:
function WidgetAnnotationElement_setTextStyle(element, font) {
// TODO: This duplicates some of the logic in CanvasGraphics.setFont().
var style = element.style;
style.fontSize = this.data.fontSize + 'px';
style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr');
if (!font) {
return;
}
style.fontWeight = (font.black ?
(font.bold ? '900' : 'bold') :
(font.bold ? 'bold' : 'normal'));
style.fontStyle = (font.italic ? 'italic' : 'normal');
// Use a reasonable default font if the font doesn't specify a fallback.
var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
style.fontFamily = fontFamily + fallbackName;
}
});
return WidgetAnnotationElement;
})();
/**
* @class
* @alias PopupAnnotationElement
*/
var PopupAnnotationElement = (function PopupAnnotationElementClosure() {
function PopupAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(PopupAnnotationElement, AnnotationElement, {
/**
* Render the popup annotation's HTML element in the empty container.
*
* @public
* @memberof PopupAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function PopupAnnotationElement_render() {
this.container.className = 'popupAnnotation';
var selector = '[data-annotation-id="' + this.data.parentId + '"]';
var parentElement = this.layer.querySelector(selector);
if (!parentElement) {
return this.container;
}
var popup = new PopupElement({
container: this.container,
trigger: parentElement,
color: this.data.color,
title: this.data.title,
contents: this.data.contents
});
// Position the popup next to the parent annotation's container.
// PDF viewers ignore a popup annotation's rectangle.
var parentLeft = parseFloat(parentElement.style.left);
var parentWidth = parseFloat(parentElement.style.width);
CustomStyle.setProp('transformOrigin', this.container,
-(parentLeft + parentWidth) + 'px -' +
parentElement.style.top);
this.container.style.left = (parentLeft + parentWidth) + 'px';
this.container.appendChild(popup.render());
return this.container;
}
});
return PopupAnnotationElement;
})();
/**
* @class
* @alias PopupElement
*/
var PopupElement = (function PopupElementClosure() {
var BACKGROUND_ENLIGHT = 0.7;
function PopupElement(parameters) {
this.container = parameters.container;
this.trigger = parameters.trigger;
this.color = parameters.color;
this.title = parameters.title;
this.contents = parameters.contents;
this.hideWrapper = parameters.hideWrapper || false;
this.pinned = false;
}
PopupElement.prototype = /** @lends PopupElement.prototype */ {
/**
* Render the popup's HTML element.
*
* @public
* @memberof PopupElement
* @returns {HTMLSectionElement}
*/
render: function PopupElement_render() {
var wrapper = document.createElement('div');
wrapper.className = 'popupWrapper';
// For Popup annotations we hide the entire section because it contains
// only the popup. However, for Text annotations without a separate Popup
// annotation, we cannot hide the entire container as the image would
// disappear too. In that special case, hiding the wrapper suffices.
this.hideElement = (this.hideWrapper ? wrapper : this.container);
this.hideElement.setAttribute('hidden', true);
var popup = document.createElement('div');
popup.className = 'popup';
var color = this.color;
if (color) {
// Enlighten the color.
var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
}
var contents = this._formatContents(this.contents);
var title = document.createElement('h1');
title.textContent = this.title;
// Attach the event listeners to the trigger element.
this.trigger.addEventListener('click', this._toggle.bind(this));
this.trigger.addEventListener('mouseover', this._show.bind(this, false));
this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
popup.addEventListener('click', this._hide.bind(this, true));
popup.appendChild(title);
popup.appendChild(contents);
wrapper.appendChild(popup);
return wrapper;
},
/**
* Format the contents of the popup by adding newlines where necessary.
*
* @private
* @param {string} contents
* @memberof PopupElement
* @returns {HTMLParagraphElement}
*/
_formatContents: function PopupElement_formatContents(contents) {
var p = document.createElement('p');
var lines = contents.split(/(?:\r\n?|\n)/);
for (var i = 0, ii = lines.length; i < ii; ++i) {
var line = lines[i];
p.appendChild(document.createTextNode(line));
if (i < (ii - 1)) {
p.appendChild(document.createElement('br'));
}
}
return p;
},
/**
* Toggle the visibility of the popup.
*
* @private
* @memberof PopupElement
*/
_toggle: function PopupElement_toggle() {
if (this.pinned) {
this._hide(true);
} else {
this._show(true);
}
},
/**
* Show the popup.
*
* @private
* @param {boolean} pin
* @memberof PopupElement
*/
_show: function PopupElement_show(pin) {
if (pin) {
this.pinned = true;
}
if (this.hideElement.hasAttribute('hidden')) {
this.hideElement.removeAttribute('hidden');
this.container.style.zIndex += 1;
}
},
/**
* Hide the popup.
*
* @private
* @param {boolean} unpin
* @memberof PopupElement
*/
_hide: function PopupElement_hide(unpin) {
if (unpin) {
this.pinned = false;
}
if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
this.hideElement.setAttribute('hidden', true);
this.container.style.zIndex -= 1;
}
}
};
return PopupElement;
})();
/**
* @class
* @alias HighlightAnnotationElement
*/
var HighlightAnnotationElement = (
function HighlightAnnotationElementClosure() {
function HighlightAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(HighlightAnnotationElement, AnnotationElement, {
/**
* Render the highlight annotation's HTML element in the empty container.
*
* @public
* @memberof HighlightAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function HighlightAnnotationElement_render() {
this.container.className = 'highlightAnnotation';
return this.container;
}
});
return HighlightAnnotationElement;
})();
/**
* @class
* @alias UnderlineAnnotationElement
*/
var UnderlineAnnotationElement = (
function UnderlineAnnotationElementClosure() {
function UnderlineAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
/**
* Render the underline annotation's HTML element in the empty container.
*
* @public
* @memberof UnderlineAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function UnderlineAnnotationElement_render() {
this.container.className = 'underlineAnnotation';
return this.container;
}
});
return UnderlineAnnotationElement;
})();
/**
* @class
* @alias SquigglyAnnotationElement
*/
var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() {
function SquigglyAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
/**
* Render the squiggly annotation's HTML element in the empty container.
*
* @public
* @memberof SquigglyAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function SquigglyAnnotationElement_render() {
this.container.className = 'squigglyAnnotation';
return this.container;
}
});
return SquigglyAnnotationElement;
})();
/**
* @class
* @alias StrikeOutAnnotationElement
*/
var StrikeOutAnnotationElement = (
function StrikeOutAnnotationElementClosure() {
function StrikeOutAnnotationElement(parameters) {
AnnotationElement.call(this, parameters);
}
Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
/**
* Render the strikeout annotation's HTML element in the empty container.
*
* @public
* @memberof StrikeOutAnnotationElement
* @returns {HTMLSectionElement}
*/
render: function StrikeOutAnnotationElement_render() {
this.container.className = 'strikeoutAnnotation';
return this.container;
}
});
return StrikeOutAnnotationElement;
})();
/**
* @typedef {Object} AnnotationLayerParameters
* @property {PageViewport} viewport
* @property {HTMLDivElement} div
* @property {Array} annotations
* @property {PDFPage} page
* @property {IPDFLinkService} linkService
*/
/**
* @class
* @alias AnnotationLayer
*/
var AnnotationLayer = (function AnnotationLayerClosure() {
return {
/**
* Render a new annotation layer with all annotation elements.
*
* @public
* @param {AnnotationLayerParameters} parameters
* @memberof AnnotationLayer
*/
render: function AnnotationLayer_render(parameters) {
var annotationElementFactory = new AnnotationElementFactory();
for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
var data = parameters.annotations[i];
if (!data || !data.hasHtml) {
continue;
}
var properties = {
data: data,
layer: parameters.div,
page: parameters.page,
viewport: parameters.viewport,
linkService: parameters.linkService
};
var element = annotationElementFactory.create(properties);
parameters.div.appendChild(element.render());
}
},
/**
* Update the annotation elements on existing annotation layer.
*
* @public
* @param {AnnotationLayerParameters} parameters
* @memberof AnnotationLayer
*/
update: function AnnotationLayer_update(parameters) {
for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
var data = parameters.annotations[i];
var element = parameters.div.querySelector(
'[data-annotation-id="' + data.id + '"]');
if (element) {
CustomStyle.setProp('transform', element,
'matrix(' + parameters.viewport.transform.join(',') + ')');
}
}
parameters.div.removeAttribute('hidden');
}
};
})();
PDFJS.AnnotationLayer = AnnotationLayer;
exports.AnnotationLayer = AnnotationLayer;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil,
root.pdfjsSharedGlobal);
}
}(this, function (exports, sharedUtil, sharedGlobal) {
var assert = sharedUtil.assert;
var bytesToString = sharedUtil.bytesToString;
var string32 = sharedUtil.string32;
var shadow = sharedUtil.shadow;
var warn = sharedUtil.warn;
var PDFJS = sharedGlobal.PDFJS;
var globalScope = sharedGlobal.globalScope;
var isWorker = sharedGlobal.isWorker;
function FontLoader(docId) {
this.docId = docId;
this.styleElement = null;
this.nativeFontFaces = [];
this.loadTestFontId = 0;
this.loadingContext = {
requests: [],
nextRequestId: 0
};
}
FontLoader.prototype = {
insertRule: function fontLoaderInsertRule(rule) {
var styleElement = this.styleElement;
if (!styleElement) {
styleElement = this.styleElement = document.createElement('style');
styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
document.documentElement.getElementsByTagName('head')[0].appendChild(
styleElement);
}
var styleSheet = styleElement.sheet;
styleSheet.insertRule(rule, styleSheet.cssRules.length);
},
clear: function fontLoaderClear() {
var styleElement = this.styleElement;
if (styleElement) {
styleElement.parentNode.removeChild(styleElement);
styleElement = this.styleElement = null;
}
this.nativeFontFaces.forEach(function(nativeFontFace) {
document.fonts.delete(nativeFontFace);
});
this.nativeFontFaces.length = 0;
},
get loadTestFont() {
// This is a CFF font with 1 glyph for '.' that fills its entire width and
// height.
return shadow(this, 'loadTestFont', atob(
'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
'ABAAAAAAAAAAAD6AAAAAAAAA=='
));
},
addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
this.nativeFontFaces.push(nativeFontFace);
document.fonts.add(nativeFontFace);
},
bind: function fontLoaderBind(fonts, callback) {
assert(!isWorker, 'bind() shall be called from main thread');
var rules = [];
var fontsToLoad = [];
var fontLoadPromises = [];
var getNativeFontPromise = function(nativeFontFace) {
// Return a promise that is always fulfilled, even when the font fails to
// load.
return nativeFontFace.loaded.catch(function(e) {
warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
});
};
for (var i = 0, ii = fonts.length; i < ii; i++) {
var font = fonts[i];
// Add the font to the DOM only once or skip if the font
// is already loaded.
if (font.attached || font.loading === false) {
continue;
}
font.attached = true;
if (FontLoader.isFontLoadingAPISupported) {
var nativeFontFace = font.createNativeFontFace();
if (nativeFontFace) {
this.addNativeFontFace(nativeFontFace);
fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
}
} else {
var rule = font.createFontFaceRule();
if (rule) {
this.insertRule(rule);
rules.push(rule);
fontsToLoad.push(font);
}
}
}
var request = this.queueLoadingCallback(callback);
if (FontLoader.isFontLoadingAPISupported) {
Promise.all(fontLoadPromises).then(function() {
request.complete();
});
} else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
this.prepareFontLoadEvent(rules, fontsToLoad, request);
} else {
request.complete();
}
},
queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
function LoadLoader_completeRequest() {
assert(!request.end, 'completeRequest() cannot be called twice');
request.end = Date.now();
// sending all completed requests in order how they were queued
while (context.requests.length > 0 && context.requests[0].end) {
var otherRequest = context.requests.shift();
setTimeout(otherRequest.callback, 0);
}
}
var context = this.loadingContext;
var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
var request = {
id: requestId,
complete: LoadLoader_completeRequest,
callback: callback,
started: Date.now()
};
context.requests.push(request);
return request;
},
prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
fonts,
request) {
/** Hack begin */
// There's currently no event when a font has finished downloading so the
// following code is a dirty hack to 'guess' when a font is
// ready. It's assumed fonts are loaded in order, so add a known test
// font after the desired fonts and then test for the loading of that
// test font.
function int32(data, offset) {
return (data.charCodeAt(offset) << 24) |
(data.charCodeAt(offset + 1) << 16) |
(data.charCodeAt(offset + 2) << 8) |
(data.charCodeAt(offset + 3) & 0xff);
}
function spliceString(s, offset, remove, insert) {
var chunk1 = s.substr(0, offset);
var chunk2 = s.substr(offset + remove);
return chunk1 + insert + chunk2;
}
var i, ii;
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
var ctx = canvas.getContext('2d');
var called = 0;
function isFontReady(name, callback) {
called++;
// With setTimeout clamping this gives the font ~100ms to load.
if(called > 30) {
warn('Load test font never loaded.');
callback();
return;
}
ctx.font = '30px ' + name;
ctx.fillText('.', 0, 20);
var imageData = ctx.getImageData(0, 0, 1, 1);
if (imageData.data[3] > 0) {
callback();
return;
}
setTimeout(isFontReady.bind(null, name, callback));
}
var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
// Chromium seems to cache fonts based on a hash of the actual font data,
// so the font must be modified for each load test else it will appear to
// be loaded already.
// TODO: This could maybe be made faster by avoiding the btoa of the full
// font by splitting it in chunks before hand and padding the font id.
var data = this.loadTestFont;
var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
loadTestFontId);
// CFF checksum is important for IE, adjusting it
var CFF_CHECKSUM_OFFSET = 16;
var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
var checksum = int32(data, CFF_CHECKSUM_OFFSET);
for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
}
if (i < loadTestFontId.length) { // align to 4 bytes boundary
checksum = (checksum - XXXX_VALUE +
int32(loadTestFontId + 'XXX', i)) | 0;
}
data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
url + '}';
this.insertRule(rule);
var names = [];
for (i = 0, ii = fonts.length; i < ii; i++) {
names.push(fonts[i].loadedName);
}
names.push(loadTestFontId);
var div = document.createElement('div');
div.setAttribute('style',
'visibility: hidden;' +
'width: 10px; height: 10px;' +
'position: absolute; top: 0px; left: 0px;');
for (i = 0, ii = names.length; i < ii; ++i) {
var span = document.createElement('span');
span.textContent = 'Hi';
span.style.fontFamily = names[i];
div.appendChild(span);
}
document.body.appendChild(div);
isFontReady(loadTestFontId, function() {
document.body.removeChild(div);
request.complete();
});
/** Hack end */
}
};
FontLoader.isFontLoadingAPISupported = (!isWorker &&
typeof document !== 'undefined' && !!document.fonts);
Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
get: function () {
var supported = false;
// User agent string sniffing is bad, but there is no reliable way to tell
// if font is fully loaded and ready to be used with canvas.
var userAgent = window.navigator.userAgent;
var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
if (m && m[1] >= 14) {
supported = true;
}
// TODO other browsers
if (userAgent === 'node') {
supported = true;
}
return shadow(FontLoader, 'isSyncFontLoadingSupported', supported);
},
enumerable: true,
configurable: true
});
var FontFaceObject = (function FontFaceObjectClosure() {
function FontFaceObject(translatedData) {
this.compiledGlyphs = {};
// importing translated data
for (var i in translatedData) {
this[i] = translatedData[i];
}
}
Object.defineProperty(FontFaceObject, 'isEvalSupported', {
get: function () {
var evalSupport = false;
if (PDFJS.isEvalSupported) {
try {
/* jshint evil: true */
new Function('');
evalSupport = true;
} catch (e) {}
}
return shadow(this, 'isEvalSupported', evalSupport);
},
enumerable: true,
configurable: true
});
FontFaceObject.prototype = {
createNativeFontFace: function FontFaceObject_createNativeFontFace() {
if (!this.data) {
return null;
}
if (PDFJS.disableFontFace) {
this.disableFontFace = true;
return null;
}
var nativeFontFace = new FontFace(this.loadedName, this.data, {});
if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
globalScope['FontInspector'].enabled) {
globalScope['FontInspector'].fontAdded(this);
}
return nativeFontFace;
},
createFontFaceRule: function FontFaceObject_createFontFaceRule() {
if (!this.data) {
return null;
}
if (PDFJS.disableFontFace) {
this.disableFontFace = true;
return null;
}
var data = bytesToString(new Uint8Array(this.data));
var fontName = this.loadedName;
// Add the font-face rule to the document
var url = ('url(data:' + this.mimetype + ';base64,' +
window.btoa(data) + ');');
var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
globalScope['FontInspector'].enabled) {
globalScope['FontInspector'].fontAdded(this, url);
}
return rule;
},
getPathGenerator:
function FontFaceObject_getPathGenerator(objs, character) {
if (!(character in this.compiledGlyphs)) {
var cmds = objs.get(this.loadedName + '_path_' + character);
var current, i, len;
// If we can, compile cmds into JS for MAXIMUM SPEED
if (FontFaceObject.isEvalSupported) {
var args, js = '';
for (i = 0, len = cmds.length; i < len; i++) {
current = cmds[i];
if (current.args !== undefined) {
args = current.args.join(',');
} else {
args = '';
}
js += 'c.' + current.cmd + '(' + args + ');\n';
}
/* jshint -W054 */
this.compiledGlyphs[character] = new Function('c', 'size', js);
} else {
// But fall back on using Function.prototype.apply() if we're
// blocked from using eval() for whatever reason (like CSP policies)
this.compiledGlyphs[character] = function(c, size) {
for (i = 0, len = cmds.length; i < len; i++) {
current = cmds[i];
if (current.cmd === 'scale') {
current.args = [size, -size];
}
c[current.cmd].apply(c, current.args);
}
};
}
}
return this.compiledGlyphs[character];
}
};
return FontFaceObject;
})();
exports.FontFaceObject = FontFaceObject;
exports.FontLoader = FontLoader;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil);
}
}(this, function (exports, sharedUtil) {
var error = sharedUtil.error;
var Metadata = PDFJS.Metadata = (function MetadataClosure() {
function fixMetadata(meta) {
return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
function(code, d1, d2, d3) {
return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
});
var chars = '';
for (var i = 0; i < bytes.length; i += 2) {
var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
code !== 38 && false ? String.fromCharCode(code) :
'&#x' + (0x10000 + code).toString(16).substring(1) + ';';
}
return '>' + chars;
});
}
function Metadata(meta) {
if (typeof meta === 'string') {
// Ghostscript produces invalid metadata
meta = fixMetadata(meta);
var parser = new DOMParser();
meta = parser.parseFromString(meta, 'application/xml');
} else if (!(meta instanceof Document)) {
error('Metadata: Invalid metadata object');
}
this.metaDocument = meta;
this.metadata = {};
this.parse();
}
Metadata.prototype = {
parse: function Metadata_parse() {
var doc = this.metaDocument;
var rdf = doc.documentElement;
if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
rdf = rdf.firstChild;
while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
rdf = rdf.nextSibling;
}
}
var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
return;
}
var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
for (i = 0, length = children.length; i < length; i++) {
desc = children[i];
if (desc.nodeName.toLowerCase() !== 'rdf:description') {
continue;
}
for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
entry = desc.childNodes[ii];
name = entry.nodeName.toLowerCase();
this.metadata[name] = entry.textContent.trim();
}
}
}
},
get: function Metadata_get(name) {
return this.metadata[name] || null;
},
has: function Metadata_has(name) {
return typeof this.metadata[name] !== 'undefined';
}
};
return Metadata;
})();
exports.Metadata = Metadata;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil);
}
}(this, function (exports, sharedUtil) {
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
var ImageKind = sharedUtil.ImageKind;
var OPS = sharedUtil.OPS;
var Util = sharedUtil.Util;
var isNum = sharedUtil.isNum;
var isArray = sharedUtil.isArray;
var warn = sharedUtil.warn;
var SVG_DEFAULTS = {
fontStyle: 'normal',
fontWeight: 'normal',
fillColor: '#000000'
};
var convertImgDataToPng = (function convertImgDataToPngClosure() {
var PNG_HEADER =
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
var CHUNK_WRAPPER_SIZE = 12;
var crcTable = new Int32Array(256);
for (var i = 0; i < 256; i++) {
var c = i;
for (var h = 0; h < 8; h++) {
if (c & 1) {
c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
} else {
c = (c >> 1) & 0x7fffffff;
}
}
crcTable[i] = c;
}
function crc32(data, start, end) {
var crc = -1;
for (var i = start; i < end; i++) {
var a = (crc ^ data[i]) & 0xff;
var b = crcTable[a];
crc = (crc >>> 8) ^ b;
}
return crc ^ -1;
}
function writePngChunk(type, body, data, offset) {
var p = offset;
var len = body.length;
data[p] = len >> 24 & 0xff;
data[p + 1] = len >> 16 & 0xff;
data[p + 2] = len >> 8 & 0xff;
data[p + 3] = len & 0xff;
p += 4;
data[p] = type.charCodeAt(0) & 0xff;
data[p + 1] = type.charCodeAt(1) & 0xff;
data[p + 2] = type.charCodeAt(2) & 0xff;
data[p + 3] = type.charCodeAt(3) & 0xff;
p += 4;
data.set(body, p);
p += body.length;
var crc = crc32(data, offset + 4, p);
data[p] = crc >> 24 & 0xff;
data[p + 1] = crc >> 16 & 0xff;
data[p + 2] = crc >> 8 & 0xff;
data[p + 3] = crc & 0xff;
}
function adler32(data, start, end) {
var a = 1;
var b = 0;
for (var i = start; i < end; ++i) {
a = (a + (data[i] & 0xff)) % 65521;
b = (b + a) % 65521;
}
return (b << 16) | a;
}
function encode(imgData, kind) {
var width = imgData.width;
var height = imgData.height;
var bitDepth, colorType, lineSize;
var bytes = imgData.data;
switch (kind) {
case ImageKind.GRAYSCALE_1BPP:
colorType = 0;
bitDepth = 1;
lineSize = (width + 7) >> 3;
break;
case ImageKind.RGB_24BPP:
colorType = 2;
bitDepth = 8;
lineSize = width * 3;
break;
case ImageKind.RGBA_32BPP:
colorType = 6;
bitDepth = 8;
lineSize = width * 4;
break;
default:
throw new Error('invalid format');
}
// prefix every row with predictor 0
var literals = new Uint8Array((1 + lineSize) * height);
var offsetLiterals = 0, offsetBytes = 0;
var y, i;
for (y = 0; y < height; ++y) {
literals[offsetLiterals++] = 0; // no prediction
literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
offsetLiterals);
offsetBytes += lineSize;
offsetLiterals += lineSize;
}
if (kind === ImageKind.GRAYSCALE_1BPP) {
// inverting for B/W
offsetLiterals = 0;
for (y = 0; y < height; y++) {
offsetLiterals++; // skipping predictor
for (i = 0; i < lineSize; i++) {
literals[offsetLiterals++] ^= 0xFF;
}
}
}
var ihdr = new Uint8Array([
width >> 24 & 0xff,
width >> 16 & 0xff,
width >> 8 & 0xff,
width & 0xff,
height >> 24 & 0xff,
height >> 16 & 0xff,
height >> 8 & 0xff,
height & 0xff,
bitDepth, // bit depth
colorType, // color type
0x00, // compression method
0x00, // filter method
0x00 // interlace method
]);
var len = literals.length;
var maxBlockLength = 0xFFFF;
var deflateBlocks = Math.ceil(len / maxBlockLength);
var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
var pi = 0;
idat[pi++] = 0x78; // compression method and flags
idat[pi++] = 0x9c; // flags
var pos = 0;
while (len > maxBlockLength) {
// writing non-final DEFLATE blocks type 0 and length of 65535
idat[pi++] = 0x00;
idat[pi++] = 0xff;
idat[pi++] = 0xff;
idat[pi++] = 0x00;
idat[pi++] = 0x00;
idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
pi += maxBlockLength;
pos += maxBlockLength;
len -= maxBlockLength;
}
// writing non-final DEFLATE blocks type 0
idat[pi++] = 0x01;
idat[pi++] = len & 0xff;
idat[pi++] = len >> 8 & 0xff;
idat[pi++] = (~len & 0xffff) & 0xff;
idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
idat.set(literals.subarray(pos), pi);
pi += literals.length - pos;
var adler = adler32(literals, 0, literals.length); // checksum
idat[pi++] = adler >> 24 & 0xff;
idat[pi++] = adler >> 16 & 0xff;
idat[pi++] = adler >> 8 & 0xff;
idat[pi++] = adler & 0xff;
// PNG will consists: header, IHDR+data, IDAT+data, and IEND.
var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
ihdr.length + idat.length;
var data = new Uint8Array(pngLength);
var offset = 0;
data.set(PNG_HEADER, offset);
offset += PNG_HEADER.length;
writePngChunk('IHDR', ihdr, data, offset);
offset += CHUNK_WRAPPER_SIZE + ihdr.length;
writePngChunk('IDATA', idat, data, offset);
offset += CHUNK_WRAPPER_SIZE + idat.length;
writePngChunk('IEND', new Uint8Array(0), data, offset);
return PDFJS.createObjectURL(data, 'image/png');
}
return function convertImgDataToPng(imgData) {
var kind = (imgData.kind === undefined ?
ImageKind.GRAYSCALE_1BPP : imgData.kind);
return encode(imgData, kind);
};
})();
var SVGExtraState = (function SVGExtraStateClosure() {
function SVGExtraState() {
this.fontSizeScale = 1;
this.fontWeight = SVG_DEFAULTS.fontWeight;
this.fontSize = 0;
this.textMatrix = IDENTITY_MATRIX;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.leading = 0;
// Current point (in user coordinates)
this.x = 0;
this.y = 0;
// Start of text line (in text coordinates)
this.lineX = 0;
this.lineY = 0;
// Character and word spacing
this.charSpacing = 0;
this.wordSpacing = 0;
this.textHScale = 1;
this.textRise = 0;
// Default foreground and background colors
this.fillColor = SVG_DEFAULTS.fillColor;
this.strokeColor = '#000000';
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.lineJoin = '';
this.lineCap = '';
this.miterLimit = 0;
this.dashArray = [];
this.dashPhase = 0;
this.dependencies = [];
// Clipping
this.clipId = '';
this.pendingClip = false;
this.maskId = '';
}
SVGExtraState.prototype = {
clone: function SVGExtraState_clone() {
return Object.create(this);
},
setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
this.x = x;
this.y = y;
}
};
return SVGExtraState;
})();
var SVGGraphics = (function SVGGraphicsClosure() {
function createScratchSVG(width, height) {
var NS = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(NS, 'svg:svg');
svg.setAttributeNS(null, 'version', '1.1');
svg.setAttributeNS(null, 'width', width + 'px');
svg.setAttributeNS(null, 'height', height + 'px');
svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
return svg;
}
function opListToTree(opList) {
var opTree = [];
var tmp = [];
var opListLen = opList.length;
for (var x = 0; x < opListLen; x++) {
if (opList[x].fn === 'save') {
opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
tmp.push(opTree);
opTree = opTree[opTree.length - 1].items;
continue;
}
if(opList[x].fn === 'restore') {
opTree = tmp.pop();
} else {
opTree.push(opList[x]);
}
}
return opTree;
}
/**
* Formats float number.
* @param value {number} number to format.
* @returns {string}
*/
function pf(value) {
if (value === (value | 0)) { // integer number
return value.toString();
}
var s = value.toFixed(10);
var i = s.length - 1;
if (s[i] !== '0') {
return s;
}
// removing trailing zeros
do {
i--;
} while (s[i] === '0');
return s.substr(0, s[i] === '.' ? i : i + 1);
}
/**
* Formats transform matrix. The standard rotation, scale and translate
* matrices are replaced by their shorter forms, and for identity matrix
* returns empty string to save the memory.
* @param m {Array} matrix to format.
* @returns {string}
*/
function pm(m) {
if (m[4] === 0 && m[5] === 0) {
if (m[1] === 0 && m[2] === 0) {
if (m[0] === 1 && m[3] === 1) {
return '';
}
return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
}
if (m[0] === m[3] && m[1] === -m[2]) {
var a = Math.acos(m[0]) * 180 / Math.PI;
return 'rotate(' + pf(a) + ')';
}
} else {
if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
}
}
return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
}
function SVGGraphics(commonObjs, objs) {
this.current = new SVGExtraState();
this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
this.transformStack = [];
this.extraStack = [];
this.commonObjs = commonObjs;
this.objs = objs;
this.pendingEOFill = false;
this.embedFonts = false;
this.embeddedFonts = {};
this.cssStyle = null;
}
var NS = 'http://www.w3.org/2000/svg';
var XML_NS = 'http://www.w3.org/XML/1998/namespace';
var XLINK_NS = 'http://www.w3.org/1999/xlink';
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
var clipCount = 0;
var maskCount = 0;
SVGGraphics.prototype = {
save: function SVGGraphics_save() {
this.transformStack.push(this.transformMatrix);
var old = this.current;
this.extraStack.push(old);
this.current = old.clone();
},
restore: function SVGGraphics_restore() {
this.transformMatrix = this.transformStack.pop();
this.current = this.extraStack.pop();
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.pgrp.appendChild(this.tgrp);
},
group: function SVGGraphics_group(items) {
this.save();
this.executeOpTree(items);
this.restore();
},
loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
var fnArray = operatorList.fnArray;
var fnArrayLen = fnArray.length;
var argsArray = operatorList.argsArray;
var self = this;
for (var i = 0; i < fnArrayLen; i++) {
if (OPS.dependency === fnArray[i]) {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var obj = deps[n];
var common = obj.substring(0, 2) === 'g_';
var promise;
if (common) {
promise = new Promise(function(resolve) {
self.commonObjs.get(obj, resolve);
});
} else {
promise = new Promise(function(resolve) {
self.objs.get(obj, resolve);
});
}
this.current.dependencies.push(promise);
}
}
}
return Promise.all(this.current.dependencies);
},
transform: function SVGGraphics_transform(a, b, c, d, e, f) {
var transformMatrix = [a, b, c, d, e, f];
this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
transformMatrix);
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
this.svg = createScratchSVG(viewport.width, viewport.height);
this.viewport = viewport;
return this.loadDependencies(operatorList).then(function () {
this.transformMatrix = IDENTITY_MATRIX;
this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.defs = document.createElementNS(NS, 'svg:defs');
this.pgrp.appendChild(this.defs);
this.pgrp.appendChild(this.tgrp);
this.svg.appendChild(this.pgrp);
var opTree = this.convertOpList(operatorList);
this.executeOpTree(opTree);
return this.svg;
}.bind(this));
},
convertOpList: function SVGGraphics_convertOpList(operatorList) {
var argsArray = operatorList.argsArray;
var fnArray = operatorList.fnArray;
var fnArrayLen = fnArray.length;
var REVOPS = [];
var opList = [];
for (var op in OPS) {
REVOPS[OPS[op]] = op;
}
for (var x = 0; x < fnArrayLen; x++) {
var fnId = fnArray[x];
opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
}
return opListToTree(opList);
},
executeOpTree: function SVGGraphics_executeOpTree(opTree) {
var opTreeLen = opTree.length;
for(var x = 0; x < opTreeLen; x++) {
var fn = opTree[x].fn;
var fnId = opTree[x].fnId;
var args = opTree[x].args;
switch (fnId | 0) {
case OPS.beginText:
this.beginText();
break;
case OPS.setLeading:
this.setLeading(args);
break;
case OPS.setLeadingMoveText:
this.setLeadingMoveText(args[0], args[1]);
break;
case OPS.setFont:
this.setFont(args);
break;
case OPS.showText:
this.showText(args[0]);
break;
case OPS.showSpacedText:
this.showText(args[0]);
break;
case OPS.endText:
this.endText();
break;
case OPS.moveText:
this.moveText(args[0], args[1]);
break;
case OPS.setCharSpacing:
this.setCharSpacing(args[0]);
break;
case OPS.setWordSpacing:
this.setWordSpacing(args[0]);
break;
case OPS.setHScale:
this.setHScale(args[0]);
break;
case OPS.setTextMatrix:
this.setTextMatrix(args[0], args[1], args[2],
args[3], args[4], args[5]);
break;
case OPS.setLineWidth:
this.setLineWidth(args[0]);
break;
case OPS.setLineJoin:
this.setLineJoin(args[0]);
break;
case OPS.setLineCap:
this.setLineCap(args[0]);
break;
case OPS.setMiterLimit:
this.setMiterLimit(args[0]);
break;
case OPS.setFillRGBColor:
this.setFillRGBColor(args[0], args[1], args[2]);
break;
case OPS.setStrokeRGBColor:
this.setStrokeRGBColor(args[0], args[1], args[2]);
break;
case OPS.setDash:
this.setDash(args[0], args[1]);
break;
case OPS.setGState:
this.setGState(args[0]);
break;
case OPS.fill:
this.fill();
break;
case OPS.eoFill:
this.eoFill();
break;
case OPS.stroke:
this.stroke();
break;
case OPS.fillStroke:
this.fillStroke();
break;
case OPS.eoFillStroke:
this.eoFillStroke();
break;
case OPS.clip:
this.clip('nonzero');
break;
case OPS.eoClip:
this.clip('evenodd');
break;
case OPS.paintSolidColorImageMask:
this.paintSolidColorImageMask();
break;
case OPS.paintJpegXObject:
this.paintJpegXObject(args[0], args[1], args[2]);
break;
case OPS.paintImageXObject:
this.paintImageXObject(args[0]);
break;
case OPS.paintInlineImageXObject:
this.paintInlineImageXObject(args[0]);
break;
case OPS.paintImageMaskXObject:
this.paintImageMaskXObject(args[0]);
break;
case OPS.paintFormXObjectBegin:
this.paintFormXObjectBegin(args[0], args[1]);
break;
case OPS.paintFormXObjectEnd:
this.paintFormXObjectEnd();
break;
case OPS.closePath:
this.closePath();
break;
case OPS.closeStroke:
this.closeStroke();
break;
case OPS.closeFillStroke:
this.closeFillStroke();
break;
case OPS.nextLine:
this.nextLine();
break;
case OPS.transform:
this.transform(args[0], args[1], args[2], args[3],
args[4], args[5]);
break;
case OPS.constructPath:
this.constructPath(args[0], args[1]);
break;
case OPS.endPath:
this.endPath();
break;
case 92:
this.group(opTree[x].items);
break;
default:
warn('Unimplemented method '+ fn);
break;
}
}
},
setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
this.current.wordSpacing = wordSpacing;
},
setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
this.current.charSpacing = charSpacing;
},
nextLine: function SVGGraphics_nextLine() {
this.moveText(0, this.current.leading);
},
setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
var current = this.current;
this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
current.xcoords = [];
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.txtElement = document.createElementNS(NS, 'svg:text');
current.txtElement.appendChild(current.tspan);
},
beginText: function SVGGraphics_beginText() {
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
this.current.textMatrix = IDENTITY_MATRIX;
this.current.lineMatrix = IDENTITY_MATRIX;
this.current.tspan = document.createElementNS(NS, 'svg:tspan');
this.current.txtElement = document.createElementNS(NS, 'svg:text');
this.current.txtgrp = document.createElementNS(NS, 'svg:g');
this.current.xcoords = [];
},
moveText: function SVGGraphics_moveText(x, y) {
var current = this.current;
this.current.x = this.current.lineX += x;
this.current.y = this.current.lineY += y;
current.xcoords = [];
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
},
showText: function SVGGraphics_showText(glyphs) {
var current = this.current;
var font = current.font;
var fontSize = current.fontSize;
if (fontSize === 0) {
return;
}
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var fontDirection = current.fontDirection;
var textHScale = current.textHScale * fontDirection;
var glyphsLength = glyphs.length;
var vertical = font.vertical;
var widthAdvanceScale = fontSize * current.fontMatrix[0];
var x = 0, i;
for (i = 0; i < glyphsLength; ++i) {
var glyph = glyphs[i];
if (glyph === null) {
// word break
x += fontDirection * wordSpacing;
continue;
} else if (isNum(glyph)) {
x += -glyph * fontSize * 0.001;
continue;
}
current.xcoords.push(current.x + x * textHScale);
var width = glyph.width;
var character = glyph.fontChar;
var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
x += charWidth;
current.tspan.textContent += character;
}
if (vertical) {
current.y -= x * textHScale;
} else {
current.x += x * textHScale;
}
current.tspan.setAttributeNS(null, 'x',
current.xcoords.map(pf).join(' '));
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
current.tspan.setAttributeNS(null, 'font-size',
pf(current.fontSize) + 'px');
if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
}
if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
}
if (current.fillColor !== SVG_DEFAULTS.fillColor) {
current.tspan.setAttributeNS(null, 'fill', current.fillColor);
}
current.txtElement.setAttributeNS(null, 'transform',
pm(current.textMatrix) +
' scale(1, -1)' );
current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
current.txtElement.appendChild(current.tspan);
current.txtgrp.appendChild(current.txtElement);
this.tgrp.appendChild(current.txtElement);
},
setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
this.setLeading(-y);
this.moveText(x, y);
},
addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
if (!this.cssStyle) {
this.cssStyle = document.createElementNS(NS, 'svg:style');
this.cssStyle.setAttributeNS(null, 'type', 'text/css');
this.defs.appendChild(this.cssStyle);
}
var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
this.cssStyle.textContent +=
'@font-face { font-family: "' + fontObj.loadedName + '";' +
' src: url(' + url + '); }\n';
},
setFont: function SVGGraphics_setFont(details) {
var current = this.current;
var fontObj = this.commonObjs.get(details[0]);
var size = details[1];
this.current.font = fontObj;
if (this.embedFonts && fontObj.data &&
!this.embeddedFonts[fontObj.loadedName]) {
this.addFontStyle(fontObj);
this.embeddedFonts[fontObj.loadedName] = fontObj;
}
current.fontMatrix = (fontObj.fontMatrix ?
fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
if (size < 0) {
size = -size;
current.fontDirection = -1;
} else {
current.fontDirection = 1;
}
current.fontSize = size;
current.fontFamily = fontObj.loadedName;
current.fontWeight = bold;
current.fontStyle = italic;
current.tspan = document.createElementNS(NS, 'svg:tspan');
current.tspan.setAttributeNS(null, 'y', pf(-current.y));
current.xcoords = [];
},
endText: function SVGGraphics_endText() {
if (this.current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
// Path properties
setLineWidth: function SVGGraphics_setLineWidth(width) {
this.current.lineWidth = width;
},
setLineCap: function SVGGraphics_setLineCap(style) {
this.current.lineCap = LINE_CAP_STYLES[style];
},
setLineJoin: function SVGGraphics_setLineJoin(style) {
this.current.lineJoin = LINE_JOIN_STYLES[style];
},
setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
this.current.miterLimit = limit;
},
setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.current.strokeColor = color;
},
setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.current.fillColor = color;
this.current.tspan = document.createElementNS(NS, 'svg:tspan');
this.current.xcoords = [];
},
setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
this.current.dashArray = dashArray;
this.current.dashPhase = dashPhase;
},
constructPath: function SVGGraphics_constructPath(ops, args) {
var current = this.current;
var x = current.x, y = current.y;
current.path = document.createElementNS(NS, 'svg:path');
var d = [];
var opLength = ops.length;
for (var i = 0, j = 0; i < opLength; i++) {
switch (ops[i] | 0) {
case OPS.rectangle:
x = args[j++];
y = args[j++];
var width = args[j++];
var height = args[j++];
var xw = x + width;
var yh = y + height;
d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
'L', pf(x), pf(yh), 'Z');
break;
case OPS.moveTo:
x = args[j++];
y = args[j++];
d.push('M', pf(x), pf(y));
break;
case OPS.lineTo:
x = args[j++];
y = args[j++];
d.push('L', pf(x) , pf(y));
break;
case OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
pf(args[j + 3]), pf(x), pf(y));
j += 6;
break;
case OPS.curveTo2:
x = args[j + 2];
y = args[j + 3];
d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
pf(args[j + 2]), pf(args[j + 3]));
j += 4;
break;
case OPS.curveTo3:
x = args[j + 2];
y = args[j + 3];
d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
pf(x), pf(y));
j += 4;
break;
case OPS.closePath:
d.push('Z');
break;
}
}
current.path.setAttributeNS(null, 'd', d.join(' '));
current.path.setAttributeNS(null, 'stroke-miterlimit',
pf(current.miterLimit));
current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
current.path.setAttributeNS(null, 'stroke-width',
pf(current.lineWidth) + 'px');
current.path.setAttributeNS(null, 'stroke-dasharray',
current.dashArray.map(pf).join(' '));
current.path.setAttributeNS(null, 'stroke-dashoffset',
pf(current.dashPhase) + 'px');
current.path.setAttributeNS(null, 'fill', 'none');
this.tgrp.appendChild(current.path);
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
// Saving a reference in current.element so that it can be addressed
// in 'fill' and 'stroke'
current.element = current.path;
current.setCurrentPoint(x, y);
},
endPath: function SVGGraphics_endPath() {
var current = this.current;
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
this.tgrp = document.createElementNS(NS, 'svg:g');
this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
},
clip: function SVGGraphics_clip(type) {
var current = this.current;
// Add current path to clipping path
current.clipId = 'clippath' + clipCount;
clipCount++;
this.clippath = document.createElementNS(NS, 'svg:clipPath');
this.clippath.setAttributeNS(null, 'id', current.clipId);
var clipElement = current.element.cloneNode();
if (type === 'evenodd') {
clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
} else {
clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
}
this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
this.clippath.appendChild(clipElement);
this.defs.appendChild(this.clippath);
// Create a new group with that attribute
current.pendingClip = true;
this.cgrp = document.createElementNS(NS, 'svg:g');
this.cgrp.setAttributeNS(null, 'clip-path',
'url(#' + current.clipId + ')');
this.pgrp.appendChild(this.cgrp);
},
closePath: function SVGGraphics_closePath() {
var current = this.current;
var d = current.path.getAttributeNS(null, 'd');
d += 'Z';
current.path.setAttributeNS(null, 'd', d);
},
setLeading: function SVGGraphics_setLeading(leading) {
this.current.leading = -leading;
},
setTextRise: function SVGGraphics_setTextRise(textRise) {
this.current.textRise = textRise;
},
setHScale: function SVGGraphics_setHScale(scale) {
this.current.textHScale = scale / 100;
},
setGState: function SVGGraphics_setGState(states) {
for (var i = 0, ii = states.length; i < ii; i++) {
var state = states[i];
var key = state[0];
var value = state[1];
switch (key) {
case 'LW':
this.setLineWidth(value);
break;
case 'LC':
this.setLineCap(value);
break;
case 'LJ':
this.setLineJoin(value);
break;
case 'ML':
this.setMiterLimit(value);
break;
case 'D':
this.setDash(value[0], value[1]);
break;
case 'RI':
break;
case 'FL':
break;
case 'Font':
this.setFont(value);
break;
case 'CA':
break;
case 'ca':
break;
case 'BM':
break;
case 'SMask':
break;
}
}
},
fill: function SVGGraphics_fill() {
var current = this.current;
current.element.setAttributeNS(null, 'fill', current.fillColor);
},
stroke: function SVGGraphics_stroke() {
var current = this.current;
current.element.setAttributeNS(null, 'stroke', current.strokeColor);
current.element.setAttributeNS(null, 'fill', 'none');
},
eoFill: function SVGGraphics_eoFill() {
var current = this.current;
current.element.setAttributeNS(null, 'fill', current.fillColor);
current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
},
fillStroke: function SVGGraphics_fillStroke() {
// Order is important since stroke wants fill to be none.
// First stroke, then if fill needed, it will be overwritten.
this.stroke();
this.fill();
},
eoFillStroke: function SVGGraphics_eoFillStroke() {
this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
this.fillStroke();
},
closeStroke: function SVGGraphics_closeStroke() {
this.closePath();
this.stroke();
},
closeFillStroke: function SVGGraphics_closeFillStroke() {
this.closePath();
this.fillStroke();
},
paintSolidColorImageMask:
function SVGGraphics_paintSolidColorImageMask() {
var current = this.current;
var rect = document.createElementNS(NS, 'svg:rect');
rect.setAttributeNS(null, 'x', '0');
rect.setAttributeNS(null, 'y', '0');
rect.setAttributeNS(null, 'width', '1px');
rect.setAttributeNS(null, 'height', '1px');
rect.setAttributeNS(null, 'fill', current.fillColor);
this.tgrp.appendChild(rect);
},
paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
var current = this.current;
var imgObj = this.objs.get(objId);
var imgEl = document.createElementNS(NS, 'svg:image');
imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
imgEl.setAttributeNS(null, 'x', '0');
imgEl.setAttributeNS(null, 'y', pf(-h));
imgEl.setAttributeNS(null, 'transform',
'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
this.tgrp.appendChild(imgEl);
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
},
paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
this.paintInlineImageXObject(imgData);
},
paintInlineImageXObject:
function SVGGraphics_paintInlineImageXObject(imgData, mask) {
var current = this.current;
var width = imgData.width;
var height = imgData.height;
var imgSrc = convertImgDataToPng(imgData);
var cliprect = document.createElementNS(NS, 'svg:rect');
cliprect.setAttributeNS(null, 'x', '0');
cliprect.setAttributeNS(null, 'y', '0');
cliprect.setAttributeNS(null, 'width', pf(width));
cliprect.setAttributeNS(null, 'height', pf(height));
current.element = cliprect;
this.clip('nonzero');
var imgEl = document.createElementNS(NS, 'svg:image');
imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
imgEl.setAttributeNS(null, 'x', '0');
imgEl.setAttributeNS(null, 'y', pf(-height));
imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
imgEl.setAttributeNS(null, 'transform',
'scale(' + pf(1 / width) + ' ' +
pf(-1 / height) + ')');
if (mask) {
mask.appendChild(imgEl);
} else {
this.tgrp.appendChild(imgEl);
}
if (current.pendingClip) {
this.cgrp.appendChild(this.tgrp);
this.pgrp.appendChild(this.cgrp);
} else {
this.pgrp.appendChild(this.tgrp);
}
},
paintImageMaskXObject:
function SVGGraphics_paintImageMaskXObject(imgData) {
var current = this.current;
var width = imgData.width;
var height = imgData.height;
var fillColor = current.fillColor;
current.maskId = 'mask' + maskCount++;
var mask = document.createElementNS(NS, 'svg:mask');
mask.setAttributeNS(null, 'id', current.maskId);
var rect = document.createElementNS(NS, 'svg:rect');
rect.setAttributeNS(null, 'x', '0');
rect.setAttributeNS(null, 'y', '0');
rect.setAttributeNS(null, 'width', pf(width));
rect.setAttributeNS(null, 'height', pf(height));
rect.setAttributeNS(null, 'fill', fillColor);
rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
this.defs.appendChild(mask);
this.tgrp.appendChild(rect);
this.paintInlineImageXObject(imgData, mask);
},
paintFormXObjectBegin:
function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
this.save();
if (isArray(matrix) && matrix.length === 6) {
this.transform(matrix[0], matrix[1], matrix[2],
matrix[3], matrix[4], matrix[5]);
}
if (isArray(bbox) && bbox.length === 4) {
var width = bbox[2] - bbox[0];
var height = bbox[3] - bbox[1];
var cliprect = document.createElementNS(NS, 'svg:rect');
cliprect.setAttributeNS(null, 'x', bbox[0]);
cliprect.setAttributeNS(null, 'y', bbox[1]);
cliprect.setAttributeNS(null, 'width', pf(width));
cliprect.setAttributeNS(null, 'height', pf(height));
this.current.element = cliprect;
this.clip('nonzero');
this.endPath();
}
},
paintFormXObjectEnd:
function SVGGraphics_paintFormXObjectEnd() {
this.restore();
}
};
return SVGGraphics;
})();
PDFJS.SVGGraphics = SVGGraphics;
exports.SVGGraphics = SVGGraphics;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayDOMUtils, root.pdfjsSharedGlobal);
}
}(this, function (exports, sharedUtil, displayDOMUtils, sharedGlobal) {
var Util = sharedUtil.Util;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var CustomStyle = displayDOMUtils.CustomStyle;
var PDFJS = sharedGlobal.PDFJS;
/**
* Text layer render parameters.
*
* @typedef {Object} TextLayerRenderParameters
* @property {TextContent} textContent - Text content to render (the object is
* returned by the page's getTextContent() method).
* @property {HTMLElement} container - HTML element that will contain text runs.
* @property {PDFJS.PageViewport} viewport - The target viewport to properly
* layout the text runs.
* @property {Array} textDivs - (optional) HTML elements that are correspond
* the text items of the textContent input. This is output and shall be
* initially be set to empty array.
* @property {number} timeout - (optional) Delay in milliseconds before
* rendering of the text runs occurs.
*/
var renderTextLayer = (function renderTextLayerClosure() {
var MAX_TEXT_DIVS_TO_RENDER = 100000;
var NonWhitespaceRegexp = /\S/;
function isAllWhitespace(str) {
return !NonWhitespaceRegexp.test(str);
}
function appendText(textDivs, viewport, geom, styles) {
var style = styles[geom.fontName];
var textDiv = document.createElement('div');
textDivs.push(textDiv);
if (isAllWhitespace(geom.str)) {
textDiv.dataset.isWhitespace = true;
return;
}
var tx = Util.transform(viewport.transform, geom.transform);
var angle = Math.atan2(tx[1], tx[0]);
if (style.vertical) {
angle += Math.PI / 2;
}
var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
var fontAscent = fontHeight;
if (style.ascent) {
fontAscent = style.ascent * fontAscent;
} else if (style.descent) {
fontAscent = (1 + style.descent) * fontAscent;
}
var left;
var top;
if (angle === 0) {
left = tx[4];
top = tx[5] - fontAscent;
} else {
left = tx[4] + (fontAscent * Math.sin(angle));
top = tx[5] - (fontAscent * Math.cos(angle));
}
textDiv.style.left = left + 'px';
textDiv.style.top = top + 'px';
textDiv.style.fontSize = fontHeight + 'px';
textDiv.style.fontFamily = style.fontFamily;
textDiv.textContent = geom.str;
// |fontName| is only used by the Font Inspector. This test will succeed
// when e.g. the Font Inspector is off but the Stepper is on, but it's
// not worth the effort to do a more accurate test.
if (PDFJS.pdfBug) {
textDiv.dataset.fontName = geom.fontName;
}
// Storing into dataset will convert number into string.
if (angle !== 0) {
textDiv.dataset.angle = angle * (180 / Math.PI);
}
// We don't bother scaling single-char text divs, because it has very
// little effect on text highlighting. This makes scrolling on docs with
// lots of such divs a lot faster.
if (geom.str.length > 1) {
if (style.vertical) {
textDiv.dataset.canvasWidth = geom.height * viewport.scale;
} else {
textDiv.dataset.canvasWidth = geom.width * viewport.scale;
}
}
}
function render(task) {
if (task._canceled) {
return;
}
var textLayerFrag = task._container;
var textDivs = task._textDivs;
var capability = task._capability;
var textDivsLength = textDivs.length;
// No point in rendering many divs as it would make the browser
// unusable even after the divs are rendered.
if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
capability.resolve();
return;
}
var canvas = document.createElement('canvas');
canvas.mozOpaque = true;
var ctx = canvas.getContext('2d', {alpha: false});
var lastFontSize;
var lastFontFamily;
for (var i = 0; i < textDivsLength; i++) {
var textDiv = textDivs[i];
if (textDiv.dataset.isWhitespace !== undefined) {
continue;
}
var fontSize = textDiv.style.fontSize;
var fontFamily = textDiv.style.fontFamily;
// Only build font string and set to context if different from last.
if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
ctx.font = fontSize + ' ' + fontFamily;
lastFontSize = fontSize;
lastFontFamily = fontFamily;
}
var width = ctx.measureText(textDiv.textContent).width;
if (width > 0) {
textLayerFrag.appendChild(textDiv);
var transform;
if (textDiv.dataset.canvasWidth !== undefined) {
// Dataset values come of type string.
var textScale = textDiv.dataset.canvasWidth / width;
transform = 'scaleX(' + textScale + ')';
} else {
transform = '';
}
var rotation = textDiv.dataset.angle;
if (rotation) {
transform = 'rotate(' + rotation + 'deg) ' + transform;
}
if (transform) {
CustomStyle.setProp('transform' , textDiv, transform);
}
}
}
capability.resolve();
}
/**
* Text layer rendering task.
*
* @param {TextContent} textContent
* @param {HTMLElement} container
* @param {PDFJS.PageViewport} viewport
* @param {Array} textDivs
* @private
*/
function TextLayerRenderTask(textContent, container, viewport, textDivs) {
this._textContent = textContent;
this._container = container;
this._viewport = viewport;
textDivs = textDivs || [];
this._textDivs = textDivs;
this._canceled = false;
this._capability = createPromiseCapability();
this._renderTimer = null;
}
TextLayerRenderTask.prototype = {
get promise() {
return this._capability.promise;
},
cancel: function TextLayer_cancel() {
this._canceled = true;
if (this._renderTimer !== null) {
clearTimeout(this._renderTimer);
this._renderTimer = null;
}
this._capability.reject('canceled');
},
_render: function TextLayer_render(timeout) {
var textItems = this._textContent.items;
var styles = this._textContent.styles;
var textDivs = this._textDivs;
var viewport = this._viewport;
for (var i = 0, len = textItems.length; i < len; i++) {
appendText(textDivs, viewport, textItems[i], styles);
}
if (!timeout) { // Render right away
render(this);
} else { // Schedule
var self = this;
this._renderTimer = setTimeout(function() {
render(self);
self._renderTimer = null;
}, timeout);
}
}
};
/**
* Starts rendering of the text layer.
*
* @param {TextLayerRenderParameters} renderParameters
* @returns {TextLayerRenderTask}
*/
function renderTextLayer(renderParameters) {
var task = new TextLayerRenderTask(renderParameters.textContent,
renderParameters.container,
renderParameters.viewport,
renderParameters.textDivs);
task._render(renderParameters.timeout);
return task;
}
return renderTextLayer;
})();
PDFJS.renderTextLayer = renderTextLayer;
exports.renderTextLayer = renderTextLayer;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil);
}
}(this, function (exports, sharedUtil) {
var shadow = sharedUtil.shadow;
var WebGLUtils = (function WebGLUtilsClosure() {
function loadShader(gl, code, shaderType) {
var shader = gl.createShader(shaderType);
gl.shaderSource(shader, code);
gl.compileShader(shader);
var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!compiled) {
var errorMsg = gl.getShaderInfoLog(shader);
throw new Error('Error during shader compilation: ' + errorMsg);
}
return shader;
}
function createVertexShader(gl, code) {
return loadShader(gl, code, gl.VERTEX_SHADER);
}
function createFragmentShader(gl, code) {
return loadShader(gl, code, gl.FRAGMENT_SHADER);
}
function createProgram(gl, shaders) {
var program = gl.createProgram();
for (var i = 0, ii = shaders.length; i < ii; ++i) {
gl.attachShader(program, shaders[i]);
}
gl.linkProgram(program);
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
var errorMsg = gl.getProgramInfoLog(program);
throw new Error('Error during program linking: ' + errorMsg);
}
return program;
}
function createTexture(gl, image, textureId) {
gl.activeTexture(textureId);
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Set the parameters so we can render any size image.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
return texture;
}
var currentGL, currentCanvas;
function generateGL() {
if (currentGL) {
return;
}
currentCanvas = document.createElement('canvas');
currentGL = currentCanvas.getContext('webgl',
{ premultipliedalpha: false });
}
var smaskVertexShaderCode = '\
attribute vec2 a_position; \
attribute vec2 a_texCoord; \
\
uniform vec2 u_resolution; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_texCoord = a_texCoord; \
} ';
var smaskFragmentShaderCode = '\
precision mediump float; \
\
uniform vec4 u_backdrop; \
uniform int u_subtype; \
uniform sampler2D u_image; \
uniform sampler2D u_mask; \
\
varying vec2 v_texCoord; \
\
void main() { \
vec4 imageColor = texture2D(u_image, v_texCoord); \
vec4 maskColor = texture2D(u_mask, v_texCoord); \
if (u_backdrop.a > 0.0) { \
maskColor.rgb = maskColor.rgb * maskColor.a + \
u_backdrop.rgb * (1.0 - maskColor.a); \
} \
float lum; \
if (u_subtype == 0) { \
lum = maskColor.a; \
} else { \
lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
maskColor.b * 0.11; \
} \
imageColor.a *= lum; \
imageColor.rgb *= imageColor.a; \
gl_FragColor = imageColor; \
} ';
var smaskCache = null;
function initSmaskGL() {
var canvas, gl;
generateGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
// setup a GLSL program
var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
cache.positionLocation = gl.getAttribLocation(program, 'a_position');
cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
var texLayerLocation = gl.getUniformLocation(program, 'u_image');
var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
// provide texture coordinates for the rectangle.
var texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texCoordLocation);
gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
gl.uniform1i(texLayerLocation, 0);
gl.uniform1i(texMaskLocation, 1);
smaskCache = cache;
}
function composeSMask(layer, mask, properties) {
var width = layer.width, height = layer.height;
if (!smaskCache) {
initSmaskGL();
}
var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
if (properties.backdrop) {
gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
properties.backdrop[1], properties.backdrop[2], 1);
} else {
gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
}
gl.uniform1i(cache.subtypeLocation,
properties.subtype === 'Luminosity' ? 1 : 0);
// Create a textures
var texture = createTexture(gl, layer, gl.TEXTURE0);
var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
// Create a buffer and put a single clipspace rectangle in
// it (2 triangles)
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0, 0,
width, 0,
0, height,
0, height,
width, 0,
width, height]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
// draw
gl.clearColor(0, 0, 0, 0);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 6);
gl.flush();
gl.deleteTexture(texture);
gl.deleteTexture(maskTexture);
gl.deleteBuffer(buffer);
return canvas;
}
var figuresVertexShaderCode = '\
attribute vec2 a_position; \
attribute vec3 a_color; \
\
uniform vec2 u_resolution; \
uniform vec2 u_scale; \
uniform vec2 u_offset; \
\
varying vec4 v_color; \
\
void main() { \
vec2 position = (a_position + u_offset) * u_scale; \
vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
\
v_color = vec4(a_color / 255.0, 1.0); \
} ';
var figuresFragmentShaderCode = '\
precision mediump float; \
\
varying vec4 v_color; \
\
void main() { \
gl_FragColor = v_color; \
} ';
var figuresCache = null;
function initFiguresGL() {
var canvas, gl;
generateGL();
canvas = currentCanvas;
currentCanvas = null;
gl = currentGL;
currentGL = null;
// setup a GLSL program
var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
var program = createProgram(gl, [vertexShader, fragmentShader]);
gl.useProgram(program);
var cache = {};
cache.gl = gl;
cache.canvas = canvas;
cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
cache.positionLocation = gl.getAttribLocation(program, 'a_position');
cache.colorLocation = gl.getAttribLocation(program, 'a_color');
figuresCache = cache;
}
function drawFigures(width, height, backgroundColor, figures, context) {
if (!figuresCache) {
initFiguresGL();
}
var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
canvas.width = width;
canvas.height = height;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.uniform2f(cache.resolutionLocation, width, height);
// count triangle points
var count = 0;
var i, ii, rows;
for (i = 0, ii = figures.length; i < ii; i++) {
switch (figures[i].type) {
case 'lattice':
rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
break;
case 'triangles':
count += figures[i].coords.length;
break;
}
}
// transfer data
var coords = new Float32Array(count * 2);
var colors = new Uint8Array(count * 3);
var coordsMap = context.coords, colorsMap = context.colors;
var pIndex = 0, cIndex = 0;
for (i = 0, ii = figures.length; i < ii; i++) {
var figure = figures[i], ps = figure.coords, cs = figure.colors;
switch (figure.type) {
case 'lattice':
var cols = figure.verticesPerRow;
rows = (ps.length / cols) | 0;
for (var row = 1; row < rows; row++) {
var offset = row * cols + 1;
for (var col = 1; col < cols; col++, offset++) {
coords[pIndex] = coordsMap[ps[offset - cols - 1]];
coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
coords[pIndex + 2] = coordsMap[ps[offset - cols]];
coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
coords[pIndex + 4] = coordsMap[ps[offset - 1]];
coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
colors[cIndex] = colorsMap[cs[offset - cols - 1]];
colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
colors[cIndex + 3] = colorsMap[cs[offset - cols]];
colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
colors[cIndex + 6] = colorsMap[cs[offset - 1]];
colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
coords[pIndex + 6] = coords[pIndex + 2];
coords[pIndex + 7] = coords[pIndex + 3];
coords[pIndex + 8] = coords[pIndex + 4];
coords[pIndex + 9] = coords[pIndex + 5];
coords[pIndex + 10] = coordsMap[ps[offset]];
coords[pIndex + 11] = coordsMap[ps[offset] + 1];
colors[cIndex + 9] = colors[cIndex + 3];
colors[cIndex + 10] = colors[cIndex + 4];
colors[cIndex + 11] = colors[cIndex + 5];
colors[cIndex + 12] = colors[cIndex + 6];
colors[cIndex + 13] = colors[cIndex + 7];
colors[cIndex + 14] = colors[cIndex + 8];
colors[cIndex + 15] = colorsMap[cs[offset]];
colors[cIndex + 16] = colorsMap[cs[offset] + 1];
colors[cIndex + 17] = colorsMap[cs[offset] + 2];
pIndex += 12;
cIndex += 18;
}
}
break;
case 'triangles':
for (var j = 0, jj = ps.length; j < jj; j++) {
coords[pIndex] = coordsMap[ps[j]];
coords[pIndex + 1] = coordsMap[ps[j] + 1];
colors[cIndex] = colorsMap[cs[j]];
colors[cIndex + 1] = colorsMap[cs[j] + 1];
colors[cIndex + 2] = colorsMap[cs[j] + 2];
pIndex += 2;
cIndex += 3;
}
break;
}
}
// draw
if (backgroundColor) {
gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
backgroundColor[2] / 255, 1.0);
} else {
gl.clearColor(0, 0, 0, 0);
}
gl.clear(gl.COLOR_BUFFER_BIT);
var coordsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.positionLocation);
gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
var colorsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
gl.enableVertexAttribArray(cache.colorLocation);
gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
0, 0);
gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
gl.drawArrays(gl.TRIANGLES, 0, count);
gl.flush();
gl.deleteBuffer(coordsBuffer);
gl.deleteBuffer(colorsBuffer);
return canvas;
}
function cleanup() {
if (smaskCache && smaskCache.canvas) {
smaskCache.canvas.width = 0;
smaskCache.canvas.height = 0;
}
if (figuresCache && figuresCache.canvas) {
figuresCache.canvas.width = 0;
figuresCache.canvas.height = 0;
}
smaskCache = null;
figuresCache = null;
}
return {
get isEnabled() {
if (PDFJS.disableWebGL) {
return false;
}
var enabled = false;
try {
generateGL();
enabled = !!currentGL;
} catch (e) { }
return shadow(this, 'isEnabled', enabled);
},
composeSMask: composeSMask,
drawFigures: drawFigures,
clear: cleanup
};
})();
exports.WebGLUtils = WebGLUtils;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayWebGL);
}
}(this, function (exports, sharedUtil, displayWebGL) {
var Util = sharedUtil.Util;
var info = sharedUtil.info;
var isArray = sharedUtil.isArray;
var error = sharedUtil.error;
var WebGLUtils = displayWebGL.WebGLUtils;
var ShadingIRs = {};
ShadingIRs.RadialAxial = {
fromIR: function RadialAxial_fromIR(raw) {
var type = raw[1];
var colorStops = raw[2];
var p0 = raw[3];
var p1 = raw[4];
var r0 = raw[5];
var r1 = raw[6];
return {
type: 'Pattern',
getPattern: function RadialAxial_getPattern(ctx) {
var grad;
if (type === 'axial') {
grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
} else if (type === 'radial') {
grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
}
for (var i = 0, ii = colorStops.length; i < ii; ++i) {
var c = colorStops[i];
grad.addColorStop(c[0], c[1]);
}
return grad;
}
};
}
};
var createMeshCanvas = (function createMeshCanvasClosure() {
function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
// Very basic Gouraud-shaded triangle rasterization algorithm.
var coords = context.coords, colors = context.colors;
var bytes = data.data, rowSize = data.width * 4;
var tmp;
if (coords[p1 + 1] > coords[p2 + 1]) {
tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
}
if (coords[p2 + 1] > coords[p3 + 1]) {
tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
}
if (coords[p1 + 1] > coords[p2 + 1]) {
tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
}
var x1 = (coords[p1] + context.offsetX) * context.scaleX;
var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
var x2 = (coords[p2] + context.offsetX) * context.scaleX;
var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
var x3 = (coords[p3] + context.offsetX) * context.scaleX;
var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
if (y1 >= y3) {
return;
}
var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
var minY = Math.round(y1), maxY = Math.round(y3);
var xa, car, cag, cab;
var xb, cbr, cbg, cbb;
var k;
for (var y = minY; y <= maxY; y++) {
if (y < y2) {
k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
xa = x1 - (x1 - x2) * k;
car = c1r - (c1r - c2r) * k;
cag = c1g - (c1g - c2g) * k;
cab = c1b - (c1b - c2b) * k;
} else {
k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
xa = x2 - (x2 - x3) * k;
car = c2r - (c2r - c3r) * k;
cag = c2g - (c2g - c3g) * k;
cab = c2b - (c2b - c3b) * k;
}
k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
xb = x1 - (x1 - x3) * k;
cbr = c1r - (c1r - c3r) * k;
cbg = c1g - (c1g - c3g) * k;
cbb = c1b - (c1b - c3b) * k;
var x1_ = Math.round(Math.min(xa, xb));
var x2_ = Math.round(Math.max(xa, xb));
var j = rowSize * y + x1_ * 4;
for (var x = x1_; x <= x2_; x++) {
k = (xa - x) / (xa - xb);
k = k < 0 ? 0 : k > 1 ? 1 : k;
bytes[j++] = (car - (car - cbr) * k) | 0;
bytes[j++] = (cag - (cag - cbg) * k) | 0;
bytes[j++] = (cab - (cab - cbb) * k) | 0;
bytes[j++] = 255;
}
}
}
function drawFigure(data, figure, context) {
var ps = figure.coords;
var cs = figure.colors;
var i, ii;
switch (figure.type) {
case 'lattice':
var verticesPerRow = figure.verticesPerRow;
var rows = Math.floor(ps.length / verticesPerRow) - 1;
var cols = verticesPerRow - 1;
for (i = 0; i < rows; i++) {
var q = i * verticesPerRow;
for (var j = 0; j < cols; j++, q++) {
drawTriangle(data, context,
ps[q], ps[q + 1], ps[q + verticesPerRow],
cs[q], cs[q + 1], cs[q + verticesPerRow]);
drawTriangle(data, context,
ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
}
}
break;
case 'triangles':
for (i = 0, ii = ps.length; i < ii; i += 3) {
drawTriangle(data, context,
ps[i], ps[i + 1], ps[i + 2],
cs[i], cs[i + 1], cs[i + 2]);
}
break;
default:
error('illigal figure');
break;
}
}
function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
backgroundColor, cachedCanvases) {
// we will increase scale on some weird factor to let antialiasing take
// care of "rough" edges
var EXPECTED_SCALE = 1.1;
// MAX_PATTERN_SIZE is used to avoid OOM situation.
var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
var offsetX = Math.floor(bounds[0]);
var offsetY = Math.floor(bounds[1]);
var boundsWidth = Math.ceil(bounds[2]) - offsetX;
var boundsHeight = Math.ceil(bounds[3]) - offsetY;
var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
EXPECTED_SCALE)), MAX_PATTERN_SIZE);
var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
EXPECTED_SCALE)), MAX_PATTERN_SIZE);
var scaleX = boundsWidth / width;
var scaleY = boundsHeight / height;
var context = {
coords: coords,
colors: colors,
offsetX: -offsetX,
offsetY: -offsetY,
scaleX: 1 / scaleX,
scaleY: 1 / scaleY
};
var canvas, tmpCanvas, i, ii;
if (WebGLUtils.isEnabled) {
canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
figures, context);
// https://bugzilla.mozilla.org/show_bug.cgi?id=972126
tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
tmpCanvas.context.drawImage(canvas, 0, 0);
canvas = tmpCanvas.canvas;
} else {
tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false);
var tmpCtx = tmpCanvas.context;
var data = tmpCtx.createImageData(width, height);
if (backgroundColor) {
var bytes = data.data;
for (i = 0, ii = bytes.length; i < ii; i += 4) {
bytes[i] = backgroundColor[0];
bytes[i + 1] = backgroundColor[1];
bytes[i + 2] = backgroundColor[2];
bytes[i + 3] = 255;
}
}
for (i = 0; i < figures.length; i++) {
drawFigure(data, figures[i], context);
}
tmpCtx.putImageData(data, 0, 0);
canvas = tmpCanvas.canvas;
}
return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
scaleX: scaleX, scaleY: scaleY};
}
return createMeshCanvas;
})();
ShadingIRs.Mesh = {
fromIR: function Mesh_fromIR(raw) {
//var type = raw[1];
var coords = raw[2];
var colors = raw[3];
var figures = raw[4];
var bounds = raw[5];
var matrix = raw[6];
//var bbox = raw[7];
var background = raw[8];
return {
type: 'Pattern',
getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
var scale;
if (shadingFill) {
scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
} else {
// Obtain scale from matrix and current transformation matrix.
scale = Util.singularValueDecompose2dScale(owner.baseTransform);
if (matrix) {
var matrixScale = Util.singularValueDecompose2dScale(matrix);
scale = [scale[0] * matrixScale[0],
scale[1] * matrixScale[1]];
}
}
// Rasterizing on the main thread since sending/queue large canvases
// might cause OOM.
var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
colors, figures, shadingFill ? null : background,
owner.cachedCanvases);
if (!shadingFill) {
ctx.setTransform.apply(ctx, owner.baseTransform);
if (matrix) {
ctx.transform.apply(ctx, matrix);
}
}
ctx.translate(temporaryPatternCanvas.offsetX,
temporaryPatternCanvas.offsetY);
ctx.scale(temporaryPatternCanvas.scaleX,
temporaryPatternCanvas.scaleY);
return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
}
};
}
};
ShadingIRs.Dummy = {
fromIR: function Dummy_fromIR() {
return {
type: 'Pattern',
getPattern: function Dummy_fromIR_getPattern() {
return 'hotpink';
}
};
}
};
function getShadingPatternFromIR(raw) {
var shadingIR = ShadingIRs[raw[0]];
if (!shadingIR) {
error('Unknown IR type: ' + raw[0]);
}
return shadingIR.fromIR(raw);
}
var TilingPattern = (function TilingPatternClosure() {
var PaintType = {
COLORED: 1,
UNCOLORED: 2
};
var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
this.operatorList = IR[2];
this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
this.bbox = IR[4];
this.xstep = IR[5];
this.ystep = IR[6];
this.paintType = IR[7];
this.tilingType = IR[8];
this.color = color;
this.canvasGraphicsFactory = canvasGraphicsFactory;
this.baseTransform = baseTransform;
this.type = 'Pattern';
this.ctx = ctx;
}
TilingPattern.prototype = {
createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
var operatorList = this.operatorList;
var bbox = this.bbox;
var xstep = this.xstep;
var ystep = this.ystep;
var paintType = this.paintType;
var tilingType = this.tilingType;
var color = this.color;
var canvasGraphicsFactory = this.canvasGraphicsFactory;
info('TilingType: ' + tilingType);
var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
var topLeft = [x0, y0];
// we want the canvas to be as large as the step size
var botRight = [x0 + xstep, y0 + ystep];
var width = botRight[0] - topLeft[0];
var height = botRight[1] - topLeft[1];
// Obtain scale from matrix and current transformation matrix.
var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
var curMatrixScale = Util.singularValueDecompose2dScale(
this.baseTransform);
var combinedScale = [matrixScale[0] * curMatrixScale[0],
matrixScale[1] * curMatrixScale[1]];
// MAX_PATTERN_SIZE is used to avoid OOM situation.
// Use width and height values that are as close as possible to the end
// result when the pattern is used. Too low value makes the pattern look
// blurry. Too large value makes it look too crispy.
width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
MAX_PATTERN_SIZE);
height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
MAX_PATTERN_SIZE);
var tmpCanvas = owner.cachedCanvases.getCanvas('pattern',
width, height, true);
var tmpCtx = tmpCanvas.context;
var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
graphics.groupLevel = owner.groupLevel;
this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
this.setScale(width, height, xstep, ystep);
this.transformToScale(graphics);
// transform coordinates to pattern space
var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
graphics.transform.apply(graphics, tmpTranslate);
this.clipBbox(graphics, bbox, x0, y0, x1, y1);
graphics.executeOperatorList(operatorList);
return tmpCanvas.canvas;
},
setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
this.scale = [width / xstep, height / ystep];
},
transformToScale: function TilingPattern_transformToScale(graphics) {
var scale = this.scale;
var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
graphics.transform.apply(graphics, tmpScale);
},
scaleToContext: function TilingPattern_scaleToContext() {
var scale = this.scale;
this.ctx.scale(1 / scale[0], 1 / scale[1]);
},
clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
if (bbox && isArray(bbox) && bbox.length === 4) {
var bboxWidth = x1 - x0;
var bboxHeight = y1 - y0;
graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
graphics.clip();
graphics.endPath();
}
},
setFillAndStrokeStyleToContext:
function setFillAndStrokeStyleToContext(context, paintType, color) {
switch (paintType) {
case PaintType.COLORED:
var ctx = this.ctx;
context.fillStyle = ctx.fillStyle;
context.strokeStyle = ctx.strokeStyle;
break;
case PaintType.UNCOLORED:
var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
context.fillStyle = cssColor;
context.strokeStyle = cssColor;
break;
default:
error('Unsupported paint type: ' + paintType);
}
},
getPattern: function TilingPattern_getPattern(ctx, owner) {
var temporaryPatternCanvas = this.createPatternCanvas(owner);
ctx = this.ctx;
ctx.setTransform.apply(ctx, this.baseTransform);
ctx.transform.apply(ctx, this.matrix);
this.scaleToContext();
return ctx.createPattern(temporaryPatternCanvas, 'repeat');
}
};
return TilingPattern;
})();
exports.getShadingPatternFromIR = getShadingPatternFromIR;
exports.TilingPattern = TilingPattern;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
}
}(this, function (exports, sharedUtil, displayPatternHelper, displayWebGL) {
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
var ImageKind = sharedUtil.ImageKind;
var OPS = sharedUtil.OPS;
var TextRenderingMode = sharedUtil.TextRenderingMode;
var Uint32ArrayView = sharedUtil.Uint32ArrayView;
var Util = sharedUtil.Util;
var assert = sharedUtil.assert;
var info = sharedUtil.info;
var isNum = sharedUtil.isNum;
var isArray = sharedUtil.isArray;
var error = sharedUtil.error;
var shadow = sharedUtil.shadow;
var warn = sharedUtil.warn;
var TilingPattern = displayPatternHelper.TilingPattern;
var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
var WebGLUtils = displayWebGL.WebGLUtils;
// <canvas> contexts store most of the state we need natively.
// However, PDF needs a bit more state, which we store here.
// Minimal font size that would be used during canvas fillText operations.
var MIN_FONT_SIZE = 16;
// Maximum font size that would be used during canvas fillText operations.
var MAX_FONT_SIZE = 100;
var MAX_GROUP_SIZE = 4096;
// Heuristic value used when enforcing minimum line widths.
var MIN_WIDTH_FACTOR = 0.65;
var COMPILE_TYPE3_GLYPHS = true;
var MAX_SIZE_TO_COMPILE = 1000;
var FULL_CHUNK_HEIGHT = 16;
function createScratchCanvas(width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
function addContextCurrentTransform(ctx) {
// If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
if (!ctx.mozCurrentTransform) {
ctx._originalSave = ctx.save;
ctx._originalRestore = ctx.restore;
ctx._originalRotate = ctx.rotate;
ctx._originalScale = ctx.scale;
ctx._originalTranslate = ctx.translate;
ctx._originalTransform = ctx.transform;
ctx._originalSetTransform = ctx.setTransform;
ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
ctx._transformStack = [];
Object.defineProperty(ctx, 'mozCurrentTransform', {
get: function getCurrentTransform() {
return this._transformMatrix;
}
});
Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
get: function getCurrentTransformInverse() {
// Calculation done using WolframAlpha:
// http://www.wolframalpha.com/input/?
// i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
var m = this._transformMatrix;
var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
var ad_bc = a * d - b * c;
var bc_ad = b * c - a * d;
return [
d / ad_bc,
b / bc_ad,
c / bc_ad,
a / ad_bc,
(d * e - c * f) / bc_ad,
(b * e - a * f) / ad_bc
];
}
});
ctx.save = function ctxSave() {
var old = this._transformMatrix;
this._transformStack.push(old);
this._transformMatrix = old.slice(0, 6);
this._originalSave();
};
ctx.restore = function ctxRestore() {
var prev = this._transformStack.pop();
if (prev) {
this._transformMatrix = prev;
this._originalRestore();
}
};
ctx.translate = function ctxTranslate(x, y) {
var m = this._transformMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
this._originalTranslate(x, y);
};
ctx.scale = function ctxScale(x, y) {
var m = this._transformMatrix;
m[0] = m[0] * x;
m[1] = m[1] * x;
m[2] = m[2] * y;
m[3] = m[3] * y;
this._originalScale(x, y);
};
ctx.transform = function ctxTransform(a, b, c, d, e, f) {
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * a + m[2] * b,
m[1] * a + m[3] * b,
m[0] * c + m[2] * d,
m[1] * c + m[3] * d,
m[0] * e + m[2] * f + m[4],
m[1] * e + m[3] * f + m[5]
];
ctx._originalTransform(a, b, c, d, e, f);
};
ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
this._transformMatrix = [a, b, c, d, e, f];
ctx._originalSetTransform(a, b, c, d, e, f);
};
ctx.rotate = function ctxRotate(angle) {
var cosValue = Math.cos(angle);
var sinValue = Math.sin(angle);
var m = this._transformMatrix;
this._transformMatrix = [
m[0] * cosValue + m[2] * sinValue,
m[1] * cosValue + m[3] * sinValue,
m[0] * (-sinValue) + m[2] * cosValue,
m[1] * (-sinValue) + m[3] * cosValue,
m[4],
m[5]
];
this._originalRotate(angle);
};
}
}
var CachedCanvases = (function CachedCanvasesClosure() {
function CachedCanvases() {
this.cache = Object.create(null);
}
CachedCanvases.prototype = {
getCanvas: function CachedCanvases_getCanvas(id, width, height,
trackTransform) {
var canvasEntry;
if (this.cache[id] !== undefined) {
canvasEntry = this.cache[id];
canvasEntry.canvas.width = width;
canvasEntry.canvas.height = height;
// reset canvas transform for emulated mozCurrentTransform, if needed
canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
} else {
var canvas = createScratchCanvas(width, height);
var ctx = canvas.getContext('2d');
if (trackTransform) {
addContextCurrentTransform(ctx);
}
this.cache[id] = canvasEntry = {canvas: canvas, context: ctx};
}
return canvasEntry;
},
clear: function () {
for (var id in this.cache) {
var canvasEntry = this.cache[id];
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
canvasEntry.canvas.width = 0;
canvasEntry.canvas.height = 0;
delete this.cache[id];
}
}
};
return CachedCanvases;
})();
function compileType3Glyph(imgData) {
var POINT_TO_PROCESS_LIMIT = 1000;
var width = imgData.width, height = imgData.height;
var i, j, j0, width1 = width + 1;
var points = new Uint8Array(width1 * (height + 1));
var POINT_TYPES =
new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
// decodes bit-packed mask data
var lineSize = (width + 7) & ~7, data0 = imgData.data;
var data = new Uint8Array(lineSize * height), pos = 0, ii;
for (i = 0, ii = data0.length; i < ii; i++) {
var mask = 128, elem = data0[i];
while (mask > 0) {
data[pos++] = (elem & mask) ? 0 : 255;
mask >>= 1;
}
}
// finding iteresting points: every point is located between mask pixels,
// so there will be points of the (width + 1)x(height + 1) grid. Every point
// will have flags assigned based on neighboring mask pixels:
// 4 | 8
// --P--
// 2 | 1
// We are interested only in points with the flags:
// - outside corners: 1, 2, 4, 8;
// - inside corners: 7, 11, 13, 14;
// - and, intersections: 5, 10.
var count = 0;
pos = 0;
if (data[pos] !== 0) {
points[0] = 1;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j] = data[pos] ? 2 : 1;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j] = 2;
++count;
}
for (i = 1; i < height; i++) {
pos = i * lineSize;
j0 = i * width1;
if (data[pos - lineSize] !== data[pos]) {
points[j0] = data[pos] ? 1 : 8;
++count;
}
// 'sum' is the position of the current pixel configuration in the 'TYPES'
// array (in order 8-1-2-4, so we can use '>>2' to shift the column).
var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
for (j = 1; j < width; j++) {
sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
(data[pos - lineSize + 1] ? 8 : 0);
if (POINT_TYPES[sum]) {
points[j0 + j] = POINT_TYPES[sum];
++count;
}
pos++;
}
if (data[pos - lineSize] !== data[pos]) {
points[j0 + j] = data[pos] ? 2 : 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
}
pos = lineSize * (height - 1);
j0 = i * width1;
if (data[pos] !== 0) {
points[j0] = 8;
++count;
}
for (j = 1; j < width; j++) {
if (data[pos] !== data[pos + 1]) {
points[j0 + j] = data[pos] ? 4 : 8;
++count;
}
pos++;
}
if (data[pos] !== 0) {
points[j0 + j] = 4;
++count;
}
if (count > POINT_TO_PROCESS_LIMIT) {
return null;
}
// building outlines
var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
var outlines = [];
for (i = 0; count && i <= height; i++) {
var p = i * width1;
var end = p + width;
while (p < end && !points[p]) {
p++;
}
if (p === end) {
continue;
}
var coords = [p % width1, i];
var type = points[p], p0 = p, pp;
do {
var step = steps[type];
do {
p += step;
} while (!points[p]);
pp = points[p];
if (pp !== 5 && pp !== 10) {
// set new direction
type = pp;
// delete mark
points[p] = 0;
} else { // type is 5 or 10, ie, a crossing
// set new direction
type = pp & ((0x33 * type) >> 4);
// set new type for "future hit"
points[p] &= (type >> 2 | type << 2);
}
coords.push(p % width1);
coords.push((p / width1) | 0);
--count;
} while (p0 !== p);
outlines.push(coords);
--i;
}
var drawOutline = function(c) {
c.save();
// the path shall be painted in [0..1]x[0..1] space
c.scale(1 / width, -1 / height);
c.translate(0, -height);
c.beginPath();
for (var i = 0, ii = outlines.length; i < ii; i++) {
var o = outlines[i];
c.moveTo(o[0], o[1]);
for (var j = 2, jj = o.length; j < jj; j += 2) {
c.lineTo(o[j], o[j+1]);
}
}
c.fill();
c.beginPath();
c.restore();
};
return drawOutline;
}
var CanvasExtraState = (function CanvasExtraStateClosure() {
function CanvasExtraState(old) {
// Are soft masks and alpha values shapes or opacities?
this.alphaIsShape = false;
this.fontSize = 0;
this.fontSizeScale = 1;
this.textMatrix = IDENTITY_MATRIX;
this.textMatrixScale = 1;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.leading = 0;
// Current point (in user coordinates)
this.x = 0;
this.y = 0;
// Start of text line (in text coordinates)
this.lineX = 0;
this.lineY = 0;
// Character and word spacing
this.charSpacing = 0;
this.wordSpacing = 0;
this.textHScale = 1;
this.textRenderingMode = TextRenderingMode.FILL;
this.textRise = 0;
// Default fore and background colors
this.fillColor = '#000000';
this.strokeColor = '#000000';
this.patternFill = false;
// Note: fill alpha applies to all non-stroking operations
this.fillAlpha = 1;
this.strokeAlpha = 1;
this.lineWidth = 1;
this.activeSMask = null; // nonclonable field (see the save method below)
this.old = old;
}
CanvasExtraState.prototype = {
clone: function CanvasExtraState_clone() {
return Object.create(this);
},
setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
this.x = x;
this.y = y;
}
};
return CanvasExtraState;
})();
var CanvasGraphics = (function CanvasGraphicsClosure() {
// Defines the time the executeOperatorList is going to be executing
// before it stops and shedules a continue of execution.
var EXECUTION_TIME = 15;
// Defines the number of steps before checking the execution time
var EXECUTION_STEPS = 10;
function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
this.ctx = canvasCtx;
this.current = new CanvasExtraState();
this.stateStack = [];
this.pendingClip = null;
this.pendingEOFill = false;
this.res = null;
this.xobjs = null;
this.commonObjs = commonObjs;
this.objs = objs;
this.imageLayer = imageLayer;
this.groupStack = [];
this.processingType3 = null;
// Patterns are painted relative to the initial page/form transform, see pdf
// spec 8.7.2 NOTE 1.
this.baseTransform = null;
this.baseTransformStack = [];
this.groupLevel = 0;
this.smaskStack = [];
this.smaskCounter = 0;
this.tempSMask = null;
this.cachedCanvases = new CachedCanvases();
if (canvasCtx) {
// NOTE: if mozCurrentTransform is polyfilled, then the current state of
// the transformation must already be set in canvasCtx._transformMatrix.
addContextCurrentTransform(canvasCtx);
}
this.cachedGetSinglePixelWidth = null;
}
function putBinaryImageData(ctx, imgData) {
if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
ctx.putImageData(imgData, 0, 0);
return;
}
// Put the image data to the canvas in chunks, rather than putting the
// whole image at once. This saves JS memory, because the ImageData object
// is smaller. It also possibly saves C++ memory within the implementation
// of putImageData(). (E.g. in Firefox we make two short-lived copies of
// the data passed to putImageData()). |n| shouldn't be too small, however,
// because too many putImageData() calls will slow things down.
//
// Note: as written, if the last chunk is partial, the putImageData() call
// will (conceptually) put pixels past the bounds of the canvas. But
// that's ok; any such pixels are ignored.
var height = imgData.height, width = imgData.width;
var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
var srcPos = 0, destPos;
var src = imgData.data;
var dest = chunkImgData.data;
var i, j, thisChunkHeight, elemsInThisChunk;
// There are multiple forms in which the pixel data can be passed, and
// imgData.kind tells us which one this is.
if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
// Grayscale, 1 bit per pixel (i.e. black-and-white).
var srcLength = src.byteLength;
var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
new Uint32ArrayView(dest);
var dest32DataLength = dest32.length;
var fullSrcDiff = (width + 7) >> 3;
var white = 0xFFFFFFFF;
var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
0xFF000000 : 0x000000FF;
for (i = 0; i < totalChunks; i++) {
thisChunkHeight =
(i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
destPos = 0;
for (j = 0; j < thisChunkHeight; j++) {
var srcDiff = srcLength - srcPos;
var k = 0;
var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
var kEndUnrolled = kEnd & ~7;
var mask = 0;
var srcByte = 0;
for (; k < kEndUnrolled; k += 8) {
srcByte = src[srcPos++];
dest32[destPos++] = (srcByte & 128) ? white : black;
dest32[destPos++] = (srcByte & 64) ? white : black;
dest32[destPos++] = (srcByte & 32) ? white : black;
dest32[destPos++] = (srcByte & 16) ? white : black;
dest32[destPos++] = (srcByte & 8) ? white : black;
dest32[destPos++] = (srcByte & 4) ? white : black;
dest32[destPos++] = (srcByte & 2) ? white : black;
dest32[destPos++] = (srcByte & 1) ? white : black;
}
for (; k < kEnd; k++) {
if (mask === 0) {
srcByte = src[srcPos++];
mask = 128;
}
dest32[destPos++] = (srcByte & mask) ? white : black;
mask >>= 1;
}
}
// We ran out of input. Make all remaining pixels transparent.
while (destPos < dest32DataLength) {
dest32[destPos++] = 0;
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
} else if (imgData.kind === ImageKind.RGBA_32BPP) {
// RGBA, 32-bits per pixel.
j = 0;
elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
for (i = 0; i < fullChunks; i++) {
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
srcPos += elemsInThisChunk;
ctx.putImageData(chunkImgData, 0, j);
j += FULL_CHUNK_HEIGHT;
}
if (i < totalChunks) {
elemsInThisChunk = width * partialChunkHeight * 4;
dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
ctx.putImageData(chunkImgData, 0, j);
}
} else if (imgData.kind === ImageKind.RGB_24BPP) {
// RGB, 24-bits per pixel.
thisChunkHeight = FULL_CHUNK_HEIGHT;
elemsInThisChunk = width * thisChunkHeight;
for (i = 0; i < totalChunks; i++) {
if (i >= fullChunks) {
thisChunkHeight = partialChunkHeight;
elemsInThisChunk = width * thisChunkHeight;
}
destPos = 0;
for (j = elemsInThisChunk; j--;) {
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = src[srcPos++];
dest[destPos++] = 255;
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
} else {
error('bad image kind: ' + imgData.kind);
}
}
function putBinaryImageMask(ctx, imgData) {
var height = imgData.height, width = imgData.width;
var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
var srcPos = 0;
var src = imgData.data;
var dest = chunkImgData.data;
for (var i = 0; i < totalChunks; i++) {
var thisChunkHeight =
(i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
// Expand the mask so it can be used by the canvas. Any required
// inversion has already been handled.
var destPos = 3; // alpha component offset
for (var j = 0; j < thisChunkHeight; j++) {
var mask = 0;
for (var k = 0; k < width; k++) {
if (!mask) {
var elem = src[srcPos++];
mask = 128;
}
dest[destPos] = (elem & mask) ? 0 : 255;
destPos += 4;
mask >>= 1;
}
}
ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
}
}
function copyCtxState(sourceCtx, destCtx) {
var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
'globalCompositeOperation', 'font'];
for (var i = 0, ii = properties.length; i < ii; i++) {
var property = properties[i];
if (sourceCtx[property] !== undefined) {
destCtx[property] = sourceCtx[property];
}
}
if (sourceCtx.setLineDash !== undefined) {
destCtx.setLineDash(sourceCtx.getLineDash());
destCtx.lineDashOffset = sourceCtx.lineDashOffset;
} else if (sourceCtx.mozDashOffset !== undefined) {
destCtx.mozDash = sourceCtx.mozDash;
destCtx.mozDashOffset = sourceCtx.mozDashOffset;
}
}
function composeSMaskBackdrop(bytes, r0, g0, b0) {
var length = bytes.length;
for (var i = 3; i < length; i += 4) {
var alpha = bytes[i];
if (alpha === 0) {
bytes[i - 3] = r0;
bytes[i - 2] = g0;
bytes[i - 1] = b0;
} else if (alpha < 255) {
var alpha_ = 255 - alpha;
bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
}
}
}
function composeSMaskAlpha(maskData, layerData, transferMap) {
var length = maskData.length;
var scale = 1 / 255;
for (var i = 3; i < length; i += 4) {
var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
layerData[i] = (layerData[i] * alpha * scale) | 0;
}
}
function composeSMaskLuminosity(maskData, layerData, transferMap) {
var length = maskData.length;
for (var i = 3; i < length; i += 4) {
var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
(maskData[i - 2] * 152) + // * 0.59 ....
(maskData[i - 1] * 28); // * 0.11 ....
layerData[i] = transferMap ?
(layerData[i] * transferMap[y >> 8]) >> 8 :
(layerData[i] * y) >> 16;
}
}
function genericComposeSMask(maskCtx, layerCtx, width, height,
subtype, backdrop, transferMap) {
var hasBackdrop = !!backdrop;
var r0 = hasBackdrop ? backdrop[0] : 0;
var g0 = hasBackdrop ? backdrop[1] : 0;
var b0 = hasBackdrop ? backdrop[2] : 0;
var composeFn;
if (subtype === 'Luminosity') {
composeFn = composeSMaskLuminosity;
} else {
composeFn = composeSMaskAlpha;
}
// processing image in chunks to save memory
var PIXELS_TO_PROCESS = 1048576;
var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
for (var row = 0; row < height; row += chunkSize) {
var chunkHeight = Math.min(chunkSize, height - row);
var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
if (hasBackdrop) {
composeSMaskBackdrop(maskData.data, r0, g0, b0);
}
composeFn(maskData.data, layerData.data, transferMap);
maskCtx.putImageData(layerData, 0, row);
}
}
function composeSMask(ctx, smask, layerCtx) {
var mask = smask.canvas;
var maskCtx = smask.context;
ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
smask.offsetX, smask.offsetY);
var backdrop = smask.backdrop || null;
if (!smask.transferMap && WebGLUtils.isEnabled) {
var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
{subtype: smask.subtype, backdrop: backdrop});
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.drawImage(composed, smask.offsetX, smask.offsetY);
return;
}
genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
smask.subtype, backdrop, smask.transferMap);
ctx.drawImage(mask, 0, 0);
}
var LINE_CAP_STYLES = ['butt', 'round', 'square'];
var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
var NORMAL_CLIP = {};
var EO_CLIP = {};
CanvasGraphics.prototype = {
beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport,
transparency) {
// For pdfs that use blend modes we have to clear the canvas else certain
// blend modes can look wrong since we'd be blending with a white
// backdrop. The problem with a transparent backdrop though is we then
// don't get sub pixel anti aliasing on text, creating temporary
// transparent canvas when we have blend modes.
var width = this.ctx.canvas.width;
var height = this.ctx.canvas.height;
this.ctx.save();
this.ctx.fillStyle = 'rgb(255, 255, 255)';
this.ctx.fillRect(0, 0, width, height);
this.ctx.restore();
if (transparency) {
var transparentCanvas = this.cachedCanvases.getCanvas(
'transparent', width, height, true);
this.compositeCtx = this.ctx;
this.transparentCanvas = transparentCanvas.canvas;
this.ctx = transparentCanvas.context;
this.ctx.save();
// The transform can be applied before rendering, transferring it to
// the new canvas.
this.ctx.transform.apply(this.ctx,
this.compositeCtx.mozCurrentTransform);
}
this.ctx.save();
if (transform) {
this.ctx.transform.apply(this.ctx, transform);
}
this.ctx.transform.apply(this.ctx, viewport.transform);
this.baseTransform = this.ctx.mozCurrentTransform.slice();
if (this.imageLayer) {
this.imageLayer.beginLayout();
}
},
executeOperatorList: function CanvasGraphics_executeOperatorList(
operatorList,
executionStartIdx, continueCallback,
stepper) {
var argsArray = operatorList.argsArray;
var fnArray = operatorList.fnArray;
var i = executionStartIdx || 0;
var argsArrayLen = argsArray.length;
// Sometimes the OperatorList to execute is empty.
if (argsArrayLen === i) {
return i;
}
var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
typeof continueCallback === 'function');
var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
var steps = 0;
var commonObjs = this.commonObjs;
var objs = this.objs;
var fnId;
while (true) {
if (stepper !== undefined && i === stepper.nextBreakPoint) {
stepper.breakIt(i, continueCallback);
return i;
}
fnId = fnArray[i];
if (fnId !== OPS.dependency) {
this[fnId].apply(this, argsArray[i]);
} else {
var deps = argsArray[i];
for (var n = 0, nn = deps.length; n < nn; n++) {
var depObjId = deps[n];
var common = depObjId[0] === 'g' && depObjId[1] === '_';
var objsPool = common ? commonObjs : objs;
// If the promise isn't resolved yet, add the continueCallback
// to the promise and bail out.
if (!objsPool.isResolved(depObjId)) {
objsPool.get(depObjId, continueCallback);
return i;
}
}
}
i++;
// If the entire operatorList was executed, stop as were done.
if (i === argsArrayLen) {
return i;
}
// If the execution took longer then a certain amount of time and
// `continueCallback` is specified, interrupt the execution.
if (chunkOperations && ++steps > EXECUTION_STEPS) {
if (Date.now() > endTime) {
continueCallback();
return i;
}
steps = 0;
}
// If the operatorList isn't executed completely yet OR the execution
// time was short enough, do another execution round.
}
},
endDrawing: function CanvasGraphics_endDrawing() {
this.ctx.restore();
if (this.transparentCanvas) {
this.ctx = this.compositeCtx;
this.ctx.drawImage(this.transparentCanvas, 0, 0);
this.transparentCanvas = null;
}
this.cachedCanvases.clear();
WebGLUtils.clear();
if (this.imageLayer) {
this.imageLayer.endLayout();
}
},
// Graphics state
setLineWidth: function CanvasGraphics_setLineWidth(width) {
this.current.lineWidth = width;
this.ctx.lineWidth = width;
},
setLineCap: function CanvasGraphics_setLineCap(style) {
this.ctx.lineCap = LINE_CAP_STYLES[style];
},
setLineJoin: function CanvasGraphics_setLineJoin(style) {
this.ctx.lineJoin = LINE_JOIN_STYLES[style];
},
setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
this.ctx.miterLimit = limit;
},
setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
var ctx = this.ctx;
if (ctx.setLineDash !== undefined) {
ctx.setLineDash(dashArray);
ctx.lineDashOffset = dashPhase;
} else {
ctx.mozDash = dashArray;
ctx.mozDashOffset = dashPhase;
}
},
setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
// Maybe if we one day fully support color spaces this will be important
// for now we can ignore.
// TODO set rendering intent?
},
setFlatness: function CanvasGraphics_setFlatness(flatness) {
// There's no way to control this with canvas, but we can safely ignore.
// TODO set flatness?
},
setGState: function CanvasGraphics_setGState(states) {
for (var i = 0, ii = states.length; i < ii; i++) {
var state = states[i];
var key = state[0];
var value = state[1];
switch (key) {
case 'LW':
this.setLineWidth(value);
break;
case 'LC':
this.setLineCap(value);
break;
case 'LJ':
this.setLineJoin(value);
break;
case 'ML':
this.setMiterLimit(value);
break;
case 'D':
this.setDash(value[0], value[1]);
break;
case 'RI':
this.setRenderingIntent(value);
break;
case 'FL':
this.setFlatness(value);
break;
case 'Font':
this.setFont(value[0], value[1]);
break;
case 'CA':
this.current.strokeAlpha = state[1];
break;
case 'ca':
this.current.fillAlpha = state[1];
this.ctx.globalAlpha = state[1];
break;
case 'BM':
if (value && value.name && (value.name !== 'Normal')) {
var mode = value.name.replace(/([A-Z])/g,
function(c) {
return '-' + c.toLowerCase();
}
).substring(1);
this.ctx.globalCompositeOperation = mode;
if (this.ctx.globalCompositeOperation !== mode) {
warn('globalCompositeOperation "' + mode +
'" is not supported');
}
} else {
this.ctx.globalCompositeOperation = 'source-over';
}
break;
case 'SMask':
if (this.current.activeSMask) {
this.endSMaskGroup();
}
this.current.activeSMask = value ? this.tempSMask : null;
if (this.current.activeSMask) {
this.beginSMaskGroup();
}
this.tempSMask = null;
break;
}
}
},
beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
var activeSMask = this.current.activeSMask;
var drawnWidth = activeSMask.canvas.width;
var drawnHeight = activeSMask.canvas.height;
var cacheId = 'smaskGroupAt' + this.groupLevel;
var scratchCanvas = this.cachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var currentCtx = this.ctx;
var currentTransform = currentCtx.mozCurrentTransform;
this.ctx.save();
var groupCtx = scratchCanvas.context;
groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
},
endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
var groupCtx = this.ctx;
this.groupLevel--;
this.ctx = this.groupStack.pop();
composeSMask(this.ctx, this.current.activeSMask, groupCtx);
this.ctx.restore();
copyCtxState(groupCtx, this.ctx);
},
save: function CanvasGraphics_save() {
this.ctx.save();
var old = this.current;
this.stateStack.push(old);
this.current = old.clone();
this.current.activeSMask = null;
},
restore: function CanvasGraphics_restore() {
if (this.stateStack.length !== 0) {
if (this.current.activeSMask !== null) {
this.endSMaskGroup();
}
this.current = this.stateStack.pop();
this.ctx.restore();
// Ensure that the clipping path is reset (fixes issue6413.pdf).
this.pendingClip = null;
this.cachedGetSinglePixelWidth = null;
}
},
transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
this.ctx.transform(a, b, c, d, e, f);
this.cachedGetSinglePixelWidth = null;
},
// Path
constructPath: function CanvasGraphics_constructPath(ops, args) {
var ctx = this.ctx;
var current = this.current;
var x = current.x, y = current.y;
for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
switch (ops[i] | 0) {
case OPS.rectangle:
x = args[j++];
y = args[j++];
var width = args[j++];
var height = args[j++];
if (width === 0) {
width = this.getSinglePixelWidth();
}
if (height === 0) {
height = this.getSinglePixelWidth();
}
var xw = x + width;
var yh = y + height;
this.ctx.moveTo(x, y);
this.ctx.lineTo(xw, y);
this.ctx.lineTo(xw, yh);
this.ctx.lineTo(x, yh);
this.ctx.lineTo(x, y);
this.ctx.closePath();
break;
case OPS.moveTo:
x = args[j++];
y = args[j++];
ctx.moveTo(x, y);
break;
case OPS.lineTo:
x = args[j++];
y = args[j++];
ctx.lineTo(x, y);
break;
case OPS.curveTo:
x = args[j + 4];
y = args[j + 5];
ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
x, y);
j += 6;
break;
case OPS.curveTo2:
ctx.bezierCurveTo(x, y, args[j], args[j + 1],
args[j + 2], args[j + 3]);
x = args[j + 2];
y = args[j + 3];
j += 4;
break;
case OPS.curveTo3:
x = args[j + 2];
y = args[j + 3];
ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
j += 4;
break;
case OPS.closePath:
ctx.closePath();
break;
}
}
current.setCurrentPoint(x, y);
},
closePath: function CanvasGraphics_closePath() {
this.ctx.closePath();
},
stroke: function CanvasGraphics_stroke(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var strokeColor = this.current.strokeColor;
// Prevent drawing too thin lines by enforcing a minimum line width.
ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
this.current.lineWidth);
// For stroke we want to temporarily change the global alpha to the
// stroking alpha.
ctx.globalAlpha = this.current.strokeAlpha;
if (strokeColor && strokeColor.hasOwnProperty('type') &&
strokeColor.type === 'Pattern') {
// for patterns, we transform to pattern space, calculate
// the pattern, call stroke, and restore to user space
ctx.save();
ctx.strokeStyle = strokeColor.getPattern(ctx, this);
ctx.stroke();
ctx.restore();
} else {
ctx.stroke();
}
if (consumePath) {
this.consumePath();
}
// Restore the global alpha to the fill alpha
ctx.globalAlpha = this.current.fillAlpha;
},
closeStroke: function CanvasGraphics_closeStroke() {
this.closePath();
this.stroke();
},
fill: function CanvasGraphics_fill(consumePath) {
consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
var ctx = this.ctx;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var needRestore = false;
if (isPatternFill) {
ctx.save();
if (this.baseTransform) {
ctx.setTransform.apply(ctx, this.baseTransform);
}
ctx.fillStyle = fillColor.getPattern(ctx, this);
needRestore = true;
}
if (this.pendingEOFill) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.fill();
ctx.mozFillRule = 'nonzero';
} else {
ctx.fill('evenodd');
}
this.pendingEOFill = false;
} else {
ctx.fill();
}
if (needRestore) {
ctx.restore();
}
if (consumePath) {
this.consumePath();
}
},
eoFill: function CanvasGraphics_eoFill() {
this.pendingEOFill = true;
this.fill();
},
fillStroke: function CanvasGraphics_fillStroke() {
this.fill(false);
this.stroke(false);
this.consumePath();
},
eoFillStroke: function CanvasGraphics_eoFillStroke() {
this.pendingEOFill = true;
this.fillStroke();
},
closeFillStroke: function CanvasGraphics_closeFillStroke() {
this.closePath();
this.fillStroke();
},
closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
this.pendingEOFill = true;
this.closePath();
this.fillStroke();
},
endPath: function CanvasGraphics_endPath() {
this.consumePath();
},
// Clipping
clip: function CanvasGraphics_clip() {
this.pendingClip = NORMAL_CLIP;
},
eoClip: function CanvasGraphics_eoClip() {
this.pendingClip = EO_CLIP;
},
// Text
beginText: function CanvasGraphics_beginText() {
this.current.textMatrix = IDENTITY_MATRIX;
this.current.textMatrixScale = 1;
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
endText: function CanvasGraphics_endText() {
var paths = this.pendingTextPaths;
var ctx = this.ctx;
if (paths === undefined) {
ctx.beginPath();
return;
}
ctx.save();
ctx.beginPath();
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
ctx.setTransform.apply(ctx, path.transform);
ctx.translate(path.x, path.y);
path.addToPath(ctx, path.fontSize);
}
ctx.restore();
ctx.clip();
ctx.beginPath();
delete this.pendingTextPaths;
},
setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
this.current.charSpacing = spacing;
},
setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
this.current.wordSpacing = spacing;
},
setHScale: function CanvasGraphics_setHScale(scale) {
this.current.textHScale = scale / 100;
},
setLeading: function CanvasGraphics_setLeading(leading) {
this.current.leading = -leading;
},
setFont: function CanvasGraphics_setFont(fontRefName, size) {
var fontObj = this.commonObjs.get(fontRefName);
var current = this.current;
if (!fontObj) {
error('Can\'t find font for ' + fontRefName);
}
current.fontMatrix = (fontObj.fontMatrix ?
fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
// A valid matrix needs all main diagonal elements to be non-zero
// This also ensures we bypass FF bugzilla bug #719844.
if (current.fontMatrix[0] === 0 ||
current.fontMatrix[3] === 0) {
warn('Invalid font matrix for font ' + fontRefName);
}
// The spec for Tf (setFont) says that 'size' specifies the font 'scale',
// and in some docs this can be negative (inverted x-y axes).
if (size < 0) {
size = -size;
current.fontDirection = -1;
} else {
current.fontDirection = 1;
}
this.current.font = fontObj;
this.current.fontSize = size;
if (fontObj.isType3Font) {
return; // we don't need ctx.font for Type3 fonts
}
var name = fontObj.loadedName || 'sans-serif';
var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') :
(fontObj.bold ? 'bold' : 'normal');
var italic = fontObj.italic ? 'italic' : 'normal';
var typeface = '"' + name + '", ' + fontObj.fallbackName;
// Some font backends cannot handle fonts below certain size.
// Keeping the font at minimal size and using the fontSizeScale to change
// the current transformation matrix before the fillText/strokeText.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
this.current.fontSizeScale = size / browserFontSize;
var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
this.ctx.font = rule;
},
setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
this.current.textRenderingMode = mode;
},
setTextRise: function CanvasGraphics_setTextRise(rise) {
this.current.textRise = rise;
},
moveText: function CanvasGraphics_moveText(x, y) {
this.current.x = this.current.lineX += x;
this.current.y = this.current.lineY += y;
},
setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
this.setLeading(-y);
this.moveText(x, y);
},
setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
this.current.textMatrix = [a, b, c, d, e, f];
this.current.textMatrixScale = Math.sqrt(a * a + b * b);
this.current.x = this.current.lineX = 0;
this.current.y = this.current.lineY = 0;
},
nextLine: function CanvasGraphics_nextLine() {
this.moveText(0, this.current.leading);
},
paintChar: function CanvasGraphics_paintChar(character, x, y) {
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var textRenderingMode = current.textRenderingMode;
var fontSize = current.fontSize / current.fontSizeScale;
var fillStrokeMode = textRenderingMode &
TextRenderingMode.FILL_STROKE_MASK;
var isAddToPathSet = !!(textRenderingMode &
TextRenderingMode.ADD_TO_PATH_FLAG);
var addToPath;
if (font.disableFontFace || isAddToPathSet) {
addToPath = font.getPathGenerator(this.commonObjs, character);
}
if (font.disableFontFace) {
ctx.save();
ctx.translate(x, y);
ctx.beginPath();
addToPath(ctx, fontSize);
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fill();
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.stroke();
}
ctx.restore();
} else {
if (fillStrokeMode === TextRenderingMode.FILL ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.fillText(character, x, y);
}
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
ctx.strokeText(character, x, y);
}
}
if (isAddToPathSet) {
var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
paths.push({
transform: ctx.mozCurrentTransform,
x: x,
y: y,
fontSize: fontSize,
addToPath: addToPath
});
}
},
get isFontSubpixelAAEnabled() {
// Checks if anti-aliasing is enabled when scaled text is painted.
// On Windows GDI scaled fonts looks bad.
var ctx = document.createElement('canvas').getContext('2d');
ctx.scale(1.5, 1);
ctx.fillText('I', 0, 10);
var data = ctx.getImageData(0, 0, 10, 10).data;
var enabled = false;
for (var i = 3; i < data.length; i += 4) {
if (data[i] > 0 && data[i] < 255) {
enabled = true;
break;
}
}
return shadow(this, 'isFontSubpixelAAEnabled', enabled);
},
showText: function CanvasGraphics_showText(glyphs) {
var current = this.current;
var font = current.font;
if (font.isType3Font) {
return this.showType3Text(glyphs);
}
var fontSize = current.fontSize;
if (fontSize === 0) {
return;
}
var ctx = this.ctx;
var fontSizeScale = current.fontSizeScale;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var fontDirection = current.fontDirection;
var textHScale = current.textHScale * fontDirection;
var glyphsLength = glyphs.length;
var vertical = font.vertical;
var spacingDir = vertical ? 1 : -1;
var defaultVMetrics = font.defaultVMetrics;
var widthAdvanceScale = fontSize * current.fontMatrix[0];
var simpleFillText =
current.textRenderingMode === TextRenderingMode.FILL &&
!font.disableFontFace;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y + current.textRise);
if (current.patternFill) {
// TODO: Some shading patterns are not applied correctly to text,
// e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
ctx.fillStyle = current.fillColor.getPattern(ctx, this);
}
if (fontDirection > 0) {
ctx.scale(textHScale, -1);
} else {
ctx.scale(textHScale, 1);
}
var lineWidth = current.lineWidth;
var scale = current.textMatrixScale;
if (scale === 0 || lineWidth === 0) {
var fillStrokeMode = current.textRenderingMode &
TextRenderingMode.FILL_STROKE_MASK;
if (fillStrokeMode === TextRenderingMode.STROKE ||
fillStrokeMode === TextRenderingMode.FILL_STROKE) {
this.cachedGetSinglePixelWidth = null;
lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
}
} else {
lineWidth /= scale;
}
if (fontSizeScale !== 1.0) {
ctx.scale(fontSizeScale, fontSizeScale);
lineWidth /= fontSizeScale;
}
ctx.lineWidth = lineWidth;
var x = 0, i;
for (i = 0; i < glyphsLength; ++i) {
var glyph = glyphs[i];
if (isNum(glyph)) {
x += spacingDir * glyph * fontSize / 1000;
continue;
}
var restoreNeeded = false;
var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
var character = glyph.fontChar;
var accent = glyph.accent;
var scaledX, scaledY, scaledAccentX, scaledAccentY;
var width = glyph.width;
if (vertical) {
var vmetric, vx, vy;
vmetric = glyph.vmetric || defaultVMetrics;
vx = glyph.vmetric ? vmetric[1] : width * 0.5;
vx = -vx * widthAdvanceScale;
vy = vmetric[2] * widthAdvanceScale;
width = vmetric ? -vmetric[0] : width;
scaledX = vx / fontSizeScale;
scaledY = (x + vy) / fontSizeScale;
} else {
scaledX = x / fontSizeScale;
scaledY = 0;
}
if (font.remeasure && width > 0) {
// Some standard fonts may not have the exact width: rescale per
// character if measured width is greater than expected glyph width
// and subpixel-aa is enabled, otherwise just center the glyph.
var measuredWidth = ctx.measureText(character).width * 1000 /
fontSize * fontSizeScale;
if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
var characterScaleX = width / measuredWidth;
restoreNeeded = true;
ctx.save();
ctx.scale(characterScaleX, 1);
scaledX /= characterScaleX;
} else if (width !== measuredWidth) {
scaledX += (width - measuredWidth) / 2000 *
fontSize / fontSizeScale;
}
}
if (simpleFillText && !accent) {
// common case
ctx.fillText(character, scaledX, scaledY);
} else {
this.paintChar(character, scaledX, scaledY);
if (accent) {
scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
}
}
var charWidth = width * widthAdvanceScale + spacing * fontDirection;
x += charWidth;
if (restoreNeeded) {
ctx.restore();
}
}
if (vertical) {
current.y -= x * textHScale;
} else {
current.x += x * textHScale;
}
ctx.restore();
},
showType3Text: function CanvasGraphics_showType3Text(glyphs) {
// Type3 fonts - each glyph is a "mini-PDF"
var ctx = this.ctx;
var current = this.current;
var font = current.font;
var fontSize = current.fontSize;
var fontDirection = current.fontDirection;
var spacingDir = font.vertical ? 1 : -1;
var charSpacing = current.charSpacing;
var wordSpacing = current.wordSpacing;
var textHScale = current.textHScale * fontDirection;
var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
var glyphsLength = glyphs.length;
var isTextInvisible =
current.textRenderingMode === TextRenderingMode.INVISIBLE;
var i, glyph, width, spacingLength;
if (isTextInvisible || fontSize === 0) {
return;
}
this.cachedGetSinglePixelWidth = null;
ctx.save();
ctx.transform.apply(ctx, current.textMatrix);
ctx.translate(current.x, current.y);
ctx.scale(textHScale, fontDirection);
for (i = 0; i < glyphsLength; ++i) {
glyph = glyphs[i];
if (isNum(glyph)) {
spacingLength = spacingDir * glyph * fontSize / 1000;
this.ctx.translate(spacingLength, 0);
current.x += spacingLength * textHScale;
continue;
}
var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
var operatorList = font.charProcOperatorList[glyph.operatorListId];
if (!operatorList) {
warn('Type3 character \"' + glyph.operatorListId +
'\" is not available');
continue;
}
this.processingType3 = glyph;
this.save();
ctx.scale(fontSize, fontSize);
ctx.transform.apply(ctx, fontMatrix);
this.executeOperatorList(operatorList);
this.restore();
var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
width = transformed[0] * fontSize + spacing;
ctx.translate(width, 0);
current.x += width * textHScale;
}
ctx.restore();
this.processingType3 = null;
},
// Type3 fonts
setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
// We can safely ignore this since the width should be the same
// as the width in the Widths array.
},
setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
yWidth,
llx,
lly,
urx,
ury) {
// TODO According to the spec we're also suppose to ignore any operators
// that set color or include images while processing this type3 font.
this.ctx.rect(llx, lly, urx - llx, ury - lly);
this.clip();
this.endPath();
},
// Color
getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
var pattern;
if (IR[0] === 'TilingPattern') {
var color = IR[1];
var baseTransform = this.baseTransform ||
this.ctx.mozCurrentTransform.slice();
var self = this;
var canvasGraphicsFactory = {
createCanvasGraphics: function (ctx) {
return new CanvasGraphics(ctx, self.commonObjs, self.objs);
}
};
pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory,
baseTransform);
} else {
pattern = getShadingPatternFromIR(IR);
}
return pattern;
},
setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
this.current.strokeColor = this.getColorN_Pattern(arguments);
},
setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
this.current.fillColor = this.getColorN_Pattern(arguments);
this.current.patternFill = true;
},
setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.ctx.strokeStyle = color;
this.current.strokeColor = color;
},
setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
var color = Util.makeCssRgb(r, g, b);
this.ctx.fillStyle = color;
this.current.fillColor = color;
this.current.patternFill = false;
},
shadingFill: function CanvasGraphics_shadingFill(patternIR) {
var ctx = this.ctx;
this.save();
var pattern = getShadingPatternFromIR(patternIR);
ctx.fillStyle = pattern.getPattern(ctx, this, true);
var inv = ctx.mozCurrentTransformInverse;
if (inv) {
var canvas = ctx.canvas;
var width = canvas.width;
var height = canvas.height;
var bl = Util.applyTransform([0, 0], inv);
var br = Util.applyTransform([0, height], inv);
var ul = Util.applyTransform([width, 0], inv);
var ur = Util.applyTransform([width, height], inv);
var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
} else {
// HACK to draw the gradient onto an infinite rectangle.
// PDF gradients are drawn across the entire image while
// Canvas only allows gradients to be drawn in a rectangle
// The following bug should allow us to remove this.
// https://bugzilla.mozilla.org/show_bug.cgi?id=664884
this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
}
this.restore();
},
// Images
beginInlineImage: function CanvasGraphics_beginInlineImage() {
error('Should not call beginInlineImage');
},
beginImageData: function CanvasGraphics_beginImageData() {
error('Should not call beginImageData');
},
paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
bbox) {
this.save();
this.baseTransformStack.push(this.baseTransform);
if (isArray(matrix) && 6 === matrix.length) {
this.transform.apply(this, matrix);
}
this.baseTransform = this.ctx.mozCurrentTransform;
if (isArray(bbox) && 4 === bbox.length) {
var width = bbox[2] - bbox[0];
var height = bbox[3] - bbox[1];
this.ctx.rect(bbox[0], bbox[1], width, height);
this.clip();
this.endPath();
}
},
paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
this.restore();
this.baseTransform = this.baseTransformStack.pop();
},
beginGroup: function CanvasGraphics_beginGroup(group) {
this.save();
var currentCtx = this.ctx;
// TODO non-isolated groups - according to Rik at adobe non-isolated
// group results aren't usually that different and they even have tools
// that ignore this setting. Notes from Rik on implmenting:
// - When you encounter an transparency group, create a new canvas with
// the dimensions of the bbox
// - copy the content from the previous canvas to the new canvas
// - draw as usual
// - remove the backdrop alpha:
// alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
// value of your transparency group and 'alphaBackdrop' the alpha of the
// backdrop
// - remove background color:
// colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
if (!group.isolated) {
info('TODO: Support non-isolated groups.');
}
// TODO knockout - supposedly possible with the clever use of compositing
// modes.
if (group.knockout) {
warn('Knockout groups not supported.');
}
var currentTransform = currentCtx.mozCurrentTransform;
if (group.matrix) {
currentCtx.transform.apply(currentCtx, group.matrix);
}
assert(group.bbox, 'Bounding box is required.');
// Based on the current transform figure out how big the bounding box
// will actually be.
var bounds = Util.getAxialAlignedBoundingBox(
group.bbox,
currentCtx.mozCurrentTransform);
// Clip the bounding box to the current canvas.
var canvasBounds = [0,
0,
currentCtx.canvas.width,
currentCtx.canvas.height];
bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
// Use ceil in case we're between sizes so we don't create canvas that is
// too small and make the canvas at least 1x1 pixels.
var offsetX = Math.floor(bounds[0]);
var offsetY = Math.floor(bounds[1]);
var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
var scaleX = 1, scaleY = 1;
if (drawnWidth > MAX_GROUP_SIZE) {
scaleX = drawnWidth / MAX_GROUP_SIZE;
drawnWidth = MAX_GROUP_SIZE;
}
if (drawnHeight > MAX_GROUP_SIZE) {
scaleY = drawnHeight / MAX_GROUP_SIZE;
drawnHeight = MAX_GROUP_SIZE;
}
var cacheId = 'groupAt' + this.groupLevel;
if (group.smask) {
// Using two cache entries is case if masks are used one after another.
cacheId += '_smask_' + ((this.smaskCounter++) % 2);
}
var scratchCanvas = this.cachedCanvases.getCanvas(
cacheId, drawnWidth, drawnHeight, true);
var groupCtx = scratchCanvas.context;
// Since we created a new canvas that is just the size of the bounding box
// we have to translate the group ctx.
groupCtx.scale(1 / scaleX, 1 / scaleY);
groupCtx.translate(-offsetX, -offsetY);
groupCtx.transform.apply(groupCtx, currentTransform);
if (group.smask) {
// Saving state and cached mask to be used in setGState.
this.smaskStack.push({
canvas: scratchCanvas.canvas,
context: groupCtx,
offsetX: offsetX,
offsetY: offsetY,
scaleX: scaleX,
scaleY: scaleY,
subtype: group.smask.subtype,
backdrop: group.smask.backdrop,
transferMap: group.smask.transferMap || null
});
} else {
// Setup the current ctx so when the group is popped we draw it at the
// right location.
currentCtx.setTransform(1, 0, 0, 1, 0, 0);
currentCtx.translate(offsetX, offsetY);
currentCtx.scale(scaleX, scaleY);
}
// The transparency group inherits all off the current graphics state
// except the blend mode, soft mask, and alpha constants.
copyCtxState(currentCtx, groupCtx);
this.ctx = groupCtx;
this.setGState([
['BM', 'Normal'],
['ca', 1],
['CA', 1]
]);
this.groupStack.push(currentCtx);
this.groupLevel++;
},
endGroup: function CanvasGraphics_endGroup(group) {
this.groupLevel--;
var groupCtx = this.ctx;
this.ctx = this.groupStack.pop();
// Turn off image smoothing to avoid sub pixel interpolation which can
// look kind of blurry for some pdfs.
if (this.ctx.imageSmoothingEnabled !== undefined) {
this.ctx.imageSmoothingEnabled = false;
} else {
this.ctx.mozImageSmoothingEnabled = false;
}
if (group.smask) {
this.tempSMask = this.smaskStack.pop();
} else {
this.ctx.drawImage(groupCtx.canvas, 0, 0);
}
this.restore();
},
beginAnnotations: function CanvasGraphics_beginAnnotations() {
this.save();
this.current = new CanvasExtraState();
if (this.baseTransform) {
this.ctx.setTransform.apply(this.ctx, this.baseTransform);
}
},
endAnnotations: function CanvasGraphics_endAnnotations() {
this.restore();
},
beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
matrix) {
this.save();
if (isArray(rect) && 4 === rect.length) {
var width = rect[2] - rect[0];
var height = rect[3] - rect[1];
this.ctx.rect(rect[0], rect[1], width, height);
this.clip();
this.endPath();
}
this.transform.apply(this, transform);
this.transform.apply(this, matrix);
},
endAnnotation: function CanvasGraphics_endAnnotation() {
this.restore();
},
paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
var domImage = this.objs.get(objId);
if (!domImage) {
warn('Dependent image isn\'t ready yet');
return;
}
this.save();
var ctx = this.ctx;
// scale the image to the unit square
ctx.scale(1 / w, -1 / h);
ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
0, -h, w, h);
if (this.imageLayer) {
var currentTransform = ctx.mozCurrentTransformInverse;
var position = this.getCanvasPosition(0, 0);
this.imageLayer.appendImage({
objId: objId,
left: position[0],
top: position[1],
width: w / currentTransform[0],
height: h / currentTransform[3]
});
}
this.restore();
},
paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
var ctx = this.ctx;
var width = img.width, height = img.height;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var glyph = this.processingType3;
if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
glyph.compiled =
compileType3Glyph({data: img.data, width: width, height: height});
} else {
glyph.compiled = null;
}
}
if (glyph && glyph.compiled) {
glyph.compiled(ctx);
return;
}
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, img);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
this.paintInlineImageXObject(maskCanvas.canvas);
},
paintImageMaskXObjectRepeat:
function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
scaleY, positions) {
var width = imgData.width;
var height = imgData.height;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, imgData);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
var ctx = this.ctx;
for (var i = 0, ii = positions.length; i < ii; i += 2) {
ctx.save();
ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageMaskXObjectGroup:
function CanvasGraphics_paintImageMaskXObjectGroup(images) {
var ctx = this.ctx;
var fillColor = this.current.fillColor;
var isPatternFill = this.current.patternFill;
for (var i = 0, ii = images.length; i < ii; i++) {
var image = images[i];
var width = image.width, height = image.height;
var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas',
width, height);
var maskCtx = maskCanvas.context;
maskCtx.save();
putBinaryImageMask(maskCtx, image);
maskCtx.globalCompositeOperation = 'source-in';
maskCtx.fillStyle = isPatternFill ?
fillColor.getPattern(maskCtx, this) : fillColor;
maskCtx.fillRect(0, 0, width, height);
maskCtx.restore();
ctx.save();
ctx.transform.apply(ctx, image.transform);
ctx.scale(1, -1);
ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
0, -1, 1, 1);
ctx.restore();
}
},
paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
this.paintInlineImageXObject(imgData);
},
paintImageXObjectRepeat:
function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
positions) {
var imgData = this.objs.get(objId);
if (!imgData) {
warn('Dependent image isn\'t ready yet');
return;
}
var width = imgData.width;
var height = imgData.height;
var map = [];
for (var i = 0, ii = positions.length; i < ii; i += 2) {
map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
positions[i + 1]], x: 0, y: 0, w: width, h: height});
}
this.paintInlineImageXObjectGroup(imgData, map);
},
paintInlineImageXObject:
function CanvasGraphics_paintInlineImageXObject(imgData) {
var width = imgData.width;
var height = imgData.height;
var ctx = this.ctx;
this.save();
// scale the image to the unit square
ctx.scale(1 / width, -1 / height);
var currentTransform = ctx.mozCurrentTransformInverse;
var a = currentTransform[0], b = currentTransform[1];
var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
var c = currentTransform[2], d = currentTransform[3];
var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
var imgToPaint, tmpCanvas;
// instanceof HTMLElement does not work in jsdom node.js module
if (imgData instanceof HTMLElement || !imgData.data) {
imgToPaint = imgData;
} else {
tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
width, height);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
imgToPaint = tmpCanvas.canvas;
}
var paintWidth = width, paintHeight = height;
var tmpCanvasId = 'prescale1';
// Vertial or horizontal scaling shall not be more than 2 to not loose the
// pixels during drawImage operation, painting on the temporary canvas(es)
// that are twice smaller in size
while ((widthScale > 2 && paintWidth > 1) ||
(heightScale > 2 && paintHeight > 1)) {
var newWidth = paintWidth, newHeight = paintHeight;
if (widthScale > 2 && paintWidth > 1) {
newWidth = Math.ceil(paintWidth / 2);
widthScale /= paintWidth / newWidth;
}
if (heightScale > 2 && paintHeight > 1) {
newHeight = Math.ceil(paintHeight / 2);
heightScale /= paintHeight / newHeight;
}
tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId,
newWidth, newHeight);
tmpCtx = tmpCanvas.context;
tmpCtx.clearRect(0, 0, newWidth, newHeight);
tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, 0, newWidth, newHeight);
imgToPaint = tmpCanvas.canvas;
paintWidth = newWidth;
paintHeight = newHeight;
tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
}
ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
0, -height, width, height);
if (this.imageLayer) {
var position = this.getCanvasPosition(0, -height);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: width / currentTransform[0],
height: height / currentTransform[3]
});
}
this.restore();
},
paintInlineImageXObjectGroup:
function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
var ctx = this.ctx;
var w = imgData.width;
var h = imgData.height;
var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
var tmpCtx = tmpCanvas.context;
putBinaryImageData(tmpCtx, imgData);
for (var i = 0, ii = map.length; i < ii; i++) {
var entry = map[i];
ctx.save();
ctx.transform.apply(ctx, entry.transform);
ctx.scale(1, -1);
ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
0, -1, 1, 1);
if (this.imageLayer) {
var position = this.getCanvasPosition(entry.x, entry.y);
this.imageLayer.appendImage({
imgData: imgData,
left: position[0],
top: position[1],
width: w,
height: h
});
}
ctx.restore();
}
},
paintSolidColorImageMask:
function CanvasGraphics_paintSolidColorImageMask() {
this.ctx.fillRect(0, 0, 1, 1);
},
paintXObject: function CanvasGraphics_paintXObject() {
warn('Unsupported \'paintXObject\' command.');
},
// Marked content
markPoint: function CanvasGraphics_markPoint(tag) {
// TODO Marked content.
},
markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
// TODO Marked content.
},
beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
// TODO Marked content.
},
beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
tag, properties) {
// TODO Marked content.
},
endMarkedContent: function CanvasGraphics_endMarkedContent() {
// TODO Marked content.
},
// Compatibility
beginCompat: function CanvasGraphics_beginCompat() {
// TODO ignore undefined operators (should we do that anyway?)
},
endCompat: function CanvasGraphics_endCompat() {
// TODO stop ignoring undefined operators
},
// Helper functions
consumePath: function CanvasGraphics_consumePath() {
var ctx = this.ctx;
if (this.pendingClip) {
if (this.pendingClip === EO_CLIP) {
if (ctx.mozFillRule !== undefined) {
ctx.mozFillRule = 'evenodd';
ctx.clip();
ctx.mozFillRule = 'nonzero';
} else {
ctx.clip('evenodd');
}
} else {
ctx.clip();
}
this.pendingClip = null;
}
ctx.beginPath();
},
getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
if (this.cachedGetSinglePixelWidth === null) {
var inverse = this.ctx.mozCurrentTransformInverse;
// max of the current horizontal and vertical scale
this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
(inverse[0] * inverse[0] + inverse[1] * inverse[1]),
(inverse[2] * inverse[2] + inverse[3] * inverse[3])));
}
return this.cachedGetSinglePixelWidth;
},
getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
var transform = this.ctx.mozCurrentTransform;
return [
transform[0] * x + transform[2] * y + transform[4],
transform[1] * x + transform[3] * y + transform[5]
];
}
};
for (var op in OPS) {
CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
}
return CanvasGraphics;
})();
exports.CanvasGraphics = CanvasGraphics;
exports.createScratchCanvas = createScratchCanvas;
}));
(function (root, factory) {
{
factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil,
root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas,
root.pdfjsDisplayMetadata, root.pdfjsSharedGlobal);
}
}(this, function (exports, sharedUtil, displayFontLoader, displayCanvas,
displayMetadata, sharedGlobal, amdRequire) {
var InvalidPDFException = sharedUtil.InvalidPDFException;
var MessageHandler = sharedUtil.MessageHandler;
var MissingPDFException = sharedUtil.MissingPDFException;
var PasswordResponses = sharedUtil.PasswordResponses;
var PasswordException = sharedUtil.PasswordException;
var StatTimer = sharedUtil.StatTimer;
var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
var UnknownErrorException = sharedUtil.UnknownErrorException;
var Util = sharedUtil.Util;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var combineUrl = sharedUtil.combineUrl;
var error = sharedUtil.error;
var deprecated = sharedUtil.deprecated;
var info = sharedUtil.info;
var isArrayBuffer = sharedUtil.isArrayBuffer;
var loadJpegStream = sharedUtil.loadJpegStream;
var stringToBytes = sharedUtil.stringToBytes;
var warn = sharedUtil.warn;
var FontFaceObject = displayFontLoader.FontFaceObject;
var FontLoader = displayFontLoader.FontLoader;
var CanvasGraphics = displayCanvas.CanvasGraphics;
var createScratchCanvas = displayCanvas.createScratchCanvas;
var Metadata = displayMetadata.Metadata;
var PDFJS = sharedGlobal.PDFJS;
var globalScope = sharedGlobal.globalScope;
var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
var useRequireEnsure = false;
if (typeof module !== 'undefined' && module.require) {
// node.js - disable worker and set require.ensure.
PDFJS.disableWorker = true;
if (typeof require.ensure === 'undefined') {
require.ensure = require('node-ensure');
}
useRequireEnsure = true;
}
if (typeof __webpack_require__ !== 'undefined') {
// Webpack - get/bundle pdf.worker.js as additional file.
PDFJS.workerSrc = require('entry?name=[hash]-worker.js!./pdf.worker.js');
useRequireEnsure = true;
}
if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
PDFJS.workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
}
var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
require.ensure([], function () {
require('./pdf.worker.js');
callback();
});
}) : (typeof requirejs !== 'undefined') ? (function (callback) {
requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
callback();
});
}) : null;
/**
* The maximum allowed image size in total pixels e.g. width * height. Images
* above this value will not be drawn. Use -1 for no limit.
* @var {number}
*/
PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
-1 : PDFJS.maxImageSize);
/**
* The url of where the predefined Adobe CMaps are located. Include trailing
* slash.
* @var {string}
*/
PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
/**
* Specifies if CMaps are binary packed.
* @var {boolean}
*/
PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
/**
* By default fonts are converted to OpenType fonts and loaded via font face
* rules. If disabled, the font will be rendered using a built in font renderer
* that constructs the glyphs with primitive path commands.
* @var {boolean}
*/
PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
false : PDFJS.disableFontFace);
/**
* Path for image resources, mainly for annotation icons. Include trailing
* slash.
* @var {string}
*/
PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
'' : PDFJS.imageResourcesPath);
/**
* Disable the web worker and run all code on the main thread. This will happen
* automatically if the browser doesn't support workers or sending typed arrays
* to workers.
* @var {boolean}
*/
PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
false : PDFJS.disableWorker);
/**
* Path and filename of the worker file. Required when the worker is enabled in
* development mode. If unspecified in the production build, the worker will be
* loaded based on the location of the pdf.js file. It is recommended that
* the workerSrc is set in a custom application to prevent issues caused by
* third-party frameworks and libraries.
* @var {string}
*/
PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
/**
* Disable range request loading of PDF files. When enabled and if the server
* supports partial content requests then the PDF will be fetched in chunks.
* Enabled (false) by default.
* @var {boolean}
*/
PDFJS.disableRange = (PDFJS.disableRange === undefined ?
false : PDFJS.disableRange);
/**
* Disable streaming of PDF file data. By default PDF.js attempts to load PDF
* in chunks. This default behavior can be disabled.
* @var {boolean}
*/
PDFJS.disableStream = (PDFJS.disableStream === undefined ?
false : PDFJS.disableStream);
/**
* Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
* will automatically keep fetching more data even if it isn't needed to display
* the current page. This default behavior can be disabled.
*
* NOTE: It is also necessary to disable streaming, see above,
* in order for disabling of pre-fetching to work correctly.
* @var {boolean}
*/
PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
false : PDFJS.disableAutoFetch);
/**
* Enables special hooks for debugging PDF.js.
* @var {boolean}
*/
PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
/**
* Enables transfer usage in postMessage for ArrayBuffers.
* @var {boolean}
*/
PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
true : PDFJS.postMessageTransfers);
/**
* Disables URL.createObjectURL usage.
* @var {boolean}
*/
PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
false : PDFJS.disableCreateObjectURL);
/**
* Disables WebGL usage.
* @var {boolean}
*/
PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
true : PDFJS.disableWebGL);
/**
* Disables fullscreen support, and by extension Presentation Mode,
* in browsers which support the fullscreen API.
* @var {boolean}
*/
PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
false : PDFJS.disableFullscreen);
/**
* Enables CSS only zooming.
* @var {boolean}
*/
PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
false : PDFJS.useOnlyCssZoom);
/**
* Controls the logging level.
* The constants from PDFJS.VERBOSITY_LEVELS should be used:
* - errors
* - warnings [default]
* - infos
* @var {number}
*/
PDFJS.verbosity = (PDFJS.verbosity === undefined ?
PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
/**
* The maximum supported canvas size in total pixels e.g. width * height.
* The default value is 4096 * 4096. Use -1 for no limit.
* @var {number}
*/
PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
16777216 : PDFJS.maxCanvasPixels);
/**
* (Deprecated) Opens external links in a new window if enabled.
* The default behavior opens external links in the PDF.js window.
*
* NOTE: This property has been deprecated, please use
* `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
* @var {boolean}
*/
PDFJS.openExternalLinksInNewWindow = (
PDFJS.openExternalLinksInNewWindow === undefined ?
false : PDFJS.openExternalLinksInNewWindow);
/**
* Specifies the |target| attribute for external links.
* The constants from PDFJS.LinkTarget should be used:
* - NONE [default]
* - SELF
* - BLANK
* - PARENT
* - TOP
* @var {number}
*/
PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ?
PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget);
/**
* Specifies the |rel| attribute for external links. Defaults to stripping
* the referrer.
* @var {string}
*/
PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ?
'noreferrer' : PDFJS.externalLinkRel);
/**
* Determines if we can eval strings as JS. Primarily used to improve
* performance for font rendering.
* @var {boolean}
*/
PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ?
true : PDFJS.isEvalSupported);
/**
* Document initialization / loading parameters object.
*
* @typedef {Object} DocumentInitParameters
* @property {string} url - The URL of the PDF.
* @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
* (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
* use atob() to convert it to a binary string first.
* @property {Object} httpHeaders - Basic authentication headers.
* @property {boolean} withCredentials - Indicates whether or not cross-site
* Access-Control requests should be made using credentials such as cookies
* or authorization headers. The default is false.
* @property {string} password - For decrypting password-protected PDFs.
* @property {TypedArray} initialData - A typed array with the first portion or
* all of the pdf data. Used by the extension since some data is already
* loaded before the switch to range requests.
* @property {number} length - The PDF file length. It's used for progress
* reports and range requests operations.
* @property {PDFDataRangeTransport} range
* @property {number} rangeChunkSize - Optional parameter to specify
* maximum number of bytes fetched per range request. The default value is
* 2^16 = 65536.
* @property {PDFWorker} worker - The worker that will be used for the loading
* and parsing of the PDF data.
*/
/**
* @typedef {Object} PDFDocumentStats
* @property {Array} streamTypes - Used stream types in the document (an item
* is set to true if specific stream ID was used in the document).
* @property {Array} fontTypes - Used font type in the document (an item is set
* to true if specific font ID was used in the document).
*/
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
* Can be a url to where a PDF is located, a typed array (Uint8Array)
* already populated with data or parameter object.
*
* @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
* if you want to manually serve range requests for data in the PDF.
*
* @param {function} passwordCallback (deprecated) It is used to request a
* password if wrong or no password was provided. The callback receives two
* parameters: function that needs to be called with new password and reason
* (see {PasswordResponses}).
*
* @param {function} progressCallback (deprecated) It is used to be able to
* monitor the loading progress of the PDF file (necessary to implement e.g.
* a loading bar). The callback receives an {Object} with the properties:
* {number} loaded and {number} total.
*
* @return {PDFDocumentLoadingTask}
*/
PDFJS.getDocument = function getDocument(src,
pdfDataRangeTransport,
passwordCallback,
progressCallback) {
var task = new PDFDocumentLoadingTask();
// Support of the obsolete arguments (for compatibility with API v1.0)
if (arguments.length > 1) {
deprecated('getDocument is called with pdfDataRangeTransport, ' +
'passwordCallback or progressCallback argument');
}
if (pdfDataRangeTransport) {
if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
// Not a PDFDataRangeTransport instance, trying to add missing properties.
pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
pdfDataRangeTransport.length = src.length;
pdfDataRangeTransport.initialData = src.initialData;
if (!pdfDataRangeTransport.abort) {
pdfDataRangeTransport.abort = function () {};
}
}
src = Object.create(src);
src.range = pdfDataRangeTransport;
}
task.onPassword = passwordCallback || null;
task.onProgress = progressCallback || null;
var source;
if (typeof src === 'string') {
source = { url: src };
} else if (isArrayBuffer(src)) {
source = { data: src };
} else if (src instanceof PDFDataRangeTransport) {
source = { range: src };
} else {
if (typeof src !== 'object') {
error('Invalid parameter in getDocument, need either Uint8Array, ' +
'string or a parameter object');
}
if (!src.url && !src.data && !src.range) {
error('Invalid parameter object: need either .data, .range or .url');
}
source = src;
}
var params = {};
var rangeTransport = null;
var worker = null;
for (var key in source) {
if (key === 'url' && typeof window !== 'undefined') {
// The full path is required in the 'url' field.
params[key] = combineUrl(window.location.href, source[key]);
continue;
} else if (key === 'range') {
rangeTransport = source[key];
continue;
} else if (key === 'worker') {
worker = source[key];
continue;
} else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
// Converting string or array-like data to Uint8Array.
var pdfBytes = source[key];
if (typeof pdfBytes === 'string') {
params[key] = stringToBytes(pdfBytes);
} else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
!isNaN(pdfBytes.length)) {
params[key] = new Uint8Array(pdfBytes);
} else if (isArrayBuffer(pdfBytes)) {
params[key] = new Uint8Array(pdfBytes);
} else {
error('Invalid PDF binary data: either typed array, string or ' +
'array-like object is expected in the data property.');
}
continue;
}
params[key] = source[key];
}
params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
if (!worker) {
// Worker was not provided -- creating and owning our own.
worker = new PDFWorker();
task._worker = worker;
}
var docId = task.docId;
worker.promise.then(function () {
if (task.destroyed) {
throw new Error('Loading aborted');
}
return _fetchDocument(worker, params, rangeTransport, docId).then(
function (workerId) {
if (task.destroyed) {
throw new Error('Loading aborted');
}
var messageHandler = new MessageHandler(docId, workerId, worker.port);
messageHandler.send('Ready', null);
var transport = new WorkerTransport(messageHandler, task, rangeTransport);
task._transport = transport;
});
}).catch(task._capability.reject);
return task;
};
/**
* Starts fetching of specified PDF document/data.
* @param {PDFWorker} worker
* @param {Object} source
* @param {PDFDataRangeTransport} pdfDataRangeTransport
* @param {string} docId Unique document id, used as MessageHandler id.
* @returns {Promise} The promise, which is resolved when worker id of
* MessageHandler is known.
* @private
*/
function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
if (worker.destroyed) {
return Promise.reject(new Error('Worker was destroyed'));
}
source.disableAutoFetch = PDFJS.disableAutoFetch;
source.disableStream = PDFJS.disableStream;
source.chunkedViewerLoading = !!pdfDataRangeTransport;
if (pdfDataRangeTransport) {
source.length = pdfDataRangeTransport.length;
source.initialData = pdfDataRangeTransport.initialData;
}
return worker.messageHandler.sendWithPromise('GetDocRequest', {
docId: docId,
source: source,
disableRange: PDFJS.disableRange,
maxImageSize: PDFJS.maxImageSize,
cMapUrl: PDFJS.cMapUrl,
cMapPacked: PDFJS.cMapPacked,
disableFontFace: PDFJS.disableFontFace,
disableCreateObjectURL: PDFJS.disableCreateObjectURL,
verbosity: PDFJS.verbosity
}).then(function (workerId) {
if (worker.destroyed) {
throw new Error('Worker was destroyed');
}
return workerId;
});
}
/**
* PDF document loading operation.
* @class
* @alias PDFDocumentLoadingTask
*/
var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
var nextDocumentId = 0;
/** @constructs PDFDocumentLoadingTask */
function PDFDocumentLoadingTask() {
this._capability = createPromiseCapability();
this._transport = null;
this._worker = null;
/**
* Unique document loading task id -- used in MessageHandlers.
* @type {string}
*/
this.docId = 'd' + (nextDocumentId++);
/**
* Shows if loading task is destroyed.
* @type {boolean}
*/
this.destroyed = false;
/**
* Callback to request a password if wrong or no password was provided.
* The callback receives two parameters: function that needs to be called
* with new password and reason (see {PasswordResponses}).
*/
this.onPassword = null;
/**
* Callback to be able to monitor the loading progress of the PDF file
* (necessary to implement e.g. a loading bar). The callback receives
* an {Object} with the properties: {number} loaded and {number} total.
*/
this.onProgress = null;
/**
* Callback to when unsupported feature is used. The callback receives
* an {PDFJS.UNSUPPORTED_FEATURES} argument.
*/
this.onUnsupportedFeature = null;
}
PDFDocumentLoadingTask.prototype =
/** @lends PDFDocumentLoadingTask.prototype */ {
/**
* @return {Promise}
*/
get promise() {
return this._capability.promise;
},
/**
* Aborts all network requests and destroys worker.
* @return {Promise} A promise that is resolved after destruction activity
* is completed.
*/
destroy: function () {
this.destroyed = true;
var transportDestroyed = !this._transport ? Promise.resolve() :
this._transport.destroy();
return transportDestroyed.then(function () {
this._transport = null;
if (this._worker) {
this._worker.destroy();
this._worker = null;
}
}.bind(this));
},
/**
* Registers callbacks to indicate the document loading completion.
*
* @param {function} onFulfilled The callback for the loading completion.
* @param {function} onRejected The callback for the loading failure.
* @return {Promise} A promise that is resolved after the onFulfilled or
* onRejected callback.
*/
then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
return this.promise.then.apply(this.promise, arguments);
}
};
return PDFDocumentLoadingTask;
})();
/**
* Abstract class to support range requests file loading.
* @class
* @alias PDFJS.PDFDataRangeTransport
* @param {number} length
* @param {Uint8Array} initialData
*/
var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
function PDFDataRangeTransport(length, initialData) {
this.length = length;
this.initialData = initialData;
this._rangeListeners = [];
this._progressListeners = [];
this._progressiveReadListeners = [];
this._readyCapability = createPromiseCapability();
}
PDFDataRangeTransport.prototype =
/** @lends PDFDataRangeTransport.prototype */ {
addRangeListener:
function PDFDataRangeTransport_addRangeListener(listener) {
this._rangeListeners.push(listener);
},
addProgressListener:
function PDFDataRangeTransport_addProgressListener(listener) {
this._progressListeners.push(listener);
},
addProgressiveReadListener:
function PDFDataRangeTransport_addProgressiveReadListener(listener) {
this._progressiveReadListeners.push(listener);
},
onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
var listeners = this._rangeListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](begin, chunk);
}
},
onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
this._readyCapability.promise.then(function () {
var listeners = this._progressListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](loaded);
}
}.bind(this));
},
onDataProgressiveRead:
function PDFDataRangeTransport_onDataProgress(chunk) {
this._readyCapability.promise.then(function () {
var listeners = this._progressiveReadListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](chunk);
}
}.bind(this));
},
transportReady: function PDFDataRangeTransport_transportReady() {
this._readyCapability.resolve();
},
requestDataRange:
function PDFDataRangeTransport_requestDataRange(begin, end) {
throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
},
abort: function PDFDataRangeTransport_abort() {
}
};
return PDFDataRangeTransport;
})();
PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
/**
* Proxy to a PDFDocument in the worker thread. Also, contains commonly used
* properties that can be read synchronously.
* @class
* @alias PDFDocumentProxy
*/
var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
this.pdfInfo = pdfInfo;
this.transport = transport;
this.loadingTask = loadingTask;
}
PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
/**
* @return {number} Total number of pages the PDF contains.
*/
get numPages() {
return this.pdfInfo.numPages;
},
/**
* @return {string} A unique ID to identify a PDF. Not guaranteed to be
* unique.
*/
get fingerprint() {
return this.pdfInfo.fingerprint;
},
/**
* @param {number} pageNumber The page number to get. The first page is 1.
* @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
* object.
*/
getPage: function PDFDocumentProxy_getPage(pageNumber) {
return this.transport.getPage(pageNumber);
},
/**
* @param {{num: number, gen: number}} ref The page reference. Must have
* the 'num' and 'gen' properties.
* @return {Promise} A promise that is resolved with the page index that is
* associated with the reference.
*/
getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
return this.transport.getPageIndex(ref);
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named destinations to reference numbers.
*
* This can be slow for large documents: use getDestination instead
*/
getDestinations: function PDFDocumentProxy_getDestinations() {
return this.transport.getDestinations();
},
/**
* @param {string} id The named destination to get.
* @return {Promise} A promise that is resolved with all information
* of the given named destination.
*/
getDestination: function PDFDocumentProxy_getDestination(id) {
return this.transport.getDestination(id);
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named attachments to their content.
*/
getAttachments: function PDFDocumentProxy_getAttachments() {
return this.transport.getAttachments();
},
/**
* @return {Promise} A promise that is resolved with an array of all the
* JavaScript strings in the name tree.
*/
getJavaScript: function PDFDocumentProxy_getJavaScript() {
return this.transport.getJavaScript();
},
/**
* @return {Promise} A promise that is resolved with an {Array} that is a
* tree outline (if it has one) of the PDF. The tree is in the format of:
* [
* {
* title: string,
* bold: boolean,
* italic: boolean,
* color: rgb array,
* dest: dest obj,
* items: array of more items like this
* },
* ...
* ].
*/
getOutline: function PDFDocumentProxy_getOutline() {
return this.transport.getOutline();
},
/**
* @return {Promise} A promise that is resolved with an {Object} that has
* info and metadata properties. Info is an {Object} filled with anything
* available in the information dictionary and similarly metadata is a
* {Metadata} object with information from the metadata section of the PDF.
*/
getMetadata: function PDFDocumentProxy_getMetadata() {
return this.transport.getMetadata();
},
/**
* @return {Promise} A promise that is resolved with a TypedArray that has
* the raw data from the PDF.
*/
getData: function PDFDocumentProxy_getData() {
return this.transport.getData();
},
/**
* @return {Promise} A promise that is resolved when the document's data
* is loaded. It is resolved with an {Object} that contains the length
* property that indicates size of the PDF data in bytes.
*/
getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
return this.transport.downloadInfoCapability.promise;
},
/**
* @return {Promise} A promise this is resolved with current stats about
* document structures (see {@link PDFDocumentStats}).
*/
getStats: function PDFDocumentProxy_getStats() {
return this.transport.getStats();
},
/**
* Cleans up resources allocated by the document, e.g. created @font-face.
*/
cleanup: function PDFDocumentProxy_cleanup() {
this.transport.startCleanup();
},
/**
* Destroys current document instance and terminates worker.
*/
destroy: function PDFDocumentProxy_destroy() {
return this.loadingTask.destroy();
}
};
return PDFDocumentProxy;
})();
/**
* Page getTextContent parameters.
*
* @typedef {Object} getTextContentParameters
* @param {boolean} normalizeWhitespace - replaces all occurrences of
* whitespace with standard spaces (0x20). The default value is `false`.
*/
/**
* Page text content.
*
* @typedef {Object} TextContent
* @property {array} items - array of {@link TextItem}
* @property {Object} styles - {@link TextStyles} objects, indexed by font
* name.
*/
/**
* Page text content part.
*
* @typedef {Object} TextItem
* @property {string} str - text content.
* @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
* @property {array} transform - transformation matrix.
* @property {number} width - width in device space.
* @property {number} height - height in device space.
* @property {string} fontName - font name used by pdf.js for converted font.
*/
/**
* Text style.
*
* @typedef {Object} TextStyle
* @property {number} ascent - font ascent.
* @property {number} descent - font descent.
* @property {boolean} vertical - text is in vertical mode.
* @property {string} fontFamily - possible font family
*/
/**
* Page annotation parameters.
*
* @typedef {Object} GetAnnotationsParameters
* @param {string} intent - Determines the annotations that will be fetched,
* can be either 'display' (viewable annotations) or 'print'
* (printable annotations).
* If the parameter is omitted, all annotations are fetched.
*/
/**
* Page render parameters.
*
* @typedef {Object} RenderParameters
* @property {Object} canvasContext - A 2D context of a DOM Canvas object.
* @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
* calling of PDFPage.getViewport method.
* @property {string} intent - Rendering intent, can be 'display' or 'print'
* (default value is 'display').
* @property {Array} transform - (optional) Additional transform, applied
* just before viewport transform.
* @property {Object} imageLayer - (optional) An object that has beginLayout,
* endLayout and appendImage functions.
* @property {function} continueCallback - (deprecated) A function that will be
* called each time the rendering is paused. To continue
* rendering call the function that is the first argument
* to the callback.
*/
/**
* PDF page operator list.
*
* @typedef {Object} PDFOperatorList
* @property {Array} fnArray - Array containing the operator functions.
* @property {Array} argsArray - Array containing the arguments of the
* functions.
*/
/**
* Proxy to a PDFPage in the worker thread.
* @class
* @alias PDFPageProxy
*/
var PDFPageProxy = (function PDFPageProxyClosure() {
function PDFPageProxy(pageIndex, pageInfo, transport) {
this.pageIndex = pageIndex;
this.pageInfo = pageInfo;
this.transport = transport;
this.stats = new StatTimer();
this.stats.enabled = !!globalScope.PDFJS.enableStats;
this.commonObjs = transport.commonObjs;
this.objs = new PDFObjects();
this.cleanupAfterRender = false;
this.pendingCleanup = false;
this.intentStates = {};
this.destroyed = false;
}
PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
/**
* @return {number} Page number of the page. First page is 1.
*/
get pageNumber() {
return this.pageIndex + 1;
},
/**
* @return {number} The number of degrees the page is rotated clockwise.
*/
get rotate() {
return this.pageInfo.rotate;
},
/**
* @return {Object} The reference that points to this page. It has 'num' and
* 'gen' properties.
*/
get ref() {
return this.pageInfo.ref;
},
/**
* @return {Array} An array of the visible portion of the PDF page in the
* user space units - [x1, y1, x2, y2].
*/
get view() {
return this.pageInfo.view;
},
/**
* @param {number} scale The desired scale of the viewport.
* @param {number} rotate Degrees to rotate the viewport. If omitted this
* defaults to the page rotation.
* @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
* along with transforms required for rendering.
*/
getViewport: function PDFPageProxy_getViewport(scale, rotate) {
if (arguments.length < 2) {
rotate = this.rotate;
}
return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
},
/**
* @param {GetAnnotationsParameters} params - Annotation parameters.
* @return {Promise} A promise that is resolved with an {Array} of the
* annotation objects.
*/
getAnnotations: function PDFPageProxy_getAnnotations(params) {
var intent = (params && params.intent) || null;
if (!this.annotationsPromise || this.annotationsIntent !== intent) {
this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
intent);
this.annotationsIntent = intent;
}
return this.annotationsPromise;
},
/**
* Begins the process of rendering a page to the desired context.
* @param {RenderParameters} params Page render parameters.
* @return {RenderTask} An object that contains the promise, which
* is resolved when the page finishes rendering.
*/
render: function PDFPageProxy_render(params) {
var stats = this.stats;
stats.time('Overall');
// If there was a pending destroy cancel it so no cleanup happens during
// this call to render.
this.pendingCleanup = false;
var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = {};
}
var intentState = this.intentStates[renderingIntent];
// If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.receivingOperatorList = true;
intentState.displayReadyCapability = createPromiseCapability();
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
this.stats.time('Page Request');
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageNumber - 1,
intent: renderingIntent
});
}
var internalRenderTask = new InternalRenderTask(complete, params,
this.objs,
this.commonObjs,
intentState.operatorList,
this.pageNumber);
internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
if (!intentState.renderTasks) {
intentState.renderTasks = [];
}
intentState.renderTasks.push(internalRenderTask);
var renderTask = internalRenderTask.task;
// Obsolete parameter support
if (params.continueCallback) {
deprecated('render is used with continueCallback parameter');
renderTask.onContinue = params.continueCallback;
}
var self = this;
intentState.displayReadyCapability.promise.then(
function pageDisplayReadyPromise(transparency) {
if (self.pendingCleanup) {
complete();
return;
}
stats.time('Rendering');
internalRenderTask.initalizeGraphics(transparency);
internalRenderTask.operatorListChanged();
},
function pageDisplayReadPromiseError(reason) {
complete(reason);
}
);
function complete(error) {
var i = intentState.renderTasks.indexOf(internalRenderTask);
if (i >= 0) {
intentState.renderTasks.splice(i, 1);
}
if (self.cleanupAfterRender) {
self.pendingCleanup = true;
}
self._tryCleanup();
if (error) {
internalRenderTask.capability.reject(error);
} else {
internalRenderTask.capability.resolve();
}
stats.timeEnd('Rendering');
stats.timeEnd('Overall');
}
return renderTask;
},
/**
* @return {Promise} A promise resolved with an {@link PDFOperatorList}
* object that represents page's operator list.
*/
getOperatorList: function PDFPageProxy_getOperatorList() {
function operatorListChanged() {
if (intentState.operatorList.lastChunk) {
intentState.opListReadCapability.resolve(intentState.operatorList);
}
}
var renderingIntent = 'oplist';
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = {};
}
var intentState = this.intentStates[renderingIntent];
if (!intentState.opListReadCapability) {
var opListTask = {};
opListTask.operatorListChanged = operatorListChanged;
intentState.receivingOperatorList = true;
intentState.opListReadCapability = createPromiseCapability();
intentState.renderTasks = [];
intentState.renderTasks.push(opListTask);
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false
};
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageIndex,
intent: renderingIntent
});
}
return intentState.opListReadCapability.promise;
},
/**
* @param {getTextContentParameters} params - getTextContent parameters.
* @return {Promise} That is resolved a {@link TextContent}
* object that represent the page text content.
*/
getTextContent: function PDFPageProxy_getTextContent(params) {
var normalizeWhitespace = (params && params.normalizeWhitespace) || false;
return this.transport.messageHandler.sendWithPromise('GetTextContent', {
pageIndex: this.pageNumber - 1,
normalizeWhitespace: normalizeWhitespace,
});
},
/**
* Destroys page object.
*/
_destroy: function PDFPageProxy_destroy() {
this.destroyed = true;
this.transport.pageCache[this.pageIndex] = null;
var waitOn = [];
Object.keys(this.intentStates).forEach(function(intent) {
var intentState = this.intentStates[intent];
intentState.renderTasks.forEach(function(renderTask) {
var renderCompleted = renderTask.capability.promise.
catch(function () {}); // ignoring failures
waitOn.push(renderCompleted);
renderTask.cancel();
});
}, this);
this.objs.clear();
this.annotationsPromise = null;
this.pendingCleanup = false;
return Promise.all(waitOn);
},
/**
* Cleans up resources allocated by the page. (deprecated)
*/
destroy: function() {
deprecated('page destroy method, use cleanup() instead');
this.cleanup();
},
/**
* Cleans up resources allocated by the page.
*/
cleanup: function PDFPageProxy_cleanup() {
this.pendingCleanup = true;
this._tryCleanup();
},
/**
* For internal use only. Attempts to clean up if rendering is in a state
* where that's possible.
* @ignore
*/
_tryCleanup: function PDFPageProxy_tryCleanup() {
if (!this.pendingCleanup ||
Object.keys(this.intentStates).some(function(intent) {
var intentState = this.intentStates[intent];
return (intentState.renderTasks.length !== 0 ||
intentState.receivingOperatorList);
}, this)) {
return;
}
Object.keys(this.intentStates).forEach(function(intent) {
delete this.intentStates[intent];
}, this);
this.objs.clear();
this.annotationsPromise = null;
this.pendingCleanup = false;
},
/**
* For internal use only.
* @ignore
*/
_startRenderPage: function PDFPageProxy_startRenderPage(transparency,
intent) {
var intentState = this.intentStates[intent];
// TODO Refactor RenderPageRequest to separate rendering
// and operator list logic
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.resolve(transparency);
}
},
/**
* For internal use only.
* @ignore
*/
_renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
intent) {
var intentState = this.intentStates[intent];
var i, ii;
// Add the new chunk to the current operator list.
for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
intentState.operatorList.argsArray.push(
operatorListChunk.argsArray[i]);
}
intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
// Notify all the rendering tasks there are more operators to be consumed.
for (i = 0; i < intentState.renderTasks.length; i++) {
intentState.renderTasks[i].operatorListChanged();
}
if (operatorListChunk.lastChunk) {
intentState.receivingOperatorList = false;
this._tryCleanup();
}
}
};
return PDFPageProxy;
})();
/**
* PDF.js web worker abstraction, it controls instantiation of PDF documents and
* WorkerTransport for them. If creation of a web worker is not possible,
* a "fake" worker will be used instead.
* @class
*/
var PDFWorker = (function PDFWorkerClosure() {
var nextFakeWorkerId = 0;
function getWorkerSrc() {
if (PDFJS.workerSrc) {
return PDFJS.workerSrc;
}
if (pdfjsFilePath) {
return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
}
error('No PDFJS.workerSrc specified');
}
// Loads worker code into main thread.
function setupFakeWorkerGlobal() {
if (!PDFJS.fakeWorkerFilesLoadedCapability) {
PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
// In the developer build load worker_loader which in turn loads all the
// other files and resolves the promise. In production only the
// pdf.worker.js file is needed.
var loader = fakeWorkerFilesLoader || function (callback) {
Util.loadScript(getWorkerSrc(), callback);
};
loader(function () {
PDFJS.fakeWorkerFilesLoadedCapability.resolve();
});
}
return PDFJS.fakeWorkerFilesLoadedCapability.promise;
}
function PDFWorker(name) {
this.name = name;
this.destroyed = false;
this._readyCapability = createPromiseCapability();
this._port = null;
this._webWorker = null;
this._messageHandler = null;
this._initialize();
}
PDFWorker.prototype = /** @lends PDFWorker.prototype */ {
get promise() {
return this._readyCapability.promise;
},
get port() {
return this._port;
},
get messageHandler() {
return this._messageHandler;
},
_initialize: function PDFWorker_initialize() {
// If worker support isn't disabled explicit and the browser has worker
// support, create a new web worker and test if it/the browser fullfills
// all requirements to run parts of pdf.js in a web worker.
// Right now, the requirement is, that an Uint8Array is still an
// Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
var workerSrc = getWorkerSrc();
try {
// Some versions of FF can't create a worker on localhost, see:
// https://bugzilla.mozilla.org/show_bug.cgi?id=683280
var worker = new Worker(workerSrc);
var messageHandler = new MessageHandler('main', 'worker', worker);
messageHandler.on('test', function PDFWorker_test(data) {
if (this.destroyed) {
this._readyCapability.reject(new Error('Worker was destroyed'));
messageHandler.destroy();
worker.terminate();
return; // worker was destroyed
}
var supportTypedArray = data && data.supportTypedArray;
if (supportTypedArray) {
this._messageHandler = messageHandler;
this._port = worker;
this._webWorker = worker;
if (!data.supportTransfers) {
PDFJS.postMessageTransfers = false;
}
this._readyCapability.resolve();
} else {
this._setupFakeWorker();
messageHandler.destroy();
worker.terminate();
}
}.bind(this));
messageHandler.on('console_log', function (data) {
console.log.apply(console, data);
});
messageHandler.on('console_error', function (data) {
console.error.apply(console, data);
});
messageHandler.on('ready', function (data) {
if (this.destroyed) {
this._readyCapability.reject(new Error('Worker was destroyed'));
messageHandler.destroy();
worker.terminate();
return; // worker was destroyed
}
try {
sendTest();
} catch (e) {
// We need fallback to a faked worker.
this._setupFakeWorker();
}
}.bind(this));
var sendTest = function () {
var testObj = new Uint8Array(
[PDFJS.postMessageTransfers ? 255 : 0]);
// Some versions of Opera throw a DATA_CLONE_ERR on serializing the
// typed array. Also, checking if we can use transfers.
try {
messageHandler.send('test', testObj, [testObj.buffer]);
} catch (ex) {
info('Cannot use postMessage transfers');
testObj[0] = 0;
messageHandler.send('test', testObj);
}
};
// It might take time for worker to initialize (especially when AMD
// loader is used). We will try to send test immediately, and then
// when 'ready' message will arrive. The worker shall process only
// first received 'test'.
sendTest();
return;
} catch (e) {
info('The worker has been disabled.');
}
}
// Either workers are disabled, not supported or have thrown an exception.
// Thus, we fallback to a faked worker.
this._setupFakeWorker();
},
_setupFakeWorker: function PDFWorker_setupFakeWorker() {
if (!globalScope.PDFJS.disableWorker) {
warn('Setting up fake worker.');
globalScope.PDFJS.disableWorker = true;
}
setupFakeWorkerGlobal().then(function () {
if (this.destroyed) {
this._readyCapability.reject(new Error('Worker was destroyed'));
return;
}
// If we don't use a worker, just post/sendMessage to the main thread.
var port = {
_listeners: [],
postMessage: function (obj) {
var e = {data: obj};
this._listeners.forEach(function (listener) {
listener.call(this, e);
}, this);
},
addEventListener: function (name, listener) {
this._listeners.push(listener);
},
removeEventListener: function (name, listener) {
var i = this._listeners.indexOf(listener);
this._listeners.splice(i, 1);
},
terminate: function () {}
};
this._port = port;
// All fake workers use the same port, making id unique.
var id = 'fake' + (nextFakeWorkerId++);
// If the main thread is our worker, setup the handling for the
// messages -- the main thread sends to it self.
var workerHandler = new MessageHandler(id + '_worker', id, port);
PDFJS.WorkerMessageHandler.setup(workerHandler, port);
var messageHandler = new MessageHandler(id, id + '_worker', port);
this._messageHandler = messageHandler;
this._readyCapability.resolve();
}.bind(this));
},
/**
* Destroys the worker instance.
*/
destroy: function PDFWorker_destroy() {
this.destroyed = true;
if (this._webWorker) {
// We need to terminate only web worker created resource.
this._webWorker.terminate();
this._webWorker = null;
}
this._port = null;
if (this._messageHandler) {
this._messageHandler.destroy();
this._messageHandler = null;
}
}
};
return PDFWorker;
})();
PDFJS.PDFWorker = PDFWorker;
/**
* For internal use only.
* @ignore
*/
var WorkerTransport = (function WorkerTransportClosure() {
function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
this.messageHandler = messageHandler;
this.loadingTask = loadingTask;
this.pdfDataRangeTransport = pdfDataRangeTransport;
this.commonObjs = new PDFObjects();
this.fontLoader = new FontLoader(loadingTask.docId);
this.destroyed = false;
this.destroyCapability = null;
this.pageCache = [];
this.pagePromises = [];
this.downloadInfoCapability = createPromiseCapability();
this.setupMessageHandler();
}
WorkerTransport.prototype = {
destroy: function WorkerTransport_destroy() {
if (this.destroyCapability) {
return this.destroyCapability.promise;
}
this.destroyed = true;
this.destroyCapability = createPromiseCapability();
var waitOn = [];
// We need to wait for all renderings to be completed, e.g.
// timeout/rAF can take a long time.
this.pageCache.forEach(function (page) {
if (page) {
waitOn.push(page._destroy());
}
});
this.pageCache = [];
this.pagePromises = [];
var self = this;
// We also need to wait for the worker to finish its long running tasks.
var terminated = this.messageHandler.sendWithPromise('Terminate', null);
waitOn.push(terminated);
Promise.all(waitOn).then(function () {
self.fontLoader.clear();
if (self.pdfDataRangeTransport) {
self.pdfDataRangeTransport.abort();
self.pdfDataRangeTransport = null;
}
if (self.messageHandler) {
self.messageHandler.destroy();
self.messageHandler = null;
}
self.destroyCapability.resolve();
}, this.destroyCapability.reject);
return this.destroyCapability.promise;
},
setupMessageHandler:
function WorkerTransport_setupMessageHandler() {
var messageHandler = this.messageHandler;
function updatePassword(password) {
messageHandler.send('UpdatePassword', password);
}
var pdfDataRangeTransport = this.pdfDataRangeTransport;
if (pdfDataRangeTransport) {
pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
messageHandler.send('OnDataRange', {
begin: begin,
chunk: chunk
});
});
pdfDataRangeTransport.addProgressListener(function(loaded) {
messageHandler.send('OnDataProgress', {
loaded: loaded
});
});
pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
messageHandler.send('OnDataRange', {
chunk: chunk
});
});
messageHandler.on('RequestDataRange',
function transportDataRange(data) {
pdfDataRangeTransport.requestDataRange(data.begin, data.end);
}, this);
}
messageHandler.on('GetDoc', function transportDoc(data) {
var pdfInfo = data.pdfInfo;
this.numPages = data.pdfInfo.numPages;
var loadingTask = this.loadingTask;
var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
this.pdfDocument = pdfDocument;
loadingTask._capability.resolve(pdfDocument);
}, this);
messageHandler.on('NeedPassword',
function transportNeedPassword(exception) {
var loadingTask = this.loadingTask;
if (loadingTask.onPassword) {
return loadingTask.onPassword(updatePassword,
PasswordResponses.NEED_PASSWORD);
}
loadingTask._capability.reject(
new PasswordException(exception.message, exception.code));
}, this);
messageHandler.on('IncorrectPassword',
function transportIncorrectPassword(exception) {
var loadingTask = this.loadingTask;
if (loadingTask.onPassword) {
return loadingTask.onPassword(updatePassword,
PasswordResponses.INCORRECT_PASSWORD);
}
loadingTask._capability.reject(
new PasswordException(exception.message, exception.code));
}, this);
messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
this.loadingTask._capability.reject(
new InvalidPDFException(exception.message));
}, this);
messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
this.loadingTask._capability.reject(
new MissingPDFException(exception.message));
}, this);
messageHandler.on('UnexpectedResponse',
function transportUnexpectedResponse(exception) {
this.loadingTask._capability.reject(
new UnexpectedResponseException(exception.message, exception.status));
}, this);
messageHandler.on('UnknownError',
function transportUnknownError(exception) {
this.loadingTask._capability.reject(
new UnknownErrorException(exception.message, exception.details));
}, this);
messageHandler.on('DataLoaded', function transportPage(data) {
this.downloadInfoCapability.resolve(data);
}, this);
messageHandler.on('PDFManagerReady', function transportPage(data) {
if (this.pdfDataRangeTransport) {
this.pdfDataRangeTransport.transportReady();
}
}, this);
messageHandler.on('StartRenderPage', function transportRender(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var page = this.pageCache[data.pageIndex];
page.stats.timeEnd('Page Request');
page._startRenderPage(data.transparency, data.intent);
}, this);
messageHandler.on('RenderPageChunk', function transportRender(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var page = this.pageCache[data.pageIndex];
page._renderPageChunk(data.operatorList, data.intent);
}, this);
messageHandler.on('commonobj', function transportObj(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var id = data[0];
var type = data[1];
if (this.commonObjs.hasData(id)) {
return;
}
switch (type) {
case 'Font':
var exportedData = data[2];
var font;
if ('error' in exportedData) {
var error = exportedData.error;
warn('Error during font loading: ' + error);
this.commonObjs.resolve(id, error);
break;
} else {
font = new FontFaceObject(exportedData);
}
this.fontLoader.bind(
[font],
function fontReady(fontObjs) {
this.commonObjs.resolve(id, font);
}.bind(this)
);
break;
case 'FontPath':
this.commonObjs.resolve(id, data[2]);
break;
default:
error('Got unknown common object type ' + type);
}
}, this);
messageHandler.on('obj', function transportObj(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var id = data[0];
var pageIndex = data[1];
var type = data[2];
var pageProxy = this.pageCache[pageIndex];
var imageData;
if (pageProxy.objs.hasData(id)) {
return;
}
switch (type) {
case 'JpegStream':
imageData = data[3];
loadJpegStream(id, imageData, pageProxy.objs);
break;
case 'Image':
imageData = data[3];
pageProxy.objs.resolve(id, imageData);
// heuristics that will allow not to store large data
var MAX_IMAGE_SIZE_TO_STORE = 8000000;
if (imageData && 'data' in imageData &&
imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
pageProxy.cleanupAfterRender = true;
}
break;
default:
error('Got unknown object type ' + type);
}
}, this);
messageHandler.on('DocProgress', function transportDocProgress(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var loadingTask = this.loadingTask;
if (loadingTask.onProgress) {
loadingTask.onProgress({
loaded: data.loaded,
total: data.total
});
}
}, this);
messageHandler.on('PageError', function transportError(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var page = this.pageCache[data.pageNum - 1];
var intentState = page.intentStates[data.intent];
if (intentState.displayReadyCapability) {
intentState.displayReadyCapability.reject(data.error);
} else {
error(data.error);
}
}, this);
messageHandler.on('UnsupportedFeature',
function transportUnsupportedFeature(data) {
if (this.destroyed) {
return; // Ignore any pending requests if the worker was terminated.
}
var featureId = data.featureId;
var loadingTask = this.loadingTask;
if (loadingTask.onUnsupportedFeature) {
loadingTask.onUnsupportedFeature(featureId);
}
PDFJS.UnsupportedManager.notify(featureId);
}, this);
messageHandler.on('JpegDecode', function(data) {
if (this.destroyed) {
return Promise.reject('Worker was terminated');
}
var imageUrl = data[0];
var components = data[1];
if (components !== 3 && components !== 1) {
return Promise.reject(
new Error('Only 3 components or 1 component can be returned'));
}
return new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () {
var width = img.width;
var height = img.height;
var size = width * height;
var rgbaLength = size * 4;
var buf = new Uint8Array(size * components);
var tmpCanvas = createScratchCanvas(width, height);
var tmpCtx = tmpCanvas.getContext('2d');
tmpCtx.drawImage(img, 0, 0);
var data = tmpCtx.getImageData(0, 0, width, height).data;
var i, j;
if (components === 3) {
for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
buf[j] = data[i];
buf[j + 1] = data[i + 1];
buf[j + 2] = data[i + 2];
}
} else if (components === 1) {
for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
buf[j] = data[i];
}
}
resolve({ data: buf, width: width, height: height});
};
img.onerror = function () {
reject(new Error('JpegDecode failed to load image'));
};
img.src = imageUrl;
});
}, this);
},
getData: function WorkerTransport_getData() {
return this.messageHandler.sendWithPromise('GetData', null);
},
getPage: function WorkerTransport_getPage(pageNumber, capability) {
if (pageNumber <= 0 || pageNumber > this.numPages ||
(pageNumber|0) !== pageNumber) {
return Promise.reject(new Error('Invalid page request'));
}
var pageIndex = pageNumber - 1;
if (pageIndex in this.pagePromises) {
return this.pagePromises[pageIndex];
}
var promise = this.messageHandler.sendWithPromise('GetPage', {
pageIndex: pageIndex
}).then(function (pageInfo) {
if (this.destroyed) {
throw new Error('Transport destroyed');
}
var page = new PDFPageProxy(pageIndex, pageInfo, this);
this.pageCache[pageIndex] = page;
return page;
}.bind(this));
this.pagePromises[pageIndex] = promise;
return promise;
},
getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
},
getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
return this.messageHandler.sendWithPromise('GetAnnotations', {
pageIndex: pageIndex,
intent: intent,
});
},
getDestinations: function WorkerTransport_getDestinations() {
return this.messageHandler.sendWithPromise('GetDestinations', null);
},
getDestination: function WorkerTransport_getDestination(id) {
return this.messageHandler.sendWithPromise('GetDestination', { id: id });
},
getAttachments: function WorkerTransport_getAttachments() {
return this.messageHandler.sendWithPromise('GetAttachments', null);
},
getJavaScript: function WorkerTransport_getJavaScript() {
return this.messageHandler.sendWithPromise('GetJavaScript', null);
},
getOutline: function WorkerTransport_getOutline() {
return this.messageHandler.sendWithPromise('GetOutline', null);
},
getMetadata: function WorkerTransport_getMetadata() {
return this.messageHandler.sendWithPromise('GetMetadata', null).
then(function transportMetadata(results) {
return {
info: results[0],
metadata: (results[1] ? new Metadata(results[1]) : null)
};
});
},
getStats: function WorkerTransport_getStats() {
return this.messageHandler.sendWithPromise('GetStats', null);
},
startCleanup: function WorkerTransport_startCleanup() {
this.messageHandler.sendWithPromise('Cleanup', null).
then(function endCleanup() {
for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
var page = this.pageCache[i];
if (page) {
page.cleanup();
}
}
this.commonObjs.clear();
this.fontLoader.clear();
}.bind(this));
}
};
return WorkerTransport;
})();
/**
* A PDF document and page is built of many objects. E.g. there are objects
* for fonts, images, rendering code and such. These objects might get processed
* inside of a worker. The `PDFObjects` implements some basic functions to
* manage these objects.
* @ignore
*/
var PDFObjects = (function PDFObjectsClosure() {
function PDFObjects() {
this.objs = {};
}
PDFObjects.prototype = {
/**
* Internal function.
* Ensures there is an object defined for `objId`.
*/
ensureObj: function PDFObjects_ensureObj(objId) {
if (this.objs[objId]) {
return this.objs[objId];
}
var obj = {
capability: createPromiseCapability(),
data: null,
resolved: false
};
this.objs[objId] = obj;
return obj;
},
/**
* If called *without* callback, this returns the data of `objId` but the
* object needs to be resolved. If it isn't, this function throws.
*
* If called *with* a callback, the callback is called with the data of the
* object once the object is resolved. That means, if you call this
* function and the object is already resolved, the callback gets called
* right away.
*/
get: function PDFObjects_get(objId, callback) {
// If there is a callback, then the get can be async and the object is
// not required to be resolved right now
if (callback) {
this.ensureObj(objId).capability.promise.then(callback);
return null;
}
// If there isn't a callback, the user expects to get the resolved data
// directly.
var obj = this.objs[objId];
// If there isn't an object yet or the object isn't resolved, then the
// data isn't ready yet!
if (!obj || !obj.resolved) {
error('Requesting object that isn\'t resolved yet ' + objId);
}
return obj.data;
},
/**
* Resolves the object `objId` with optional `data`.
*/
resolve: function PDFObjects_resolve(objId, data) {
var obj = this.ensureObj(objId);
obj.resolved = true;
obj.data = data;
obj.capability.resolve(data);
},
isResolved: function PDFObjects_isResolved(objId) {
var objs = this.objs;
if (!objs[objId]) {
return false;
} else {
return objs[objId].resolved;
}
},
hasData: function PDFObjects_hasData(objId) {
return this.isResolved(objId);
},
/**
* Returns the data of `objId` if object exists, null otherwise.
*/
getData: function PDFObjects_getData(objId) {
var objs = this.objs;
if (!objs[objId] || !objs[objId].resolved) {
return null;
} else {
return objs[objId].data;
}
},
clear: function PDFObjects_clear() {
this.objs = {};
}
};
return PDFObjects;
})();
/**
* Allows controlling of the rendering tasks.
* @class
* @alias RenderTask
*/
var RenderTask = (function RenderTaskClosure() {
function RenderTask(internalRenderTask) {
this._internalRenderTask = internalRenderTask;
/**
* Callback for incremental rendering -- a function that will be called
* each time the rendering is paused. To continue rendering call the
* function that is the first argument to the callback.
* @type {function}
*/
this.onContinue = null;
}
RenderTask.prototype = /** @lends RenderTask.prototype */ {
/**
* Promise for rendering task completion.
* @return {Promise}
*/
get promise() {
return this._internalRenderTask.capability.promise;
},
/**
* Cancels the rendering task. If the task is currently rendering it will
* not be cancelled until graphics pauses with a timeout. The promise that
* this object extends will resolved when cancelled.
*/
cancel: function RenderTask_cancel() {
this._internalRenderTask.cancel();
},
/**
* Registers callbacks to indicate the rendering task completion.
*
* @param {function} onFulfilled The callback for the rendering completion.
* @param {function} onRejected The callback for the rendering failure.
* @return {Promise} A promise that is resolved after the onFulfilled or
* onRejected callback.
*/
then: function RenderTask_then(onFulfilled, onRejected) {
return this.promise.then.apply(this.promise, arguments);
}
};
return RenderTask;
})();
/**
* For internal use only.
* @ignore
*/
var InternalRenderTask = (function InternalRenderTaskClosure() {
function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
pageNumber) {
this.callback = callback;
this.params = params;
this.objs = objs;
this.commonObjs = commonObjs;
this.operatorListIdx = null;
this.operatorList = operatorList;
this.pageNumber = pageNumber;
this.running = false;
this.graphicsReadyCallback = null;
this.graphicsReady = false;
this.useRequestAnimationFrame = false;
this.cancelled = false;
this.capability = createPromiseCapability();
this.task = new RenderTask(this);
// caching this-bound methods
this._continueBound = this._continue.bind(this);
this._scheduleNextBound = this._scheduleNext.bind(this);
this._nextBound = this._next.bind(this);
}
InternalRenderTask.prototype = {
initalizeGraphics:
function InternalRenderTask_initalizeGraphics(transparency) {
if (this.cancelled) {
return;
}
if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
globalScope.StepperManager.enabled) {
this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
this.stepper.init(this.operatorList);
this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
}
var params = this.params;
this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
this.objs, params.imageLayer);
this.gfx.beginDrawing(params.transform, params.viewport, transparency);
this.operatorListIdx = 0;
this.graphicsReady = true;
if (this.graphicsReadyCallback) {
this.graphicsReadyCallback();
}
},
cancel: function InternalRenderTask_cancel() {
this.running = false;
this.cancelled = true;
this.callback('cancelled');
},
operatorListChanged: function InternalRenderTask_operatorListChanged() {
if (!this.graphicsReady) {
if (!this.graphicsReadyCallback) {
this.graphicsReadyCallback = this._continueBound;
}
return;
}
if (this.stepper) {
this.stepper.updateOperatorList(this.operatorList);
}
if (this.running) {
return;
}
this._continue();
},
_continue: function InternalRenderTask__continue() {
this.running = true;
if (this.cancelled) {
return;
}
if (this.task.onContinue) {
this.task.onContinue.call(this.task, this._scheduleNextBound);
} else {
this._scheduleNext();
}
},
_scheduleNext: function InternalRenderTask__scheduleNext() {
if (this.useRequestAnimationFrame) {
window.requestAnimationFrame(this._nextBound);
} else {
Promise.resolve(undefined).then(this._nextBound);
}
},
_next: function InternalRenderTask__next() {
if (this.cancelled) {
return;
}
this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
this.operatorListIdx,
this._continueBound,
this.stepper);
if (this.operatorListIdx === this.operatorList.argsArray.length) {
this.running = false;
if (this.operatorList.lastChunk) {
this.gfx.endDrawing();
this.callback();
}
}
}
};
return InternalRenderTask;
})();
/**
* (Deprecated) Global observer of unsupported feature usages. Use
* onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
*/
PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() {
var listeners = [];
return {
listen: function (cb) {
deprecated('Global UnsupportedManager.listen is used: ' +
' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
listeners.push(cb);
},
notify: function (featureId) {
for (var i = 0, ii = listeners.length; i < ii; i++) {
listeners[i](featureId);
}
}
};
})();
exports.getDocument = PDFJS.getDocument;
exports.PDFDataRangeTransport = PDFDataRangeTransport;
exports.PDFDocumentProxy = PDFDocumentProxy;
exports.PDFPageProxy = PDFPageProxy;
}));
}).call(pdfjsLibs);
exports.PDFJS = pdfjsLibs.pdfjsSharedGlobal.PDFJS;
exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
exports.PDFDataRangeTransport =
pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
exports.AnnotationLayer =
pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
exports.UnexpectedResponseException =
pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
}));
| mit |
ninjablocks/ninja-sentinel | yeoman/components/moment/CONTRIBUTING.md | 1722 | Submitting Issues
=================
If you are submitting a bug with moment, please create a [jsfiddle](http://jsfiddle.net/) demonstrating the issue.
Contributing
============
To contribute, fork the library and install these npm packages.
npm install jshint uglify-js nodeunit
You can add tests to the files in `/test/moment` or add a new test file if you are adding a new feature.
To run the tests, do `make test` to run all tests, `make test-moment` to test the core library, and `make test-lang` to test all the languages.
To check the filesize, you can use `make size`.
To minify all the files, use `make moment` to minify moment, `make langs` to minify all the lang files, or just `make` to minfy everything.
If your code passes the unit tests (including the ones you wrote), submit a pull request.
Submitting pull requests
========================
Moment.js now uses [git-flow](https://github.com/nvie/gitflow). If you're not familiar with git-flow, please read up on it, you'll be glad you did.
When submitting new features, please create a new feature branch using `git flow feature start <name>` and submit the pull request to the `develop` branch.
Pull requests for enhancements for features should be submitted to the `develop` branch as well.
When submitting a bugfix, please check if there is an existing bugfix branch. If the latest stable version is `1.5.0`, the bugfix branch would be `hotfix/1.5.1`. All pull requests for bug fixes should be on a `hotfix` branch, unless the bug fix depends on a new feature.
The `master` branch should always have the latest stable version. When bugfix or minor releases are needed, the develop/hotfix branch will be merged into master and released.
| mit |
solashirai/edx-platform | common/djangoapps/third_party_auth/tests/specs/test_lti.py | 7079 | """
Integration tests for third_party_auth LTI auth providers
"""
import unittest
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from oauthlib.oauth1.rfc5849 import Client, SIGNATURE_TYPE_BODY
from third_party_auth.tests import testutil
FORM_ENCODED = 'application/x-www-form-urlencoded'
LTI_CONSUMER_KEY = 'consumer'
LTI_CONSUMER_SECRET = 'secret'
LTI_TPA_LOGIN_URL = 'http://testserver/auth/login/lti/'
LTI_TPA_COMPLETE_URL = 'http://testserver/auth/complete/lti/'
OTHER_LTI_CONSUMER_KEY = 'settings-consumer'
OTHER_LTI_CONSUMER_SECRET = 'secret2'
LTI_USER_ID = 'lti_user_id'
EDX_USER_ID = 'test_user'
EMAIL = '[email protected]'
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
class IntegrationTestLTI(testutil.TestCase):
"""
Integration tests for third_party_auth LTI auth providers
"""
def setUp(self):
super(IntegrationTestLTI, self).setUp()
self.client.defaults['SERVER_NAME'] = 'testserver'
self.url_prefix = 'http://testserver'
self.configure_lti_provider(
name='Other Tool Consumer 1', enabled=True,
lti_consumer_key='other1',
lti_consumer_secret='secret1',
lti_max_timestamp_age=10,
)
self.configure_lti_provider(
name='LTI Test Tool Consumer', enabled=True,
lti_consumer_key=LTI_CONSUMER_KEY,
lti_consumer_secret=LTI_CONSUMER_SECRET,
lti_max_timestamp_age=10,
)
self.configure_lti_provider(
name='Tool Consumer with Secret in Settings', enabled=True,
lti_consumer_key=OTHER_LTI_CONSUMER_KEY,
lti_consumer_secret='',
lti_max_timestamp_age=10,
)
self.lti = Client(
client_key=LTI_CONSUMER_KEY,
client_secret=LTI_CONSUMER_SECRET,
signature_type=SIGNATURE_TYPE_BODY,
)
def test_lti_login(self):
# The user initiates a login from an external site
(uri, _headers, body) = self.lti.sign(
uri=LTI_TPA_LOGIN_URL, http_method='POST',
headers={'Content-Type': FORM_ENCODED},
body={
'user_id': LTI_USER_ID,
'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll',
}
)
login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)
# The user should be redirected to the registration form
self.assertEqual(login_response.status_code, 302)
self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))
register_response = self.client.get(login_response['Location'])
self.assertEqual(register_response.status_code, 200)
self.assertIn('"currentProvider": "LTI Test Tool Consumer"', register_response.content)
self.assertIn('"errorMessage": null', register_response.content)
# Now complete the form:
ajax_register_response = self.client.post(
reverse('user_api_registration'),
{
'email': EMAIL,
'name': 'Myself',
'username': EDX_USER_ID,
'honor_code': True,
}
)
self.assertEqual(ajax_register_response.status_code, 200)
continue_response = self.client.get(LTI_TPA_COMPLETE_URL)
# The user should be redirected to the finish_auth view which will enroll them.
# FinishAuthView.js reads the URL parameters directly from $.url
self.assertEqual(continue_response.status_code, 302)
self.assertEqual(
continue_response['Location'],
'http://testserver/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll'
)
# Now check that we can login again
self.client.logout()
self.verify_user_email(EMAIL)
(uri, _headers, body) = self.lti.sign(
uri=LTI_TPA_LOGIN_URL, http_method='POST',
headers={'Content-Type': FORM_ENCODED},
body={'user_id': LTI_USER_ID}
)
login_2_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)
# The user should be redirected to the dashboard
self.assertEqual(login_2_response.status_code, 302)
self.assertEqual(login_2_response['Location'], LTI_TPA_COMPLETE_URL)
continue_2_response = self.client.get(login_2_response['Location'])
self.assertEqual(continue_2_response.status_code, 302)
self.assertTrue(continue_2_response['Location'].endswith(reverse('dashboard')))
# Check that the user was created correctly
user = User.objects.get(email=EMAIL)
self.assertEqual(user.username, EDX_USER_ID)
def test_reject_initiating_login(self):
response = self.client.get(LTI_TPA_LOGIN_URL)
self.assertEqual(response.status_code, 405) # Not Allowed
def test_reject_bad_login(self):
login_response = self.client.post(
path=LTI_TPA_LOGIN_URL, content_type=FORM_ENCODED,
data="invalid=login"
)
# The user should be redirected to the login page with an error message
# (auth_entry defaults to login for this provider)
self.assertEqual(login_response.status_code, 302)
self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))
error_response = self.client.get(login_response['Location'])
self.assertIn(
'Authentication failed: LTI parameters could not be validated.',
error_response.content
)
def test_can_load_consumer_secret_from_settings(self):
lti = Client(
client_key=OTHER_LTI_CONSUMER_KEY,
client_secret=OTHER_LTI_CONSUMER_SECRET,
signature_type=SIGNATURE_TYPE_BODY,
)
(uri, _headers, body) = lti.sign(
uri=LTI_TPA_LOGIN_URL, http_method='POST',
headers={'Content-Type': FORM_ENCODED},
body={
'user_id': LTI_USER_ID,
'custom_tpa_next': '/account/finish_auth/?course_id=my_course_id&enrollment_action=enroll',
}
)
with self.settings(SOCIAL_AUTH_LTI_CONSUMER_SECRETS={OTHER_LTI_CONSUMER_KEY: OTHER_LTI_CONSUMER_SECRET}):
login_response = self.client.post(path=uri, content_type=FORM_ENCODED, data=body)
# The user should be redirected to the registration form
self.assertEqual(login_response.status_code, 302)
self.assertTrue(login_response['Location'].endswith(reverse('signin_user')))
register_response = self.client.get(login_response['Location'])
self.assertEqual(register_response.status_code, 200)
self.assertIn(
'"currentProvider": "Tool Consumer with Secret in Settings"',
register_response.content
)
self.assertIn('"errorMessage": null', register_response.content)
| agpl-3.0 |
marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/sql/planner/sanity/NoSubqueryExpressionLeftChecker.java | 1903 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.sanity;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.ExpressionExtractor;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.tree.DefaultTraversalVisitor;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.SubqueryExpression;
import java.util.Map;
import static java.lang.String.format;
public final class NoSubqueryExpressionLeftChecker
implements PlanSanityChecker.Checker
{
@Override
public void validate(PlanNode plan, Session session, Metadata metadata, SqlParser sqlParser, Map<Symbol, Type> types)
{
for (Expression expression : ExpressionExtractor.extractExpressions(plan)) {
new DefaultTraversalVisitor<Void, Void>()
{
@Override
protected Void visitSubqueryExpression(SubqueryExpression node, Void context)
{
throw new IllegalStateException(format("Unexpected subquery expression in logical plan: %s", node));
}
}.process(expression, null);
}
}
}
| apache-2.0 |
carmine/northshore | ui/node_modules/popsicle/dist/form.js | 353 | var FormData = require('form-data');
function form(obj) {
var form = new FormData();
if (obj) {
Object.keys(obj).forEach(function (name) {
form.append(name, obj[name]);
});
}
return form;
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = form;
//# sourceMappingURL=form.js.map | apache-2.0 |
scheib/chromium | third_party/blink/web_tests/external/wpt/infrastructure/server/resources/expect-title-meta.js | 312 | if (!self.GLOBAL || self.GLOBAL.isWindow()) {
test(() => {
assert_equals(document.title, "foo");
}, '<title> exists');
test(() => {
assert_equals(document.querySelectorAll("meta[name=timeout][content=long]").length, 1);
}, '<meta name=timeout> exists');
}
scripts.push('expect-title-meta.js');
| bsd-3-clause |
benjaminjkraft/django | tests/proxy_models/models.py | 4514 | """
By specifying the 'proxy' Meta attribute, model subclasses can specify that
they will take data directly from the table of their base class table rather
than using a new table of their own. This allows them to act as simple proxies,
providing a modified interface to the data from the base class.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# A couple of managers for testing managing overriding in proxy model cases.
class PersonManager(models.Manager):
def get_queryset(self):
return super(PersonManager, self).get_queryset().exclude(name="fred")
class SubManager(models.Manager):
def get_queryset(self):
return super(SubManager, self).get_queryset().exclude(name="wilma")
@python_2_unicode_compatible
class Person(models.Model):
"""
A simple concrete base class.
"""
name = models.CharField(max_length=50)
objects = PersonManager()
def __str__(self):
return self.name
class Abstract(models.Model):
"""
A simple abstract base class, to be used for error checking.
"""
data = models.CharField(max_length=10)
class Meta:
abstract = True
class MyPerson(Person):
"""
A proxy subclass, this should not get a new table. Overrides the default
manager.
"""
class Meta:
proxy = True
ordering = ["name"]
permissions = (
("display_users", "May display users information"),
)
objects = SubManager()
other = PersonManager()
def has_special_name(self):
return self.name.lower() == "special"
class ManagerMixin(models.Model):
excluder = SubManager()
class Meta:
abstract = True
class OtherPerson(Person, ManagerMixin):
"""
A class with the default manager from Person, plus an secondary manager.
"""
class Meta:
proxy = True
ordering = ["name"]
class StatusPerson(MyPerson):
"""
A non-proxy subclass of a proxy, it should get a new table.
"""
status = models.CharField(max_length=80)
# We can even have proxies of proxies (and subclass of those).
class MyPersonProxy(MyPerson):
class Meta:
proxy = True
class LowerStatusPerson(MyPersonProxy):
status = models.CharField(max_length=80)
@python_2_unicode_compatible
class User(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class UserProxy(User):
class Meta:
proxy = True
class UserProxyProxy(UserProxy):
class Meta:
proxy = True
# We can still use `select_related()` to include related models in our querysets.
class Country(models.Model):
name = models.CharField(max_length=50)
@python_2_unicode_compatible
class State(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country, models.CASCADE)
def __str__(self):
return self.name
class StateProxy(State):
class Meta:
proxy = True
# Proxy models still works with filters (on related fields)
# and select_related, even when mixed with model inheritance
@python_2_unicode_compatible
class BaseUser(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return ':'.join((self.__class__.__name__, self.name,))
class TrackerUser(BaseUser):
status = models.CharField(max_length=50)
class ProxyTrackerUser(TrackerUser):
class Meta:
proxy = True
@python_2_unicode_compatible
class Issue(models.Model):
summary = models.CharField(max_length=255)
assignee = models.ForeignKey(ProxyTrackerUser, models.CASCADE, related_name='issues')
def __str__(self):
return ':'.join((self.__class__.__name__, self.summary,))
class Bug(Issue):
version = models.CharField(max_length=50)
reporter = models.ForeignKey(BaseUser, models.CASCADE)
class ProxyBug(Bug):
"""
Proxy of an inherited class
"""
class Meta:
proxy = True
class ProxyProxyBug(ProxyBug):
"""
A proxy of proxy model with related field
"""
class Meta:
proxy = True
class Improvement(Issue):
"""
A model that has relation to a proxy model
or to a proxy of proxy model
"""
version = models.CharField(max_length=50)
reporter = models.ForeignKey(ProxyTrackerUser, models.CASCADE)
associated_bug = models.ForeignKey(ProxyProxyBug, models.CASCADE)
class ProxyImprovement(Improvement):
class Meta:
proxy = True
| bsd-3-clause |
mimecine/mongrel2 | src/polarssl/bignum.h | 19580 | /**
* \file bignum.h
*
* \brief Multi-precision integer library
*
* Copyright (C) 2006-2010, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef POLARSSL_BIGNUM_H
#define POLARSSL_BIGNUM_H
#include <stdio.h>
#include <string.h>
#include "config.h"
#define POLARSSL_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */
#define POLARSSL_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */
#define POLARSSL_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */
#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The buffer is too small to write to. */
#define POLARSSL_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */
#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */
#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */
#define POLARSSL_ERR_MPI_MALLOC_FAILED -0x0010 /**< Memory allocation failed. */
#define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup
/*
* Maximum size MPIs are allowed to grow to in number of limbs.
*/
#define POLARSSL_MPI_MAX_LIMBS 10000
/*
* Maximum window size used for modular exponentiation. Default: 6
* Minimum value: 1. Maximum value: 6.
*
* Result is an array of ( 2 << POLARSSL_MPI_WINDOW_SIZE ) MPIs used
* for the sliding window calculation. (So 64 by default)
*
* Reduction in size, reduces speed.
*/
#define POLARSSL_MPI_WINDOW_SIZE 6 /**< Maximum windows size used. */
/*
* Maximum size of MPIs allowed in bits and bytes for user-MPIs.
* ( Default: 512 bytes => 4096 bits )
*
* Note: Calculations can results temporarily in larger MPIs. So the number
* of limbs required (POLARSSL_MPI_MAX_LIMBS) is higher.
*/
#define POLARSSL_MPI_MAX_SIZE 512 /**< Maximum number of bytes for usable MPIs. */
#define POLARSSL_MPI_MAX_BITS ( 8 * POLARSSL_MPI_MAX_SIZE ) /**< Maximum number of bits for usable MPIs. */
/*
* When reading from files with mpi_read_file() the buffer should have space
* for a (short) label, the MPI (in the provided radix), the newline
* characters and the '\0'.
*
* By default we assume at least a 10 char label, a minimum radix of 10
* (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).
*/
#define POLARSSL_MPI_READ_BUFFER_SIZE 1250
/*
* Define the base integer type, architecture-wise
*/
#if defined(POLARSSL_HAVE_INT8)
typedef signed char t_sint;
typedef unsigned char t_uint;
typedef unsigned short t_udbl;
#else
#if defined(POLARSSL_HAVE_INT16)
typedef signed short t_sint;
typedef unsigned short t_uint;
typedef unsigned long t_udbl;
#else
typedef signed long t_sint;
typedef unsigned long t_uint;
#if defined(_MSC_VER) && defined(_M_IX86)
typedef unsigned __int64 t_udbl;
#else
#if defined(__GNUC__) && ( \
defined(__amd64__) || defined(__x86_64__) || \
defined(__ppc64__) || defined(__powerpc64__) || \
defined(__ia64__) || defined(__alpha__) || \
(defined(__sparc__) && defined(__arch64__)) || \
defined(__s390x__) )
typedef unsigned int t_udbl __attribute__((mode(TI)));
#define POLARSSL_HAVE_LONGLONG
#else
#if defined(POLARSSL_HAVE_LONGLONG)
typedef unsigned long long t_udbl;
#endif
#endif
#endif
#endif
#endif
/**
* \brief MPI structure
*/
typedef struct
{
int s; /*!< integer sign */
size_t n; /*!< total # of limbs */
t_uint *p; /*!< pointer to limbs */
}
mpi;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Initialize one MPI
*
* \param X One MPI to initialize.
*/
void mpi_init( mpi *X );
/**
* \brief Unallocate one MPI
*
* \param X One MPI to unallocate.
*/
void mpi_free( mpi *X );
/**
* \brief Enlarge to the specified number of limbs
*
* \param X MPI to grow
* \param nblimbs The target number of limbs
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_grow( mpi *X, size_t nblimbs );
/**
* \brief Copy the contents of Y into X
*
* \param X Destination MPI
* \param Y Source MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_copy( mpi *X, const mpi *Y );
/**
* \brief Swap the contents of X and Y
*
* \param X First MPI value
* \param Y Second MPI value
*/
void mpi_swap( mpi *X, mpi *Y );
/**
* \brief Set value from integer
*
* \param X MPI to set
* \param z Value to use
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_lset( mpi *X, t_sint z );
/*
* \brief Get a specific bit from X
*
* \param X MPI to use
* \param pos Zero-based index of the bit in X
*
* \return Either a 0 or a 1
*/
int mpi_get_bit( mpi *X, size_t pos );
/*
* \brief Set a bit of X to a specific value of 0 or 1
*
* \note Will grow X if necessary to set a bit to 1 in a not yet
* existing limb. Will not grow if bit should be set to 0
*
* \param X MPI to use
* \param pos Zero-based index of the bit in X
* \param val The value to set the bit to (0 or 1)
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1
*/
int mpi_set_bit( mpi *X, size_t pos, unsigned char val );
/**
* \brief Return the number of least significant bits
*
* \param X MPI to use
*/
size_t mpi_lsb( const mpi *X );
/**
* \brief Return the number of most significant bits
*
* \param X MPI to use
*/
size_t mpi_msb( const mpi *X );
/**
* \brief Return the total size in bytes
*
* \param X MPI to use
*/
size_t mpi_size( const mpi *X );
/**
* \brief Import from an ASCII string
*
* \param X Destination MPI
* \param radix Input numeric base
* \param s Null-terminated string buffer
*
* \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code
*/
int mpi_read_string( mpi *X, int radix, const char *s );
/**
* \brief Export into an ASCII string
*
* \param X Source MPI
* \param radix Output numeric base
* \param s String buffer
* \param slen String buffer size
*
* \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code.
* *slen is always updated to reflect the amount
* of data that has (or would have) been written.
*
* \note Call this function with *slen = 0 to obtain the
* minimum required buffer size in *slen.
*/
int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen );
/**
* \brief Read X from an opened file
*
* \param X Destination MPI
* \param radix Input numeric base
* \param fin Input file handle
*
* \return 0 if successful, POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if
* the file read buffer is too small or a
* POLARSSL_ERR_MPI_XXX error code
*/
int mpi_read_file( mpi *X, int radix, FILE *fin );
/**
* \brief Write X into an opened file, or stdout if fout is NULL
*
* \param p Prefix, can be NULL
* \param X Source MPI
* \param radix Output numeric base
* \param fout Output file handle (can be NULL)
*
* \return 0 if successful, or a POLARSSL_ERR_MPI_XXX error code
*
* \note Set fout == NULL to print X on the console.
*/
int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout );
/**
* \brief Import X from unsigned binary data, big endian
*
* \param X Destination MPI
* \param buf Input buffer
* \param buflen Input buffer size
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen );
/**
* \brief Export X into unsigned binary data, big endian
*
* \param X Source MPI
* \param buf Output buffer
* \param buflen Output buffer size
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough
*/
int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen );
/**
* \brief Left-shift: X <<= count
*
* \param X MPI to shift
* \param count Amount to shift
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_shift_l( mpi *X, size_t count );
/**
* \brief Right-shift: X >>= count
*
* \param X MPI to shift
* \param count Amount to shift
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_shift_r( mpi *X, size_t count );
/**
* \brief Compare unsigned values
*
* \param X Left-hand MPI
* \param Y Right-hand MPI
*
* \return 1 if |X| is greater than |Y|,
* -1 if |X| is lesser than |Y| or
* 0 if |X| is equal to |Y|
*/
int mpi_cmp_abs( const mpi *X, const mpi *Y );
/**
* \brief Compare signed values
*
* \param X Left-hand MPI
* \param Y Right-hand MPI
*
* \return 1 if X is greater than Y,
* -1 if X is lesser than Y or
* 0 if X is equal to Y
*/
int mpi_cmp_mpi( const mpi *X, const mpi *Y );
/**
* \brief Compare signed values
*
* \param X Left-hand MPI
* \param z The integer value to compare to
*
* \return 1 if X is greater than z,
* -1 if X is lesser than z or
* 0 if X is equal to z
*/
int mpi_cmp_int( const mpi *X, t_sint z );
/**
* \brief Unsigned addition: X = |A| + |B|
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_add_abs( mpi *X, const mpi *A, const mpi *B );
/**
* \brief Unsigned substraction: X = |A| - |B|
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_NEGATIVE_VALUE if B is greater than A
*/
int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B );
/**
* \brief Signed addition: X = A + B
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B );
/**
* \brief Signed substraction: X = A - B
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B );
/**
* \brief Signed addition: X = A + b
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param b The integer value to add
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_add_int( mpi *X, const mpi *A, t_sint b );
/**
* \brief Signed substraction: X = A - b
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param b The integer value to subtract
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_sub_int( mpi *X, const mpi *A, t_sint b );
/**
* \brief Baseline multiplication: X = A * B
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B );
/**
* \brief Baseline multiplication: X = A * b
* Note: b is an unsigned integer type, thus
* Negative values of b are ignored.
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param b The integer value to multiply with
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_mul_int( mpi *X, const mpi *A, t_sint b );
/**
* \brief Division by mpi: A = Q * B + R
*
* \param Q Destination MPI for the quotient
* \param R Destination MPI for the rest value
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0
*
* \note Either Q or R can be NULL.
*/
int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B );
/**
* \brief Division by int: A = Q * b + R
*
* \param Q Destination MPI for the quotient
* \param R Destination MPI for the rest value
* \param A Left-hand MPI
* \param b Integer to divide by
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0
*
* \note Either Q or R can be NULL.
*/
int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b );
/**
* \brief Modulo: R = A mod B
*
* \param R Destination MPI for the rest value
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0,
* POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0
*/
int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B );
/**
* \brief Modulo: r = A mod b
*
* \param r Destination t_uint
* \param A Left-hand MPI
* \param b Integer to divide by
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0,
* POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0
*/
int mpi_mod_int( t_uint *r, const mpi *A, t_sint b );
/**
* \brief Sliding-window exponentiation: X = A^E mod N
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param E Exponent MPI
* \param N Modular MPI
* \param _RR Speed-up MPI used for recalculations
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or even
*
* \note _RR is used to avoid re-computing R*R mod N across
* multiple calls, which speeds up things a bit. It can
* be set to NULL if the extra performance is unneeded.
*/
int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR );
/**
* \brief Fill an MPI X with size bytes of random
*
* \param X Destination MPI
* \param size Size in bytes
* \param f_rng RNG function
* \param p_rng RNG parameter
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_fill_random( mpi *X, size_t size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Greatest common divisor: G = gcd(A, B)
*
* \param G Destination MPI
* \param A Left-hand MPI
* \param B Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed
*/
int mpi_gcd( mpi *G, const mpi *A, const mpi *B );
/**
* \brief Modular inverse: X = A^-1 mod N
*
* \param X Destination MPI
* \param A Left-hand MPI
* \param N Right-hand MPI
*
* \return 0 if successful,
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or nil
POLARSSL_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N
*/
int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N );
/**
* \brief Miller-Rabin primality test
*
* \param X MPI to check
* \param f_rng RNG function
* \param p_rng RNG parameter
*
* \return 0 if successful (probably prime),
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_NOT_ACCEPTABLE if X is not prime
*/
int mpi_is_prime( mpi *X,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Prime number generation
*
* \param X Destination MPI
* \param nbits Required size of X in bits ( 3 <= nbits <= POLARSSL_MPI_MAX_BITS )
* \param dh_flag If 1, then (X-1)/2 will be prime too
* \param f_rng RNG function
* \param p_rng RNG parameter
*
* \return 0 if successful (probably prime),
* POLARSSL_ERR_MPI_MALLOC_FAILED if memory allocation failed,
* POLARSSL_ERR_MPI_BAD_INPUT_DATA if nbits is < 3
*/
int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*/
int mpi_self_test( int verbose );
#ifdef __cplusplus
}
#endif
#endif /* bignum.h */
| bsd-3-clause |
shimingsg/corefx | src/System.Threading/tests/SemaphoreSlimTests.cs | 25845 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
/// <summary>
/// SemaphoreSlim unit tests
/// </summary>
public class SemaphoreSlimTests
{
/// <summary>
/// SemaphoreSlim public methods and properties to be tested
/// </summary>
private enum SemaphoreSlimActions
{
Constructor,
Wait,
WaitAsync,
Release,
Dispose,
CurrentCount,
AvailableWaitHandle
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor()
{
RunSemaphoreSlimTest0_Ctor(0, 10, null);
RunSemaphoreSlimTest0_Ctor(5, 10, null);
RunSemaphoreSlimTest0_Ctor(10, 10, null);
}
[Fact]
public static void RunSemaphoreSlimTest0_Ctor_Negative()
{
RunSemaphoreSlimTest0_Ctor(10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(10, -1, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest0_Ctor(-1, 10, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait()
{
// Infinite timeout
RunSemaphoreSlimTest1_Wait(10, 10, -1, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_Wait(10, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 0, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_Wait(10, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(1, 10, 10, true, null);
RunSemaphoreSlimTest1_Wait(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_Wait_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_Wait(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_Wait
(10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException));
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync()
{
// Infinite timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -1, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, -1, true, null);
// Zero timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 0, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 0, false, null);
// Positive timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(1, 10, 10, true, null);
RunSemaphoreSlimTest1_WaitAsync(0, 10, 10, false, null);
}
[Fact]
public static void RunSemaphoreSlimTest1_WaitAsync_NegativeCases()
{
// Invalid timeout
RunSemaphoreSlimTest1_WaitAsync(10, 10, -10, true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync
(10, 10, new TimeSpan(0, 0, int.MaxValue), true, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest1_WaitAsync2();
}
[Fact]
public static void RunSemaphoreSlimTest2_Release()
{
// Valid release count
RunSemaphoreSlimTest2_Release(5, 10, 1, null);
RunSemaphoreSlimTest2_Release(0, 10, 1, null);
RunSemaphoreSlimTest2_Release(5, 10, 5, null);
}
[Fact]
public static void RunSemaphoreSlimTest2_Release_NegativeCases()
{
// Invalid release count
RunSemaphoreSlimTest2_Release(5, 10, 0, typeof(ArgumentOutOfRangeException));
RunSemaphoreSlimTest2_Release(5, 10, -1, typeof(ArgumentOutOfRangeException));
// Semaphore Full
RunSemaphoreSlimTest2_Release(10, 10, 1, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(5, 10, 6, typeof(SemaphoreFullException));
RunSemaphoreSlimTest2_Release(int.MaxValue - 1, int.MaxValue, 10, typeof(SemaphoreFullException));
}
[Fact]
public static void RunSemaphoreSlimTest4_Dispose()
{
RunSemaphoreSlimTest4_Dispose(5, 10, null, null);
RunSemaphoreSlimTest4_Dispose(5, 10, SemaphoreSlimActions.CurrentCount, null);
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Wait, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.WaitAsync, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.Release, typeof(ObjectDisposedException));
RunSemaphoreSlimTest4_Dispose
(5, 10, SemaphoreSlimActions.AvailableWaitHandle, typeof(ObjectDisposedException));
}
[Fact]
public static void RunSemaphoreSlimTest5_CurrentCount()
{
RunSemaphoreSlimTest5_CurrentCount(5, 10, null);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Wait);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.WaitAsync);
RunSemaphoreSlimTest5_CurrentCount(5, 10, SemaphoreSlimActions.Release);
}
[Fact]
public static void RunSemaphoreSlimTest7_AvailableWaitHandle()
{
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, null, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, null, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.Wait, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.Wait, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(1, 10, SemaphoreSlimActions.WaitAsync, false);
RunSemaphoreSlimTest7_AvailableWaitHandle(5, 10, SemaphoreSlimActions.WaitAsync, true);
RunSemaphoreSlimTest7_AvailableWaitHandle(0, 10, SemaphoreSlimActions.Release, true);
}
/// <summary>
/// Test SemaphoreSlim constructor
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest0_Ctor(int initial, int maximum, Type exceptionType)
{
string methodFailed = "RunSemaphoreSlimTest0_Ctor(" + initial + "," + maximum + "): FAILED. ";
Exception exception = null;
try
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Assert.Equal(initial, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
exception = ex;
}
}
/// <summary>
/// Test SemaphoreSlim Wait
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_Wait
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.Wait((TimeSpan)timeout);
}
else
{
result = semaphore.Wait((int)timeout);
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="timeout">The timeout parameter for the wait method, it must be either int or TimeSpan</param>
/// <param name="returnValue">The expected wait return value</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest1_WaitAsync
(int initial, int maximum, object timeout, bool returnValue, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
bool result = false;
if (timeout is TimeSpan)
{
result = semaphore.WaitAsync((TimeSpan)timeout).Result;
}
else
{
result = semaphore.WaitAsync((int)timeout).Result;
}
Assert.Equal(returnValue, result);
if (result)
{
Assert.Equal(initial - 1, semaphore.CurrentCount);
}
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim WaitAsync
/// The test verifies that SemaphoreSlim.Release() does not execute any user code synchronously.
/// </summary>
private static void RunSemaphoreSlimTest1_WaitAsync2()
{
SemaphoreSlim semaphore = new SemaphoreSlim(1);
ThreadLocal<int> counter = new ThreadLocal<int>(() => 0);
bool nonZeroObserved = false;
const int asyncActions = 20;
int remAsyncActions = asyncActions;
ManualResetEvent mre = new ManualResetEvent(false);
Action<int> doWorkAsync = async delegate (int i)
{
await semaphore.WaitAsync();
if (counter.Value > 0)
{
nonZeroObserved = true;
}
counter.Value = counter.Value + 1;
semaphore.Release();
counter.Value = counter.Value - 1;
if (Interlocked.Decrement(ref remAsyncActions) == 0) mre.Set();
};
semaphore.Wait();
for (int i = 0; i < asyncActions; i++) doWorkAsync(i);
semaphore.Release();
mre.WaitOne();
Assert.False(nonZeroObserved, "RunSemaphoreSlimTest1_WaitAsync2: FAILED. SemaphoreSlim.Release() seems to have synchronously invoked a continuation.");
}
/// <summary>
/// Test SemaphoreSlim Release
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="releaseCount">The release count for the release method</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest2_Release
(int initial, int maximum, int releaseCount, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
int oldCount = semaphore.Release(releaseCount);
Assert.Equal(initial, oldCount);
Assert.Equal(initial + releaseCount, semaphore.CurrentCount);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Call specific SemaphoreSlim method or property
/// </summary>
/// <param name="semaphore">The SemaphoreSlim instance</param>
/// <param name="action">The action name</param>
/// <param name="param">The action parameter, null if it takes no parameters</param>
/// <returns>The action return value, null if the action returns void</returns>
private static object CallSemaphoreAction
(SemaphoreSlim semaphore, SemaphoreSlimActions? action, object param)
{
if (action == SemaphoreSlimActions.Wait)
{
if (param is TimeSpan)
{
return semaphore.Wait((TimeSpan)param);
}
else if (param is int)
{
return semaphore.Wait((int)param);
}
semaphore.Wait();
return null;
}
else if (action == SemaphoreSlimActions.WaitAsync)
{
if (param is TimeSpan)
{
return semaphore.WaitAsync((TimeSpan)param).Result;
}
else if (param is int)
{
return semaphore.WaitAsync((int)param).Result;
}
semaphore.WaitAsync().Wait();
return null;
}
else if (action == SemaphoreSlimActions.Release)
{
if (param != null)
{
return semaphore.Release((int)param);
}
return semaphore.Release();
}
else if (action == SemaphoreSlimActions.Dispose)
{
semaphore.Dispose();
return null;
}
else if (action == SemaphoreSlimActions.CurrentCount)
{
return semaphore.CurrentCount;
}
else if (action == SemaphoreSlimActions.AvailableWaitHandle)
{
return semaphore.AvailableWaitHandle;
}
return null;
}
/// <summary>
/// Test SemaphoreSlim Dispose
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called after Dispose</param>
/// <param name="exceptionType">The type of the thrown exception in case of invalid cases,
/// null for valid cases</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest4_Dispose(int initial, int maximum, SemaphoreSlimActions? action, Type exceptionType)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
try
{
semaphore.Dispose();
CallSemaphoreAction(semaphore, action, null);
}
catch (Exception ex)
{
Assert.NotNull(exceptionType);
Assert.IsType(exceptionType, ex);
}
}
/// <summary>
/// Test SemaphoreSlim CurrentCount property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before CurrentCount</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest5_CurrentCount(int initial, int maximum, SemaphoreSlimActions? action)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
if (action == null)
{
Assert.Equal(initial, semaphore.CurrentCount);
}
else
{
Assert.Equal(initial + (action == SemaphoreSlimActions.Release ? 1 : -1), semaphore.CurrentCount);
}
}
/// <summary>
/// Test SemaphoreSlim AvailableWaitHandle property
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="action">SemaphoreSlim action to be called before WaitHandle</param>
/// <param name="state">The expected wait handle state</param>
/// <returns>True if the test succeeded, false otherwise</returns>
private static void RunSemaphoreSlimTest7_AvailableWaitHandle(int initial, int maximum, SemaphoreSlimActions? action, bool state)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
CallSemaphoreAction(semaphore, action, null);
Assert.NotNull(semaphore.AvailableWaitHandle);
Assert.Equal(state, semaphore.AvailableWaitHandle.WaitOne(0));
}
/// <summary>
/// Test SemaphoreSlim Wait and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
[Theory]
[InlineData(5, 1000, 50, 50, 50, 0, 5, 1000)]
[InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]
[InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]
public static void RunSemaphoreSlimTest8_ConcWaitAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] threads = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < threads.Length; i++)
{
if (i < waitThreads)
{
// We are creating the Task using TaskCreationOptions.LongRunning to
// force usage of another thread (which will be the case on the default scheduler
// with its current implementation). Without this, the release tasks will likely get
// queued behind the wait tasks in the pool, making it very likely that the wait tasks
// will starve the very tasks that when run would unblock them.
threads[i] = new Task(delegate ()
{
mre.WaitOne();
if (semaphore.Wait(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
}, TaskCreationOptions.LongRunning);
}
else
{
threads[i] = new Task(delegate ()
{
mre.WaitOne();
semaphore.Release();
});
}
threads[i].Start(TaskScheduler.Default);
}
mre.Set();
//wait work to be done;
Task.WaitAll(threads);
//check the number of succeeded and failed wait
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
/// <summary>
/// Test SemaphoreSlim WaitAsync and Release methods concurrently
/// </summary>
/// <param name="initial">The initial semaphore count</param>
/// <param name="maximum">The maximum semaphore count</param>
/// <param name="waitThreads">Number of the threads that call Wait method</param>
/// <param name="releaseThreads">Number of the threads that call Release method</param>
/// <param name="succeededWait">Number of succeeded wait threads</param>
/// <param name="failedWait">Number of failed wait threads</param>
/// <param name="finalCount">The final semaphore count</param>
/// <returns>True if the test succeeded, false otherwise</returns>
[Theory]
[InlineData(5, 1000, 50, 50, 50, 0, 5, 500)]
[InlineData(0, 1000, 50, 25, 25, 25, 0, 500)]
[InlineData(0, 1000, 50, 0, 0, 50, 0, 100)]
public static void RunSemaphoreSlimTest8_ConcWaitAsyncAndRelease(int initial, int maximum,
int waitThreads, int releaseThreads, int succeededWait, int failedWait, int finalCount, int timeout)
{
SemaphoreSlim semaphore = new SemaphoreSlim(initial, maximum);
Task[] tasks = new Task[waitThreads + releaseThreads];
int succeeded = 0;
int failed = 0;
ManualResetEvent mre = new ManualResetEvent(false);
// launch threads
for (int i = 0; i < tasks.Length; i++)
{
if (i < waitThreads)
{
tasks[i] = Task.Run(async delegate
{
mre.WaitOne();
if (await semaphore.WaitAsync(timeout))
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failed);
}
});
}
else
{
tasks[i] = Task.Run(delegate
{
mre.WaitOne();
semaphore.Release();
});
}
}
mre.Set();
//wait work to be done;
Task.WaitAll(tasks);
Assert.Equal(succeededWait, succeeded);
Assert.Equal(failedWait, failed);
Assert.Equal(finalCount, semaphore.CurrentCount);
}
[Theory]
[InlineData(10, 10)]
[InlineData(1, 10)]
[InlineData(10, 1)]
public static void TestConcurrentWaitAndWaitAsync(int syncWaiters, int asyncWaiters)
{
int totalWaiters = syncWaiters + asyncWaiters;
var semaphore = new SemaphoreSlim(0);
Task[] tasks = new Task[totalWaiters];
const int ITERS = 10;
int randSeed = unchecked((int)DateTime.Now.Ticks);
for (int i = 0; i < syncWaiters; i++)
{
tasks[i] = Task.Run(delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
semaphore.Wait();
semaphore.Release();
}
});
}
for (int i = syncWaiters; i < totalWaiters; i++)
{
tasks[i] = Task.Run(async delegate
{
//Random rand = new Random(Interlocked.Increment(ref randSeed));
for (int iter = 0; iter < ITERS; iter++)
{
await semaphore.WaitAsync();
semaphore.Release();
}
});
}
semaphore.Release(totalWaiters / 2);
Task.WaitAll(tasks);
}
}
}
| mit |
NetEase/pomelo-admin-web | public/front/auditsPanel.css | 5485 | /*
* Copyright (C) 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
.audits-sidebar-tree-item .icon {
content: url(Images/resourcesTimeGraphIcon.png);
}
.audit-result-sidebar-tree-item .icon {
content: url(Images/resourceDocumentIcon.png);
}
.audit-launcher-view {
z-index: 1000;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: white;
font-size: 13px;
overflow-x: hidden;
overflow-y: overlay;
display: none;
}
.audit-launcher-view.visible {
display: block;
}
.audit-launcher-view .audit-launcher-view-content {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 0 0 0 16px;
white-space: nowrap;
display: -webkit-box;
text-align: left;
-webkit-box-orient: vertical;
}
.audit-launcher-view h1 {
padding-top: 15px;
}
.audit-launcher-view h1.no-audits {
text-align: center;
font-style: italic;
position: relative;
left: -8px;
}
.audit-launcher-view div.button-container {
display: -webkit-box;
-webkit-box-orient: vertical;
width: 100%;
padding: 16px 0;
}
.audit-launcher-view div.audit-categories-container {
position: relative;
top: 11px;
left: 0;
width: 100%;
overflow-y: auto;
}
.audit-launcher-view button {
margin: 0 5px 0 0;
}
.audit-launcher-view button:active {
background-color: rgb(215, 215, 215);
background-image: -webkit-gradient(linear, left top, left bottom, from(rgb(194, 194, 194)), to(rgb(239, 239, 239)));
}
.panel-enabler-view.audit-launcher-view label {
padding: 0 0 5px 0;
margin: 0;
}
.panel-enabler-view.audit-launcher-view label.disabled {
color: rgb(130, 130, 130);
}
.audit-launcher-view input[type="checkbox"] {
margin-left: 0;
}
.audit-launcher-view .resource-progress > img {
content: url(Images/spinner.gif);
vertical-align: text-top;
margin: 0 4px 0 8px;
}
.audit-result-view {
overflow: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: none;
}
.audit-result-view.visible {
display: block;
}
.audit-result-view .severity-severe {
content: url(Images/errorRedDot.png);
}
.audit-result-view .severity-warning {
content: url(Images/warningOrangeDot.png);
}
.audit-result-view .severity-info {
content: url(Images/successGreenDot.png);
}
.audit-result-tree li.parent::before {
content: url(Images/treeRightTriangleBlack.png);
float: left;
width: 8px;
height: 8px;
margin-top: 1px;
padding-right: 2px;
}
.audit-result-tree {
font-size: 11px;
line-height: 14px;
-webkit-user-select: text;
}
.audit-result-tree > ol {
position: relative;
padding: 2px 6px !important;
margin: 0;
color: rgb(84, 84, 84);
cursor: default;
min-width: 100%;
}
.audit-result-tree, .audit-result-tree ol {
list-style-type: none;
-webkit-padding-start: 12px;
margin: 0;
}
.audit-result-tree ol.outline-disclosure {
-webkit-padding-start: 0;
}
.audit-result-tree .section .header {
padding-left: 13px;
}
.audit-result-tree .section .header::before {
left: 2px;
}
.audit-result-tree li {
padding: 0 0 0 14px;
margin-top: 1px;
margin-bottom: 1px;
word-wrap: break-word;
margin-left: -2px;
}
.audit-result-tree li.parent {
margin-left: -12px
}
.audit-result-tree li.parent::before {
content: url(Images/treeRightTriangleBlack.png);
float: left;
width: 8px;
height: 8px;
margin-top: 0;
padding-right: 2px;
}
.audit-result-tree li.parent.expanded::before {
content: url(Images/treeDownTriangleBlack.png);
}
.audit-result-tree ol.children {
display: none;
}
.audit-result-tree ol.children.expanded {
display: block;
}
.audit-result {
font-weight: bold;
color: black;
}
.audit-result img {
float: left;
margin-left: -28px;
margin-top: -1px;
}
| mit |
Subsets and Splits