repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
atom/superstring
vendor/pcre/10.23/src/sljit/sljitNativeSPARC_32.c
7825
/* * Stack-less Just-In-Time compiler * * Copyright 2009-2012 Zoltan Herczeg (hzmester@freemail.hu). All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) 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 HOLDER(S) 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. */ static sljit_s32 load_immediate(struct sljit_compiler *compiler, sljit_s32 dst, sljit_sw imm) { if (imm <= SIMM_MAX && imm >= SIMM_MIN) return push_inst(compiler, OR | D(dst) | S1(0) | IMM(imm), DR(dst)); FAIL_IF(push_inst(compiler, SETHI | D(dst) | ((imm >> 10) & 0x3fffff), DR(dst))); return (imm & 0x3ff) ? push_inst(compiler, OR | D(dst) | S1(dst) | IMM_ARG | (imm & 0x3ff), DR(dst)) : SLJIT_SUCCESS; } #define ARG2(flags, src2) ((flags & SRC2_IMM) ? IMM(src2) : S2(src2)) static SLJIT_INLINE sljit_s32 emit_single_op(struct sljit_compiler *compiler, sljit_s32 op, sljit_s32 flags, sljit_s32 dst, sljit_s32 src1, sljit_sw src2) { SLJIT_COMPILE_ASSERT(ICC_IS_SET == SET_FLAGS, icc_is_set_and_set_flags_must_be_the_same); switch (op) { case SLJIT_MOV: case SLJIT_MOV_U32: case SLJIT_MOV_S32: case SLJIT_MOV_P: SLJIT_ASSERT(src1 == TMP_REG1 && !(flags & SRC2_IMM)); if (dst != src2) return push_inst(compiler, OR | D(dst) | S1(0) | S2(src2), DR(dst)); return SLJIT_SUCCESS; case SLJIT_MOV_U8: case SLJIT_MOV_S8: SLJIT_ASSERT(src1 == TMP_REG1 && !(flags & SRC2_IMM)); if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) { if (op == SLJIT_MOV_U8) return push_inst(compiler, AND | D(dst) | S1(src2) | IMM(0xff), DR(dst)); FAIL_IF(push_inst(compiler, SLL | D(dst) | S1(src2) | IMM(24), DR(dst))); return push_inst(compiler, SRA | D(dst) | S1(dst) | IMM(24), DR(dst)); } else if (dst != src2) SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; case SLJIT_MOV_U16: case SLJIT_MOV_S16: SLJIT_ASSERT(src1 == TMP_REG1 && !(flags & SRC2_IMM)); if ((flags & (REG_DEST | REG2_SOURCE)) == (REG_DEST | REG2_SOURCE)) { FAIL_IF(push_inst(compiler, SLL | D(dst) | S1(src2) | IMM(16), DR(dst))); return push_inst(compiler, (op == SLJIT_MOV_S16 ? SRA : SRL) | D(dst) | S1(dst) | IMM(16), DR(dst)); } else if (dst != src2) SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; case SLJIT_NOT: SLJIT_ASSERT(src1 == TMP_REG1 && !(flags & SRC2_IMM)); return push_inst(compiler, XNOR | (flags & SET_FLAGS) | D(dst) | S1(0) | S2(src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_CLZ: SLJIT_ASSERT(src1 == TMP_REG1 && !(flags & SRC2_IMM)); /* sparc 32 does not support SLJIT_KEEP_FLAGS. Not sure I can fix this. */ FAIL_IF(push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(src2) | S2(0), SET_FLAGS)); FAIL_IF(push_inst(compiler, OR | D(TMP_REG1) | S1(0) | S2(src2), DR(TMP_REG1))); FAIL_IF(push_inst(compiler, BICC | DA(0x1) | (7 & DISP_MASK), UNMOVABLE_INS)); FAIL_IF(push_inst(compiler, OR | (flags & SET_FLAGS) | D(dst) | S1(0) | IMM(32), UNMOVABLE_INS | (flags & SET_FLAGS))); FAIL_IF(push_inst(compiler, OR | D(dst) | S1(0) | IMM(-1), DR(dst))); /* Loop. */ FAIL_IF(push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(TMP_REG1) | S2(0), SET_FLAGS)); FAIL_IF(push_inst(compiler, SLL | D(TMP_REG1) | S1(TMP_REG1) | IMM(1), DR(TMP_REG1))); FAIL_IF(push_inst(compiler, BICC | DA(0xe) | (-2 & DISP_MASK), UNMOVABLE_INS)); return push_inst(compiler, ADD | (flags & SET_FLAGS) | D(dst) | S1(dst) | IMM(1), UNMOVABLE_INS | (flags & SET_FLAGS)); case SLJIT_ADD: return push_inst(compiler, ADD | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_ADDC: return push_inst(compiler, ADDC | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_SUB: return push_inst(compiler, SUB | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_SUBC: return push_inst(compiler, SUBC | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_MUL: FAIL_IF(push_inst(compiler, SMUL | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst))); if (!(flags & SET_FLAGS)) return SLJIT_SUCCESS; FAIL_IF(push_inst(compiler, SRA | D(TMP_REG1) | S1(dst) | IMM(31), DR(TMP_REG1))); FAIL_IF(push_inst(compiler, RDY | D(TMP_LINK), DR(TMP_LINK))); return push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(TMP_REG1) | S2(TMP_LINK), MOVABLE_INS | SET_FLAGS); case SLJIT_AND: return push_inst(compiler, AND | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_OR: return push_inst(compiler, OR | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_XOR: return push_inst(compiler, XOR | (flags & SET_FLAGS) | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst) | (flags & SET_FLAGS)); case SLJIT_SHL: FAIL_IF(push_inst(compiler, SLL | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst))); return !(flags & SET_FLAGS) ? SLJIT_SUCCESS : push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(dst) | S2(0), SET_FLAGS); case SLJIT_LSHR: FAIL_IF(push_inst(compiler, SRL | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst))); return !(flags & SET_FLAGS) ? SLJIT_SUCCESS : push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(dst) | S2(0), SET_FLAGS); case SLJIT_ASHR: FAIL_IF(push_inst(compiler, SRA | D(dst) | S1(src1) | ARG2(flags, src2), DR(dst))); return !(flags & SET_FLAGS) ? SLJIT_SUCCESS : push_inst(compiler, SUB | SET_FLAGS | D(0) | S1(dst) | S2(0), SET_FLAGS); } SLJIT_ASSERT_STOP(); return SLJIT_SUCCESS; } static SLJIT_INLINE sljit_s32 emit_const(struct sljit_compiler *compiler, sljit_s32 dst, sljit_sw init_value) { FAIL_IF(push_inst(compiler, SETHI | D(dst) | ((init_value >> 10) & 0x3fffff), DR(dst))); return push_inst(compiler, OR | D(dst) | S1(dst) | IMM_ARG | (init_value & 0x3ff), DR(dst)); } SLJIT_API_FUNC_ATTRIBUTE void sljit_set_jump_addr(sljit_uw addr, sljit_uw new_target, sljit_sw executable_offset) { sljit_ins *inst = (sljit_ins *)addr; inst[0] = (inst[0] & 0xffc00000) | ((new_target >> 10) & 0x3fffff); inst[1] = (inst[1] & 0xfffffc00) | (new_target & 0x3ff); inst = (sljit_ins *)SLJIT_ADD_EXEC_OFFSET(inst, executable_offset); SLJIT_CACHE_FLUSH(inst, inst + 2); } SLJIT_API_FUNC_ATTRIBUTE void sljit_set_const(sljit_uw addr, sljit_sw new_constant, sljit_sw executable_offset) { sljit_ins *inst = (sljit_ins *)addr; inst[0] = (inst[0] & 0xffc00000) | ((new_constant >> 10) & 0x3fffff); inst[1] = (inst[1] & 0xfffffc00) | (new_constant & 0x3ff); inst = (sljit_ins *)SLJIT_ADD_EXEC_OFFSET(inst, executable_offset); SLJIT_CACHE_FLUSH(inst, inst + 2); }
mit
thaim/ansible
test/units/modules/storage/netapp/test_netapp_e_mgmt_interface.py
28142
# coding=utf-8 # (c) 2018, NetApp Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from ansible.modules.storage.netapp.netapp_e_mgmt_interface import MgmtInterface from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args __metaclass__ = type import mock from units.compat.mock import PropertyMock class MgmtInterfaceTest(ModuleTestCase): REQUIRED_PARAMS = { 'api_username': 'rw', 'api_password': 'password', 'api_url': 'http://localhost', 'ssid': '1', } TEST_DATA = [ { "controllerRef": "070000000000000000000001", "controllerSlot": 1, "interfaceName": "wan0", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 1, "alias": "creG1g-AP-a", "ipv4Enabled": True, "ipv4Address": "10.1.1.10", "linkStatus": "up", "ipv4SubnetMask": "255.255.255.0", "ipv4AddressConfigMethod": "configStatic", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 0, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", }, { "addressType": "ipv4", "ipv4Address": "10.10.0.20", } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "disabled", "ntpServers": None }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000001", "controllerSlot": 1, "interfaceName": "wan1", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 2, "alias": "creG1g-AP-a", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 1, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", "ipv6Address": None }, { "addressType": "ipv4", "ipv4Address": "10.10.0.20", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "disabled", "ntpServers": None }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000002", "controllerSlot": 2, "interfaceName": "wan0", "interfaceRef": "2800070000000000000000000001000000000000", "channel": 1, "alias": "creG1g-AP-b", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 0, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.1.0.250", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "stat", "ntpServers": [ { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.13.1.5", "ipv6Address": None } }, { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.15.1.8", "ipv6Address": None } } ] }, "dhcpAcquiredNtpServers": [] }, }, { "controllerRef": "070000000000000000000002", "controllerSlot": 2, "interfaceName": "wan1", "interfaceRef": "2801070000000000000000000001000000000000", "channel": 2, "alias": "creG1g-AP-b", "ipv4Enabled": True, "ipv4Address": "0.0.0.0", "ipv4SubnetMask": "0.0.0.0", "ipv4AddressConfigMethod": "configDhcp", "ipv4GatewayAddress": "10.1.1.1", "ipv6Enabled": False, "physicalLocation": { "slot": 1, }, "dnsProperties": { "acquisitionProperties": { "dnsAcquisitionType": "stat", "dnsServers": [ { "addressType": "ipv4", "ipv4Address": "10.19.1.2", "ipv6Address": None } ] }, "dhcpAcquiredDnsServers": [] }, "ntpProperties": { "acquisitionProperties": { "ntpAcquisitionType": "stat", "ntpServers": [ { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.13.1.5", "ipv6Address": None } }, { "addrType": "ipvx", "domainName": None, "ipvxAddress": { "addressType": "ipv4", "ipv4Address": "10.15.1.18", "ipv6Address": None } } ] }, "dhcpAcquiredNtpServers": [] }, }, ] REQ_FUNC = 'ansible.modules.storage.netapp.netapp_e_mgmt_interface.request' def _set_args(self, args=None): module_args = self.REQUIRED_PARAMS.copy() if args is not None: module_args.update(args) set_module_args(module_args) def test_controller_property_pass(self): """Verify dictionary return from controller property.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { 'A': {'controllerRef': '070000000000000000000001', 'controllerSlot': 1, 'ssh': False}, 'B': {'controllerRef': '070000000000000000000002', 'controllerSlot': 2, 'ssh': True}} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, controller_request)): response = mgmt_interface.controllers self.assertTrue(response == expected) def test_controller_property_fail(self): """Verify controllers endpoint request failure causes AnsibleFailJson exception.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { 'A': {'controllerRef': '070000000000000000000001', 'controllerSlot': 1, 'ssh': False}, 'B': {'controllerRef': '070000000000000000000002', 'controllerSlot': 2, 'ssh': True}} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"Failed to retrieve the controller settings."): with mock.patch(self.REQ_FUNC, return_value=Exception): response = mgmt_interface.controllers def test_interface_property_match_pass(self): """Verify return value from interface property.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.0", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.250", "addressType": "ipv4"}, {"ipv4Address": "10.10.0.20", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.10", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, side_effect=[(200, self.TEST_DATA), (200, controller_request)]): iface = mgmt_interface.interface self.assertTrue(iface == expected) def test_interface_property_request_exception_fail(self): """Verify ethernet-interfaces endpoint request failure results in AnsibleFailJson exception.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"Failed to retrieve defined management interfaces."): with mock.patch(self.REQ_FUNC, side_effect=[Exception, (200, controller_request)]): iface = mgmt_interface.interface def test_interface_property_no_match_fail(self): """Verify return value from interface property.""" initial = { "state": "enable", "controller": "A", "name": "wrong_name", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"We could not find an interface matching"): with mock.patch(self.REQ_FUNC, side_effect=[(200, self.TEST_DATA), (200, controller_request)]): iface = mgmt_interface.interface def test_get_enable_interface_settings_enabled_pass(self): """Validate get_enable_interface_settings updates properly.""" initial = { "state": "enable", "controller": "A", "name": "wrong_name", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} iface = {"enabled": False} expected_iface = {} self._set_args(initial) mgmt_interface = MgmtInterface() update, expected_iface, body = mgmt_interface.get_enable_interface_settings(iface, expected_iface, False, {}) self.assertTrue(update and expected_iface["enabled"] and body["ipv4Enabled"]) def test_get_enable_interface_settings_disabled_pass(self): """Validate get_enable_interface_settings updates properly.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static"} iface = {"enabled": True} expected_iface = {} self._set_args(initial) mgmt_interface = MgmtInterface() update, expected_iface, body = mgmt_interface.get_enable_interface_settings(iface, expected_iface, False, {}) self.assertTrue(update and not expected_iface["enabled"] and not body["ipv4Enabled"]) def test_update_array_interface_ssh_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "state": "enable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_static_ntp_disable_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "dns_config_method": "static", "dns_address": "192.168.1.1", "dns_address_backup": "192.168.1.100", "ntp_config_method": "disable"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "configDhcp", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_dhcp_ntp_static_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "ntp_config_method": "static", "ntp_address": "192.168.1.1", "ntp_address_backup": "192.168.1.100", "dns_config_method": "dhcp"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "link_status": "up", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "configStatic", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertTrue(update) def test_update_array_dns_dhcp_ntp_static_no_change_pass(self): """Verify get_interface_settings gives the right static configuration response.""" initial = { "controller": "A", "name": "wan0", "ntp_config_method": "dhcp", "dns_config_method": "dhcp"} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "dhcp", "controllerRef": "070000000000000000000001", "config_method": "static", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "dhcp", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.11", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with mock.patch(self.REQ_FUNC, return_value=(200, None)): update = mgmt_interface.update_array(settings, iface) self.assertFalse(update) def test_update_array_ipv4_ipv6_disabled_fail(self): """Verify exception is thrown when both ipv4 and ipv6 would be disabled at the same time.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.11", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"This storage-system already has IPv6 connectivity disabled."): with mock.patch(self.REQ_FUNC, return_value=(422, dict(ipv4Enabled=False, retcode="4", errorMessage=""))): mgmt_interface.update_array(settings, iface) def test_update_array_request_error_fail(self): """Verify exception is thrown when request results in an error.""" initial = { "state": "disable", "controller": "A", "name": "wan0", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": True} iface = {"dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} settings = {"controllerRef": "070000000000000000000001", "ssh": False} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleFailJson, r"We failed to configure the management interface."): with mock.patch(self.REQ_FUNC, return_value=(300, dict(ipv4Enabled=False, retcode="4", errorMessage=""))): mgmt_interface.update_array(settings, iface) def test_update_pass(self): """Validate update method completes.""" initial = { "state": "enable", "controller": "A", "channel": "1", "address": "192.168.1.1", "subnet_mask": "255.255.255.1", "config_method": "static", "ssh": "yes"} controller_request = [ {"physicalLocation": {"slot": 2}, "controllerRef": "070000000000000000000002", "networkSettings": {"remoteAccessEnabled": True}}, {"physicalLocation": {"slot": 1}, "controllerRef": "070000000000000000000001", "networkSettings": {"remoteAccessEnabled": False}}] expected = { "dns_servers": [{"ipv4Address": "10.1.0.20", "addressType": "ipv4"}, {"ipv4Address": "10.1.0.50", "addressType": "ipv4"}], "subnet_mask": "255.255.255.0", "ntp_servers": None, "ntp_config_method": "disabled", "controllerRef": "070000000000000000000001", "config_method": "configStatic", "enabled": True, "gateway": "10.1.1.1", "alias": "creG1g-AP-a", "controllerSlot": 1, "dns_config_method": "stat", "id": "2800070000000000000000000001000000000000", "address": "10.1.1.111", "ipv6Enabled": False, "channel": 1} self._set_args(initial) mgmt_interface = MgmtInterface() with self.assertRaisesRegexp(AnsibleExitJson, r"The interface settings have been updated."): with mock.patch(self.REQ_FUNC, side_effect=[(200, None), (200, controller_request), (200, self.TEST_DATA), (200, controller_request), (200, self.TEST_DATA)]): mgmt_interface.update()
mit
NaosProject/Naos.Serialization
Naos.Serialization.Test/.recipes/OBeautifulCode.Validation/Parameter.cs
2753
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Parameter.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode 2018. All rights reserved. // </copyright> // <auto-generated> // Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Validation source. // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- namespace OBeautifulCode.Validation.Recipes { using System; using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents a parameter that is being validated. /// </summary> #if !OBeautifulCodeValidationRecipesProject [System.Diagnostics.DebuggerStepThrough] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Validation", "See package version number")] internal #else public #endif class Parameter { /// <summary> /// Gets or sets the parameter value. /// </summary> public object Value { get; set; } /// <summary> /// Gets or sets the type of the value of the parameter. /// </summary> public Type ValueType { get; set; } /// <summary> /// Gets or sets the name of the parameter. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets a value indicating whether <see cref="ParameterValidator.Named{TParameterValue}(TParameterValue, string)"/> has been called. /// </summary> public bool HasBeenNamed { get; set; } /// <summary> /// Gets or sets a value indicating whether <see cref="ParameterValidator.Must{TParameterValue}(TParameterValue)"/> has been called. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Musted", Justification = "This is the best wording for this identifier.")] public bool HasBeenMusted { get; set; } /// <summary> /// Gets or sets a value indicating whether <see cref="ParameterValidator.Each(Parameter)"/> has been called. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eached", Justification = "This is the best wording for this identifier.")] public bool HasBeenEached { get; set; } /// <summary> /// Gets or sets a value indicating whether at least one validation has been performed on the paramter. /// </summary> public bool HasBeenValidated { get; set; } } }
mit
tizbac/mediacomMP82S4
kernel/drivers/misc/bp/chips/sc6610.c
6729
/* drivers/misc/bp/chips/sc6610.c * * Copyright (C) 2012-2015 ROCKCHIP. * Author: luowei <lw@rock-chips.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/i2c.h> #include <linux/irq.h> #include <linux/gpio.h> #include <linux/input.h> #include <linux/platform_device.h> #include <linux/fs.h> #include <linux/uaccess.h> #include <linux/miscdevice.h> #include <linux/circ_buf.h> #include <linux/interrupt.h> #include <linux/miscdevice.h> #include <mach/iomux.h> #include <mach/gpio.h> #include <asm/gpio.h> #include <linux/delay.h> #include <linux/poll.h> #include <linux/wait.h> #include <linux/wakelock.h> #include <linux/workqueue.h> #include <linux/slab.h> #include <linux/earlysuspend.h> #include <linux/bp-auto.h> #if 0 #define DBG(x...) printk(x) #else #define DBG(x...) #endif /****************operate according to bp chip:start************/ static int bp_active(struct bp_private_data *bp, int enable) { int result = 0; if(enable) { printk("<-----sc6610 power on-------->\n"); gpio_set_value(bp->ops->bp_power, GPIO_HIGH); } else { printk("<-----sc6610 power off-------->\n"); gpio_set_value(bp->ops->bp_power, GPIO_LOW); msleep(500); } return result; } static void ap_wake_bp_work(struct work_struct *work) { return; } static int bp_wake_ap(struct bp_private_data *bp) { int result = 0; printk("<-----sc6610 bp_wake_ap-------->\n"); bp->suspend_status = 0; wake_lock_timeout(&bp->bp_wakelock, 10 * HZ); return result; } static int bp_init(struct bp_private_data *bp) { int result = 0; gpio_direction_input(bp->ops->bp_wakeup_ap); gpio_direction_output(bp->ops->bp_power,GPIO_LOW); gpio_direction_output(bp->ops->ap_wakeup_bp,GPIO_HIGH); INIT_DELAYED_WORK(&bp->wakeup_work, ap_wake_bp_work); return result; } static int bp_reset(struct bp_private_data *bp) { printk("ioctrl sc6610 reset !!! \n"); gpio_set_value(bp->ops->bp_power, GPIO_LOW); msleep(2000); gpio_set_value(bp->ops->bp_power, GPIO_HIGH); return 0; } static int bp_shutdown(struct bp_private_data *bp) { int result = 0; if(bp->ops->active) bp->ops->active(bp, 0); cancel_delayed_work_sync(&bp->wakeup_work); return result; } static int bp_suspend(struct bp_private_data *bp) { int result = 0; bp->suspend_status = 1; gpio_set_value(bp->ops->ap_wakeup_bp, GPIO_LOW); return result; } static int bp_resume(struct bp_private_data *bp) { printk("<-----sc6610 bp_resume-------->\n"); bp->suspend_status = 0; gpio_set_value(bp->ops->ap_wakeup_bp, GPIO_HIGH); return 0; } struct bp_operate bp_sc6610_ops = { #if defined(CONFIG_ARCH_RK2928) .name = "sc6610", .bp_id = BP_ID_SC6610, .bp_bus = BP_BUS_TYPE_UART, .bp_pid = 0, .bp_vid = 0, .bp_power = RK2928_PIN3_PC2, // 3g_power .bp_en = BP_UNKNOW_DATA, // 3g_en .bp_reset = BP_UNKNOW_DATA, .ap_ready = BP_UNKNOW_DATA, // .bp_ready = BP_UNKNOW_DATA, .ap_wakeup_bp = RK2928_PIN3_PC4, .bp_wakeup_ap = RK2928_PIN3_PC3, // .bp_uart_en = BP_UNKNOW_DATA, //EINT9 .bp_usb_en = BP_UNKNOW_DATA, //W_disable .bp_assert = RK2928_PIN3_PC5, .trig = IRQF_TRIGGER_RISING, .active = bp_active, .init = bp_init, .reset = bp_reset, .ap_wake_bp = NULL, .bp_wake_ap = bp_wake_ap, .shutdown = bp_shutdown, .read_status = NULL, .write_status = NULL, .suspend = bp_suspend, .resume = bp_resume, .misc_name = NULL, .private_miscdev = NULL, #elif defined(CONFIG_ARCH_RK30) .name = "sc6610", .bp_id = BP_ID_SC6610, .bp_bus = BP_BUS_TYPE_UART, .bp_pid = 0, .bp_vid = 0, .bp_power = BP_UNKNOW_DATA, // RK2928_PIN3_PC2, // 3g_power .bp_en = BP_UNKNOW_DATA, // 3g_en .bp_reset = BP_UNKNOW_DATA, .ap_ready = BP_UNKNOW_DATA, // .bp_ready = BP_UNKNOW_DATA, .ap_wakeup_bp = BP_UNKNOW_DATA, // RK2928_PIN3_PC4, .bp_wakeup_ap = BP_UNKNOW_DATA, // RK2928_PIN3_PC3, // .bp_uart_en = BP_UNKNOW_DATA, //EINT9 .bp_usb_en = BP_UNKNOW_DATA, //W_disable .bp_assert = BP_UNKNOW_DATA, // RK2928_PIN3_PC5, .trig = IRQF_TRIGGER_RISING, .active = bp_active, .init = bp_init, .reset = bp_reset, .ap_wake_bp = NULL, .bp_wake_ap = bp_wake_ap, .shutdown = bp_shutdown, .read_status = NULL, .write_status = NULL, .suspend = bp_suspend, .resume = bp_resume, .misc_name = NULL, .private_miscdev = NULL, #else .name = "sc6610", .bp_id = BP_ID_SC6610, .bp_bus = BP_BUS_TYPE_UART, .bp_pid = 0, .bp_vid = 0, .bp_power = BP_UNKNOW_DATA, // RK2928_PIN3_PC2, // 3g_power .bp_en = BP_UNKNOW_DATA, // 3g_en .bp_reset = BP_UNKNOW_DATA, .ap_ready = BP_UNKNOW_DATA, // .bp_ready = BP_UNKNOW_DATA, .ap_wakeup_bp = BP_UNKNOW_DATA, // RK2928_PIN3_PC4, .bp_wakeup_ap = BP_UNKNOW_DATA, // RK2928_PIN3_PC3, // .bp_uart_en = BP_UNKNOW_DATA, //EINT9 .bp_usb_en = BP_UNKNOW_DATA, //W_disable .bp_assert = BP_UNKNOW_DATA, // RK2928_PIN3_PC5, .trig = IRQF_TRIGGER_RISING, .active = bp_active, .init = bp_init, .reset = bp_reset, .ap_wake_bp = NULL, .bp_wake_ap = bp_wake_ap, .shutdown = bp_shutdown, .read_status = NULL, .write_status = NULL, .suspend = bp_suspend, .resume = bp_resume, .misc_name = NULL, .private_miscdev = NULL, #endif }; /****************operate according to bp chip:end************/ //function name should not be changed static struct bp_operate *bp_get_ops(void) { return &bp_sc6610_ops; } static int __init bp_sc6610_init(void) { struct bp_operate *ops = bp_get_ops(); int result = 0; result = bp_register_slave(NULL, NULL, bp_get_ops); if(result) { return result; } if(ops->private_miscdev) { result = misc_register(ops->private_miscdev); if (result < 0) { printk("%s:misc_register err\n",__func__); return result; } } DBG("%s\n",__func__); return result; } static void __exit bp_sc6610_exit(void) { //struct bp_operate *ops = bp_get_ops(); bp_unregister_slave(NULL, NULL, bp_get_ops); } subsys_initcall(bp_sc6610_init); module_exit(bp_sc6610_exit);
gpl-2.0
DDTChen/CookieVLC
vlc/contrib/android/live555/liveMedia/QCELPAudioRTPSource.cpp
16387
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved. // Qualcomm "PureVoice" (aka. "QCELP") Audio RTP Sources // Implementation #include "QCELPAudioRTPSource.hh" #include "MultiFramedRTPSource.hh" #include "FramedFilter.hh" #include <string.h> #include <stdlib.h> // This source is implemented internally by two separate sources: // (i) a RTP source for the raw (interleaved) QCELP frames, and // (ii) a deinterleaving filter that reads from this. // Define these two new classes here: class RawQCELPRTPSource: public MultiFramedRTPSource { public: static RawQCELPRTPSource* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency); unsigned char interleaveL() const { return fInterleaveL; } unsigned char interleaveN() const { return fInterleaveN; } unsigned char& frameIndex() { return fFrameIndex; } // index within pkt private: RawQCELPRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency); // called only by createNew() virtual ~RawQCELPRTPSource(); private: // redefined virtual functions: virtual Boolean processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize); virtual char const* MIMEtype() const; virtual Boolean hasBeenSynchronizedUsingRTCP(); private: unsigned char fInterleaveL, fInterleaveN, fFrameIndex; unsigned fNumSuccessiveSyncedPackets; }; class QCELPDeinterleaver: public FramedFilter { public: static QCELPDeinterleaver* createNew(UsageEnvironment& env, RawQCELPRTPSource* inputSource); private: QCELPDeinterleaver(UsageEnvironment& env, RawQCELPRTPSource* inputSource); // called only by "createNew()" virtual ~QCELPDeinterleaver(); static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); void afterGettingFrame1(unsigned frameSize, struct timeval presentationTime); private: // Redefined virtual functions: void doGetNextFrame(); virtual void doStopGettingFrames(); private: class QCELPDeinterleavingBuffer* fDeinterleavingBuffer; Boolean fNeedAFrame; }; ////////// QCELPAudioRTPSource implementation ////////// FramedSource* QCELPAudioRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs, RTPSource*& resultRTPSource, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) { RawQCELPRTPSource* rawRTPSource; resultRTPSource = rawRTPSource = RawQCELPRTPSource::createNew(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency); if (resultRTPSource == NULL) return NULL; QCELPDeinterleaver* deinterleaver = QCELPDeinterleaver::createNew(env, rawRTPSource); if (deinterleaver == NULL) { Medium::close(resultRTPSource); resultRTPSource = NULL; } return deinterleaver; } ////////// QCELPBufferedPacket and QCELPBufferedPacketFactory ////////// // A subclass of BufferedPacket, used to separate out QCELP frames. class QCELPBufferedPacket: public BufferedPacket { public: QCELPBufferedPacket(RawQCELPRTPSource& ourSource); virtual ~QCELPBufferedPacket(); private: // redefined virtual functions virtual unsigned nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize); private: RawQCELPRTPSource& fOurSource; }; class QCELPBufferedPacketFactory: public BufferedPacketFactory { private: // redefined virtual functions virtual BufferedPacket* createNewPacket(MultiFramedRTPSource* ourSource); }; ///////// RawQCELPRTPSource implementation //////// RawQCELPRTPSource* RawQCELPRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) { return new RawQCELPRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency); } RawQCELPRTPSource::RawQCELPRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat, unsigned rtpTimestampFrequency) : MultiFramedRTPSource(env, RTPgs, rtpPayloadFormat, rtpTimestampFrequency, new QCELPBufferedPacketFactory), fInterleaveL(0), fInterleaveN(0), fFrameIndex(0), fNumSuccessiveSyncedPackets(0) { } RawQCELPRTPSource::~RawQCELPRTPSource() { } Boolean RawQCELPRTPSource ::processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize) { unsigned char* headerStart = packet->data(); unsigned packetSize = packet->dataSize(); // First, check whether this packet's RTP timestamp is synchronized: if (RTPSource::hasBeenSynchronizedUsingRTCP()) { ++fNumSuccessiveSyncedPackets; } else { fNumSuccessiveSyncedPackets = 0; } // There's a 1-byte header indicating the interleave parameters if (packetSize < 1) return False; // Get the interleaving parameters from the 1-byte header, // and check them for validity: unsigned char const firstByte = headerStart[0]; unsigned char const interleaveL = (firstByte&0x38)>>3; unsigned char const interleaveN = firstByte&0x07; #ifdef DEBUG fprintf(stderr, "packetSize: %d, interleaveL: %d, interleaveN: %d\n", packetSize, interleaveL, interleaveN); #endif if (interleaveL > 5 || interleaveN > interleaveL) return False; //invalid fInterleaveL = interleaveL; fInterleaveN = interleaveN; fFrameIndex = 0; // initially resultSpecialHeaderSize = 1; return True; } char const* RawQCELPRTPSource::MIMEtype() const { return "audio/QCELP"; } Boolean RawQCELPRTPSource::hasBeenSynchronizedUsingRTCP() { // Don't report ourselves as being synchronized until we've received // at least a complete interleave cycle of synchronized packets. // This ensures that the receiver is currently getting a frame from // a packet that was synchronized. if (fNumSuccessiveSyncedPackets > (unsigned)(fInterleaveL+1)) { fNumSuccessiveSyncedPackets = fInterleaveL+2; // prevents overflow return True; } return False; } ///// QCELPBufferedPacket and QCELPBufferedPacketFactory implementation QCELPBufferedPacket::QCELPBufferedPacket(RawQCELPRTPSource& ourSource) : fOurSource(ourSource) { } QCELPBufferedPacket::~QCELPBufferedPacket() { } unsigned QCELPBufferedPacket:: nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize) { // The size of the QCELP frame is determined by the first byte: if (dataSize == 0) return 0; // sanity check unsigned char const firstByte = framePtr[0]; unsigned frameSize; switch (firstByte) { case 0: { frameSize = 1; break; } case 1: { frameSize = 4; break; } case 2: { frameSize = 8; break; } case 3: { frameSize = 17; break; } case 4: { frameSize = 35; break; } default: { frameSize = 0; break; } } #ifdef DEBUG fprintf(stderr, "QCELPBufferedPacket::nextEnclosedFrameSize(): frameSize: %d, dataSize: %d\n", frameSize, dataSize); #endif if (dataSize < frameSize) return 0; ++fOurSource.frameIndex(); return frameSize; } BufferedPacket* QCELPBufferedPacketFactory ::createNewPacket(MultiFramedRTPSource* ourSource) { return new QCELPBufferedPacket((RawQCELPRTPSource&)(*ourSource)); } ///////// QCELPDeinterleavingBuffer ///////// // (used to implement QCELPDeinterleaver) #define QCELP_MAX_FRAME_SIZE 35 #define QCELP_MAX_INTERLEAVE_L 5 #define QCELP_MAX_FRAMES_PER_PACKET 10 #define QCELP_MAX_INTERLEAVE_GROUP_SIZE \ ((QCELP_MAX_INTERLEAVE_L+1)*QCELP_MAX_FRAMES_PER_PACKET) class QCELPDeinterleavingBuffer { public: QCELPDeinterleavingBuffer(); virtual ~QCELPDeinterleavingBuffer(); void deliverIncomingFrame(unsigned frameSize, unsigned char interleaveL, unsigned char interleaveN, unsigned char frameIndex, unsigned short packetSeqNum, struct timeval presentationTime); Boolean retrieveFrame(unsigned char* to, unsigned maxSize, unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes, struct timeval& resultPresentationTime); unsigned char* inputBuffer() { return fInputBuffer; } unsigned inputBufferSize() const { return QCELP_MAX_FRAME_SIZE; } private: class FrameDescriptor { public: FrameDescriptor(); virtual ~FrameDescriptor(); unsigned frameSize; unsigned char* frameData; struct timeval presentationTime; }; // Use two banks of descriptors - one for incoming, one for outgoing FrameDescriptor fFrames[QCELP_MAX_INTERLEAVE_GROUP_SIZE][2]; unsigned char fIncomingBankId; // toggles between 0 and 1 unsigned char fIncomingBinMax; // in the incoming bank unsigned char fOutgoingBinMax; // in the outgoing bank unsigned char fNextOutgoingBin; Boolean fHaveSeenPackets; u_int16_t fLastPacketSeqNumForGroup; unsigned char* fInputBuffer; struct timeval fLastRetrievedPresentationTime; }; ////////// QCELPDeinterleaver implementation ///////// QCELPDeinterleaver* QCELPDeinterleaver::createNew(UsageEnvironment& env, RawQCELPRTPSource* inputSource) { return new QCELPDeinterleaver(env, inputSource); } QCELPDeinterleaver::QCELPDeinterleaver(UsageEnvironment& env, RawQCELPRTPSource* inputSource) : FramedFilter(env, inputSource), fNeedAFrame(False) { fDeinterleavingBuffer = new QCELPDeinterleavingBuffer(); } QCELPDeinterleaver::~QCELPDeinterleaver() { delete fDeinterleavingBuffer; } static unsigned const uSecsPerFrame = 20000; // 20 ms void QCELPDeinterleaver::doGetNextFrame() { // First, try getting a frame from the deinterleaving buffer: if (fDeinterleavingBuffer->retrieveFrame(fTo, fMaxSize, fFrameSize, fNumTruncatedBytes, fPresentationTime)) { // Success! fNeedAFrame = False; fDurationInMicroseconds = uSecsPerFrame; // Call our own 'after getting' function. Because we're not a 'leaf' // source, we can call this directly, without risking // infinite recursion afterGetting(this); return; } // No luck, so ask our source for help: fNeedAFrame = True; if (!fInputSource->isCurrentlyAwaitingData()) { fInputSource->getNextFrame(fDeinterleavingBuffer->inputBuffer(), fDeinterleavingBuffer->inputBufferSize(), afterGettingFrame, this, FramedSource::handleClosure, this); } } void QCELPDeinterleaver::doStopGettingFrames() { fNeedAFrame = False; fInputSource->stopGettingFrames(); } void QCELPDeinterleaver ::afterGettingFrame(void* clientData, unsigned frameSize, unsigned /*numTruncatedBytes*/, struct timeval presentationTime, unsigned /*durationInMicroseconds*/) { QCELPDeinterleaver* deinterleaver = (QCELPDeinterleaver*)clientData; deinterleaver->afterGettingFrame1(frameSize, presentationTime); } void QCELPDeinterleaver ::afterGettingFrame1(unsigned frameSize, struct timeval presentationTime) { RawQCELPRTPSource* source = (RawQCELPRTPSource*)fInputSource; // First, put the frame into our deinterleaving buffer: fDeinterleavingBuffer ->deliverIncomingFrame(frameSize, source->interleaveL(), source->interleaveN(), source->frameIndex(), source->curPacketRTPSeqNum(), presentationTime); // Then, try delivering a frame to the client (if he wants one): if (fNeedAFrame) doGetNextFrame(); } ////////// QCELPDeinterleavingBuffer implementation ///////// QCELPDeinterleavingBuffer::QCELPDeinterleavingBuffer() : fIncomingBankId(0), fIncomingBinMax(0), fOutgoingBinMax(0), fNextOutgoingBin(0), fHaveSeenPackets(False) { fInputBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE]; } QCELPDeinterleavingBuffer::~QCELPDeinterleavingBuffer() { delete[] fInputBuffer; } void QCELPDeinterleavingBuffer ::deliverIncomingFrame(unsigned frameSize, unsigned char interleaveL, unsigned char interleaveN, unsigned char frameIndex, unsigned short packetSeqNum, struct timeval presentationTime) { // First perform a sanity check on the parameters: // (This is overkill, as the source should have already done this.) if (frameSize > QCELP_MAX_FRAME_SIZE || interleaveL > QCELP_MAX_INTERLEAVE_L || interleaveN > interleaveL || frameIndex == 0 || frameIndex > QCELP_MAX_FRAMES_PER_PACKET) { #ifdef DEBUG fprintf(stderr, "QCELPDeinterleavingBuffer::deliverIncomingFrame() param sanity check failed (%d,%d,%d,%d)\n", frameSize, interleaveL, interleaveN, frameIndex); #endif return; } // The input "presentationTime" was that of the first frame in this // packet. Update it for the current frame: unsigned uSecIncrement = (frameIndex-1)*(interleaveL+1)*uSecsPerFrame; presentationTime.tv_usec += uSecIncrement; presentationTime.tv_sec += presentationTime.tv_usec/1000000; presentationTime.tv_usec = presentationTime.tv_usec%1000000; // Next, check whether this packet is part of a new interleave group if (!fHaveSeenPackets || seqNumLT(fLastPacketSeqNumForGroup, packetSeqNum)) { // We've moved to a new interleave group fHaveSeenPackets = True; fLastPacketSeqNumForGroup = packetSeqNum + interleaveL - interleaveN; // Switch the incoming and outgoing banks: fIncomingBankId ^= 1; unsigned char tmp = fIncomingBinMax; fIncomingBinMax = fOutgoingBinMax; fOutgoingBinMax = tmp; fNextOutgoingBin = 0; } // Now move the incoming frame into the appropriate bin: unsigned const binNumber = interleaveN + (frameIndex-1)*(interleaveL+1); FrameDescriptor& inBin = fFrames[binNumber][fIncomingBankId]; unsigned char* curBuffer = inBin.frameData; inBin.frameData = fInputBuffer; inBin.frameSize = frameSize; inBin.presentationTime = presentationTime; if (curBuffer == NULL) curBuffer = new unsigned char[QCELP_MAX_FRAME_SIZE]; fInputBuffer = curBuffer; if (binNumber >= fIncomingBinMax) { fIncomingBinMax = binNumber + 1; } } Boolean QCELPDeinterleavingBuffer ::retrieveFrame(unsigned char* to, unsigned maxSize, unsigned& resultFrameSize, unsigned& resultNumTruncatedBytes, struct timeval& resultPresentationTime) { if (fNextOutgoingBin >= fOutgoingBinMax) return False; // none left FrameDescriptor& outBin = fFrames[fNextOutgoingBin][fIncomingBankId^1]; unsigned char* fromPtr; unsigned char fromSize = outBin.frameSize; outBin.frameSize = 0; // for the next time this bin is used // Check whether this frame is missing; if so, return an 'erasure' frame: unsigned char erasure = 14; if (fromSize == 0) { fromPtr = &erasure; fromSize = 1; // Compute this erasure frame's presentation time via extrapolation: resultPresentationTime = fLastRetrievedPresentationTime; resultPresentationTime.tv_usec += uSecsPerFrame; if (resultPresentationTime.tv_usec >= 1000000) { ++resultPresentationTime.tv_sec; resultPresentationTime.tv_usec -= 1000000; } } else { // Normal case - a frame exists: fromPtr = outBin.frameData; resultPresentationTime = outBin.presentationTime; } fLastRetrievedPresentationTime = resultPresentationTime; if (fromSize > maxSize) { resultNumTruncatedBytes = fromSize - maxSize; resultFrameSize = maxSize; } else { resultNumTruncatedBytes = 0; resultFrameSize = fromSize; } memmove(to, fromPtr, resultFrameSize); ++fNextOutgoingBin; return True; } QCELPDeinterleavingBuffer::FrameDescriptor::FrameDescriptor() : frameSize(0), frameData(NULL) { } QCELPDeinterleavingBuffer::FrameDescriptor::~FrameDescriptor() { delete[] frameData; }
gpl-2.0
ghmajx/asuswrt-merlin
release/src/router/samba-3.5.8/source4/dsdb/schema/schema_convert_to_ol.c
10025
/* schema conversion routines Copyright (C) Andrew Bartlett 2006-2008 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "ldb.h" #include "dsdb/samdb/samdb.h" #include "system/locale.h" #define SEPERATOR "\n " struct attr_map { char *old_attr; char *new_attr; }; struct oid_map { char *old_oid; char *new_oid; }; static char *print_schema_recursive(char *append_to_string, struct dsdb_schema *schema, const char *print_class, enum dsdb_schema_convert_target target, const char **attrs_skip, const struct attr_map *attr_map, const struct oid_map *oid_map) { char *out = append_to_string; const struct dsdb_class *objectclass; objectclass = dsdb_class_by_lDAPDisplayName(schema, print_class); if (!objectclass) { DEBUG(0, ("Cannot find class %s in schema\n", print_class)); return NULL; } do { TALLOC_CTX *mem_ctx = talloc_new(append_to_string); const char *name = objectclass->lDAPDisplayName; const char *oid = objectclass->governsID_oid; const char *subClassOf = objectclass->subClassOf; int objectClassCategory = objectclass->objectClassCategory; const char **must; const char **may; char *schema_entry = NULL; struct ldb_val objectclass_name_as_ldb_val = data_blob_string_const(objectclass->lDAPDisplayName); struct ldb_message_element objectclass_name_as_el = { .name = "objectClass", .num_values = 1, .values = &objectclass_name_as_ldb_val }; int j; int attr_idx; if (!mem_ctx) { DEBUG(0, ("Failed to create new talloc context\n")); return NULL; } /* We have been asked to skip some attributes/objectClasses */ if (attrs_skip && str_list_check_ci(attrs_skip, name)) { continue; } /* We might have been asked to remap this oid, due to a conflict */ for (j=0; oid_map && oid_map[j].old_oid; j++) { if (strcasecmp(oid, oid_map[j].old_oid) == 0) { oid = oid_map[j].new_oid; break; } } /* We might have been asked to remap this name, due to a conflict */ for (j=0; name && attr_map && attr_map[j].old_attr; j++) { if (strcasecmp(name, attr_map[j].old_attr) == 0) { name = attr_map[j].new_attr; break; } } may = dsdb_full_attribute_list(mem_ctx, schema, &objectclass_name_as_el, DSDB_SCHEMA_ALL_MAY); for (j=0; may && may[j]; j++) { /* We might have been asked to remap this name, due to a conflict */ for (attr_idx=0; attr_map && attr_map[attr_idx].old_attr; attr_idx++) { if (strcasecmp(may[j], attr_map[attr_idx].old_attr) == 0) { may[j] = attr_map[attr_idx].new_attr; break; } } } must = dsdb_full_attribute_list(mem_ctx, schema, &objectclass_name_as_el, DSDB_SCHEMA_ALL_MUST); for (j=0; must && must[j]; j++) { /* We might have been asked to remap this name, due to a conflict */ for (attr_idx=0; attr_map && attr_map[attr_idx].old_attr; attr_idx++) { if (strcasecmp(must[j], attr_map[attr_idx].old_attr) == 0) { must[j] = attr_map[attr_idx].new_attr; break; } } } schema_entry = schema_class_description(mem_ctx, target, SEPERATOR, oid, name, NULL, subClassOf, objectClassCategory, must, may, NULL); if (schema_entry == NULL) { DEBUG(0, ("failed to generate schema description for %s\n", name)); return NULL; } switch (target) { case TARGET_OPENLDAP: out = talloc_asprintf_append(out, "objectclass %s\n\n", schema_entry); break; case TARGET_FEDORA_DS: out = talloc_asprintf_append(out, "objectClasses: %s\n", schema_entry); break; } talloc_free(mem_ctx); } while (0); for (objectclass=schema->classes; objectclass; objectclass = objectclass->next) { if (ldb_attr_cmp(objectclass->subClassOf, print_class) == 0 && ldb_attr_cmp(objectclass->lDAPDisplayName, print_class) != 0) { out = print_schema_recursive(out, schema, objectclass->lDAPDisplayName, target, attrs_skip, attr_map, oid_map); } } return out; } /* Routine to linearise our internal schema into the format that OpenLDAP and Fedora DS use for their backend. The 'mappings' are of a format like: #Standard OpenLDAP attributes labeledURI #The memberOf plugin provides this attribute memberOf #These conflict with OpenLDAP builtins attributeTypes:samba4AttributeTypes 2.5.21.5:1.3.6.1.4.1.7165.4.255.7 */ char *dsdb_convert_schema_to_openldap(struct ldb_context *ldb, char *target_str, const char *mappings) { /* Read list of attributes to skip, OIDs to map */ TALLOC_CTX *mem_ctx = talloc_new(ldb); char *line; char *out; const char **attrs_skip = NULL; int num_skip = 0; struct oid_map *oid_map = NULL; int num_oid_maps = 0; struct attr_map *attr_map = NULL; int num_attr_maps = 0; struct dsdb_attribute *attribute; struct dsdb_schema *schema; enum dsdb_schema_convert_target target; char *next_line = talloc_strdup(mem_ctx, mappings); if (!target_str || strcasecmp(target_str, "openldap") == 0) { target = TARGET_OPENLDAP; } else if (strcasecmp(target_str, "fedora-ds") == 0) { target = TARGET_FEDORA_DS; } else { DEBUG(0, ("Invalid target type for schema conversion %s\n", target_str)); return NULL; } /* The mappings are line-seperated, and specify details such as OIDs to skip etc */ while (1) { line = next_line; next_line = strchr(line, '\n'); if (!next_line) { break; } next_line[0] = '\0'; next_line++; /* Blank Line */ if (line[0] == '\0') { continue; } /* Comment */ if (line[0] == '#') { continue; } if (isdigit(line[0])) { char *p = strchr(line, ':'); if (!p) { DEBUG(0, ("schema mapping file line has OID but no OID to map to: %s\n", line)); return NULL; } p[0] = '\0'; p++; oid_map = talloc_realloc(mem_ctx, oid_map, struct oid_map, num_oid_maps + 2); trim_string(line, " ", " "); oid_map[num_oid_maps].old_oid = talloc_strdup(oid_map, line); trim_string(p, " ", " "); oid_map[num_oid_maps].new_oid = p; num_oid_maps++; oid_map[num_oid_maps].old_oid = NULL; } else { char *p = strchr(line, ':'); if (p) { /* remap attribute/objectClass */ p[0] = '\0'; p++; attr_map = talloc_realloc(mem_ctx, attr_map, struct attr_map, num_attr_maps + 2); trim_string(line, " ", " "); attr_map[num_attr_maps].old_attr = talloc_strdup(attr_map, line); trim_string(p, " ", " "); attr_map[num_attr_maps].new_attr = p; num_attr_maps++; attr_map[num_attr_maps].old_attr = NULL; } else { /* skip attribute/objectClass */ attrs_skip = talloc_realloc(mem_ctx, attrs_skip, const char *, num_skip + 2); trim_string(line, " ", " "); attrs_skip[num_skip] = talloc_strdup(attrs_skip, line); num_skip++; attrs_skip[num_skip] = NULL; } } } schema = dsdb_get_schema(ldb); if (!schema) { DEBUG(0, ("No schema on ldb to convert!\n")); return NULL; } switch (target) { case TARGET_OPENLDAP: out = talloc_strdup(mem_ctx, ""); break; case TARGET_FEDORA_DS: out = talloc_strdup(mem_ctx, "dn: cn=schema\n"); break; } for (attribute=schema->attributes; attribute; attribute = attribute->next) { const char *name = attribute->lDAPDisplayName; const char *oid = attribute->attributeID_oid; const char *syntax = attribute->attributeSyntax_oid; const char *equality = NULL, *substring = NULL; bool single_value = attribute->isSingleValued; char *schema_entry = NULL; int j; /* We have been asked to skip some attributes/objectClasses */ if (attrs_skip && str_list_check_ci(attrs_skip, name)) { continue; } /* We might have been asked to remap this oid, due to a conflict */ for (j=0; oid && oid_map && oid_map[j].old_oid; j++) { if (strcasecmp(oid, oid_map[j].old_oid) == 0) { oid = oid_map[j].new_oid; break; } } if (attribute->syntax) { /* We might have been asked to remap this oid, * due to a conflict, or lack of * implementation */ syntax = attribute->syntax->ldap_oid; /* We might have been asked to remap this oid, due to a conflict */ for (j=0; syntax && oid_map && oid_map[j].old_oid; j++) { if (strcasecmp(syntax, oid_map[j].old_oid) == 0) { syntax = oid_map[j].new_oid; break; } } equality = attribute->syntax->equality; substring = attribute->syntax->substring; } /* We might have been asked to remap this name, due to a conflict */ for (j=0; name && attr_map && attr_map[j].old_attr; j++) { if (strcasecmp(name, attr_map[j].old_attr) == 0) { name = attr_map[j].new_attr; break; } } schema_entry = schema_attribute_description(mem_ctx, target, SEPERATOR, oid, name, equality, substring, syntax, single_value, false, NULL, NULL, NULL, NULL, false, false); if (schema_entry == NULL) { DEBUG(0, ("failed to generate attribute description for %s\n", name)); return NULL; } switch (target) { case TARGET_OPENLDAP: out = talloc_asprintf_append(out, "attributetype %s\n\n", schema_entry); break; case TARGET_FEDORA_DS: out = talloc_asprintf_append(out, "attributeTypes: %s\n", schema_entry); break; } } out = print_schema_recursive(out, schema, "top", target, attrs_skip, attr_map, oid_map); return out; }
gpl-2.0
MoKee/android_kernel_motorola_omap4-common
arch/arm/plat-omap/include/plat/serial.h
3767
/* * arch/arm/plat-omap/include/mach/serial.h * * Copyright (C) 2009 Texas Instruments * Addded OMAP4 support- Santosh Shilimkar <santosh.shilimkar@ti.com> * * 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 __ASM_ARCH_SERIAL_H #define __ASM_ARCH_SERIAL_H #include <linux/init.h> /* * Memory entry used for the DEBUG_LL UART configuration. See also * uncompress.h and debug-macro.S. * * Note that using a memory location for storing the UART configuration * has at least two limitations: * * 1. Kernel uncompress code cannot overlap OMAP_UART_INFO as the * uncompress code could then partially overwrite itself * 2. We assume printascii is called at least once before paging_init, * and addruart has a chance to read OMAP_UART_INFO */ #define OMAP_UART_INFO (PLAT_PHYS_OFFSET + 0x3ffc) /* OMAP1 serial ports */ #define OMAP1_UART1_BASE 0xfffb0000 #define OMAP1_UART2_BASE 0xfffb0800 #define OMAP1_UART3_BASE 0xfffb9800 /* OMAP2 serial ports */ #define OMAP2_UART1_BASE 0x4806a000 #define OMAP2_UART2_BASE 0x4806c000 #define OMAP2_UART3_BASE 0x4806e000 /* OMAP3 serial ports */ #define OMAP3_UART1_BASE OMAP2_UART1_BASE #define OMAP3_UART2_BASE OMAP2_UART2_BASE #define OMAP3_UART3_BASE 0x49020000 #define OMAP3_UART4_BASE 0x49042000 /* Only on 36xx */ /* OMAP4 serial ports */ #define OMAP4_UART1_BASE OMAP2_UART1_BASE #define OMAP4_UART2_BASE OMAP2_UART2_BASE #define OMAP4_UART3_BASE 0x48020000 #define OMAP4_UART4_BASE 0x4806e000 /* TI816X serial ports */ #define TI816X_UART1_BASE 0x48020000 #define TI816X_UART2_BASE 0x48022000 #define TI816X_UART3_BASE 0x48024000 /* External port on Zoom2/3 */ #define ZOOM_UART_BASE 0x10000000 #define ZOOM_UART_VIRT 0xfa400000 #define OMAP_PORT_SHIFT 2 #define OMAP7XX_PORT_SHIFT 0 #define ZOOM_PORT_SHIFT 1 #define OMAP1510_BASE_BAUD (12000000/16) #define OMAP16XX_BASE_BAUD (48000000/16) #define OMAP24XX_BASE_BAUD (48000000/16) /* * DEBUG_LL port encoding stored into the UART1 scratchpad register by * decomp_setup in uncompress.h */ #define OMAP1UART1 11 #define OMAP1UART2 12 #define OMAP1UART3 13 #define OMAP2UART1 21 #define OMAP2UART2 22 #define OMAP2UART3 23 #define OMAP3UART1 OMAP2UART1 #define OMAP3UART2 OMAP2UART2 #define OMAP3UART3 33 #define OMAP3UART4 34 /* Only on 36xx */ #define OMAP4UART1 OMAP2UART1 #define OMAP4UART2 OMAP2UART2 #define OMAP4UART3 43 #define OMAP4UART4 44 #define TI816XUART1 81 #define TI816XUART2 82 #define TI816XUART3 83 #define ZOOM_UART 95 /* Only on zoom2/3 */ /* This is only used by 8250.c for omap1510 */ #define is_omap_port(pt) ({int __ret = 0; \ if ((pt)->port.mapbase == OMAP1_UART1_BASE || \ (pt)->port.mapbase == OMAP1_UART2_BASE || \ (pt)->port.mapbase == OMAP1_UART3_BASE) \ __ret = 1; \ __ret; \ }) #ifndef __ASSEMBLER__ struct omap_board_data; struct omap_uart_port_info; struct omap_device_pad; extern void omap_serial_init(struct omap_uart_port_info *platform_data); extern void omap_serial_board_init(struct omap_uart_port_info *platform_data); extern void omap_serial_init_port(struct omap_board_data *bdata, struct omap_uart_port_info *platform_data); void __init omap_serial_init_port_pads(int id, struct omap_device_pad *pads, int size, struct omap_uart_port_info *info); extern u32 omap_uart_resume_idle(void); extern int omap_uart_wake(u8 id); extern int omap_uart_enable(u8 uart_num); extern int omap_uart_disable(u8 uart_num); #define MUX_PULL_UP ((1<<8) | (1<<4) | (1<<3) | (7)) void omap_rts_mux_write(u16 val, int num); #endif #endif
gpl-2.0
liaoqingwei/ltp
testcases/kernel/syscalls/setgroups/setgroups03.c
5762
/* * * Copyright (c) International Business Machines Corp., 2001 * * 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 */ /* * Test Name: setgroups03 * * Test Description: * Verify that, * 1. setgroups() fails with -1 and sets errno to EINVAL if the size * argument value is > NGROUPS * 2. setgroups() fails with -1 and sets errno to EPERM if the * calling process is not super-user. * * Expected Result: * setgroups() should fail with return value -1 and set expected errno. * * Algorithm: * Setup: * Setup signal handling. * Pause for SIGUSR1 if option specified. * * Test: * Loop if the proper options are given. * Execute system call * Check return code, if system call failed (return=-1) * if errno set == expected errno * Issue sys call fails with expected return value and errno. * Otherwise, * Issue sys call fails with unexpected errno. * Otherwise, * Issue sys call returns unexpected value. * * Cleanup: * Print errno log and/or timing stats if options given * * Usage: <for command-line> * setgroups03 [-c n] [-e] [-i n] [-I x] [-P x] [-t] * where, -c n : Run n copies concurrently. * -f : Turn off functionality Testing. * -i n : Execute test n times. * -I x : Execute test for x seconds. * -P x : Pause for x seconds between iterations. * -t : Turn on syscall timing. * * HISTORY * 07/2001 Ported by Wayne Boyer * * RESTRICTIONS: * This test should be executed by 'non-super-user' only. * */ #include <limits.h> #include <sys/types.h> #include <unistd.h> #include <errno.h> #include <pwd.h> #include <grp.h> #include "test.h" #include "compat_16.h" #define TESTUSER "nobody" char nobody_uid[] = "nobody"; struct passwd *ltpuser; TCID_DEFINE(setgroups03); int TST_TOTAL = 2; GID_T *groups_list; /* Array to hold gids for getgroups() */ int setup1(); /* setup function to test error EPERM */ void setup(); /* setup function for the test */ void cleanup(); /* cleanup function for the test */ struct test_case_t { /* test case struct. to hold ref. test cond's */ size_t gsize_add; int list; char *desc; int exp_errno; int (*setupfunc) (); } Test_cases[] = { { 1, 1, "Size is > sysconf(_SC_NGROUPS_MAX)", EINVAL, NULL}, { 0, 2, "Permission denied, not super-user", EPERM, setup1} }; int main(int ac, char **av) { int lc; int gidsetsize; /* total no. of groups */ int i; char *test_desc; /* test specific error message */ int ngroups_max = sysconf(_SC_NGROUPS_MAX); /* max no. of groups in the current system */ tst_parse_opts(ac, av, NULL, NULL); groups_list = malloc(ngroups_max * sizeof(GID_T)); if (groups_list == NULL) { tst_brkm(TBROK, NULL, "malloc failed to alloc %zu errno " " %d ", ngroups_max * sizeof(GID_T), errno); } setup(); for (lc = 0; TEST_LOOPING(lc); lc++) { tst_count = 0; for (i = 0; i < TST_TOTAL; i++) { if (Test_cases[i].setupfunc != NULL) { Test_cases[i].setupfunc(); } gidsetsize = ngroups_max + Test_cases[i].gsize_add; test_desc = Test_cases[i].desc; /* * Call setgroups() to test different test conditions * verify that it fails with -1 return value and * sets appropriate errno. */ TEST(SETGROUPS(cleanup, gidsetsize, groups_list)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "setgroups(%d) returned %ld, " "expected -1, errno=%d", gidsetsize, TEST_RETURN, Test_cases[i].exp_errno); continue; } if (TEST_ERRNO == Test_cases[i].exp_errno) { tst_resm(TPASS, "setgroups(%d) fails, %s, errno=%d", gidsetsize, test_desc, TEST_ERRNO); } else { tst_resm(TFAIL, "setgroups(%d) fails, %s, " "errno=%d, expected errno=%d", gidsetsize, test_desc, TEST_ERRNO, Test_cases[i].exp_errno); } } } cleanup(); tst_exit(); } /* * setup() - performs all ONE TIME setup for this test. * * Call individual test specific setup functions. */ void setup(void) { tst_require_root(); tst_sig(NOFORK, DEF_HANDLER, cleanup); TEST_PAUSE; } /* * setup1 - Setup function to test setgroups() which returns -1 * and sets errno to EPERM. * * Get the user info. from /etc/passwd file. * This function returns 0 on success. */ int setup1(void) { struct passwd *user_info; /* struct. to hold test user info */ /* Switch to nobody user for correct error code collection */ ltpuser = getpwnam(nobody_uid); if (seteuid(ltpuser->pw_uid) == -1) { tst_resm(TINFO, "setreuid failed to " "to set the effective uid to %d", ltpuser->pw_uid); perror("setreuid"); } if ((user_info = getpwnam(TESTUSER)) == NULL) { tst_brkm(TFAIL, cleanup, "getpwnam(2) of %s Failed", TESTUSER); } if (!GID_SIZE_CHECK(user_info->pw_gid)) { tst_brkm(TBROK, cleanup, "gid returned from getpwnam is too large for testing setgroups16"); } groups_list[0] = user_info->pw_gid; return 0; } /* * cleanup() - performs all ONE TIME cleanup for this test at * completion or premature exit. */ void cleanup(void) { }
gpl-2.0
johnparker007/mame
src/devices/sound/zsg2.h
2381
// license:BSD-3-Clause // copyright-holders:Olivier Galibert, R. Belmont, hap, superctr /* ZOOM ZSG-2 custom wavetable synthesizer */ #ifndef MAME_SOUND_ZSG2_H #define MAME_SOUND_ZSG2_H #pragma once // ======================> zsg2_device class zsg2_device : public device_t, public device_sound_interface { public: zsg2_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock); // configuration helpers auto ext_read() { return m_ext_read_handler.bind(); } uint16_t read(offs_t offset, uint16_t mem_mask = ~0); void write(offs_t offset, uint16_t data, uint16_t mem_mask = ~0); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; // sound stream update overrides virtual void sound_stream_update(sound_stream &stream, std::vector<read_stream_view> const &inputs, std::vector<write_stream_view> &outputs) override; private: const uint16_t STATUS_ACTIVE = 0x8000; // 16 registers per channel, 48 channels struct zchan { uint16_t v[16]; uint16_t status; uint32_t cur_pos; uint32_t step_ptr; uint32_t step; uint32_t start_pos; uint32_t end_pos; uint32_t loop_pos; uint32_t page; uint16_t vol; uint16_t vol_initial; uint16_t vol_target; int16_t vol_delta; uint16_t output_cutoff; uint16_t output_cutoff_initial; uint16_t output_cutoff_target; int16_t output_cutoff_delta; int32_t emphasis_filter_state; int32_t output_filter_state; // Attenuation for output channels uint8_t output_gain[4]; int16_t samples[5]; // +1 history }; uint16_t m_gain_tab[256]; uint16_t m_reg[32]; zchan m_chan[48]; uint32_t m_sample_count; required_region_ptr<uint32_t> m_mem_base; uint32_t m_read_address; std::unique_ptr<uint32_t[]> m_mem_copy; uint32_t m_mem_blocks; std::unique_ptr<int16_t[]> m_full_samples; sound_stream *m_stream; devcb_read32 m_ext_read_handler; uint32_t read_memory(uint32_t offset); void chan_w(int ch, int reg, uint16_t data); uint16_t chan_r(int ch, int reg); void control_w(int reg, uint16_t data); uint16_t control_r(int reg); int16_t *prepare_samples(uint32_t offset); void filter_samples(zchan *ch); int16_t get_ramp(uint8_t val); inline uint16_t ramp(uint16_t current, uint16_t target, int16_t delta); }; DECLARE_DEVICE_TYPE(ZSG2, zsg2_device) #endif // MAME_SOUND_ZSG2_H
gpl-2.0
frenos/wireshark
epan/dissectors/packet-oipf.c
6404
/* packet-oipf.c * Dissector for Open IPTV Forum protocols * Copyright 2012, Martin Kaiser <martin@kaiser.cx> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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. */ /* This dissector supports the CI+ Content and Service Protection Gateway (CSPG-CI+) as defined in in Open IPTV Forum Specification Volume 7 V2.1 http://www.openiptvforum.org/release_2.html */ #include "config.h" #include <epan/packet.h> void proto_register_oipf(void); void proto_reg_handoff_oipf(void); static int proto_oipf_ciplus = -1; static gint ett_oipf_ciplus = -1; static int hf_oipf_ciplus_cmd_id = -1; static int hf_oipf_ciplus_ca_sys_id = -1; static int hf_oipf_ciplus_trx_id = -1; static int hf_oipf_ciplus_send_datatype_nbr = -1; static int hf_oipf_ciplus_dat_id = -1; static int hf_oipf_ciplus_dat_len = -1; static int hf_oipf_ciplus_data = -1; /* the application id for this protocol in the CI+ SAS resource this is actually a 64bit hex number, we can't use a 64bit number as a key for the dissector table directly, we have to process it as a string (the string must not be a local variable as glib stores a pointer to it in the hash table) */ static const gchar sas_app_id_str_oipf[] = "0x0108113101190000"; static const value_string oipf_ciplus_cmd_id[] = { { 0x01, "send_msg" }, { 0x02, "reply_msg" }, { 0x03, "parental_control_info" }, { 0x04, "rights_info" }, { 0x05, "system_info" }, { 0, NULL } }; static const value_string oipf_ciplus_dat_id[] = { { 0x01, "oipf_ca_vendor_specific_information" }, { 0x02, "oipf_country_code" }, { 0x03, "oipf_parental_control_url" }, { 0x04, "oipf_rating_type" }, { 0x05, "oipf_rating_value" }, { 0x06, "oipf_rights_issuer_url" }, { 0x07, "oipf_access_status" }, { 0x08, "oipf_status" }, { 0, NULL } }; static int dissect_oipf_ciplus(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_) { gint msg_len; proto_tree *oipf_ciplus_tree; guint offset = 0; guint8 i, send_datatype_nbr; guint16 dat_len; /* an OIPF CI+ message minimally contains command_id (1 byte), ca sys id (2 bytes), transaction id (4 bytes) and number of sent datatypes (1 byte) */ msg_len = tvb_reported_length(tvb); if (msg_len < 8) return 0; oipf_ciplus_tree = proto_tree_add_subtree(tree, tvb, 0, msg_len, ett_oipf_ciplus, NULL, "Open IPTV Forum CSPG-CI+"); proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_cmd_id, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_ca_sys_id, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_trx_id, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; send_datatype_nbr = tvb_get_guint8(tvb, offset); proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_send_datatype_nbr, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; for (i=0; i<send_datatype_nbr; i++) { proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_dat_id, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; dat_len = tvb_get_ntohs(tvb, offset); proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_dat_len, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(oipf_ciplus_tree, hf_oipf_ciplus_data, tvb, offset, dat_len, ENC_NA); offset += dat_len; } return offset; } void proto_register_oipf(void) { static gint *ett[] = { &ett_oipf_ciplus }; static hf_register_info hf[] = { { &hf_oipf_ciplus_cmd_id, { "Command ID", "oipf.ciplus.cmd_id", FT_UINT8, BASE_HEX, VALS(oipf_ciplus_cmd_id), 0, NULL, HFILL } }, { &hf_oipf_ciplus_ca_sys_id, { "CA system ID", "oipf.ciplus.ca_system_id", FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_oipf_ciplus_trx_id, { "Transaction ID", "oipf.ciplus.transaction_id", FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_oipf_ciplus_send_datatype_nbr, { "Number of data items", "oipf.ciplus.num_items", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_oipf_ciplus_dat_id, { "Datatype ID", "oipf.ciplus.datatype_id", FT_UINT8, BASE_HEX, VALS(oipf_ciplus_dat_id), 0, NULL, HFILL } }, { &hf_oipf_ciplus_dat_len, { "Datatype length", "oipf.ciplus.datatype_len", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_oipf_ciplus_data, { "Data", "oipf.ciplus.data", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } } }; proto_oipf_ciplus = proto_register_protocol( "Open IPTV Forum CSPG-CI+", "OIPF CI+", "oipf.ciplus"); proto_register_field_array(proto_oipf_ciplus, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_oipf(void) { dissector_handle_t oipf_ciplus_handle; oipf_ciplus_handle = new_create_dissector_handle(dissect_oipf_ciplus, proto_oipf_ciplus); dissector_add_string("dvb-ci.sas.app_id_str", sas_app_id_str_oipf, oipf_ciplus_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
gpl-2.0
DirtyDevs/android_kernel_motorola_ghost
sound/soc/msm/msm8960.c
69042
/* Copyright (c) 2011-2013 The Linux Foundation. All rights reserved. * Copyright (c) 2013, Motorola Mobility LLC * * 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/clk.h> #include <linux/delay.h> #include <linux/gpio.h> #include <linux/mfd/pm8xxx/pm8921.h> #include <linux/platform_device.h> #include <linux/mfd/pm8xxx/pm8921.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/of_gpio.h> #include <sound/core.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/pcm.h> #include <sound/jack.h> #include <asm/mach-types.h> #include <mach/socinfo.h> #include <linux/mfd/wcd9xxx/core.h> #include <linux/input.h> #include "msm-pcm-routing.h" #include <sound/msm-dai-q6.h> #include "../codecs/wcd9310.h" #ifdef CONFIG_SND_SOC_TPA6165A2 #include "../codecs/tpa6165a2-core.h" #endif /* 8960 machine driver */ #define PM8921_GPIO_BASE NR_GPIO_IRQS #define PM8921_IRQ_BASE (NR_MSM_IRQS + NR_GPIO_IRQS) #define PM8921_GPIO_PM_TO_SYS(pm_gpio) (pm_gpio - 1 + PM8921_GPIO_BASE) #define MSM8960_SPK_ON 1 #define MSM8960_SPK_OFF 0 #define msm8960_SLIM_0_RX_MAX_CHANNELS 2 #define msm8960_SLIM_0_TX_MAX_CHANNELS 4 #define SAMPLE_RATE_8KHZ 8000 #define SAMPLE_RATE_16KHZ 16000 #define BOTTOM_SPK_AMP_POS 0x1 #define BOTTOM_SPK_AMP_NEG 0x2 #define TOP_SPK_AMP_POS 0x4 #define TOP_SPK_AMP_NEG 0x8 #define TOP_SPK_AMP 0x10 #define GPIO_AUX_PCM_DOUT 63 #define GPIO_AUX_PCM_DIN 64 #define GPIO_AUX_PCM_SYNC 65 #define GPIO_AUX_PCM_CLK 66 #define TABLA_EXT_CLK_RATE 12288000 #define TABLA_MBHC_DEF_BUTTONS 8 #define TABLA_MBHC_DEF_RLOADS 5 #define JACK_DETECT_GPIO 38 #define JACK_DETECT_INT PM8921_GPIO_IRQ(PM8921_IRQ_BASE, JACK_DETECT_GPIO) #define JACK_US_EURO_SEL_GPIO 35 struct msm8960_asoc_mach_data { struct gpio *pri_i2s_gpios; unsigned int num_pri_i2s_gpios; struct gpio *mi2s_gpios; unsigned int num_mi2s_gpios; }; static u32 top_spk_pamp_gpio = PM8921_GPIO_PM_TO_SYS(18); static u32 bottom_spk_pamp_gpio = PM8921_GPIO_PM_TO_SYS(19); static int msm8960_spk_control; static int msm8960_ext_bottom_spk_pamp; static int msm8960_ext_top_spk_pamp; static int msm8960_slim_0_rx_ch = 1; static int msm8960_slim_0_tx_ch = 1; static int msm8960_btsco_rate = SAMPLE_RATE_8KHZ; static int msm8960_btsco_ch = 1; static int hdmi_rate_variable; static int msm_hdmi_rx_ch = 2; static int msm8960_auxpcm_rate = SAMPLE_RATE_8KHZ; static struct clk *mi2s_rx_osr_clk; static struct clk *mi2s_rx_bit_clk; static atomic_t mi2s_rsc_ref; static struct clk *pri_i2s_tx_bit_clk; static struct clk *pri_i2s_tx_osr_clk; static struct clk *codec_clk; static int clk_users; static int msm8960_headset_gpios_configured; static struct snd_soc_jack hs_jack; static struct snd_soc_jack button_jack; static atomic_t auxpcm_rsc_ref; static bool hs_detect_use_gpio; module_param(hs_detect_use_gpio, bool, 0444); MODULE_PARM_DESC(hs_detect_use_gpio, "Use GPIO for headset detection"); static bool hs_detect_extn_cable; module_param(hs_detect_extn_cable, bool, 0444); MODULE_PARM_DESC(hs_detect_extn_cable, "Enable extension cable feature"); static bool hs_detect_use_firmware; module_param(hs_detect_use_firmware, bool, 0444); MODULE_PARM_DESC(hs_detect_use_firmware, "Use firmware for headset detection"); static int msm8960_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable, bool dapm); static bool msm8960_swap_gnd_mic(struct snd_soc_codec *codec); static struct tabla_mbhc_config mbhc_cfg = { .headset_jack = &hs_jack, .button_jack = &button_jack, .read_fw_bin = false, .calibration = NULL, .micbias = TABLA_MICBIAS2, .mclk_cb_fn = msm8960_enable_codec_ext_clk, .mclk_rate = TABLA_EXT_CLK_RATE, .gpio = 0, .gpio_irq = 0, .gpio_level_insert = 1, .swap_gnd_mic = NULL, .detect_extn_cable = false, }; static u32 us_euro_sel_gpio = PM8921_GPIO_PM_TO_SYS(JACK_US_EURO_SEL_GPIO); static struct mutex cdc_mclk_mutex; static void msm8960_enable_ext_spk_amp_gpio(u32 spk_amp_gpio) { int ret = 0; struct pm_gpio param = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S4, .out_strength = PM_GPIO_STRENGTH_MED, . function = PM_GPIO_FUNC_NORMAL, }; if (spk_amp_gpio == bottom_spk_pamp_gpio) { ret = gpio_request(bottom_spk_pamp_gpio, "BOTTOM_SPK_AMP"); if (ret) { pr_err("%s: Error requesting BOTTOM SPK AMP GPIO %u\n", __func__, bottom_spk_pamp_gpio); return; } ret = pm8xxx_gpio_config(bottom_spk_pamp_gpio, &param); if (ret) pr_err("%s: Failed to configure Bottom Spk Ampl" " gpio %u\n", __func__, bottom_spk_pamp_gpio); else { pr_debug("%s: enable Bottom spkr amp gpio\n", __func__); gpio_direction_output(bottom_spk_pamp_gpio, 1); } } else if (spk_amp_gpio == top_spk_pamp_gpio) { ret = gpio_request(top_spk_pamp_gpio, "TOP_SPK_AMP"); if (ret) { pr_err("%s: Error requesting GPIO %d\n", __func__, top_spk_pamp_gpio); return; } ret = pm8xxx_gpio_config(top_spk_pamp_gpio, &param); if (ret) pr_err("%s: Failed to configure Top Spk Ampl" " gpio %u\n", __func__, top_spk_pamp_gpio); else { pr_debug("%s: enable Top spkr amp gpio\n", __func__); gpio_direction_output(top_spk_pamp_gpio, 1); } } else { pr_err("%s: ERROR : Invalid External Speaker Ampl GPIO." " gpio = %u\n", __func__, spk_amp_gpio); return; } } static void msm8960_ext_spk_power_amp_on(u32 spk) { if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) { if ((msm8960_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) && (msm8960_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) { pr_debug("%s() External Bottom Speaker Ampl already " "turned on. spk = 0x%08x\n", __func__, spk); return; } msm8960_ext_bottom_spk_pamp |= spk; if ((msm8960_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) && (msm8960_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) { msm8960_enable_ext_spk_amp_gpio(bottom_spk_pamp_gpio); pr_debug("%s: slepping 4 ms after turning on external " " Bottom Speaker Ampl\n", __func__); usleep_range(4000, 4000); } } else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG | TOP_SPK_AMP)) { pr_debug("%s: top_spk_amp_state = 0x%x spk_event = 0x%x\n", __func__, msm8960_ext_top_spk_pamp, spk); if (((msm8960_ext_top_spk_pamp & TOP_SPK_AMP_POS) && (msm8960_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) || (msm8960_ext_top_spk_pamp & TOP_SPK_AMP)) { pr_debug("%s() External Top Speaker Ampl already" "turned on. spk = 0x%08x\n", __func__, spk); return; } msm8960_ext_top_spk_pamp |= spk; if (((msm8960_ext_top_spk_pamp & TOP_SPK_AMP_POS) && (msm8960_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) || (msm8960_ext_top_spk_pamp & TOP_SPK_AMP)) { msm8960_enable_ext_spk_amp_gpio(top_spk_pamp_gpio); pr_debug("%s: sleeping 4 ms after turning on " " external Top Speaker Ampl\n", __func__); usleep_range(4000, 4000); } } else { pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n", __func__, spk); return; } } static void msm8960_ext_spk_power_amp_off(u32 spk) { if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) { if (!msm8960_ext_bottom_spk_pamp) return; gpio_direction_output(bottom_spk_pamp_gpio, 0); gpio_free(bottom_spk_pamp_gpio); msm8960_ext_bottom_spk_pamp = 0; pr_debug("%s: sleeping 4 ms after turning off external Bottom" " Speaker Ampl\n", __func__); usleep_range(4000, 4000); } else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG | TOP_SPK_AMP)) { pr_debug("%s: top_spk_amp_state = 0x%x spk_event = 0x%x\n", __func__, msm8960_ext_top_spk_pamp, spk); if (!msm8960_ext_top_spk_pamp) return; if ((spk & TOP_SPK_AMP_POS) || (spk & TOP_SPK_AMP_NEG)) { msm8960_ext_top_spk_pamp &= (~(TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG)); } else if (spk & TOP_SPK_AMP) { msm8960_ext_top_spk_pamp &= ~TOP_SPK_AMP; } if (msm8960_ext_top_spk_pamp) return; gpio_direction_output(top_spk_pamp_gpio, 0); gpio_free(top_spk_pamp_gpio); msm8960_ext_top_spk_pamp = 0; pr_debug("%s: sleeping 4 ms after ext Top Spek Ampl is off\n", __func__); usleep_range(4000, 4000); } else { pr_err("%s: ERROR : Invalid Ext Spk Ampl. spk = 0x%08x\n", __func__, spk); return; } } static void msm8960_ext_control(struct snd_soc_codec *codec) { struct snd_soc_dapm_context *dapm = &codec->dapm; mutex_lock(&dapm->codec->mutex); pr_debug("%s: msm8960_spk_control = %d", __func__, msm8960_spk_control); if (msm8960_spk_control == MSM8960_SPK_ON) { snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg"); } else { snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Neg"); } snd_soc_dapm_sync(dapm); mutex_unlock(&dapm->codec->mutex); } static int msm8960_get_spk(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm8960_spk_control = %d", __func__, msm8960_spk_control); ucontrol->value.integer.value[0] = msm8960_spk_control; return 0; } static int msm8960_set_spk(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); pr_debug("%s()\n", __func__); if (msm8960_spk_control == ucontrol->value.integer.value[0]) return 0; msm8960_spk_control = ucontrol->value.integer.value[0]; msm8960_ext_control(codec); return 1; } static int msm8960_spkramp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { pr_debug("%s() %x\n", __func__, SND_SOC_DAPM_EVENT_ON(event)); if (SND_SOC_DAPM_EVENT_ON(event)) { if (!strncmp(w->name, "Ext Spk Bottom Pos", 18)) msm8960_ext_spk_power_amp_on(BOTTOM_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18)) msm8960_ext_spk_power_amp_on(BOTTOM_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top Pos", 15)) msm8960_ext_spk_power_amp_on(TOP_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Top Neg", 15)) msm8960_ext_spk_power_amp_on(TOP_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top", 12)) msm8960_ext_spk_power_amp_on(TOP_SPK_AMP); else { pr_err("%s() Invalid Speaker Widget = %s\n", __func__, w->name); return -EINVAL; } } else { if (!strncmp(w->name, "Ext Spk Bottom Pos", 18)) msm8960_ext_spk_power_amp_off(BOTTOM_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18)) msm8960_ext_spk_power_amp_off(BOTTOM_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top Pos", 15)) msm8960_ext_spk_power_amp_off(TOP_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Top Neg", 15)) msm8960_ext_spk_power_amp_off(TOP_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top", 12)) msm8960_ext_spk_power_amp_off(TOP_SPK_AMP); else { pr_err("%s() Invalid Speaker Widget = %s\n", __func__, w->name); return -EINVAL; } } return 0; } static int msm8960_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable, bool dapm) { int r = 0; pr_debug("%s: enable = %d\n", __func__, enable); mutex_lock(&cdc_mclk_mutex); if (enable) { clk_users++; pr_debug("%s: clk_users = %d\n", __func__, clk_users); if (clk_users == 1) { if (codec_clk) { clk_set_rate(codec_clk, TABLA_EXT_CLK_RATE); clk_prepare_enable(codec_clk); tabla_mclk_enable(codec, 1, dapm); } else { pr_err("%s: Error setting Tabla MCLK\n", __func__); clk_users--; r = -EINVAL; } } } else { if (clk_users > 0) { clk_users--; pr_debug("%s: clk_users = %d\n", __func__, clk_users); if (clk_users == 0) { pr_debug("%s: disabling MCLK. clk_users = %d\n", __func__, clk_users); tabla_mclk_enable(codec, 0, dapm); clk_disable_unprepare(codec_clk); } } else { pr_err("%s: Error releasing Tabla MCLK\n", __func__); r = -EINVAL; } } mutex_unlock(&cdc_mclk_mutex); return r; } static bool msm8960_swap_gnd_mic(struct snd_soc_codec *codec) { int value = gpio_get_value_cansleep(us_euro_sel_gpio); pr_debug("%s: US EURO select switch %d to %d\n", __func__, value, !value); gpio_set_value_cansleep(us_euro_sel_gpio, !value); return true; } static int msm8960_mclk_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { pr_debug("%s: event = %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: return msm8960_enable_codec_ext_clk(w->codec, 1, true); case SND_SOC_DAPM_POST_PMD: return msm8960_enable_codec_ext_clk(w->codec, 0, true); } return 0; } static const struct snd_soc_dapm_widget msm8960_dapm_widgets[] = { SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0, msm8960_mclk_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SPK("Ext Spk Bottom Pos", msm8960_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Bottom Neg", msm8960_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Top Pos", msm8960_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Top Neg", msm8960_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Top", msm8960_spkramp_event), SND_SOC_DAPM_MIC("Primary Mic", NULL), SND_SOC_DAPM_MIC("Secondary Mic", NULL), SND_SOC_DAPM_MIC("Tertiary Mic", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL), SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL), }; static const struct snd_soc_dapm_route common_audio_map[] = { {"RX_BIAS", NULL, "MCLK"}, {"LDO_H", NULL, "MCLK"}, /* Speaker path */ {"Ext Spk Bottom Pos", NULL, "LINEOUT2"}, {"Ext Spk Bottom Neg", NULL, "LINEOUT4"}, {"Ext Spk Top Pos", NULL, "LINEOUT1"}, {"Ext Spk Top Neg", NULL, "LINEOUT3"}, {"Ext Spk Top", NULL, "LINEOUT5"}, /* Microphone path */ {"AMIC3", NULL, "MIC BIAS1 External"}, {"MIC BIAS1 External", NULL, "Primary Mic"}, {"AMIC4", NULL, "MIC BIAS3 External"}, {"MIC BIAS3 External", NULL, "Secondary Mic"}, {"AMIC1", NULL, "MIC BIAS4 External"}, {"MIC BIAS4 External", NULL, "Tertiary Mic"}, {"AMIC2", NULL, "MIC BIAS2 External"}, {"MIC BIAS2 External", NULL, "Headset Mic"}, /** * AMIC3 and AMIC4 inputs are connected to ANC microphones * These mics are biased differently on CDP and FLUID * routing entries below are based on bias arrangement * on FLUID. */ {"AMIC3", NULL, "MIC BIAS3 Internal1"}, {"MIC BIAS2 External", NULL, "ANCRight Headset Mic"}, {"AMIC4", NULL, "MIC BIAS1 Internal2"}, {"MIC BIAS2 External", NULL, "ANCLeft Headset Mic"}, {"HEADPHONE", NULL, "LDO_H"}, }; #ifdef CONFIG_SND_SOC_TPA6165A2 static int msm8960_ext_hp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { if (SND_SOC_DAPM_EVENT_ON(event)) tpa6165_hp_event(1); else tpa6165_hp_event(0); return 0; } static int msm8960_ext_mic_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { if (SND_SOC_DAPM_EVENT_ON(event)) tpa6165_mic_event(1); else tpa6165_mic_event(0); return 0; } static const struct snd_soc_dapm_widget tpa6165_dapm_widgets[] = { SND_SOC_DAPM_INPUT("TPA6165 Mic"), SND_SOC_DAPM_MIC("TPA6165 Headset Mic", msm8960_ext_mic_event), SND_SOC_DAPM_HP("TPA6165 HEADPHONE", msm8960_ext_hp_event), }; static const struct snd_soc_dapm_route tpa6165_hp_map[] = { {"TPA6165 HEADPHONE", NULL, "HEADPHONE"}, {"TPA6165 Mic", NULL, "MIC BIAS2 External"}, {"MIC BIAS2 External", NULL, "TPA6165 Headset Mic"}, }; #endif static const char *spk_function[] = {"Off", "On"}; static const char *slim0_rx_ch_text[] = {"One", "Two"}; static const char *slim0_tx_ch_text[] = {"One", "Two", "Three", "Four"}; static char const *hdmi_rx_ch_text[] = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight"}; static const char * const hdmi_rate[] = {"Default", "Variable"}; static const struct soc_enum msm8960_enum[] = { SOC_ENUM_SINGLE_EXT(2, spk_function), SOC_ENUM_SINGLE_EXT(2, slim0_rx_ch_text), SOC_ENUM_SINGLE_EXT(4, slim0_tx_ch_text), SOC_ENUM_SINGLE_EXT(2, hdmi_rate), SOC_ENUM_SINGLE_EXT(7, hdmi_rx_ch_text), }; static const char *btsco_rate_text[] = {"8000", "16000"}; static const struct soc_enum msm8960_btsco_enum[] = { SOC_ENUM_SINGLE_EXT(2, btsco_rate_text), }; static const char *auxpcm_rate_text[] = {"rate_8000", "rate_16000"}; static const struct soc_enum msm8960_auxpcm_enum[] = { SOC_ENUM_SINGLE_EXT(2, auxpcm_rate_text), }; static int msm8960_slim_0_rx_ch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm8960_slim_0_rx_ch = %d\n", __func__, msm8960_slim_0_rx_ch); ucontrol->value.integer.value[0] = msm8960_slim_0_rx_ch - 1; return 0; } static int msm8960_slim_0_rx_ch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { msm8960_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1; pr_debug("%s: msm8960_slim_0_rx_ch = %d\n", __func__, msm8960_slim_0_rx_ch); return 1; } static int msm8960_slim_0_tx_ch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm8960_slim_0_tx_ch = %d\n", __func__, msm8960_slim_0_tx_ch); ucontrol->value.integer.value[0] = msm8960_slim_0_tx_ch - 1; return 0; } static int msm8960_slim_0_tx_ch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { msm8960_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1; pr_debug("%s: msm8960_slim_0_tx_ch = %d\n", __func__, msm8960_slim_0_tx_ch); return 1; } static int msm8960_btsco_rate_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm8960_btsco_rate = %d", __func__, msm8960_btsco_rate); ucontrol->value.integer.value[0] = msm8960_btsco_rate; return 0; } static int msm8960_btsco_rate_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { switch (ucontrol->value.integer.value[0]) { case 8000: msm8960_btsco_rate = SAMPLE_RATE_8KHZ; break; case 16000: msm8960_btsco_rate = SAMPLE_RATE_16KHZ; break; default: msm8960_btsco_rate = SAMPLE_RATE_8KHZ; break; } pr_debug("%s: msm8960_btsco_rate = %d\n", __func__, msm8960_btsco_rate); return 0; } static int msm8960_auxpcm_rate_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm8960_auxpcm_rate = %d", __func__, msm8960_auxpcm_rate); ucontrol->value.integer.value[0] = msm8960_auxpcm_rate; return 0; } static int msm8960_auxpcm_rate_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { switch (ucontrol->value.integer.value[0]) { case 0: msm8960_auxpcm_rate = SAMPLE_RATE_8KHZ; break; case 1: msm8960_auxpcm_rate = SAMPLE_RATE_16KHZ; break; default: msm8960_auxpcm_rate = SAMPLE_RATE_8KHZ; break; } pr_debug("%s: msm8960_auxpcm_rate = %d" "ucontrol->value.integer.value[0] = %d\n", __func__, msm8960_auxpcm_rate, (int)ucontrol->value.integer.value[0]); return 0; } static int msm_hdmi_rx_ch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_hdmi_rx_ch = %d\n", __func__, msm_hdmi_rx_ch); ucontrol->value.integer.value[0] = msm_hdmi_rx_ch - 2; return 0; } static int msm_hdmi_rx_ch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { msm_hdmi_rx_ch = ucontrol->value.integer.value[0] + 2; pr_debug("%s: msm_hdmi_rx_ch = %d\n", __func__, msm_hdmi_rx_ch); return 1; } static int msm8960_hdmi_rate_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { hdmi_rate_variable = ucontrol->value.integer.value[0]; pr_debug("%s: hdmi_rate_variable = %d\n", __func__, hdmi_rate_variable); return 0; } static int msm8960_hdmi_rate_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.integer.value[0] = hdmi_rate_variable; return 0; } static const struct snd_kcontrol_new tabla_msm8960_controls[] = { SOC_ENUM_EXT("Speaker Function", msm8960_enum[0], msm8960_get_spk, msm8960_set_spk), SOC_ENUM_EXT("SLIM_0_RX Channels", msm8960_enum[1], msm8960_slim_0_rx_ch_get, msm8960_slim_0_rx_ch_put), SOC_ENUM_EXT("SLIM_0_TX Channels", msm8960_enum[2], msm8960_slim_0_tx_ch_get, msm8960_slim_0_tx_ch_put), SOC_ENUM_EXT("Internal BTSCO SampleRate", msm8960_btsco_enum[0], msm8960_btsco_rate_get, msm8960_btsco_rate_put), SOC_ENUM_EXT("AUX PCM SampleRate", msm8960_auxpcm_enum[0], msm8960_auxpcm_rate_get, msm8960_auxpcm_rate_put), SOC_ENUM_EXT("HDMI RX Rate", msm8960_enum[3], msm8960_hdmi_rate_get, msm8960_hdmi_rate_put), SOC_ENUM_EXT("HDMI_RX Channels", msm8960_enum[4], msm_hdmi_rx_ch_get, msm_hdmi_rx_ch_put), }; static void *def_tabla_mbhc_cal(void) { void *tabla_cal; struct tabla_mbhc_btn_detect_cfg *btn_cfg; u16 *btn_low, *btn_high; u8 *n_ready, *n_cic, *gain; tabla_cal = kzalloc(TABLA_MBHC_CAL_SIZE(TABLA_MBHC_DEF_BUTTONS, TABLA_MBHC_DEF_RLOADS), GFP_KERNEL); if (!tabla_cal) { pr_err("%s: out of memory\n", __func__); return NULL; } #define S(X, Y) ((TABLA_MBHC_CAL_GENERAL_PTR(tabla_cal)->X) = (Y)) S(t_ldoh, 100); S(t_bg_fast_settle, 100); S(t_shutdown_plug_rem, 255); S(mbhc_nsa, 4); S(mbhc_navg, 4); #undef S #define S(X, Y) ((TABLA_MBHC_CAL_PLUG_DET_PTR(tabla_cal)->X) = (Y)) S(mic_current, TABLA_PID_MIC_5_UA); S(hph_current, TABLA_PID_MIC_5_UA); S(t_mic_pid, 100); S(t_ins_complete, 250); S(t_ins_retry, 200); #undef S #define S(X, Y) ((TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla_cal)->X) = (Y)) S(v_no_mic, 30); S(v_hs_max, 2400); #undef S #define S(X, Y) ((TABLA_MBHC_CAL_BTN_DET_PTR(tabla_cal)->X) = (Y)) S(c[0], 62); S(c[1], 124); S(nc, 1); S(n_meas, 3); S(mbhc_nsc, 11); S(n_btn_meas, 1); S(n_btn_con, 2); S(num_btn, TABLA_MBHC_DEF_BUTTONS); S(v_btn_press_delta_sta, 100); S(v_btn_press_delta_cic, 50); #undef S btn_cfg = TABLA_MBHC_CAL_BTN_DET_PTR(tabla_cal); btn_low = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_V_BTN_LOW); btn_high = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_V_BTN_HIGH); btn_low[0] = -50; btn_high[0] = 21; btn_low[1] = 22; btn_high[1] = 67; btn_low[2] = 68; btn_high[2] = 111; btn_low[3] = 112; btn_high[3] = 153; btn_low[4] = 154; btn_high[4] = 191; btn_low[5] = 192; btn_high[5] = 233; btn_low[6] = 234; btn_high[6] = 272; btn_low[7] = 273; btn_high[7] = 400; n_ready = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_N_READY); n_ready[0] = 80; n_ready[1] = 68; n_cic = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_N_CIC); n_cic[0] = 60; n_cic[1] = 47; gain = tabla_mbhc_cal_btn_det_mp(btn_cfg, TABLA_BTN_DET_GAIN); gain[0] = 11; gain[1] = 9; return tabla_cal; } static int msm8960_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret = 0; unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS]; unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { pr_debug("%s: rx_0_ch=%d\n", __func__, msm8960_slim_0_rx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, msm8960_slim_0_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0, msm8960_slim_0_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } else { pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, msm8960_slim_0_tx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, msm8960_slim_0_tx_ch, tx_ch, 0 , 0); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, msm8960_slim_0_tx_ch, tx_ch, 0, 0); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } end: return ret; } static int msm8960_slimbus_2_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret = 0; unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS]; unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0; unsigned int num_tx_ch = 0; unsigned int num_rx_ch = 0; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { num_rx_ch = params_channels(params); pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, num_rx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, num_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0, num_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } else { num_tx_ch = params_channels(params); pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, num_tx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, num_tx_ch, tx_ch, 0 , 0); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, num_tx_ch, tx_ch, 0, 0); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } end: return ret; } static int msm8960_audrx_init(struct snd_soc_pcm_runtime *rtd) { int err, ret; struct snd_soc_codec *codec = rtd->codec; struct snd_soc_dapm_context *dapm = &codec->dapm; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct pm_gpio jack_gpio_cfg = { .direction = PM_GPIO_DIR_IN, .pull = PM_GPIO_PULL_UP_1P5, .function = PM_GPIO_FUNC_NORMAL, .vin_sel = 2, .inv_int_pol = 0, }; pr_debug("%s(), dev_name%s\n", __func__, dev_name(cpu_dai->dev)); if (machine_is_msm8960_liquid()) { top_spk_pamp_gpio = (PM8921_GPIO_PM_TO_SYS(19)); bottom_spk_pamp_gpio = (PM8921_GPIO_PM_TO_SYS(18)); } snd_soc_dapm_new_controls(dapm, msm8960_dapm_widgets, ARRAY_SIZE(msm8960_dapm_widgets)); snd_soc_dapm_add_routes(dapm, common_audio_map, ARRAY_SIZE(common_audio_map)); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg"); snd_soc_dapm_sync(dapm); codec_clk = clk_get(cpu_dai->dev, "osr_clk"); if (machine_is_msm8960_cdp()) mbhc_cfg.swap_gnd_mic = msm8960_swap_gnd_mic; err = snd_soc_jack_new(codec, "Headset Jack", (SND_JACK_HEADSET | SND_JACK_LINEOUT | SND_JACK_OC_HPHL | SND_JACK_OC_HPHR | SND_JACK_UNSUPPORTED), &hs_jack); if (err) { pr_err("failed to create new jack\n"); return err; } err = snd_soc_jack_new(codec, "Button Jack", TABLA_JACK_BUTTON_MASK, &button_jack); if (err) { pr_err("failed to create new jack\n"); return err; } ret = snd_jack_set_key(button_jack.jack, SND_JACK_BTN_0, KEY_MEDIA); if (ret) { pr_err("%s: Failed to set code for btn-0\n", __func__); return ret; } #ifdef CONFIG_SND_SOC_TPA6165A2 err = tpa6165_hs_detect(codec, &hs_jack, &button_jack); if (!err) { pr_info("%s:tpa6165 hs det mechanism is used", __func__); /* dapm controls for tpa6165 */ snd_soc_dapm_new_controls(dapm, tpa6165_dapm_widgets, ARRAY_SIZE(tpa6165_dapm_widgets)); snd_soc_dapm_add_routes(dapm, tpa6165_hp_map, ARRAY_SIZE(tpa6165_hp_map)); snd_soc_dapm_enable_pin(dapm, "TPA6165 HEADPHONE"); snd_soc_dapm_enable_pin(dapm, "TPA6165 MIC"); snd_soc_dapm_sync(dapm); return err; } #endif if (hs_detect_use_gpio) { mbhc_cfg.gpio = PM8921_GPIO_PM_TO_SYS(JACK_DETECT_GPIO); mbhc_cfg.gpio_irq = JACK_DETECT_INT; if (hs_detect_extn_cable) mbhc_cfg.detect_extn_cable = true; } if (mbhc_cfg.gpio) { err = pm8xxx_gpio_config(mbhc_cfg.gpio, &jack_gpio_cfg); if (err) { pr_err("%s: pm8xxx_gpio_config JACK_DETECT failed %d\n", __func__, err); return err; } } mbhc_cfg.read_fw_bin = hs_detect_use_firmware; err = tabla_hs_detect(codec, &mbhc_cfg); return err; } static int msm8960_slim_0_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; channels->min = channels->max = msm8960_slim_0_rx_ch; return 0; } static int msm8960_slim_0_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; channels->min = channels->max = msm8960_slim_0_tx_ch; return 0; } static int msm8960_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; return 0; } static int msm8960_be_hw_pri_i2s_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); pr_debug("%s()\n", __func__); rate->min = rate->max = 16000; return 0; } static int msm8960_hdmi_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s channels->min %u channels->max %u ()\n", __func__, channels->min, channels->max); if (!hdmi_rate_variable) rate->min = rate->max = 48000; channels->min = channels->max = msm_hdmi_rx_ch; if (channels->max < 2) channels->min = channels->max = 2; return 0; } static int msm8960_btsco_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); rate->min = rate->max = msm8960_btsco_rate; channels->min = channels->max = msm8960_btsco_ch; return 0; } static int msm8960_auxpcm_be_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); rate->min = rate->max = msm8960_auxpcm_rate; /* PCM only supports mono output */ channels->min = channels->max = 1; return 0; } static int msm8960_proxy_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; return 0; } static int msm8960_aux_pcm_get_gpios(void) { int ret = 0; pr_debug("%s\n", __func__); ret = gpio_request(GPIO_AUX_PCM_DOUT, "AUX PCM DOUT"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM DOUT", __func__, GPIO_AUX_PCM_DOUT); goto fail_dout; } ret = gpio_request(GPIO_AUX_PCM_DIN, "AUX PCM DIN"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM DIN", __func__, GPIO_AUX_PCM_DIN); goto fail_din; } ret = gpio_request(GPIO_AUX_PCM_SYNC, "AUX PCM SYNC"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM SYNC", __func__, GPIO_AUX_PCM_SYNC); goto fail_sync; } ret = gpio_request(GPIO_AUX_PCM_CLK, "AUX PCM CLK"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM CLK", __func__, GPIO_AUX_PCM_CLK); goto fail_clk; } return 0; fail_clk: gpio_free(GPIO_AUX_PCM_SYNC); fail_sync: gpio_free(GPIO_AUX_PCM_DIN); fail_din: gpio_free(GPIO_AUX_PCM_DOUT); fail_dout: return ret; } static int msm_mi2s_rx_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; int rate = params_rate(params); int bit_clk_set; bit_clk_set = 12288000/(rate * 2 * 16); clk_set_rate(mi2s_rx_bit_clk, bit_clk_set); /* if it is msm stub dummy codec dai, it doesnt support this op * causes an unneseccary failure to startup path. */ if (strncmp(codec_dai->name, "msm-stub-tx", 11)) { ret = snd_soc_dai_set_sysclk(codec_dai, 0, TABLA_EXT_CLK_RATE, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("can't set rx codec clk configuration\n"); return ret; } } return 1; } static void msm_mi2s_rx_shutdown(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_card *card = rtd->card; struct msm8960_asoc_mach_data *data = snd_soc_card_get_drvdata(card); if (!data) { pr_err("%s: no machine data!\n", __func__); return; } if (atomic_dec_return(&mi2s_rsc_ref) == 0) { if (mi2s_rx_bit_clk) { clk_disable_unprepare(mi2s_rx_bit_clk); clk_put(mi2s_rx_bit_clk); mi2s_rx_bit_clk = NULL; } if (mi2s_rx_osr_clk) { clk_disable_unprepare(mi2s_rx_osr_clk); clk_put(mi2s_rx_osr_clk); mi2s_rx_osr_clk = NULL; } gpio_free_array(data->mi2s_gpios, data->num_mi2s_gpios); } } static int msm_mi2s_rx_startup(struct snd_pcm_substream *substream) { int ret = 0; struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_card *card = rtd->card; struct msm8960_asoc_mach_data *data = snd_soc_card_get_drvdata(card); if (!data) { pr_err("%s: no machine data!\n", __func__); return -ENODEV; } if (atomic_inc_return(&mi2s_rsc_ref) == 1) { ret = gpio_request_array(data->mi2s_gpios, data->num_mi2s_gpios); if (ret < 0) goto mi2s_gpio_fail; mi2s_rx_osr_clk = clk_get(cpu_dai->dev, "osr_clk"); if (IS_ERR(mi2s_rx_osr_clk)) { pr_err("Failed to get mi2s_rx_osr_clk\n"); ret = PTR_ERR(mi2s_rx_osr_clk); goto osr_clk_fail; } clk_set_rate(mi2s_rx_osr_clk, TABLA_EXT_CLK_RATE); ret = clk_prepare_enable(mi2s_rx_osr_clk); if (ret != 0) { pr_err("Unable to enable mi2s_rx_osr_clk\n"); clk_put(mi2s_rx_osr_clk); mi2s_rx_osr_clk = NULL; goto osr_clk_fail; } mi2s_rx_bit_clk = clk_get(cpu_dai->dev, "bit_clk"); if (IS_ERR(mi2s_rx_bit_clk)) { pr_err("Failed to get mi2s_osr_clk\n"); ret = PTR_ERR(mi2s_rx_bit_clk); goto bit_clk_fail; } /* Actual bit clk rate is set up in hw_param value 8 is arrived from assuming rate to be 48k here */ clk_set_rate(mi2s_rx_bit_clk, 8); ret = clk_prepare_enable(mi2s_rx_bit_clk); if (ret != 0) { pr_err("Unable to enable mi2s_rx_bit_clk\n"); clk_put(mi2s_rx_bit_clk); mi2s_rx_bit_clk = NULL; goto bit_clk_fail; } ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBS_CFS); if (ret < 0) { pr_err("set format for msm dai failed\n"); goto msm_dai_fail; } /* if it is msm stub dummy codec dai, it doesnt support this op causes an unnecessary failure to startup path. */ if (strncmp(codec_dai->name, "msm-stub-tx", 11)) { ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_CBS_CFS|SND_SOC_DAIFMT_I2S); if (ret < 0) { pr_err("set format for codec dai failed\n"); goto codec_dai_fail; } } } pr_debug("%s: ret = %d\n", __func__, ret); return ret; codec_dai_fail: msm_dai_fail: clk_disable_unprepare(mi2s_rx_bit_clk); clk_put(mi2s_rx_bit_clk); mi2s_rx_bit_clk = NULL; bit_clk_fail: clk_disable_unprepare(mi2s_rx_osr_clk); clk_put(mi2s_rx_osr_clk); mi2s_rx_osr_clk = NULL; osr_clk_fail: gpio_free_array(data->mi2s_gpios, data->num_mi2s_gpios); mi2s_gpio_fail: atomic_dec(&mi2s_rsc_ref); return ret; } static int msm8960_aux_pcm_free_gpios(void) { gpio_free(GPIO_AUX_PCM_DIN); gpio_free(GPIO_AUX_PCM_DOUT); gpio_free(GPIO_AUX_PCM_SYNC); gpio_free(GPIO_AUX_PCM_CLK); return 0; } static int msm_primary_i2s_tx_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { int rate = params_rate(params); int bit_clk_set = 0; pr_debug("%s rate: %d\n", __func__, rate); if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { bit_clk_set = TABLA_EXT_CLK_RATE/(rate * 2 * 16); clk_set_rate(pri_i2s_tx_bit_clk, bit_clk_set); return 1; } return -EINVAL; } static void msm_primary_i2s_tx_shutdown(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_card *card = rtd->card; struct msm8960_asoc_mach_data *data = snd_soc_card_get_drvdata(card); if (!data) { pr_err("%s: no machine data!\n", __func__); return; } if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { if (pri_i2s_tx_osr_clk) { clk_disable_unprepare(pri_i2s_tx_osr_clk); clk_put(pri_i2s_tx_osr_clk); pri_i2s_tx_osr_clk = NULL; } if (pri_i2s_tx_bit_clk) { clk_disable_unprepare(pri_i2s_tx_bit_clk); clk_put(pri_i2s_tx_bit_clk); pri_i2s_tx_bit_clk = NULL; } gpio_free_array(data->pri_i2s_gpios, data->num_pri_i2s_gpios); } } static int msm_primary_i2s_tx_startup(struct snd_pcm_substream *substream) { int ret = -EINVAL; struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; struct snd_soc_card *card = rtd->card; struct msm8960_asoc_mach_data *data = snd_soc_card_get_drvdata(card); if (!data) { pr_err("%s: no machine data!\n", __func__); return -ENODEV; } if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) { ret = gpio_request_array(data->pri_i2s_gpios, data->num_pri_i2s_gpios); if (ret < 0) return ret; pri_i2s_tx_osr_clk = clk_get(cpu_dai->dev, "osr_clk"); if (IS_ERR(pri_i2s_tx_osr_clk)) { pr_err("Failed to get pri_i2s_tx_osr_clk\n"); ret = PTR_ERR(pri_i2s_tx_osr_clk); goto osr_clk_fail; } clk_set_rate(pri_i2s_tx_osr_clk, TABLA_EXT_CLK_RATE); ret = clk_prepare_enable(pri_i2s_tx_osr_clk); if (ret != 0) { pr_err("Unable to enable pri_i2s_tx_osr_clk\n"); goto osr_clk_en_fail; } pri_i2s_tx_bit_clk = clk_get(cpu_dai->dev, "bit_clk"); if (IS_ERR(pri_i2s_tx_bit_clk)) { pr_err("Failed to get pri_i2s_tx_bit_clk\n"); ret = PTR_ERR(pri_i2s_tx_bit_clk); goto bit_clk_fail; } /* Actual bit clk rate is set up in hw_param value 24 is arrived from assuming rate to be 16k here */ clk_set_rate(pri_i2s_tx_bit_clk, 24); ret = clk_prepare_enable(pri_i2s_tx_bit_clk); if (ret != 0) { pr_err("Unable to enable pri_i2s_tx_bit_clk\n"); goto bit_clk_en_fail; } ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_CBS_CFS); if (ret < 0) { pr_err("set format for cpu dai failed\n"); goto set_fmt_fail; } } pr_debug("%s: ret = %d\n", __func__, ret); return ret; set_fmt_fail: clk_disable_unprepare(pri_i2s_tx_bit_clk); bit_clk_en_fail: clk_put(pri_i2s_tx_bit_clk); pri_i2s_tx_bit_clk = NULL; bit_clk_fail: clk_disable_unprepare(pri_i2s_tx_osr_clk); osr_clk_en_fail: clk_put(pri_i2s_tx_osr_clk); pri_i2s_tx_osr_clk = NULL; osr_clk_fail: gpio_free_array(data->pri_i2s_gpios, data->num_pri_i2s_gpios); return ret; } static int msm8960_startup(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; pr_debug("%s(): dai_link_str_name = %s cpu_dai = %s codec_dai = %s\n", __func__, rtd->dai_link->stream_name, rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name); return 0; } static int msm8960_auxpcm_startup(struct snd_pcm_substream *substream) { int ret = 0; pr_debug("%s(): substream = %s, auxpcm_rsc_ref counter = %d\n", __func__, substream->name, atomic_read(&auxpcm_rsc_ref)); if (atomic_inc_return(&auxpcm_rsc_ref) == 1) ret = msm8960_aux_pcm_get_gpios(); if (ret < 0) { pr_err("%s: Aux PCM GPIO request failed\n", __func__); return -EINVAL; } return 0; } static void msm8960_auxpcm_shutdown(struct snd_pcm_substream *substream) { pr_debug("%s(): substream = %s, auxpcm_rsc_ref counter = %d\n", __func__, substream->name, atomic_read(&auxpcm_rsc_ref)); if (atomic_dec_return(&auxpcm_rsc_ref) == 0) msm8960_aux_pcm_free_gpios(); } static void msm8960_shutdown(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; pr_debug("%s(): dai_link str_name = %s cpu_dai = %s codec_dai = %s\n", __func__, rtd->dai_link->stream_name, rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name); } static struct snd_soc_ops msm8960_be_ops = { .startup = msm8960_startup, .hw_params = msm8960_hw_params, .shutdown = msm8960_shutdown, }; static struct snd_soc_ops msm8960_auxpcm_be_ops = { .startup = msm8960_auxpcm_startup, .shutdown = msm8960_auxpcm_shutdown, }; static struct snd_soc_ops msm8960_slimbus_2_be_ops = { .startup = msm8960_startup, .hw_params = msm8960_slimbus_2_hw_params, .shutdown = msm8960_shutdown, }; static struct snd_soc_ops msm_mi2s_rx_be_ops = { .startup = msm_mi2s_rx_startup, .shutdown = msm_mi2s_rx_shutdown, .hw_params = msm_mi2s_rx_hw_params, }; static struct snd_soc_ops msm_primary_i2s_tx_be_ops = { .startup = msm_primary_i2s_tx_startup, .shutdown = msm_primary_i2s_tx_shutdown, .hw_params = msm_primary_i2s_tx_hw_params, }; /* Digital audio interface glue - connects codec <---> CPU */ static struct snd_soc_dai_link msm8960_dai_common[] = { /* FrontEnd DAI Links */ { .name = "MSM8960 Media1", .stream_name = "MultiMedia1", .cpu_dai_name = "MultiMedia1", .platform_name = "msm-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_MULTIMEDIA1 }, { .name = "MSM8960 Media2", .stream_name = "MultiMedia2", .cpu_dai_name = "MultiMedia2", .platform_name = "msm-multi-ch-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_MULTIMEDIA2, }, { .name = "Circuit-Switch Voice", .stream_name = "CS-Voice", .cpu_dai_name = "CS-VOICE", .platform_name = "msm-pcm-voice", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_CS_VOICE, }, { .name = "MSM VoIP", .stream_name = "VoIP", .cpu_dai_name = "VoIP", .platform_name = "msm-voip-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_VOIP, }, { .name = "MSM8960 LPA", .stream_name = "LPA", .cpu_dai_name = "MultiMedia3", .platform_name = "msm-pcm-lpa", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_MULTIMEDIA3, }, /* Hostless PMC purpose */ { .name = "SLIMBUS_0 Hostless", .stream_name = "SLIMBUS_0 Hostless", .cpu_dai_name = "SLIMBUS0_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "INT_FM Hostless", .stream_name = "INT_FM Hostless", .cpu_dai_name = "INT_FM_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "MSM AFE-PCM RX", .stream_name = "AFE-PROXY RX", .cpu_dai_name = "msm-dai-q6.241", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .platform_name = "msm-pcm-afe", .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = "MSM AFE-PCM TX", .stream_name = "AFE-PROXY TX", .cpu_dai_name = "msm-dai-q6.240", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .platform_name = "msm-pcm-afe", .ignore_suspend = 1, }, { .name = "MSM8960 Compr", .stream_name = "COMPR", .cpu_dai_name = "MultiMedia4", .platform_name = "msm-compr-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .be_id = MSM_FRONTEND_DAI_MULTIMEDIA4, }, { .name = "AUXPCM Hostless", .stream_name = "AUXPCM Hostless", .cpu_dai_name = "AUXPCM_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, /* HDMI Hostless */ { .name = "HDMI_RX_HOSTLESS", .stream_name = "HDMI_RX_HOSTLESS", .cpu_dai_name = "HDMI_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "VoLTE", .stream_name = "VoLTE", .cpu_dai_name = "VoLTE", .platform_name = "msm-pcm-voice", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, /* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .be_id = MSM_FRONTEND_DAI_VOLTE, }, { .name = "Voice2", .stream_name = "Voice2", .cpu_dai_name = "Voice2", .platform_name = "msm-pcm-voice", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1,/* this dainlink has playback support */ .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .be_id = MSM_FRONTEND_DAI_VOICE2, }, { .name = "MSM8960 LowLatency", .stream_name = "MultiMedia5", .cpu_dai_name = "MultiMedia5", .platform_name = "msm-lowlatency-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, /* this dainlink has playback support */ .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA5, }, /* Backend BT/FM DAI Links */ { .name = LPASS_BE_INT_BT_SCO_RX, .stream_name = "Internal BT-SCO Playback", .cpu_dai_name = "msm-dai-q6.12288", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_BT_SCO_RX, .be_hw_params_fixup = msm8960_btsco_be_hw_params_fixup, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = LPASS_BE_INT_BT_SCO_TX, .stream_name = "Internal BT-SCO Capture", .cpu_dai_name = "msm-dai-q6.12289", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_BT_SCO_TX, .be_hw_params_fixup = msm8960_btsco_be_hw_params_fixup, }, { .name = LPASS_BE_INT_FM_RX, .stream_name = "Internal FM Playback", .cpu_dai_name = "msm-dai-q6.12292", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_FM_RX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = LPASS_BE_INT_FM_TX, .stream_name = "Internal FM Capture", .cpu_dai_name = "msm-dai-q6.12293", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_FM_TX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, }, /* HDMI BACK END DAI Link */ { .name = LPASS_BE_HDMI, .stream_name = "HDMI Playback", .cpu_dai_name = "msm-dai-q6-hdmi.8", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_HDMI_RX, .be_hw_params_fixup = msm8960_hdmi_be_hw_params_fixup, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, /* Backend AFE DAI Links */ { .name = LPASS_BE_AFE_PCM_RX, .stream_name = "AFE Playback", .cpu_dai_name = "msm-dai-q6.224", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AFE_PCM_RX, .be_hw_params_fixup = msm8960_proxy_be_hw_params_fixup, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = LPASS_BE_AFE_PCM_TX, .stream_name = "AFE Capture", .cpu_dai_name = "msm-dai-q6.225", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AFE_PCM_TX, .be_hw_params_fixup = msm8960_proxy_be_hw_params_fixup, }, /* AUX PCM Backend DAI Links */ { .name = LPASS_BE_AUXPCM_RX, .stream_name = "AUX PCM Playback", .cpu_dai_name = "msm-dai-q6.2", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AUXPCM_RX, .be_hw_params_fixup = msm8960_auxpcm_be_params_fixup, .ops = &msm8960_auxpcm_be_ops, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_AUXPCM_TX, .stream_name = "AUX PCM Capture", .cpu_dai_name = "msm-dai-q6.3", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AUXPCM_TX, .be_hw_params_fixup = msm8960_auxpcm_be_params_fixup, .ops = &msm8960_auxpcm_be_ops, }, /* Incall Music BACK END DAI Link */ { .name = LPASS_BE_VOICE_PLAYBACK_TX, .stream_name = "Voice Farend Playback", .cpu_dai_name = "msm-dai-q6.32773", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_VOICE_PLAYBACK_TX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, }, /* Incall Record Uplink BACK END DAI Link */ { .name = LPASS_BE_INCALL_RECORD_TX, .stream_name = "Voice Uplink Capture", .cpu_dai_name = "msm-dai-q6.32772", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INCALL_RECORD_TX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, }, /* Incall Record Downlink BACK END DAI Link */ { .name = LPASS_BE_INCALL_RECORD_RX, .stream_name = "Voice Downlink Capture", .cpu_dai_name = "msm-dai-q6.32771", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INCALL_RECORD_RX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, }; static struct snd_soc_dai_link msm8960_dai_delta_tabla1x[] = { /* Backend DAI Links */ { .name = LPASS_BE_SLIMBUS_0_RX, .stream_name = "Slimbus Playback", .cpu_dai_name = "msm-dai-q6.16384", .platform_name = "msm-pcm-routing", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_rx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX, .init = &msm8960_audrx_init, .be_hw_params_fixup = msm8960_slim_0_rx_be_hw_params_fixup, .ops = &msm8960_be_ops, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = LPASS_BE_SLIMBUS_0_TX, .stream_name = "Slimbus Capture", .cpu_dai_name = "msm-dai-q6.16385", .platform_name = "msm-pcm-routing", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_tx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX, .be_hw_params_fixup = msm8960_slim_0_tx_be_hw_params_fixup, .ops = &msm8960_be_ops, }, /* Ultrasound TX Back End DAI Link */ { .name = "SLIMBUS_2 Hostless Capture", .stream_name = "SLIMBUS_2 Hostless Capture", .cpu_dai_name = "msm-dai-q6.16389", .platform_name = "msm-pcm-hostless", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_tx2", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm8960_slimbus_2_be_ops, }, /* Ultrasound RX Back End DAI Link */ { .name = "SLIMBUS_2 Hostless Playback", .stream_name = "SLIMBUS_2 Hostless Playback", .cpu_dai_name = "msm-dai-q6.16388", .platform_name = "msm-pcm-hostless", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_rx3", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm8960_slimbus_2_be_ops, }, }; static struct snd_soc_dai_link msm8960_dai_delta_tabla2x[] = { /* Backend DAI Links */ { .name = LPASS_BE_SLIMBUS_0_RX, .stream_name = "Slimbus Playback", .cpu_dai_name = "msm-dai-q6.16384", .platform_name = "msm-pcm-routing", .codec_name = "tabla_codec", .codec_dai_name = "tabla_rx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX, .init = &msm8960_audrx_init, .be_hw_params_fixup = msm8960_slim_0_rx_be_hw_params_fixup, .ops = &msm8960_be_ops, .ignore_pmdown_time = 1, /* this dainlink has playback support */ }, { .name = LPASS_BE_SLIMBUS_0_TX, .stream_name = "Slimbus Capture", .cpu_dai_name = "msm-dai-q6.16385", .platform_name = "msm-pcm-routing", .codec_name = "tabla_codec", .codec_dai_name = "tabla_tx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX, .be_hw_params_fixup = msm8960_slim_0_tx_be_hw_params_fixup, .ops = &msm8960_be_ops, }, /* Ultrasound TX Back End DAI Link */ { .name = "SLIMBUS_2 Hostless Capture", .stream_name = "SLIMBUS_2 Hostless Capture", .cpu_dai_name = "msm-dai-q6.16389", .platform_name = "msm-pcm-hostless", .codec_name = "tabla_codec", .codec_dai_name = "tabla_tx2", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm8960_slimbus_2_be_ops, }, /* Ultrasound RX Back End DAI Link */ { .name = "SLIMBUS_2 Hostless Playback", .stream_name = "SLIMBUS_2 Hostless Playback", .cpu_dai_name = "msm-dai-q6.16388", .platform_name = "msm-pcm-hostless", .codec_name = "tabla_codec", .codec_dai_name = "tabla_rx3", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm8960_slimbus_2_be_ops, }, }; /* Add new MMI DAI links to this structure */ static struct snd_soc_dai_link mmi_dai_links[] = { #ifdef CONFIG_SND_SOC_TLV320AIC3253 /* MI2S I2S RX BACK END DAI Link */ { .name = LPASS_BE_MI2S_RX, .stream_name = "MI2S Playback", .cpu_dai_name = "msm-dai-q6-mi2s", .platform_name = "msm-pcm-routing", .codec_name = "tlv320aic3253.10-0018", .codec_dai_name = "tlv320aic3253_codec", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_MI2S_RX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ops = &msm_mi2s_rx_be_ops, }, #endif /* Primary I2S TX BACK END DAI Link */ { .name = LPASS_BE_PRI_I2S_TX, .stream_name = "Primary I2S Capture", .cpu_dai_name = "msm-dai-q6.1", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_PRI_I2S_TX, .be_hw_params_fixup = msm8960_be_hw_pri_i2s_params_fixup, .ops = &msm_primary_i2s_tx_be_ops, }, #ifdef CONFIG_SND_SOC_TFA9890 /* MI2S I2S RX BACK END DAI Link */ { .name = LPASS_BE_MI2S_RX, .stream_name = "MI2S Playback", .cpu_dai_name = "msm-dai-q6-mi2s", .platform_name = "msm-pcm-routing", .codec_name = "tfa9890.10-0034", .codec_dai_name = "tfa9890_codec", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_MI2S_RX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ops = &msm_mi2s_rx_be_ops, }, #endif /* MI2S I2S TX BACK END DAI Link */ { .name = LPASS_BE_MI2S_TX, .stream_name = "MI2S Capture", .cpu_dai_name = "msm-dai-q6-mi2s", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_MI2S_TX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ops = &msm_mi2s_rx_be_ops, }, /* MI2S I2S RX BACK END DAI Link */ { .name = LPASS_BE_MI2S_RX, .stream_name = "MI2S Playback", .cpu_dai_name = "msm-dai-q6-mi2s", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_MI2S_RX, .be_hw_params_fixup = msm8960_be_hw_params_fixup, .ops = &msm_mi2s_rx_be_ops, }, }; static struct snd_soc_dai_link msm8960_tabla1x_dai[ ARRAY_SIZE(msm8960_dai_common) + ARRAY_SIZE(msm8960_dai_delta_tabla1x)]; static struct snd_soc_dai_link msm8960_dai[ ARRAY_SIZE(msm8960_dai_common) + ARRAY_SIZE(msm8960_dai_delta_tabla2x) + ARRAY_SIZE(mmi_dai_links)]; static struct snd_soc_card snd_soc_tabla1x_card_msm8960 = { .name = "msm8960-tabla1x-snd-card", .long_name = "msm8960-snd-card-wcd", .dai_link = msm8960_tabla1x_dai, .num_links = ARRAY_SIZE(msm8960_tabla1x_dai), .controls = tabla_msm8960_controls, .num_controls = ARRAY_SIZE(tabla_msm8960_controls), }; static struct snd_soc_card snd_soc_card_msm8960 = { .name = "msm8960-snd-card", .long_name = "msm8960-snd-card-wcd", .dai_link = msm8960_dai, .num_links = ARRAY_SIZE(msm8960_dai), .controls = tabla_msm8960_controls, .num_controls = ARRAY_SIZE(tabla_msm8960_controls), }; static struct platform_device *msm8960_snd_device; static struct platform_device *msm8960_snd_tabla1x_device; static int msm8960_configure_headset_mic_gpios(void) { #ifdef CONFIG_MACH_MSM8960_MMI /* FIXME: Headset GPIOs must be passed to as parameters to ensure */ /* no conflicts!!! MMI HW design re-uses these GPIOS in EMU */ pr_err("%s: US_EURO, AV_SWITCH gpios not configured!!!\n", __func__); return -EINVAL; #else int ret; struct pm_gpio param = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S4, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, }; ret = gpio_request(PM8921_GPIO_PM_TO_SYS(23), "AV_SWITCH"); if (ret) { pr_err("%s: Failed to request gpio %d\n", __func__, PM8921_GPIO_PM_TO_SYS(23)); return ret; } ret = pm8xxx_gpio_config(PM8921_GPIO_PM_TO_SYS(23), &param); if (ret) pr_err("%s: Failed to configure gpio %d\n", __func__, PM8921_GPIO_PM_TO_SYS(23)); else gpio_direction_output(PM8921_GPIO_PM_TO_SYS(23), 0); ret = gpio_request(us_euro_sel_gpio, "US_EURO_SWITCH"); if (ret) { pr_err("%s: Failed to request gpio %d\n", __func__, us_euro_sel_gpio); gpio_free(PM8921_GPIO_PM_TO_SYS(23)); return ret; } ret = pm8xxx_gpio_config(us_euro_sel_gpio, &param); if (ret) pr_err("%s: Failed to configure gpio %d\n", __func__, us_euro_sel_gpio); else gpio_direction_output(us_euro_sel_gpio, 0); return 0; #endif } static void msm8960_free_headset_mic_gpios(void) { if (msm8960_headset_gpios_configured) { gpio_free(PM8921_GPIO_PM_TO_SYS(23)); gpio_free(us_euro_sel_gpio); } } #ifdef CONFIG_OF static void msm8960_of_add_dai_links(struct snd_soc_card *card, struct device_node *np) { struct snd_soc_dai_link *tbl = card->dai_link; struct device_node *dai; int i; int ret; const char *ln; if (!np) return; /* Get the specified longname */ ret = of_property_read_string(np, "qcom,msm8960-card-longname", &ln); if (!ret) { snd_soc_tabla1x_card_msm8960.long_name = ln; snd_soc_card_msm8960.long_name = ln; } /* Move pointer to end of table */ tbl += card->num_links; for_each_child_of_node(np, dai) { const char *name; if (!of_device_is_available(dai)) continue; if (!of_device_is_compatible(dai, "qcom,msm8960-dai-link")) continue; ret = of_property_read_string(dai, "qcom,msm8960-codec-name", &name); if (ret) { pr_err("%s: missing codec-name property\n", __func__); continue; } for (i = 0; i < ARRAY_SIZE(mmi_dai_links); i++) { struct snd_soc_dai_link *cur = &mmi_dai_links[i]; /* If no match, skip it */ if (of_prop_cmp(cur->codec_dai_name, name)) continue; pr_debug("%s: Adding MMI DAI link: %s\n", __func__, name); memcpy(tbl, cur, sizeof(struct snd_soc_dai_link)); tbl++; card->num_links++; } } } static void msm8960_free_mach_data(struct snd_soc_card *card) { struct msm8960_asoc_mach_data *data = snd_soc_card_get_drvdata(card); if (data) { kfree(data->pri_i2s_gpios); kfree(data->mi2s_gpios); } kfree(data); } static void msm8960_of_parse_dt(struct snd_soc_card *card, struct device_node *np) { struct msm8960_asoc_mach_data *data; struct gpio *p = NULL; unsigned int cnt; int ret; int i; if (!np) return; data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) { pr_err("%s: couldn't allocate mach data\n", __func__); return; } cnt = of_gpio_named_count(np, "gpios-pri-i2s"); ret = of_property_count_strings(np, "gpios-pri-i2s-names"); if (cnt && cnt != ret) { pr_err("%s: PRI I2S GPIO and label mismatch\n", __func__); goto free_data; } if (cnt) { p = kzalloc(sizeof(struct gpio) * cnt, GFP_KERNEL); if (!p) { pr_err("%s: pri_i2s_gpio alloc failed\n", __func__); goto free_data; } data->pri_i2s_gpios = p; data->num_pri_i2s_gpios = cnt; } for (i = 0; p && i < cnt; i++) { p[i].gpio = of_get_named_gpio(np, "gpios-pri-i2s", i); of_property_read_string_index(np, "gpios-pri-i2s-names", i, &p[i].label); pr_debug("%s: index: %d GPIO: %d name: %s\n", __func__, i, p[i].gpio, p[i].label); } cnt = of_gpio_named_count(np, "gpios-mi2s"); ret = of_property_count_strings(np, "gpios-mi2s-names"); if (cnt && cnt != ret) { pr_err("%s: MI2S GPIO and label mismatch\n", __func__); goto free_pri_i2s; } if (cnt) { p = kzalloc(sizeof(struct gpio) * cnt, GFP_KERNEL); if (!p) { pr_err("%s: mi2s_gpio alloc failed\n", __func__); goto free_pri_i2s; } data->mi2s_gpios = p; data->num_mi2s_gpios = cnt; } for (i = 0; p && i < cnt; i++) { p[i].gpio = of_get_named_gpio(np, "gpios-mi2s", i); of_property_read_string_index(np, "gpios-mi2s-names", i, &p[i].label); pr_debug("%s: index: %d GPIO: %d name: %s\n", __func__, i, p[i].gpio, p[i].label); } snd_soc_card_set_drvdata(card, data); return; free_pri_i2s: kfree(data->pri_i2s_gpios); free_data: kfree(data); return; } #else static inline void msm8960_of_add_dai_links(struct snd_soc_card *card, struct device_node *np) { } static inline void msm8960_free_mach_data(struct snd_soc_card *card) { } static inline void msm8960_of_parse_dt(struct snd_soc_card *card, struct device_node *np) { } #endif static int __init msm8960_audio_init(void) { int ret; struct device_node *np; if (!soc_class_is_msm8960()) { pr_debug("%s: Not the right machine type\n", __func__); return -ENODEV ; } mbhc_cfg.calibration = def_tabla_mbhc_cal(); if (!mbhc_cfg.calibration) { pr_err("Calibration data allocation failed\n"); return -ENOMEM; } msm8960_snd_device = platform_device_alloc("soc-audio", 0); if (!msm8960_snd_device) { pr_err("Platform device allocation failed\n"); kfree(mbhc_cfg.calibration); return -ENOMEM; } np = of_find_compatible_node(NULL, NULL, "qcom,msm8960-soc-audio"); snd_soc_card_msm8960.num_links = 0; memcpy(msm8960_dai, msm8960_dai_common, sizeof(msm8960_dai_common)); snd_soc_card_msm8960.num_links += ARRAY_SIZE(msm8960_dai_common); memcpy(msm8960_dai + ARRAY_SIZE(msm8960_dai_common), msm8960_dai_delta_tabla2x, sizeof(msm8960_dai_delta_tabla2x)); snd_soc_card_msm8960.num_links += ARRAY_SIZE(msm8960_dai_delta_tabla2x); /* Add DT supported DAI Links */ msm8960_of_add_dai_links(&snd_soc_card_msm8960, np); /* Parse DT */ msm8960_of_parse_dt(&snd_soc_card_msm8960, np); platform_set_drvdata(msm8960_snd_device, &snd_soc_card_msm8960); ret = platform_device_add(msm8960_snd_device); if (ret) { platform_device_put(msm8960_snd_device); kfree(mbhc_cfg.calibration); return ret; } msm8960_snd_tabla1x_device = platform_device_alloc("soc-audio", 1); if (!msm8960_snd_tabla1x_device) { pr_err("Platform device allocation failed\n"); kfree(mbhc_cfg.calibration); msm8960_free_mach_data(&snd_soc_card_msm8960); return -ENOMEM; } memcpy(msm8960_tabla1x_dai, msm8960_dai_common, sizeof(msm8960_dai_common)); memcpy(msm8960_tabla1x_dai + ARRAY_SIZE(msm8960_dai_common), msm8960_dai_delta_tabla1x, sizeof(msm8960_dai_delta_tabla1x)); platform_set_drvdata(msm8960_snd_tabla1x_device, &snd_soc_tabla1x_card_msm8960); ret = platform_device_add(msm8960_snd_tabla1x_device); if (ret) { platform_device_put(msm8960_snd_tabla1x_device); kfree(mbhc_cfg.calibration); msm8960_free_mach_data(&snd_soc_card_msm8960); return ret; } if (cpu_is_msm8960()) { if (msm8960_configure_headset_mic_gpios()) { pr_err("%s Fail to configure headset mic gpios\n", __func__); msm8960_headset_gpios_configured = 0; } else msm8960_headset_gpios_configured = 1; } else { msm8960_headset_gpios_configured = 0; pr_debug("%s headset GPIO 23 and 35 not configured msm960ab", __func__); } mutex_init(&cdc_mclk_mutex); atomic_set(&auxpcm_rsc_ref, 0); atomic_set(&mi2s_rsc_ref, 0); return ret; } module_init(msm8960_audio_init); static void __exit msm8960_audio_exit(void) { if (!soc_class_is_msm8960()) { pr_debug("%s: Not the right machine type\n", __func__); return ; } msm8960_free_mach_data(&snd_soc_card_msm8960); msm8960_free_headset_mic_gpios(); platform_device_unregister(msm8960_snd_device); platform_device_unregister(msm8960_snd_tabla1x_device); kfree(mbhc_cfg.calibration); mutex_destroy(&cdc_mclk_mutex); } module_exit(msm8960_audio_exit); MODULE_DESCRIPTION("ALSA SoC MSM8960"); MODULE_LICENSE("GPL v2");
gpl-2.0
jskurka/PyChess-Learning-Module
doc/pychess.widgets.BookCellRenderer.html
23470
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>Python: module pychess.widgets.BookCellRenderer</title> </head><body bgcolor="#f0f0f8"> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="#7799ee"> <td valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong><a href="pychess.html"><font color="#ffffff">pychess</font></a>.<a href="pychess.widgets.html"><font color="#ffffff">widgets</font></a>.BookCellRenderer</strong></big></big></font></td ><td align=right valign=bottom ><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/home/thomas/Programmering/python/skak/svn/lib/pychess/widgets/BookCellRenderer.py">/home/thomas/Programmering/python/skak/svn/lib/pychess/widgets/BookCellRenderer.py</a></font></td></tr></table> <p></p> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#aa55cc"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#fffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr> <tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="gobject.html">gobject</a><br> </td><td width="25%" valign=top><a href="gtk.html">gtk</a><br> </td><td width="25%" valign=top></td><td width="25%" valign=top></td></tr></table></td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ee77aa"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr> <tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl> <dt><font face="helvetica, arial"><a href="__builtin__.html#file">__builtin__.file</a>(<a href="__builtin__.html#object">__builtin__.object</a>) </font></dt><dd> <dl> <dt><font face="helvetica, arial"><a href="pychess.widgets.BookCellRenderer.html#Fileadapter">Fileadapter</a> </font></dt></dl> </dd> <dt><font face="helvetica, arial"><a href="gtk.html#GenericCellRenderer">gtk.GenericCellRenderer</a>(<a href="gtk.html#CellRenderer">gtk.CellRenderer</a>) </font></dt><dd> <dl> <dt><font face="helvetica, arial"><a href="pychess.widgets.BookCellRenderer.html#BookCellRenderer">BookCellRenderer</a> </font></dt></dl> </dd> </dl> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="BookCellRenderer">class <strong>BookCellRenderer</strong></a>(<a href="gtk.html#GenericCellRenderer">gtk.GenericCellRenderer</a>)</font></td></tr> <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl><dt>Method resolution order:</dt> <dd><a href="pychess.widgets.BookCellRenderer.html#BookCellRenderer">BookCellRenderer</a></dd> <dd><a href="gtk.html#GenericCellRenderer">gtk.GenericCellRenderer</a></dd> <dd><a href="gtk.html#CellRenderer">gtk.CellRenderer</a></dd> <dd><a href="gtk.html#Object">gtk.Object</a></dd> <dd><a href="gobject.html#GObject">gobject.GObject</a></dd> <dd><a href="__builtin__.html#object">__builtin__.object</a></dd> </dl> <hr> Methods defined here:<br> <dl><dt><a name="BookCellRenderer-__init__"><strong>__init__</strong></a>(self)</dt></dl> <dl><dt><a name="BookCellRenderer-do_get_property"><strong>do_get_property</strong></a>(self, pspec)</dt></dl> <dl><dt><a name="BookCellRenderer-do_set_property"><strong>do_set_property</strong></a>(self, pspec, value)</dt></dl> <dl><dt><a name="BookCellRenderer-on_get_size"><strong>on_get_size</strong></a>(self, widget, cell_area<font color="#909090">=None</font>)</dt></dl> <dl><dt><a name="BookCellRenderer-on_render"><strong>on_render</strong></a>(self, window, widget, background_area, cell_area, expose_area, flags)</dt></dl> <hr> Data and other attributes defined here:<br> <dl><dt><strong>__gtype__</strong> = &lt;GType pychess+widgets+BookCellRenderer+BookCellRenderer (164200320)&gt;</dl> <hr> Methods inherited from <a href="gtk.html#CellRenderer">gtk.CellRenderer</a>:<br> <dl><dt><a name="BookCellRenderer-activate"><strong>activate</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-editing_canceled"><strong>editing_canceled</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-get_fixed_size"><strong>get_fixed_size</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-get_size"><strong>get_size</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-render"><strong>render</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-set_fixed_size"><strong>set_fixed_size</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-start_editing"><strong>start_editing</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-stop_editing"><strong>stop_editing</strong></a>(...)</dt></dl> <hr> Data and other attributes inherited from <a href="gtk.html#CellRenderer">gtk.CellRenderer</a>:<br> <dl><dt><strong>do_activate</strong> = &lt;built-in method do_activate of GObjectMeta object&gt;</dl> <dl><dt><strong>do_editing_canceled</strong> = &lt;built-in method do_editing_canceled of GObjectMeta object&gt;</dl> <dl><dt><strong>do_editing_started</strong> = &lt;built-in method do_editing_started of GObjectMeta object&gt;</dl> <dl><dt><strong>do_get_size</strong> = &lt;built-in method do_get_size of GObjectMeta object&gt;</dl> <dl><dt><strong>do_render</strong> = &lt;built-in method do_render of GObjectMeta object&gt;</dl> <dl><dt><strong>do_start_editing</strong> = &lt;built-in method do_start_editing of GObjectMeta object&gt;</dl> <hr> Methods inherited from <a href="gtk.html#Object">gtk.Object</a>:<br> <dl><dt><a name="BookCellRenderer-destroy"><strong>destroy</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-flags"><strong>flags</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-remove_data"><strong>remove_data</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-remove_no_notify"><strong>remove_no_notify</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-set_flags"><strong>set_flags</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-unset_flags"><strong>unset_flags</strong></a>(...)</dt></dl> <hr> Data and other attributes inherited from <a href="gtk.html#Object">gtk.Object</a>:<br> <dl><dt><strong>do_destroy</strong> = &lt;built-in method do_destroy of GObjectMeta object&gt;</dl> <hr> Methods inherited from <a href="gobject.html#GObject">gobject.GObject</a>:<br> <dl><dt><a name="BookCellRenderer-__cmp__"><strong>__cmp__</strong></a>(...)</dt><dd><tt>x.<a href="#BookCellRenderer-__cmp__">__cmp__</a>(y)&nbsp;&lt;==&gt;&nbsp;cmp(x,y)</tt></dd></dl> <dl><dt><a name="BookCellRenderer-__gobject_init__"><strong>__gobject_init__</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-__hash__"><strong>__hash__</strong></a>(...)</dt><dd><tt>x.<a href="#BookCellRenderer-__hash__">__hash__</a>()&nbsp;&lt;==&gt;&nbsp;hash(x)</tt></dd></dl> <dl><dt><a name="BookCellRenderer-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#BookCellRenderer-__repr__">__repr__</a>()&nbsp;&lt;==&gt;&nbsp;repr(x)</tt></dd></dl> <dl><dt><a name="BookCellRenderer-chain"><strong>chain</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-connect"><strong>connect</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-connect_after"><strong>connect_after</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-connect_object"><strong>connect_object</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-connect_object_after"><strong>connect_object_after</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-disconnect"><strong>disconnect</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-disconnect_by_func"><strong>disconnect_by_func</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-emit"><strong>emit</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-emit_stop_by_name"><strong>emit_stop_by_name</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-freeze_notify"><strong>freeze_notify</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-get_data"><strong>get_data</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-get_property"><strong>get_property</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_block"><strong>handler_block</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_block_by_func"><strong>handler_block_by_func</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_disconnect"><strong>handler_disconnect</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_is_connected"><strong>handler_is_connected</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_unblock"><strong>handler_unblock</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-handler_unblock_by_func"><strong>handler_unblock_by_func</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-notify"><strong>notify</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-set_data"><strong>set_data</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-set_property"><strong>set_property</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-stop_emission"><strong>stop_emission</strong></a>(...)</dt></dl> <dl><dt><a name="BookCellRenderer-thaw_notify"><strong>thaw_notify</strong></a>(...)</dt></dl> <hr> Data and other attributes inherited from <a href="gobject.html#GObject">gobject.GObject</a>:<br> <dl><dt><strong>__dict__</strong> = &lt;dictproxy object&gt;</dl> <dl><dt><strong>__gdoc__</strong> = 'Object pychess+widgets+BookCellRenderer+BookCell...-peger<font color="#c040c0">\n\n</font>Signals from GObject:<font color="#c040c0">\n</font> notify (GParam)<font color="#c040c0">\n\n</font>'</dl> <dl><dt><strong>__grefcount__</strong> = &lt;attribute '__grefcount__' of 'gobject.GObject' objects&gt;</dl> <dl><dt><strong>__new__</strong> = &lt;built-in method __new__ of GObjectMeta object&gt;<dd><tt>T.<a href="#BookCellRenderer-__new__">__new__</a>(S,&nbsp;...)&nbsp;-&gt;&nbsp;a&nbsp;new&nbsp;object&nbsp;with&nbsp;type&nbsp;S,&nbsp;a&nbsp;subtype&nbsp;of&nbsp;T</tt></dl> <dl><dt><strong>props</strong> = &lt;gobject.GProps object&gt;</dl> </td></tr></table> <p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#ffc8d8"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#000000" face="helvetica, arial"><a name="Fileadapter">class <strong>Fileadapter</strong></a>(<a href="__builtin__.html#file">__builtin__.file</a>)</font></td></tr> <tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl><dt>Method resolution order:</dt> <dd><a href="pychess.widgets.BookCellRenderer.html#Fileadapter">Fileadapter</a></dd> <dd><a href="__builtin__.html#file">__builtin__.file</a></dd> <dd><a href="__builtin__.html#object">__builtin__.object</a></dd> </dl> <hr> Methods defined here:<br> <dl><dt><a name="Fileadapter-__init__"><strong>__init__</strong></a>(self, loader)</dt><dd><tt>#Doesn't&nbsp;work&nbsp;:(</tt></dd></dl> <dl><dt><a name="Fileadapter-write"><strong>write</strong></a>(self, s)</dt></dl> <hr> Data and other attributes defined here:<br> <dl><dt><strong>__dict__</strong> = &lt;dictproxy object&gt;<dd><tt>dictionary&nbsp;for&nbsp;instance&nbsp;variables&nbsp;(if&nbsp;defined)</tt></dl> <hr> Methods inherited from <a href="__builtin__.html#file">__builtin__.file</a>:<br> <dl><dt><a name="Fileadapter-__delattr__"><strong>__delattr__</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-__delattr__">__delattr__</a>('name')&nbsp;&lt;==&gt;&nbsp;del&nbsp;x.name</tt></dd></dl> <dl><dt><a name="Fileadapter-__getattribute__"><strong>__getattribute__</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-__getattribute__">__getattribute__</a>('name')&nbsp;&lt;==&gt;&nbsp;x.name</tt></dd></dl> <dl><dt><a name="Fileadapter-__iter__"><strong>__iter__</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-__iter__">__iter__</a>()&nbsp;&lt;==&gt;&nbsp;iter(x)</tt></dd></dl> <dl><dt><a name="Fileadapter-__repr__"><strong>__repr__</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-__repr__">__repr__</a>()&nbsp;&lt;==&gt;&nbsp;repr(x)</tt></dd></dl> <dl><dt><a name="Fileadapter-__setattr__"><strong>__setattr__</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-__setattr__">__setattr__</a>('name',&nbsp;value)&nbsp;&lt;==&gt;&nbsp;x.name&nbsp;=&nbsp;value</tt></dd></dl> <dl><dt><a name="Fileadapter-close"><strong>close</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-close">close</a>()&nbsp;-&gt;&nbsp;None&nbsp;or&nbsp;(perhaps)&nbsp;an&nbsp;integer.&nbsp;&nbsp;Close&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>.<br> &nbsp;<br> Sets&nbsp;data&nbsp;attribute&nbsp;.closed&nbsp;to&nbsp;True.&nbsp;&nbsp;A&nbsp;closed&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;cannot&nbsp;be&nbsp;used&nbsp;for<br> further&nbsp;I/O&nbsp;operations.&nbsp;&nbsp;<a href="#Fileadapter-close">close</a>()&nbsp;may&nbsp;be&nbsp;called&nbsp;more&nbsp;than&nbsp;once&nbsp;without<br> error.&nbsp;&nbsp;Some&nbsp;kinds&nbsp;of&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;objects&nbsp;(for&nbsp;example,&nbsp;opened&nbsp;by&nbsp;popen())<br> may&nbsp;return&nbsp;an&nbsp;exit&nbsp;status&nbsp;upon&nbsp;closing.</tt></dd></dl> <dl><dt><a name="Fileadapter-fileno"><strong>fileno</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-fileno">fileno</a>()&nbsp;-&gt;&nbsp;integer&nbsp;"<a href="__builtin__.html#file">file</a>&nbsp;descriptor".<br> &nbsp;<br> This&nbsp;is&nbsp;needed&nbsp;for&nbsp;lower-level&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;interfaces,&nbsp;such&nbsp;os.<a href="#Fileadapter-read">read</a>().</tt></dd></dl> <dl><dt><a name="Fileadapter-flush"><strong>flush</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-flush">flush</a>()&nbsp;-&gt;&nbsp;None.&nbsp;&nbsp;Flush&nbsp;the&nbsp;internal&nbsp;I/O&nbsp;buffer.</tt></dd></dl> <dl><dt><a name="Fileadapter-isatty"><strong>isatty</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-isatty">isatty</a>()&nbsp;-&gt;&nbsp;true&nbsp;or&nbsp;false.&nbsp;&nbsp;True&nbsp;if&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;is&nbsp;connected&nbsp;to&nbsp;a&nbsp;tty&nbsp;device.</tt></dd></dl> <dl><dt><a name="Fileadapter-next"><strong>next</strong></a>(...)</dt><dd><tt>x.<a href="#Fileadapter-next">next</a>()&nbsp;-&gt;&nbsp;the&nbsp;next&nbsp;value,&nbsp;or&nbsp;raise&nbsp;StopIteration</tt></dd></dl> <dl><dt><a name="Fileadapter-read"><strong>read</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-read">read</a>([size])&nbsp;-&gt;&nbsp;read&nbsp;at&nbsp;most&nbsp;size&nbsp;bytes,&nbsp;returned&nbsp;as&nbsp;a&nbsp;string.<br> &nbsp;<br> If&nbsp;the&nbsp;size&nbsp;argument&nbsp;is&nbsp;negative&nbsp;or&nbsp;omitted,&nbsp;read&nbsp;until&nbsp;EOF&nbsp;is&nbsp;reached.<br> Notice&nbsp;that&nbsp;when&nbsp;in&nbsp;non-blocking&nbsp;mode,&nbsp;less&nbsp;data&nbsp;than&nbsp;what&nbsp;was&nbsp;requested<br> may&nbsp;be&nbsp;returned,&nbsp;even&nbsp;if&nbsp;no&nbsp;size&nbsp;parameter&nbsp;was&nbsp;given.</tt></dd></dl> <dl><dt><a name="Fileadapter-readinto"><strong>readinto</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-readinto">readinto</a>()&nbsp;-&gt;&nbsp;Undocumented.&nbsp;&nbsp;Don't&nbsp;use&nbsp;this;&nbsp;it&nbsp;may&nbsp;go&nbsp;away.</tt></dd></dl> <dl><dt><a name="Fileadapter-readline"><strong>readline</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-readline">readline</a>([size])&nbsp;-&gt;&nbsp;next&nbsp;line&nbsp;from&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>,&nbsp;as&nbsp;a&nbsp;string.<br> &nbsp;<br> Retain&nbsp;newline.&nbsp;&nbsp;A&nbsp;non-negative&nbsp;size&nbsp;argument&nbsp;limits&nbsp;the&nbsp;maximum<br> number&nbsp;of&nbsp;bytes&nbsp;to&nbsp;return&nbsp;(an&nbsp;incomplete&nbsp;line&nbsp;may&nbsp;be&nbsp;returned&nbsp;then).<br> Return&nbsp;an&nbsp;empty&nbsp;string&nbsp;at&nbsp;EOF.</tt></dd></dl> <dl><dt><a name="Fileadapter-readlines"><strong>readlines</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-readlines">readlines</a>([size])&nbsp;-&gt;&nbsp;list&nbsp;of&nbsp;strings,&nbsp;each&nbsp;a&nbsp;line&nbsp;from&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>.<br> &nbsp;<br> Call&nbsp;<a href="#Fileadapter-readline">readline</a>()&nbsp;repeatedly&nbsp;and&nbsp;return&nbsp;a&nbsp;list&nbsp;of&nbsp;the&nbsp;lines&nbsp;so&nbsp;read.<br> The&nbsp;optional&nbsp;size&nbsp;argument,&nbsp;if&nbsp;given,&nbsp;is&nbsp;an&nbsp;approximate&nbsp;bound&nbsp;on&nbsp;the<br> total&nbsp;number&nbsp;of&nbsp;bytes&nbsp;in&nbsp;the&nbsp;lines&nbsp;returned.</tt></dd></dl> <dl><dt><a name="Fileadapter-seek"><strong>seek</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-seek">seek</a>(offset[,&nbsp;whence])&nbsp;-&gt;&nbsp;None.&nbsp;&nbsp;Move&nbsp;to&nbsp;new&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;position.<br> &nbsp;<br> Argument&nbsp;offset&nbsp;is&nbsp;a&nbsp;byte&nbsp;count.&nbsp;&nbsp;Optional&nbsp;argument&nbsp;whence&nbsp;defaults&nbsp;to<br> 0&nbsp;(offset&nbsp;from&nbsp;start&nbsp;of&nbsp;<a href="__builtin__.html#file">file</a>,&nbsp;offset&nbsp;should&nbsp;be&nbsp;&gt;=&nbsp;0);&nbsp;other&nbsp;values&nbsp;are&nbsp;1<br> (move&nbsp;relative&nbsp;to&nbsp;current&nbsp;position,&nbsp;positive&nbsp;or&nbsp;negative),&nbsp;and&nbsp;2&nbsp;(move<br> relative&nbsp;to&nbsp;end&nbsp;of&nbsp;<a href="__builtin__.html#file">file</a>,&nbsp;usually&nbsp;negative,&nbsp;although&nbsp;many&nbsp;platforms&nbsp;allow<br> seeking&nbsp;beyond&nbsp;the&nbsp;end&nbsp;of&nbsp;a&nbsp;<a href="__builtin__.html#file">file</a>).&nbsp;&nbsp;If&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;is&nbsp;opened&nbsp;in&nbsp;text&nbsp;mode,<br> only&nbsp;offsets&nbsp;returned&nbsp;by&nbsp;<a href="#Fileadapter-tell">tell</a>()&nbsp;are&nbsp;legal.&nbsp;&nbsp;Use&nbsp;of&nbsp;other&nbsp;offsets&nbsp;causes<br> undefined&nbsp;behavior.<br> Note&nbsp;that&nbsp;not&nbsp;all&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;objects&nbsp;are&nbsp;seekable.</tt></dd></dl> <dl><dt><a name="Fileadapter-tell"><strong>tell</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-tell">tell</a>()&nbsp;-&gt;&nbsp;current&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;position,&nbsp;an&nbsp;integer&nbsp;(may&nbsp;be&nbsp;a&nbsp;long&nbsp;integer).</tt></dd></dl> <dl><dt><a name="Fileadapter-truncate"><strong>truncate</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-truncate">truncate</a>([size])&nbsp;-&gt;&nbsp;None.&nbsp;&nbsp;Truncate&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;to&nbsp;at&nbsp;most&nbsp;size&nbsp;bytes.<br> &nbsp;<br> Size&nbsp;defaults&nbsp;to&nbsp;the&nbsp;current&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;position,&nbsp;as&nbsp;returned&nbsp;by&nbsp;<a href="#Fileadapter-tell">tell</a>().</tt></dd></dl> <dl><dt><a name="Fileadapter-writelines"><strong>writelines</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-writelines">writelines</a>(sequence_of_strings)&nbsp;-&gt;&nbsp;None.&nbsp;&nbsp;Write&nbsp;the&nbsp;strings&nbsp;to&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>.<br> &nbsp;<br> Note&nbsp;that&nbsp;newlines&nbsp;are&nbsp;not&nbsp;added.&nbsp;&nbsp;The&nbsp;sequence&nbsp;can&nbsp;be&nbsp;any&nbsp;iterable&nbsp;object<br> producing&nbsp;strings.&nbsp;This&nbsp;is&nbsp;equivalent&nbsp;to&nbsp;calling&nbsp;<a href="#Fileadapter-write">write</a>()&nbsp;for&nbsp;each&nbsp;string.</tt></dd></dl> <dl><dt><a name="Fileadapter-xreadlines"><strong>xreadlines</strong></a>(...)</dt><dd><tt><a href="#Fileadapter-xreadlines">xreadlines</a>()&nbsp;-&gt;&nbsp;returns&nbsp;self.<br> &nbsp;<br> For&nbsp;backward&nbsp;compatibility.&nbsp;File&nbsp;objects&nbsp;now&nbsp;include&nbsp;the&nbsp;performance<br> optimizations&nbsp;previously&nbsp;implemented&nbsp;in&nbsp;the&nbsp;xreadlines&nbsp;module.</tt></dd></dl> <hr> Data and other attributes inherited from <a href="__builtin__.html#file">__builtin__.file</a>:<br> <dl><dt><strong>__new__</strong> = &lt;built-in method __new__ of type object&gt;<dd><tt>T.<a href="#Fileadapter-__new__">__new__</a>(S,&nbsp;...)&nbsp;-&gt;&nbsp;a&nbsp;new&nbsp;object&nbsp;with&nbsp;type&nbsp;S,&nbsp;a&nbsp;subtype&nbsp;of&nbsp;T</tt></dl> <dl><dt><strong>closed</strong> = &lt;attribute 'closed' of 'file' objects&gt;<dd><tt>True&nbsp;if&nbsp;the&nbsp;<a href="__builtin__.html#file">file</a>&nbsp;is&nbsp;closed</tt></dl> <dl><dt><strong>encoding</strong> = &lt;member 'encoding' of 'file' objects&gt;<dd><tt><a href="__builtin__.html#file">file</a>&nbsp;encoding</tt></dl> <dl><dt><strong>mode</strong> = &lt;member 'mode' of 'file' objects&gt;<dd><tt><a href="__builtin__.html#file">file</a>&nbsp;mode&nbsp;('r',&nbsp;'U',&nbsp;'w',&nbsp;'a',&nbsp;possibly&nbsp;with&nbsp;'b'&nbsp;or&nbsp;'+'&nbsp;added)</tt></dl> <dl><dt><strong>name</strong> = &lt;member 'name' of 'file' objects&gt;<dd><tt><a href="__builtin__.html#file">file</a>&nbsp;name</tt></dl> <dl><dt><strong>newlines</strong> = &lt;attribute 'newlines' of 'file' objects&gt;<dd><tt>end-of-line&nbsp;convention&nbsp;used&nbsp;in&nbsp;this&nbsp;<a href="__builtin__.html#file">file</a></tt></dl> <dl><dt><strong>softspace</strong> = &lt;member 'softspace' of 'file' objects&gt;<dd><tt>flag&nbsp;indicating&nbsp;that&nbsp;a&nbsp;space&nbsp;needs&nbsp;to&nbsp;be&nbsp;printed;&nbsp;used&nbsp;by&nbsp;print</tt></dl> </td></tr></table></td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#eeaa77"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr> <tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><dl><dt><a name="-ceil"><strong>ceil</strong></a>(...)</dt><dd><tt><a href="#-ceil">ceil</a>(x)<br> &nbsp;<br> Return&nbsp;the&nbsp;ceiling&nbsp;of&nbsp;x&nbsp;as&nbsp;a&nbsp;float.<br> This&nbsp;is&nbsp;the&nbsp;smallest&nbsp;integral&nbsp;value&nbsp;&gt;=&nbsp;x.</tt></dd></dl> <dl><dt><a name="-connectToPixbuf"><strong>connectToPixbuf</strong></a>(pixbuf, cairo)</dt></dl> <dl><dt><a name="-getCairoPixbuf"><strong>getCairoPixbuf</strong></a>(width, height)</dt></dl> <dl><dt><a name="-paintGraph"><strong>paintGraph</strong></a>(cairo, win, draw, loss, rect)</dt></dl> <dl><dt><a name="-pathBlock"><strong>pathBlock</strong></a>(cairo, x, y, w, h)</dt></dl> <dl><dt><a name="-surfaceToPixbuf"><strong>surfaceToPixbuf</strong></a>(surface)</dt></dl> <dl><dt><a name="-surfaceToPixbuf2"><strong>surfaceToPixbuf2</strong></a>(surface)</dt></dl> </td></tr></table><p> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="#55aa55"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr> <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td> <td width="100%"><strong>height</strong> = 23<br> <strong>width</strong> = 80</td></tr></table> </body></html>
gpl-3.0
ShopwareHackathon/shopware_search_optimization
shopware.php
3731
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ // Check the minimum required php version if (version_compare(PHP_VERSION, '5.4.0', '<')) { header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Your server is running PHP version ' . PHP_VERSION . ' but Shopware 5 requires at least PHP 5.4.0'; echo '<h2>Fehler</h2>'; echo 'Auf Ihrem Server läuft PHP version ' . PHP_VERSION . ', Shopware 5 benötigt mindestens PHP 5.4.0'; return; } // Check for active auto update or manual update if (is_file('files/update/update.json') || is_dir('update-assets')) { header('Content-type: text/html; charset=utf-8', true, 503); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 1200'); echo file_get_contents(__DIR__ . '/recovery/update/maintenance.html'); return; } // Check for installation if (is_dir('recovery/install') && !is_file('recovery/install/data/install.lock')) { if (PHP_SAPI == 'cli') { echo 'Shopware 5 must be configured before use. Please run the Shopware installer by executing \'php recovery/install/index.php\'.'.PHP_EOL; } else { $basePath = 'recovery/install'; $baseURL = str_replace(basename(__FILE__), '', $_SERVER['SCRIPT_NAME']); $baseURL = rtrim($baseURL, '/'); $installerURL = $baseURL.'/'.$basePath; if (strpos($_SERVER['REQUEST_URI'], $basePath) === false) { header('Location: '.$installerURL); exit; } header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Shopware 5 must be configured before use. Please run the <a href="recovery/install/?language=en">installer</a>.'; echo '<h2>Fehler</h2>'; echo 'Shopware 5 muss zunächst konfiguriert werden. Bitte führen Sie den <a href="recovery/install/?language=de">Installer</a> aus.'; } exit; } // check for composer autoloader if (!file_exists('vendor/autoload.php')) { header('Content-type: text/html; charset=utf-8', true, 503); echo '<h2>Error</h2>'; echo 'Please execute "composer install" from the command line to install the required dependencies for Shopware 5'; echo '<h2>Fehler</h2>'; echo 'Bitte führen Sie zuerst "composer install" aus.'; return; } require __DIR__ . '/autoload.php'; use Shopware\Kernel; use Shopware\Components\HttpCache\AppCache; use Symfony\Component\HttpFoundation\Request; $environment = getenv('SHOPWARE_ENV') ?: getenv('REDIRECT_SHOPWARE_ENV') ?: 'production'; $kernel = new Kernel($environment, $environment !== 'production'); if ($kernel->isHttpCacheEnabled()) { $kernel = new AppCache($kernel, $kernel->getHttpCacheConfig()); } $request = Request::createFromGlobals(); $kernel->handle($request) ->send();
agpl-3.0
ndufresne/gst-plugins-good
gst/rtp/gstrtptheorapay.c
29116
/* GStreamer * Copyright (C) <2006> Wim Taymans <wim.taymans@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <string.h> #include <gst/rtp/gstrtpbuffer.h> #include "fnv1hash.h" #include "gstrtptheorapay.h" #define THEORA_ID_LEN 42 GST_DEBUG_CATEGORY_STATIC (rtptheorapay_debug); #define GST_CAT_DEFAULT (rtptheorapay_debug) /* references: * http://svn.xiph.org/trunk/theora/doc/draft-ietf-avt-rtp-theora-01.txt */ static GstStaticPadTemplate gst_rtp_theora_pay_src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("application/x-rtp, " "media = (string) \"video\", " "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " "clock-rate = (int) 90000, " "encoding-name = (string) \"THEORA\"" /* All required parameters * * "sampling = (string) { "YCbCr-4:2:0", "YCbCr-4:2:2", "YCbCr-4:4:4" } " * "width = (string) [1, 1048561] (multiples of 16) " * "height = (string) [1, 1048561] (multiples of 16) " * "configuration = (string) ANY" */ /* All optional parameters * * "configuration-uri =" * "delivery-method = (string) { inline, in_band, out_band/<specific_name> } " */ ) ); static GstStaticPadTemplate gst_rtp_theora_pay_sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("video/x-theora") ); #define DEFAULT_CONFIG_INTERVAL 0 enum { PROP_0, PROP_CONFIG_INTERVAL }; #define gst_rtp_theora_pay_parent_class parent_class G_DEFINE_TYPE (GstRtpTheoraPay, gst_rtp_theora_pay, GST_TYPE_RTP_BASE_PAYLOAD); static gboolean gst_rtp_theora_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps); static GstStateChangeReturn gst_rtp_theora_pay_change_state (GstElement * element, GstStateChange transition); static GstFlowReturn gst_rtp_theora_pay_handle_buffer (GstRTPBasePayload * pad, GstBuffer * buffer); static gboolean gst_rtp_theora_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event); static gboolean gst_rtp_theora_pay_parse_id (GstRTPBasePayload * basepayload, guint8 * data, guint size); static gboolean gst_rtp_theora_pay_finish_headers (GstRTPBasePayload * basepayload); static void gst_rtp_theora_pay_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_rtp_theora_pay_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void gst_rtp_theora_pay_class_init (GstRtpTheoraPayClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstRTPBasePayloadClass *gstrtpbasepayload_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass; gstelement_class->change_state = gst_rtp_theora_pay_change_state; gstrtpbasepayload_class->set_caps = gst_rtp_theora_pay_setcaps; gstrtpbasepayload_class->handle_buffer = gst_rtp_theora_pay_handle_buffer; gstrtpbasepayload_class->sink_event = gst_rtp_theora_pay_sink_event; gobject_class->set_property = gst_rtp_theora_pay_set_property; gobject_class->get_property = gst_rtp_theora_pay_get_property; gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&gst_rtp_theora_pay_src_template)); gst_element_class_add_pad_template (gstelement_class, gst_static_pad_template_get (&gst_rtp_theora_pay_sink_template)); gst_element_class_set_static_metadata (gstelement_class, "RTP Theora payloader", "Codec/Payloader/Network/RTP", "Payload-encode Theora video into RTP packets (draft-01 RFC XXXX)", "Wim Taymans <wim.taymans@gmail.com>"); GST_DEBUG_CATEGORY_INIT (rtptheorapay_debug, "rtptheorapay", 0, "Theora RTP Payloader"); g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CONFIG_INTERVAL, g_param_spec_uint ("config-interval", "Config Send Interval", "Send Config Insertion Interval in seconds (configuration headers " "will be multiplexed in the data stream when detected.) (0 = disabled)", 0, 3600, DEFAULT_CONFIG_INTERVAL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS) ); } static void gst_rtp_theora_pay_init (GstRtpTheoraPay * rtptheorapay) { rtptheorapay->last_config = GST_CLOCK_TIME_NONE; } static void gst_rtp_theora_pay_clear_packet (GstRtpTheoraPay * rtptheorapay) { if (rtptheorapay->packet) gst_buffer_unref (rtptheorapay->packet); rtptheorapay->packet = NULL; } static void gst_rtp_theora_pay_cleanup (GstRtpTheoraPay * rtptheorapay) { g_list_foreach (rtptheorapay->headers, (GFunc) gst_mini_object_unref, NULL); g_list_free (rtptheorapay->headers); rtptheorapay->headers = NULL; gst_rtp_theora_pay_clear_packet (rtptheorapay); if (rtptheorapay->config_data) g_free (rtptheorapay->config_data); rtptheorapay->config_data = NULL; rtptheorapay->last_config = GST_CLOCK_TIME_NONE; } static gboolean gst_rtp_theora_pay_setcaps (GstRTPBasePayload * basepayload, GstCaps * caps) { GstRtpTheoraPay *rtptheorapay; GstStructure *s; const GValue *array; gint asize, i; GstBuffer *buf; GstMapInfo map; rtptheorapay = GST_RTP_THEORA_PAY (basepayload); s = gst_caps_get_structure (caps, 0); rtptheorapay->need_headers = TRUE; if ((array = gst_structure_get_value (s, "streamheader")) == NULL) goto done; if (G_VALUE_TYPE (array) != GST_TYPE_ARRAY) goto done; if ((asize = gst_value_array_get_size (array)) < 3) goto done; for (i = 0; i < asize; i++) { const GValue *value; value = gst_value_array_get_value (array, i); if ((buf = gst_value_get_buffer (value)) == NULL) goto null_buffer; gst_buffer_map (buf, &map, GST_MAP_READ); /* no data packets allowed */ if (map.size < 1) goto invalid_streamheader; /* we need packets with id 0x80, 0x81, 0x82 */ if (map.data[0] != 0x80 + i) goto invalid_streamheader; if (i == 0) { /* identification, we need to parse this in order to get the clock rate. */ if (G_UNLIKELY (!gst_rtp_theora_pay_parse_id (basepayload, map.data, map.size))) goto parse_id_failed; } GST_DEBUG_OBJECT (rtptheorapay, "collecting header %d", i); rtptheorapay->headers = g_list_append (rtptheorapay->headers, gst_buffer_ref (buf)); gst_buffer_unmap (buf, &map); } if (!gst_rtp_theora_pay_finish_headers (basepayload)) goto finish_failed; done: return TRUE; /* ERRORS */ null_buffer: { GST_WARNING_OBJECT (rtptheorapay, "streamheader with null buffer received"); return FALSE; } invalid_streamheader: { GST_WARNING_OBJECT (rtptheorapay, "unable to parse initial header"); gst_buffer_unmap (buf, &map); return FALSE; } parse_id_failed: { GST_WARNING_OBJECT (rtptheorapay, "unable to parse initial header"); gst_buffer_unmap (buf, &map); return FALSE; } finish_failed: { GST_WARNING_OBJECT (rtptheorapay, "unable to finish headers"); return FALSE; } } static void gst_rtp_theora_pay_reset_packet (GstRtpTheoraPay * rtptheorapay, guint8 TDT) { guint payload_len; GstRTPBuffer rtp = { NULL }; GST_DEBUG_OBJECT (rtptheorapay, "reset packet"); rtptheorapay->payload_pos = 4; gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_READ, &rtp); payload_len = gst_rtp_buffer_get_payload_len (&rtp); gst_rtp_buffer_unmap (&rtp); rtptheorapay->payload_left = payload_len - 4; rtptheorapay->payload_duration = 0; rtptheorapay->payload_F = 0; rtptheorapay->payload_TDT = TDT; rtptheorapay->payload_pkts = 0; } static void gst_rtp_theora_pay_init_packet (GstRtpTheoraPay * rtptheorapay, guint8 TDT, GstClockTime timestamp) { GST_DEBUG_OBJECT (rtptheorapay, "starting new packet, TDT: %d", TDT); if (rtptheorapay->packet) gst_buffer_unref (rtptheorapay->packet); /* new packet allocate max packet size */ rtptheorapay->packet = gst_rtp_buffer_new_allocate_len (GST_RTP_BASE_PAYLOAD_MTU (rtptheorapay), 0, 0); gst_rtp_theora_pay_reset_packet (rtptheorapay, TDT); GST_BUFFER_TIMESTAMP (rtptheorapay->packet) = timestamp; } static GstFlowReturn gst_rtp_theora_pay_flush_packet (GstRtpTheoraPay * rtptheorapay) { GstFlowReturn ret; guint8 *payload; guint hlen; GstRTPBuffer rtp = { NULL }; /* check for empty packet */ if (!rtptheorapay->packet || rtptheorapay->payload_pos <= 4) return GST_FLOW_OK; GST_DEBUG_OBJECT (rtptheorapay, "flushing packet"); gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp); /* fix header */ payload = gst_rtp_buffer_get_payload (&rtp); /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ident | F |TDT|# pkts.| * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * F: Fragment type (0=none, 1=start, 2=cont, 3=end) * TDT: Theora data type (0=theora, 1=config, 2=comment, 3=reserved) * pkts: number of packets. */ payload[0] = (rtptheorapay->payload_ident >> 16) & 0xff; payload[1] = (rtptheorapay->payload_ident >> 8) & 0xff; payload[2] = (rtptheorapay->payload_ident) & 0xff; payload[3] = (rtptheorapay->payload_F & 0x3) << 6 | (rtptheorapay->payload_TDT & 0x3) << 4 | (rtptheorapay->payload_pkts & 0xf); gst_rtp_buffer_unmap (&rtp); /* shrink the buffer size to the last written byte */ hlen = gst_rtp_buffer_calc_header_len (0); gst_buffer_resize (rtptheorapay->packet, 0, hlen + rtptheorapay->payload_pos); GST_BUFFER_DURATION (rtptheorapay->packet) = rtptheorapay->payload_duration; /* push, this gives away our ref to the packet, so clear it. */ ret = gst_rtp_base_payload_push (GST_RTP_BASE_PAYLOAD (rtptheorapay), rtptheorapay->packet); rtptheorapay->packet = NULL; return ret; } static gboolean gst_rtp_theora_pay_finish_headers (GstRTPBasePayload * basepayload) { GstRtpTheoraPay *rtptheorapay = GST_RTP_THEORA_PAY (basepayload); GList *walk; guint length, size, n_headers, configlen, extralen; gchar *wstr, *hstr, *configuration; guint8 *data, *config; guint32 ident; gboolean res; GST_DEBUG_OBJECT (rtptheorapay, "finish headers"); if (!rtptheorapay->headers) { GST_DEBUG_OBJECT (rtptheorapay, "We need 2 headers but have none"); goto no_headers; } /* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Number of packed headers | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Packed header | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Packed header | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | .... | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * We only construct a config containing 1 packed header like this: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ident | length .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * .. | n. of headers | length1 | length2 .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * .. | Identification Header .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ................................................................. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * .. | Comment Header .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ................................................................. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * .. Comment Header | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Setup Header .. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ................................................................. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * .. Setup Header | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ /* we need 4 bytes for the number of headers (which is always 1), 3 bytes for * the ident, 2 bytes for length, 1 byte for n. of headers. */ size = 4 + 3 + 2 + 1; /* count the size of the headers first and update the hash */ length = 0; n_headers = 0; ident = fnv1_hash_32_new (); extralen = 1; for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) { GstBuffer *buf = GST_BUFFER_CAST (walk->data); GstMapInfo map; guint bsize; bsize = gst_buffer_get_size (buf); length += bsize; n_headers++; /* count number of bytes needed for length fields, we don't need this for * the last header. */ if (g_list_next (walk)) { do { size++; extralen++; bsize >>= 7; } while (bsize); } /* update hash */ gst_buffer_map (buf, &map, GST_MAP_READ); ident = fnv1_hash_32_update (ident, map.data, map.size); gst_buffer_unmap (buf, &map); } /* packet length is header size + packet length */ configlen = size + length; config = data = g_malloc (configlen); /* number of packed headers, we only pack 1 header */ data[0] = 0; data[1] = 0; data[2] = 0; data[3] = 1; ident = fnv1_hash_32_to_24 (ident); rtptheorapay->payload_ident = ident; GST_DEBUG_OBJECT (rtptheorapay, "ident 0x%08x", ident); /* take lower 3 bytes */ data[4] = (ident >> 16) & 0xff; data[5] = (ident >> 8) & 0xff; data[6] = ident & 0xff; /* store length of all theora headers */ data[7] = ((length) >> 8) & 0xff; data[8] = (length) & 0xff; /* store number of headers minus one. */ data[9] = n_headers - 1; data += 10; /* store length for each header */ for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) { GstBuffer *buf = GST_BUFFER_CAST (walk->data); guint bsize, size, temp; guint flag; /* only need to store the length when it's not the last header */ if (!g_list_next (walk)) break; bsize = gst_buffer_get_size (buf); /* calc size */ size = 0; do { size++; bsize >>= 7; } while (bsize); temp = size; bsize = gst_buffer_get_size (buf); /* write the size backwards */ flag = 0; while (size) { size--; data[size] = (bsize & 0x7f) | flag; bsize >>= 7; flag = 0x80; /* Flag bit on all bytes of the length except the last */ } data += temp; } /* copy header data */ for (walk = rtptheorapay->headers; walk; walk = g_list_next (walk)) { GstBuffer *buf = GST_BUFFER_CAST (walk->data); gst_buffer_extract (buf, 0, data, gst_buffer_get_size (buf)); data += gst_buffer_get_size (buf); gst_buffer_unref (buf); } g_list_free (rtptheorapay->headers); rtptheorapay->headers = NULL; rtptheorapay->need_headers = FALSE; /* serialize to base64 */ configuration = g_base64_encode (config, configlen); /* store for later re-sending */ if (rtptheorapay->config_data) g_free (rtptheorapay->config_data); rtptheorapay->config_size = configlen - 4 - 3 - 2; rtptheorapay->config_data = g_malloc (rtptheorapay->config_size); rtptheorapay->config_extra_len = extralen; memcpy (rtptheorapay->config_data, config + 4 + 3 + 2, rtptheorapay->config_size); g_free (config); /* configure payloader settings */ wstr = g_strdup_printf ("%d", rtptheorapay->width); hstr = g_strdup_printf ("%d", rtptheorapay->height); gst_rtp_base_payload_set_options (basepayload, "video", TRUE, "THEORA", 90000); res = gst_rtp_base_payload_set_outcaps (basepayload, "sampling", G_TYPE_STRING, "YCbCr-4:2:0", "width", G_TYPE_STRING, wstr, "height", G_TYPE_STRING, hstr, "configuration", G_TYPE_STRING, configuration, "delivery-method", G_TYPE_STRING, "inline", /* don't set the other defaults */ NULL); g_free (wstr); g_free (hstr); g_free (configuration); return res; /* ERRORS */ no_headers: { GST_DEBUG_OBJECT (rtptheorapay, "finish headers"); return FALSE; } } static gboolean gst_rtp_theora_pay_parse_id (GstRTPBasePayload * basepayload, guint8 * data, guint size) { GstRtpTheoraPay *rtptheorapay; gint width, height; rtptheorapay = GST_RTP_THEORA_PAY (basepayload); if (G_UNLIKELY (size < 42)) goto too_short; if (G_UNLIKELY (memcmp (data, "\200theora", 7))) goto invalid_start; data += 7; if (G_UNLIKELY (data[0] != 3)) goto invalid_version; if (G_UNLIKELY (data[1] != 2)) goto invalid_version; data += 3; width = GST_READ_UINT16_BE (data) << 4; data += 2; height = GST_READ_UINT16_BE (data) << 4; data += 2; /* FIXME, parse pixel format */ /* store values */ rtptheorapay->width = width; rtptheorapay->height = height; return TRUE; /* ERRORS */ too_short: { GST_ELEMENT_ERROR (basepayload, STREAM, DECODE, (NULL), ("Identification packet is too short, need at least 42, got %d", size)); return FALSE; } invalid_start: { GST_ELEMENT_ERROR (basepayload, STREAM, DECODE, (NULL), ("Invalid header start in identification packet")); return FALSE; } invalid_version: { GST_ELEMENT_ERROR (basepayload, STREAM, DECODE, (NULL), ("Invalid version")); return FALSE; } } static GstFlowReturn gst_rtp_theora_pay_payload_buffer (GstRtpTheoraPay * rtptheorapay, guint8 TDT, guint8 * data, guint size, GstClockTime timestamp, GstClockTime duration, guint not_in_length) { GstFlowReturn ret = GST_FLOW_OK; guint newsize; guint packet_len; GstClockTime newduration; gboolean flush; guint plen; guint8 *ppos, *payload; gboolean fragmented; GstRTPBuffer rtp = { NULL }; /* size increases with packet length and 2 bytes size eader. */ newduration = rtptheorapay->payload_duration; if (duration != GST_CLOCK_TIME_NONE) newduration += duration; newsize = rtptheorapay->payload_pos + 2 + size; packet_len = gst_rtp_buffer_calc_packet_len (newsize, 0, 0); /* check buffer filled against length and max latency */ flush = gst_rtp_base_payload_is_filled (GST_RTP_BASE_PAYLOAD (rtptheorapay), packet_len, newduration); /* we can store up to 15 theora packets in one RTP packet. */ flush |= (rtptheorapay->payload_pkts == 15); /* flush if we have a new TDT */ if (rtptheorapay->packet) flush |= (rtptheorapay->payload_TDT != TDT); if (flush) ret = gst_rtp_theora_pay_flush_packet (rtptheorapay); /* create new packet if we must */ if (!rtptheorapay->packet) { gst_rtp_theora_pay_init_packet (rtptheorapay, TDT, timestamp); } gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp); payload = gst_rtp_buffer_get_payload (&rtp); ppos = payload + rtptheorapay->payload_pos; fragmented = FALSE; /* put buffer in packet, it either fits completely or needs to be fragmented * over multiple RTP packets. */ do { plen = MIN (rtptheorapay->payload_left - 2, size); GST_DEBUG_OBJECT (rtptheorapay, "append %u bytes", plen); /* data is copied in the payload with a 2 byte length header */ ppos[0] = ((plen - not_in_length) >> 8) & 0xff; ppos[1] = ((plen - not_in_length) & 0xff); if (plen) memcpy (&ppos[2], data, plen); /* only first (only) configuration cuts length field */ /* NOTE: spec (if any) is not clear on this ... */ not_in_length = 0; size -= plen; data += plen; rtptheorapay->payload_pos += plen + 2; rtptheorapay->payload_left -= plen + 2; if (fragmented) { if (size == 0) /* last fragment, set F to 0x3. */ rtptheorapay->payload_F = 0x3; else /* fragment continues, set F to 0x2. */ rtptheorapay->payload_F = 0x2; } else { if (size > 0) { /* fragmented packet starts, set F to 0x1, mark ourselves as * fragmented. */ rtptheorapay->payload_F = 0x1; fragmented = TRUE; } } if (fragmented) { gst_rtp_buffer_unmap (&rtp); /* fragmented packets are always flushed and have ptks of 0 */ rtptheorapay->payload_pkts = 0; ret = gst_rtp_theora_pay_flush_packet (rtptheorapay); if (size > 0) { /* start new packet and get pointers. TDT stays the same. */ gst_rtp_theora_pay_init_packet (rtptheorapay, rtptheorapay->payload_TDT, timestamp); gst_rtp_buffer_map (rtptheorapay->packet, GST_MAP_WRITE, &rtp); payload = gst_rtp_buffer_get_payload (&rtp); ppos = payload + rtptheorapay->payload_pos; } } else { /* unfragmented packet, update stats for next packet, size == 0 and we * exit the while loop */ rtptheorapay->payload_pkts++; if (duration != GST_CLOCK_TIME_NONE) rtptheorapay->payload_duration += duration; } } while (size); if (rtp.buffer) gst_rtp_buffer_unmap (&rtp); return ret; } static GstFlowReturn gst_rtp_theora_pay_handle_buffer (GstRTPBasePayload * basepayload, GstBuffer * buffer) { GstRtpTheoraPay *rtptheorapay; GstFlowReturn ret; GstMapInfo map; gsize size; guint8 *data; GstClockTime duration, timestamp; guint8 TDT; gboolean keyframe = FALSE; rtptheorapay = GST_RTP_THEORA_PAY (basepayload); gst_buffer_map (buffer, &map, GST_MAP_READ); data = map.data; size = map.size; duration = GST_BUFFER_DURATION (buffer); timestamp = GST_BUFFER_TIMESTAMP (buffer); GST_DEBUG_OBJECT (rtptheorapay, "size %" G_GSIZE_FORMAT ", duration %" GST_TIME_FORMAT, size, GST_TIME_ARGS (duration)); /* find packet type */ if (size == 0) { TDT = 0; keyframe = FALSE; } else if (data[0] & 0x80) { /* header */ if (data[0] == 0x80) { /* identification, we need to parse this in order to get the clock rate. */ if (G_UNLIKELY (!gst_rtp_theora_pay_parse_id (basepayload, data, size))) goto parse_id_failed; TDT = 1; } else if (data[0] == 0x81) { /* comment */ TDT = 2; } else if (data[0] == 0x82) { /* setup */ TDT = 1; } else goto unknown_header; } else { /* data */ TDT = 0; keyframe = ((data[0] & 0x40) == 0); } /* we need to collect the headers and construct a config string from them */ if (TDT != 0) { GST_DEBUG_OBJECT (rtptheorapay, "collecting header, buffer %p", buffer); /* append header to the list of headers */ gst_buffer_unmap (buffer, &map); rtptheorapay->headers = g_list_append (rtptheorapay->headers, buffer); ret = GST_FLOW_OK; goto done; } else if (rtptheorapay->headers) { if (rtptheorapay->need_headers) { if (!gst_rtp_theora_pay_finish_headers (basepayload)) goto header_error; } else { g_list_free_full (rtptheorapay->headers, (GDestroyNotify) gst_buffer_unref); rtptheorapay->headers = NULL; } } /* there is a config request, see if we need to insert it */ if (keyframe && (rtptheorapay->config_interval > 0) && rtptheorapay->config_data) { gboolean send_config = FALSE; if (rtptheorapay->last_config != -1) { guint64 diff; GST_LOG_OBJECT (rtptheorapay, "now %" GST_TIME_FORMAT ", last VOP-I %" GST_TIME_FORMAT, GST_TIME_ARGS (timestamp), GST_TIME_ARGS (rtptheorapay->last_config)); /* calculate diff between last config in milliseconds */ if (timestamp > rtptheorapay->last_config) { diff = timestamp - rtptheorapay->last_config; } else { diff = 0; } GST_DEBUG_OBJECT (rtptheorapay, "interval since last config %" GST_TIME_FORMAT, GST_TIME_ARGS (diff)); /* bigger than interval, queue config */ /* FIXME should convert timestamps to running time */ if (GST_TIME_AS_SECONDS (diff) >= rtptheorapay->config_interval) { GST_DEBUG_OBJECT (rtptheorapay, "time to send config"); send_config = TRUE; } } else { /* no known previous config time, send now */ GST_DEBUG_OBJECT (rtptheorapay, "no previous config time, send now"); send_config = TRUE; } if (send_config) { /* we need to send config now first */ /* different TDT type forces flush */ gst_rtp_theora_pay_payload_buffer (rtptheorapay, 1, rtptheorapay->config_data, rtptheorapay->config_size, timestamp, GST_CLOCK_TIME_NONE, rtptheorapay->config_extra_len); if (timestamp != -1) { rtptheorapay->last_config = timestamp; } } } ret = gst_rtp_theora_pay_payload_buffer (rtptheorapay, TDT, data, size, timestamp, duration, 0); gst_buffer_unmap (buffer, &map); gst_buffer_unref (buffer); done: return ret; /* ERRORS */ parse_id_failed: { gst_buffer_unmap (buffer, &map); gst_buffer_unref (buffer); return GST_FLOW_ERROR; } unknown_header: { GST_ELEMENT_WARNING (rtptheorapay, STREAM, DECODE, (NULL), ("Ignoring unknown header received")); gst_buffer_unmap (buffer, &map); gst_buffer_unref (buffer); return GST_FLOW_OK; } header_error: { GST_ELEMENT_WARNING (rtptheorapay, STREAM, DECODE, (NULL), ("Error initializing header config")); gst_buffer_unmap (buffer, &map); gst_buffer_unref (buffer); return GST_FLOW_OK; } } static gboolean gst_rtp_theora_pay_sink_event (GstRTPBasePayload * payload, GstEvent * event) { GstRtpTheoraPay *rtptheorapay = GST_RTP_THEORA_PAY (payload); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_FLUSH_STOP: gst_rtp_theora_pay_clear_packet (rtptheorapay); break; default: break; } /* false to let parent handle event as well */ return GST_RTP_BASE_PAYLOAD_CLASS (parent_class)->sink_event (payload, event); } static GstStateChangeReturn gst_rtp_theora_pay_change_state (GstElement * element, GstStateChange transition) { GstRtpTheoraPay *rtptheorapay; GstStateChangeReturn ret; rtptheorapay = GST_RTP_THEORA_PAY (element); switch (transition) { default: break; } ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); switch (transition) { case GST_STATE_CHANGE_PAUSED_TO_READY: gst_rtp_theora_pay_cleanup (rtptheorapay); break; default: break; } return ret; } static void gst_rtp_theora_pay_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstRtpTheoraPay *rtptheorapay; rtptheorapay = GST_RTP_THEORA_PAY (object); switch (prop_id) { case PROP_CONFIG_INTERVAL: rtptheorapay->config_interval = g_value_get_uint (value); break; default: break; } } static void gst_rtp_theora_pay_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstRtpTheoraPay *rtptheorapay; rtptheorapay = GST_RTP_THEORA_PAY (object); switch (prop_id) { case PROP_CONFIG_INTERVAL: g_value_set_uint (value, rtptheorapay->config_interval); break; default: break; } } gboolean gst_rtp_theora_pay_plugin_init (GstPlugin * plugin) { return gst_element_register (plugin, "rtptheorapay", GST_RANK_SECONDARY, GST_TYPE_RTP_THEORA_PAY); }
lgpl-2.1
xumingxin7398/angularjs-mdwhat
node_modules/angular-drag-and-drop-lists/demo/multi/multi-frame.html
1083
<h1>Demo: Multiselect Lists</h1> <div class="alert alert-success"> <strong>Instructions:</strong> Click on items to select/unselect them. When dragging, all selected items will be moved at once. </div> <div class="multiDemo row"> <div class="col-md-8"> <div class="row"> <div ng-repeat="list in models" class="col-md-6"> <div class="panel panel-info"> <div class="panel-heading"> <h3 class="panel-title">List {{list.listName}}</h3> </div> <div class="panel-body" ng-include="'multi/multi.html'"></div> </div> </div> </div> <div view-source="multi"></div> </div> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Generated Model</h3> </div> <div class="panel-body"> <pre class="code">{{modelAsJson}}</pre> </div> </div> </div> </div>
apache-2.0
Juni4567/meritscholarship
wp-content/plugins3/paid-memberships-pro/email/checkout_express_admin.html
510
<p>There was a new member checkout at !!sitename!!.</p> <p>Below are details about the new membership account and a receipt for the initial membership invoice.</p> <p>Account: !!display_name!! (!!user_email!!)</p> <p>Membership Level: !!membership_level_name!!</p> <p>Membership Fee: !!membership_cost!!</p> !!membership_expiration!! !!discount_code!! <p> Invoice #!!invoice_id!! on !!invoice_date!!<br /> Total Billed: !!invoice_total!! </p> <p>Log in to your membership account here: !!login_link!!</p>
apache-2.0
zhencui/azure-powershell
src/ServiceManagement/Services/Commands.Test/Environment/GetAzureEnvironmentTests.cs
3485
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Test.Mocks; using Microsoft.WindowsAzure.Commands.Profile; using Microsoft.WindowsAzure.Commands.Profile.Models; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Moq; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Xunit; using Microsoft.Azure.Commands.Common.Authentication; namespace Microsoft.WindowsAzure.Commands.Test.Environment { public class GetAzureEnvironmentTests : SMTestBase { private MemoryDataStore dataStore; public GetAzureEnvironmentTests() { dataStore = new MemoryDataStore(); AzureSession.DataStore = dataStore; } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void GetsAzureEnvironments() { List<PSAzureEnvironment> environments = null; Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>(); commandRuntimeMock.Setup(c => c.WriteObject(It.IsAny<object>(), It.IsAny<bool>())) .Callback<object, bool>((e, _) => environments = (List<PSAzureEnvironment>)e); GetAzureEnvironmentCommand cmdlet = new GetAzureEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object }; AzureSMCmdlet.CurrentProfile = new AzureSMProfile(); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); Assert.Equal(4, environments.Count); } [Fact] [Trait(Category.AcceptanceType, Category.CheckIn)] public void GetsAzureEnvironment() { List<PSAzureEnvironment> environments = null; Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>(); commandRuntimeMock.Setup(c => c.WriteObject(It.IsAny<object>(), It.IsAny<bool>())) .Callback<object, bool>((e, _) => environments = (List<PSAzureEnvironment>)e); GetAzureEnvironmentCommand cmdlet = new GetAzureEnvironmentCommand() { CommandRuntime = commandRuntimeMock.Object, Name = EnvironmentName.AzureChinaCloud }; AzureSMCmdlet.CurrentProfile = new AzureSMProfile(); cmdlet.InvokeBeginProcessing(); cmdlet.ExecuteCmdlet(); cmdlet.InvokeEndProcessing(); Assert.Equal(1, environments.Count); } } }
apache-2.0
irudyak/ignite
modules/web-console/web-agent/src/main/java/org/apache/ignite/console/demo/AgentMetadataDemo.java
3471
/* * 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.ignite.console.demo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.h2.tools.RunScript; import org.h2.tools.Server; import static org.apache.ignite.console.agent.AgentUtils.resolvePath; /** * Demo for metadata load from database. * * H2 database will be started and several tables will be created. */ public class AgentMetadataDemo { /** */ private static final Logger log = Logger.getLogger(AgentMetadataDemo.class.getName()); /** */ private static final AtomicBoolean initLatch = new AtomicBoolean(); /** * @param jdbcUrl Connection url. * @return true if url is used for test-drive. */ public static boolean isTestDriveUrl(String jdbcUrl) { return "jdbc:h2:mem:demo-db".equals(jdbcUrl); } /** * Start H2 database and populate it with several tables. */ public static Connection testDrive() throws SQLException { if (initLatch.compareAndSet(false, true)) { log.info("DEMO: Prepare in-memory H2 database..."); try { Class.forName("org.h2.Driver"); Connection conn = DriverManager.getConnection("jdbc:h2:mem:demo-db;DB_CLOSE_DELAY=-1", "sa", ""); File sqlScript = resolvePath("demo/db-init.sql"); //noinspection ConstantConditions RunScript.execute(conn, new FileReader(sqlScript)); log.info("DEMO: Sample tables created."); conn.close(); Server.createTcpServer("-tcpDaemon").start(); log.info("DEMO: TcpServer stared."); log.info("DEMO: JDBC URL for test drive metadata load: jdbc:h2:mem:demo-db"); } catch (ClassNotFoundException e) { log.error("DEMO: Failed to load H2 driver!", e); throw new SQLException("Failed to load H2 driver", e); } catch (SQLException e) { log.error("DEMO: Failed to start test drive for metadata!", e); throw e; } catch (FileNotFoundException | NullPointerException e) { log.error("DEMO: Failed to find demo database init script file: demo/db-init.sql"); throw new SQLException("Failed to start demo for metadata", e); } } return DriverManager.getConnection("jdbc:h2:mem:demo-db;DB_CLOSE_DELAY=-1", "sa", ""); } }
apache-2.0
smartan/lucene
src/main/java/org/apache/lucene/search/similarities/LMDirichletSimilarity.java
3519
package org.apache.lucene.search.similarities; /* * 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. */ import java.util.Locale; import org.apache.lucene.search.Explanation; /** * Bayesian smoothing using Dirichlet priors. From Chengxiang Zhai and John * Lafferty. 2001. A study of smoothing methods for language models applied to * Ad Hoc information retrieval. In Proceedings of the 24th annual international * ACM SIGIR conference on Research and development in information retrieval * (SIGIR '01). ACM, New York, NY, USA, 334-342. * <p> * The formula as defined the paper assigns a negative score to documents that * contain the term, but with fewer occurrences than predicted by the collection * language model. The Lucene implementation returns {@code 0} for such * documents. * </p> * * @lucene.experimental */ public class LMDirichletSimilarity extends LMSimilarity { /** The &mu; parameter. */ private final float mu; /** Instantiates the similarity with the provided &mu; parameter. */ public LMDirichletSimilarity(CollectionModel collectionModel, float mu) { super(collectionModel); this.mu = mu; } /** Instantiates the similarity with the provided &mu; parameter. */ public LMDirichletSimilarity(float mu) { this.mu = mu; } /** Instantiates the similarity with the default &mu; value of 2000. */ public LMDirichletSimilarity(CollectionModel collectionModel) { this(collectionModel, 2000); } /** Instantiates the similarity with the default &mu; value of 2000. */ public LMDirichletSimilarity() { this(2000); } @Override protected float score(BasicStats stats, float freq, float docLen) { float score = stats.getTotalBoost() * (float)(Math.log(1 + freq / (mu * ((LMStats)stats).getCollectionProbability())) + Math.log(mu / (docLen + mu))); return score > 0.0f ? score : 0.0f; } @Override protected void explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen) { if (stats.getTotalBoost() != 1.0f) { expl.addDetail(new Explanation(stats.getTotalBoost(), "boost")); } expl.addDetail(new Explanation(mu, "mu")); Explanation weightExpl = new Explanation(); weightExpl.setValue((float)Math.log(1 + freq / (mu * ((LMStats)stats).getCollectionProbability()))); weightExpl.setDescription("term weight"); expl.addDetail(weightExpl); expl.addDetail(new Explanation( (float)Math.log(mu / (docLen + mu)), "document norm")); super.explain(expl, stats, doc, freq, docLen); } /** Returns the &mu; parameter. */ public float getMu() { return mu; } @Override public String getName() { return String.format(Locale.ROOT, "Dirichlet(%f)", getMu()); } }
apache-2.0
yaowee/libflame
lapack-test/3.5.0/EIG/dlahd2.f
19347
*> \brief \b DLAHD2 * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE DLAHD2( IOUNIT, PATH ) * * .. Scalar Arguments .. * CHARACTER*3 PATH * INTEGER IOUNIT * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DLAHD2 prints header information for the different test paths. *> \endverbatim * * Arguments: * ========== * *> \param[in] IOUNIT *> \verbatim *> IOUNIT is INTEGER. *> On entry, IOUNIT specifies the unit number to which the *> header information should be printed. *> \endverbatim *> *> \param[in] PATH *> \verbatim *> PATH is CHARACTER*3. *> On entry, PATH contains the name of the path for which the *> header information is to be printed. Current paths are *> *> DHS, ZHS: Non-symmetric eigenproblem. *> DST, ZST: Symmetric eigenproblem. *> DSG, ZSG: Symmetric Generalized eigenproblem. *> DBD, ZBD: Singular Value Decomposition (SVD) *> DBB, ZBB: General Banded reduction to bidiagonal form *> *> These paths also are supplied in double precision (replace *> leading S by D and leading C by Z in path names). *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2013 * *> \ingroup double_eig * * ===================================================================== SUBROUTINE DLAHD2( IOUNIT, PATH ) * * -- LAPACK test routine (version 3.5.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2013 * * .. Scalar Arguments .. CHARACTER*3 PATH INTEGER IOUNIT * .. * * ===================================================================== * * .. Local Scalars .. LOGICAL CORZ, SORD CHARACTER*2 C2 INTEGER J * .. * .. External Functions .. LOGICAL LSAME, LSAMEN EXTERNAL LSAME, LSAMEN * .. * .. Executable Statements .. * IF( IOUNIT.LE.0 ) $ RETURN SORD = LSAME( PATH, 'S' ) .OR. LSAME( PATH, 'D' ) CORZ = LSAME( PATH, 'C' ) .OR. LSAME( PATH, 'Z' ) IF( .NOT.SORD .AND. .NOT.CORZ ) THEN WRITE( IOUNIT, FMT = 9999 )PATH END IF C2 = PATH( 2: 3 ) * IF( LSAMEN( 2, C2, 'HS' ) ) THEN IF( SORD ) THEN * * Real Non-symmetric Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9998 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9988 ) WRITE( IOUNIT, FMT = 9987 ) WRITE( IOUNIT, FMT = 9986 )'pairs ', 'pairs ', 'prs.', $ 'prs.' WRITE( IOUNIT, FMT = 9985 ) * * Tests performed * WRITE( IOUNIT, FMT = 9984 )'orthogonal', '''=transpose', $ ( '''', J = 1, 6 ) * ELSE * * Complex Non-symmetric Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9997 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9988 ) WRITE( IOUNIT, FMT = 9987 ) WRITE( IOUNIT, FMT = 9986 )'e.vals', 'e.vals', 'e.vs', $ 'e.vs' WRITE( IOUNIT, FMT = 9985 ) * * Tests performed * WRITE( IOUNIT, FMT = 9984 )'unitary', '*=conj.transp.', $ ( '*', J = 1, 6 ) END IF * ELSE IF( LSAMEN( 2, C2, 'ST' ) ) THEN * IF( SORD ) THEN * * Real Symmetric Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9996 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9983 ) WRITE( IOUNIT, FMT = 9982 ) WRITE( IOUNIT, FMT = 9981 )'Symmetric' * * Tests performed * WRITE( IOUNIT, FMT = 9968 ) * ELSE * * Complex Hermitian Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9995 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9983 ) WRITE( IOUNIT, FMT = 9982 ) WRITE( IOUNIT, FMT = 9981 )'Hermitian' * * Tests performed * WRITE( IOUNIT, FMT = 9967 ) END IF * ELSE IF( LSAMEN( 2, C2, 'SG' ) ) THEN * IF( SORD ) THEN * * Real Symmetric Generalized Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9992 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9980 ) WRITE( IOUNIT, FMT = 9979 ) WRITE( IOUNIT, FMT = 9978 )'Symmetric' * * Tests performed * WRITE( IOUNIT, FMT = 9977 ) WRITE( IOUNIT, FMT = 9976 ) * ELSE * * Complex Hermitian Generalized Eigenvalue Problem: * WRITE( IOUNIT, FMT = 9991 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9980 ) WRITE( IOUNIT, FMT = 9979 ) WRITE( IOUNIT, FMT = 9978 )'Hermitian' * * Tests performed * WRITE( IOUNIT, FMT = 9975 ) WRITE( IOUNIT, FMT = 9974 ) * END IF * ELSE IF( LSAMEN( 2, C2, 'BD' ) ) THEN * IF( SORD ) THEN * * Real Singular Value Decomposition: * WRITE( IOUNIT, FMT = 9994 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9973 ) * * Tests performed * WRITE( IOUNIT, FMT = 9972 )'orthogonal' WRITE( IOUNIT, FMT = 9971 ) ELSE * * Complex Singular Value Decomposition: * WRITE( IOUNIT, FMT = 9993 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9973 ) * * Tests performed * WRITE( IOUNIT, FMT = 9972 )'unitary ' WRITE( IOUNIT, FMT = 9971 ) END IF * ELSE IF( LSAMEN( 2, C2, 'BB' ) ) THEN * IF( SORD ) THEN * * Real General Band reduction to bidiagonal form: * WRITE( IOUNIT, FMT = 9990 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9970 ) * * Tests performed * WRITE( IOUNIT, FMT = 9969 )'orthogonal' ELSE * * Complex Band reduction to bidiagonal form: * WRITE( IOUNIT, FMT = 9989 )PATH * * Matrix types * WRITE( IOUNIT, FMT = 9970 ) * * Tests performed * WRITE( IOUNIT, FMT = 9969 )'unitary ' END IF * ELSE * WRITE( IOUNIT, FMT = 9999 )PATH RETURN END IF * RETURN * 9999 FORMAT( 1X, A3, ': no header available' ) 9998 FORMAT( / 1X, A3, ' -- Real Non-symmetric eigenvalue problem' ) 9997 FORMAT( / 1X, A3, ' -- Complex Non-symmetric eigenvalue problem' ) 9996 FORMAT( / 1X, A3, ' -- Real Symmetric eigenvalue problem' ) 9995 FORMAT( / 1X, A3, ' -- Complex Hermitian eigenvalue problem' ) 9994 FORMAT( / 1X, A3, ' -- Real Singular Value Decomposition' ) 9993 FORMAT( / 1X, A3, ' -- Complex Singular Value Decomposition' ) 9992 FORMAT( / 1X, A3, ' -- Real Symmetric Generalized eigenvalue ', $ 'problem' ) 9991 FORMAT( / 1X, A3, ' -- Complex Hermitian Generalized eigenvalue ', $ 'problem' ) 9990 FORMAT( / 1X, A3, ' -- Real Band reduc. to bidiagonal form' ) 9989 FORMAT( / 1X, A3, ' -- Complex Band reduc. to bidiagonal form' ) * 9988 FORMAT( ' Matrix types (see xCHKHS for details): ' ) * 9987 FORMAT( / ' Special Matrices:', / ' 1=Zero matrix. ', $ ' ', ' 5=Diagonal: geometr. spaced entries.', $ / ' 2=Identity matrix. ', ' 6=Diagona', $ 'l: clustered entries.', / ' 3=Transposed Jordan block. ', $ ' ', ' 7=Diagonal: large, evenly spaced.', / ' ', $ '4=Diagonal: evenly spaced entries. ', ' 8=Diagonal: s', $ 'mall, evenly spaced.' ) 9986 FORMAT( ' Dense, Non-Symmetric Matrices:', / ' 9=Well-cond., ev', $ 'enly spaced eigenvals.', ' 14=Ill-cond., geomet. spaced e', $ 'igenals.', / ' 10=Well-cond., geom. spaced eigenvals. ', $ ' 15=Ill-conditioned, clustered e.vals.', / ' 11=Well-cond', $ 'itioned, clustered e.vals. ', ' 16=Ill-cond., random comp', $ 'lex ', A6, / ' 12=Well-cond., random complex ', A6, ' ', $ ' 17=Ill-cond., large rand. complx ', A4, / ' 13=Ill-condi', $ 'tioned, evenly spaced. ', ' 18=Ill-cond., small rand.', $ ' complx ', A4 ) 9985 FORMAT( ' 19=Matrix with random O(1) entries. ', ' 21=Matrix ', $ 'with small random entries.', / ' 20=Matrix with large ran', $ 'dom entries. ' ) 9984 FORMAT( / ' Tests performed: ', '(H is Hessenberg, T is Schur,', $ ' U and Z are ', A, ',', / 20X, A, ', W is a diagonal matr', $ 'ix of eigenvalues,', / 20X, 'L and R are the left and rig', $ 'ht eigenvector matrices)', / ' 1 = | A - U H U', A1, ' |', $ ' / ( |A| n ulp ) ', ' 2 = | I - U U', A1, ' | / ', $ '( n ulp )', / ' 3 = | H - Z T Z', A1, ' | / ( |H| n ulp ', $ ') ', ' 4 = | I - Z Z', A1, ' | / ( n ulp )', $ / ' 5 = | A - UZ T (UZ)', A1, ' | / ( |A| n ulp ) ', $ ' 6 = | I - UZ (UZ)', A1, ' | / ( n ulp )', / ' 7 = | T(', $ 'e.vects.) - T(no e.vects.) | / ( |T| ulp )', / ' 8 = | W', $ '(e.vects.) - W(no e.vects.) | / ( |W| ulp )', / ' 9 = | ', $ 'TR - RW | / ( |T| |R| ulp ) ', ' 10 = | LT - WL | / (', $ ' |T| |L| ulp )', / ' 11= |HX - XW| / (|H| |X| ulp) (inv.', $ 'it)', ' 12= |YH - WY| / (|H| |Y| ulp) (inv.it)' ) * * Symmetric/Hermitian eigenproblem * 9983 FORMAT( ' Matrix types (see xDRVST for details): ' ) * 9982 FORMAT( / ' Special Matrices:', / ' 1=Zero matrix. ', $ ' ', ' 5=Diagonal: clustered entries.', / ' 2=', $ 'Identity matrix. ', ' 6=Diagonal: lar', $ 'ge, evenly spaced.', / ' 3=Diagonal: evenly spaced entri', $ 'es. ', ' 7=Diagonal: small, evenly spaced.', / ' 4=D', $ 'iagonal: geometr. spaced entries.' ) 9981 FORMAT( ' Dense ', A, ' Matrices:', / ' 8=Evenly spaced eigen', $ 'vals. ', ' 12=Small, evenly spaced eigenvals.', $ / ' 9=Geometrically spaced eigenvals. ', ' 13=Matrix ', $ 'with random O(1) entries.', / ' 10=Clustered eigenvalues.', $ ' ', ' 14=Matrix with large random entries.', $ / ' 11=Large, evenly spaced eigenvals. ', ' 15=Matrix ', $ 'with small random entries.' ) * * Symmetric/Hermitian Generalized eigenproblem * 9980 FORMAT( ' Matrix types (see xDRVSG for details): ' ) * 9979 FORMAT( / ' Special Matrices:', / ' 1=Zero matrix. ', $ ' ', ' 5=Diagonal: clustered entries.', / ' 2=', $ 'Identity matrix. ', ' 6=Diagonal: lar', $ 'ge, evenly spaced.', / ' 3=Diagonal: evenly spaced entri', $ 'es. ', ' 7=Diagonal: small, evenly spaced.', / ' 4=D', $ 'iagonal: geometr. spaced entries.' ) 9978 FORMAT( ' Dense or Banded ', A, ' Matrices: ', $ / ' 8=Evenly spaced eigenvals. ', $ ' 15=Matrix with small random entries.', $ / ' 9=Geometrically spaced eigenvals. ', $ ' 16=Evenly spaced eigenvals, KA=1, KB=1.', $ / ' 10=Clustered eigenvalues. ', $ ' 17=Evenly spaced eigenvals, KA=2, KB=1.', $ / ' 11=Large, evenly spaced eigenvals. ', $ ' 18=Evenly spaced eigenvals, KA=2, KB=2.', $ / ' 12=Small, evenly spaced eigenvals. ', $ ' 19=Evenly spaced eigenvals, KA=3, KB=1.', $ / ' 13=Matrix with random O(1) entries. ', $ ' 20=Evenly spaced eigenvals, KA=3, KB=2.', $ / ' 14=Matrix with large random entries.', $ ' 21=Evenly spaced eigenvals, KA=3, KB=3.' ) 9977 FORMAT( / ' Tests performed: ', $ / '( For each pair (A,B), where A is of the given type ', $ / ' and B is a random well-conditioned matrix. D is ', $ / ' diagonal, and Z is orthogonal. )', $ / ' 1 = DSYGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 2 = DSPGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 3 = DSBGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 4 = DSYGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 5 = DSPGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 6 = DSBGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ' ) 9976 FORMAT( ' 7 = DSYGV, with ITYPE=2 and UPLO=''U'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / ' 8 = DSPGV, with ITYPE=2 and UPLO=''U'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / ' 9 = DSPGV, with ITYPE=2 and UPLO=''L'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / '10 = DSPGV, with ITYPE=2 and UPLO=''L'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / '11 = DSYGV, with ITYPE=3 and UPLO=''U'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '12 = DSPGV, with ITYPE=3 and UPLO=''U'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '13 = DSYGV, with ITYPE=3 and UPLO=''L'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '14 = DSPGV, with ITYPE=3 and UPLO=''L'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ' ) 9975 FORMAT( / ' Tests performed: ', $ / '( For each pair (A,B), where A is of the given type ', $ / ' and B is a random well-conditioned matrix. D is ', $ / ' diagonal, and Z is unitary. )', $ / ' 1 = ZHEGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 2 = ZHPGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 3 = ZHBGV, with ITYPE=1 and UPLO=''U'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 4 = ZHEGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 5 = ZHPGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ', $ / ' 6 = ZHBGV, with ITYPE=1 and UPLO=''L'':', $ ' | A Z - B Z D | / ( |A| |Z| n ulp ) ' ) 9974 FORMAT( ' 7 = ZHEGV, with ITYPE=2 and UPLO=''U'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / ' 8 = ZHPGV, with ITYPE=2 and UPLO=''U'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / ' 9 = ZHPGV, with ITYPE=2 and UPLO=''L'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / '10 = ZHPGV, with ITYPE=2 and UPLO=''L'':', $ ' | A B Z - Z D | / ( |A| |Z| n ulp ) ', $ / '11 = ZHEGV, with ITYPE=3 and UPLO=''U'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '12 = ZHPGV, with ITYPE=3 and UPLO=''U'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '13 = ZHEGV, with ITYPE=3 and UPLO=''L'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ', $ / '14 = ZHPGV, with ITYPE=3 and UPLO=''L'':', $ ' | B A Z - Z D | / ( |A| |Z| n ulp ) ' ) * * Singular Value Decomposition * 9973 FORMAT( ' Matrix types (see xCHKBD for details):', $ / ' Diagonal matrices:', / ' 1: Zero', 28X, $ ' 5: Clustered entries', / ' 2: Identity', 24X, $ ' 6: Large, evenly spaced entries', $ / ' 3: Evenly spaced entries', 11X, $ ' 7: Small, evenly spaced entries', $ / ' 4: Geometrically spaced entries', $ / ' General matrices:', / ' 8: Evenly spaced sing. vals.', $ 7X, '12: Small, evenly spaced sing vals', $ / ' 9: Geometrically spaced sing vals ', $ '13: Random, O(1) entries', / ' 10: Clustered sing. vals.', $ 11X, '14: Random, scaled near overflow', $ / ' 11: Large, evenly spaced sing vals ', $ '15: Random, scaled near underflow' ) * 9972 FORMAT( / ' Test ratios: ', $ '(B: bidiagonal, S: diagonal, Q, P, U, and V: ', A10, / 16X, $ 'X: m x nrhs, Y = Q'' X, and Z = U'' Y)', $ / ' 1: norm( A - Q B P'' ) / ( norm(A) max(m,n) ulp )', $ / ' 2: norm( I - Q'' Q ) / ( m ulp )', $ / ' 3: norm( I - P'' P ) / ( n ulp )', $ / ' 4: norm( B - U S V'' ) / ( norm(B) min(m,n) ulp )', / $ ' 5: norm( Y - U Z ) / ( norm(Z) max(min(m,n),k) ulp )' $ , / ' 6: norm( I - U'' U ) / ( min(m,n) ulp )', $ / ' 7: norm( I - V'' V ) / ( min(m,n) ulp )' ) 9971 FORMAT( ' 8: Test ordering of S (0 if nondecreasing, 1/ulp ', $ ' otherwise)', / $ ' 9: norm( S - S2 ) / ( norm(S) ulp ),', $ ' where S2 is computed', / 44X, $ 'without computing U and V''', $ / ' 10: Sturm sequence test ', $ '(0 if sing. vals of B within THRESH of S)', $ / ' 11: norm( A - (QU) S (V'' P'') ) / ', $ '( norm(A) max(m,n) ulp )', / $ ' 12: norm( X - (QU) Z ) / ( |X| max(M,k) ulp )', $ / ' 13: norm( I - (QU)''(QU) ) / ( M ulp )', $ / ' 14: norm( I - (V'' P'') (P V) ) / ( N ulp )' ) * * Band reduction to bidiagonal form * 9970 FORMAT( ' Matrix types (see xCHKBB for details):', $ / ' Diagonal matrices:', / ' 1: Zero', 28X, $ ' 5: Clustered entries', / ' 2: Identity', 24X, $ ' 6: Large, evenly spaced entries', $ / ' 3: Evenly spaced entries', 11X, $ ' 7: Small, evenly spaced entries', $ / ' 4: Geometrically spaced entries', $ / ' General matrices:', / ' 8: Evenly spaced sing. vals.', $ 7X, '12: Small, evenly spaced sing vals', $ / ' 9: Geometrically spaced sing vals ', $ '13: Random, O(1) entries', / ' 10: Clustered sing. vals.', $ 11X, '14: Random, scaled near overflow', $ / ' 11: Large, evenly spaced sing vals ', $ '15: Random, scaled near underflow' ) * 9969 FORMAT( / ' Test ratios: ', '(B: upper bidiagonal, Q and P: ', $ A10, / 16X, 'C: m x nrhs, PT = P'', Y = Q'' C)', $ / ' 1: norm( A - Q B PT ) / ( norm(A) max(m,n) ulp )', $ / ' 2: norm( I - Q'' Q ) / ( m ulp )', $ / ' 3: norm( I - PT PT'' ) / ( n ulp )', $ / ' 4: norm( Y - Q'' C ) / ( norm(Y) max(m,nrhs) ulp )' ) 9968 FORMAT( / ' Tests performed: See ddrvst.f' ) 9967 FORMAT( / ' Tests performed: See sdrvst.f' ) * * End of DLAHD2 * END
bsd-3-clause
iwinoto/v4l-media_build-devel
media/drivers/net/ethernet/sun/cassini.c
142749
/* cassini.c: Sun Microsystems Cassini(+) ethernet driver. * * Copyright (C) 2004 Sun Microsystems Inc. * Copyright (C) 2003 Adrian Sun (asun@darksunrising.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * 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/>. * * This driver uses the sungem driver (c) David Miller * (davem@redhat.com) as its basis. * * The cassini chip has a number of features that distinguish it from * the gem chip: * 4 transmit descriptor rings that are used for either QoS (VLAN) or * load balancing (non-VLAN mode) * batching of multiple packets * multiple CPU dispatching * page-based RX descriptor engine with separate completion rings * Gigabit support (GMII and PCS interface) * MIF link up/down detection works * * RX is handled by page sized buffers that are attached as fragments to * the skb. here's what's done: * -- driver allocates pages at a time and keeps reference counts * on them. * -- the upper protocol layers assume that the header is in the skb * itself. as a result, cassini will copy a small amount (64 bytes) * to make them happy. * -- driver appends the rest of the data pages as frags to skbuffs * and increments the reference count * -- on page reclamation, the driver swaps the page with a spare page. * if that page is still in use, it frees its reference to that page, * and allocates a new page for use. otherwise, it just recycles the * the page. * * NOTE: cassini can parse the header. however, it's not worth it * as long as the network stack requires a header copy. * * TX has 4 queues. currently these queues are used in a round-robin * fashion for load balancing. They can also be used for QoS. for that * to work, however, QoS information needs to be exposed down to the driver * level so that subqueues get targeted to particular transmit rings. * alternatively, the queues can be configured via use of the all-purpose * ioctl. * * RX DATA: the rx completion ring has all the info, but the rx desc * ring has all of the data. RX can conceivably come in under multiple * interrupts, but the INT# assignment needs to be set up properly by * the BIOS and conveyed to the driver. PCI BIOSes don't know how to do * that. also, the two descriptor rings are designed to distinguish between * encrypted and non-encrypted packets, but we use them for buffering * instead. * * by default, the selective clear mask is set up to process rx packets. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/compiler.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/vmalloc.h> #include <linux/ioport.h> #include <linux/pci.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/list.h> #include <linux/dma-mapping.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/ethtool.h> #include <linux/crc32.h> #include <linux/random.h> #include <linux/mii.h> #include <linux/ip.h> #include <linux/tcp.h> #include <linux/mutex.h> #include <linux/firmware.h> #include <net/checksum.h> #include <linux/atomic.h> #include <asm/io.h> #include <asm/byteorder.h> #include <asm/uaccess.h> #define cas_page_map(x) kmap_atomic((x)) #define cas_page_unmap(x) kunmap_atomic((x)) #define CAS_NCPUS num_online_cpus() #define cas_skb_release(x) netif_rx(x) /* select which firmware to use */ #define USE_HP_WORKAROUND #define HP_WORKAROUND_DEFAULT /* select which firmware to use as default */ #define CAS_HP_ALT_FIRMWARE cas_prog_null /* alternate firmware */ #include "cassini.h" #define USE_TX_COMPWB /* use completion writeback registers */ #define USE_CSMA_CD_PROTO /* standard CSMA/CD */ #define USE_RX_BLANK /* hw interrupt mitigation */ #undef USE_ENTROPY_DEV /* don't test for entropy device */ /* NOTE: these aren't useable unless PCI interrupts can be assigned. * also, we need to make cp->lock finer-grained. */ #undef USE_PCI_INTB #undef USE_PCI_INTC #undef USE_PCI_INTD #undef USE_QOS #undef USE_VPD_DEBUG /* debug vpd information if defined */ /* rx processing options */ #define USE_PAGE_ORDER /* specify to allocate large rx pages */ #define RX_DONT_BATCH 0 /* if 1, don't batch flows */ #define RX_COPY_ALWAYS 0 /* if 0, use frags */ #define RX_COPY_MIN 64 /* copy a little to make upper layers happy */ #undef RX_COUNT_BUFFERS /* define to calculate RX buffer stats */ #define DRV_MODULE_NAME "cassini" #define DRV_MODULE_VERSION "1.6" #define DRV_MODULE_RELDATE "21 May 2008" #define CAS_DEF_MSG_ENABLE \ (NETIF_MSG_DRV | \ NETIF_MSG_PROBE | \ NETIF_MSG_LINK | \ NETIF_MSG_TIMER | \ NETIF_MSG_IFDOWN | \ NETIF_MSG_IFUP | \ NETIF_MSG_RX_ERR | \ NETIF_MSG_TX_ERR) /* length of time before we decide the hardware is borked, * and dev->tx_timeout() should be called to fix the problem */ #define CAS_TX_TIMEOUT (HZ) #define CAS_LINK_TIMEOUT (22*HZ/10) #define CAS_LINK_FAST_TIMEOUT (1) /* timeout values for state changing. these specify the number * of 10us delays to be used before giving up. */ #define STOP_TRIES_PHY 1000 #define STOP_TRIES 5000 /* specify a minimum frame size to deal with some fifo issues * max mtu == 2 * page size - ethernet header - 64 - swivel = * 2 * page_size - 0x50 */ #define CAS_MIN_FRAME 97 #define CAS_1000MB_MIN_FRAME 255 #define CAS_MIN_MTU 60 #define CAS_MAX_MTU min(((cp->page_size << 1) - 0x50), 9000) #if 1 /* * Eliminate these and use separate atomic counters for each, to * avoid a race condition. */ #else #define CAS_RESET_MTU 1 #define CAS_RESET_ALL 2 #define CAS_RESET_SPARE 3 #endif static char version[] = DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n"; static int cassini_debug = -1; /* -1 == use CAS_DEF_MSG_ENABLE as value */ static int link_mode; MODULE_AUTHOR("Adrian Sun (asun@darksunrising.com)"); MODULE_DESCRIPTION("Sun Cassini(+) ethernet driver"); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("sun/cassini.bin"); module_param(cassini_debug, int, 0); MODULE_PARM_DESC(cassini_debug, "Cassini bitmapped debugging message enable value"); module_param(link_mode, int, 0); MODULE_PARM_DESC(link_mode, "default link mode"); /* * Work around for a PCS bug in which the link goes down due to the chip * being confused and never showing a link status of "up." */ #define DEFAULT_LINKDOWN_TIMEOUT 5 /* * Value in seconds, for user input. */ static int linkdown_timeout = DEFAULT_LINKDOWN_TIMEOUT; module_param(linkdown_timeout, int, 0); MODULE_PARM_DESC(linkdown_timeout, "min reset interval in sec. for PCS linkdown issue; disabled if not positive"); /* * value in 'ticks' (units used by jiffies). Set when we init the * module because 'HZ' in actually a function call on some flavors of * Linux. This will default to DEFAULT_LINKDOWN_TIMEOUT * HZ. */ static int link_transition_timeout; static u16 link_modes[] = { BMCR_ANENABLE, /* 0 : autoneg */ 0, /* 1 : 10bt half duplex */ BMCR_SPEED100, /* 2 : 100bt half duplex */ BMCR_FULLDPLX, /* 3 : 10bt full duplex */ BMCR_SPEED100|BMCR_FULLDPLX, /* 4 : 100bt full duplex */ CAS_BMCR_SPEED1000|BMCR_FULLDPLX /* 5 : 1000bt full duplex */ }; static DEFINE_PCI_DEVICE_TABLE(cas_pci_tbl) = { { PCI_VENDOR_ID_SUN, PCI_DEVICE_ID_SUN_CASSINI, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, { PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SATURN, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL }, { 0, } }; MODULE_DEVICE_TABLE(pci, cas_pci_tbl); static void cas_set_link_modes(struct cas *cp); static inline void cas_lock_tx(struct cas *cp) { int i; for (i = 0; i < N_TX_RINGS; i++) spin_lock(&cp->tx_lock[i]); } static inline void cas_lock_all(struct cas *cp) { spin_lock_irq(&cp->lock); cas_lock_tx(cp); } /* WTZ: QA was finding deadlock problems with the previous * versions after long test runs with multiple cards per machine. * See if replacing cas_lock_all with safer versions helps. The * symptoms QA is reporting match those we'd expect if interrupts * aren't being properly restored, and we fixed a previous deadlock * with similar symptoms by using save/restore versions in other * places. */ #define cas_lock_all_save(cp, flags) \ do { \ struct cas *xxxcp = (cp); \ spin_lock_irqsave(&xxxcp->lock, flags); \ cas_lock_tx(xxxcp); \ } while (0) static inline void cas_unlock_tx(struct cas *cp) { int i; for (i = N_TX_RINGS; i > 0; i--) spin_unlock(&cp->tx_lock[i - 1]); } static inline void cas_unlock_all(struct cas *cp) { cas_unlock_tx(cp); spin_unlock_irq(&cp->lock); } #define cas_unlock_all_restore(cp, flags) \ do { \ struct cas *xxxcp = (cp); \ cas_unlock_tx(xxxcp); \ spin_unlock_irqrestore(&xxxcp->lock, flags); \ } while (0) static void cas_disable_irq(struct cas *cp, const int ring) { /* Make sure we won't get any more interrupts */ if (ring == 0) { writel(0xFFFFFFFF, cp->regs + REG_INTR_MASK); return; } /* disable completion interrupts and selectively mask */ if (cp->cas_flags & CAS_FLAG_REG_PLUS) { switch (ring) { #if defined (USE_PCI_INTB) || defined(USE_PCI_INTC) || defined(USE_PCI_INTD) #ifdef USE_PCI_INTB case 1: #endif #ifdef USE_PCI_INTC case 2: #endif #ifdef USE_PCI_INTD case 3: #endif writel(INTRN_MASK_CLEAR_ALL | INTRN_MASK_RX_EN, cp->regs + REG_PLUS_INTRN_MASK(ring)); break; #endif default: writel(INTRN_MASK_CLEAR_ALL, cp->regs + REG_PLUS_INTRN_MASK(ring)); break; } } } static inline void cas_mask_intr(struct cas *cp) { int i; for (i = 0; i < N_RX_COMP_RINGS; i++) cas_disable_irq(cp, i); } static void cas_enable_irq(struct cas *cp, const int ring) { if (ring == 0) { /* all but TX_DONE */ writel(INTR_TX_DONE, cp->regs + REG_INTR_MASK); return; } if (cp->cas_flags & CAS_FLAG_REG_PLUS) { switch (ring) { #if defined (USE_PCI_INTB) || defined(USE_PCI_INTC) || defined(USE_PCI_INTD) #ifdef USE_PCI_INTB case 1: #endif #ifdef USE_PCI_INTC case 2: #endif #ifdef USE_PCI_INTD case 3: #endif writel(INTRN_MASK_RX_EN, cp->regs + REG_PLUS_INTRN_MASK(ring)); break; #endif default: break; } } } static inline void cas_unmask_intr(struct cas *cp) { int i; for (i = 0; i < N_RX_COMP_RINGS; i++) cas_enable_irq(cp, i); } static inline void cas_entropy_gather(struct cas *cp) { #ifdef USE_ENTROPY_DEV if ((cp->cas_flags & CAS_FLAG_ENTROPY_DEV) == 0) return; batch_entropy_store(readl(cp->regs + REG_ENTROPY_IV), readl(cp->regs + REG_ENTROPY_IV), sizeof(uint64_t)*8); #endif } static inline void cas_entropy_reset(struct cas *cp) { #ifdef USE_ENTROPY_DEV if ((cp->cas_flags & CAS_FLAG_ENTROPY_DEV) == 0) return; writel(BIM_LOCAL_DEV_PAD | BIM_LOCAL_DEV_PROM | BIM_LOCAL_DEV_EXT, cp->regs + REG_BIM_LOCAL_DEV_EN); writeb(ENTROPY_RESET_STC_MODE, cp->regs + REG_ENTROPY_RESET); writeb(0x55, cp->regs + REG_ENTROPY_RAND_REG); /* if we read back 0x0, we don't have an entropy device */ if (readb(cp->regs + REG_ENTROPY_RAND_REG) == 0) cp->cas_flags &= ~CAS_FLAG_ENTROPY_DEV; #endif } /* access to the phy. the following assumes that we've initialized the MIF to * be in frame rather than bit-bang mode */ static u16 cas_phy_read(struct cas *cp, int reg) { u32 cmd; int limit = STOP_TRIES_PHY; cmd = MIF_FRAME_ST | MIF_FRAME_OP_READ; cmd |= CAS_BASE(MIF_FRAME_PHY_ADDR, cp->phy_addr); cmd |= CAS_BASE(MIF_FRAME_REG_ADDR, reg); cmd |= MIF_FRAME_TURN_AROUND_MSB; writel(cmd, cp->regs + REG_MIF_FRAME); /* poll for completion */ while (limit-- > 0) { udelay(10); cmd = readl(cp->regs + REG_MIF_FRAME); if (cmd & MIF_FRAME_TURN_AROUND_LSB) return cmd & MIF_FRAME_DATA_MASK; } return 0xFFFF; /* -1 */ } static int cas_phy_write(struct cas *cp, int reg, u16 val) { int limit = STOP_TRIES_PHY; u32 cmd; cmd = MIF_FRAME_ST | MIF_FRAME_OP_WRITE; cmd |= CAS_BASE(MIF_FRAME_PHY_ADDR, cp->phy_addr); cmd |= CAS_BASE(MIF_FRAME_REG_ADDR, reg); cmd |= MIF_FRAME_TURN_AROUND_MSB; cmd |= val & MIF_FRAME_DATA_MASK; writel(cmd, cp->regs + REG_MIF_FRAME); /* poll for completion */ while (limit-- > 0) { udelay(10); cmd = readl(cp->regs + REG_MIF_FRAME); if (cmd & MIF_FRAME_TURN_AROUND_LSB) return 0; } return -1; } static void cas_phy_powerup(struct cas *cp) { u16 ctl = cas_phy_read(cp, MII_BMCR); if ((ctl & BMCR_PDOWN) == 0) return; ctl &= ~BMCR_PDOWN; cas_phy_write(cp, MII_BMCR, ctl); } static void cas_phy_powerdown(struct cas *cp) { u16 ctl = cas_phy_read(cp, MII_BMCR); if (ctl & BMCR_PDOWN) return; ctl |= BMCR_PDOWN; cas_phy_write(cp, MII_BMCR, ctl); } /* cp->lock held. note: the last put_page will free the buffer */ static int cas_page_free(struct cas *cp, cas_page_t *page) { pci_unmap_page(cp->pdev, page->dma_addr, cp->page_size, PCI_DMA_FROMDEVICE); __free_pages(page->buffer, cp->page_order); kfree(page); return 0; } #ifdef RX_COUNT_BUFFERS #define RX_USED_ADD(x, y) ((x)->used += (y)) #define RX_USED_SET(x, y) ((x)->used = (y)) #else #define RX_USED_ADD(x, y) #define RX_USED_SET(x, y) #endif /* local page allocation routines for the receive buffers. jumbo pages * require at least 8K contiguous and 8K aligned buffers. */ static cas_page_t *cas_page_alloc(struct cas *cp, const gfp_t flags) { cas_page_t *page; page = kmalloc(sizeof(cas_page_t), flags); if (!page) return NULL; INIT_LIST_HEAD(&page->list); RX_USED_SET(page, 0); page->buffer = alloc_pages(flags, cp->page_order); if (!page->buffer) goto page_err; page->dma_addr = pci_map_page(cp->pdev, page->buffer, 0, cp->page_size, PCI_DMA_FROMDEVICE); return page; page_err: kfree(page); return NULL; } /* initialize spare pool of rx buffers, but allocate during the open */ static void cas_spare_init(struct cas *cp) { spin_lock(&cp->rx_inuse_lock); INIT_LIST_HEAD(&cp->rx_inuse_list); spin_unlock(&cp->rx_inuse_lock); spin_lock(&cp->rx_spare_lock); INIT_LIST_HEAD(&cp->rx_spare_list); cp->rx_spares_needed = RX_SPARE_COUNT; spin_unlock(&cp->rx_spare_lock); } /* used on close. free all the spare buffers. */ static void cas_spare_free(struct cas *cp) { struct list_head list, *elem, *tmp; /* free spare buffers */ INIT_LIST_HEAD(&list); spin_lock(&cp->rx_spare_lock); list_splice_init(&cp->rx_spare_list, &list); spin_unlock(&cp->rx_spare_lock); list_for_each_safe(elem, tmp, &list) { cas_page_free(cp, list_entry(elem, cas_page_t, list)); } INIT_LIST_HEAD(&list); #if 1 /* * Looks like Adrian had protected this with a different * lock than used everywhere else to manipulate this list. */ spin_lock(&cp->rx_inuse_lock); list_splice_init(&cp->rx_inuse_list, &list); spin_unlock(&cp->rx_inuse_lock); #else spin_lock(&cp->rx_spare_lock); list_splice_init(&cp->rx_inuse_list, &list); spin_unlock(&cp->rx_spare_lock); #endif list_for_each_safe(elem, tmp, &list) { cas_page_free(cp, list_entry(elem, cas_page_t, list)); } } /* replenish spares if needed */ static void cas_spare_recover(struct cas *cp, const gfp_t flags) { struct list_head list, *elem, *tmp; int needed, i; /* check inuse list. if we don't need any more free buffers, * just free it */ /* make a local copy of the list */ INIT_LIST_HEAD(&list); spin_lock(&cp->rx_inuse_lock); list_splice_init(&cp->rx_inuse_list, &list); spin_unlock(&cp->rx_inuse_lock); list_for_each_safe(elem, tmp, &list) { cas_page_t *page = list_entry(elem, cas_page_t, list); /* * With the lockless pagecache, cassini buffering scheme gets * slightly less accurate: we might find that a page has an * elevated reference count here, due to a speculative ref, * and skip it as in-use. Ideally we would be able to reclaim * it. However this would be such a rare case, it doesn't * matter too much as we should pick it up the next time round. * * Importantly, if we find that the page has a refcount of 1 * here (our refcount), then we know it is definitely not inuse * so we can reuse it. */ if (page_count(page->buffer) > 1) continue; list_del(elem); spin_lock(&cp->rx_spare_lock); if (cp->rx_spares_needed > 0) { list_add(elem, &cp->rx_spare_list); cp->rx_spares_needed--; spin_unlock(&cp->rx_spare_lock); } else { spin_unlock(&cp->rx_spare_lock); cas_page_free(cp, page); } } /* put any inuse buffers back on the list */ if (!list_empty(&list)) { spin_lock(&cp->rx_inuse_lock); list_splice(&list, &cp->rx_inuse_list); spin_unlock(&cp->rx_inuse_lock); } spin_lock(&cp->rx_spare_lock); needed = cp->rx_spares_needed; spin_unlock(&cp->rx_spare_lock); if (!needed) return; /* we still need spares, so try to allocate some */ INIT_LIST_HEAD(&list); i = 0; while (i < needed) { cas_page_t *spare = cas_page_alloc(cp, flags); if (!spare) break; list_add(&spare->list, &list); i++; } spin_lock(&cp->rx_spare_lock); list_splice(&list, &cp->rx_spare_list); cp->rx_spares_needed -= i; spin_unlock(&cp->rx_spare_lock); } /* pull a page from the list. */ static cas_page_t *cas_page_dequeue(struct cas *cp) { struct list_head *entry; int recover; spin_lock(&cp->rx_spare_lock); if (list_empty(&cp->rx_spare_list)) { /* try to do a quick recovery */ spin_unlock(&cp->rx_spare_lock); cas_spare_recover(cp, GFP_ATOMIC); spin_lock(&cp->rx_spare_lock); if (list_empty(&cp->rx_spare_list)) { netif_err(cp, rx_err, cp->dev, "no spare buffers available\n"); spin_unlock(&cp->rx_spare_lock); return NULL; } } entry = cp->rx_spare_list.next; list_del(entry); recover = ++cp->rx_spares_needed; spin_unlock(&cp->rx_spare_lock); /* trigger the timer to do the recovery */ if ((recover & (RX_SPARE_RECOVER_VAL - 1)) == 0) { #if 1 atomic_inc(&cp->reset_task_pending); atomic_inc(&cp->reset_task_pending_spare); schedule_work(&cp->reset_task); #else atomic_set(&cp->reset_task_pending, CAS_RESET_SPARE); schedule_work(&cp->reset_task); #endif } return list_entry(entry, cas_page_t, list); } static void cas_mif_poll(struct cas *cp, const int enable) { u32 cfg; cfg = readl(cp->regs + REG_MIF_CFG); cfg &= (MIF_CFG_MDIO_0 | MIF_CFG_MDIO_1); if (cp->phy_type & CAS_PHY_MII_MDIO1) cfg |= MIF_CFG_PHY_SELECT; /* poll and interrupt on link status change. */ if (enable) { cfg |= MIF_CFG_POLL_EN; cfg |= CAS_BASE(MIF_CFG_POLL_REG, MII_BMSR); cfg |= CAS_BASE(MIF_CFG_POLL_PHY, cp->phy_addr); } writel((enable) ? ~(BMSR_LSTATUS | BMSR_ANEGCOMPLETE) : 0xFFFF, cp->regs + REG_MIF_MASK); writel(cfg, cp->regs + REG_MIF_CFG); } /* Must be invoked under cp->lock */ static void cas_begin_auto_negotiation(struct cas *cp, struct ethtool_cmd *ep) { u16 ctl; #if 1 int lcntl; int changed = 0; int oldstate = cp->lstate; int link_was_not_down = !(oldstate == link_down); #endif /* Setup link parameters */ if (!ep) goto start_aneg; lcntl = cp->link_cntl; if (ep->autoneg == AUTONEG_ENABLE) cp->link_cntl = BMCR_ANENABLE; else { u32 speed = ethtool_cmd_speed(ep); cp->link_cntl = 0; if (speed == SPEED_100) cp->link_cntl |= BMCR_SPEED100; else if (speed == SPEED_1000) cp->link_cntl |= CAS_BMCR_SPEED1000; if (ep->duplex == DUPLEX_FULL) cp->link_cntl |= BMCR_FULLDPLX; } #if 1 changed = (lcntl != cp->link_cntl); #endif start_aneg: if (cp->lstate == link_up) { netdev_info(cp->dev, "PCS link down\n"); } else { if (changed) { netdev_info(cp->dev, "link configuration changed\n"); } } cp->lstate = link_down; cp->link_transition = LINK_TRANSITION_LINK_DOWN; if (!cp->hw_running) return; #if 1 /* * WTZ: If the old state was link_up, we turn off the carrier * to replicate everything we do elsewhere on a link-down * event when we were already in a link-up state.. */ if (oldstate == link_up) netif_carrier_off(cp->dev); if (changed && link_was_not_down) { /* * WTZ: This branch will simply schedule a full reset after * we explicitly changed link modes in an ioctl. See if this * fixes the link-problems we were having for forced mode. */ atomic_inc(&cp->reset_task_pending); atomic_inc(&cp->reset_task_pending_all); schedule_work(&cp->reset_task); cp->timer_ticks = 0; mod_timer(&cp->link_timer, jiffies + CAS_LINK_TIMEOUT); return; } #endif if (cp->phy_type & CAS_PHY_SERDES) { u32 val = readl(cp->regs + REG_PCS_MII_CTRL); if (cp->link_cntl & BMCR_ANENABLE) { val |= (PCS_MII_RESTART_AUTONEG | PCS_MII_AUTONEG_EN); cp->lstate = link_aneg; } else { if (cp->link_cntl & BMCR_FULLDPLX) val |= PCS_MII_CTRL_DUPLEX; val &= ~PCS_MII_AUTONEG_EN; cp->lstate = link_force_ok; } cp->link_transition = LINK_TRANSITION_LINK_CONFIG; writel(val, cp->regs + REG_PCS_MII_CTRL); } else { cas_mif_poll(cp, 0); ctl = cas_phy_read(cp, MII_BMCR); ctl &= ~(BMCR_FULLDPLX | BMCR_SPEED100 | CAS_BMCR_SPEED1000 | BMCR_ANENABLE); ctl |= cp->link_cntl; if (ctl & BMCR_ANENABLE) { ctl |= BMCR_ANRESTART; cp->lstate = link_aneg; } else { cp->lstate = link_force_ok; } cp->link_transition = LINK_TRANSITION_LINK_CONFIG; cas_phy_write(cp, MII_BMCR, ctl); cas_mif_poll(cp, 1); } cp->timer_ticks = 0; mod_timer(&cp->link_timer, jiffies + CAS_LINK_TIMEOUT); } /* Must be invoked under cp->lock. */ static int cas_reset_mii_phy(struct cas *cp) { int limit = STOP_TRIES_PHY; u16 val; cas_phy_write(cp, MII_BMCR, BMCR_RESET); udelay(100); while (--limit) { val = cas_phy_read(cp, MII_BMCR); if ((val & BMCR_RESET) == 0) break; udelay(10); } return limit <= 0; } static void cas_saturn_firmware_init(struct cas *cp) { const struct firmware *fw; const char fw_name[] = "sun/cassini.bin"; int err; if (PHY_NS_DP83065 != cp->phy_id) return; err = request_firmware(&fw, fw_name, &cp->pdev->dev); if (err) { pr_err("Failed to load firmware \"%s\"\n", fw_name); return; } if (fw->size < 2) { pr_err("bogus length %zu in \"%s\"\n", fw->size, fw_name); goto out; } cp->fw_load_addr= fw->data[1] << 8 | fw->data[0]; cp->fw_size = fw->size - 2; cp->fw_data = vmalloc(cp->fw_size); if (!cp->fw_data) goto out; memcpy(cp->fw_data, &fw->data[2], cp->fw_size); out: release_firmware(fw); } static void cas_saturn_firmware_load(struct cas *cp) { int i; if (!cp->fw_data) return; cas_phy_powerdown(cp); /* expanded memory access mode */ cas_phy_write(cp, DP83065_MII_MEM, 0x0); /* pointer configuration for new firmware */ cas_phy_write(cp, DP83065_MII_REGE, 0x8ff9); cas_phy_write(cp, DP83065_MII_REGD, 0xbd); cas_phy_write(cp, DP83065_MII_REGE, 0x8ffa); cas_phy_write(cp, DP83065_MII_REGD, 0x82); cas_phy_write(cp, DP83065_MII_REGE, 0x8ffb); cas_phy_write(cp, DP83065_MII_REGD, 0x0); cas_phy_write(cp, DP83065_MII_REGE, 0x8ffc); cas_phy_write(cp, DP83065_MII_REGD, 0x39); /* download new firmware */ cas_phy_write(cp, DP83065_MII_MEM, 0x1); cas_phy_write(cp, DP83065_MII_REGE, cp->fw_load_addr); for (i = 0; i < cp->fw_size; i++) cas_phy_write(cp, DP83065_MII_REGD, cp->fw_data[i]); /* enable firmware */ cas_phy_write(cp, DP83065_MII_REGE, 0x8ff8); cas_phy_write(cp, DP83065_MII_REGD, 0x1); } /* phy initialization */ static void cas_phy_init(struct cas *cp) { u16 val; /* if we're in MII/GMII mode, set up phy */ if (CAS_PHY_MII(cp->phy_type)) { writel(PCS_DATAPATH_MODE_MII, cp->regs + REG_PCS_DATAPATH_MODE); cas_mif_poll(cp, 0); cas_reset_mii_phy(cp); /* take out of isolate mode */ if (PHY_LUCENT_B0 == cp->phy_id) { /* workaround link up/down issue with lucent */ cas_phy_write(cp, LUCENT_MII_REG, 0x8000); cas_phy_write(cp, MII_BMCR, 0x00f1); cas_phy_write(cp, LUCENT_MII_REG, 0x0); } else if (PHY_BROADCOM_B0 == (cp->phy_id & 0xFFFFFFFC)) { /* workarounds for broadcom phy */ cas_phy_write(cp, BROADCOM_MII_REG8, 0x0C20); cas_phy_write(cp, BROADCOM_MII_REG7, 0x0012); cas_phy_write(cp, BROADCOM_MII_REG5, 0x1804); cas_phy_write(cp, BROADCOM_MII_REG7, 0x0013); cas_phy_write(cp, BROADCOM_MII_REG5, 0x1204); cas_phy_write(cp, BROADCOM_MII_REG7, 0x8006); cas_phy_write(cp, BROADCOM_MII_REG5, 0x0132); cas_phy_write(cp, BROADCOM_MII_REG7, 0x8006); cas_phy_write(cp, BROADCOM_MII_REG5, 0x0232); cas_phy_write(cp, BROADCOM_MII_REG7, 0x201F); cas_phy_write(cp, BROADCOM_MII_REG5, 0x0A20); } else if (PHY_BROADCOM_5411 == cp->phy_id) { val = cas_phy_read(cp, BROADCOM_MII_REG4); val = cas_phy_read(cp, BROADCOM_MII_REG4); if (val & 0x0080) { /* link workaround */ cas_phy_write(cp, BROADCOM_MII_REG4, val & ~0x0080); } } else if (cp->cas_flags & CAS_FLAG_SATURN) { writel((cp->phy_type & CAS_PHY_MII_MDIO0) ? SATURN_PCFG_FSI : 0x0, cp->regs + REG_SATURN_PCFG); /* load firmware to address 10Mbps auto-negotiation * issue. NOTE: this will need to be changed if the * default firmware gets fixed. */ if (PHY_NS_DP83065 == cp->phy_id) { cas_saturn_firmware_load(cp); } cas_phy_powerup(cp); } /* advertise capabilities */ val = cas_phy_read(cp, MII_BMCR); val &= ~BMCR_ANENABLE; cas_phy_write(cp, MII_BMCR, val); udelay(10); cas_phy_write(cp, MII_ADVERTISE, cas_phy_read(cp, MII_ADVERTISE) | (ADVERTISE_10HALF | ADVERTISE_10FULL | ADVERTISE_100HALF | ADVERTISE_100FULL | CAS_ADVERTISE_PAUSE | CAS_ADVERTISE_ASYM_PAUSE)); if (cp->cas_flags & CAS_FLAG_1000MB_CAP) { /* make sure that we don't advertise half * duplex to avoid a chip issue */ val = cas_phy_read(cp, CAS_MII_1000_CTRL); val &= ~CAS_ADVERTISE_1000HALF; val |= CAS_ADVERTISE_1000FULL; cas_phy_write(cp, CAS_MII_1000_CTRL, val); } } else { /* reset pcs for serdes */ u32 val; int limit; writel(PCS_DATAPATH_MODE_SERDES, cp->regs + REG_PCS_DATAPATH_MODE); /* enable serdes pins on saturn */ if (cp->cas_flags & CAS_FLAG_SATURN) writel(0, cp->regs + REG_SATURN_PCFG); /* Reset PCS unit. */ val = readl(cp->regs + REG_PCS_MII_CTRL); val |= PCS_MII_RESET; writel(val, cp->regs + REG_PCS_MII_CTRL); limit = STOP_TRIES; while (--limit > 0) { udelay(10); if ((readl(cp->regs + REG_PCS_MII_CTRL) & PCS_MII_RESET) == 0) break; } if (limit <= 0) netdev_warn(cp->dev, "PCS reset bit would not clear [%08x]\n", readl(cp->regs + REG_PCS_STATE_MACHINE)); /* Make sure PCS is disabled while changing advertisement * configuration. */ writel(0x0, cp->regs + REG_PCS_CFG); /* Advertise all capabilities except half-duplex. */ val = readl(cp->regs + REG_PCS_MII_ADVERT); val &= ~PCS_MII_ADVERT_HD; val |= (PCS_MII_ADVERT_FD | PCS_MII_ADVERT_SYM_PAUSE | PCS_MII_ADVERT_ASYM_PAUSE); writel(val, cp->regs + REG_PCS_MII_ADVERT); /* enable PCS */ writel(PCS_CFG_EN, cp->regs + REG_PCS_CFG); /* pcs workaround: enable sync detect */ writel(PCS_SERDES_CTRL_SYNCD_EN, cp->regs + REG_PCS_SERDES_CTRL); } } static int cas_pcs_link_check(struct cas *cp) { u32 stat, state_machine; int retval = 0; /* The link status bit latches on zero, so you must * read it twice in such a case to see a transition * to the link being up. */ stat = readl(cp->regs + REG_PCS_MII_STATUS); if ((stat & PCS_MII_STATUS_LINK_STATUS) == 0) stat = readl(cp->regs + REG_PCS_MII_STATUS); /* The remote-fault indication is only valid * when autoneg has completed. */ if ((stat & (PCS_MII_STATUS_AUTONEG_COMP | PCS_MII_STATUS_REMOTE_FAULT)) == (PCS_MII_STATUS_AUTONEG_COMP | PCS_MII_STATUS_REMOTE_FAULT)) netif_info(cp, link, cp->dev, "PCS RemoteFault\n"); /* work around link detection issue by querying the PCS state * machine directly. */ state_machine = readl(cp->regs + REG_PCS_STATE_MACHINE); if ((state_machine & PCS_SM_LINK_STATE_MASK) != SM_LINK_STATE_UP) { stat &= ~PCS_MII_STATUS_LINK_STATUS; } else if (state_machine & PCS_SM_WORD_SYNC_STATE_MASK) { stat |= PCS_MII_STATUS_LINK_STATUS; } if (stat & PCS_MII_STATUS_LINK_STATUS) { if (cp->lstate != link_up) { if (cp->opened) { cp->lstate = link_up; cp->link_transition = LINK_TRANSITION_LINK_UP; cas_set_link_modes(cp); netif_carrier_on(cp->dev); } } } else if (cp->lstate == link_up) { cp->lstate = link_down; if (link_transition_timeout != 0 && cp->link_transition != LINK_TRANSITION_REQUESTED_RESET && !cp->link_transition_jiffies_valid) { /* * force a reset, as a workaround for the * link-failure problem. May want to move this to a * point a bit earlier in the sequence. If we had * generated a reset a short time ago, we'll wait for * the link timer to check the status until a * timer expires (link_transistion_jiffies_valid is * true when the timer is running.) Instead of using * a system timer, we just do a check whenever the * link timer is running - this clears the flag after * a suitable delay. */ retval = 1; cp->link_transition = LINK_TRANSITION_REQUESTED_RESET; cp->link_transition_jiffies = jiffies; cp->link_transition_jiffies_valid = 1; } else { cp->link_transition = LINK_TRANSITION_ON_FAILURE; } netif_carrier_off(cp->dev); if (cp->opened) netif_info(cp, link, cp->dev, "PCS link down\n"); /* Cassini only: if you force a mode, there can be * sync problems on link down. to fix that, the following * things need to be checked: * 1) read serialink state register * 2) read pcs status register to verify link down. * 3) if link down and serial link == 0x03, then you need * to global reset the chip. */ if ((cp->cas_flags & CAS_FLAG_REG_PLUS) == 0) { /* should check to see if we're in a forced mode */ stat = readl(cp->regs + REG_PCS_SERDES_STATE); if (stat == 0x03) return 1; } } else if (cp->lstate == link_down) { if (link_transition_timeout != 0 && cp->link_transition != LINK_TRANSITION_REQUESTED_RESET && !cp->link_transition_jiffies_valid) { /* force a reset, as a workaround for the * link-failure problem. May want to move * this to a point a bit earlier in the * sequence. */ retval = 1; cp->link_transition = LINK_TRANSITION_REQUESTED_RESET; cp->link_transition_jiffies = jiffies; cp->link_transition_jiffies_valid = 1; } else { cp->link_transition = LINK_TRANSITION_STILL_FAILED; } } return retval; } static int cas_pcs_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 stat = readl(cp->regs + REG_PCS_INTR_STATUS); if ((stat & PCS_INTR_STATUS_LINK_CHANGE) == 0) return 0; return cas_pcs_link_check(cp); } static int cas_txmac_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 txmac_stat = readl(cp->regs + REG_MAC_TX_STATUS); if (!txmac_stat) return 0; netif_printk(cp, intr, KERN_DEBUG, cp->dev, "txmac interrupt, txmac_stat: 0x%x\n", txmac_stat); /* Defer timer expiration is quite normal, * don't even log the event. */ if ((txmac_stat & MAC_TX_DEFER_TIMER) && !(txmac_stat & ~MAC_TX_DEFER_TIMER)) return 0; spin_lock(&cp->stat_lock[0]); if (txmac_stat & MAC_TX_UNDERRUN) { netdev_err(dev, "TX MAC xmit underrun\n"); cp->net_stats[0].tx_fifo_errors++; } if (txmac_stat & MAC_TX_MAX_PACKET_ERR) { netdev_err(dev, "TX MAC max packet size error\n"); cp->net_stats[0].tx_errors++; } /* The rest are all cases of one of the 16-bit TX * counters expiring. */ if (txmac_stat & MAC_TX_COLL_NORMAL) cp->net_stats[0].collisions += 0x10000; if (txmac_stat & MAC_TX_COLL_EXCESS) { cp->net_stats[0].tx_aborted_errors += 0x10000; cp->net_stats[0].collisions += 0x10000; } if (txmac_stat & MAC_TX_COLL_LATE) { cp->net_stats[0].tx_aborted_errors += 0x10000; cp->net_stats[0].collisions += 0x10000; } spin_unlock(&cp->stat_lock[0]); /* We do not keep track of MAC_TX_COLL_FIRST and * MAC_TX_PEAK_ATTEMPTS events. */ return 0; } static void cas_load_firmware(struct cas *cp, cas_hp_inst_t *firmware) { cas_hp_inst_t *inst; u32 val; int i; i = 0; while ((inst = firmware) && inst->note) { writel(i, cp->regs + REG_HP_INSTR_RAM_ADDR); val = CAS_BASE(HP_INSTR_RAM_HI_VAL, inst->val); val |= CAS_BASE(HP_INSTR_RAM_HI_MASK, inst->mask); writel(val, cp->regs + REG_HP_INSTR_RAM_DATA_HI); val = CAS_BASE(HP_INSTR_RAM_MID_OUTARG, inst->outarg >> 10); val |= CAS_BASE(HP_INSTR_RAM_MID_OUTOP, inst->outop); val |= CAS_BASE(HP_INSTR_RAM_MID_FNEXT, inst->fnext); val |= CAS_BASE(HP_INSTR_RAM_MID_FOFF, inst->foff); val |= CAS_BASE(HP_INSTR_RAM_MID_SNEXT, inst->snext); val |= CAS_BASE(HP_INSTR_RAM_MID_SOFF, inst->soff); val |= CAS_BASE(HP_INSTR_RAM_MID_OP, inst->op); writel(val, cp->regs + REG_HP_INSTR_RAM_DATA_MID); val = CAS_BASE(HP_INSTR_RAM_LOW_OUTMASK, inst->outmask); val |= CAS_BASE(HP_INSTR_RAM_LOW_OUTSHIFT, inst->outshift); val |= CAS_BASE(HP_INSTR_RAM_LOW_OUTEN, inst->outenab); val |= CAS_BASE(HP_INSTR_RAM_LOW_OUTARG, inst->outarg); writel(val, cp->regs + REG_HP_INSTR_RAM_DATA_LOW); ++firmware; ++i; } } static void cas_init_rx_dma(struct cas *cp) { u64 desc_dma = cp->block_dvma; u32 val; int i, size; /* rx free descriptors */ val = CAS_BASE(RX_CFG_SWIVEL, RX_SWIVEL_OFF_VAL); val |= CAS_BASE(RX_CFG_DESC_RING, RX_DESC_RINGN_INDEX(0)); val |= CAS_BASE(RX_CFG_COMP_RING, RX_COMP_RINGN_INDEX(0)); if ((N_RX_DESC_RINGS > 1) && (cp->cas_flags & CAS_FLAG_REG_PLUS)) /* do desc 2 */ val |= CAS_BASE(RX_CFG_DESC_RING1, RX_DESC_RINGN_INDEX(1)); writel(val, cp->regs + REG_RX_CFG); val = (unsigned long) cp->init_rxds[0] - (unsigned long) cp->init_block; writel((desc_dma + val) >> 32, cp->regs + REG_RX_DB_HI); writel((desc_dma + val) & 0xffffffff, cp->regs + REG_RX_DB_LOW); writel(RX_DESC_RINGN_SIZE(0) - 4, cp->regs + REG_RX_KICK); if (cp->cas_flags & CAS_FLAG_REG_PLUS) { /* rx desc 2 is for IPSEC packets. however, * we don't it that for that purpose. */ val = (unsigned long) cp->init_rxds[1] - (unsigned long) cp->init_block; writel((desc_dma + val) >> 32, cp->regs + REG_PLUS_RX_DB1_HI); writel((desc_dma + val) & 0xffffffff, cp->regs + REG_PLUS_RX_DB1_LOW); writel(RX_DESC_RINGN_SIZE(1) - 4, cp->regs + REG_PLUS_RX_KICK1); } /* rx completion registers */ val = (unsigned long) cp->init_rxcs[0] - (unsigned long) cp->init_block; writel((desc_dma + val) >> 32, cp->regs + REG_RX_CB_HI); writel((desc_dma + val) & 0xffffffff, cp->regs + REG_RX_CB_LOW); if (cp->cas_flags & CAS_FLAG_REG_PLUS) { /* rx comp 2-4 */ for (i = 1; i < MAX_RX_COMP_RINGS; i++) { val = (unsigned long) cp->init_rxcs[i] - (unsigned long) cp->init_block; writel((desc_dma + val) >> 32, cp->regs + REG_PLUS_RX_CBN_HI(i)); writel((desc_dma + val) & 0xffffffff, cp->regs + REG_PLUS_RX_CBN_LOW(i)); } } /* read selective clear regs to prevent spurious interrupts * on reset because complete == kick. * selective clear set up to prevent interrupts on resets */ readl(cp->regs + REG_INTR_STATUS_ALIAS); writel(INTR_RX_DONE | INTR_RX_BUF_UNAVAIL, cp->regs + REG_ALIAS_CLEAR); if (cp->cas_flags & CAS_FLAG_REG_PLUS) { for (i = 1; i < N_RX_COMP_RINGS; i++) readl(cp->regs + REG_PLUS_INTRN_STATUS_ALIAS(i)); /* 2 is different from 3 and 4 */ if (N_RX_COMP_RINGS > 1) writel(INTR_RX_DONE_ALT | INTR_RX_BUF_UNAVAIL_1, cp->regs + REG_PLUS_ALIASN_CLEAR(1)); for (i = 2; i < N_RX_COMP_RINGS; i++) writel(INTR_RX_DONE_ALT, cp->regs + REG_PLUS_ALIASN_CLEAR(i)); } /* set up pause thresholds */ val = CAS_BASE(RX_PAUSE_THRESH_OFF, cp->rx_pause_off / RX_PAUSE_THRESH_QUANTUM); val |= CAS_BASE(RX_PAUSE_THRESH_ON, cp->rx_pause_on / RX_PAUSE_THRESH_QUANTUM); writel(val, cp->regs + REG_RX_PAUSE_THRESH); /* zero out dma reassembly buffers */ for (i = 0; i < 64; i++) { writel(i, cp->regs + REG_RX_TABLE_ADDR); writel(0x0, cp->regs + REG_RX_TABLE_DATA_LOW); writel(0x0, cp->regs + REG_RX_TABLE_DATA_MID); writel(0x0, cp->regs + REG_RX_TABLE_DATA_HI); } /* make sure address register is 0 for normal operation */ writel(0x0, cp->regs + REG_RX_CTRL_FIFO_ADDR); writel(0x0, cp->regs + REG_RX_IPP_FIFO_ADDR); /* interrupt mitigation */ #ifdef USE_RX_BLANK val = CAS_BASE(RX_BLANK_INTR_TIME, RX_BLANK_INTR_TIME_VAL); val |= CAS_BASE(RX_BLANK_INTR_PKT, RX_BLANK_INTR_PKT_VAL); writel(val, cp->regs + REG_RX_BLANK); #else writel(0x0, cp->regs + REG_RX_BLANK); #endif /* interrupt generation as a function of low water marks for * free desc and completion entries. these are used to trigger * housekeeping for rx descs. we don't use the free interrupt * as it's not very useful */ /* val = CAS_BASE(RX_AE_THRESH_FREE, RX_AE_FREEN_VAL(0)); */ val = CAS_BASE(RX_AE_THRESH_COMP, RX_AE_COMP_VAL); writel(val, cp->regs + REG_RX_AE_THRESH); if (cp->cas_flags & CAS_FLAG_REG_PLUS) { val = CAS_BASE(RX_AE1_THRESH_FREE, RX_AE_FREEN_VAL(1)); writel(val, cp->regs + REG_PLUS_RX_AE1_THRESH); } /* Random early detect registers. useful for congestion avoidance. * this should be tunable. */ writel(0x0, cp->regs + REG_RX_RED); /* receive page sizes. default == 2K (0x800) */ val = 0; if (cp->page_size == 0x1000) val = 0x1; else if (cp->page_size == 0x2000) val = 0x2; else if (cp->page_size == 0x4000) val = 0x3; /* round mtu + offset. constrain to page size. */ size = cp->dev->mtu + 64; if (size > cp->page_size) size = cp->page_size; if (size <= 0x400) i = 0x0; else if (size <= 0x800) i = 0x1; else if (size <= 0x1000) i = 0x2; else i = 0x3; cp->mtu_stride = 1 << (i + 10); val = CAS_BASE(RX_PAGE_SIZE, val); val |= CAS_BASE(RX_PAGE_SIZE_MTU_STRIDE, i); val |= CAS_BASE(RX_PAGE_SIZE_MTU_COUNT, cp->page_size >> (i + 10)); val |= CAS_BASE(RX_PAGE_SIZE_MTU_OFF, 0x1); writel(val, cp->regs + REG_RX_PAGE_SIZE); /* enable the header parser if desired */ if (CAS_HP_FIRMWARE == cas_prog_null) return; val = CAS_BASE(HP_CFG_NUM_CPU, CAS_NCPUS > 63 ? 0 : CAS_NCPUS); val |= HP_CFG_PARSE_EN | HP_CFG_SYN_INC_MASK; val |= CAS_BASE(HP_CFG_TCP_THRESH, HP_TCP_THRESH_VAL); writel(val, cp->regs + REG_HP_CFG); } static inline void cas_rxc_init(struct cas_rx_comp *rxc) { memset(rxc, 0, sizeof(*rxc)); rxc->word4 = cpu_to_le64(RX_COMP4_ZERO); } /* NOTE: we use the ENC RX DESC ring for spares. the rx_page[0,1] * flipping is protected by the fact that the chip will not * hand back the same page index while it's being processed. */ static inline cas_page_t *cas_page_spare(struct cas *cp, const int index) { cas_page_t *page = cp->rx_pages[1][index]; cas_page_t *new; if (page_count(page->buffer) == 1) return page; new = cas_page_dequeue(cp); if (new) { spin_lock(&cp->rx_inuse_lock); list_add(&page->list, &cp->rx_inuse_list); spin_unlock(&cp->rx_inuse_lock); } return new; } /* this needs to be changed if we actually use the ENC RX DESC ring */ static cas_page_t *cas_page_swap(struct cas *cp, const int ring, const int index) { cas_page_t **page0 = cp->rx_pages[0]; cas_page_t **page1 = cp->rx_pages[1]; /* swap if buffer is in use */ if (page_count(page0[index]->buffer) > 1) { cas_page_t *new = cas_page_spare(cp, index); if (new) { page1[index] = page0[index]; page0[index] = new; } } RX_USED_SET(page0[index], 0); return page0[index]; } static void cas_clean_rxds(struct cas *cp) { /* only clean ring 0 as ring 1 is used for spare buffers */ struct cas_rx_desc *rxd = cp->init_rxds[0]; int i, size; /* release all rx flows */ for (i = 0; i < N_RX_FLOWS; i++) { struct sk_buff *skb; while ((skb = __skb_dequeue(&cp->rx_flows[i]))) { cas_skb_release(skb); } } /* initialize descriptors */ size = RX_DESC_RINGN_SIZE(0); for (i = 0; i < size; i++) { cas_page_t *page = cas_page_swap(cp, 0, i); rxd[i].buffer = cpu_to_le64(page->dma_addr); rxd[i].index = cpu_to_le64(CAS_BASE(RX_INDEX_NUM, i) | CAS_BASE(RX_INDEX_RING, 0)); } cp->rx_old[0] = RX_DESC_RINGN_SIZE(0) - 4; cp->rx_last[0] = 0; cp->cas_flags &= ~CAS_FLAG_RXD_POST(0); } static void cas_clean_rxcs(struct cas *cp) { int i, j; /* take ownership of rx comp descriptors */ memset(cp->rx_cur, 0, sizeof(*cp->rx_cur)*N_RX_COMP_RINGS); memset(cp->rx_new, 0, sizeof(*cp->rx_new)*N_RX_COMP_RINGS); for (i = 0; i < N_RX_COMP_RINGS; i++) { struct cas_rx_comp *rxc = cp->init_rxcs[i]; for (j = 0; j < RX_COMP_RINGN_SIZE(i); j++) { cas_rxc_init(rxc + j); } } } #if 0 /* When we get a RX fifo overflow, the RX unit is probably hung * so we do the following. * * If any part of the reset goes wrong, we return 1 and that causes the * whole chip to be reset. */ static int cas_rxmac_reset(struct cas *cp) { struct net_device *dev = cp->dev; int limit; u32 val; /* First, reset MAC RX. */ writel(cp->mac_rx_cfg & ~MAC_RX_CFG_EN, cp->regs + REG_MAC_RX_CFG); for (limit = 0; limit < STOP_TRIES; limit++) { if (!(readl(cp->regs + REG_MAC_RX_CFG) & MAC_RX_CFG_EN)) break; udelay(10); } if (limit == STOP_TRIES) { netdev_err(dev, "RX MAC will not disable, resetting whole chip\n"); return 1; } /* Second, disable RX DMA. */ writel(0, cp->regs + REG_RX_CFG); for (limit = 0; limit < STOP_TRIES; limit++) { if (!(readl(cp->regs + REG_RX_CFG) & RX_CFG_DMA_EN)) break; udelay(10); } if (limit == STOP_TRIES) { netdev_err(dev, "RX DMA will not disable, resetting whole chip\n"); return 1; } mdelay(5); /* Execute RX reset command. */ writel(SW_RESET_RX, cp->regs + REG_SW_RESET); for (limit = 0; limit < STOP_TRIES; limit++) { if (!(readl(cp->regs + REG_SW_RESET) & SW_RESET_RX)) break; udelay(10); } if (limit == STOP_TRIES) { netdev_err(dev, "RX reset command will not execute, resetting whole chip\n"); return 1; } /* reset driver rx state */ cas_clean_rxds(cp); cas_clean_rxcs(cp); /* Now, reprogram the rest of RX unit. */ cas_init_rx_dma(cp); /* re-enable */ val = readl(cp->regs + REG_RX_CFG); writel(val | RX_CFG_DMA_EN, cp->regs + REG_RX_CFG); writel(MAC_RX_FRAME_RECV, cp->regs + REG_MAC_RX_MASK); val = readl(cp->regs + REG_MAC_RX_CFG); writel(val | MAC_RX_CFG_EN, cp->regs + REG_MAC_RX_CFG); return 0; } #endif static int cas_rxmac_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 stat = readl(cp->regs + REG_MAC_RX_STATUS); if (!stat) return 0; netif_dbg(cp, intr, cp->dev, "rxmac interrupt, stat: 0x%x\n", stat); /* these are all rollovers */ spin_lock(&cp->stat_lock[0]); if (stat & MAC_RX_ALIGN_ERR) cp->net_stats[0].rx_frame_errors += 0x10000; if (stat & MAC_RX_CRC_ERR) cp->net_stats[0].rx_crc_errors += 0x10000; if (stat & MAC_RX_LEN_ERR) cp->net_stats[0].rx_length_errors += 0x10000; if (stat & MAC_RX_OVERFLOW) { cp->net_stats[0].rx_over_errors++; cp->net_stats[0].rx_fifo_errors++; } /* We do not track MAC_RX_FRAME_COUNT and MAC_RX_VIOL_ERR * events. */ spin_unlock(&cp->stat_lock[0]); return 0; } static int cas_mac_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 stat = readl(cp->regs + REG_MAC_CTRL_STATUS); if (!stat) return 0; netif_printk(cp, intr, KERN_DEBUG, cp->dev, "mac interrupt, stat: 0x%x\n", stat); /* This interrupt is just for pause frame and pause * tracking. It is useful for diagnostics and debug * but probably by default we will mask these events. */ if (stat & MAC_CTRL_PAUSE_STATE) cp->pause_entered++; if (stat & MAC_CTRL_PAUSE_RECEIVED) cp->pause_last_time_recvd = (stat >> 16); return 0; } /* Must be invoked under cp->lock. */ static inline int cas_mdio_link_not_up(struct cas *cp) { u16 val; switch (cp->lstate) { case link_force_ret: netif_info(cp, link, cp->dev, "Autoneg failed again, keeping forced mode\n"); cas_phy_write(cp, MII_BMCR, cp->link_fcntl); cp->timer_ticks = 5; cp->lstate = link_force_ok; cp->link_transition = LINK_TRANSITION_LINK_CONFIG; break; case link_aneg: val = cas_phy_read(cp, MII_BMCR); /* Try forced modes. we try things in the following order: * 1000 full -> 100 full/half -> 10 half */ val &= ~(BMCR_ANRESTART | BMCR_ANENABLE); val |= BMCR_FULLDPLX; val |= (cp->cas_flags & CAS_FLAG_1000MB_CAP) ? CAS_BMCR_SPEED1000 : BMCR_SPEED100; cas_phy_write(cp, MII_BMCR, val); cp->timer_ticks = 5; cp->lstate = link_force_try; cp->link_transition = LINK_TRANSITION_LINK_CONFIG; break; case link_force_try: /* Downgrade from 1000 to 100 to 10 Mbps if necessary. */ val = cas_phy_read(cp, MII_BMCR); cp->timer_ticks = 5; if (val & CAS_BMCR_SPEED1000) { /* gigabit */ val &= ~CAS_BMCR_SPEED1000; val |= (BMCR_SPEED100 | BMCR_FULLDPLX); cas_phy_write(cp, MII_BMCR, val); break; } if (val & BMCR_SPEED100) { if (val & BMCR_FULLDPLX) /* fd failed */ val &= ~BMCR_FULLDPLX; else { /* 100Mbps failed */ val &= ~BMCR_SPEED100; } cas_phy_write(cp, MII_BMCR, val); break; } default: break; } return 0; } /* must be invoked with cp->lock held */ static int cas_mii_link_check(struct cas *cp, const u16 bmsr) { int restart; if (bmsr & BMSR_LSTATUS) { /* Ok, here we got a link. If we had it due to a forced * fallback, and we were configured for autoneg, we * retry a short autoneg pass. If you know your hub is * broken, use ethtool ;) */ if ((cp->lstate == link_force_try) && (cp->link_cntl & BMCR_ANENABLE)) { cp->lstate = link_force_ret; cp->link_transition = LINK_TRANSITION_LINK_CONFIG; cas_mif_poll(cp, 0); cp->link_fcntl = cas_phy_read(cp, MII_BMCR); cp->timer_ticks = 5; if (cp->opened) netif_info(cp, link, cp->dev, "Got link after fallback, retrying autoneg once...\n"); cas_phy_write(cp, MII_BMCR, cp->link_fcntl | BMCR_ANENABLE | BMCR_ANRESTART); cas_mif_poll(cp, 1); } else if (cp->lstate != link_up) { cp->lstate = link_up; cp->link_transition = LINK_TRANSITION_LINK_UP; if (cp->opened) { cas_set_link_modes(cp); netif_carrier_on(cp->dev); } } return 0; } /* link not up. if the link was previously up, we restart the * whole process */ restart = 0; if (cp->lstate == link_up) { cp->lstate = link_down; cp->link_transition = LINK_TRANSITION_LINK_DOWN; netif_carrier_off(cp->dev); if (cp->opened) netif_info(cp, link, cp->dev, "Link down\n"); restart = 1; } else if (++cp->timer_ticks > 10) cas_mdio_link_not_up(cp); return restart; } static int cas_mif_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 stat = readl(cp->regs + REG_MIF_STATUS); u16 bmsr; /* check for a link change */ if (CAS_VAL(MIF_STATUS_POLL_STATUS, stat) == 0) return 0; bmsr = CAS_VAL(MIF_STATUS_POLL_DATA, stat); return cas_mii_link_check(cp, bmsr); } static int cas_pci_interrupt(struct net_device *dev, struct cas *cp, u32 status) { u32 stat = readl(cp->regs + REG_PCI_ERR_STATUS); if (!stat) return 0; netdev_err(dev, "PCI error [%04x:%04x]", stat, readl(cp->regs + REG_BIM_DIAG)); /* cassini+ has this reserved */ if ((stat & PCI_ERR_BADACK) && ((cp->cas_flags & CAS_FLAG_REG_PLUS) == 0)) pr_cont(" <No ACK64# during ABS64 cycle>"); if (stat & PCI_ERR_DTRTO) pr_cont(" <Delayed transaction timeout>"); if (stat & PCI_ERR_OTHER) pr_cont(" <other>"); if (stat & PCI_ERR_BIM_DMA_WRITE) pr_cont(" <BIM DMA 0 write req>"); if (stat & PCI_ERR_BIM_DMA_READ) pr_cont(" <BIM DMA 0 read req>"); pr_cont("\n"); if (stat & PCI_ERR_OTHER) { u16 cfg; /* Interrogate PCI config space for the * true cause. */ pci_read_config_word(cp->pdev, PCI_STATUS, &cfg); netdev_err(dev, "Read PCI cfg space status [%04x]\n", cfg); if (cfg & PCI_STATUS_PARITY) netdev_err(dev, "PCI parity error detected\n"); if (cfg & PCI_STATUS_SIG_TARGET_ABORT) netdev_err(dev, "PCI target abort\n"); if (cfg & PCI_STATUS_REC_TARGET_ABORT) netdev_err(dev, "PCI master acks target abort\n"); if (cfg & PCI_STATUS_REC_MASTER_ABORT) netdev_err(dev, "PCI master abort\n"); if (cfg & PCI_STATUS_SIG_SYSTEM_ERROR) netdev_err(dev, "PCI system error SERR#\n"); if (cfg & PCI_STATUS_DETECTED_PARITY) netdev_err(dev, "PCI parity error\n"); /* Write the error bits back to clear them. */ cfg &= (PCI_STATUS_PARITY | PCI_STATUS_SIG_TARGET_ABORT | PCI_STATUS_REC_TARGET_ABORT | PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY); pci_write_config_word(cp->pdev, PCI_STATUS, cfg); } /* For all PCI errors, we should reset the chip. */ return 1; } /* All non-normal interrupt conditions get serviced here. * Returns non-zero if we should just exit the interrupt * handler right now (ie. if we reset the card which invalidates * all of the other original irq status bits). */ static int cas_abnormal_irq(struct net_device *dev, struct cas *cp, u32 status) { if (status & INTR_RX_TAG_ERROR) { /* corrupt RX tag framing */ netif_printk(cp, rx_err, KERN_DEBUG, cp->dev, "corrupt rx tag framing\n"); spin_lock(&cp->stat_lock[0]); cp->net_stats[0].rx_errors++; spin_unlock(&cp->stat_lock[0]); goto do_reset; } if (status & INTR_RX_LEN_MISMATCH) { /* length mismatch. */ netif_printk(cp, rx_err, KERN_DEBUG, cp->dev, "length mismatch for rx frame\n"); spin_lock(&cp->stat_lock[0]); cp->net_stats[0].rx_errors++; spin_unlock(&cp->stat_lock[0]); goto do_reset; } if (status & INTR_PCS_STATUS) { if (cas_pcs_interrupt(dev, cp, status)) goto do_reset; } if (status & INTR_TX_MAC_STATUS) { if (cas_txmac_interrupt(dev, cp, status)) goto do_reset; } if (status & INTR_RX_MAC_STATUS) { if (cas_rxmac_interrupt(dev, cp, status)) goto do_reset; } if (status & INTR_MAC_CTRL_STATUS) { if (cas_mac_interrupt(dev, cp, status)) goto do_reset; } if (status & INTR_MIF_STATUS) { if (cas_mif_interrupt(dev, cp, status)) goto do_reset; } if (status & INTR_PCI_ERROR_STATUS) { if (cas_pci_interrupt(dev, cp, status)) goto do_reset; } return 0; do_reset: #if 1 atomic_inc(&cp->reset_task_pending); atomic_inc(&cp->reset_task_pending_all); netdev_err(dev, "reset called in cas_abnormal_irq [0x%x]\n", status); schedule_work(&cp->reset_task); #else atomic_set(&cp->reset_task_pending, CAS_RESET_ALL); netdev_err(dev, "reset called in cas_abnormal_irq\n"); schedule_work(&cp->reset_task); #endif return 1; } /* NOTE: CAS_TABORT returns 1 or 2 so that it can be used when * determining whether to do a netif_stop/wakeup */ #define CAS_TABORT(x) (((x)->cas_flags & CAS_FLAG_TARGET_ABORT) ? 2 : 1) #define CAS_ROUND_PAGE(x) (((x) + PAGE_SIZE - 1) & PAGE_MASK) static inline int cas_calc_tabort(struct cas *cp, const unsigned long addr, const int len) { unsigned long off = addr + len; if (CAS_TABORT(cp) == 1) return 0; if ((CAS_ROUND_PAGE(off) - off) > TX_TARGET_ABORT_LEN) return 0; return TX_TARGET_ABORT_LEN; } static inline void cas_tx_ringN(struct cas *cp, int ring, int limit) { struct cas_tx_desc *txds; struct sk_buff **skbs; struct net_device *dev = cp->dev; int entry, count; spin_lock(&cp->tx_lock[ring]); txds = cp->init_txds[ring]; skbs = cp->tx_skbs[ring]; entry = cp->tx_old[ring]; count = TX_BUFF_COUNT(ring, entry, limit); while (entry != limit) { struct sk_buff *skb = skbs[entry]; dma_addr_t daddr; u32 dlen; int frag; if (!skb) { /* this should never occur */ entry = TX_DESC_NEXT(ring, entry); continue; } /* however, we might get only a partial skb release. */ count -= skb_shinfo(skb)->nr_frags + + cp->tx_tiny_use[ring][entry].nbufs + 1; if (count < 0) break; netif_printk(cp, tx_done, KERN_DEBUG, cp->dev, "tx[%d] done, slot %d\n", ring, entry); skbs[entry] = NULL; cp->tx_tiny_use[ring][entry].nbufs = 0; for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) { struct cas_tx_desc *txd = txds + entry; daddr = le64_to_cpu(txd->buffer); dlen = CAS_VAL(TX_DESC_BUFLEN, le64_to_cpu(txd->control)); pci_unmap_page(cp->pdev, daddr, dlen, PCI_DMA_TODEVICE); entry = TX_DESC_NEXT(ring, entry); /* tiny buffer may follow */ if (cp->tx_tiny_use[ring][entry].used) { cp->tx_tiny_use[ring][entry].used = 0; entry = TX_DESC_NEXT(ring, entry); } } spin_lock(&cp->stat_lock[ring]); cp->net_stats[ring].tx_packets++; cp->net_stats[ring].tx_bytes += skb->len; spin_unlock(&cp->stat_lock[ring]); dev_kfree_skb_irq(skb); } cp->tx_old[ring] = entry; /* this is wrong for multiple tx rings. the net device needs * multiple queues for this to do the right thing. we wait * for 2*packets to be available when using tiny buffers */ if (netif_queue_stopped(dev) && (TX_BUFFS_AVAIL(cp, ring) > CAS_TABORT(cp)*(MAX_SKB_FRAGS + 1))) netif_wake_queue(dev); spin_unlock(&cp->tx_lock[ring]); } static void cas_tx(struct net_device *dev, struct cas *cp, u32 status) { int limit, ring; #ifdef USE_TX_COMPWB u64 compwb = le64_to_cpu(cp->init_block->tx_compwb); #endif netif_printk(cp, intr, KERN_DEBUG, cp->dev, "tx interrupt, status: 0x%x, %llx\n", status, (unsigned long long)compwb); /* process all the rings */ for (ring = 0; ring < N_TX_RINGS; ring++) { #ifdef USE_TX_COMPWB /* use the completion writeback registers */ limit = (CAS_VAL(TX_COMPWB_MSB, compwb) << 8) | CAS_VAL(TX_COMPWB_LSB, compwb); compwb = TX_COMPWB_NEXT(compwb); #else limit = readl(cp->regs + REG_TX_COMPN(ring)); #endif if (cp->tx_old[ring] != limit) cas_tx_ringN(cp, ring, limit); } } static int cas_rx_process_pkt(struct cas *cp, struct cas_rx_comp *rxc, int entry, const u64 *words, struct sk_buff **skbref) { int dlen, hlen, len, i, alloclen; int off, swivel = RX_SWIVEL_OFF_VAL; struct cas_page *page; struct sk_buff *skb; void *addr, *crcaddr; __sum16 csum; char *p; hlen = CAS_VAL(RX_COMP2_HDR_SIZE, words[1]); dlen = CAS_VAL(RX_COMP1_DATA_SIZE, words[0]); len = hlen + dlen; if (RX_COPY_ALWAYS || (words[2] & RX_COMP3_SMALL_PKT)) alloclen = len; else alloclen = max(hlen, RX_COPY_MIN); skb = netdev_alloc_skb(cp->dev, alloclen + swivel + cp->crc_size); if (skb == NULL) return -1; *skbref = skb; skb_reserve(skb, swivel); p = skb->data; addr = crcaddr = NULL; if (hlen) { /* always copy header pages */ i = CAS_VAL(RX_COMP2_HDR_INDEX, words[1]); page = cp->rx_pages[CAS_VAL(RX_INDEX_RING, i)][CAS_VAL(RX_INDEX_NUM, i)]; off = CAS_VAL(RX_COMP2_HDR_OFF, words[1]) * 0x100 + swivel; i = hlen; if (!dlen) /* attach FCS */ i += cp->crc_size; pci_dma_sync_single_for_cpu(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); addr = cas_page_map(page->buffer); memcpy(p, addr + off, i); pci_dma_sync_single_for_device(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); cas_page_unmap(addr); RX_USED_ADD(page, 0x100); p += hlen; swivel = 0; } if (alloclen < (hlen + dlen)) { skb_frag_t *frag = skb_shinfo(skb)->frags; /* normal or jumbo packets. we use frags */ i = CAS_VAL(RX_COMP1_DATA_INDEX, words[0]); page = cp->rx_pages[CAS_VAL(RX_INDEX_RING, i)][CAS_VAL(RX_INDEX_NUM, i)]; off = CAS_VAL(RX_COMP1_DATA_OFF, words[0]) + swivel; hlen = min(cp->page_size - off, dlen); if (hlen < 0) { netif_printk(cp, rx_err, KERN_DEBUG, cp->dev, "rx page overflow: %d\n", hlen); dev_kfree_skb_irq(skb); return -1; } i = hlen; if (i == dlen) /* attach FCS */ i += cp->crc_size; pci_dma_sync_single_for_cpu(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); /* make sure we always copy a header */ swivel = 0; if (p == (char *) skb->data) { /* not split */ addr = cas_page_map(page->buffer); memcpy(p, addr + off, RX_COPY_MIN); pci_dma_sync_single_for_device(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); cas_page_unmap(addr); off += RX_COPY_MIN; swivel = RX_COPY_MIN; RX_USED_ADD(page, cp->mtu_stride); } else { RX_USED_ADD(page, hlen); } skb_put(skb, alloclen); skb_shinfo(skb)->nr_frags++; skb->data_len += hlen - swivel; skb->truesize += hlen - swivel; skb->len += hlen - swivel; __skb_frag_set_page(frag, page->buffer); __skb_frag_ref(frag); frag->page_offset = off; skb_frag_size_set(frag, hlen - swivel); /* any more data? */ if ((words[0] & RX_COMP1_SPLIT_PKT) && ((dlen -= hlen) > 0)) { hlen = dlen; off = 0; i = CAS_VAL(RX_COMP2_NEXT_INDEX, words[1]); page = cp->rx_pages[CAS_VAL(RX_INDEX_RING, i)][CAS_VAL(RX_INDEX_NUM, i)]; pci_dma_sync_single_for_cpu(cp->pdev, page->dma_addr, hlen + cp->crc_size, PCI_DMA_FROMDEVICE); pci_dma_sync_single_for_device(cp->pdev, page->dma_addr, hlen + cp->crc_size, PCI_DMA_FROMDEVICE); skb_shinfo(skb)->nr_frags++; skb->data_len += hlen; skb->len += hlen; frag++; __skb_frag_set_page(frag, page->buffer); __skb_frag_ref(frag); frag->page_offset = 0; skb_frag_size_set(frag, hlen); RX_USED_ADD(page, hlen + cp->crc_size); } if (cp->crc_size) { addr = cas_page_map(page->buffer); crcaddr = addr + off + hlen; } } else { /* copying packet */ if (!dlen) goto end_copy_pkt; i = CAS_VAL(RX_COMP1_DATA_INDEX, words[0]); page = cp->rx_pages[CAS_VAL(RX_INDEX_RING, i)][CAS_VAL(RX_INDEX_NUM, i)]; off = CAS_VAL(RX_COMP1_DATA_OFF, words[0]) + swivel; hlen = min(cp->page_size - off, dlen); if (hlen < 0) { netif_printk(cp, rx_err, KERN_DEBUG, cp->dev, "rx page overflow: %d\n", hlen); dev_kfree_skb_irq(skb); return -1; } i = hlen; if (i == dlen) /* attach FCS */ i += cp->crc_size; pci_dma_sync_single_for_cpu(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); addr = cas_page_map(page->buffer); memcpy(p, addr + off, i); pci_dma_sync_single_for_device(cp->pdev, page->dma_addr + off, i, PCI_DMA_FROMDEVICE); cas_page_unmap(addr); if (p == (char *) skb->data) /* not split */ RX_USED_ADD(page, cp->mtu_stride); else RX_USED_ADD(page, i); /* any more data? */ if ((words[0] & RX_COMP1_SPLIT_PKT) && ((dlen -= hlen) > 0)) { p += hlen; i = CAS_VAL(RX_COMP2_NEXT_INDEX, words[1]); page = cp->rx_pages[CAS_VAL(RX_INDEX_RING, i)][CAS_VAL(RX_INDEX_NUM, i)]; pci_dma_sync_single_for_cpu(cp->pdev, page->dma_addr, dlen + cp->crc_size, PCI_DMA_FROMDEVICE); addr = cas_page_map(page->buffer); memcpy(p, addr, dlen + cp->crc_size); pci_dma_sync_single_for_device(cp->pdev, page->dma_addr, dlen + cp->crc_size, PCI_DMA_FROMDEVICE); cas_page_unmap(addr); RX_USED_ADD(page, dlen + cp->crc_size); } end_copy_pkt: if (cp->crc_size) { addr = NULL; crcaddr = skb->data + alloclen; } skb_put(skb, alloclen); } csum = (__force __sum16)htons(CAS_VAL(RX_COMP4_TCP_CSUM, words[3])); if (cp->crc_size) { /* checksum includes FCS. strip it out. */ csum = csum_fold(csum_partial(crcaddr, cp->crc_size, csum_unfold(csum))); if (addr) cas_page_unmap(addr); } skb->protocol = eth_type_trans(skb, cp->dev); if (skb->protocol == htons(ETH_P_IP)) { skb->csum = csum_unfold(~csum); skb->ip_summed = CHECKSUM_COMPLETE; } else skb_checksum_none_assert(skb); return len; } /* we can handle up to 64 rx flows at a time. we do the same thing * as nonreassm except that we batch up the buffers. * NOTE: we currently just treat each flow as a bunch of packets that * we pass up. a better way would be to coalesce the packets * into a jumbo packet. to do that, we need to do the following: * 1) the first packet will have a clean split between header and * data. save both. * 2) each time the next flow packet comes in, extend the * data length and merge the checksums. * 3) on flow release, fix up the header. * 4) make sure the higher layer doesn't care. * because packets get coalesced, we shouldn't run into fragment count * issues. */ static inline void cas_rx_flow_pkt(struct cas *cp, const u64 *words, struct sk_buff *skb) { int flowid = CAS_VAL(RX_COMP3_FLOWID, words[2]) & (N_RX_FLOWS - 1); struct sk_buff_head *flow = &cp->rx_flows[flowid]; /* this is protected at a higher layer, so no need to * do any additional locking here. stick the buffer * at the end. */ __skb_queue_tail(flow, skb); if (words[0] & RX_COMP1_RELEASE_FLOW) { while ((skb = __skb_dequeue(flow))) { cas_skb_release(skb); } } } /* put rx descriptor back on ring. if a buffer is in use by a higher * layer, this will need to put in a replacement. */ static void cas_post_page(struct cas *cp, const int ring, const int index) { cas_page_t *new; int entry; entry = cp->rx_old[ring]; new = cas_page_swap(cp, ring, index); cp->init_rxds[ring][entry].buffer = cpu_to_le64(new->dma_addr); cp->init_rxds[ring][entry].index = cpu_to_le64(CAS_BASE(RX_INDEX_NUM, index) | CAS_BASE(RX_INDEX_RING, ring)); entry = RX_DESC_ENTRY(ring, entry + 1); cp->rx_old[ring] = entry; if (entry % 4) return; if (ring == 0) writel(entry, cp->regs + REG_RX_KICK); else if ((N_RX_DESC_RINGS > 1) && (cp->cas_flags & CAS_FLAG_REG_PLUS)) writel(entry, cp->regs + REG_PLUS_RX_KICK1); } /* only when things are bad */ static int cas_post_rxds_ringN(struct cas *cp, int ring, int num) { unsigned int entry, last, count, released; int cluster; cas_page_t **page = cp->rx_pages[ring]; entry = cp->rx_old[ring]; netif_printk(cp, intr, KERN_DEBUG, cp->dev, "rxd[%d] interrupt, done: %d\n", ring, entry); cluster = -1; count = entry & 0x3; last = RX_DESC_ENTRY(ring, num ? entry + num - 4: entry - 4); released = 0; while (entry != last) { /* make a new buffer if it's still in use */ if (page_count(page[entry]->buffer) > 1) { cas_page_t *new = cas_page_dequeue(cp); if (!new) { /* let the timer know that we need to * do this again */ cp->cas_flags |= CAS_FLAG_RXD_POST(ring); if (!timer_pending(&cp->link_timer)) mod_timer(&cp->link_timer, jiffies + CAS_LINK_FAST_TIMEOUT); cp->rx_old[ring] = entry; cp->rx_last[ring] = num ? num - released : 0; return -ENOMEM; } spin_lock(&cp->rx_inuse_lock); list_add(&page[entry]->list, &cp->rx_inuse_list); spin_unlock(&cp->rx_inuse_lock); cp->init_rxds[ring][entry].buffer = cpu_to_le64(new->dma_addr); page[entry] = new; } if (++count == 4) { cluster = entry; count = 0; } released++; entry = RX_DESC_ENTRY(ring, entry + 1); } cp->rx_old[ring] = entry; if (cluster < 0) return 0; if (ring == 0) writel(cluster, cp->regs + REG_RX_KICK); else if ((N_RX_DESC_RINGS > 1) && (cp->cas_flags & CAS_FLAG_REG_PLUS)) writel(cluster, cp->regs + REG_PLUS_RX_KICK1); return 0; } /* process a completion ring. packets are set up in three basic ways: * small packets: should be copied header + data in single buffer. * large packets: header and data in a single buffer. * split packets: header in a separate buffer from data. * data may be in multiple pages. data may be > 256 * bytes but in a single page. * * NOTE: RX page posting is done in this routine as well. while there's * the capability of using multiple RX completion rings, it isn't * really worthwhile due to the fact that the page posting will * force serialization on the single descriptor ring. */ static int cas_rx_ringN(struct cas *cp, int ring, int budget) { struct cas_rx_comp *rxcs = cp->init_rxcs[ring]; int entry, drops; int npackets = 0; netif_printk(cp, intr, KERN_DEBUG, cp->dev, "rx[%d] interrupt, done: %d/%d\n", ring, readl(cp->regs + REG_RX_COMP_HEAD), cp->rx_new[ring]); entry = cp->rx_new[ring]; drops = 0; while (1) { struct cas_rx_comp *rxc = rxcs + entry; struct sk_buff *uninitialized_var(skb); int type, len; u64 words[4]; int i, dring; words[0] = le64_to_cpu(rxc->word1); words[1] = le64_to_cpu(rxc->word2); words[2] = le64_to_cpu(rxc->word3); words[3] = le64_to_cpu(rxc->word4); /* don't touch if still owned by hw */ type = CAS_VAL(RX_COMP1_TYPE, words[0]); if (type == 0) break; /* hw hasn't cleared the zero bit yet */ if (words[3] & RX_COMP4_ZERO) { break; } /* get info on the packet */ if (words[3] & (RX_COMP4_LEN_MISMATCH | RX_COMP4_BAD)) { spin_lock(&cp->stat_lock[ring]); cp->net_stats[ring].rx_errors++; if (words[3] & RX_COMP4_LEN_MISMATCH) cp->net_stats[ring].rx_length_errors++; if (words[3] & RX_COMP4_BAD) cp->net_stats[ring].rx_crc_errors++; spin_unlock(&cp->stat_lock[ring]); /* We'll just return it to Cassini. */ drop_it: spin_lock(&cp->stat_lock[ring]); ++cp->net_stats[ring].rx_dropped; spin_unlock(&cp->stat_lock[ring]); goto next; } len = cas_rx_process_pkt(cp, rxc, entry, words, &skb); if (len < 0) { ++drops; goto drop_it; } /* see if it's a flow re-assembly or not. the driver * itself handles release back up. */ if (RX_DONT_BATCH || (type == 0x2)) { /* non-reassm: these always get released */ cas_skb_release(skb); } else { cas_rx_flow_pkt(cp, words, skb); } spin_lock(&cp->stat_lock[ring]); cp->net_stats[ring].rx_packets++; cp->net_stats[ring].rx_bytes += len; spin_unlock(&cp->stat_lock[ring]); next: npackets++; /* should it be released? */ if (words[0] & RX_COMP1_RELEASE_HDR) { i = CAS_VAL(RX_COMP2_HDR_INDEX, words[1]); dring = CAS_VAL(RX_INDEX_RING, i); i = CAS_VAL(RX_INDEX_NUM, i); cas_post_page(cp, dring, i); } if (words[0] & RX_COMP1_RELEASE_DATA) { i = CAS_VAL(RX_COMP1_DATA_INDEX, words[0]); dring = CAS_VAL(RX_INDEX_RING, i); i = CAS_VAL(RX_INDEX_NUM, i); cas_post_page(cp, dring, i); } if (words[0] & RX_COMP1_RELEASE_NEXT) { i = CAS_VAL(RX_COMP2_NEXT_INDEX, words[1]); dring = CAS_VAL(RX_INDEX_RING, i); i = CAS_VAL(RX_INDEX_NUM, i); cas_post_page(cp, dring, i); } /* skip to the next entry */ entry = RX_COMP_ENTRY(ring, entry + 1 + CAS_VAL(RX_COMP1_SKIP, words[0])); #ifdef USE_NAPI if (budget && (npackets >= budget)) break; #endif } cp->rx_new[ring] = entry; if (drops) netdev_info(cp->dev, "Memory squeeze, deferring packet\n"); return npackets; } /* put completion entries back on the ring */ static void cas_post_rxcs_ringN(struct net_device *dev, struct cas *cp, int ring) { struct cas_rx_comp *rxc = cp->init_rxcs[ring]; int last, entry; last = cp->rx_cur[ring]; entry = cp->rx_new[ring]; netif_printk(cp, intr, KERN_DEBUG, dev, "rxc[%d] interrupt, done: %d/%d\n", ring, readl(cp->regs + REG_RX_COMP_HEAD), entry); /* zero and re-mark descriptors */ while (last != entry) { cas_rxc_init(rxc + last); last = RX_COMP_ENTRY(ring, last + 1); } cp->rx_cur[ring] = last; if (ring == 0) writel(last, cp->regs + REG_RX_COMP_TAIL); else if (cp->cas_flags & CAS_FLAG_REG_PLUS) writel(last, cp->regs + REG_PLUS_RX_COMPN_TAIL(ring)); } /* cassini can use all four PCI interrupts for the completion ring. * rings 3 and 4 are identical */ #if defined(USE_PCI_INTC) || defined(USE_PCI_INTD) static inline void cas_handle_irqN(struct net_device *dev, struct cas *cp, const u32 status, const int ring) { if (status & (INTR_RX_COMP_FULL_ALT | INTR_RX_COMP_AF_ALT)) cas_post_rxcs_ringN(dev, cp, ring); } static irqreturn_t cas_interruptN(int irq, void *dev_id) { struct net_device *dev = dev_id; struct cas *cp = netdev_priv(dev); unsigned long flags; int ring = (irq == cp->pci_irq_INTC) ? 2 : 3; u32 status = readl(cp->regs + REG_PLUS_INTRN_STATUS(ring)); /* check for shared irq */ if (status == 0) return IRQ_NONE; spin_lock_irqsave(&cp->lock, flags); if (status & INTR_RX_DONE_ALT) { /* handle rx separately */ #ifdef USE_NAPI cas_mask_intr(cp); napi_schedule(&cp->napi); #else cas_rx_ringN(cp, ring, 0); #endif status &= ~INTR_RX_DONE_ALT; } if (status) cas_handle_irqN(dev, cp, status, ring); spin_unlock_irqrestore(&cp->lock, flags); return IRQ_HANDLED; } #endif #ifdef USE_PCI_INTB /* everything but rx packets */ static inline void cas_handle_irq1(struct cas *cp, const u32 status) { if (status & INTR_RX_BUF_UNAVAIL_1) { /* Frame arrived, no free RX buffers available. * NOTE: we can get this on a link transition. */ cas_post_rxds_ringN(cp, 1, 0); spin_lock(&cp->stat_lock[1]); cp->net_stats[1].rx_dropped++; spin_unlock(&cp->stat_lock[1]); } if (status & INTR_RX_BUF_AE_1) cas_post_rxds_ringN(cp, 1, RX_DESC_RINGN_SIZE(1) - RX_AE_FREEN_VAL(1)); if (status & (INTR_RX_COMP_AF | INTR_RX_COMP_FULL)) cas_post_rxcs_ringN(cp, 1); } /* ring 2 handles a few more events than 3 and 4 */ static irqreturn_t cas_interrupt1(int irq, void *dev_id) { struct net_device *dev = dev_id; struct cas *cp = netdev_priv(dev); unsigned long flags; u32 status = readl(cp->regs + REG_PLUS_INTRN_STATUS(1)); /* check for shared interrupt */ if (status == 0) return IRQ_NONE; spin_lock_irqsave(&cp->lock, flags); if (status & INTR_RX_DONE_ALT) { /* handle rx separately */ #ifdef USE_NAPI cas_mask_intr(cp); napi_schedule(&cp->napi); #else cas_rx_ringN(cp, 1, 0); #endif status &= ~INTR_RX_DONE_ALT; } if (status) cas_handle_irq1(cp, status); spin_unlock_irqrestore(&cp->lock, flags); return IRQ_HANDLED; } #endif static inline void cas_handle_irq(struct net_device *dev, struct cas *cp, const u32 status) { /* housekeeping interrupts */ if (status & INTR_ERROR_MASK) cas_abnormal_irq(dev, cp, status); if (status & INTR_RX_BUF_UNAVAIL) { /* Frame arrived, no free RX buffers available. * NOTE: we can get this on a link transition. */ cas_post_rxds_ringN(cp, 0, 0); spin_lock(&cp->stat_lock[0]); cp->net_stats[0].rx_dropped++; spin_unlock(&cp->stat_lock[0]); } else if (status & INTR_RX_BUF_AE) { cas_post_rxds_ringN(cp, 0, RX_DESC_RINGN_SIZE(0) - RX_AE_FREEN_VAL(0)); } if (status & (INTR_RX_COMP_AF | INTR_RX_COMP_FULL)) cas_post_rxcs_ringN(dev, cp, 0); } static irqreturn_t cas_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; struct cas *cp = netdev_priv(dev); unsigned long flags; u32 status = readl(cp->regs + REG_INTR_STATUS); if (status == 0) return IRQ_NONE; spin_lock_irqsave(&cp->lock, flags); if (status & (INTR_TX_ALL | INTR_TX_INTME)) { cas_tx(dev, cp, status); status &= ~(INTR_TX_ALL | INTR_TX_INTME); } if (status & INTR_RX_DONE) { #ifdef USE_NAPI cas_mask_intr(cp); napi_schedule(&cp->napi); #else cas_rx_ringN(cp, 0, 0); #endif status &= ~INTR_RX_DONE; } if (status) cas_handle_irq(dev, cp, status); spin_unlock_irqrestore(&cp->lock, flags); return IRQ_HANDLED; } #ifdef USE_NAPI static int cas_poll(struct napi_struct *napi, int budget) { struct cas *cp = container_of(napi, struct cas, napi); struct net_device *dev = cp->dev; int i, enable_intr, credits; u32 status = readl(cp->regs + REG_INTR_STATUS); unsigned long flags; spin_lock_irqsave(&cp->lock, flags); cas_tx(dev, cp, status); spin_unlock_irqrestore(&cp->lock, flags); /* NAPI rx packets. we spread the credits across all of the * rxc rings * * to make sure we're fair with the work we loop through each * ring N_RX_COMP_RING times with a request of * budget / N_RX_COMP_RINGS */ enable_intr = 1; credits = 0; for (i = 0; i < N_RX_COMP_RINGS; i++) { int j; for (j = 0; j < N_RX_COMP_RINGS; j++) { credits += cas_rx_ringN(cp, j, budget / N_RX_COMP_RINGS); if (credits >= budget) { enable_intr = 0; goto rx_comp; } } } rx_comp: /* final rx completion */ spin_lock_irqsave(&cp->lock, flags); if (status) cas_handle_irq(dev, cp, status); #ifdef USE_PCI_INTB if (N_RX_COMP_RINGS > 1) { status = readl(cp->regs + REG_PLUS_INTRN_STATUS(1)); if (status) cas_handle_irq1(dev, cp, status); } #endif #ifdef USE_PCI_INTC if (N_RX_COMP_RINGS > 2) { status = readl(cp->regs + REG_PLUS_INTRN_STATUS(2)); if (status) cas_handle_irqN(dev, cp, status, 2); } #endif #ifdef USE_PCI_INTD if (N_RX_COMP_RINGS > 3) { status = readl(cp->regs + REG_PLUS_INTRN_STATUS(3)); if (status) cas_handle_irqN(dev, cp, status, 3); } #endif spin_unlock_irqrestore(&cp->lock, flags); if (enable_intr) { napi_complete(napi); cas_unmask_intr(cp); } return credits; } #endif #ifdef CONFIG_NET_POLL_CONTROLLER static void cas_netpoll(struct net_device *dev) { struct cas *cp = netdev_priv(dev); cas_disable_irq(cp, 0); cas_interrupt(cp->pdev->irq, dev); cas_enable_irq(cp, 0); #ifdef USE_PCI_INTB if (N_RX_COMP_RINGS > 1) { /* cas_interrupt1(); */ } #endif #ifdef USE_PCI_INTC if (N_RX_COMP_RINGS > 2) { /* cas_interruptN(); */ } #endif #ifdef USE_PCI_INTD if (N_RX_COMP_RINGS > 3) { /* cas_interruptN(); */ } #endif } #endif static void cas_tx_timeout(struct net_device *dev) { struct cas *cp = netdev_priv(dev); netdev_err(dev, "transmit timed out, resetting\n"); if (!cp->hw_running) { netdev_err(dev, "hrm.. hw not running!\n"); return; } netdev_err(dev, "MIF_STATE[%08x]\n", readl(cp->regs + REG_MIF_STATE_MACHINE)); netdev_err(dev, "MAC_STATE[%08x]\n", readl(cp->regs + REG_MAC_STATE_MACHINE)); netdev_err(dev, "TX_STATE[%08x:%08x:%08x] FIFO[%08x:%08x:%08x] SM1[%08x] SM2[%08x]\n", readl(cp->regs + REG_TX_CFG), readl(cp->regs + REG_MAC_TX_STATUS), readl(cp->regs + REG_MAC_TX_CFG), readl(cp->regs + REG_TX_FIFO_PKT_CNT), readl(cp->regs + REG_TX_FIFO_WRITE_PTR), readl(cp->regs + REG_TX_FIFO_READ_PTR), readl(cp->regs + REG_TX_SM_1), readl(cp->regs + REG_TX_SM_2)); netdev_err(dev, "RX_STATE[%08x:%08x:%08x]\n", readl(cp->regs + REG_RX_CFG), readl(cp->regs + REG_MAC_RX_STATUS), readl(cp->regs + REG_MAC_RX_CFG)); netdev_err(dev, "HP_STATE[%08x:%08x:%08x:%08x]\n", readl(cp->regs + REG_HP_STATE_MACHINE), readl(cp->regs + REG_HP_STATUS0), readl(cp->regs + REG_HP_STATUS1), readl(cp->regs + REG_HP_STATUS2)); #if 1 atomic_inc(&cp->reset_task_pending); atomic_inc(&cp->reset_task_pending_all); schedule_work(&cp->reset_task); #else atomic_set(&cp->reset_task_pending, CAS_RESET_ALL); schedule_work(&cp->reset_task); #endif } static inline int cas_intme(int ring, int entry) { /* Algorithm: IRQ every 1/2 of descriptors. */ if (!(entry & ((TX_DESC_RINGN_SIZE(ring) >> 1) - 1))) return 1; return 0; } static void cas_write_txd(struct cas *cp, int ring, int entry, dma_addr_t mapping, int len, u64 ctrl, int last) { struct cas_tx_desc *txd = cp->init_txds[ring] + entry; ctrl |= CAS_BASE(TX_DESC_BUFLEN, len); if (cas_intme(ring, entry)) ctrl |= TX_DESC_INTME; if (last) ctrl |= TX_DESC_EOF; txd->control = cpu_to_le64(ctrl); txd->buffer = cpu_to_le64(mapping); } static inline void *tx_tiny_buf(struct cas *cp, const int ring, const int entry) { return cp->tx_tiny_bufs[ring] + TX_TINY_BUF_LEN*entry; } static inline dma_addr_t tx_tiny_map(struct cas *cp, const int ring, const int entry, const int tentry) { cp->tx_tiny_use[ring][tentry].nbufs++; cp->tx_tiny_use[ring][entry].used = 1; return cp->tx_tiny_dvma[ring] + TX_TINY_BUF_LEN*entry; } static inline int cas_xmit_tx_ringN(struct cas *cp, int ring, struct sk_buff *skb) { struct net_device *dev = cp->dev; int entry, nr_frags, frag, tabort, tentry; dma_addr_t mapping; unsigned long flags; u64 ctrl; u32 len; spin_lock_irqsave(&cp->tx_lock[ring], flags); /* This is a hard error, log it. */ if (TX_BUFFS_AVAIL(cp, ring) <= CAS_TABORT(cp)*(skb_shinfo(skb)->nr_frags + 1)) { netif_stop_queue(dev); spin_unlock_irqrestore(&cp->tx_lock[ring], flags); netdev_err(dev, "BUG! Tx Ring full when queue awake!\n"); return 1; } ctrl = 0; if (skb->ip_summed == CHECKSUM_PARTIAL) { const u64 csum_start_off = skb_checksum_start_offset(skb); const u64 csum_stuff_off = csum_start_off + skb->csum_offset; ctrl = TX_DESC_CSUM_EN | CAS_BASE(TX_DESC_CSUM_START, csum_start_off) | CAS_BASE(TX_DESC_CSUM_STUFF, csum_stuff_off); } entry = cp->tx_new[ring]; cp->tx_skbs[ring][entry] = skb; nr_frags = skb_shinfo(skb)->nr_frags; len = skb_headlen(skb); mapping = pci_map_page(cp->pdev, virt_to_page(skb->data), offset_in_page(skb->data), len, PCI_DMA_TODEVICE); tentry = entry; tabort = cas_calc_tabort(cp, (unsigned long) skb->data, len); if (unlikely(tabort)) { /* NOTE: len is always > tabort */ cas_write_txd(cp, ring, entry, mapping, len - tabort, ctrl | TX_DESC_SOF, 0); entry = TX_DESC_NEXT(ring, entry); skb_copy_from_linear_data_offset(skb, len - tabort, tx_tiny_buf(cp, ring, entry), tabort); mapping = tx_tiny_map(cp, ring, entry, tentry); cas_write_txd(cp, ring, entry, mapping, tabort, ctrl, (nr_frags == 0)); } else { cas_write_txd(cp, ring, entry, mapping, len, ctrl | TX_DESC_SOF, (nr_frags == 0)); } entry = TX_DESC_NEXT(ring, entry); for (frag = 0; frag < nr_frags; frag++) { const skb_frag_t *fragp = &skb_shinfo(skb)->frags[frag]; len = skb_frag_size(fragp); mapping = skb_frag_dma_map(&cp->pdev->dev, fragp, 0, len, DMA_TO_DEVICE); tabort = cas_calc_tabort(cp, fragp->page_offset, len); if (unlikely(tabort)) { void *addr; /* NOTE: len is always > tabort */ cas_write_txd(cp, ring, entry, mapping, len - tabort, ctrl, 0); entry = TX_DESC_NEXT(ring, entry); addr = cas_page_map(skb_frag_page(fragp)); memcpy(tx_tiny_buf(cp, ring, entry), addr + fragp->page_offset + len - tabort, tabort); cas_page_unmap(addr); mapping = tx_tiny_map(cp, ring, entry, tentry); len = tabort; } cas_write_txd(cp, ring, entry, mapping, len, ctrl, (frag + 1 == nr_frags)); entry = TX_DESC_NEXT(ring, entry); } cp->tx_new[ring] = entry; if (TX_BUFFS_AVAIL(cp, ring) <= CAS_TABORT(cp)*(MAX_SKB_FRAGS + 1)) netif_stop_queue(dev); netif_printk(cp, tx_queued, KERN_DEBUG, dev, "tx[%d] queued, slot %d, skblen %d, avail %d\n", ring, entry, skb->len, TX_BUFFS_AVAIL(cp, ring)); writel(entry, cp->regs + REG_TX_KICKN(ring)); spin_unlock_irqrestore(&cp->tx_lock[ring], flags); return 0; } static netdev_tx_t cas_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct cas *cp = netdev_priv(dev); /* this is only used as a load-balancing hint, so it doesn't * need to be SMP safe */ static int ring; if (skb_padto(skb, cp->min_frame_size)) return NETDEV_TX_OK; /* XXX: we need some higher-level QoS hooks to steer packets to * individual queues. */ if (cas_xmit_tx_ringN(cp, ring++ & N_TX_RINGS_MASK, skb)) return NETDEV_TX_BUSY; return NETDEV_TX_OK; } static void cas_init_tx_dma(struct cas *cp) { u64 desc_dma = cp->block_dvma; unsigned long off; u32 val; int i; /* set up tx completion writeback registers. must be 8-byte aligned */ #ifdef USE_TX_COMPWB off = offsetof(struct cas_init_block, tx_compwb); writel((desc_dma + off) >> 32, cp->regs + REG_TX_COMPWB_DB_HI); writel((desc_dma + off) & 0xffffffff, cp->regs + REG_TX_COMPWB_DB_LOW); #endif /* enable completion writebacks, enable paced mode, * disable read pipe, and disable pre-interrupt compwbs */ val = TX_CFG_COMPWB_Q1 | TX_CFG_COMPWB_Q2 | TX_CFG_COMPWB_Q3 | TX_CFG_COMPWB_Q4 | TX_CFG_DMA_RDPIPE_DIS | TX_CFG_PACED_MODE | TX_CFG_INTR_COMPWB_DIS; /* write out tx ring info and tx desc bases */ for (i = 0; i < MAX_TX_RINGS; i++) { off = (unsigned long) cp->init_txds[i] - (unsigned long) cp->init_block; val |= CAS_TX_RINGN_BASE(i); writel((desc_dma + off) >> 32, cp->regs + REG_TX_DBN_HI(i)); writel((desc_dma + off) & 0xffffffff, cp->regs + REG_TX_DBN_LOW(i)); /* don't zero out the kick register here as the system * will wedge */ } writel(val, cp->regs + REG_TX_CFG); /* program max burst sizes. these numbers should be different * if doing QoS. */ #ifdef USE_QOS writel(0x800, cp->regs + REG_TX_MAXBURST_0); writel(0x1600, cp->regs + REG_TX_MAXBURST_1); writel(0x2400, cp->regs + REG_TX_MAXBURST_2); writel(0x4800, cp->regs + REG_TX_MAXBURST_3); #else writel(0x800, cp->regs + REG_TX_MAXBURST_0); writel(0x800, cp->regs + REG_TX_MAXBURST_1); writel(0x800, cp->regs + REG_TX_MAXBURST_2); writel(0x800, cp->regs + REG_TX_MAXBURST_3); #endif } /* Must be invoked under cp->lock. */ static inline void cas_init_dma(struct cas *cp) { cas_init_tx_dma(cp); cas_init_rx_dma(cp); } static void cas_process_mc_list(struct cas *cp) { u16 hash_table[16]; u32 crc; struct netdev_hw_addr *ha; int i = 1; memset(hash_table, 0, sizeof(hash_table)); netdev_for_each_mc_addr(ha, cp->dev) { if (i <= CAS_MC_EXACT_MATCH_SIZE) { /* use the alternate mac address registers for the * first 15 multicast addresses */ writel((ha->addr[4] << 8) | ha->addr[5], cp->regs + REG_MAC_ADDRN(i*3 + 0)); writel((ha->addr[2] << 8) | ha->addr[3], cp->regs + REG_MAC_ADDRN(i*3 + 1)); writel((ha->addr[0] << 8) | ha->addr[1], cp->regs + REG_MAC_ADDRN(i*3 + 2)); i++; } else { /* use hw hash table for the next series of * multicast addresses */ crc = ether_crc_le(ETH_ALEN, ha->addr); crc >>= 24; hash_table[crc >> 4] |= 1 << (15 - (crc & 0xf)); } } for (i = 0; i < 16; i++) writel(hash_table[i], cp->regs + REG_MAC_HASH_TABLEN(i)); } /* Must be invoked under cp->lock. */ static u32 cas_setup_multicast(struct cas *cp) { u32 rxcfg = 0; int i; if (cp->dev->flags & IFF_PROMISC) { rxcfg |= MAC_RX_CFG_PROMISC_EN; } else if (cp->dev->flags & IFF_ALLMULTI) { for (i=0; i < 16; i++) writel(0xFFFF, cp->regs + REG_MAC_HASH_TABLEN(i)); rxcfg |= MAC_RX_CFG_HASH_FILTER_EN; } else { cas_process_mc_list(cp); rxcfg |= MAC_RX_CFG_HASH_FILTER_EN; } return rxcfg; } /* must be invoked under cp->stat_lock[N_TX_RINGS] */ static void cas_clear_mac_err(struct cas *cp) { writel(0, cp->regs + REG_MAC_COLL_NORMAL); writel(0, cp->regs + REG_MAC_COLL_FIRST); writel(0, cp->regs + REG_MAC_COLL_EXCESS); writel(0, cp->regs + REG_MAC_COLL_LATE); writel(0, cp->regs + REG_MAC_TIMER_DEFER); writel(0, cp->regs + REG_MAC_ATTEMPTS_PEAK); writel(0, cp->regs + REG_MAC_RECV_FRAME); writel(0, cp->regs + REG_MAC_LEN_ERR); writel(0, cp->regs + REG_MAC_ALIGN_ERR); writel(0, cp->regs + REG_MAC_FCS_ERR); writel(0, cp->regs + REG_MAC_RX_CODE_ERR); } static void cas_mac_reset(struct cas *cp) { int i; /* do both TX and RX reset */ writel(0x1, cp->regs + REG_MAC_TX_RESET); writel(0x1, cp->regs + REG_MAC_RX_RESET); /* wait for TX */ i = STOP_TRIES; while (i-- > 0) { if (readl(cp->regs + REG_MAC_TX_RESET) == 0) break; udelay(10); } /* wait for RX */ i = STOP_TRIES; while (i-- > 0) { if (readl(cp->regs + REG_MAC_RX_RESET) == 0) break; udelay(10); } if (readl(cp->regs + REG_MAC_TX_RESET) | readl(cp->regs + REG_MAC_RX_RESET)) netdev_err(cp->dev, "mac tx[%d]/rx[%d] reset failed [%08x]\n", readl(cp->regs + REG_MAC_TX_RESET), readl(cp->regs + REG_MAC_RX_RESET), readl(cp->regs + REG_MAC_STATE_MACHINE)); } /* Must be invoked under cp->lock. */ static void cas_init_mac(struct cas *cp) { unsigned char *e = &cp->dev->dev_addr[0]; int i; cas_mac_reset(cp); /* setup core arbitration weight register */ writel(CAWR_RR_DIS, cp->regs + REG_CAWR); /* XXX Use pci_dma_burst_advice() */ #if !defined(CONFIG_SPARC64) && !defined(CONFIG_ALPHA) /* set the infinite burst register for chips that don't have * pci issues. */ if ((cp->cas_flags & CAS_FLAG_TARGET_ABORT) == 0) writel(INF_BURST_EN, cp->regs + REG_INF_BURST); #endif writel(0x1BF0, cp->regs + REG_MAC_SEND_PAUSE); writel(0x00, cp->regs + REG_MAC_IPG0); writel(0x08, cp->regs + REG_MAC_IPG1); writel(0x04, cp->regs + REG_MAC_IPG2); /* change later for 802.3z */ writel(0x40, cp->regs + REG_MAC_SLOT_TIME); /* min frame + FCS */ writel(ETH_ZLEN + 4, cp->regs + REG_MAC_FRAMESIZE_MIN); /* Ethernet payload + header + FCS + optional VLAN tag. NOTE: we * specify the maximum frame size to prevent RX tag errors on * oversized frames. */ writel(CAS_BASE(MAC_FRAMESIZE_MAX_BURST, 0x2000) | CAS_BASE(MAC_FRAMESIZE_MAX_FRAME, (CAS_MAX_MTU + ETH_HLEN + 4 + 4)), cp->regs + REG_MAC_FRAMESIZE_MAX); /* NOTE: crc_size is used as a surrogate for half-duplex. * workaround saturn half-duplex issue by increasing preamble * size to 65 bytes. */ if ((cp->cas_flags & CAS_FLAG_SATURN) && cp->crc_size) writel(0x41, cp->regs + REG_MAC_PA_SIZE); else writel(0x07, cp->regs + REG_MAC_PA_SIZE); writel(0x04, cp->regs + REG_MAC_JAM_SIZE); writel(0x10, cp->regs + REG_MAC_ATTEMPT_LIMIT); writel(0x8808, cp->regs + REG_MAC_CTRL_TYPE); writel((e[5] | (e[4] << 8)) & 0x3ff, cp->regs + REG_MAC_RANDOM_SEED); writel(0, cp->regs + REG_MAC_ADDR_FILTER0); writel(0, cp->regs + REG_MAC_ADDR_FILTER1); writel(0, cp->regs + REG_MAC_ADDR_FILTER2); writel(0, cp->regs + REG_MAC_ADDR_FILTER2_1_MASK); writel(0, cp->regs + REG_MAC_ADDR_FILTER0_MASK); /* setup mac address in perfect filter array */ for (i = 0; i < 45; i++) writel(0x0, cp->regs + REG_MAC_ADDRN(i)); writel((e[4] << 8) | e[5], cp->regs + REG_MAC_ADDRN(0)); writel((e[2] << 8) | e[3], cp->regs + REG_MAC_ADDRN(1)); writel((e[0] << 8) | e[1], cp->regs + REG_MAC_ADDRN(2)); writel(0x0001, cp->regs + REG_MAC_ADDRN(42)); writel(0xc200, cp->regs + REG_MAC_ADDRN(43)); writel(0x0180, cp->regs + REG_MAC_ADDRN(44)); cp->mac_rx_cfg = cas_setup_multicast(cp); spin_lock(&cp->stat_lock[N_TX_RINGS]); cas_clear_mac_err(cp); spin_unlock(&cp->stat_lock[N_TX_RINGS]); /* Setup MAC interrupts. We want to get all of the interesting * counter expiration events, but we do not want to hear about * normal rx/tx as the DMA engine tells us that. */ writel(MAC_TX_FRAME_XMIT, cp->regs + REG_MAC_TX_MASK); writel(MAC_RX_FRAME_RECV, cp->regs + REG_MAC_RX_MASK); /* Don't enable even the PAUSE interrupts for now, we * make no use of those events other than to record them. */ writel(0xffffffff, cp->regs + REG_MAC_CTRL_MASK); } /* Must be invoked under cp->lock. */ static void cas_init_pause_thresholds(struct cas *cp) { /* Calculate pause thresholds. Setting the OFF threshold to the * full RX fifo size effectively disables PAUSE generation */ if (cp->rx_fifo_size <= (2 * 1024)) { cp->rx_pause_off = cp->rx_pause_on = cp->rx_fifo_size; } else { int max_frame = (cp->dev->mtu + ETH_HLEN + 4 + 4 + 64) & ~63; if (max_frame * 3 > cp->rx_fifo_size) { cp->rx_pause_off = 7104; cp->rx_pause_on = 960; } else { int off = (cp->rx_fifo_size - (max_frame * 2)); int on = off - max_frame; cp->rx_pause_off = off; cp->rx_pause_on = on; } } } static int cas_vpd_match(const void __iomem *p, const char *str) { int len = strlen(str) + 1; int i; for (i = 0; i < len; i++) { if (readb(p + i) != str[i]) return 0; } return 1; } /* get the mac address by reading the vpd information in the rom. * also get the phy type and determine if there's an entropy generator. * NOTE: this is a bit convoluted for the following reasons: * 1) vpd info has order-dependent mac addresses for multinic cards * 2) the only way to determine the nic order is to use the slot * number. * 3) fiber cards don't have bridges, so their slot numbers don't * mean anything. * 4) we don't actually know we have a fiber card until after * the mac addresses are parsed. */ static int cas_get_vpd_info(struct cas *cp, unsigned char *dev_addr, const int offset) { void __iomem *p = cp->regs + REG_EXPANSION_ROM_RUN_START; void __iomem *base, *kstart; int i, len; int found = 0; #define VPD_FOUND_MAC 0x01 #define VPD_FOUND_PHY 0x02 int phy_type = CAS_PHY_MII_MDIO0; /* default phy type */ int mac_off = 0; #if defined(CONFIG_SPARC) const unsigned char *addr; #endif /* give us access to the PROM */ writel(BIM_LOCAL_DEV_PROM | BIM_LOCAL_DEV_PAD, cp->regs + REG_BIM_LOCAL_DEV_EN); /* check for an expansion rom */ if (readb(p) != 0x55 || readb(p + 1) != 0xaa) goto use_random_mac_addr; /* search for beginning of vpd */ base = NULL; for (i = 2; i < EXPANSION_ROM_SIZE; i++) { /* check for PCIR */ if ((readb(p + i + 0) == 0x50) && (readb(p + i + 1) == 0x43) && (readb(p + i + 2) == 0x49) && (readb(p + i + 3) == 0x52)) { base = p + (readb(p + i + 8) | (readb(p + i + 9) << 8)); break; } } if (!base || (readb(base) != 0x82)) goto use_random_mac_addr; i = (readb(base + 1) | (readb(base + 2) << 8)) + 3; while (i < EXPANSION_ROM_SIZE) { if (readb(base + i) != 0x90) /* no vpd found */ goto use_random_mac_addr; /* found a vpd field */ len = readb(base + i + 1) | (readb(base + i + 2) << 8); /* extract keywords */ kstart = base + i + 3; p = kstart; while ((p - kstart) < len) { int klen = readb(p + 2); int j; char type; p += 3; /* look for the following things: * -- correct length == 29 * 3 (type) + 2 (size) + * 18 (strlen("local-mac-address") + 1) + * 6 (mac addr) * -- VPD Instance 'I' * -- VPD Type Bytes 'B' * -- VPD data length == 6 * -- property string == local-mac-address * * -- correct length == 24 * 3 (type) + 2 (size) + * 12 (strlen("entropy-dev") + 1) + * 7 (strlen("vms110") + 1) * -- VPD Instance 'I' * -- VPD Type String 'B' * -- VPD data length == 7 * -- property string == entropy-dev * * -- correct length == 18 * 3 (type) + 2 (size) + * 9 (strlen("phy-type") + 1) + * 4 (strlen("pcs") + 1) * -- VPD Instance 'I' * -- VPD Type String 'S' * -- VPD data length == 4 * -- property string == phy-type * * -- correct length == 23 * 3 (type) + 2 (size) + * 14 (strlen("phy-interface") + 1) + * 4 (strlen("pcs") + 1) * -- VPD Instance 'I' * -- VPD Type String 'S' * -- VPD data length == 4 * -- property string == phy-interface */ if (readb(p) != 'I') goto next; /* finally, check string and length */ type = readb(p + 3); if (type == 'B') { if ((klen == 29) && readb(p + 4) == 6 && cas_vpd_match(p + 5, "local-mac-address")) { if (mac_off++ > offset) goto next; /* set mac address */ for (j = 0; j < 6; j++) dev_addr[j] = readb(p + 23 + j); goto found_mac; } } if (type != 'S') goto next; #ifdef USE_ENTROPY_DEV if ((klen == 24) && cas_vpd_match(p + 5, "entropy-dev") && cas_vpd_match(p + 17, "vms110")) { cp->cas_flags |= CAS_FLAG_ENTROPY_DEV; goto next; } #endif if (found & VPD_FOUND_PHY) goto next; if ((klen == 18) && readb(p + 4) == 4 && cas_vpd_match(p + 5, "phy-type")) { if (cas_vpd_match(p + 14, "pcs")) { phy_type = CAS_PHY_SERDES; goto found_phy; } } if ((klen == 23) && readb(p + 4) == 4 && cas_vpd_match(p + 5, "phy-interface")) { if (cas_vpd_match(p + 19, "pcs")) { phy_type = CAS_PHY_SERDES; goto found_phy; } } found_mac: found |= VPD_FOUND_MAC; goto next; found_phy: found |= VPD_FOUND_PHY; next: p += klen; } i += len + 3; } use_random_mac_addr: if (found & VPD_FOUND_MAC) goto done; #if defined(CONFIG_SPARC) addr = of_get_property(cp->of_node, "local-mac-address", NULL); if (addr != NULL) { memcpy(dev_addr, addr, ETH_ALEN); goto done; } #endif /* Sun MAC prefix then 3 random bytes. */ pr_info("MAC address not found in ROM VPD\n"); dev_addr[0] = 0x08; dev_addr[1] = 0x00; dev_addr[2] = 0x20; get_random_bytes(dev_addr + 3, 3); done: writel(0, cp->regs + REG_BIM_LOCAL_DEV_EN); return phy_type; } /* check pci invariants */ static void cas_check_pci_invariants(struct cas *cp) { struct pci_dev *pdev = cp->pdev; cp->cas_flags = 0; if ((pdev->vendor == PCI_VENDOR_ID_SUN) && (pdev->device == PCI_DEVICE_ID_SUN_CASSINI)) { if (pdev->revision >= CAS_ID_REVPLUS) cp->cas_flags |= CAS_FLAG_REG_PLUS; if (pdev->revision < CAS_ID_REVPLUS02u) cp->cas_flags |= CAS_FLAG_TARGET_ABORT; /* Original Cassini supports HW CSUM, but it's not * enabled by default as it can trigger TX hangs. */ if (pdev->revision < CAS_ID_REV2) cp->cas_flags |= CAS_FLAG_NO_HW_CSUM; } else { /* Only sun has original cassini chips. */ cp->cas_flags |= CAS_FLAG_REG_PLUS; /* We use a flag because the same phy might be externally * connected. */ if ((pdev->vendor == PCI_VENDOR_ID_NS) && (pdev->device == PCI_DEVICE_ID_NS_SATURN)) cp->cas_flags |= CAS_FLAG_SATURN; } } static int cas_check_invariants(struct cas *cp) { struct pci_dev *pdev = cp->pdev; u32 cfg; int i; /* get page size for rx buffers. */ cp->page_order = 0; #ifdef USE_PAGE_ORDER if (PAGE_SHIFT < CAS_JUMBO_PAGE_SHIFT) { /* see if we can allocate larger pages */ struct page *page = alloc_pages(GFP_ATOMIC, CAS_JUMBO_PAGE_SHIFT - PAGE_SHIFT); if (page) { __free_pages(page, CAS_JUMBO_PAGE_SHIFT - PAGE_SHIFT); cp->page_order = CAS_JUMBO_PAGE_SHIFT - PAGE_SHIFT; } else { printk("MTU limited to %d bytes\n", CAS_MAX_MTU); } } #endif cp->page_size = (PAGE_SIZE << cp->page_order); /* Fetch the FIFO configurations. */ cp->tx_fifo_size = readl(cp->regs + REG_TX_FIFO_SIZE) * 64; cp->rx_fifo_size = RX_FIFO_SIZE; /* finish phy determination. MDIO1 takes precedence over MDIO0 if * they're both connected. */ cp->phy_type = cas_get_vpd_info(cp, cp->dev->dev_addr, PCI_SLOT(pdev->devfn)); if (cp->phy_type & CAS_PHY_SERDES) { cp->cas_flags |= CAS_FLAG_1000MB_CAP; return 0; /* no more checking needed */ } /* MII */ cfg = readl(cp->regs + REG_MIF_CFG); if (cfg & MIF_CFG_MDIO_1) { cp->phy_type = CAS_PHY_MII_MDIO1; } else if (cfg & MIF_CFG_MDIO_0) { cp->phy_type = CAS_PHY_MII_MDIO0; } cas_mif_poll(cp, 0); writel(PCS_DATAPATH_MODE_MII, cp->regs + REG_PCS_DATAPATH_MODE); for (i = 0; i < 32; i++) { u32 phy_id; int j; for (j = 0; j < 3; j++) { cp->phy_addr = i; phy_id = cas_phy_read(cp, MII_PHYSID1) << 16; phy_id |= cas_phy_read(cp, MII_PHYSID2); if (phy_id && (phy_id != 0xFFFFFFFF)) { cp->phy_id = phy_id; goto done; } } } pr_err("MII phy did not respond [%08x]\n", readl(cp->regs + REG_MIF_STATE_MACHINE)); return -1; done: /* see if we can do gigabit */ cfg = cas_phy_read(cp, MII_BMSR); if ((cfg & CAS_BMSR_1000_EXTEND) && cas_phy_read(cp, CAS_MII_1000_EXTEND)) cp->cas_flags |= CAS_FLAG_1000MB_CAP; return 0; } /* Must be invoked under cp->lock. */ static inline void cas_start_dma(struct cas *cp) { int i; u32 val; int txfailed = 0; /* enable dma */ val = readl(cp->regs + REG_TX_CFG) | TX_CFG_DMA_EN; writel(val, cp->regs + REG_TX_CFG); val = readl(cp->regs + REG_RX_CFG) | RX_CFG_DMA_EN; writel(val, cp->regs + REG_RX_CFG); /* enable the mac */ val = readl(cp->regs + REG_MAC_TX_CFG) | MAC_TX_CFG_EN; writel(val, cp->regs + REG_MAC_TX_CFG); val = readl(cp->regs + REG_MAC_RX_CFG) | MAC_RX_CFG_EN; writel(val, cp->regs + REG_MAC_RX_CFG); i = STOP_TRIES; while (i-- > 0) { val = readl(cp->regs + REG_MAC_TX_CFG); if ((val & MAC_TX_CFG_EN)) break; udelay(10); } if (i < 0) txfailed = 1; i = STOP_TRIES; while (i-- > 0) { val = readl(cp->regs + REG_MAC_RX_CFG); if ((val & MAC_RX_CFG_EN)) { if (txfailed) { netdev_err(cp->dev, "enabling mac failed [tx:%08x:%08x]\n", readl(cp->regs + REG_MIF_STATE_MACHINE), readl(cp->regs + REG_MAC_STATE_MACHINE)); } goto enable_rx_done; } udelay(10); } netdev_err(cp->dev, "enabling mac failed [%s:%08x:%08x]\n", (txfailed ? "tx,rx" : "rx"), readl(cp->regs + REG_MIF_STATE_MACHINE), readl(cp->regs + REG_MAC_STATE_MACHINE)); enable_rx_done: cas_unmask_intr(cp); /* enable interrupts */ writel(RX_DESC_RINGN_SIZE(0) - 4, cp->regs + REG_RX_KICK); writel(0, cp->regs + REG_RX_COMP_TAIL); if (cp->cas_flags & CAS_FLAG_REG_PLUS) { if (N_RX_DESC_RINGS > 1) writel(RX_DESC_RINGN_SIZE(1) - 4, cp->regs + REG_PLUS_RX_KICK1); for (i = 1; i < N_RX_COMP_RINGS; i++) writel(0, cp->regs + REG_PLUS_RX_COMPN_TAIL(i)); } } /* Must be invoked under cp->lock. */ static void cas_read_pcs_link_mode(struct cas *cp, int *fd, int *spd, int *pause) { u32 val = readl(cp->regs + REG_PCS_MII_LPA); *fd = (val & PCS_MII_LPA_FD) ? 1 : 0; *pause = (val & PCS_MII_LPA_SYM_PAUSE) ? 0x01 : 0x00; if (val & PCS_MII_LPA_ASYM_PAUSE) *pause |= 0x10; *spd = 1000; } /* Must be invoked under cp->lock. */ static void cas_read_mii_link_mode(struct cas *cp, int *fd, int *spd, int *pause) { u32 val; *fd = 0; *spd = 10; *pause = 0; /* use GMII registers */ val = cas_phy_read(cp, MII_LPA); if (val & CAS_LPA_PAUSE) *pause = 0x01; if (val & CAS_LPA_ASYM_PAUSE) *pause |= 0x10; if (val & LPA_DUPLEX) *fd = 1; if (val & LPA_100) *spd = 100; if (cp->cas_flags & CAS_FLAG_1000MB_CAP) { val = cas_phy_read(cp, CAS_MII_1000_STATUS); if (val & (CAS_LPA_1000FULL | CAS_LPA_1000HALF)) *spd = 1000; if (val & CAS_LPA_1000FULL) *fd = 1; } } /* A link-up condition has occurred, initialize and enable the * rest of the chip. * * Must be invoked under cp->lock. */ static void cas_set_link_modes(struct cas *cp) { u32 val; int full_duplex, speed, pause; full_duplex = 0; speed = 10; pause = 0; if (CAS_PHY_MII(cp->phy_type)) { cas_mif_poll(cp, 0); val = cas_phy_read(cp, MII_BMCR); if (val & BMCR_ANENABLE) { cas_read_mii_link_mode(cp, &full_duplex, &speed, &pause); } else { if (val & BMCR_FULLDPLX) full_duplex = 1; if (val & BMCR_SPEED100) speed = 100; else if (val & CAS_BMCR_SPEED1000) speed = (cp->cas_flags & CAS_FLAG_1000MB_CAP) ? 1000 : 100; } cas_mif_poll(cp, 1); } else { val = readl(cp->regs + REG_PCS_MII_CTRL); cas_read_pcs_link_mode(cp, &full_duplex, &speed, &pause); if ((val & PCS_MII_AUTONEG_EN) == 0) { if (val & PCS_MII_CTRL_DUPLEX) full_duplex = 1; } } netif_info(cp, link, cp->dev, "Link up at %d Mbps, %s-duplex\n", speed, full_duplex ? "full" : "half"); val = MAC_XIF_TX_MII_OUTPUT_EN | MAC_XIF_LINK_LED; if (CAS_PHY_MII(cp->phy_type)) { val |= MAC_XIF_MII_BUFFER_OUTPUT_EN; if (!full_duplex) val |= MAC_XIF_DISABLE_ECHO; } if (full_duplex) val |= MAC_XIF_FDPLX_LED; if (speed == 1000) val |= MAC_XIF_GMII_MODE; writel(val, cp->regs + REG_MAC_XIF_CFG); /* deal with carrier and collision detect. */ val = MAC_TX_CFG_IPG_EN; if (full_duplex) { val |= MAC_TX_CFG_IGNORE_CARRIER; val |= MAC_TX_CFG_IGNORE_COLL; } else { #ifndef USE_CSMA_CD_PROTO val |= MAC_TX_CFG_NEVER_GIVE_UP_EN; val |= MAC_TX_CFG_NEVER_GIVE_UP_LIM; #endif } /* val now set up for REG_MAC_TX_CFG */ /* If gigabit and half-duplex, enable carrier extension * mode. increase slot time to 512 bytes as well. * else, disable it and make sure slot time is 64 bytes. * also activate checksum bug workaround */ if ((speed == 1000) && !full_duplex) { writel(val | MAC_TX_CFG_CARRIER_EXTEND, cp->regs + REG_MAC_TX_CFG); val = readl(cp->regs + REG_MAC_RX_CFG); val &= ~MAC_RX_CFG_STRIP_FCS; /* checksum workaround */ writel(val | MAC_RX_CFG_CARRIER_EXTEND, cp->regs + REG_MAC_RX_CFG); writel(0x200, cp->regs + REG_MAC_SLOT_TIME); cp->crc_size = 4; /* minimum size gigabit frame at half duplex */ cp->min_frame_size = CAS_1000MB_MIN_FRAME; } else { writel(val, cp->regs + REG_MAC_TX_CFG); /* checksum bug workaround. don't strip FCS when in * half-duplex mode */ val = readl(cp->regs + REG_MAC_RX_CFG); if (full_duplex) { val |= MAC_RX_CFG_STRIP_FCS; cp->crc_size = 0; cp->min_frame_size = CAS_MIN_MTU; } else { val &= ~MAC_RX_CFG_STRIP_FCS; cp->crc_size = 4; cp->min_frame_size = CAS_MIN_FRAME; } writel(val & ~MAC_RX_CFG_CARRIER_EXTEND, cp->regs + REG_MAC_RX_CFG); writel(0x40, cp->regs + REG_MAC_SLOT_TIME); } if (netif_msg_link(cp)) { if (pause & 0x01) { netdev_info(cp->dev, "Pause is enabled (rxfifo: %d off: %d on: %d)\n", cp->rx_fifo_size, cp->rx_pause_off, cp->rx_pause_on); } else if (pause & 0x10) { netdev_info(cp->dev, "TX pause enabled\n"); } else { netdev_info(cp->dev, "Pause is disabled\n"); } } val = readl(cp->regs + REG_MAC_CTRL_CFG); val &= ~(MAC_CTRL_CFG_SEND_PAUSE_EN | MAC_CTRL_CFG_RECV_PAUSE_EN); if (pause) { /* symmetric or asymmetric pause */ val |= MAC_CTRL_CFG_SEND_PAUSE_EN; if (pause & 0x01) { /* symmetric pause */ val |= MAC_CTRL_CFG_RECV_PAUSE_EN; } } writel(val, cp->regs + REG_MAC_CTRL_CFG); cas_start_dma(cp); } /* Must be invoked under cp->lock. */ static void cas_init_hw(struct cas *cp, int restart_link) { if (restart_link) cas_phy_init(cp); cas_init_pause_thresholds(cp); cas_init_mac(cp); cas_init_dma(cp); if (restart_link) { /* Default aneg parameters */ cp->timer_ticks = 0; cas_begin_auto_negotiation(cp, NULL); } else if (cp->lstate == link_up) { cas_set_link_modes(cp); netif_carrier_on(cp->dev); } } /* Must be invoked under cp->lock. on earlier cassini boards, * SOFT_0 is tied to PCI reset. we use this to force a pci reset, * let it settle out, and then restore pci state. */ static void cas_hard_reset(struct cas *cp) { writel(BIM_LOCAL_DEV_SOFT_0, cp->regs + REG_BIM_LOCAL_DEV_EN); udelay(20); pci_restore_state(cp->pdev); } static void cas_global_reset(struct cas *cp, int blkflag) { int limit; /* issue a global reset. don't use RSTOUT. */ if (blkflag && !CAS_PHY_MII(cp->phy_type)) { /* For PCS, when the blkflag is set, we should set the * SW_REST_BLOCK_PCS_SLINK bit to prevent the results of * the last autonegotiation from being cleared. We'll * need some special handling if the chip is set into a * loopback mode. */ writel((SW_RESET_TX | SW_RESET_RX | SW_RESET_BLOCK_PCS_SLINK), cp->regs + REG_SW_RESET); } else { writel(SW_RESET_TX | SW_RESET_RX, cp->regs + REG_SW_RESET); } /* need to wait at least 3ms before polling register */ mdelay(3); limit = STOP_TRIES; while (limit-- > 0) { u32 val = readl(cp->regs + REG_SW_RESET); if ((val & (SW_RESET_TX | SW_RESET_RX)) == 0) goto done; udelay(10); } netdev_err(cp->dev, "sw reset failed\n"); done: /* enable various BIM interrupts */ writel(BIM_CFG_DPAR_INTR_ENABLE | BIM_CFG_RMA_INTR_ENABLE | BIM_CFG_RTA_INTR_ENABLE, cp->regs + REG_BIM_CFG); /* clear out pci error status mask for handled errors. * we don't deal with DMA counter overflows as they happen * all the time. */ writel(0xFFFFFFFFU & ~(PCI_ERR_BADACK | PCI_ERR_DTRTO | PCI_ERR_OTHER | PCI_ERR_BIM_DMA_WRITE | PCI_ERR_BIM_DMA_READ), cp->regs + REG_PCI_ERR_STATUS_MASK); /* set up for MII by default to address mac rx reset timeout * issue */ writel(PCS_DATAPATH_MODE_MII, cp->regs + REG_PCS_DATAPATH_MODE); } static void cas_reset(struct cas *cp, int blkflag) { u32 val; cas_mask_intr(cp); cas_global_reset(cp, blkflag); cas_mac_reset(cp); cas_entropy_reset(cp); /* disable dma engines. */ val = readl(cp->regs + REG_TX_CFG); val &= ~TX_CFG_DMA_EN; writel(val, cp->regs + REG_TX_CFG); val = readl(cp->regs + REG_RX_CFG); val &= ~RX_CFG_DMA_EN; writel(val, cp->regs + REG_RX_CFG); /* program header parser */ if ((cp->cas_flags & CAS_FLAG_TARGET_ABORT) || (CAS_HP_ALT_FIRMWARE == cas_prog_null)) { cas_load_firmware(cp, CAS_HP_FIRMWARE); } else { cas_load_firmware(cp, CAS_HP_ALT_FIRMWARE); } /* clear out error registers */ spin_lock(&cp->stat_lock[N_TX_RINGS]); cas_clear_mac_err(cp); spin_unlock(&cp->stat_lock[N_TX_RINGS]); } /* Shut down the chip, must be called with pm_mutex held. */ static void cas_shutdown(struct cas *cp) { unsigned long flags; /* Make us not-running to avoid timers respawning */ cp->hw_running = 0; del_timer_sync(&cp->link_timer); /* Stop the reset task */ #if 0 while (atomic_read(&cp->reset_task_pending_mtu) || atomic_read(&cp->reset_task_pending_spare) || atomic_read(&cp->reset_task_pending_all)) schedule(); #else while (atomic_read(&cp->reset_task_pending)) schedule(); #endif /* Actually stop the chip */ cas_lock_all_save(cp, flags); cas_reset(cp, 0); if (cp->cas_flags & CAS_FLAG_SATURN) cas_phy_powerdown(cp); cas_unlock_all_restore(cp, flags); } static int cas_change_mtu(struct net_device *dev, int new_mtu) { struct cas *cp = netdev_priv(dev); if (new_mtu < CAS_MIN_MTU || new_mtu > CAS_MAX_MTU) return -EINVAL; dev->mtu = new_mtu; if (!netif_running(dev) || !netif_device_present(dev)) return 0; /* let the reset task handle it */ #if 1 atomic_inc(&cp->reset_task_pending); if ((cp->phy_type & CAS_PHY_SERDES)) { atomic_inc(&cp->reset_task_pending_all); } else { atomic_inc(&cp->reset_task_pending_mtu); } schedule_work(&cp->reset_task); #else atomic_set(&cp->reset_task_pending, (cp->phy_type & CAS_PHY_SERDES) ? CAS_RESET_ALL : CAS_RESET_MTU); pr_err("reset called in cas_change_mtu\n"); schedule_work(&cp->reset_task); #endif flush_work(&cp->reset_task); return 0; } static void cas_clean_txd(struct cas *cp, int ring) { struct cas_tx_desc *txd = cp->init_txds[ring]; struct sk_buff *skb, **skbs = cp->tx_skbs[ring]; u64 daddr, dlen; int i, size; size = TX_DESC_RINGN_SIZE(ring); for (i = 0; i < size; i++) { int frag; if (skbs[i] == NULL) continue; skb = skbs[i]; skbs[i] = NULL; for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) { int ent = i & (size - 1); /* first buffer is never a tiny buffer and so * needs to be unmapped. */ daddr = le64_to_cpu(txd[ent].buffer); dlen = CAS_VAL(TX_DESC_BUFLEN, le64_to_cpu(txd[ent].control)); pci_unmap_page(cp->pdev, daddr, dlen, PCI_DMA_TODEVICE); if (frag != skb_shinfo(skb)->nr_frags) { i++; /* next buffer might by a tiny buffer. * skip past it. */ ent = i & (size - 1); if (cp->tx_tiny_use[ring][ent].used) i++; } } dev_kfree_skb_any(skb); } /* zero out tiny buf usage */ memset(cp->tx_tiny_use[ring], 0, size*sizeof(*cp->tx_tiny_use[ring])); } /* freed on close */ static inline void cas_free_rx_desc(struct cas *cp, int ring) { cas_page_t **page = cp->rx_pages[ring]; int i, size; size = RX_DESC_RINGN_SIZE(ring); for (i = 0; i < size; i++) { if (page[i]) { cas_page_free(cp, page[i]); page[i] = NULL; } } } static void cas_free_rxds(struct cas *cp) { int i; for (i = 0; i < N_RX_DESC_RINGS; i++) cas_free_rx_desc(cp, i); } /* Must be invoked under cp->lock. */ static void cas_clean_rings(struct cas *cp) { int i; /* need to clean all tx rings */ memset(cp->tx_old, 0, sizeof(*cp->tx_old)*N_TX_RINGS); memset(cp->tx_new, 0, sizeof(*cp->tx_new)*N_TX_RINGS); for (i = 0; i < N_TX_RINGS; i++) cas_clean_txd(cp, i); /* zero out init block */ memset(cp->init_block, 0, sizeof(struct cas_init_block)); cas_clean_rxds(cp); cas_clean_rxcs(cp); } /* allocated on open */ static inline int cas_alloc_rx_desc(struct cas *cp, int ring) { cas_page_t **page = cp->rx_pages[ring]; int size, i = 0; size = RX_DESC_RINGN_SIZE(ring); for (i = 0; i < size; i++) { if ((page[i] = cas_page_alloc(cp, GFP_KERNEL)) == NULL) return -1; } return 0; } static int cas_alloc_rxds(struct cas *cp) { int i; for (i = 0; i < N_RX_DESC_RINGS; i++) { if (cas_alloc_rx_desc(cp, i) < 0) { cas_free_rxds(cp); return -1; } } return 0; } static void cas_reset_task(struct work_struct *work) { struct cas *cp = container_of(work, struct cas, reset_task); #if 0 int pending = atomic_read(&cp->reset_task_pending); #else int pending_all = atomic_read(&cp->reset_task_pending_all); int pending_spare = atomic_read(&cp->reset_task_pending_spare); int pending_mtu = atomic_read(&cp->reset_task_pending_mtu); if (pending_all == 0 && pending_spare == 0 && pending_mtu == 0) { /* We can have more tasks scheduled than actually * needed. */ atomic_dec(&cp->reset_task_pending); return; } #endif /* The link went down, we reset the ring, but keep * DMA stopped. Use this function for reset * on error as well. */ if (cp->hw_running) { unsigned long flags; /* Make sure we don't get interrupts or tx packets */ netif_device_detach(cp->dev); cas_lock_all_save(cp, flags); if (cp->opened) { /* We call cas_spare_recover when we call cas_open. * but we do not initialize the lists cas_spare_recover * uses until cas_open is called. */ cas_spare_recover(cp, GFP_ATOMIC); } #if 1 /* test => only pending_spare set */ if (!pending_all && !pending_mtu) goto done; #else if (pending == CAS_RESET_SPARE) goto done; #endif /* when pending == CAS_RESET_ALL, the following * call to cas_init_hw will restart auto negotiation. * Setting the second argument of cas_reset to * !(pending == CAS_RESET_ALL) will set this argument * to 1 (avoiding reinitializing the PHY for the normal * PCS case) when auto negotiation is not restarted. */ #if 1 cas_reset(cp, !(pending_all > 0)); if (cp->opened) cas_clean_rings(cp); cas_init_hw(cp, (pending_all > 0)); #else cas_reset(cp, !(pending == CAS_RESET_ALL)); if (cp->opened) cas_clean_rings(cp); cas_init_hw(cp, pending == CAS_RESET_ALL); #endif done: cas_unlock_all_restore(cp, flags); netif_device_attach(cp->dev); } #if 1 atomic_sub(pending_all, &cp->reset_task_pending_all); atomic_sub(pending_spare, &cp->reset_task_pending_spare); atomic_sub(pending_mtu, &cp->reset_task_pending_mtu); atomic_dec(&cp->reset_task_pending); #else atomic_set(&cp->reset_task_pending, 0); #endif } static void cas_link_timer(unsigned long data) { struct cas *cp = (struct cas *) data; int mask, pending = 0, reset = 0; unsigned long flags; if (link_transition_timeout != 0 && cp->link_transition_jiffies_valid && ((jiffies - cp->link_transition_jiffies) > (link_transition_timeout))) { /* One-second counter so link-down workaround doesn't * cause resets to occur so fast as to fool the switch * into thinking the link is down. */ cp->link_transition_jiffies_valid = 0; } if (!cp->hw_running) return; spin_lock_irqsave(&cp->lock, flags); cas_lock_tx(cp); cas_entropy_gather(cp); /* If the link task is still pending, we just * reschedule the link timer */ #if 1 if (atomic_read(&cp->reset_task_pending_all) || atomic_read(&cp->reset_task_pending_spare) || atomic_read(&cp->reset_task_pending_mtu)) goto done; #else if (atomic_read(&cp->reset_task_pending)) goto done; #endif /* check for rx cleaning */ if ((mask = (cp->cas_flags & CAS_FLAG_RXD_POST_MASK))) { int i, rmask; for (i = 0; i < MAX_RX_DESC_RINGS; i++) { rmask = CAS_FLAG_RXD_POST(i); if ((mask & rmask) == 0) continue; /* post_rxds will do a mod_timer */ if (cas_post_rxds_ringN(cp, i, cp->rx_last[i]) < 0) { pending = 1; continue; } cp->cas_flags &= ~rmask; } } if (CAS_PHY_MII(cp->phy_type)) { u16 bmsr; cas_mif_poll(cp, 0); bmsr = cas_phy_read(cp, MII_BMSR); /* WTZ: Solaris driver reads this twice, but that * may be due to the PCS case and the use of a * common implementation. Read it twice here to be * safe. */ bmsr = cas_phy_read(cp, MII_BMSR); cas_mif_poll(cp, 1); readl(cp->regs + REG_MIF_STATUS); /* avoid dups */ reset = cas_mii_link_check(cp, bmsr); } else { reset = cas_pcs_link_check(cp); } if (reset) goto done; /* check for tx state machine confusion */ if ((readl(cp->regs + REG_MAC_TX_STATUS) & MAC_TX_FRAME_XMIT) == 0) { u32 val = readl(cp->regs + REG_MAC_STATE_MACHINE); u32 wptr, rptr; int tlm = CAS_VAL(MAC_SM_TLM, val); if (((tlm == 0x5) || (tlm == 0x3)) && (CAS_VAL(MAC_SM_ENCAP_SM, val) == 0)) { netif_printk(cp, tx_err, KERN_DEBUG, cp->dev, "tx err: MAC_STATE[%08x]\n", val); reset = 1; goto done; } val = readl(cp->regs + REG_TX_FIFO_PKT_CNT); wptr = readl(cp->regs + REG_TX_FIFO_WRITE_PTR); rptr = readl(cp->regs + REG_TX_FIFO_READ_PTR); if ((val == 0) && (wptr != rptr)) { netif_printk(cp, tx_err, KERN_DEBUG, cp->dev, "tx err: TX_FIFO[%08x:%08x:%08x]\n", val, wptr, rptr); reset = 1; } if (reset) cas_hard_reset(cp); } done: if (reset) { #if 1 atomic_inc(&cp->reset_task_pending); atomic_inc(&cp->reset_task_pending_all); schedule_work(&cp->reset_task); #else atomic_set(&cp->reset_task_pending, CAS_RESET_ALL); pr_err("reset called in cas_link_timer\n"); schedule_work(&cp->reset_task); #endif } if (!pending) mod_timer(&cp->link_timer, jiffies + CAS_LINK_TIMEOUT); cas_unlock_tx(cp); spin_unlock_irqrestore(&cp->lock, flags); } /* tiny buffers are used to avoid target abort issues with * older cassini's */ static void cas_tx_tiny_free(struct cas *cp) { struct pci_dev *pdev = cp->pdev; int i; for (i = 0; i < N_TX_RINGS; i++) { if (!cp->tx_tiny_bufs[i]) continue; pci_free_consistent(pdev, TX_TINY_BUF_BLOCK, cp->tx_tiny_bufs[i], cp->tx_tiny_dvma[i]); cp->tx_tiny_bufs[i] = NULL; } } static int cas_tx_tiny_alloc(struct cas *cp) { struct pci_dev *pdev = cp->pdev; int i; for (i = 0; i < N_TX_RINGS; i++) { cp->tx_tiny_bufs[i] = pci_alloc_consistent(pdev, TX_TINY_BUF_BLOCK, &cp->tx_tiny_dvma[i]); if (!cp->tx_tiny_bufs[i]) { cas_tx_tiny_free(cp); return -1; } } return 0; } static int cas_open(struct net_device *dev) { struct cas *cp = netdev_priv(dev); int hw_was_up, err; unsigned long flags; mutex_lock(&cp->pm_mutex); hw_was_up = cp->hw_running; /* The power-management mutex protects the hw_running * etc. state so it is safe to do this bit without cp->lock */ if (!cp->hw_running) { /* Reset the chip */ cas_lock_all_save(cp, flags); /* We set the second arg to cas_reset to zero * because cas_init_hw below will have its second * argument set to non-zero, which will force * autonegotiation to start. */ cas_reset(cp, 0); cp->hw_running = 1; cas_unlock_all_restore(cp, flags); } err = -ENOMEM; if (cas_tx_tiny_alloc(cp) < 0) goto err_unlock; /* alloc rx descriptors */ if (cas_alloc_rxds(cp) < 0) goto err_tx_tiny; /* allocate spares */ cas_spare_init(cp); cas_spare_recover(cp, GFP_KERNEL); /* We can now request the interrupt as we know it's masked * on the controller. cassini+ has up to 4 interrupts * that can be used, but you need to do explicit pci interrupt * mapping to expose them */ if (request_irq(cp->pdev->irq, cas_interrupt, IRQF_SHARED, dev->name, (void *) dev)) { netdev_err(cp->dev, "failed to request irq !\n"); err = -EAGAIN; goto err_spare; } #ifdef USE_NAPI napi_enable(&cp->napi); #endif /* init hw */ cas_lock_all_save(cp, flags); cas_clean_rings(cp); cas_init_hw(cp, !hw_was_up); cp->opened = 1; cas_unlock_all_restore(cp, flags); netif_start_queue(dev); mutex_unlock(&cp->pm_mutex); return 0; err_spare: cas_spare_free(cp); cas_free_rxds(cp); err_tx_tiny: cas_tx_tiny_free(cp); err_unlock: mutex_unlock(&cp->pm_mutex); return err; } static int cas_close(struct net_device *dev) { unsigned long flags; struct cas *cp = netdev_priv(dev); #ifdef USE_NAPI napi_disable(&cp->napi); #endif /* Make sure we don't get distracted by suspend/resume */ mutex_lock(&cp->pm_mutex); netif_stop_queue(dev); /* Stop traffic, mark us closed */ cas_lock_all_save(cp, flags); cp->opened = 0; cas_reset(cp, 0); cas_phy_init(cp); cas_begin_auto_negotiation(cp, NULL); cas_clean_rings(cp); cas_unlock_all_restore(cp, flags); free_irq(cp->pdev->irq, (void *) dev); cas_spare_free(cp); cas_free_rxds(cp); cas_tx_tiny_free(cp); mutex_unlock(&cp->pm_mutex); return 0; } static struct { const char name[ETH_GSTRING_LEN]; } ethtool_cassini_statnames[] = { {"collisions"}, {"rx_bytes"}, {"rx_crc_errors"}, {"rx_dropped"}, {"rx_errors"}, {"rx_fifo_errors"}, {"rx_frame_errors"}, {"rx_length_errors"}, {"rx_over_errors"}, {"rx_packets"}, {"tx_aborted_errors"}, {"tx_bytes"}, {"tx_dropped"}, {"tx_errors"}, {"tx_fifo_errors"}, {"tx_packets"} }; #define CAS_NUM_STAT_KEYS ARRAY_SIZE(ethtool_cassini_statnames) static struct { const int offsets; /* neg. values for 2nd arg to cas_read_phy */ } ethtool_register_table[] = { {-MII_BMSR}, {-MII_BMCR}, {REG_CAWR}, {REG_INF_BURST}, {REG_BIM_CFG}, {REG_RX_CFG}, {REG_HP_CFG}, {REG_MAC_TX_CFG}, {REG_MAC_RX_CFG}, {REG_MAC_CTRL_CFG}, {REG_MAC_XIF_CFG}, {REG_MIF_CFG}, {REG_PCS_CFG}, {REG_SATURN_PCFG}, {REG_PCS_MII_STATUS}, {REG_PCS_STATE_MACHINE}, {REG_MAC_COLL_EXCESS}, {REG_MAC_COLL_LATE} }; #define CAS_REG_LEN ARRAY_SIZE(ethtool_register_table) #define CAS_MAX_REGS (sizeof (u32)*CAS_REG_LEN) static void cas_read_regs(struct cas *cp, u8 *ptr, int len) { u8 *p; int i; unsigned long flags; spin_lock_irqsave(&cp->lock, flags); for (i = 0, p = ptr; i < len ; i ++, p += sizeof(u32)) { u16 hval; u32 val; if (ethtool_register_table[i].offsets < 0) { hval = cas_phy_read(cp, -ethtool_register_table[i].offsets); val = hval; } else { val= readl(cp->regs+ethtool_register_table[i].offsets); } memcpy(p, (u8 *)&val, sizeof(u32)); } spin_unlock_irqrestore(&cp->lock, flags); } static struct net_device_stats *cas_get_stats(struct net_device *dev) { struct cas *cp = netdev_priv(dev); struct net_device_stats *stats = cp->net_stats; unsigned long flags; int i; unsigned long tmp; /* we collate all of the stats into net_stats[N_TX_RING] */ if (!cp->hw_running) return stats + N_TX_RINGS; /* collect outstanding stats */ /* WTZ: the Cassini spec gives these as 16 bit counters but * stored in 32-bit words. Added a mask of 0xffff to be safe, * in case the chip somehow puts any garbage in the other bits. * Also, counter usage didn't seem to mach what Adrian did * in the parts of the code that set these quantities. Made * that consistent. */ spin_lock_irqsave(&cp->stat_lock[N_TX_RINGS], flags); stats[N_TX_RINGS].rx_crc_errors += readl(cp->regs + REG_MAC_FCS_ERR) & 0xffff; stats[N_TX_RINGS].rx_frame_errors += readl(cp->regs + REG_MAC_ALIGN_ERR) &0xffff; stats[N_TX_RINGS].rx_length_errors += readl(cp->regs + REG_MAC_LEN_ERR) & 0xffff; #if 1 tmp = (readl(cp->regs + REG_MAC_COLL_EXCESS) & 0xffff) + (readl(cp->regs + REG_MAC_COLL_LATE) & 0xffff); stats[N_TX_RINGS].tx_aborted_errors += tmp; stats[N_TX_RINGS].collisions += tmp + (readl(cp->regs + REG_MAC_COLL_NORMAL) & 0xffff); #else stats[N_TX_RINGS].tx_aborted_errors += readl(cp->regs + REG_MAC_COLL_EXCESS); stats[N_TX_RINGS].collisions += readl(cp->regs + REG_MAC_COLL_EXCESS) + readl(cp->regs + REG_MAC_COLL_LATE); #endif cas_clear_mac_err(cp); /* saved bits that are unique to ring 0 */ spin_lock(&cp->stat_lock[0]); stats[N_TX_RINGS].collisions += stats[0].collisions; stats[N_TX_RINGS].rx_over_errors += stats[0].rx_over_errors; stats[N_TX_RINGS].rx_frame_errors += stats[0].rx_frame_errors; stats[N_TX_RINGS].rx_fifo_errors += stats[0].rx_fifo_errors; stats[N_TX_RINGS].tx_aborted_errors += stats[0].tx_aborted_errors; stats[N_TX_RINGS].tx_fifo_errors += stats[0].tx_fifo_errors; spin_unlock(&cp->stat_lock[0]); for (i = 0; i < N_TX_RINGS; i++) { spin_lock(&cp->stat_lock[i]); stats[N_TX_RINGS].rx_length_errors += stats[i].rx_length_errors; stats[N_TX_RINGS].rx_crc_errors += stats[i].rx_crc_errors; stats[N_TX_RINGS].rx_packets += stats[i].rx_packets; stats[N_TX_RINGS].tx_packets += stats[i].tx_packets; stats[N_TX_RINGS].rx_bytes += stats[i].rx_bytes; stats[N_TX_RINGS].tx_bytes += stats[i].tx_bytes; stats[N_TX_RINGS].rx_errors += stats[i].rx_errors; stats[N_TX_RINGS].tx_errors += stats[i].tx_errors; stats[N_TX_RINGS].rx_dropped += stats[i].rx_dropped; stats[N_TX_RINGS].tx_dropped += stats[i].tx_dropped; memset(stats + i, 0, sizeof(struct net_device_stats)); spin_unlock(&cp->stat_lock[i]); } spin_unlock_irqrestore(&cp->stat_lock[N_TX_RINGS], flags); return stats + N_TX_RINGS; } static void cas_set_multicast(struct net_device *dev) { struct cas *cp = netdev_priv(dev); u32 rxcfg, rxcfg_new; unsigned long flags; int limit = STOP_TRIES; if (!cp->hw_running) return; spin_lock_irqsave(&cp->lock, flags); rxcfg = readl(cp->regs + REG_MAC_RX_CFG); /* disable RX MAC and wait for completion */ writel(rxcfg & ~MAC_RX_CFG_EN, cp->regs + REG_MAC_RX_CFG); while (readl(cp->regs + REG_MAC_RX_CFG) & MAC_RX_CFG_EN) { if (!limit--) break; udelay(10); } /* disable hash filter and wait for completion */ limit = STOP_TRIES; rxcfg &= ~(MAC_RX_CFG_PROMISC_EN | MAC_RX_CFG_HASH_FILTER_EN); writel(rxcfg & ~MAC_RX_CFG_EN, cp->regs + REG_MAC_RX_CFG); while (readl(cp->regs + REG_MAC_RX_CFG) & MAC_RX_CFG_HASH_FILTER_EN) { if (!limit--) break; udelay(10); } /* program hash filters */ cp->mac_rx_cfg = rxcfg_new = cas_setup_multicast(cp); rxcfg |= rxcfg_new; writel(rxcfg, cp->regs + REG_MAC_RX_CFG); spin_unlock_irqrestore(&cp->lock, flags); } static void cas_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct cas *cp = netdev_priv(dev); strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version)); strlcpy(info->bus_info, pci_name(cp->pdev), sizeof(info->bus_info)); info->regdump_len = cp->casreg_len < CAS_MAX_REGS ? cp->casreg_len : CAS_MAX_REGS; info->n_stats = CAS_NUM_STAT_KEYS; } static int cas_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct cas *cp = netdev_priv(dev); u16 bmcr; int full_duplex, speed, pause; unsigned long flags; enum link_state linkstate = link_up; cmd->advertising = 0; cmd->supported = SUPPORTED_Autoneg; if (cp->cas_flags & CAS_FLAG_1000MB_CAP) { cmd->supported |= SUPPORTED_1000baseT_Full; cmd->advertising |= ADVERTISED_1000baseT_Full; } /* Record PHY settings if HW is on. */ spin_lock_irqsave(&cp->lock, flags); bmcr = 0; linkstate = cp->lstate; if (CAS_PHY_MII(cp->phy_type)) { cmd->port = PORT_MII; cmd->transceiver = (cp->cas_flags & CAS_FLAG_SATURN) ? XCVR_INTERNAL : XCVR_EXTERNAL; cmd->phy_address = cp->phy_addr; cmd->advertising |= ADVERTISED_TP | ADVERTISED_MII | ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full; cmd->supported |= (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_TP | SUPPORTED_MII); if (cp->hw_running) { cas_mif_poll(cp, 0); bmcr = cas_phy_read(cp, MII_BMCR); cas_read_mii_link_mode(cp, &full_duplex, &speed, &pause); cas_mif_poll(cp, 1); } } else { cmd->port = PORT_FIBRE; cmd->transceiver = XCVR_INTERNAL; cmd->phy_address = 0; cmd->supported |= SUPPORTED_FIBRE; cmd->advertising |= ADVERTISED_FIBRE; if (cp->hw_running) { /* pcs uses the same bits as mii */ bmcr = readl(cp->regs + REG_PCS_MII_CTRL); cas_read_pcs_link_mode(cp, &full_duplex, &speed, &pause); } } spin_unlock_irqrestore(&cp->lock, flags); if (bmcr & BMCR_ANENABLE) { cmd->advertising |= ADVERTISED_Autoneg; cmd->autoneg = AUTONEG_ENABLE; ethtool_cmd_speed_set(cmd, ((speed == 10) ? SPEED_10 : ((speed == 1000) ? SPEED_1000 : SPEED_100))); cmd->duplex = full_duplex ? DUPLEX_FULL : DUPLEX_HALF; } else { cmd->autoneg = AUTONEG_DISABLE; ethtool_cmd_speed_set(cmd, ((bmcr & CAS_BMCR_SPEED1000) ? SPEED_1000 : ((bmcr & BMCR_SPEED100) ? SPEED_100 : SPEED_10))); cmd->duplex = (bmcr & BMCR_FULLDPLX) ? DUPLEX_FULL : DUPLEX_HALF; } if (linkstate != link_up) { /* Force these to "unknown" if the link is not up and * autonogotiation in enabled. We can set the link * speed to 0, but not cmd->duplex, * because its legal values are 0 and 1. Ethtool will * print the value reported in parentheses after the * word "Unknown" for unrecognized values. * * If in forced mode, we report the speed and duplex * settings that we configured. */ if (cp->link_cntl & BMCR_ANENABLE) { ethtool_cmd_speed_set(cmd, 0); cmd->duplex = 0xff; } else { ethtool_cmd_speed_set(cmd, SPEED_10); if (cp->link_cntl & BMCR_SPEED100) { ethtool_cmd_speed_set(cmd, SPEED_100); } else if (cp->link_cntl & CAS_BMCR_SPEED1000) { ethtool_cmd_speed_set(cmd, SPEED_1000); } cmd->duplex = (cp->link_cntl & BMCR_FULLDPLX)? DUPLEX_FULL : DUPLEX_HALF; } } return 0; } static int cas_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct cas *cp = netdev_priv(dev); unsigned long flags; u32 speed = ethtool_cmd_speed(cmd); /* Verify the settings we care about. */ if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE) return -EINVAL; if (cmd->autoneg == AUTONEG_DISABLE && ((speed != SPEED_1000 && speed != SPEED_100 && speed != SPEED_10) || (cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL))) return -EINVAL; /* Apply settings and restart link process. */ spin_lock_irqsave(&cp->lock, flags); cas_begin_auto_negotiation(cp, cmd); spin_unlock_irqrestore(&cp->lock, flags); return 0; } static int cas_nway_reset(struct net_device *dev) { struct cas *cp = netdev_priv(dev); unsigned long flags; if ((cp->link_cntl & BMCR_ANENABLE) == 0) return -EINVAL; /* Restart link process. */ spin_lock_irqsave(&cp->lock, flags); cas_begin_auto_negotiation(cp, NULL); spin_unlock_irqrestore(&cp->lock, flags); return 0; } static u32 cas_get_link(struct net_device *dev) { struct cas *cp = netdev_priv(dev); return cp->lstate == link_up; } static u32 cas_get_msglevel(struct net_device *dev) { struct cas *cp = netdev_priv(dev); return cp->msg_enable; } static void cas_set_msglevel(struct net_device *dev, u32 value) { struct cas *cp = netdev_priv(dev); cp->msg_enable = value; } static int cas_get_regs_len(struct net_device *dev) { struct cas *cp = netdev_priv(dev); return cp->casreg_len < CAS_MAX_REGS ? cp->casreg_len: CAS_MAX_REGS; } static void cas_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *p) { struct cas *cp = netdev_priv(dev); regs->version = 0; /* cas_read_regs handles locks (cp->lock). */ cas_read_regs(cp, p, regs->len / sizeof(u32)); } static int cas_get_sset_count(struct net_device *dev, int sset) { switch (sset) { case ETH_SS_STATS: return CAS_NUM_STAT_KEYS; default: return -EOPNOTSUPP; } } static void cas_get_strings(struct net_device *dev, u32 stringset, u8 *data) { memcpy(data, &ethtool_cassini_statnames, CAS_NUM_STAT_KEYS * ETH_GSTRING_LEN); } static void cas_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *estats, u64 *data) { struct cas *cp = netdev_priv(dev); struct net_device_stats *stats = cas_get_stats(cp->dev); int i = 0; data[i++] = stats->collisions; data[i++] = stats->rx_bytes; data[i++] = stats->rx_crc_errors; data[i++] = stats->rx_dropped; data[i++] = stats->rx_errors; data[i++] = stats->rx_fifo_errors; data[i++] = stats->rx_frame_errors; data[i++] = stats->rx_length_errors; data[i++] = stats->rx_over_errors; data[i++] = stats->rx_packets; data[i++] = stats->tx_aborted_errors; data[i++] = stats->tx_bytes; data[i++] = stats->tx_dropped; data[i++] = stats->tx_errors; data[i++] = stats->tx_fifo_errors; data[i++] = stats->tx_packets; BUG_ON(i != CAS_NUM_STAT_KEYS); } static const struct ethtool_ops cas_ethtool_ops = { .get_drvinfo = cas_get_drvinfo, .get_settings = cas_get_settings, .set_settings = cas_set_settings, .nway_reset = cas_nway_reset, .get_link = cas_get_link, .get_msglevel = cas_get_msglevel, .set_msglevel = cas_set_msglevel, .get_regs_len = cas_get_regs_len, .get_regs = cas_get_regs, .get_sset_count = cas_get_sset_count, .get_strings = cas_get_strings, .get_ethtool_stats = cas_get_ethtool_stats, }; static int cas_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct cas *cp = netdev_priv(dev); struct mii_ioctl_data *data = if_mii(ifr); unsigned long flags; int rc = -EOPNOTSUPP; /* Hold the PM mutex while doing ioctl's or we may collide * with open/close and power management and oops. */ mutex_lock(&cp->pm_mutex); switch (cmd) { case SIOCGMIIPHY: /* Get address of MII PHY in use. */ data->phy_id = cp->phy_addr; /* Fallthrough... */ case SIOCGMIIREG: /* Read MII PHY register. */ spin_lock_irqsave(&cp->lock, flags); cas_mif_poll(cp, 0); data->val_out = cas_phy_read(cp, data->reg_num & 0x1f); cas_mif_poll(cp, 1); spin_unlock_irqrestore(&cp->lock, flags); rc = 0; break; case SIOCSMIIREG: /* Write MII PHY register. */ spin_lock_irqsave(&cp->lock, flags); cas_mif_poll(cp, 0); rc = cas_phy_write(cp, data->reg_num & 0x1f, data->val_in); cas_mif_poll(cp, 1); spin_unlock_irqrestore(&cp->lock, flags); break; default: break; } mutex_unlock(&cp->pm_mutex); return rc; } /* When this chip sits underneath an Intel 31154 bridge, it is the * only subordinate device and we can tweak the bridge settings to * reflect that fact. */ static void cas_program_bridge(struct pci_dev *cas_pdev) { struct pci_dev *pdev = cas_pdev->bus->self; u32 val; if (!pdev) return; if (pdev->vendor != 0x8086 || pdev->device != 0x537c) return; /* Clear bit 10 (Bus Parking Control) in the Secondary * Arbiter Control/Status Register which lives at offset * 0x41. Using a 32-bit word read/modify/write at 0x40 * is much simpler so that's how we do this. */ pci_read_config_dword(pdev, 0x40, &val); val &= ~0x00040000; pci_write_config_dword(pdev, 0x40, val); /* Max out the Multi-Transaction Timer settings since * Cassini is the only device present. * * The register is 16-bit and lives at 0x50. When the * settings are enabled, it extends the GRANT# signal * for a requestor after a transaction is complete. This * allows the next request to run without first needing * to negotiate the GRANT# signal back. * * Bits 12:10 define the grant duration: * * 1 -- 16 clocks * 2 -- 32 clocks * 3 -- 64 clocks * 4 -- 128 clocks * 5 -- 256 clocks * * All other values are illegal. * * Bits 09:00 define which REQ/GNT signal pairs get the * GRANT# signal treatment. We set them all. */ pci_write_config_word(pdev, 0x50, (5 << 10) | 0x3ff); /* The Read Prefecth Policy register is 16-bit and sits at * offset 0x52. It enables a "smart" pre-fetch policy. We * enable it and max out all of the settings since only one * device is sitting underneath and thus bandwidth sharing is * not an issue. * * The register has several 3 bit fields, which indicates a * multiplier applied to the base amount of prefetching the * chip would do. These fields are at: * * 15:13 --- ReRead Primary Bus * 12:10 --- FirstRead Primary Bus * 09:07 --- ReRead Secondary Bus * 06:04 --- FirstRead Secondary Bus * * Bits 03:00 control which REQ/GNT pairs the prefetch settings * get enabled on. Bit 3 is a grouped enabler which controls * all of the REQ/GNT pairs from [8:3]. Bits 2 to 0 control * the individual REQ/GNT pairs [2:0]. */ pci_write_config_word(pdev, 0x52, (0x7 << 13) | (0x7 << 10) | (0x7 << 7) | (0x7 << 4) | (0xf << 0)); /* Force cacheline size to 0x8 */ pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, 0x08); /* Force latency timer to maximum setting so Cassini can * sit on the bus as long as it likes. */ pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xff); } static const struct net_device_ops cas_netdev_ops = { .ndo_open = cas_open, .ndo_stop = cas_close, .ndo_start_xmit = cas_start_xmit, .ndo_get_stats = cas_get_stats, .ndo_set_rx_mode = cas_set_multicast, .ndo_do_ioctl = cas_ioctl, .ndo_tx_timeout = cas_tx_timeout, .ndo_change_mtu = cas_change_mtu, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = cas_netpoll, #endif }; static int cas_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { static int cas_version_printed = 0; unsigned long casreg_len; struct net_device *dev; struct cas *cp; int i, err, pci_using_dac; u16 pci_cmd; u8 orig_cacheline_size = 0, cas_cacheline_size = 0; if (cas_version_printed++ == 0) pr_info("%s", version); err = pci_enable_device(pdev); if (err) { dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n"); return err; } if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) { dev_err(&pdev->dev, "Cannot find proper PCI device " "base address, aborting\n"); err = -ENODEV; goto err_out_disable_pdev; } dev = alloc_etherdev(sizeof(*cp)); if (!dev) { err = -ENOMEM; goto err_out_disable_pdev; } SET_NETDEV_DEV(dev, &pdev->dev); err = pci_request_regions(pdev, dev->name); if (err) { dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n"); goto err_out_free_netdev; } pci_set_master(pdev); /* we must always turn on parity response or else parity * doesn't get generated properly. disable SERR/PERR as well. * in addition, we want to turn MWI on. */ pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd); pci_cmd &= ~PCI_COMMAND_SERR; pci_cmd |= PCI_COMMAND_PARITY; pci_write_config_word(pdev, PCI_COMMAND, pci_cmd); if (pci_try_set_mwi(pdev)) pr_warning("Could not enable MWI for %s\n", pci_name(pdev)); cas_program_bridge(pdev); /* * On some architectures, the default cache line size set * by pci_try_set_mwi reduces perforamnce. We have to increase * it for this case. To start, we'll print some configuration * data. */ #if 1 pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &orig_cacheline_size); if (orig_cacheline_size < CAS_PREF_CACHELINE_SIZE) { cas_cacheline_size = (CAS_PREF_CACHELINE_SIZE < SMP_CACHE_BYTES) ? CAS_PREF_CACHELINE_SIZE : SMP_CACHE_BYTES; if (pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, cas_cacheline_size)) { dev_err(&pdev->dev, "Could not set PCI cache " "line size\n"); goto err_write_cacheline; } } #endif /* Configure DMA attributes. */ if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) { pci_using_dac = 1; err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64)); if (err < 0) { dev_err(&pdev->dev, "Unable to obtain 64-bit DMA " "for consistent allocations\n"); goto err_out_free_res; } } else { err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); if (err) { dev_err(&pdev->dev, "No usable DMA configuration, " "aborting\n"); goto err_out_free_res; } pci_using_dac = 0; } casreg_len = pci_resource_len(pdev, 0); cp = netdev_priv(dev); cp->pdev = pdev; #if 1 /* A value of 0 indicates we never explicitly set it */ cp->orig_cacheline_size = cas_cacheline_size ? orig_cacheline_size: 0; #endif cp->dev = dev; cp->msg_enable = (cassini_debug < 0) ? CAS_DEF_MSG_ENABLE : cassini_debug; #if defined(CONFIG_SPARC) cp->of_node = pci_device_to_OF_node(pdev); #endif cp->link_transition = LINK_TRANSITION_UNKNOWN; cp->link_transition_jiffies_valid = 0; spin_lock_init(&cp->lock); spin_lock_init(&cp->rx_inuse_lock); spin_lock_init(&cp->rx_spare_lock); for (i = 0; i < N_TX_RINGS; i++) { spin_lock_init(&cp->stat_lock[i]); spin_lock_init(&cp->tx_lock[i]); } spin_lock_init(&cp->stat_lock[N_TX_RINGS]); mutex_init(&cp->pm_mutex); init_timer(&cp->link_timer); cp->link_timer.function = cas_link_timer; cp->link_timer.data = (unsigned long) cp; #if 1 /* Just in case the implementation of atomic operations * change so that an explicit initialization is necessary. */ atomic_set(&cp->reset_task_pending, 0); atomic_set(&cp->reset_task_pending_all, 0); atomic_set(&cp->reset_task_pending_spare, 0); atomic_set(&cp->reset_task_pending_mtu, 0); #endif INIT_WORK(&cp->reset_task, cas_reset_task); /* Default link parameters */ if (link_mode >= 0 && link_mode < 6) cp->link_cntl = link_modes[link_mode]; else cp->link_cntl = BMCR_ANENABLE; cp->lstate = link_down; cp->link_transition = LINK_TRANSITION_LINK_DOWN; netif_carrier_off(cp->dev); cp->timer_ticks = 0; /* give us access to cassini registers */ cp->regs = pci_iomap(pdev, 0, casreg_len); if (!cp->regs) { dev_err(&pdev->dev, "Cannot map device registers, aborting\n"); goto err_out_free_res; } cp->casreg_len = casreg_len; pci_save_state(pdev); cas_check_pci_invariants(cp); cas_hard_reset(cp); cas_reset(cp, 0); if (cas_check_invariants(cp)) goto err_out_iounmap; if (cp->cas_flags & CAS_FLAG_SATURN) cas_saturn_firmware_init(cp); cp->init_block = (struct cas_init_block *) pci_alloc_consistent(pdev, sizeof(struct cas_init_block), &cp->block_dvma); if (!cp->init_block) { dev_err(&pdev->dev, "Cannot allocate init block, aborting\n"); goto err_out_iounmap; } for (i = 0; i < N_TX_RINGS; i++) cp->init_txds[i] = cp->init_block->txds[i]; for (i = 0; i < N_RX_DESC_RINGS; i++) cp->init_rxds[i] = cp->init_block->rxds[i]; for (i = 0; i < N_RX_COMP_RINGS; i++) cp->init_rxcs[i] = cp->init_block->rxcs[i]; for (i = 0; i < N_RX_FLOWS; i++) skb_queue_head_init(&cp->rx_flows[i]); dev->netdev_ops = &cas_netdev_ops; dev->ethtool_ops = &cas_ethtool_ops; dev->watchdog_timeo = CAS_TX_TIMEOUT; #ifdef USE_NAPI netif_napi_add(dev, &cp->napi, cas_poll, 64); #endif dev->irq = pdev->irq; dev->dma = 0; /* Cassini features. */ if ((cp->cas_flags & CAS_FLAG_NO_HW_CSUM) == 0) dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG; if (pci_using_dac) dev->features |= NETIF_F_HIGHDMA; if (register_netdev(dev)) { dev_err(&pdev->dev, "Cannot register net device, aborting\n"); goto err_out_free_consistent; } i = readl(cp->regs + REG_BIM_CFG); netdev_info(dev, "Sun Cassini%s (%sbit/%sMHz PCI/%s) Ethernet[%d] %pM\n", (cp->cas_flags & CAS_FLAG_REG_PLUS) ? "+" : "", (i & BIM_CFG_32BIT) ? "32" : "64", (i & BIM_CFG_66MHZ) ? "66" : "33", (cp->phy_type == CAS_PHY_SERDES) ? "Fi" : "Cu", pdev->irq, dev->dev_addr); pci_set_drvdata(pdev, dev); cp->hw_running = 1; cas_entropy_reset(cp); cas_phy_init(cp); cas_begin_auto_negotiation(cp, NULL); return 0; err_out_free_consistent: pci_free_consistent(pdev, sizeof(struct cas_init_block), cp->init_block, cp->block_dvma); err_out_iounmap: mutex_lock(&cp->pm_mutex); if (cp->hw_running) cas_shutdown(cp); mutex_unlock(&cp->pm_mutex); pci_iounmap(pdev, cp->regs); err_out_free_res: pci_release_regions(pdev); err_write_cacheline: /* Try to restore it in case the error occurred after we * set it. */ pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, orig_cacheline_size); err_out_free_netdev: free_netdev(dev); err_out_disable_pdev: pci_disable_device(pdev); return -ENODEV; } static void cas_remove_one(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct cas *cp; if (!dev) return; cp = netdev_priv(dev); unregister_netdev(dev); if (cp->fw_data) vfree(cp->fw_data); mutex_lock(&cp->pm_mutex); cancel_work_sync(&cp->reset_task); if (cp->hw_running) cas_shutdown(cp); mutex_unlock(&cp->pm_mutex); #if 1 if (cp->orig_cacheline_size) { /* Restore the cache line size if we had modified * it. */ pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, cp->orig_cacheline_size); } #endif pci_free_consistent(pdev, sizeof(struct cas_init_block), cp->init_block, cp->block_dvma); pci_iounmap(pdev, cp->regs); free_netdev(dev); pci_release_regions(pdev); pci_disable_device(pdev); } #ifdef CONFIG_PM static int cas_suspend(struct pci_dev *pdev, pm_message_t state) { struct net_device *dev = pci_get_drvdata(pdev); struct cas *cp = netdev_priv(dev); unsigned long flags; mutex_lock(&cp->pm_mutex); /* If the driver is opened, we stop the DMA */ if (cp->opened) { netif_device_detach(dev); cas_lock_all_save(cp, flags); /* We can set the second arg of cas_reset to 0 * because on resume, we'll call cas_init_hw with * its second arg set so that autonegotiation is * restarted. */ cas_reset(cp, 0); cas_clean_rings(cp); cas_unlock_all_restore(cp, flags); } if (cp->hw_running) cas_shutdown(cp); mutex_unlock(&cp->pm_mutex); return 0; } static int cas_resume(struct pci_dev *pdev) { struct net_device *dev = pci_get_drvdata(pdev); struct cas *cp = netdev_priv(dev); netdev_info(dev, "resuming\n"); mutex_lock(&cp->pm_mutex); cas_hard_reset(cp); if (cp->opened) { unsigned long flags; cas_lock_all_save(cp, flags); cas_reset(cp, 0); cp->hw_running = 1; cas_clean_rings(cp); cas_init_hw(cp, 1); cas_unlock_all_restore(cp, flags); netif_device_attach(dev); } mutex_unlock(&cp->pm_mutex); return 0; } #endif /* CONFIG_PM */ static struct pci_driver cas_driver = { .name = DRV_MODULE_NAME, .id_table = cas_pci_tbl, .probe = cas_init_one, .remove = cas_remove_one, #ifdef CONFIG_PM .suspend = cas_suspend, .resume = cas_resume #endif }; static int __init cas_init(void) { if (linkdown_timeout > 0) link_transition_timeout = linkdown_timeout * HZ; else link_transition_timeout = 0; return pci_register_driver(&cas_driver); } static void __exit cas_cleanup(void) { pci_unregister_driver(&cas_driver); } module_init(cas_init); module_exit(cas_cleanup);
gpl-2.0
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/this-side-up/32.d.ts
63
import { ThisSideUp32 } from "../../"; export = ThisSideUp32;
mit
subash-a/DefinitelyTyped
facebook-js-sdk/index.d.ts
2970
// Type definitions for the Facebook Javascript SDK // Project: https://developers.facebook.com/docs/javascript // Definitions by: Amrit Kahlon <https://github.com/amritk/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import fb = facebook; declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { api: any; AppEvents: any; Canvas: any; Event: any; /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. * * @param callback function to handle the response. */ getAuthResponse(callback: (response: AuthResponse) => void): void; /** * FB.getLoginStatus() allows you to determine if a user is * logged in to Facebook and has authenticated your app. * * @param callback function to handle the response. */ getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * * @param params params for the initialization. */ init(params: InitParams): void; /** * Use this function to log the user in * * Calling FB.login() results in the JS SDK attempting to open a popup window. * As such, this method should only be called after a user click event, otherwise * the popup window will be blocked by most browsers. * * @param callback function to handle the response. * @param options optional ILoginOption to add params such as scope. */ login(callback: (response: AuthResponse) => void, options?: LoginOptions): void; /** * The method FB.logout() logs the user out of your site and, in some cases, Facebook. * * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; ui: any; XFBML: any; } interface InitParams { appId: string; version?: string; cookie?: boolean; status?: boolean; xfbml?: boolean; frictionlessRequests?: boolean; hideFlashCallback?: boolean; } interface LoginOptions { auth_type?: string; scope?: string; return_scopes?: boolean; enable_profile_selector?: boolean; profile_selector_ids?: string; } //////////////////////// // // RESPONSES // //////////////////////// interface AuthResponse { status: string; authResponse: { accessToken: string; expiresIn: number; signedRequest: string; userID: string; } } }
mit
kairyan/ramda
test/add.js
287
var assert = require('assert'); var R = require('..'); describe('add', function() { it('adds together two numbers', function() { assert.strictEqual(R.add(3, 7), 10); }); it('is curried', function() { var incr = R.add(1); assert.strictEqual(incr(42), 43); }); });
mit
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/send-to-back/32.d.ts
63
import { SendToBack32 } from "../../"; export = SendToBack32;
mit
bashrc/hubzilla-debian
src/library/intl/src/Language/LanguageRepository.php
2786
<?php namespace CommerceGuys\Intl\Language; use CommerceGuys\Intl\LocaleResolverTrait; use CommerceGuys\Intl\Exception\UnknownLanguageException; /** * Manages languages based on JSON definitions. */ class LanguageRepository implements LanguageRepositoryInterface { use LocaleResolverTrait; /** * Per-locale language definitions. * * @var array */ protected $definitions = array(); /** * Creates a LanguageRepository instance. * * @param string $definitionPath The path to the currency definitions. * Defaults to 'resources/language'. */ public function __construct($definitionPath = null) { $this->definitionPath = $definitionPath ? $definitionPath : __DIR__ . '/../../resources/language/'; } /** * {@inheritdoc} */ public function get($languageCode, $locale = null, $fallbackLocale = null) { $locale = $this->resolveLocale($locale, $fallbackLocale); $definitions = $this->loadDefinitions($locale); if (!isset($definitions[$languageCode])) { throw new UnknownLanguageException($languageCode); } return $this->createLanguageFromDefinition($definitions[$languageCode], $locale); } /** * {@inheritdoc} */ public function getAll($locale = null, $fallbackLocale = null) { $locale = $this->resolveLocale($locale, $fallbackLocale); $definitions = $this->loadDefinitions($locale); $languages = array(); foreach ($definitions as $languageCode => $definition) { $languages[$languageCode] = $this->createLanguageFromDefinition($definition, $locale); } return $languages; } /** * Loads the language definitions for the provided locale. * * @param string $locale The desired locale. * * @return array */ protected function loadDefinitions($locale) { if (!isset($this->definitions[$locale])) { $filename = $this->definitionPath . $locale . '.json'; $this->definitions[$locale] = json_decode(file_get_contents($filename), true); } return $this->definitions[$locale]; } /** * Creates a language object from the provided definition. * * @param array $definition The language definition. * @param string $locale The locale of the language definition. * * @return Language */ protected function createLanguageFromDefinition(array $definition, $locale) { $language = new Language(); $language->setLanguageCode($definition['code']); $language->setName($definition['name']); $language->setLocale($locale); return $language; } }
mit
markogresak/DefinitelyTyped
types/carbon__icons-react/lib/wind-gusts/24.d.ts
61
import { WindGusts24 } from "../../"; export = WindGusts24;
mit
evansj/openhab
bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/adapter/TrimToNullStringAdapter.java
1031
/** * Copyright (c) 2010-2016, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.homematic.internal.model.adapter; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.apache.commons.lang.StringUtils; /** * JAXB Adapter to trim a string value to null. * * @author Gerhard Riegler * @since 1.5.0 */ public class TrimToNullStringAdapter extends XmlAdapter<String, Object> { /** * {@inheritDoc} */ @Override public Object unmarshal(String value) throws Exception { return StringUtils.trimToNull(value); } /** * {@inheritDoc} */ @Override public String marshal(Object value) throws Exception { if (value == null) { return null; } return value.toString(); } }
epl-1.0
reuk/waveguide
wayverb/JuceLibraryCode/modules/juce_gui_basics/layout/juce_ComponentBuilder.cpp
8800
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ namespace ComponentBuilderHelpers { static String getStateId (const ValueTree& state) { return state [ComponentBuilder::idProperty].toString(); } static Component* removeComponentWithID (OwnedArray<Component>& components, const String& compId) { jassert (compId.isNotEmpty()); for (int i = components.size(); --i >= 0;) { Component* const c = components.getUnchecked (i); if (c->getComponentID() == compId) return components.removeAndReturn (i); } return nullptr; } static Component* findComponentWithID (Component& c, const String& compId) { jassert (compId.isNotEmpty()); if (c.getComponentID() == compId) return &c; for (int i = c.getNumChildComponents(); --i >= 0;) if (Component* const child = findComponentWithID (*c.getChildComponent (i), compId)) return child; return nullptr; } static Component* createNewComponent (ComponentBuilder::TypeHandler& type, const ValueTree& state, Component* parent) { Component* const c = type.addNewComponentFromState (state, parent); jassert (c != nullptr && c->getParentComponent() == parent); c->setComponentID (getStateId (state)); return c; } static void updateComponent (ComponentBuilder& builder, const ValueTree& state) { if (Component* topLevelComp = builder.getManagedComponent()) { ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state); const String uid (getStateId (state)); if (type == nullptr || uid.isEmpty()) { // ..handle the case where a child of the actual state node has changed. if (state.getParent().isValid()) updateComponent (builder, state.getParent()); } else { if (Component* const changedComp = findComponentWithID (*topLevelComp, uid)) type->updateComponentFromState (changedComp, state); } } } } //============================================================================== const Identifier ComponentBuilder::idProperty ("id"); ComponentBuilder::ComponentBuilder() : imageProvider (nullptr) { } ComponentBuilder::ComponentBuilder (const ValueTree& state_) : state (state_), imageProvider (nullptr) { state.addListener (this); } ComponentBuilder::~ComponentBuilder() { state.removeListener (this); #if JUCE_DEBUG // Don't delete the managed component!! The builder owns that component, and will delete // it automatically when it gets deleted. jassert (componentRef.get() == static_cast<Component*> (component)); #endif } Component* ComponentBuilder::getManagedComponent() { if (component == nullptr) { component = createComponent(); #if JUCE_DEBUG componentRef = component; #endif } return component; } Component* ComponentBuilder::createComponent() { jassert (types.size() > 0); // You need to register all the necessary types before you can load a component! if (TypeHandler* const type = getHandlerForState (state)) return ComponentBuilderHelpers::createNewComponent (*type, state, nullptr); jassertfalse; // trying to create a component from an unknown type of ValueTree return nullptr; } void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type) { jassert (type != nullptr); // Don't try to move your types around! Once a type has been added to a builder, the // builder owns it, and you should leave it alone! jassert (type->builder == nullptr); types.add (type); type->builder = this; } ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const { const Identifier targetType (s.getType()); for (int i = 0; i < types.size(); ++i) { TypeHandler* const t = types.getUnchecked(i); if (t->type == targetType) return t; } return nullptr; } int ComponentBuilder::getNumHandlers() const noexcept { return types.size(); } ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const noexcept { return types [index]; } void ComponentBuilder::registerStandardComponentTypes() { Drawable::registerDrawableTypeHandlers (*this); } void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) noexcept { imageProvider = newImageProvider; } ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const noexcept { return imageProvider; } void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&, int) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree, int, int) { ComponentBuilderHelpers::updateComponent (*this, tree); } void ComponentBuilder::valueTreeParentChanged (ValueTree& tree) { ComponentBuilderHelpers::updateComponent (*this, tree); } //============================================================================== ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType) : type (valueTreeType), builder (nullptr) { } ComponentBuilder::TypeHandler::~TypeHandler() { } ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const noexcept { // A type handler needs to be registered with a ComponentBuilder before using it! jassert (builder != nullptr); return builder; } void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children) { using namespace ComponentBuilderHelpers; const int numExistingChildComps = parent.getNumChildComponents(); Array<Component*> componentsInOrder; componentsInOrder.ensureStorageAllocated (numExistingChildComps); { OwnedArray<Component> existingComponents; existingComponents.ensureStorageAllocated (numExistingChildComps); for (int i = 0; i < numExistingChildComps; ++i) existingComponents.add (parent.getChildComponent (i)); const int newNumChildren = children.getNumChildren(); for (int i = 0; i < newNumChildren; ++i) { const ValueTree childState (children.getChild (i)); Component* c = removeComponentWithID (existingComponents, getStateId (childState)); if (c == nullptr) { if (TypeHandler* const type = getHandlerForState (childState)) c = ComponentBuilderHelpers::createNewComponent (*type, childState, &parent); else jassertfalse; } if (c != nullptr) componentsInOrder.add (c); } // (remaining unused items in existingComponents get deleted here as it goes out of scope) } // Make sure the z-order is correct.. if (componentsInOrder.size() > 0) { componentsInOrder.getLast()->toFront (false); for (int i = componentsInOrder.size() - 1; --i >= 0;) componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1)); } }
gpl-2.0
Lehkeda/android_kernel_samsung_mint2g
drivers/video/spreadtrum/lcd_hx8369.c
7918
/* * Copyright (C) 2012 Spreadtrum Communications Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/delay.h> #include "lcdpanel.h" static int32_t hx8369_init(struct panel_spec *self) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; /* SET password */ send_cmd(0xB9); send_data(0xFF); send_data(0x83); send_data(0x69); /* Set Power */ send_cmd(0xB1); send_data(0x9D); send_data(0x00); send_data(0x34); send_data(0x07); send_data(0x00); send_data(0x0B); send_data(0x0B); send_data(0x1A); send_data(0x22); send_data(0x3F); send_data(0x3F); send_data(0x01); send_data(0x23); send_data(0x01); send_data(0xE6); send_data(0xE6); send_data(0xE6); send_data(0xE6); send_data(0xE6); /* SET Display 480x800 */ send_cmd(0xB2); send_data(0x00); send_data(0x20); send_data(0x03); send_data(0x03); send_data(0x70); send_data(0x00); send_data(0xFF); send_data(0x00); send_data(0x00); send_data(0x00); send_data(0x00); send_data(0x03); send_data(0x03); send_data(0x00); send_data(0x01); /* SET Display 480x800 */ send_cmd(0xB4); send_data(0x00); send_data(0x18); send_data(0x80); send_data(0x06); send_data(0x02); /* OSC */ send_cmd(0xB0); send_data(0x00); send_data(0x09); /*05 42HZ 07 50HZ 0B 100% 67HZ */ /* SET VCOM */ send_cmd(0xB6); send_data(0x4A); send_data(0x4A); /* SET GIP */ send_cmd(0xD5); send_data(0x00); send_data(0x03); send_data(0x03); send_data(0x00); send_data(0x01); send_data(0x02); send_data(0x28); send_data(0x70); send_data(0x11); send_data(0x13); send_data(0x00); send_data(0x00); send_data(0x40); send_data(0x06); send_data(0x51); send_data(0x07); send_data(0x00); send_data(0x00); send_data(0x41); send_data(0x06); send_data(0x50); send_data(0x07); send_data(0x07); send_data(0x0F); send_data(0x04); send_data(0x00); /* Set Gamma */ send_cmd(0xE0); send_data(0x00); send_data(0x01); send_data(0x04); send_data(0x23); send_data(0x22); send_data(0x3F); send_data(0x13); send_data(0x39); send_data(0x06); send_data(0x0B); send_data(0x0E); send_data(0x12); send_data(0x15); send_data(0x13); send_data(0x15); send_data(0x13); send_data(0x1B); send_data(0x00); send_data(0x01); send_data(0x04); send_data(0x23); send_data(0x22); send_data(0x3F); send_data(0x13); send_data(0x39); send_data(0x06); send_data(0x0B); send_data(0x0E); send_data(0x12); send_data(0x15); send_data(0x13); send_data(0x15); send_data(0x13); send_data(0x1B); send_cmd(0x35); /* TE on*/ send_data(0x00); /* set CSEL */ send_cmd(0x3A); send_data(0x07); /* CSEL=0x06, 16bit-color CSEL=0x06, 18bit-color CSEL=0x07, 24bit-color */ /*24 bit don't need to set 2DH*/ /* Sleep Out */ send_cmd(0x11); LCD_DelayMS(120); #if 0 { /* for test the lcd */ int i; send_cmd(0x2C); //Write data for (i = 0; i < 480*800/3; i++) send_data(0xff); for (i = 0; i < 480*800/3; i++) send_data(0xff00); for (i = 0; i < 480*800/3; i++) send_data(0xff0000); } #endif /* Display On */ send_cmd(0x29); LCD_DelayMS (120); /* Write data */ send_cmd(0x2C); return 0; } static int32_t hx8369_set_window(struct panel_spec *self, uint16_t left, uint16_t top, uint16_t right, uint16_t bottom) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; pr_debug("hx8369_set_window:%d, %d, %d, %d\n", left, top, right, bottom); /* col */ send_cmd(0x2A); send_data((left >> 8)); send_data((left & 0xFF)); send_data((right >> 8)); send_data((right & 0xFF)); /* row */ send_cmd(0x2B); send_data((top >> 8)); send_data((top & 0xFF)); send_data((bottom >> 8)); send_data((bottom & 0xFF)); /* Write data */ send_cmd(0x2C); return 0; } static int32_t hx8369_invalidate(struct panel_spec *self) { return self->ops->panel_set_window(self, 0, 0, self->width-1, self->height-1); } static int32_t hx8369_invalidate_rect(struct panel_spec *self, uint16_t left, uint16_t top, uint16_t right, uint16_t bottom) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; pr_debug("hx8369_invalidate_rect\n"); /* TE scanline */ send_cmd(0x44); send_data((top >> 8)); send_data((top & 0xFF)); return self->ops->panel_set_window(self, left, top, right, bottom); } static int32_t hx8369_set_direction(struct panel_spec *self, uint16_t direction) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; pr_debug("hx8369_set_direction\n"); send_cmd(0x36); switch (direction) { case LCD_DIRECT_NORMAL: send_data(0); break; case LCD_DIRECT_ROT_90: send_data(0xA0); break; case LCD_DIRECT_ROT_180: send_data(0x60); break; case LCD_DIRECT_ROT_270: send_data(0xB0); break; case LCD_DIRECT_MIR_H: send_data(0x40); break; case LCD_DIRECT_MIR_V: send_data(0x10); break; case LCD_DIRECT_MIR_HV: send_data(0xE0); break; default: pr_debug("unknown lcd direction!\n"); send_data(0x0); direction = LCD_DIRECT_NORMAL; break; } self->direction = direction; return 0; } static int32_t hx8369_enter_sleep(struct panel_spec *self, uint8_t is_sleep) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; if(is_sleep) { /* Sleep In */ send_cmd(0x28); LCD_DelayMS(120); send_cmd(0x10); LCD_DelayMS(120); } else { #if 1 /* Sleep Out */ send_cmd(0x11); LCD_DelayMS(120); send_cmd(0x29); LCD_DelayMS(120); #else /* re init */ se1f->ops->reset(self); se1f->ops->lcd_init(self); #endif } return 0; } static uint32_t hx8369_read_id(struct panel_spec *self) { send_data_t send_cmd = self->info.mcu->ops->send_cmd; send_data_t send_data = self->info.mcu->ops->send_data; read_data_t read_data = self->info.mcu->ops->read_data; send_cmd(0xB9); send_data(0xFF); send_data(0x83); send_data(0x69); send_cmd(0xF4); read_data(); return read_data(); } static struct panel_operations lcd_hx8369_operations = { .panel_init = hx8369_init, .panel_set_window = hx8369_set_window, .panel_invalidate = hx8369_invalidate, .panel_invalidate_rect = hx8369_invalidate_rect, .panel_set_direction = hx8369_set_direction, .panel_enter_sleep = hx8369_enter_sleep, .panel_readid = hx8369_read_id, }; static struct timing_mcu lcd_hx8369_timing[] = { [LCD_REGISTER_TIMING] = { /* read/write register timing (ns) */ .rcss = 25, /* 25 ns */ .rlpw = 70, .rhpw = 70, .wcss = 10, .wlpw = 50, .whpw = 50, }, [LCD_GRAM_TIMING] = { /* read/write gram timing (ns) */ .rcss = 25, .rlpw = 70, .rhpw = 70, .wcss = 0, .wlpw = 15, .whpw = 24, } }; static struct info_mcu lcd_hx8369_info = { .bus_mode = LCD_BUS_8080, .bus_width = 24, .timing = lcd_hx8369_timing, .ops = NULL, }; struct panel_spec lcd_hx8369_spec = { #ifdef CONFIG_FB_LCD_HX8369_HVGA_TEST .width = 320, .height = 480, #else .width = 480, .height = 800, #endif .mode = LCD_MODE_MCU, .direction = LCD_DIRECT_NORMAL, .info = { .mcu = &lcd_hx8369_info, }, .ops = &lcd_hx8369_operations, }; struct panel_cfg lcd_hx8369 = { /* this panel may on both CS0/1 */ .lcd_cs = -1, .lcd_id = 0x69, .lcd_name = "lcd_hx8369", .panel = &lcd_hx8369_spec, }; static int __init lcd_hx8369_init(void) { return sprd_register_panel(&lcd_hx8369); } subsys_initcall(lcd_hx8369_init);
gpl-2.0
AlexanderDolgan/sputnik
wp-content/themes/node_modules/gulp.spritesmith/node_modules/url2/test/url2-spec.js
2582
var URL = require("../url2"); var tests = [ { source: "", target: "", relative: "" }, { source: "foo/bar/", target: "foo/bar/", relative: "" }, { source: "foo/bar/baz", target: "foo/bar/", relative: "./" }, { source: "foo/bar/", target: "/foo/bar/", relative: "/foo/bar/" }, { source: "/foo/bar/baz", target: "/foo/bar/quux", relative: "quux" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/asdf", relative: "quux/asdf" }, { source: "/foo/bar/baz", target: "/foo/bar/quux/baz", relative: "quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz", relative: "../quux/baz" }, { source: "/foo/bar/baz", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?a=10", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "/foo/bar/baz?b=20", target: "/foo/quux/baz?a=10", relative: "../quux/baz?a=10" }, { source: "http://example.com", target: "/foo/bar", relative: "/foo/bar" }, { source: "", target: "http://example.com/foo/bar", relative: "http://example.com/foo/bar" }, { source: "", target: "#foo", relative: "#foo" }, { source: "", target: "?a=10", relative: "?a=10" }, { source: "?a=10", target: "#foo", relative: "?a=10#foo" }, { source: "file:///test.js", target: "file:///test.js", relative: "test.js" }, { source: "file:///test.js", target: "file:///test/test.js", relative: "test/test.js" } ]; describe("relative", function () { tests.forEach(function (test) { (test.focus ? iit : it)( test.label || ( "from " + JSON.stringify(test.source) + " " + "to " + JSON.stringify(test.target) ), function () { expect(URL.relative(test.source, test.target)) .toBe(test.relative) } ) }); it("should format a url with a path property", function () { expect(URL.format({path: "a/b"})).toEqual("a/b"); expect(URL.format({path: "a/b?c=d"})).toEqual("a/b?c=d"); }); });
gpl-2.0
ghmajx/asuswrt-merlin
release/src/router/madwimax-0.1.1/src/tap_dev.h
1321
/* * This is a reverse-engineered driver for mobile WiMAX (802.16e) devices * based on Samsung CMC-730 chip. * Copyright (C) 2008-2009 Alexander Gordeev <lasaine@lvk.cs.msu.su> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _TUN_DEV_H #define _TUN_DEV_H int tap_open(char *dev); int tap_close(int fd, char *dev); int tap_write(int fd, const void *buf, int len); int tap_read(int fd, void *buf, int len); int tap_set_hwaddr(int fd, const char *dev, unsigned char *hwaddr); int tap_set_mtu(int fd, const char *dev, int mtu); int tap_bring_up(int fd, const char *dev); int tap_bring_down(int fd, const char *dev); #endif // _TUN_DEV_H
gpl-2.0
gsambrotta/discourse
lib/freedom_patches/raw_handlebars.rb
2215
# barber patches to re-route raw compilation via ember compat handlebars class Barber::Precompiler def sources [File.open("#{Rails.root}/vendor/assets/javascripts/handlebars.js"), precompiler] end def precompiler if !@precompiler source = File.read("#{Rails.root}/app/assets/javascripts/discourse-common/lib/raw-handlebars.js.es6") template = Tilt::ES6ModuleTranspilerTemplate.new {} transpiled = template.babel_transpile(source) # very hacky but lets us use ES6. I'm ashamed of this code -RW transpiled.gsub!(/^export .*$/, '') @precompiler = StringIO.new <<END var __RawHandlebars; (function() { #{transpiled}; __RawHandlebars = RawHandlebars; })(); Barber = { precompile: function(string) { return __RawHandlebars.precompile(string, false).toString(); } }; END end @precompiler end end module Discourse module Ember module Handlebars module Helper def precompile_handlebars(string) "require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});" end def compile_handlebars(string) "require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});" end end end end end class Ember::Handlebars::Template include Discourse::Ember::Handlebars::Helper def precompile_handlebars(string, input=nil) "require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});" end def compile_handlebars(string, input=nil) "require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});" end def global_template_target(namespace, module_name, config) "#{namespace}[#{template_path(module_name, config).inspect}]" end # FIXME: Previously, ember-handlebars-templates uses the logical path which incorrectly # returned paths with the `.raw` extension and our code is depending on the `.raw` # to find the right template to use. def actual_name(input) actual_name = input[:name] input[:filename].include?('.raw') ? "#{actual_name}.raw" : actual_name end end
gpl-2.0
philip-sorokin/joomla-cms
tests/unit/suites/libraries/joomla/linkedin/JLinkedinCommunicationsTest.php
10137
<?php /** * @package Joomla.UnitTest * @subpackage Linkedin * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JLinkedinCommunications. * * @package Joomla.UnitTest * @subpackage Linkedin * * @since 13.1 */ class JLinkedinCommunicationsTest extends TestCase { /** * @var JRegistry Options for the Linkedin object. * @since 13.1 */ protected $options; /** * @var JHttp Mock http object. * @since 13.1 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 13.1 */ protected $input; /** * @var JLinkedinCommunications Object under test. * @since 13.1 */ protected $object; /** * @var JLinkedinOAuth Authentication object for the Twitter object. * @since 13.1 */ protected $oauth; /** * @var string Sample JSON string. * @since 13.1 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON error message. * @since 13.1 */ protected $errorString = '{"errorCode":401, "message": "Generic error"}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void */ protected function setUp() { parent::setUp(); $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php"; $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input); $this->oauth->setToken(array('key' => $key, 'secret' => $secret)); $this->object = new JLinkedinCommunications($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); parent::tearDown(); } /** * Tests the inviteByEmail method * * @return void * * @since 13.1 */ public function testInviteByEmail() { $email = 'example@domain.com'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/email=' . $email . '"> <first-name>' . $first_name . '</first-name> <last-name>' . $last_name . '</last-name> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection), $this->equalTo($returnData) ); } /** * Tests the inviteByEmail method - failure * * @return void * * @expectedException DomainException * @since 13.1 */ public function testInviteByEmailFailure() { $email = 'example@domain.com'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/email=' . $email . '"> <first-name>' . $first_name . '</first-name> <last-name>' . $last_name . '</last-name> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection); } /** * Tests the inviteById method * * @return void * * @since 13.1 */ public function testInviteById() { $id = 'lcnIwDU0S6'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $name = 'NAME_SEARCH'; $value = 'mwjY'; $path = '/v1/people-search:(people:(api-standard-profile-request))'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = '{"apiStandardProfileRequest": {"headers": {"_total": 1,"values": [{"name": "x-li-auth-token","value": "' . $name . ':' . $value . '"}]}}}'; $data['format'] = 'json'; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/id=' . $id . '"> </person> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> <item-content> <invitation-request> <connect-type>' . $connection . '</connect-type> <authorization> <name>' . $name . '</name> <value>' . $value . '</value> </authorization> </invitation-request> </item-content> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->at(1)) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection), $this->equalTo($returnData) ); } /** * Tests the inviteById method - failure * * @return void * * @expectedException RuntimeException * @since 13.1 */ public function testInviteByIdFailure() { $id = 'lcnIwDU0S6'; $first_name = 'Frist'; $last_name = 'Last'; $subject = 'Subject'; $body = 'body'; $connection = 'friend'; $path = '/v1/people-search:(people:(api-standard-profile-request))'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $data['format'] = 'json'; $data['first-name'] = $first_name; $data['last-name'] = $last_name; $path = $this->oauth->toUrl($path, $data); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection); } /** * Tests the sendMessage method * * @return void * * @since 13.1 */ public function testSendMessage() { $recipient = array('~', 'lcnIwDU0S6'); $subject = 'Subject'; $body = 'body'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/~"/> </recipient> <recipient> <person path="/people/lcnIwDU0S6"/> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 201; $returnData->body = $this->sampleString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->sendMessage($recipient, $subject, $body), $this->equalTo($returnData) ); } /** * Tests the sendMessage method - failure * * @return void * * @expectedException DomainException * @since 13.1 */ public function testSendMessageFailure() { $recipient = array('~', 'lcnIwDU0S6'); $subject = 'Subject'; $body = 'body'; $path = '/v1/people/~/mailbox'; // Build the xml. $xml = '<mailbox-item> <recipients> <recipient> <person path="/people/~"/> </recipient> <recipient> <person path="/people/lcnIwDU0S6"/> </recipient> </recipients> <subject>' . $subject . '</subject> <body>' . $body . '</body> </mailbox-item>'; $header['Content-Type'] = 'text/xml'; $returnData = new stdClass; $returnData->code = 401; $returnData->body = $this->errorString; $this->client->expects($this->once()) ->method('post', $xml, $header) ->with($path) ->will($this->returnValue($returnData)); $this->object->sendMessage($recipient, $subject, $body); } }
gpl-2.0
gazoo74/linux
drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c
24143
/* * Copyright 2012 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include <linux/pci.h> #include <linux/acpi.h> #include <linux/slab.h> #include <linux/power_supply.h> #include <linux/pm_runtime.h> #include <acpi/video.h> #include <drm/drmP.h> #include <drm/drm_crtc_helper.h> #include "amdgpu.h" #include "amdgpu_pm.h" #include "amdgpu_display.h" #include "amd_acpi.h" #include "atom.h" struct amdgpu_atif_notification_cfg { bool enabled; int command_code; }; struct amdgpu_atif_notifications { bool thermal_state; bool forced_power_state; bool system_power_state; bool brightness_change; bool dgpu_display_event; bool gpu_package_power_limit; }; struct amdgpu_atif_functions { bool system_params; bool sbios_requests; bool temperature_change; bool query_backlight_transfer_characteristics; bool ready_to_undock; bool external_gpu_information; }; struct amdgpu_atif { acpi_handle handle; struct amdgpu_atif_notifications notifications; struct amdgpu_atif_functions functions; struct amdgpu_atif_notification_cfg notification_cfg; struct amdgpu_encoder *encoder_for_bl; struct amdgpu_dm_backlight_caps backlight_caps; }; /* Call the ATIF method */ /** * amdgpu_atif_call - call an ATIF method * * @handle: acpi handle * @function: the ATIF function to execute * @params: ATIF function params * * Executes the requested ATIF function (all asics). * Returns a pointer to the acpi output buffer. */ static union acpi_object *amdgpu_atif_call(struct amdgpu_atif *atif, int function, struct acpi_buffer *params) { acpi_status status; union acpi_object atif_arg_elements[2]; struct acpi_object_list atif_arg; struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; atif_arg.count = 2; atif_arg.pointer = &atif_arg_elements[0]; atif_arg_elements[0].type = ACPI_TYPE_INTEGER; atif_arg_elements[0].integer.value = function; if (params) { atif_arg_elements[1].type = ACPI_TYPE_BUFFER; atif_arg_elements[1].buffer.length = params->length; atif_arg_elements[1].buffer.pointer = params->pointer; } else { /* We need a second fake parameter */ atif_arg_elements[1].type = ACPI_TYPE_INTEGER; atif_arg_elements[1].integer.value = 0; } status = acpi_evaluate_object(atif->handle, NULL, &atif_arg, &buffer); /* Fail only if calling the method fails and ATIF is supported */ if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) { DRM_DEBUG_DRIVER("failed to evaluate ATIF got %s\n", acpi_format_exception(status)); kfree(buffer.pointer); return NULL; } return buffer.pointer; } /** * amdgpu_atif_parse_notification - parse supported notifications * * @n: supported notifications struct * @mask: supported notifications mask from ATIF * * Use the supported notifications mask from ATIF function * ATIF_FUNCTION_VERIFY_INTERFACE to determine what notifications * are supported (all asics). */ static void amdgpu_atif_parse_notification(struct amdgpu_atif_notifications *n, u32 mask) { n->thermal_state = mask & ATIF_THERMAL_STATE_CHANGE_REQUEST_SUPPORTED; n->forced_power_state = mask & ATIF_FORCED_POWER_STATE_CHANGE_REQUEST_SUPPORTED; n->system_power_state = mask & ATIF_SYSTEM_POWER_SOURCE_CHANGE_REQUEST_SUPPORTED; n->brightness_change = mask & ATIF_PANEL_BRIGHTNESS_CHANGE_REQUEST_SUPPORTED; n->dgpu_display_event = mask & ATIF_DGPU_DISPLAY_EVENT_SUPPORTED; n->gpu_package_power_limit = mask & ATIF_GPU_PACKAGE_POWER_LIMIT_REQUEST_SUPPORTED; } /** * amdgpu_atif_parse_functions - parse supported functions * * @f: supported functions struct * @mask: supported functions mask from ATIF * * Use the supported functions mask from ATIF function * ATIF_FUNCTION_VERIFY_INTERFACE to determine what functions * are supported (all asics). */ static void amdgpu_atif_parse_functions(struct amdgpu_atif_functions *f, u32 mask) { f->system_params = mask & ATIF_GET_SYSTEM_PARAMETERS_SUPPORTED; f->sbios_requests = mask & ATIF_GET_SYSTEM_BIOS_REQUESTS_SUPPORTED; f->temperature_change = mask & ATIF_TEMPERATURE_CHANGE_NOTIFICATION_SUPPORTED; f->query_backlight_transfer_characteristics = mask & ATIF_QUERY_BACKLIGHT_TRANSFER_CHARACTERISTICS_SUPPORTED; f->ready_to_undock = mask & ATIF_READY_TO_UNDOCK_NOTIFICATION_SUPPORTED; f->external_gpu_information = mask & ATIF_GET_EXTERNAL_GPU_INFORMATION_SUPPORTED; } /** * amdgpu_atif_verify_interface - verify ATIF * * @handle: acpi handle * @atif: amdgpu atif struct * * Execute the ATIF_FUNCTION_VERIFY_INTERFACE ATIF function * to initialize ATIF and determine what features are supported * (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atif_verify_interface(struct amdgpu_atif *atif) { union acpi_object *info; struct atif_verify_interface output; size_t size; int err = 0; info = amdgpu_atif_call(atif, ATIF_FUNCTION_VERIFY_INTERFACE, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 12) { DRM_INFO("ATIF buffer is too small: %zu\n", size); err = -EINVAL; goto out; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); /* TODO: check version? */ DRM_DEBUG_DRIVER("ATIF version %u\n", output.version); amdgpu_atif_parse_notification(&atif->notifications, output.notification_mask); amdgpu_atif_parse_functions(&atif->functions, output.function_bits); out: kfree(info); return err; } static acpi_handle amdgpu_atif_probe_handle(acpi_handle dhandle) { acpi_handle handle = NULL; char acpi_method_name[255] = { 0 }; struct acpi_buffer buffer = { sizeof(acpi_method_name), acpi_method_name }; acpi_status status; /* For PX/HG systems, ATIF and ATPX are in the iGPU's namespace, on dGPU only * systems, ATIF is in the dGPU's namespace. */ status = acpi_get_handle(dhandle, "ATIF", &handle); if (ACPI_SUCCESS(status)) goto out; if (amdgpu_has_atpx()) { status = acpi_get_handle(amdgpu_atpx_get_dhandle(), "ATIF", &handle); if (ACPI_SUCCESS(status)) goto out; } DRM_DEBUG_DRIVER("No ATIF handle found\n"); return NULL; out: acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer); DRM_DEBUG_DRIVER("Found ATIF handle %s\n", acpi_method_name); return handle; } /** * amdgpu_atif_get_notification_params - determine notify configuration * * @handle: acpi handle * @n: atif notification configuration struct * * Execute the ATIF_FUNCTION_GET_SYSTEM_PARAMETERS ATIF function * to determine if a notifier is used and if so which one * (all asics). This is either Notify(VGA, 0x81) or Notify(VGA, n) * where n is specified in the result if a notifier is used. * Returns 0 on success, error on failure. */ static int amdgpu_atif_get_notification_params(struct amdgpu_atif *atif) { union acpi_object *info; struct amdgpu_atif_notification_cfg *n = &atif->notification_cfg; struct atif_system_params params; size_t size; int err = 0; info = amdgpu_atif_call(atif, ATIF_FUNCTION_GET_SYSTEM_PARAMETERS, NULL); if (!info) { err = -EIO; goto out; } size = *(u16 *) info->buffer.pointer; if (size < 10) { err = -EINVAL; goto out; } memset(&params, 0, sizeof(params)); size = min(sizeof(params), size); memcpy(&params, info->buffer.pointer, size); DRM_DEBUG_DRIVER("SYSTEM_PARAMS: mask = %#x, flags = %#x\n", params.flags, params.valid_mask); params.flags = params.flags & params.valid_mask; if ((params.flags & ATIF_NOTIFY_MASK) == ATIF_NOTIFY_NONE) { n->enabled = false; n->command_code = 0; } else if ((params.flags & ATIF_NOTIFY_MASK) == ATIF_NOTIFY_81) { n->enabled = true; n->command_code = 0x81; } else { if (size < 11) { err = -EINVAL; goto out; } n->enabled = true; n->command_code = params.command_code; } out: DRM_DEBUG_DRIVER("Notification %s, command code = %#x\n", (n->enabled ? "enabled" : "disabled"), n->command_code); kfree(info); return err; } /** * amdgpu_atif_query_backlight_caps - get min and max backlight input signal * * @handle: acpi handle * * Execute the QUERY_BRIGHTNESS_TRANSFER_CHARACTERISTICS ATIF function * to determine the acceptable range of backlight values * * Backlight_caps.caps_valid will be set to true if the query is successful * * The input signals are in range 0-255 * * This function assumes the display with backlight is the first LCD * * Returns 0 on success, error on failure. */ static int amdgpu_atif_query_backlight_caps(struct amdgpu_atif *atif) { union acpi_object *info; struct atif_qbtc_output characteristics; struct atif_qbtc_arguments arguments; struct acpi_buffer params; size_t size; int err = 0; arguments.size = sizeof(arguments); arguments.requested_display = ATIF_QBTC_REQUEST_LCD1; params.length = sizeof(arguments); params.pointer = (void *)&arguments; info = amdgpu_atif_call(atif, ATIF_FUNCTION_QUERY_BRIGHTNESS_TRANSFER_CHARACTERISTICS, &params); if (!info) { err = -EIO; goto out; } size = *(u16 *) info->buffer.pointer; if (size < 10) { err = -EINVAL; goto out; } memset(&characteristics, 0, sizeof(characteristics)); size = min(sizeof(characteristics), size); memcpy(&characteristics, info->buffer.pointer, size); atif->backlight_caps.caps_valid = true; atif->backlight_caps.min_input_signal = characteristics.min_input_signal; atif->backlight_caps.max_input_signal = characteristics.max_input_signal; out: kfree(info); return err; } /** * amdgpu_atif_get_sbios_requests - get requested sbios event * * @handle: acpi handle * @req: atif sbios request struct * * Execute the ATIF_FUNCTION_GET_SYSTEM_BIOS_REQUESTS ATIF function * to determine what requests the sbios is making to the driver * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atif_get_sbios_requests(struct amdgpu_atif *atif, struct atif_sbios_requests *req) { union acpi_object *info; size_t size; int count = 0; info = amdgpu_atif_call(atif, ATIF_FUNCTION_GET_SYSTEM_BIOS_REQUESTS, NULL); if (!info) return -EIO; size = *(u16 *)info->buffer.pointer; if (size < 0xd) { count = -EINVAL; goto out; } memset(req, 0, sizeof(*req)); size = min(sizeof(*req), size); memcpy(req, info->buffer.pointer, size); DRM_DEBUG_DRIVER("SBIOS pending requests: %#x\n", req->pending); count = hweight32(req->pending); out: kfree(info); return count; } /** * amdgpu_atif_handler - handle ATIF notify requests * * @adev: amdgpu_device pointer * @event: atif sbios request struct * * Checks the acpi event and if it matches an atif event, * handles it. * * Returns: * NOTIFY_BAD or NOTIFY_DONE, depending on the event. */ static int amdgpu_atif_handler(struct amdgpu_device *adev, struct acpi_bus_event *event) { struct amdgpu_atif *atif = adev->atif; int count; DRM_DEBUG_DRIVER("event, device_class = %s, type = %#x\n", event->device_class, event->type); if (strcmp(event->device_class, ACPI_VIDEO_CLASS) != 0) return NOTIFY_DONE; /* Is this actually our event? */ if (!atif || !atif->notification_cfg.enabled || event->type != atif->notification_cfg.command_code) { /* These events will generate keypresses otherwise */ if (event->type == ACPI_VIDEO_NOTIFY_PROBE) return NOTIFY_BAD; else return NOTIFY_DONE; } if (atif->functions.sbios_requests) { struct atif_sbios_requests req; /* Check pending SBIOS requests */ count = amdgpu_atif_get_sbios_requests(atif, &req); if (count <= 0) return NOTIFY_BAD; DRM_DEBUG_DRIVER("ATIF: %d pending SBIOS requests\n", count); /* todo: add DC handling */ if ((req.pending & ATIF_PANEL_BRIGHTNESS_CHANGE_REQUEST) && !amdgpu_device_has_dc_support(adev)) { struct amdgpu_encoder *enc = atif->encoder_for_bl; if (enc) { struct amdgpu_encoder_atom_dig *dig = enc->enc_priv; DRM_DEBUG_DRIVER("Changing brightness to %d\n", req.backlight_level); amdgpu_display_backlight_set_level(adev, enc, req.backlight_level); #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) || defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE) backlight_force_update(dig->bl_dev, BACKLIGHT_UPDATE_HOTKEY); #endif } } if (req.pending & ATIF_DGPU_DISPLAY_EVENT) { if (adev->flags & AMD_IS_PX) { pm_runtime_get_sync(adev->ddev->dev); /* Just fire off a uevent and let userspace tell us what to do */ drm_helper_hpd_irq_event(adev->ddev); pm_runtime_mark_last_busy(adev->ddev->dev); pm_runtime_put_autosuspend(adev->ddev->dev); } } /* TODO: check other events */ } /* We've handled the event, stop the notifier chain. The ACPI interface * overloads ACPI_VIDEO_NOTIFY_PROBE, we don't want to send that to * userspace if the event was generated only to signal a SBIOS * request. */ return NOTIFY_BAD; } /* Call the ATCS method */ /** * amdgpu_atcs_call - call an ATCS method * * @handle: acpi handle * @function: the ATCS function to execute * @params: ATCS function params * * Executes the requested ATCS function (all asics). * Returns a pointer to the acpi output buffer. */ static union acpi_object *amdgpu_atcs_call(acpi_handle handle, int function, struct acpi_buffer *params) { acpi_status status; union acpi_object atcs_arg_elements[2]; struct acpi_object_list atcs_arg; struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; atcs_arg.count = 2; atcs_arg.pointer = &atcs_arg_elements[0]; atcs_arg_elements[0].type = ACPI_TYPE_INTEGER; atcs_arg_elements[0].integer.value = function; if (params) { atcs_arg_elements[1].type = ACPI_TYPE_BUFFER; atcs_arg_elements[1].buffer.length = params->length; atcs_arg_elements[1].buffer.pointer = params->pointer; } else { /* We need a second fake parameter */ atcs_arg_elements[1].type = ACPI_TYPE_INTEGER; atcs_arg_elements[1].integer.value = 0; } status = acpi_evaluate_object(handle, "ATCS", &atcs_arg, &buffer); /* Fail only if calling the method fails and ATIF is supported */ if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) { DRM_DEBUG_DRIVER("failed to evaluate ATCS got %s\n", acpi_format_exception(status)); kfree(buffer.pointer); return NULL; } return buffer.pointer; } /** * amdgpu_atcs_parse_functions - parse supported functions * * @f: supported functions struct * @mask: supported functions mask from ATCS * * Use the supported functions mask from ATCS function * ATCS_FUNCTION_VERIFY_INTERFACE to determine what functions * are supported (all asics). */ static void amdgpu_atcs_parse_functions(struct amdgpu_atcs_functions *f, u32 mask) { f->get_ext_state = mask & ATCS_GET_EXTERNAL_STATE_SUPPORTED; f->pcie_perf_req = mask & ATCS_PCIE_PERFORMANCE_REQUEST_SUPPORTED; f->pcie_dev_rdy = mask & ATCS_PCIE_DEVICE_READY_NOTIFICATION_SUPPORTED; f->pcie_bus_width = mask & ATCS_SET_PCIE_BUS_WIDTH_SUPPORTED; } /** * amdgpu_atcs_verify_interface - verify ATCS * * @handle: acpi handle * @atcs: amdgpu atcs struct * * Execute the ATCS_FUNCTION_VERIFY_INTERFACE ATCS function * to initialize ATCS and determine what features are supported * (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atcs_verify_interface(acpi_handle handle, struct amdgpu_atcs *atcs) { union acpi_object *info; struct atcs_verify_interface output; size_t size; int err = 0; info = amdgpu_atcs_call(handle, ATCS_FUNCTION_VERIFY_INTERFACE, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 8) { DRM_INFO("ATCS buffer is too small: %zu\n", size); err = -EINVAL; goto out; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); /* TODO: check version? */ DRM_DEBUG_DRIVER("ATCS version %u\n", output.version); amdgpu_atcs_parse_functions(&atcs->functions, output.function_bits); out: kfree(info); return err; } /** * amdgpu_acpi_is_pcie_performance_request_supported * * @adev: amdgpu_device pointer * * Check if the ATCS pcie_perf_req and pcie_dev_rdy methods * are supported (all asics). * returns true if supported, false if not. */ bool amdgpu_acpi_is_pcie_performance_request_supported(struct amdgpu_device *adev) { struct amdgpu_atcs *atcs = &adev->atcs; if (atcs->functions.pcie_perf_req && atcs->functions.pcie_dev_rdy) return true; return false; } /** * amdgpu_acpi_pcie_notify_device_ready * * @adev: amdgpu_device pointer * * Executes the PCIE_DEVICE_READY_NOTIFICATION method * (all asics). * returns 0 on success, error on failure. */ int amdgpu_acpi_pcie_notify_device_ready(struct amdgpu_device *adev) { acpi_handle handle; union acpi_object *info; struct amdgpu_atcs *atcs = &adev->atcs; /* Get the device handle */ handle = ACPI_HANDLE(&adev->pdev->dev); if (!handle) return -EINVAL; if (!atcs->functions.pcie_dev_rdy) return -EINVAL; info = amdgpu_atcs_call(handle, ATCS_FUNCTION_PCIE_DEVICE_READY_NOTIFICATION, NULL); if (!info) return -EIO; kfree(info); return 0; } /** * amdgpu_acpi_pcie_performance_request * * @adev: amdgpu_device pointer * @perf_req: requested perf level (pcie gen speed) * @advertise: set advertise caps flag if set * * Executes the PCIE_PERFORMANCE_REQUEST method to * change the pcie gen speed (all asics). * returns 0 on success, error on failure. */ int amdgpu_acpi_pcie_performance_request(struct amdgpu_device *adev, u8 perf_req, bool advertise) { acpi_handle handle; union acpi_object *info; struct amdgpu_atcs *atcs = &adev->atcs; struct atcs_pref_req_input atcs_input; struct atcs_pref_req_output atcs_output; struct acpi_buffer params; size_t size; u32 retry = 3; if (amdgpu_acpi_pcie_notify_device_ready(adev)) return -EINVAL; /* Get the device handle */ handle = ACPI_HANDLE(&adev->pdev->dev); if (!handle) return -EINVAL; if (!atcs->functions.pcie_perf_req) return -EINVAL; atcs_input.size = sizeof(struct atcs_pref_req_input); /* client id (bit 2-0: func num, 7-3: dev num, 15-8: bus num) */ atcs_input.client_id = adev->pdev->devfn | (adev->pdev->bus->number << 8); atcs_input.valid_flags_mask = ATCS_VALID_FLAGS_MASK; atcs_input.flags = ATCS_WAIT_FOR_COMPLETION; if (advertise) atcs_input.flags |= ATCS_ADVERTISE_CAPS; atcs_input.req_type = ATCS_PCIE_LINK_SPEED; atcs_input.perf_req = perf_req; params.length = sizeof(struct atcs_pref_req_input); params.pointer = &atcs_input; while (retry--) { info = amdgpu_atcs_call(handle, ATCS_FUNCTION_PCIE_PERFORMANCE_REQUEST, &params); if (!info) return -EIO; memset(&atcs_output, 0, sizeof(atcs_output)); size = *(u16 *) info->buffer.pointer; if (size < 3) { DRM_INFO("ATCS buffer is too small: %zu\n", size); kfree(info); return -EINVAL; } size = min(sizeof(atcs_output), size); memcpy(&atcs_output, info->buffer.pointer, size); kfree(info); switch (atcs_output.ret_val) { case ATCS_REQUEST_REFUSED: default: return -EINVAL; case ATCS_REQUEST_COMPLETE: return 0; case ATCS_REQUEST_IN_PROGRESS: udelay(10); break; } } return 0; } /** * amdgpu_acpi_event - handle notify events * * @nb: notifier block * @val: val * @data: acpi event * * Calls relevant amdgpu functions in response to various * acpi events. * Returns NOTIFY code */ static int amdgpu_acpi_event(struct notifier_block *nb, unsigned long val, void *data) { struct amdgpu_device *adev = container_of(nb, struct amdgpu_device, acpi_nb); struct acpi_bus_event *entry = (struct acpi_bus_event *)data; if (strcmp(entry->device_class, ACPI_AC_CLASS) == 0) { if (power_supply_is_system_supplied() > 0) DRM_DEBUG_DRIVER("pm: AC\n"); else DRM_DEBUG_DRIVER("pm: DC\n"); amdgpu_pm_acpi_event_handler(adev); } /* Check for pending SBIOS requests */ return amdgpu_atif_handler(adev, entry); } /* Call all ACPI methods here */ /** * amdgpu_acpi_init - init driver acpi support * * @adev: amdgpu_device pointer * * Verifies the AMD ACPI interfaces and registers with the acpi * notifier chain (all asics). * Returns 0 on success, error on failure. */ int amdgpu_acpi_init(struct amdgpu_device *adev) { acpi_handle handle, atif_handle; struct amdgpu_atif *atif; struct amdgpu_atcs *atcs = &adev->atcs; int ret; /* Get the device handle */ handle = ACPI_HANDLE(&adev->pdev->dev); if (!adev->bios || !handle) return 0; /* Call the ATCS method */ ret = amdgpu_atcs_verify_interface(handle, atcs); if (ret) { DRM_DEBUG_DRIVER("Call to ATCS verify_interface failed: %d\n", ret); } /* Probe for ATIF, and initialize it if found */ atif_handle = amdgpu_atif_probe_handle(handle); if (!atif_handle) goto out; atif = kzalloc(sizeof(*atif), GFP_KERNEL); if (!atif) { DRM_WARN("Not enough memory to initialize ATIF\n"); goto out; } atif->handle = atif_handle; /* Call the ATIF method */ ret = amdgpu_atif_verify_interface(atif); if (ret) { DRM_DEBUG_DRIVER("Call to ATIF verify_interface failed: %d\n", ret); kfree(atif); goto out; } adev->atif = atif; if (atif->notifications.brightness_change) { struct drm_encoder *tmp; /* Find the encoder controlling the brightness */ list_for_each_entry(tmp, &adev->ddev->mode_config.encoder_list, head) { struct amdgpu_encoder *enc = to_amdgpu_encoder(tmp); if ((enc->devices & (ATOM_DEVICE_LCD_SUPPORT)) && enc->enc_priv) { struct amdgpu_encoder_atom_dig *dig = enc->enc_priv; if (dig->bl_dev) { atif->encoder_for_bl = enc; break; } } } } if (atif->functions.sbios_requests && !atif->functions.system_params) { /* XXX check this workraround, if sbios request function is * present we have to see how it's configured in the system * params */ atif->functions.system_params = true; } if (atif->functions.system_params) { ret = amdgpu_atif_get_notification_params(atif); if (ret) { DRM_DEBUG_DRIVER("Call to GET_SYSTEM_PARAMS failed: %d\n", ret); /* Disable notification */ atif->notification_cfg.enabled = false; } } if (atif->functions.query_backlight_transfer_characteristics) { ret = amdgpu_atif_query_backlight_caps(atif); if (ret) { DRM_DEBUG_DRIVER("Call to QUERY_BACKLIGHT_TRANSFER_CHARACTERISTICS failed: %d\n", ret); atif->backlight_caps.caps_valid = false; } } else { atif->backlight_caps.caps_valid = false; } out: adev->acpi_nb.notifier_call = amdgpu_acpi_event; register_acpi_notifier(&adev->acpi_nb); return ret; } void amdgpu_acpi_get_backlight_caps(struct amdgpu_device *adev, struct amdgpu_dm_backlight_caps *caps) { if (!adev->atif) { caps->caps_valid = false; return; } caps->caps_valid = adev->atif->backlight_caps.caps_valid; caps->min_input_signal = adev->atif->backlight_caps.min_input_signal; caps->max_input_signal = adev->atif->backlight_caps.max_input_signal; } /** * amdgpu_acpi_fini - tear down driver acpi support * * @adev: amdgpu_device pointer * * Unregisters with the acpi notifier chain (all asics). */ void amdgpu_acpi_fini(struct amdgpu_device *adev) { unregister_acpi_notifier(&adev->acpi_nb); kfree(adev->atif); }
gpl-2.0
JonnyH/pandora-kernel
arch/s390/kernel/asm-offsets.c
1704
/* * Generate definitions needed by assembly language modules. * This code generates raw asm output which is post-processed to extract * and format the required data. */ #include <linux/sched.h> #include <linux/kbuild.h> int main(void) { DEFINE(__THREAD_info, offsetof(struct task_struct, stack)); DEFINE(__THREAD_ksp, offsetof(struct task_struct, thread.ksp)); DEFINE(__THREAD_per, offsetof(struct task_struct, thread.per_info)); DEFINE(__THREAD_mm_segment, offsetof(struct task_struct, thread.mm_segment)); BLANK(); DEFINE(__TASK_pid, offsetof(struct task_struct, pid)); BLANK(); DEFINE(__PER_atmid, offsetof(per_struct, lowcore.words.perc_atmid)); DEFINE(__PER_address, offsetof(per_struct, lowcore.words.address)); DEFINE(__PER_access_id, offsetof(per_struct, lowcore.words.access_id)); BLANK(); DEFINE(__TI_task, offsetof(struct thread_info, task)); DEFINE(__TI_domain, offsetof(struct thread_info, exec_domain)); DEFINE(__TI_flags, offsetof(struct thread_info, flags)); DEFINE(__TI_cpu, offsetof(struct thread_info, cpu)); DEFINE(__TI_precount, offsetof(struct thread_info, preempt_count)); BLANK(); DEFINE(__PT_ARGS, offsetof(struct pt_regs, args)); DEFINE(__PT_PSW, offsetof(struct pt_regs, psw)); DEFINE(__PT_GPRS, offsetof(struct pt_regs, gprs)); DEFINE(__PT_ORIG_GPR2, offsetof(struct pt_regs, orig_gpr2)); DEFINE(__PT_ILC, offsetof(struct pt_regs, ilc)); DEFINE(__PT_TRAP, offsetof(struct pt_regs, trap)); DEFINE(__PT_SIZE, sizeof(struct pt_regs)); BLANK(); DEFINE(__SF_BACKCHAIN, offsetof(struct stack_frame, back_chain)); DEFINE(__SF_GPRS, offsetof(struct stack_frame, gprs)); DEFINE(__SF_EMPTY, offsetof(struct stack_frame, empty1)); return 0; }
gpl-2.0
duvall/android_kernel_samsung_smdk4412
drivers/net/wireless/bcmdhd/dhd_sdio.c
255126
/* * DHD Bus Module for SDIO * * Copyright (C) 1999-2012, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: dhd_sdio.c 404381 2013-05-26 05:00:59Z $ */ #include <typedefs.h> #include <osl.h> #include <bcmsdh.h> #ifdef BCMEMBEDIMAGE #include BCMEMBEDIMAGE #endif /* BCMEMBEDIMAGE */ #include <bcmdefs.h> #include <bcmutils.h> #include <bcmendian.h> #include <bcmdevs.h> #include <siutils.h> #include <hndpmu.h> #include <hndsoc.h> #include <bcmsdpcm.h> #if defined(DHD_DEBUG) #include <hndrte_armtrap.h> #include <hndrte_cons.h> #endif /* defined(DHD_DEBUG) */ #include <sbchipc.h> #include <sbhnddma.h> #include <sdio.h> #ifdef BCMSPI #include <spid.h> #endif /* BCMSPI */ #include <sbsdio.h> #include <sbsdpcmdev.h> #include <bcmsdpcm.h> #include <bcmsdbus.h> #include <proto/ethernet.h> #include <proto/802.1d.h> #include <proto/802.11.h> #include <dngl_stats.h> #include <dhd.h> #include <dhd_bus.h> #include <dhd_proto.h> #include <dhd_dbg.h> #include <dhdioctl.h> #include <sdiovar.h> #ifndef DHDSDIO_MEM_DUMP_FNAME #define DHDSDIO_MEM_DUMP_FNAME "mem_dump" #endif #define QLEN 256 /* bulk rx and tx queue lengths */ #define FCHI (QLEN - 10) #define FCLOW (FCHI / 2) #define PRIOMASK 7 #define TXRETRIES 2 /* # of retries for tx frames */ #ifndef DHD_RXBOUND #define DHD_RXBOUND 50 /* Default for max rx frames in one scheduling */ #endif #ifndef DHD_TXBOUND #define DHD_TXBOUND 20 /* Default for max tx frames in one scheduling */ #endif #define DHD_TXMINMAX 1 /* Max tx frames if rx still pending */ #define MEMBLOCK 2048 /* Block size used for downloading of dongle image */ #define MAX_NVRAMBUF_SIZE 4096 /* max nvram buf size */ #define MAX_DATA_BUF (32 * 1024) /* Must be large enough to hold biggest possible glom */ #ifndef DHD_FIRSTREAD #define DHD_FIRSTREAD 32 #endif #if !ISPOWEROF2(DHD_FIRSTREAD) #error DHD_FIRSTREAD is not a power of 2! #endif #ifdef BCMSDIOH_TXGLOM /* Total length of TX frame header for dongle protocol */ #define SDPCM_HDRLEN (SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN + SDPCM_SWHEADER_LEN) /* Total length of RX frame for dongle protocol */ #else /* Total length of TX frame header for dongle protocol */ #define SDPCM_HDRLEN (SDPCM_FRAMETAG_LEN + SDPCM_SWHEADER_LEN) #endif #define SDPCM_HDRLEN_RX (SDPCM_FRAMETAG_LEN + SDPCM_SWHEADER_LEN) #ifdef SDTEST #define SDPCM_RESERVE (SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + DHD_SDALIGN) #else #define SDPCM_RESERVE (SDPCM_HDRLEN + DHD_SDALIGN) #endif /* Space for header read, limit for data packets */ #ifndef MAX_HDR_READ #define MAX_HDR_READ 32 #endif #if !ISPOWEROF2(MAX_HDR_READ) #error MAX_HDR_READ is not a power of 2! #endif #define MAX_RX_DATASZ 2048 /* Maximum milliseconds to wait for F2 to come up */ #define DHD_WAIT_F2RDY 3000 /* Bump up limit on waiting for HT to account for first startup; * if the image is doing a CRC calculation before programming the PMU * for HT availability, it could take a couple hundred ms more, so * max out at a 1 second (1000000us). */ #if (PMU_MAX_TRANSITION_DLY <= 1000000) #undef PMU_MAX_TRANSITION_DLY #define PMU_MAX_TRANSITION_DLY 1000000 #endif /* Value for ChipClockCSR during initial setup */ #define DHD_INIT_CLKCTL1 (SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ) #define DHD_INIT_CLKCTL2 (SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP) /* Flags for SDH calls */ #define F2SYNC (SDIO_REQ_4BYTE | SDIO_REQ_FIXED) /* Packet free applicable unconditionally for sdio and sdspi. Conditional if * bufpool was present for gspi bus. */ #define PKTFREE2() if ((bus->bus != SPI_BUS) || bus->usebufpool) \ PKTFREE(bus->dhd->osh, pkt, FALSE); DHD_SPINWAIT_SLEEP_INIT(sdioh_spinwait_sleep); #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) extern void bcmsdh_set_irq(int flag); #endif /* defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) */ #ifdef PROP_TXSTATUS extern void dhd_wlfc_txcomplete(dhd_pub_t *dhd, void *txp, bool success); extern void dhd_wlfc_trigger_pktcommit(dhd_pub_t *dhd); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) DEFINE_MUTEX(_dhd_sdio_mutex_lock_); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) */ #ifdef DHD_DEBUG /* Device console log buffer state */ #define CONSOLE_LINE_MAX 192 #define CONSOLE_BUFFER_MAX 2024 typedef struct dhd_console { uint count; /* Poll interval msec counter */ uint log_addr; /* Log struct address (fixed) */ hndrte_log_t log; /* Log struct (host copy) */ uint bufsize; /* Size of log buffer */ uint8 *buf; /* Log buffer (host copy) */ uint last; /* Last buffer read index */ } dhd_console_t; #endif /* DHD_DEBUG */ #define REMAP_ENAB(bus) ((bus)->remap) #define REMAP_ISADDR(bus, a) (((a) >= ((bus)->orig_ramsize)) && ((a) < ((bus)->ramsize))) #define KSO_ENAB(bus) ((bus)->kso) #define SR_ENAB(bus) ((bus)->_srenab) #define SLPAUTO_ENAB(bus) ((SR_ENAB(bus)) && ((bus)->_slpauto)) #define MIN_RSRC_ADDR (SI_ENUM_BASE + 0x618) #define MIN_RSRC_SR 0x3 #define CORE_CAPEXT_ADDR (SI_ENUM_BASE + 0x64c) #define CORE_CAPEXT_SR_SUPPORTED_MASK (1 << 1) #define RCTL_MACPHY_DISABLE_MASK (1 << 26) #define RCTL_LOGIC_DISABLE_MASK (1 << 27) #define OOB_WAKEUP_ENAB(bus) ((bus)->_oobwakeup) #define GPIO_DEV_SRSTATE 16 /* Host gpio17 mapped to device gpio0 SR state */ #define GPIO_DEV_SRSTATE_TIMEOUT 320000 /* 320ms */ #define GPIO_DEV_WAKEUP 17 /* Host gpio17 mapped to device gpio1 wakeup */ #define CC_CHIPCTRL2_GPIO1_WAKEUP (1 << 0) #define OVERFLOW_BLKSZ512_WM 48 #define OVERFLOW_BLKSZ512_MES 80 #define CC_PMUCC3 (0x3) /* Private data for SDIO bus interaction */ typedef struct dhd_bus { dhd_pub_t *dhd; bcmsdh_info_t *sdh; /* Handle for BCMSDH calls */ si_t *sih; /* Handle for SI calls */ char *vars; /* Variables (from CIS and/or other) */ uint varsz; /* Size of variables buffer */ uint32 sbaddr; /* Current SB window pointer (-1, invalid) */ sdpcmd_regs_t *regs; /* Registers for SDIO core */ uint sdpcmrev; /* SDIO core revision */ uint armrev; /* CPU core revision */ uint ramrev; /* SOCRAM core revision */ uint32 ramsize; /* Size of RAM in SOCRAM (bytes) */ uint32 orig_ramsize; /* Size of RAM in SOCRAM (bytes) */ uint32 srmemsize; /* Size of SRMEM */ uint32 bus; /* gSPI or SDIO bus */ uint32 hostintmask; /* Copy of Host Interrupt Mask */ uint32 intstatus; /* Intstatus bits (events) pending */ bool dpc_sched; /* Indicates DPC schedule (intrpt rcvd) */ bool fcstate; /* State of dongle flow-control */ uint16 cl_devid; /* cached devid for dhdsdio_probe_attach() */ char *fw_path; /* module_param: path to firmware image */ char *nv_path; /* module_param: path to nvram vars file */ const char *nvram_params; /* user specified nvram params. */ uint blocksize; /* Block size of SDIO transfers */ uint roundup; /* Max roundup limit */ struct pktq txq; /* Queue length used for flow-control */ uint8 flowcontrol; /* per prio flow control bitmask */ uint8 tx_seq; /* Transmit sequence number (next) */ uint8 tx_max; /* Maximum transmit sequence allowed */ uint8 hdrbuf[MAX_HDR_READ + DHD_SDALIGN]; uint8 *rxhdr; /* Header of current rx frame (in hdrbuf) */ uint16 nextlen; /* Next Read Len from last header */ uint8 rx_seq; /* Receive sequence number (expected) */ bool rxskip; /* Skip receive (awaiting NAK ACK) */ void *glomd; /* Packet containing glomming descriptor */ void *glom; /* Packet chain for glommed superframe */ uint glomerr; /* Glom packet read errors */ uint8 *rxbuf; /* Buffer for receiving control packets */ uint rxblen; /* Allocated length of rxbuf */ uint8 *rxctl; /* Aligned pointer into rxbuf */ uint8 *databuf; /* Buffer for receiving big glom packet */ uint8 *dataptr; /* Aligned pointer into databuf */ uint rxlen; /* Length of valid data in buffer */ uint8 sdpcm_ver; /* Bus protocol reported by dongle */ bool intr; /* Use interrupts */ bool poll; /* Use polling */ bool ipend; /* Device interrupt is pending */ bool intdis; /* Interrupts disabled by isr */ uint intrcount; /* Count of device interrupt callbacks */ uint lastintrs; /* Count as of last watchdog timer */ uint spurious; /* Count of spurious interrupts */ uint pollrate; /* Ticks between device polls */ uint polltick; /* Tick counter */ uint pollcnt; /* Count of active polls */ #ifdef DHD_DEBUG dhd_console_t console; /* Console output polling support */ uint console_addr; /* Console address from shared struct */ #endif /* DHD_DEBUG */ uint regfails; /* Count of R_REG/W_REG failures */ uint clkstate; /* State of sd and backplane clock(s) */ bool activity; /* Activity flag for clock down */ int32 idletime; /* Control for activity timeout */ int32 idlecount; /* Activity timeout counter */ int32 idleclock; /* How to set bus driver when idle */ int32 sd_divisor; /* Speed control to bus driver */ int32 sd_mode; /* Mode control to bus driver */ int32 sd_rxchain; /* If bcmsdh api accepts PKT chains */ bool use_rxchain; /* If dhd should use PKT chains */ bool sleeping; /* Is SDIO bus sleeping? */ uint rxflow_mode; /* Rx flow control mode */ bool rxflow; /* Is rx flow control on */ uint prev_rxlim_hit; /* Is prev rx limit exceeded (per dpc schedule) */ bool alp_only; /* Don't use HT clock (ALP only) */ /* Field to decide if rx of control frames happen in rxbuf or lb-pool */ bool usebufpool; #ifdef SDTEST /* external loopback */ bool ext_loop; uint8 loopid; /* pktgen configuration */ uint pktgen_freq; /* Ticks between bursts */ uint pktgen_count; /* Packets to send each burst */ uint pktgen_print; /* Bursts between count displays */ uint pktgen_total; /* Stop after this many */ uint pktgen_minlen; /* Minimum packet data len */ uint pktgen_maxlen; /* Maximum packet data len */ uint pktgen_mode; /* Configured mode: tx, rx, or echo */ uint pktgen_stop; /* Number of tx failures causing stop */ /* active pktgen fields */ uint pktgen_tick; /* Tick counter for bursts */ uint pktgen_ptick; /* Burst counter for printing */ uint pktgen_sent; /* Number of test packets generated */ uint pktgen_rcvd; /* Number of test packets received */ uint pktgen_prev_time; /* Time at which previous stats where printed */ uint pktgen_prev_sent; /* Number of test packets generated when * previous stats were printed */ uint pktgen_prev_rcvd; /* Number of test packets received when * previous stats were printed */ uint pktgen_fail; /* Number of failed send attempts */ uint16 pktgen_len; /* Length of next packet to send */ #define PKTGEN_RCV_IDLE (0) #define PKTGEN_RCV_ONGOING (1) uint16 pktgen_rcv_state; /* receive state */ uint pktgen_rcvd_rcvsession; /* test pkts rcvd per rcv session. */ #endif /* SDTEST */ /* Some additional counters */ uint tx_sderrs; /* Count of tx attempts with sd errors */ uint fcqueued; /* Tx packets that got queued */ uint rxrtx; /* Count of rtx requests (NAK to dongle) */ uint rx_toolong; /* Receive frames too long to receive */ uint rxc_errors; /* SDIO errors when reading control frames */ uint rx_hdrfail; /* SDIO errors on header reads */ uint rx_badhdr; /* Bad received headers (roosync?) */ uint rx_badseq; /* Mismatched rx sequence number */ uint fc_rcvd; /* Number of flow-control events received */ uint fc_xoff; /* Number which turned on flow-control */ uint fc_xon; /* Number which turned off flow-control */ uint rxglomfail; /* Failed deglom attempts */ uint rxglomframes; /* Number of glom frames (superframes) */ uint rxglompkts; /* Number of packets from glom frames */ uint f2rxhdrs; /* Number of header reads */ uint f2rxdata; /* Number of frame data reads */ uint f2txdata; /* Number of f2 frame writes */ uint f1regdata; /* Number of f1 register accesses */ #ifdef BCMSPI bool dwordmode; #endif /* BCMSPI */ uint8 *ctrl_frame_buf; uint32 ctrl_frame_len; bool ctrl_frame_stat; #ifndef BCMSPI uint32 rxint_mode; /* rx interrupt mode */ #endif /* BCMSPI */ bool remap; /* Contiguous 1MB RAM: 512K socram + 512K devram * Available with socram rev 16 * Remap region not DMA-able */ bool kso; bool _slpauto; bool _oobwakeup; bool _srenab; bool readframes; bool reqbussleep; uint32 resetinstr; uint32 dongle_ram_base; #ifdef BCMSDIOH_TXGLOM void *glom_pkt_arr[SDPCM_MAXGLOM_SIZE]; /* Array of pkts for glomming */ uint16 glom_cnt; /* Number of pkts in the glom array */ uint16 glom_total_len; /* Total length of pkts in glom array */ bool glom_enable; /* Flag to indicate whether tx glom is enabled/disabled */ uint8 glom_mode; /* Glom mode - 0-copy mode, 1 - Multi-descriptor mode */ uint32 glomsize; /* Glom size limitation */ #endif } dhd_bus_t; /* clkstate */ #define CLK_NONE 0 #define CLK_SDONLY 1 #define CLK_PENDING 2 /* Not used yet */ #define CLK_AVAIL 3 #define DHD_NOPMU(dhd) (FALSE) #ifdef DHD_DEBUG static int qcount[NUMPRIO]; static int tx_packets[NUMPRIO]; #endif /* DHD_DEBUG */ /* Deferred transmit */ const uint dhd_deferred_tx = 1; extern uint dhd_watchdog_ms; extern void dhd_os_wd_timer(void *bus, uint wdtick); /* Tx/Rx bounds */ uint dhd_txbound; uint dhd_rxbound; uint dhd_txminmax = DHD_TXMINMAX; /* override the RAM size if possible */ #define DONGLE_MIN_MEMSIZE (128 *1024) int dhd_dongle_memsize; #ifndef REPEAT_READFRAME static bool dhd_doflow; #else extern bool dhd_doflow; #endif /* REPEAT_READFRAME */ static bool dhd_alignctl; static bool sd1idle; static bool retrydata; #define RETRYCHAN(chan) (((chan) == SDPCM_EVENT_CHANNEL) || retrydata) #ifdef BCMSPI /* At a watermark around 8 the spid hits underflow error. */ static const uint watermark = 32; static const uint mesbusyctrl = 0; #elif defined(SDIO_CRC_ERROR_FIX) static uint watermark = 48; static uint mesbusyctrl = 80; #else static const uint watermark = 8; static const uint mesbusyctrl = 0; #endif /* BCMSPI */ static const uint firstread = DHD_FIRSTREAD; #define HDATLEN (firstread - (SDPCM_HDRLEN)) /* Retry count for register access failures */ static const uint retry_limit = 2; /* Force even SD lengths (some host controllers mess up on odd bytes) */ static bool forcealign; #define ALIGNMENT 4 #if defined(OOB_INTR_ONLY) && defined(HW_OOB) extern void bcmsdh_enable_hw_oob_intr(void *sdh, bool enable); #endif #if defined(OOB_INTR_ONLY) && defined(SDIO_ISR_THREAD) #error OOB_INTR_ONLY is NOT working with SDIO_ISR_THREAD #endif /* defined(OOB_INTR_ONLY) && defined(SDIO_ISR_THREAD) */ #define PKTALIGN(osh, p, len, align) \ do { \ uint datalign; \ datalign = (uintptr)PKTDATA((osh), (p)); \ datalign = ROUNDUP(datalign, (align)) - datalign; \ ASSERT(datalign < (align)); \ ASSERT(PKTLEN((osh), (p)) >= ((len) + datalign)); \ if (datalign) \ PKTPULL((osh), (p), datalign); \ PKTSETLEN((osh), (p), (len)); \ } while (0) /* Limit on rounding up frames */ static const uint max_roundup = 512; /* Try doing readahead */ static bool dhd_readahead; /* To check if there's window offered */ #define DATAOK(bus) \ (((uint8)(bus->tx_max - bus->tx_seq) > 1) && \ (((uint8)(bus->tx_max - bus->tx_seq) & 0x80) == 0)) /* To check if there's window offered for ctrl frame */ #define TXCTLOK(bus) \ (((uint8)(bus->tx_max - bus->tx_seq) != 0) && \ (((uint8)(bus->tx_max - bus->tx_seq) & 0x80) == 0)) /* Number of pkts available in dongle for data RX */ #define DATABUFCNT(bus) \ ((uint8)(bus->tx_max - bus->tx_seq) - 1) /* Macros to get register read/write status */ /* NOTE: these assume a local dhdsdio_bus_t *bus! */ #define R_SDREG(regvar, regaddr, retryvar) \ do { \ retryvar = 0; \ do { \ regvar = R_REG(bus->dhd->osh, regaddr); \ } while (bcmsdh_regfail(bus->sdh) && (++retryvar <= retry_limit)); \ if (retryvar) { \ bus->regfails += (retryvar-1); \ if (retryvar > retry_limit) { \ DHD_ERROR(("%s: FAILED" #regvar "READ, LINE %d\n", \ __FUNCTION__, __LINE__)); \ regvar = 0; \ } \ } \ } while (0) #define W_SDREG(regval, regaddr, retryvar) \ do { \ retryvar = 0; \ do { \ W_REG(bus->dhd->osh, regaddr, regval); \ } while (bcmsdh_regfail(bus->sdh) && (++retryvar <= retry_limit)); \ if (retryvar) { \ bus->regfails += (retryvar-1); \ if (retryvar > retry_limit) \ DHD_ERROR(("%s: FAILED REGISTER WRITE, LINE %d\n", \ __FUNCTION__, __LINE__)); \ } \ } while (0) #define BUS_WAKE(bus) \ do { \ bus->idlecount = 0; \ if ((bus)->sleeping) \ dhdsdio_bussleep((bus), FALSE); \ } while (0); /* * pktavail interrupts from dongle to host can be managed in 3 different ways * whenever there is a packet available in dongle to transmit to host. * * Mode 0: Dongle writes the software host mailbox and host is interrupted. * Mode 1: (sdiod core rev >= 4) * Device sets a new bit in the intstatus whenever there is a packet * available in fifo. Host can't clear this specific status bit until all the * packets are read from the FIFO. No need to ack dongle intstatus. * Mode 2: (sdiod core rev >= 4) * Device sets a bit in the intstatus, and host acks this by writing * one to this bit. Dongle won't generate anymore packet interrupts * until host reads all the packets from the dongle and reads a zero to * figure that there are no more packets. No need to disable host ints. * Need to ack the intstatus. */ #define SDIO_DEVICE_HMB_RXINT 0 /* default old way */ #define SDIO_DEVICE_RXDATAINT_MODE_0 1 /* from sdiod rev 4 */ #define SDIO_DEVICE_RXDATAINT_MODE_1 2 /* from sdiod rev 4 */ #ifdef BCMSPI #define FRAME_AVAIL_MASK(bus) I_HMB_FRAME_IND #define DHD_BUS SPI_BUS /* check packet-available-interrupt in piggybacked dstatus */ #define PKT_AVAILABLE(bus, intstatus) (bcmsdh_get_dstatus(bus->sdh) & STATUS_F2_PKT_AVAILABLE) #define HOSTINTMASK (I_HMB_FC_CHANGE | I_HMB_HOST_INT) #define GSPI_PR55150_BAILOUT \ do { \ uint32 dstatussw = bcmsdh_get_dstatus((void *)bus->sdh); \ uint32 dstatushw = bcmsdh_cfg_read_word(bus->sdh, SDIO_FUNC_0, SPID_STATUS_REG, NULL); \ uint32 intstatuserr = 0; \ uint retries = 0; \ \ R_SDREG(intstatuserr, &bus->regs->intstatus, retries); \ printf("dstatussw = 0x%x, dstatushw = 0x%x, intstatus = 0x%x\n", \ dstatussw, dstatushw, intstatuserr); \ \ bus->nextlen = 0; \ *finished = TRUE; \ } while (0) #else /* BCMSDIO */ #define FRAME_AVAIL_MASK(bus) \ ((bus->rxint_mode == SDIO_DEVICE_HMB_RXINT) ? I_HMB_FRAME_IND : I_XMTDATA_AVAIL) #define DHD_BUS SDIO_BUS #define PKT_AVAILABLE(bus, intstatus) ((intstatus) & (FRAME_AVAIL_MASK(bus))) #define HOSTINTMASK (I_HMB_SW_MASK | I_CHIPACTIVE) #define GSPI_PR55150_BAILOUT #endif /* BCMSPI */ #ifdef SDTEST static void dhdsdio_testrcv(dhd_bus_t *bus, void *pkt, uint seq); static void dhdsdio_sdtest_set(dhd_bus_t *bus, uint count); #endif #ifdef DHD_DEBUG static int dhdsdio_checkdied(dhd_bus_t *bus, char *data, uint size); static int dhd_serialconsole(dhd_bus_t *bus, bool get, bool enable, int *bcmerror); #endif /* DHD_DEBUG */ static int dhdsdio_devcap_set(dhd_bus_t *bus, uint8 cap); static int dhdsdio_download_state(dhd_bus_t *bus, bool enter); static void dhdsdio_release(dhd_bus_t *bus, osl_t *osh); static void dhdsdio_release_malloc(dhd_bus_t *bus, osl_t *osh); static void dhdsdio_disconnect(void *ptr); static bool dhdsdio_chipmatch(uint16 chipid); static bool dhdsdio_probe_attach(dhd_bus_t *bus, osl_t *osh, void *sdh, void * regsva, uint16 devid); static bool dhdsdio_probe_malloc(dhd_bus_t *bus, osl_t *osh, void *sdh); static bool dhdsdio_probe_init(dhd_bus_t *bus, osl_t *osh, void *sdh); static void dhdsdio_release_dongle(dhd_bus_t *bus, osl_t *osh, bool dongle_isolation, bool reset_flag); static void dhd_dongle_setmemsize(struct dhd_bus *bus, int mem_size); static int dhd_bcmsdh_recv_buf(dhd_bus_t *bus, uint32 addr, uint fn, uint flags, uint8 *buf, uint nbytes, void *pkt, bcmsdh_cmplt_fn_t complete, void *handle); static int dhd_bcmsdh_send_buf(dhd_bus_t *bus, uint32 addr, uint fn, uint flags, uint8 *buf, uint nbytes, void *pkt, bcmsdh_cmplt_fn_t complete, void *handle); #ifdef BCMSDIOH_TXGLOM static void dhd_bcmsdh_glom_post(dhd_bus_t *bus, uint8 *frame, void *pkt, uint len); static void dhd_bcmsdh_glom_clear(dhd_bus_t *bus); #endif static bool dhdsdio_download_firmware(dhd_bus_t *bus, osl_t *osh, void *sdh); static int _dhdsdio_download_firmware(dhd_bus_t *bus); static int dhdsdio_download_code_file(dhd_bus_t *bus, char *image_path); static int dhdsdio_download_nvram(dhd_bus_t *bus); #ifdef BCMEMBEDIMAGE static int dhdsdio_download_code_array(dhd_bus_t *bus); #endif static int dhdsdio_bussleep(dhd_bus_t *bus, bool sleep); static int dhdsdio_clkctl(dhd_bus_t *bus, uint target, bool pendok); static uint8 dhdsdio_sleepcsr_get(dhd_bus_t *bus); #ifdef WLMEDIA_HTSF #include <htsf.h> extern uint32 dhd_get_htsf(void *dhd, int ifidx); #endif /* WLMEDIA_HTSF */ static void dhd_overflow_war(struct dhd_bus *bus) { int err; uint8 devctl, wm, mes; /* See .ppt in PR for these recommended values */ if (bus->blocksize == 512) { wm = OVERFLOW_BLKSZ512_WM; mes = OVERFLOW_BLKSZ512_MES; } else { mes = bus->blocksize/4; wm = bus->blocksize/4; } /* Update watermark */ bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_WATERMARK, wm, &err); devctl = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); devctl |= SBSDIO_DEVCTL_F2WM_ENAB; bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, devctl, &err); /* Update MES */ bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_MESBUSYCTRL, (mes | SBSDIO_MESBUSYCTRL_ENAB), &err); DHD_INFO(("Apply overflow WAR: 0x%02x 0x%02x 0x%02x\n", bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err), bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_WATERMARK, &err), bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_MESBUSYCTRL, &err))); } static void dhd_dongle_setmemsize(struct dhd_bus *bus, int mem_size) { int32 min_size = DONGLE_MIN_MEMSIZE; /* Restrict the memsize to user specified limit */ DHD_ERROR(("user: Restrict the dongle ram size to %d, min accepted %d\n", dhd_dongle_memsize, min_size)); if ((dhd_dongle_memsize > min_size) && (dhd_dongle_memsize < (int32)bus->orig_ramsize)) bus->ramsize = dhd_dongle_memsize; } static int dhdsdio_set_siaddr_window(dhd_bus_t *bus, uint32 address) { int err = 0; bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SBADDRLOW, (address >> 8) & SBSDIO_SBADDRLOW_MASK, &err); if (!err) bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SBADDRMID, (address >> 16) & SBSDIO_SBADDRMID_MASK, &err); if (!err) bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SBADDRHIGH, (address >> 24) & SBSDIO_SBADDRHIGH_MASK, &err); return err; } #ifdef BCMSPI static void dhdsdio_wkwlan(dhd_bus_t *bus, bool on) { int err; uint32 regdata; bcmsdh_info_t *sdh = bus->sdh; if (bus->sih->buscoretype == SDIOD_CORE_ID) { /* wake up wlan function :WAKE_UP goes as ht_avail_request and alp_avail_request */ regdata = bcmsdh_cfg_read_word(sdh, SDIO_FUNC_0, SPID_CONFIG, NULL); DHD_INFO(("F0 REG0 rd = 0x%x\n", regdata)); if (on == TRUE) regdata |= WAKE_UP; else regdata &= ~WAKE_UP; bcmsdh_cfg_write_word(sdh, SDIO_FUNC_0, SPID_CONFIG, regdata, &err); } } #endif /* BCMSPI */ #ifdef USE_OOB_GPIO1 static int dhdsdio_oobwakeup_init(dhd_bus_t *bus) { uint32 val, addr, data; bcmsdh_gpioouten(bus->sdh, GPIO_DEV_WAKEUP); addr = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_addr); data = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_data); /* Set device for gpio1 wakeup */ bcmsdh_reg_write(bus->sdh, addr, 4, 2); val = bcmsdh_reg_read(bus->sdh, data, 4); val |= CC_CHIPCTRL2_GPIO1_WAKEUP; bcmsdh_reg_write(bus->sdh, data, 4, val); bus->_oobwakeup = TRUE; return 0; } #endif /* USE_OOB_GPIO1 */ #ifndef BCMSPI /* * Query if FW is in SR mode */ static bool dhdsdio_sr_cap(dhd_bus_t *bus) { bool cap = FALSE; uint32 core_capext, addr, data; if (bus->sih->chip == BCM4324_CHIP_ID) { addr = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_addr); data = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_data); bcmsdh_reg_write(bus->sdh, addr, 4, 3); core_capext = bcmsdh_reg_read(bus->sdh, data, 4); } else if (bus->sih->chip == BCM4330_CHIP_ID) { core_capext = FALSE; } else if (bus->sih->chip == BCM4335_CHIP_ID) { core_capext = TRUE; } else { core_capext = bcmsdh_reg_read(bus->sdh, CORE_CAPEXT_ADDR, 4); core_capext = (core_capext & CORE_CAPEXT_SR_SUPPORTED_MASK); } if (!(core_capext)) return FALSE; if (bus->sih->chip == BCM4324_CHIP_ID) { /* FIX: Should change to query SR control register instead */ cap = TRUE; } else if (bus->sih->chip == BCM4335_CHIP_ID) { uint32 enabval = 0; addr = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_addr); data = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_data); bcmsdh_reg_write(bus->sdh, addr, 4, CC_PMUCC3); enabval = bcmsdh_reg_read(bus->sdh, data, 4); if (enabval) cap = TRUE; } else { data = bcmsdh_reg_read(bus->sdh, SI_ENUM_BASE + OFFSETOF(chipcregs_t, retention_ctl), 4); if ((data & (RCTL_MACPHY_DISABLE_MASK | RCTL_LOGIC_DISABLE_MASK)) == 0) cap = TRUE; } return cap; } static int dhdsdio_srwar_init(dhd_bus_t *bus) { bcmsdh_gpio_init(bus->sdh); #ifdef USE_OOB_GPIO1 dhdsdio_oobwakeup_init(bus); #endif return 0; } static int dhdsdio_sr_init(dhd_bus_t *bus) { uint8 val; int err = 0; if ((bus->sih->chip == BCM4334_CHIP_ID) && (bus->sih->chiprev == 2)) dhdsdio_srwar_init(bus); val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WAKEUPCTRL, NULL); val |= 1 << SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT; bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WAKEUPCTRL, 1 << SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT, &err); val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WAKEUPCTRL, NULL); /* Add CMD14 Support */ dhdsdio_devcap_set(bus, (SDIOD_CCCR_BRCM_CARDCAP_CMD14_SUPPORT | SDIOD_CCCR_BRCM_CARDCAP_CMD14_EXT)); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, SBSDIO_FORCE_HT, &err); bus->_slpauto = dhd_slpauto ? TRUE : FALSE; bus->_srenab = TRUE; return 0; } #endif /* BCMSPI */ /* * FIX: Be sure KSO bit is enabled * Currently, it's defaulting to 0 which should be 1. */ static int dhdsdio_clk_kso_init(dhd_bus_t *bus) { uint8 val; int err = 0; /* set flag */ bus->kso = TRUE; /* * Enable KeepSdioOn (KSO) bit for normal operation * Default is 0 (4334A0) so set it. Fixed in B0. */ val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, NULL); if (!(val & SBSDIO_FUNC1_SLEEPCSR_KSO_MASK)) { val |= (SBSDIO_FUNC1_SLEEPCSR_KSO_EN << SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, val, &err); if (err) DHD_ERROR(("%s: SBSDIO_FUNC1_SLEEPCSR err: 0x%x\n", __FUNCTION__, err)); } return 0; } #define KSO_DBG(x) #define KSO_WAIT_US 50 #if defined(CUSTOMER_HW4) #define MAX_KSO_ATTEMPTS 64 #else #define MAX_KSO_ATTEMPTS (PMU_MAX_TRANSITION_DLY/KSO_WAIT_US) #endif /* CUSTOMER_HW4 */ static int dhdsdio_clk_kso_enab(dhd_bus_t *bus, bool on) { uint8 wr_val = 0, rd_val, cmp_val, bmask; int err = 0; int try_cnt = 0; KSO_DBG(("%s> op:%s\n", __FUNCTION__, (on ? "KSO_SET" : "KSO_CLR"))); wr_val |= (on << SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, wr_val, &err); if (on) { cmp_val = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK | SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK; bmask = cmp_val; msleep(3); } else { /* Put device to sleep, turn off KSO */ cmp_val = 0; bmask = SBSDIO_FUNC1_SLEEPCSR_KSO_MASK; } do { rd_val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, &err); if (((rd_val & bmask) == cmp_val) && !err) break; KSO_DBG(("%s> KSO wr/rd retry:%d, ERR:%x \n", __FUNCTION__, try_cnt, err)); OSL_DELAY(KSO_WAIT_US); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, wr_val, &err); } while (try_cnt++ < MAX_KSO_ATTEMPTS); if (try_cnt > 2) KSO_DBG(("%s> op:%s, try_cnt:%d, rd_val:%x, ERR:%x \n", __FUNCTION__, (on ? "KSO_SET" : "KSO_CLR"), try_cnt, rd_val, err)); if (try_cnt > MAX_KSO_ATTEMPTS) { DHD_ERROR(("%s> op:%s, ERROR: try_cnt:%d, rd_val:%x, ERR:%x \n", __FUNCTION__, (on ? "KSO_SET" : "KSO_CLR"), try_cnt, rd_val, err)); } return err; } static int dhdsdio_clk_kso_iovar(dhd_bus_t *bus, bool on) { int err = 0; if (on == FALSE) { BUS_WAKE(bus); dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); DHD_ERROR(("%s: KSO disable clk: 0x%x\n", __FUNCTION__, bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err))); dhdsdio_clk_kso_enab(bus, FALSE); } else { DHD_ERROR(("%s: KSO enable\n", __FUNCTION__)); /* Make sure we have SD bus access */ if (bus->clkstate == CLK_NONE) { DHD_ERROR(("%s: Request SD clk\n", __FUNCTION__)); dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); } /* Double-write to be safe in case transition of AOS */ dhdsdio_clk_kso_enab(bus, TRUE); dhdsdio_clk_kso_enab(bus, TRUE); OSL_DELAY(4000); /* Wait for device ready during transition to wake-up */ SPINWAIT(((dhdsdio_sleepcsr_get(bus)) != (SBSDIO_FUNC1_SLEEPCSR_KSO_MASK | SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK)), (10000)); DHD_ERROR(("%s: sleepcsr: 0x%x\n", __FUNCTION__, dhdsdio_sleepcsr_get(bus))); } bus->kso = on; BCM_REFERENCE(err); return 0; } static uint8 dhdsdio_sleepcsr_get(dhd_bus_t *bus) { int err = 0; uint8 val = 0; val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SLEEPCSR, &err); if (err) DHD_TRACE(("Failed to read SLEEPCSR: %d\n", err)); return val; } uint8 dhdsdio_devcap_get(dhd_bus_t *bus) { return bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_BRCM_CARDCAP, NULL); } static int dhdsdio_devcap_set(dhd_bus_t *bus, uint8 cap) { int err = 0; bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_BRCM_CARDCAP, cap, &err); if (err) DHD_ERROR(("%s: devcap set err: 0x%x\n", __FUNCTION__, err)); return 0; } static int dhdsdio_clk_devsleep_iovar(dhd_bus_t *bus, bool on) { int err = 0, retry; uint8 val; retry = 0; if (on == TRUE) { /* Enter Sleep */ /* Be sure we request clk before going to sleep * so we can wake-up with clk request already set * else device can go back to sleep immediately */ if (!SLPAUTO_ENAB(bus)) dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); else { val = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if ((val & SBSDIO_CSR_MASK) == 0) { DHD_ERROR(("%s: No clock before enter sleep:0x%x\n", __FUNCTION__, val)); /* Reset clock request */ bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, SBSDIO_ALP_AVAIL_REQ, &err); DHD_ERROR(("%s: clock before sleep:0x%x\n", __FUNCTION__, bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err))); } } DHD_TRACE(("%s: clk before sleep: 0x%x\n", __FUNCTION__, bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err))); #ifdef USE_CMD14 err = bcmsdh_sleep(bus->sdh, TRUE); #else err = dhdsdio_clk_kso_enab(bus, FALSE); if (OOB_WAKEUP_ENAB(bus)) err = bcmsdh_gpioout(bus->sdh, GPIO_DEV_WAKEUP, FALSE); /* GPIO_1 is off */ #endif } else { /* Exit Sleep */ /* Make sure we have SD bus access */ if (bus->clkstate == CLK_NONE) { DHD_TRACE(("%s: Request SD clk\n", __FUNCTION__)); dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); } if ((bus->sih->chip == BCM4334_CHIP_ID) && (bus->sih->chiprev == 2)) { SPINWAIT((bcmsdh_gpioin(bus->sdh, GPIO_DEV_SRSTATE) != TRUE), GPIO_DEV_SRSTATE_TIMEOUT); if (bcmsdh_gpioin(bus->sdh, GPIO_DEV_SRSTATE) == FALSE) { DHD_ERROR(("ERROR: GPIO_DEV_SRSTATE still low!\n")); } } #ifdef USE_CMD14 err = bcmsdh_sleep(bus->sdh, FALSE); if (SLPAUTO_ENAB(bus) && (err != 0)) { OSL_DELAY(10000); DHD_TRACE(("%s: Resync device sleep\n", __FUNCTION__)); /* Toggle sleep to resync with host and device */ err = bcmsdh_sleep(bus->sdh, TRUE); OSL_DELAY(10000); err = bcmsdh_sleep(bus->sdh, FALSE); if (err) { OSL_DELAY(10000); DHD_ERROR(("%s: CMD14 exit failed again!\n", __FUNCTION__)); /* Toggle sleep to resync with host and device */ err = bcmsdh_sleep(bus->sdh, TRUE); OSL_DELAY(10000); err = bcmsdh_sleep(bus->sdh, FALSE); if (err) { DHD_ERROR(("%s: CMD14 exit failed twice!\n", __FUNCTION__)); DHD_ERROR(("%s: FATAL: Device non-response!\n", __FUNCTION__)); err = 0; } } } #else if (OOB_WAKEUP_ENAB(bus)) err = bcmsdh_gpioout(bus->sdh, GPIO_DEV_WAKEUP, TRUE); /* GPIO_1 is on */ do { err = dhdsdio_clk_kso_enab(bus, TRUE); if (err) OSL_DELAY(10000); } while ((err != 0) && (++retry < 3)); if (err != 0) { DHD_ERROR(("ERROR: kso set failed retry: %d\n", retry)); err = 0; /* continue anyway */ } #endif /* !USE_CMD14 */ if (err == 0) { uint8 csr; /* Wait for device ready during transition to wake-up */ SPINWAIT((((csr = dhdsdio_sleepcsr_get(bus)) & SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK) != (SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK)), (20000)); DHD_TRACE(("%s: ExitSleep sleepcsr: 0x%x\n", __FUNCTION__, csr)); if (!(csr & SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK)) { DHD_ERROR(("%s:ERROR: ExitSleep device NOT Ready! 0x%x\n", __FUNCTION__, csr)); err = BCME_NODEVICE; } SPINWAIT((((csr = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err)) & SBSDIO_HT_AVAIL) != (SBSDIO_HT_AVAIL)), (10000)); } } /* Update if successful */ if (err == 0) bus->kso = on ? FALSE : TRUE; else { DHD_ERROR(("%s: Sleep request failed: on:%d err:%d\n", __FUNCTION__, on, err)); if (!on && retry > 2) bus->kso = TRUE; } return err; } /* Turn backplane clock on or off */ static int dhdsdio_htclk(dhd_bus_t *bus, bool on, bool pendok) { #define HT_AVAIL_ERROR_MAX 10 static int ht_avail_error = 0; int err; uint8 clkctl, clkreq, devctl; bcmsdh_info_t *sdh; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); clkctl = 0; sdh = bus->sdh; if (!KSO_ENAB(bus)) return BCME_OK; if (SLPAUTO_ENAB(bus)) { bus->clkstate = (on ? CLK_AVAIL : CLK_SDONLY); return BCME_OK; } if (on) { /* Request HT Avail */ clkreq = bus->alp_only ? SBSDIO_ALP_AVAIL_REQ : SBSDIO_HT_AVAIL_REQ; #ifdef BCMSPI dhdsdio_wkwlan(bus, TRUE); #endif /* BCMSPI */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err); if (err) { ht_avail_error++; if (ht_avail_error < HT_AVAIL_ERROR_MAX) { DHD_ERROR(("%s: HT Avail request error: %d\n", __FUNCTION__, err)); } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) else if (ht_avail_error == HT_AVAIL_ERROR_MAX) { dhd_os_send_hang_message(bus->dhd); } #endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27) */ return BCME_ERROR; } else { ht_avail_error = 0; } /* Check current status */ clkctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if (err) { DHD_ERROR(("%s: HT Avail read error: %d\n", __FUNCTION__, err)); return BCME_ERROR; } #if !defined(OOB_INTR_ONLY) /* Go to pending and await interrupt if appropriate */ if (!SBSDIO_CLKAV(clkctl, bus->alp_only) && pendok) { /* Allow only clock-available interrupt */ devctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); if (err) { DHD_ERROR(("%s: Devctl access error setting CA: %d\n", __FUNCTION__, err)); return BCME_ERROR; } devctl |= SBSDIO_DEVCTL_CA_INT_ONLY; bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, devctl, &err); DHD_INFO(("CLKCTL: set PENDING\n")); bus->clkstate = CLK_PENDING; return BCME_OK; } else #endif /* !defined (OOB_INTR_ONLY) */ { if (bus->clkstate == CLK_PENDING) { /* Cancel CA-only interrupt filter */ devctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY; bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, devctl, &err); } } /* Otherwise, wait here (polling) for HT Avail */ if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) { SPINWAIT_SLEEP(sdioh_spinwait_sleep, ((clkctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err)), !SBSDIO_CLKAV(clkctl, bus->alp_only)), PMU_MAX_TRANSITION_DLY); } if (err) { DHD_ERROR(("%s: HT Avail request error: %d\n", __FUNCTION__, err)); return BCME_ERROR; } if (!SBSDIO_CLKAV(clkctl, bus->alp_only)) { DHD_ERROR(("%s: HT Avail timeout (%d): clkctl 0x%02x\n", __FUNCTION__, PMU_MAX_TRANSITION_DLY, clkctl)); return BCME_ERROR; } /* Mark clock available */ bus->clkstate = CLK_AVAIL; DHD_INFO(("CLKCTL: turned ON\n")); #if defined(DHD_DEBUG) if (bus->alp_only == TRUE) { #if !defined(BCMLXSDMMC) if (!SBSDIO_ALPONLY(clkctl)) { DHD_ERROR(("%s: HT Clock, when ALP Only\n", __FUNCTION__)); } #endif /* !defined(BCMLXSDMMC) */ } else { if (SBSDIO_ALPONLY(clkctl)) { DHD_ERROR(("%s: HT Clock should be on.\n", __FUNCTION__)); } } #endif /* defined (DHD_DEBUG) */ bus->activity = TRUE; #ifdef DHD_USE_IDLECOUNT bus->idlecount = 0; #endif /* DHD_USE_IDLECOUNT */ } else { clkreq = 0; if (bus->clkstate == CLK_PENDING) { /* Cancel CA-only interrupt filter */ devctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY; bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, devctl, &err); } bus->clkstate = CLK_SDONLY; if (!SR_ENAB(bus)) { bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, clkreq, &err); DHD_INFO(("CLKCTL: turned OFF\n")); if (err) { DHD_ERROR(("%s: Failed access turning clock off: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } #ifdef BCMSPI dhdsdio_wkwlan(bus, FALSE); #endif /* BCMSPI */ } return BCME_OK; } /* Change idle/active SD state */ static int dhdsdio_sdclk(dhd_bus_t *bus, bool on) { #ifndef BCMSPI int err; int32 iovalue; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (on) { if (bus->idleclock == DHD_IDLE_STOP) { /* Turn on clock and restore mode */ iovalue = 1; err = bcmsdh_iovar_op(bus->sdh, "sd_clock", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error enabling sd_clock: %d\n", __FUNCTION__, err)); return BCME_ERROR; } iovalue = bus->sd_mode; err = bcmsdh_iovar_op(bus->sdh, "sd_mode", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error changing sd_mode: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } else if (bus->idleclock != DHD_IDLE_ACTIVE) { /* Restore clock speed */ iovalue = bus->sd_divisor; err = bcmsdh_iovar_op(bus->sdh, "sd_divisor", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error restoring sd_divisor: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } bus->clkstate = CLK_SDONLY; } else { /* Stop or slow the SD clock itself */ if ((bus->sd_divisor == -1) || (bus->sd_mode == -1)) { DHD_TRACE(("%s: can't idle clock, divisor %d mode %d\n", __FUNCTION__, bus->sd_divisor, bus->sd_mode)); return BCME_ERROR; } if (bus->idleclock == DHD_IDLE_STOP) { if (sd1idle) { /* Change to SD1 mode and turn off clock */ iovalue = 1; err = bcmsdh_iovar_op(bus->sdh, "sd_mode", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error changing sd_clock: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } iovalue = 0; err = bcmsdh_iovar_op(bus->sdh, "sd_clock", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error disabling sd_clock: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } else if (bus->idleclock != DHD_IDLE_ACTIVE) { /* Set divisor to idle value */ iovalue = bus->idleclock; err = bcmsdh_iovar_op(bus->sdh, "sd_divisor", NULL, 0, &iovalue, sizeof(iovalue), TRUE); if (err) { DHD_ERROR(("%s: error changing sd_divisor: %d\n", __FUNCTION__, err)); return BCME_ERROR; } } bus->clkstate = CLK_NONE; } #endif /* BCMSPI */ return BCME_OK; } /* Transition SD and backplane clock readiness */ static int dhdsdio_clkctl(dhd_bus_t *bus, uint target, bool pendok) { int ret = BCME_OK; #ifdef DHD_DEBUG uint oldstate = bus->clkstate; #endif /* DHD_DEBUG */ DHD_TRACE(("%s: Enter\n", __FUNCTION__)); /* Early exit if we're already there */ if (bus->clkstate == target) { if (target == CLK_AVAIL) { dhd_os_wd_timer(bus->dhd, dhd_watchdog_ms); bus->activity = TRUE; #ifdef DHD_USE_IDLECOUNT bus->idlecount = 0; #endif /* DHD_USE_IDLECOUNT */ } return ret; } switch (target) { case CLK_AVAIL: /* Make sure SD clock is available */ if (bus->clkstate == CLK_NONE) dhdsdio_sdclk(bus, TRUE); /* Now request HT Avail on the backplane */ ret = dhdsdio_htclk(bus, TRUE, pendok); if (ret == BCME_OK) { dhd_os_wd_timer(bus->dhd, dhd_watchdog_ms); bus->activity = TRUE; #ifdef DHD_USE_IDLECOUNT bus->idlecount = 0; #endif /* DHD_USE_IDLECOUNT */ } break; case CLK_SDONLY: /* Remove HT request, or bring up SD clock */ if (bus->clkstate == CLK_NONE) ret = dhdsdio_sdclk(bus, TRUE); else if (bus->clkstate == CLK_AVAIL) ret = dhdsdio_htclk(bus, FALSE, FALSE); else DHD_ERROR(("dhdsdio_clkctl: request for %d -> %d\n", bus->clkstate, target)); if (ret == BCME_OK) { dhd_os_wd_timer(bus->dhd, dhd_watchdog_ms); } break; case CLK_NONE: /* Make sure to remove HT request */ if (bus->clkstate == CLK_AVAIL) ret = dhdsdio_htclk(bus, FALSE, FALSE); /* Now remove the SD clock */ ret = dhdsdio_sdclk(bus, FALSE); #ifdef DHD_DEBUG if (dhd_console_ms == 0) #endif /* DHD_DEBUG */ if (bus->poll == 0) dhd_os_wd_timer(bus->dhd, 0); break; } #ifdef DHD_DEBUG DHD_INFO(("dhdsdio_clkctl: %d -> %d\n", oldstate, bus->clkstate)); #endif /* DHD_DEBUG */ return ret; } static int dhdsdio_bussleep(dhd_bus_t *bus, bool sleep) { int err = 0; bcmsdh_info_t *sdh = bus->sdh; sdpcmd_regs_t *regs = bus->regs; uint retries = 0; DHD_INFO(("dhdsdio_bussleep: request %s (currently %s)\n", (sleep ? "SLEEP" : "WAKE"), (bus->sleeping ? "SLEEP" : "WAKE"))); /* Done if we're already in the requested state */ if (sleep == bus->sleeping) return BCME_OK; /* Going to sleep: set the alarm and turn off the lights... */ if (sleep) { /* Don't sleep if something is pending */ #ifdef CUSTOMER_HW4 if (bus->dpc_sched || bus->rxskip || pktq_len(&bus->txq) || bus->readframes) #else if (bus->dpc_sched || bus->rxskip || pktq_len(&bus->txq)) #endif /* CUSTOMER_HW4 */ return BCME_BUSY; if (!SLPAUTO_ENAB(bus)) { /* Disable SDIO interrupts (no longer interested) */ bcmsdh_intr_disable(bus->sdh); /* Make sure the controller has the bus up */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); /* Tell device to start using OOB wakeup */ W_SDREG(SMB_USE_OOB, &regs->tosbmailbox, retries); if (retries > retry_limit) DHD_ERROR(("CANNOT SIGNAL CHIP, WILL NOT WAKE UP!!\n")); /* Turn off our contribution to the HT clock request */ dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, SBSDIO_FORCE_HW_CLKREQ_OFF, NULL); /* Isolate the bus */ if (bus->sih->chip != BCM4329_CHIP_ID && bus->sih->chip != BCM4319_CHIP_ID) { bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, SBSDIO_DEVCTL_PADS_ISO, NULL); } } else { /* Leave interrupts enabled since device can exit sleep and * interrupt host */ err = dhdsdio_clk_devsleep_iovar(bus, TRUE /* sleep */); } /* Change state */ bus->sleeping = TRUE; } else { /* Waking up: bus power up is ok, set local state */ if (!SLPAUTO_ENAB(bus)) { bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, 0, &err); /* Force pad isolation off if possible (in case power never toggled) */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, 0, NULL); /* Make sure the controller has the bus up */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); /* Send misc interrupt to indicate OOB not needed */ W_SDREG(0, &regs->tosbmailboxdata, retries); if (retries <= retry_limit) W_SDREG(SMB_DEV_INT, &regs->tosbmailbox, retries); if (retries > retry_limit) DHD_ERROR(("CANNOT SIGNAL CHIP TO CLEAR OOB!!\n")); /* Make sure we have SD bus access */ dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); /* Enable interrupts again */ if (bus->intr && (bus->dhd->busstate == DHD_BUS_DATA)) { bus->intdis = FALSE; bcmsdh_intr_enable(bus->sdh); } } else { err = dhdsdio_clk_devsleep_iovar(bus, FALSE /* wake */); } if (err == 0) { /* Change state */ bus->sleeping = FALSE; } } return err; } #if defined(CUSTOMER_HW4) && defined(USE_DYNAMIC_F2_BLKSIZE) int dhdsdio_func_blocksize(dhd_pub_t *dhd, int function_num, int block_size) { int func_blk_size = function_num; int bcmerr = 0; int result; bcmerr = dhd_bus_iovar_op(dhd, "sd_blocksize", &func_blk_size, sizeof(int), &result, sizeof(int), IOV_GET); if (bcmerr != BCME_OK) { DHD_ERROR(("%s: Get F%d Block size error\n", __FUNCTION__, function_num)); return BCME_ERROR; } if (result != block_size) { DHD_TRACE_HW4(("%s: F%d Block size set from %d to %d\n", __FUNCTION__, function_num, result, block_size)); func_blk_size = function_num << 16 | block_size; bcmerr = dhd_bus_iovar_op(dhd, "sd_blocksize", NULL, 0, &func_blk_size, sizeof(int32), IOV_SET); if (bcmerr != BCME_OK) { DHD_ERROR(("%s: Set F2 Block size error\n", __FUNCTION__)); return BCME_ERROR; } } return BCME_OK; } #endif /* CUSTOMER_HW4 && USE_DYNAMIC_F2_BLKSIZE */ #if defined(OOB_INTR_ONLY) void dhd_enable_oob_intr(struct dhd_bus *bus, bool enable) { #if defined(HW_OOB) bcmsdh_enable_hw_oob_intr(bus->sdh, enable); #else sdpcmd_regs_t *regs = bus->regs; uint retries = 0; dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); if (enable == TRUE) { /* Tell device to start using OOB wakeup */ W_SDREG(SMB_USE_OOB, &regs->tosbmailbox, retries); if (retries > retry_limit) DHD_ERROR(("CANNOT SIGNAL CHIP, WILL NOT WAKE UP!!\n")); } else { /* Send misc interrupt to indicate OOB not needed */ W_SDREG(0, &regs->tosbmailboxdata, retries); if (retries <= retry_limit) W_SDREG(SMB_DEV_INT, &regs->tosbmailbox, retries); } /* Turn off our contribution to the HT clock request */ dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); #endif /* !defined(HW_OOB) */ } #endif /* defined(OOB_INTR_ONLY) */ #ifdef DHDTCPACK_SUPPRESS extern bool dhd_use_tcpack_suppress; /* Please be sure this function is called under dhd_os_tcpacklock() */ void dhd_onoff_tcpack_sup(void *pub, bool on) { dhd_pub_t *dhdp = (dhd_pub_t *)pub; if (dhd_use_tcpack_suppress != on) { DHD_ERROR(("dhd_onoff_tcpack_sup: %d -> %d\n", dhd_use_tcpack_suppress, on)); dhd_use_tcpack_suppress = on; dhdp->tcp_ack_info_cnt = 0; bzero(dhdp->tcp_ack_info_tbl, sizeof(struct tcp_ack_info)*MAXTCPSTREAMS); } else DHD_ERROR(("dhd_onoff_tcpack_sup: alread %d\n", on)); return; } inline void dhd_tcpack_check_xmit(dhd_pub_t *dhdp, void *pkt) { uint8 i; tcp_ack_info_t *tcp_ack_info = NULL; int tbl_cnt; dhd_os_tcpacklock(dhdp); tbl_cnt = dhdp->tcp_ack_info_cnt; for (i = 0; i < tbl_cnt; i++) { tcp_ack_info = &dhdp->tcp_ack_info_tbl[i]; if (tcp_ack_info->p_tcpackinqueue == pkt) { /* This pkt is being transmitted so remove the tcp_ack_info of it. * compact the array unless the last element, * then the pkt's array is removed. */ if (i < tbl_cnt-1) { memmove(&dhdp->tcp_ack_info_tbl[i], &dhdp->tcp_ack_info_tbl[i+1], sizeof(struct tcp_ack_info)*(tbl_cnt - (i+1))); } bzero(&dhdp->tcp_ack_info_tbl[tbl_cnt-1], sizeof(struct tcp_ack_info)); if (--dhdp->tcp_ack_info_cnt < 0) { DHD_ERROR(("dhdsdio_sendfromq:(ERROR) tcp_ack_info_cnt %d" " Stop using tcpack_suppress\n", dhdp->tcp_ack_info_cnt)); dhd_onoff_tcpack_sup(dhdp, FALSE); } break; } } dhd_os_tcpackunlock(dhdp); } bool dhd_tcpack_suppress(dhd_pub_t *dhdp, void *pkt) { uint8 *eh_header; uint16 eh_type; uint8 *ip_header; uint8 *tcp_header; uint32 ip_hdr_len; uint32 cur_framelen; uint8 bdc_hdr_len = BDC_HEADER_LEN; uint8 wlfc_hdr_len = 0; uint8 *data = PKTDATA(dhdp->osh, pkt); cur_framelen = PKTLEN(dhdp->osh, pkt); #ifdef PROP_TXSTATUS /* In this case, BDC header is not pushed in dhd_sendpkt() */ if (dhdp->wlfc_state) { bdc_hdr_len = 0; wlfc_hdr_len = 8; } #endif if (cur_framelen < bdc_hdr_len + ETHER_HDR_LEN) { DHD_TRACE(("dhd_tcpack_suppress: Too short packet length %d\n", cur_framelen)); return FALSE; } /* Get rid of BDC header */ eh_header = data + bdc_hdr_len; cur_framelen -= bdc_hdr_len; eh_type = eh_header[12] << 8 | eh_header[13]; if (eh_type != ETHER_TYPE_IP) { DHD_TRACE(("dhd_tcpack_suppress: Not a IP packet 0x%x\n", eh_type)); return FALSE; } DHD_TRACE(("dhd_tcpack_suppress: IP pkt! 0x%x\n", eh_type)); ip_header = eh_header + ETHER_HDR_LEN; cur_framelen -= ETHER_HDR_LEN; ip_hdr_len = 4 * (ip_header[0] & 0x0f); if ((ip_header[0] & 0xf0) != 0x40) { DHD_TRACE(("dhd_tcpack_suppress: Not IPv4!\n")); return FALSE; } if (cur_framelen < ip_hdr_len) { DHD_ERROR(("dhd_tcpack_suppress: IP packet length %d wrong!\n", cur_framelen)); return FALSE; } /* not tcp */ if (ip_header[9] != 0x06) { DHD_TRACE(("dhd_tcpack_suppress: Not a TCP packet 0x%x\n", ip_header[9])); return FALSE; } DHD_TRACE(("dhd_tcpack_suppress: TCP pkt!\n")); tcp_header = ip_header + ip_hdr_len; /* is it an ack ? */ if (tcp_header[13] == 0x10) { #if defined(DHD_DEBUG) uint32 tcp_seq_num = tcp_header[4] << 24 | tcp_header[5] << 16 | tcp_header[6] << 8 | tcp_header[7]; #endif uint32 tcp_ack_num = tcp_header[8] << 24 | tcp_header[9] << 16 | tcp_header[10] << 8 | tcp_header[11]; uint16 ip_tcp_ttllen = (ip_header[3] & 0xff) + (ip_header[2] << 8); uint32 tcp_hdr_len = 4*((tcp_header[12] & 0xf0) >> 4); DHD_TRACE(("dhd_tcpack_suppress: TCP ACK seq %ud ack %ud\n", tcp_seq_num, tcp_ack_num)); /* zero length ? */ if (ip_tcp_ttllen == ip_hdr_len + tcp_hdr_len) { int i; tcp_ack_info_t *tcp_ack_info = NULL; DHD_TRACE(("dhd_tcpack_suppress: TCP ACK zero length\n")); /* Look for tcp_ack_info that has the same * ip src/dst addrs and tcp src/dst ports */ dhd_os_tcpacklock(dhdp); for (i = 0; i < dhdp->tcp_ack_info_cnt; i++) { if (dhdp->tcp_ack_info_tbl[i].p_tcpackinqueue && !memcmp(&ip_header[12], dhdp->tcp_ack_info_tbl[i].ipaddrs, 8) && !memcmp(tcp_header, dhdp->tcp_ack_info_tbl[i].tcpports, 4)) { tcp_ack_info = &dhdp->tcp_ack_info_tbl[i]; break; } } if (i == dhdp->tcp_ack_info_cnt && i < MAXTCPSTREAMS) tcp_ack_info = &dhdp->tcp_ack_info_tbl[dhdp->tcp_ack_info_cnt++]; if (!tcp_ack_info) { DHD_TRACE(("dhd_tcpack_suppress: No empty tcp ack info" "%d %d %d %d, %d %d %d %d\n", tcp_header[0], tcp_header[1], tcp_header[2], tcp_header[3], dhdp->tcp_ack_info_tbl[i].tcpports[0], dhdp->tcp_ack_info_tbl[i].tcpports[1], dhdp->tcp_ack_info_tbl[i].tcpports[2], dhdp->tcp_ack_info_tbl[i].tcpports[3])); dhd_os_tcpackunlock(dhdp); return FALSE; } if (tcp_ack_info->p_tcpackinqueue) { if (tcp_ack_num > tcp_ack_info->tcpack_number) { void *prevpkt = tcp_ack_info->p_tcpackinqueue; uint8 pushed_len = SDPCM_HDRLEN + (BDC_HEADER_LEN - bdc_hdr_len) + wlfc_hdr_len; #ifdef PROP_TXSTATUS /* In case the prev pkt is delayenqueued * but not delayedequeued yet, it may not have * any additional header yet. */ if (dhdp->wlfc_state && (PKTLEN(dhdp->osh, prevpkt) == tcp_ack_info->ip_tcp_ttllen + ETHER_HDR_LEN)) pushed_len = 0; #endif if ((ip_tcp_ttllen == tcp_ack_info->ip_tcp_ttllen) && (PKTLEN(dhdp->osh, pkt) == PKTLEN(dhdp->osh, prevpkt) - pushed_len)) { bcopy(PKTDATA(dhdp->osh, pkt), PKTDATA(dhdp->osh, prevpkt) + pushed_len, PKTLEN(dhdp->osh, pkt)); PKTFREE(dhdp->osh, pkt, FALSE); DHD_TRACE(("dhd_tcpack_suppress: pkt 0x%p" " TCP ACK replace %ud -> %ud\n", prevpkt, tcp_ack_info->tcpack_number, tcp_ack_num)); tcp_ack_info->tcpack_number = tcp_ack_num; dhd_os_tcpackunlock(dhdp); return TRUE; } else DHD_TRACE(("dhd_tcpack_suppress: len mismatch" " %d(%d) %d(%d)\n", PKTLEN(dhdp->osh, pkt), ip_tcp_ttllen, PKTLEN(dhdp->osh, prevpkt), tcp_ack_info->ip_tcp_ttllen)); } else { #ifdef TCPACK_TEST void *prevpkt = tcp_ack_info->p_tcpackinqueue; #endif DHD_TRACE(("dhd_tcpack_suppress: TCP ACK number reverse" " prev %ud (0x%p) new %ud (0x%p)\n", tcp_ack_info->tcpack_number, tcp_ack_info->p_tcpackinqueue, tcp_ack_num, pkt)); #ifdef TCPACK_TEST if (PKTLEN(dhdp->osh, pkt) == PKTLEN(dhdp->osh, prevpkt)) { PKTFREE(dhdp->osh, pkt, FALSE); dhd_os_tcpackunlock(dhdp); return TRUE; } #endif } } else { tcp_ack_info->p_tcpackinqueue = pkt; tcp_ack_info->tcpack_number = tcp_ack_num; tcp_ack_info->ip_tcp_ttllen = ip_tcp_ttllen; bcopy(&ip_header[12], tcp_ack_info->ipaddrs, 8); bcopy(tcp_header, tcp_ack_info->tcpports, 4); } dhd_os_tcpackunlock(dhdp); } else DHD_TRACE(("dhd_tcpack_suppress: TCP ACK with DATA len %d\n", ip_tcp_ttllen - ip_hdr_len - tcp_hdr_len)); } return FALSE; } #endif /* DHDTCPACK_SUPPRESS */ /* Writes a HW/SW header into the packet and sends it. */ /* Assumes: (a) header space already there, (b) caller holds lock */ static int dhdsdio_txpkt(dhd_bus_t *bus, void *pkt, uint chan, bool free_pkt, bool queue_only) { int ret; osl_t *osh; uint8 *frame; uint16 len, pad1 = 0, act_len = 0; uint32 swheader; uint retries = 0; uint32 real_pad = 0; bcmsdh_info_t *sdh; void *new; int i; int pkt_cnt; #ifdef BCMSDIOH_TXGLOM uint8 *frame_tmp; #endif #ifdef WLMEDIA_HTSF char *p; htsfts_t *htsf_ts; #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); sdh = bus->sdh; osh = bus->dhd->osh; #ifdef DHDTCPACK_SUPPRESS if (dhd_use_tcpack_suppress) { dhd_tcpack_check_xmit(bus->dhd, pkt); } #endif /* DHDTCPACK_SUPPRESS */ if (bus->dhd->dongle_reset) { ret = BCME_NOTREADY; goto done; } frame = (uint8*)PKTDATA(osh, pkt); #ifdef WLMEDIA_HTSF if (PKTLEN(osh, pkt) >= 100) { p = PKTDATA(osh, pkt); htsf_ts = (htsfts_t*) (p + HTSF_HOSTOFFSET + 12); if (htsf_ts->magic == HTSFMAGIC) { htsf_ts->c20 = get_cycles(); htsf_ts->t20 = dhd_get_htsf(bus->dhd->info, 0); } } #endif /* WLMEDIA_HTSF */ /* Add alignment padding, allocate new packet if needed */ if ((pad1 = ((uintptr)frame % DHD_SDALIGN))) { if (PKTHEADROOM(osh, pkt) < pad1) { DHD_INFO(("%s: insufficient headroom %d for %d pad1\n", __FUNCTION__, (int)PKTHEADROOM(osh, pkt), pad1)); bus->dhd->tx_realloc++; new = PKTGET(osh, (PKTLEN(osh, pkt) + DHD_SDALIGN), TRUE); if (!new) { DHD_ERROR(("%s: couldn't allocate new %d-byte packet\n", __FUNCTION__, PKTLEN(osh, pkt) + DHD_SDALIGN)); ret = BCME_NOMEM; goto done; } PKTALIGN(osh, new, PKTLEN(osh, pkt), DHD_SDALIGN); bcopy(PKTDATA(osh, pkt), PKTDATA(osh, new), PKTLEN(osh, pkt)); if (free_pkt) PKTFREE(osh, pkt, TRUE); /* free the pkt if canned one is not used */ free_pkt = TRUE; pkt = new; frame = (uint8*)PKTDATA(osh, pkt); ASSERT(((uintptr)frame % DHD_SDALIGN) == 0); pad1 = 0; } else { PKTPUSH(osh, pkt, pad1); frame = (uint8*)PKTDATA(osh, pkt); ASSERT((pad1 + SDPCM_HDRLEN) <= (int) PKTLEN(osh, pkt)); bzero(frame, pad1 + SDPCM_HDRLEN); } } ASSERT(pad1 < DHD_SDALIGN); /* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */ len = (uint16)PKTLEN(osh, pkt); *(uint16*)frame = htol16(len); *(((uint16*)frame) + 1) = htol16(~len); #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) { uint32 hwheader1 = 0, hwheader2 = 0; act_len = len; /* Software tag: channel, sequence number, data offset */ swheader = ((chan << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | ((bus->tx_seq + bus->glom_cnt) % SDPCM_SEQUENCE_WRAP) | (((pad1 + SDPCM_HDRLEN) << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK); htol32_ua_store(swheader, frame + SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN); htol32_ua_store(0, frame + SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN + sizeof(swheader)); if (queue_only) { uint8 alignment = ALIGNMENT; #if defined(BCMLXSDMMC) && defined(CUSTOMER_HW4) if (bus->glom_mode == SDPCM_TXGLOM_MDESC) alignment = DHD_SDALIGN; #endif /* defined(BCMLXSDMMC) && defined(CUSTOMER_HW4) */ if (forcealign && (len & (alignment - 1))) len = ROUNDUP(len, alignment); /* Hardware extention tag */ /* 2byte frame length, 1byte-, 1byte frame flag, * 2byte-hdrlength, 2byte padlenght */ hwheader1 = (act_len - SDPCM_FRAMETAG_LEN) | (0 << 24); hwheader2 = (len - act_len) << 16; htol32_ua_store(hwheader1, frame + SDPCM_FRAMETAG_LEN); htol32_ua_store(hwheader2, frame + SDPCM_FRAMETAG_LEN + 4); real_pad = len - act_len; if (PKTTAILROOM(osh, pkt) < real_pad) { DHD_INFO(("%s 1: insufficient tailroom %d for %d real_pad\n", __FUNCTION__, (int)PKTTAILROOM(osh, pkt), real_pad)); if (PKTPADTAILROOM(osh, pkt, real_pad)) { DHD_ERROR(("padding error size %d\n", real_pad)); } } #ifdef BCMLXSDMMC PKTSETLEN(osh, pkt, len); #endif /* BCMLXSDMMC */ /* Post the frame pointer to sdio glom array */ dhd_bcmsdh_glom_post(bus, frame, pkt, len); /* Save the pkt pointer in bus glom array */ bus->glom_pkt_arr[bus->glom_cnt] = pkt; bus->glom_total_len += len; bus->glom_cnt++; return BCME_OK; } else { /* Raise len to next SDIO block to eliminate tail command */ if (bus->roundup && bus->blocksize && ((bus->glom_total_len + len) > bus->blocksize)) { uint16 pad2 = bus->blocksize - ((bus->glom_total_len + len) % bus->blocksize); if ((pad2 <= bus->roundup) && (pad2 < bus->blocksize)) { len += pad2; } else { } } else if ((bus->glom_total_len + len) % DHD_SDALIGN) { len += DHD_SDALIGN - ((bus->glom_total_len + len) % DHD_SDALIGN); } if (forcealign && (len & (ALIGNMENT - 1))) { len = ROUNDUP(len, ALIGNMENT); } /* Hardware extention tag */ /* 2byte frame length, 1byte-, 1byte frame flag, * 2byte-hdrlength, 2byte padlenght */ hwheader1 = (act_len - SDPCM_FRAMETAG_LEN) | (1 << 24); hwheader2 = (len - act_len) << 16; htol32_ua_store(hwheader1, frame + SDPCM_FRAMETAG_LEN); htol32_ua_store(hwheader2, frame + SDPCM_FRAMETAG_LEN + 4); real_pad = len - act_len; if (PKTTAILROOM(osh, pkt) < real_pad) { DHD_INFO(("%s 2: insufficient tailroom %d" " for %d real_pad\n", __FUNCTION__, (int)PKTTAILROOM(osh, pkt), real_pad)); if (PKTPADTAILROOM(osh, pkt, real_pad)) { DHD_ERROR(("padding error size %d\n", real_pad)); } } #ifdef BCMLXSDMMC PKTSETLEN(osh, pkt, len); #endif /* BCMLXSDMMC */ /* Post the frame pointer to sdio glom array */ dhd_bcmsdh_glom_post(bus, frame, pkt, len); /* Save the pkt pointer in bus glom array */ bus->glom_pkt_arr[bus->glom_cnt] = pkt; bus->glom_cnt++; bus->glom_total_len += len; /* Update the total length on the first pkt */ frame_tmp = (uint8*)PKTDATA(osh, bus->glom_pkt_arr[0]); *(uint16*)frame_tmp = htol16(bus->glom_total_len); *(((uint16*)frame_tmp) + 1) = htol16(~bus->glom_total_len); } } else #endif /* BCMSDIOH_TXGLOM */ { act_len = len; /* Software tag: channel, sequence number, data offset */ swheader = ((chan << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | bus->tx_seq | (((pad1 + SDPCM_HDRLEN) << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK); htol32_ua_store(swheader, frame + SDPCM_FRAMETAG_LEN); htol32_ua_store(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader)); #ifdef DHD_DEBUG if (PKTPRIO(pkt) < ARRAYSIZE(tx_packets)) { tx_packets[PKTPRIO(pkt)]++; } if (DHD_BYTES_ON() && (((DHD_CTL_ON() && (chan == SDPCM_CONTROL_CHANNEL)) || (DHD_DATA_ON() && (chan != SDPCM_CONTROL_CHANNEL))))) { prhex("Tx Frame", frame, len); } else if (DHD_HDRS_ON()) { prhex("TxHdr", frame, MIN(len, 16)); } #endif #ifndef BCMSPI /* Raise len to next SDIO block to eliminate tail command */ if (bus->roundup && bus->blocksize && (len > bus->blocksize)) { uint16 pad2 = bus->blocksize - (len % bus->blocksize); if ((pad2 <= bus->roundup) && (pad2 < bus->blocksize)) #ifdef NOTUSED if (pad2 <= PKTTAILROOM(osh, pkt)) #endif /* NOTUSED */ len += pad2; } else if (len % DHD_SDALIGN) { len += DHD_SDALIGN - (len % DHD_SDALIGN); } #endif /* BCMSPI */ /* Some controllers have trouble with odd bytes -- round to even */ if (forcealign && (len & (ALIGNMENT - 1))) { #ifdef NOTUSED if (PKTTAILROOM(osh, pkt)) #endif len = ROUNDUP(len, ALIGNMENT); #ifdef NOTUSED else DHD_ERROR(("%s: sending unrounded %d-byte packet\n", __FUNCTION__, len)); #endif } real_pad = len - act_len; if (PKTTAILROOM(osh, pkt) < real_pad) { DHD_INFO(("%s 3: insufficient tailroom %d for %d real_pad\n", __FUNCTION__, (int)PKTTAILROOM(osh, pkt), real_pad)); if (PKTPADTAILROOM(osh, pkt, real_pad)) { DHD_ERROR(("CHK3: padding error size %d\n", real_pad)); ret = BCME_NOMEM; goto done; } #ifndef BCMLXSDMMC else PKTSETLEN(osh, pkt, act_len); #endif } #ifdef BCMLXSDMMC PKTSETLEN(osh, pkt, len); #endif /* BCMLXSDMMC */ } do { ret = dhd_bcmsdh_send_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, frame, len, pkt, NULL, NULL); bus->f2txdata++; ASSERT(ret != BCME_PENDING); if (ret == BCME_NODEVICE) { DHD_ERROR(("%s: Device asleep already\n", __FUNCTION__)); } else if (ret < 0) { /* On failure, abort the command and terminate the frame */ DHD_ERROR(("%s: sdio error %d, abort command and terminate frame.\n", __FUNCTION__, ret)); bus->tx_sderrs++; bcmsdh_abort(sdh, SDIO_FUNC_2); #ifdef BCMSPI DHD_ERROR(("%s: gSPI transmit error. Check Overflow or F2-fifo-not-ready" " counters.\n", __FUNCTION__)); #endif /* BCMSPI */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM, NULL); bus->f1regdata++; for (i = 0; i < 3; i++) { uint8 hi, lo; hi = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCHI, NULL); lo = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCLO, NULL); bus->f1regdata += 2; if ((hi == 0) && (lo == 0)) break; } } if (ret == 0) { #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) { bus->tx_seq = (bus->tx_seq + bus->glom_cnt) % SDPCM_SEQUENCE_WRAP; } else #endif { bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP; } } } while ((ret < 0) && retrydata && retries++ < TXRETRIES); done: #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) { dhd_bcmsdh_glom_clear(bus); pkt_cnt = bus->glom_cnt; } else #endif { pkt_cnt = 1; } /* restore pkt buffer pointer before calling tx complete routine */ while (pkt_cnt) { #ifdef BCMSDIOH_TXGLOM uint32 doff; if (bus->glom_enable) { #ifdef BCMLXSDMMC uint32 pad2 = 0; #endif /* BCMLXSDMMC */ pkt = bus->glom_pkt_arr[bus->glom_cnt - pkt_cnt]; frame = (uint8*)PKTDATA(osh, pkt); doff = ltoh32_ua(frame + SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN); doff = (doff & SDPCM_DOFFSET_MASK) >> SDPCM_DOFFSET_SHIFT; #ifdef BCMLXSDMMC pad2 = ltoh32_ua(frame + SDPCM_FRAMETAG_LEN + 4) >> 16; PKTSETLEN(osh, pkt, PKTLEN(osh, pkt) - pad2); #endif /* BCMLXSDMMC */ PKTPULL(osh, pkt, doff); } else #endif /* BCMSDIOH_TXGLOM */ { #ifdef BCMLXSDMMC if (act_len > 0) PKTSETLEN(osh, pkt, act_len); #endif /* BCMLXSDMMC */ PKTPULL(osh, pkt, SDPCM_HDRLEN + pad1); } #ifdef PROP_TXSTATUS if (bus->dhd->wlfc_state) { dhd_os_sdunlock(bus->dhd); dhd_wlfc_txcomplete(bus->dhd, pkt, ret == 0); dhd_os_sdlock(bus->dhd); } else { #endif /* PROP_TXSTATUS */ #ifdef SDTEST if (chan != SDPCM_TEST_CHANNEL) { dhd_txcomplete(bus->dhd, pkt, ret != 0); } #else /* SDTEST */ dhd_txcomplete(bus->dhd, pkt, ret != 0); #endif /* SDTEST */ if (free_pkt) PKTFREE(osh, pkt, TRUE); #ifdef PROP_TXSTATUS } #endif pkt_cnt--; } #ifdef BCMSDIOH_TXGLOM /* Reset the glom array */ if (bus->glom_enable) { bus->glom_cnt = 0; bus->glom_total_len = 0; } #endif return ret; } int dhd_bus_txdata(struct dhd_bus *bus, void *pkt) { int ret = BCME_ERROR; osl_t *osh; uint datalen, prec; #ifdef DHD_TX_DUMP uint8 *dump_data; uint16 protocol; #ifdef DHD_TX_FULL_DUMP int i; #endif /* DHD_TX_FULL_DUMP */ #endif /* DHD_TX_DUMP */ DHD_TRACE(("%s: Enter\n", __FUNCTION__)); osh = bus->dhd->osh; datalen = PKTLEN(osh, pkt); #ifdef SDTEST /* Push the test header if doing loopback */ if (bus->ext_loop) { uint8* data; PKTPUSH(osh, pkt, SDPCM_TEST_HDRLEN); data = PKTDATA(osh, pkt); *data++ = SDPCM_TEST_ECHOREQ; *data++ = (uint8)bus->loopid++; *data++ = (datalen >> 0); *data++ = (datalen >> 8); datalen += SDPCM_TEST_HDRLEN; } #endif /* SDTEST */ #ifdef DHD_TX_DUMP dump_data = PKTDATA(osh, pkt); dump_data += 4; /* skip 4 bytes header */ protocol = (dump_data[12] << 8) | dump_data[13]; #ifdef DHD_TX_FULL_DUMP DHD_ERROR(("TX DUMP\n")); for (i = 0; i < (datalen - 4); i++) { DHD_ERROR(("%02X ", dump_data[i])); if ((i & 15) == 15) printk("\n"); } DHD_ERROR(("\n")); #endif /* DHD_TX_FULL_DUMP */ if (protocol == ETHER_TYPE_802_1X) { DHD_ERROR(("ETHER_TYPE_802_1X: ver %d, type %d, replay %d\n", dump_data[14], dump_data[15], dump_data[30])); } #endif /* DHD_TX_DUMP */ /* Add space for the header */ PKTPUSH(osh, pkt, SDPCM_HDRLEN); ASSERT(ISALIGNED((uintptr)PKTDATA(osh, pkt), 2)); prec = PRIO2PREC((PKTPRIO(pkt) & PRIOMASK)); #ifndef DHDTHREAD /* Lock: we're about to use shared data/code (and SDIO) */ dhd_os_sdlock(bus->dhd); #endif /* DHDTHREAD */ /* Check for existing queue, current flow-control, pending event, or pending clock */ if (dhd_deferred_tx || bus->fcstate || pktq_len(&bus->txq) || bus->dpc_sched || (!DATAOK(bus)) || (bus->flowcontrol & NBITVAL(prec)) || (bus->clkstate != CLK_AVAIL)) { DHD_TRACE(("%s: deferring pktq len %d\n", __FUNCTION__, pktq_len(&bus->txq))); bus->fcqueued++; /* Priority based enq */ dhd_os_sdlock_txq(bus->dhd); if (dhd_prec_enq(bus->dhd, &bus->txq, pkt, prec) == FALSE) { PKTPULL(osh, pkt, SDPCM_HDRLEN); #ifndef DHDTHREAD /* Need to also release txqlock before releasing sdlock. * This thread still has txqlock and releases sdlock. * Deadlock happens when dpc() grabs sdlock first then * attempts to grab txqlock. */ dhd_os_sdunlock_txq(bus->dhd); dhd_os_sdunlock(bus->dhd); #endif #ifdef PROP_TXSTATUS if (bus->dhd->wlfc_state) dhd_wlfc_txcomplete(bus->dhd, pkt, FALSE); else #endif dhd_txcomplete(bus->dhd, pkt, FALSE); #ifndef DHDTHREAD dhd_os_sdlock(bus->dhd); dhd_os_sdlock_txq(bus->dhd); #endif #ifdef PROP_TXSTATUS /* let the caller decide whether to free the packet */ if (!bus->dhd->wlfc_state) #endif PKTFREE(osh, pkt, TRUE); ret = BCME_NORESOURCE; } else ret = BCME_OK; if ((pktq_len(&bus->txq) >= FCHI) && dhd_doflow) dhd_txflowcontrol(bus->dhd, ALL_INTERFACES, ON); #ifdef DHD_DEBUG if (pktq_plen(&bus->txq, prec) > qcount[prec]) qcount[prec] = pktq_plen(&bus->txq, prec); #endif dhd_os_sdunlock_txq(bus->dhd); /* Schedule DPC if needed to send queued packet(s) */ if (dhd_deferred_tx && !bus->dpc_sched) { bus->dpc_sched = TRUE; dhd_sched_dpc(bus->dhd); } } else { #ifdef DHDTHREAD /* Lock: we're about to use shared data/code (and SDIO) */ dhd_os_sdlock(bus->dhd); #endif /* DHDTHREAD */ /* Otherwise, send it now */ BUS_WAKE(bus); /* Make sure back plane ht clk is on, no pending allowed */ dhdsdio_clkctl(bus, CLK_AVAIL, TRUE); #ifndef SDTEST ret = dhdsdio_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, TRUE, FALSE); #else ret = dhdsdio_txpkt(bus, pkt, (bus->ext_loop ? SDPCM_TEST_CHANNEL : SDPCM_DATA_CHANNEL), TRUE, FALSE); #endif if (ret) bus->dhd->tx_errors++; else bus->dhd->dstats.tx_bytes += datalen; if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, TRUE); } #ifdef DHDTHREAD dhd_os_sdunlock(bus->dhd); #endif /* DHDTHREAD */ } #ifndef DHDTHREAD dhd_os_sdunlock(bus->dhd); #endif /* DHDTHREAD */ return ret; } static uint dhdsdio_sendfromq(dhd_bus_t *bus, uint maxframes) { void *pkt; uint32 intstatus = 0; uint retries = 0; int ret = 0, prec_out; uint cnt = 0; uint datalen; uint8 tx_prec_map; uint8 txpktqlen = 0; #ifdef BCMSDIOH_TXGLOM uint i; uint8 glom_cnt; #endif dhd_pub_t *dhd = bus->dhd; sdpcmd_regs_t *regs = bus->regs; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (!KSO_ENAB(bus)) { DHD_ERROR(("%s: Device asleep\n", __FUNCTION__)); return BCME_NODEVICE; } tx_prec_map = ~bus->flowcontrol; /* Send frames until the limit or some other event */ for (cnt = 0; (cnt < maxframes) && DATAOK(bus); cnt++) { #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) { void *pkttable[SDPCM_MAXGLOM_SIZE]; dhd_os_sdlock_txq(bus->dhd); glom_cnt = MIN(DATABUFCNT(bus), bus->glomsize); glom_cnt = MIN(glom_cnt, pktq_mlen(&bus->txq, tx_prec_map)); glom_cnt = MIN(glom_cnt, maxframes-cnt); /* Limiting the size to 2pkts in case of copy */ if (bus->glom_mode == SDPCM_TXGLOM_CPY) glom_cnt = MIN(glom_cnt, 10); for (i = 0; i < glom_cnt; i++) pkttable[i] = pktq_mdeq(&bus->txq, tx_prec_map, &prec_out); txpktqlen = pktq_len(&bus->txq); dhd_os_sdunlock_txq(bus->dhd); if (glom_cnt == 0) break; datalen = 0; for (i = 0; i < glom_cnt; i++) { if ((pkt = pkttable[i]) == NULL) { /* This case should not happen */ DHD_ERROR(("No pkts in the queue for glomming\n")); break; } datalen += (PKTLEN(bus->dhd->osh, pkt) - SDPCM_HDRLEN); #ifndef SDTEST ret = dhdsdio_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, TRUE, (i == (glom_cnt-1))? FALSE: TRUE); #else ret = dhdsdio_txpkt(bus, pkt, (bus->ext_loop ? SDPCM_TEST_CHANNEL : SDPCM_DATA_CHANNEL), TRUE, (i == (glom_cnt-1))? FALSE: TRUE); #endif } cnt += i-1; } else #endif /* BCMSDIOH_TXGLOM */ { dhd_os_sdlock_txq(bus->dhd); if ((pkt = pktq_mdeq(&bus->txq, tx_prec_map, &prec_out)) == NULL) { txpktqlen = pktq_len(&bus->txq); dhd_os_sdunlock_txq(bus->dhd); break; } txpktqlen = pktq_len(&bus->txq); dhd_os_sdunlock_txq(bus->dhd); datalen = PKTLEN(bus->dhd->osh, pkt) - SDPCM_HDRLEN; #ifndef SDTEST ret = dhdsdio_txpkt(bus, pkt, SDPCM_DATA_CHANNEL, TRUE, FALSE); #else ret = dhdsdio_txpkt(bus, pkt, (bus->ext_loop ? SDPCM_TEST_CHANNEL : SDPCM_DATA_CHANNEL), TRUE, FALSE); #endif } if (ret) bus->dhd->tx_errors++; else bus->dhd->dstats.tx_bytes += datalen; /* In poll mode, need to check for other events */ if (!bus->intr && cnt) { /* Check device status, signal pending interrupt */ R_SDREG(intstatus, &regs->intstatus, retries); bus->f2txdata++; if (bcmsdh_regfail(bus->sdh)) break; if (intstatus & bus->hostintmask) bus->ipend = TRUE; } } /* Deflow-control stack if needed */ if (dhd_doflow && dhd->up && (dhd->busstate == DHD_BUS_DATA) && dhd->txoff && (txpktqlen < FCLOW)) dhd_txflowcontrol(dhd, ALL_INTERFACES, OFF); return cnt; } static void dhdsdio_sendpendctl(dhd_bus_t *bus) { bcmsdh_info_t *sdh = bus->sdh; int ret, i; uint8* frame_seq = bus->ctrl_frame_buf + SDPCM_FRAMETAG_LEN; #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) frame_seq += SDPCM_HWEXT_LEN; #endif if (*frame_seq != bus->tx_seq) { DHD_INFO(("%s IOCTL frame seq lag detected!" " frm_seq:%d != bus->tx_seq:%d, corrected\n", __FUNCTION__, *frame_seq, bus->tx_seq)); *frame_seq = bus->tx_seq; } ret = dhd_bcmsdh_send_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, (uint8 *)bus->ctrl_frame_buf, (uint32)bus->ctrl_frame_len, NULL, NULL, NULL); ASSERT(ret != BCME_PENDING); if (ret == BCME_NODEVICE) { DHD_ERROR(("%s: Device asleep already\n", __FUNCTION__)); } else if (ret < 0) { /* On failure, abort the command and terminate the frame */ DHD_INFO(("%s: sdio error %d, abort command and terminate frame.\n", __FUNCTION__, ret)); bus->tx_sderrs++; bcmsdh_abort(sdh, SDIO_FUNC_2); bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM, NULL); bus->f1regdata++; for (i = 0; i < 3; i++) { uint8 hi, lo; hi = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCHI, NULL); lo = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCLO, NULL); bus->f1regdata += 2; if ((hi == 0) && (lo == 0)) break; } } if (ret == 0) { bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP; } bus->ctrl_frame_stat = FALSE; dhd_wait_event_wakeup(bus->dhd); } int dhd_bus_txctl(struct dhd_bus *bus, uchar *msg, uint msglen) { uint8 *frame; uint16 len; uint32 swheader; uint retries = 0; bcmsdh_info_t *sdh = bus->sdh; uint8 doff = 0; int ret = -1; int i; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus->dhd->dongle_reset) return -EIO; /* Back the pointer to make a room for bus header */ frame = msg - SDPCM_HDRLEN; len = (msglen += SDPCM_HDRLEN); /* Add alignment padding (optional for ctl frames) */ if (dhd_alignctl) { if ((doff = ((uintptr)frame % DHD_SDALIGN))) { frame -= doff; len += doff; msglen += doff; bzero(frame, doff + SDPCM_HDRLEN); } ASSERT(doff < DHD_SDALIGN); } doff += SDPCM_HDRLEN; #ifndef BCMSPI /* Round send length to next SDIO block */ if (bus->roundup && bus->blocksize && (len > bus->blocksize)) { uint16 pad = bus->blocksize - (len % bus->blocksize); if ((pad <= bus->roundup) && (pad < bus->blocksize)) len += pad; } else if (len % DHD_SDALIGN) { len += DHD_SDALIGN - (len % DHD_SDALIGN); } #endif /* BCMSPI */ /* Satisfy length-alignment requirements */ if (forcealign && (len & (ALIGNMENT - 1))) len = ROUNDUP(len, ALIGNMENT); ASSERT(ISALIGNED((uintptr)frame, 2)); /* Need to lock here to protect txseq and SDIO tx calls */ dhd_os_sdlock(bus->dhd); BUS_WAKE(bus); /* Make sure backplane clock is on */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); /* Hardware tag: 2 byte len followed by 2 byte ~len check (all LE) */ *(uint16*)frame = htol16((uint16)msglen); *(((uint16*)frame) + 1) = htol16(~msglen); #ifdef BCMSDIOH_TXGLOM if (bus->glom_enable) { uint32 hwheader1, hwheader2; /* Software tag: channel, sequence number, data offset */ swheader = ((SDPCM_CONTROL_CHANNEL << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | bus->tx_seq | ((doff << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK); htol32_ua_store(swheader, frame + SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN); htol32_ua_store(0, frame + SDPCM_FRAMETAG_LEN + SDPCM_HWEXT_LEN + sizeof(swheader)); hwheader1 = (msglen - SDPCM_FRAMETAG_LEN) | (1 << 24); hwheader2 = (len - (msglen)) << 16; htol32_ua_store(hwheader1, frame + SDPCM_FRAMETAG_LEN); htol32_ua_store(hwheader2, frame + SDPCM_FRAMETAG_LEN + 4); *(uint16*)frame = htol16(len); *(((uint16*)frame) + 1) = htol16(~(len)); } else #endif /* BCMSDIOH_TXGLOM */ { /* Software tag: channel, sequence number, data offset */ swheader = ((SDPCM_CONTROL_CHANNEL << SDPCM_CHANNEL_SHIFT) & SDPCM_CHANNEL_MASK) | bus->tx_seq | ((doff << SDPCM_DOFFSET_SHIFT) & SDPCM_DOFFSET_MASK); htol32_ua_store(swheader, frame + SDPCM_FRAMETAG_LEN); htol32_ua_store(0, frame + SDPCM_FRAMETAG_LEN + sizeof(swheader)); } if (!TXCTLOK(bus)) { DHD_INFO(("%s: No bus credit bus->tx_max %d, bus->tx_seq %d\n", __FUNCTION__, bus->tx_max, bus->tx_seq)); bus->ctrl_frame_stat = TRUE; /* Send from dpc */ bus->ctrl_frame_buf = frame; bus->ctrl_frame_len = len; if (!bus->dpc_sched) { bus->dpc_sched = TRUE; dhd_sched_dpc(bus->dhd); } if (bus->ctrl_frame_stat) { dhd_wait_for_event(bus->dhd, &bus->ctrl_frame_stat); } if (bus->ctrl_frame_stat == FALSE) { DHD_INFO(("%s: ctrl_frame_stat == FALSE\n", __FUNCTION__)); ret = 0; } else { bus->dhd->txcnt_timeout++; if (!bus->dhd->hang_was_sent) { #ifdef CUSTOMER_HW4 uint32 status, retry = 0; R_SDREG(status, &bus->regs->intstatus, retry); DHD_TRACE_HW4(("%s: txcnt_timeout, INT status=0x%08X\n", __FUNCTION__, status)); DHD_TRACE_HW4(("%s : tx_max : %d, tx_seq : %d, clkstate : %d \n", __FUNCTION__, bus->tx_max, bus->tx_seq, bus->clkstate)); #endif /* CUSTOMER_HW4 */ DHD_ERROR(("%s: ctrl_frame_stat == TRUE txcnt_timeout=%d\n", __FUNCTION__, bus->dhd->txcnt_timeout)); } ret = -1; bus->ctrl_frame_stat = FALSE; goto done; } } bus->dhd->txcnt_timeout = 0; if (ret == -1) { #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_CTL_ON()) { prhex("Tx Frame", frame, len); } else if (DHD_HDRS_ON()) { prhex("TxHdr", frame, MIN(len, 16)); } #endif do { ret = dhd_bcmsdh_send_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, frame, len, NULL, NULL, NULL); ASSERT(ret != BCME_PENDING); if (ret == BCME_NODEVICE) { DHD_ERROR(("%s: Device asleep already\n", __FUNCTION__)); } else if (ret < 0) { /* On failure, abort the command and terminate the frame */ DHD_INFO(("%s: sdio error %d, abort command and terminate frame.\n", __FUNCTION__, ret)); bus->tx_sderrs++; bcmsdh_abort(sdh, SDIO_FUNC_2); #ifdef BCMSPI DHD_ERROR(("%s: Check Overflow or F2-fifo-not-ready counters." " gSPI transmit error on control channel.\n", __FUNCTION__)); #endif /* BCMSPI */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_FRAMECTRL, SFC_WF_TERM, NULL); bus->f1regdata++; for (i = 0; i < 3; i++) { uint8 hi, lo; hi = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCHI, NULL); lo = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_WFRAMEBCLO, NULL); bus->f1regdata += 2; if ((hi == 0) && (lo == 0)) break; } } if (ret == 0) { bus->tx_seq = (bus->tx_seq + 1) % SDPCM_SEQUENCE_WRAP; } } while ((ret < 0) && retries++ < TXRETRIES); } done: if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, TRUE); } dhd_os_sdunlock(bus->dhd); if (ret) bus->dhd->tx_ctlerrs++; else bus->dhd->tx_ctlpkts++; if (bus->dhd->txcnt_timeout >= MAX_CNTL_TX_TIMEOUT) return -ETIMEDOUT; return ret ? -EIO : 0; } int dhd_bus_rxctl(struct dhd_bus *bus, uchar *msg, uint msglen) { int timeleft; uint rxlen = 0; bool pending; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus->dhd->dongle_reset) return -EIO; /* Wait until control frame is available */ timeleft = dhd_os_ioctl_resp_wait(bus->dhd, &bus->rxlen, &pending); dhd_os_sdlock(bus->dhd); rxlen = bus->rxlen; bcopy(bus->rxctl, msg, MIN(msglen, rxlen)); bus->rxlen = 0; dhd_os_sdunlock(bus->dhd); if (rxlen) { DHD_CTL(("%s: resumed on rxctl frame, got %d expected %d\n", __FUNCTION__, rxlen, msglen)); } else if (timeleft == 0) { #ifdef DHD_DEBUG uint32 status, retry = 0; R_SDREG(status, &bus->regs->intstatus, retry); DHD_ERROR(("%s: resumed on timeout, INT status=0x%08X\n", __FUNCTION__, status)); #else DHD_ERROR(("%s: resumed on timeout\n", __FUNCTION__)); #endif /* DHD_DEBUG */ #ifdef DHD_DEBUG dhd_os_sdlock(bus->dhd); dhdsdio_checkdied(bus, NULL, 0); dhd_os_sdunlock(bus->dhd); #endif /* DHD_DEBUG */ } else if (pending == TRUE) { /* signal pending */ DHD_ERROR(("%s: signal pending\n", __FUNCTION__)); return -EINTR; } else { DHD_CTL(("%s: resumed for unknown reason?\n", __FUNCTION__)); #ifdef DHD_DEBUG dhd_os_sdlock(bus->dhd); dhdsdio_checkdied(bus, NULL, 0); dhd_os_sdunlock(bus->dhd); #endif /* DHD_DEBUG */ } if (timeleft == 0) { if (rxlen == 0) bus->dhd->rxcnt_timeout++; DHD_ERROR(("%s: rxcnt_timeout=%d, rxlen=%d\n", __FUNCTION__, bus->dhd->rxcnt_timeout, rxlen)); } else bus->dhd->rxcnt_timeout = 0; if (rxlen) bus->dhd->rx_ctlpkts++; else bus->dhd->rx_ctlerrs++; if (bus->dhd->rxcnt_timeout >= MAX_CNTL_RX_TIMEOUT) return -ETIMEDOUT; if (bus->dhd->dongle_trap_occured) return -EREMOTEIO; return rxlen ? (int)rxlen : -EIO; } /* IOVar table */ enum { IOV_INTR = 1, IOV_POLLRATE, IOV_SDREG, IOV_SBREG, IOV_SDCIS, IOV_MEMBYTES, IOV_MEMSIZE, #ifdef DHD_DEBUG IOV_CHECKDIED, IOV_SERIALCONS, #endif /* DHD_DEBUG */ IOV_SET_DOWNLOAD_STATE, IOV_SOCRAM_STATE, IOV_FORCEEVEN, IOV_SDIOD_DRIVE, IOV_READAHEAD, IOV_SDRXCHAIN, IOV_ALIGNCTL, IOV_SDALIGN, IOV_DEVRESET, IOV_CPU, #if defined(SDIO_CRC_ERROR_FIX) IOV_WATERMARK, IOV_MESBUSYCTRL, #endif /* SDIO_CRC_ERROR_FIX */ #ifdef SDTEST IOV_PKTGEN, IOV_EXTLOOP, #endif /* SDTEST */ IOV_SPROM, IOV_TXBOUND, IOV_RXBOUND, IOV_TXMINMAX, IOV_IDLETIME, IOV_IDLECLOCK, IOV_SD1IDLE, IOV_SLEEP, IOV_DONGLEISOLATION, IOV_KSO, IOV_DEVSLEEP, IOV_DEVCAP, IOV_VARS, #ifdef SOFTAP IOV_FWPATH, #endif IOV_TXGLOMSIZE, IOV_TXGLOMMODE }; const bcm_iovar_t dhdsdio_iovars[] = { {"intr", IOV_INTR, 0, IOVT_BOOL, 0 }, {"sleep", IOV_SLEEP, 0, IOVT_BOOL, 0 }, {"pollrate", IOV_POLLRATE, 0, IOVT_UINT32, 0 }, {"idletime", IOV_IDLETIME, 0, IOVT_INT32, 0 }, {"idleclock", IOV_IDLECLOCK, 0, IOVT_INT32, 0 }, {"sd1idle", IOV_SD1IDLE, 0, IOVT_BOOL, 0 }, {"membytes", IOV_MEMBYTES, 0, IOVT_BUFFER, 2 * sizeof(int) }, {"memsize", IOV_MEMSIZE, 0, IOVT_UINT32, 0 }, {"dwnldstate", IOV_SET_DOWNLOAD_STATE, 0, IOVT_BOOL, 0 }, {"socram_state", IOV_SOCRAM_STATE, 0, IOVT_BOOL, 0 }, {"vars", IOV_VARS, 0, IOVT_BUFFER, 0 }, {"sdiod_drive", IOV_SDIOD_DRIVE, 0, IOVT_UINT32, 0 }, {"readahead", IOV_READAHEAD, 0, IOVT_BOOL, 0 }, {"sdrxchain", IOV_SDRXCHAIN, 0, IOVT_BOOL, 0 }, {"alignctl", IOV_ALIGNCTL, 0, IOVT_BOOL, 0 }, {"sdalign", IOV_SDALIGN, 0, IOVT_BOOL, 0 }, {"devreset", IOV_DEVRESET, 0, IOVT_BOOL, 0 }, #ifdef DHD_DEBUG {"sdreg", IOV_SDREG, 0, IOVT_BUFFER, sizeof(sdreg_t) }, {"sbreg", IOV_SBREG, 0, IOVT_BUFFER, sizeof(sdreg_t) }, {"sd_cis", IOV_SDCIS, 0, IOVT_BUFFER, DHD_IOCTL_MAXLEN }, {"forcealign", IOV_FORCEEVEN, 0, IOVT_BOOL, 0 }, {"txbound", IOV_TXBOUND, 0, IOVT_UINT32, 0 }, {"rxbound", IOV_RXBOUND, 0, IOVT_UINT32, 0 }, {"txminmax", IOV_TXMINMAX, 0, IOVT_UINT32, 0 }, {"cpu", IOV_CPU, 0, IOVT_BOOL, 0 }, #ifdef DHD_DEBUG {"checkdied", IOV_CHECKDIED, 0, IOVT_BUFFER, 0 }, {"serial", IOV_SERIALCONS, 0, IOVT_UINT32, 0 }, #endif /* DHD_DEBUG */ #endif /* DHD_DEBUG */ #ifdef SDTEST {"extloop", IOV_EXTLOOP, 0, IOVT_BOOL, 0 }, {"pktgen", IOV_PKTGEN, 0, IOVT_BUFFER, sizeof(dhd_pktgen_t) }, #endif /* SDTEST */ #if defined(SDIO_CRC_ERROR_FIX) {"watermark", IOV_WATERMARK, 0, IOVT_UINT32, 0 }, {"mesbusyctrl", IOV_MESBUSYCTRL, 0, IOVT_UINT32, 0 }, #endif /* SDIO_CRC_ERROR_FIX */ {"devcap", IOV_DEVCAP, 0, IOVT_UINT32, 0 }, {"dngl_isolation", IOV_DONGLEISOLATION, 0, IOVT_UINT32, 0 }, {"kso", IOV_KSO, 0, IOVT_UINT32, 0 }, {"devsleep", IOV_DEVSLEEP, 0, IOVT_UINT32, 0 }, #ifdef SOFTAP {"fwpath", IOV_FWPATH, 0, IOVT_BUFFER, 0 }, #endif {"txglomsize", IOV_TXGLOMSIZE, 0, IOVT_UINT32, 0 }, {"txglommode", IOV_TXGLOMMODE, 0, IOVT_UINT32, 0 }, {NULL, 0, 0, 0, 0 } }; static void dhd_dump_pct(struct bcmstrbuf *strbuf, char *desc, uint num, uint div) { uint q1, q2; if (!div) { bcm_bprintf(strbuf, "%s N/A", desc); } else { q1 = num / div; q2 = (100 * (num - (q1 * div))) / div; bcm_bprintf(strbuf, "%s %d.%02d", desc, q1, q2); } } void dhd_bus_dump(dhd_pub_t *dhdp, struct bcmstrbuf *strbuf) { dhd_bus_t *bus = dhdp->bus; bcm_bprintf(strbuf, "Bus SDIO structure:\n"); bcm_bprintf(strbuf, "hostintmask 0x%08x intstatus 0x%08x sdpcm_ver %d\n", bus->hostintmask, bus->intstatus, bus->sdpcm_ver); bcm_bprintf(strbuf, "fcstate %d qlen %d tx_seq %d, max %d, rxskip %d rxlen %d rx_seq %d\n", bus->fcstate, pktq_len(&bus->txq), bus->tx_seq, bus->tx_max, bus->rxskip, bus->rxlen, bus->rx_seq); bcm_bprintf(strbuf, "intr %d intrcount %d lastintrs %d spurious %d\n", bus->intr, bus->intrcount, bus->lastintrs, bus->spurious); bcm_bprintf(strbuf, "pollrate %d pollcnt %d regfails %d\n", bus->pollrate, bus->pollcnt, bus->regfails); bcm_bprintf(strbuf, "\nAdditional counters:\n"); bcm_bprintf(strbuf, "tx_sderrs %d fcqueued %d rxrtx %d rx_toolong %d rxc_errors %d\n", bus->tx_sderrs, bus->fcqueued, bus->rxrtx, bus->rx_toolong, bus->rxc_errors); bcm_bprintf(strbuf, "rx_hdrfail %d badhdr %d badseq %d\n", bus->rx_hdrfail, bus->rx_badhdr, bus->rx_badseq); bcm_bprintf(strbuf, "fc_rcvd %d, fc_xoff %d, fc_xon %d\n", bus->fc_rcvd, bus->fc_xoff, bus->fc_xon); bcm_bprintf(strbuf, "rxglomfail %d, rxglomframes %d, rxglompkts %d\n", bus->rxglomfail, bus->rxglomframes, bus->rxglompkts); bcm_bprintf(strbuf, "f2rx (hdrs/data) %d (%d/%d), f2tx %d f1regs %d\n", (bus->f2rxhdrs + bus->f2rxdata), bus->f2rxhdrs, bus->f2rxdata, bus->f2txdata, bus->f1regdata); { dhd_dump_pct(strbuf, "\nRx: pkts/f2rd", bus->dhd->rx_packets, (bus->f2rxhdrs + bus->f2rxdata)); dhd_dump_pct(strbuf, ", pkts/f1sd", bus->dhd->rx_packets, bus->f1regdata); dhd_dump_pct(strbuf, ", pkts/sd", bus->dhd->rx_packets, (bus->f2rxhdrs + bus->f2rxdata + bus->f1regdata)); dhd_dump_pct(strbuf, ", pkts/int", bus->dhd->rx_packets, bus->intrcount); bcm_bprintf(strbuf, "\n"); dhd_dump_pct(strbuf, "Rx: glom pct", (100 * bus->rxglompkts), bus->dhd->rx_packets); dhd_dump_pct(strbuf, ", pkts/glom", bus->rxglompkts, bus->rxglomframes); bcm_bprintf(strbuf, "\n"); dhd_dump_pct(strbuf, "Tx: pkts/f2wr", bus->dhd->tx_packets, bus->f2txdata); dhd_dump_pct(strbuf, ", pkts/f1sd", bus->dhd->tx_packets, bus->f1regdata); dhd_dump_pct(strbuf, ", pkts/sd", bus->dhd->tx_packets, (bus->f2txdata + bus->f1regdata)); dhd_dump_pct(strbuf, ", pkts/int", bus->dhd->tx_packets, bus->intrcount); bcm_bprintf(strbuf, "\n"); dhd_dump_pct(strbuf, "Total: pkts/f2rw", (bus->dhd->tx_packets + bus->dhd->rx_packets), (bus->f2txdata + bus->f2rxhdrs + bus->f2rxdata)); dhd_dump_pct(strbuf, ", pkts/f1sd", (bus->dhd->tx_packets + bus->dhd->rx_packets), bus->f1regdata); dhd_dump_pct(strbuf, ", pkts/sd", (bus->dhd->tx_packets + bus->dhd->rx_packets), (bus->f2txdata + bus->f2rxhdrs + bus->f2rxdata + bus->f1regdata)); dhd_dump_pct(strbuf, ", pkts/int", (bus->dhd->tx_packets + bus->dhd->rx_packets), bus->intrcount); bcm_bprintf(strbuf, "\n\n"); } #ifdef SDTEST if (bus->pktgen_count) { bcm_bprintf(strbuf, "pktgen config and count:\n"); bcm_bprintf(strbuf, "freq %d count %d print %d total %d min %d len %d\n", bus->pktgen_freq, bus->pktgen_count, bus->pktgen_print, bus->pktgen_total, bus->pktgen_minlen, bus->pktgen_maxlen); bcm_bprintf(strbuf, "send attempts %d rcvd %d fail %d\n", bus->pktgen_sent, bus->pktgen_rcvd, bus->pktgen_fail); } #endif /* SDTEST */ #ifdef DHD_DEBUG bcm_bprintf(strbuf, "dpc_sched %d host interrupt%spending\n", bus->dpc_sched, (bcmsdh_intr_pending(bus->sdh) ? " " : " not ")); bcm_bprintf(strbuf, "blocksize %d roundup %d\n", bus->blocksize, bus->roundup); #endif /* DHD_DEBUG */ bcm_bprintf(strbuf, "clkstate %d activity %d idletime %d idlecount %d sleeping %d\n", bus->clkstate, bus->activity, bus->idletime, bus->idlecount, bus->sleeping); } void dhd_bus_clearcounts(dhd_pub_t *dhdp) { dhd_bus_t *bus = (dhd_bus_t *)dhdp->bus; bus->intrcount = bus->lastintrs = bus->spurious = bus->regfails = 0; bus->rxrtx = bus->rx_toolong = bus->rxc_errors = 0; bus->rx_hdrfail = bus->rx_badhdr = bus->rx_badseq = 0; bus->tx_sderrs = bus->fc_rcvd = bus->fc_xoff = bus->fc_xon = 0; bus->rxglomfail = bus->rxglomframes = bus->rxglompkts = 0; bus->f2rxhdrs = bus->f2rxdata = bus->f2txdata = bus->f1regdata = 0; } #ifdef SDTEST static int dhdsdio_pktgen_get(dhd_bus_t *bus, uint8 *arg) { dhd_pktgen_t pktgen; pktgen.version = DHD_PKTGEN_VERSION; pktgen.freq = bus->pktgen_freq; pktgen.count = bus->pktgen_count; pktgen.print = bus->pktgen_print; pktgen.total = bus->pktgen_total; pktgen.minlen = bus->pktgen_minlen; pktgen.maxlen = bus->pktgen_maxlen; pktgen.numsent = bus->pktgen_sent; pktgen.numrcvd = bus->pktgen_rcvd; pktgen.numfail = bus->pktgen_fail; pktgen.mode = bus->pktgen_mode; pktgen.stop = bus->pktgen_stop; bcopy(&pktgen, arg, sizeof(pktgen)); return 0; } static int dhdsdio_pktgen_set(dhd_bus_t *bus, uint8 *arg) { dhd_pktgen_t pktgen; uint oldcnt, oldmode; bcopy(arg, &pktgen, sizeof(pktgen)); if (pktgen.version != DHD_PKTGEN_VERSION) return BCME_BADARG; oldcnt = bus->pktgen_count; oldmode = bus->pktgen_mode; bus->pktgen_freq = pktgen.freq; bus->pktgen_count = pktgen.count; bus->pktgen_print = pktgen.print; bus->pktgen_total = pktgen.total; bus->pktgen_minlen = pktgen.minlen; bus->pktgen_maxlen = pktgen.maxlen; bus->pktgen_mode = pktgen.mode; bus->pktgen_stop = pktgen.stop; bus->pktgen_tick = bus->pktgen_ptick = 0; bus->pktgen_prev_time = jiffies; bus->pktgen_len = MAX(bus->pktgen_len, bus->pktgen_minlen); bus->pktgen_len = MIN(bus->pktgen_len, bus->pktgen_maxlen); /* Clear counts for a new pktgen (mode change, or was stopped) */ if (bus->pktgen_count && (!oldcnt || oldmode != bus->pktgen_mode)) { bus->pktgen_sent = bus->pktgen_prev_sent = bus->pktgen_rcvd = 0; bus->pktgen_prev_rcvd = bus->pktgen_fail = 0; } return 0; } #endif /* SDTEST */ static void dhdsdio_devram_remap(dhd_bus_t *bus, bool val) { uint8 enable, protect, remap; si_socdevram(bus->sih, FALSE, &enable, &protect, &remap); remap = val ? TRUE : FALSE; si_socdevram(bus->sih, TRUE, &enable, &protect, &remap); } static int dhdsdio_membytes(dhd_bus_t *bus, bool write, uint32 address, uint8 *data, uint size) { int bcmerror = 0; uint32 sdaddr; uint dsize; /* In remap mode, adjust address beyond socram and redirect * to devram at SOCDEVRAM_BP_ADDR since remap address > orig_ramsize * is not backplane accessible */ if (REMAP_ENAB(bus) && REMAP_ISADDR(bus, address)) { address -= bus->orig_ramsize; address += SOCDEVRAM_BP_ADDR; } /* Determine initial transfer parameters */ sdaddr = address & SBSDIO_SB_OFT_ADDR_MASK; if ((sdaddr + size) & SBSDIO_SBWINDOW_MASK) dsize = (SBSDIO_SB_OFT_ADDR_LIMIT - sdaddr); else dsize = size; /* Set the backplane window to include the start address */ if ((bcmerror = dhdsdio_set_siaddr_window(bus, address))) { DHD_ERROR(("%s: window change failed\n", __FUNCTION__)); goto xfer_done; } /* Do the transfer(s) */ while (size) { DHD_INFO(("%s: %s %d bytes at offset 0x%08x in window 0x%08x\n", __FUNCTION__, (write ? "write" : "read"), dsize, sdaddr, (address & SBSDIO_SBWINDOW_MASK))); if ((bcmerror = bcmsdh_rwdata(bus->sdh, write, sdaddr, data, dsize))) { DHD_ERROR(("%s: membytes transfer failed\n", __FUNCTION__)); break; } /* Adjust for next transfer (if any) */ if ((size -= dsize)) { data += dsize; address += dsize; if ((bcmerror = dhdsdio_set_siaddr_window(bus, address))) { DHD_ERROR(("%s: window change failed\n", __FUNCTION__)); break; } sdaddr = 0; dsize = MIN(SBSDIO_SB_OFT_ADDR_LIMIT, size); } } xfer_done: /* Return the window to backplane enumeration space for core access */ if (dhdsdio_set_siaddr_window(bus, bcmsdh_cur_sbwad(bus->sdh))) { DHD_ERROR(("%s: FAILED to set window back to 0x%x\n", __FUNCTION__, bcmsdh_cur_sbwad(bus->sdh))); } return bcmerror; } #ifdef DHD_DEBUG static int dhdsdio_readshared(dhd_bus_t *bus, sdpcm_shared_t *sh) { uint32 addr; int rv, i; uint32 shaddr = 0; shaddr = bus->dongle_ram_base + bus->ramsize - 4; i = 0; do { /* Read last word in memory to determine address of sdpcm_shared structure */ if ((rv = dhdsdio_membytes(bus, FALSE, shaddr, (uint8 *)&addr, 4)) < 0) return rv; addr = ltoh32(addr); DHD_INFO(("sdpcm_shared address 0x%08X\n", addr)); /* * Check if addr is valid. * NVRAM length at the end of memory should have been overwritten. */ if (addr == 0 || ((~addr >> 16) & 0xffff) == (addr & 0xffff)) { if ((bus->srmemsize > 0) && (i++ == 0)) { shaddr -= bus->srmemsize; } else { DHD_ERROR(("%s: address (0x%08x) of sdpcm_shared invalid\n", __FUNCTION__, addr)); return BCME_ERROR; } } else break; } while (i < 2); /* Read hndrte_shared structure */ if ((rv = dhdsdio_membytes(bus, FALSE, addr, (uint8 *)sh, sizeof(sdpcm_shared_t))) < 0) return rv; /* Endianness */ sh->flags = ltoh32(sh->flags); sh->trap_addr = ltoh32(sh->trap_addr); sh->assert_exp_addr = ltoh32(sh->assert_exp_addr); sh->assert_file_addr = ltoh32(sh->assert_file_addr); sh->assert_line = ltoh32(sh->assert_line); sh->console_addr = ltoh32(sh->console_addr); sh->msgtrace_addr = ltoh32(sh->msgtrace_addr); if ((sh->flags & SDPCM_SHARED_VERSION_MASK) == 3 && SDPCM_SHARED_VERSION == 1) return BCME_OK; if ((sh->flags & SDPCM_SHARED_VERSION_MASK) != SDPCM_SHARED_VERSION) { DHD_ERROR(("%s: sdpcm_shared version %d in dhd " "is different than sdpcm_shared version %d in dongle\n", __FUNCTION__, SDPCM_SHARED_VERSION, sh->flags & SDPCM_SHARED_VERSION_MASK)); return BCME_ERROR; } return BCME_OK; } #define CONSOLE_LINE_MAX 192 static int dhdsdio_readconsole(dhd_bus_t *bus) { dhd_console_t *c = &bus->console; uint8 line[CONSOLE_LINE_MAX], ch; uint32 n, idx, addr; int rv; /* Don't do anything until FWREADY updates console address */ if (bus->console_addr == 0) return 0; if (!KSO_ENAB(bus)) return 0; /* Read console log struct */ addr = bus->console_addr + OFFSETOF(hndrte_cons_t, log); if ((rv = dhdsdio_membytes(bus, FALSE, addr, (uint8 *)&c->log, sizeof(c->log))) < 0) return rv; /* Allocate console buffer (one time only) */ if (c->buf == NULL) { c->bufsize = ltoh32(c->log.buf_size); if ((c->buf = MALLOC(bus->dhd->osh, c->bufsize)) == NULL) return BCME_NOMEM; } idx = ltoh32(c->log.idx); /* Protect against corrupt value */ if (idx > c->bufsize) return BCME_ERROR; /* Skip reading the console buffer if the index pointer has not moved */ if (idx == c->last) return BCME_OK; /* Read the console buffer */ addr = ltoh32(c->log.buf); if ((rv = dhdsdio_membytes(bus, FALSE, addr, c->buf, c->bufsize)) < 0) return rv; while (c->last != idx) { for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) { if (c->last == idx) { /* This would output a partial line. Instead, back up * the buffer pointer and output this line next time around. */ if (c->last >= n) c->last -= n; else c->last = c->bufsize - n; goto break2; } ch = c->buf[c->last]; c->last = (c->last + 1) % c->bufsize; if (ch == '\n') break; line[n] = ch; } if (n > 0) { if (line[n - 1] == '\r') n--; line[n] = 0; printf("CONSOLE: %s\n", line); } } break2: return BCME_OK; } static int dhdsdio_checkdied(dhd_bus_t *bus, char *data, uint size) { int bcmerror = 0; uint msize = 512; char *mbuffer = NULL; char *console_buffer = NULL; uint maxstrlen = 256; char *str = NULL; trap_t tr; sdpcm_shared_t sdpcm_shared; struct bcmstrbuf strbuf; uint32 console_ptr, console_size, console_index; uint8 line[CONSOLE_LINE_MAX], ch; uint32 n, i, addr; int rv; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (DHD_NOCHECKDIED_ON()) return 0; if (data == NULL) { /* * Called after a rx ctrl timeout. "data" is NULL. * allocate memory to trace the trap or assert. */ size = msize; mbuffer = data = MALLOC(bus->dhd->osh, msize); if (mbuffer == NULL) { DHD_ERROR(("%s: MALLOC(%d) failed \n", __FUNCTION__, msize)); bcmerror = BCME_NOMEM; goto done; } } if ((str = MALLOC(bus->dhd->osh, maxstrlen)) == NULL) { DHD_ERROR(("%s: MALLOC(%d) failed \n", __FUNCTION__, maxstrlen)); bcmerror = BCME_NOMEM; goto done; } if ((bcmerror = dhdsdio_readshared(bus, &sdpcm_shared)) < 0) goto done; bcm_binit(&strbuf, data, size); bcm_bprintf(&strbuf, "msgtrace address : 0x%08X\nconsole address : 0x%08X\n", sdpcm_shared.msgtrace_addr, sdpcm_shared.console_addr); if ((sdpcm_shared.flags & SDPCM_SHARED_ASSERT_BUILT) == 0) { /* NOTE: Misspelled assert is intentional - DO NOT FIX. * (Avoids conflict with real asserts for programmatic parsing of output.) */ bcm_bprintf(&strbuf, "Assrt not built in dongle\n"); } if ((sdpcm_shared.flags & (SDPCM_SHARED_ASSERT|SDPCM_SHARED_TRAP)) == 0) { /* NOTE: Misspelled assert is intentional - DO NOT FIX. * (Avoids conflict with real asserts for programmatic parsing of output.) */ bcm_bprintf(&strbuf, "No trap%s in dongle", (sdpcm_shared.flags & SDPCM_SHARED_ASSERT_BUILT) ?"/assrt" :""); } else { if (sdpcm_shared.flags & SDPCM_SHARED_ASSERT) { /* Download assert */ bcm_bprintf(&strbuf, "Dongle assert"); if (sdpcm_shared.assert_exp_addr != 0) { str[0] = '\0'; if ((bcmerror = dhdsdio_membytes(bus, FALSE, sdpcm_shared.assert_exp_addr, (uint8 *)str, maxstrlen)) < 0) goto done; str[maxstrlen - 1] = '\0'; bcm_bprintf(&strbuf, " expr \"%s\"", str); } if (sdpcm_shared.assert_file_addr != 0) { str[0] = '\0'; if ((bcmerror = dhdsdio_membytes(bus, FALSE, sdpcm_shared.assert_file_addr, (uint8 *)str, maxstrlen)) < 0) goto done; str[maxstrlen - 1] = '\0'; bcm_bprintf(&strbuf, " file \"%s\"", str); } bcm_bprintf(&strbuf, " line %d ", sdpcm_shared.assert_line); } if (sdpcm_shared.flags & SDPCM_SHARED_TRAP) { bus->dhd->dongle_trap_occured = TRUE; if ((bcmerror = dhdsdio_membytes(bus, FALSE, sdpcm_shared.trap_addr, (uint8*)&tr, sizeof(trap_t))) < 0) goto done; bcm_bprintf(&strbuf, "Dongle trap type 0x%x @ epc 0x%x, cpsr 0x%x, spsr 0x%x, sp 0x%x," "lp 0x%x, rpc 0x%x Trap offset 0x%x, " "r0 0x%x, r1 0x%x, r2 0x%x, r3 0x%x, " "r4 0x%x, r5 0x%x, r6 0x%x, r7 0x%x\n\n", ltoh32(tr.type), ltoh32(tr.epc), ltoh32(tr.cpsr), ltoh32(tr.spsr), ltoh32(tr.r13), ltoh32(tr.r14), ltoh32(tr.pc), ltoh32(sdpcm_shared.trap_addr), ltoh32(tr.r0), ltoh32(tr.r1), ltoh32(tr.r2), ltoh32(tr.r3), ltoh32(tr.r4), ltoh32(tr.r5), ltoh32(tr.r6), ltoh32(tr.r7)); addr = sdpcm_shared.console_addr + OFFSETOF(hndrte_cons_t, log); if ((rv = dhdsdio_membytes(bus, FALSE, addr, (uint8 *)&console_ptr, sizeof(console_ptr))) < 0) goto printbuf; addr = sdpcm_shared.console_addr + OFFSETOF(hndrte_cons_t, log.buf_size); if ((rv = dhdsdio_membytes(bus, FALSE, addr, (uint8 *)&console_size, sizeof(console_size))) < 0) goto printbuf; addr = sdpcm_shared.console_addr + OFFSETOF(hndrte_cons_t, log.idx); if ((rv = dhdsdio_membytes(bus, FALSE, addr, (uint8 *)&console_index, sizeof(console_index))) < 0) goto printbuf; console_ptr = ltoh32(console_ptr); console_size = ltoh32(console_size); console_index = ltoh32(console_index); if (console_size > CONSOLE_BUFFER_MAX || !(console_buffer = MALLOC(bus->dhd->osh, console_size))) goto printbuf; if ((rv = dhdsdio_membytes(bus, FALSE, console_ptr, (uint8 *)console_buffer, console_size)) < 0) goto printbuf; for (i = 0, n = 0; i < console_size; i += n + 1) { for (n = 0; n < CONSOLE_LINE_MAX - 2; n++) { ch = console_buffer[(console_index + i + n) % console_size]; if (ch == '\n') break; line[n] = ch; } if (n > 0) { if (line[n - 1] == '\r') n--; line[n] = 0; /* Don't use DHD_ERROR macro since we print * a lot of information quickly. The macro * will truncate a lot of the printfs */ if (dhd_msg_level & DHD_ERROR_VAL) printf("CONSOLE: %s\n", line); } } } } printbuf: if (sdpcm_shared.flags & (SDPCM_SHARED_ASSERT | SDPCM_SHARED_TRAP)) { DHD_ERROR(("%s: %s\n", __FUNCTION__, strbuf.origbuf)); } done: if (mbuffer) MFREE(bus->dhd->osh, mbuffer, msize); if (str) MFREE(bus->dhd->osh, str, maxstrlen); if (console_buffer) MFREE(bus->dhd->osh, console_buffer, console_size); return bcmerror; } #endif /* #ifdef DHD_DEBUG */ int dhdsdio_downloadvars(dhd_bus_t *bus, void *arg, int len) { int bcmerror = BCME_OK; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); /* Basic sanity checks */ if (bus->dhd->up) { bcmerror = BCME_NOTDOWN; goto err; } if (!len) { bcmerror = BCME_BUFTOOSHORT; goto err; } /* Free the old ones and replace with passed variables */ if (bus->vars) MFREE(bus->dhd->osh, bus->vars, bus->varsz); bus->vars = MALLOC(bus->dhd->osh, len); bus->varsz = bus->vars ? len : 0; if (bus->vars == NULL) { bcmerror = BCME_NOMEM; goto err; } /* Copy the passed variables, which should include the terminating double-null */ bcopy(arg, bus->vars, bus->varsz); err: return bcmerror; } #ifdef DHD_DEBUG #define CC_PLL_CHIPCTRL_SERIAL_ENAB (1 << 24) #define CC_CHIPCTRL_JTAG_SEL (1 << 3) #define CC_CHIPCTRL_GPIO_SEL (0x3) #define CC_PLL_CHIPCTRL_SERIAL_ENAB_4334 (1 << 28) static int dhd_serialconsole(dhd_bus_t *bus, bool set, bool enable, int *bcmerror) { int int_val; uint32 addr, data, uart_enab = 0; uint32 jtag_sel = CC_CHIPCTRL_JTAG_SEL; uint32 gpio_sel = CC_CHIPCTRL_GPIO_SEL; addr = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_addr); data = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol_data); *bcmerror = 0; bcmsdh_reg_write(bus->sdh, addr, 4, 1); if (bcmsdh_regfail(bus->sdh)) { *bcmerror = BCME_SDIO_ERROR; return -1; } int_val = bcmsdh_reg_read(bus->sdh, data, 4); if (bcmsdh_regfail(bus->sdh)) { *bcmerror = BCME_SDIO_ERROR; return -1; } if (bus->sih->chip == BCM4330_CHIP_ID) { uart_enab = CC_PLL_CHIPCTRL_SERIAL_ENAB; } else if (bus->sih->chip == BCM4334_CHIP_ID || bus->sih->chip == BCM43341_CHIP_ID || 0) { if (enable) { /* Moved to PMU chipcontrol 1 from 4330 */ int_val &= ~gpio_sel; int_val |= jtag_sel; } else { int_val |= gpio_sel; int_val &= ~jtag_sel; } uart_enab = CC_PLL_CHIPCTRL_SERIAL_ENAB_4334; } if (!set) return (int_val & uart_enab); if (enable) int_val |= uart_enab; else int_val &= ~uart_enab; bcmsdh_reg_write(bus->sdh, data, 4, int_val); if (bcmsdh_regfail(bus->sdh)) { *bcmerror = BCME_SDIO_ERROR; return -1; } if (bus->sih->chip == BCM4330_CHIP_ID) { uint32 chipcontrol; addr = SI_ENUM_BASE + OFFSETOF(chipcregs_t, chipcontrol); chipcontrol = bcmsdh_reg_read(bus->sdh, addr, 4); chipcontrol &= ~jtag_sel; if (enable) { chipcontrol |= jtag_sel; chipcontrol &= ~gpio_sel; } bcmsdh_reg_write(bus->sdh, addr, 4, chipcontrol); } return (int_val & uart_enab); } #endif static int dhdsdio_doiovar(dhd_bus_t *bus, const bcm_iovar_t *vi, uint32 actionid, const char *name, void *params, int plen, void *arg, int len, int val_size) { int bcmerror = 0; int32 int_val = 0; bool bool_val = 0; DHD_TRACE(("%s: Enter, action %d name %s params %p plen %d arg %p len %d val_size %d\n", __FUNCTION__, actionid, name, params, plen, arg, len, val_size)); if ((bcmerror = bcm_iovar_lencheck(vi, arg, len, IOV_ISSET(actionid))) != 0) goto exit; if (plen >= (int)sizeof(int_val)) bcopy(params, &int_val, sizeof(int_val)); bool_val = (int_val != 0) ? TRUE : FALSE; /* Some ioctls use the bus */ dhd_os_sdlock(bus->dhd); /* Check if dongle is in reset. If so, only allow DEVRESET iovars */ if (bus->dhd->dongle_reset && !(actionid == IOV_SVAL(IOV_DEVRESET) || actionid == IOV_GVAL(IOV_DEVRESET))) { bcmerror = BCME_NOTREADY; goto exit; } /* * Special handling for keepSdioOn: New SDIO Wake-up Mechanism */ if ((vi->varid == IOV_KSO) && (IOV_ISSET(actionid))) { dhdsdio_clk_kso_iovar(bus, bool_val); goto exit; } else if ((vi->varid == IOV_DEVSLEEP) && (IOV_ISSET(actionid))) { { dhdsdio_clk_devsleep_iovar(bus, bool_val); if (!SLPAUTO_ENAB(bus) && (bool_val == FALSE) && (bus->ipend)) { DHD_ERROR(("INT pending in devsleep 1, dpc_sched: %d\n", bus->dpc_sched)); if (!bus->dpc_sched) { bus->dpc_sched = TRUE; dhd_sched_dpc(bus->dhd); } } } goto exit; } /* Handle sleep stuff before any clock mucking */ if (vi->varid == IOV_SLEEP) { if (IOV_ISSET(actionid)) { bcmerror = dhdsdio_bussleep(bus, bool_val); } else { int_val = (int32)bus->sleeping; bcopy(&int_val, arg, val_size); } goto exit; } /* Request clock to allow SDIO accesses */ if (!bus->dhd->dongle_reset) { BUS_WAKE(bus); dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); } switch (actionid) { case IOV_GVAL(IOV_INTR): int_val = (int32)bus->intr; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_INTR): bus->intr = bool_val; bus->intdis = FALSE; if (bus->dhd->up) { if (bus->intr) { DHD_INTR(("%s: enable SDIO device interrupts\n", __FUNCTION__)); bcmsdh_intr_enable(bus->sdh); } else { DHD_INTR(("%s: disable SDIO interrupts\n", __FUNCTION__)); bcmsdh_intr_disable(bus->sdh); } } break; case IOV_GVAL(IOV_POLLRATE): int_val = (int32)bus->pollrate; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_POLLRATE): bus->pollrate = (uint)int_val; bus->poll = (bus->pollrate != 0); break; case IOV_GVAL(IOV_IDLETIME): int_val = bus->idletime; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_IDLETIME): if ((int_val < 0) && (int_val != DHD_IDLE_IMMEDIATE)) { bcmerror = BCME_BADARG; } else { bus->idletime = int_val; } break; case IOV_GVAL(IOV_IDLECLOCK): int_val = (int32)bus->idleclock; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_IDLECLOCK): bus->idleclock = int_val; break; case IOV_GVAL(IOV_SD1IDLE): int_val = (int32)sd1idle; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_SD1IDLE): sd1idle = bool_val; break; case IOV_SVAL(IOV_MEMBYTES): case IOV_GVAL(IOV_MEMBYTES): { uint32 address; uint size, dsize; uint8 *data; bool set = (actionid == IOV_SVAL(IOV_MEMBYTES)); ASSERT(plen >= 2*sizeof(int)); address = (uint32)int_val; bcopy((char *)params + sizeof(int_val), &int_val, sizeof(int_val)); size = (uint)int_val; /* Do some validation */ dsize = set ? plen - (2 * sizeof(int)) : len; if (dsize < size) { DHD_ERROR(("%s: error on %s membytes, addr 0x%08x size %d dsize %d\n", __FUNCTION__, (set ? "set" : "get"), address, size, dsize)); bcmerror = BCME_BADARG; break; } DHD_INFO(("%s: Request to %s %d bytes at address 0x%08x\n", __FUNCTION__, (set ? "write" : "read"), size, address)); /* check if CR4 */ if (si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { /* if address is 0, store the reset instruction to be written in 0 */ if (address == 0) { bus->resetinstr = *(((uint32*)params) + 2); } /* Add start of RAM address to the address given by user */ address += bus->dongle_ram_base; } else { /* If we know about SOCRAM, check for a fit */ if ((bus->orig_ramsize) && ((address > bus->orig_ramsize) || (address + size > bus->orig_ramsize))) { uint8 enable, protect, remap; si_socdevram(bus->sih, FALSE, &enable, &protect, &remap); if (!enable || protect) { DHD_ERROR(("%s: ramsize 0x%08x doesn't have %d bytes at 0x%08x\n", __FUNCTION__, bus->orig_ramsize, size, address)); DHD_ERROR(("%s: socram enable %d, protect %d\n", __FUNCTION__, enable, protect)); bcmerror = BCME_BADARG; break; } if (!REMAP_ENAB(bus) && (address >= SOCDEVRAM_ARM_ADDR)) { uint32 devramsize = si_socdevram_size(bus->sih); if ((address < SOCDEVRAM_ARM_ADDR) || (address + size > (SOCDEVRAM_ARM_ADDR + devramsize))) { DHD_ERROR(("%s: bad address 0x%08x, size 0x%08x\n", __FUNCTION__, address, size)); DHD_ERROR(("%s: socram range 0x%08x,size 0x%08x\n", __FUNCTION__, SOCDEVRAM_ARM_ADDR, devramsize)); bcmerror = BCME_BADARG; break; } /* move it such that address is real now */ address -= SOCDEVRAM_ARM_ADDR; address += SOCDEVRAM_BP_ADDR; DHD_INFO(("%s: Request to %s %d bytes @ Mapped address 0x%08x\n", __FUNCTION__, (set ? "write" : "read"), size, address)); } else if (REMAP_ENAB(bus) && REMAP_ISADDR(bus, address) && remap) { /* Can not access remap region while devram remap bit is set * ROM content would be returned in this case */ DHD_ERROR(("%s: Need to disable remap for address 0x%08x\n", __FUNCTION__, address)); bcmerror = BCME_ERROR; break; } } } /* Generate the actual data pointer */ data = set ? (uint8*)params + 2 * sizeof(int): (uint8*)arg; /* Call to do the transfer */ bcmerror = dhdsdio_membytes(bus, set, address, data, size); break; } case IOV_GVAL(IOV_MEMSIZE): int_val = (int32)bus->ramsize; bcopy(&int_val, arg, val_size); break; case IOV_GVAL(IOV_SDIOD_DRIVE): int_val = (int32)dhd_sdiod_drive_strength; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_SDIOD_DRIVE): dhd_sdiod_drive_strength = int_val; si_sdiod_drive_strength_init(bus->sih, bus->dhd->osh, dhd_sdiod_drive_strength); break; case IOV_SVAL(IOV_SET_DOWNLOAD_STATE): bcmerror = dhdsdio_download_state(bus, bool_val); break; case IOV_SVAL(IOV_SOCRAM_STATE): bcmerror = dhdsdio_download_state(bus, bool_val); break; case IOV_SVAL(IOV_VARS): bcmerror = dhdsdio_downloadvars(bus, arg, len); break; case IOV_GVAL(IOV_READAHEAD): int_val = (int32)dhd_readahead; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_READAHEAD): if (bool_val && !dhd_readahead) bus->nextlen = 0; dhd_readahead = bool_val; break; case IOV_GVAL(IOV_SDRXCHAIN): int_val = (int32)bus->use_rxchain; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_SDRXCHAIN): if (bool_val && !bus->sd_rxchain) bcmerror = BCME_UNSUPPORTED; else bus->use_rxchain = bool_val; break; #ifndef BCMSPI case IOV_GVAL(IOV_ALIGNCTL): int_val = (int32)dhd_alignctl; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_ALIGNCTL): dhd_alignctl = bool_val; break; #endif /* BCMSPI */ case IOV_GVAL(IOV_SDALIGN): int_val = DHD_SDALIGN; bcopy(&int_val, arg, val_size); break; #ifdef DHD_DEBUG case IOV_GVAL(IOV_VARS): if (bus->varsz < (uint)len) bcopy(bus->vars, arg, bus->varsz); else bcmerror = BCME_BUFTOOSHORT; break; #endif /* DHD_DEBUG */ #ifdef DHD_DEBUG case IOV_GVAL(IOV_SDREG): { sdreg_t *sd_ptr; uint32 addr, size; sd_ptr = (sdreg_t *)params; addr = (uintptr)bus->regs + sd_ptr->offset; size = sd_ptr->func; int_val = (int32)bcmsdh_reg_read(bus->sdh, addr, size); if (bcmsdh_regfail(bus->sdh)) bcmerror = BCME_SDIO_ERROR; bcopy(&int_val, arg, sizeof(int32)); break; } case IOV_SVAL(IOV_SDREG): { sdreg_t *sd_ptr; uint32 addr, size; sd_ptr = (sdreg_t *)params; addr = (uintptr)bus->regs + sd_ptr->offset; size = sd_ptr->func; bcmsdh_reg_write(bus->sdh, addr, size, sd_ptr->value); if (bcmsdh_regfail(bus->sdh)) bcmerror = BCME_SDIO_ERROR; break; } /* Same as above, but offset is not backplane (not SDIO core) */ case IOV_GVAL(IOV_SBREG): { sdreg_t sdreg; uint32 addr, size; bcopy(params, &sdreg, sizeof(sdreg)); addr = SI_ENUM_BASE + sdreg.offset; size = sdreg.func; int_val = (int32)bcmsdh_reg_read(bus->sdh, addr, size); if (bcmsdh_regfail(bus->sdh)) bcmerror = BCME_SDIO_ERROR; bcopy(&int_val, arg, sizeof(int32)); break; } case IOV_SVAL(IOV_SBREG): { sdreg_t sdreg; uint32 addr, size; bcopy(params, &sdreg, sizeof(sdreg)); addr = SI_ENUM_BASE + sdreg.offset; size = sdreg.func; bcmsdh_reg_write(bus->sdh, addr, size, sdreg.value); if (bcmsdh_regfail(bus->sdh)) bcmerror = BCME_SDIO_ERROR; break; } case IOV_GVAL(IOV_SDCIS): { *(char *)arg = 0; bcmstrcat(arg, "\nFunc 0\n"); bcmsdh_cis_read(bus->sdh, 0x10, (uint8 *)arg + strlen(arg), SBSDIO_CIS_SIZE_LIMIT); bcmstrcat(arg, "\nFunc 1\n"); bcmsdh_cis_read(bus->sdh, 0x11, (uint8 *)arg + strlen(arg), SBSDIO_CIS_SIZE_LIMIT); bcmstrcat(arg, "\nFunc 2\n"); bcmsdh_cis_read(bus->sdh, 0x12, (uint8 *)arg + strlen(arg), SBSDIO_CIS_SIZE_LIMIT); break; } case IOV_GVAL(IOV_FORCEEVEN): int_val = (int32)forcealign; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_FORCEEVEN): forcealign = bool_val; break; case IOV_GVAL(IOV_TXBOUND): int_val = (int32)dhd_txbound; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_TXBOUND): dhd_txbound = (uint)int_val; break; case IOV_GVAL(IOV_RXBOUND): int_val = (int32)dhd_rxbound; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_RXBOUND): dhd_rxbound = (uint)int_val; break; case IOV_GVAL(IOV_TXMINMAX): int_val = (int32)dhd_txminmax; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_TXMINMAX): dhd_txminmax = (uint)int_val; break; case IOV_GVAL(IOV_SERIALCONS): int_val = dhd_serialconsole(bus, FALSE, 0, &bcmerror); if (bcmerror != 0) break; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_SERIALCONS): dhd_serialconsole(bus, TRUE, bool_val, &bcmerror); break; #endif /* DHD_DEBUG */ #ifdef SDTEST case IOV_GVAL(IOV_EXTLOOP): int_val = (int32)bus->ext_loop; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_EXTLOOP): bus->ext_loop = bool_val; break; case IOV_GVAL(IOV_PKTGEN): bcmerror = dhdsdio_pktgen_get(bus, arg); break; case IOV_SVAL(IOV_PKTGEN): bcmerror = dhdsdio_pktgen_set(bus, arg); break; #endif /* SDTEST */ #if defined(SDIO_CRC_ERROR_FIX) case IOV_GVAL(IOV_WATERMARK): int_val = (int32)watermark; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_WATERMARK): watermark = (uint)int_val; watermark = (watermark > SBSDIO_WATERMARK_MASK) ? SBSDIO_WATERMARK_MASK : watermark; DHD_ERROR(("Setting watermark as 0x%x.\n", watermark)); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_WATERMARK, (uint8)watermark, NULL); break; case IOV_GVAL(IOV_MESBUSYCTRL): int_val = (int32)mesbusyctrl; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_MESBUSYCTRL): mesbusyctrl = (uint)int_val; mesbusyctrl = (mesbusyctrl > SBSDIO_MESBUSYCTRL_MASK) ? SBSDIO_MESBUSYCTRL_MASK : mesbusyctrl; DHD_ERROR(("Setting mesbusyctrl as 0x%x.\n", mesbusyctrl)); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_MESBUSYCTRL, ((uint8)mesbusyctrl | 0x80), NULL); break; #endif /* SDIO_CRC_ERROR_FIX */ case IOV_GVAL(IOV_DONGLEISOLATION): int_val = bus->dhd->dongle_isolation; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_DONGLEISOLATION): bus->dhd->dongle_isolation = bool_val; break; case IOV_SVAL(IOV_DEVRESET): DHD_TRACE(("%s: Called set IOV_DEVRESET=%d dongle_reset=%d busstate=%d\n", __FUNCTION__, bool_val, bus->dhd->dongle_reset, bus->dhd->busstate)); ASSERT(bus->dhd->osh); /* ASSERT(bus->cl_devid); */ dhd_bus_devreset(bus->dhd, (uint8)bool_val); break; #ifdef SOFTAP case IOV_GVAL(IOV_FWPATH): { uint32 fw_path_len; fw_path_len = strlen(bus->fw_path); DHD_INFO(("[softap] get fwpath, l=%d\n", len)); if (fw_path_len > len-1) { bcmerror = BCME_BUFTOOSHORT; break; } if (fw_path_len) { bcopy(bus->fw_path, arg, fw_path_len); ((uchar*)arg)[fw_path_len] = 0; } break; } case IOV_SVAL(IOV_FWPATH): DHD_INFO(("[softap] set fwpath, idx=%d\n", int_val)); switch (int_val) { case 1: bus->fw_path = fw_path; /* ordinary one */ break; case 2: bus->fw_path = fw_path2; break; default: bcmerror = BCME_BADARG; break; } DHD_INFO(("[softap] new fw path: %s\n", (bus->fw_path[0] ? bus->fw_path : "NULL"))); break; #endif /* SOFTAP */ case IOV_GVAL(IOV_DEVRESET): DHD_TRACE(("%s: Called get IOV_DEVRESET\n", __FUNCTION__)); /* Get its status */ int_val = (bool) bus->dhd->dongle_reset; bcopy(&int_val, arg, val_size); break; case IOV_GVAL(IOV_KSO): int_val = dhdsdio_sleepcsr_get(bus); bcopy(&int_val, arg, val_size); break; case IOV_GVAL(IOV_DEVCAP): int_val = dhdsdio_devcap_get(bus); bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_DEVCAP): dhdsdio_devcap_set(bus, (uint8) int_val); break; #ifdef BCMSDIOH_TXGLOM case IOV_GVAL(IOV_TXGLOMSIZE): int_val = (int32)bus->glomsize; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_TXGLOMSIZE): if (int_val > SDPCM_MAXGLOM_SIZE) { bcmerror = BCME_ERROR; } else { bus->glomsize = (uint)int_val; } break; case IOV_GVAL(IOV_TXGLOMMODE): int_val = (int32)bus->glom_mode; bcopy(&int_val, arg, val_size); break; case IOV_SVAL(IOV_TXGLOMMODE): if ((int_val != SDPCM_TXGLOM_CPY) && (int_val != SDPCM_TXGLOM_MDESC)) { bcmerror = BCME_RANGE; } else { if ((bus->glom_mode = bcmsdh_set_mode(bus->sdh, (uint)int_val)) != int_val) bcmerror = BCME_ERROR; } break; #endif /* BCMSDIOH_TXGLOM */ default: bcmerror = BCME_UNSUPPORTED; break; } exit: if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, TRUE); } dhd_os_sdunlock(bus->dhd); return bcmerror; } static int dhdsdio_write_vars(dhd_bus_t *bus) { int bcmerror = 0; uint32 varsize, phys_size; uint32 varaddr; uint8 *vbuffer; uint32 varsizew; #ifdef DHD_DEBUG uint8 *nvram_ularray; #endif /* DHD_DEBUG */ /* Even if there are no vars are to be written, we still need to set the ramsize. */ varsize = bus->varsz ? ROUNDUP(bus->varsz, 4) : 0; varaddr = (bus->ramsize - 4) - varsize; varaddr += bus->dongle_ram_base; if (bus->vars) { if ((bus->sih->buscoretype == SDIOD_CORE_ID) && (bus->sdpcmrev == 7)) { if (((varaddr & 0x3C) == 0x3C) && (varsize > 4)) { DHD_ERROR(("PR85623WAR in place\n")); varsize += 4; varaddr -= 4; } } vbuffer = (uint8 *)MALLOC(bus->dhd->osh, varsize); if (!vbuffer) return BCME_NOMEM; bzero(vbuffer, varsize); bcopy(bus->vars, vbuffer, bus->varsz); /* Write the vars list */ bcmerror = dhdsdio_membytes(bus, TRUE, varaddr, vbuffer, varsize); #ifdef DHD_DEBUG /* Verify NVRAM bytes */ DHD_INFO(("Compare NVRAM dl & ul; varsize=%d\n", varsize)); nvram_ularray = (uint8*)MALLOC(bus->dhd->osh, varsize); if (!nvram_ularray) return BCME_NOMEM; /* Upload image to verify downloaded contents. */ memset(nvram_ularray, 0xaa, varsize); /* Read the vars list to temp buffer for comparison */ bcmerror = dhdsdio_membytes(bus, FALSE, varaddr, nvram_ularray, varsize); if (bcmerror) { DHD_ERROR(("%s: error %d on reading %d nvram bytes at 0x%08x\n", __FUNCTION__, bcmerror, varsize, varaddr)); } /* Compare the org NVRAM with the one read from RAM */ if (memcmp(vbuffer, nvram_ularray, varsize)) { DHD_ERROR(("%s: Downloaded NVRAM image is corrupted.\n", __FUNCTION__)); } else DHD_ERROR(("%s: Download, Upload and compare of NVRAM succeeded.\n", __FUNCTION__)); MFREE(bus->dhd->osh, nvram_ularray, varsize); #endif /* DHD_DEBUG */ MFREE(bus->dhd->osh, vbuffer, varsize); } phys_size = REMAP_ENAB(bus) ? bus->ramsize : bus->orig_ramsize; phys_size += bus->dongle_ram_base; /* adjust to the user specified RAM */ DHD_INFO(("Physical memory size: %d, usable memory size: %d\n", phys_size, bus->ramsize)); DHD_INFO(("Vars are at %d, orig varsize is %d\n", varaddr, varsize)); varsize = ((phys_size - 4) - varaddr); /* * Determine the length token: * Varsize, converted to words, in lower 16-bits, checksum in upper 16-bits. */ if (bcmerror) { varsizew = 0; } else { varsizew = varsize / 4; varsizew = (~varsizew << 16) | (varsizew & 0x0000FFFF); varsizew = htol32(varsizew); } DHD_INFO(("New varsize is %d, length token=0x%08x\n", varsize, varsizew)); /* Write the length token to the last word */ bcmerror = dhdsdio_membytes(bus, TRUE, (phys_size - 4), (uint8*)&varsizew, 4); return bcmerror; } static int dhdsdio_download_state(dhd_bus_t *bus, bool enter) { uint retries; int bcmerror = 0; int foundcr4 = 0; if (!bus->sih) return BCME_ERROR; /* To enter download state, disable ARM and reset SOCRAM. * To exit download state, simply reset ARM (default is RAM boot). */ if (enter) { bus->alp_only = TRUE; if (!(si_setcore(bus->sih, ARM7S_CORE_ID, 0)) && !(si_setcore(bus->sih, ARMCM3_CORE_ID, 0))) { if (si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { foundcr4 = 1; } else { DHD_ERROR(("%s: Failed to find ARM core!\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } } if (!foundcr4) { si_core_disable(bus->sih, 0); if (bcmsdh_regfail(bus->sdh)) { bcmerror = BCME_SDIO_ERROR; goto fail; } if (!(si_setcore(bus->sih, SOCRAM_CORE_ID, 0))) { DHD_ERROR(("%s: Failed to find SOCRAM core!\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } si_core_reset(bus->sih, 0, 0); if (bcmsdh_regfail(bus->sdh)) { DHD_ERROR(("%s: Failure trying reset SOCRAM core?\n", __FUNCTION__)); bcmerror = BCME_SDIO_ERROR; goto fail; } /* Disable remap for download */ if (REMAP_ENAB(bus) && si_socdevram_remap_isenb(bus->sih)) dhdsdio_devram_remap(bus, FALSE); /* Clear the top bit of memory */ if (bus->ramsize) { uint32 zeros = 0; if (dhdsdio_membytes(bus, TRUE, bus->ramsize - 4, (uint8*)&zeros, 4) < 0) { bcmerror = BCME_SDIO_ERROR; goto fail; } } } else { /* For CR4, * Halt ARM * Remove ARM reset * Read RAM base address [0x18_0000] * [next] Download firmware * [done at else] Populate the reset vector * [done at else] Remove ARM halt */ /* Halt ARM & remove reset */ si_core_reset(bus->sih, SICF_CPUHALT, SICF_CPUHALT); } } else { if (!si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { if (!(si_setcore(bus->sih, SOCRAM_CORE_ID, 0))) { DHD_ERROR(("%s: Failed to find SOCRAM core!\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } if (!si_iscoreup(bus->sih)) { DHD_ERROR(("%s: SOCRAM core is down after reset?\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } if ((bcmerror = dhdsdio_write_vars(bus))) { DHD_ERROR(("%s: could not write vars to RAM\n", __FUNCTION__)); goto fail; } /* Enable remap before ARM reset but after vars. * No backplane access in remap mode */ if (REMAP_ENAB(bus) && !si_socdevram_remap_isenb(bus->sih)) dhdsdio_devram_remap(bus, TRUE); if (!si_setcore(bus->sih, PCMCIA_CORE_ID, 0) && !si_setcore(bus->sih, SDIOD_CORE_ID, 0)) { DHD_ERROR(("%s: Can't change back to SDIO core?\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } W_SDREG(0xFFFFFFFF, &bus->regs->intstatus, retries); if (!(si_setcore(bus->sih, ARM7S_CORE_ID, 0)) && !(si_setcore(bus->sih, ARMCM3_CORE_ID, 0))) { DHD_ERROR(("%s: Failed to find ARM core!\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } } else { /* cr4 has no socram, but tcm's */ /* write vars */ if ((bcmerror = dhdsdio_write_vars(bus))) { DHD_ERROR(("%s: could not write vars to RAM\n", __FUNCTION__)); goto fail; } if (!si_setcore(bus->sih, PCMCIA_CORE_ID, 0) && !si_setcore(bus->sih, SDIOD_CORE_ID, 0)) { DHD_ERROR(("%s: Can't change back to SDIO core?\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } W_SDREG(0xFFFFFFFF, &bus->regs->intstatus, retries); /* switch back to arm core again */ if (!(si_setcore(bus->sih, ARMCR4_CORE_ID, 0))) { DHD_ERROR(("%s: Failed to find ARM CR4 core!\n", __FUNCTION__)); bcmerror = BCME_ERROR; goto fail; } /* write address 0 with reset instruction */ bcmerror = dhdsdio_membytes(bus, TRUE, 0, (uint8 *)&bus->resetinstr, sizeof(bus->resetinstr)); /* now remove reset and halt and continue to run CR4 */ } si_core_reset(bus->sih, 0, 0); if (bcmsdh_regfail(bus->sdh)) { DHD_ERROR(("%s: Failure trying to reset ARM core?\n", __FUNCTION__)); bcmerror = BCME_SDIO_ERROR; goto fail; } /* Allow HT Clock now that the ARM is running. */ bus->alp_only = FALSE; bus->dhd->busstate = DHD_BUS_LOAD; } fail: /* Always return to SDIOD core */ if (!si_setcore(bus->sih, PCMCIA_CORE_ID, 0)) si_setcore(bus->sih, SDIOD_CORE_ID, 0); return bcmerror; } int dhd_bus_iovar_op(dhd_pub_t *dhdp, const char *name, void *params, int plen, void *arg, int len, bool set) { dhd_bus_t *bus = dhdp->bus; const bcm_iovar_t *vi = NULL; int bcmerror = 0; int val_size; uint32 actionid; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); ASSERT(name); ASSERT(len >= 0); /* Get MUST have return space */ ASSERT(set || (arg && len)); /* Set does NOT take qualifiers */ ASSERT(!set || (!params && !plen)); /* Look up var locally; if not found pass to host driver */ if ((vi = bcm_iovar_lookup(dhdsdio_iovars, name)) == NULL) { dhd_os_sdlock(bus->dhd); BUS_WAKE(bus); /* Turn on clock in case SD command needs backplane */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); bcmerror = bcmsdh_iovar_op(bus->sdh, name, params, plen, arg, len, set); /* Check for bus configuration changes of interest */ /* If it was divisor change, read the new one */ if (set && strcmp(name, "sd_divisor") == 0) { if (bcmsdh_iovar_op(bus->sdh, "sd_divisor", NULL, 0, &bus->sd_divisor, sizeof(int32), FALSE) != BCME_OK) { bus->sd_divisor = -1; DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, name)); } else { DHD_INFO(("%s: noted %s update, value now %d\n", __FUNCTION__, name, bus->sd_divisor)); } } /* If it was a mode change, read the new one */ if (set && strcmp(name, "sd_mode") == 0) { if (bcmsdh_iovar_op(bus->sdh, "sd_mode", NULL, 0, &bus->sd_mode, sizeof(int32), FALSE) != BCME_OK) { bus->sd_mode = -1; DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, name)); } else { DHD_INFO(("%s: noted %s update, value now %d\n", __FUNCTION__, name, bus->sd_mode)); } } /* Similar check for blocksize change */ if (set && strcmp(name, "sd_blocksize") == 0) { int32 fnum = 2; if (bcmsdh_iovar_op(bus->sdh, "sd_blocksize", &fnum, sizeof(int32), &bus->blocksize, sizeof(int32), FALSE) != BCME_OK) { bus->blocksize = 0; DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, "sd_blocksize")); } else { DHD_INFO(("%s: noted %s update, value now %d\n", __FUNCTION__, "sd_blocksize", bus->blocksize)); if (bus->sih->chip == BCM4335_CHIP_ID) dhd_overflow_war(bus); } } bus->roundup = MIN(max_roundup, bus->blocksize); if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, TRUE); } dhd_os_sdunlock(bus->dhd); goto exit; } DHD_CTL(("%s: %s %s, len %d plen %d\n", __FUNCTION__, name, (set ? "set" : "get"), len, plen)); /* set up 'params' pointer in case this is a set command so that * the convenience int and bool code can be common to set and get */ if (params == NULL) { params = arg; plen = len; } if (vi->type == IOVT_VOID) val_size = 0; else if (vi->type == IOVT_BUFFER) val_size = len; else /* all other types are integer sized */ val_size = sizeof(int); actionid = set ? IOV_SVAL(vi->varid) : IOV_GVAL(vi->varid); bcmerror = dhdsdio_doiovar(bus, vi, actionid, name, params, plen, arg, len, val_size); exit: return bcmerror; } void dhd_bus_stop(struct dhd_bus *bus, bool enforce_mutex) { osl_t *osh; uint32 local_hostintmask; uint8 saveclk, dat; uint retries; int err; if (!bus->dhd) return; osh = bus->dhd->osh; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); bcmsdh_waitlockfree(NULL); if (enforce_mutex) dhd_os_sdlock(bus->dhd); if ((bus->dhd->busstate == DHD_BUS_DOWN) || bus->dhd->hang_was_sent) { /* if Firmware already hangs disbale any interrupt */ bus->dhd->busstate = DHD_BUS_DOWN; bus->hostintmask = 0; bcmsdh_intr_disable(bus->sdh); } else { BUS_WAKE(bus); if (KSO_ENAB(bus)) { /* Mask the interrupt */ dat = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_INTEN, NULL); dat &= ~(INTR_CTL_FUNC1_EN | INTR_CTL_FUNC2_EN); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_INTEN, dat, NULL); } /* Change our idea of bus state */ bus->dhd->busstate = DHD_BUS_DOWN; if (KSO_ENAB(bus)) { /* Enable clock for device interrupts */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); /* Disable and clear interrupts at the chip level also */ W_SDREG(0, &bus->regs->hostintmask, retries); local_hostintmask = bus->hostintmask; bus->hostintmask = 0; /* Force clocks on backplane to be sure F2 interrupt propagates */ saveclk = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if (!err) { bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, (saveclk | SBSDIO_FORCE_HT), &err); } if (err) { DHD_ERROR(("%s: Failed to force clock for F2: err %d\n", __FUNCTION__, err)); } /* Turn off the bus (F2), free any pending packets */ DHD_INTR(("%s: disable SDIO interrupts\n", __FUNCTION__)); bcmsdh_intr_disable(bus->sdh); #ifndef BCMSPI bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_IOEN, SDIO_FUNC_ENABLE_1, NULL); #endif /* !BCMSPI */ /* Clear any pending interrupts now that F2 is disabled */ W_SDREG(local_hostintmask, &bus->regs->intstatus, retries); } /* Turn off the backplane clock (only) */ dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); } /* Clear the data packet queues */ pktq_flush(osh, &bus->txq, TRUE, NULL, 0); /* Clear any held glomming stuff */ if (bus->glomd) PKTFREE(osh, bus->glomd, FALSE); if (bus->glom) PKTFREE(osh, bus->glom, FALSE); bus->glom = bus->glomd = NULL; /* Clear rx control and wake any waiters */ bus->rxlen = 0; dhd_os_ioctl_resp_wake(bus->dhd); /* Reset some F2 state stuff */ bus->rxskip = FALSE; bus->tx_seq = bus->rx_seq = 0; bus->tx_max = 4; if (enforce_mutex) dhd_os_sdunlock(bus->dhd); } #ifdef BCMSDIOH_TXGLOM void dhd_txglom_enable(dhd_pub_t *dhdp, bool enable) { dhd_bus_t *bus = dhdp->bus; char buf[256]; uint32 rxglom; int32 ret; if (enable) { rxglom = 1; memset(buf, 0, sizeof(buf)); bcm_mkiovar("bus:rxglom", (void *)&rxglom, 4, buf, sizeof(buf)); ret = dhd_wl_ioctl_cmd(dhdp, WLC_SET_VAR, buf, sizeof(buf), TRUE, 0); if (!(ret < 0)) { bus->glom_enable = TRUE; } } else { bus->glom_enable = FALSE; } } #endif /* BCMSDIOH_TXGLOM */ int dhd_bus_init(dhd_pub_t *dhdp, bool enforce_mutex) { dhd_bus_t *bus = dhdp->bus; dhd_timeout_t tmo; uint retries = 0; uint8 ready, enable; int err, ret = 0; #ifdef BCMSPI uint32 dstatus = 0; /* gSPI device-status bits */ #else /* BCMSPI */ uint8 saveclk; #endif /* BCMSPI */ DHD_TRACE(("%s: Enter\n", __FUNCTION__)); ASSERT(bus->dhd); if (!bus->dhd) return 0; if (enforce_mutex) dhd_os_sdlock(bus->dhd); /* Make sure backplane clock is on, needed to generate F2 interrupt */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); if (bus->clkstate != CLK_AVAIL) { DHD_ERROR(("%s: clock state is wrong. state = %d\n", __FUNCTION__, bus->clkstate)); ret = -1; goto exit; } #ifdef BCMSPI /* fake "ready" for spi, wake-wlan would have already enabled F1 and F2 */ ready = (SDIO_FUNC_ENABLE_1 | SDIO_FUNC_ENABLE_2); enable = 0; /* Give the dongle some time to do its thing and set IOR2 */ dhd_timeout_start(&tmo, WAIT_F2RXFIFORDY * WAIT_F2RXFIFORDY_DELAY * 1000); while (!enable && !dhd_timeout_expired(&tmo)) { dstatus = bcmsdh_cfg_read_word(bus->sdh, SDIO_FUNC_0, SPID_STATUS_REG, NULL); if (dstatus & STATUS_F2_RX_READY) enable = TRUE; } if (enable) { DHD_ERROR(("Took %u usec before dongle is ready\n", tmo.elapsed)); enable = ready; } else { DHD_ERROR(("dstatus when timed out on f2-fifo not ready = 0x%x\n", dstatus)); DHD_ERROR(("Waited %u usec, dongle is not ready\n", tmo.elapsed)); ret = -1; goto exit; } #else /* !BCMSPI */ /* Force clocks on backplane to be sure F2 interrupt propagates */ saveclk = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if (!err) { bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, (saveclk | SBSDIO_FORCE_HT), &err); } if (err) { DHD_ERROR(("%s: Failed to force clock for F2: err %d\n", __FUNCTION__, err)); ret = -1; goto exit; } /* Enable function 2 (frame transfers) */ W_SDREG((SDPCM_PROT_VERSION << SMB_DATA_VERSION_SHIFT), &bus->regs->tosbmailboxdata, retries); enable = (SDIO_FUNC_ENABLE_1 | SDIO_FUNC_ENABLE_2); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_IOEN, enable, NULL); /* Give the dongle some time to do its thing and set IOR2 */ dhd_timeout_start(&tmo, DHD_WAIT_F2RDY * 1000); ready = 0; while (ready != enable && !dhd_timeout_expired(&tmo)) ready = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_IORDY, NULL); #endif /* !BCMSPI */ DHD_ERROR(("%s: enable 0x%02x, ready 0x%02x (waited %uus)\n", __FUNCTION__, enable, ready, tmo.elapsed)); /* If F2 successfully enabled, set core and enable interrupts */ if (ready == enable) { /* Make sure we're talking to the core. */ if (!(bus->regs = si_setcore(bus->sih, PCMCIA_CORE_ID, 0))) bus->regs = si_setcore(bus->sih, SDIOD_CORE_ID, 0); ASSERT(bus->regs != NULL); /* Set up the interrupt mask and enable interrupts */ bus->hostintmask = HOSTINTMASK; /* corerev 4 could use the newer interrupt logic to detect the frames */ #ifndef BCMSPI if ((bus->sih->buscoretype == SDIOD_CORE_ID) && (bus->sdpcmrev == 4) && (bus->rxint_mode != SDIO_DEVICE_HMB_RXINT)) { bus->hostintmask &= ~I_HMB_FRAME_IND; bus->hostintmask |= I_XMTDATA_AVAIL; } #endif /* BCMSPI */ W_SDREG(bus->hostintmask, &bus->regs->hostintmask, retries); #ifdef SDIO_CRC_ERROR_FIX if (bus->blocksize < 512) { mesbusyctrl = watermark = bus->blocksize / 4; } #endif /* SDIO_CRC_ERROR_FIX */ if (bus->sih->chip != BCM4335_CHIP_ID) { bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_WATERMARK, (uint8)watermark, &err); } #ifdef SDIO_CRC_ERROR_FIX bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_MESBUSYCTRL, (uint8)mesbusyctrl|0x80, &err); bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, SBSDIO_DEVCTL_EN_F2_BLK_WATERMARK, NULL); #endif /* SDIO_CRC_ERROR_FIX */ /* Set bus state according to enable result */ dhdp->busstate = DHD_BUS_DATA; /* bcmsdh_intr_unmask(bus->sdh); */ bus->intdis = FALSE; if (bus->intr) { DHD_INTR(("%s: enable SDIO device interrupts\n", __FUNCTION__)); bcmsdh_intr_enable(bus->sdh); } else { DHD_INTR(("%s: disable SDIO interrupts\n", __FUNCTION__)); bcmsdh_intr_disable(bus->sdh); } } #ifndef BCMSPI else { /* Disable F2 again */ enable = SDIO_FUNC_ENABLE_1; bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_IOEN, enable, NULL); } if (dhdsdio_sr_cap(bus)) dhdsdio_sr_init(bus); else bcmsdh_cfg_write(bus->sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, saveclk, &err); #endif /* !BCMSPI */ /* If we didn't come up, turn off backplane clock */ if (dhdp->busstate != DHD_BUS_DATA) dhdsdio_clkctl(bus, CLK_NONE, FALSE); exit: if (enforce_mutex) dhd_os_sdunlock(bus->dhd); return ret; } static void dhdsdio_rxfail(dhd_bus_t *bus, bool abort, bool rtx) { bcmsdh_info_t *sdh = bus->sdh; sdpcmd_regs_t *regs = bus->regs; uint retries = 0; uint16 lastrbc; uint8 hi, lo; int err; DHD_ERROR(("%s: %sterminate frame%s\n", __FUNCTION__, (abort ? "abort command, " : ""), (rtx ? ", send NAK" : ""))); if (!KSO_ENAB(bus)) { DHD_ERROR(("%s: Device asleep\n", __FUNCTION__)); return; } if (abort) { bcmsdh_abort(sdh, SDIO_FUNC_2); } bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_FRAMECTRL, SFC_RF_TERM, &err); if (err) { DHD_ERROR(("%s: SBSDIO_FUNC1_FRAMECTRL cmd err\n", __FUNCTION__)); goto fail; } bus->f1regdata++; /* Wait until the packet has been flushed (device/FIFO stable) */ for (lastrbc = retries = 0xffff; retries > 0; retries--) { hi = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_RFRAMEBCHI, NULL); lo = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_RFRAMEBCLO, &err); if (err) { DHD_ERROR(("%s: SBSDIO_FUNC1_RFAMEBCLO cmd err\n", __FUNCTION__)); goto fail; } bus->f1regdata += 2; if ((hi == 0) && (lo == 0)) break; if ((hi > (lastrbc >> 8)) && (lo > (lastrbc & 0x00ff))) { DHD_ERROR(("%s: count growing: last 0x%04x now 0x%04x\n", __FUNCTION__, lastrbc, ((hi << 8) + lo))); } lastrbc = (hi << 8) + lo; } if (!retries) { DHD_ERROR(("%s: count never zeroed: last 0x%04x\n", __FUNCTION__, lastrbc)); } else { DHD_INFO(("%s: flush took %d iterations\n", __FUNCTION__, (0xffff - retries))); } if (rtx) { bus->rxrtx++; W_SDREG(SMB_NAK, &regs->tosbmailbox, retries); bus->f1regdata++; if (retries <= retry_limit) { bus->rxskip = TRUE; } } /* Clear partial in any case */ bus->nextlen = 0; fail: /* If we can't reach the device, signal failure */ if (err || bcmsdh_regfail(sdh)) bus->dhd->busstate = DHD_BUS_DOWN; } static void dhdsdio_read_control(dhd_bus_t *bus, uint8 *hdr, uint len, uint doff) { bcmsdh_info_t *sdh = bus->sdh; uint rdlen, pad; int sdret; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); /* Control data already received in aligned rxctl */ if ((bus->bus == SPI_BUS) && (!bus->usebufpool)) goto gotpkt; ASSERT(bus->rxbuf); /* Set rxctl for frame (w/optional alignment) */ bus->rxctl = bus->rxbuf; if (dhd_alignctl) { bus->rxctl += firstread; if ((pad = ((uintptr)bus->rxctl % DHD_SDALIGN))) bus->rxctl += (DHD_SDALIGN - pad); bus->rxctl -= firstread; } ASSERT(bus->rxctl >= bus->rxbuf); /* Copy the already-read portion over */ bcopy(hdr, bus->rxctl, firstread); if (len <= firstread) goto gotpkt; /* Copy the full data pkt in gSPI case and process ioctl. */ if (bus->bus == SPI_BUS) { bcopy(hdr, bus->rxctl, len); goto gotpkt; } /* Raise rdlen to next SDIO block to avoid tail command */ rdlen = len - firstread; if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) { pad = bus->blocksize - (rdlen % bus->blocksize); if ((pad <= bus->roundup) && (pad < bus->blocksize) && ((len + pad) < bus->dhd->maxctl)) rdlen += pad; } else if (rdlen % DHD_SDALIGN) { rdlen += DHD_SDALIGN - (rdlen % DHD_SDALIGN); } /* Satisfy length-alignment requirements */ if (forcealign && (rdlen & (ALIGNMENT - 1))) rdlen = ROUNDUP(rdlen, ALIGNMENT); /* Drop if the read is too big or it exceeds our maximum */ if ((rdlen + firstread) > bus->dhd->maxctl) { DHD_ERROR(("%s: %d-byte control read exceeds %d-byte buffer\n", __FUNCTION__, rdlen, bus->dhd->maxctl)); bus->dhd->rx_errors++; dhdsdio_rxfail(bus, FALSE, FALSE); goto done; } if ((len - doff) > bus->dhd->maxctl) { DHD_ERROR(("%s: %d-byte ctl frame (%d-byte ctl data) exceeds %d-byte limit\n", __FUNCTION__, len, (len - doff), bus->dhd->maxctl)); bus->dhd->rx_errors++; bus->rx_toolong++; dhdsdio_rxfail(bus, FALSE, FALSE); goto done; } /* Read remainder of frame body into the rxctl buffer */ sdret = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, (bus->rxctl + firstread), rdlen, NULL, NULL, NULL); bus->f2rxdata++; ASSERT(sdret != BCME_PENDING); /* Control frame failures need retransmission */ if (sdret < 0) { DHD_ERROR(("%s: read %d control bytes failed: %d\n", __FUNCTION__, rdlen, sdret)); bus->rxc_errors++; /* dhd.rx_ctlerrs is higher level */ dhdsdio_rxfail(bus, TRUE, TRUE); goto done; } gotpkt: #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_CTL_ON()) { prhex("RxCtrl", bus->rxctl, len); } #endif /* Point to valid data and indicate its length */ bus->rxctl += doff; bus->rxlen = len - doff; done: /* Awake any waiters */ dhd_os_ioctl_resp_wake(bus->dhd); } static uint8 dhdsdio_rxglom(dhd_bus_t *bus, uint8 rxseq) { uint16 dlen, totlen; uint8 *dptr, num = 0; uint16 sublen, check; void *pfirst, *plast, *pnext; void * list_tail[DHD_MAX_IFS] = { NULL }; void * list_head[DHD_MAX_IFS] = { NULL }; uint8 idx; osl_t *osh = bus->dhd->osh; int errcode; uint8 chan, seq, doff, sfdoff; uint8 txmax; uchar reorder_info_buf[WLHOST_REORDERDATA_TOTLEN]; uint reorder_info_len; int ifidx = 0; bool usechain = bus->use_rxchain; /* If packets, issue read(s) and send up packet chain */ /* Return sequence numbers consumed? */ DHD_TRACE(("dhdsdio_rxglom: start: glomd %p glom %p\n", bus->glomd, bus->glom)); /* If there's a descriptor, generate the packet chain */ if (bus->glomd) { dhd_os_sdlock_rxq(bus->dhd); pfirst = plast = pnext = NULL; dlen = (uint16)PKTLEN(osh, bus->glomd); dptr = PKTDATA(osh, bus->glomd); if (!dlen || (dlen & 1)) { DHD_ERROR(("%s: bad glomd len (%d), ignore descriptor\n", __FUNCTION__, dlen)); dlen = 0; } for (totlen = num = 0; dlen; num++) { /* Get (and move past) next length */ sublen = ltoh16_ua(dptr); dlen -= sizeof(uint16); dptr += sizeof(uint16); if ((sublen < SDPCM_HDRLEN_RX) || ((num == 0) && (sublen < (2 * SDPCM_HDRLEN_RX)))) { DHD_ERROR(("%s: descriptor len %d bad: %d\n", __FUNCTION__, num, sublen)); pnext = NULL; break; } if (sublen % DHD_SDALIGN) { DHD_ERROR(("%s: sublen %d not a multiple of %d\n", __FUNCTION__, sublen, DHD_SDALIGN)); usechain = FALSE; } totlen += sublen; /* For last frame, adjust read len so total is a block multiple */ if (!dlen) { sublen += (ROUNDUP(totlen, bus->blocksize) - totlen); totlen = ROUNDUP(totlen, bus->blocksize); } /* Allocate/chain packet for next subframe */ if ((pnext = PKTGET(osh, sublen + DHD_SDALIGN, FALSE)) == NULL) { DHD_ERROR(("%s: PKTGET failed, num %d len %d\n", __FUNCTION__, num, sublen)); break; } ASSERT(!PKTLINK(pnext)); if (!pfirst) { ASSERT(!plast); pfirst = plast = pnext; } else { ASSERT(plast); PKTSETNEXT(osh, plast, pnext); plast = pnext; } /* Adhere to start alignment requirements */ PKTALIGN(osh, pnext, sublen, DHD_SDALIGN); } /* If all allocations succeeded, save packet chain in bus structure */ if (pnext) { DHD_GLOM(("%s: allocated %d-byte packet chain for %d subframes\n", __FUNCTION__, totlen, num)); if (DHD_GLOM_ON() && bus->nextlen) { if (totlen != bus->nextlen) { DHD_GLOM(("%s: glomdesc mismatch: nextlen %d glomdesc %d " "rxseq %d\n", __FUNCTION__, bus->nextlen, totlen, rxseq)); } } bus->glom = pfirst; pfirst = pnext = NULL; } else { if (pfirst) PKTFREE(osh, pfirst, FALSE); bus->glom = NULL; num = 0; } /* Done with descriptor packet */ PKTFREE(osh, bus->glomd, FALSE); bus->glomd = NULL; bus->nextlen = 0; dhd_os_sdunlock_rxq(bus->dhd); } /* Ok -- either we just generated a packet chain, or had one from before */ if (bus->glom) { if (DHD_GLOM_ON()) { DHD_GLOM(("%s: attempt superframe read, packet chain:\n", __FUNCTION__)); for (pnext = bus->glom; pnext; pnext = PKTNEXT(osh, pnext)) { DHD_GLOM((" %p: %p len 0x%04x (%d)\n", pnext, (uint8*)PKTDATA(osh, pnext), PKTLEN(osh, pnext), PKTLEN(osh, pnext))); } } pfirst = bus->glom; dlen = (uint16)pkttotlen(osh, pfirst); /* Do an SDIO read for the superframe. Configurable iovar to * read directly into the chained packet, or allocate a large * packet and and copy into the chain. */ if (usechain) { errcode = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(bus->sdh), SDIO_FUNC_2, F2SYNC, (uint8*)PKTDATA(osh, pfirst), dlen, pfirst, NULL, NULL); } else if (bus->dataptr) { errcode = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(bus->sdh), SDIO_FUNC_2, F2SYNC, bus->dataptr, dlen, NULL, NULL, NULL); sublen = (uint16)pktfrombuf(osh, pfirst, 0, dlen, bus->dataptr); if (sublen != dlen) { DHD_ERROR(("%s: FAILED TO COPY, dlen %d sublen %d\n", __FUNCTION__, dlen, sublen)); errcode = -1; } pnext = NULL; } else { DHD_ERROR(("COULDN'T ALLOC %d-BYTE GLOM, FORCE FAILURE\n", dlen)); errcode = -1; } bus->f2rxdata++; ASSERT(errcode != BCME_PENDING); /* On failure, kill the superframe, allow a couple retries */ if (errcode < 0) { DHD_ERROR(("%s: glom read of %d bytes failed: %d\n", __FUNCTION__, dlen, errcode)); bus->dhd->rx_errors++; if (bus->glomerr++ < 3) { dhdsdio_rxfail(bus, TRUE, TRUE); } else { bus->glomerr = 0; dhdsdio_rxfail(bus, TRUE, FALSE); dhd_os_sdlock_rxq(bus->dhd); PKTFREE(osh, bus->glom, FALSE); dhd_os_sdunlock_rxq(bus->dhd); bus->rxglomfail++; bus->glom = NULL; } return 0; } #ifdef DHD_DEBUG if (DHD_GLOM_ON()) { prhex("SUPERFRAME", PKTDATA(osh, pfirst), MIN(PKTLEN(osh, pfirst), 48)); } #endif /* Validate the superframe header */ dptr = (uint8 *)PKTDATA(osh, pfirst); sublen = ltoh16_ua(dptr); check = ltoh16_ua(dptr + sizeof(uint16)); chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]); seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]); bus->nextlen = dptr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET]; if ((bus->nextlen << 4) > MAX_RX_DATASZ) { DHD_INFO(("%s: got frame w/nextlen too large (%d) seq %d\n", __FUNCTION__, bus->nextlen, seq)); bus->nextlen = 0; } doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]); txmax = SDPCM_WINDOW_VALUE(&dptr[SDPCM_FRAMETAG_LEN]); errcode = 0; if ((uint16)~(sublen^check)) { DHD_ERROR(("%s (superframe): HW hdr error: len/check 0x%04x/0x%04x\n", __FUNCTION__, sublen, check)); errcode = -1; } else if (ROUNDUP(sublen, bus->blocksize) != dlen) { DHD_ERROR(("%s (superframe): len 0x%04x, rounded 0x%04x, expect 0x%04x\n", __FUNCTION__, sublen, ROUNDUP(sublen, bus->blocksize), dlen)); errcode = -1; } else if (SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]) != SDPCM_GLOM_CHANNEL) { DHD_ERROR(("%s (superframe): bad channel %d\n", __FUNCTION__, SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]))); errcode = -1; } else if (SDPCM_GLOMDESC(&dptr[SDPCM_FRAMETAG_LEN])) { DHD_ERROR(("%s (superframe): got second descriptor?\n", __FUNCTION__)); errcode = -1; } else if ((doff < SDPCM_HDRLEN_RX) || (doff > (PKTLEN(osh, pfirst) - SDPCM_HDRLEN_RX))) { DHD_ERROR(("%s (superframe): Bad data offset %d: HW %d pkt %d min %d\n", __FUNCTION__, doff, sublen, PKTLEN(osh, pfirst), SDPCM_HDRLEN_RX)); errcode = -1; } /* Check sequence number of superframe SW header */ if (rxseq != seq) { DHD_INFO(("%s: (superframe) rx_seq %d, expected %d\n", __FUNCTION__, seq, rxseq)); bus->rx_badseq++; rxseq = seq; } /* Check window for sanity */ if ((uint8)(txmax - bus->tx_seq) > 0x40) { DHD_ERROR(("%s: got unlikely tx max %d with tx_seq %d\n", __FUNCTION__, txmax, bus->tx_seq)); txmax = bus->tx_max; } bus->tx_max = txmax; /* Remove superframe header, remember offset */ PKTPULL(osh, pfirst, doff); sfdoff = doff; /* Validate all the subframe headers */ for (num = 0, pnext = pfirst; pnext && !errcode; num++, pnext = PKTNEXT(osh, pnext)) { dptr = (uint8 *)PKTDATA(osh, pnext); dlen = (uint16)PKTLEN(osh, pnext); sublen = ltoh16_ua(dptr); check = ltoh16_ua(dptr + sizeof(uint16)); chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]); doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]); #ifdef DHD_DEBUG if (DHD_GLOM_ON()) { prhex("subframe", dptr, 32); } #endif if ((uint16)~(sublen^check)) { DHD_ERROR(("%s (subframe %d): HW hdr error: " "len/check 0x%04x/0x%04x\n", __FUNCTION__, num, sublen, check)); errcode = -1; } else if ((sublen > dlen) || (sublen < SDPCM_HDRLEN_RX)) { DHD_ERROR(("%s (subframe %d): length mismatch: " "len 0x%04x, expect 0x%04x\n", __FUNCTION__, num, sublen, dlen)); errcode = -1; } else if ((chan != SDPCM_DATA_CHANNEL) && (chan != SDPCM_EVENT_CHANNEL)) { DHD_ERROR(("%s (subframe %d): bad channel %d\n", __FUNCTION__, num, chan)); errcode = -1; } else if ((doff < SDPCM_HDRLEN_RX) || (doff > sublen)) { DHD_ERROR(("%s (subframe %d): Bad data offset %d: HW %d min %d\n", __FUNCTION__, num, doff, sublen, SDPCM_HDRLEN_RX)); errcode = -1; } } if (errcode) { /* Terminate frame on error, request a couple retries */ if (bus->glomerr++ < 3) { /* Restore superframe header space */ PKTPUSH(osh, pfirst, sfdoff); dhdsdio_rxfail(bus, TRUE, TRUE); } else { bus->glomerr = 0; dhdsdio_rxfail(bus, TRUE, FALSE); dhd_os_sdlock_rxq(bus->dhd); PKTFREE(osh, bus->glom, FALSE); dhd_os_sdunlock_rxq(bus->dhd); bus->rxglomfail++; bus->glom = NULL; } bus->nextlen = 0; return 0; } /* Basic SD framing looks ok - process each packet (header) */ bus->glom = NULL; plast = NULL; dhd_os_sdlock_rxq(bus->dhd); for (num = 0; pfirst; rxseq++, pfirst = pnext) { pnext = PKTNEXT(osh, pfirst); PKTSETNEXT(osh, pfirst, NULL); dptr = (uint8 *)PKTDATA(osh, pfirst); sublen = ltoh16_ua(dptr); chan = SDPCM_PACKET_CHANNEL(&dptr[SDPCM_FRAMETAG_LEN]); seq = SDPCM_PACKET_SEQUENCE(&dptr[SDPCM_FRAMETAG_LEN]); doff = SDPCM_DOFFSET_VALUE(&dptr[SDPCM_FRAMETAG_LEN]); DHD_GLOM(("%s: Get subframe %d, %p(%p/%d), sublen %d chan %d seq %d\n", __FUNCTION__, num, pfirst, PKTDATA(osh, pfirst), PKTLEN(osh, pfirst), sublen, chan, seq)); ASSERT((chan == SDPCM_DATA_CHANNEL) || (chan == SDPCM_EVENT_CHANNEL)); if (rxseq != seq) { DHD_GLOM(("%s: rx_seq %d, expected %d\n", __FUNCTION__, seq, rxseq)); bus->rx_badseq++; rxseq = seq; } #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_DATA_ON()) { prhex("Rx Subframe Data", dptr, dlen); } #endif PKTSETLEN(osh, pfirst, sublen); PKTPULL(osh, pfirst, doff); reorder_info_len = sizeof(reorder_info_buf); if (PKTLEN(osh, pfirst) == 0) { PKTFREE(bus->dhd->osh, pfirst, FALSE); continue; } else if (dhd_prot_hdrpull(bus->dhd, &ifidx, pfirst, reorder_info_buf, &reorder_info_len) != 0) { DHD_ERROR(("%s: rx protocol error\n", __FUNCTION__)); bus->dhd->rx_errors++; PKTFREE(osh, pfirst, FALSE); continue; } if (reorder_info_len) { uint32 free_buf_count; void *ppfirst; ppfirst = pfirst; /* Reordering info from the firmware */ dhd_process_pkt_reorder_info(bus->dhd, reorder_info_buf, reorder_info_len, &ppfirst, &free_buf_count); if (free_buf_count == 0) { continue; } else { void *temp; /* go to the end of the chain and attach the pnext there */ temp = ppfirst; while (PKTNEXT(osh, temp) != NULL) { temp = PKTNEXT(osh, temp); } pfirst = temp; if (list_tail[ifidx] == NULL) { list_head[ifidx] = ppfirst; list_tail[ifidx] = pfirst; } else { PKTSETNEXT(osh, list_tail[ifidx], ppfirst); list_tail[ifidx] = pfirst; } } num += (uint8)free_buf_count; } else { /* this packet will go up, link back into chain and count it */ if (list_tail[ifidx] == NULL) { list_head[ifidx] = list_tail[ifidx] = pfirst; } else { PKTSETNEXT(osh, list_tail[ifidx], pfirst); list_tail[ifidx] = pfirst; } num++; } #ifdef DHD_DEBUG if (DHD_GLOM_ON()) { DHD_GLOM(("%s subframe %d to stack, %p(%p/%d) nxt/lnk %p/%p\n", __FUNCTION__, num, pfirst, PKTDATA(osh, pfirst), PKTLEN(osh, pfirst), PKTNEXT(osh, pfirst), PKTLINK(pfirst))); prhex("", (uint8 *)PKTDATA(osh, pfirst), MIN(PKTLEN(osh, pfirst), 32)); } #endif /* DHD_DEBUG */ } dhd_os_sdunlock_rxq(bus->dhd); for (idx = 0; idx < DHD_MAX_IFS; idx++) { if (list_head[idx]) { void *temp; uint8 cnt = 0; temp = list_head[idx]; do { temp = PKTNEXT(osh, temp); cnt++; } while (temp); if (cnt) { dhd_os_sdunlock(bus->dhd); dhd_rx_frame(bus->dhd, idx, list_head[idx], cnt, 0); dhd_os_sdlock(bus->dhd); } } } bus->rxglomframes++; bus->rxglompkts += num; } return num; } /* Return TRUE if there may be more frames to read */ static uint #ifdef REPEAT_READFRAME dhdsdio_readframes(dhd_bus_t *bus, uint maxframes, bool *finished, bool tx_enable) #else dhdsdio_readframes(dhd_bus_t *bus, uint maxframes, bool *finished) #endif { osl_t *osh = bus->dhd->osh; bcmsdh_info_t *sdh = bus->sdh; uint16 len, check; /* Extracted hardware header fields */ uint8 chan, seq, doff; /* Extracted software header fields */ uint8 fcbits; /* Extracted fcbits from software header */ uint8 delta; void *pkt; /* Packet for event or data frames */ uint16 pad; /* Number of pad bytes to read */ uint16 rdlen; /* Total number of bytes to read */ uint8 rxseq; /* Next sequence number to expect */ uint rxleft = 0; /* Remaining number of frames allowed */ int sdret; /* Return code from bcmsdh calls */ uint8 txmax; /* Maximum tx sequence offered */ #ifdef BCMSPI uint32 dstatus = 0; /* gSPI device status bits of */ #endif /* BCMSPI */ bool len_consistent; /* Result of comparing readahead len and len from hw-hdr */ uint8 *rxbuf; int ifidx = 0; uint rxcount = 0; /* Total frames read */ uchar reorder_info_buf[WLHOST_REORDERDATA_TOTLEN]; uint reorder_info_len; uint pkt_count; #if defined(DHD_DEBUG) || defined(SDTEST) bool sdtest = FALSE; /* To limit message spew from test mode */ #endif DHD_TRACE(("%s: Enter\n", __FUNCTION__)); bus->readframes = TRUE; if (!KSO_ENAB(bus)) { DHD_ERROR(("%s: KSO off\n", __FUNCTION__)); bus->readframes = FALSE; return 0; } ASSERT(maxframes); #ifdef SDTEST /* Allow pktgen to override maxframes */ if (bus->pktgen_count && (bus->pktgen_mode == DHD_PKTGEN_RECV)) { maxframes = bus->pktgen_count; sdtest = TRUE; } #endif /* Not finished unless we encounter no more frames indication */ *finished = FALSE; #ifdef BCMSPI /* Get pktlen from gSPI device F0 reg. */ if (bus->bus == SPI_BUS) { /* Peek in dstatus bits and find out size to do rx-read. */ dstatus = bcmsdh_get_dstatus(bus->sdh); if (dstatus == 0) DHD_ERROR(("%s:ZERO spi dstatus, a case observed in PR61352 hit !!!\n", __FUNCTION__)); DHD_TRACE(("Device status from regread = 0x%x\n", dstatus)); DHD_TRACE(("Device status from bit-reconstruction = 0x%x\n", bcmsdh_get_dstatus((void *)bus->sdh))); if ((dstatus & STATUS_F2_PKT_AVAILABLE) && (((dstatus & STATUS_UNDERFLOW)) == 0)) { bus->nextlen = ((dstatus & STATUS_F2_PKT_LEN_MASK) >> STATUS_F2_PKT_LEN_SHIFT); /* '0' size with pkt-available interrupt is eqvt to 2048 bytes */ bus->nextlen = (bus->nextlen == 0) ? SPI_MAX_PKT_LEN : bus->nextlen; if (bus->dwordmode) bus->nextlen = bus->nextlen << 2; DHD_TRACE(("Entering %s: length to be read from gSPI = %d\n", __FUNCTION__, bus->nextlen)); } else { if (dstatus & STATUS_F2_PKT_AVAILABLE) DHD_ERROR(("Underflow during %s.\n", __FUNCTION__)); else DHD_ERROR(("False pkt-available intr.\n")); *finished = TRUE; return (maxframes - rxleft); } } #endif /* BCMSPI */ for (rxseq = bus->rx_seq, rxleft = maxframes; !bus->rxskip && rxleft && bus->dhd->busstate != DHD_BUS_DOWN; rxseq++, rxleft--) { #ifdef DHDTHREAD if ( #ifdef REPEAT_READFRAME tx_enable && #endif TXCTLOK(bus) && bus->ctrl_frame_stat && (bus->clkstate == CLK_AVAIL)) dhdsdio_sendpendctl(bus); /* tx more to improve rx performance */ else if ( #ifdef REPEAT_READFRAME tx_enable && #endif (bus->clkstate == CLK_AVAIL) && !bus->fcstate && pktq_mlen(&bus->txq, ~bus->flowcontrol) && DATAOK(bus)) { dhdsdio_sendfromq(bus, dhd_txbound); } #endif /* DHDTHREAD */ /* Handle glomming separately */ if (bus->glom || bus->glomd) { uint8 cnt; DHD_GLOM(("%s: calling rxglom: glomd %p, glom %p\n", __FUNCTION__, bus->glomd, bus->glom)); cnt = dhdsdio_rxglom(bus, rxseq); DHD_GLOM(("%s: rxglom returned %d\n", __FUNCTION__, cnt)); rxseq += cnt - 1; rxleft = (rxleft > cnt) ? (rxleft - cnt) : 1; continue; } /* Try doing single read if we can */ if (dhd_readahead && bus->nextlen) { uint16 nextlen = bus->nextlen; bus->nextlen = 0; if (bus->bus == SPI_BUS) { rdlen = len = nextlen; } else { rdlen = len = nextlen << 4; /* Pad read to blocksize for efficiency */ if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) { pad = bus->blocksize - (rdlen % bus->blocksize); if ((pad <= bus->roundup) && (pad < bus->blocksize) && ((rdlen + pad + firstread) < MAX_RX_DATASZ)) rdlen += pad; } else if (rdlen % DHD_SDALIGN) { rdlen += DHD_SDALIGN - (rdlen % DHD_SDALIGN); } } /* We use bus->rxctl buffer in WinXP for initial control pkt receives. * Later we use buffer-poll for data as well as control packets. * This is required because dhd receives full frame in gSPI unlike SDIO. * After the frame is received we have to distinguish whether it is data * or non-data frame. */ /* Allocate a packet buffer */ dhd_os_sdlock_rxq(bus->dhd); if (!(pkt = PKTGET(osh, rdlen + DHD_SDALIGN, FALSE))) { if (bus->bus == SPI_BUS) { bus->usebufpool = FALSE; bus->rxctl = bus->rxbuf; if (dhd_alignctl) { bus->rxctl += firstread; if ((pad = ((uintptr)bus->rxctl % DHD_SDALIGN))) bus->rxctl += (DHD_SDALIGN - pad); bus->rxctl -= firstread; } ASSERT(bus->rxctl >= bus->rxbuf); rxbuf = bus->rxctl; /* Read the entire frame */ sdret = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, rxbuf, rdlen, NULL, NULL, NULL); bus->f2rxdata++; ASSERT(sdret != BCME_PENDING); #ifdef BCMSPI if (bcmsdh_get_dstatus((void *)bus->sdh) & STATUS_UNDERFLOW) { bus->nextlen = 0; *finished = TRUE; DHD_ERROR(("%s: read %d control bytes failed " "due to spi underflow\n", __FUNCTION__, rdlen)); /* dhd.rx_ctlerrs is higher level */ bus->rxc_errors++; dhd_os_sdunlock_rxq(bus->dhd); continue; } #endif /* BCMSPI */ /* Control frame failures need retransmission */ if (sdret < 0) { DHD_ERROR(("%s: read %d control bytes failed: %d\n", __FUNCTION__, rdlen, sdret)); /* dhd.rx_ctlerrs is higher level */ bus->rxc_errors++; dhd_os_sdunlock_rxq(bus->dhd); dhdsdio_rxfail(bus, TRUE, (bus->bus == SPI_BUS) ? FALSE : TRUE); continue; } } else { /* Give up on data, request rtx of events */ DHD_ERROR(("%s (nextlen): PKTGET failed: len %d rdlen %d " "expected rxseq %d\n", __FUNCTION__, len, rdlen, rxseq)); /* Just go try again w/normal header read */ dhd_os_sdunlock_rxq(bus->dhd); continue; } } else { if (bus->bus == SPI_BUS) bus->usebufpool = TRUE; ASSERT(!PKTLINK(pkt)); PKTALIGN(osh, pkt, rdlen, DHD_SDALIGN); rxbuf = (uint8 *)PKTDATA(osh, pkt); /* Read the entire frame */ sdret = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, rxbuf, rdlen, pkt, NULL, NULL); bus->f2rxdata++; ASSERT(sdret != BCME_PENDING); #ifdef BCMSPI if (bcmsdh_get_dstatus((void *)bus->sdh) & STATUS_UNDERFLOW) { bus->nextlen = 0; *finished = TRUE; DHD_ERROR(("%s (nextlen): read %d bytes failed due " "to spi underflow\n", __FUNCTION__, rdlen)); PKTFREE(bus->dhd->osh, pkt, FALSE); bus->dhd->rx_errors++; dhd_os_sdunlock_rxq(bus->dhd); continue; } #endif /* BCMSPI */ if (sdret < 0) { DHD_ERROR(("%s (nextlen): read %d bytes failed: %d\n", __FUNCTION__, rdlen, sdret)); PKTFREE(bus->dhd->osh, pkt, FALSE); bus->dhd->rx_errors++; dhd_os_sdunlock_rxq(bus->dhd); /* Force retry w/normal header read. Don't attempt NAK for * gSPI */ dhdsdio_rxfail(bus, TRUE, (bus->bus == SPI_BUS) ? FALSE : TRUE); continue; } } dhd_os_sdunlock_rxq(bus->dhd); /* Now check the header */ bcopy(rxbuf, bus->rxhdr, SDPCM_HDRLEN_RX); /* Extract hardware header fields */ len = ltoh16_ua(bus->rxhdr); check = ltoh16_ua(bus->rxhdr + sizeof(uint16)); /* All zeros means readahead info was bad */ if (!(len|check)) { DHD_INFO(("%s (nextlen): read zeros in HW header???\n", __FUNCTION__)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); GSPI_PR55150_BAILOUT; continue; } /* Validate check bytes */ if ((uint16)~(len^check)) { DHD_ERROR(("%s (nextlen): HW hdr error: nextlen/len/check" " 0x%04x/0x%04x/0x%04x\n", __FUNCTION__, nextlen, len, check)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); bus->rx_badhdr++; dhdsdio_rxfail(bus, FALSE, FALSE); GSPI_PR55150_BAILOUT; continue; } /* Validate frame length */ if (len < SDPCM_HDRLEN_RX) { DHD_ERROR(("%s (nextlen): HW hdr length invalid: %d\n", __FUNCTION__, len)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); GSPI_PR55150_BAILOUT; continue; } /* Check for consistency with readahead info */ #ifdef BCMSPI if (bus->bus == SPI_BUS) { if (bus->dwordmode) { uint16 spilen; if ((bus->sih->chip == BCM4329_CHIP_ID) && (bus->sih->chiprev == 2)) spilen = ROUNDUP(len, 16); else spilen = ROUNDUP(len, 4); len_consistent = (nextlen != spilen); } else len_consistent = (nextlen != len); } else #endif /* BCMSPI */ len_consistent = (nextlen != (ROUNDUP(len, 16) >> 4)); if (len_consistent) { /* Mismatch, force retry w/normal header (may be >4K) */ DHD_ERROR(("%s (nextlen): mismatch, nextlen %d len %d rnd %d; " "expected rxseq %d\n", __FUNCTION__, nextlen, len, ROUNDUP(len, 16), rxseq)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); dhdsdio_rxfail(bus, TRUE, (bus->bus == SPI_BUS) ? FALSE : TRUE); GSPI_PR55150_BAILOUT; continue; } /* Extract software header fields */ chan = SDPCM_PACKET_CHANNEL(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); seq = SDPCM_PACKET_SEQUENCE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); doff = SDPCM_DOFFSET_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); txmax = SDPCM_WINDOW_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); #ifdef BCMSPI /* Save the readahead length if there is one */ if (bus->bus == SPI_BUS) { /* Use reconstructed dstatus bits and find out readahead size */ dstatus = bcmsdh_get_dstatus((void *)bus->sdh); DHD_INFO(("Device status from bit-reconstruction = 0x%x\n", bcmsdh_get_dstatus((void *)bus->sdh))); if (dstatus & STATUS_F2_PKT_AVAILABLE) { bus->nextlen = ((dstatus & STATUS_F2_PKT_LEN_MASK) >> STATUS_F2_PKT_LEN_SHIFT); bus->nextlen = (bus->nextlen == 0) ? SPI_MAX_PKT_LEN : bus->nextlen; if (bus->dwordmode) bus->nextlen = bus->nextlen << 2; DHD_INFO(("readahead len from gSPI = %d \n", bus->nextlen)); bus->dhd->rx_readahead_cnt ++; } else { bus->nextlen = 0; *finished = TRUE; } } else { #endif /* BCMSPI */ bus->nextlen = bus->rxhdr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET]; if ((bus->nextlen << 4) > MAX_RX_DATASZ) { DHD_INFO(("%s (nextlen): got frame w/nextlen too large" " (%d), seq %d\n", __FUNCTION__, bus->nextlen, seq)); bus->nextlen = 0; } bus->dhd->rx_readahead_cnt ++; #ifdef BCMSPI } #endif /* BCMSPI */ /* Handle Flow Control */ fcbits = SDPCM_FCMASK_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); delta = 0; if (~bus->flowcontrol & fcbits) { bus->fc_xoff++; delta = 1; } if (bus->flowcontrol & ~fcbits) { bus->fc_xon++; delta = 1; } if (delta) { bus->fc_rcvd++; bus->flowcontrol = fcbits; } /* Check and update sequence number */ if (rxseq != seq) { DHD_INFO(("%s (nextlen): rx_seq %d, expected %d\n", __FUNCTION__, seq, rxseq)); bus->rx_badseq++; rxseq = seq; } /* Check window for sanity */ if ((uint8)(txmax - bus->tx_seq) > 0x40) { #ifdef BCMSPI if ((bus->bus == SPI_BUS) && !(dstatus & STATUS_F2_RX_READY)) { DHD_ERROR(("%s: got unlikely tx max %d with tx_seq %d\n", __FUNCTION__, txmax, bus->tx_seq)); txmax = bus->tx_seq + 2; } else { #endif /* BCMSPI */ DHD_ERROR(("%s: got unlikely tx max %d with tx_seq %d\n", __FUNCTION__, txmax, bus->tx_seq)); txmax = bus->tx_max; #ifdef BCMSPI } #endif /* BCMSPI */ } bus->tx_max = txmax; #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_DATA_ON()) { prhex("Rx Data", rxbuf, len); } else if (DHD_HDRS_ON()) { prhex("RxHdr", bus->rxhdr, SDPCM_HDRLEN_RX); } #endif if (chan == SDPCM_CONTROL_CHANNEL) { if (bus->bus == SPI_BUS) { dhdsdio_read_control(bus, rxbuf, len, doff); if (bus->usebufpool) { dhd_os_sdlock_rxq(bus->dhd); PKTFREE(bus->dhd->osh, pkt, FALSE); dhd_os_sdunlock_rxq(bus->dhd); } continue; } else { DHD_ERROR(("%s (nextlen): readahead on control" " packet %d?\n", __FUNCTION__, seq)); /* Force retry w/normal header read */ bus->nextlen = 0; dhdsdio_rxfail(bus, FALSE, TRUE); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); continue; } } if ((bus->bus == SPI_BUS) && !bus->usebufpool) { DHD_ERROR(("Received %d bytes on %d channel. Running out of " "rx pktbuf's or not yet malloced.\n", len, chan)); continue; } /* Validate data offset */ if ((doff < SDPCM_HDRLEN_RX) || (doff > len)) { DHD_ERROR(("%s (nextlen): bad data offset %d: HW len %d min %d\n", __FUNCTION__, doff, len, SDPCM_HDRLEN_RX)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE2(); dhd_os_sdunlock_rxq(bus->dhd); ASSERT(0); dhdsdio_rxfail(bus, FALSE, FALSE); continue; } /* All done with this one -- now deliver the packet */ goto deliver; } /* gSPI frames should not be handled in fractions */ if (bus->bus == SPI_BUS) { break; } /* Read frame header (hardware and software) */ sdret = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, bus->rxhdr, firstread, NULL, NULL, NULL); bus->f2rxhdrs++; ASSERT(sdret != BCME_PENDING); if (sdret < 0) { DHD_ERROR(("%s: RXHEADER FAILED: %d\n", __FUNCTION__, sdret)); bus->rx_hdrfail++; dhdsdio_rxfail(bus, TRUE, TRUE); continue; } #ifdef DHD_DEBUG if (DHD_BYTES_ON() || DHD_HDRS_ON()) { prhex("RxHdr", bus->rxhdr, SDPCM_HDRLEN_RX); } #endif /* Extract hardware header fields */ len = ltoh16_ua(bus->rxhdr); check = ltoh16_ua(bus->rxhdr + sizeof(uint16)); /* All zeros means no more frames */ if (!(len|check)) { *finished = TRUE; break; } /* Validate check bytes */ if ((uint16)~(len^check)) { DHD_ERROR(("%s: HW hdr error: len/check 0x%04x/0x%04x\n", __FUNCTION__, len, check)); bus->rx_badhdr++; dhdsdio_rxfail(bus, FALSE, FALSE); continue; } /* Validate frame length */ if (len < SDPCM_HDRLEN_RX) { DHD_ERROR(("%s: HW hdr length invalid: %d\n", __FUNCTION__, len)); continue; } /* Extract software header fields */ chan = SDPCM_PACKET_CHANNEL(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); seq = SDPCM_PACKET_SEQUENCE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); doff = SDPCM_DOFFSET_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); txmax = SDPCM_WINDOW_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); /* Validate data offset */ if ((doff < SDPCM_HDRLEN_RX) || (doff > len)) { DHD_ERROR(("%s: Bad data offset %d: HW len %d, min %d seq %d\n", __FUNCTION__, doff, len, SDPCM_HDRLEN_RX, seq)); bus->rx_badhdr++; ASSERT(0); dhdsdio_rxfail(bus, FALSE, FALSE); continue; } /* Save the readahead length if there is one */ bus->nextlen = bus->rxhdr[SDPCM_FRAMETAG_LEN + SDPCM_NEXTLEN_OFFSET]; if ((bus->nextlen << 4) > MAX_RX_DATASZ) { DHD_INFO(("%s (nextlen): got frame w/nextlen too large (%d), seq %d\n", __FUNCTION__, bus->nextlen, seq)); bus->nextlen = 0; } /* Handle Flow Control */ fcbits = SDPCM_FCMASK_VALUE(&bus->rxhdr[SDPCM_FRAMETAG_LEN]); delta = 0; if (~bus->flowcontrol & fcbits) { bus->fc_xoff++; delta = 1; } if (bus->flowcontrol & ~fcbits) { bus->fc_xon++; delta = 1; } if (delta) { bus->fc_rcvd++; bus->flowcontrol = fcbits; } /* Check and update sequence number */ if (rxseq != seq) { DHD_INFO(("%s: rx_seq %d, expected %d\n", __FUNCTION__, seq, rxseq)); bus->rx_badseq++; rxseq = seq; } /* Check window for sanity */ if ((uint8)(txmax - bus->tx_seq) > 0x40) { DHD_ERROR(("%s: got unlikely tx max %d with tx_seq %d\n", __FUNCTION__, txmax, bus->tx_seq)); txmax = bus->tx_max; } bus->tx_max = txmax; /* Call a separate function for control frames */ if (chan == SDPCM_CONTROL_CHANNEL) { dhdsdio_read_control(bus, bus->rxhdr, len, doff); continue; } ASSERT((chan == SDPCM_DATA_CHANNEL) || (chan == SDPCM_EVENT_CHANNEL) || (chan == SDPCM_TEST_CHANNEL) || (chan == SDPCM_GLOM_CHANNEL)); /* Length to read */ rdlen = (len > firstread) ? (len - firstread) : 0; /* May pad read to blocksize for efficiency */ if (bus->roundup && bus->blocksize && (rdlen > bus->blocksize)) { pad = bus->blocksize - (rdlen % bus->blocksize); if ((pad <= bus->roundup) && (pad < bus->blocksize) && ((rdlen + pad + firstread) < MAX_RX_DATASZ)) rdlen += pad; } else if (rdlen % DHD_SDALIGN) { rdlen += DHD_SDALIGN - (rdlen % DHD_SDALIGN); } /* Satisfy length-alignment requirements */ if (forcealign && (rdlen & (ALIGNMENT - 1))) rdlen = ROUNDUP(rdlen, ALIGNMENT); if ((rdlen + firstread) > MAX_RX_DATASZ) { /* Too long -- skip this frame */ DHD_ERROR(("%s: too long: len %d rdlen %d\n", __FUNCTION__, len, rdlen)); bus->dhd->rx_errors++; bus->rx_toolong++; dhdsdio_rxfail(bus, FALSE, FALSE); continue; } dhd_os_sdlock_rxq(bus->dhd); if (!(pkt = PKTGET(osh, (rdlen + firstread + DHD_SDALIGN), FALSE))) { /* Give up on data, request rtx of events */ DHD_ERROR(("%s: PKTGET failed: rdlen %d chan %d\n", __FUNCTION__, rdlen, chan)); bus->dhd->rx_dropped++; dhd_os_sdunlock_rxq(bus->dhd); dhdsdio_rxfail(bus, FALSE, RETRYCHAN(chan)); continue; } dhd_os_sdunlock_rxq(bus->dhd); ASSERT(!PKTLINK(pkt)); /* Leave room for what we already read, and align remainder */ ASSERT(firstread < (PKTLEN(osh, pkt))); PKTPULL(osh, pkt, firstread); PKTALIGN(osh, pkt, rdlen, DHD_SDALIGN); /* Read the remaining frame data */ sdret = dhd_bcmsdh_recv_buf(bus, bcmsdh_cur_sbwad(sdh), SDIO_FUNC_2, F2SYNC, ((uint8 *)PKTDATA(osh, pkt)), rdlen, pkt, NULL, NULL); bus->f2rxdata++; ASSERT(sdret != BCME_PENDING); if (sdret < 0) { DHD_ERROR(("%s: read %d %s bytes failed: %d\n", __FUNCTION__, rdlen, ((chan == SDPCM_EVENT_CHANNEL) ? "event" : ((chan == SDPCM_DATA_CHANNEL) ? "data" : "test")), sdret)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE(bus->dhd->osh, pkt, FALSE); dhd_os_sdunlock_rxq(bus->dhd); bus->dhd->rx_errors++; dhdsdio_rxfail(bus, TRUE, RETRYCHAN(chan)); continue; } /* Copy the already-read portion */ PKTPUSH(osh, pkt, firstread); bcopy(bus->rxhdr, PKTDATA(osh, pkt), firstread); #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_DATA_ON()) { prhex("Rx Data", PKTDATA(osh, pkt), len); } #endif deliver: /* Save superframe descriptor and allocate packet frame */ if (chan == SDPCM_GLOM_CHANNEL) { if (SDPCM_GLOMDESC(&bus->rxhdr[SDPCM_FRAMETAG_LEN])) { DHD_GLOM(("%s: got glom descriptor, %d bytes:\n", __FUNCTION__, len)); #ifdef DHD_DEBUG if (DHD_GLOM_ON()) { prhex("Glom Data", PKTDATA(osh, pkt), len); } #endif PKTSETLEN(osh, pkt, len); ASSERT(doff == SDPCM_HDRLEN_RX); PKTPULL(osh, pkt, SDPCM_HDRLEN_RX); bus->glomd = pkt; } else { DHD_ERROR(("%s: glom superframe w/o descriptor!\n", __FUNCTION__)); dhdsdio_rxfail(bus, FALSE, FALSE); } continue; } /* Fill in packet len and prio, deliver upward */ PKTSETLEN(osh, pkt, len); PKTPULL(osh, pkt, doff); #ifdef SDTEST /* Test channel packets are processed separately */ if (chan == SDPCM_TEST_CHANNEL) { dhdsdio_testrcv(bus, pkt, seq); continue; } #endif /* SDTEST */ if (PKTLEN(osh, pkt) == 0) { dhd_os_sdlock_rxq(bus->dhd); PKTFREE(bus->dhd->osh, pkt, FALSE); dhd_os_sdunlock_rxq(bus->dhd); continue; } else if (dhd_prot_hdrpull(bus->dhd, &ifidx, pkt, reorder_info_buf, &reorder_info_len) != 0) { DHD_ERROR(("%s: rx protocol error\n", __FUNCTION__)); dhd_os_sdlock_rxq(bus->dhd); PKTFREE(bus->dhd->osh, pkt, FALSE); dhd_os_sdunlock_rxq(bus->dhd); bus->dhd->rx_errors++; continue; } if (reorder_info_len) { /* Reordering info from the firmware */ dhd_process_pkt_reorder_info(bus->dhd, reorder_info_buf, reorder_info_len, &pkt, &pkt_count); if (pkt_count == 0) continue; } else pkt_count = 1; /* Unlock during rx call */ dhd_os_sdunlock(bus->dhd); dhd_rx_frame(bus->dhd, ifidx, pkt, pkt_count, chan); dhd_os_sdlock(bus->dhd); } rxcount = maxframes - rxleft; #ifdef DHD_DEBUG /* Message if we hit the limit */ if (!rxleft && !sdtest) DHD_DATA(("%s: hit rx limit of %d frames\n", __FUNCTION__, maxframes)); else #endif /* DHD_DEBUG */ DHD_DATA(("%s: processed %d frames\n", __FUNCTION__, rxcount)); /* Back off rxseq if awaiting rtx, update rx_seq */ if (bus->rxskip) rxseq--; bus->rx_seq = rxseq; if (bus->reqbussleep) { dhdsdio_bussleep(bus, TRUE); bus->reqbussleep = FALSE; } bus->readframes = FALSE; return rxcount; } static uint32 dhdsdio_hostmail(dhd_bus_t *bus) { sdpcmd_regs_t *regs = bus->regs; uint32 intstatus = 0; uint32 hmb_data; uint8 fcbits; uint retries = 0; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); /* Read mailbox data and ack that we did so */ R_SDREG(hmb_data, &regs->tohostmailboxdata, retries); if (retries <= retry_limit) W_SDREG(SMB_INT_ACK, &regs->tosbmailbox, retries); bus->f1regdata += 2; /* Dongle recomposed rx frames, accept them again */ if (hmb_data & HMB_DATA_NAKHANDLED) { DHD_INFO(("Dongle reports NAK handled, expect rtx of %d\n", bus->rx_seq)); if (!bus->rxskip) { DHD_ERROR(("%s: unexpected NAKHANDLED!\n", __FUNCTION__)); } bus->rxskip = FALSE; intstatus |= FRAME_AVAIL_MASK(bus); } /* * DEVREADY does not occur with gSPI. */ if (hmb_data & (HMB_DATA_DEVREADY | HMB_DATA_FWREADY)) { bus->sdpcm_ver = (hmb_data & HMB_DATA_VERSION_MASK) >> HMB_DATA_VERSION_SHIFT; if (bus->sdpcm_ver != SDPCM_PROT_VERSION) DHD_ERROR(("Version mismatch, dongle reports %d, expecting %d\n", bus->sdpcm_ver, SDPCM_PROT_VERSION)); else DHD_INFO(("Dongle ready, protocol version %d\n", bus->sdpcm_ver)); #ifndef BCMSPI /* make sure for the SDIO_DEVICE_RXDATAINT_MODE_1 corecontrol is proper */ if ((bus->sih->buscoretype == SDIOD_CORE_ID) && (bus->sdpcmrev >= 4) && (bus->rxint_mode == SDIO_DEVICE_RXDATAINT_MODE_1)) { uint32 val; val = R_REG(bus->dhd->osh, &bus->regs->corecontrol); val &= ~CC_XMTDATAAVAIL_MODE; val |= CC_XMTDATAAVAIL_CTRL; W_REG(bus->dhd->osh, &bus->regs->corecontrol, val); val = R_REG(bus->dhd->osh, &bus->regs->corecontrol); } #endif /* BCMSPI */ #ifdef DHD_DEBUG /* Retrieve console state address now that firmware should have updated it */ { sdpcm_shared_t shared; if (dhdsdio_readshared(bus, &shared) == 0) bus->console_addr = shared.console_addr; } #endif /* DHD_DEBUG */ } /* * Flow Control has been moved into the RX headers and this out of band * method isn't used any more. Leave this here for possibly remaining backward * compatible with older dongles */ if (hmb_data & HMB_DATA_FC) { fcbits = (hmb_data & HMB_DATA_FCDATA_MASK) >> HMB_DATA_FCDATA_SHIFT; if (fcbits & ~bus->flowcontrol) bus->fc_xoff++; if (bus->flowcontrol & ~fcbits) bus->fc_xon++; bus->fc_rcvd++; bus->flowcontrol = fcbits; } #ifdef DHD_DEBUG /* At least print a message if FW halted */ if (hmb_data & HMB_DATA_FWHALT) { DHD_ERROR(("INTERNAL ERROR: FIRMWARE HALTED : set BUS DOWN\n")); dhdsdio_checkdied(bus, NULL, 0); bus->dhd->busstate = DHD_BUS_DOWN; } #endif /* DHD_DEBUG */ /* Shouldn't be any others */ if (hmb_data & ~(HMB_DATA_DEVREADY | HMB_DATA_FWHALT | HMB_DATA_NAKHANDLED | HMB_DATA_FC | HMB_DATA_FWREADY | HMB_DATA_FCDATA_MASK | HMB_DATA_VERSION_MASK)) { DHD_ERROR(("Unknown mailbox data content: 0x%02x\n", hmb_data)); } return intstatus; } #ifdef REPEAT_READFRAME extern uint dhd_dpcpoll; #endif static bool dhdsdio_dpc(dhd_bus_t *bus) { bcmsdh_info_t *sdh = bus->sdh; sdpcmd_regs_t *regs = bus->regs; uint32 intstatus, newstatus = 0; uint retries = 0; uint rxlimit = dhd_rxbound; /* Rx frames to read before resched */ uint txlimit = dhd_txbound; /* Tx frames to send before resched */ uint framecnt = 0; /* Temporary counter of tx/rx frames */ bool rxdone = TRUE; /* Flag for no more read data */ bool resched = FALSE; /* Flag indicating resched wanted */ DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus->dhd->busstate == DHD_BUS_DOWN) { DHD_ERROR(("%s: Bus down, ret\n", __FUNCTION__)); bus->intstatus = 0; return 0; } /* Start with leftover status bits */ intstatus = bus->intstatus; dhd_os_sdlock(bus->dhd); if (!SLPAUTO_ENAB(bus) && !KSO_ENAB(bus)) { DHD_ERROR(("%s: Device asleep\n", __FUNCTION__)); goto exit; } /* If waiting for HTAVAIL, check status */ if (!SLPAUTO_ENAB(bus) && (bus->clkstate == CLK_PENDING)) { int err; uint8 clkctl, devctl = 0; #ifdef DHD_DEBUG /* Check for inconsistent device control */ devctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); if (err) { DHD_ERROR(("%s: error reading DEVCTL: %d\n", __FUNCTION__, err)); bus->dhd->busstate = DHD_BUS_DOWN; } else { ASSERT(devctl & SBSDIO_DEVCTL_CA_INT_ONLY); } #endif /* DHD_DEBUG */ /* Read CSR, if clock on switch to AVAIL, else ignore */ clkctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if (err) { DHD_ERROR(("%s: error reading CSR: %d\n", __FUNCTION__, err)); bus->dhd->busstate = DHD_BUS_DOWN; } DHD_INFO(("DPC: PENDING, devctl 0x%02x clkctl 0x%02x\n", devctl, clkctl)); if (SBSDIO_HTAV(clkctl)) { devctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, &err); if (err) { DHD_ERROR(("%s: error reading DEVCTL: %d\n", __FUNCTION__, err)); bus->dhd->busstate = DHD_BUS_DOWN; } devctl &= ~SBSDIO_DEVCTL_CA_INT_ONLY; bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_DEVICE_CTL, devctl, &err); if (err) { DHD_ERROR(("%s: error writing DEVCTL: %d\n", __FUNCTION__, err)); bus->dhd->busstate = DHD_BUS_DOWN; } bus->clkstate = CLK_AVAIL; } else { goto clkwait; } } BUS_WAKE(bus); /* Make sure backplane clock is on */ dhdsdio_clkctl(bus, CLK_AVAIL, TRUE); if (bus->clkstate != CLK_AVAIL) goto clkwait; /* Pending interrupt indicates new device status */ if (bus->ipend) { bus->ipend = FALSE; R_SDREG(newstatus, &regs->intstatus, retries); bus->f1regdata++; if (bcmsdh_regfail(bus->sdh)) newstatus = 0; newstatus &= bus->hostintmask; bus->fcstate = !!(newstatus & I_HMB_FC_STATE); if (newstatus) { bus->f1regdata++; #ifndef BCMSPI if ((bus->rxint_mode == SDIO_DEVICE_RXDATAINT_MODE_0) && (newstatus == I_XMTDATA_AVAIL)) { } else #endif /* BCMSPI */ W_SDREG(newstatus, &regs->intstatus, retries); } } /* Merge new bits with previous */ intstatus |= newstatus; bus->intstatus = 0; /* Handle flow-control change: read new state in case our ack * crossed another change interrupt. If change still set, assume * FC ON for safety, let next loop through do the debounce. */ if (intstatus & I_HMB_FC_CHANGE) { intstatus &= ~I_HMB_FC_CHANGE; W_SDREG(I_HMB_FC_CHANGE, &regs->intstatus, retries); R_SDREG(newstatus, &regs->intstatus, retries); bus->f1regdata += 2; bus->fcstate = !!(newstatus & (I_HMB_FC_STATE | I_HMB_FC_CHANGE)); intstatus |= (newstatus & bus->hostintmask); } /* Just being here means nothing more to do for chipactive */ if (intstatus & I_CHIPACTIVE) { /* ASSERT(bus->clkstate == CLK_AVAIL); */ intstatus &= ~I_CHIPACTIVE; } /* Handle host mailbox indication */ if (intstatus & I_HMB_HOST_INT) { intstatus &= ~I_HMB_HOST_INT; intstatus |= dhdsdio_hostmail(bus); } /* Generally don't ask for these, can get CRC errors... */ if (intstatus & I_WR_OOSYNC) { DHD_ERROR(("Dongle reports WR_OOSYNC\n")); intstatus &= ~I_WR_OOSYNC; } if (intstatus & I_RD_OOSYNC) { DHD_ERROR(("Dongle reports RD_OOSYNC\n")); intstatus &= ~I_RD_OOSYNC; } if (intstatus & I_SBINT) { DHD_ERROR(("Dongle reports SBINT\n")); intstatus &= ~I_SBINT; } /* Would be active due to wake-wlan in gSPI */ if (intstatus & I_CHIPACTIVE) { DHD_INFO(("Dongle reports CHIPACTIVE\n")); intstatus &= ~I_CHIPACTIVE; } /* Ignore frame indications if rxskip is set */ if (bus->rxskip) { intstatus &= ~FRAME_AVAIL_MASK(bus); } /* On frame indication, read available frames */ if (PKT_AVAILABLE(bus, intstatus)) { #ifdef REPEAT_READFRAME framecnt = dhdsdio_readframes(bus, rxlimit, &rxdone, true); #else framecnt = dhdsdio_readframes(bus, rxlimit, &rxdone); #endif if (rxdone || bus->rxskip) intstatus &= ~FRAME_AVAIL_MASK(bus); rxlimit -= MIN(framecnt, rxlimit); } /* Keep still-pending events for next scheduling */ bus->intstatus = intstatus; clkwait: /* Re-enable interrupts to detect new device events (mailbox, rx frame) * or clock availability. (Allows tx loop to check ipend if desired.) * (Unless register access seems hosed, as we may not be able to ACK...) */ if (bus->intr && bus->intdis && !bcmsdh_regfail(sdh)) { DHD_INTR(("%s: enable SDIO interrupts, rxdone %d framecnt %d\n", __FUNCTION__, rxdone, framecnt)); bus->intdis = FALSE; #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) bcmsdh_oob_intr_set(1); #endif /* defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) */ bcmsdh_intr_enable(sdh); } #if defined(OOB_INTR_ONLY) && !defined(HW_OOB) /* In case of SW-OOB(using edge trigger), * Check interrupt status in the dongle again after enable irq on the host. * and rechedule dpc if interrupt is pended in the dongle. * There is a chance to miss OOB interrupt while irq is disabled on the host. * No need to do this with HW-OOB(level trigger) */ R_SDREG(newstatus, &regs->intstatus, retries); if (bcmsdh_regfail(bus->sdh)) newstatus = 0; if (newstatus & bus->hostintmask) { bus->ipend = TRUE; resched = TRUE; } #endif /* defined(OOB_INTR_ONLY) && !defined(HW_OOB) */ #ifdef PROP_TXSTATUS dhd_wlfc_trigger_pktcommit(bus->dhd); #endif if (TXCTLOK(bus) && bus->ctrl_frame_stat && (bus->clkstate == CLK_AVAIL)) dhdsdio_sendpendctl(bus); /* Send queued frames (limit 1 if rx may still be pending) */ else if ((bus->clkstate == CLK_AVAIL) && !bus->fcstate && pktq_mlen(&bus->txq, ~bus->flowcontrol) && txlimit && DATAOK(bus)) { framecnt = rxdone ? txlimit : MIN(txlimit, dhd_txminmax); framecnt = dhdsdio_sendfromq(bus, framecnt); txlimit -= framecnt; } /* Resched the DPC if ctrl cmd is pending on bus credit */ if (bus->ctrl_frame_stat) resched = TRUE; /* Resched if events or tx frames are pending, else await next interrupt */ /* On failed register access, all bets are off: no resched or interrupts */ if ((bus->dhd->busstate == DHD_BUS_DOWN) || bcmsdh_regfail(sdh)) { if ((bus->sih && bus->sih->buscorerev >= 12) && !(dhdsdio_sleepcsr_get(bus) & SBSDIO_FUNC1_SLEEPCSR_KSO_MASK)) { /* Bus failed because of KSO */ DHD_ERROR(("%s: Bus failed due to KSO\n", __FUNCTION__)); bus->kso = FALSE; } else { DHD_ERROR(("%s: failed backplane access over SDIO, halting operation\n", __FUNCTION__)); bus->dhd->busstate = DHD_BUS_DOWN; bus->intstatus = 0; } } else if (bus->clkstate == CLK_PENDING) { /* Awaiting I_CHIPACTIVE; don't resched */ } else if (bus->intstatus || bus->ipend || (!bus->fcstate && pktq_mlen(&bus->txq, ~bus->flowcontrol) && DATAOK(bus)) || PKT_AVAILABLE(bus, bus->intstatus)) { /* Read multiple frames */ resched = TRUE; } bus->dpc_sched = resched; /* If we're done for now, turn off clock request. */ if ((bus->idletime == DHD_IDLE_IMMEDIATE) && (bus->clkstate != CLK_PENDING)) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, FALSE); } exit: #ifdef REPEAT_READFRAME if (!resched && dhd_dpcpoll) { resched = dhdsdio_readframes(bus, dhd_rxbound, &rxdone, true); } #endif dhd_os_sdunlock(bus->dhd); return resched; } bool dhd_bus_dpc(struct dhd_bus *bus) { bool resched; /* Call the DPC directly. */ DHD_TRACE(("Calling dhdsdio_dpc() from %s\n", __FUNCTION__)); resched = dhdsdio_dpc(bus); return resched; } void dhdsdio_isr(void *arg) { dhd_bus_t *bus = (dhd_bus_t*)arg; bcmsdh_info_t *sdh; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (!bus) { DHD_ERROR(("%s : bus is null pointer , exit \n", __FUNCTION__)); return; } sdh = bus->sdh; if (bus->dhd->busstate == DHD_BUS_DOWN) { DHD_ERROR(("%s : bus is down. we have nothing to do\n", __FUNCTION__)); return; } DHD_TRACE(("%s: Enter\n", __FUNCTION__)); /* Count the interrupt call */ bus->intrcount++; bus->ipend = TRUE; /* Shouldn't get this interrupt if we're sleeping? */ if (!SLPAUTO_ENAB(bus)) { if (bus->sleeping) { DHD_ERROR(("INTERRUPT WHILE SLEEPING??\n")); return; } else if (!KSO_ENAB(bus)) { DHD_ERROR(("ISR in devsleep 1\n")); } } /* Disable additional interrupts (is this needed now)? */ if (bus->intr) { DHD_INTR(("%s: disable SDIO interrupts\n", __FUNCTION__)); } else { DHD_ERROR(("dhdsdio_isr() w/o interrupt configured!\n")); } bcmsdh_intr_disable(sdh); bus->intdis = TRUE; #if defined(SDIO_ISR_THREAD) DHD_TRACE(("Calling dhdsdio_dpc() from %s\n", __FUNCTION__)); DHD_OS_WAKE_LOCK(bus->dhd); while (dhdsdio_dpc(bus)); DHD_OS_WAKE_UNLOCK(bus->dhd); #else bus->dpc_sched = TRUE; dhd_sched_dpc(bus->dhd); #endif } #ifdef SDTEST static void dhdsdio_pktgen_init(dhd_bus_t *bus) { /* Default to specified length, or full range */ if (dhd_pktgen_len) { bus->pktgen_maxlen = MIN(dhd_pktgen_len, MAX_PKTGEN_LEN); bus->pktgen_minlen = bus->pktgen_maxlen; } else { bus->pktgen_maxlen = MAX_PKTGEN_LEN; bus->pktgen_minlen = 0; } bus->pktgen_len = (uint16)bus->pktgen_minlen; /* Default to per-watchdog burst with 10s print time */ bus->pktgen_freq = 1; bus->pktgen_print = dhd_watchdog_ms ? (10000 / dhd_watchdog_ms) : 0; bus->pktgen_count = (dhd_pktgen * dhd_watchdog_ms + 999) / 1000; /* Default to echo mode */ bus->pktgen_mode = DHD_PKTGEN_ECHO; bus->pktgen_stop = 1; } static void dhdsdio_pktgen(dhd_bus_t *bus) { void *pkt; uint8 *data; uint pktcount; uint fillbyte; osl_t *osh = bus->dhd->osh; uint16 len; ulong time_lapse; uint sent_pkts; uint rcvd_pkts; /* Display current count if appropriate */ if (bus->pktgen_print && (++bus->pktgen_ptick >= bus->pktgen_print)) { bus->pktgen_ptick = 0; printf("%s: send attempts %d, rcvd %d, errors %d\n", __FUNCTION__, bus->pktgen_sent, bus->pktgen_rcvd, bus->pktgen_fail); /* Print throughput stats only for constant length packet runs */ if (bus->pktgen_minlen == bus->pktgen_maxlen) { time_lapse = jiffies - bus->pktgen_prev_time; bus->pktgen_prev_time = jiffies; sent_pkts = bus->pktgen_sent - bus->pktgen_prev_sent; bus->pktgen_prev_sent = bus->pktgen_sent; rcvd_pkts = bus->pktgen_rcvd - bus->pktgen_prev_rcvd; bus->pktgen_prev_rcvd = bus->pktgen_rcvd; printf("%s: Tx Throughput %d kbps, Rx Throughput %d kbps\n", __FUNCTION__, (sent_pkts * bus->pktgen_len / jiffies_to_msecs(time_lapse)) * 8, (rcvd_pkts * bus->pktgen_len / jiffies_to_msecs(time_lapse)) * 8); } } /* For recv mode, just make sure dongle has started sending */ if (bus->pktgen_mode == DHD_PKTGEN_RECV) { if (bus->pktgen_rcv_state == PKTGEN_RCV_IDLE) { bus->pktgen_rcv_state = PKTGEN_RCV_ONGOING; dhdsdio_sdtest_set(bus, bus->pktgen_total); } return; } /* Otherwise, generate or request the specified number of packets */ for (pktcount = 0; pktcount < bus->pktgen_count; pktcount++) { /* Stop if total has been reached */ if (bus->pktgen_total && (bus->pktgen_sent >= bus->pktgen_total)) { bus->pktgen_count = 0; break; } /* Allocate an appropriate-sized packet */ if (bus->pktgen_mode == DHD_PKTGEN_RXBURST) { len = SDPCM_TEST_PKT_CNT_FLD_LEN; } else { len = bus->pktgen_len; } if (!(pkt = PKTGET(osh, (len + SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + DHD_SDALIGN), TRUE))) {; DHD_ERROR(("%s: PKTGET failed!\n", __FUNCTION__)); break; } PKTALIGN(osh, pkt, (len + SDPCM_HDRLEN + SDPCM_TEST_HDRLEN), DHD_SDALIGN); data = (uint8*)PKTDATA(osh, pkt) + SDPCM_HDRLEN; /* Write test header cmd and extra based on mode */ switch (bus->pktgen_mode) { case DHD_PKTGEN_ECHO: *data++ = SDPCM_TEST_ECHOREQ; *data++ = (uint8)bus->pktgen_sent; break; case DHD_PKTGEN_SEND: *data++ = SDPCM_TEST_DISCARD; *data++ = (uint8)bus->pktgen_sent; break; case DHD_PKTGEN_RXBURST: *data++ = SDPCM_TEST_BURST; *data++ = (uint8)bus->pktgen_count; /* Just for backward compatability */ break; default: DHD_ERROR(("Unrecognized pktgen mode %d\n", bus->pktgen_mode)); PKTFREE(osh, pkt, TRUE); bus->pktgen_count = 0; return; } /* Write test header length field */ *data++ = (bus->pktgen_len >> 0); *data++ = (bus->pktgen_len >> 8); /* Write frame count in a 4 byte field adjucent to SDPCM test header for * burst mode */ if (bus->pktgen_mode == DHD_PKTGEN_RXBURST) { *data++ = (uint8)(bus->pktgen_count >> 0); *data++ = (uint8)(bus->pktgen_count >> 8); *data++ = (uint8)(bus->pktgen_count >> 16); *data++ = (uint8)(bus->pktgen_count >> 24); } else { /* Then fill in the remainder -- N/A for burst */ for (fillbyte = 0; fillbyte < len; fillbyte++) *data++ = SDPCM_TEST_FILL(fillbyte, (uint8)bus->pktgen_sent); } #ifdef DHD_DEBUG if (DHD_BYTES_ON() && DHD_DATA_ON()) { data = (uint8*)PKTDATA(osh, pkt) + SDPCM_HDRLEN; prhex("dhdsdio_pktgen: Tx Data", data, PKTLEN(osh, pkt) - SDPCM_HDRLEN); } #endif /* Send it */ if (dhdsdio_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, TRUE, FALSE)) { bus->pktgen_fail++; if (bus->pktgen_stop && bus->pktgen_stop == bus->pktgen_fail) bus->pktgen_count = 0; } bus->pktgen_sent++; /* Bump length if not fixed, wrap at max */ if (++bus->pktgen_len > bus->pktgen_maxlen) bus->pktgen_len = (uint16)bus->pktgen_minlen; /* Special case for burst mode: just send one request! */ if (bus->pktgen_mode == DHD_PKTGEN_RXBURST) break; } } static void dhdsdio_sdtest_set(dhd_bus_t *bus, uint count) { void *pkt; uint8 *data; osl_t *osh = bus->dhd->osh; /* Allocate the packet */ if (!(pkt = PKTGET(osh, SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + SDPCM_TEST_PKT_CNT_FLD_LEN + DHD_SDALIGN, TRUE))) { DHD_ERROR(("%s: PKTGET failed!\n", __FUNCTION__)); return; } PKTALIGN(osh, pkt, (SDPCM_HDRLEN + SDPCM_TEST_HDRLEN + SDPCM_TEST_PKT_CNT_FLD_LEN), DHD_SDALIGN); data = (uint8*)PKTDATA(osh, pkt) + SDPCM_HDRLEN; /* Fill in the test header */ *data++ = SDPCM_TEST_SEND; *data++ = (count > 0)?TRUE:FALSE; *data++ = (bus->pktgen_maxlen >> 0); *data++ = (bus->pktgen_maxlen >> 8); *data++ = (uint8)(count >> 0); *data++ = (uint8)(count >> 8); *data++ = (uint8)(count >> 16); *data++ = (uint8)(count >> 24); /* Send it */ if (dhdsdio_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, TRUE, FALSE)) bus->pktgen_fail++; } static void dhdsdio_testrcv(dhd_bus_t *bus, void *pkt, uint seq) { osl_t *osh = bus->dhd->osh; uint8 *data; uint pktlen; uint8 cmd; uint8 extra; uint16 len; uint16 offset; /* Check for min length */ if ((pktlen = PKTLEN(osh, pkt)) < SDPCM_TEST_HDRLEN) { DHD_ERROR(("dhdsdio_restrcv: toss runt frame, pktlen %d\n", pktlen)); PKTFREE(osh, pkt, FALSE); return; } /* Extract header fields */ data = PKTDATA(osh, pkt); cmd = *data++; extra = *data++; len = *data++; len += *data++ << 8; DHD_TRACE(("%s:cmd:%d, xtra:%d,len:%d\n", __FUNCTION__, cmd, extra, len)); /* Check length for relevant commands */ if (cmd == SDPCM_TEST_DISCARD || cmd == SDPCM_TEST_ECHOREQ || cmd == SDPCM_TEST_ECHORSP) { if (pktlen != len + SDPCM_TEST_HDRLEN) { DHD_ERROR(("dhdsdio_testrcv: frame length mismatch, pktlen %d seq %d" " cmd %d extra %d len %d\n", pktlen, seq, cmd, extra, len)); PKTFREE(osh, pkt, FALSE); return; } } /* Process as per command */ switch (cmd) { case SDPCM_TEST_ECHOREQ: /* Rx->Tx turnaround ok (even on NDIS w/current implementation) */ *(uint8 *)(PKTDATA(osh, pkt)) = SDPCM_TEST_ECHORSP; if (dhdsdio_txpkt(bus, pkt, SDPCM_TEST_CHANNEL, TRUE, FALSE) == 0) { bus->pktgen_sent++; } else { bus->pktgen_fail++; PKTFREE(osh, pkt, FALSE); } bus->pktgen_rcvd++; break; case SDPCM_TEST_ECHORSP: if (bus->ext_loop) { PKTFREE(osh, pkt, FALSE); bus->pktgen_rcvd++; break; } for (offset = 0; offset < len; offset++, data++) { if (*data != SDPCM_TEST_FILL(offset, extra)) { DHD_ERROR(("dhdsdio_testrcv: echo data mismatch: " "offset %d (len %d) expect 0x%02x rcvd 0x%02x\n", offset, len, SDPCM_TEST_FILL(offset, extra), *data)); break; } } PKTFREE(osh, pkt, FALSE); bus->pktgen_rcvd++; break; case SDPCM_TEST_DISCARD: { int i = 0; uint8 *prn = data; uint8 testval = extra; for (i = 0; i < len; i++) { if (*prn != testval) { DHD_ERROR(("DIErr@Pkt#:%d,Ix:%d, expected:0x%x, got:0x%x\n", i, bus->pktgen_rcvd_rcvsession, testval, *prn)); prn++; testval++; } } } PKTFREE(osh, pkt, FALSE); bus->pktgen_rcvd++; break; case SDPCM_TEST_BURST: case SDPCM_TEST_SEND: default: DHD_INFO(("dhdsdio_testrcv: unsupported or unknown command, pktlen %d seq %d" " cmd %d extra %d len %d\n", pktlen, seq, cmd, extra, len)); PKTFREE(osh, pkt, FALSE); break; } /* For recv mode, stop at limit (and tell dongle to stop sending) */ if (bus->pktgen_mode == DHD_PKTGEN_RECV) { if (bus->pktgen_rcv_state != PKTGEN_RCV_IDLE) { bus->pktgen_rcvd_rcvsession++; if (bus->pktgen_total && (bus->pktgen_rcvd_rcvsession >= bus->pktgen_total)) { bus->pktgen_count = 0; DHD_ERROR(("Pktgen:rcv test complete!\n")); bus->pktgen_rcv_state = PKTGEN_RCV_IDLE; dhdsdio_sdtest_set(bus, FALSE); bus->pktgen_rcvd_rcvsession = 0; } } } } #endif /* SDTEST */ extern void dhd_disable_intr(dhd_pub_t *dhdp) { dhd_bus_t *bus; bus = dhdp->bus; bcmsdh_intr_disable(bus->sdh); } extern bool dhd_bus_watchdog(dhd_pub_t *dhdp) { dhd_bus_t *bus; DHD_TIMER(("%s: Enter\n", __FUNCTION__)); bus = dhdp->bus; if (bus->dhd->dongle_reset) return FALSE; /* Ignore the timer if simulating bus down */ if (!SLPAUTO_ENAB(bus) && bus->sleeping) return FALSE; if (dhdp->busstate == DHD_BUS_DOWN) return FALSE; /* Poll period: check device if appropriate. */ if (!SLPAUTO_ENAB(bus) && (bus->poll && (++bus->polltick >= bus->pollrate))) { uint32 intstatus = 0; /* Reset poll tick */ bus->polltick = 0; /* Check device if no interrupts */ if (!bus->intr || (bus->intrcount == bus->lastintrs)) { #ifndef BCMSPI if (!bus->dpc_sched) { uint8 devpend; devpend = bcmsdh_cfg_read(bus->sdh, SDIO_FUNC_0, SDIOD_CCCR_INTPEND, NULL); intstatus = devpend & (INTR_STATUS_FUNC1 | INTR_STATUS_FUNC2); } #else if (!bus->dpc_sched) { uint32 devpend; devpend = bcmsdh_cfg_read_word(bus->sdh, SDIO_FUNC_0, SPID_STATUS_REG, NULL); intstatus = devpend & STATUS_F2_PKT_AVAILABLE; } #endif /* !BCMSPI */ /* If there is something, make like the ISR and schedule the DPC */ if (intstatus) { bus->pollcnt++; bus->ipend = TRUE; if (bus->intr) { bcmsdh_intr_disable(bus->sdh); } bus->dpc_sched = TRUE; dhd_sched_dpc(bus->dhd); } } /* Update interrupt tracking */ bus->lastintrs = bus->intrcount; } #ifdef DHD_DEBUG /* Poll for console output periodically */ if (dhdp->busstate == DHD_BUS_DATA && dhd_console_ms != 0) { bus->console.count += dhd_watchdog_ms; if (bus->console.count >= dhd_console_ms) { bus->console.count -= dhd_console_ms; /* Make sure backplane clock is on */ if (SLPAUTO_ENAB(bus)) dhdsdio_bussleep(bus, FALSE); else dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); if (dhdsdio_readconsole(bus) < 0) dhd_console_ms = 0; /* On error, stop trying */ } } #endif /* DHD_DEBUG */ #ifdef SDTEST /* Generate packets if configured */ if (bus->pktgen_count && (++bus->pktgen_tick >= bus->pktgen_freq)) { /* Make sure backplane clock is on */ if (SLPAUTO_ENAB(bus)) dhdsdio_bussleep(bus, FALSE); else dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); bus->pktgen_tick = 0; dhdsdio_pktgen(bus); } #endif /* On idle timeout clear activity flag and/or turn off clock */ #ifdef DHD_USE_IDLECOUNT if (bus->activity) bus->activity = FALSE; else { bus->idlecount++; if (bus->idlecount >= bus->idletime) { DHD_TIMER(("%s: DHD Idle state!!\n", __FUNCTION__)); if (SLPAUTO_ENAB(bus)) { if (dhdsdio_bussleep(bus, TRUE) != BCME_BUSY) dhd_os_wd_timer(bus->dhd, 0); } else dhdsdio_clkctl(bus, CLK_NONE, FALSE); bus->idlecount = 0; } } #else if ((bus->idletime > 0) && (bus->clkstate == CLK_AVAIL)) { if (++bus->idlecount > bus->idletime) { bus->idlecount = 0; if (bus->activity) { bus->activity = FALSE; if (SLPAUTO_ENAB(bus)) { if (!bus->readframes) dhdsdio_bussleep(bus, TRUE); else bus->reqbussleep = TRUE; } else dhdsdio_clkctl(bus, CLK_NONE, FALSE); } } } #endif /* DHD_USE_IDLECOUNT */ return bus->ipend; } #ifdef DHD_DEBUG extern int dhd_bus_console_in(dhd_pub_t *dhdp, uchar *msg, uint msglen) { dhd_bus_t *bus = dhdp->bus; uint32 addr, val; int rv; void *pkt; /* Address could be zero if CONSOLE := 0 in dongle Makefile */ if (bus->console_addr == 0) return BCME_UNSUPPORTED; /* Exclusive bus access */ dhd_os_sdlock(bus->dhd); /* Don't allow input if dongle is in reset */ if (bus->dhd->dongle_reset) { dhd_os_sdunlock(bus->dhd); return BCME_NOTREADY; } /* Request clock to allow SDIO accesses */ BUS_WAKE(bus); /* No pend allowed since txpkt is called later, ht clk has to be on */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); /* Zero cbuf_index */ addr = bus->console_addr + OFFSETOF(hndrte_cons_t, cbuf_idx); val = htol32(0); if ((rv = dhdsdio_membytes(bus, TRUE, addr, (uint8 *)&val, sizeof(val))) < 0) goto done; /* Write message into cbuf */ addr = bus->console_addr + OFFSETOF(hndrte_cons_t, cbuf); if ((rv = dhdsdio_membytes(bus, TRUE, addr, (uint8 *)msg, msglen)) < 0) goto done; /* Write length into vcons_in */ addr = bus->console_addr + OFFSETOF(hndrte_cons_t, vcons_in); val = htol32(msglen); if ((rv = dhdsdio_membytes(bus, TRUE, addr, (uint8 *)&val, sizeof(val))) < 0) goto done; /* Bump dongle by sending an empty packet on the event channel. * sdpcm_sendup (RX) checks for virtual console input. */ if ((pkt = PKTGET(bus->dhd->osh, 4 + SDPCM_RESERVE, TRUE)) != NULL) dhdsdio_txpkt(bus, pkt, SDPCM_EVENT_CHANNEL, TRUE, FALSE); done: if ((bus->idletime == DHD_IDLE_IMMEDIATE) && !bus->dpc_sched) { bus->activity = FALSE; dhdsdio_clkctl(bus, CLK_NONE, TRUE); } dhd_os_sdunlock(bus->dhd); return rv; } #endif /* DHD_DEBUG */ #ifdef DHD_DEBUG static void dhd_dump_cis(uint fn, uint8 *cis) { uint byte, tag, tdata; DHD_INFO(("Function %d CIS:\n", fn)); for (tdata = byte = 0; byte < SBSDIO_CIS_SIZE_LIMIT; byte++) { if ((byte % 16) == 0) DHD_INFO((" ")); DHD_INFO(("%02x ", cis[byte])); if ((byte % 16) == 15) DHD_INFO(("\n")); if (!tdata--) { tag = cis[byte]; if (tag == 0xff) break; else if (!tag) tdata = 0; else if ((byte + 1) < SBSDIO_CIS_SIZE_LIMIT) tdata = cis[byte + 1] + 1; else DHD_INFO(("]")); } } if ((byte % 16) != 15) DHD_INFO(("\n")); } #endif /* DHD_DEBUG */ static bool dhdsdio_chipmatch(uint16 chipid) { if (chipid == BCM4325_CHIP_ID) return TRUE; if (chipid == BCM4329_CHIP_ID) return TRUE; if (chipid == BCM4315_CHIP_ID) return TRUE; if (chipid == BCM4319_CHIP_ID) return TRUE; if (chipid == BCM4336_CHIP_ID) return TRUE; if (chipid == BCM4330_CHIP_ID) return TRUE; if (chipid == BCM43237_CHIP_ID) return TRUE; if (chipid == BCM43362_CHIP_ID) return TRUE; if (chipid == BCM4314_CHIP_ID) return TRUE; if (chipid == BCM43242_CHIP_ID) return TRUE; if (chipid == BCM43341_CHIP_ID) return TRUE; if (chipid == BCM43143_CHIP_ID) return TRUE; if (chipid == BCM43342_CHIP_ID) return TRUE; if (chipid == BCM4334_CHIP_ID) return TRUE; if (chipid == BCM43239_CHIP_ID) return TRUE; if (chipid == BCM4324_CHIP_ID) return TRUE; if (chipid == BCM4335_CHIP_ID) return TRUE; if (chipid == BCM4350_CHIP_ID) return TRUE; return FALSE; } static void * dhdsdio_probe(uint16 venid, uint16 devid, uint16 bus_no, uint16 slot, uint16 func, uint bustype, void *regsva, osl_t * osh, void *sdh) { int ret; dhd_bus_t *bus; #ifdef GET_CUSTOM_MAC_ENABLE struct ether_addr ea_addr; #endif /* GET_CUSTOM_MAC_ENABLE */ #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) if (mutex_is_locked(&_dhd_sdio_mutex_lock_) == 0) { DHD_ERROR(("%s : no mutex held. set lock\n", __FUNCTION__)); } else { DHD_ERROR(("%s : mutex is locked!. wait for unlocking\n", __FUNCTION__)); } mutex_lock(&_dhd_sdio_mutex_lock_); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) */ /* Init global variables at run-time, not as part of the declaration. * This is required to support init/de-init of the driver. Initialization * of globals as part of the declaration results in non-deterministic * behavior since the value of the globals may be different on the * first time that the driver is initialized vs subsequent initializations. */ dhd_txbound = DHD_TXBOUND; dhd_rxbound = DHD_RXBOUND; #ifdef BCMSPI dhd_alignctl = FALSE; #else dhd_alignctl = TRUE; #endif /* BCMSPI */ sd1idle = TRUE; dhd_readahead = TRUE; retrydata = FALSE; #ifndef REPEAT_READFRAME dhd_doflow = FALSE; #else dhd_doflow = TRUE; #endif /* REPEAT_READFRAME */ dhd_dongle_memsize = 0; dhd_txminmax = DHD_TXMINMAX; #ifdef BCMSPI forcealign = FALSE; #else forcealign = TRUE; #endif /* !BCMSPI */ DHD_TRACE(("%s: Enter\n", __FUNCTION__)); DHD_INFO(("%s: venid 0x%04x devid 0x%04x\n", __FUNCTION__, venid, devid)); /* We make assumptions about address window mappings */ ASSERT((uintptr)regsva == SI_ENUM_BASE); /* BCMSDH passes venid and devid based on CIS parsing -- but low-power start * means early parse could fail, so here we should get either an ID * we recognize OR (-1) indicating we must request power first. */ /* Check the Vendor ID */ switch (venid) { case 0x0000: case VENDOR_BROADCOM: break; default: DHD_ERROR(("%s: unknown vendor: 0x%04x\n", __FUNCTION__, venid)); goto forcereturn; } /* Check the Device ID and make sure it's one that we support */ switch (devid) { case BCM4325_D11DUAL_ID: /* 4325 802.11a/g id */ case BCM4325_D11G_ID: /* 4325 802.11g 2.4Ghz band id */ case BCM4325_D11A_ID: /* 4325 802.11a 5Ghz band id */ DHD_INFO(("%s: found 4325 Dongle\n", __FUNCTION__)); break; case BCM4329_D11N_ID: /* 4329 802.11n dualband device */ case BCM4329_D11N2G_ID: /* 4329 802.11n 2.4G device */ case BCM4329_D11N5G_ID: /* 4329 802.11n 5G device */ case 0x4329: DHD_INFO(("%s: found 4329 Dongle\n", __FUNCTION__)); break; case BCM4315_D11DUAL_ID: /* 4315 802.11a/g id */ case BCM4315_D11G_ID: /* 4315 802.11g id */ case BCM4315_D11A_ID: /* 4315 802.11a id */ DHD_INFO(("%s: found 4315 Dongle\n", __FUNCTION__)); break; case BCM4319_D11N_ID: /* 4319 802.11n id */ case BCM4319_D11N2G_ID: /* 4319 802.11n2g id */ case BCM4319_D11N5G_ID: /* 4319 802.11n5g id */ DHD_INFO(("%s: found 4319 Dongle\n", __FUNCTION__)); break; case 0: DHD_INFO(("%s: allow device id 0, will check chip internals\n", __FUNCTION__)); break; default: DHD_ERROR(("%s: skipping 0x%04x/0x%04x, not a dongle\n", __FUNCTION__, venid, devid)); goto forcereturn; } if (osh == NULL) { /* Ask the OS interface part for an OSL handle */ if (!(osh = dhd_osl_attach(sdh, DHD_BUS))) { DHD_ERROR(("%s: osl_attach failed!\n", __FUNCTION__)); goto forcereturn; } } /* Allocate private bus interface state */ if (!(bus = MALLOC(osh, sizeof(dhd_bus_t)))) { DHD_ERROR(("%s: MALLOC of dhd_bus_t failed\n", __FUNCTION__)); goto fail; } bzero(bus, sizeof(dhd_bus_t)); bus->sdh = sdh; bus->cl_devid = (uint16)devid; bus->bus = DHD_BUS; bus->tx_seq = SDPCM_SEQUENCE_WRAP - 1; bus->usebufpool = FALSE; /* Use bufpool if allocated, else use locally malloced rxbuf */ /* attach the common module */ dhd_common_init(osh); /* attempt to attach to the dongle */ if (!(dhdsdio_probe_attach(bus, osh, sdh, regsva, devid))) { DHD_ERROR(("%s: dhdsdio_probe_attach failed\n", __FUNCTION__)); goto fail; } /* Attach to the dhd/OS/network interface */ if (!(bus->dhd = dhd_attach(osh, bus, SDPCM_RESERVE))) { DHD_ERROR(("%s: dhd_attach failed\n", __FUNCTION__)); goto fail; } /* Allocate buffers */ if (!(dhdsdio_probe_malloc(bus, osh, sdh))) { DHD_ERROR(("%s: dhdsdio_probe_malloc failed\n", __FUNCTION__)); goto fail; } if (!(dhdsdio_probe_init(bus, osh, sdh))) { DHD_ERROR(("%s: dhdsdio_probe_init failed\n", __FUNCTION__)); goto fail; } if (bus->intr) { /* Register interrupt callback, but mask it (not operational yet). */ DHD_INTR(("%s: disable SDIO interrupts (not interested yet)\n", __FUNCTION__)); bcmsdh_intr_disable(sdh); if ((ret = bcmsdh_intr_reg(sdh, dhdsdio_isr, bus)) != 0) { DHD_ERROR(("%s: FAILED: bcmsdh_intr_reg returned %d\n", __FUNCTION__, ret)); goto fail; } DHD_INTR(("%s: registered SDIO interrupt function ok\n", __FUNCTION__)); } else { DHD_INFO(("%s: SDIO interrupt function is NOT registered due to polling mode\n", __FUNCTION__)); } DHD_INFO(("%s: completed!!\n", __FUNCTION__)); #ifdef GET_CUSTOM_MAC_ENABLE /* Read MAC address from external customer place */ memset(&ea_addr, 0, sizeof(ea_addr)); ret = dhd_custom_get_mac_address(ea_addr.octet); if (!ret) { memcpy(bus->dhd->mac.octet, (void *)&ea_addr, ETHER_ADDR_LEN); } #endif /* GET_CUSTOM_MAC_ENABLE */ /* if firmware path present try to download and bring up bus */ if (dhd_download_fw_on_driverload) { if ((ret = dhd_bus_start(bus->dhd)) != 0) { DHD_ERROR(("%s: dhd_bus_start failed\n", __FUNCTION__)); goto fail; } } /* Ok, have the per-port tell the stack we're open for business */ if (dhd_net_attach(bus->dhd, 0) != 0) { DHD_ERROR(("%s: Net attach failed!!\n", __FUNCTION__)); goto fail; } #if defined(CUSTOMER_HW4) && defined(BCMHOST_XTAL_PU_TIME_MOD) bcmsdh_reg_write(bus->sdh, 0x18000620, 2, 11); bcmsdh_reg_write(bus->sdh, 0x18000628, 4, 0x00F80001); #endif #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) mutex_unlock(&_dhd_sdio_mutex_lock_); DHD_ERROR(("%s : the lock is released.\n", __FUNCTION__)); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) */ return bus; fail: dhdsdio_release(bus, osh); forcereturn: #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) mutex_unlock(&_dhd_sdio_mutex_lock_); DHD_ERROR(("%s : the lock is released.\n", __FUNCTION__)); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)) */ return NULL; } #ifdef REGON_BP_HANG_FIX static int dhd_sdio_backplane_reset(struct dhd_bus *bus) { uint32 temp = 0; DHD_ERROR(("Resetting the backplane to avoid failure in firmware download..\n")); temp = bcmsdh_reg_read(bus->sdh, 0x180021e0, 4); DHD_INFO(("SDIO Clk Control Reg = %x\n", temp)); /* Force HT req from PMU */ bcmsdh_reg_write(bus->sdh, 0x18000644, 4, 0x6000005); /* Increase the clock stretch duration. */ bcmsdh_reg_write(bus->sdh, 0x18000630, 4, 0xC8FFC8); /* Setting ALP clock request in SDIOD clock control status register */ bcmsdh_reg_write(bus->sdh, 0x180021e0, 4, 0x41); /* Allowing clock from SR engine to SR memory */ bcmsdh_reg_write(bus->sdh, 0x18004400, 4, 0xf92f1); /* Disabling SR Engine before SR binary download. */ bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x0); /* Enabling clock from backplane to SR memory */ bcmsdh_reg_write(bus->sdh, 0x18004400, 4, 0xf9af1); /* Initializing SR memory address register in SOCRAM */ bcmsdh_reg_write(bus->sdh, 0x18004408, 4, 0x0); /* Downloading the SR binary */ bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0xc0002000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x80008000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x1051f080); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x80008000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x1050f080); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x80008000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x1050f080); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x80008000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x1050f080); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000004); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000604); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00001604); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00001404); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a08c80); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010001); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x14a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00011404); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00002000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x04a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00002000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0xf8000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00002000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x04a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00002000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0xf8000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00011604); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010604); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010004); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x14a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000004); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010001); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x14a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010004); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00010000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x14a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x30a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000008); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x04a00000); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0x00000008); bcmsdh_reg_write(bus->sdh, 0x1800440c, 4, 0xfc000000); /* SR Binary Download complete */ /* Allowing clock from SR engine to SR memory */ bcmsdh_reg_write(bus->sdh, 0x18004400, 4, 0xf92f1); /* Turning ON SR Engine to initiate backplane reset Repeated ?? Maharana */ bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x0); bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x2); bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x37); bcmsdh_reg_write(bus->sdh, 0x18000650, 4, 0x3); temp = bcmsdh_reg_read(bus->sdh, 0x18000654, 4); DHD_INFO(("0x18000654 = %x\n", temp)); bcmsdh_reg_write(bus->sdh, 0x18000654, 4, 0x800037); OSL_DELAY(100000); /* Rolling back the original values for clock stretch and PMU timers */ bcmsdh_reg_write(bus->sdh, 0x18000644, 4, 0x0); bcmsdh_reg_write(bus->sdh, 0x18000630, 4, 0xC800C8); /* Removing ALP clock request in SDIOD clock control status register */ bcmsdh_reg_write(bus->sdh, 0x180021e0, 4, 0x40); OSL_DELAY(10000); return TRUE; } static int dhdsdio_sdio_hang_war(struct dhd_bus *bus) { uint32 temp = 0, temp2 = 0, counter = 0, BT_pwr_up = 0, BT_ready = 0; /* Removing reset of D11 Core */ bcmsdh_reg_write(bus->sdh, 0x18101408, 4, 0x3); bcmsdh_reg_write(bus->sdh, 0x18101800, 4, 0x0); bcmsdh_reg_write(bus->sdh, 0x18101408, 4, 0x1); /* Reading CLB XTAL BT cntrl register */ bcmsdh_reg_write(bus->sdh, 0x180013D8, 2, 0xD1); bcmsdh_reg_write(bus->sdh, 0x180013DA, 2, 0x12); bcmsdh_reg_write(bus->sdh, 0x180013D8, 2, 0x2D0); /* Read if BT is powered up */ temp = bcmsdh_reg_read(bus->sdh, 0x180013DA, 2); /* Read BT_ready from WLAN wireless register */ temp2 = bcmsdh_reg_read(bus->sdh, 0x1800002C, 4); /* Check if the BT is powered up and ready. The duration between BT being powered up and BT becoming ready is the problematic window for WLAN. If we move ahead at this time then we may encounter a corrupted backplane later. So we wait for BT to be ready and then proceed after checking the health of the backplane. If the backplane shows indications of failure then we have to do a full reset of the backplane using SR engine and then proceed. */ (temp & 0xF0) ? (BT_pwr_up = 1):(BT_pwr_up = 0); (temp2 & (1<<17)) ? (BT_ready = 1):(BT_ready = 0); DHD_ERROR(("WARNING: Checking if BT is ready BT_pwr_up = %x" "BT_ready = %x \n", BT_pwr_up, BT_ready)); while (BT_pwr_up && !BT_ready) { OSL_DELAY(1000); bcmsdh_reg_write(bus->sdh, 0x180013D8, 2, 0x2D0); temp = bcmsdh_reg_read(bus->sdh, 0x180013DA, 2); temp2 = bcmsdh_reg_read(bus->sdh, 0x1800002C, 4); (temp & 0xF0) ? (BT_pwr_up = 1):(BT_pwr_up = 0); (temp2 & (1<<17)) ? (BT_ready = 1):(BT_ready = 0); counter++; if (counter == 5000) { DHD_ERROR(("WARNING: Going ahead after 5 secs with" "risk of failure because BT ready is not yet set\n")); break; } } DHD_ERROR(("\nWARNING: WL Proceeding BT_pwr_up = %x BT_ready = %x" "\n", BT_pwr_up, BT_ready)); counter = 0; OSL_DELAY(10000); /* Get the information of who accessed the crucial backplane entities by reading read and write access registers */ DHD_TRACE(("%d: Read Value @ 0x18104808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18104808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810480C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810480C, 4))); DHD_TRACE(("%d: Read Value @ 0x18106808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18106808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810680C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810680C, 4))); DHD_TRACE(("%d: Read Value @ 0x18107808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18107808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810780C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810780C, 4))); DHD_TRACE(("%d: Read Value @ 0x18108808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18108808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810880C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810880C, 4))); DHD_TRACE(("%d: Read Value @ 0x18109808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18109808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810980C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810980C, 4))); DHD_TRACE(("%d: Read Value @ 0x1810C808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810c808, 4))); DHD_TRACE(("%d: Read Value @ 0x1810C80C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810c80C, 4))); counter = 0; while ((bcmsdh_reg_read(bus->sdh, 0x18104808, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810480C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x18106808, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810680C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810780C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810780C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810880C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810880C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810980C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810980C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810C80C, 4) == 5) || (bcmsdh_reg_read(bus->sdh, 0x1810C80C, 4) == 5)) { if (++counter > 10) { DHD_ERROR(("Unable to recover the backkplane corruption" "..Tried %d times.. Exiting\n", counter)); break; } OSL_DELAY(10000); dhd_sdio_backplane_reset(bus); /* Get the information of who accessed the crucial backplane entities by reading read and write access registers */ DHD_ERROR(("%d: Read Value @ 0x18104808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18104808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810480C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810480C, 4))); DHD_ERROR(("%d: Read Value @ 0x18106808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18106808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810680C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810680C, 4))); DHD_ERROR(("%d: Read Value @ 0x18107808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18107808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810780C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810780C, 4))); DHD_ERROR(("%d: Read Value @ 0x18108808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18108808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810880C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810880C, 4))); DHD_ERROR(("%d: Read Value @ 0x18109808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x18109808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810980C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810980C, 4))); DHD_ERROR(("%d: Read Value @ 0x1810C808 = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810c808, 4))); DHD_ERROR(("%d: Read Value @ 0x1810C80C = %x." "\n", __LINE__, bcmsdh_reg_read(bus->sdh, 0x1810c80C, 4))); } /* Set the WL ready to indicate BT that we are done with backplane reset */ DHD_ERROR(("Setting up AXI_OK\n")); bcmsdh_reg_write(bus->sdh, 0x18000658, 4, 0x3); temp = bcmsdh_reg_read(bus->sdh, 0x1800065c, 4); temp |= 0x80000000; bcmsdh_reg_write(bus->sdh, 0x1800065c, 4, temp); return TRUE; } #endif /* REGON_BP_HANG_FIX */ static bool dhdsdio_probe_attach(struct dhd_bus *bus, osl_t *osh, void *sdh, void *regsva, uint16 devid) { #ifndef BCMSPI int err = 0; uint8 clkctl = 0; #endif /* !BCMSPI */ bus->alp_only = TRUE; bus->sih = NULL; /* Return the window to backplane enumeration space for core access */ if (dhdsdio_set_siaddr_window(bus, SI_ENUM_BASE)) { DHD_ERROR(("%s: FAILED to return to SI_ENUM_BASE\n", __FUNCTION__)); } #ifdef DHD_DEBUG DHD_ERROR(("F1 signature read @0x18000000=0x%4x\n", bcmsdh_reg_read(bus->sdh, SI_ENUM_BASE, 4))); #endif /* DHD_DEBUG */ #ifndef BCMSPI /* wake-wlan in gSPI will bring up the htavail/alpavail clocks. */ /* Force PLL off until si_attach() programs PLL control regs */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, DHD_INIT_CLKCTL1, &err); if (!err) clkctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, &err); if (err || ((clkctl & ~SBSDIO_AVBITS) != DHD_INIT_CLKCTL1)) { DHD_ERROR(("dhdsdio_probe: ChipClkCSR access: err %d wrote 0x%02x read 0x%02x\n", err, DHD_INIT_CLKCTL1, clkctl)); goto fail; } #endif /* !BCMSPI */ #ifdef DHD_DEBUG if (DHD_INFO_ON()) { uint fn, numfn; uint8 *cis[SDIOD_MAX_IOFUNCS]; int err = 0; #ifndef BCMSPI numfn = bcmsdh_query_iofnum(sdh); ASSERT(numfn <= SDIOD_MAX_IOFUNCS); /* Make sure ALP is available before trying to read CIS */ SPINWAIT(((clkctl = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, NULL)), !SBSDIO_ALPAV(clkctl)), PMU_MAX_TRANSITION_DLY); /* Now request ALP be put on the bus */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, DHD_INIT_CLKCTL2, &err); OSL_DELAY(65); #else numfn = 0; /* internally func is hardcoded to 1 as gSPI has cis on F1 only */ #endif /* !BCMSPI */ for (fn = 0; fn <= numfn; fn++) { if (!(cis[fn] = MALLOC(osh, SBSDIO_CIS_SIZE_LIMIT))) { DHD_INFO(("dhdsdio_probe: fn %d cis malloc failed\n", fn)); break; } bzero(cis[fn], SBSDIO_CIS_SIZE_LIMIT); if ((err = bcmsdh_cis_read(sdh, fn, cis[fn], SBSDIO_CIS_SIZE_LIMIT))) { DHD_INFO(("dhdsdio_probe: fn %d cis read err %d\n", fn, err)); MFREE(osh, cis[fn], SBSDIO_CIS_SIZE_LIMIT); break; } dhd_dump_cis(fn, cis[fn]); } while (fn-- > 0) { ASSERT(cis[fn]); MFREE(osh, cis[fn], SBSDIO_CIS_SIZE_LIMIT); } if (err) { DHD_ERROR(("dhdsdio_probe: failure reading or parsing CIS\n")); goto fail; } } #endif /* DHD_DEBUG */ /* si_attach() will provide an SI handle and scan the backplane */ if (!(bus->sih = si_attach((uint)devid, osh, regsva, DHD_BUS, sdh, &bus->vars, &bus->varsz))) { DHD_ERROR(("%s: si_attach failed!\n", __FUNCTION__)); goto fail; } #ifdef REGON_BP_HANG_FIX /* WAR - for 43241 B0-B1-B2. B3 onwards do not need this */ if (((uint16)bus->sih->chip == BCM4324_CHIP_ID) && (bus->sih->chiprev < 3)) dhdsdio_sdio_hang_war(bus); #endif /* REGON_BP_HANG_FIX */ bcmsdh_chipinfo(sdh, bus->sih->chip, bus->sih->chiprev); if (!dhdsdio_chipmatch((uint16)bus->sih->chip)) { DHD_ERROR(("%s: unsupported chip: 0x%04x\n", __FUNCTION__, bus->sih->chip)); goto fail; } if (bus->sih->buscorerev >= 12) dhdsdio_clk_kso_init(bus); else bus->kso = TRUE; if (CST4330_CHIPMODE_SDIOD(bus->sih->chipst)) { } si_sdiod_drive_strength_init(bus->sih, osh, dhd_sdiod_drive_strength); /* Get info on the ARM and SOCRAM cores... */ if (!DHD_NOPMU(bus)) { if ((si_setcore(bus->sih, ARM7S_CORE_ID, 0)) || (si_setcore(bus->sih, ARMCM3_CORE_ID, 0)) || (si_setcore(bus->sih, ARMCR4_CORE_ID, 0))) { bus->armrev = si_corerev(bus->sih); } else { DHD_ERROR(("%s: failed to find ARM core!\n", __FUNCTION__)); goto fail; } if (!si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { if (!(bus->orig_ramsize = si_socram_size(bus->sih))) { DHD_ERROR(("%s: failed to find SOCRAM memory!\n", __FUNCTION__)); goto fail; } } else { /* cr4 has a different way to find the RAM size from TCM's */ if (!(bus->orig_ramsize = si_tcm_size(bus->sih))) { DHD_ERROR(("%s: failed to find CR4-TCM memory!\n", __FUNCTION__)); goto fail; } /* also populate base address */ switch ((uint16)bus->sih->chip) { case BCM4335_CHIP_ID: bus->dongle_ram_base = CR4_4335_RAM_BASE; break; case BCM4350_CHIP_ID: bus->dongle_ram_base = CR4_4350_RAM_BASE; break; case BCM4360_CHIP_ID: bus->dongle_ram_base = CR4_4360_RAM_BASE; break; default: bus->dongle_ram_base = 0; DHD_ERROR(("%s: WARNING: Using default ram base at 0x%x\n", __FUNCTION__, bus->dongle_ram_base)); } } bus->ramsize = bus->orig_ramsize; if (dhd_dongle_memsize) dhd_dongle_setmemsize(bus, dhd_dongle_memsize); DHD_ERROR(("DHD: dongle ram size is set to %d(orig %d) at 0x%x\n", bus->ramsize, bus->orig_ramsize, bus->dongle_ram_base)); bus->srmemsize = si_socram_srmem_size(bus->sih); } /* ...but normally deal with the SDPCMDEV core */ if (!(bus->regs = si_setcore(bus->sih, PCMCIA_CORE_ID, 0)) && !(bus->regs = si_setcore(bus->sih, SDIOD_CORE_ID, 0))) { DHD_ERROR(("%s: failed to find SDIODEV core!\n", __FUNCTION__)); goto fail; } bus->sdpcmrev = si_corerev(bus->sih); /* Set core control so an SDIO reset does a backplane reset */ OR_REG(osh, &bus->regs->corecontrol, CC_BPRESEN); #ifndef BCMSPI bus->rxint_mode = SDIO_DEVICE_HMB_RXINT; if ((bus->sih->buscoretype == SDIOD_CORE_ID) && (bus->sdpcmrev >= 4) && (bus->rxint_mode == SDIO_DEVICE_RXDATAINT_MODE_1)) { uint32 val; val = R_REG(osh, &bus->regs->corecontrol); val &= ~CC_XMTDATAAVAIL_MODE; val |= CC_XMTDATAAVAIL_CTRL; W_REG(osh, &bus->regs->corecontrol, val); } #endif /* BCMSPI */ pktq_init(&bus->txq, (PRIOMASK + 1), QLEN); /* Locate an appropriately-aligned portion of hdrbuf */ bus->rxhdr = (uint8 *)ROUNDUP((uintptr)&bus->hdrbuf[0], DHD_SDALIGN); /* Set the poll and/or interrupt flags */ bus->intr = (bool)dhd_intr; if ((bus->poll = (bool)dhd_poll)) bus->pollrate = 1; #ifdef BCMSDIOH_TXGLOM /* Setting default Glom mode */ bus->glom_mode = bcmsdh_set_mode(bus->sdh, SDPCM_DEFGLOM_MODE); /* Setting default Glom size */ bus->glomsize = SDPCM_DEFGLOM_SIZE; #endif return TRUE; fail: if (bus->sih != NULL) { si_detach(bus->sih); bus->sih = NULL; } return FALSE; } static bool dhdsdio_probe_malloc(dhd_bus_t *bus, osl_t *osh, void *sdh) { DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus->dhd->maxctl) { bus->rxblen = ROUNDUP((bus->dhd->maxctl + SDPCM_HDRLEN), ALIGNMENT) + DHD_SDALIGN; if (!(bus->rxbuf = DHD_OS_PREALLOC(osh, DHD_PREALLOC_RXBUF, bus->rxblen))) { DHD_ERROR(("%s: MALLOC of %d-byte rxbuf failed\n", __FUNCTION__, bus->rxblen)); goto fail; } } /* Allocate buffer to receive glomed packet */ if (!(bus->databuf = DHD_OS_PREALLOC(osh, DHD_PREALLOC_DATABUF, MAX_DATA_BUF))) { DHD_ERROR(("%s: MALLOC of %d-byte databuf failed\n", __FUNCTION__, MAX_DATA_BUF)); /* release rxbuf which was already located as above */ if (!bus->rxblen) DHD_OS_PREFREE(osh, bus->rxbuf, bus->rxblen); goto fail; } /* Align the buffer */ if ((uintptr)bus->databuf % DHD_SDALIGN) bus->dataptr = bus->databuf + (DHD_SDALIGN - ((uintptr)bus->databuf % DHD_SDALIGN)); else bus->dataptr = bus->databuf; return TRUE; fail: return FALSE; } static bool dhdsdio_probe_init(dhd_bus_t *bus, osl_t *osh, void *sdh) { int32 fnum; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); #ifdef SDTEST dhdsdio_pktgen_init(bus); #endif /* SDTEST */ #ifndef BCMSPI /* Disable F2 to clear any intermediate frame state on the dongle */ bcmsdh_cfg_write(sdh, SDIO_FUNC_0, SDIOD_CCCR_IOEN, SDIO_FUNC_ENABLE_1, NULL); #endif /* !BCMSPI */ bus->dhd->busstate = DHD_BUS_DOWN; bus->sleeping = FALSE; bus->rxflow = FALSE; bus->prev_rxlim_hit = 0; #ifndef BCMSPI /* Done with backplane-dependent accesses, can drop clock... */ bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, 0, NULL); #endif /* !BCMSPI */ /* ...and initialize clock/power states */ bus->clkstate = CLK_SDONLY; bus->idletime = (int32)dhd_idletime; bus->idleclock = DHD_IDLE_ACTIVE; /* Query the SD clock speed */ if (bcmsdh_iovar_op(sdh, "sd_divisor", NULL, 0, &bus->sd_divisor, sizeof(int32), FALSE) != BCME_OK) { DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, "sd_divisor")); bus->sd_divisor = -1; } else { DHD_INFO(("%s: Initial value for %s is %d\n", __FUNCTION__, "sd_divisor", bus->sd_divisor)); } /* Query the SD bus mode */ if (bcmsdh_iovar_op(sdh, "sd_mode", NULL, 0, &bus->sd_mode, sizeof(int32), FALSE) != BCME_OK) { DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, "sd_mode")); bus->sd_mode = -1; } else { DHD_INFO(("%s: Initial value for %s is %d\n", __FUNCTION__, "sd_mode", bus->sd_mode)); } /* Query the F2 block size, set roundup accordingly */ fnum = 2; if (bcmsdh_iovar_op(sdh, "sd_blocksize", &fnum, sizeof(int32), &bus->blocksize, sizeof(int32), FALSE) != BCME_OK) { bus->blocksize = 0; DHD_ERROR(("%s: fail on %s get\n", __FUNCTION__, "sd_blocksize")); } else { DHD_INFO(("%s: Initial value for %s is %d\n", __FUNCTION__, "sd_blocksize", bus->blocksize)); if (bus->sih->chip == BCM4335_CHIP_ID) dhd_overflow_war(bus); } bus->roundup = MIN(max_roundup, bus->blocksize); /* Query if bus module supports packet chaining, default to use if supported */ if (bcmsdh_iovar_op(sdh, "sd_rxchain", NULL, 0, &bus->sd_rxchain, sizeof(int32), FALSE) != BCME_OK) { bus->sd_rxchain = FALSE; } else { DHD_INFO(("%s: bus module (through bcmsdh API) %s chaining\n", __FUNCTION__, (bus->sd_rxchain ? "supports" : "does not support"))); } bus->use_rxchain = (bool)bus->sd_rxchain; return TRUE; } bool dhd_bus_download_firmware(struct dhd_bus *bus, osl_t *osh, char *pfw_path, char *pnv_path) { bool ret; bus->fw_path = pfw_path; bus->nv_path = pnv_path; ret = dhdsdio_download_firmware(bus, osh, bus->sdh); #ifdef BCMSPI #ifdef GSPI_DWORD_MODE /* Enable the dwordmode in gSPI before first F2 transaction */ if ((bus->sih->chip == BCM4329_CHIP_ID) && (bus->sih->chiprev > 1)) { bcmsdh_dwordmode(bus->sdh, TRUE); bus->dwordmode = TRUE; } #endif /* GSPI_DWORD_MODE */ #endif /* BCMSPI */ return ret; } static bool dhdsdio_download_firmware(struct dhd_bus *bus, osl_t *osh, void *sdh) { bool ret; DHD_OS_WAKE_LOCK(bus->dhd); /* Download the firmware */ dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); ret = _dhdsdio_download_firmware(bus) == 0; dhdsdio_clkctl(bus, CLK_SDONLY, FALSE); DHD_OS_WAKE_UNLOCK(bus->dhd); return ret; } /* Detach and free everything */ static void dhdsdio_release(dhd_bus_t *bus, osl_t *osh) { bool dongle_isolation = FALSE; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus) { ASSERT(osh); if (bus->dhd) { dongle_isolation = bus->dhd->dongle_isolation; dhd_detach(bus->dhd); } /* De-register interrupt handler */ bcmsdh_intr_disable(bus->sdh); bcmsdh_intr_dereg(bus->sdh); if (bus->dhd) { dhdsdio_release_dongle(bus, osh, dongle_isolation, TRUE); dhd_free(bus->dhd); bus->dhd = NULL; } dhdsdio_release_malloc(bus, osh); #ifdef DHD_DEBUG if (bus->console.buf != NULL) MFREE(osh, bus->console.buf, bus->console.bufsize); #endif MFREE(osh, bus, sizeof(dhd_bus_t)); } if (osh) dhd_osl_detach(osh); DHD_TRACE(("%s: Disconnected\n", __FUNCTION__)); } static void dhdsdio_release_malloc(dhd_bus_t *bus, osl_t *osh) { DHD_TRACE(("%s: Enter\n", __FUNCTION__)); if (bus->dhd && bus->dhd->dongle_reset) return; if (bus->rxbuf) { #ifndef CONFIG_DHD_USE_STATIC_BUF MFREE(osh, bus->rxbuf, bus->rxblen); #endif bus->rxctl = bus->rxbuf = NULL; bus->rxlen = 0; } if (bus->databuf) { #ifndef CONFIG_DHD_USE_STATIC_BUF MFREE(osh, bus->databuf, MAX_DATA_BUF); #endif bus->databuf = NULL; } if (bus->vars && bus->varsz) { MFREE(osh, bus->vars, bus->varsz); bus->vars = NULL; } } static void dhdsdio_release_dongle(dhd_bus_t *bus, osl_t *osh, bool dongle_isolation, bool reset_flag) { DHD_TRACE(("%s: Enter bus->dhd %p bus->dhd->dongle_reset %d \n", __FUNCTION__, bus->dhd, bus->dhd->dongle_reset)); if ((bus->dhd && bus->dhd->dongle_reset) && reset_flag) return; if (bus->sih) { #if !defined(BCMLXSDMMC) if (bus->dhd) { dhdsdio_clkctl(bus, CLK_AVAIL, FALSE); } if (KSO_ENAB(bus) && (dongle_isolation == FALSE)) si_watchdog(bus->sih, 4); #endif /* !defined(BCMLXSDMMC) */ if (bus->dhd) { dhdsdio_clkctl(bus, CLK_NONE, FALSE); } si_detach(bus->sih); bus->sih = NULL; if (bus->vars && bus->varsz) MFREE(osh, bus->vars, bus->varsz); bus->vars = NULL; } DHD_TRACE(("%s: Disconnected\n", __FUNCTION__)); } static void dhdsdio_disconnect(void *ptr) { dhd_bus_t *bus = (dhd_bus_t *)ptr; DHD_TRACE(("%s: Enter\n", __FUNCTION__)); #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) if (mutex_is_locked(&_dhd_sdio_mutex_lock_) == 0) { DHD_ERROR(("%s : no mutex held. set lock\n", __FUNCTION__)); } else { DHD_ERROR(("%s : mutex is locked!. wait for unlocking\n", __FUNCTION__)); } mutex_lock(&_dhd_sdio_mutex_lock_); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) */ if (bus) { ASSERT(bus->dhd); dhdsdio_release(bus, bus->dhd->osh); } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) mutex_unlock(&_dhd_sdio_mutex_lock_); DHD_ERROR(("%s : the lock is released.\n", __FUNCTION__)); #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) */ DHD_TRACE(("%s: Disconnected\n", __FUNCTION__)); } /* Register/Unregister functions are called by the main DHD entry * point (e.g. module insertion) to link with the bus driver, in * order to look for or await the device. */ static bcmsdh_driver_t dhd_sdio = { dhdsdio_probe, dhdsdio_disconnect }; int dhd_bus_register(void) { DHD_TRACE(("%s: Enter\n", __FUNCTION__)); return bcmsdh_register(&dhd_sdio); } void dhd_bus_unregister(void) { DHD_TRACE(("%s: Enter\n", __FUNCTION__)); bcmsdh_unregister(); } #if defined(BCMLXSDMMC) /* Register a dummy SDIO client driver in order to be notified of new SDIO device */ int dhd_bus_reg_sdio_notify(void* semaphore) { return bcmsdh_reg_sdio_notify(semaphore); } void dhd_bus_unreg_sdio_notify(void) { bcmsdh_unreg_sdio_notify(); } #endif /* defined(BCMLXSDMMC) */ #ifdef BCMEMBEDIMAGE static int dhdsdio_download_code_array(struct dhd_bus *bus) { int bcmerror = -1; int offset = 0; unsigned char *ularray = NULL; DHD_INFO(("%s: download embedded firmware...\n", __FUNCTION__)); /* Download image */ while ((offset + MEMBLOCK) < sizeof(dlarray)) { /* check if CR4 */ if (si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { /* if address is 0, store the reset instruction to be written in 0 */ if (offset == 0) { bus->resetinstr = *(((uint32*)dlarray)); /* Add start of RAM address to the address given by user */ offset += bus->dongle_ram_base; } } bcmerror = dhdsdio_membytes(bus, TRUE, offset, (uint8 *) (dlarray + offset), MEMBLOCK); if (bcmerror) { DHD_ERROR(("%s: error %d on writing %d membytes at 0x%08x\n", __FUNCTION__, bcmerror, MEMBLOCK, offset)); goto err; } offset += MEMBLOCK; } if (offset < sizeof(dlarray)) { bcmerror = dhdsdio_membytes(bus, TRUE, offset, (uint8 *) (dlarray + offset), sizeof(dlarray) - offset); if (bcmerror) { DHD_ERROR(("%s: error %d on writing %d membytes at 0x%08x\n", __FUNCTION__, bcmerror, sizeof(dlarray) - offset, offset)); goto err; } } #ifdef DHD_DEBUG /* Upload and compare the downloaded code */ { ularray = MALLOC(bus->dhd->osh, bus->ramsize); /* Upload image to verify downloaded contents. */ offset = 0; memset(ularray, 0xaa, bus->ramsize); while ((offset + MEMBLOCK) < sizeof(dlarray)) { bcmerror = dhdsdio_membytes(bus, FALSE, offset, ularray + offset, MEMBLOCK); if (bcmerror) { DHD_ERROR(("%s: error %d on reading %d membytes at 0x%08x\n", __FUNCTION__, bcmerror, MEMBLOCK, offset)); goto err; } offset += MEMBLOCK; } if (offset < sizeof(dlarray)) { bcmerror = dhdsdio_membytes(bus, FALSE, offset, ularray + offset, sizeof(dlarray) - offset); if (bcmerror) { DHD_ERROR(("%s: error %d on reading %d membytes at 0x%08x\n", __FUNCTION__, bcmerror, sizeof(dlarray) - offset, offset)); goto err; } } if (memcmp(dlarray, ularray, sizeof(dlarray))) { DHD_ERROR(("%s: Downloaded image is corrupted (%s, %s, %s).\n", __FUNCTION__, dlimagename, dlimagever, dlimagedate)); goto err; } else DHD_ERROR(("%s: Download, Upload and compare succeeded (%s, %s, %s).\n", __FUNCTION__, dlimagename, dlimagever, dlimagedate)); } #endif /* DHD_DEBUG */ err: if (ularray) MFREE(bus->dhd->osh, ularray, bus->ramsize); return bcmerror; } #endif /* BCMEMBEDIMAGE */ static int dhdsdio_download_code_file(struct dhd_bus *bus, char *pfw_path) { int bcmerror = -1; int offset = 0; int len; void *image = NULL; uint8 *memblock = NULL, *memptr; DHD_INFO(("%s: download firmware %s\n", __FUNCTION__, pfw_path)); image = dhd_os_open_image(pfw_path); if (image == NULL) goto err; memptr = memblock = MALLOC(bus->dhd->osh, MEMBLOCK + DHD_SDALIGN); if (memblock == NULL) { DHD_ERROR(("%s: Failed to allocate memory %d bytes\n", __FUNCTION__, MEMBLOCK)); goto err; } if ((uint32)(uintptr)memblock % DHD_SDALIGN) memptr += (DHD_SDALIGN - ((uint32)(uintptr)memblock % DHD_SDALIGN)); /* Download image */ while ((len = dhd_os_get_image_block((char*)memptr, MEMBLOCK, image))) { if (len < 0) { DHD_ERROR(("%s: dhd_os_get_image_block failed (%d)\n", __FUNCTION__, len)); bcmerror = BCME_ERROR; goto err; } /* check if CR4 */ if (si_setcore(bus->sih, ARMCR4_CORE_ID, 0)) { /* if address is 0, store the reset instruction to be written in 0 */ if (offset == 0) { bus->resetinstr = *(((uint32*)memptr)); /* Add start of RAM address to the address given by user */ offset += bus->dongle_ram_base; } } bcmerror = dhdsdio_membytes(bus, TRUE, offset, memptr, len); if (bcmerror) { DHD_ERROR(("%s: error %d on writing %d membytes at 0x%08x\n", __FUNCTION__, bcmerror, MEMBLOCK, offset)); goto err; } offset += MEMBLOCK; } err: if (memblock) MFREE(bus->dhd->osh, memblock, MEMBLOCK + DHD_SDALIGN); if (image) dhd_os_close_image(image); return bcmerror; } /* EXAMPLE: nvram_array nvram_arry format: name=value Use carriage return at the end of each assignment, and an empty string with carriage return at the end of array. For example: unsigned char nvram_array[] = {"name1=value1\n", "name2=value2\n", "\n"}; Hex values start with 0x, and mac addr format: xx:xx:xx:xx:xx:xx. Search "EXAMPLE: nvram_array" to see how the array is activated. */ void dhd_bus_set_nvram_params(struct dhd_bus * bus, const char *nvram_params) { bus->nvram_params = nvram_params; } static int dhdsdio_download_nvram(struct dhd_bus *bus) { int bcmerror = -1; uint len; void * image = NULL; char * memblock = NULL; char *bufp; char *pnv_path; bool nvram_file_exists; pnv_path = bus->nv_path; nvram_file_exists = ((pnv_path != NULL) && (pnv_path[0] != '\0')); if (!nvram_file_exists && (bus->nvram_params == NULL)) return (0); if (nvram_file_exists) { image = dhd_os_open_image(pnv_path); if (image == NULL) goto err; } memblock = MALLOC(bus->dhd->osh, MAX_NVRAMBUF_SIZE); if (memblock == NULL) { DHD_ERROR(("%s: Failed to allocate memory %d bytes\n", __FUNCTION__, MAX_NVRAMBUF_SIZE)); goto err; } /* Download variables */ if (nvram_file_exists) { len = dhd_os_get_image_block(memblock, MAX_NVRAMBUF_SIZE, image); } else { len = strlen(bus->nvram_params); ASSERT(len <= MAX_NVRAMBUF_SIZE); memcpy(memblock, bus->nvram_params, len); } if (len > 0 && len < MAX_NVRAMBUF_SIZE) { bufp = (char *)memblock; bufp[len] = 0; len = process_nvram_vars(bufp, len); if (len % 4) { len += 4 - (len % 4); } bufp += len; *bufp++ = 0; if (len) bcmerror = dhdsdio_downloadvars(bus, memblock, len + 1); if (bcmerror) { DHD_ERROR(("%s: error downloading vars: %d\n", __FUNCTION__, bcmerror)); } } else { DHD_ERROR(("%s: error reading nvram file: %d\n", __FUNCTION__, len)); bcmerror = BCME_SDIO_ERROR; } err: if (memblock) MFREE(bus->dhd->osh, memblock, MAX_NVRAMBUF_SIZE); if (image) dhd_os_close_image(image); return bcmerror; } static int _dhdsdio_download_firmware(struct dhd_bus *bus) { int bcmerror = -1; bool embed = FALSE; /* download embedded firmware */ bool dlok = FALSE; /* download firmware succeeded */ /* Out immediately if no image to download */ if ((bus->fw_path == NULL) || (bus->fw_path[0] == '\0')) { #ifdef BCMEMBEDIMAGE embed = TRUE; #else return 0; #endif } /* Keep arm in reset */ if (dhdsdio_download_state(bus, TRUE)) { DHD_ERROR(("%s: error placing ARM core in reset\n", __FUNCTION__)); goto err; } /* External image takes precedence if specified */ if ((bus->fw_path != NULL) && (bus->fw_path[0] != '\0')) { if (dhdsdio_download_code_file(bus, bus->fw_path)) { DHD_ERROR(("%s: dongle image file download failed\n", __FUNCTION__)); #ifdef BCMEMBEDIMAGE embed = TRUE; #else goto err; #endif } else { embed = FALSE; dlok = TRUE; } } #ifdef BCMEMBEDIMAGE if (embed) { if (dhdsdio_download_code_array(bus)) { DHD_ERROR(("%s: dongle image array download failed\n", __FUNCTION__)); goto err; } else { dlok = TRUE; } } #else BCM_REFERENCE(embed); #endif if (!dlok) { DHD_ERROR(("%s: dongle image download failed\n", __FUNCTION__)); goto err; } /* EXAMPLE: nvram_array */ /* If a valid nvram_arry is specified as above, it can be passed down to dongle */ /* dhd_bus_set_nvram_params(bus, (char *)&nvram_array); */ /* External nvram takes precedence if specified */ if (dhdsdio_download_nvram(bus)) { DHD_ERROR(("%s: dongle nvram file download failed\n", __FUNCTION__)); goto err; } /* Take arm out of reset */ if (dhdsdio_download_state(bus, FALSE)) { DHD_ERROR(("%s: error getting out of ARM core reset\n", __FUNCTION__)); goto err; } bcmerror = 0; err: return bcmerror; } static int dhd_bcmsdh_recv_buf(dhd_bus_t *bus, uint32 addr, uint fn, uint flags, uint8 *buf, uint nbytes, void *pkt, bcmsdh_cmplt_fn_t complete, void *handle) { int status; if (!KSO_ENAB(bus)) { DHD_ERROR(("%s: Device asleep\n", __FUNCTION__)); return BCME_NODEVICE; } status = bcmsdh_recv_buf(bus->sdh, addr, fn, flags, buf, nbytes, pkt, complete, handle); return status; } static int dhd_bcmsdh_send_buf(dhd_bus_t *bus, uint32 addr, uint fn, uint flags, uint8 *buf, uint nbytes, void *pkt, bcmsdh_cmplt_fn_t complete, void *handle) { if (!KSO_ENAB(bus)) { DHD_ERROR(("%s: Device asleep\n", __FUNCTION__)); return BCME_NODEVICE; } return (bcmsdh_send_buf(bus->sdh, addr, fn, flags, buf, nbytes, pkt, complete, handle)); } #ifdef BCMSDIOH_TXGLOM static void dhd_bcmsdh_glom_post(dhd_bus_t *bus, uint8 *frame, void *pkt, uint len) { bcmsdh_glom_post(bus->sdh, frame, pkt, len); } static void dhd_bcmsdh_glom_clear(dhd_bus_t *bus) { bcmsdh_glom_clear(bus->sdh); } #endif uint dhd_bus_chip(struct dhd_bus *bus) { ASSERT(bus->sih != NULL); return bus->sih->chip; } void * dhd_bus_pub(struct dhd_bus *bus) { return bus->dhd; } void * dhd_bus_txq(struct dhd_bus *bus) { return &bus->txq; } uint dhd_bus_hdrlen(struct dhd_bus *bus) { return SDPCM_HDRLEN; } int dhd_bus_devreset(dhd_pub_t *dhdp, uint8 flag) { int bcmerror = 0; dhd_bus_t *bus; bus = dhdp->bus; if (flag == TRUE) { if (!bus->dhd->dongle_reset) { dhd_os_sdlock(dhdp); dhd_os_wd_timer(dhdp, 0); #if !defined(IGNORE_ETH0_DOWN) /* Force flow control as protection when stop come before ifconfig_down */ dhd_txflowcontrol(bus->dhd, ALL_INTERFACES, ON); #endif /* !defined(IGNORE_ETH0_DOWN) */ /* Expect app to have torn down any connection before calling */ /* Stop the bus, disable F2 */ dhd_bus_stop(bus, FALSE); #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) /* Clean up any pending IRQ */ bcmsdh_set_irq(FALSE); #endif /* defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) */ /* Clean tx/rx buffer pointers, detach from the dongle */ dhdsdio_release_dongle(bus, bus->dhd->osh, TRUE, TRUE); bus->dhd->dongle_reset = TRUE; bus->dhd->up = FALSE; #ifdef BCMSDIOH_TXGLOM dhd_txglom_enable(dhdp, FALSE); #endif dhd_os_sdunlock(dhdp); DHD_TRACE(("%s: WLAN OFF DONE\n", __FUNCTION__)); /* App can now remove power from device */ } else bcmerror = BCME_SDIO_ERROR; } else { /* App must have restored power to device before calling */ DHD_TRACE(("\n\n%s: == WLAN ON ==\n", __FUNCTION__)); if (bus->dhd->dongle_reset) { /* Turn on WLAN */ #ifdef DHDTHREAD dhd_os_sdlock(dhdp); #endif /* DHDTHREAD */ /* Reset SD client */ bcmsdh_reset(bus->sdh); /* Attempt to re-attach & download */ if (dhdsdio_probe_attach(bus, bus->dhd->osh, bus->sdh, (uint32 *)SI_ENUM_BASE, bus->cl_devid)) { /* Attempt to download binary to the dongle */ if (dhdsdio_probe_init(bus, bus->dhd->osh, bus->sdh) && dhdsdio_download_firmware(bus, bus->dhd->osh, bus->sdh)) { /* Re-init bus, enable F2 transfer */ bcmerror = dhd_bus_init((dhd_pub_t *) bus->dhd, FALSE); if (bcmerror == BCME_OK) { #if defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) bcmsdh_set_irq(TRUE); #ifndef BCMSPI_ANDROID dhd_enable_oob_intr(bus, TRUE); #endif /* !BCMSPI_ANDROID */ #endif /* defined(OOB_INTR_ONLY) || defined(BCMSPI_ANDROID) */ bus->dhd->dongle_reset = FALSE; bus->dhd->up = TRUE; #if !defined(IGNORE_ETH0_DOWN) /* Restore flow control */ dhd_txflowcontrol(bus->dhd, ALL_INTERFACES, OFF); #endif dhd_os_wd_timer(dhdp, dhd_watchdog_ms); #ifdef BCMSDIOH_TXGLOM if ((dhdp->busstate == DHD_BUS_DATA) && bcmsdh_glom_enabled()) { dhd_txglom_enable(dhdp, TRUE); } #endif /* BCMSDIOH_TXGLOM */ DHD_TRACE(("%s: WLAN ON DONE\n", __FUNCTION__)); } else { dhd_bus_stop(bus, FALSE); dhdsdio_release_dongle(bus, bus->dhd->osh, TRUE, FALSE); } } else bcmerror = BCME_SDIO_ERROR; } else bcmerror = BCME_SDIO_ERROR; #ifdef DHDTHREAD dhd_os_sdunlock(dhdp); #endif /* DHDTHREAD */ } else { bcmerror = BCME_SDIO_ERROR; DHD_INFO(("%s called when dongle is not in reset\n", __FUNCTION__)); DHD_INFO(("Will call dhd_bus_start instead\n")); sdioh_start(NULL, 1); if ((bcmerror = dhd_bus_start(dhdp)) != 0) DHD_ERROR(("%s: dhd_bus_start fail with %d\n", __FUNCTION__, bcmerror)); } } return bcmerror; } /* Get Chip ID version */ uint dhd_bus_chip_id(dhd_pub_t *dhdp) { dhd_bus_t *bus = dhdp->bus; return bus->sih->chip; } int dhd_bus_membytes(dhd_pub_t *dhdp, bool set, uint32 address, uint8 *data, uint size) { dhd_bus_t *bus; bus = dhdp->bus; return dhdsdio_membytes(bus, set, address, data, size); } #if defined(CUSTOMER_HW4) && defined(SUPPORT_MULTIPLE_REVISION) static int concate_revision_bcm4334(dhd_bus_t *bus, char *path, int path_len) { #define REV_ID_ADDR 0x1E008F90 #define BCM4334_B1_UNIQUE 0x30312E36 uint chipver; uint32 unique_id; uint8 data[4]; char chipver_tag[4] = "_b?"; DHD_TRACE(("%s: BCM4334 Multiple Revision Check\n", __FUNCTION__)); if (bus->sih->chip != BCM4334_CHIP_ID) { DHD_ERROR(("%s:Chip is not BCM4334\n", __FUNCTION__)); return -1; } chipver = bus->sih->chiprev; if (chipver == 0x2) { dhdsdio_membytes(bus, FALSE, REV_ID_ADDR, data, 4); unique_id = load32_ua(data); if (unique_id == BCM4334_B1_UNIQUE) chipver = 0x01; } DHD_ERROR(("CHIP VER = [0x%x]\n", chipver)); if (chipver == 1) { DHD_ERROR(("----- CHIP bcm4334_B0 -----\n")); strcpy(chipver_tag, "_b0"); } else if (chipver == 2) { DHD_ERROR(("----- CHIP bcm4334_B1 -----\n")); strcpy(chipver_tag, "_b1"); } else if (chipver == 3) { DHD_ERROR(("----- CHIP bcm4334_B2 -----\n")); strcpy(chipver_tag, "_b2"); } else { DHD_ERROR(("----- Invalid chip version -----\n")); return -1; } strcat(path, chipver_tag); #undef REV_ID_ADDR #undef BCM4334_B1_UNIQUE return 0; } static int concate_revision_bcm4335 (dhd_bus_t *bus, char *fw_path, int fw_path_len, char *nv_path, int nv_path_len) { uint chipver; char chipver_tag[4] = {0, }; DHD_TRACE(("%s: BCM4335 Multiple Revision Check\n", __FUNCTION__)); if (bus->sih->chip != BCM4335_CHIP_ID) { DHD_ERROR(("%s:Chip is not BCM4335\n", __FUNCTION__)); return -1; } chipver = bus->sih->chiprev; DHD_ERROR(("CHIP VER = [0x%x]\n", chipver)); if (chipver == 0x0) { DHD_ERROR(("----- CHIP bcm4335_A0 -----\n")); strcpy(chipver_tag, "_a0"); } else if (chipver == 0x1) { DHD_ERROR(("----- CHIP bcm4335_B0 -----\n")); } strcat(fw_path, chipver_tag); strcat(nv_path, chipver_tag); return 0; } int concate_revision(dhd_bus_t *bus, char *fw_path, int fw_path_len, char *nv_path, int nv_path_len) { if (!bus || !bus->sih) { DHD_ERROR(("%s:Bus is Invalid\n", __FUNCTION__)); return -1; } switch (bus->sih->chip) { case BCM4334_CHIP_ID: return concate_revision_bcm4334(bus, fw_path, fw_path_len); case BCM4335_CHIP_ID: return concate_revision_bcm4335(bus, fw_path, fw_path_len, nv_path, nv_path_len); } DHD_ERROR(("REVISION SPECIFIC feature is not required\n")); return 0; } #endif /* CUSTOMER_HW4 && SUPPORT_MULTIPLE_REVISION */
gpl-2.0
ericbarns/WP-e-Commerce
wpsc-includes/currency.helpers.php
1953
<?php function _wpsc_get_exchange_rate( $from, $to ) { if ( $from == $to ) { return 1; } $key = "wpsc_exchange_{$from}_{$to}"; if ( $rate = get_transient( $key ) ) { return (float) $rate; } $url = add_query_arg( array( 'a' => '1', 'from' => $from, 'to' => $to ), 'http://www.google.com/finance/converter' ); $url = apply_filters( '_wpsc_get_exchange_rate_service_endpoint', $url, $from, $to ); $response = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 10 ) ) ); if ( has_filter( '_wpsc_get_exchange_rate' ) ) { return (float) apply_filters( '_wpsc_get_exchange_rate', $response, $from, $to ); } if ( empty( $response ) ) { return $response; } else { $rate = explode( 'bld>', $response ); $rate = explode( $to, $rate[1] ); $rate = trim( $rate[0] ); set_transient( $key, $rate, DAY_IN_SECONDS ); return (float) $rate; } } function wpsc_convert_currency( $amt, $from, $to ) { if ( empty( $from ) || empty( $to ) ) { return $amt; } $rate = _wpsc_get_exchange_rate( $from, $to ); if ( is_wp_error( $rate ) ) { return $rate; } return $rate * $amt; } function wpsc_string_to_float( $string ) { global $wp_locale; $decimal_separator = get_option( 'wpsc_decimal_separator', $wp_locale->number_format['decimal_point'] ); $string = preg_replace( '/[^0-9\\' . $decimal_separator . ']/', '', $string ); $string = str_replace( $decimal_separator, '.', $string ); return (float) $string; } function wpsc_format_number( $number, $decimals = 2 ) { global $wp_locale; $decimal_separator = get_option( 'wpsc_decimal_separator', $wp_locale->number_format['decimal_point'] ); $thousands_separator = get_option( 'wpsc_thousands_separator', $wp_locale->number_format['thousands_sep'] ); $formatted = number_format( (float) $number, $decimals, $decimal_separator, $thousands_separator ); return $formatted; }
gpl-2.0
deetail/kimchi4u
client/collections/countries.js
128
import { Mongo } from "meteor/mongo"; /** * Client side collections */ export const Countries = new Mongo.Collection(null);
gpl-3.0
coderb0t/CouchPotatoServer
couchpotato/core/plugins/release/main.py
20734
from inspect import ismethod, isfunction import os import time import traceback from CodernityDB.database import RecordDeleted, RecordNotFound from couchpotato import md5, get_db from couchpotato.api import addApiView from couchpotato.core.event import fireEvent, addEvent from couchpotato.core.helpers.encoding import toUnicode, sp from couchpotato.core.helpers.variable import getTitle, tryInt from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from .index import ReleaseIndex, ReleaseStatusIndex, ReleaseIDIndex, ReleaseDownloadIndex from couchpotato.environment import Env log = CPLog(__name__) class Release(Plugin): _database = { 'release': ReleaseIndex, 'release_status': ReleaseStatusIndex, 'release_identifier': ReleaseIDIndex, 'release_download': ReleaseDownloadIndex } def __init__(self): addApiView('release.manual_download', self.manualDownload, docs = { 'desc': 'Send a release manually to the downloaders', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addApiView('release.delete', self.deleteView, docs = { 'desc': 'Delete releases', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addApiView('release.ignore', self.ignore, docs = { 'desc': 'Toggle ignore, for bad or wrong releases', 'params': { 'id': {'type': 'id', 'desc': 'ID of the release object in release-table'} } }) addEvent('release.add', self.add) addEvent('release.download', self.download) addEvent('release.try_download_result', self.tryDownloadResult) addEvent('release.create_from_search', self.createFromSearch) addEvent('release.delete', self.delete) addEvent('release.clean', self.clean) addEvent('release.update_status', self.updateStatus) addEvent('release.with_status', self.withStatus) addEvent('release.for_media', self.forMedia) # Clean releases that didn't have activity in the last week addEvent('app.load', self.cleanDone, priority = 1000) fireEvent('schedule.interval', 'movie.clean_releases', self.cleanDone, hours = 12) def cleanDone(self): log.debug('Removing releases from dashboard') now = time.time() week = 604800 db = get_db() # Get (and remove) parentless releases releases = db.all('release', with_doc = False) media_exist = [] reindex = 0 for release in releases: if release.get('key') in media_exist: continue try: try: doc = db.get('id', release.get('_id')) except RecordDeleted: reindex += 1 continue db.get('id', release.get('key')) media_exist.append(release.get('key')) try: if doc.get('status') == 'ignore': doc['status'] = 'ignored' db.update(doc) except: log.error('Failed fixing mis-status tag: %s', traceback.format_exc()) except ValueError: fireEvent('database.delete_corrupted', release.get('key'), traceback_error = traceback.format_exc(0)) reindex += 1 except RecordDeleted: db.delete(doc) log.debug('Deleted orphaned release: %s', doc) reindex += 1 except: log.debug('Failed cleaning up orphaned releases: %s', traceback.format_exc()) if reindex > 0: db.reindex() del media_exist # get movies last_edit more than a week ago medias = fireEvent('media.with_status', ['done', 'active'], single = True) for media in medias: if media.get('last_edit', 0) > (now - week): continue for rel in self.forMedia(media['_id']): # Remove all available releases if rel['status'] in ['available']: self.delete(rel['_id']) # Set all snatched and downloaded releases to ignored to make sure they are ignored when re-adding the media elif rel['status'] in ['snatched', 'downloaded']: self.updateStatus(rel['_id'], status = 'ignored') if 'recent' in media.get('tags', []): fireEvent('media.untag', media.get('_id'), 'recent', single = True) def add(self, group, update_info = True, update_id = None): try: db = get_db() release_identifier = '%s.%s.%s' % (group['identifier'], group['meta_data'].get('audio', 'unknown'), group['meta_data']['quality']['identifier']) # Add movie if it doesn't exist try: media = db.get('media', 'imdb-%s' % group['identifier'], with_doc = True)['doc'] except: media = fireEvent('movie.add', params = { 'identifier': group['identifier'], 'profile_id': None, }, search_after = False, update_after = update_info, notify_after = False, status = 'done', single = True) release = None if update_id: try: release = db.get('id', update_id) release.update({ 'identifier': release_identifier, 'last_edit': int(time.time()), 'status': 'done', }) except: log.error('Failed updating existing release: %s', traceback.format_exc()) else: # Add Release if not release: release = { '_t': 'release', 'media_id': media['_id'], 'identifier': release_identifier, 'quality': group['meta_data']['quality'].get('identifier'), 'is_3d': group['meta_data']['quality'].get('is_3d', 0), 'last_edit': int(time.time()), 'status': 'done' } try: r = db.get('release_identifier', release_identifier, with_doc = True)['doc'] r['media_id'] = media['_id'] except: log.debug('Failed updating release by identifier "%s". Inserting new.', release_identifier) r = db.insert(release) # Update with ref and _id release.update({ '_id': r['_id'], '_rev': r['_rev'], }) # Empty out empty file groups release['files'] = dict((k, [toUnicode(x) for x in v]) for k, v in group['files'].items() if v) db.update(release) fireEvent('media.restatus', media['_id'], allowed_restatus = ['done'], single = True) return True except: log.error('Failed: %s', traceback.format_exc()) return False def deleteView(self, id = None, **kwargs): return { 'success': self.delete(id) } def delete(self, release_id): try: db = get_db() rel = db.get('id', release_id) db.delete(rel) return True except RecordDeleted: log.debug('Already deleted: %s', release_id) return True except: log.error('Failed: %s', traceback.format_exc()) return False def clean(self, release_id): try: db = get_db() rel = db.get('id', release_id) raw_files = rel.get('files') if len(raw_files) == 0: self.delete(rel['_id']) else: files = {} for file_type in raw_files: for release_file in raw_files.get(file_type, []): if os.path.isfile(sp(release_file)): if file_type not in files: files[file_type] = [] files[file_type].append(release_file) rel['files'] = files db.update(rel) return True except: log.error('Failed: %s', traceback.format_exc()) return False def ignore(self, id = None, **kwargs): db = get_db() try: if id: rel = db.get('id', id, with_doc = True) self.updateStatus(id, 'available' if rel['status'] in ['ignored', 'failed'] else 'ignored') return { 'success': True } except: log.error('Failed: %s', traceback.format_exc()) return { 'success': False } def manualDownload(self, id = None, **kwargs): db = get_db() try: release = db.get('id', id) item = release['info'] movie = db.get('id', release['media_id']) fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Snatching "%s"' % item['name']) # Get matching provider provider = fireEvent('provider.belongs_to', item['url'], provider = item.get('provider'), single = True) if item.get('protocol') != 'torrent_magnet': item['download'] = provider.loginDownload if provider.urls.get('login') else provider.download success = self.download(data = item, media = movie, manual = True) if success: fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Successfully snatched "%s"' % item['name']) return { 'success': success == True } except: log.error('Couldn\'t find release with id: %s: %s', (id, traceback.format_exc())) return { 'success': False } def download(self, data, media, manual = False): # Test to see if any downloaders are enabled for this type downloader_enabled = fireEvent('download.enabled', manual, data, single = True) if not downloader_enabled: log.info('Tried to download, but none of the "%s" downloaders are enabled or gave an error', data.get('protocol')) return False # Download NZB or torrent file filedata = None if data.get('download') and (ismethod(data.get('download')) or isfunction(data.get('download'))): try: filedata = data.get('download')(url = data.get('url'), nzb_id = data.get('id')) except: log.error('Tried to download, but the "%s" provider gave an error: %s', (data.get('protocol'), traceback.format_exc())) return False if filedata == 'try_next': return filedata elif not filedata: return False # Send NZB or torrent file to downloader download_result = fireEvent('download', data = data, media = media, manual = manual, filedata = filedata, single = True) if not download_result: log.info('Tried to download, but the "%s" downloader gave an error', data.get('protocol')) return False log.debug('Downloader result: %s', download_result) try: db = get_db() try: rls = db.get('release_identifier', md5(data['url']), with_doc = True)['doc'] except: log.error('No release found to store download information in') return False renamer_enabled = Env.setting('enabled', 'renamer') # Save download-id info if returned if isinstance(download_result, dict): rls['download_info'] = download_result db.update(rls) log_movie = '%s (%s) in %s' % (getTitle(media), media['info'].get('year'), rls['quality']) snatch_message = 'Snatched "%s": %s from %s' % (data.get('name'), log_movie, (data.get('provider', '') + data.get('provider_extra', ''))) log.info(snatch_message) fireEvent('%s.snatched' % data['type'], message = snatch_message, data = media) # Mark release as snatched if renamer_enabled: self.updateStatus(rls['_id'], status = 'snatched') # If renamer isn't used, mark media done if finished or release downloaded else: if media['status'] == 'active': profile = db.get('id', media['profile_id']) if fireEvent('quality.isfinish', {'identifier': rls['quality'], 'is_3d': rls.get('is_3d', False)}, profile, single = True): log.info('Renamer disabled, marking media as finished: %s', log_movie) # Mark release done self.updateStatus(rls['_id'], status = 'done') # Mark media done fireEvent('media.restatus', media['_id'], single = True) return True # Assume release downloaded self.updateStatus(rls['_id'], status = 'downloaded') except: log.error('Failed storing download status: %s', traceback.format_exc()) return False return True def tryDownloadResult(self, results, media, quality_custom): wait_for = False let_through = False filtered_results = [] minimum_seeders = tryInt(Env.setting('minimum_seeders', section = 'torrent', default = 1)) # Filter out ignored and other releases we don't want for rel in results: if rel['status'] in ['ignored', 'failed']: log.info('Ignored: %s', rel['name']) continue if rel['score'] < quality_custom.get('minimum_score'): log.info('Ignored, score "%s" to low, need at least "%s": %s', (rel['score'], quality_custom.get('minimum_score'), rel['name'])) continue if rel['size'] <= 50: log.info('Ignored, size "%sMB" to low: %s', (rel['size'], rel['name'])) continue if 'seeders' in rel and rel.get('seeders') < minimum_seeders: log.info('Ignored, not enough seeders, has %s needs %s: %s', (rel.get('seeders'), minimum_seeders, rel['name'])) continue # If a single release comes through the "wait for", let through all rel['wait_for'] = False if quality_custom.get('index') != 0 and quality_custom.get('wait_for', 0) > 0 and rel.get('age') <= quality_custom.get('wait_for', 0): rel['wait_for'] = True else: let_through = True filtered_results.append(rel) # Loop through filtered results for rel in filtered_results: # Only wait if not a single release is old enough if rel.get('wait_for') and not let_through: log.info('Ignored, waiting %s days: %s', (quality_custom.get('wait_for') - rel.get('age'), rel['name'])) wait_for = True continue downloaded = fireEvent('release.download', data = rel, media = media, single = True) if downloaded is True: return True elif downloaded != 'try_next': break return wait_for def createFromSearch(self, search_results, media, quality): try: db = get_db() found_releases = [] is_3d = False try: is_3d = quality['custom']['3d'] except: pass for rel in search_results: rel_identifier = md5(rel['url']) release = { '_t': 'release', 'identifier': rel_identifier, 'media_id': media.get('_id'), 'quality': quality.get('identifier'), 'is_3d': is_3d, 'status': rel.get('status', 'available'), 'last_edit': int(time.time()), 'info': {} } # Add downloader info if provided try: release['download_info'] = rel['download_info'] del rel['download_info'] except: pass try: rls = db.get('release_identifier', rel_identifier, with_doc = True)['doc'] except: rls = db.insert(release) rls.update(release) # Update info, but filter out functions for info in rel: try: if not isinstance(rel[info], (str, unicode, int, long, float)): continue rls['info'][info] = toUnicode(rel[info]) if isinstance(rel[info], (str, unicode)) else rel[info] except: log.debug('Couldn\'t add %s to ReleaseInfo: %s', (info, traceback.format_exc())) db.update(rls) # Update release in search_results rel['status'] = rls.get('status') if rel['status'] == 'available': found_releases.append(rel_identifier) return found_releases except: log.error('Failed: %s', traceback.format_exc()) return [] def updateStatus(self, release_id, status = None): if not status: return False try: db = get_db() rel = db.get('id', release_id) if rel and rel.get('status') != status: release_name = None if rel.get('files'): for file_type in rel.get('files', {}): if file_type == 'movie': for release_file in rel['files'][file_type]: release_name = os.path.basename(release_file) break if not release_name and rel.get('info'): release_name = rel['info'].get('name') #update status in Db log.debug('Marking release %s as %s', (release_name, status)) rel['status'] = status rel['last_edit'] = int(time.time()) db.update(rel) #Update all movie info as there is no release update function fireEvent('notify.frontend', type = 'release.update_status', data = rel) return True except: log.error('Failed: %s', traceback.format_exc()) return False def withStatus(self, status, with_doc = True): db = get_db() status = list(status if isinstance(status, (list, tuple)) else [status]) for s in status: for ms in db.get_many('release_status', s): if with_doc: try: doc = db.get('id', ms['_id']) yield doc except RecordNotFound: log.debug('Record not found, skipping: %s', ms['_id']) else: yield ms def forMedia(self, media_id): db = get_db() raw_releases = db.get_many('release', media_id) releases = [] for r in raw_releases: try: doc = db.get('id', r.get('_id')) releases.append(doc) except RecordDeleted: pass except (ValueError, EOFError): fireEvent('database.delete_corrupted', r.get('_id'), traceback_error = traceback.format_exc(0)) releases = sorted(releases, key = lambda k: k.get('info', {}).get('score', 0), reverse = True) # Sort based on preferred search method download_preference = self.conf('preferred_method', section = 'searcher') if download_preference != 'both': releases = sorted(releases, key = lambda k: k.get('info', {}).get('protocol', '')[:3], reverse = (download_preference == 'torrent')) return releases or []
gpl-3.0
hartzell/terraform
vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_cloudwatch_event_target.go
11014
package aws import ( "fmt" "log" "math" "regexp" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" events "github.com/aws/aws-sdk-go/service/cloudwatchevents" "github.com/hashicorp/terraform/helper/validation" ) func resourceAwsCloudWatchEventTarget() *schema.Resource { return &schema.Resource{ Create: resourceAwsCloudWatchEventTargetCreate, Read: resourceAwsCloudWatchEventTargetRead, Update: resourceAwsCloudWatchEventTargetUpdate, Delete: resourceAwsCloudWatchEventTargetDelete, Schema: map[string]*schema.Schema{ "rule": { Type: schema.TypeString, Required: true, ForceNew: true, ValidateFunc: validateCloudWatchEventRuleName, }, "target_id": { Type: schema.TypeString, Optional: true, Computed: true, ForceNew: true, ValidateFunc: validateCloudWatchEventTargetId, }, "arn": { Type: schema.TypeString, Required: true, }, "input": { Type: schema.TypeString, Optional: true, ConflictsWith: []string{"input_path"}, // We could be normalizing the JSON here, // but for built-in targets input may not be JSON }, "input_path": { Type: schema.TypeString, Optional: true, ConflictsWith: []string{"input"}, }, "role_arn": { Type: schema.TypeString, Optional: true, }, "run_command_targets": { Type: schema.TypeList, Optional: true, MaxItems: 5, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "key": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 128), }, "values": { Type: schema.TypeList, Required: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, }, }, "ecs_target": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "task_count": { Type: schema.TypeInt, Optional: true, ValidateFunc: validation.IntBetween(1, math.MaxInt32), }, "task_definition_arn": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 1600), }, }, }, }, "input_transformer": { Type: schema.TypeList, Optional: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "input_paths": { Type: schema.TypeMap, Optional: true, }, "input_template": { Type: schema.TypeString, Required: true, ValidateFunc: validation.StringLenBetween(1, 8192), }, }, }, }, }, } } func resourceAwsCloudWatchEventTargetCreate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn rule := d.Get("rule").(string) var targetId string if v, ok := d.GetOk("target_id"); ok { targetId = v.(string) } else { targetId = resource.UniqueId() d.Set("target_id", targetId) } input := buildPutTargetInputStruct(d) log.Printf("[DEBUG] Creating CloudWatch Event Target: %s", input) out, err := conn.PutTargets(input) if err != nil { return fmt.Errorf("Creating CloudWatch Event Target failed: %s", err) } if len(out.FailedEntries) > 0 { return fmt.Errorf("Creating CloudWatch Event Target failed: %s", out.FailedEntries) } id := rule + "-" + targetId d.SetId(id) log.Printf("[INFO] CloudWatch Event Target %q created", d.Id()) return resourceAwsCloudWatchEventTargetRead(d, meta) } func resourceAwsCloudWatchEventTargetRead(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn t, err := findEventTargetById( d.Get("target_id").(string), d.Get("rule").(string), nil, conn) if err != nil { if regexp.MustCompile(" not found$").MatchString(err.Error()) { log.Printf("[WARN] Removing CloudWatch Event Target %q because it's gone.", d.Id()) d.SetId("") return nil } if awsErr, ok := err.(awserr.Error); ok { // This should never happen, but it's useful // for recovering from https://github.com/hashicorp/terraform/issues/5389 if awsErr.Code() == "ValidationException" { log.Printf("[WARN] Removing CloudWatch Event Target %q because it never existed.", d.Id()) d.SetId("") return nil } if awsErr.Code() == "ResourceNotFoundException" { log.Printf("[WARN] CloudWatch Event Target (%q) not found. Removing it from state.", d.Id()) d.SetId("") return nil } } return err } log.Printf("[DEBUG] Found Event Target: %s", t) d.Set("arn", t.Arn) d.Set("target_id", t.Id) d.Set("input", t.Input) d.Set("input_path", t.InputPath) d.Set("role_arn", t.RoleArn) if t.RunCommandParameters != nil { if err := d.Set("run_command_targets", flattenAwsCloudWatchEventTargetRunParameters(t.RunCommandParameters)); err != nil { return fmt.Errorf("[DEBUG] Error setting run_command_targets error: %#v", err) } } if t.EcsParameters != nil { if err := d.Set("ecs_target", flattenAwsCloudWatchEventTargetEcsParameters(t.EcsParameters)); err != nil { return fmt.Errorf("[DEBUG] Error setting ecs_target error: %#v", err) } } if t.InputTransformer != nil { if err := d.Set("input_transformer", flattenAwsCloudWatchInputTransformer(t.InputTransformer)); err != nil { return fmt.Errorf("[DEBUG] Error setting input_transformer error: %#v", err) } } return nil } func findEventTargetById(id, rule string, nextToken *string, conn *events.CloudWatchEvents) (*events.Target, error) { input := events.ListTargetsByRuleInput{ Rule: aws.String(rule), NextToken: nextToken, Limit: aws.Int64(100), // Set limit to allowed maximum to prevent API throttling } log.Printf("[DEBUG] Reading CloudWatch Event Target: %s", input) out, err := conn.ListTargetsByRule(&input) if err != nil { return nil, err } for _, t := range out.Targets { if *t.Id == id { return t, nil } } if out.NextToken != nil { return findEventTargetById(id, rule, nextToken, conn) } return nil, fmt.Errorf("CloudWatch Event Target %q (%q) not found", id, rule) } func resourceAwsCloudWatchEventTargetUpdate(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn input := buildPutTargetInputStruct(d) log.Printf("[DEBUG] Updating CloudWatch Event Target: %s", input) _, err := conn.PutTargets(input) if err != nil { return fmt.Errorf("Updating CloudWatch Event Target failed: %s", err) } return resourceAwsCloudWatchEventTargetRead(d, meta) } func resourceAwsCloudWatchEventTargetDelete(d *schema.ResourceData, meta interface{}) error { conn := meta.(*AWSClient).cloudwatcheventsconn input := events.RemoveTargetsInput{ Ids: []*string{aws.String(d.Get("target_id").(string))}, Rule: aws.String(d.Get("rule").(string)), } log.Printf("[INFO] Deleting CloudWatch Event Target: %s", input) _, err := conn.RemoveTargets(&input) if err != nil { return fmt.Errorf("Error deleting CloudWatch Event Target: %s", err) } log.Println("[INFO] CloudWatch Event Target deleted") d.SetId("") return nil } func buildPutTargetInputStruct(d *schema.ResourceData) *events.PutTargetsInput { e := &events.Target{ Arn: aws.String(d.Get("arn").(string)), Id: aws.String(d.Get("target_id").(string)), } if v, ok := d.GetOk("input"); ok { e.Input = aws.String(v.(string)) } if v, ok := d.GetOk("input_path"); ok { e.InputPath = aws.String(v.(string)) } if v, ok := d.GetOk("role_arn"); ok { e.RoleArn = aws.String(v.(string)) } if v, ok := d.GetOk("run_command_targets"); ok { e.RunCommandParameters = expandAwsCloudWatchEventTargetRunParameters(v.([]interface{})) } if v, ok := d.GetOk("ecs_target"); ok { e.EcsParameters = expandAwsCloudWatchEventTargetEcsParameters(v.([]interface{})) } if v, ok := d.GetOk("input_transformer"); ok { e.InputTransformer = expandAwsCloudWatchEventTransformerParameters(v.([]interface{})) } input := events.PutTargetsInput{ Rule: aws.String(d.Get("rule").(string)), Targets: []*events.Target{e}, } return &input } func expandAwsCloudWatchEventTargetRunParameters(config []interface{}) *events.RunCommandParameters { commands := make([]*events.RunCommandTarget, 0) for _, c := range config { param := c.(map[string]interface{}) command := &events.RunCommandTarget{ Key: aws.String(param["key"].(string)), Values: expandStringList(param["values"].([]interface{})), } commands = append(commands, command) } command := &events.RunCommandParameters{ RunCommandTargets: commands, } return command } func expandAwsCloudWatchEventTargetEcsParameters(config []interface{}) *events.EcsParameters { ecsParameters := &events.EcsParameters{} for _, c := range config { param := c.(map[string]interface{}) ecsParameters.TaskCount = aws.Int64(int64(param["task_count"].(int))) ecsParameters.TaskDefinitionArn = aws.String(param["task_definition_arn"].(string)) } return ecsParameters } func expandAwsCloudWatchEventTransformerParameters(config []interface{}) *events.InputTransformer { transformerParameters := &events.InputTransformer{} inputPathsMaps := map[string]*string{} for _, c := range config { param := c.(map[string]interface{}) inputPaths := param["input_paths"].(map[string]interface{}) for k, v := range inputPaths { inputPathsMaps[k] = aws.String(v.(string)) } transformerParameters.InputTemplate = aws.String(param["input_template"].(string)) } transformerParameters.InputPathsMap = inputPathsMaps return transformerParameters } func flattenAwsCloudWatchEventTargetRunParameters(runCommand *events.RunCommandParameters) []map[string]interface{} { result := make([]map[string]interface{}, 0) for _, x := range runCommand.RunCommandTargets { config := make(map[string]interface{}) config["key"] = *x.Key config["values"] = flattenStringList(x.Values) result = append(result, config) } return result } func flattenAwsCloudWatchEventTargetEcsParameters(ecsParameters *events.EcsParameters) []map[string]interface{} { config := make(map[string]interface{}) config["task_count"] = *ecsParameters.TaskCount config["task_definition_arn"] = *ecsParameters.TaskDefinitionArn result := []map[string]interface{}{config} return result } func flattenAwsCloudWatchInputTransformer(inputTransformer *events.InputTransformer) []map[string]interface{} { config := make(map[string]interface{}) inputPathsMap := make(map[string]string) for k, v := range inputTransformer.InputPathsMap { inputPathsMap[k] = *v } config["input_template"] = *inputTransformer.InputTemplate config["input_paths"] = inputPathsMap result := []map[string]interface{}{config} return result }
mpl-2.0
liuqr/edx-xiaodun
common/djangoapps/pipeline_mako/__init__.py
2354
from edxmako.shortcuts import render_to_string from pipeline.conf import settings from pipeline.packager import Packager from pipeline.utils import guess_type from static_replace import try_staticfiles_lookup def compressed_css(package_name): package = settings.PIPELINE_CSS.get(package_name, {}) if package: package = {package_name: package} packager = Packager(css_packages=package, js_packages={}) package = packager.package_for('css', package_name) if settings.PIPELINE: return render_css(package, package.output_filename) else: paths = packager.compile(package.paths) return render_individual_css(package, paths) def render_css(package, path): template_name = package.template_name or "mako/css.html" context = package.extra_context url = try_staticfiles_lookup(path) context.update({ 'type': guess_type(path, 'text/css'), 'url': url, }) return render_to_string(template_name, context) def render_individual_css(package, paths): tags = [render_css(package, path) for path in paths] return '\n'.join(tags) def compressed_js(package_name): package = settings.PIPELINE_JS.get(package_name, {}) if package: package = {package_name: package} packager = Packager(css_packages={}, js_packages=package) package = packager.package_for('js', package_name) if settings.PIPELINE: return render_js(package, package.output_filename) else: paths = packager.compile(package.paths) templates = packager.pack_templates(package) return render_individual_js(package, paths, templates) def render_js(package, path): template_name = package.template_name or "mako/js.html" context = package.extra_context context.update({ 'type': guess_type(path, 'text/javascript'), 'url': try_staticfiles_lookup(path) }) return render_to_string(template_name, context) def render_inline_js(package, js): context = package.extra_context context.update({ 'source': js }) return render_to_string("mako/inline_js.html", context) def render_individual_js(package, paths, templates=None): tags = [render_js(package, js) for js in paths] if templates: tags.append(render_inline_js(package, templates)) return '\n'.join(tags)
agpl-3.0
backenklee/RIOT
sys/net/gnrc/network_layer/ipv6/gnrc_ipv6.c
33189
/* * Copyright (C) 2015 Martine Lenders <mlenders@inf.fu-berlin.de> * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @{ * * @file */ #include <assert.h> #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include "byteorder.h" #include "cpu_conf.h" #include "kernel_types.h" #include "net/gnrc.h" #include "net/gnrc/icmpv6.h" #include "net/gnrc/ndp.h" #include "net/gnrc/sixlowpan/ctx.h" #include "net/gnrc/sixlowpan/nd.h" #include "net/gnrc/sixlowpan/nd/router.h" #include "net/protnum.h" #include "thread.h" #include "utlist.h" #include "net/gnrc/ipv6/nc.h" #include "net/gnrc/ipv6/netif.h" #include "net/gnrc/ipv6/whitelist.h" #include "net/gnrc/ipv6/blacklist.h" #include "net/gnrc/ipv6.h" #define ENABLE_DEBUG (0) #include "debug.h" #define _MAX_L2_ADDR_LEN (8U) #if ENABLE_DEBUG static char _stack[GNRC_IPV6_STACK_SIZE + THREAD_EXTRA_STACKSIZE_PRINTF]; #else static char _stack[GNRC_IPV6_STACK_SIZE]; #endif #ifdef MODULE_FIB #include "net/fib.h" #include "net/fib/table.h" /** * @brief buffer to store the entries in the IPv6 forwarding table */ static fib_entry_t _fib_entries[GNRC_IPV6_FIB_TABLE_SIZE]; /** * @brief the IPv6 forwarding table */ fib_table_t gnrc_ipv6_fib_table; #endif #if ENABLE_DEBUG static char addr_str[IPV6_ADDR_MAX_STR_LEN]; #endif kernel_pid_t gnrc_ipv6_pid = KERNEL_PID_UNDEF; /* handles GNRC_NETAPI_MSG_TYPE_RCV commands */ static void _receive(gnrc_pktsnip_t *pkt); /* Sends packet over the appropriate interface(s). * prep_hdr: prepare header for sending (call to _fill_ipv6_hdr()), otherwise * assume it is already prepared */ static void _send(gnrc_pktsnip_t *pkt, bool prep_hdr); /* Main event loop for IPv6 */ static void *_event_loop(void *args); /* Handles encapsulated IPv6 packets: http://tools.ietf.org/html/rfc2473 */ static void _decapsulate(gnrc_pktsnip_t *pkt); kernel_pid_t gnrc_ipv6_init(void) { if (gnrc_ipv6_pid == KERNEL_PID_UNDEF) { gnrc_ipv6_pid = thread_create(_stack, sizeof(_stack), GNRC_IPV6_PRIO, THREAD_CREATE_STACKTEST, _event_loop, NULL, "ipv6"); } #ifdef MODULE_FIB gnrc_ipv6_fib_table.data.entries = _fib_entries; gnrc_ipv6_fib_table.table_type = FIB_TABLE_TYPE_SH; gnrc_ipv6_fib_table.size = GNRC_IPV6_FIB_TABLE_SIZE; fib_init(&gnrc_ipv6_fib_table); #endif return gnrc_ipv6_pid; } static void _dispatch_next_header(gnrc_pktsnip_t *current, gnrc_pktsnip_t *pkt, uint8_t nh, bool interested); /* * current pkt * | | * v v * IPv6 <- IPv6_EXT <- IPv6_EXT <- UNDEF */ void gnrc_ipv6_demux(kernel_pid_t iface, gnrc_pktsnip_t *current, gnrc_pktsnip_t *pkt, uint8_t nh) { bool interested = false; current->type = gnrc_nettype_from_protnum(nh); switch (nh) { #ifdef MODULE_GNRC_ICMPV6 case PROTNUM_ICMPV6: assert(current == pkt); interested = true; break; #endif #ifdef MODULE_GNRC_IPV6_EXT case PROTNUM_IPV6_EXT_HOPOPT: case PROTNUM_IPV6_EXT_DST: case PROTNUM_IPV6_EXT_RH: case PROTNUM_IPV6_EXT_FRAG: case PROTNUM_IPV6_EXT_AH: case PROTNUM_IPV6_EXT_ESP: case PROTNUM_IPV6_EXT_MOB: interested = true; break; #endif case PROTNUM_IPV6: assert(current == pkt); interested = true; break; default: (void)iface; #ifdef MODULE_GNRC_SIXLOWPAN_IPHC_NHC /* second statement is true for small 6LoWPAN NHC decompressed frames * since in this case it looks like * * * GNRC_NETTYPE_UNDEF <- pkt * v * * GNRC_NETTYPE_UDP <- current * v * * GNRC_NETTYPE_EXT * v * * GNRC_NETTYPE_IPV6 */ assert((current == pkt) || (current == pkt->next)); #else assert(current == pkt); #endif break; } _dispatch_next_header(current, pkt, nh, interested); if (!interested) { return; } switch (nh) { #ifdef MODULE_GNRC_ICMPV6 case PROTNUM_ICMPV6: DEBUG("ipv6: handle ICMPv6 packet (nh = %u)\n", nh); gnrc_icmpv6_demux(iface, pkt); return; #endif #ifdef MODULE_GNRC_IPV6_EXT case PROTNUM_IPV6_EXT_HOPOPT: case PROTNUM_IPV6_EXT_DST: case PROTNUM_IPV6_EXT_RH: case PROTNUM_IPV6_EXT_FRAG: case PROTNUM_IPV6_EXT_AH: case PROTNUM_IPV6_EXT_ESP: case PROTNUM_IPV6_EXT_MOB: DEBUG("ipv6: handle extension header (nh = %u)\n", nh); gnrc_ipv6_ext_demux(iface, current, pkt, nh); return; #endif case PROTNUM_IPV6: DEBUG("ipv6: handle encapsulated IPv6 packet (nh = %u)\n", nh); _decapsulate(pkt); return; default: assert(false); break; } assert(false); } ipv6_hdr_t *gnrc_ipv6_get_header(gnrc_pktsnip_t *pkt) { ipv6_hdr_t *hdr = NULL; gnrc_pktsnip_t *tmp = gnrc_pktsnip_search_type(pkt, GNRC_NETTYPE_IPV6); if ((tmp) && ipv6_hdr_is(tmp->data)) { hdr = ((ipv6_hdr_t*) tmp->data); } return hdr; } /* internal functions */ static void _dispatch_next_header(gnrc_pktsnip_t *current, gnrc_pktsnip_t *pkt, uint8_t nh, bool interested) { #ifdef MODULE_GNRC_IPV6_EXT const bool should_dispatch_current_type = ((current->type != GNRC_NETTYPE_IPV6_EXT) || (current->next->type == GNRC_NETTYPE_IPV6)); #else const bool should_dispatch_current_type = (current->next->type == GNRC_NETTYPE_IPV6); #endif DEBUG("ipv6: forward nh = %u to other threads\n", nh); /* dispatch IPv6 extension header only once */ if (should_dispatch_current_type) { bool should_release = (gnrc_netreg_num(GNRC_NETTYPE_IPV6, nh) == 0) && (!interested); if (!should_release) { gnrc_pktbuf_hold(pkt, 1); /* don't remove from packet buffer in * next dispatch */ } if (gnrc_netapi_dispatch_receive(current->type, GNRC_NETREG_DEMUX_CTX_ALL, pkt) == 0) { gnrc_pktbuf_release(pkt); } if (should_release) { return; } } if (interested) { gnrc_pktbuf_hold(pkt, 1); /* don't remove from packet buffer in * next dispatch */ } if (gnrc_netapi_dispatch_receive(GNRC_NETTYPE_IPV6, nh, pkt) == 0) { gnrc_pktbuf_release(pkt); } } static void *_event_loop(void *args) { msg_t msg, reply, msg_q[GNRC_IPV6_MSG_QUEUE_SIZE]; gnrc_netreg_entry_t me_reg = GNRC_NETREG_ENTRY_INIT_PID(GNRC_NETREG_DEMUX_CTX_ALL, sched_active_pid); (void)args; msg_init_queue(msg_q, GNRC_IPV6_MSG_QUEUE_SIZE); /* register interest in all IPv6 packets */ gnrc_netreg_register(GNRC_NETTYPE_IPV6, &me_reg); /* preinitialize ACK */ reply.type = GNRC_NETAPI_MSG_TYPE_ACK; /* start event loop */ while (1) { DEBUG("ipv6: waiting for incoming message.\n"); msg_receive(&msg); switch (msg.type) { case GNRC_NETAPI_MSG_TYPE_RCV: DEBUG("ipv6: GNRC_NETAPI_MSG_TYPE_RCV received\n"); _receive(msg.content.ptr); break; case GNRC_NETAPI_MSG_TYPE_SND: DEBUG("ipv6: GNRC_NETAPI_MSG_TYPE_SND received\n"); _send(msg.content.ptr, true); break; case GNRC_NETAPI_MSG_TYPE_GET: case GNRC_NETAPI_MSG_TYPE_SET: DEBUG("ipv6: reply to unsupported get/set\n"); reply.content.value = -ENOTSUP; msg_reply(&msg, &reply); break; #ifdef MODULE_GNRC_NDP case GNRC_NDP_MSG_RTR_TIMEOUT: DEBUG("ipv6: Router timeout received\n"); ((gnrc_ipv6_nc_t *)msg.content.ptr)->flags &= ~GNRC_IPV6_NC_IS_ROUTER; break; /* XXX reactivate when https://github.com/RIOT-OS/RIOT/issues/5122 is * solved properly */ /* case GNRC_NDP_MSG_ADDR_TIMEOUT: */ /* DEBUG("ipv6: Router advertisement timer event received\n"); */ /* gnrc_ipv6_netif_remove_addr(KERNEL_PID_UNDEF, */ /* msg.content.ptr); */ /* break; */ case GNRC_NDP_MSG_NBR_SOL_RETRANS: DEBUG("ipv6: Neigbor solicitation retransmission timer event received\n"); gnrc_ndp_retrans_nbr_sol(msg.content.ptr); break; case GNRC_NDP_MSG_NC_STATE_TIMEOUT: DEBUG("ipv6: Neigbor cache state timeout received\n"); gnrc_ndp_state_timeout(msg.content.ptr); break; #endif #ifdef MODULE_GNRC_NDP_ROUTER case GNRC_NDP_MSG_RTR_ADV_RETRANS: DEBUG("ipv6: Router advertisement retransmission event received\n"); gnrc_ndp_router_retrans_rtr_adv(msg.content.ptr); break; case GNRC_NDP_MSG_RTR_ADV_DELAY: DEBUG("ipv6: Delayed router advertisement event received\n"); gnrc_ndp_router_send_rtr_adv(msg.content.ptr); break; #endif #ifdef MODULE_GNRC_NDP_HOST case GNRC_NDP_MSG_RTR_SOL_RETRANS: DEBUG("ipv6: Router solicitation retransmission event received\n"); gnrc_ndp_host_retrans_rtr_sol(msg.content.ptr); break; #endif #ifdef MODULE_GNRC_SIXLOWPAN_ND case GNRC_SIXLOWPAN_ND_MSG_MC_RTR_SOL: DEBUG("ipv6: Multicast router solicitation event received\n"); gnrc_sixlowpan_nd_mc_rtr_sol(msg.content.ptr); break; case GNRC_SIXLOWPAN_ND_MSG_UC_RTR_SOL: DEBUG("ipv6: Unicast router solicitation event received\n"); gnrc_sixlowpan_nd_uc_rtr_sol(msg.content.ptr); break; # ifdef MODULE_GNRC_SIXLOWPAN_CTX case GNRC_SIXLOWPAN_ND_MSG_DELETE_CTX: DEBUG("ipv6: Delete 6LoWPAN context event received\n"); gnrc_sixlowpan_ctx_remove(((((gnrc_sixlowpan_ctx_t *)msg.content.ptr)->flags_id) & GNRC_SIXLOWPAN_CTX_FLAGS_CID_MASK)); break; # endif #endif #ifdef MODULE_GNRC_SIXLOWPAN_ND_ROUTER case GNRC_SIXLOWPAN_ND_MSG_ABR_TIMEOUT: DEBUG("ipv6: border router timeout event received\n"); gnrc_sixlowpan_nd_router_abr_remove(msg.content.ptr); break; /* XXX reactivate when https://github.com/RIOT-OS/RIOT/issues/5122 is * solved properly */ /* case GNRC_SIXLOWPAN_ND_MSG_AR_TIMEOUT: */ /* DEBUG("ipv6: address registration timeout received\n"); */ /* gnrc_sixlowpan_nd_router_gc_nc(msg.content.ptr); */ /* break; */ case GNRC_NDP_MSG_RTR_ADV_SIXLOWPAN_DELAY: DEBUG("ipv6: Delayed router advertisement event received\n"); gnrc_ipv6_nc_t *nc_entry = msg.content.ptr; gnrc_ndp_internal_send_rtr_adv(nc_entry->iface, NULL, &(nc_entry->ipv6_addr), false); break; #endif default: break; } } return NULL; } static void _send_to_iface(kernel_pid_t iface, gnrc_pktsnip_t *pkt) { ((gnrc_netif_hdr_t *)pkt->data)->if_pid = iface; gnrc_ipv6_netif_t *if_entry = gnrc_ipv6_netif_get(iface); assert(if_entry != NULL); if (gnrc_pkt_len(pkt->next) > if_entry->mtu) { DEBUG("ipv6: packet too big\n"); gnrc_pktbuf_release(pkt); return; } #ifdef MODULE_NETSTATS_IPV6 if_entry->stats.tx_success++; if_entry->stats.tx_bytes += gnrc_pkt_len(pkt->next); #endif #ifdef MODULE_GNRC_SIXLOWPAN if (if_entry->flags & GNRC_IPV6_NETIF_FLAGS_SIXLOWPAN) { DEBUG("ipv6: send to 6LoWPAN instead\n"); if (!gnrc_netapi_dispatch_send(GNRC_NETTYPE_SIXLOWPAN, GNRC_NETREG_DEMUX_CTX_ALL, pkt)) { DEBUG("ipv6: no 6LoWPAN thread found\n"); gnrc_pktbuf_release(pkt); } return; } #endif if (gnrc_netapi_send(iface, pkt) < 1) { DEBUG("ipv6: unable to send packet\n"); gnrc_pktbuf_release(pkt); } } static gnrc_pktsnip_t *_create_netif_hdr(uint8_t *dst_l2addr, uint16_t dst_l2addr_len, gnrc_pktsnip_t *pkt) { gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst_l2addr, dst_l2addr_len); if (netif == NULL) { DEBUG("ipv6: error on interface header allocation, dropping packet\n"); gnrc_pktbuf_release(pkt); return NULL; } if (pkt->type == GNRC_NETTYPE_NETIF) { /* remove old netif header, since checking it for correctness would * cause to much overhead. * netif header might have been allocated by some higher layer either * to set a sending interface or some flags. Interface was already * copied using iface parameter, so we only need to copy the flags * (minus the broadcast/multicast flags) */ DEBUG("ipv6: copy old interface header flags\n"); gnrc_netif_hdr_t *netif_new = netif->data, *netif_old = pkt->data; netif_new->flags = netif_old->flags & \ ~(GNRC_NETIF_HDR_FLAGS_BROADCAST | GNRC_NETIF_HDR_FLAGS_MULTICAST); DEBUG("ipv6: removed old interface header\n"); pkt = gnrc_pktbuf_remove_snip(pkt, pkt); } /* add netif to front of the pkt list */ LL_PREPEND(pkt, netif); return pkt; } /* functions for sending */ static void _send_unicast(kernel_pid_t iface, uint8_t *dst_l2addr, uint16_t dst_l2addr_len, gnrc_pktsnip_t *pkt) { DEBUG("ipv6: add interface header to packet\n"); if ((pkt = _create_netif_hdr(dst_l2addr, dst_l2addr_len, pkt)) == NULL) { return; } DEBUG("ipv6: send unicast over interface %" PRIkernel_pid "\n", iface); /* and send to interface */ #ifdef MODULE_NETSTATS_IPV6 gnrc_ipv6_netif_get_stats(iface)->tx_unicast_count++; #endif _send_to_iface(iface, pkt); } static int _fill_ipv6_hdr(kernel_pid_t iface, gnrc_pktsnip_t *ipv6, gnrc_pktsnip_t *payload) { int res; ipv6_hdr_t *hdr = ipv6->data; hdr->len = byteorder_htons(gnrc_pkt_len(payload)); DEBUG("ipv6: set payload length to %u (network byteorder %04" PRIx16 ")\n", (unsigned) gnrc_pkt_len(payload), hdr->len.u16); /* check if e.g. extension header was not already marked */ if (hdr->nh == PROTNUM_RESERVED) { hdr->nh = gnrc_nettype_to_protnum(payload->type); /* if still reserved: mark no next header */ if (hdr->nh == PROTNUM_RESERVED) { hdr->nh = PROTNUM_IPV6_NONXT; } } DEBUG("ipv6: set next header to %u\n", hdr->nh); if (hdr->hl == 0) { if (iface == KERNEL_PID_UNDEF) { hdr->hl = GNRC_IPV6_NETIF_DEFAULT_HL; } else { hdr->hl = gnrc_ipv6_netif_get(iface)->cur_hl; } } if (ipv6_addr_is_unspecified(&hdr->src)) { if (ipv6_addr_is_loopback(&hdr->dst)) { ipv6_addr_set_loopback(&hdr->src); } else { ipv6_addr_t *src = gnrc_ipv6_netif_find_best_src_addr(iface, &hdr->dst, false); if (src != NULL) { DEBUG("ipv6: set packet source to %s\n", ipv6_addr_to_str(addr_str, src, sizeof(addr_str))); memcpy(&hdr->src, src, sizeof(ipv6_addr_t)); } /* Otherwise leave unspecified */ } } DEBUG("ipv6: calculate checksum for upper header.\n"); if ((res = gnrc_netreg_calc_csum(payload, ipv6)) < 0) { if (res != -ENOENT) { /* if there is no checksum we are okay */ DEBUG("ipv6: checksum calculation failed.\n"); return res; } } return 0; } static inline void _send_multicast_over_iface(kernel_pid_t iface, gnrc_pktsnip_t *pkt) { DEBUG("ipv6: send multicast over interface %" PRIkernel_pid "\n", iface); /* mark as multicast */ ((gnrc_netif_hdr_t *)pkt->data)->flags |= GNRC_NETIF_HDR_FLAGS_MULTICAST; #ifdef MODULE_NETSTATS_IPV6 gnrc_ipv6_netif_get_stats(iface)->tx_mcast_count++; #endif /* and send to interface */ _send_to_iface(iface, pkt); } static void _send_multicast(kernel_pid_t iface, gnrc_pktsnip_t *pkt, gnrc_pktsnip_t *ipv6, gnrc_pktsnip_t *payload, bool prep_hdr) { kernel_pid_t ifs[GNRC_NETIF_NUMOF]; size_t ifnum = 0; if (iface == KERNEL_PID_UNDEF) { /* get list of interfaces */ ifnum = gnrc_netif_get(ifs); /* throw away packet if no one is interested */ if (ifnum == 0) { DEBUG("ipv6: no interfaces registered, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } } #if GNRC_NETIF_NUMOF > 1 /* interface not given: send over all interfaces */ if (iface == KERNEL_PID_UNDEF) { /* send packet to link layer */ gnrc_pktbuf_hold(pkt, ifnum - 1); for (size_t i = 0; i < ifnum; i++) { if (prep_hdr) { /* need to get second write access (duplication) to fill IPv6 * header interface-local */ gnrc_pktsnip_t *tmp = gnrc_pktbuf_start_write(pkt); gnrc_pktsnip_t *ptr = tmp->next; ipv6 = tmp; if (ipv6 == NULL) { DEBUG("ipv6: unable to get write access to IPv6 header, " "for interface %" PRIkernel_pid "\n", ifs[i]); gnrc_pktbuf_release(pkt); return; } /* multiple interfaces => possibly different source addresses * => different checksums => duplication of payload needed */ while (ptr != payload->next) { /* duplicate everything including payload */ tmp->next = gnrc_pktbuf_start_write(ptr); if (tmp->next == NULL) { DEBUG("ipv6: unable to get write access to payload, drop it\n"); gnrc_pktbuf_release(ipv6); return; } tmp = tmp->next; ptr = ptr->next; } if (_fill_ipv6_hdr(ifs[i], ipv6, tmp) < 0) { /* error on filling up header */ gnrc_pktbuf_release(ipv6); return; } } if ((ipv6 = _create_netif_hdr(NULL, 0, ipv6)) == NULL) { return; } _send_multicast_over_iface(ifs[i], ipv6); } } else { if (prep_hdr) { if (_fill_ipv6_hdr(iface, ipv6, payload) < 0) { /* error on filling up header */ gnrc_pktbuf_release(pkt); return; } } _send_multicast_over_iface(iface, pkt); } #else /* GNRC_NETIF_NUMOF */ (void)ifnum; /* not used in this build branch */ if (iface == KERNEL_PID_UNDEF) { iface = ifs[0]; /* allocate interface header */ if ((pkt = _create_netif_hdr(NULL, 0, pkt)) == NULL) { return; } } if (prep_hdr) { if (_fill_ipv6_hdr(iface, ipv6, payload) < 0) { /* error on filling up header */ gnrc_pktbuf_release(pkt); return; } } _send_multicast_over_iface(iface, pkt); #endif /* GNRC_NETIF_NUMOF */ } static inline kernel_pid_t _next_hop_l2addr(uint8_t *l2addr, uint8_t *l2addr_len, kernel_pid_t iface, ipv6_addr_t *dst, gnrc_pktsnip_t *pkt) { kernel_pid_t found_iface; #if defined(MODULE_GNRC_SIXLOWPAN_ND) (void)pkt; found_iface = gnrc_sixlowpan_nd_next_hop_l2addr(l2addr, l2addr_len, iface, dst); if (found_iface > KERNEL_PID_UNDEF) { return found_iface; } #endif #if defined(MODULE_GNRC_NDP_NODE) found_iface = gnrc_ndp_node_next_hop_l2addr(l2addr, l2addr_len, iface, dst, pkt); #elif !defined(MODULE_GNRC_SIXLOWPAN_ND) && defined(MODULE_GNRC_IPV6_NC) (void)pkt; gnrc_ipv6_nc_t *nc = gnrc_ipv6_nc_get(iface, dst); found_iface = gnrc_ipv6_nc_get_l2_addr(l2addr, l2addr_len, nc); #elif !defined(MODULE_GNRC_SIXLOWPAN_ND) found_iface = KERNEL_PID_UNDEF; (void)l2addr; (void)l2addr_len; (void)iface; (void)dst; (void)pkt; *l2addr_len = 0; #endif return found_iface; } static void _send(gnrc_pktsnip_t *pkt, bool prep_hdr) { kernel_pid_t iface = KERNEL_PID_UNDEF; gnrc_pktsnip_t *ipv6, *payload; ipv6_addr_t *tmp; ipv6_hdr_t *hdr; /* get IPv6 snip and (if present) generic interface header */ if (pkt->type == GNRC_NETTYPE_NETIF) { /* If there is already a netif header (routing protocols and * neighbor discovery might add them to preset sending interface) */ iface = ((gnrc_netif_hdr_t *)pkt->data)->if_pid; /* seize payload as temporary variable */ ipv6 = gnrc_pktbuf_start_write(pkt); /* write protect for later removal * in _send_unicast() */ if (ipv6 == NULL) { DEBUG("ipv6: unable to get write access to netif header, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } pkt = ipv6; /* Reset pkt from temporary variable */ ipv6 = pkt->next; } else { ipv6 = pkt; } /* seize payload as temporary variable */ payload = gnrc_pktbuf_start_write(ipv6); if (payload == NULL) { DEBUG("ipv6: unable to get write access to IPv6 header, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } if (ipv6 != pkt) { /* in case packet has netif header */ pkt->next = payload;/* pkt is already write-protected so we can do that */ } else { pkt = payload; /* pkt is the IPv6 header so we just write-protected it */ } ipv6 = payload; /* Reset ipv6 from temporary variable */ hdr = ipv6->data; payload = ipv6->next; if (ipv6_addr_is_multicast(&hdr->dst)) { _send_multicast(iface, pkt, ipv6, payload, prep_hdr); } else if ((ipv6_addr_is_loopback(&hdr->dst)) || /* dst is loopback address */ ((iface == KERNEL_PID_UNDEF) && /* or dst registered to any local interface */ ((iface = gnrc_ipv6_netif_find_by_addr(&tmp, &hdr->dst)) != KERNEL_PID_UNDEF)) || ((iface != KERNEL_PID_UNDEF) && /* or dst registered to given interface */ (gnrc_ipv6_netif_find_addr(iface, &hdr->dst) != NULL))) { uint8_t *rcv_data; gnrc_pktsnip_t *ptr = ipv6, *rcv_pkt; if (prep_hdr) { if (_fill_ipv6_hdr(iface, ipv6, payload) < 0) { /* error on filling up header */ gnrc_pktbuf_release(pkt); return; } } rcv_pkt = gnrc_pktbuf_add(NULL, NULL, gnrc_pkt_len(ipv6), GNRC_NETTYPE_IPV6); if (rcv_pkt == NULL) { DEBUG("ipv6: error on generating loopback packet\n"); gnrc_pktbuf_release(pkt); return; } rcv_data = rcv_pkt->data; /* "reverse" packet (by making it one snip as if received from NIC) */ while (ptr != NULL) { memcpy(rcv_data, ptr->data, ptr->size); rcv_data += ptr->size; ptr = ptr->next; } gnrc_pktbuf_release(pkt); DEBUG("ipv6: packet is addressed to myself => loopback\n"); if (gnrc_netapi_receive(gnrc_ipv6_pid, rcv_pkt) < 1) { DEBUG("ipv6: unable to deliver packet\n"); gnrc_pktbuf_release(rcv_pkt); } } else { uint8_t l2addr_len = GNRC_IPV6_NC_L2_ADDR_MAX; uint8_t l2addr[l2addr_len]; iface = _next_hop_l2addr(l2addr, &l2addr_len, iface, &hdr->dst, pkt); if (iface == KERNEL_PID_UNDEF) { DEBUG("ipv6: error determining next hop's link layer address\n"); gnrc_pktbuf_release(pkt); return; } if (prep_hdr) { if (_fill_ipv6_hdr(iface, ipv6, payload) < 0) { /* error on filling up header */ gnrc_pktbuf_release(pkt); return; } } _send_unicast(iface, l2addr, l2addr_len, pkt); } } /* functions for receiving */ static inline bool _pkt_not_for_me(kernel_pid_t *iface, ipv6_hdr_t *hdr) { if (ipv6_addr_is_loopback(&hdr->dst)) { return false; } else if ((!ipv6_addr_is_link_local(&hdr->dst)) || (*iface == KERNEL_PID_UNDEF)) { kernel_pid_t if_pid = gnrc_ipv6_netif_find_by_addr(NULL, &hdr->dst); if (*iface == KERNEL_PID_UNDEF) { *iface = if_pid; /* Use original interface for reply if * existent */ } return (if_pid == KERNEL_PID_UNDEF); } else { return (gnrc_ipv6_netif_find_addr(*iface, &hdr->dst) == NULL); } } static void _receive(gnrc_pktsnip_t *pkt) { kernel_pid_t iface = KERNEL_PID_UNDEF; gnrc_pktsnip_t *ipv6, *netif, *first_ext; ipv6_hdr_t *hdr; assert(pkt != NULL); netif = gnrc_pktsnip_search_type(pkt, GNRC_NETTYPE_NETIF); if (netif != NULL) { iface = ((gnrc_netif_hdr_t *)netif->data)->if_pid; #ifdef MODULE_NETSTATS_IPV6 assert(iface); netstats_t *stats = gnrc_ipv6_netif_get_stats(iface); stats->rx_count++; stats->rx_bytes += (gnrc_pkt_len(pkt) - netif->size); #endif } first_ext = pkt; for (ipv6 = pkt; ipv6 != NULL; ipv6 = ipv6->next) { /* find IPv6 header if already marked */ if ((ipv6->type == GNRC_NETTYPE_IPV6) && (ipv6->size == sizeof(ipv6_hdr_t)) && (ipv6_hdr_is(ipv6->data))) { break; } first_ext = ipv6; } if (ipv6 == NULL) { if (!ipv6_hdr_is(pkt->data)) { DEBUG("ipv6: Received packet was not IPv6, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } #ifdef MODULE_GNRC_IPV6_WHITELIST if (!gnrc_ipv6_whitelisted(&((ipv6_hdr_t *)(pkt->data))->src)) { DEBUG("ipv6: Source address not whitelisted, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } #endif #ifdef MODULE_GNRC_IPV6_BLACKLIST if (gnrc_ipv6_blacklisted(&((ipv6_hdr_t *)(pkt->data))->src)) { DEBUG("ipv6: Source address blacklisted, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } #endif /* seize ipv6 as a temporary variable */ ipv6 = gnrc_pktbuf_start_write(pkt); if (ipv6 == NULL) { DEBUG("ipv6: unable to get write access to packet, drop it\n"); gnrc_pktbuf_release(pkt); return; } pkt = ipv6; /* reset pkt from temporary variable */ ipv6 = gnrc_pktbuf_mark(pkt, sizeof(ipv6_hdr_t), GNRC_NETTYPE_IPV6); first_ext = pkt; pkt->type = GNRC_NETTYPE_UNDEF; /* snip is no longer IPv6 */ if (ipv6 == NULL) { DEBUG("ipv6: error marking IPv6 header, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } } #ifdef MODULE_GNRC_IPV6_WHITELIST else if (!gnrc_ipv6_whitelisted(&((ipv6_hdr_t *)(ipv6->data))->src)) { /* if ipv6 header already marked*/ DEBUG("ipv6: Source address not whitelisted, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } #endif #ifdef MODULE_GNRC_IPV6_BLACKLIST else if (gnrc_ipv6_blacklisted(&((ipv6_hdr_t *)(ipv6->data))->src)) { /* if ipv6 header already marked*/ DEBUG("ipv6: Source address blacklisted, dropping packet\n"); gnrc_pktbuf_release(pkt); return; } #endif /* extract header */ hdr = (ipv6_hdr_t *)ipv6->data; /* if available, remove any padding that was added by lower layers * to fulfill their minimum size requirements (e.g. ethernet) */ if (byteorder_ntohs(hdr->len) < pkt->size) { gnrc_pktbuf_realloc_data(pkt, byteorder_ntohs(hdr->len)); } else if (byteorder_ntohs(hdr->len) > (gnrc_pkt_len_upto(pkt, GNRC_NETTYPE_IPV6) - sizeof(ipv6_hdr_t))) { DEBUG("ipv6: invalid payload length: %d, actual: %d, dropping packet\n", (int) byteorder_ntohs(hdr->len), (int) (gnrc_pkt_len_upto(pkt, GNRC_NETTYPE_IPV6) - sizeof(ipv6_hdr_t))); gnrc_pktbuf_release(pkt); return; } DEBUG("ipv6: Received (src = %s, ", ipv6_addr_to_str(addr_str, &(hdr->src), sizeof(addr_str))); DEBUG("dst = %s, next header = %u, length = %" PRIu16 ")\n", ipv6_addr_to_str(addr_str, &(hdr->dst), sizeof(addr_str)), hdr->nh, byteorder_ntohs(hdr->len)); if (_pkt_not_for_me(&iface, hdr)) { /* if packet is not for me */ DEBUG("ipv6: packet destination not this host\n"); #ifdef MODULE_GNRC_IPV6_ROUTER /* only routers redirect */ /* redirect to next hop */ DEBUG("ipv6: decrement hop limit to %u\n", (uint8_t) (hdr->hl - 1)); /* RFC 4291, section 2.5.6 states: "Routers must not forward any * packets with Link-Local source or destination addresses to other * links." */ if ((ipv6_addr_is_link_local(&(hdr->src))) || (ipv6_addr_is_link_local(&(hdr->dst)))) { DEBUG("ipv6: do not forward packets with link-local source or" " destination address\n"); gnrc_pktbuf_release(pkt); return; } /* TODO: check if receiving interface is router */ else if (--(hdr->hl) > 0) { /* drop packets that *reach* Hop Limit 0 */ gnrc_pktsnip_t *reversed_pkt = NULL, *ptr = pkt; DEBUG("ipv6: forward packet to next hop\n"); /* pkt might not be writable yet, if header was given above */ ipv6 = gnrc_pktbuf_start_write(ipv6); if (ipv6 == NULL) { DEBUG("ipv6: unable to get write access to packet: dropping it\n"); gnrc_pktbuf_release(pkt); return; } /* remove L2 headers around IPV6 */ netif = gnrc_pktsnip_search_type(pkt, GNRC_NETTYPE_NETIF); if (netif != NULL) { gnrc_pktbuf_remove_snip(pkt, netif); } /* reverse packet snip list order */ while (ptr != NULL) { gnrc_pktsnip_t *next; ptr = gnrc_pktbuf_start_write(ptr); /* duplicate if not already done */ if (ptr == NULL) { DEBUG("ipv6: unable to get write access to packet: dropping it\n"); gnrc_pktbuf_release(reversed_pkt); gnrc_pktbuf_release(pkt); return; } next = ptr->next; ptr->next = reversed_pkt; reversed_pkt = ptr; ptr = next; } _send(reversed_pkt, false); return; } else { DEBUG("ipv6: hop limit reached 0: drop packet\n"); gnrc_pktbuf_release(pkt); return; } #else /* MODULE_GNRC_IPV6_ROUTER */ DEBUG("ipv6: dropping packet\n"); /* non rounting hosts just drop the packet */ gnrc_pktbuf_release(pkt); return; #endif /* MODULE_GNRC_IPV6_ROUTER */ } /* IPv6 internal demuxing (ICMPv6, Extension headers etc.) */ gnrc_ipv6_demux(iface, first_ext, pkt, hdr->nh); } static void _decapsulate(gnrc_pktsnip_t *pkt) { gnrc_pktsnip_t *ptr = pkt; pkt->type = GNRC_NETTYPE_UNDEF; /* prevent payload (the encapsulated packet) * from being removed */ /* Remove encapsulating IPv6 header */ while ((ptr->next != NULL) && (ptr->next->type == GNRC_NETTYPE_IPV6)) { gnrc_pktbuf_remove_snip(pkt, pkt->next); } pkt->type = GNRC_NETTYPE_IPV6; _receive(pkt); } /** @} */
lgpl-2.1
backenklee/RIOT
sys/net/gnrc/sock/ip/gnrc_sock_ip.c
6053
/* * Copyright (C) 2015 Martine Lenders <mlenders@inf.fu-berlin.de> * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @{ * * @file * @brief GNRC implementation of @ref net_sock_ip * * @author Martine Lenders <mlenders@inf.fu-berlin.de> */ #include <errno.h> #include "byteorder.h" #include "net/af.h" #include "net/protnum.h" #include "net/gnrc/ipv6.h" #include "net/sock/ip.h" #include "random.h" #include "gnrc_sock_internal.h" int sock_ip_create(sock_ip_t *sock, const sock_ip_ep_t *local, const sock_ip_ep_t *remote, uint8_t proto, uint16_t flags) { assert(sock); if ((local != NULL) && (remote != NULL) && (local->netif != SOCK_ADDR_ANY_NETIF) && (remote->netif != SOCK_ADDR_ANY_NETIF) && (local->netif != remote->netif)) { return -EINVAL; } memset(&sock->local, 0, sizeof(sock_ip_ep_t)); if (local != NULL) { if (gnrc_af_not_supported(local->family)) { return -EAFNOSUPPORT; } memcpy(&sock->local, local, sizeof(sock_ip_ep_t)); } memset(&sock->remote, 0, sizeof(sock_ip_ep_t)); if (remote != NULL) { if (gnrc_af_not_supported(remote->family)) { return -EAFNOSUPPORT; } if (gnrc_ep_addr_any(remote)) { return -EINVAL; } memcpy(&sock->remote, remote, sizeof(sock_ip_ep_t)); } gnrc_sock_create(&sock->reg, GNRC_NETTYPE_IPV6, proto); sock->flags = flags; return 0; } void sock_ip_close(sock_ip_t *sock) { assert(sock != NULL); gnrc_netreg_unregister(GNRC_NETTYPE_IPV6, &sock->reg.entry); } int sock_ip_get_local(sock_ip_t *sock, sock_ip_ep_t *local) { assert(sock && local); if (sock->local.family == AF_UNSPEC) { return -EADDRNOTAVAIL; } memcpy(local, &sock->local, sizeof(sock_ip_ep_t)); return 0; } int sock_ip_get_remote(sock_ip_t *sock, sock_ip_ep_t *remote) { assert(sock && remote); if (sock->remote.family == AF_UNSPEC) { return -ENOTCONN; } memcpy(remote, &sock->remote, sizeof(sock_ip_ep_t)); return 0; } ssize_t sock_ip_recv(sock_ip_t *sock, void *data, size_t max_len, uint32_t timeout, sock_ip_ep_t *remote) { gnrc_pktsnip_t *pkt; sock_ip_ep_t tmp; int res; assert((sock != NULL) && (data != NULL) && (max_len > 0)); if (sock->local.family == 0) { return -EADDRNOTAVAIL; } tmp.family = sock->local.family; res = gnrc_sock_recv((gnrc_sock_reg_t *)sock, &pkt, timeout, &tmp); if (res < 0) { return res; } if (pkt->size > max_len) { gnrc_pktbuf_release(pkt); return -ENOBUFS; } if (remote != NULL) { /* return remote to possibly block if wrong remote */ memcpy(remote, &tmp, sizeof(tmp)); } if ((sock->remote.family != AF_UNSPEC) && /* check remote end-point if set */ /* We only have IPv6 for now, so just comparing the whole end point * should suffice */ ((memcmp(&sock->remote.addr, &ipv6_addr_unspecified, sizeof(ipv6_addr_t)) != 0) && (memcmp(&sock->remote.addr, &tmp.addr, sizeof(ipv6_addr_t)) != 0))) { gnrc_pktbuf_release(pkt); return -EPROTO; } memcpy(data, pkt->data, pkt->size); gnrc_pktbuf_release(pkt); return (int)pkt->size; } ssize_t sock_ip_send(sock_ip_t *sock, const void *data, size_t len, uint8_t proto, const sock_ip_ep_t *remote) { int res; gnrc_pktsnip_t *pkt; sock_ip_ep_t local; sock_ip_ep_t rem; assert((sock != NULL) || (remote != NULL)); assert((len == 0) || (data != NULL)); /* (len != 0) => (data != NULL) */ if ((remote != NULL) && (sock != NULL) && (sock->local.netif != SOCK_ADDR_ANY_NETIF) && (remote->netif != SOCK_ADDR_ANY_NETIF) && (sock->local.netif != remote->netif)) { return -EINVAL; } if ((remote == NULL) && /* sock can't be NULL as per assertion above */ (sock->remote.family == AF_UNSPEC)) { return -ENOTCONN; } else if ((remote != NULL) && (gnrc_ep_addr_any(remote))) { return -EINVAL; } /* compiler evaluates lazily so this isn't a redundundant check and cppcheck * is being weird here anyways */ /* cppcheck-suppress nullPointerRedundantCheck */ /* cppcheck-suppress nullPointer */ if ((sock == NULL) || (sock->local.family == AF_UNSPEC)) { /* no sock or sock currently unbound */ memset(&local, 0, sizeof(local)); } else { if (sock != NULL) { proto = (uint8_t)sock->reg.entry.demux_ctx; } memcpy(&local, &sock->local, sizeof(local)); } if (remote == NULL) { /* sock can't be NULL at this point */ memcpy(&rem, &sock->remote, sizeof(rem)); } else { memcpy(&rem, remote, sizeof(rem)); } if ((remote != NULL) && (remote->family == AF_UNSPEC) && (sock->remote.family != AF_UNSPEC)) { /* remote was set on create so take its family */ rem.family = sock->remote.family; } else if ((remote != NULL) && gnrc_af_not_supported(remote->family)) { return -EAFNOSUPPORT; } else if ((local.family == AF_UNSPEC) && (rem.family != AF_UNSPEC)) { /* local was set to 0 above */ local.family = rem.family; } else if ((local.family != AF_UNSPEC) && (rem.family == AF_UNSPEC)) { /* local was given on create, but remote family wasn't given by user and * there was no remote given on create, take from local */ rem.family = local.family; } pkt = gnrc_pktbuf_add(NULL, (void *)data, len, GNRC_NETTYPE_UNDEF); if (pkt == NULL) { return -ENOMEM; } res = gnrc_sock_send(pkt, &local, &rem, proto); if (res <= 0) { return res; } return res; } /** @} */
lgpl-2.1
cdmdotnet/CQRS
wiki/docs/2.4/html/search/classes_14.html
1018
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.13"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="classes_14.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
lgpl-2.1
ijokarumawak/nifi
nifi-nar-bundles/nifi-standard-services/nifi-hbase-client-service-api/src/main/java/org/apache/nifi/hbase/DeleteRequest.java
2100
/* * 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.nifi.hbase; /** * Encapsulates the information for a delete operation. */ public class DeleteRequest { private byte[] rowId; private byte[] columnFamily; private byte[] columnQualifier; private String visibilityLabel; public DeleteRequest(byte[] rowId, byte[] columnFamily, byte[] columnQualifier, String visibilityLabel) { this.rowId = rowId; this.columnFamily = columnFamily; this.columnQualifier = columnQualifier; this.visibilityLabel = visibilityLabel; } public byte[] getRowId() { return rowId; } public byte[] getColumnFamily() { return columnFamily; } public byte[] getColumnQualifier() { return columnQualifier; } public String getVisibilityLabel() { return visibilityLabel; } @Override public String toString() { return new StringBuilder() .append(String.format("Row ID: %s\n", new String(rowId))) .append(String.format("Column Family: %s\n", new String(columnFamily))) .append(String.format("Column Qualifier: %s\n", new String(columnQualifier))) .append(visibilityLabel != null ? String.format("Visibility Label: %s", visibilityLabel) : "") .toString(); } }
apache-2.0
material-components/material-components-ios
components/Collections/src/private/MDCCollectionViewStyler.h
1243
// Copyright 2016-present the Material Components for iOS 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. #import "MDCCollectionViewStyling.h" /** The MDCCollectionViewStyler class provides a default implementation for a UICollectionView to set its style properties. */ @interface MDCCollectionViewStyler : NSObject <MDCCollectionViewStyling> - (nonnull instancetype)init NS_UNAVAILABLE; /** Initializes and returns a newly allocated styler object with the specified collection view. Designated initializer. @param collectionView The controller's collection view. */ - (nonnull instancetype)initWithCollectionView:(nonnull UICollectionView *)collectionView NS_DESIGNATED_INITIALIZER; @end
apache-2.0
kkk669/mxnet
perl-package/AI-MXNet/lib/AI/MXNet/Module/Base.pm
37133
# 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. use strict; use warnings; package AI::MXNet::BatchEndParam; use Mouse; use AI::MXNet::Function::Parameters; has [qw/epoch nbatch/] => (is => 'rw', isa => 'Int'); has 'eval_metric' => (is => 'rw', isa => 'AI::MXNet::EvalMetric'); package AI::MXNet::Module::Base; use Mouse; use AI::MXNet::Base; use Time::HiRes qw(time); =head1 NAME AI::MXNet::Module::Base - Base class for AI::MXNet::Module and AI::MXNet::Module::Bucketing =cut func _as_list($obj) { return [$obj] if ((ref($obj)//'') ne 'ARRAY'); return $obj; } # Check that all input names are in symbol's argument method _check_input_names( AI::MXNet::Symbol $symbol, ArrayRef[Str] $names, Str $typename, Bool $throw ) { my @candidates; my %args = map { push @candidates, $_ if not /_(?:weight|bias|gamma|beta)$/; $_ => 1 } @{ $symbol->list_arguments }; for my $name (@$names) { my $msg; if(not exists $args{$name} and $name ne 'softmax_label') { $msg = sprintf("\033[91mYou created Module with Module(..., %s_names=%s) but " ."input with name '%s' is not found in symbol.list_arguments(). " ."Did you mean one of:\n\t%s\033[0m", $typename, "@$names", $name, join("\n\t", @candidates) ); if($throw) { confess($msg); } else { AI::MXNet::Logging->warning($msg); } } } } # Check that input names matches input data descriptors method _check_names_match( ArrayRef[Str] $data_names, ArrayRef[NameShapeOrDataDesc] $data_shapes, Str $name, Bool $throw ) { return if (not @$data_shapes and @$data_names == 1 and $data_names->[0] eq 'softmax_label'); my @actual = sort map { @{$_}[0] } @{ $data_shapes }; my @data_names = sort @$data_names; if("@data_names" ne "@actual") { my $msg = sprintf( "Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)", $name, $name, "@actual", "@data_names" ); if($throw) { confess($msg); } else { AI::MXNet::Logging->warning($msg); } } } method _parse_data_desc( ArrayRef[Str] $data_names, Maybe[ArrayRef[Str]] $label_names, ArrayRef[NameShapeOrDataDesc] $data_shapes, Maybe[ArrayRef[NameShapeOrDataDesc]] $label_shapes ) { $data_shapes = [map { blessed $_ ? $_ : AI::MXNet::DataDesc->new(@$_) } @$data_shapes]; $self->_check_names_match($data_names, $data_shapes, 'data', 1); if($label_shapes) { $label_shapes = [map { blessed $_ ? $_ : AI::MXNet::DataDesc->new(@$_) } @$label_shapes]; $self->_check_names_match($label_names, $label_shapes, 'label', 0); } else { $self->_check_names_match($label_names, [], 'label', 0); } return ($data_shapes, $label_shapes); } =head1 DESCRIPTION The base class of a modules. A module represents a computation component. The design purpose of a module is that it abstract a computation "machine", that one can run forward, backward, update parameters, etc. We aim to make the APIs easy to use, especially in the case when we need to use imperative API to work with multiple modules (e.g. stochastic depth network). A module has several states: - Initial state. Memory is not allocated yet, not ready for computation yet. - Binded. Shapes for inputs, outputs, and parameters are all known, memory allocated, ready for computation. - Parameter initialized. For modules with parameters, doing computation before initializing the parameters might result in undefined outputs. - Optimizer installed. An optimizer can be installed to a module. After this, the parameters of the module can be updated according to the optimizer after gradients are computed (forward-backward). In order for a module to interact with others, a module should be able to report the following information in its raw stage (before binded) - data_names: array ref of string indicating the names of required data. - output_names: array ref of string indicating the names of required outputs. And also the following richer information after binded: - state information - binded: bool, indicating whether the memory buffers needed for computation has been allocated. - for_training: whether the module is binded for training (if binded). - params_initialized: bool, indicating whether the parameters of this modules has been initialized. - optimizer_initialized: bool, indicating whether an optimizer is defined and initialized. - inputs_need_grad: bool, indicating whether gradients with respect to the input data is needed. Might be useful when implementing composition of modules. - input/output information - data_shapes: am array ref of [name, shape]. In theory, since the memory is allocated, we could directly provide the data arrays. But in the case of data parallelization, the data arrays might not be of the same shape as viewed from the external world. - label_shapes: an array ref of [name, shape]. This might be [] if the module does not need labels (e.g. it does not contains a loss function at the top), or a module is not binded for training. - output_shapes: an array ref of [name, shape] for outputs of the module. - parameters (for modules with parameters) - get_params(): return an array ($arg_params, $aux_params). Each of those is a hash ref of name to NDArray mapping. Those NDArrays always on CPU. The actual parameters used for computing might be on other devices (GPUs), this function will retrieve (a copy of) the latest parameters. Therefore, modifying - get_params($arg_params, $aux_params): assign parameters to the devices doing the computation. - init_params(...): a more flexible interface to assign or initialize the parameters. - setup - bind(): prepare environment for computation. - init_optimizer(): install optimizer for parameter updating. - computation - forward(data_batch): forward operation. - backward(out_grads=): backward operation. - update(): update parameters according to installed optimizer. - get_outputs(): get outputs of the previous forward operation. - get_input_grads(): get the gradients with respect to the inputs computed in the previous backward operation. - update_metric(metric, labels): update performance metric for the previous forward computed results. - other properties (mostly for backward compatability) - symbol: the underlying symbolic graph for this module (if any) This property is not necessarily constant. For example, for AI::MXNet::Module::Bucketing, this property is simply the *current* symbol being used. For other modules, this value might not be well defined. When those intermediate-level API are implemented properly, the following high-level API will be automatically available for a module: - fit: train the module parameters on a data set - predict: run prediction on a data set and collect outputs - score: run prediction on a data set and evaluate performance =cut has 'logger' => (is => 'rw', default => sub { AI::MXNet::Logging->get_logger }); has '_symbol' => (is => 'rw', init_arg => 'symbol', isa => 'AI::MXNet::Symbol'); has [ qw/binded for_training inputs_need_grad params_initialized optimizer_initialized/ ] => (is => 'rw', isa => 'Bool', init_arg => undef, default => 0); ################################################################################ # High Level API ################################################################################ =head2 forward_backward A convenient function that calls both forward and backward. =cut method forward_backward(AI::MXNet::DataBatch $data_batch) { $self->forward($data_batch, is_train => 1); $self->backward(); } =head2 score Run prediction on eval_data and evaluate the performance according to eval_metric. Parameters ---------- $eval_data : AI::MXNet::DataIter $eval_metric : AI::MXNet::EvalMetric :$num_batch= : Maybe[Int] Number of batches to run. Default is undef, indicating run until the AI::MXNet::DataIter finishes. :$batch_end_callback= : Maybe[Callback] Could also be a array ref of functions. :$reset=1 : Bool Default 1, indicating whether we should reset $eval_data before starting evaluating. $epoch=0 : Int Default is 0. For compatibility, this will be passed to callbacks (if any). During training, this will correspond to the training epoch number. =cut method score( AI::MXNet::DataIter $eval_data, EvalMetric $eval_metric, Maybe[Int] :$num_batch=, Maybe[Callback]|ArrayRef[Callback] :$batch_end_callback=, Maybe[Callback]|ArrayRef[Callback] :$score_end_callback=, Bool :$reset=1, Int :$epoch=0 ) { assert($self->binded and $self->params_initialized); $eval_data->reset if $reset; if(not blessed $eval_metric or not $eval_metric->isa('AI::MXNet::EvalMetric')) { $eval_metric = AI::MXNet::Metric->create($eval_metric); } $eval_metric->reset(); my $actual_num_batch = 0; my $nbatch = 0; while(my $eval_batch = <$eval_data>) { last if (defined $num_batch and $nbatch == $num_batch); $self->forward($eval_batch, is_train => 0); $self->update_metric($eval_metric, $eval_batch->label); if (defined $batch_end_callback) { my $batch_end_params = AI::MXNet::BatchEndParam->new( epoch => $epoch, nbatch => $nbatch, eval_metric => $eval_metric ); for my $callback (@{ _as_list($batch_end_callback) }) { $callback->($batch_end_params); } } $actual_num_batch++; $nbatch++ } if($score_end_callback) { my $params = AI::MXNet::BatchEndParam->new( epoch => $epoch, nbatch => $actual_num_batch, eval_metric => $eval_metric, ); for my $callback (@{ _as_list($score_end_callback) }) { $callback->($params); } } return $eval_metric->get_name_value; } =head2 iter_predict Iterate over predictions. Parameters ---------- $eval_data : AI::MXNet::DataIter :$num_batch= : Maybe[Int] Default is undef, indicating running all the batches in the data iterator. :$reset=1 : bool Default is 1, indicating whether we should reset the data iter before start doing prediction. =cut method iter_predict(AI::MXNet::DataIter $eval_data, Maybe[Int] :$num_batch=, Bool :$reset=1) { assert($self->binded and $self->params_initialized); if($reset) { $eval_data->reset; } my $nbatch = 0; my @out; while(my $eval_batch = <$eval_data>) { last if defined $num_batch and $nbatch == $num_batch; $self->forward($eval_batch, is_train => 0); my $pad = $eval_batch->pad; my $outputs = [ map { $_->slice([0, $_->shape->[0] - ($pad//0) - 1]) } @{ $self->get_outputs() } ]; push @out, [$outputs, $nbatch, $eval_batch]; $nbatch++; } return @out; } =head2 predict Run prediction and collect the outputs. Parameters ---------- $eval_data : AI::MXNet::DataIter :$num_batch= : Maybe[Int] Default is undef, indicating running all the batches in the data iterator. :$merge_batches=1 : Bool Default is 1. :$reset=1 : Bool Default is 1, indicating whether we should reset the data iter before start doing prediction. :$always_output_list=0 : Bool Default is 0, see the doc for return values. Returns ------- When $merge_batches is 1 (by default), the return value will be an array ref [$out1, $out2, $out3] where each element is concatenation of the outputs for all the mini-batches. If $always_output_list` also is 0 (by default), then in the case of a single output, $out1 is returned in stead of [$out1]. When $merge_batches is 0, the return value will be a nested array ref like [[$out1_batch1, $out2_batch1], [$out1_batch2], ...]. This mode is useful because in some cases (e.g. bucketing), the module does not necessarily produce the same number of outputs. The objects in the results are AI::MXNet::NDArray`s. If you need to work with pdl array, just call ->aspdl() on each AI::MXNet::NDArray. =cut method predict( AI::MXNet::DataIter $eval_data, Maybe[Int] :$num_batch=, Bool :$merge_batches=1, Bool :$reset=1, Bool :$always_output_list=0 ) { assert($self->binded and $self->params_initialized); $eval_data->reset() if $reset; my @output_list; my $nbatch = 0; while(my $eval_batch = <$eval_data>) { last if defined $num_batch and $nbatch == $num_batch; $self->forward($eval_batch, is_train => 0); my $pad = $eval_batch->pad; my $outputs = [map { $_->slice([0, $_->shape->[0]-($pad//0)-1])->copy } @{ $self->get_outputs }]; push @output_list, $outputs; } return () unless @output_list; if($merge_batches) { my $num_outputs = @{ $output_list[0] }; for my $out (@output_list) { unless(@{ $out } == $num_outputs) { confess('Cannot merge batches, as num of outputs is not the same ' .'in mini-batches. Maybe bucketing is used?'); } } my @output_list2; for my $i (0..$num_outputs-1) { push @output_list2, AI::MXNet::NDArray->concatenate([map { $_->[$i] } @output_list]); } if($num_outputs == 1 and not $always_output_list) { return $output_list2[0]; } return @output_list2; } return @output_list; } =head2 fit Train the module parameters. Parameters ---------- $train_data : AI::MXNet::DataIter :$eval_data= : Maybe[AI::MXNet::DataIter] If not undef, it will be used as a validation set to evaluate the performance after each epoch. :$eval_metric='acc' : str or AI::MXNet::EvalMetric subclass object. Default is 'accuracy'. The performance measure used to display during training. Other possible predefined metrics are: 'ce' (CrossEntropy), 'f1', 'mae', 'mse', 'rmse', 'top_k_accuracy' :$epoch_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions. Each callback will be called with the current $epoch, $symbol, $arg_params and $aux_params. :$batch_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions. Each callback will be called with a AI::MXNet::BatchEndParam. :$kvstore='local' : str or AI::MXNet::KVStore Default is 'local'. :$optimizer : str or AI::MXNet::Optimizer Default is 'sgd' :$optimizer_params : hash ref Default { learning_rate => 0.01 }. The parameters for the optimizer constructor. :$eval_end_callback= : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions These will be called at the end of each full evaluation, with the metrics over the entire evaluation set. :$eval_batch_end_callback : Maybe[Callback]|ArrayRef[Callback] function or array ref of functions These will be called at the end of each minibatch during evaluation :$initializer= : Initializer Will be called to initialize the module parameters if not already initialized. :$arg_params= : hash ref Default undef, if not undef, must be an existing parameters from a trained model or loaded from a checkpoint (previously saved model). In this case, the value here will be used to initialize the module parameters, unless they are already initialized by the user via a call to init_params or fit. $arg_params have higher priority than the $initializer. :$aux_params= : hash ref Default is undef. This is similar to the $arg_params, except for auxiliary states. :$allow_missing=0 : Bool Default is 0. Indicates whether we allow missing parameters when $arg_params and $aux_params are not undefined. If this is 1, then the missing parameters will be initialized via the $initializer. :$force_rebind=0 : Bool Default is 0. Whether to force rebinding the executors if already binded. :$force_init=0 : Bool Default is 0. Indicates whether we should force initialization even if the parameters are already initialized. :$begin_epoch=0 : Int Default is 0. Indicates the starting epoch. Usually, if we are resuming from a checkpoint saved at a previous training phase at epoch N, then we should specify this value as N+1. :$num_epoch : Int Number of epochs for the training. =cut method fit( AI::MXNet::DataIter $train_data, Maybe[AI::MXNet::DataIter] :$eval_data=, EvalMetric :$eval_metric='acc', Maybe[Callback]|ArrayRef[Callback] :$epoch_end_callback=, Maybe[Callback]|ArrayRef[Callback] :$batch_end_callback=, KVStore :$kvstore='local', Optimizer :$optimizer='sgd', HashRef :$optimizer_params={ learning_rate => 0.01 }, Maybe[Callback]|ArrayRef[Callback] :$eval_end_callback=, Maybe[Callback]|ArrayRef[Callback] :$eval_batch_end_callback=, AI::MXNet::Initializer :$initializer=AI::MXNet::Initializer->Uniform(scale => 0.01), Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=, Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=, Bool :$allow_missing=0, Bool :$force_rebind=0, Bool :$force_init=0, Int :$begin_epoch=0, Int :$num_epoch, Maybe[EvalMetric] :$validation_metric=, Maybe[AI::MXNet::Monitor] :$monitor= ) { $self->bind( data_shapes => $train_data->provide_data, label_shapes => $train_data->provide_label, for_training => 1, force_rebind => $force_rebind ); if($monitor) { $self->install_monitor($monitor); } $self->init_params( initializer => $initializer, arg_params => $arg_params, aux_params => $aux_params, allow_missing => $allow_missing, force_init => $force_init ); $self->init_optimizer( kvstore => $kvstore, optimizer => $optimizer, optimizer_params => $optimizer_params ); if(not defined $validation_metric) { $validation_metric = $eval_metric; } $eval_metric = AI::MXNet::Metric->create($eval_metric) unless blessed $eval_metric; ################################################################################ # training loop ################################################################################ for my $epoch ($begin_epoch..$num_epoch-1) { my $tic = time; $eval_metric->reset; my $nbatch = 0; my $end_of_batch = 0; my $next_data_batch = <$train_data>; while(not $end_of_batch) { my $data_batch = $next_data_batch; $monitor->tic if $monitor; $self->forward_backward($data_batch); $self->update; $next_data_batch = <$train_data>; if(defined $next_data_batch) { $self->prepare($next_data_batch); } else { $end_of_batch = 1; } $self->update_metric($eval_metric, $data_batch->label); $monitor->toc_print if $monitor; if(defined $batch_end_callback) { my $batch_end_params = AI::MXNet::BatchEndParam->new( epoch => $epoch, nbatch => $nbatch, eval_metric => $eval_metric ); for my $callback (@{ _as_list($batch_end_callback) }) { $callback->($batch_end_params); } } $nbatch++; } # one epoch of training is finished my $name_value = $eval_metric->get_name_value; while(my ($name, $val) = each %{ $name_value }) { $self->logger->info('Epoch[%d] Train-%s=%f', $epoch, $name, $val); } my $toc = time; $self->logger->info('Epoch[%d] Time cost=%.3f', $epoch, ($toc-$tic)); # sync aux params across devices my ($arg_params, $aux_params) = $self->get_params; $self->set_params($arg_params, $aux_params); if($epoch_end_callback) { for my $callback (@{ _as_list($epoch_end_callback) }) { $callback->($epoch, $self->get_symbol, $arg_params, $aux_params); } } #---------------------------------------- # evaluation on validation set if(defined $eval_data) { my $res = $self->score( $eval_data, $validation_metric, score_end_callback => $eval_end_callback, batch_end_callback => $eval_batch_end_callback, epoch => $epoch ); #TODO: pull this into default while(my ($name, $val) = each %{ $res }) { $self->logger->info('Epoch[%d] Validation-%s=%f', $epoch, $name, $val); } } # end of 1 epoch, reset the data-iter for another epoch $train_data->reset; } } ################################################################################ # Symbol information ################################################################################ =head2 get_symbol The symbol used by this module. =cut method get_symbol() { $self->symbol } =head2 data_names An array ref of names for data required by this module. =cut method data_names() { confess("NotImplemented") } =head2 output_names An array ref of names for the outputs of this module. =cut method output_names() { confess("NotImplemented") } ################################################################################ # Input/Output information ################################################################################ =head2 data_shapes An array ref of AI::MXNet::DataDesc objects specifying the data inputs to this module. =cut method data_shapes() { confess("NotImplemented") } =head2 label_shapes A array ref of AI::MXNet::DataDesc objects specifying the label inputs to this module. If this module does not accept labels -- either it is a module without a loss function, or it is not binded for training, then this should return an empty array ref. =cut method label_shapes() { confess("NotImplemented") } =head2 output_shapes An array ref of (name, shape) array refs specifying the outputs of this module. =cut method output_shapes() { confess("NotImplemented") } ################################################################################ # Parameters of a module ################################################################################ =head2 get_params The parameters, these are potentially a copies of the the actual parameters used to do computation on the device. Returns ------- ($arg_params, $aux_params), a pair of hash refs of name to value mapping. =cut method get_params() { confess("NotImplemented") } =head2 init_params Initialize the parameters and auxiliary states. Parameters ---------- :$initializer : Maybe[AI::MXNet::Initializer] Called to initialize parameters if needed. :$arg_params= : Maybe[HashRef[AI::MXNet::NDArray]] If not undef, should be a hash ref of existing arg_params. :$aux_params : Maybe[HashRef[AI::MXNet::NDArray]] If not undef, should be a hash ref of existing aux_params. :$allow_missing=0 : Bool If true, params could contain missing values, and the initializer will be called to fill those missing params. :$force_init=0 : Bool If true, will force re-initialize even if already initialized. :$allow_extra=0 : Boolean, optional Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. =cut method init_params( Maybe[AI::MXNet::Initializer] :$initializer=AI::MXNet::Initializer->Uniform(0.01), Maybe[HashRef[AI::MXNet::NDArray]] :$arg_params=, Maybe[HashRef[AI::MXNet::NDArray]] :$aux_params=, Bool :$allow_missing=0, Bool :$force_init=0, Bool :$allow_extra=0 ) { confess("NotImplemented"); } =head2 set_params Assign parameter and aux state values. Parameters ---------- $arg_params= : Maybe[HashRef[AI::MXNet::NDArray]] Hash ref of name to value (NDArray) mapping. $aux_params= : Maybe[HashRef[AI::MXNet::NDArray]] Hash Ref of name to value (`NDArray`) mapping. :$allow_missing=0 : Bool If true, params could contain missing values, and the initializer will be called to fill those missing params. :$force_init=0 : Bool If true, will force re-initialize even if already initialized. :$allow_extra=0 : Bool Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. =cut method set_params( Maybe[HashRef[AI::MXNet::NDArray]] $arg_params=, Maybe[HashRef[AI::MXNet::NDArray]] $aux_params=, Bool :$allow_missing=0, Bool :$force_init=0, Bool :$allow_extra=0 ) { $self->init_params( initializer => undef, arg_params => $arg_params, aux_params => $aux_params, allow_missing => $allow_missing, force_init => $force_init, allow_extra => $allow_extra ); } =head2 save_params Save model parameters to file. Parameters ---------- $fname : str Path to output param file. $arg_params= : Maybe[HashRef[AI::MXNet::NDArray]] $aux_params= : Maybe[HashRef[AI::MXNet::NDArray]] =cut method save_params( Str $fname, Maybe[HashRef[AI::MXNet::NDArray]] $arg_params=, Maybe[HashRef[AI::MXNet::NDArray]] $aux_params= ) { ($arg_params, $aux_params) = $self->get_params unless (defined $arg_params and defined $aux_params); my %save_dict; while(my ($k, $v) = each %{ $arg_params }) { $save_dict{"arg:$k"} = $v->as_in_context(AI::MXNet::Context->cpu); } while(my ($k, $v) = each %{ $aux_params }) { $save_dict{"aux:$k"} = $v->as_in_context(AI::MXNet::Context->cpu); } AI::MXNet::NDArray->save($fname, \%save_dict); } =head2 load_params Load model parameters from file. Parameters ---------- $fname : str Path to input param file. =cut method load_params(Str $fname) { my %save_dict = %{ AI::MXNet::NDArray->load($fname) }; my %arg_params; my %aux_params; while(my ($k, $v) = each %save_dict) { my ($arg_type, $name) = split(/:/, $k, 2); if($arg_type eq 'arg') { $arg_params{ $name } = $v; } elsif($arg_type eq 'aux') { $aux_params{ $name } = $v; } else { confess("Invalid param file $fname"); } } $self->set_params(\%arg_params, \%aux_params); } =head2 get_states The states from all devices Parameters ---------- $merge_multi_context=1 : Bool Default is true (1). In the case when data-parallelism is used, the states will be collected from multiple devices. A true value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- If $merge_multi_context is 1, it is like [$out1, $out2]. Otherwise, it is like [[$out1_dev1, $out1_dev2], [$out2_dev1, $out2_dev2]]. All the output elements are AI::MXNet::NDArray. =cut method get_states(Bool $merge_multi_context=1) { assert($self->binded and $self->params_initialized); assert(not $merge_multi_context); return []; } =head2 set_states Set value for states. You can specify either $states or $value, not both. Parameters ---------- $states= : Maybe[ArrayRef[ArrayRef[AI::MXNet::NDArray]]] source states arrays formatted like [[$state1_dev1, $state1_dev2], [$state2_dev1, $state2_dev2]]. $value= : Maybe[Num] a single scalar value for all state arrays. =cut method set_states(Maybe[ArrayRef[ArrayRef[AI::MXNet::NDArray]]] $states=, Maybe[Num] $value=) { assert($self->binded and $self->params_initialized); assert(not $states and not $value); } =head2 install_monitor Install monitor on all executors Parameters ---------- $mon : AI::MXNet::Monitor =cut method install_monitor(AI::MXNet::Monitor $mon) { confess("NotImplemented") } =head2 prepare Prepare the module for processing a data batch. Usually involves switching a bucket and reshaping. Parameters ---------- $data_batch : AI::MXNet::DataBatch =cut method prepare(AI::MXNet::DataBatch $data_batch){} ################################################################################ # Computations ################################################################################ =head2 forward Forward computation. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or switching from training to predicting, module rebinding is required. Parameters ---------- $data_batch : DataBatch Could be anything with similar API implemented. :$is_train= : Bool Default is undef, which means is_train takes the value of $self->for_training. =cut method forward(AI::MXNet::DataBatch $data_batch, Bool :$is_train=) { confess("NotImplemented") } =head2 backward Backward computation. Parameters ---------- $out_grads : Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]], optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs that are not a loss function. =cut method backward(Maybe[AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]] $out_grads=) { confess("NotImplemented") } =head2 get_outputs The outputs of the previous forward computation. Parameters ---------- $merge_multi_context=1 : Bool =cut method get_outputs(Bool $merge_multi_context=1) { confess("NotImplemented") } =head2 get_input_grads The gradients to the inputs, computed in the previous backward computation. Parameters ---------- $merge_multi_context=1 : Bool =cut method get_input_grads(Bool $merge_multi_context=1) { confess("NotImplemented") } =head2 update Update parameters according to the installed optimizer and the gradients computed in the previous forward-backward batch. =cut method update() { confess("NotImplemented") } =head2 update_metric Evaluate and accumulate evaluation metric on outputs of the last forward computation. Parameters ---------- $eval_metric : EvalMetric $labels : ArrayRef[AI::MXNet::NDArray] Typically $data_batch->label. =cut method update_metric(EvalMetric $eval_metric, ArrayRef[AI::MXNet::NDArray] $labels) { confess("NotImplemented") } ################################################################################ # module setup ################################################################################ =head2 bind Binds the symbols in order to construct the executors. This is necessary before the computations can be performed. Parameters ---------- $data_shapes : ArrayRef[AI::MXNet::DataDesc] Typically is $data_iter->provide_data. :$label_shapes= : Maybe[ArrayRef[AI::MXNet::DataDesc]] Typically is $data_iter->provide_label. :$for_training=1 : Bool Default is 1. Whether the executors should be bind for training. :$inputs_need_grad=0 : Bool Default is 0. Whether the gradients to the input data need to be computed. Typically this is not needed. But this might be needed when implementing composition of modules. :$force_rebind=0 : Bool Default is 0. This function does nothing if the executors are already binded. But with this as 1, the executors will be forced to rebind. :$shared_module= : A subclass of AI::MXNet::Module::Base Default is undef. This is used in bucketing. When not undef, the shared module essentially corresponds to a different bucket -- a module with different symbol but with the same sets of parameters (e.g. unrolled RNNs with different lengths). :$grad_req='write' : Str|ArrayRef[Str]|HashRef[Str] Requirement for gradient accumulation. Can be 'write', 'add', or 'null' (defaults to 'write'). Can be specified globally (str) or for each argument (array ref, hash ref). =cut method bind( ArrayRef[AI::MXNet::DataDesc] $data_shapes, Maybe[ArrayRef[AI::MXNet::DataDesc]] :$label_shapes=, Bool :$for_training=1, Bool :$inputs_need_grad=0, Bool :$force_rebind=0, Maybe[AI::MXNet::BaseModule] :$shared_module=, Str|ArrayRef[Str]|HashRef[Str] :$grad_req='write' ) { confess("NotImplemented") } =head2 init_optimizer Install and initialize optimizers. Parameters ---------- :$kvstore='local' : str or KVStore :$optimizer='sgd' : str or Optimizer :$optimizer_params={ learning_rate => 0.01 } : hash ref :$force_init=0 : Bool =cut method init_optimizer( Str :$kvstore='local', Optimizer :$optimizer='sgd', HashRef :$optimizer_params={ learning_rate => 0.01 }, Bool :$force_init=0 ) { confess("NotImplemented") } ################################################################################ # misc ################################################################################ =head2 symbol The symbol associated with this module. Except for AI::MXNet::Module, for other types of modules (e.g. AI::MXNet::Module::Bucketing), this property might not be a constant throughout its life time. Some modules might not even be associated with any symbols. =cut method symbol() { return $self->_symbol; } 1;
apache-2.0
physhi/roslyn
src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs
3081
// 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. #nullable disable using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a sequence of values. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct SequenceEdit : IEquatable<SequenceEdit> { private readonly int _oldIndex; private readonly int _newIndex; internal SequenceEdit(int oldIndex, int newIndex) { Debug.Assert(oldIndex >= -1); Debug.Assert(newIndex >= -1); Debug.Assert(newIndex != -1 || oldIndex != -1); _oldIndex = oldIndex; _newIndex = newIndex; } /// <summary> /// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>. /// </summary> public EditKind Kind { get { if (_oldIndex == -1) { return EditKind.Insert; } if (_newIndex == -1) { return EditKind.Delete; } return EditKind.Update; } } /// <summary> /// Index in the old sequence, or -1 if the edit is insert. /// </summary> public int OldIndex => _oldIndex; /// <summary> /// Index in the new sequence, or -1 if the edit is delete. /// </summary> public int NewIndex => _newIndex; public bool Equals(SequenceEdit other) { return _oldIndex == other._oldIndex && _newIndex == other._newIndex; } public override bool Equals(object obj) => obj is SequenceEdit && Equals((SequenceEdit)obj); public override int GetHashCode() => Hash.Combine(_oldIndex, _newIndex); private string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " (" + _oldIndex + ")"; case EditKind.Insert: return result + " (" + _newIndex + ")"; case EditKind.Update: return result + " (" + _oldIndex + " -> " + _newIndex + ")"; } return result; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly SequenceEdit _sequenceEdit; public TestAccessor(SequenceEdit sequenceEdit) => _sequenceEdit = sequenceEdit; internal string GetDebuggerDisplay() => _sequenceEdit.GetDebuggerDisplay(); } } }
apache-2.0
muzining/net
x/net/icmp/extension_test.go
8186
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package icmp import ( "fmt" "net" "reflect" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) func TestMarshalAndParseExtension(t *testing.T) { fn := func(t *testing.T, proto int, typ Type, hdr, obj []byte, te Extension) error { b, err := te.Marshal(proto) if err != nil { return err } if !reflect.DeepEqual(b, obj) { return fmt.Errorf("got %#v; want %#v", b, obj) } switch typ { case ipv4.ICMPTypeExtendedEchoRequest, ipv6.ICMPTypeExtendedEchoRequest: exts, l, err := parseExtensions(typ, append(hdr, obj...), 0) if err != nil { return err } if l != 0 { return fmt.Errorf("got %d; want 0", l) } if !reflect.DeepEqual(exts, []Extension{te}) { return fmt.Errorf("got %#v; want %#v", exts[0], te) } default: for i, wire := range []struct { data []byte // original datagram inlattr int // length of padded original datagram, a hint outlattr int // length of padded original datagram, a want err error }{ {nil, 0, -1, errNoExtension}, {make([]byte, 127), 128, -1, errNoExtension}, {make([]byte, 128), 127, -1, errNoExtension}, {make([]byte, 128), 128, -1, errNoExtension}, {make([]byte, 128), 129, -1, errNoExtension}, {append(make([]byte, 128), append(hdr, obj...)...), 127, 128, nil}, {append(make([]byte, 128), append(hdr, obj...)...), 128, 128, nil}, {append(make([]byte, 128), append(hdr, obj...)...), 129, 128, nil}, {append(make([]byte, 512), append(hdr, obj...)...), 511, -1, errNoExtension}, {append(make([]byte, 512), append(hdr, obj...)...), 512, 512, nil}, {append(make([]byte, 512), append(hdr, obj...)...), 513, -1, errNoExtension}, } { exts, l, err := parseExtensions(typ, wire.data, wire.inlattr) if err != wire.err { return fmt.Errorf("#%d: got %v; want %v", i, err, wire.err) } if wire.err != nil { continue } if l != wire.outlattr { return fmt.Errorf("#%d: got %d; want %d", i, l, wire.outlattr) } if !reflect.DeepEqual(exts, []Extension{te}) { return fmt.Errorf("#%d: got %#v; want %#v", i, exts[0], te) } } } return nil } t.Run("MPLSLabelStack", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // MPLS label stack with no label { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x01, 0x01, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, }, }, // MPLS label stack with a single label { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x01, 0x01, 0x03, 0xe8, 0xe9, 0xff, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, // MPLS label stack with multiple labels { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x01, 0x01, 0x03, 0xe8, 0xde, 0xfe, 0x03, 0xe8, 0xe1, 0xff, }, ext: &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16013, TC: 0x7, S: false, TTL: 254, }, { Label: 16014, TC: 0, S: true, TTL: 255, }, }, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) t.Run("InterfaceInfo", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // Interface information with no attribute { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x02, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, }, }, // Interface information with ifIndex and name { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0a, Interface: &net.Interface{ Index: 16, Name: "en101", }, }, }, // Interface information with ifIndex, IPAddr, name and MTU { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeDestinationUnreachable, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x28, 0x02, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x02, 0x00, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, }, ext: &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) t.Run("InterfaceIdent", func(t *testing.T) { for _, et := range []struct { proto int typ Type hdr []byte obj []byte ext Extension }{ // Interface identification by name { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x03, 0x01, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByName, Name: "en101", }, }, // Interface identification by index { proto: iana.ProtocolIPv6ICMP, typ: ipv6.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x03, 0x02, 0x00, 0x00, 0x03, 0x8f, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByIndex, Index: 911, }, }, // Interface identification by address { proto: iana.ProtocolICMP, typ: ipv4.ICMPTypeExtendedEchoRequest, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x03, 0x03, byte(iana.AddrFamily48bitMAC >> 8), byte(iana.AddrFamily48bitMAC & 0x0f), 0x06, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0x00, 0x00, }, ext: &InterfaceIdent{ Class: classInterfaceIdent, Type: typeInterfaceByAddress, AFI: iana.AddrFamily48bitMAC, Addr: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}, }, }, } { if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil { t.Error(err) } } }) } func TestParseInterfaceName(t *testing.T) { ifi := InterfaceInfo{Interface: &net.Interface{}} for i, tt := range []struct { b []byte error }{ {[]byte{0, 'e', 'n', '0'}, errInvalidExtension}, {[]byte{4, 'e', 'n', '0'}, nil}, {[]byte{7, 'e', 'n', '0', 0xff, 0xff, 0xff, 0xff}, errInvalidExtension}, {[]byte{8, 'e', 'n', '0', 0xff, 0xff, 0xff}, errMessageTooShort}, } { if _, err := ifi.parseName(tt.b); err != tt.error { t.Errorf("#%d: got %v; want %v", i, err, tt.error) } } }
bsd-3-clause
6by9/userland
interface/mmal/test/examples/example_basic_2.c
15866
/* Copyright (c) 2012, Broadcom Europe Ltd 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 the copyright holder 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 HOLDER 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. */ #include "bcm_host.h" #include "mmal.h" #include "util/mmal_default_components.h" #include "util/mmal_util_params.h" #include "util/mmal_util.h" #include "interface/vcos/vcos.h" #include <stdio.h> #define CHECK_STATUS(status, msg) if (status != MMAL_SUCCESS) { fprintf(stderr, msg"\n"); goto error; } static uint8_t codec_header_bytes[512]; static unsigned int codec_header_bytes_size = sizeof(codec_header_bytes); static FILE *source_file; /* Macros abstracting the I/O, just to make the example code clearer */ #define SOURCE_OPEN(uri) \ source_file = fopen(uri, "rb"); if (!source_file) goto error; #define SOURCE_READ_CODEC_CONFIG_DATA(bytes, size) \ size = fread(bytes, 1, size, source_file); rewind(source_file) #define SOURCE_READ_DATA_INTO_BUFFER(a) \ a->length = fread(a->data, 1, a->alloc_size - 128, source_file); \ a->offset = 0 #define SOURCE_CLOSE() \ if (source_file) fclose(source_file) /** Context for our application */ static struct CONTEXT_T { VCOS_SEMAPHORE_T semaphore; MMAL_QUEUE_T *queue; MMAL_STATUS_T status; } context; static void log_video_format(MMAL_ES_FORMAT_T *format) { if (format->type != MMAL_ES_TYPE_VIDEO) return; fprintf(stderr, "fourcc: %4.4s, width: %i, height: %i, (%i,%i,%i,%i)\n", (char *)&format->encoding, format->es->video.width, format->es->video.height, format->es->video.crop.x, format->es->video.crop.y, format->es->video.crop.width, format->es->video.crop.height); } /** Callback from the control port. * Component is sending us an event. */ static void control_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata; switch (buffer->cmd) { case MMAL_EVENT_EOS: /* Only sink component generate EOS events */ break; case MMAL_EVENT_ERROR: /* Something went wrong. Signal this to the application */ ctx->status = *(MMAL_STATUS_T *)buffer->data; break; default: break; } /* Done with the event, recycle it */ mmal_buffer_header_release(buffer); /* Kick the processing thread */ vcos_semaphore_post(&ctx->semaphore); } /** Callback from the input port. * Buffer has been consumed and is available to be used again. */ static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata; /* The decoder is done with the data, just recycle the buffer header into its pool */ mmal_buffer_header_release(buffer); /* Kick the processing thread */ vcos_semaphore_post(&ctx->semaphore); } /** Callback from the output port. * Buffer has been produced by the port and is available for processing. */ static void output_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer) { struct CONTEXT_T *ctx = (struct CONTEXT_T *)port->userdata; /* Queue the decoded video frame */ mmal_queue_put(ctx->queue, buffer); /* Kick the processing thread */ vcos_semaphore_post(&ctx->semaphore); } int main(int argc, char **argv) { MMAL_STATUS_T status = MMAL_EINVAL; MMAL_COMPONENT_T *decoder = 0; MMAL_POOL_T *pool_in = 0, *pool_out = 0; MMAL_BOOL_T eos_sent = MMAL_FALSE, eos_received = MMAL_FALSE; unsigned int count; if (argc < 2) { fprintf(stderr, "invalid arguments\n"); return -1; } bcm_host_init(); vcos_semaphore_create(&context.semaphore, "example", 1); SOURCE_OPEN(argv[1]); /* Create the decoder component. * This specific component exposes 2 ports (1 input and 1 output). Like most components * its expects the format of its input port to be set by the client in order for it to * know what kind of data it will be fed. */ status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &decoder); CHECK_STATUS(status, "failed to create decoder"); /* Enable control port so we can receive events from the component */ decoder->control->userdata = (void *)&context; status = mmal_port_enable(decoder->control, control_callback); CHECK_STATUS(status, "failed to enable control port"); /* Get statistics on the input port */ MMAL_PARAMETER_CORE_STATISTICS_T stats = {{0}}; stats.hdr.id = MMAL_PARAMETER_CORE_STATISTICS; stats.hdr.size = sizeof(MMAL_PARAMETER_CORE_STATISTICS_T); status = mmal_port_parameter_get(decoder->input[0], &stats.hdr); CHECK_STATUS(status, "failed to get stats"); fprintf(stderr, "stats: %i, %i", stats.stats.buffer_count, stats.stats.max_delay); /* Set the zero-copy parameter on the input port */ MMAL_PARAMETER_BOOLEAN_T zc = {{MMAL_PARAMETER_ZERO_COPY, sizeof(zc)}, MMAL_TRUE}; status = mmal_port_parameter_set(decoder->input[0], &zc.hdr); fprintf(stderr, "status: %i\n", status); /* Set the zero-copy parameter on the output port */ status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_ZERO_COPY, MMAL_TRUE); fprintf(stderr, "status: %i\n", status); /* Set format of video decoder input port */ MMAL_ES_FORMAT_T *format_in = decoder->input[0]->format; format_in->type = MMAL_ES_TYPE_VIDEO; format_in->encoding = MMAL_ENCODING_H264; format_in->es->video.width = 1280; format_in->es->video.height = 720; format_in->es->video.frame_rate.num = 30; format_in->es->video.frame_rate.den = 1; format_in->es->video.par.num = 1; format_in->es->video.par.den = 1; /* If the data is known to be framed then the following flag should be set: * format_in->flags |= MMAL_ES_FORMAT_FLAG_FRAMED; */ SOURCE_READ_CODEC_CONFIG_DATA(codec_header_bytes, codec_header_bytes_size); status = mmal_format_extradata_alloc(format_in, codec_header_bytes_size); CHECK_STATUS(status, "failed to allocate extradata"); format_in->extradata_size = codec_header_bytes_size; if (format_in->extradata_size) memcpy(format_in->extradata, codec_header_bytes, format_in->extradata_size); status = mmal_port_format_commit(decoder->input[0]); CHECK_STATUS(status, "failed to commit format"); /* Our decoder can do internal colour conversion, ask for a conversion to RGB565 */ MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format; format_out->encoding = MMAL_ENCODING_RGB16; status = mmal_port_format_commit(decoder->output[0]); CHECK_STATUS(status, "failed to commit format"); /* Display the output port format */ fprintf(stderr, "%s\n", decoder->output[0]->name); fprintf(stderr, " type: %i, fourcc: %4.4s\n", format_out->type, (char *)&format_out->encoding); fprintf(stderr, " bitrate: %i, framed: %i\n", format_out->bitrate, !!(format_out->flags & MMAL_ES_FORMAT_FLAG_FRAMED)); fprintf(stderr, " extra data: %i, %p\n", format_out->extradata_size, format_out->extradata); fprintf(stderr, " width: %i, height: %i, (%i,%i,%i,%i)\n", format_out->es->video.width, format_out->es->video.height, format_out->es->video.crop.x, format_out->es->video.crop.y, format_out->es->video.crop.width, format_out->es->video.crop.height); /* The format of both ports is now set so we can get their buffer requirements and create * our buffer headers. We use the buffer pool API to create these. */ decoder->input[0]->buffer_num = decoder->input[0]->buffer_num_min; decoder->input[0]->buffer_size = decoder->input[0]->buffer_size_min; decoder->output[0]->buffer_num = decoder->output[0]->buffer_num_min; decoder->output[0]->buffer_size = decoder->output[0]->buffer_size_min; pool_in = mmal_port_pool_create(decoder->output[0], decoder->input[0]->buffer_num, decoder->input[0]->buffer_size); pool_out = mmal_port_pool_create(decoder->output[0], decoder->output[0]->buffer_num, decoder->output[0]->buffer_size); /* Create a queue to store our decoded video frames. The callback we will get when * a frame has been decoded will put the frame into this queue. */ context.queue = mmal_queue_create(); /* Store a reference to our context in each port (will be used during callbacks) */ decoder->input[0]->userdata = (void *)&context; decoder->output[0]->userdata = (void *)&context; /* Enable all the input port and the output port. * The callback specified here is the function which will be called when the buffer header * we sent to the component has been processed. */ status = mmal_port_enable(decoder->input[0], input_callback); CHECK_STATUS(status, "failed to enable input port"); status = mmal_port_enable(decoder->output[0], output_callback); CHECK_STATUS(status, "failed to enable output port"); /* Component won't start processing data until it is enabled. */ status = mmal_component_enable(decoder); CHECK_STATUS(status, "failed to enable component"); /* Start decoding */ fprintf(stderr, "start decoding\n"); /* This is the main processing loop */ for (count = 0; !eos_received && count < 500; count++) { MMAL_BUFFER_HEADER_T *buffer; /* Wait for buffer headers to be available on either of the decoder ports */ vcos_semaphore_wait(&context.semaphore); /* Check for errors */ if (context.status != MMAL_SUCCESS) { fprintf(stderr, "Aborting due to error\n"); break; } /* Send data to decode to the input port of the video decoder */ if (!eos_sent && (buffer = mmal_queue_get(pool_in->queue)) != NULL) { SOURCE_READ_DATA_INTO_BUFFER(buffer); if(!buffer->length) eos_sent = MMAL_TRUE; buffer->flags = buffer->length ? 0 : MMAL_BUFFER_HEADER_FLAG_EOS; buffer->pts = buffer->dts = MMAL_TIME_UNKNOWN; fprintf(stderr, "sending %i bytes\n", (int)buffer->length); status = mmal_port_send_buffer(decoder->input[0], buffer); CHECK_STATUS(status, "failed to send buffer"); } /* Get our decoded frames */ while ((buffer = mmal_queue_get(context.queue)) != NULL) { /* We have a frame, do something with it (why not display it for instance?). * Once we're done with it, we release it. It will automatically go back * to its original pool so it can be reused for a new video frame. */ eos_received = buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS; if (buffer->cmd) { fprintf(stderr, "received event %4.4s\n", (char *)&buffer->cmd); if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED) { MMAL_EVENT_FORMAT_CHANGED_T *event = mmal_event_format_changed_get(buffer); if (event) { fprintf(stderr, "----------Port format changed----------\n"); log_video_format(decoder->output[0]->format); fprintf(stderr, "-----------------to---------------------\n"); log_video_format(event->format); fprintf(stderr, " buffers num (opt %i, min %i), size (opt %i, min: %i)\n", event->buffer_num_recommended, event->buffer_num_min, event->buffer_size_recommended, event->buffer_size_min); fprintf(stderr, "----------------------------------------\n"); } //Assume we can't reuse the buffers, so have to disable, destroy //pool, create new pool, enable port, feed in buffers. status = mmal_port_disable(decoder->output[0]); CHECK_STATUS(status, "failed to disable port"); //Clear the queue of all buffers while(mmal_queue_length(pool_out->queue) != pool_out->headers_num) { MMAL_BUFFER_HEADER_T *buf; fprintf(stderr, "Wait for buffers to be returned. Have %d of %d buffers\n", mmal_queue_length(pool_out->queue), pool_out->headers_num); vcos_semaphore_wait(&context.semaphore); fprintf(stderr, "Got semaphore\n"); buf = mmal_queue_get(context.queue); mmal_buffer_header_release(buf); } fprintf(stderr, "Got all buffers\n"); mmal_port_pool_destroy(decoder->output[0], pool_out); status = mmal_format_full_copy(decoder->output[0]->format, event->format); CHECK_STATUS(status, "failed to copy port format"); status = mmal_port_format_commit(decoder->output[0]); CHECK_STATUS(status, "failed to commit port format"); pool_out = mmal_port_pool_create(decoder->output[0], decoder->output[0]->buffer_num, decoder->output[0]->buffer_size); status = mmal_port_enable(decoder->output[0], output_callback); CHECK_STATUS(status, "failed to enable port"); //Allow the following loop to send all the buffers back to the decoder } } else fprintf(stderr, "decoded frame (flags %x)\n", buffer->flags); mmal_buffer_header_release(buffer); } /* Send empty buffers to the output port of the decoder */ while ((buffer = mmal_queue_get(pool_out->queue)) != NULL) { status = mmal_port_send_buffer(decoder->output[0], buffer); CHECK_STATUS(status, "failed to send buffer"); } } /* Stop decoding */ fprintf(stderr, "stop decoding - count %d, eos_received %d\n", count, eos_received); /* Stop everything. Not strictly necessary since mmal_component_destroy() * will do that anyway */ mmal_port_disable(decoder->input[0]); mmal_port_disable(decoder->output[0]); mmal_component_disable(decoder); error: /* Cleanup everything */ if (pool_in) mmal_port_pool_destroy(decoder->input[0], pool_in); if (pool_out) mmal_port_pool_destroy(decoder->output[0], pool_out); if (decoder) mmal_component_destroy(decoder); if (context.queue) mmal_queue_destroy(context.queue); SOURCE_CLOSE(); vcos_semaphore_delete(&context.semaphore); return status == MMAL_SUCCESS ? 0 : -1; }
bsd-3-clause
mxOBS/deb-pkg_trusty_chromium-browser
third_party/libc++/trunk/test/input.output/iostream.format/quoted.manip/quoted.pass.cpp
5616
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <iomanip> // quoted #include <iomanip> #include <sstream> #include <string> #include <cassert> #if _LIBCPP_STD_VER > 11 bool is_skipws ( const std::istream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } bool is_skipws ( const std::wistream *is ) { return ( is->flags() & std::ios_base::skipws ) != 0; } void both_ways ( const char *p ) { std::string str(p); auto q = std::quoted(str); std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << q; ss >> q; } void round_trip ( const char *p ) { std::stringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const char *p ) { std::stringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::string s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const char *p, char delim ) { std::stringstream ss; ss << std::quoted(p, delim); std::string s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const char *p, char escape ) { std::stringstream ss; ss << std::quoted(p, '"', escape ); std::string s; ss >> std::quoted(s, '"', escape ); assert ( s == p ); } std::string quote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << std::quoted(p, delim, escape); std::string s; ss >> s; // no quote return s; } std::string unquote ( const char *p, char delim='"', char escape='\\' ) { std::stringstream ss; ss << p; std::string s; ss >> std::quoted(s, delim, escape); return s; } void test_padding () { { std::stringstream ss; ss << std::left << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "`abc`!!!!!" ); } { std::stringstream ss; ss << std::right << std::setw(10) << std::setfill('!') << std::quoted("abc", '`'); assert ( ss.str() == "!!!!!`abc`" ); } } void round_trip ( const wchar_t *p ) { std::wstringstream ss; bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_ws ( const wchar_t *p ) { std::wstringstream ss; std::noskipws ( ss ); bool skippingws = is_skipws ( &ss ); ss << std::quoted(p); std::wstring s; ss >> std::quoted(s); assert ( s == p ); assert ( skippingws == is_skipws ( &ss )); } void round_trip_d ( const wchar_t *p, wchar_t delim ) { std::wstringstream ss; ss << std::quoted(p, delim); std::wstring s; ss >> std::quoted(s, delim); assert ( s == p ); } void round_trip_e ( const wchar_t *p, wchar_t escape ) { std::wstringstream ss; ss << std::quoted(p, wchar_t('"'), escape ); std::wstring s; ss >> std::quoted(s, wchar_t('"'), escape ); assert ( s == p ); } std::wstring quote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << std::quoted(p, delim, escape); std::wstring s; ss >> s; // no quote return s; } std::wstring unquote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) { std::wstringstream ss; ss << p; std::wstring s; ss >> std::quoted(s, delim, escape); return s; } int main() { both_ways ( "" ); // This is a compilation check round_trip ( "" ); round_trip_ws ( "" ); round_trip_d ( "", 'q' ); round_trip_e ( "", 'q' ); round_trip ( L"" ); round_trip_ws ( L"" ); round_trip_d ( L"", 'q' ); round_trip_e ( L"", 'q' ); round_trip ( "Hi" ); round_trip_ws ( "Hi" ); round_trip_d ( "Hi", '!' ); round_trip_e ( "Hi", '!' ); assert ( quote ( "Hi", '!' ) == "!Hi!" ); assert ( quote ( "Hi!", '!' ) == R"(!Hi\!!)" ); round_trip ( L"Hi" ); round_trip_ws ( L"Hi" ); round_trip_d ( L"Hi", '!' ); round_trip_e ( L"Hi", '!' ); assert ( quote ( L"Hi", '!' ) == L"!Hi!" ); assert ( quote ( L"Hi!", '!' ) == LR"(!Hi\!!)" ); round_trip ( "Hi Mom" ); round_trip_ws ( "Hi Mom" ); round_trip ( L"Hi Mom" ); round_trip_ws ( L"Hi Mom" ); assert ( quote ( "" ) == "\"\"" ); assert ( quote ( L"" ) == L"\"\"" ); assert ( quote ( "a" ) == "\"a\"" ); assert ( quote ( L"a" ) == L"\"a\"" ); // missing end quote - must not hang assert ( unquote ( "\"abc" ) == "abc" ); assert ( unquote ( L"\"abc" ) == L"abc" ); assert ( unquote ( "abc" ) == "abc" ); // no delimiter assert ( unquote ( L"abc" ) == L"abc" ); // no delimiter assert ( unquote ( "abc def" ) == "abc" ); // no delimiter assert ( unquote ( L"abc def" ) == L"abc" ); // no delimiter assert ( unquote ( "" ) == "" ); // nothing there assert ( unquote ( L"" ) == L"" ); // nothing there test_padding (); } #else int main() {} #endif
bsd-3-clause
jpetto/olympia
src/olympia/discovery/templates/discovery/modules/go-mobile.html
629
<li class="panel"> <div id="go-mobile" class="feature promo"> <hgroup> <h2>{{ _('Get Add-ons On The Go') }}</h2> </hgroup> <div class="wrap"> <div> <p>{% trans url='http://www.firefox.com/m/' %} Visit <a href="{{ url }}">firefox.com/m</a> to get Firefox on your phone and personalize your browser anytime, anywhere. Easily discover and install add-ons from the mobile Add-ons Manager. {% endtrans %}</p> <p><a href="https://addons.mozilla.org/android/" class="button add">{{ _('Get Mobile Add-ons') }}</a></p> </div> </div> </div> </li>
bsd-3-clause
androidarmv6/android_external_chromium_org
components/wifi/wifi_service.h
6323
// 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_UTILITY_WIFI_WIFI_SERVICE_H_ #define CHROME_UTILITY_WIFI_WIFI_SERVICE_H_ #include <list> #include <string> #include <vector> #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop_proxy.h" #include "base/threading/sequenced_worker_pool.h" #include "base/values.h" #include "components/wifi/wifi_export.h" namespace wifi { // WiFiService interface used by implementation of chrome.networkingPrivate // JavaScript extension API. All methods should be called on worker thread. // It could be created on any (including UI) thread, so nothing expensive should // be done in the constructor. class WIFI_EXPORT WiFiService { public: typedef std::vector<std::string> NetworkGuidList; typedef base::Callback< void(const NetworkGuidList& network_guid_list)> NetworkGuidListCallback; virtual ~WiFiService() {} // Initialize WiFiService, store |task_runner| for posting worker tasks. virtual void Initialize( scoped_refptr<base::SequencedTaskRunner> task_runner) = 0; // UnInitialize WiFiService. virtual void UnInitialize() = 0; // Create instance of |WiFiService| for normal use. static WiFiService* Create(); // Create instance of |WiFiService| for unit test use. static WiFiService* CreateForTest(); // Get Properties of network identified by |network_guid|. Populates // |properties| on success, |error| on failure. virtual void GetProperties(const std::string& network_guid, DictionaryValue* properties, std::string* error) = 0; // Gets the merged properties of the network with id |network_guid| from the // sources: User settings, shared settings, user policy, device policy and // the currently active settings. Populates |managed_properties| on success, // |error| on failure. virtual void GetManagedProperties(const std::string& network_guid, DictionaryValue* managed_properties, std::string* error) = 0; // Get the cached read-only properties of the network with id |network_guid|. // This is meant to be a higher performance function than |GetProperties|, // which requires a round trip to query the networking subsystem. It only // returns a subset of the properties returned by |GetProperties|. Populates // |properties| on success, |error| on failure. virtual void GetState(const std::string& network_guid, DictionaryValue* properties, std::string* error) = 0; // Set Properties of network identified by |network_guid|. Populates |error| // on failure. virtual void SetProperties(const std::string& network_guid, scoped_ptr<base::DictionaryValue> properties, std::string* error) = 0; // Creates a new network configuration from |properties|. If |shared| is true, // share this network configuration with other users. If a matching configured // network already exists, this will fail and populate |error|. On success // populates the |network_guid| of the new network. virtual void CreateNetwork(bool shared, scoped_ptr<base::DictionaryValue> properties, std::string* network_guid, std::string* error) = 0; // Get list of visible networks of |network_type| (one of onc::network_type). // Populates |network_list| on success. virtual void GetVisibleNetworks(const std::string& network_type, ListValue* network_list) = 0; // Request network scan. Send |NetworkListChanged| event on completion. virtual void RequestNetworkScan() = 0; // Start connect to network identified by |network_guid|. Populates |error| // on failure. virtual void StartConnect(const std::string& network_guid, std::string* error) = 0; // Start disconnect from network identified by |network_guid|. Populates // |error| on failure. virtual void StartDisconnect(const std::string& network_guid, std::string* error) = 0; // Set observers to run when |NetworksChanged| and |NetworksListChanged| // events needs to be sent. Notifications are posted on |message_loop_proxy|. virtual void SetEventObservers( scoped_refptr<base::MessageLoopProxy> message_loop_proxy, const NetworkGuidListCallback& networks_changed_observer, const NetworkGuidListCallback& network_list_changed_observer) = 0; protected: WiFiService() {} typedef int32 Frequency; enum FrequencyEnum { kFrequencyAny = 0, kFrequencyUnknown = 0, kFrequency2400 = 2400, kFrequency5000 = 5000 }; typedef std::list<Frequency> FrequencyList; // Network Properties, used as result of |GetProperties| and // |GetVisibleNetworks|. struct WIFI_EXPORT NetworkProperties { NetworkProperties(); ~NetworkProperties(); std::string connection_state; std::string guid; std::string name; std::string ssid; std::string bssid; std::string type; std::string security; // |password| field is used to pass wifi password for network creation via // |CreateNetwork| or connection via |StartConnect|. It does not persist // once operation is completed. std::string password; // WiFi Signal Strength. 0..100 uint32 signal_strength; bool auto_connect; Frequency frequency; FrequencyList frequency_list; std::string json_extra; // Extra JSON properties for unit tests scoped_ptr<base::DictionaryValue> ToValue(bool network_list) const; // Updates only properties set in |value|. bool UpdateFromValue(const base::DictionaryValue& value); static std::string MacAddressAsString(const uint8 mac_as_int[6]); static bool OrderByType(const NetworkProperties& l, const NetworkProperties& r); }; typedef std::list<NetworkProperties> NetworkList; private: DISALLOW_COPY_AND_ASSIGN(WiFiService); }; } // namespace wifi #endif // CHROME_UTILITY_WIFI_WIFI_SERVICE_H_
bsd-3-clause
PeterDaveHello/jsdelivr
files/planck/0.1.34/planck-with-testbed.js
464606
/* * Planck.js v0.1.34 * * Copyright (c) 2016-2017 Ali Shakiba http://shakiba.me/planck.js * Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /* * Stage.js * * @copyright 2017 Ali Shakiba http://shakiba.me/stage.js * @license The MIT License */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.planck=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var planck = require("../lib/"); var Stage = require("stage-js/platform/web"); module.exports = planck; planck.testbed = function(opts, callback) { if (typeof opts === "function") { callback = opts; opts = null; } Stage(function(stage, canvas) { stage.on(Stage.Mouse.START, function() { window.focus(); document.activeElement && document.activeElement.blur(); canvas.focus(); }); stage.MAX_ELAPSE = 1e3 / 30; var Vec2 = planck.Vec2; var testbed = {}; var paused = false; stage.on("resume", function() { paused = false; testbed._resume && testbed._resume(); }); stage.on("pause", function() { paused = true; testbed._pause && testbed._pause(); }); testbed.isPaused = function() { return paused; }; testbed.togglePause = function() { paused ? testbed.play() : testbed.pause(); }; testbed.pause = function() { stage.pause(); }; testbed.resume = function() { stage.resume(); testbed.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.focus = function() { document.activeElement && document.activeElement.blur(); canvas.focus(); }; testbed.debug = false; testbed.width = 80; testbed.height = 60; testbed.x = 0; testbed.y = -10; testbed.ratio = 16; testbed.hz = 60; testbed.speed = 1; testbed.activeKeys = {}; testbed.background = "#222222"; var statusText = ""; var statusMap = {}; function statusSet(name, value) { if (typeof value !== "function" && typeof value !== "object") { statusMap[name] = value; } } function statusMerge(obj) { for (var key in obj) { statusSet(key, obj[key]); } } testbed.status = function(a, b) { if (typeof b !== "undefined") { statusSet(a, b); } else if (a && typeof a === "object") { statusMerge(a); } else if (typeof a === "string") { statusText = a; } testbed._status && testbed._status(statusText, statusMap); }; testbed.info = function(text) { testbed._info && testbed._info(text); }; var lastDrawHash = "", drawHash = ""; (function() { var drawingTexture = new Stage.Texture(); stage.append(Stage.image(drawingTexture)); var buffer = []; stage.tick(function() { buffer.length = 0; }, true); drawingTexture.draw = function(ctx) { ctx.save(); ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y); ctx.lineWidth = 2 / testbed.ratio; ctx.lineCap = "round"; for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) { drawing(ctx, testbed.ratio); } ctx.restore(); }; testbed.drawPoint = function(p, r, color) { buffer.push(function(ctx, ratio) { ctx.beginPath(); ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "point" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawCircle = function(p, r, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, 2 * Math.PI); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color; }; testbed.drawSegment = function(a, b, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.strokeStyle = color; ctx.stroke(); }); drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color; }; testbed.drawPolygon = function(points, color) { if (!points || !points.length) { return; } buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); for (var i = 1; i < points.length; i++) { ctx.lineTo(points[i].x, points[i].y); } ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "segment"; for (var i = 1; i < points.length; i++) { drawHash += points[i].x + "," + points[i].y + ","; } drawHash += color; }; testbed.drawAABB = function(aabb, color) { buffer.push(function(ctx) { ctx.beginPath(); ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y); ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y); ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y); ctx.strokeStyle = color; ctx.closePath(); ctx.stroke(); }); drawHash += "aabb"; drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ","; drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ","; drawHash += color; }; testbed.color = function(r, g, b) { r = r * 256 | 0; g = g * 256 | 0; b = b * 256 | 0; return "rgb(" + r + ", " + g + ", " + b + ")"; }; })(); var world = callback(testbed); var viewer = new Viewer(world, testbed); var lastX = 0, lastY = 0; stage.tick(function(dt, t) { if (lastX !== testbed.x || lastY !== testbed.y) { viewer.offset(-testbed.x, -testbed.y); lastX = testbed.x, lastY = testbed.y; } }); viewer.tick(function(dt, t) { if (typeof testbed.step === "function") { testbed.step(dt, t); } if (targetBody) { testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)"); } if (lastDrawHash !== drawHash) { lastDrawHash = drawHash; stage.touch(); } drawHash = ""; return true; }); viewer.scale(1, -1); stage.background(testbed.background); stage.viewbox(testbed.width, testbed.height); stage.pin("alignX", -.5); stage.pin("alignY", -.5); stage.prepend(viewer); function findBody(point) { var body; var aabb = planck.AABB(point, point); world.queryAABB(aabb, function(fixture) { if (body) { return; } if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) { return; } body = fixture.getBody(); return true; }); return body; } var mouseGround = world.createBody(); var mouseJoint; var targetBody; var mouseMove = { x: 0, y: 0 }; viewer.attr("spy", true).on(Stage.Mouse.START, function(point) { if (targetBody) { return; } var body = findBody(point); if (!body) { return; } if (testbed.mouseForce) { targetBody = body; } else { mouseJoint = planck.MouseJoint({ maxForce: 1e3 }, mouseGround, body, Vec2(point)); world.createJoint(mouseJoint); } }).on(Stage.Mouse.MOVE, function(point) { if (mouseJoint) { mouseJoint.setTarget(point); } mouseMove.x = point.x; mouseMove.y = point.y; }).on(Stage.Mouse.END, function(point) { if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { var force = Vec2.sub(point, targetBody.getPosition()); targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true); targetBody = null; } }).on(Stage.Mouse.CANCEL, function(point) { if (mouseJoint) { world.destroyJoint(mouseJoint); mouseJoint = null; } if (targetBody) { targetBody = null; } }); window.addEventListener("keydown", function(e) { switch (e.keyCode) { case "P".charCodeAt(0): testbed.togglePause(); break; } }, false); var downKeys = {}; window.addEventListener("keydown", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = true; updateActiveKeys(keyCode, true); testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode)); }); window.addEventListener("keyup", function(e) { var keyCode = e.keyCode; downKeys[keyCode] = false; updateActiveKeys(keyCode, false); testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode)); }); var activeKeys = testbed.activeKeys; function updateActiveKeys(keyCode, down) { var char = String.fromCharCode(keyCode); if (/\w/.test(char)) { activeKeys[char] = down; } activeKeys.right = downKeys[39] || activeKeys["D"]; activeKeys.left = downKeys[37] || activeKeys["A"]; activeKeys.up = downKeys[38] || activeKeys["W"]; activeKeys.down = downKeys[40] || activeKeys["S"]; activeKeys.fire = downKeys[32] || downKeys[13]; } }); }; Viewer._super = Stage; Viewer.prototype = Stage._create(Viewer._super.prototype); function Viewer(world, opts) { Viewer._super.call(this); this.label("Planck"); opts = opts || {}; var options = this._options = {}; this._options.speed = opts.speed || 1; this._options.hz = opts.hz || 60; if (Math.abs(this._options.hz) < 1) { this._options.hz = 1 / this._options.hz; } this._options.ratio = opts.ratio || 16; this._options.lineWidth = 2 / this._options.ratio; this._world = world; var timeStep = 1 / this._options.hz; var elapsedTime = 0; this.tick(function(dt) { dt = dt * .001 * options.speed; elapsedTime += dt; while (elapsedTime > timeStep) { world.step(timeStep); elapsedTime -= timeStep; } this.renderWorld(); return true; }, true); world.on("remove-fixture", function(obj) { obj.ui && obj.ui.remove(); }); world.on("remove-joint", function(obj) { obj.ui && obj.ui.remove(); }); } Viewer.prototype.renderWorld = function(world) { var world = this._world; var viewer = this; for (var b = world.getBodyList(); b; b = b.getNext()) { for (var f = b.getFixtureList(); f; f = f.getNext()) { if (!f.ui) { if (f.render && f.render.stroke) { this._options.strokeStyle = f.render.stroke; } else if (b.render && b.render.stroke) { this._options.strokeStyle = b.render.stroke; } else if (b.isDynamic()) { this._options.strokeStyle = "rgba(255,255,255,0.9)"; } else if (b.isKinematic()) { this._options.strokeStyle = "rgba(255,255,255,0.7)"; } else if (b.isStatic()) { this._options.strokeStyle = "rgba(255,255,255,0.5)"; } if (f.render && f.render.fill) { this._options.fillStyle = f.render.fill; } else if (b.render && b.render.fill) { this._options.fillStyle = b.render.fill; } else { this._options.fillStyle = ""; } var type = f.getType(); var shape = f.getShape(); if (type == "circle") { f.ui = viewer.drawCircle(shape, this._options); } if (type == "edge") { f.ui = viewer.drawEdge(shape, this._options); } if (type == "polygon") { f.ui = viewer.drawPolygon(shape, this._options); } if (type == "chain") { f.ui = viewer.drawChain(shape, this._options); } if (f.ui) { f.ui.appendTo(viewer); } } if (f.ui) { var p = b.getPosition(), r = b.getAngle(); if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) { f.ui.__lastX = p.x; f.ui.__lastY = p.y; f.ui.__lastR = r; f.ui.offset(p.x, p.y); f.ui.rotate(r); } } } } for (var j = world.getJointList(); j; j = j.getNext()) { var type = j.getType(); var a = j.getAnchorA(); var b = j.getAnchorB(); if (!j.ui) { this._options.strokeStyle = "rgba(255,255,255,0.2)"; j.ui = viewer.drawJoint(j, this._options); j.ui.pin("handle", .5); if (j.ui) { j.ui.appendTo(viewer); } } if (j.ui) { var cx = (a.x + b.x) * .5; var cy = (a.y + b.y) * .5; var dx = a.x - b.x; var dy = a.y - b.y; var d = Math.sqrt(dx * dx + dy * dy); j.ui.width(d); j.ui.rotate(Math.atan2(dy, dx)); j.ui.offset(cx, cy); } } }; Viewer.prototype.drawJoint = function(joint, options) { var lw = options.lineWidth; var ratio = options.ratio; var length = 10; var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).stretch(); return image; }; Viewer.prototype.drawCircle = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var r = shape.m_radius; var cx = r + lw; var cy = r + lw; var w = r * 2 + lw * 2; var h = r * 2 + lw * 2; var texture = Stage.canvas(function(ctx) { this.size(w, h, ratio); ctx.scale(ratio, ratio); ctx.arc(cx, cy, r, 0, 2 * Math.PI); if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); } ctx.lineTo(cx, cy); ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture).offset(shape.m_p.x - cx, shape.m_p.y - cy); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawEdge = function(edge, options) { var lw = options.lineWidth; var ratio = options.ratio; var v1 = edge.m_vertex1; var v2 = edge.m_vertex2; var dx = v2.x - v1.x; var dy = v2.y - v1.y; var length = Math.sqrt(dx * dx + dy * dy); var texture = Stage.canvas(function(ctx) { this.size(length + 2 * lw, 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); ctx.moveTo(lw, lw); ctx.lineTo(lw + length, lw); ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var minX = Math.min(v1.x, v2.x); var minY = Math.min(v1.y, v2.y); var image = Stage.image(texture); image.rotate(Math.atan2(dy, dx)); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawPolygon = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) { ctx.closePath(); } if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; Viewer.prototype.drawChain = function(shape, options) { var lw = options.lineWidth; var ratio = options.ratio; var vertices = shape.m_vertices; if (!vertices.length) { return; } var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } var width = maxX - minX; var height = maxY - minY; var texture = Stage.canvas(function(ctx) { this.size(width + 2 * lw, height + 2 * lw, ratio); ctx.scale(ratio, ratio); ctx.beginPath(); for (var i = 0; i < vertices.length; ++i) { var v = vertices[i]; var x = v.x - minX + lw; var y = v.y - minY + lw; if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (vertices.length > 2) {} if (options.fillStyle) { ctx.fillStyle = options.fillStyle; ctx.fill(); ctx.closePath(); } ctx.lineCap = "round"; ctx.lineWidth = options.lineWidth; ctx.strokeStyle = options.strokeStyle; ctx.stroke(); }); var image = Stage.image(texture); image.offset(minX - lw, minY - lw); var node = Stage.create().append(image); return node; }; },{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Body; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var Rot = require("./common/Rot"); var Math = require("./common/Math"); var Sweep = require("./common/Sweep"); var Transform = require("./common/Transform"); var Velocity = require("./common/Velocity"); var Position = require("./common/Position"); var Fixture = require("./Fixture"); var Shape = require("./Shape"); var World = require("./World"); var staticBody = Body.STATIC = "static"; var kinematicBody = Body.KINEMATIC = "kinematic"; var dynamicBody = Body.DYNAMIC = "dynamic"; var BodyDef = { type: staticBody, position: Vec2.zero(), angle: 0, linearVelocity: Vec2.zero(), angularVelocity: 0, linearDamping: 0, angularDamping: 0, fixedRotation: false, bullet: false, gravityScale: 1, allowSleep: true, awake: true, active: true, userData: null }; function Body(world, def) { def = options(def, BodyDef); ASSERT && common.assert(Vec2.isValid(def.position)); ASSERT && common.assert(Vec2.isValid(def.linearVelocity)); ASSERT && common.assert(Math.isFinite(def.angle)); ASSERT && common.assert(Math.isFinite(def.angularVelocity)); ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0); ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0); this.m_world = world; this.m_awakeFlag = def.awake; this.m_autoSleepFlag = def.allowSleep; this.m_bulletFlag = def.bullet; this.m_fixedRotationFlag = def.fixedRotation; this.m_activeFlag = def.active; this.m_islandFlag = false; this.m_toiFlag = false; this.m_userData = def.userData; this.m_type = def.type; if (this.m_type == dynamicBody) { this.m_mass = 1; this.m_invMass = 1; } else { this.m_mass = 0; this.m_invMass = 0; } this.m_I = 0; this.m_invI = 0; this.m_xf = Transform.identity(); this.m_xf.p = Vec2.clone(def.position); this.m_xf.q.setAngle(def.angle); this.m_sweep = new Sweep(); this.m_sweep.setTransform(this.m_xf); this.c_velocity = new Velocity(); this.c_position = new Position(); this.m_force = Vec2.zero(); this.m_torque = 0; this.m_linearVelocity = Vec2.clone(def.linearVelocity); this.m_angularVelocity = def.angularVelocity; this.m_linearDamping = def.linearDamping; this.m_angularDamping = def.angularDamping; this.m_gravityScale = def.gravityScale; this.m_sleepTime = 0; this.m_jointList = null; this.m_contactList = null; this.m_fixtureList = null; this.m_prev = null; this.m_next = null; } Body.prototype.isWorldLocked = function() { return this.m_world && this.m_world.isLocked() ? true : false; }; Body.prototype.getWorld = function() { return this.m_world; }; Body.prototype.getNext = function() { return this.m_next; }; Body.prototype.setUserData = function(data) { this.m_userData = data; }; Body.prototype.getUserData = function() { return this.m_userData; }; Body.prototype.getFixtureList = function() { return this.m_fixtureList; }; Body.prototype.getJointList = function() { return this.m_jointList; }; Body.prototype.getContactList = function() { return this.m_contactList; }; Body.prototype.isStatic = function() { return this.m_type == staticBody; }; Body.prototype.isDynamic = function() { return this.m_type == dynamicBody; }; Body.prototype.isKinematic = function() { return this.m_type == kinematicBody; }; Body.prototype.setStatic = function() { this.setType(staticBody); return this; }; Body.prototype.setDynamic = function() { this.setType(dynamicBody); return this; }; Body.prototype.setKinematic = function() { this.setType(kinematicBody); return this; }; Body.prototype.getType = function() { return this.m_type; }; Body.prototype.setType = function(type) { ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody); ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type == type) { return; } this.m_type = type; this.resetMassData(); if (this.m_type == staticBody) { this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_sweep.forward(); this.synchronizeFixtures(); } this.setAwake(true); this.m_force.setZero(); this.m_torque = 0; var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { var proxyCount = f.m_proxyCount; for (var i = 0; i < proxyCount; ++i) { broadPhase.touchProxy(f.m_proxies[i].proxyId); } } }; Body.prototype.isBullet = function() { return this.m_bulletFlag; }; Body.prototype.setBullet = function(flag) { this.m_bulletFlag = !!flag; }; Body.prototype.isSleepingAllowed = function() { return this.m_autoSleepFlag; }; Body.prototype.setSleepingAllowed = function(flag) { this.m_autoSleepFlag = !!flag; if (this.m_autoSleepFlag == false) { this.setAwake(true); } }; Body.prototype.isAwake = function() { return this.m_awakeFlag; }; Body.prototype.setAwake = function(flag) { if (flag) { if (this.m_awakeFlag == false) { this.m_awakeFlag = true; this.m_sleepTime = 0; } } else { this.m_awakeFlag = false; this.m_sleepTime = 0; this.m_linearVelocity.setZero(); this.m_angularVelocity = 0; this.m_force.setZero(); this.m_torque = 0; } }; Body.prototype.isActive = function() { return this.m_activeFlag; }; Body.prototype.setActive = function(flag) { ASSERT && common.assert(this.isWorldLocked() == false); if (flag == this.m_activeFlag) { return; } this.m_activeFlag = !!flag; if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.createProxies(broadPhase, this.m_xf); } } else { var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.destroyProxies(broadPhase); } var ce = this.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.m_world.destroyContact(ce0.contact); } this.m_contactList = null; } }; Body.prototype.isFixedRotation = function() { return this.m_fixedRotationFlag; }; Body.prototype.setFixedRotation = function(flag) { if (this.m_fixedRotationFlag == flag) { return; } this.m_fixedRotationFlag = !!flag; this.m_angularVelocity = 0; this.resetMassData(); }; Body.prototype.getTransform = function() { return this.m_xf; }; Body.prototype.setTransform = function(position, angle) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } this.m_xf.set(position, angle); this.m_sweep.setTransform(this.m_xf); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, this.m_xf, this.m_xf); } }; Body.prototype.synchronizeTransform = function() { this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.synchronizeFixtures = function() { var xf = Transform.identity(); this.m_sweep.getTransform(xf, 0); var broadPhase = this.m_world.m_broadPhase; for (var f = this.m_fixtureList; f; f = f.m_next) { f.synchronize(broadPhase, xf, this.m_xf); } }; Body.prototype.advance = function(alpha) { this.m_sweep.advance(alpha); this.m_sweep.c.set(this.m_sweep.c0); this.m_sweep.a = this.m_sweep.a0; this.m_sweep.getTransform(this.m_xf, 1); }; Body.prototype.getPosition = function() { return this.m_xf.p; }; Body.prototype.setPosition = function(p) { this.setTransform(p, this.m_sweep.a); }; Body.prototype.getAngle = function() { return this.m_sweep.a; }; Body.prototype.setAngle = function(angle) { this.setTransform(this.m_xf.p, angle); }; Body.prototype.getWorldCenter = function() { return this.m_sweep.c; }; Body.prototype.getLocalCenter = function() { return this.m_sweep.localCenter; }; Body.prototype.getLinearVelocity = function() { return this.m_linearVelocity; }; Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) { var localCenter = Vec2.sub(worldPoint, this.m_sweep.c); return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter)); }; Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) { return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint)); }; Body.prototype.setLinearVelocity = function(v) { if (this.m_type == staticBody) { return; } if (Vec2.dot(v, v) > 0) { this.setAwake(true); } this.m_linearVelocity.set(v); }; Body.prototype.getAngularVelocity = function() { return this.m_angularVelocity; }; Body.prototype.setAngularVelocity = function(w) { if (this.m_type == staticBody) { return; } if (w * w > 0) { this.setAwake(true); } this.m_angularVelocity = w; }; Body.prototype.getLinearDamping = function() { return this.m_linearDamping; }; Body.prototype.setLinearDamping = function(linearDamping) { this.m_linearDamping = linearDamping; }; Body.prototype.getAngularDamping = function() { return this.m_angularDamping; }; Body.prototype.setAngularDamping = function(angularDamping) { this.m_angularDamping = angularDamping; }; Body.prototype.getGravityScale = function() { return this.m_gravityScale; }; Body.prototype.setGravityScale = function(scale) { this.m_gravityScale = scale; }; Body.prototype.getMass = function() { return this.m_mass; }; Body.prototype.getInertia = function() { return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter); }; function MassData() { this.mass = 0; this.center = Vec2.zero(); this.I = 0; } Body.prototype.getMassData = function(data) { data.mass = this.m_mass; data.I = this.getInertia(); data.center.set(this.m_sweep.localCenter); }; Body.prototype.resetMassData = function() { this.m_mass = 0; this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_sweep.localCenter.setZero(); if (this.isStatic() || this.isKinematic()) { this.m_sweep.c0.set(this.m_xf.p); this.m_sweep.c.set(this.m_xf.p); this.m_sweep.a0 = this.m_sweep.a; return; } ASSERT && common.assert(this.isDynamic()); var localCenter = Vec2.zero(); for (var f = this.m_fixtureList; f; f = f.m_next) { if (f.m_density == 0) { continue; } var massData = new MassData(); f.getMassData(massData); this.m_mass += massData.mass; localCenter.wAdd(massData.mass, massData.center); this.m_I += massData.I; } if (this.m_mass > 0) { this.m_invMass = 1 / this.m_mass; localCenter.mul(this.m_invMass); } else { this.m_mass = 1; this.m_invMass = 1; } if (this.m_I > 0 && this.m_fixedRotationFlag == false) { this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter); ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } else { this.m_I = 0; this.m_invI = 0; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(localCenter, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.setMassData = function(massData) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } if (this.m_type != dynamicBody) { return; } this.m_invMass = 0; this.m_I = 0; this.m_invI = 0; this.m_mass = massData.mass; if (this.m_mass <= 0) { this.m_mass = 1; } this.m_invMass = 1 / this.m_mass; if (massData.I > 0 && this.m_fixedRotationFlag == false) { this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center); ASSERT && common.assert(this.m_I > 0); this.m_invI = 1 / this.m_I; } var oldCenter = Vec2.clone(this.m_sweep.c); this.m_sweep.setLocalCenter(massData.center, this.m_xf); this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter))); }; Body.prototype.applyForce = function(force, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force); } }; Body.prototype.applyForceToCenter = function(force, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_force.add(force); } }; Body.prototype.applyTorque = function(torque, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_torque += torque; } }; Body.prototype.applyLinearImpulse = function(impulse, point, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_linearVelocity.wAdd(this.m_invMass, impulse); this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse); } }; Body.prototype.applyAngularImpulse = function(impulse, wake) { if (this.m_type != dynamicBody) { return; } if (wake && this.m_awakeFlag == false) { this.setAwake(true); } if (this.m_awakeFlag) { this.m_angularVelocity += this.m_invI * impulse; } }; Body.prototype.shouldCollide = function(that) { if (this.m_type != dynamicBody && that.m_type != dynamicBody) { return false; } for (var jn = this.m_jointList; jn; jn = jn.next) { if (jn.other == that) { if (jn.joint.m_collideConnected == false) { return false; } } } return true; }; Body.prototype.createFixture = function(shape, fixdef) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return null; } var fixture = new Fixture(this, shape, fixdef); if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.createProxies(broadPhase, this.m_xf); } fixture.m_next = this.m_fixtureList; this.m_fixtureList = fixture; if (fixture.m_density > 0) { this.resetMassData(); } this.m_world.m_newFixture = true; return fixture; }; Body.prototype.destroyFixture = function(fixture) { ASSERT && common.assert(this.isWorldLocked() == false); if (this.isWorldLocked() == true) { return; } ASSERT && common.assert(fixture.m_body == this); var node = this.m_fixtureList; var found = false; while (node != null) { if (node == fixture) { node = fixture.m_next; found = true; break; } node = node.m_next; } ASSERT && common.assert(found); var edge = this.m_contactList; while (edge) { var c = edge.contact; edge = edge.next; var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); if (fixture == fixtureA || fixture == fixtureB) { this.m_world.destroyContact(c); } } if (this.m_activeFlag) { var broadPhase = this.m_world.m_broadPhase; fixture.destroyProxies(broadPhase); } fixture.m_body = null; fixture.m_next = null; this.m_world.publish("remove-fixture", fixture); this.resetMassData(); }; Body.prototype.getWorldPoint = function(localPoint) { return Transform.mul(this.m_xf, localPoint); }; Body.prototype.getWorldVector = function(localVector) { return Rot.mul(this.m_xf.q, localVector); }; Body.prototype.getLocalPoint = function(worldPoint) { return Transform.mulT(this.m_xf, worldPoint); }; Body.prototype.getLocalVector = function(worldVector) { return Rot.mulT(this.m_xf.q, worldVector); }; },{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var DEBUG_SOLVER = false; var common = require("./util/common"); var Math = require("./common/Math"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Mat22 = require("./common/Mat22"); var Rot = require("./common/Rot"); var Settings = require("./Settings"); var Manifold = require("./Manifold"); var Distance = require("./collision/Distance"); module.exports = Contact; function ContactEdge(contact) { this.contact = contact; this.prev; this.next; this.other; } function Contact(fA, indexA, fB, indexB, evaluateFcn) { this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_manifold = new Manifold(); this.m_prev = null; this.m_next = null; this.m_toi = 1; this.m_toiCount = 0; this.m_toiFlag = false; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); this.m_tangentSpeed = 0; this.m_enabledFlag = true; this.m_islandFlag = false; this.m_touchingFlag = false; this.m_filterFlag = false; this.m_bulletHitFlag = false; this.v_points = []; this.v_normal = Vec2.zero(); this.v_normalMass = new Mat22(); this.v_K = new Mat22(); this.v_pointCount; this.v_tangentSpeed; this.v_friction; this.v_restitution; this.v_invMassA; this.v_invMassB; this.v_invIA; this.v_invIB; this.p_localPoints = []; this.p_localNormal = Vec2.zero(); this.p_localPoint = Vec2.zero(); this.p_localCenterA = Vec2.zero(); this.p_localCenterB = Vec2.zero(); this.p_type; this.p_radiusA; this.p_radiusB; this.p_pointCount; this.p_invMassA; this.p_invMassB; this.p_invIA; this.p_invIB; } Contact.prototype.initConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var manifold = this.getManifold(); var pointCount = manifold.pointCount; ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; DEBUG && common.debug("pc", this.v_pointCount, pointCount); this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA = Vec2.clone(bodyA.m_sweep.localCenter); this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal = Vec2.clone(manifold.localNormal); this.p_localPoint = Vec2.clone(manifold.localPoint); this.p_pointCount = pointCount; for (var j = 0; j < pointCount; ++j) { var cp = manifold.points[j]; var vcp = this.v_points[j] = new VelocityConstraintPoint(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0; vcp.tangentImpulse = 0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0; vcp.tangentMass = 0; vcp.velocityBias = 0; this.p_localPoints[j] = Vec2.clone(cp.localPoint); } }; Contact.prototype.getManifold = function() { return this.m_manifold; }; Contact.prototype.getWorldManifold = function(worldManifold) { var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); }; Contact.prototype.setEnabled = function(flag) { this.m_enabledFlag = !!flag; }; Contact.prototype.isEnabled = function() { return this.m_enabledFlag; }; Contact.prototype.isTouching = function() { return this.m_touchingFlag; }; Contact.prototype.getNext = function() { return this.m_next; }; Contact.prototype.getFixtureA = function() { return this.m_fixtureA; }; Contact.prototype.getFixtureB = function() { return this.m_fixtureB; }; Contact.prototype.getChildIndexA = function() { return this.m_indexA; }; Contact.prototype.getChildIndexB = function() { return this.m_indexB; }; Contact.prototype.flagForFiltering = function() { this.m_filterFlag = true; }; Contact.prototype.setFriction = function(friction) { this.m_friction = friction; }; Contact.prototype.getFriction = function() { return this.m_friction; }; Contact.prototype.resetFriction = function() { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); }; Contact.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Contact.prototype.getRestitution = function() { return this.m_restitution; }; Contact.prototype.resetRestitution = function() { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); }; Contact.prototype.setTangentSpeed = function(speed) { this.m_tangentSpeed = speed; }; Contact.prototype.getTangentSpeed = function() { return this.m_tangentSpeed; }; Contact.prototype.evaluate = function(manifold, xfA, xfB) { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); }; Contact.prototype.update = function(listener) { this.m_enabledFlag = true; var touching = false; var wasTouching = this.m_touchingFlag; var sensorA = this.m_fixtureA.isSensor(); var sensorB = this.m_fixtureB.isSensor(); var sensor = sensorA || sensorB; var bodyA = this.m_fixtureA.getBody(); var bodyB = this.m_fixtureB.getBody(); var xfA = bodyA.getTransform(); var xfB = bodyB.getTransform(); if (sensor) { var shapeA = this.m_fixtureA.getShape(); var shapeB = this.m_fixtureB.getShape(); touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); this.m_manifold.pointCount = 0; } else { var oldManifold = this.m_manifold; this.m_manifold = new Manifold(); this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; for (var i = 0; i < this.m_manifold.pointCount; ++i) { var nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0; nmp.tangentImpulse = 0; for (var j = 0; j < oldManifold.pointCount; ++j) { var omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (wasTouching == false && touching == true && listener) { listener.beginContact(this); } if (wasTouching == true && touching == false && listener) { listener.endContact(this); } if (sensor == false && touching && listener) { listener.preSolve(this, oldManifold); } }; Contact.prototype.solvePositionConstraint = function(step) { return this._solvePositionConstraint(step, false); }; Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) { return this._solvePositionConstraint(step, true, toiA, toiB); }; Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var mA = 0; var iA = 0; if (!toi || (bodyA == toiA || bodyA == toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } var mB = 0; var iB = 0; if (!toi || (bodyB == toiA || bodyB == toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } var cA = Vec2.clone(positionA.c); var aA = positionA.a; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var minSeparation = 0; for (var j = 0; j < this.p_pointCount; ++j) { var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p = Vec2.sub(cA, Rot.mul(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mul(xfB.q, localCenterB)); var normal, point, separation; switch (this.p_type) { case Manifold.e_circles: var pointA = Transform.mul(xfA, this.p_localPoint); var pointB = Transform.mul(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.wAdd(.5, pointA, .5, pointB); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.p_localNormal); var planePoint = Transform.mul(xfA, this.p_localPoint); var clipPoint = Transform.mul(xfB, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.p_localNormal); var planePoint = Transform.mul(xfB, this.p_localPoint); var clipPoint = Transform.mul(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; normal.mul(-1); break; } var rA = Vec2.sub(point, cA); var rB = Vec2.sub(point, cB); minSeparation = Math.min(minSeparation, separation); var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0); var rnA = Vec2.cross(rA, normal); var rnB = Vec2.cross(rB, normal); var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; var impulse = K > 0 ? -C / K : 0; var P = Vec2.mul(impulse, normal); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(cB); positionB.a = aB; return minSeparation; }; function VelocityConstraintPoint() { this.rA = Vec2.zero(); this.rB = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.normalMass = 0; this.tangentMass = 0; this.velocityBias = 0; } Contact.prototype.initVelocityConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var radiusA = this.p_radiusA; var radiusB = this.p_radiusB; var manifold = this.getManifold(); var mA = this.v_invMassA; var mB = this.v_invMassB; var iA = this.v_invIA; var iB = this.v_invIB; var localCenterA = Vec2.clone(this.p_localCenterA); var localCenterB = Vec2.clone(this.p_localCenterB); var cA = Vec2.clone(positionA.c); var aA = positionA.a; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var cB = Vec2.clone(positionB.c); var aB = positionB.a; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; ASSERT && common.assert(manifold.pointCount > 0); var xfA = Transform.identity(); var xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.wSet(1, cA, -1, Rot.mul(xfA.q, localCenterA)); xfB.p.wSet(1, cB, -1, Rot.mul(xfB.q, localCenterB)); var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; vcp.rA.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); DEBUG && common.debug("vcp.rA", worldManifold.points[j].x, worldManifold.points[j].y, cA.x, cA.y, vcp.rA.x, vcp.rA.y); var rnA = Vec2.cross(vcp.rA, this.v_normal); var rnB = Vec2.cross(vcp.rB, this.v_normal); var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0; var tangent = Vec2.cross(this.v_normal, 1); var rtA = Vec2.cross(vcp.rA, tangent); var rtB = Vec2.cross(vcp.rB, tangent); var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0; vcp.velocityBias = 0; var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } if (this.v_pointCount == 2 && step.blockSolve) { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var rn1A = Vec2.cross(vcp1.rA, this.v_normal); var rn1B = Vec2.cross(vcp1.rB, this.v_normal); var rn2A = Vec2.cross(vcp2.rA, this.v_normal); var rn2B = Vec2.cross(vcp2.rB, this.v_normal); var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; var k_maxConditionNumber = 1e3; DEBUG && common.debug("k1x2: ", k11, k22, k12, mA, mB, iA, rn1A, rn2A, iB, rn1B, rn2B); if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.warmStartConstraint = function(step) { var fixtureA = this.m_fixtureA; var fixtureB = this.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); var velocityA = bodyA.c_velocity; var velocityB = bodyB.c_velocity; var positionA = bodyA.c_position; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var P = Vec2.wAdd(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); DEBUG && common.debug(iA, iB, vcp.rA.x, vcp.rA.y, vcp.rB.x, vcp.rB.y, P.x, P.y); wA -= iA * Vec2.cross(vcp.rA, P); vA.wSub(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.wAdd(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; Contact.prototype.storeConstraintImpulses = function(step) { var manifold = this.m_manifold; for (var j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } }; Contact.prototype.solveVelocityConstraint = function(step) { var bodyA = this.m_fixtureA.m_body; var bodyB = this.m_fixtureB.m_body; var velocityA = bodyA.c_velocity; var positionA = bodyA.c_position; var velocityB = bodyB.c_velocity; var positionB = bodyB.c_position; var mA = this.v_invMassA; var iA = this.v_invIA; var mB = this.v_invMassB; var iB = this.v_invIB; var vA = Vec2.clone(velocityA.v); var wA = velocityA.w; var vB = Vec2.clone(velocityB.v); var wB = velocityB.w; var normal = this.v_normal; var tangent = Vec2.cross(normal, 1); var friction = this.v_friction; ASSERT && common.assert(this.v_pointCount == 1 || this.v_pointCount == 2); for (var j = 0; j < this.v_pointCount; ++j) { var vcp = this.v_points[j]; var dv = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; var lambda = vcp.tangentMass * -vt; var maxFriction = friction * vcp.normalImpulse; var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; var P = Vec2.mul(lambda, tangent); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } if (this.v_pointCount == 1 || step.blockSolve == false) { for (var i = 0; i < this.v_pointCount; ++i) { var vcp = this.v_points[i]; var dv = Vec2.zero(); dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA)); var vn = Vec2.dot(dv, normal); var lambda = -vcp.normalMass * (vn - vcp.velocityBias); var newImpulse = Math.max(vcp.normalImpulse + lambda, 0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; var P = Vec2.mul(lambda, normal); vA.wSub(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { var vcp1 = this.v_points[0]; var vcp2 = this.v_points[1]; var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); ASSERT && common.assert(a.x >= 0 && a.y >= 0); var dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA)); var dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA)); var vn1 = Vec2.dot(dv1, normal); var vn2 = Vec2.dot(dv2, normal); var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); b.sub(Mat22.mul(this.v_K, a)); var k_errorTol = .001; for (;;) { var x = Vec2.neg(Mat22.mul(this.v_normalMass, b)); if (x.x >= 0 && x.y >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA); dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA); vn1 = Dot(dv1, normal); vn2 = Dot(dv2, normal); ASSERT && common.assert(Abs(vn1 - vcp1.velocityBias) < k_errorTol); ASSERT && common.assert(Abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = -vcp1.normalMass * b.x; x.y = 0; vn1 = 0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); var dv1 = Vec2.sub(dv1B, dv1A); vn1 = Vec2.dot(dv1, normal); ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0; if (x.y >= 0 && vn1 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); var dv1 = Vec2.sub(dv2B, dv2A); vn2 = Vec2.dot(dv2, normal); ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } x.x = 0; x.y = 0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0 && vn2 >= 0) { var d = Vec2.sub(x, a); var P1 = Vec2.mul(d.x, normal); var P2 = Vec2.mul(d.y, normal); vA.wSub(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.wAdd(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; }; function mixFriction(friction1, friction2) { return Math.sqrt(friction1 * friction2); } function mixRestitution(restitution1, restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } var s_registers = []; Contact.addType = function(type1, type2, callback) { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; }; Contact.create = function(fixtureA, indexA, fixtureB, indexB) { var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var contact, evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = new Contact(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; if (fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; }; Contact.destroy = function(contact, listener) { var fixtureA = contact.m_fixtureA; var fixtureB = contact.m_fixtureB; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } var typeA = fixtureA.getType(); var typeB = fixtureB.getType(); var destroyFcn = s_registers[typeA][typeB].destroyFcn; if (typeof destroyFcn === "function") { destroyFcn(contact); } }; },{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],4:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Fixture; var common = require("./util/common"); var options = require("./util/options"); var Vec2 = require("./common/Vec2"); var AABB = require("./collision/AABB"); var FixtureDef = { userData: null, friction: .2, restitution: 0, density: 0, isSensor: false, filterGroupIndex: 0, filterCategoryBits: 1, filterMaskBits: 65535 }; function FixtureProxy(fixture, childIndex) { this.aabb = new AABB(); this.fixture = fixture; this.childIndex = childIndex; this.proxyId; } function Fixture(body, shape, def) { if (shape.shape) { def = shape; shape = shape.shape; } else if (typeof def === "number") { def = { density: def }; } def = options(def, FixtureDef); this.m_body = body; this.m_friction = def.friction; this.m_restitution = def.restitution; this.m_density = def.density; this.m_isSensor = def.isSensor; this.m_filterGroupIndex = def.filterGroupIndex; this.m_filterCategoryBits = def.filterCategoryBits; this.m_filterMaskBits = def.filterMaskBits; this.m_shape = shape; this.m_next = null; this.m_proxies = []; this.m_proxyCount = 0; var childCount = this.m_shape.getChildCount(); for (var i = 0; i < childCount; ++i) { this.m_proxies[i] = new FixtureProxy(this, i); } this.m_userData = def.userData; } Fixture.prototype.getType = function() { return this.m_shape.getType(); }; Fixture.prototype.getShape = function() { return this.m_shape; }; Fixture.prototype.isSensor = function() { return this.m_isSensor; }; Fixture.prototype.setSensor = function(sensor) { if (sensor != this.m_isSensor) { this.m_body.setAwake(true); this.m_isSensor = sensor; } }; Fixture.prototype.getUserData = function() { return this.m_userData; }; Fixture.prototype.setUserData = function(data) { this.m_userData = data; }; Fixture.prototype.getBody = function() { return this.m_body; }; Fixture.prototype.getNext = function() { return this.m_next; }; Fixture.prototype.getDensity = function() { return this.m_density; }; Fixture.prototype.setDensity = function(density) { ASSERT && common.assert(Math.isFinite(density) && density >= 0); this.m_density = density; }; Fixture.prototype.getFriction = function() { return this.m_friction; }; Fixture.prototype.setFriction = function(friction) { this.m_friction = friction; }; Fixture.prototype.getRestitution = function() { return this.m_restitution; }; Fixture.prototype.setRestitution = function(restitution) { this.m_restitution = restitution; }; Fixture.prototype.testPoint = function(p) { return this.m_shape.testPoint(this.m_body.getTransform(), p); }; Fixture.prototype.rayCast = function(output, input, childIndex) { return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex); }; Fixture.prototype.getMassData = function(massData) { this.m_shape.computeMass(massData, this.m_density); }; Fixture.prototype.getAABB = function(childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount); return this.m_proxies[childIndex].aabb; }; Fixture.prototype.createProxies = function(broadPhase, xf) { ASSERT && common.assert(this.m_proxyCount == 0); this.m_proxyCount = this.m_shape.getChildCount(); for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; this.m_shape.computeAABB(proxy.aabb, xf, i); proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy); } }; Fixture.prototype.destroyProxies = function(broadPhase) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; broadPhase.destroyProxy(proxy.proxyId); proxy.proxyId = null; } this.m_proxyCount = 0; }; Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) { for (var i = 0; i < this.m_proxyCount; ++i) { var proxy = this.m_proxies[i]; var aabb1 = new AABB(); var aabb2 = new AABB(); this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex); this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex); proxy.aabb.combine(aabb1, aabb2); var displacement = Vec2.sub(xf2.p, xf1.p); broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement); } }; Fixture.prototype.setFilterData = function(filter) { this.m_filterGroupIndex = filter.groupIndex; this.m_filterCategoryBits = filter.categoryBits; this.m_filterMaskBits = filter.maskBits; this.refilter(); }; Fixture.prototype.getFilterGroupIndex = function() { return this.m_filterGroupIndex; }; Fixture.prototype.getFilterCategoryBits = function() { return this.m_filterCategoryBits; }; Fixture.prototype.getFilterMaskBits = function() { return this.m_filterMaskBits; }; Fixture.prototype.refilter = function() { if (this.m_body == null) { return; } var edge = this.m_body.getContactList(); while (edge) { var contact = edge.contact; var fixtureA = contact.getFixtureA(); var fixtureB = contact.getFixtureB(); if (fixtureA == this || fixtureB == this) { contact.flagForFiltering(); } edge = edge.next; } var world = this.m_body.getWorld(); if (world == null) { return; } var broadPhase = world.m_broadPhase; for (var i = 0; i < this.m_proxyCount; ++i) { broadPhase.touchProxy(this.m_proxies[i].proxyId); } }; Fixture.prototype.shouldCollide = function(that) { if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) { return that.m_filterGroupIndex > 0; } var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0; return collide; }; },{"./collision/AABB":11,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Joint; var common = require("./util/common"); function JointEdge() { this.other = null; this.joint = null; this.prev = null; this.next = null; } var JointDef = { userData: null, collideConnected: false }; function Joint(def, bodyA, bodyB) { bodyA = def.bodyA || bodyA; bodyB = def.bodyB || bodyB; ASSERT && common.assert(bodyA); ASSERT && common.assert(bodyB); ASSERT && common.assert(bodyA != bodyB); this.m_type = "unknown-joint"; this.m_bodyA = bodyA; this.m_bodyB = bodyB; this.m_index = 0; this.m_collideConnected = !!def.collideConnected; this.m_prev = null; this.m_next = null; this.m_edgeA = new JointEdge(); this.m_edgeB = new JointEdge(); this.m_islandFlag = false; this.m_userData = def.userData; } Joint.prototype.isActive = function() { return this.m_bodyA.isActive() && this.m_bodyB.isActive(); }; Joint.prototype.getType = function() { return this.m_type; }; Joint.prototype.getBodyA = function() { return this.m_bodyA; }; Joint.prototype.getBodyB = function() { return this.m_bodyB; }; Joint.prototype.getNext = function() { return this.m_next; }; Joint.prototype.getUserData = function() { return this.m_userData; }; Joint.prototype.setUserData = function(data) { this.m_userData = data; }; Joint.prototype.getCollideConnected = function() { return this.m_collideConnected; }; Joint.prototype.getAnchorA = function() {}; Joint.prototype.getAnchorB = function() {}; Joint.prototype.getReactionForce = function(inv_dt) {}; Joint.prototype.getReactionTorque = function(inv_dt) {}; Joint.prototype.shiftOrigin = function(newOrigin) {}; Joint.prototype.initVelocityConstraints = function(step) {}; Joint.prototype.solveVelocityConstraints = function(step) {}; Joint.prototype.solvePositionConstraints = function(step) {}; },{"./util/common":51}],6:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("./util/common"); var Vec2 = require("./common/Vec2"); var Transform = require("./common/Transform"); var Math = require("./common/Math"); var Rot = require("./common/Rot"); module.exports = Manifold; module.exports.clipSegmentToLine = clipSegmentToLine; module.exports.clipVertex = ClipVertex; module.exports.getPointStates = getPointStates; module.exports.PointState = PointState; Manifold.e_circles = 0; Manifold.e_faceA = 1; Manifold.e_faceB = 2; Manifold.e_vertex = 0; Manifold.e_face = 1; function Manifold() { this.type; this.localNormal = Vec2.zero(); this.localPoint = Vec2.zero(); this.points = [ new ManifoldPoint(), new ManifoldPoint() ]; this.pointCount = 0; } function ManifoldPoint() { this.localPoint = Vec2.zero(); this.normalImpulse = 0; this.tangentImpulse = 0; this.id = new ContactID(); } function ContactID() { this.cf = new ContactFeature(); this.key; } ContactID.prototype.set = function(o) { this.key = o.key; this.cf.set(o.cf); }; function ContactFeature() { this.indexA; this.indexB; this.typeA; this.typeB; } ContactFeature.prototype.set = function(o) { this.indexA = o.indexA; this.indexB = o.indexB; this.typeA = o.typeA; this.typeB = o.typeB; }; function WorldManifold() { this.normal; this.points = []; this.separations = []; } Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) { if (this.pointCount == 0) { return; } wm = wm || new WorldManifold(); var normal = wm.normal; var points = wm.points; var separations = wm.separations; switch (this.type) { case Manifold.e_circles: normal = Vec2.neo(1, 0); var pointA = Transform.mul(xfA, this.localPoint); var pointB = Transform.mul(xfB, this.points[0].localPoint); var dist = Vec2.sub(pointB, pointA); if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) { normal.set(dist); normal.normalize(); } points[0] = Vec2.mid(pointA, pointB); separations[0] = -radiusB - radiusA; points.length = 1; separations.length = 1; break; case Manifold.e_faceA: normal = Rot.mul(xfA.q, this.localNormal); var planePoint = Transform.mul(xfA, this.localPoint); DEBUG && common.debug("faceA", this.localPoint.x, this.localPoint.y, this.localNormal.x, this.localNormal.y, normal.x, normal.y); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfB, this.points[i].localPoint); var cA = Vec2.clone(clipPoint).wAdd(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cB = Vec2.clone(clipPoint).wSub(radiusB, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal); DEBUG && common.debug(i, this.points[i].localPoint.x, this.points[i].localPoint.y, planePoint.x, planePoint.y, xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s, xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s, radiusA, radiusB, clipPoint.x, clipPoint.y, cA.x, cA.y, cB.x, cB.y, separations[i], points[i].x, points[i].y); } points.length = this.pointCount; separations.length = this.pointCount; break; case Manifold.e_faceB: normal = Rot.mul(xfB.q, this.localNormal); var planePoint = Transform.mul(xfB, this.localPoint); for (var i = 0; i < this.pointCount; ++i) { var clipPoint = Transform.mul(xfA, this.points[i].localPoint); var cB = Vec2.zero().wSet(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal); var cA = Vec2.zero().wSet(1, clipPoint, -radiusA, normal); points[i] = Vec2.mid(cA, cB); separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal); } points.length = this.pointCount; separations.length = this.pointCount; normal.mul(-1); break; } wm.normal = normal; wm.points = points; wm.separations = separations; return wm; }; var PointState = { nullState: 0, addState: 1, persistState: 2, removeState: 3 }; function getPointStates(state1, state2, manifold1, manifold2) { for (var i = 0; i < manifold1.pointCount; ++i) { var id = manifold1.points[i].id; state1[i] = PointState.removeState; for (var j = 0; j < manifold2.pointCount; ++j) { if (manifold2.points[j].id.key == id.key) { state1[i] = PointState.persistState; break; } } } for (var i = 0; i < manifold2.pointCount; ++i) { var id = manifold2.points[i].id; state2[i] = PointState.addState; for (var j = 0; j < manifold1.pointCount; ++j) { if (manifold1.points[j].id.key == id.key) { state2[i] = PointState.persistState; break; } } } } function ClipVertex() { this.v = Vec2.zero(); this.id = new ContactID(); } ClipVertex.prototype.set = function(o) { this.v.set(o.v); this.id.set(o.id); }; function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) { var numOut = 0; var distance0 = Vec2.dot(normal, vIn[0].v) - offset; var distance1 = Vec2.dot(normal, vIn[1].v) - offset; if (distance0 <= 0) vOut[numOut++].set(vIn[0]); if (distance1 <= 0) vOut[numOut++].set(vIn[1]); if (distance0 * distance1 < 0) { var interp = distance0 / (distance0 - distance1); vOut[numOut].v.wSet(1 - interp, vIn[0].v, interp, vIn[1].v); vOut[numOut].id.cf.indexA = vertexIndexA; vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; vOut[numOut].id.cf.typeA = ContactFeature.e_vertex; vOut[numOut].id.cf.typeB = ContactFeature.e_face; ++numOut; } return numOut; } },{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = exports; Settings.maxManifoldPoints = 2; Settings.maxPolygonVertices = 12; Settings.aabbExtension = .1; Settings.aabbMultiplier = 2; Settings.linearSlop = .005; Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop; Settings.angularSlop = 2 / 180 * Math.PI; Settings.polygonRadius = 2 * Settings.linearSlop; Settings.maxSubSteps = 8; Settings.maxTOIContacts = 32; Settings.maxTOIIterations = 20; Settings.maxDistnceIterations = 20; Settings.velocityThreshold = 1; Settings.maxLinearCorrection = .2; Settings.maxAngularCorrection = 8 / 180 * Math.PI; Settings.maxTranslation = 2; Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation; Settings.maxRotation = .5 * Math.PI; Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation; Settings.baumgarte = .2; Settings.toiBaugarte = .75; Settings.timeToSleep = .5; Settings.linearSleepTolerance = .01; Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2); Settings.angularSleepTolerance = 2 / 180 * Math.PI; Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2); },{}],8:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Shape; var Math = require("./common/Math"); function Shape() { this.m_type; this.m_radius; } Shape.isValid = function(shape) { return !!shape; }; Shape.prototype.getRadius = function() { return this.m_radius; }; Shape.prototype.getType = function() { return this.m_type; }; Shape.prototype._clone = function() {}; Shape.prototype.getChildCount = function() {}; Shape.prototype.testPoint = function(xf, p) {}; Shape.prototype.rayCast = function(output, input, transform, childIndex) {}; Shape.prototype.computeAABB = function(aabb, xf, childIndex) {}; Shape.prototype.computeMass = function(massData, density) {}; Shape.prototype.computeDistanceProxy = function(proxy) {}; },{"./common/Math":18}],9:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Solver; module.exports.TimeStep = TimeStep; var Settings = require("./Settings"); var common = require("./util/common"); var Timer = require("./util/Timer"); var Vec2 = require("./common/Vec2"); var Math = require("./common/Math"); var Body = require("./Body"); var Contact = require("./Contact"); var Joint = require("./Joint"); var TimeOfImpact = require("./collision/TimeOfImpact"); var TOIInput = TimeOfImpact.Input; var TOIOutput = TimeOfImpact.Output; var Distance = require("./collision/Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function Profile() { this.solveInit; this.solveVelocity; this.solvePosition; } function TimeStep(dt) { this.dt = 0; this.inv_dt = 0; this.velocityIterations = 0; this.positionIterations = 0; this.warmStarting = false; this.blockSolve = true; this.inv_dt0 = 0; this.dtRatio = 1; } TimeStep.prototype.reset = function(dt) { if (this.dt > 0) { this.inv_dt0 = this.inv_dt; } this.dt = dt; this.inv_dt = dt == 0 ? 0 : 1 / dt; this.dtRatio = dt * this.inv_dt0; }; function Solver(world) { this.m_world = world; this.m_profile = new Profile(); this.m_stack = []; this.m_bodies = []; this.m_contacts = []; this.m_joints = []; } Solver.prototype.clear = function() { this.m_stack.length = 0; this.m_bodies.length = 0; this.m_contacts.length = 0; this.m_joints.length = 0; }; Solver.prototype.addBody = function(body) { ASSERT && common.assert(body instanceof Body, "Not a Body!", body); this.m_bodies.push(body); }; Solver.prototype.addContact = function(contact) { ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact); this.m_contacts.push(contact); }; Solver.prototype.addJoint = function(joint) { ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint); this.m_joints.push(joint); }; Solver.prototype.solveWorld = function(step) { var world = this.m_world; var profile = this.m_profile; profile.solveInit = 0; profile.solveVelocity = 0; profile.solvePosition = 0; for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; } for (var c = world.m_contactList; c; c = c.m_next) { c.m_islandFlag = false; } for (var j = world.m_jointList; j; j = j.m_next) { j.m_islandFlag = false; } var stack = this.m_stack; var loop = -1; for (var seed = world.m_bodyList; seed; seed = seed.m_next) { loop++; if (seed.m_islandFlag) { continue; } if (seed.isAwake() == false || seed.isActive() == false) { continue; } if (seed.isStatic()) { continue; } this.clear(); stack.push(seed); seed.m_islandFlag = true; while (stack.length > 0) { var b = stack.pop(); ASSERT && common.assert(b.isActive() == true); this.addBody(b); b.setAwake(true); if (b.isStatic()) { continue; } for (var ce = b.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } if (contact.isEnabled() == false || contact.isTouching() == false) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } this.addContact(contact); contact.m_islandFlag = true; var other = ce.other; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } for (var je = b.m_jointList; je; je = je.next) { if (je.joint.m_islandFlag == true) { continue; } var other = je.other; if (other.isActive() == false) { continue; } this.addJoint(je.joint); je.joint.m_islandFlag = true; if (other.m_islandFlag) { continue; } stack.push(other); other.m_islandFlag = true; } } this.solveIsland(step); for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; if (b.isStatic()) { b.m_islandFlag = false; } } } }; Solver.prototype.solveIsland = function(step) { var world = this.m_world; var profile = this.m_profile; var gravity = world.m_gravity; var allowSleep = world.m_allowSleep; var timer = Timer.now(); var h = step.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.m_sweep.c); var a = body.m_sweep.a; var v = Vec2.clone(body.m_linearVelocity); var w = body.m_angularVelocity; body.m_sweep.c0.set(body.m_sweep.c); body.m_sweep.a0 = body.m_sweep.a; DEBUG && common.debug("P: ", a, c.x, c.y, w, v.x, v.y); if (body.isDynamic()) { v.wAdd(h * body.m_gravityScale, gravity); v.wAdd(h * body.m_invMass, body.m_force); w += h * body.m_invI * body.m_torque; DEBUG && common.debug("N: " + h, body.m_gravityScale, gravity.x, gravity.y, body.m_invMass, body.m_force.x, body.m_force.y); v.mul(1 / (1 + h * body.m_linearDamping)); w *= 1 / (1 + h * body.m_angularDamping); } common.debug("A: ", a, c.x, c.y, w, v.x, v.y); body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; } timer = Timer.now(); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(step); } DEBUG && this.printBodies("M: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(step); } DEBUG && this.printBodies("R: "); if (step.warmStarting) { for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.warmStartConstraint(step); } } DEBUG && this.printBodies("Q: "); for (var i = 0; i < this.m_joints.length; ++i) { var joint = this.m_joints[i]; joint.initVelocityConstraints(step); } DEBUG && this.printBodies("E: "); profile.solveInit = Timer.diff(timer); timer = Timer.now(); for (var i = 0; i < step.velocityIterations; ++i) { DEBUG && common.debug("--", i); for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; joint.solveVelocityConstraints(step); } for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(step); } } DEBUG && this.printBodies("D: "); for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.storeConstraintImpulses(step); } profile.solveVelocity = Timer.diff(timer); DEBUG && this.printBodies("C: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.wAdd(h, v); a += h * w; body.c_position.c.set(c); body.c_position.a = a; body.c_velocity.v.set(v); body.c_velocity.w = w; } DEBUG && this.printBodies("B: "); timer = Timer.now(); var positionSolved = false; for (var i = 0; i < step.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraint(step); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -3 * Settings.linearSlop; var jointsOkay = true; for (var j = 0; j < this.m_joints.length; ++j) { var joint = this.m_joints[j]; var jointOkay = joint.solvePositionConstraints(step); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { positionSolved = true; break; } } DEBUG && this.printBodies("L: "); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_sweep.c.set(body.c_position.c); body.m_sweep.a = body.c_position.a; body.m_linearVelocity.set(body.c_velocity.v); body.m_angularVelocity = body.c_velocity.w; body.synchronizeTransform(); } profile.solvePosition = Timer.diff(timer); this.postSolveIsland(); if (allowSleep) { var minSleepTime = Infinity; var linTolSqr = Settings.linearSleepToleranceSqr; var angTolSqr = Settings.angularSleepToleranceSqr; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; if (body.isStatic()) { continue; } if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) { body.m_sleepTime = 0; minSleepTime = 0; } else { body.m_sleepTime += h; minSleepTime = Math.min(minSleepTime, body.m_sleepTime); } } if (minSleepTime >= Settings.timeToSleep && positionSolved) { for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.setAwake(false); } } } }; Solver.prototype.printBodies = function(tag) { for (var i = 0; i < this.m_bodies.length; ++i) { var b = this.m_bodies[i]; common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y); } }; var s_subStep = new TimeStep(); Solver.prototype.solveWorldTOI = function(step) { DEBUG && common.debug("TOI++++++World"); var world = this.m_world; var profile = this.m_profile; DEBUG && common.debug("Z:", world.m_stepComplete); if (world.m_stepComplete) { for (var b = world.m_bodyList; b; b = b.m_next) { b.m_islandFlag = false; b.m_sweep.alpha0 = 0; DEBUG && common.debug("b.alpha0:", b.m_sweep.alpha0); } for (var c = world.m_contactList; c; c = c.m_next) { c.m_toiFlag = false; c.m_islandFlag = false; c.m_toiCount = 0; c.m_toi = 1; } } if (DEBUG) for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("X:", c.m_toiFlag); } for (;;) { DEBUG && common.debug(";;"); var minContact = null; var minAlpha = 1; for (var c = world.m_contactList; c; c = c.m_next) { DEBUG && common.debug("alpha0::", c.getFixtureA().getBody().m_sweep.alpha0, c.getFixtureB().getBody().m_sweep.alpha0); if (c.isEnabled() == false) { continue; } DEBUG && common.debug("toiCount:", c.m_toiCount, Settings.maxSubSteps); if (c.m_toiCount > Settings.maxSubSteps) { continue; } DEBUG && common.debug("toiFlag:", c.m_toiFlag); var alpha = 1; if (c.m_toiFlag) { alpha = c.m_toi; } else { var fA = c.getFixtureA(); var fB = c.getFixtureB(); DEBUG && common.debug("sensor:", fA.isSensor(), fB.isSensor()); if (fA.isSensor() || fB.isSensor()) { continue; } var bA = fA.getBody(); var bB = fB.getBody(); ASSERT && common.assert(bA.isDynamic() || bB.isDynamic()); var activeA = bA.isAwake() && !bA.isStatic(); var activeB = bB.isAwake() && !bB.isStatic(); DEBUG && common.debug("awakestatic:", bA.isAwake(), bA.isStatic()); DEBUG && common.debug("awakestatic:", bB.isAwake(), bB.isStatic()); DEBUG && common.debug("active:", activeA, activeB); if (activeA == false && activeB == false) { continue; } DEBUG && common.debug("alpha:", alpha, bA.m_sweep.alpha0, bB.m_sweep.alpha0); var collideA = bA.isBullet() || !bA.isDynamic(); var collideB = bB.isBullet() || !bB.isDynamic(); DEBUG && common.debug("collide:", collideA, collideB); if (collideA == false && collideB == false) { continue; } var alpha0 = bA.m_sweep.alpha0; if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) { alpha0 = bB.m_sweep.alpha0; bA.m_sweep.advance(alpha0); } else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) { alpha0 = bA.m_sweep.alpha0; bB.m_sweep.advance(alpha0); } DEBUG && common.debug("alpha0:", alpha0, bA.m_sweep.alpha0, bB.m_sweep.alpha0); ASSERT && common.assert(alpha0 < 1); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var sweepA = bA.m_sweep; var sweepB = bB.m_sweep; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); var input = new TOIInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.sweepA.set(bA.m_sweep); input.sweepB.set(bB.m_sweep); input.tMax = 1; var output = new TOIOutput(); TimeOfImpact(output, input); var beta = output.t; DEBUG && common.debug("state:", output.state, TOIOutput.e_touching); if (output.state == TOIOutput.e_touching) { alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1); } else { alpha = 1; } c.m_toi = alpha; c.m_toiFlag = true; } DEBUG && common.debug("minAlpha:", minAlpha, alpha); if (alpha < minAlpha) { minContact = c; minAlpha = alpha; } } DEBUG && common.debug("minContact:", minContact == null, 1 - 10 * Math.EPSILON < minAlpha, minAlpha); if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) { world.m_stepComplete = true; break; } var fA = minContact.getFixtureA(); var fB = minContact.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var backup1 = bA.m_sweep.clone(); var backup2 = bB.m_sweep.clone(); bA.advance(minAlpha); bB.advance(minAlpha); minContact.update(world); minContact.m_toiFlag = false; ++minContact.m_toiCount; if (minContact.isEnabled() == false || minContact.isTouching() == false) { minContact.setEnabled(false); bA.m_sweep.set(backup1); bB.m_sweep.set(backup2); bA.synchronizeTransform(); bB.synchronizeTransform(); continue; } bA.setAwake(true); bB.setAwake(true); this.clear(); this.addBody(bA); this.addBody(bB); this.addContact(minContact); bA.m_islandFlag = true; bB.m_islandFlag = true; minContact.m_islandFlag = true; var bodies = [ bA, bB ]; for (var i = 0; i < bodies.length; ++i) { var body = bodies[i]; if (body.isDynamic()) { for (var ce = body.m_contactList; ce; ce = ce.next) { var contact = ce.contact; if (contact.m_islandFlag) { continue; } var other = ce.other; if (other.isDynamic() && !body.isBullet() && !other.isBullet()) { continue; } var sensorA = contact.m_fixtureA.m_isSensor; var sensorB = contact.m_fixtureB.m_isSensor; if (sensorA || sensorB) { continue; } var backup = other.m_sweep.clone(); if (other.m_islandFlag == false) { other.advance(minAlpha); } contact.update(world); if (contact.isEnabled() == false || contact.isTouching() == false) { other.m_sweep.set(backup); other.synchronizeTransform(); continue; } contact.m_islandFlag = true; this.addContact(contact); if (other.m_islandFlag) { continue; } other.m_islandFlag = true; if (!other.isStatic()) { other.setAwake(true); } this.addBody(other); } } } s_subStep.reset((1 - minAlpha) * step.dt); s_subStep.dtRatio = 1; s_subStep.positionIterations = 20; s_subStep.velocityIterations = step.velocityIterations; s_subStep.warmStarting = false; this.solveIslandTOI(s_subStep, bA, bB); for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.m_islandFlag = false; if (!body.isDynamic()) { continue; } body.synchronizeFixtures(); for (var ce = body.m_contactList; ce; ce = ce.next) { ce.contact.m_toiFlag = false; ce.contact.m_islandFlag = false; } } world.findNewContacts(); if (world.m_subStepping) { world.m_stepComplete = false; break; } } if (DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) { var c = b.m_sweep.c; var a = b.m_sweep.a; var v = b.m_linearVelocity; var w = b.m_angularVelocity; DEBUG && common.debug("== ", a, c.x, c.y, w, v.x, v.y); } }; Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) { DEBUG && common.debug("TOI++++++Island"); var world = this.m_world; var profile = this.m_profile; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; body.c_position.c.set(body.m_sweep.c); body.c_position.a = body.m_sweep.a; body.c_velocity.v.set(body.m_linearVelocity); body.c_velocity.w = body.m_angularVelocity; } for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initConstraint(subStep); } for (var i = 0; i < subStep.positionIterations; ++i) { var minSeparation = 0; for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB); minSeparation = Math.min(minSeparation, separation); } var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop; if (contactsOkay) { break; } } if (false) { for (var i = 0; i < this.m_contacts.length; ++i) { var c = this.m_contacts[i]; var fA = c.getFixtureA(); var fB = c.getFixtureB(); var bA = fA.getBody(); var bB = fB.getBody(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var input = new DistanceInput(); input.proxyA.set(fA.getShape(), indexA); input.proxyB.set(fB.getShape(), indexB); input.transformA = bA.getTransform(); input.transformB = bB.getTransform(); input.useRadii = false; var output = new DistanceOutput(); var cache = new SimplexCache(); Distance(output, cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } } toiA.m_sweep.c0.set(toiA.c_position.c); toiA.m_sweep.a0 = toiA.c_position.a; toiB.m_sweep.c0.set(toiB.c_position.c); toiB.m_sweep.a0 = toiB.c_position.a; for (var i = 0; i < this.m_contacts.length; ++i) { var contact = this.m_contacts[i]; contact.initVelocityConstraint(subStep); } for (var i = 0; i < subStep.velocityIterations; ++i) { for (var j = 0; j < this.m_contacts.length; ++j) { var contact = this.m_contacts[j]; contact.solveVelocityConstraint(subStep); } } var h = subStep.dt; for (var i = 0; i < this.m_bodies.length; ++i) { var body = this.m_bodies[i]; var c = Vec2.clone(body.c_position.c); var a = body.c_position.a; var v = Vec2.clone(body.c_velocity.v); var w = body.c_velocity.w; var translation = Vec2.mul(h, v); if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) { var ratio = Settings.maxTranslation / translation.length(); v.mul(ratio); } var rotation = h * w; if (rotation * rotation > Settings.maxRotationSquared) { var ratio = Settings.maxRotation / Math.abs(rotation); w *= ratio; } c.wAdd(h, v); a += h * w; body.c_position.c = c; body.c_position.a = a; body.c_velocity.v = v; body.c_velocity.w = w; body.m_sweep.c = c; body.m_sweep.a = a; body.m_linearVelocity = v; body.m_angularVelocity = w; body.synchronizeTransform(); } this.postSolveIsland(); DEBUG && common.debug("TOI------Island"); }; function ContactImpulse() { this.normalImpulses = []; this.tangentImpulses = []; } Solver.prototype.postSolveIsland = function() { var impulse = new ContactImpulse(); for (var c = 0; c < this.m_contacts.length; ++c) { var contact = this.m_contacts[c]; for (var p = 0; p < contact.v_points.length; ++p) { impulse.normalImpulses.push(contact.v_points[p].normalImpulse); impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse); } this.m_world.postSolve(contact, impulse); } }; },{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/Timer":50,"./util/common":51}],10:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = World; var options = require("./util/options"); var common = require("./util/common"); var Timer = require("./util/Timer"); var Vec2 = require("./common/Vec2"); var BroadPhase = require("./collision/BroadPhase"); var Solver = require("./Solver"); var Body = require("./Body"); var Contact = require("./Contact"); var WorldDef = { gravity: Vec2.zero(), allowSleep: true, warmStarting: true, continuousPhysics: true, subStepping: false, blockSolve: true, velocityIterations: 8, positionIterations: 3 }; function World(def) { if (!(this instanceof World)) { return new World(def); } if (def && Vec2.isValid(def)) { def = { gravity: def }; } def = options(def, WorldDef); this.m_solver = new Solver(this); this.m_broadPhase = new BroadPhase(); this.m_contactList = null; this.m_contactCount = 0; this.m_bodyList = null; this.m_bodyCount = 0; this.m_jointList = null; this.m_jointCount = 0; this.m_stepComplete = true; this.m_allowSleep = def.allowSleep; this.m_gravity = Vec2.clone(def.gravity); this.m_clearForces = true; this.m_newFixture = false; this.m_locked = false; this.m_warmStarting = def.warmStarting; this.m_continuousPhysics = def.continuousPhysics; this.m_subStepping = def.subStepping; this.m_blockSolve = def.blockSolve; this.m_velocityIterations = def.velocityIterations; this.m_positionIterations = def.positionIterations; this.m_t = 0; this.m_stepCount = 0; this.addPair = this.createContact.bind(this); } World.prototype.getBodyList = function() { return this.m_bodyList; }; World.prototype.getJointList = function() { return this.m_jointList; }; World.prototype.getContactList = function() { return this.m_contactList; }; World.prototype.getBodyCount = function() { return this.m_bodyCount; }; World.prototype.getJointCount = function() { return this.m_jointCount; }; World.prototype.getContactCount = function() { return this.m_contactCount; }; World.prototype.setGravity = function(gravity) { this.m_gravity = gravity; }; World.prototype.getGravity = function() { return this.m_gravity; }; World.prototype.isLocked = function() { return this.m_locked; }; World.prototype.setAllowSleeping = function(flag) { if (flag == this.m_allowSleep) { return; } this.m_allowSleep = flag; if (this.m_allowSleep == false) { for (var b = this.m_bodyList; b; b = b.m_next) { b.setAwake(true); } } }; World.prototype.getAllowSleeping = function() { return this.m_allowSleep; }; World.prototype.setWarmStarting = function(flag) { this.m_warmStarting = flag; }; World.prototype.getWarmStarting = function() { return this.m_warmStarting; }; World.prototype.setContinuousPhysics = function(flag) { this.m_continuousPhysics = flag; }; World.prototype.getContinuousPhysics = function() { return this.m_continuousPhysics; }; World.prototype.setSubStepping = function(flag) { this.m_subStepping = flag; }; World.prototype.getSubStepping = function() { return this.m_subStepping; }; World.prototype.setAutoClearForces = function(flag) { this.m_clearForces = flag; }; World.prototype.getAutoClearForces = function() { return this.m_clearForces; }; World.prototype.clearForces = function() { for (var body = this.m_bodyList; body; body = body.getNext()) { body.m_force.setZero(); body.m_torque = 0; } }; World.prototype.queryAABB = function(aabb, queryCallback) { ASSERT && common.assert(typeof queryCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.query(aabb, function(proxyId) { var proxy = broadPhase.getUserData(proxyId); return queryCallback(proxy.fixture); }); }; World.prototype.rayCast = function(point1, point2, reportFixtureCallback) { ASSERT && common.assert(typeof reportFixtureCallback === "function"); var broadPhase = this.m_broadPhase; this.m_broadPhase.rayCast({ maxFraction: 1, p1: point1, p2: point2 }, function(input, proxyId) { var proxy = broadPhase.getUserData(proxyId); var fixture = proxy.fixture; var index = proxy.childIndex; var output = {}; var hit = fixture.rayCast(output, input, index); if (hit) { var fraction = output.fraction; var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2)); return reportFixtureCallback(fixture, point, output.normal, fraction); } return input.maxFraction; }); }; World.prototype.getProxyCount = function() { return this.m_broadPhase.getProxyCount(); }; World.prototype.getTreeHeight = function() { return this.m_broadPhase.getTreeHeight(); }; World.prototype.getTreeBalance = function() { return this.m_broadPhase.getTreeBalance(); }; World.prototype.getTreeQuality = function() { return this.m_broadPhase.getTreeQuality(); }; World.prototype.shiftOrigin = function(newOrigin) { ASSERT && common.assert(this.m_locked == false); if (this.m_locked) { return; } for (var b = this.m_bodyList; b; b = b.m_next) { b.m_xf.p.sub(newOrigin); b.m_sweep.c0.sub(newOrigin); b.m_sweep.c.sub(newOrigin); } for (var j = this.m_jointList; j; j = j.m_next) { j.shiftOrigin(newOrigin); } this.m_broadPhase.shiftOrigin(newOrigin); }; World.prototype.createBody = function(def, angle) { ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } if (def && Vec2.isValid(def)) { def = { position: def, angle: angle }; } var body = new Body(this, def); body.m_prev = null; body.m_next = this.m_bodyList; if (this.m_bodyList) { this.m_bodyList.m_prev = body; } this.m_bodyList = body; ++this.m_bodyCount; return body; }; World.prototype.createDynamicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "dynamic"; return this.createBody(def); }; World.prototype.createKinematicBody = function(def, angle) { if (!def) { def = {}; } else if (Vec2.isValid(def)) { def = { position: def, angle: angle }; } def.type = "kinematic"; return this.createBody(def); }; World.prototype.destroyBody = function(b) { ASSERT && common.assert(this.m_bodyCount > 0); ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (b.m_destroyed) { return false; } var je = b.m_jointList; while (je) { var je0 = je; je = je.next; this.publish("remove-joint", je0.joint); this.destroyJoint(je0.joint); b.m_jointList = je; } b.m_jointList = null; var ce = b.m_contactList; while (ce) { var ce0 = ce; ce = ce.next; this.destroyContact(ce0.contact); b.m_contactList = ce; } b.m_contactList = null; var f = b.m_fixtureList; while (f) { var f0 = f; f = f.m_next; this.publish("remove-fixture", f0); f0.destroyProxies(this.m_broadPhase); b.m_fixtureList = f; } b.m_fixtureList = null; if (b.m_prev) { b.m_prev.m_next = b.m_next; } if (b.m_next) { b.m_next.m_prev = b.m_prev; } if (b == this.m_bodyList) { this.m_bodyList = b.m_next; } b.m_destroyed = true; --this.m_bodyCount; return true; }; World.prototype.createJoint = function(joint) { ASSERT && common.assert(!!joint.m_bodyA); ASSERT && common.assert(!!joint.m_bodyB); ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return null; } joint.m_prev = null; joint.m_next = this.m_jointList; if (this.m_jointList) { this.m_jointList.m_prev = joint; } this.m_jointList = joint; ++this.m_jointCount; joint.m_edgeA.joint = joint; joint.m_edgeA.other = joint.m_bodyB; joint.m_edgeA.prev = null; joint.m_edgeA.next = joint.m_bodyA.m_jointList; if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA; joint.m_bodyA.m_jointList = joint.m_edgeA; joint.m_edgeB.joint = joint; joint.m_edgeB.other = joint.m_bodyA; joint.m_edgeB.prev = null; joint.m_edgeB.next = joint.m_bodyB.m_jointList; if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB; joint.m_bodyB.m_jointList = joint.m_edgeB; if (joint.m_collideConnected == false) { for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) { if (edge.other == joint.m_bodyA) { edge.contact.flagForFiltering(); } } } return joint; }; World.prototype.destroyJoint = function(joint) { ASSERT && common.assert(this.isLocked() == false); if (this.isLocked()) { return; } if (joint.m_prev) { joint.m_prev.m_next = joint.m_next; } if (joint.m_next) { joint.m_next.m_prev = joint.m_prev; } if (joint == this.m_jointList) { this.m_jointList = joint.m_next; } var bodyA = joint.m_bodyA; var bodyB = joint.m_bodyB; bodyA.setAwake(true); bodyB.setAwake(true); if (joint.m_edgeA.prev) { joint.m_edgeA.prev.next = joint.m_edgeA.next; } if (joint.m_edgeA.next) { joint.m_edgeA.next.prev = joint.m_edgeA.prev; } if (joint.m_edgeA == bodyA.m_jointList) { bodyA.m_jointList = joint.m_edgeA.next; } joint.m_edgeA.prev = null; joint.m_edgeA.next = null; if (joint.m_edgeB.prev) { joint.m_edgeB.prev.next = joint.m_edgeB.next; } if (joint.m_edgeB.next) { joint.m_edgeB.next.prev = joint.m_edgeB.prev; } if (joint.m_edgeB == bodyB.m_jointList) { bodyB.m_jointList = joint.m_edgeB.next; } joint.m_edgeB.prev = null; joint.m_edgeB.next = null; ASSERT && common.assert(this.m_jointCount > 0); --this.m_jointCount; if (joint.m_collideConnected == false) { var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { edge.contact.flagForFiltering(); } edge = edge.next; } } this.publish("remove-joint", joint); }; var s_step = new Solver.TimeStep(); World.prototype.step = function(timeStep, velocityIterations, positionIterations) { if ((velocityIterations | 0) !== velocityIterations) { velocityIterations = 0; } velocityIterations = velocityIterations || this.m_velocityIterations; positionIterations = positionIterations || this.m_positionIterations; this.m_stepCount++; if (this.m_newFixture) { this.findNewContacts(); this.m_newFixture = false; } this.m_locked = true; s_step.reset(timeStep); s_step.velocityIterations = velocityIterations; s_step.positionIterations = positionIterations; s_step.warmStarting = this.m_warmStarting; s_step.blockSolve = this.m_blockSolve; this.updateContacts(); if (this.m_stepComplete && timeStep > 0) { this.m_solver.solveWorld(s_step); for (var b = this.m_bodyList; b; b = b.getNext()) { if (b.m_islandFlag == false) { continue; } if (b.isStatic()) { continue; } b.synchronizeFixtures(); } this.findNewContacts(); } if (this.m_continuousPhysics && timeStep > 0) { this.m_solver.solveWorldTOI(s_step); } if (this.m_clearForces) { this.clearForces(); } this.m_locked = false; }; World.prototype.findNewContacts = function() { this.m_broadPhase.updatePairs(this.addPair); }; World.prototype.createContact = function(proxyA, proxyB) { var fixtureA = proxyA.fixture; var fixtureB = proxyB.fixture; var indexA = proxyA.childIndex; var indexB = proxyB.childIndex; var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (bodyA == bodyB) { return; } var edge = bodyB.getContactList(); while (edge) { if (edge.other == bodyA) { var fA = edge.contact.getFixtureA(); var fB = edge.contact.getFixtureB(); var iA = edge.contact.getChildIndexA(); var iB = edge.contact.getChildIndexB(); if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) { return; } if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) { return; } } edge = edge.next; } if (bodyB.shouldCollide(bodyA) == false) { return; } if (fixtureB.shouldCollide(fixtureA) == false) { return; } var contact = Contact.create(fixtureA, indexA, fixtureB, indexB); if (contact == null) { return; } contact.m_prev = null; if (this.m_contactList != null) { contact.m_next = this.m_contactList; this.m_contactList.m_prev = contact; } this.m_contactList = contact; ++this.m_contactCount; }; World.prototype.updateContacts = function() { var c, next_c = this.m_contactList; while (c = next_c) { next_c = c.getNext(); var fixtureA = c.getFixtureA(); var fixtureB = c.getFixtureB(); var indexA = c.getChildIndexA(); var indexB = c.getChildIndexB(); var bodyA = fixtureA.getBody(); var bodyB = fixtureB.getBody(); if (c.m_filterFlag) { if (bodyB.shouldCollide(bodyA) == false) { this.destroyContact(c); continue; } if (fixtureB.shouldCollide(fixtureA) == false) { this.destroyContact(c); continue; } c.m_filterFlag = false; } var activeA = bodyA.isAwake() && !bodyA.isStatic(); var activeB = bodyB.isAwake() && !bodyB.isStatic(); if (activeA == false && activeB == false) { continue; } var proxyIdA = fixtureA.m_proxies[indexA].proxyId; var proxyIdB = fixtureB.m_proxies[indexB].proxyId; var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB); if (overlap == false) { this.destroyContact(c); continue; } c.update(this); } }; World.prototype.destroyContact = function(contact) { Contact.destroy(contact, this); if (contact.m_prev) { contact.m_prev.m_next = contact.m_next; } if (contact.m_next) { contact.m_next.m_prev = contact.m_prev; } if (contact == this.m_contactList) { this.m_contactList = contact.m_next; } --this.m_contactCount; }; World.prototype._listeners = null; World.prototype.on = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } if (!this._listeners) { this._listeners = {}; } if (!this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(listener); return this; }; World.prototype.off = function(name, listener) { if (typeof name !== "string" || typeof listener !== "function") { return this; } var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return this; } var index = listeners.indexOf(listener); if (index >= 0) { listeners.splice(index, 1); } return this; }; World.prototype.publish = function(name, arg1, arg2, arg3) { var listeners = this._listeners && this._listeners[name]; if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].call(this, arg1, arg2, arg3); } return listeners.length; }; World.prototype.beginContact = function(contact) { this.publish("begin-contact", contact); }; World.prototype.endContact = function(contact) { this.publish("end-contact", contact); }; World.prototype.preSolve = function(contact, oldManifold) { this.publish("pre-solve", contact, oldManifold); }; World.prototype.postSolve = function(contact, impulse) { this.publish("post-solve", contact, impulse); }; },{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/Timer":50,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); module.exports = AABB; function AABB(lower, upper) { if (!(this instanceof AABB)) { return new AABB(lower, upper); } this.lowerBound = Vec2.zero(); this.upperBound = Vec2.zero(); if (typeof lower === "object") { this.lowerBound.set(lower); } if (typeof upper === "object") { this.upperBound.set(upper); } } AABB.prototype.isValid = function() { return AABB.isValid(this); }; AABB.isValid = function(aabb) { var d = Vec2.sub(aabb.upperBound, aabb.lowerBound); var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound); return valid; }; AABB.prototype.getCenter = function() { return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5); }; AABB.prototype.getExtents = function() { return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5); }; AABB.prototype.getPerimeter = function() { return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y); }; AABB.prototype.combine = function(a, b) { b = b || this; this.lowerBound.set(Math.min(a.lowerBound.x, b.lowerBound.x), Math.min(a.lowerBound.y, b.lowerBound.y)); this.upperBound.set(Math.max(a.upperBound.x, b.upperBound.x), Math.max(a.upperBound.y, b.upperBound.y)); }; AABB.prototype.combinePoints = function(a, b) { this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y)); this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y)); }; AABB.prototype.set = function(aabb) { this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y); this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y); }; AABB.prototype.contains = function(aabb) { var result = true; result = result && this.lowerBound.x <= aabb.lowerBound.x; result = result && this.lowerBound.y <= aabb.lowerBound.y; result = result && aabb.upperBound.x <= this.upperBound.x; result = result && aabb.upperBound.y <= this.upperBound.y; return result; }; AABB.prototype.extend = function(value) { AABB.extend(this, value); }; AABB.extend = function(aabb, value) { aabb.lowerBound.x -= value; aabb.lowerBound.y -= value; aabb.upperBound.x += value; aabb.upperBound.y += value; }; AABB.testOverlap = function(a, b) { var d1x = b.lowerBound.x - a.upperBound.x; var d2x = a.lowerBound.x - b.upperBound.x; var d1y = b.lowerBound.y - a.upperBound.y; var d2y = a.lowerBound.y - b.upperBound.y; if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) { return false; } return true; }; AABB.areEqual = function(a, b) { return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound); }; AABB.diff = function(a, b) { var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x)); var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y)); var wA = a.upperBound.x - a.lowerBound.x; var hA = a.upperBound.y - a.lowerBound.y; var hB = b.upperBound.y - b.lowerBound.y; var hB = b.upperBound.y - b.lowerBound.y; return wA * hA + wB * hB - wD * hD; }; AABB.prototype.rayCast = function(output, input) { var tmin = -Infinity; var tmax = Infinity; var p = input.p1; var d = Vec2.sub(input.p2, input.p1); var absD = Vec2.abs(d); var normal = Vec2.zero(); for (var f = "x"; f !== null; f = f === "x" ? "y" : null) { if (absD.x < Math.EPSILON) { if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) { return false; } } else { var inv_d = 1 / d[f]; var t1 = (this.lowerBound[f] - p[f]) * inv_d; var t2 = (this.upperBound[f] - p[f]) * inv_d; var s = -1; if (t1 > t2) { var temp = t1; t1 = t2, t2 = temp; s = 1; } if (t1 > tmin) { normal.setZero(); normal[f] = s; tmin = t1; } tmax = Math.min(tmax, t2); if (tmin > tmax) { return false; } } } if (tmin < 0 || input.maxFraction < tmin) { return false; } output.fraction = tmin; output.normal = normal; return true; }; AABB.prototype.toString = function() { return JSON.stringify(this); }; },{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Math = require("../common/Math"); var AABB = require("./AABB"); var DynamicTree = require("./DynamicTree"); module.exports = BroadPhase; function BroadPhase() { this.m_tree = new DynamicTree(); this.m_proxyCount = 0; this.m_moveBuffer = []; this.queryCallback = this.queryCallback.bind(this); } BroadPhase.prototype.getUserData = function(proxyId) { return this.m_tree.getUserData(proxyId); }; BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) { var aabbA = this.m_tree.getFatAABB(proxyIdA); var aabbB = this.m_tree.getFatAABB(proxyIdB); return AABB.testOverlap(aabbA, aabbB); }; BroadPhase.prototype.getFatAABB = function(proxyId) { return this.m_tree.getFatAABB(proxyId); }; BroadPhase.prototype.getProxyCount = function() { return this.m_proxyCount; }; BroadPhase.prototype.getTreeHeight = function() { return this.m_tree.getHeight(); }; BroadPhase.prototype.getTreeBalance = function() { return this.m_tree.getMaxBalance(); }; BroadPhase.prototype.getTreeQuality = function() { return this.m_tree.getAreaRatio(); }; BroadPhase.prototype.query = function(aabb, queryCallback) { this.m_tree.query(aabb, queryCallback); }; BroadPhase.prototype.rayCast = function(input, rayCastCallback) { this.m_tree.rayCast(input, rayCastCallback); }; BroadPhase.prototype.shiftOrigin = function(newOrigin) { this.m_tree.shiftOrigin(newOrigin); }; BroadPhase.prototype.createProxy = function(aabb, userData) { ASSERT && common.assert(AABB.isValid(aabb)); var proxyId = this.m_tree.createProxy(aabb, userData); this.m_proxyCount++; this.bufferMove(proxyId); return proxyId; }; BroadPhase.prototype.destroyProxy = function(proxyId) { this.unbufferMove(proxyId); this.m_proxyCount--; this.m_tree.destroyProxy(proxyId); }; BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) { ASSERT && common.assert(AABB.isValid(aabb)); var changed = this.m_tree.moveProxy(proxyId, aabb, displacement); if (changed) { this.bufferMove(proxyId); } }; BroadPhase.prototype.touchProxy = function(proxyId) { this.bufferMove(proxyId); }; BroadPhase.prototype.bufferMove = function(proxyId) { this.m_moveBuffer.push(proxyId); }; BroadPhase.prototype.unbufferMove = function(proxyId) { for (var i = 0; i < this.m_moveBuffer.length; ++i) { if (this.m_moveBuffer[i] == proxyId) { this.m_moveBuffer[i] = null; } } }; BroadPhase.prototype.updatePairs = function(addPairCallback) { ASSERT && common.assert(typeof addPairCallback === "function"); this.m_callback = addPairCallback; while (this.m_moveBuffer.length > 0) { this.m_queryProxyId = this.m_moveBuffer.pop(); if (this.m_queryProxyId === null) { continue; } var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId); this.m_tree.query(fatAABB, this.queryCallback); } }; BroadPhase.prototype.queryCallback = function(proxyId) { if (proxyId == this.m_queryProxyId) { return true; } var proxyIdA = Math.min(proxyId, this.m_queryProxyId); var proxyIdB = Math.max(proxyId, this.m_queryProxyId); var userDataA = this.m_tree.getUserData(proxyIdA); var userDataB = this.m_tree.getUserData(proxyIdB); this.m_callback(userDataA, userDataB); return true; }; },{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Distance; module.exports.Input = DistanceInput; module.exports.Output = DistanceOutput; module.exports.Proxy = DistanceProxy; module.exports.Cache = SimplexCache; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); stats.gjkCalls = 0; stats.gjkIters = 0; stats.gjkMaxIters = 0; function DistanceInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.transformA = null; this.transformB = null; this.useRadii = false; } function DistanceOutput() { this.pointA = Vec2.zero(); this.pointB = Vec2.zero(); this.distance; this.iterations; } function SimplexCache() { this.metric = 0; this.indexA = []; this.indexB = []; this.count = 0; } function Distance(output, cache, input) { ++stats.gjkCalls; var proxyA = input.proxyA; var proxyB = input.proxyB; var xfA = input.transformA; var xfB = input.transformB; DEBUG && common.debug("cahce:", cache.metric, cache.count); DEBUG && common.debug("proxyA:", proxyA.m_count); DEBUG && common.debug("proxyB:", proxyB.m_count); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); var simplex = new Simplex(); simplex.readCache(cache, proxyA, xfA, proxyB, xfB); DEBUG && common.debug("cache", simplex.print()); var vertices = simplex.m_v; var k_maxIters = Settings.maxDistnceIterations; var saveA = []; var saveB = []; var saveCount = 0; var distanceSqr1 = Infinity; var distanceSqr2 = Infinity; var iter = 0; while (iter < k_maxIters) { saveCount = simplex.m_count; for (var i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } simplex.solve(); if (simplex.m_count == 3) { break; } var p = simplex.getClosestPoint(); distanceSqr2 = p.lengthSquared(); if (distanceSqr2 >= distanceSqr1) {} distanceSqr1 = distanceSqr2; var d = simplex.getSearchDirection(); if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) { break; } var vertex = vertices[simplex.m_count]; vertex.indexA = proxyA.getSupport(Rot.mulT(xfA.q, Vec2.neg(d))); vertex.wA = Transform.mul(xfA, proxyA.getVertex(vertex.indexA)); vertex.indexB = proxyB.getSupport(Rot.mulT(xfB.q, d)); vertex.wB = Transform.mul(xfB, proxyB.getVertex(vertex.indexB)); vertex.w = Vec2.sub(vertex.wB, vertex.wA); ++iter; ++stats.gjkIters; var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) { duplicate = true; break; } } if (duplicate) { break; } ++simplex.m_count; } stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter); simplex.getWitnessPoints(output.pointA, output.pointB); output.distance = Vec2.distance(output.pointA, output.pointB); output.iterations = iter; DEBUG && common.debug("Distance:", output.distance, output.pointA.x, output.pointA.y, output.pointB.x, output.pointB.y); simplex.writeCache(cache); if (input.useRadii) { var rA = proxyA.m_radius; var rB = proxyB.m_radius; if (output.distance > rA + rB && output.distance > Math.EPSILON) { output.distance -= rA + rB; var normal = Vec2.sub(output.pointB, output.pointA); normal.normalize(); output.pointA.wAdd(rA, normal); output.pointB.wSub(rB, normal); } else { var p = Vec2.mid(output.pointA, output.pointB); output.pointA.set(p); output.pointB.set(p); output.distance = 0; } } } function DistanceProxy() { this.m_buffer = []; this.m_vertices = []; this.m_count = 0; this.m_radius = 0; } DistanceProxy.prototype.getVertexCount = function() { return this.m_count; }; DistanceProxy.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; DistanceProxy.prototype.getSupport = function(d) { var bestIndex = 0; var bestValue = Vec2.dot(this.m_vertices[0], d); for (var i = 0; i < this.m_count; ++i) { var value = Vec2.dot(this.m_vertices[i], d); if (value > bestValue) { bestIndex = i; bestValue = value; } } return bestIndex; }; DistanceProxy.prototype.getSupportVertex = function(d) { return this.m_vertices[this.getSupport(d)]; }; DistanceProxy.prototype.set = function(shape, index) { ASSERT && common.assert(typeof shape.computeDistanceProxy === "function"); shape.computeDistanceProxy(this, index); }; function SimplexVertex() { this.indexA; this.indexB; this.wA = Vec2.zero(); this.wB = Vec2.zero(); this.w = Vec2.zero(); this.a; } SimplexVertex.prototype.set = function(v) { this.indexA = v.indexA; this.indexB = v.indexB; this.wA = Vec2.clone(v.wA); this.wB = Vec2.clone(v.wB); this.w = Vec2.clone(v.w); this.a = v.a; }; function Simplex() { this.m_v1 = new SimplexVertex(); this.m_v2 = new SimplexVertex(); this.m_v3 = new SimplexVertex(); this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ]; this.m_count; } Simplex.prototype.print = function() { if (this.m_count == 3) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString(); } else if (this.m_count == 2) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString(); } else if (this.m_count == 1) { return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString(); } else { return "+" + this.m_count; } }; Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) { ASSERT && common.assert(cache.count <= 3); this.m_count = cache.count; for (var i = 0; i < this.m_count; ++i) { var v = this.m_v[i]; v.indexA = cache.indexA[i]; v.indexB = cache.indexB[i]; var wALocal = proxyA.getVertex(v.indexA); var wBLocal = proxyB.getVertex(v.indexB); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 0; } if (this.m_count > 1) { var metric1 = cache.metric; var metric2 = this.getMetric(); if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) { this.m_count = 0; } } if (this.m_count == 0) { var v = this.m_v[0]; v.indexA = 0; v.indexB = 0; var wALocal = proxyA.getVertex(0); var wBLocal = proxyB.getVertex(0); v.wA = Transform.mul(transformA, wALocal); v.wB = Transform.mul(transformB, wBLocal); v.w = Vec2.sub(v.wB, v.wA); v.a = 1; this.m_count = 1; } }; Simplex.prototype.writeCache = function(cache) { cache.metric = this.getMetric(); cache.count = this.m_count; for (var i = 0; i < this.m_count; ++i) { cache.indexA[i] = this.m_v[i].indexA; cache.indexB[i] = this.m_v[i].indexB; } }; Simplex.prototype.getSearchDirection = function() { switch (this.m_count) { case 1: return Vec2.neg(this.m_v1.w); case 2: { var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w); var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w)); if (sgn > 0) { return Vec2.cross(1, e12); } else { return Vec2.cross(e12, 1); } } default: ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getClosestPoint = function() { switch (this.m_count) { case 0: ASSERT && common.assert(false); return Vec2.zero(); case 1: return Vec2.clone(this.m_v1.w); case 2: return Vec2.wAdd(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w); case 3: return Vec2.zero(); default: ASSERT && common.assert(false); return Vec2.zero(); } }; Simplex.prototype.getWitnessPoints = function(pA, pB) { switch (this.m_count) { case 0: ASSERT && common.assert(false); break; case 1: DEBUG && common.debug("case1", this.print()); pA.set(this.m_v1.wA); pB.set(this.m_v1.wB); break; case 2: DEBUG && common.debug("case2", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pB.wSet(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB); break; case 3: DEBUG && common.debug("case3", this.print()); pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA); pA.wAdd(this.m_v3.a, this.m_v3.wA); pB.set(pA); break; default: ASSERT && common.assert(false); break; } }; Simplex.prototype.getMetric = function() { switch (this.m_count) { case 0: ASSERT && common.assert(false); return 0; case 1: return 0; case 2: return Vec2.distance(this.m_v1.w, this.m_v2.w); case 3: return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w)); default: ASSERT && common.assert(false); return 0; } }; Simplex.prototype.solve = function() { switch (this.m_count) { case 1: break; case 2: this.solve2(); break; case 3: this.solve3(); break; default: ASSERT && common.assert(false); } }; Simplex.prototype.solve2 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var e12 = Vec2.sub(w2, w1); var d12_2 = -Vec2.dot(w1, e12); if (d12_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } var d12_1 = Vec2.dot(w2, e12); if (d12_1 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; }; Simplex.prototype.solve3 = function() { var w1 = this.m_v1.w; var w2 = this.m_v2.w; var w3 = this.m_v3.w; var e12 = Vec2.sub(w2, w1); var w1e12 = Vec2.dot(w1, e12); var w2e12 = Vec2.dot(w2, e12); var d12_1 = w2e12; var d12_2 = -w1e12; var e13 = Vec2.sub(w3, w1); var w1e13 = Vec2.dot(w1, e13); var w3e13 = Vec2.dot(w3, e13); var d13_1 = w3e13; var d13_2 = -w1e13; var e23 = Vec2.sub(w3, w2); var w2e23 = Vec2.dot(w2, e23); var w3e23 = Vec2.dot(w3, e23); var d23_1 = w3e23; var d23_2 = -w2e23; var n123 = Vec2.cross(e12, e13); var d123_1 = n123 * Vec2.cross(w2, w3); var d123_2 = n123 * Vec2.cross(w3, w1); var d123_3 = n123 * Vec2.cross(w1, w2); if (d12_2 <= 0 && d13_2 <= 0) { this.m_v1.a = 1; this.m_count = 1; return; } if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { var inv_d12 = 1 / (d12_1 + d12_2); this.m_v1.a = d12_1 * inv_d12; this.m_v2.a = d12_2 * inv_d12; this.m_count = 2; return; } if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { var inv_d13 = 1 / (d13_1 + d13_2); this.m_v1.a = d13_1 * inv_d13; this.m_v3.a = d13_2 * inv_d13; this.m_count = 2; this.m_v2.set(this.m_v3); return; } if (d12_1 <= 0 && d23_2 <= 0) { this.m_v2.a = 1; this.m_count = 1; this.m_v1.set(this.m_v2); return; } if (d13_1 <= 0 && d23_1 <= 0) { this.m_v3.a = 1; this.m_count = 1; this.m_v1.set(this.m_v3); return; } if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { var inv_d23 = 1 / (d23_1 + d23_2); this.m_v2.a = d23_1 * inv_d23; this.m_v3.a = d23_2 * inv_d23; this.m_count = 2; this.m_v1.set(this.m_v3); return; } var inv_d123 = 1 / (d123_1 + d123_2 + d123_3); this.m_v1.a = d123_1 * inv_d123; this.m_v2.a = d123_2 * inv_d123; this.m_v3.a = d123_3 * inv_d123; this.m_count = 3; }; Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) { var input = new DistanceInput(); input.proxyA.set(shapeA, indexA); input.proxyB.set(shapeB, indexB); input.transformA = xfA; input.transformB = xfB; input.useRadii = true; var cache = new SimplexCache(); var output = new DistanceOutput(); Distance(output, cache, input); return output.distance < 10 * Math.EPSILON; }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51}],14:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var Settings = require("../Settings"); var common = require("../util/common"); var Pool = require("../util/Pool"); var Vec2 = require("../common/Vec2"); var Math = require("../common/Math"); var AABB = require("./AABB"); module.exports = DynamicTree; function TreeNode(id) { this.id = id; this.aabb = new AABB(); this.userData = null; this.parent = null; this.child1 = null; this.child2 = null; this.height = -1; this.toString = function() { return this.id + ": " + this.userData; }; } TreeNode.prototype.isLeaf = function() { return this.child1 == null; }; function DynamicTree() { this.m_root = null; this.m_nodes = {}; this.m_lastProxyId = 0; this.m_pool = new Pool({ create: function() { return new TreeNode(); } }); } DynamicTree.prototype.getUserData = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); return node.userData; }; DynamicTree.prototype.getFatAABB = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); return node.aabb; }; DynamicTree.prototype.allocateNode = function() { var node = this.m_pool.allocate(); node.id = ++this.m_lastProxyId; node.userData = null; node.parent = null; node.child1 = null; node.child2 = null; node.height = -1; this.m_nodes[node.id] = node; return node; }; DynamicTree.prototype.freeNode = function(node) { this.m_pool.release(node); node.height = -1; delete this.m_nodes[node.id]; }; DynamicTree.prototype.createProxy = function(aabb, userData) { ASSERT && common.assert(AABB.isValid(aabb)); var node = this.allocateNode(); node.aabb.set(aabb); AABB.extend(node.aabb, Settings.aabbExtension); node.userData = userData; node.height = 0; this.insertLeaf(node); return node.id; }; DynamicTree.prototype.destroyProxy = function(id) { var node = this.m_nodes[id]; ASSERT && common.assert(!!node); ASSERT && common.assert(node.isLeaf()); this.removeLeaf(node); this.freeNode(node); }; DynamicTree.prototype.moveProxy = function(id, aabb, d) { ASSERT && common.assert(AABB.isValid(aabb)); ASSERT && common.assert(!d || Vec2.isValid(d)); var node = this.m_nodes[id]; ASSERT && common.assert(!!node); ASSERT && common.assert(node.isLeaf()); if (node.aabb.contains(aabb)) { return false; } this.removeLeaf(node); node.aabb.set(aabb); aabb = node.aabb; AABB.extend(aabb, Settings.aabbExtension); if (d.x < 0) { aabb.lowerBound.x += d.x * Settings.aabbMultiplier; } else { aabb.upperBound.x += d.x * Settings.aabbMultiplier; } if (d.y < 0) { aabb.lowerBound.y += d.y * Settings.aabbMultiplier; } else { aabb.upperBound.y += d.y * Settings.aabbMultiplier; } this.insertLeaf(node); return true; }; DynamicTree.prototype.insertLeaf = function(leaf) { ASSERT && common.assert(AABB.isValid(leaf.aabb)); if (this.m_root == null) { this.m_root = leaf; this.m_root.parent = null; return; } var leafAABB = leaf.aabb; var index = this.m_root; while (index.isLeaf() == false) { var child1 = index.child1; var child2 = index.child2; var area = index.aabb.getPerimeter(); var combinedAABB = new AABB(); combinedAABB.combine(index.aabb, leafAABB); var combinedArea = combinedAABB.getPerimeter(); var cost = 2 * combinedArea; var inheritanceCost = 2 * (combinedArea - area); var cost1; if (child1.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); cost1 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child1.aabb); var oldArea = child1.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost1 = newArea - oldArea + inheritanceCost; } var cost2; if (child2.isLeaf()) { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); cost2 = aabb.getPerimeter() + inheritanceCost; } else { var aabb = new AABB(); aabb.combine(leafAABB, child2.aabb); var oldArea = child2.aabb.getPerimeter(); var newArea = aabb.getPerimeter(); cost2 = newArea - oldArea + inheritanceCost; } if (cost < cost1 && cost < cost2) { break; } if (cost1 < cost2) { index = child1; } else { index = child2; } } var sibling = index; var oldParent = sibling.parent; var newParent = this.allocateNode(); newParent.parent = oldParent; newParent.userData = null; newParent.aabb.combine(leafAABB, sibling.aabb); newParent.height = sibling.height + 1; if (oldParent != null) { if (oldParent.child1 == sibling) { oldParent.child1 = newParent; } else { oldParent.child2 = newParent; } newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; } else { newParent.child1 = sibling; newParent.child2 = leaf; sibling.parent = newParent; leaf.parent = newParent; this.m_root = newParent; } index = leaf.parent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; ASSERT && common.assert(child1 != null); ASSERT && common.assert(child2 != null); index.height = 1 + Math.max(child1.height, child2.height); index.aabb.combine(child1.aabb, child2.aabb); index = index.parent; } }; DynamicTree.prototype.removeLeaf = function(leaf) { if (leaf == this.m_root) { this.m_root = null; return; } var parent = leaf.parent; var grandParent = parent.parent; var sibling; if (parent.child1 == leaf) { sibling = parent.child2; } else { sibling = parent.child1; } if (grandParent != null) { if (grandParent.child1 == parent) { grandParent.child1 = sibling; } else { grandParent.child2 = sibling; } sibling.parent = grandParent; this.freeNode(parent); var index = grandParent; while (index != null) { index = this.balance(index); var child1 = index.child1; var child2 = index.child2; index.aabb.combine(child1.aabb, child2.aabb); index.height = 1 + Math.max(child1.height, child2.height); index = index.parent; } } else { this.m_root = sibling; sibling.parent = null; this.freeNode(parent); } }; DynamicTree.prototype.balance = function(iA) { ASSERT && common.assert(iA != null); var A = iA; if (A.isLeaf() || A.height < 2) { return iA; } var B = A.child1; var C = A.child2; var balance = C.height - B.height; if (balance > 1) { var F = C.child1; var G = C.child2; C.child1 = A; C.parent = A.parent; A.parent = C; if (C.parent != null) { if (C.parent.child1 == iA) { C.parent.child1 = C; } else { C.parent.child2 = C; } } else { this.m_root = C; } if (F.height > G.height) { C.child2 = F; A.child2 = G; G.parent = A; A.aabb.combine(B.aabb, G.aabb); C.aabb.combine(A.aabb, F.aabb); A.height = 1 + Math.max(B.height, G.height); C.height = 1 + Math.max(A.height, F.height); } else { C.child2 = G; A.child2 = F; F.parent = A; A.aabb.combine(B.aabb, F.aabb); C.aabb.combine(A.aabb, G.aabb); A.height = 1 + Math.max(B.height, F.height); C.height = 1 + Math.max(A.height, G.height); } return C; } if (balance < -1) { var D = B.child1; var E = B.child2; B.child1 = A; B.parent = A.parent; A.parent = B; if (B.parent != null) { if (B.parent.child1 == A) { B.parent.child1 = B; } else { B.parent.child2 = B; } } else { this.m_root = B; } if (D.height > E.height) { B.child2 = D; A.child1 = E; E.parent = A; A.aabb.combine(C.aabb, E.aabb); B.aabb.combine(A.aabb, D.aabb); A.height = 1 + Math.max(C.height, E.height); B.height = 1 + Math.max(A.height, D.height); } else { B.child2 = E; A.child1 = D; D.parent = A; A.aabb.combine(C.aabb, D.aabb); B.aabb.combine(A.aabb, E.aabb); A.height = 1 + Math.max(C.height, D.height); B.height = 1 + Math.max(A.height, E.height); } return B; } return A; }; DynamicTree.prototype.getHeight = function() { if (this.m_root == null) { return 0; } return this.m_root.height; }; DynamicTree.prototype.getAreaRatio = function() { if (this.m_root == null) { return 0; } var root = this.m_root; var rootArea = root.aabb.getPerimeter(); var totalArea = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } totalArea += node.aabb.getPerimeter(); } iteratorPool.release(it); return totalArea / rootArea; }; DynamicTree.prototype.computeHeight = function(id) { var node; if (typeof id !== "undefined") { node = this.m_nodes[id]; } else { node = this.m_root; } if (node.isLeaf()) { return 0; } var height1 = ComputeHeight(node.child1); var height2 = ComputeHeight(node.child2); return 1 + Math.max(height1, height2); }; DynamicTree.prototype.validateStructure = function(node) { if (node == null) { return; } if (node == this.m_root) { ASSERT && common.assert(node.parent == null); } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { ASSERT && common.assert(child1 == null); ASSERT && common.assert(child2 == null); ASSERT && common.assert(node.height == 0); return; } ASSERT && common.assert(child1.parent == node); ASSERT && common.assert(child2.parent == node); this.validateStructure(child1); this.validateStructure(child2); }; DynamicTree.prototype.validateMetrics = function(node) { if (node == null) { return; } var child1 = node.child1; var child2 = node.child2; if (node.isLeaf()) { ASSERT && common.assert(child1 == null); ASSERT && common.assert(child2 == null); ASSERT && common.assert(node.height == 0); return; } var height1 = this.m_nodes[child1].height; var height2 = this.m_nodes[child2].height; var height = 1 + Math.max(height1, height2); ASSERT && common.assert(node.height == height); var aabb = new AABB(); aabb.combine(child1.aabb, child2.aabb); ASSERT && common.assert(AABB.areEqual(aabb, node.aabb)); this.validateMetrics(child1); this.validateMetrics(child2); }; DynamicTree.prototype.validate = function() { ValidateStructure(this.m_root); ValidateMetrics(this.m_root); ASSERT && common.assert(this.getHeight() == this.computeHeight()); }; DynamicTree.prototype.getMaxBalance = function() { var maxBalance = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height <= 1) { continue; } ASSERT && common.assert(node.isLeaf() == false); var balance = Math.abs(node.child2.height - node.child1.height); maxBalance = Math.max(maxBalance, balance); } iteratorPool.release(it); return maxBalance; }; DynamicTree.prototype.rebuildBottomUp = function() { var nodes = []; var count = 0; var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { if (node.height < 0) { continue; } if (node.isLeaf()) { node.parent = null; nodes[count] = node; ++count; } else { this.freeNode(node); } } iteratorPool.release(it); while (count > 1) { var minCost = Infinity; var iMin = -1, jMin = -1; for (var i = 0; i < count; ++i) { var aabbi = nodes[i].aabb; for (var j = i + 1; j < count; ++j) { var aabbj = nodes[j].aabb; var b = new AABB(); b.combine(aabbi, aabbj); var cost = b.getPerimeter(); if (cost < minCost) { iMin = i; jMin = j; minCost = cost; } } } var child1 = nodes[iMin]; var child2 = nodes[jMin]; var parent = this.allocateNode(); parent.child1 = child1; parent.child2 = child2; parent.height = 1 + Math.max(child1.height, child2.height); parent.aabb.combine(child1.aabb, child2.aabb); parent.parent = null; child1.parent = parent; child2.parent = parent; nodes[jMin] = nodes[count - 1]; nodes[iMin] = parent; --count; } this.m_root = nodes[0]; this.validate(); }; DynamicTree.prototype.shiftOrigin = function(newOrigin) { var node, it = iteratorPool.allocate().preorder(); while (node = it.next()) { var aabb = node.aabb; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; aabb.lowerBound.x -= newOrigin.x; aabb.lowerBound.y -= newOrigin.y; } iteratorPool.release(it); }; DynamicTree.prototype.query = function(aabb, queryCallback) { ASSERT && common.assert(typeof queryCallback === "function"); var stack = stackPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, aabb)) { if (node.isLeaf()) { var proceed = queryCallback(node.id); if (proceed == false) { return; } } else { stack.push(node.child1); stack.push(node.child2); } } } stackPool.release(stack); }; DynamicTree.prototype.rayCast = function(input, rayCastCallback) { ASSERT && common.assert(typeof rayCastCallback === "function"); var p1 = input.p1; var p2 = input.p2; var r = Vec2.sub(p2, p1); ASSERT && common.assert(r.lengthSquared() > 0); r.normalize(); var v = Vec2.cross(1, r); var abs_v = Vec2.abs(v); var maxFraction = input.maxFraction; var segmentAABB = new AABB(); var t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); var stack = stackPool.allocate(); var subInput = inputPool.allocate(); stack.push(this.m_root); while (stack.length > 0) { var node = stack.pop(); if (node == null) { continue; } if (AABB.testOverlap(node.aabb, segmentAABB) == false) { continue; } var c = node.aabb.getCenter(); var h = node.aabb.getExtents(); var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h); if (separation > 0) { continue; } if (node.isLeaf()) { subInput.p1 = Vec2.clone(input.p1); subInput.p2 = Vec2.clone(input.p2); subInput.maxFraction = maxFraction; var value = rayCastCallback(subInput, node.id); if (value == 0) { return; } if (value > 0) { maxFraction = value; t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2); segmentAABB.combinePoints(p1, t); } } else { stack.push(node.child1); stack.push(node.child2); } } stackPool.release(stack); inputPool.release(subInput); }; var inputPool = new Pool({ create: function() { return {}; }, release: function(stack) {} }); var stackPool = new Pool({ create: function() { return []; }, release: function(stack) { stack.length = 0; } }); var iteratorPool = new Pool({ create: function() { return new Iterator(); }, release: function(iterator) { iterator.close(); } }); function Iterator() { var parents = []; var states = []; return { preorder: function(root) { parents.length = 0; parents.push(root); states.length = 0; states.push(0); return this; }, next: function() { while (parents.length > 0) { var i = parents.length - 1; var node = parents[i]; if (states[i] === 0) { states[i] = 1; return node; } if (states[i] === 1) { states[i] = 2; if (node.child1) { parents.push(node.child1); states.push(1); return node.child1; } } if (states[i] === 2) { states[i] = 3; if (node.child2) { parents.push(node.child2); states.push(1); return node.child2; } } parents.pop(); states.pop(); } }, close: function() { parents.length = 0; } }; } },{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = TimeOfImpact; module.exports.Input = TOIInput; module.exports.Output = TOIOutput; var Settings = require("../Settings"); var common = require("../util/common"); var Timer = require("../util/Timer"); var stats = require("../common/stats"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Distance = require("./Distance"); var DistanceInput = Distance.Input; var DistanceOutput = Distance.Output; var DistanceProxy = Distance.Proxy; var SimplexCache = Distance.Cache; function TOIInput() { this.proxyA = new DistanceProxy(); this.proxyB = new DistanceProxy(); this.sweepA = new Sweep(); this.sweepB = new Sweep(); this.tMax; } TOIOutput.e_unknown = 0; TOIOutput.e_failed = 1; TOIOutput.e_overlapped = 2; TOIOutput.e_touching = 3; TOIOutput.e_separated = 4; function TOIOutput() { this.state; this.t; } stats.toiTime = 0; stats.toiMaxTime = 0; stats.toiCalls = 0; stats.toiIters = 0; stats.toiMaxIters = 0; stats.toiRootIters = 0; stats.toiMaxRootIters = 0; function TimeOfImpact(output, input) { var timer = Timer.now(); ++stats.toiCalls; output.state = TOIOutput.e_unknown; output.t = input.tMax; var proxyA = input.proxyA; var proxyB = input.proxyB; var sweepA = input.sweepA; var sweepB = input.sweepB; DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0); DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0); sweepA.normalize(); sweepB.normalize(); var tMax = input.tMax; var totalRadius = proxyA.m_radius + proxyB.m_radius; var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop); var tolerance = .25 * Settings.linearSlop; ASSERT && common.assert(target > tolerance); var t1 = 0; var k_maxIterations = Settings.maxTOIIterations; var iter = 0; var cache = new SimplexCache(); var distanceInput = new DistanceInput(); distanceInput.proxyA = input.proxyA; distanceInput.proxyB = input.proxyB; distanceInput.useRadii = false; for (;;) { var xfA = Transform.identity(); var xfB = Transform.identity(); sweepA.getTransform(xfA, t1); sweepB.getTransform(xfB, t1); DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s); DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s); distanceInput.transformA = xfA; distanceInput.transformB = xfB; var distanceOutput = new DistanceOutput(); Distance(distanceOutput, cache, distanceInput); DEBUG && common.debug("distance:", distanceOutput.distance); if (distanceOutput.distance <= 0) { output.state = TOIOutput.e_overlapped; output.t = 0; break; } if (distanceOutput.distance < target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; break; } var fcn = new SeparationFunction(); fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1); if (false) { var N = 100; var dx = 1 / N; var xs = []; var fs = []; var x = 0; for (var i = 0; i <= N; ++i) { sweepA.getTransform(xfA, x); sweepB.getTransform(xfB, x); var f = fcn.evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } var done = false; var t2 = tMax; var pushBackIter = 0; for (;;) { var s2 = fcn.findMinSeparation(t2); var indexA = fcn.indexA; var indexB = fcn.indexB; if (s2 > target + tolerance) { output.state = TOIOutput.e_separated; output.t = tMax; done = true; break; } if (s2 > target - tolerance) { t1 = t2; break; } var s1 = fcn.evaluate(t1); var indexA = fcn.indexA; var indexB = fcn.indexB; DEBUG && common.debug("s1:", s1, target, tolerance, t1); if (s1 < target - tolerance) { output.state = TOIOutput.e_failed; output.t = t1; done = true; break; } if (s1 <= target + tolerance) { output.state = TOIOutput.e_touching; output.t = t1; done = true; break; } var rootIterCount = 0; var a1 = t1, a2 = t2; for (;;) { var t; if (rootIterCount & 1) { t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { t = .5 * (a1 + a2); } ++rootIterCount; ++stats.toiRootIters; var s = fcn.evaluate(t); var indexA = fcn.indexA; var indexB = fcn.indexB; if (Math.abs(s - target) < tolerance) { t2 = t; break; } if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == Settings.maxPolygonVertices) { break; } } ++iter; ++stats.toiIters; if (done) { break; } if (iter == k_maxIterations) { output.state = TOIOutput.e_failed; output.t = t1; break; } } stats.toiMaxIters = Math.max(stats.toiMaxIters, iter); var time = Timer.diff(timer); stats.toiMaxTime = Math.max(stats.toiMaxTime, time); stats.toiTime += time; } var e_points = 1; var e_faceA = 2; var e_faceB = 3; function SeparationFunction() { this.m_proxyA = new DistanceProxy(); this.m_proxyB = new DistanceProxy(); this.m_sweepA; this.m_sweepB; this.m_type; this.m_localPoint = Vec2.zero(); this.m_axis = Vec2.zero(); } SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) { this.m_proxyA = proxyA; this.m_proxyB = proxyB; var count = cache.count; ASSERT && common.assert(0 < count && count < 3); this.m_sweepA = sweepA; this.m_sweepB = sweepB; var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t1); this.m_sweepB.getTransform(xfB, t1); if (count == 1) { this.m_type = e_points; var localPointA = this.m_proxyA.getVertex(cache.indexA[0]); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); this.m_axis.wSet(1, pointB, -1, pointA); var s = this.m_axis.normalize(); return s; } else if (cache.indexA[0] == cache.indexA[1]) { this.m_type = e_faceB; var localPointB1 = proxyB.getVertex(cache.indexB[0]); var localPointB2 = proxyB.getVertex(cache.indexB[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfB.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointB1, localPointB2); var pointB = Transform.mul(xfB, this.m_localPoint); var localPointA = proxyA.getVertex(cache.indexA[0]); var pointA = Transform.mul(xfA, localPointA); var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } else { this.m_type = e_faceA; var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]); var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]); this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1); this.m_axis.normalize(); var normal = Rot.mul(xfA.q, this.m_axis); this.m_localPoint = Vec2.mid(localPointA1, localPointA2); var pointA = Transform.mul(xfA, this.m_localPoint); var localPointB = this.m_proxyB.getVertex(cache.indexB[0]); var pointB = Transform.mul(xfB, localPointB); var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); if (s < 0) { this.m_axis = Vec2.neg(this.m_axis); s = -s; } return s; } }; SeparationFunction.prototype.compute = function(find, t) { var xfA = Transform.identity(); var xfB = Transform.identity(); this.m_sweepA.getTransform(xfA, t); this.m_sweepB.getTransform(xfB, t); switch (this.m_type) { case e_points: { if (find) { var axisA = Rot.mulT(xfA.q, this.m_axis); var axisB = Rot.mulT(xfB.q, Vec2.neg(this.m_axis)); this.indexA = this.m_proxyA.getSupport(axisA); this.indexB = this.m_proxyB.getSupport(axisB); } var localPointA = this.m_proxyA.getVertex(this.indexA); var localPointB = this.m_proxyB.getVertex(this.indexB); var pointA = Transform.mul(xfA, localPointA); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis); return sep; } case e_faceA: { var normal = Rot.mul(xfA.q, this.m_axis); var pointA = Transform.mul(xfA, this.m_localPoint); if (find) { var axisB = Rot.mulT(xfB.q, Vec2.neg(normal)); this.indexA = -1; this.indexB = this.m_proxyB.getSupport(axisB); } var localPointB = this.m_proxyB.getVertex(this.indexB); var pointB = Transform.mul(xfB, localPointB); var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal); return sep; } case e_faceB: { var normal = Rot.mul(xfB.q, this.m_axis); var pointB = Transform.mul(xfB, this.m_localPoint); if (find) { var axisA = Rot.mulT(xfA.q, Vec2.neg(normal)); this.indexB = -1; this.indexA = this.m_proxyA.getSupport(axisA); } var localPointA = this.m_proxyA.getVertex(this.indexA); var pointA = Transform.mul(xfA, localPointA); var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal); return sep; } default: ASSERT && common.assert(false); if (find) { this.indexA = -1; this.indexB = -1; } return 0; } }; SeparationFunction.prototype.findMinSeparation = function(t) { return this.compute(true, t); }; SeparationFunction.prototype.evaluate = function(t) { return this.compute(false, t); }; },{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat22; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); function Mat22(a, b, c, d) { if (typeof a === "object" && a !== null) { this.ex = Vec2.clone(a); this.ey = Vec2.clone(b); } else if (typeof a === "number") { this.ex = Vec2.neo(a, c); this.ey = Vec2.neo(b, d); } else { this.ex = Vec2.zero(); this.ey = Vec2.zero(); } } Mat22.prototype.toString = function() { return JSON.stringify(this); }; Mat22.isValid = function(o) { return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey); }; Mat22.assert = function(o) { if (!ASSERT) return; if (!Mat22.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Mat22!"); } }; Mat22.prototype.set = function(a, b, c, d) { if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") { this.ex.set(a, c); this.ey.set(b, d); } else if (typeof a === "object" && typeof b === "object") { this.ex.set(a); this.ey.set(b); } else if (typeof a === "object") { ASSERT && Mat22.assert(a); this.ex.set(a.ex); this.ey.set(a.ey); } else { ASSERT && common.assert(false); } }; Mat22.prototype.setIdentity = function() { this.ex.x = 1; this.ey.x = 0; this.ex.y = 0; this.ey.y = 1; }; Mat22.prototype.setZero = function() { this.ex.x = 0; this.ey.x = 0; this.ex.y = 0; this.ey.y = 0; }; Mat22.prototype.getInverse = function() { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var imx = new Mat22(); imx.ex.x = det * d; imx.ey.x = -det * b; imx.ex.y = -det * c; imx.ey.y = det * a; return imx; }; Mat22.prototype.solve = function(v) { ASSERT && Vec2.assert(v); var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } var w = Vec2.zero(); w.x = det * (d * v.x - b * v.y); w.y = det * (a * v.y - c * v.x); return w; }; Mat22.mul = function(mx, v) { if (v && "x" in v && "y" in v) { ASSERT && Vec2.assert(v); var x = mx.ex.x * v.x + mx.ey.x * v.y; var y = mx.ex.y * v.x + mx.ey.y * v.y; return Vec2.neo(x, y); } else if (v && "ex" in v && "ey" in v) { ASSERT && Mat22.assert(v); return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey)); } ASSERT && common.assert(false); }; Mat22.mulT = function(mx, v) { if (v && "x" in v && "y" in v) { ASSERT && Vec2.assert(v); return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey)); } else if (v && "ex" in v && "ey" in v) { ASSERT && Mat22.assert(v); var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex)); var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey)); return new Mat22(c1, c2); } ASSERT && common.assert(false); }; Mat22.abs = function(mx) { ASSERT && Mat22.assert(mx); return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey)); }; Mat22.add = function(mx1, mx2) { ASSERT && Mat22.assert(mx1); ASSERT && Mat22.assert(mx2); return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey)); }; },{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Mat33; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Vec3 = require("./Vec3"); function Mat33(a, b, c) { if (typeof a === "object" && a !== null) { this.ex = Vec3.clone(a); this.ey = Vec3.clone(b); this.ez = Vec3.clone(c); } else { this.ex = Vec3(); this.ey = Vec3(); this.ez = Vec3(); } } Mat33.prototype.toString = function() { return JSON.stringify(this); }; Mat33.isValid = function(o) { return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez); }; Mat33.assert = function(o) { if (!ASSERT) return; if (!Mat33.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Mat33!"); } }; Mat33.prototype.setZero = function() { this.ex.setZero(); this.ey.setZero(); this.ez.setZero(); return this; }; Mat33.prototype.solve33 = function(v) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var r = new Vec3(); r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez)); r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez)); r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v)); return r; }; Mat33.prototype.solve22 = function(v) { var a11 = this.ex.x; var a12 = this.ey.x; var a21 = this.ex.y; var a22 = this.ey.y; var det = a11 * a22 - a12 * a21; if (det != 0) { det = 1 / det; } var r = Vec2.zero(); r.x = det * (a22 * v.x - a12 * v.y); r.y = det * (a11 * v.y - a21 * v.x); return r; }; Mat33.prototype.getInverse22 = function(M) { var a = this.ex.x; var b = this.ey.x; var c = this.ex.y; var d = this.ey.y; var det = a * d - b * c; if (det != 0) { det = 1 / det; } M.ex.x = det * d; M.ey.x = -det * b; M.ex.z = 0; M.ex.y = -det * c; M.ey.y = det * a; M.ey.z = 0; M.ez.x = 0; M.ez.y = 0; M.ez.z = 0; }; Mat33.prototype.getSymInverse33 = function(M) { var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez)); if (det != 0) { det = 1 / det; } var a11 = this.ex.x; var a12 = this.ey.x; var a13 = this.ez.x; var a22 = this.ey.y; var a23 = this.ez.y; var a33 = this.ez.z; M.ex.x = det * (a22 * a33 - a23 * a23); M.ex.y = det * (a13 * a23 - a12 * a33); M.ex.z = det * (a12 * a23 - a13 * a22); M.ey.x = M.ex.y; M.ey.y = det * (a11 * a33 - a13 * a13); M.ey.z = det * (a13 * a12 - a11 * a23); M.ez.x = M.ex.z; M.ez.y = M.ey.z; M.ez.z = det * (a11 * a22 - a12 * a12); }; Mat33.mul = function(a, b) { ASSERT && Mat33.assert(a); if (b && "z" in b && "y" in b && "x" in b) { ASSERT && Vec3.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z; var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z; var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z; return new Vec3(x, y, z); } else if (b && "y" in b && "x" in b) { ASSERT && Vec2.assert(b); var x = a.ex.x * b.x + a.ey.x * b.y; var y = a.ex.y * b.x + a.ey.y * b.y; return Vec2.neo(x, y); } ASSERT && common.assert(false); }; Mat33.add = function(a, b) { ASSERT && Mat33.assert(a); ASSERT && Mat33.assert(b); return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z); }; },{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var native = Math; var math = module.exports = create(native); math.EPSILON = 1e-9; math.isFinite = function(x) { return typeof x === "number" && isFinite(x) && !isNaN(x); }; math.assert = function(x) { if (!ASSERT) return; if (!math.isFinite(x)) { DEBUG && common.debug(x); throw new Error("Invalid Number!"); } }; math.invSqrt = function(x) { return 1 / native.sqrt(x); }; math.nextPowerOfTwo = function(x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; }; math.isPowerOfTwo = function(x) { return x > 0 && (x & x - 1) == 0; }; math.mod = function(num, min, max) { if (typeof min === "undefined") { max = 1, min = 0; } else if (typeof max === "undefined") { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; math.clamp = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; math.random = function(min, max) { if (typeof min === "undefined") { max = 1; min = 0; } else if (typeof max === "undefined") { max = min; min = 0; } return min == max ? min : native.random() * (max - min) + min; }; },{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Position; var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Position() { this.c = Vec2.zero(); this.a = 0; } Position.prototype.getTransform = function(xf, p) { xf.q.set(this.a); xf.p.set(Vec2.sub(this.c, Rot.mul(xf.q, p))); return xf; }; },{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Rot; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Math = require("./Math"); function Rot(angle) { if (!(this instanceof Rot)) { return new Rot(angle); } if (typeof angle === "number") { this.setAngle(angle); } else if (typeof angle === "object") { this.set(angle); } else { this.setIdentity(); } } Rot.neo = function(angle) { var obj = Object.create(Rot.prototype); obj.setAngle(angle); return obj; }; Rot.clone = function(rot) { ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); ojb.s = rot.s; ojb.c = rot.c; return ojb; }; Rot.identity = function(rot) { ASSERT && Rot.assert(rot); var obj = Object.create(Rot.prototype); obj.s = 0; obj.c = 1; return obj; }; Rot.isValid = function(o) { return o && Math.isFinite(o.s) && Math.isFinite(o.c); }; Rot.assert = function(o) { if (!ASSERT) return; if (!Rot.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Rot!"); } }; Rot.prototype.setIdentity = function() { this.s = 0; this.c = 1; }; Rot.prototype.set = function(angle) { if (typeof angle === "object") { ASSERT && Rot.assert(angle); this.s = angle.s; this.c = angle.c; } else { ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); } }; Rot.prototype.setAngle = function(angle) { ASSERT && Math.assert(angle); this.s = Math.sin(angle); this.c = Math.cos(angle); }; Rot.prototype.getAngle = function() { return Math.atan2(this.s, this.c); }; Rot.prototype.getXAxis = function() { return Vec2.neo(this.c, this.s); }; Rot.prototype.getYAxis = function() { return Vec2.neo(-this.s, this.c); }; Rot.mul = function(rot, m) { ASSERT && Rot.assert(rot); if ("c" in m && "s" in m) { ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.s * m.c + rot.c * m.s; qr.c = rot.c * m.c - rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y); } }; Rot.mulSub = function(rot, v, w) { var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y); var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y); return Vec2.neo(x, y); }; Rot.mulT = function(rot, m) { if ("c" in m && "s" in m) { ASSERT && Rot.assert(m); var qr = Rot.identity(); qr.s = rot.c * m.s - rot.s * m.c; qr.c = rot.c * m.c + rot.s * m.s; return qr; } else if ("x" in m && "y" in m) { ASSERT && Vec2.assert(m); return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y); } }; },{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Sweep; var common = require("../util/common"); var Math = require("./Math"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); var Transform = require("./Transform"); function Sweep(c, a) { ASSERT && common.assert(typeof c === "undefined"); ASSERT && common.assert(typeof a === "undefined"); this.localCenter = Vec2.zero(); this.c = Vec2.zero(); this.a = 0; this.alpha0 = 0; this.c0 = Vec2.zero(); this.a0 = 0; } Sweep.prototype.setTransform = function(xf) { var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); this.a = xf.q.getAngle(); this.a0 = xf.q.getAngle(); }; Sweep.prototype.setLocalCenter = function(localCenter, xf) { this.localCenter.set(localCenter); var c = Transform.mul(xf, this.localCenter); this.c.set(c); this.c0.set(c); }; Sweep.prototype.getTransform = function(xf, beta) { beta = typeof beta === "undefined" ? 0 : beta; xf.q.setAngle((1 - beta) * this.a0 + beta * this.a); xf.p.wSet(1 - beta, this.c0, beta, this.c); xf.p.sub(Rot.mul(xf.q, this.localCenter)); }; Sweep.prototype.advance = function(alpha) { ASSERT && common.assert(this.alpha0 < 1); var beta = (alpha - this.alpha0) / (1 - this.alpha0); this.c0.wSet(beta, this.c, 1 - beta, this.c0); this.a0 = beta * this.a + (1 - beta) * this.a0; this.alpha0 = alpha; }; Sweep.prototype.forward = function() { this.a0 = this.a; this.c0.set(this.c); }; Sweep.prototype.normalize = function() { var a0 = Math.mod(this.a0, -Math.PI, +Math.PI); this.a -= this.a0 - a0; this.a0 = a0; }; Sweep.prototype.clone = function() { var clone = new Sweep(); clone.localCenter.set(this.localCenter); clone.alpha0 = this.alpha0; clone.a0 = this.a0; clone.a = this.a; clone.c0.set(this.c0); clone.c.set(this.c); return clone; }; Sweep.prototype.set = function(that) { this.localCenter.set(that.localCenter); this.alpha0 = that.alpha0; this.a0 = that.a0; this.a = that.a; this.c0.set(that.c0); this.c.set(that.c); }; },{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Transform; var common = require("../util/common"); var Vec2 = require("./Vec2"); var Rot = require("./Rot"); function Transform(position, rotation) { if (!(this instanceof Transform)) { return new Transform(position, rotation); } this.p = Vec2.zero(); this.q = Rot.identity(); if (typeof position !== "undefined") { this.p.set(position); } if (typeof rotation !== "undefined") { this.q.set(rotation); } } Transform.clone = function(xf) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(xf.p); obj.q = Rot.clone(xf.q); return obj; }; Transform.neo = function(position, rotation) { var obj = Object.create(Transform.prototype); obj.p = Vec2.clone(position); obj.q = Rot.clone(rotation); return obj; }; Transform.identity = function() { var obj = Object.create(Transform.prototype); obj.p = Vec2.zero(); obj.q = Rot.identity(); return obj; }; Transform.prototype.setIdentity = function() { this.p.setZero(); this.q.setIdentity(); }; Transform.prototype.set = function(a, b) { if (Transform.isValid(a)) { this.p.set(a.p); this.q.set(a.q); } else { this.p.set(a); this.q.set(b); } }; Transform.isValid = function(o) { return o && Vec2.isValid(o.p) && Rot.isValid(o.q); }; Transform.assert = function(o) { if (!ASSERT) return; if (!Transform.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Transform!"); } }; Transform.mul = function(a, b) { ASSERT && Transform.assert(a); if (Array.isArray(b)) { var arr = []; for (var i = 0; i < b.length; i++) { arr[i] = Transform.mul(a, b[i]); } return arr; } else if ("x" in b && "y" in b) { ASSERT && Vec2.assert(b); var x = a.q.c * b.x - a.q.s * b.y + a.p.x; var y = a.q.s * b.x + a.q.c * b.y + a.p.y; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q = Rot.mul(a.q, b.q); xf.p = Vec2.add(Rot.mul(a.q, b.p), a.p); return xf; } }; Transform.mulT = function(a, b) { ASSERT && Transform.assert(a); if ("x" in b && "y" in b) { ASSERT && Vec2.assert(b); var px = b.x - a.p.x; var py = b.y - a.p.y; var x = a.q.c * px + a.q.s * py; var y = -a.q.s * px + a.q.c * py; return Vec2.neo(x, y); } else if ("p" in b && "q" in b) { ASSERT && Transform.assert(b); var xf = Transform.identity(); xf.q.set(Rot.mulT(a.q, b.q)); xf.p.set(Rot.mulT(a.q, Vec2.sub(b.p, a.p))); return xf; } }; },{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec2; var common = require("../util/common"); var Math = require("./Math"); function Vec2(x, y) { if (!(this instanceof Vec2)) { return new Vec2(x, y); } if (typeof x === "undefined") { this.x = 0, this.y = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y; } else { this.x = x, this.y = y; } ASSERT && Vec2.assert(this); } Vec2.zero = function() { var obj = Object.create(Vec2.prototype); obj.x = 0; obj.y = 0; return obj; }; Vec2.neo = function(x, y) { var obj = Object.create(Vec2.prototype); obj.x = x; obj.y = y; return obj; }; Vec2.clone = function(v, depricated) { ASSERT && Vec2.assert(v); ASSERT && common.assert(!depricated); return Vec2.neo(v.x, v.y); }; Vec2.prototype.toString = function() { return JSON.stringify(this); }; Vec2.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y); }; Vec2.assert = function(o) { if (!ASSERT) return; if (!Vec2.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Vec2!"); } }; Vec2.prototype.clone = function(depricated) { return Vec2.clone(this, depricated); }; Vec2.prototype.setZero = function() { this.x = 0; this.y = 0; return this; }; Vec2.prototype.set = function(x, y) { if (typeof x === "object") { ASSERT && Vec2.assert(x); this.x = x.x; this.y = x.y; } else { ASSERT && Math.assert(x); ASSERT && Math.assert(y); this.x = x; this.y = y; } return this; }; Vec2.prototype.wSet = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x = x; this.y = y; return this; }; Vec2.prototype.add = function(w) { ASSERT && Vec2.assert(w); this.x += w.x; this.y += w.y; return this; }; Vec2.prototype.wAdd = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x += x; this.y += y; return this; }; Vec2.prototype.wSub = function(a, v, b, w) { ASSERT && Math.assert(a); ASSERT && Vec2.assert(v); var x = a * v.x; var y = a * v.y; if (typeof b !== "undefined" || typeof w !== "undefined") { ASSERT && Math.assert(b); ASSERT && Vec2.assert(w); x += b * w.x; y += b * w.y; } this.x -= x; this.y -= y; return this; }; Vec2.prototype.sub = function(w) { ASSERT && Vec2.assert(w); this.x -= w.x; this.y -= w.y; return this; }; Vec2.prototype.mul = function(m) { ASSERT && Math.assert(m); this.x *= m; this.y *= m; return this; }; Vec2.prototype.length = function() { return Vec2.lengthOf(this); }; Vec2.prototype.lengthSquared = function() { return Vec2.lengthSquared(this); }; Vec2.prototype.normalize = function() { var length = this.length(); if (length < Math.EPSILON) { return 0; } var invLength = 1 / length; this.x *= invLength; this.y *= invLength; return length; }; Vec2.lengthOf = function(v) { ASSERT && Vec2.assert(v); return Math.sqrt(v.x * v.x + v.y * v.y); }; Vec2.lengthSquared = function(v) { ASSERT && Vec2.assert(v); return v.x * v.x + v.y * v.y; }; Vec2.distance = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return Math.sqrt(dx * dx + dy * dy); }; Vec2.distanceSquared = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); var dx = v.x - w.x, dy = v.y - w.y; return dx * dx + dy * dy; }; Vec2.areEqual = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y; }; Vec2.skew = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(-v.y, v.x); }; Vec2.dot = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v.x * w.x + v.y * w.y; }; Vec2.cross = function(v, w) { if (typeof w === "number") { ASSERT && Vec2.assert(v); ASSERT && Math.assert(w); return Vec2.neo(w * v.y, -w * v.x); } else if (typeof v === "number") { ASSERT && Math.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y, v * w.x); } else { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return v.x * w.y - v.y * w.x; } }; Vec2.addCross = function(a, v, w) { if (typeof w === "number") { ASSERT && Vec2.assert(v); ASSERT && Math.assert(w); return Vec2.neo(w * v.y + a.x, -w * v.x + a.y); } else if (typeof v === "number") { ASSERT && Math.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(-v * w.y + a.x, v * w.x + a.y); } ASSERT && common.assert(false); }; Vec2.add = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(v.x + w.x, v.y + w.y); }; Vec2.wAdd = function(a, v, b, w) { var r = Vec2.zero(); r.wAdd(a, v, b, w); return r; }; Vec2.sub = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(v.x - w.x, v.y - w.y); }; Vec2.mul = function(a, b) { if (typeof a === "object") { ASSERT && Vec2.assert(a); ASSERT && Math.assert(b); return Vec2.neo(a.x * b, a.y * b); } else if (typeof b === "object") { ASSERT && Math.assert(a); ASSERT && Vec2.assert(b); return Vec2.neo(a * b.x, a * b.y); } }; Vec2.prototype.neg = function() { this.x = -this.x; this.y = -this.y; return this; }; Vec2.neg = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(-v.x, -v.y); }; Vec2.abs = function(v) { ASSERT && Vec2.assert(v); return Vec2.neo(Math.abs(v.x), Math.abs(v.y)); }; Vec2.mid = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5); }; Vec2.upper = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y)); }; Vec2.lower = function(v, w) { ASSERT && Vec2.assert(v); ASSERT && Vec2.assert(w); return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y)); }; Vec2.prototype.clamp = function(max) { var lengthSqr = this.x * this.x + this.y * this.y; if (lengthSqr > max * max) { var invLength = Math.invSqrt(lengthSqr); this.x *= invLength * max; this.y *= invLength * max; } return this; }; Vec2.clamp = function(v, max) { v = Vec2.neo(v.x, v.y); v.clamp(max); return v; }; },{"../util/common":51,"./Math":18}],24:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Vec3; var common = require("../util/common"); var Math = require("./Math"); function Vec3(x, y, z) { if (!(this instanceof Vec3)) { return new Vec3(x, y, z); } if (typeof x === "undefined") { this.x = 0, this.y = 0, this.z = 0; } else if (typeof x === "object") { this.x = x.x, this.y = x.y, this.z = x.z; } else { this.x = x, this.y = y, this.z = z; } ASSERT && Vec3.assert(this); } Vec3.prototype.toString = function() { return JSON.stringify(this); }; Vec3.isValid = function(v) { return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z); }; Vec3.assert = function(o) { if (!ASSERT) return; if (!Vec3.isValid(o)) { DEBUG && common.debug(o); throw new Error("Invalid Vec3!"); } }; Vec3.prototype.setZero = function() { this.x = 0; this.y = 0; this.z = 0; return this; }; Vec3.prototype.set = function(x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; Vec3.prototype.add = function(w) { this.x += w.x; this.y += w.y; this.z += w.z; return this; }; Vec3.prototype.sub = function(w) { this.x -= w.x; this.y -= w.y; this.z -= w.z; return this; }; Vec3.prototype.mul = function(m) { this.x *= m; this.y *= m; this.z *= m; return this; }; Vec3.areEqual = function(v, w) { return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y && v.z == w.z; }; Vec3.dot = function(v, w) { return v.x * w.x + v.y * w.y + v.z * w.z; }; Vec3.cross = function(v, w) { return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x); }; Vec3.add = function(v, w) { return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z); }; Vec3.sub = function(v, w) { return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z); }; Vec3.mul = function(v, m) { return new Vec3(m * v.x, m * v.y, m * v.z); }; Vec3.prototype.neg = function(m) { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }; Vec3.neg = function(v) { return new Vec3(-v.x, -v.y, -v.z); }; },{"../util/common":51,"./Math":18}],25:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Velocity; var Vec2 = require("./Vec2"); function Velocity() { this.v = Vec2.zero(); this.w = 0; } },{"./Vec2":23}],26:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.toString = function(newline) { newline = typeof newline === "string" ? newline : "\n"; var string = ""; for (var name in this) { if (typeof this[name] !== "function" && typeof this[name] !== "object") { string += name + ": " + this[name] + newline; } } return string; }; },{}],27:[function(require,module,exports){ exports.internal = {}; exports.Math = require("./common/Math"); exports.Vec2 = require("./common/Vec2"); exports.Transform = require("./common/Transform"); exports.Rot = require("./common/Rot"); exports.AABB = require("./collision/AABB"); exports.Shape = require("./Shape"); exports.Fixture = require("./Fixture"); exports.Body = require("./Body"); exports.Contact = require("./Contact"); exports.Joint = require("./Joint"); exports.World = require("./World"); exports.Circle = require("./shape/CircleShape"); exports.Edge = require("./shape/EdgeShape"); exports.Polygon = require("./shape/PolygonShape"); exports.Chain = require("./shape/ChainShape"); exports.Box = require("./shape/BoxShape"); require("./shape/CollideCircle"); require("./shape/CollideEdgeCircle"); exports.internal.CollidePolygons = require("./shape/CollidePolygon"); require("./shape/CollideCirclePolygone"); require("./shape/CollideEdgePolygon"); exports.DistanceJoint = require("./joint/DistanceJoint"); exports.FrictionJoint = require("./joint/FrictionJoint"); exports.GearJoint = require("./joint/GearJoint"); exports.MotorJoint = require("./joint/MotorJoint"); exports.MouseJoint = require("./joint/MouseJoint"); exports.PrismaticJoint = require("./joint/PrismaticJoint"); exports.PulleyJoint = require("./joint/PulleyJoint"); exports.RevoluteJoint = require("./joint/RevoluteJoint"); exports.RopeJoint = require("./joint/RopeJoint"); exports.WeldJoint = require("./joint/WeldJoint"); exports.WheelJoint = require("./joint/WheelJoint"); exports.internal.Sweep = require("./common/Sweep"); exports.internal.stats = require("./common/stats"); exports.internal.Manifold = require("./Manifold"); exports.internal.Distance = require("./collision/Distance"); exports.internal.TimeOfImpact = require("./collision/TimeOfImpact"); exports.internal.DynamicTree = require("./collision/DynamicTree"); exports.internal.Settings = require("./Settings"); },{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = DistanceJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); DistanceJoint.TYPE = "distance-joint"; DistanceJoint._super = Joint; DistanceJoint.prototype = create(DistanceJoint._super.prototype); var DistanceJointDef = { frequencyHz: 0, dampingRatio: 0 }; function DistanceJoint(def, bodyA, anchorA, bodyB, anchorB) { if (!(this instanceof DistanceJoint)) { return new DistanceJoint(def, bodyA, anchorA, bodyB, anchorB); } def = options(def, DistanceJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = DistanceJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchorA); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchorB); this.m_length = Vec2.distance(anchorB, anchorA); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = 0; this.m_gamma = 0; this.m_bias = 0; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } DistanceJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; DistanceJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; DistanceJoint.prototype.setLength = function(length) { this.m_length = length; }; DistanceJoint.prototype.getLength = function() { return this.m_length; }; DistanceJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; DistanceJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; DistanceJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; DistanceJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; DistanceJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; DistanceJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; DistanceJoint.prototype.getReactionForce = function(inv_dt) { var F = Vec2.mul(inv_dt * this.m_impulse, this.m_u); return F; }; DistanceJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; DistanceJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA)); var length = this.m_u.length(); if (length > Settings.linearSlop) { this.m_u.mul(1 / length); } else { this.m_u.set(0, 0); } var crAu = Vec2.cross(this.m_rA, this.m_u); var crBu = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (this.m_frequencyHz > 0) { var C = length - this.m_length; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_mass * this.m_dampingRatio * omega; var k = this.m_mass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invMass += this.m_gamma; this.m_mass = invMass != 0 ? 1 / invMass : 0; } else { this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA); var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse); this.m_impulse += impulse; var P = Vec2.mul(impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; DistanceJoint.prototype.solvePositionConstraints = function(step) { if (this.m_frequencyHz > 0) { return true; } var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var length = u.normalize(); var C = length - this.m_length; C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = FrictionJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); FrictionJoint.TYPE = "friction-joint"; FrictionJoint._super = Joint; FrictionJoint.prototype = create(FrictionJoint._super.prototype); var FrictionJointDef = { maxForce: 0, maxTorque: 0 }; function FrictionJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof FrictionJoint)) { return new FrictionJoint(def, bodyA, bodyB, anchor); } def = options(def, FrictionJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = FrictionJoint.TYPE; if (anchor) { this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); } else { this.m_localAnchorA = Vec2.zero(); this.m_localAnchorB = Vec2.zero(); } this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } FrictionJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; FrictionJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; FrictionJoint.prototype.setMaxForce = function(force) { ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; FrictionJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; FrictionJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; FrictionJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; FrictionJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; FrictionJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; FrictionJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * this.m_linearImpulse; }; FrictionJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; FrictionJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; { var Cdot = wB - wA; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA))); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = this.m_linearImpulse; this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) { this.m_linearImpulse.normalize(); this.m_linearImpulse.mul(maxImpulse); } impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; FrictionJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = GearJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var RevoluteJoint = require("./RevoluteJoint"); var PrismaticJoint = require("./PrismaticJoint"); GearJoint.TYPE = "gear-joint"; GearJoint._super = Joint; GearJoint.prototype = create(GearJoint._super.prototype); var GearJointDef = { ratio: 1 }; function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) { if (!(this instanceof GearJoint)) { return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio); } def = options(def, GearJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = GearJoint.TYPE; ASSERT && common.assert(joint1.m_type == RevoluteJoint.TYPE || joint1.m_type == PrismaticJoint.TYPE); ASSERT && common.assert(joint2.m_type == RevoluteJoint.TYPE || joint2.m_type == PrismaticJoint.TYPE); this.m_joint1 = joint1; this.m_joint2 = joint2; this.m_type1 = this.m_joint1.getType(); this.m_type2 = this.m_joint2.getType(); var coordinateA, coordinateB; this.m_bodyC = this.m_joint1.getBodyA(); this.m_bodyA = this.m_joint1.getBodyB(); var xfA = this.m_bodyA.m_xf; var aA = this.m_bodyA.m_sweep.a; var xfC = this.m_bodyC.m_xf; var aC = this.m_bodyC.m_sweep.a; if (this.m_type1 == RevoluteJoint.TYPE) { var revolute = joint1; this.m_localAnchorC = revolute.m_localAnchorA; this.m_localAnchorA = revolute.m_localAnchorB; this.m_referenceAngleA = revolute.m_referenceAngle; this.m_localAxisC = Vec2.zero(); coordinateA = aA - aC - this.m_referenceAngleA; } else { var prismatic = joint1; this.m_localAnchorC = prismatic.m_localAnchorA; this.m_localAnchorA = prismatic.m_localAnchorB; this.m_referenceAngleA = prismatic.m_referenceAngle; this.m_localAxisC = prismatic.m_localXAxisA; var pC = this.m_localAnchorC; var pA = Rot.mulT(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p))); coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC); } this.m_bodyD = this.m_joint2.getBodyA(); this.m_bodyB = this.m_joint2.getBodyB(); var xfB = this.m_bodyB.m_xf; var aB = this.m_bodyB.m_sweep.a; var xfD = this.m_bodyD.m_xf; var aD = this.m_bodyD.m_sweep.a; if (this.m_type2 == RevoluteJoint.TYPE) { var revolute = joint2; this.m_localAnchorD = revolute.m_localAnchorA; this.m_localAnchorB = revolute.m_localAnchorB; this.m_referenceAngleB = revolute.m_referenceAngle; this.m_localAxisD = Vec2.zero(); coordinateB = aB - aD - this.m_referenceAngleB; } else { var prismatic = joint2; this.m_localAnchorD = prismatic.m_localAnchorA; this.m_localAnchorB = prismatic.m_localAnchorB; this.m_referenceAngleB = prismatic.m_referenceAngle; this.m_localAxisD = prismatic.m_localXAxisA; var pD = this.m_localAnchorD; var pB = Rot.mulT(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } this.m_ratio = ratio || def.ratio; this.m_constant = coordinateA + this.m_ratio * coordinateB; this.m_impulse = 0; this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD; this.m_mA, this.m_mB, this.m_mC, this.m_mD; this.m_iA, this.m_iB, this.m_iC, this.m_iD; this.m_JvAC, this.m_JvBD; this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD; this.m_mass; } GearJoint.prototype.getJoint1 = function() { return this.m_joint1; }; GearJoint.prototype.getJoint2 = function() { return this.m_joint2; }; GearJoint.prototype.setRatio = function(ratio) { ASSERT && common.assert(IsValid(ratio)); this.m_ratio = ratio; }; GearJoint.prototype.setRatio = function() { return this.m_ratio; }; GearJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; GearJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; GearJoint.prototype.getReactionForce = function(inv_dt) { var P = this.m_impulse * this.m_JvAC; return inv_dt * P; }; GearJoint.prototype.getReactionTorque = function(inv_dt) { var L = this.m_impulse * this.m_JwA; return inv_dt * L; }; GearJoint.prototype.initVelocityConstraints = function(step) { this.m_lcA = this.m_bodyA.m_sweep.localCenter; this.m_lcB = this.m_bodyB.m_sweep.localCenter; this.m_lcC = this.m_bodyC.m_sweep.localCenter; this.m_lcD = this.m_bodyD.m_sweep.localCenter; this.m_mA = this.m_bodyA.m_invMass; this.m_mB = this.m_bodyB.m_invMass; this.m_mC = this.m_bodyC.m_invMass; this.m_mD = this.m_bodyD.m_invMass; this.m_iA = this.m_bodyA.m_invI; this.m_iB = this.m_bodyB.m_invI; this.m_iC = this.m_bodyC.m_invI; this.m_iD = this.m_bodyD.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var aC = this.m_bodyC.c_position.a; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var aD = this.m_bodyD.c_position.a; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); this.m_mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { this.m_JvAC = Vec2.zero(); this.m_JwA = 1; this.m_JwC = 1; this.m_mass += this.m_iA + this.m_iC; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); this.m_JvAC = u; this.m_JwC = Vec2.cross(rC, u); this.m_JwA = Vec2.cross(rA, u); this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA; } if (this.m_type2 == RevoluteJoint.TYPE) { this.m_JvBD = Vec2.zero(); this.m_JwB = this.m_ratio; this.m_JwD = this.m_ratio; this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); this.m_JvBD = Vec2.mul(this.m_ratio, u); this.m_JwD = this.m_ratio * Vec2.cross(rD, u); this.m_JwB = this.m_ratio * Vec2.cross(rB, u); this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB; } this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0; if (step.warmStarting) { vA.wAdd(this.m_mA * this.m_impulse, this.m_JvAC); wA += this.m_iA * this.m_impulse * this.m_JwA; vB.wAdd(this.m_mB * this.m_impulse, this.m_JvBD); wB += this.m_iB * this.m_impulse * this.m_JwB; vC.wSub(this.m_mC * this.m_impulse, this.m_JvAC); wC -= this.m_iC * this.m_impulse * this.m_JwC; vD.wSub(this.m_mD * this.m_impulse, this.m_JvBD); wD -= this.m_iD * this.m_impulse * this.m_JwD; } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vC = this.m_bodyC.c_velocity.v; var wC = this.m_bodyC.c_velocity.w; var vD = this.m_bodyD.c_velocity.v; var wD = this.m_bodyD.c_velocity.w; var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD); Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; vA.wAdd(this.m_mA * impulse, this.m_JvAC); wA += this.m_iA * impulse * this.m_JwA; vB.wAdd(this.m_mB * impulse, this.m_JvBD); wB += this.m_iB * impulse * this.m_JwB; vC.wSub(this.m_mC * impulse, this.m_JvAC); wC -= this.m_iC * impulse * this.m_JwC; vD.wSub(this.m_mD * impulse, this.m_JvBD); wD -= this.m_iD * impulse * this.m_JwD; this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; this.m_bodyC.c_velocity.v.set(vC); this.m_bodyC.c_velocity.w = wC; this.m_bodyD.c_velocity.v.set(vD); this.m_bodyD.c_velocity.w = wD; }; GearJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var cC = this.m_bodyC.c_position.c; var aC = this.m_bodyC.c_position.a; var cD = this.m_bodyD.c_position.c; var aD = this.m_bodyD.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var qC = Rot.neo(aC); var qD = Rot.neo(aD); var linearError = 0; var coordinateA, coordinateB; var JvAC, JvBD; var JwA, JwB, JwC, JwD; var mass = 0; if (this.m_type1 == RevoluteJoint.TYPE) { JvAC = Vec2.zero(); JwA = 1; JwC = 1; mass += this.m_iA + this.m_iC; coordinateA = aA - aC - this.m_referenceAngleA; } else { var u = Rot.mul(qC, this.m_localAxisC); var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA); JvAC = u; JwC = Vec2.cross(rC, u); JwA = Vec2.cross(rA, u); mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA; var pC = this.m_localAnchorC - this.m_lcC; var pA = Rot.mulT(qC, Vec2.add(rA, Vec2.sub(cA, cC))); coordinateA = Dot(pA - pC, this.m_localAxisC); } if (this.m_type2 == RevoluteJoint.TYPE) { JvBD = Vec2.zero(); JwB = this.m_ratio; JwD = this.m_ratio; mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD); coordinateB = aB - aD - this.m_referenceAngleB; } else { var u = Rot.mul(qD, this.m_localAxisD); var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB); JvBD = Vec2.mul(this.m_ratio, u); JwD = this.m_ratio * Vec2.cross(rD, u); JwB = this.m_ratio * Vec2.cross(rB, u); mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB; var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD); var pB = Rot.mulT(qD, Vec2.add(rB, Vec2.sub(cB, cD))); coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD); } var C = coordinateA + this.m_ratio * coordinateB - this.m_constant; var impulse = 0; if (mass > 0) { impulse = -C / mass; } cA.wAdd(this.m_mA * impulse, JvAC); aA += this.m_iA * impulse * JwA; cB.wAdd(this.m_mB * impulse, JvBD); aB += this.m_iB * impulse * JwB; cC.wAdd(this.m_mC * impulse, JvAC); aC -= this.m_iC * impulse * JwC; cD.wAdd(this.m_mD * impulse, JvBD); aD -= this.m_iD * impulse * JwD; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; this.m_bodyC.c_position.c.set(cC); this.m_bodyC.c_position.a = aC; this.m_bodyD.c_position.c.set(cD); this.m_bodyD.c_position.a = aD; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MotorJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MotorJoint.TYPE = "motor-joint"; MotorJoint._super = Joint; MotorJoint.prototype = create(MotorJoint._super.prototype); var MotorJointDef = { maxForce: 1, maxTorque: 1, correctionFactor: .3 }; function MotorJoint(def, bodyA, bodyB) { if (!(this instanceof MotorJoint)) { return new MotorJoint(def, bodyA, bodyB); } def = options(def, MotorJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MotorJoint.TYPE; var xB = bodyB.getPosition(); this.m_linearOffset = bodyA.getLocalPoint(xB); var angleA = bodyA.getAngle(); var angleB = bodyB.getAngle(); this.m_angularOffset = angleB - angleA; this.m_linearImpulse = Vec2.zero(); this.m_angularImpulse = 0; this.m_maxForce = def.maxForce; this.m_maxTorque = def.maxTorque; this.m_correctionFactor = def.correctionFactor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_linearError; this.m_angularError; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_linearMass; this.m_angularMass; } MotorJoint.prototype.setMaxForce = function(force) { ASSERT && common.assert(IsValid(force) && force >= 0); this.m_maxForce = force; }; MotorJoint.prototype.getMaxForce = function() { return this.m_maxForce; }; MotorJoint.prototype.setMaxTorque = function(torque) { ASSERT && common.assert(IsValid(torque) && torque >= 0); this.m_maxTorque = torque; }; MotorJoint.prototype.getMaxTorque = function() { return this.m_maxTorque; }; MotorJoint.prototype.setCorrectionFactor = function(factor) { ASSERT && common.assert(IsValid(factor) && 0 <= factor && factor <= 1); this.m_correctionFactor = factor; }; MotorJoint.prototype.getCorrectionFactor = function() { return this.m_correctionFactor; }; MotorJoint.prototype.setLinearOffset = function(linearOffset) { if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_linearOffset = linearOffset; } }; MotorJoint.prototype.getLinearOffset = function() { return this.m_linearOffset; }; MotorJoint.prototype.setAngularOffset = function(angularOffset) { if (angularOffset != this.m_angularOffset) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_angularOffset = angularOffset; } }; MotorJoint.prototype.getAngularOffset = function() { return this.m_angularOffset; }; MotorJoint.prototype.getAnchorA = function() { return this.m_bodyA.getPosition(); }; MotorJoint.prototype.getAnchorB = function() { return this.m_bodyB.getPosition(); }; MotorJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * this.m_linearImpulse; }; MotorJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_angularImpulse; }; MotorJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.neg(this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.neg(this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y; K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x; this.m_linearMass = K.getInverse(); this.m_angularMass = iA + iB; if (this.m_angularMass > 0) { this.m_angularMass = 1 / this.m_angularMass; } this.m_linearError = Vec2.zero(); this.m_linearError.wAdd(1, cB, 1, this.m_rB); this.m_linearError.wSub(1, cA, 1, this.m_rA); this.m_linearError.sub(Rot.mul(qA, this.m_linearOffset)); this.m_angularError = aB - aA - this.m_angularOffset; if (step.warmStarting) { this.m_linearImpulse.mul(step.dtRatio); this.m_angularImpulse *= step.dtRatio; var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse); } else { this.m_linearImpulse.setZero(); this.m_angularImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var h = step.dt; var inv_h = step.inv_dt; { var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError; var impulse = -this.m_angularMass * Cdot; var oldImpulse = this.m_angularImpulse; var maxImpulse = h * this.m_maxTorque; this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.zero(); Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); Cdot.wAdd(inv_h * this.m_correctionFactor, this.m_linearError); var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot)); var oldImpulse = Vec2.clone(this.m_linearImpulse); this.m_linearImpulse.add(impulse); var maxImpulse = h * this.m_maxForce; this.m_linearImpulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_linearImpulse, oldImpulse); vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; MotorJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = MouseJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); MouseJoint.TYPE = "mouse-joint"; MouseJoint._super = Joint; MouseJoint.prototype = create(MouseJoint._super.prototype); var MouseJointDef = { maxForce: 0, frequencyHz: 5, dampingRatio: .7 }; function MouseJoint(def, bodyA, bodyB, target) { if (!(this instanceof MouseJoint)) { return new MouseJoint(def, bodyA, bodyB, target); } def = options(def, MouseJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = MouseJoint.TYPE; ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0); ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0); ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0); this.m_targetA = Vec2.clone(target); this.m_localAnchorB = Transform.mulT(this.m_bodyB.getTransform(), this.m_targetA); this.m_maxForce = def.maxForce; this.m_impulse = Vec2.zero(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_beta = 0; this.m_gamma = 0; this.m_rB = Vec2.zero(); this.m_localCenterB = Vec2.zero(); this.m_invMassB = 0; this.m_invIB = 0; this.mass = new Mat22(); this.m_C = Vec2.zero(); } MouseJoint.prototype.setTarget = function(target) { if (this.m_bodyB.isAwake() == false) { this.m_bodyB.setAwake(true); } this.m_targetA = Vec2.clone(target); }; MouseJoint.prototype.getTarget = function() { return this.m_targetA; }; MouseJoint.prototype.setMaxForce = function(force) { this.m_maxForce = force; }; MouseJoint.getMaxForce = function() { return this.m_maxForce; }; MouseJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; MouseJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; MouseJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; MouseJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; MouseJoint.prototype.getAnchorA = function() { return Vec2.clone(this.m_targetA); }; MouseJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; MouseJoint.prototype.getReactionForce = function(inv_dt) { return Vec2.mul(inv_dt, this.m_impulse); }; MouseJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * 0; }; MouseJoint.prototype.shiftOrigin = function(newOrigin) { this.m_targetA.sub(newOrigin); }; MouseJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIB = this.m_bodyB.m_invI; var position = this.m_bodyB.c_position; var velocity = this.m_bodyB.c_velocity; var cB = position.c; var aB = position.a; var vB = velocity.v; var wB = velocity.w; var qB = Rot.neo(aB); var mass = this.m_bodyB.getMass(); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * mass * this.m_dampingRatio * omega; var k = mass * (omega * omega); var h = step.dt; ASSERT && common.assert(d + h * k > Math.EPSILON); this.m_gamma = h * (d + h * k); if (this.m_gamma != 0) { this.m_gamma = 1 / this.m_gamma; } this.m_beta = h * k * this.m_gamma; this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var K = new Mat22(); K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma; K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y; K.ey.x = K.ex.y; K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma; this.m_mass = K.getInverse(); this.m_C.set(cB); this.m_C.wAdd(1, this.m_rB, -1, this.m_targetA); this.m_C.mul(this.m_beta); wB *= .98; if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); vB.wAdd(this.m_invMassB, this.m_impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse); } else { this.m_impulse.setZero(); } velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solveVelocityConstraints = function(step) { var velocity = this.m_bodyB.c_velocity; var vB = Vec2.clone(velocity.v); var wB = velocity.w; var Cdot = Vec2.cross(wB, this.m_rB); Cdot.add(vB); Cdot.wAdd(1, this.m_C, this.m_gamma, this.m_impulse); Cdot.neg(); var impulse = Mat22.mul(this.m_mass, Cdot); var oldImpulse = Vec2.clone(this.m_impulse); this.m_impulse.add(impulse); var maxImpulse = step.dt * this.m_maxForce; this.m_impulse.clamp(maxImpulse); impulse = Vec2.sub(this.m_impulse, oldImpulse); vB.wAdd(this.m_invMassB, impulse); wB += this.m_invIB * Vec2.cross(this.m_rB, impulse); velocity.v.set(vB); velocity.w = wB; }; MouseJoint.prototype.solvePositionConstraints = function(step) { return true; }; },{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PrismaticJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; PrismaticJoint.TYPE = "prismatic-joint"; PrismaticJoint._super = Joint; PrismaticJoint.prototype = create(PrismaticJoint._super.prototype); var PrismaticJointDef = { enableLimit: false, lowerTranslation: 0, upperTranslation: 0, enableMotor: false, maxMotorForce: 0, motorSpeed: 0 }; function PrismaticJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof PrismaticJoint)) { return new PrismaticJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, PrismaticJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PrismaticJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_localXAxisA = def.localAxisA || bodyA.getLocalVector(axis); this.m_localXAxisA.normalize(); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_lowerTranslation = def.lowerTranslation; this.m_upperTranslation = def.upperTranslation; this.m_maxMotorForce = def.maxMotorForce; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_limitState = inactiveLimit; this.m_axis = Vec2.zero(); this.m_perp = Vec2.zero(); this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_axis, this.m_perp; this.m_s1, this.m_s2; this.m_a1, this.m_a2; this.m_K = new Mat33(); this.m_motorMass; } PrismaticJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; PrismaticJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; PrismaticJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; PrismaticJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; PrismaticJoint.prototype.getJointTranslation = function() { var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var d = Vec2.sub(pB, pA); var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA); var translation = Vec2.dot(d, axis); return translation; }; PrismaticJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var rA = Mul(bA.m_xf.q, this.m_localAnchorA - bA.m_sweep.localCenter); var rB = Mul(bB.m_xf.q, this.m_localAnchorB - bB.m_sweep.localCenter); var p1 = bA.m_sweep.c + rA; var p2 = bB.m_sweep.c + rB; var d = p2 - p1; var axis = Mul(bA.m_xf.q, this.m_localXAxisA); var vA = bA.m_linearVelocity; var vB = bB.m_linearVelocity; var wA = bA.m_angularVelocity; var wB = bB.m_angularVelocity; var speed = Dot(d, Cross(wA, axis)) + Dot(axis, vB + Cross(wB, rB) - vA - Cross(wA, rA)); return speed; }; PrismaticJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; PrismaticJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.getLowerLimit = function() { return this.m_lowerTranslation; }; PrismaticJoint.prototype.getUpperLimit = function() { return this.m_upperTranslation; }; PrismaticJoint.prototype.setLimits = function(lower, upper) { ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_lowerTranslation = lower; this.m_upperTranslation = upper; this.m_impulse.z = 0; } }; PrismaticJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; PrismaticJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; PrismaticJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; PrismaticJoint.prototype.setMaxMotorForce = function(force) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorForce = force; }; PrismaticJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; PrismaticJoint.prototype.getMotorForce = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; PrismaticJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PrismaticJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PrismaticJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * (this.m_impulse.x * this.m_perp + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis); }; PrismaticJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.y; }; PrismaticJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; { this.m_axis = Rot.mul(qA, this.m_localXAxisA); this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis); this.m_a2 = Vec2.cross(rB, this.m_axis); this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } { this.m_perp = Rot.mul(qA, this.m_localYAxisA); this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp); this.m_s2 = Vec2.cross(rB, this.m_perp); var s1test = Vec2.cross(rA, this.m_perp); var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2; var k12 = iA * this.m_s1 + iB * this.m_s2; var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * this.m_a1 + iB * this.m_a2; var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2; this.m_K.ex.set(k11, k12, k13); this.m_K.ey.set(k12, k22, k23); this.m_K.ez.set(k13, k23, k33); } if (this.m_enableLimit) { var jointTranslation = Vec2.dot(this.m_axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) { this.m_limitState = equalLimits; } else if (jointTranslation <= this.m_lowerTranslation) { if (this.m_limitState != atLowerLimit) { this.m_limitState = atLowerLimit; this.m_impulse.z = 0; } } else if (jointTranslation >= this.m_upperTranslation) { if (this.m_limitState != atUpperLimit) { this.m_limitState = atUpperLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } if (this.m_enableMotor == false) { this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.wAdd(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis); var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1; var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_enableMotor && this.m_limitState != equalLimits) { var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA; var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot); var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorForce; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; var P = Vec2.zero().wSet(impulse, this.m_axis); var LA = impulse * this.m_a1; var LB = impulse * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } var Cdot1 = Vec2.zero(); Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB; Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA; Cdot1.y = wB - wA; if (this.m_enableLimit && this.m_limitState != inactiveLimit) { var Cdot2 = 0; Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB; Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var f1 = Vec3(this.m_impulse); var df = this.m_K.solve33(Vec3.neg(Cdot)); this.m_impulse.add(df); if (this.m_limitState == atLowerLimit) { this.m_impulse.z = Math.max(this.m_impulse.z, 0); } else if (this.m_limitState == atUpperLimit) { this.m_impulse.z = Math.min(this.m_impulse.z, 0); } var b = Vec2.wAdd(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y)); var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y)); this.m_impulse.x = f2r.x; this.m_impulse.y = f2r.y; df = Vec3.sub(this.m_impulse, f1); var P = Vec2.wAdd(df.x, this.m_perp, df.z, this.m_axis); var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1; var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } else { var df = this.m_K.solve22(Vec2.neg(Cdot1)); this.m_impulse.x += df.x; this.m_impulse.y += df.y; var P = Vec2.zero().wAdd(df.x, this.m_perp); var LA = df.x * this.m_s1 + df.y; var LB = df.x * this.m_s2 + df.y; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PrismaticJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA)); var axis = Rot.mul(qA, this.m_localXAxisA); var a1 = Vec2.cross(Vec2.add(d, rA), axis); var a2 = Vec2.cross(rB, axis); var perp = Rot.mul(qA, this.m_localYAxisA); var s1 = Vec2.cross(Vec2.add(d, rA), perp); var s2 = Vec2.cross(rB, perp); var impulse = Vec3(); var C1 = Vec2.zero(); C1.x = Vec2.dot(perp, d); C1.y = aB - aA - this.m_referenceAngle; var linearError = Math.abs(C1.x); var angularError = Math.abs(C1.y); var linearSlop = Settings.linearSlop; var maxLinearCorrection = Settings.maxLinearCorrection; var active = false; var C2 = 0; if (this.m_enableLimit) { var translation = Vec2.dot(axis, d); if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) { C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection); linearError = Math.max(linearError, Math.abs(translation)); active = true; } else if (translation <= this.m_lowerTranslation) { C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0); linearError = Math.max(linearError, this.m_lowerTranslation - translation); active = true; } else if (translation >= this.m_upperTranslation) { C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection); linearError = Math.max(linearError, translation - this.m_upperTranslation); active = true; } } if (active) { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k13 = iA * s1 * a1 + iB * s2 * a2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var k23 = iA * a1 + iB * a2; var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; var K = new Mat33(); K.ex.set(k11, k12, k13); K.ey.set(k12, k22, k23); K.ez.set(k13, k23, k33); var C = Vec3(); C.x = C1.x; C.y = C1.y; C.z = C2; impulse = K.solve33(Vec3.neg(C)); } else { var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; var k12 = iA * s1 + iB * s2; var k22 = iA + iB; if (k22 == 0) { k22 = 1; } var K = new Mat22(); K.ex.set(k11, k12); K.ey.set(k12, k22); var impulse1 = K.solve(Vec2.neg(C1)); impulse.x = impulse1.x; impulse.y = impulse1.y; impulse.z = 0; } var P = Vec2.wAdd(impulse.x, perp, impulse.z, axis); var LA = impulse.x * s1 + impulse.y + impulse.z * a1; var LB = impulse.x * s2 + impulse.y + impulse.z * a2; cA.wSub(mA, P); aA -= iA * LA; cB.wAdd(mB, P); aB += iB * LB; this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PulleyJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); PulleyJoint.TYPE = "pulley-joint"; PulleyJoint.MIN_PULLEY_LENGTH = 2; PulleyJoint._super = Joint; PulleyJoint.prototype = create(PulleyJoint._super.prototype); var PulleyJointDef = { collideConnected: true }; function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) { if (!(this instanceof PulleyJoint)) { return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio); } def = options(def, PulleyJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = PulleyJoint.TYPE; this.m_groundAnchorA = groundA; this.m_groundAnchorB = groundB; this.m_localAnchorA = bodyA.getLocalPoint(anchorA); this.m_localAnchorB = bodyB.getLocalPoint(anchorB); this.m_lengthA = Vec2.distance(anchorA, groundA); this.m_lengthB = Vec2.distance(anchorB, groundB); this.m_ratio = def.ratio || ratio; ASSERT && common.assert(ratio > Math.EPSILON); this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB; this.m_impulse = 0; this.m_uA; this.m_uB; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } PulleyJoint.prototype.getGroundAnchorA = function() { return this.m_groundAnchorA; }; PulleyJoint.prototype.getGroundAnchorB = function() { return this.m_groundAnchorB; }; PulleyJoint.prototype.getLengthA = function() { return this.m_lengthA; }; PulleyJoint.prototype.getLengthB = function() { return this.m_lengthB; }; PulleyJoint.prototype.setRatio = function() { return this.m_ratio; }; PulleyJoint.prototype.getCurrentLengthA = function() { var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA); var s = this.m_groundAnchorA; return Vec2.distance(p, s); }; PulleyJoint.prototype.getCurrentLengthB = function() { var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB); var s = this.m_groundAnchorB; return Vec2.distance(p, s); }; PulleyJoint.prototype.shiftOrigin = function(newOrigin) { this.m_groundAnchorA -= newOrigin; this.m_groundAnchorB -= newOrigin; }; PulleyJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; PulleyJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; PulleyJoint.prototype.getReactionForce = function(inv_dt) { return Vec3.mul(inv_dt * this.m_impulse, this.m_uB); }; PulleyJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; PulleyJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = this.m_uA.length(); var lengthB = this.m_uB.length(); if (lengthA > 10 * Settings.linearSlop) { this.m_uA.mul(1 / lengthA); } else { this.m_uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { this.m_uB.mul(1 / lengthB); } else { this.m_uB.setZero(); } var ruA = Vec2.cross(this.m_rA, this.m_uA); var ruB = Vec2.cross(this.m_rB, this.m_uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; this.m_mass = mA + this.m_ratio * this.m_ratio * mB; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; var PA = Vec2.mul(-this.m_impulse, this.m_uA); var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB); vA.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA)); var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB)); var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB); var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var PA = Vec2.zero().wSet(-impulse, this.m_uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, this.m_uB); vA.wAdd(this.m_invMassA, PA); wA += this.m_invIA * Vec2.cross(this.m_rA, PA); vB.wAdd(this.m_invMassB, PB); wB += this.m_invIB * Vec2.cross(this.m_rB, PB); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; PulleyJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA); var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB); var lengthA = uA.length(); var lengthB = uB.length(); if (lengthA > 10 * Settings.linearSlop) { uA.mul(1 / lengthA); } else { uA.setZero(); } if (lengthB > 10 * Settings.linearSlop) { uB.mul(1 / lengthB); } else { uB.setZero(); } var ruA = Vec2.cross(rA, uA); var ruB = Vec2.cross(rB, uB); var mA = this.m_invMassA + this.m_invIA * ruA * ruA; var mB = this.m_invMassB + this.m_invIB * ruB * ruB; var mass = mA + this.m_ratio * this.m_ratio * mB; if (mass > 0) { mass = 1 / mass; } var C = this.m_constant - lengthA - this.m_ratio * lengthB; var linearError = Math.abs(C); var impulse = -mass * C; var PA = Vec2.zero().wSet(-impulse, uA); var PB = Vec2.zero().wSet(-this.m_ratio * impulse, uB); cA.wAdd(this.m_invMassA, PA); aA += this.m_invIA * Vec2.cross(rA, PA); cB.wAdd(this.m_invMassB, PB); aB += this.m_invIB * Vec2.cross(rB, PB); this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return linearError < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RevoluteJoint; var common = require("../util/common"); var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RevoluteJoint.TYPE = "revolute-joint"; RevoluteJoint._super = Joint; RevoluteJoint.prototype = create(RevoluteJoint._super.prototype); var RevoluteJointDef = { lowerAngle: 0, upperAngle: 0, maxMotorTorque: 0, motorSpeed: 0, enableLimit: false, enableMotor: false }; function RevoluteJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RevoluteJoint)) { return new RevoluteJoint(def, bodyA, bodyB, anchor); } def = options(def, RevoluteJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RevoluteJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_impulse = Vec3(); this.m_motorImpulse = 0; this.m_lowerAngle = def.lowerAngle; this.m_upperAngle = def.upperAngle; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableLimit = def.enableLimit; this.m_enableMotor = def.enableMotor; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); this.m_motorMass; this.m_limitState = inactiveLimit; } RevoluteJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RevoluteJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RevoluteJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; RevoluteJoint.prototype.getJointAngle = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle; }; RevoluteJoint.prototype.getJointSpeed = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; return bB.m_angularVelocity - bA.m_angularVelocity; }; RevoluteJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; RevoluteJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; RevoluteJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; RevoluteJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; RevoluteJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; RevoluteJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; RevoluteJoint.prototype.isLimitEnabled = function() { return this.m_enableLimit; }; RevoluteJoint.prototype.enableLimit = function(flag) { if (flag != this.m_enableLimit) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableLimit = flag; this.m_impulse.z = 0; } }; RevoluteJoint.prototype.getLowerLimit = function() { return this.m_lowerAngle; }; RevoluteJoint.prototype.getUpperLimit = function() { return this.m_upperAngle; }; RevoluteJoint.prototype.setLimits = function(lower, upper) { ASSERT && common.assert(lower <= upper); if (lower != this.m_lowerAngle || upper != this.m_upperAngle) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_impulse.z = 0; this.m_lowerAngle = lower; this.m_upperAngle = upper; } }; RevoluteJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RevoluteJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RevoluteJoint.prototype.getReactionForce = function(inv_dt) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; RevoluteJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; RevoluteJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; this.m_mass.ex.y = this.m_mass.ey.x; this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; this.m_mass.ex.z = this.m_mass.ez.x; this.m_mass.ey.z = this.m_mass.ez.y; this.m_mass.ez.z = iA + iB; this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } if (this.m_enableMotor == false || fixedRotation) { this.m_motorImpulse = 0; } if (this.m_enableLimit && fixedRotation == false) { var jointAngle = aB - aA - this.m_referenceAngle; if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) { this.m_limitState = equalLimits; } else if (jointAngle <= this.m_lowerAngle) { if (this.m_limitState != atLowerLimit) { this.m_impulse.z = 0; } this.m_limitState = atLowerLimit; } else if (jointAngle >= this.m_upperAngle) { if (this.m_limitState != atUpperLimit) { this.m_impulse.z = 0; } this.m_limitState = atUpperLimit; } else { this.m_limitState = inactiveLimit; this.m_impulse.z = 0; } } else { this.m_limitState = inactiveLimit; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); this.m_motorImpulse *= step.dtRatio; var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z); } else { this.m_impulse.setZero(); this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var fixedRotation = iA + iB == 0; if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(this.m_mass.solve33(Cdot)); if (this.m_limitState == equalLimits) { this.m_impulse.add(impulse); } else if (this.m_limitState == atLowerLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse < 0) { var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } else if (this.m_limitState == atUpperLimit) { var newImpulse = this.m_impulse.z + impulse.z; if (newImpulse > 0) { var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); var reduced = this.m_mass.solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -this.m_impulse.z; this.m_impulse.x += reduced.x; this.m_impulse.y += reduced.y; this.m_impulse.z = 0; } else { this.m_impulse.add(impulse); } } var P = Vec2.neo(impulse.x, impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } else { var Cdot = Vec2.zero(); Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse = this.m_mass.solve22(Vec2.neg(Cdot)); this.m_impulse.x += impulse.x; this.m_impulse.y += impulse.y; vA.wSub(mA, impulse); wA -= iA * Vec2.cross(this.m_rA, impulse); vB.wAdd(mB, impulse); wB += iB * Vec2.cross(this.m_rB, impulse); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RevoluteJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var angularError = 0; var positionError = 0; var fixedRotation = this.m_invIA + this.m_invIB == 0; if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) { var angle = aB - aA - this.m_referenceAngle; var limitImpulse = 0; if (this.m_limitState == equalLimits) { var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; angularError = Math.abs(C); } else if (this.m_limitState == atLowerLimit) { var C = angle - this.m_lowerAngle; angularError = -C; C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0); limitImpulse = -this.m_motorMass * C; } else if (this.m_limitState == atUpperLimit) { var C = angle - this.m_upperAngle; angularError = C; C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection); limitImpulse = -this.m_motorMass * C; } aA -= this.m_invIA * limitImpulse; aB += this.m_invIB * limitImpulse; } { qA.set(aA); qB.set(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var C = Vec2.zero(); C.wAdd(1, cB, 1, rB); C.wSub(1, cA, 1, rA); positionError = C.length(); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat22(); K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; var impulse = Vec2.neg(K.solve(C)); cA.wSub(mA, impulse); aA -= iA * Vec2.cross(rA, impulse); cB.wAdd(mB, impulse); aB += iB * Vec2.cross(rB, impulse); } this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = RopeJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); var inactiveLimit = 0; var atLowerLimit = 1; var atUpperLimit = 2; var equalLimits = 3; RopeJoint.TYPE = "rope-joint"; RopeJoint._super = Joint; RopeJoint.prototype = create(RopeJoint._super.prototype); var RopeJointDef = { maxLength: 0 }; function RopeJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof RopeJoint)) { return new RopeJoint(def, bodyA, bodyB, anchor); } def = options(def, RopeJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = RopeJoint.TYPE; this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor); this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor); this.m_maxLength = def.maxLength; this.m_mass = 0; this.m_impulse = 0; this.m_length = 0; this.m_state = inactiveLimit; this.m_u; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass; } RopeJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; RopeJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; RopeJoint.prototype.setMaxLength = function(length) { this.m_maxLength = length; }; RopeJoint.prototype.getMaxLength = function() { return this.m_maxLength; }; RopeJoint.prototype.getLimitState = function() { return this.m_state; }; RopeJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; RopeJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; RopeJoint.prototype.getReactionForce = function(inv_dt) { var F = inv_dt * this.m_impulse * this.m_u; return F; }; RopeJoint.prototype.getReactionTorque = function(inv_dt) { return 0; }; RopeJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); this.m_u = Vec2.zero(); this.m_u.wAdd(1, cB, 1, this.m_rB); this.m_u.wSub(1, cA, 1, this.m_rA); this.m_length = this.m_u.length(); var C = this.m_length - this.m_maxLength; if (C > 0) { this.m_state = atUpperLimit; } else { this.m_state = inactiveLimit; } if (this.m_length > Settings.linearSlop) { this.m_u.mul(1 / this.m_length); } else { this.m_u.setZero(); this.m_mass = 0; this.m_impulse = 0; return; } var crA = Vec2.cross(this.m_rA, this.m_u); var crB = Vec2.cross(this.m_rB, this.m_u); var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB; this.m_mass = invMass != 0 ? 1 / invMass : 0; if (step.warmStarting) { this.m_impulse *= step.dtRatio; var P = Vec2.mul(this.m_impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); } else { this.m_impulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var vpA = Vec2.addCross(vA, wA, this.m_rA); var vpB = Vec2.addCross(vB, wB, this.m_rB); var C = this.m_length - this.m_maxLength; var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA)); if (C < 0) { Cdot += step.inv_dt * C; } var impulse = -this.m_mass * Cdot; var oldImpulse = this.m_impulse; this.m_impulse = Math.min(0, this.m_impulse + impulse); impulse = this.m_impulse - oldImpulse; var P = Vec2.mul(impulse, this.m_u); vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * Vec2.cross(this.m_rA, P); vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * Vec2.cross(this.m_rB, P); this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; RopeJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA); var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB); var u = Vec2.zero(); u.wAdd(1, cB, 1, rB); u.wSub(1, cA, 1, rA); var length = u.normalize(); var C = length - this.m_maxLength; C = Math.clamp(C, 0, Settings.maxLinearCorrection); var impulse = -this.m_mass * C; var P = Vec2.mul(impulse, u); cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * Vec2.cross(rA, P); cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * Vec2.cross(rB, P); this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return length - this.m_maxLength < Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WeldJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WeldJoint.TYPE = "weld-joint"; WeldJoint._super = Joint; WeldJoint.prototype = create(WeldJoint._super.prototype); var WeldJointDef = { frequencyHz: 0, dampingRatio: 0 }; function WeldJoint(def, bodyA, bodyB, anchor) { if (!(this instanceof WeldJoint)) { return new WeldJoint(def, bodyA, bodyB, anchor); } def = options(def, WeldJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WeldJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle(); this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_impulse = Vec3(); this.m_bias = 0; this.m_gamma = 0; this.m_rA; this.m_rB; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_mass = new Mat33(); } WeldJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WeldJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WeldJoint.prototype.getReferenceAngle = function() { return this.m_referenceAngle; }; WeldJoint.prototype.setFrequency = function(hz) { this.m_frequencyHz = hz; }; WeldJoint.prototype.getFrequency = function() { return this.m_frequencyHz; }; WeldJoint.prototype.setDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WeldJoint.prototype.getDampingRatio = function() { return this.m_dampingRatio; }; WeldJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WeldJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WeldJoint.prototype.getReactionForce = function(inv_dt) { var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); return inv_dt * P; }; WeldJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_impulse.z; }; WeldJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA), qB = Rot.neo(aB); this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var K = new Mat33(); K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB; K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB; K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB; K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { K.getInverse22(this.m_mass); var invM = iA + iB; var m = invM > 0 ? 1 / invM : 0; var C = aB - aA - this.m_referenceAngle; var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * m * this.m_dampingRatio * omega; var k = m * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0; this.m_bias = C * h * k * this.m_gamma; invM += this.m_gamma; this.m_mass.ez.z = invM != 0 ? 1 / invM : 0; } else if (K.ez.z == 0) { K.getInverse22(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } else { K.getSymInverse33(this.m_mass); this.m_gamma = 0; this.m_bias = 0; } if (step.warmStarting) { this.m_impulse.mul(step.dtRatio); var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z); } else { this.m_impulse.setZero(); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solveVelocityConstraints = function(step) { var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; if (this.m_frequencyHz > 0) { var Cdot2 = wB - wA; var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z); this.m_impulse.z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var impulse1 = Vec2.neg(Mat33.mul(this.m_mass, Cdot1)); this.m_impulse.x += impulse1.x; this.m_impulse.y += impulse1.y; var P = Vec2.clone(impulse1); vA.wSub(mA, P); wA -= iA * Vec2.cross(this.m_rA, P); vB.wAdd(mB, P); wB += iB * Vec2.cross(this.m_rB, P); } else { var Cdot1 = Vec2.zero(); Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB)); Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA)); var Cdot2 = wB - wA; var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2); var impulse = Vec3.neg(Mat33.mul(this.m_mass, Cdot)); this.m_impulse.add(impulse); var P = Vec2.neo(impulse.x, impulse.y); vA.wSub(mA, P); wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z); vB.wAdd(mB, P); wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z); } this.m_bodyA.c_velocity.v = vA; this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v = vB; this.m_bodyB.c_velocity.w = wB; }; WeldJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA), qB = Rot.neo(aB); var mA = this.m_invMassA, mB = this.m_invMassB; var iA = this.m_invIA, iB = this.m_invIB; var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var positionError, angularError; var K = new Mat33(); K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; K.ez.x = -rA.y * iA - rB.y * iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; K.ez.y = rA.x * iA + rB.x * iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (this.m_frequencyHz > 0) { var C1 = Vec2.zero(); C1.wAdd(1, cB, 1, rB); C1.wSub(1, cA, 1, rA); positionError = C1.length(); angularError = 0; var P = Vec2.neg(K.solve22(C1)); cA.wSub(mA, P); aA -= iA * Vec2.cross(rA, P); cB.wAdd(mB, P); aB += iB * Vec2.cross(rB, P); } else { var C1 = Vec2.zero(); C1.wAdd(1, cB, 1, rB); C1.wSub(1, cA, 1, rA); var C2 = aB - aA - this.m_referenceAngle; positionError = C1.length(); angularError = Math.abs(C2); var C = Vec3(C1.x, C1.y, C2); var impulse = Vec3(); if (K.ez.z > 0) { impulse = Vec3.neg(K.solve33(C)); } else { var impulse2 = Vec2.neg(K.solve22(C1)); impulse.set(impulse2.x, impulse2.y, 0); } var P = Vec2.neo(impulse.x, impulse.y); cA.wSub(mA, P); aA -= iA * (Vec2.cross(rA, P) + impulse.z); cB.wAdd(mB, P); aB += iB * (Vec2.cross(rB, P) + impulse.z); } this.m_bodyA.c_position.c = cA; this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c = cB; this.m_bodyB.c_position.a = aB; return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = WheelJoint; var options = require("../util/options"); var create = require("../util/create"); var Settings = require("../Settings"); var Math = require("../common/Math"); var Vec2 = require("../common/Vec2"); var Vec3 = require("../common/Vec3"); var Mat22 = require("../common/Mat22"); var Mat33 = require("../common/Mat33"); var Rot = require("../common/Rot"); var Sweep = require("../common/Sweep"); var Transform = require("../common/Transform"); var Velocity = require("../common/Velocity"); var Position = require("../common/Position"); var Joint = require("../Joint"); WheelJoint.TYPE = "wheel-joint"; WheelJoint._super = Joint; WheelJoint.prototype = create(WheelJoint._super.prototype); var WheelJointDef = { enableMotor: false, maxMotorTorque: 0, motorSpeed: 0, frequencyHz: 2, dampingRatio: .7 }; function WheelJoint(def, bodyA, bodyB, anchor, axis) { if (!(this instanceof WheelJoint)) { return new WheelJoint(def, bodyA, bodyB, anchor, axis); } def = options(def, WheelJointDef); Joint.call(this, def, bodyA, bodyB); this.m_type = WheelJoint.TYPE; this.m_localAnchorA = bodyA.getLocalPoint(anchor); this.m_localAnchorB = bodyB.getLocalPoint(anchor); this.m_localXAxisA = bodyA.getLocalVector(axis || Vec2.neo(1, 0)); this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA); this.m_mass = 0; this.m_impulse = 0; this.m_motorMass = 0; this.m_motorImpulse = 0; this.m_springMass = 0; this.m_springImpulse = 0; this.m_maxMotorTorque = def.maxMotorTorque; this.m_motorSpeed = def.motorSpeed; this.m_enableMotor = def.enableMotor; this.m_frequencyHz = def.frequencyHz; this.m_dampingRatio = def.dampingRatio; this.m_bias = 0; this.m_gamma = 0; this.m_localCenterA; this.m_localCenterB; this.m_invMassA; this.m_invMassB; this.m_invIA; this.m_invIB; this.m_ax = Vec2.zero(); this.m_ay = Vec2.zero(); this.m_sAx; this.m_sBx; this.m_sAy; this.m_sBy; } WheelJoint.prototype.getLocalAnchorA = function() { return this.m_localAnchorA; }; WheelJoint.prototype.getLocalAnchorB = function() { return this.m_localAnchorB; }; WheelJoint.prototype.getLocalAxisA = function() { return this.m_localXAxisA; }; WheelJoint.prototype.getJointTranslation = function() { var bA = this.m_bodyA; var bB = this.m_bodyB; var pA = bA.getWorldPoint(this.m_localAnchorA); var pB = bB.getWorldPoint(this.m_localAnchorB); var d = pB - pA; var axis = bA.getWorldVector(this.m_localXAxisA); var translation = Dot(d, axis); return translation; }; WheelJoint.prototype.getJointSpeed = function() { var wA = this.m_bodyA.m_angularVelocity; var wB = this.m_bodyB.m_angularVelocity; return wB - wA; }; WheelJoint.prototype.isMotorEnabled = function() { return this.m_enableMotor; }; WheelJoint.prototype.enableMotor = function(flag) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_enableMotor = flag; }; WheelJoint.prototype.setMotorSpeed = function(speed) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_motorSpeed = speed; }; WheelJoint.prototype.getMotorSpeed = function() { return this.m_motorSpeed; }; WheelJoint.prototype.setMaxMotorTorque = function(torque) { this.m_bodyA.setAwake(true); this.m_bodyB.setAwake(true); this.m_maxMotorTorque = torque; }; WheelJoint.prototype.getMaxMotorTorque = function() { return this.m_maxMotorTorque; }; WheelJoint.prototype.getMotorTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.setSpringFrequencyHz = function(hz) { this.m_frequencyHz = hz; }; WheelJoint.prototype.getSpringFrequencyHz = function() { return this.m_frequencyHz; }; WheelJoint.prototype.setSpringDampingRatio = function(ratio) { this.m_dampingRatio = ratio; }; WheelJoint.prototype.getSpringDampingRatio = function() { return this.m_dampingRatio; }; WheelJoint.prototype.getAnchorA = function() { return this.m_bodyA.getWorldPoint(this.m_localAnchorA); }; WheelJoint.prototype.getAnchorB = function() { return this.m_bodyB.getWorldPoint(this.m_localAnchorB); }; WheelJoint.prototype.getReactionForce = function(inv_dt) { return inv_dt * (this.m_impulse * this.m_ay + this.m_springImpulse * this.m_ax); }; WheelJoint.prototype.getReactionTorque = function(inv_dt) { return inv_dt * this.m_motorImpulse; }; WheelJoint.prototype.initVelocityConstraints = function(step) { this.m_localCenterA = this.m_bodyA.m_sweep.localCenter; this.m_localCenterB = this.m_bodyB.m_sweep.localCenter; this.m_invMassA = this.m_bodyA.m_invMass; this.m_invMassB = this.m_bodyB.m_invMass; this.m_invIA = this.m_bodyA.m_invI; this.m_invIB = this.m_bodyB.m_invI; var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); { this.m_ay = Rot.mul(qA, this.m_localYAxisA); this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay); this.m_sBy = Vec2.cross(rB, this.m_ay); this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy; if (this.m_mass > 0) { this.m_mass = 1 / this.m_mass; } } this.m_springMass = 0; this.m_bias = 0; this.m_gamma = 0; if (this.m_frequencyHz > 0) { this.m_ax = Rot.mul(qA, this.m_localXAxisA); this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax); this.m_sBx = Vec2.cross(rB, this.m_ax); var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx; if (invMass > 0) { this.m_springMass = 1 / invMass; var C = Vec2.dot(d, this.m_ax); var omega = 2 * Math.PI * this.m_frequencyHz; var d = 2 * this.m_springMass * this.m_dampingRatio * omega; var k = this.m_springMass * omega * omega; var h = step.dt; this.m_gamma = h * (d + h * k); if (this.m_gamma > 0) { this.m_gamma = 1 / this.m_gamma; } this.m_bias = C * h * k * this.m_gamma; this.m_springMass = invMass + this.m_gamma; if (this.m_springMass > 0) { this.m_springMass = 1 / this.m_springMass; } } } else { this.m_springImpulse = 0; } if (this.m_enableMotor) { this.m_motorMass = iA + iB; if (this.m_motorMass > 0) { this.m_motorMass = 1 / this.m_motorMass; } } else { this.m_motorMass = 0; this.m_motorImpulse = 0; } if (step.warmStarting) { this.m_impulse *= step.dtRatio; this.m_springImpulse *= step.dtRatio; this.m_motorImpulse *= step.dtRatio; var P = Vec2.wAdd(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax); var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse; var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse; vA.wSub(this.m_invMassA, P); wA -= this.m_invIA * LA; vB.wAdd(this.m_invMassB, P); wB += this.m_invIB * LB; } else { this.m_impulse = 0; this.m_springImpulse = 0; this.m_motorImpulse = 0; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solveVelocityConstraints = function(step) { var mA = this.m_invMassA; var mB = this.m_invMassB; var iA = this.m_invIA; var iB = this.m_invIB; var vA = this.m_bodyA.c_velocity.v; var wA = this.m_bodyA.c_velocity.w; var vB = this.m_bodyB.c_velocity.v; var wB = this.m_bodyB.c_velocity.w; { var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA; var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse); this.m_springImpulse += impulse; var P = Vec2.zero().wSet(impulse, this.m_ax); var LA = impulse * this.m_sAx; var LB = impulse * this.m_sBx; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } { var Cdot = wB - wA - this.m_motorSpeed; var impulse = -this.m_motorMass * Cdot; var oldImpulse = this.m_motorImpulse; var maxImpulse = step.dt * this.m_maxMotorTorque; this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = this.m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } { var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA; var impulse = -this.m_mass * Cdot; this.m_impulse += impulse; var P = Vec2.zero().wSet(impulse, this.m_ay); var LA = impulse * this.m_sAy; var LB = impulse * this.m_sBy; vA.wSub(mA, P); wA -= iA * LA; vB.wAdd(mB, P); wB += iB * LB; } this.m_bodyA.c_velocity.v.set(vA); this.m_bodyA.c_velocity.w = wA; this.m_bodyB.c_velocity.v.set(vB); this.m_bodyB.c_velocity.w = wB; }; WheelJoint.prototype.solvePositionConstraints = function(step) { var cA = this.m_bodyA.c_position.c; var aA = this.m_bodyA.c_position.a; var cB = this.m_bodyB.c_position.c; var aB = this.m_bodyB.c_position.a; var qA = Rot.neo(aA); var qB = Rot.neo(aB); var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); var d = Vec2.zero(); d.wAdd(1, cB, 1, rB); d.wSub(1, cA, 1, rA); var ay = Rot.mul(qA, this.m_localYAxisA); var sAy = Vec2.cross(Vec2.sub(d, rA), ay); var sBy = Vec2.cross(rB, ay); var C = Vec2.dot(d, ay); var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy; var impulse; if (k != 0) { impulse = -C / k; } else { impulse = 0; } var P = Vec2.zero().wSet(impulse, ay); var LA = impulse * sAy; var LB = impulse * sBy; cA.wSub(this.m_invMassA, P); aA -= this.m_invIA * LA; cB.wAdd(this.m_invMassB, P); aB += this.m_invIB * LB; this.m_bodyA.c_position.c.set(cA); this.m_bodyA.c_position.a = aA; this.m_bodyB.c_position.c.set(cB); this.m_bodyB.c_position.a = aB; return Math.abs(C) <= Settings.linearSlop; }; },{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = BoxShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var PolygonShape = require("./PolygonShape"); BoxShape._super = PolygonShape; BoxShape.prototype = create(BoxShape._super.prototype); BoxShape.TYPE = "polygon"; function BoxShape(hx, hy, center, angle) { if (!(this instanceof BoxShape)) { return new BoxShape(hx, hy, center, angle); } BoxShape._super.call(this); this.m_vertices[0] = Vec2.neo(-hx, -hy); this.m_vertices[1] = Vec2.neo(hx, -hy); this.m_vertices[2] = Vec2.neo(hx, hy); this.m_vertices[3] = Vec2.neo(-hx, hy); this.m_normals[0] = Vec2.neo(0, -1); this.m_normals[1] = Vec2.neo(1, 0); this.m_normals[2] = Vec2.neo(0, 1); this.m_normals[3] = Vec2.neo(-1, 0); this.m_count = 4; if (center && "x" in center && "y" in center) { angle = angle || 0; this.m_centroid.set(center); var xf = Transform.identity(); xf.p.set(center); xf.q.set(angle); for (var i = 0; i < this.m_count; ++i) { this.m_vertices[i] = Transform.mul(xf, this.m_vertices[i]); this.m_normals[i] = Rot.mul(xf.q, this.m_normals[i]); } } } },{"../Settings":7,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./PolygonShape":48}],40:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = ChainShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); var EdgeShape = require("./EdgeShape"); ChainShape._super = Shape; ChainShape.prototype = create(ChainShape._super.prototype); ChainShape.TYPE = "chain"; function ChainShape(vertices, loop) { if (!(this instanceof ChainShape)) { return new ChainShape(vertices, loop); } ChainShape._super.call(this); this.m_type = ChainShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertices = []; this.m_count = 0; this.m_prevVertex = null; this.m_nextVertex = null; this.m_hasPrevVertex = false; this.m_hasNextVertex = false; if (vertices && vertices.length) { if (loop) { this._createLoop(vertices); } else { this._createChain(vertices); } } } ChainShape.prototype._createLoop = function(vertices) { ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); ASSERT && common.assert(vertices.length >= 3); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_vertices.length = 0; this.m_count = vertices.length + 1; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_vertices[vertices.length] = vertices[0].clone(); this.m_prevVertex = this.m_vertices[this.m_count - 2]; this.m_nextVertex = this.m_vertices[1]; this.m_hasPrevVertex = true; this.m_hasNextVertex = true; return this; }; ChainShape.prototype._createChain = function(vertices) { ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0); ASSERT && common.assert(vertices.length >= 2); for (var i = 1; i < vertices.length; ++i) { var v1 = vertices[i - 1]; var v2 = vertices[i]; ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared); } this.m_count = vertices.length; for (var i = 0; i < vertices.length; ++i) { this.m_vertices[i] = vertices[i].clone(); } this.m_hasPrevVertex = false; this.m_hasNextVertex = false; this.m_prevVertex = null; this.m_nextVertex = null; return this; }; ChainShape.prototype._setPrevVertex = function(prevVertex) { this.m_prevVertex = prevVertex; this.m_hasPrevVertex = true; }; ChainShape.prototype._setNextVertex = function(nextVertex) { this.m_nextVertex = nextVertex; this.m_hasNextVertex = true; }; ChainShape.prototype._clone = function() { var clone = new ChainShape(); clone.createChain(this.m_vertices); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_prevVertex = this.m_prevVertex; clone.m_nextVertex = this.m_nextVertex; clone.m_hasPrevVertex = this.m_hasPrevVertex; clone.m_hasNextVertex = this.m_hasNextVertex; return clone; }; ChainShape.prototype.getChildCount = function() { return this.m_count - 1; }; ChainShape.prototype.getChildEdge = function(edge, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1); edge.m_type = EdgeShape.TYPE; edge.m_radius = this.m_radius; edge.m_vertex1 = this.m_vertices[childIndex]; edge.m_vertex2 = this.m_vertices[childIndex + 1]; if (childIndex > 0) { edge.m_vertex0 = this.m_vertices[childIndex - 1]; edge.m_hasVertex0 = true; } else { edge.m_vertex0 = this.m_prevVertex; edge.m_hasVertex0 = this.m_hasPrevVertex; } if (childIndex < this.m_count - 2) { edge.m_vertex3 = this.m_vertices[childIndex + 2]; edge.m_hasVertex3 = true; } else { edge.m_vertex3 = this.m_nextVertex; edge.m_hasVertex3 = this.m_hasNextVertex; } }; ChainShape.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index <= this.m_count); if (index < this.m_count) { return this.m_vertices[index]; } else { return this.m_vertices[0]; } }; ChainShape.prototype.testPoint = function(xf, p) { return false; }; ChainShape.prototype.rayCast = function(output, input, xf, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1)); return edgeShape.rayCast(output, input, xf, 0); }; ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); var v1 = Transform.mul(xf, this.getVertex(childIndex)); var v2 = Transform.mul(xf, this.getVertex(childIndex + 1)); aabb.combinePoints(v1, v2); }; ChainShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center = Vec2.neo(); massData.I = 0; }; ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) { ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count); proxy.m_buffer[0] = this.getVertex(childIndex); proxy.m_buffer[1] = this.getVertex(childIndex + 1); proxy.m_vertices = proxy.m_buffer; proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = CircleShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); CircleShape._super = Shape; CircleShape.prototype = create(CircleShape._super.prototype); CircleShape.TYPE = "circle"; function CircleShape(a, b) { if (!(this instanceof CircleShape)) { return new CircleShape(a, b); } CircleShape._super.call(this); this.m_type = CircleShape.TYPE; this.m_p = Vec2.zero(); this.m_radius = 1; if (typeof a === "object" && Vec2.isValid(a)) { this.m_p.set(a); if (typeof b === "number") { this.m_radius = b; } } else if (typeof a === "number") { this.m_radius = a; } } CircleShape.prototype.getRadius = function() { return this.m_radius; }; CircleShape.prototype.getCenter = function() { return this.m_p; }; CircleShape.prototype.getSupportVertex = function(d) { return this.m_p; }; CircleShape.prototype.getVertex = function(index) { ASSERT && common.assert(index == 0); return this.m_p; }; CircleShape.prototype.getVertexCount = function(index) { return 1; }; CircleShape.prototype._clone = function() { var clone = new CircleShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_p = this.m_p.clone(); return clone; }; CircleShape.prototype.getChildCount = function() { return 1; }; CircleShape.prototype.testPoint = function(xf, p) { var center = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var d = Vec2.sub(p, center); return Vec2.dot(d, d) <= this.m_radius * this.m_radius; }; CircleShape.prototype.rayCast = function(output, input, xf, childIndex) { var position = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); var s = Vec2.sub(input.p1, position); var b = Vec2.dot(s, s) - this.m_radius * this.m_radius; var r = Vec2.sub(input.p2, input.p1); var c = Vec2.dot(s, r); var rr = Vec2.dot(r, r); var sigma = c * c - rr * b; if (sigma < 0 || rr < Math.EPSILON) { return false; } var a = -(c + Math.sqrt(sigma)); if (0 <= a && a <= input.maxFraction * rr) { a /= rr; output.fraction = a; output.normal = Vec2.add(s, Vec2.mul(a, r)); output.normal.normalize(); return true; } return false; }; CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) { var p = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p)); aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius); aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius); }; CircleShape.prototype.computeMass = function(massData, density) { massData.mass = density * Math.PI * this.m_radius * this.m_radius; massData.center = this.m_p; massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p)); }; CircleShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_p); proxy.m_count = 1; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var CircleShape = require("./CircleShape"); Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact); function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollideCircles(manifold, circleA, xfA, circleB, xfB) { manifold.pointCount = 0; var pA = Transform.mul(xfA, circleA.m_p); var pB = Transform.mul(xfB, circleB.m_p); var distSqr = Vec2.distanceSquared(pB, pA); var rA = circleA.m_radius; var rB = circleB.m_radius; var radius = rA + rB; if (distSqr > radius * radius) { return; } manifold.type = Manifold.e_circles; manifold.localPoint.set(circleA.m_p); manifold.localNormal.setZero(); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } exports.CollideCircles = CollideCircles; },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var CircleShape = require("./CircleShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact); function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) { manifold.pointCount = 0; var c = Transform.mul(xfB, circleB.m_p); var cLocal = Transform.mulT(xfA, c); var normalIndex = 0; var separation = -Infinity; var radius = polygonA.m_radius + circleB.m_radius; var vertexCount = polygonA.m_count; var vertices = polygonA.m_vertices; var normals = polygonA.m_normals; for (var i = 0; i < vertexCount; ++i) { var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i])); if (s > radius) { return; } if (s > separation) { separation = s; normalIndex = i; } } var vertIndex1 = normalIndex; var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; var v1 = vertices[vertIndex1]; var v2 = vertices[vertIndex2]; if (separation < Math.EPSILON) { manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[normalIndex]); manifold.localPoint.wSet(.5, v1, .5, v2); manifold.points[0].localPoint = circleB.m_p; manifold.points[0].id.key = 0; return; } var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1)); var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2)); if (u1 <= 0) { if (Vec2.distanceSquared(cLocal, v1) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.wSet(1, cLocal, -1, v1); manifold.localNormal.normalize(); manifold.localPoint = v1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else if (u2 <= 0) { if (Vec2.distanceSquared(cLocal, v2) > radius * radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.wSet(1, cLocal, -1, v2); manifold.localNormal.normalize(); manifold.localPoint.set(v2); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } else { var faceCenter = Vec2.mid(v1, v2); var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]); if (separation > radius) { return; } manifold.pointCount = 1; manifold.type = Manifold.e_faceA; manifold.localNormal.set(normals[vertIndex1]); manifold.localPoint.set(faceCenter); manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; } } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var CircleShape = require("./CircleShape"); Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact); Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact); function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var shapeA = fixtureA.getShape(); var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE); ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE); var chain = fixtureA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); var shapeA = edge; var shapeB = fixtureB.getShape(); CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB); } function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) { manifold.pointCount = 0; var Q = Transform.mulT(xfA, Transform.mul(xfB, circleB.m_p)); var A = edgeA.m_vertex1; var B = edgeA.m_vertex2; var e = Vec2.sub(B, A); var u = Vec2.dot(e, Vec2.sub(B, Q)); var v = Vec2.dot(e, Vec2.sub(Q, A)); var radius = edgeA.m_radius + circleB.m_radius; if (v <= 0) { var P = Vec2.clone(A); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex0) { var A1 = edgeA.m_vertex0; var B1 = A; var e1 = Vec2.sub(B1, A1); var u1 = Vec2.dot(e1, Vec2.sub(B1, Q)); if (u1 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } if (u <= 0) { var P = Vec2.clone(B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } if (edgeA.m_hasVertex3) { var B2 = edgeA.m_vertex3; var A2 = B; var e2 = Vec2.sub(B2, A2); var v2 = Vec2.dot(e2, Vec2.sub(Q, A2)); if (v2 > 0) { return; } } manifold.type = Manifold.e_circles; manifold.localNormal.setZero(); manifold.localPoint.set(P); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 1; manifold.points[0].id.cf.typeA = Manifold.e_vertex; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; return; } var den = Vec2.dot(e, e); ASSERT && common.assert(den > 0); var P = Vec2.wAdd(u / den, A, v / den, B); var d = Vec2.sub(Q, P); var dd = Vec2.dot(d, d); if (dd > radius * radius) { return; } var n = Vec2.neo(-e.y, e.x); if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) { n.set(-n.x, -n.y); } n.normalize(); manifold.type = Manifold.e_faceA; manifold.localNormal = n; manifold.localPoint.set(A); manifold.pointCount = 1; manifold.points[0].localPoint.set(circleB.m_p); manifold.points[0].id.key = 0; manifold.points[0].id.cf.indexA = 0; manifold.points[0].id.cf.typeA = Manifold.e_face; manifold.points[0].id.cf.indexB = 0; manifold.points[0].id.cf.typeB = Manifold.e_vertex; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var create = require("../util/create"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Vec2 = require("../common/Vec2"); var Rot = require("../common/Rot"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Contact = require("../Contact"); var Manifold = require("../Manifold"); var EdgeShape = require("./EdgeShape"); var ChainShape = require("./ChainShape"); var PolygonShape = require("./PolygonShape"); Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact); Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact); function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { ASSERT && common.assert(fA.getType() == EdgeShape.TYPE); ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB); } function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) { ASSERT && common.assert(fA.getType() == ChainShape.TYPE); ASSERT && common.assert(fB.getType() == PolygonShape.TYPE); var chain = fA.getShape(); var edge = new EdgeShape(); chain.getChildEdge(edge, indexA); CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB); } var e_unknown = -1; var e_edgeA = 1; var e_edgeB = 2; var e_isolated = 0; var e_concave = 1; var e_convex = 2; function EPAxis() { this.type; this.index; this.separation; } function TempPolygon() { this.vertices = []; this.normals = []; this.count = 0; } function ReferenceFace() { this.i1, this.i2; this.v1, this.v2; this.normal = Vec2.zero(); this.sideNormal1 = Vec2.zero(); this.sideOffset1; this.sideNormal2 = Vec2.zero(); this.sideOffset2; } var edgeAxis = new EPAxis(); var polygonAxis = new EPAxis(); var polygonBA = new TempPolygon(); var rf = new ReferenceFace(); function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) { DEBUG && common.debug("CollideEdgePolygon"); var m_type1, m_type2; var xf = Transform.mulT(xfA, xfB); var centroidB = Transform.mul(xf, polygonB.m_centroid); var v0 = edgeA.m_vertex0; var v1 = edgeA.m_vertex1; var v2 = edgeA.m_vertex2; var v3 = edgeA.m_vertex3; var hasVertex0 = edgeA.m_hasVertex0; var hasVertex3 = edgeA.m_hasVertex3; var edge1 = Vec2.sub(v2, v1); edge1.normalize(); var normal1 = Vec2.neo(edge1.y, -edge1.x); var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1)); var offset0 = 0; var offset2 = 0; var convex1 = false; var convex2 = false; if (hasVertex0) { var edge0 = Vec2.sub(v1, v0); edge0.normalize(); var normal0 = Vec2.neo(edge0.y, -edge0.x); convex1 = Vec2.cross(edge0, edge1) >= 0; offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0); } if (hasVertex3) { var edge2 = Vec2.sub(v3, v2); edge2.normalize(); var normal2 = Vec2.neo(edge2.y, -edge2.x); convex2 = Vec2.cross(edge1, edge2) > 0; offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2); } var front; var normal = Vec2.zero(); var lowerLimit = Vec2.zero(); var upperLimit = Vec2.zero(); if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal1); } } else if (convex1) { front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-1, normal1); } } else if (convex2) { front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal0); } } else { front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.wSet(-1, normal0); } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0 || offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal0); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } } else { front = offset0 >= 0 && offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.wSet(-1, normal0); } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0 || offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal2); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } } else { front = offset1 >= 0 && offset2 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.set(normal1); } else { normal.wSet(-1, normal1); lowerLimit.wSet(-1, normal2); upperLimit.set(normal1); } } } else { front = offset1 >= 0; if (front) { normal.set(normal1); lowerLimit.wSet(-1, normal1); upperLimit.wSet(-1, normal1); } else { normal.wSet(-1, normal1); lowerLimit.set(normal1); upperLimit.set(normal1); } } polygonBA.count = polygonB.m_count; for (var i = 0; i < polygonB.m_count; ++i) { polygonBA.vertices[i] = Transform.mul(xf, polygonB.m_vertices[i]); polygonBA.normals[i] = Rot.mul(xf.q, polygonB.m_normals[i]); } var radius = 2 * Settings.polygonRadius; manifold.pointCount = 0; { edgeAxis.type = e_edgeA; edgeAxis.index = front ? 0 : 1; edgeAxis.separation = Infinity; for (var i = 0; i < polygonBA.count; ++i) { var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1)); if (s < edgeAxis.separation) { edgeAxis.separation = s; } } } if (edgeAxis.type == e_unknown) { return; } if (edgeAxis.separation > radius) { return; } { polygonAxis.type = e_unknown; polygonAxis.index = -1; polygonAxis.separation = -Infinity; var perp = Vec2.neo(-normal.y, normal.x); for (var i = 0; i < polygonBA.count; ++i) { var n = Vec2.neg(polygonBA.normals[i]); var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1)); var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2)); var s = Math.min(s1, s2); if (s > radius) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; break; } if (Vec2.dot(n, perp) >= 0) { if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) { continue; } } else { if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) { continue; } } if (s > polygonAxis.separation) { polygonAxis.type = e_edgeB; polygonAxis.index = i; polygonAxis.separation = s; } } } if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) { return; } var k_relativeTol = .98; var k_absoluteTol = .001; var primaryAxis; if (polygonAxis.type == e_unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; if (primaryAxis.type == e_edgeA) { manifold.type = Manifold.e_faceA; var bestIndex = 0; var bestValue = Vec2.dot(normal, polygonBA.normals[0]); for (var i = 1; i < polygonBA.count; ++i) { var value = Vec2.dot(normal, polygonBA.normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } var i1 = bestIndex; var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0; ie[0].v = polygonBA.vertices[i1]; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = i1; ie[0].id.cf.typeA = Manifold.e_face; ie[0].id.cf.typeB = Manifold.e_vertex; ie[1].v = polygonBA.vertices[i2]; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = i2; ie[1].id.cf.typeA = Manifold.e_face; ie[1].id.cf.typeB = Manifold.e_vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.normal.set(normal1); } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.normal.wSet(-1, normal1); } } else { manifold.type = Manifold.e_faceB; ie[0].v = v1; ie[0].id.cf.indexA = 0; ie[0].id.cf.indexB = primaryAxis.index; ie[0].id.cf.typeA = Manifold.e_vertex; ie[0].id.cf.typeB = Manifold.e_face; ie[1].v = v2; ie[1].id.cf.indexA = 0; ie[1].id.cf.indexB = primaryAxis.index; ie[1].id.cf.typeA = Manifold.e_vertex; ie[1].id.cf.typeB = Manifold.e_face; rf.i1 = primaryAxis.index; rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0; rf.v1 = polygonBA.vertices[rf.i1]; rf.v2 = polygonBA.vertices[rf.i2]; rf.normal.set(polygonBA.normals[rf.i1]); } rf.sideNormal1.set(rf.normal.y, -rf.normal.x); rf.sideNormal2.wSet(-1, rf.sideNormal1); rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1); rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2); var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); if (np < Settings.maxManifoldPoints) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); if (np < Settings.maxManifoldPoints) { return; } if (primaryAxis.type == e_edgeA) { manifold.localNormal = Vec2.clone(rf.normal); manifold.localPoint = Vec2.clone(rf.v1); } else { manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]); manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]); } var pointCount = 0; for (var i = 0; i < Settings.maxManifoldPoints; ++i) { var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1)); if (separation <= radius) { var cp = manifold.points[pointCount]; if (primaryAxis.type == e_edgeA) { cp.localPoint = Transform.mulT(xf, clipPoints2[i].v); cp.id = clipPoints2[i].id; } else { cp.localPoint = clipPoints2[i].v; cp.id.cf.typeA = clipPoints2[i].id.cf.typeB; cp.id.cf.typeB = clipPoints2[i].id.cf.typeA; cp.id.cf.indexA = clipPoints2[i].id.cf.indexB; cp.id.cf.indexB = clipPoints2[i].id.cf.indexA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var common = require("../util/common"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Manifold = require("../Manifold"); var Contact = require("../Contact"); var Shape = require("../Shape"); var PolygonShape = require("./PolygonShape"); module.exports = CollidePolygons; Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact); function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) { ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE); ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE); CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB); } function FindMaxSeparation(poly1, xf1, poly2, xf2) { var count1 = poly1.m_count; var count2 = poly2.m_count; var n1s = poly1.m_normals; var v1s = poly1.m_vertices; var v2s = poly2.m_vertices; var xf = Transform.mulT(xf2, xf1); var bestIndex = 0; var maxSeparation = -Infinity; for (var i = 0; i < count1; ++i) { var n = Rot.mul(xf.q, n1s[i]); var v1 = Transform.mul(xf, v1s[i]); var si = Infinity; for (var j = 0; j < count2; ++j) { var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1); if (sij < si) { si = sij; } } if (si > maxSeparation) { maxSeparation = si; bestIndex = i; } } FindMaxSeparation._maxSeparation = maxSeparation; FindMaxSeparation._bestIndex = bestIndex; } function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) { var normals1 = poly1.m_normals; var count2 = poly2.m_count; var vertices2 = poly2.m_vertices; var normals2 = poly2.m_normals; ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count); var normal1 = Rot.mulT(xf2.q, Rot.mul(xf1.q, normals1[edge1])); var index = 0; var minDot = Infinity; for (var i = 0; i < count2; ++i) { var dot = Vec2.dot(normal1, normals2[i]); if (dot < minDot) { minDot = dot; index = i; } } var i1 = index; var i2 = i1 + 1 < count2 ? i1 + 1 : 0; c[0].v = Transform.mul(xf2, vertices2[i1]); c[0].id.cf.indexA = edge1; c[0].id.cf.indexB = i1; c[0].id.cf.typeA = Manifold.e_face; c[0].id.cf.typeB = Manifold.e_vertex; c[1].v = Transform.mul(xf2, vertices2[i2]); c[1].id.cf.indexA = edge1; c[1].id.cf.indexB = i2; c[1].id.cf.typeA = Manifold.e_face; c[1].id.cf.typeB = Manifold.e_vertex; } function CollidePolygons(manifold, polyA, xfA, polyB, xfB) { manifold.pointCount = 0; var totalRadius = polyA.m_radius + polyB.m_radius; FindMaxSeparation(polyA, xfA, polyB, xfB); var edgeA = FindMaxSeparation._bestIndex; var separationA = FindMaxSeparation._maxSeparation; if (separationA > totalRadius) return; FindMaxSeparation(polyB, xfB, polyA, xfA); var edgeB = FindMaxSeparation._bestIndex; var separationB = FindMaxSeparation._maxSeparation; if (separationB > totalRadius) return; var poly1; var poly2; var xf1; var xf2; var edge1; var flip; var k_tol = .1 * Settings.linearSlop; if (separationB > separationA + k_tol) { poly1 = polyB; poly2 = polyA; xf1 = xfB; xf2 = xfA; edge1 = edgeB; manifold.type = Manifold.e_faceB; flip = 1; } else { poly1 = polyA; poly2 = polyB; xf1 = xfA; xf2 = xfB; edge1 = edgeA; manifold.type = Manifold.e_faceA; flip = 0; } var incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); var count1 = poly1.m_count; var vertices1 = poly1.m_vertices; var iv1 = edge1; var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; var v11 = vertices1[iv1]; var v12 = vertices1[iv2]; var localTangent = Vec2.sub(v12, v11); localTangent.normalize(); var localNormal = Vec2.cross(localTangent, 1); var planePoint = Vec2.wAdd(.5, v11, .5, v12); var tangent = Rot.mul(xf1.q, localTangent); var normal = Vec2.cross(tangent, 1); v11 = Transform.mul(xf1, v11); v12 = Transform.mul(xf1, v12); var frontOffset = Vec2.dot(normal, v11); var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius; var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius; var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ]; var np; np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1); if (np < 2) { return; } np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); if (np < 2) { return; } manifold.localNormal = localNormal; manifold.localPoint = planePoint; var pointCount = 0; for (var i = 0; i < clipPoints2.length; ++i) { var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset; if (separation <= totalRadius) { var cp = manifold.points[pointCount]; cp.localPoint.set(Transform.mulT(xf2, clipPoints2[i].v)); cp.id = clipPoints2[i].id; if (flip) { var cf = cp.id.cf; var indexA = cf.indexA; var indexB = cf.indexB; var typeA = cf.typeA; var typeB = cf.typeB; cf.indexA = indexB; cf.indexB = indexA; cf.typeA = typeB; cf.typeB = typeA; } ++pointCount; } } manifold.pointCount = pointCount; } },{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = EdgeShape; var create = require("../util/create"); var options = require("../util/options"); var Settings = require("../Settings"); var Shape = require("../Shape"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); EdgeShape._super = Shape; EdgeShape.prototype = create(EdgeShape._super.prototype); EdgeShape.TYPE = "edge"; function EdgeShape(v1, v2) { if (!(this instanceof EdgeShape)) { return new EdgeShape(v1, v2); } EdgeShape._super.call(this); this.m_type = EdgeShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero(); this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero(); this.m_vertex0 = Vec2.zero(); this.m_vertex3 = Vec2.zero(); this.m_hasVertex0 = false; this.m_hasVertex3 = false; } EdgeShape.prototype.setNext = function(v3) { if (v3) { this.m_vertex3.set(v3); this.m_hasVertex3 = true; } else { this.m_vertex3.setZero(); this.m_hasVertex3 = false; } return this; }; EdgeShape.prototype.setPrev = function(v0) { if (v0) { this.m_vertex0.set(v0); this.m_hasVertex0 = true; } else { this.m_vertex0.setZero(); this.m_hasVertex0 = false; } return this; }; EdgeShape.prototype._set = function(v1, v2) { this.m_vertex1.set(v1); this.m_vertex2.set(v2); this.m_hasVertex0 = false; this.m_hasVertex3 = false; return this; }; EdgeShape.prototype._clone = function() { var clone = new EdgeShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_vertex1.set(this.m_vertex1); clone.m_vertex2.set(this.m_vertex2); clone.m_vertex0.set(this.m_vertex0); clone.m_vertex3.set(this.m_vertex3); clone.m_hasVertex0 = this.m_hasVertex0; clone.m_hasVertex3 = this.m_hasVertex3; return clone; }; EdgeShape.prototype.getChildCount = function() { return 1; }; EdgeShape.prototype.testPoint = function(xf, p) { return false; }; EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var v1 = this.m_vertex1; var v2 = this.m_vertex2; var e = Vec2.sub(v2, v1); var normal = Vec2.neo(e.y, -e.x); normal.normalize(); var numerator = Vec2.dot(normal, Vec2.sub(v1, p1)); var denominator = Vec2.dot(normal, d); if (denominator == 0) { return false; } var t = numerator / denominator; if (t < 0 || input.maxFraction < t) { return false; } var q = Vec2.add(p1, Vec2.mul(t, d)); var r = Vec2.sub(v2, v1); var rr = Vec2.dot(r, r); if (rr == 0) { return false; } var s = Vec2.dot(Vec2.sub(q, v1), r) / rr; if (s < 0 || 1 < s) { return false; } output.fraction = t; if (numerator > 0) { output.normal = Rot.mul(xf.q, normal).neg(); } else { output.normal = Rot.mul(xf.q, normal); } return true; }; EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) { var v1 = Transform.mul(xf, this.m_vertex1); var v2 = Transform.mul(xf, this.m_vertex2); aabb.combinePoints(v1, v2); aabb.extend(this.m_radius); }; EdgeShape.prototype.computeMass = function(massData, density) { massData.mass = 0; massData.center.wSet(.5, this.m_vertex1, .5, this.m_vertex2); massData.I = 0; }; EdgeShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices.push(this.m_vertex1); proxy.m_vertices.push(this.m_vertex2); proxy.m_count = 2; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = PolygonShape; var common = require("../util/common"); var create = require("../util/create"); var options = require("../util/options"); var Math = require("../common/Math"); var Transform = require("../common/Transform"); var Rot = require("../common/Rot"); var Vec2 = require("../common/Vec2"); var AABB = require("../collision/AABB"); var Settings = require("../Settings"); var Shape = require("../Shape"); PolygonShape._super = Shape; PolygonShape.prototype = create(PolygonShape._super.prototype); PolygonShape.TYPE = "polygon"; function PolygonShape(vertices) { if (!(this instanceof PolygonShape)) { return new PolygonShape(vertices); } PolygonShape._super.call(this); this.m_type = PolygonShape.TYPE; this.m_radius = Settings.polygonRadius; this.m_centroid = Vec2.zero(); this.m_vertices = []; this.m_normals = []; this.m_count = 0; if (vertices && vertices.length) { this._set(vertices); } } PolygonShape.prototype.getVertex = function(index) { ASSERT && common.assert(0 <= index && index < this.m_count); return this.m_vertices[index]; }; PolygonShape.prototype._clone = function() { var clone = new PolygonShape(); clone.m_type = this.m_type; clone.m_radius = this.m_radius; clone.m_count = this.m_count; clone.m_centroid.set(this.m_centroid); for (var i = 0; i < this.m_count; i++) { clone.m_vertices.push(this.m_vertices[i].clone()); } for (var i = 0; i < this.m_normals.length; i++) { clone.m_normals.push(this.m_normals[i].clone()); } return clone; }; PolygonShape.prototype.getChildCount = function() { return 1; }; function ComputeCentroid(vs, count) { ASSERT && common.assert(count >= 3); var c = Vec2.zero(); var area = 0; var pRef = Vec2.zero(); if (false) { for (var i = 0; i < count; ++i) { pRef.add(vs[i]); } pRef.mul(1 / count); } var inv3 = 1 / 3; for (var i = 0; i < count; ++i) { var p1 = pRef; var p2 = vs[i]; var p3 = i + 1 < count ? vs[i + 1] : vs[0]; var e1 = Vec2.sub(p2, p1); var e2 = Vec2.sub(p3, p1); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; c.wAdd(triangleArea * inv3, p1); c.wAdd(triangleArea * inv3, p2); c.wAdd(triangleArea * inv3, p3); } ASSERT && common.assert(area > Math.EPSILON); c.mul(1 / area); return c; } PolygonShape.prototype._set = function(vertices) { ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices); if (vertices.length < 3) { SetAsBox(1, 1); return; } var n = Math.min(vertices.length, Settings.maxPolygonVertices); var ps = []; var tempCount = 0; for (var i = 0; i < n; ++i) { var v = vertices[i]; var unique = true; for (var j = 0; j < tempCount; ++j) { if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) { unique = false; break; } } if (unique) { ps[tempCount++] = v; } } n = tempCount; if (n < 3) { ASSERT && common.assert(false); SetAsBox(1, 1); return; } var i0 = 0; var x0 = ps[0].x; for (var i = 1; i < n; ++i) { var x = ps[i].x; if (x > x0 || x == x0 && ps[i].y < ps[i0].y) { i0 = i; x0 = x; } } var hull = []; var m = 0; var ih = i0; for (;;) { hull[m] = ih; var ie = 0; for (var j = 1; j < n; ++j) { if (ie == ih) { ie = j; continue; } var r = Vec2.sub(ps[ie], ps[hull[m]]); var v = Vec2.sub(ps[j], ps[hull[m]]); var c = Vec2.cross(r, v); if (c < 0) { ie = j; } if (c == 0 && v.lengthSquared() > r.lengthSquared()) { ie = j; } } ++m; ih = ie; if (ie == i0) { break; } } if (m < 3) { ASSERT && common.assert(false); SetAsBox(1, 1); return; } this.m_count = m; for (var i = 0; i < m; ++i) { this.m_vertices[i] = ps[hull[i]]; } for (var i = 0; i < m; ++i) { var i1 = i; var i2 = i + 1 < m ? i + 1 : 0; var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]); ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON); this.m_normals[i] = Vec2.cross(edge, 1); this.m_normals[i].normalize(); } this.m_centroid = ComputeCentroid(this.m_vertices, m); }; PolygonShape.prototype.testPoint = function(xf, p) { var pLocal = Rot.mulT(xf.q, Vec2.sub(p, xf.p)); for (var i = 0; i < this.m_count; ++i) { var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i])); if (dot > 0) { return false; } } return true; }; PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) { var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p)); var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p)); var d = Vec2.sub(p2, p1); var lower = 0; var upper = input.maxFraction; var index = -1; for (var i = 0; i < this.m_count; ++i) { var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1)); var denominator = Vec2.dot(this.m_normals[i], d); if (denominator == 0) { if (numerator < 0) { return false; } } else { if (denominator < 0 && numerator < lower * denominator) { lower = numerator / denominator; index = i; } else if (denominator > 0 && numerator < upper * denominator) { upper = numerator / denominator; } } if (upper < lower) { return false; } } ASSERT && common.assert(0 <= lower && lower <= input.maxFraction); if (index >= 0) { output.fraction = lower; output.normal = Rot.mul(xf.q, this.m_normals[index]); return true; } return false; }; PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) { var minX = Infinity, minY = Infinity; var maxX = -Infinity, maxY = -Infinity; for (var i = 0; i < this.m_count; ++i) { var v = Transform.mul(xf, this.m_vertices[i]); minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x); minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y); } aabb.lowerBound.set(minX, minY); aabb.upperBound.set(maxX, maxY); aabb.extend(this.m_radius); }; PolygonShape.prototype.computeMass = function(massData, density) { ASSERT && common.assert(this.m_count >= 3); var center = Vec2.zero(); var area = 0; var I = 0; var s = Vec2.zero(); for (var i = 0; i < this.m_count; ++i) { s.add(this.m_vertices[i]); } s.mul(1 / this.m_count); var k_inv3 = 1 / 3; for (var i = 0; i < this.m_count; ++i) { var e1 = Vec2.sub(this.m_vertices[i], s); var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s); var D = Vec2.cross(e1, e2); var triangleArea = .5 * D; area += triangleArea; center.wAdd(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2); var ex1 = e1.x; var ey1 = e1.y; var ex2 = e2.x; var ey2 = e2.y; var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += .25 * k_inv3 * D * (intx2 + inty2); } massData.mass = density * area; ASSERT && common.assert(area > Math.EPSILON); center.mul(1 / area); massData.center.wSet(1, center, 1, s); massData.I = density * I; massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center)); }; PolygonShape.prototype.validate = function() { for (var i = 0; i < this.m_count; ++i) { var i1 = i; var i2 = i < this.m_count - 1 ? i1 + 1 : 0; var p = this.m_vertices[i1]; var e = Vec2.sub(this.m_vertices[i2], p); for (var j = 0; j < this.m_count; ++j) { if (j == i1 || j == i2) { continue; } var v = Vec2.sub(this.m_vertices[j], p); var c = Vec2.cross(e, v); if (c < 0) { return false; } } } return true; }; PolygonShape.prototype.computeDistanceProxy = function(proxy) { proxy.m_vertices = this.m_vertices; proxy.m_count = this.m_count; proxy.m_radius = this.m_radius; }; },{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports = Pool; function Pool(opts) { var _list = []; var _max = opts.max || Infinity; var _createFn = opts.create; var _outFn = opts.allocate; var _inFn = opts.release; var _discardFn = opts.discard; var _createCount = 0; var _outCount = 0; var _inCount = 0; var _discardCount = 0; this.max = function(n) { if (typeof n === "number") { _max = n; return this; } return _max; }; this.size = function() { return _list.length; }; this.allocate = function() { var item; if (_list.length > 0) { item = _list.shift(); } else { _createCount++; if (typeof _createFn === "function") { item = _createFn(); } else { item = {}; } } _outCount++; if (typeof _outFn === "function") { _outFn(item); } return item; }; this.release = function(item) { if (_list.length < _max) { _inCount++; if (typeof _inFn === "function") { _inFn(item); } _list.push(item); } else { _discardCount++; if (typeof _discardFn === "function") { item = _discardFn(item); } } }; this.toString = function() { return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _list.length + "/" + _max; }; } },{}],50:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; module.exports.now = function() { return Date.now(); }; module.exports.diff = function(time) { return Date.now() - time; }; },{}],51:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; exports.debug = function() { if (!DEBUG) return; console.log.apply(console, arguments); }; exports.assert = function(statement, err, log) { if (!ASSERT) return; if (statement) return; log && console.log(log); throw new Error(err); }; },{}],52:[function(require,module,exports){ if (typeof Object.create == "function") { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error("Second argument is not supported!"); if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!"); noop.prototype = proto; return new noop(); }; function noop() {} } },{}],53:[function(require,module,exports){ DEBUG = typeof DEBUG === "undefined" ? false : DEBUG; ASSERT = typeof ASSERT === "undefined" ? false : ASSERT; var propIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function(to, from) { if (to === null || typeof to === "undefined") { to = {}; } for (var key in from) { if (from.hasOwnProperty(key) && typeof to[key] === "undefined") { to[key] = from[key]; } } if (typeof Object.getOwnPropertySymbols === "function") { var symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { var symbol = symbols[i]; if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") { to[symbol] = from[symbol]; } } } return to; }; },{}],54:[function(require,module,exports){ function _identity(x) { return x; }; var _cache = {}; var _modes = {}; var _easings = {}; function Easing(token) { if (typeof token === 'function') { return token; } if (typeof token !== 'string') { return _identity; } var fn = _cache[token]; if (fn) { return fn; } var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token); if (!match || !match.length) { return _identity; } var easing = _easings[match[1]]; var mode = _modes[match[3]]; var params = match[5]; if (easing && easing.fn) { fn = easing.fn; } else if (easing && easing.fc) { fn = easing.fc.apply(easing.fc, params && params.replace(/\s+/, '').split(',')); } else { fn = _identity; } if (mode) { fn = mode.fn(fn); } // TODO: It can be a memory leak with different `params`. _cache[token] = fn; return fn; }; Easing.add = function(data) { // TODO: create a map of all { name-mode : data } var names = (data.name || data.mode).split(/\s+/); for (var i = 0; i < names.length; i++) { var name = names[i]; if (name) { (data.name ? _easings : _modes)[name] = data; } } }; Easing.add({ mode : 'in', fn : function(f) { return f; } }); Easing.add({ mode : 'out', fn : function(f) { return function(t) { return 1 - f(1 - t); }; } }); Easing.add({ mode : 'in-out', fn : function(f) { return function(t) { return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2); }; } }); Easing.add({ mode : 'out-in', fn : function(f) { return function(t) { return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2); }; } }); Easing.add({ name : 'linear', fn : function(t) { return t; } }); Easing.add({ name : 'quad', fn : function(t) { return t * t; } }); Easing.add({ name : 'cubic', fn : function(t) { return t * t * t; } }); Easing.add({ name : 'quart', fn : function(t) { return t * t * t * t; } }); Easing.add({ name : 'quint', fn : function(t) { return t * t * t * t * t; } }); Easing.add({ name : 'sin sine', fn : function(t) { return 1 - Math.cos(t * Math.PI / 2); } }); Easing.add({ name : 'exp expo', fn : function(t) { return t == 0 ? 0 : Math.pow(2, 10 * (t - 1)); } }); Easing.add({ name : 'circle circ', fn : function(t) { return 1 - Math.sqrt(1 - t * t); } }); Easing.add({ name : 'bounce', fn : function(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } }); Easing.add({ name : 'poly', fc : function(e) { return function(t) { return Math.pow(t, e); }; } }); Easing.add({ name : 'elastic', fc : function(a, p) { p = p || 0.45; a = a || 1; var s = p / (2 * Math.PI) * Math.asin(1 / a); return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p); }; } }); Easing.add({ name : 'back', fc : function(s) { s = typeof s !== 'undefined' ? s : 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } }); module.exports = Easing; },{}],55:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; require('../core')._load(function(stage, elem) { Mouse.subscribe(stage, elem); }); // TODO: capture mouse Mouse.CLICK = 'click'; Mouse.START = 'touchstart mousedown'; Mouse.MOVE = 'touchmove mousemove'; Mouse.END = 'touchend mouseup'; Mouse.CANCEL = 'touchcancel mousecancel'; Mouse.subscribe = function(stage, elem) { if (stage.mouse) { return; } stage.mouse = new Mouse(stage, elem); // `click` events are synthesized from start/end events on same nodes // `mousecancel` events are synthesized on blur or mouseup outside element elem.addEventListener('touchstart', handleStart); elem.addEventListener('touchend', handleEnd); elem.addEventListener('touchmove', handleMove); elem.addEventListener('touchcancel', handleCancel); elem.addEventListener('mousedown', handleStart); elem.addEventListener('mouseup', handleEnd); elem.addEventListener('mousemove', handleMove); document.addEventListener('mouseup', handleCancel); window.addEventListener("blur", handleCancel); var clicklist = [], cancellist = []; function handleStart(event) { event.preventDefault(); stage.mouse.locate(event); // DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); stage.mouse.lookup('click', clicklist); stage.mouse.lookup('mousecancel', cancellist); } function handleMove(event) { event.preventDefault(); stage.mouse.locate(event); stage.mouse.publish(event.type, event); } function handleEnd(event) { event.preventDefault(); // up/end location is not available, last one is used instead // DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse); stage.mouse.publish(event.type, event); if (clicklist.length) { // DEBUG && console.log('Mouse Click: ' + clicklist.length); stage.mouse.publish('click', event, clicklist); } cancellist.length = 0; } function handleCancel(event) { if (cancellist.length) { // DEBUG && console.log('Mouse Cancel: ' + event.type); stage.mouse.publish('mousecancel', event, cancellist); } clicklist.length = 0; } }; function Mouse(stage, elem) { if (!(this instanceof Mouse)) { // old-style mouse subscription return; } var ratio = stage.viewport().ratio || 1; stage.on('viewport', function(size) { ratio = size.ratio || ratio; }); this.x = 0; this.y = 0; this.toString = function() { return (this.x | 0) + 'x' + (this.y | 0); }; this.locate = function(event) { locateElevent(elem, event, this); this.x *= ratio; this.y *= ratio; }; this.lookup = function(type, collect) { this.type = type; this.root = stage; this.event = null; collect.length = 0; this.collect = collect; this.root.visit(this.visitor, this); }; this.publish = function(type, event, targets) { this.type = type; this.root = stage; this.event = event; this.collect = false; this.timeStamp = Date.now(); if (type !== 'mousemove' && type !== 'touchmove') { DEBUG && console.log(this.type + ' ' + this); } if (targets) { while (targets.length) if (this.visitor.end(targets.shift(), this)) break; targets.length = 0; } else { this.root.visit(this.visitor, this); } }; this.visitor = { reverse : true, visible : true, start : function(node, mouse) { return !node._flag(mouse.type); }, end : function(node, mouse) { // mouse: event/collect, type, root rel.raw = mouse.event; rel.type = mouse.type; rel.timeStamp = mouse.timeStamp; rel.abs.x = mouse.x; rel.abs.y = mouse.y; var listeners = node.listeners(mouse.type); if (!listeners) { return; } node.matrix().inverse().map(mouse, rel); if (!(node === mouse.root || node.hitTest(rel))) { return; } if (mouse.collect) { mouse.collect.push(node); } if (mouse.event) { var cancel = false; for (var l = 0; l < listeners.length; l++) { cancel = listeners[l].call(node, rel) ? true : cancel; } return cancel; } } }; }; // TODO: define per mouse object with get-only x and y var rel = {}, abs = {}; defineValue(rel, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(rel, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')'; }); defineValue(rel, 'abs', abs); defineValue(abs, 'clone', function(obj) { obj = obj || {}, obj.x = this.x, obj.y = this.y; return obj; }); defineValue(abs, 'toString', function() { return (this.x | 0) + 'x' + (this.y | 0); }); function defineValue(obj, name, value) { Object.defineProperty(obj, name, { value : value }); } function locateElevent(el, ev, loc) { // pageX/Y if available? if (ev.touches && ev.touches.length) { loc.x = ev.touches[0].clientX; loc.y = ev.touches[0].clientY; } else { loc.x = ev.clientX; loc.y = ev.clientY; } var rect = el.getBoundingClientRect(); loc.x -= rect.left; loc.y -= rect.top; loc.x -= el.clientLeft | 0; loc.y -= el.clientTop | 0; return loc; }; module.exports = Mouse; },{"../core":60}],56:[function(require,module,exports){ var Easing = require('./easing'); var Class = require('../core'); var Pin = require('../pin'); Class.prototype.tween = function(duration, delay, append) { if (typeof duration !== 'number') { append = duration, delay = 0, duration = 0; } else if (typeof delay !== 'number') { append = delay, delay = 0; } if (!this._tweens) { this._tweens = []; var ticktime = 0; this.tick(function(elapsed, now, last) { if (!this._tweens.length) { return; } // ignore old elapsed var ignore = ticktime != last; ticktime = now; if (ignore) { return true; } var next = this._tweens[0].tick(this, elapsed, now, last); if (next) { this._tweens.shift(); } if (typeof next === 'object') { this._tweens.unshift(next); } return true; }, true); } this.touch(); if (!append) { this._tweens.length = 0; } var tween = new Tween(this, duration, delay); this._tweens.push(tween); return tween; }; function Tween(owner, duration, delay) { this._end = {}; this._duration = duration || 400; this._delay = delay || 0; this._owner = owner; this._time = 0; }; Tween.prototype.tick = function(node, elapsed, now, last) { this._time += elapsed; if (this._time < this._delay) { return; } var time = this._time - this._delay; if (!this._start) { this._start = {}; for ( var key in this._end) { this._start[key] = this._owner.pin(key); } } var p, over; if (time < this._duration) { p = time / this._duration, over = false; } else { p = 1, over = true; } p = typeof this._easing == 'function' ? this._easing(p) : p; var q = 1 - p; for ( var key in this._end) { this._owner.pin(key, this._start[key] * q + this._end[key] * p); } if (over) { try { this._done && this._done.call(this._owner); } catch (e) { console.log(e); } return this._next || true; } }; Tween.prototype.tween = function(duration, delay) { return this._next = new Tween(this._owner, duration, delay); }; Tween.prototype.duration = function(duration) { this._duration = duration; return this; }; Tween.prototype.delay = function(delay) { this._delay = delay; return this; }; Tween.prototype.ease = function(easing) { this._easing = Easing(easing); return this; }; Tween.prototype.done = function(fn) { this._done = fn; return this; }; Tween.prototype.hide = function() { this.done(function() { this.hide(); }); return this; }; Tween.prototype.remove = function() { this.done(function() { this.remove(); }); return this; }; Tween.prototype.pin = function(a, b) { if (typeof a === 'object') { for ( var attr in a) { pinning(this._owner, this._end, attr, a[attr]); } } else if (typeof b !== 'undefined') { pinning(this._owner, this._end, a, b); } return this; }; function pinning(node, map, key, value) { if (typeof node.pin(key) === 'number') { map[key] = value; } else if (typeof node.pin(key + 'X') === 'number' && typeof node.pin(key + 'Y') === 'number') { map[key + 'X'] = value; map[key + 'Y'] = value; } } Pin._add_shortcuts(Tween); /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated Use .done(fn) instead. */ Tween.prototype.then = function(fn) { this.done(fn); return this; }; /** * @deprecated NOOP */ Tween.prototype.clear = function(forward) { return this; }; module.exports = Tween; },{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var math = require('./util/math'); Class.anim = function(frames, fps) { var anim = new Anim(); anim.frames(frames).gotoFrame(0); fps && anim.fps(fps); return anim; }; Anim._super = Class; Anim.prototype = create(Anim._super.prototype); // TODO: replace with atlas fps or texture time Class.Anim = { FPS : 15 }; function Anim() { Anim._super.call(this); this.label('Anim'); this._textures = []; this._fps = Class.Anim.FPS; this._ft = 1000 / this._fps; this._time = -1; this._repeat = 0; this._index = 0; this._frames = []; var lastTime = 0; this.tick(function(t, now, last) { if (this._time < 0 || this._frames.length <= 1) { return; } // ignore old elapsed var ignore = lastTime != last; lastTime = now; if (ignore) { return true; } this._time += t; if (this._time < this._ft) { return true; } var n = this._time / this._ft | 0; this._time -= n * this._ft; this.moveFrame(n); if (this._repeat > 0 && (this._repeat -= n) <= 0) { this.stop(); this._callback && this._callback(); return false; } return true; }, false); }; Anim.prototype.fps = function(fps) { if (typeof fps === 'undefined') { return this._fps; } this._fps = fps > 0 ? fps : Class.Anim.FPS; this._ft = 1000 / this._fps; return this; }; /** * @deprecated Use frames */ Anim.prototype.setFrames = function(a, b, c) { return this.frames(a, b, c); }; Anim.prototype.frames = function(frames) { this._index = 0; this._frames = Class.texture(frames).array(); this.touch(); return this; }; Anim.prototype.length = function() { return this._frames ? this._frames.length : 0; }; Anim.prototype.gotoFrame = function(frame, resize) { this._index = math.rotate(frame, this._frames.length) | 0; resize = resize || !this._textures[0]; this._textures[0] = this._frames[this._index]; if (resize) { this.pin('width', this._textures[0].width); this.pin('height', this._textures[0].height); } this.touch(); return this; }; Anim.prototype.moveFrame = function(move) { return this.gotoFrame(this._index + move); }; Anim.prototype.repeat = function(repeat, callback) { this._repeat = repeat * this._frames.length - 1; this._callback = callback; this.play(); return this; }; Anim.prototype.play = function(frame) { if (typeof frame !== 'undefined') { this.gotoFrame(frame); this._time = 0; } else if (this._time < 0) { this._time = 0; } this.touch(); return this; }; Anim.prototype.stop = function(frame) { this._time = -1; if (typeof frame !== 'undefined') { this.gotoFrame(frame); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('./core'); var Texture = require('./texture'); var extend = require('./util/extend'); var create = require('./util/create'); var is = require('./util/is'); var string = require('./util/string'); // name : atlas var _atlases_map = {}; // [atlas] var _atlases_arr = []; // TODO: print subquery not found error // TODO: index textures Class.atlas = function(def) { var atlas = is.fn(def.draw) ? def : new Atlas(def); if (def.name) { _atlases_map[def.name] = atlas; } _atlases_arr.push(atlas); deprecated(def, 'imagePath'); deprecated(def, 'imageRatio'); var url = def.imagePath; var ratio = def.imageRatio || 1; if (is.string(def.image)) { url = def.image; } else if (is.hash(def.image)) { url = def.image.src || def.image.url; ratio = def.image.ratio || ratio; } url && Class.preload(function(done) { url = Class.resolve(url); DEBUG && console.log('Loading atlas: ' + url); var imageloader = Class.config('image-loader'); imageloader(url, function(image) { DEBUG && console.log('Image loaded: ' + url); atlas.src(image, ratio); done(); }, function(err) { DEBUG && console.log('Error loading atlas: ' + url, err); done(); }); }); return atlas; }; Atlas._super = Texture; Atlas.prototype = create(Atlas._super.prototype); function Atlas(def) { Atlas._super.call(this); var atlas = this; deprecated(def, 'filter'); deprecated(def, 'cutouts'); deprecated(def, 'sprites'); deprecated(def, 'factory'); var map = def.map || def.filter; var ppu = def.ppu || def.ratio || 1; var trim = def.trim || 0; var textures = def.textures; var factory = def.factory; var cutouts = def.cutouts || def.sprites; function make(def) { if (!def || is.fn(def.draw)) { return def; } def = extend({}, def); if (is.fn(map)) { def = map(def); } if (ppu != 1) { def.x *= ppu, def.y *= ppu; def.width *= ppu, def.height *= ppu; def.top *= ppu, def.bottom *= ppu; def.left *= ppu, def.right *= ppu; } if (trim != 0) { def.x += trim, def.y += trim; def.width -= 2 * trim, def.height -= 2 * trim; def.top -= trim, def.bottom -= trim; def.left -= trim, def.right -= trim; } var texture = atlas.pipe(); texture.top = def.top, texture.bottom = def.bottom; texture.left = def.left, texture.right = def.right; texture.src(def.x, def.y, def.width, def.height); return texture; } function find(query) { if (textures) { if (is.fn(textures)) { return textures(query); } else if (is.hash(textures)) { return textures[query]; } } if (cutouts) { // deprecated var result = null, n = 0; for (var i = 0; i < cutouts.length; i++) { if (string.startsWith(cutouts[i].name, query)) { if (n === 0) { result = cutouts[i]; } else if (n === 1) { result = [ result, cutouts[i] ]; } else { result.push(cutouts[i]); } n++; } } if (n === 0 && is.fn(factory)) { result = function(subquery) { return factory(query + (subquery ? subquery : '')); }; } return result; } } this.select = function(query) { if (!query) { // TODO: if `textures` is texture def, map or fn? return new Selection(this.pipe()); } var found = find(query); if (found) { return new Selection(found, find, make); } }; }; var nfTexture = new Texture(); nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0; nfTexture.pipe = nfTexture.src = nfTexture.dest = function() { return this; }; nfTexture.draw = function() { }; var nfSelection = new Selection(nfTexture); function Selection(result, find, make) { function link(result, subquery) { if (!result) { return nfTexture; } else if (is.fn(result.draw)) { return result; } else if (is.hash(result) && is.number(result.width) && is.number(result.height) && is.fn(make)) { return make(result); } else if (is.hash(result) && is.defined(subquery)) { return link(result[subquery]); } else if (is.fn(result)) { return link(result(subquery)); } else if (is.array(result)) { return link(result[0]); } else if (is.string(result) && is.fn(find)) { return link(find(result)); } } this.one = function(subquery) { return link(result, subquery); }; this.array = function(arr) { var array = is.array(arr) ? arr : []; if (is.array(result)) { for (var i = 0; i < result.length; i++) { array[i] = link(result[i]); } } else { array[0] = link(result); } return array; }; } Class.texture = function(query) { if (!is.string(query)) { return new Selection(query); } var result = null, atlas, i; if ((i = query.indexOf(':')) > 0 && query.length > i + 1) { atlas = _atlases_map[query.slice(0, i)]; result = atlas && atlas.select(query.slice(i + 1)); } if (!result && (atlas = _atlases_map[query])) { result = atlas.select(); } for (i = 0; !result && i < _atlases_arr.length; i++) { result = _atlases_arr[i].select(query); } if (!result) { console.error('Texture not found: ' + query); result = nfSelection; } return result; }; function deprecated(hash, name, msg) { if (name in hash) console.log(msg ? msg.replace('%name', name) : '\'' + name + '\' field of texture atlas is deprecated.'); }; module.exports = Atlas; },{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){ var Class = require('./core'); var Texture = require('./texture'); Class.canvas = function(type, attributes, callback) { if (typeof type === 'string') { if (typeof attributes === 'object') { } else { if (typeof attributes === 'function') { callback = attributes; } attributes = {}; } } else { if (typeof type === 'function') { callback = type; } attributes = {}; type = '2d'; } var canvas = document.createElement('canvas'); var context = canvas.getContext(type, attributes); var texture = new Texture(canvas); texture.context = function() { return context; }; texture.size = function(width, height, ratio) { ratio = ratio || 1; canvas.width = width * ratio; canvas.height = height * ratio; this.src(canvas, ratio); return this; }; texture.canvas = function(fn) { if (typeof fn === 'function') { fn.call(this, context); } else if (typeof fn === 'undefined' && typeof callback === 'function') { callback.call(this, context); } return this; }; if (typeof callback === 'function') { callback.call(texture, context); } return texture; }; },{"./core":60,"./texture":71}],60:[function(require,module,exports){ if (typeof DEBUG === 'undefined') DEBUG = true; var stats = require('./util/stats'); var extend = require('./util/extend'); var is = require('./util/is'); var _await = require('./util/await'); stats.create = 0; function Class(arg) { if (!(this instanceof Class)) { if (is.fn(arg)) { return Class.app.apply(Class, arguments); } else if (is.object(arg)) { return Class.atlas.apply(Class, arguments); } else { return arg; } } stats.create++; for (var i = 0; i < _init.length; i++) { _init[i].call(this); } } var _init = []; Class._init = function(fn) { _init.push(fn); }; var _load = []; Class._load = function(fn) { _load.push(fn); }; var _config = {}; Class.config = function() { if (arguments.length === 1 && is.string(arguments[0])) { return _config[arguments[0]]; } if (arguments.length === 1 && is.object(arguments[0])) { extend(_config, arguments[0]); } if (arguments.length === 2 && is.string(arguments[0])) { _config[arguments[0], arguments[1]]; } }; var _app_queue = []; var _preload_queue = []; var _stages = []; var _loaded = false; var _paused = false; Class.app = function(app, opts) { if (!_loaded) { _app_queue.push(arguments); return; } DEBUG && console.log('Creating app...'); var loader = Class.config('app-loader'); loader(function(stage, canvas) { DEBUG && console.log('Initing app...'); for (var i = 0; i < _load.length; i++) { _load[i].call(this, stage, canvas); } app(stage, canvas); _stages.push(stage); DEBUG && console.log('Starting app...'); stage.start(); }, opts); }; var loading = _await(); Class.preload = function(load) { if (typeof load === 'string') { var url = Class.resolve(load); if (/\.js($|\?|\#)/.test(url)) { DEBUG && console.log('Loading script: ' + url); load = function(callback) { loadScript(url, callback); }; } } if (typeof load !== 'function') { return; } // if (!_started) { // _preload_queue.push(load); // return; // } load(loading()); }; Class.start = function(config) { DEBUG && console.log('Starting...'); Class.config(config); // DEBUG && console.log('Preloading...'); // _started = true; // while (_preload_queue.length) { // var load = _preload_queue.shift(); // load(loading()); // } loading.then(function() { DEBUG && console.log('Loading apps...'); _loaded = true; while (_app_queue.length) { var args = _app_queue.shift(); Class.app.apply(Class, args); } }); }; Class.pause = function() { if (!_paused) { _paused = true; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].pause(); } } }; Class.resume = function() { if (_paused) { _paused = false; for (var i = _stages.length - 1; i >= 0; i--) { _stages[i].resume(); } } }; Class.create = function() { return new Class(); }; Class.resolve = (function() { if (typeof window === 'undefined' || typeof document === 'undefined') { return function(url) { return url; }; } var scripts = document.getElementsByTagName('script'); function getScriptSrc() { // HTML5 if (document.currentScript) { return document.currentScript.src; } // IE>=10 var stack; try { var err = new Error(); if (err.stack) { stack = err.stack; } else { throw err; } } catch (err) { stack = err.stack; } if (typeof stack === 'string') { stack = stack.split('\n'); // Uses the last line, where the call started for (var i = stack.length; i--;) { var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/); if (url) { return url[1]; } } } // IE<11 if (scripts.length && 'readyState' in scripts[0]) { for (var i = scripts.length; i--;) { if (scripts[i].readyState === 'interactive') { return scripts[i].src; } } } return location.href; } return function(url) { if (/^\.\//.test(url)) { var src = getScriptSrc(); var base = src.substring(0, src.lastIndexOf('/') + 1); url = base + url.substring(2); // } else if (/^\.\.\//.test(url)) { // url = base + url; } return url; }; })(); module.exports = Class; function loadScript(src, callback) { var el = document.createElement('script'); el.addEventListener('load', function() { callback(); }); el.addEventListener('error', function(err) { callback(err || 'Error loading script: ' + src); }); el.src = src; el.id = 'preload-' + Date.now(); document.body.appendChild(el); }; },{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){ require('./util/event')(require('./core').prototype, function(obj, name, on) { obj._flag(name, on); }); },{"./core":60,"./util/event":75}],62:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var repeat = require('./util/repeat'); var create = require('./util/create'); Class.image = function(image) { var img = new Image(); image && img.image(image); return img; }; Image._super = Class; Image.prototype = create(Image._super.prototype); function Image() { Image._super.call(this); this.label('Image'); this._textures = []; this._image = null; }; /** * @deprecated Use image */ Image.prototype.setImage = function(a, b, c) { return this.image(a, b, c); }; Image.prototype.image = function(image) { this._image = Class.texture(image).one(); this.pin('width', this._image ? this._image.width : 0); this.pin('height', this._image ? this._image.height : 0); this._textures[0] = this._image.pipe(); this._textures.length = 1; return this; }; Image.prototype.tile = function(inner) { this._repeat(false, inner); return this; }; Image.prototype.stretch = function(inner) { this._repeat(true, inner); return this; }; Image.prototype._repeat = function(stretch, inner) { var self = this; this.untick(this._repeatTicker); this.tick(this._repeatTicker = function() { if (this._mo_stretch == this._pin._ts_transform) { return; } this._mo_stretch = this._pin._ts_transform; var width = this.pin('width'); var height = this.pin('height'); this._textures.length = repeat(this._image, width, height, stretch, inner, insert); }); function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) { var repeat = self._textures.length > i ? self._textures[i] : self._textures[i] = self._image.pipe(); repeat.src(sx, sy, sw, sh); repeat.dest(dx, dy, dw, dh); } }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){ module.exports = require('./core'); module.exports.Matrix = require('./matrix'); module.exports.Texture = require('./texture'); require('./atlas'); require('./tree'); require('./event'); require('./pin'); require('./loop'); require('./root'); },{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); Class.row = function(align) { return Class.create().row(align).label('Row'); }; Class.prototype.row = function(align) { this.sequence('row', align); return this; }; Class.column = function(align) { return Class.create().column(align).label('Row'); }; Class.prototype.column = function(align) { this.sequence('column', align); return this; }; Class.sequence = function(type, align) { return Class.create().sequence(type, align).label('Sequence'); }; Class.prototype.sequence = function(type, align) { this._padding = this._padding || 0; this._spacing = this._spacing || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_seq == this._ts_touch) { return; } this._mo_seq = this._ts_touch; var alignChildren = (this._mo_seqAlign != this._ts_children); this._mo_seqAlign = this._ts_children; var width = 0, height = 0; var child, next = this.first(true); var first = true; while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); if (type == 'column') { !first && (height += this._spacing); child.pin('offsetY') != height && child.pin('offsetY', height); width = Math.max(width, w); height = height + h; alignChildren && child.pin('alignX', align); } else if (type == 'row') { !first && (width += this._spacing); child.pin('offsetX') != width && child.pin('offsetX', width); width = width + w; height = Math.max(height, h); alignChildren && child.pin('alignY', align); } first = false; } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.box = function() { return Class.create().box().label('Box'); }; Class.prototype.box = function() { this._padding = this._padding || 0; this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { if (this._mo_box == this._ts_touch) { return; } this._mo_box = this._ts_touch; var width = 0, height = 0; var child, next = this.first(true); while (child = next) { next = child.next(true); child.matrix(true); var w = child.pin('boxWidth'); var h = child.pin('boxHeight'); width = Math.max(width, w); height = Math.max(height, h); } width += 2 * this._padding; height += 2 * this._padding; this.pin('width') != width && this.pin('width', width); this.pin('height') != height && this.pin('height', height); }); return this; }; Class.layer = function() { return Class.create().layer().label('Layer'); }; Class.prototype.layer = function() { this.untick(this._layoutTiker); this.tick(this._layoutTiker = function() { var parent = this.parent(); if (parent) { var width = parent.pin('width'); if (this.pin('width') != width) { this.pin('width', width); } var height = parent.pin('height'); if (this.pin('height') != height) { this.pin('height', height); } } }, true); return this; }; // TODO: move padding to pin Class.prototype.padding = function(pad) { this._padding = pad; return this; }; Class.prototype.spacing = function(space) { this._spacing = space; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){ /** * Default loader for web. */ if (typeof DEBUG === 'undefined') DEBUG = true; var Class = require('../core'); Class._supported = (function() { var elem = document.createElement('canvas'); return (elem.getContext && elem.getContext('2d')) ? true : false; })(); window.addEventListener('load', function() { DEBUG && console.log('On load.'); if (Class._supported) { Class.start(); } // TODO if not supported }, false); Class.config({ 'app-loader' : AppLoader, 'image-loader' : ImageLoader }); function AppLoader(app, configs) { configs = configs || {}; var canvas = configs.canvas, context = null, full = false; var width = 0, height = 0, ratio = 1; if (typeof canvas === 'string') { canvas = document.getElementById(canvas); } if (!canvas) { canvas = document.getElementById('cutjs') || document.getElementById('stage'); } if (!canvas) { full = true; DEBUG && console.log('Creating Canvas...'); canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = '0'; canvas.style.left = '0'; var body = document.body; body.insertBefore(canvas, body.firstChild); } context = canvas.getContext('2d'); var devicePixelRatio = window.devicePixelRatio || 1; var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; ratio = devicePixelRatio / backingStoreRatio; var requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000 / 60); }; DEBUG && console.log('Creating stage...'); var root = Class.root(requestAnimationFrame, render); function render() { context.setTransform(1, 0, 0, 1, 0, 0); context.clearRect(0, 0, width, height); root.render(context); } root.background = function(color) { canvas.style.backgroundColor = color; return this; }; app(root, canvas); resize(); window.addEventListener('resize', resize, false); window.addEventListener('orientationchange', resize, false); function resize() { if (full) { // screen.availWidth/Height? width = (window.innerWidth > 0 ? window.innerWidth : screen.width); height = (window.innerHeight > 0 ? window.innerHeight : screen.height); canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } else { width = canvas.clientWidth; height = canvas.clientHeight; } width *= ratio; height *= ratio; if (canvas.width === width && canvas.height === height) { return; } canvas.width = width; canvas.height = height; DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio); root.viewport(width, height, ratio); render(); } } function ImageLoader(src, success, error) { DEBUG && console.log('Loading image: ' + src); var image = new Image(); image.onload = function() { success(image); }; image.onerror = error; image.src = src; } },{"../core":60}],66:[function(require,module,exports){ var Class = require('./core'); require('./pin'); var stats = require('./util/stats'); Class.prototype._textures = null; Class.prototype._alpha = 1; Class.prototype.render = function(context) { if (!this._visible) { return; } stats.node++; var m = this.matrix(); context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f); // move this elsewhere! this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1); var alpha = this._pin._textureAlpha * this._alpha; if (context.globalAlpha != alpha) { context.globalAlpha = alpha; } if (this._textures !== null) { for (var i = 0, n = this._textures.length; i < n; i++) { this._textures[i].draw(context); } } if (context.globalAlpha != this._alpha) { context.globalAlpha = this._alpha; } var child, next = this._first; while (child = next) { next = child._next; child.render(context); } }; Class.prototype._tickBefore = null; Class.prototype._tickAfter = null; Class.prototype.MAX_ELAPSE = Infinity; Class.prototype._tick = function(elapsed, now, last) { if (!this._visible) { return; } if (elapsed > this.MAX_ELAPSE) { elapsed = this.MAX_ELAPSE; } var ticked = false; if (this._tickBefore !== null) { for (var i = 0, n = this._tickBefore.length; i < n; i++) { stats.tick++; ticked = this._tickBefore[i].call(this, elapsed, now, last) === true || ticked; } } var child, next = this._first; while (child = next) { next = child._next; if (child._flag('_tick')) { ticked = child._tick(elapsed, now, last) === true ? true : ticked; } } if (this._tickAfter !== null) { for (var i = 0, n = this._tickAfter.length; i < n; i++) { stats.tick++; ticked = this._tickAfter[i].call(this, elapsed, now, last) === true || ticked; } } return ticked; }; Class.prototype.tick = function(ticker, before) { if (typeof ticker !== 'function') { return; } if (before) { if (this._tickBefore === null) { this._tickBefore = []; } this._tickBefore.push(ticker); } else { if (this._tickAfter === null) { this._tickAfter = []; } this._tickAfter.push(ticker); } this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0 || this._tickBefore !== null && this._tickBefore.length > 0); }; Class.prototype.untick = function(ticker) { if (typeof ticker !== 'function') { return; } var i; if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) { this._tickBefore.splice(i, 1); } if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) { this._tickAfter.splice(i, 1); } }; Class.prototype.timeout = function(fn, time) { this.tick(function timer(t) { if ((time -= t) < 0) { this.untick(timer); fn.call(this); } else { return true; } }); }; },{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){ function Matrix(a, b, c, d, e, f) { this.reset(a, b, c, d, e, f); }; Matrix.prototype.toString = function() { return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', ' + this.e + ', ' + this.f + ']'; }; Matrix.prototype.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; Matrix.prototype.reset = function(a, b, c, d, e, f) { this._dirty = true; if (typeof a === 'object') { this.a = a.a, this.d = a.d; this.b = a.b, this.c = a.c; this.e = a.e, this.f = a.f; } else { this.a = a || 1, this.d = d || 1; this.b = b || 0, this.c = c || 0; this.e = e || 0, this.f = f || 0; } return this; }; Matrix.prototype.identity = function() { this._dirty = true; this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; return this; }; Matrix.prototype.rotate = function(angle) { if (!angle) { return this; } this._dirty = true; var u = angle ? Math.cos(angle) : 1; // android bug may give bad 0 values var v = angle ? Math.sin(angle) : 0; var a = u * this.a - v * this.b; var b = u * this.b + v * this.a; var c = u * this.c - v * this.d; var d = u * this.d + v * this.c; var e = u * this.e - v * this.f; var f = u * this.f + v * this.e; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.translate = function(x, y) { if (!x && !y) { return this; } this._dirty = true; this.e += x; this.f += y; return this; }; Matrix.prototype.scale = function(x, y) { if (!(x - 1) && !(y - 1)) { return this; } this._dirty = true; this.a *= x; this.b *= y; this.c *= x; this.d *= y; this.e *= x; this.f *= y; return this; }; Matrix.prototype.skew = function(x, y) { if (!x && !y) { return this; } this._dirty = true; var a = this.a + this.b * x; var b = this.b + this.a * y; var c = this.c + this.d * x; var d = this.d + this.c * y; var e = this.e + this.f * x; var f = this.f + this.e * y; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.concat = function(m) { this._dirty = true; var n = this; var a = n.a * m.a + n.b * m.c; var b = n.b * m.d + n.a * m.b; var c = n.c * m.a + n.d * m.c; var d = n.d * m.d + n.c * m.b; var e = n.e * m.a + m.e + n.f * m.c; var f = n.f * m.d + m.f + n.e * m.b; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; return this; }; Matrix.prototype.inverse = Matrix.prototype.reverse = function() { if (this._dirty) { this._dirty = false; this.inversed = this.inversed || new Matrix(); var z = this.a * this.d - this.b * this.c; this.inversed.a = this.d / z; this.inversed.b = -this.b / z; this.inversed.c = -this.c / z; this.inversed.d = this.a / z; this.inversed.e = (this.c * this.f - this.e * this.d) / z; this.inversed.f = (this.e * this.b - this.a * this.f) / z; } return this.inversed; }; Matrix.prototype.map = function(p, q) { q = q || {}; q.x = this.a * p.x + this.c * p.y + this.e; q.y = this.b * p.x + this.d * p.y + this.f; return q; }; Matrix.prototype.mapX = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.a * x + this.c * y + this.e; }; Matrix.prototype.mapY = function(x, y) { if (typeof x === 'object') y = x.y, x = x.x; return this.b * x + this.d * y + this.f; }; module.exports = Matrix; },{}],68:[function(require,module,exports){ var Class = require('./core'); var Matrix = require('./matrix'); var iid = 0; Class._init(function() { this._pin = new Pin(this); }); Class.prototype.matrix = function(relative) { if (relative === true) { return this._pin.relativeMatrix(); } return this._pin.absoluteMatrix(); }; Class.prototype.pin = function(a, b) { if (typeof a === 'object') { this._pin.set(a); return this; } else if (typeof a === 'string') { if (typeof b === 'undefined') { return this._pin.get(a); } else { this._pin.set(a, b); return this; } } else if (typeof a === 'undefined') { return this._pin; } }; function Pin(owner) { this._owner = owner; this._parent = null; // relative to parent this._relativeMatrix = new Matrix(); // relative to stage this._absoluteMatrix = new Matrix(); this.reset(); }; Pin.prototype.reset = function() { this._textureAlpha = 1; this._alpha = 1; this._width = 0; this._height = 0; this._scaleX = 1; this._scaleY = 1; this._skewX = 0; this._skewY = 0; this._rotation = 0; // scale/skew/rotate center this._pivoted = false; this._pivotX = null; this._pivotY = null; // self pin point this._handled = false; this._handleX = 0; this._handleY = 0; // parent pin point this._aligned = false; this._alignX = 0; this._alignY = 0; // as seen by parent px this._offsetX = 0; this._offsetY = 0; this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; // TODO: also set for owner this._ts_translate = ++iid; this._ts_transform = ++iid; this._ts_matrix = ++iid; }; Pin.prototype._update = function() { this._parent = this._owner._parent && this._owner._parent._pin; // if handled and transformed then be translated if (this._handled && this._mo_handle != this._ts_transform) { this._mo_handle = this._ts_transform; this._ts_translate = ++iid; } if (this._aligned && this._parent && this._mo_align != this._parent._ts_transform) { this._mo_align = this._parent._ts_transform; this._ts_translate = ++iid; } return this; }; Pin.prototype.toString = function() { return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')'; }; // TODO: ts fields require refactoring Pin.prototype.absoluteMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_matrix : 0); if (this._mo_abs == ts) { return this._absoluteMatrix; } this._mo_abs = ts; var abs = this._absoluteMatrix; abs.reset(this.relativeMatrix()); this._parent && abs.concat(this._parent._absoluteMatrix); this._ts_matrix = ++iid; return abs; }; Pin.prototype.relativeMatrix = function() { this._update(); var ts = Math.max(this._ts_transform, this._ts_translate, this._parent ? this._parent._ts_transform : 0); if (this._mo_rel == ts) { return this._relativeMatrix; } this._mo_rel = ts; var rel = this._relativeMatrix; rel.identity(); if (this._pivoted) { rel.translate(-this._pivotX * this._width, -this._pivotY * this._height); } rel.scale(this._scaleX, this._scaleY); rel.skew(this._skewX, this._skewY); rel.rotate(this._rotation); if (this._pivoted) { rel.translate(this._pivotX * this._width, this._pivotY * this._height); } // calculate effective box if (this._pivoted) { // origin this._boxX = 0; this._boxY = 0; this._boxWidth = this._width; this._boxHeight = this._height; } else { // aabb var p, q; if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) { p = 0, q = rel.a * this._width + rel.c * this._height; } else { p = rel.a * this._width, q = rel.c * this._height; } if (p > q) { this._boxX = q; this._boxWidth = p - q; } else { this._boxX = p; this._boxWidth = q - p; } if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) { p = 0, q = rel.b * this._width + rel.d * this._height; } else { p = rel.b * this._width, q = rel.d * this._height; } if (p > q) { this._boxY = q; this._boxHeight = p - q; } else { this._boxY = p; this._boxHeight = q - p; } } this._x = this._offsetX; this._y = this._offsetY; this._x -= this._boxX + this._handleX * this._boxWidth; this._y -= this._boxY + this._handleY * this._boxHeight; if (this._aligned && this._parent) { this._parent.relativeMatrix(); this._x += this._alignX * this._parent._width; this._y += this._alignY * this._parent._height; } rel.translate(this._x, this._y); return this._relativeMatrix; }; Pin.prototype.get = function(key) { if (typeof getters[key] === 'function') { return getters[key](this); } }; // TODO: Use defineProperty instead? What about multi-field pinning? Pin.prototype.set = function(a, b) { if (typeof a === 'string') { if (typeof setters[a] === 'function' && typeof b !== 'undefined') { setters[a](this, b); } } else if (typeof a === 'object') { for (b in a) { if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') { setters[b](this, a[b], a); } } } if (this._owner) { this._owner._ts_pin = ++iid; this._owner.touch(); } return this; }; var getters = { alpha : function(pin) { return pin._alpha; }, textureAlpha : function(pin) { return pin._textureAlpha; }, width : function(pin) { return pin._width; }, height : function(pin) { return pin._height; }, boxWidth : function(pin) { return pin._boxWidth; }, boxHeight : function(pin) { return pin._boxHeight; }, // scale : function(pin) { // }, scaleX : function(pin) { return pin._scaleX; }, scaleY : function(pin) { return pin._scaleY; }, // skew : function(pin) { // }, skewX : function(pin) { return pin._skewX; }, skewY : function(pin) { return pin._skewY; }, rotation : function(pin) { return pin._rotation; }, // pivot : function(pin) { // }, pivotX : function(pin) { return pin._pivotX; }, pivotY : function(pin) { return pin._pivotY; }, // offset : function(pin) { // }, offsetX : function(pin) { return pin._offsetX; }, offsetY : function(pin) { return pin._offsetY; }, // align : function(pin) { // }, alignX : function(pin) { return pin._alignX; }, alignY : function(pin) { return pin._alignY; }, // handle : function(pin) { // }, handleX : function(pin) { return pin._handleX; }, handleY : function(pin) { return pin._handleY; } }; var setters = { alpha : function(pin, value) { pin._alpha = value; }, textureAlpha : function(pin, value) { pin._textureAlpha = value; }, width : function(pin, value) { pin._width_ = value; pin._width = value; pin._ts_transform = ++iid; }, height : function(pin, value) { pin._height_ = value; pin._height = value; pin._ts_transform = ++iid; }, scale : function(pin, value) { pin._scaleX = value; pin._scaleY = value; pin._ts_transform = ++iid; }, scaleX : function(pin, value) { pin._scaleX = value; pin._ts_transform = ++iid; }, scaleY : function(pin, value) { pin._scaleY = value; pin._ts_transform = ++iid; }, skew : function(pin, value) { pin._skewX = value; pin._skewY = value; pin._ts_transform = ++iid; }, skewX : function(pin, value) { pin._skewX = value; pin._ts_transform = ++iid; }, skewY : function(pin, value) { pin._skewY = value; pin._ts_transform = ++iid; }, rotation : function(pin, value) { pin._rotation = value; pin._ts_transform = ++iid; }, pivot : function(pin, value) { pin._pivotX = value; pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotX : function(pin, value) { pin._pivotX = value; pin._pivoted = true; pin._ts_transform = ++iid; }, pivotY : function(pin, value) { pin._pivotY = value; pin._pivoted = true; pin._ts_transform = ++iid; }, offset : function(pin, value) { pin._offsetX = value; pin._offsetY = value; pin._ts_translate = ++iid; }, offsetX : function(pin, value) { pin._offsetX = value; pin._ts_translate = ++iid; }, offsetY : function(pin, value) { pin._offsetY = value; pin._ts_translate = ++iid; }, align : function(pin, value) { this.alignX(pin, value); this.alignY(pin, value); }, alignX : function(pin, value) { pin._alignX = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleX(pin, value); }, alignY : function(pin, value) { pin._alignY = value; pin._aligned = true; pin._ts_translate = ++iid; this.handleY(pin, value); }, handle : function(pin, value) { this.handleX(pin, value); this.handleY(pin, value); }, handleX : function(pin, value) { pin._handleX = value; pin._handled = true; pin._ts_translate = ++iid; }, handleY : function(pin, value) { pin._handleY = value; pin._handled = true; pin._ts_translate = ++iid; }, resizeMode : function(pin, value, all) { if (all) { if (value == 'in') { value = 'in-pad'; } else if (value == 'out') { value = 'out-crop'; } scaleTo(pin, all.resizeWidth, all.resizeHeight, value); } }, resizeWidth : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, value, null); } }, resizeHeight : function(pin, value, all) { if (!all || !all.resizeMode) { scaleTo(pin, null, value); } }, scaleMode : function(pin, value, all) { if (all) { scaleTo(pin, all.scaleWidth, all.scaleHeight, value); } }, scaleWidth : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, value, null); } }, scaleHeight : function(pin, value, all) { if (!all || !all.scaleMode) { scaleTo(pin, null, value); } }, matrix : function(pin, value) { this.scaleX(pin, value.a); this.skewX(pin, value.c / value.d); this.skewY(pin, value.b / value.a); this.scaleY(pin, value.d); this.offsetX(pin, value.e); this.offsetY(pin, value.f); this.rotation(pin, 0); } }; function scaleTo(pin, width, height, mode) { var w = typeof width === 'number'; var h = typeof height === 'number'; var m = typeof mode === 'string'; pin._ts_transform = ++iid; if (w) { pin._scaleX = width / pin._width_; pin._width = pin._width_; } if (h) { pin._scaleY = height / pin._height_; pin._height = pin._height_; } if (w && h && m) { if (mode == 'out' || mode == 'out-crop') { pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY); } else if (mode == 'in' || mode == 'in-pad') { pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY); } if (mode == 'out-crop' || mode == 'in-pad') { pin._width = width / pin._scaleX; pin._height = height / pin._scaleY; } } }; Class.prototype.scaleTo = function(a, b, c) { if (typeof a === 'object') c = b, b = a.y, a = a.x; scaleTo(this._pin, a, b, c); return this; }; // Used by Tween class Pin._add_shortcuts = function(Class) { Class.prototype.size = function(w, h) { this.pin('width', w); this.pin('height', h); return this; }; Class.prototype.width = function(w) { if (typeof w === 'undefined') { return this.pin('width'); } this.pin('width', w); return this; }; Class.prototype.height = function(h) { if (typeof h === 'undefined') { return this.pin('height'); } this.pin('height', h); return this; }; Class.prototype.offset = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; this.pin('offsetX', a); this.pin('offsetY', b); return this; }; Class.prototype.rotate = function(a) { this.pin('rotation', a); return this; }; Class.prototype.skew = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('skewX', a); this.pin('skewY', b); return this; }; Class.prototype.scale = function(a, b) { if (typeof a === 'object') b = a.y, a = a.x; else if (typeof b === 'undefined') b = a; this.pin('scaleX', a); this.pin('scaleY', b); return this; }; Class.prototype.alpha = function(a, ta) { this.pin('alpha', a); if (typeof ta !== 'undefined') { this.pin('textureAlpha', ta); } return this; }; }; Pin._add_shortcuts(Class); module.exports = Pin; },{"./core":60,"./matrix":67}],69:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var stats = require('./util/stats'); var create = require('./util/create'); var extend = require('./util/extend'); Root._super = Class; Root.prototype = create(Root._super.prototype); Class.root = function(request, render) { return new Root(request, render); }; function Root(request, render) { Root._super.call(this); this.label('Root'); var paused = true; var self = this; var lastTime = 0; var loop = function(now) { if (paused === true) { return; } stats.tick = stats.node = stats.draw = 0; var last = lastTime || now; var elapsed = now - last; lastTime = now; var ticked = self._tick(elapsed, now, last); if (self._mo_touch != self._ts_touch) { self._mo_touch = self._ts_touch; render(self); request(loop); } else if (ticked) { request(loop); } else { paused = true; } stats.fps = elapsed ? 1000 / elapsed : 0; }; this.start = function() { return this.resume(); }; this.resume = function() { if (paused) { this.publish('resume'); paused = false; request(loop); } return this; }; this.pause = function() { if (!paused) { this.publish('pause'); } paused = true; return this; }; this.touch_root = this.touch; this.touch = function() { this.resume(); return this.touch_root(); }; }; Root.prototype.background = function(color) { // to be implemented by loaders return this; }; Root.prototype.viewport = function(width, height, ratio) { if (typeof width === 'undefined') { return extend({}, this._viewport); } this._viewport = { width : width, height : height, ratio : ratio || 1 }; this.viewbox(); var data = extend({}, this._viewport); this.visit({ start : function(node) { if (!node._flag('viewport')) { return true; } node.publish('viewport', [ data ]); } }); return this; }; // TODO: static/fixed viewbox Root.prototype.viewbox = function(width, height, mode) { if (typeof width === 'number' && typeof height === 'number') { this._viewbox = { width : width, height : height, mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad' }; } var box = this._viewbox; var size = this._viewport; if (size && box) { this.pin({ width : box.width, height : box.height }); this.scaleTo(size.width, size.height, box.mode); } else if (size) { this.pin({ width : size.width, height : size.height }); } return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){ var Class = require('./core'); require('./pin'); require('./loop'); var create = require('./util/create'); var is = require('./util/is'); Class.string = function(frames) { return new Str().frames(frames); }; Str._super = Class; Str.prototype = create(Str._super.prototype); function Str() { Str._super.call(this); this.label('String'); this._textures = []; }; /** * @deprecated Use frames */ Str.prototype.setFont = function(a, b, c) { return this.frames(a, b, c); }; Str.prototype.frames = function(frames) { this._textures = []; if (typeof frames == 'string') { frames = Class.texture(frames); this._item = function(value) { return frames.one(value); }; } else if (typeof frames === 'object') { this._item = function(value) { return frames[value]; }; } else if (typeof frames === 'function') { this._item = frames; } return this; }; /** * @deprecated Use value */ Str.prototype.setValue = function(a, b, c) { return this.value(a, b, c); }; Str.prototype.value = function(value) { if (typeof value === 'undefined') { return this._value; } if (this._value === value) { return this; } this._value = value; if (value === null) { value = ''; } else if (typeof value !== 'string' && !is.array(value)) { value = value.toString(); } this._spacing = this._spacing || 0; var width = 0, height = 0; for (var i = 0; i < value.length; i++) { var image = this._textures[i] = this._item(value[i]); width += i > 0 ? this._spacing : 0; image.dest(width, 0); width = width + image.width; height = Math.max(height, image.height); } this.pin('width', width); this.pin('height', height); this._textures.length = value.length; return this; }; },{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){ var stats = require('./util/stats'); var math = require('./util/math'); function Texture(image, ratio) { if (typeof image === 'object') { this.src(image, ratio); } } Texture.prototype.pipe = function() { return new Texture(this); }; /** * Signatures: (image), (x, y, w, h), (w, h) */ Texture.prototype.src = function(x, y, w, h) { if (typeof x === 'object') { var image = x, ratio = y || 1; this._image = image; this._sx = this._dx = 0; this._sy = this._dy = 0; this._sw = this._dw = image.width / ratio; this._sh = this._dh = image.height / ratio; this.width = image.width / ratio; this.height = image.height / ratio; this.ratio = ratio; } else { if (typeof w === 'undefined') { w = x, h = y; } else { this._sx = x, this._sy = y; } this._sw = this._dw = w; this._sh = this._dh = h; this.width = w; this.height = h; } return this; }; /** * Signatures: (x, y, w, h), (x, y) */ Texture.prototype.dest = function(x, y, w, h) { this._dx = x, this._dy = y; this._dx = x, this._dy = y; if (typeof w !== 'undefined') { this._dw = w, this._dh = h; this.width = w, this.height = h; } return this; }; Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) { var image = this._image; if (image === null || typeof image !== 'object') { return; } var sx = this._sx, sy = this._sy; var sw = this._sw, sh = this._sh; var dx = this._dx, dy = this._dy; var dw = this._dw, dh = this._dh; if (typeof x3 !== 'undefined') { x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1); y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1); sx += x1, sy += y1, sw = x2, sh = y2; dx = x3, dy = y3, dw = x4, dh = y4; } else if (typeof x2 !== 'undefined') { dx = x1, dy = y1, dw = x2, dh = y2; } else if (typeof x1 !== 'undefined') { dw = x1, dh = y1; } var ratio = this.ratio || 1; sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio; try { if (typeof image.draw === 'function') { image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh); } else { stats.draw++; context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh); } } catch (ex) { if (!image._draw_failed) { console.log('Unable to draw: ', image); console.log(ex); image._draw_failed = true; } } }; module.exports = Texture; },{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){ var Class = require('./core'); var is = require('./util/is'); var iid = 0; // TODO: do not clear next/prev/parent on remove Class.prototype._label = ''; Class.prototype._visible = true; Class.prototype._parent = null; Class.prototype._next = null; Class.prototype._prev = null; Class.prototype._first = null; Class.prototype._last = null; Class.prototype._attrs = null; Class.prototype._flags = null; Class.prototype.toString = function() { return '[' + this._label + ']'; }; /** * @deprecated Use label() */ Class.prototype.id = function(id) { return this.label(id); }; Class.prototype.label = function(label) { if (typeof label === 'undefined') { return this._label; } this._label = label; return this; }; Class.prototype.attr = function(name, value) { if (typeof value === 'undefined') { return this._attrs !== null ? this._attrs[name] : undefined; } (this._attrs !== null ? this._attrs : this._attrs = {})[name] = value; return this; }; Class.prototype.visible = function(visible) { if (typeof visible === 'undefined') { return this._visible; } this._visible = visible; this._parent && (this._parent._ts_children = ++iid); this._ts_pin = ++iid; this.touch(); return this; }; Class.prototype.hide = function() { return this.visible(false); }; Class.prototype.show = function() { return this.visible(true); }; Class.prototype.parent = function() { return this._parent; }; Class.prototype.next = function(visible) { var next = this._next; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.prev = function(visible) { var prev = this._prev; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.first = function(visible) { var next = this._first; while (next && visible && !next._visible) { next = next._next; } return next; }; Class.prototype.last = function(visible) { var prev = this._last; while (prev && visible && !prev._visible) { prev = prev._prev; } return prev; }; Class.prototype.visit = function(visitor, data) { var reverse = visitor.reverse; var visible = visitor.visible; if (visitor.start && visitor.start(this, data)) { return; } var child, next = reverse ? this.last(visible) : this.first(visible); while (child = next) { next = reverse ? child.prev(visible) : child.next(visible); if (child.visit(visitor, data)) { return true; } } return visitor.end && visitor.end(this, data); }; Class.prototype.append = function(child, more) { if (is.array(child)) for (var i = 0; i < child.length; i++) append(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) append(this, arguments[i]); else if (typeof child !== 'undefined') append(this, child); return this; }; Class.prototype.prepend = function(child, more) { if (is.array(child)) for (var i = child.length - 1; i >= 0; i--) prepend(this, child[i]); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) prepend(this, arguments[i]); else if (typeof child !== 'undefined') prepend(this, child); return this; }; Class.prototype.appendTo = function(parent) { append(parent, this); return this; }; Class.prototype.prependTo = function(parent) { prepend(parent, this); return this; }; Class.prototype.insertNext = function(sibling, more) { if (is.array(sibling)) for (var i = 0; i < sibling.length; i++) insertAfter(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = 0; i < arguments.length; i++) insertAfter(arguments[i], this); else if (typeof sibling !== 'undefined') insertAfter(sibling, this); return this; }; Class.prototype.insertPrev = function(sibling, more) { if (is.array(sibling)) for (var i = sibling.length - 1; i >= 0; i--) insertBefore(sibling[i], this); else if (typeof more !== 'undefined') // deprecated for (var i = arguments.length - 1; i >= 0; i--) insertBefore(arguments[i], this); else if (typeof sibling !== 'undefined') insertBefore(sibling, this); return this; }; Class.prototype.insertAfter = function(prev) { insertAfter(this, prev); return this; }; Class.prototype.insertBefore = function(next) { insertBefore(this, next); return this; }; function append(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._last) { parent._last._next = child; child._prev = parent._last; } child._parent = parent; parent._last = child; if (!parent._first) { parent._first = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); } function prepend(parent, child) { _ensure(child); _ensure(parent); child.remove(); if (parent._first) { parent._first._prev = child; child._next = parent._first; } child._parent = parent; parent._first = child; if (!parent._last) { parent._last = child; } child._parent._flag(child, true); child._ts_parent = ++iid; parent._ts_children = ++iid; parent.touch(); }; function insertBefore(self, next) { _ensure(self); _ensure(next); self.remove(); var parent = next._parent; var prev = next._prev; next._prev = self; prev && (prev._next = self) || parent && (parent._first = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; function insertAfter(self, prev) { _ensure(self); _ensure(prev); self.remove(); var parent = prev._parent; var next = prev._next; prev._next = self; next && (next._prev = self) || parent && (parent._last = self); self._parent = parent; self._prev = prev; self._next = next; self._parent._flag(self, true); self._ts_parent = ++iid; self.touch(); }; Class.prototype.remove = function(child, more) { if (typeof child !== 'undefined') { if (is.array(child)) { for (var i = 0; i < child.length; i++) _ensure(child[i]).remove(); } else if (typeof more !== 'undefined') { for (var i = 0; i < arguments.length; i++) _ensure(arguments[i]).remove(); } else { _ensure(child).remove(); } return this; } if (this._prev) { this._prev._next = this._next; } if (this._next) { this._next._prev = this._prev; } if (this._parent) { if (this._parent._first === this) { this._parent._first = this._next; } if (this._parent._last === this) { this._parent._last = this._prev; } this._parent._flag(this, false); this._parent._ts_children = ++iid; this._parent.touch(); } this._prev = this._next = this._parent = null; this._ts_parent = ++iid; // this._parent.touch(); return this; }; Class.prototype.empty = function() { var child, next = this._first; while (child = next) { next = child._next; child._prev = child._next = child._parent = null; this._flag(child, false); } this._first = this._last = null; this._ts_children = ++iid; this.touch(); return this; }; Class.prototype.touch = function() { this._ts_touch = ++iid; this._parent && this._parent.touch(); return this; }; /** * Deep flags used for optimizing event distribution. */ Class.prototype._flag = function(obj, name) { if (typeof name === 'undefined') { return this._flags !== null && this._flags[obj] || 0; } if (typeof obj === 'string') { if (name) { this._flags = this._flags || {}; if (!this._flags[obj] && this._parent) { this._parent._flag(obj, true); } this._flags[obj] = (this._flags[obj] || 0) + 1; } else if (this._flags && this._flags[obj] > 0) { if (this._flags[obj] == 1 && this._parent) { this._parent._flag(obj, false); } this._flags[obj] = this._flags[obj] - 1; } } if (typeof obj === 'object') { if (obj._flags) { for ( var type in obj._flags) { if (obj._flags[type] > 0) { this._flag(type, name); } } } } return this; }; /** * @private */ Class.prototype.hitTest = function(hit) { if (this.attr('spy')) { return true; } return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0 && hit.y <= this._pin._height; }; function _ensure(obj) { if (obj && obj instanceof Class) { return obj; } throw 'Invalid node: ' + obj; }; module.exports = Class; },{"./core":60,"./util/is":77}],73:[function(require,module,exports){ module.exports = function() { var count = 0; function fork(fn, n) { count += n = (typeof n === 'number' && n >= 1 ? n : 1); return function() { fn && fn.apply(this, arguments); if (n > 0) { n--, count--, call(); } }; } var then = []; function call() { if (count === 0) { while (then.length) { setTimeout(then.shift(), 0); } } } fork.then = function(fn) { if (count === 0) { setTimeout(fn, 0); } else { then.push(fn); } }; return fork; }; },{}],74:[function(require,module,exports){ if (typeof Object.create == 'function') { module.exports = function(proto, props) { return Object.create.call(Object, proto, props); }; } else { module.exports = function(proto, props) { if (props) throw Error('Second argument is not supported!'); if (typeof proto !== 'object' || proto === null) throw Error('Invalid prototype!'); noop.prototype = proto; return new noop; }; function noop() { } } },{}],75:[function(require,module,exports){ module.exports = function(prototype, callback) { prototype._listeners = null; prototype.on = prototype.listen = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { this._listeners = {}; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i]; this._listeners[type] = this._listeners[type] || []; this._listeners[type].push(listener); if (typeof callback === 'function') { callback(this, type, true); } } } return this; }; prototype.off = function(types, listener) { if (!types || !types.length || typeof listener !== 'function') { return this; } if (this._listeners === null) { return this; } var isarray = typeof types !== 'string' && typeof types.join === 'function'; if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) { for (var i = 0; i < types.length; i++) { var type = types[i], all = this._listeners[type], index; if (all && (index = all.indexOf(listener)) >= 0) { all.splice(index, 1); if (!all.length) { delete this._listeners[type]; } if (typeof callback === 'function') { callback(this, type, false); } } } } return this; }; prototype.listeners = function(type) { return this._listeners && this._listeners[type]; }; prototype.publish = function(name, args) { var listeners = this.listeners(name); if (!listeners || !listeners.length) { return 0; } for (var l = 0; l < listeners.length; l++) { listeners[l].apply(this, args); } return listeners.length; }; prototype.trigger = function(name, args) { this.publish(name, args); return this; }; }; },{}],76:[function(require,module,exports){ module.exports = function(base) { for (var i = 1; i < arguments.length; i++) { var obj = arguments[i]; for ( var key in obj) { if (obj.hasOwnProperty(key)) { base[key] = obj[key]; } } } return base; }; },{}],77:[function(require,module,exports){ /** * ! is the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var NON_HOST_TYPES = { 'boolean' : 1, 'number' : 1, 'string' : 1, 'undefined' : 1 }; var hexRegex = /^[A-Fa-f0-9]+$/; var is = module.exports = {}; is.a = is.an = is.type = function(value, type) { return typeof value === type; }; is.defined = function(value) { return typeof value !== 'undefined'; }; is.empty = function(value) { var type = toStr.call(value); var key; if ('[object Array]' === type || '[object Arguments]' === type || '[object String]' === type) { return value.length === 0; } if ('[object Object]' === type) { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; is.equal = function(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if ('[object Object]' === type) { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if ('[object Array]' === type) { key = value.length; if (key !== other.length) { return false; } while (--key) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if ('[object Function]' === type) { return value.prototype === other.prototype; } if ('[object Date]' === type) { return value.getTime() === other.getTime(); } return false; }; is.instance = function(value, constructor) { return value instanceof constructor; }; is.nil = function(value) { return value === null; }; is.undef = function(value) { return typeof value === 'undefined'; }; is.array = function(value) { return '[object Array]' === toStr.call(value); }; is.emptyarray = function(value) { return is.array(value) && value.length === 0; }; is.arraylike = function(value) { return !!value && !is.boolean(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; is.boolean = function(value) { return '[object Boolean]' === toStr.call(value); }; is.element = function(value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; is.fn = function(value) { return '[object Function]' === toStr.call(value); }; is.number = function(value) { return '[object Number]' === toStr.call(value); }; is.nan = function(value) { return !is.number(value) || value !== value; }; is.object = function(value) { return '[object Object]' === toStr.call(value); }; is.hash = function(value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; is.regexp = function(value) { return '[object RegExp]' === toStr.call(value); }; is.string = function(value) { return '[object String]' === toStr.call(value); }; is.hex = function(value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; },{}],78:[function(require,module,exports){ var create = require('./create'); var native = Math; module.exports = create(Math); module.exports.random = function(min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } return min == max ? min : native.random() * (max - min) + min; }; module.exports.rotate = function(num, min, max) { if (typeof min === 'undefined') { max = 1, min = 0; } else if (typeof max === 'undefined') { max = min, min = 0; } if (max > min) { num = (num - min) % (max - min); return num + (num < 0 ? max : min); } else { num = (num - max) % (min - max); return num + (num <= 0 ? min : max); } }; module.exports.limit = function(num, min, max) { if (num < min) { return min; } else if (num > max) { return max; } else { return num; } }; module.exports.length = function(x, y) { return native.sqrt(x * x + y * y); }; },{"./create":74}],79:[function(require,module,exports){ module.exports = function(img, owidth, oheight, stretch, inner, insert) { var width = img.width; var height = img.height; var left = img.left; var right = img.right; var top = img.top; var bottom = img.bottom; left = typeof left === 'number' && left === left ? left : 0; right = typeof right === 'number' && right === right ? right : 0; top = typeof top === 'number' && top === top ? top : 0; bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0; width = width - left - right; height = height - top - bottom; if (!inner) { owidth = Math.max(owidth - left - right, 0); oheight = Math.max(oheight - top - bottom, 0); } var i = 0; if (top > 0 && left > 0) insert(i++, 0, 0, left, top, 0, 0, left, top); if (bottom > 0 && left > 0) insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom); if (top > 0 && right > 0) insert(i++, width + left, 0, right, top, owidth + left, 0, right, top); if (bottom > 0 && right > 0) insert(i++, width + left, height + top, right, bottom, owidth + left, oheight + top, right, bottom); if (stretch) { if (top > 0) insert(i++, left, 0, width, top, left, 0, owidth, top); if (bottom > 0) insert(i++, left, height + top, width, bottom, left, oheight + top, owidth, bottom); if (left > 0) insert(i++, 0, top, left, height, 0, top, left, oheight); if (right > 0) insert(i++, width + left, top, right, height, owidth + left, top, right, oheight); // center insert(i++, left, top, width, height, left, top, owidth, oheight); } else { // tile var l = left, r = owidth, w; while (r > 0) { w = Math.min(width, r), r -= width; var t = top, b = oheight, h; while (b > 0) { h = Math.min(height, b), b -= height; insert(i++, left, top, w, h, l, t, w, h); if (r <= 0) { if (left) insert(i++, 0, top, left, h, 0, t, left, h); if (right) insert(i++, width + left, top, right, h, l + w, t, right, h); } t += h; } if (top) insert(i++, left, 0, w, top, l, 0, w, top); if (bottom) insert(i++, left, height + top, w, bottom, l, t, w, bottom); l += w; } } return i; }; },{}],80:[function(require,module,exports){ module.exports = {}; },{}],81:[function(require,module,exports){ module.exports.startsWith = function(str, sub) { return typeof str === 'string' && typeof sub === 'string' && str.substring(0, sub.length) == sub; }; },{}],82:[function(require,module,exports){ module.exports = require('../lib/'); require('../lib/canvas'); require('../lib/image'); require('../lib/anim'); require('../lib/str'); require('../lib/layout'); require('../lib/addon/tween'); module.exports.Mouse = require('../lib/addon/mouse'); module.exports.Math = require('../lib/util/math'); module.exports._extend = require('../lib/util/extend'); module.exports._create = require('../lib/util/create'); require('../lib/loader/web'); },{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1) });
mit
kennynaoh/cdnjs
ajax/libs/godlike.css/3.5.1/godlike.css
4514
@charset "UTF-8"; @-ms-viewport { width: device-width; initial-scale: 1; } @-moz-viewport { width: device-width; initial-scale: 1; } @-webkit-viewport { width: device-width; initial-scale: 1; } *, :before, :after { box-sizing: border-box; } html { height: 100%; } body { position: relative; min-height: 100%; overflow: auto; overflow-x: hidden; margin: 0; padding: 0; word-wrap: break-word; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -ms-text-size-adjust: 100%; -moz-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; -webkit-tap-highlight-color: rgba(0,0,0,0); -ms-touch-action: manipulation; touch-action: manipulation; } article, aside, details, figcaption, figure, footer, header, main, menu, nav, section, summary { display: block; } video, audio, canvas { display: inline-block; } span, a { display: inline-block; } a, input, button, textarea, optgroup, select, fieldset, figure, legend, address { font: inherit; color: inherit; line-height: inherit; text-transform: inherit; text-shadow: inherit; border: none; background: none; box-shadow: none; border-radius: 0; margin: 0; padding: 0; } a, button, [type='button'], [type='submit'] { transition: color 0.25s, background 0.25s, opacity 0.25s; } a { cursor: pointer; text-decoration: none; -webkit-text-decoration-skip: none; } button { overflow: visible; -webkit-font-smoothing: inherit; letter-spacing: inherit; } p { margin: 0; -ms-hyphens: auto; -moz-hyphens: auto; -webkit-hyphens: auto; hyphens: auto; } b, strong { font-weight: 700; } img, svg, embed, object, iframe, video, audio, canvas { border: 0; vertical-align: middle; max-width: 100%; height: auto; } img { image-rendering: optimizeQuality; } svg { fill: currentColor; } svg:not(:root) { overflow: hidden; } progress { vertical-align: baseline; } h1, h2, h3, h4, h5, h6 { text-rendering: optimizeLegibility; font: inherit; color: inherit; margin: 0; } ul, ol, menu { margin: 0; padding: 0; -moz-padding: 0; -webkit-padding: 0; list-style: none; } input, select, button, button > *, a > * { display: inline-block; vertical-align: middle; } button, label, select, summary, [type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'] { user-select: none; cursor: pointer; } [type='search'], [type='range'], [type="radio"] ::-webkit-search-cancel-button, ::-webkit-search-decoration, ::-webkit-outer-spin-button, ::-webkit-inner-spin-button, ::-webkit-slider-thumb { -webkit-appearance: none; } ::-webkit-file-upload-button { -webkit-appearance: button; font: inherit; } ::-webkit-contacts-auto-fill-button, ::-webkit-credentials-auto-fill-button { visibility: hidden; pointer-events: none; position: absolute; right: 0; } :-webkit-autofill { box-shadow: inset 0 0 0 1000px #fff; } ::-webkit-details-marker { display: none; } [type="radio"] { -webkit-appearance: radio; } [type='number'] { -moz-appearance: textfield; } ::-ms-clear, ::-ms-reveal { display: none; } input, textarea { width: 100%; } textarea { overflow: auto; resize: none; } :active, :hover, :focus { outline: 0; outline-offset: 0; } :disabled { pointer-events: none; } ::-moz-focus-outer, ::-moz-focus-inner { border: 0; padding: 0; } ::placeholder, ::-moz-placeholder { opacity: 1; } table { border-spacing: 0; border-collapse: collapse; } td, th { padding: 0; text-align: center; } article p:not(:empty) { margin-top: 0.7em; margin-bottom: 0.7em; } article img, article embed, article object, article iframe, article video { display: block; margin: auto; } article span, article a { display: inline; } article ul, article ol, article menu { margin-top: 0.7em; margin-bottom: 0.7em; } article ul ul, article ol ul, article menu ul, article ul ol, article ol ol, article menu ol, article ul menu, article ol menu, article menu menu { margin: 0; padding-left: 1em; } article ul > li:before, article ol > li:before, article menu > li:before { padding-right: 0.5em; } article ul > li p, article ol > li p, article menu > li p { display: inline; } article ul > li:before, article menu > li:before { content: '•'; font-family: Tahoma; } article ul > li li:before, article menu > li li:before { content: '○'; } article ol { counter-reset: count; } article ol > li:before { content: counter(count) '.'; counter-increment: count; }
mit
commaai/openpilot
third_party/android_hardware_libhardware/include/hardware/vibrator.h
2301
/* * Copyright (C) 2013 The Android Open Source Project * * 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. */ #ifndef _HARDWARE_VIBRATOR_H #define _HARDWARE_VIBRATOR_H #include <hardware/hardware.h> __BEGIN_DECLS #define VIBRATOR_API_VERSION HARDWARE_MODULE_API_VERSION(1,0) /** * The id of this module */ #define VIBRATOR_HARDWARE_MODULE_ID "vibrator" /** * The id of the main vibrator device */ #define VIBRATOR_DEVICE_ID_MAIN "main_vibrator" struct vibrator_device; typedef struct vibrator_device { /** * Common methods of the vibrator device. This *must* be the first member of * vibrator_device as users of this structure will cast a hw_device_t to * vibrator_device pointer in contexts where it's known the hw_device_t references a * vibrator_device. */ struct hw_device_t common; /** Turn on vibrator * * What happens when this function is called while the the timeout of a * previous call has not expired is implementation dependent. * * @param timeout_ms number of milliseconds to vibrate * * @return 0 in case of success, negative errno code else */ int (*vibrator_on)(struct vibrator_device* vibradev, unsigned int timeout_ms); /** Turn off vibrator * * It is not guaranteed that the vibrator will be immediately stopped: the * behaviour is implementation dependent. * * @return 0 in case of success, negative errno code else */ int (*vibrator_off)(struct vibrator_device* vibradev); } vibrator_device_t; static inline int vibrator_open(const struct hw_module_t* module, vibrator_device_t** device) { return module->methods->open(module, VIBRATOR_DEVICE_ID_MAIN, (struct hw_device_t**)device); } __END_DECLS #endif // _HARDWARE_VIBRATOR_H
mit
hdo/EmulationStation
data/converted/help_dpad_right_svg.cpp
17883
//this file was auto-generated from "dpad_right.svg" by res2h #include "../Resources.h" const size_t help_dpad_right_svg_size = 3216; const unsigned char help_dpad_right_svg_data[3216] = { 0x3c,0x3f,0x78,0x6d,0x6c,0x20,0x76,0x65,0x72,0x73, 0x69,0x6f,0x6e,0x3d,0x22,0x31,0x2e,0x30,0x22,0x20, 0x65,0x6e,0x63,0x6f,0x64,0x69,0x6e,0x67,0x3d,0x22, 0x75,0x74,0x66,0x2d,0x38,0x22,0x3f,0x3e,0x0d,0x0a, 0x3c,0x21,0x2d,0x2d,0x20,0x47,0x65,0x6e,0x65,0x72, 0x61,0x74,0x6f,0x72,0x3a,0x20,0x41,0x64,0x6f,0x62, 0x65,0x20,0x49,0x6c,0x6c,0x75,0x73,0x74,0x72,0x61, 0x74,0x6f,0x72,0x20,0x31,0x36,0x2e,0x30,0x2e,0x33, 0x2c,0x20,0x53,0x56,0x47,0x20,0x45,0x78,0x70,0x6f, 0x72,0x74,0x20,0x50,0x6c,0x75,0x67,0x2d,0x49,0x6e, 0x20,0x2e,0x20,0x53,0x56,0x47,0x20,0x56,0x65,0x72, 0x73,0x69,0x6f,0x6e,0x3a,0x20,0x36,0x2e,0x30,0x30, 0x20,0x42,0x75,0x69,0x6c,0x64,0x20,0x30,0x29,0x20, 0x20,0x2d,0x2d,0x3e,0x0d,0x0a,0x3c,0x21,0x44,0x4f, 0x43,0x54,0x59,0x50,0x45,0x20,0x73,0x76,0x67,0x20, 0x50,0x55,0x42,0x4c,0x49,0x43,0x20,0x22,0x2d,0x2f, 0x2f,0x57,0x33,0x43,0x2f,0x2f,0x44,0x54,0x44,0x20, 0x53,0x56,0x47,0x20,0x31,0x2e,0x31,0x2f,0x2f,0x45, 0x4e,0x22,0x20,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f, 0x2f,0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72, 0x67,0x2f,0x47,0x72,0x61,0x70,0x68,0x69,0x63,0x73, 0x2f,0x53,0x56,0x47,0x2f,0x31,0x2e,0x31,0x2f,0x44, 0x54,0x44,0x2f,0x73,0x76,0x67,0x31,0x31,0x2e,0x64, 0x74,0x64,0x22,0x3e,0x0d,0x0a,0x3c,0x73,0x76,0x67, 0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x3d,0x22, 0x31,0x2e,0x31,0x22,0x20,0x69,0x64,0x3d,0x22,0x5f, 0x78,0x33,0x30,0x5f,0x22,0x20,0x78,0x6d,0x6c,0x6e, 0x73,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f, 0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72,0x67, 0x2f,0x32,0x30,0x30,0x30,0x2f,0x73,0x76,0x67,0x22, 0x20,0x78,0x6d,0x6c,0x6e,0x73,0x3a,0x78,0x6c,0x69, 0x6e,0x6b,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f, 0x2f,0x77,0x77,0x77,0x2e,0x77,0x33,0x2e,0x6f,0x72, 0x67,0x2f,0x31,0x39,0x39,0x39,0x2f,0x78,0x6c,0x69, 0x6e,0x6b,0x22,0x20,0x78,0x3d,0x22,0x30,0x70,0x78, 0x22,0x20,0x79,0x3d,0x22,0x30,0x70,0x78,0x22,0x0d, 0x0a,0x09,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22, 0x33,0x37,0x2e,0x30,0x36,0x31,0x70,0x78,0x22,0x20, 0x68,0x65,0x69,0x67,0x68,0x74,0x3d,0x22,0x33,0x37, 0x2e,0x30,0x36,0x31,0x70,0x78,0x22,0x20,0x76,0x69, 0x65,0x77,0x42,0x6f,0x78,0x3d,0x22,0x30,0x20,0x30, 0x20,0x33,0x37,0x2e,0x30,0x36,0x31,0x20,0x33,0x37, 0x2e,0x30,0x36,0x31,0x22,0x20,0x65,0x6e,0x61,0x62, 0x6c,0x65,0x2d,0x62,0x61,0x63,0x6b,0x67,0x72,0x6f, 0x75,0x6e,0x64,0x3d,0x22,0x6e,0x65,0x77,0x20,0x30, 0x20,0x30,0x20,0x33,0x37,0x2e,0x30,0x36,0x31,0x20, 0x33,0x37,0x2e,0x30,0x36,0x31,0x22,0x20,0x78,0x6d, 0x6c,0x3a,0x73,0x70,0x61,0x63,0x65,0x3d,0x22,0x70, 0x72,0x65,0x73,0x65,0x72,0x76,0x65,0x22,0x3e,0x0d, 0x0a,0x3c,0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e, 0x0d,0x0a,0x09,0x09,0x3c,0x67,0x3e,0x0d,0x0a,0x09, 0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20,0x66,0x69, 0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46,0x46,0x46, 0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x32,0x32,0x2e, 0x30,0x38,0x36,0x2c,0x33,0x37,0x2e,0x30,0x36,0x68, 0x2d,0x37,0x2e,0x31,0x31,0x31,0x63,0x2d,0x32,0x2e, 0x32,0x38,0x39,0x2c,0x30,0x2d,0x33,0x2e,0x31,0x31, 0x39,0x2d,0x31,0x2e,0x38,0x36,0x36,0x2d,0x33,0x2e, 0x31,0x31,0x39,0x2d,0x33,0x2e,0x31,0x32,0x31,0x76, 0x2d,0x38,0x2e,0x37,0x33,0x32,0x48,0x33,0x2e,0x31, 0x32,0x31,0x43,0x30,0x2e,0x38,0x33,0x31,0x2c,0x32, 0x35,0x2e,0x32,0x30,0x36,0x2c,0x30,0x2c,0x32,0x33, 0x2e,0x33,0x34,0x2c,0x30,0x2c,0x32,0x32,0x2e,0x30, 0x38,0x35,0x0d,0x0a,0x09,0x09,0x09,0x09,0x76,0x2d, 0x37,0x2e,0x31,0x31,0x63,0x30,0x2d,0x32,0x2e,0x32, 0x38,0x39,0x2c,0x31,0x2e,0x38,0x36,0x37,0x2d,0x33, 0x2e,0x31,0x32,0x2c,0x33,0x2e,0x31,0x32,0x31,0x2d, 0x33,0x2e,0x31,0x32,0x68,0x38,0x2e,0x37,0x33,0x33, 0x56,0x33,0x2e,0x31,0x32,0x31,0x43,0x31,0x31,0x2e, 0x38,0x35,0x35,0x2c,0x30,0x2e,0x38,0x33,0x31,0x2c, 0x31,0x33,0x2e,0x37,0x32,0x2c,0x30,0x2c,0x31,0x34, 0x2e,0x39,0x37,0x34,0x2c,0x30,0x68,0x37,0x2e,0x31, 0x31,0x31,0x63,0x32,0x2e,0x32,0x39,0x2c,0x30,0x2c, 0x33,0x2e,0x31,0x32,0x31,0x2c,0x31,0x2e,0x38,0x36, 0x37,0x2c,0x33,0x2e,0x31,0x32,0x31,0x2c,0x33,0x2e, 0x31,0x32,0x31,0x76,0x38,0x2e,0x37,0x33,0x32,0x0d, 0x0a,0x09,0x09,0x09,0x09,0x68,0x38,0x2e,0x37,0x33, 0x31,0x63,0x32,0x2e,0x32,0x39,0x2c,0x30,0x2c,0x33, 0x2e,0x31,0x32,0x31,0x2c,0x31,0x2e,0x38,0x36,0x35, 0x2c,0x33,0x2e,0x31,0x32,0x31,0x2c,0x33,0x2e,0x31, 0x32,0x76,0x37,0x2e,0x31,0x31,0x63,0x30,0x2c,0x32, 0x2e,0x32,0x39,0x2d,0x31,0x2e,0x38,0x36,0x36,0x2c, 0x33,0x2e,0x31,0x32,0x31,0x2d,0x33,0x2e,0x31,0x32, 0x31,0x2c,0x33,0x2e,0x31,0x32,0x31,0x68,0x2d,0x38, 0x2e,0x37,0x33,0x31,0x76,0x38,0x2e,0x37,0x33,0x32, 0x0d,0x0a,0x09,0x09,0x09,0x09,0x43,0x32,0x35,0x2e, 0x32,0x30,0x37,0x2c,0x33,0x36,0x2e,0x32,0x32,0x39, 0x2c,0x32,0x33,0x2e,0x33,0x34,0x31,0x2c,0x33,0x37, 0x2e,0x30,0x36,0x2c,0x32,0x32,0x2e,0x30,0x38,0x36, 0x2c,0x33,0x37,0x2e,0x30,0x36,0x7a,0x20,0x4d,0x33, 0x2e,0x31,0x32,0x31,0x2c,0x31,0x33,0x2e,0x33,0x35, 0x34,0x43,0x32,0x2e,0x37,0x34,0x35,0x2c,0x31,0x33, 0x2e,0x33,0x35,0x39,0x2c,0x31,0x2e,0x35,0x2c,0x31, 0x33,0x2e,0x34,0x39,0x33,0x2c,0x31,0x2e,0x35,0x2c, 0x31,0x34,0x2e,0x39,0x37,0x34,0x76,0x37,0x2e,0x31, 0x31,0x0d,0x0a,0x09,0x09,0x09,0x09,0x63,0x30,0x2e, 0x30,0x30,0x36,0x2c,0x30,0x2e,0x33,0x37,0x36,0x2c, 0x30,0x2e,0x31,0x33,0x39,0x2c,0x31,0x2e,0x36,0x32, 0x31,0x2c,0x31,0x2e,0x36,0x32,0x31,0x2c,0x31,0x2e, 0x36,0x32,0x31,0x68,0x31,0x30,0x2e,0x32,0x33,0x33, 0x76,0x31,0x30,0x2e,0x32,0x33,0x32,0x63,0x30,0x2e, 0x30,0x30,0x35,0x2c,0x30,0x2e,0x33,0x37,0x36,0x2c, 0x30,0x2e,0x31,0x34,0x2c,0x31,0x2e,0x36,0x32,0x31, 0x2c,0x31,0x2e,0x36,0x31,0x39,0x2c,0x31,0x2e,0x36, 0x32,0x31,0x68,0x37,0x2e,0x31,0x30,0x38,0x0d,0x0a, 0x09,0x09,0x09,0x09,0x63,0x30,0x2e,0x33,0x38,0x34, 0x2d,0x30,0x2e,0x30,0x30,0x37,0x2c,0x31,0x2e,0x36, 0x32,0x34,0x2d,0x30,0x2e,0x31,0x34,0x33,0x2c,0x31, 0x2e,0x36,0x32,0x34,0x2d,0x31,0x2e,0x36,0x32,0x31, 0x56,0x32,0x33,0x2e,0x37,0x30,0x36,0x68,0x31,0x30, 0x2e,0x32,0x33,0x31,0x63,0x30,0x2e,0x33,0x37,0x36, 0x2d,0x30,0x2e,0x30,0x30,0x36,0x2c,0x31,0x2e,0x36, 0x32,0x31,0x2d,0x30,0x2e,0x31,0x34,0x2c,0x31,0x2e, 0x36,0x32,0x31,0x2d,0x31,0x2e,0x36,0x32,0x31,0x76, 0x2d,0x37,0x2e,0x31,0x31,0x0d,0x0a,0x09,0x09,0x09, 0x09,0x63,0x2d,0x30,0x2e,0x30,0x30,0x36,0x2d,0x30, 0x2e,0x33,0x37,0x36,0x2d,0x30,0x2e,0x31,0x34,0x2d, 0x31,0x2e,0x36,0x32,0x2d,0x31,0x2e,0x36,0x32,0x31, 0x2d,0x31,0x2e,0x36,0x32,0x68,0x2d,0x31,0x30,0x2e, 0x32,0x33,0x56,0x33,0x2e,0x31,0x32,0x31,0x43,0x32, 0x33,0x2e,0x37,0x30,0x31,0x2c,0x32,0x2e,0x37,0x34, 0x35,0x2c,0x32,0x33,0x2e,0x35,0x36,0x37,0x2c,0x31, 0x2e,0x35,0x2c,0x32,0x32,0x2e,0x30,0x38,0x36,0x2c, 0x31,0x2e,0x35,0x68,0x2d,0x37,0x2e,0x31,0x31,0x31, 0x0d,0x0a,0x09,0x09,0x09,0x09,0x63,0x2d,0x30,0x2e, 0x33,0x37,0x36,0x2c,0x30,0x2e,0x30,0x30,0x36,0x2d, 0x31,0x2e,0x36,0x31,0x39,0x2c,0x30,0x2e,0x31,0x34, 0x2d,0x31,0x2e,0x36,0x31,0x39,0x2c,0x31,0x2e,0x36, 0x32,0x31,0x76,0x31,0x30,0x2e,0x32,0x33,0x32,0x4c, 0x33,0x2e,0x31,0x32,0x31,0x2c,0x31,0x33,0x2e,0x33, 0x35,0x34,0x4c,0x33,0x2e,0x31,0x32,0x31,0x2c,0x31, 0x33,0x2e,0x33,0x35,0x34,0x7a,0x22,0x2f,0x3e,0x0d, 0x0a,0x09,0x09,0x3c,0x2f,0x67,0x3e,0x0d,0x0a,0x09, 0x3c,0x2f,0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e, 0x0d,0x0a,0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20, 0x66,0x69,0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46, 0x46,0x46,0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x31, 0x38,0x2e,0x35,0x33,0x31,0x2c,0x32,0x32,0x2e,0x31, 0x38,0x31,0x63,0x2d,0x32,0x2e,0x30,0x31,0x33,0x2c, 0x30,0x2d,0x33,0x2e,0x36,0x34,0x39,0x2d,0x31,0x2e, 0x36,0x33,0x39,0x2d,0x33,0x2e,0x36,0x34,0x39,0x2d, 0x33,0x2e,0x36,0x35,0x31,0x73,0x31,0x2e,0x36,0x33, 0x38,0x2d,0x33,0x2e,0x36,0x35,0x2c,0x33,0x2e,0x36, 0x34,0x39,0x2d,0x33,0x2e,0x36,0x35,0x63,0x32,0x2e, 0x30,0x31,0x33,0x2c,0x30,0x2c,0x33,0x2e,0x36,0x35, 0x2c,0x31,0x2e,0x36,0x33,0x39,0x2c,0x33,0x2e,0x36, 0x35,0x2c,0x33,0x2e,0x36,0x35,0x0d,0x0a,0x09,0x09, 0x09,0x43,0x32,0x32,0x2e,0x31,0x38,0x32,0x2c,0x32, 0x30,0x2e,0x35,0x34,0x33,0x2c,0x32,0x30,0x2e,0x35, 0x34,0x34,0x2c,0x32,0x32,0x2e,0x31,0x38,0x31,0x2c, 0x31,0x38,0x2e,0x35,0x33,0x31,0x2c,0x32,0x32,0x2e, 0x31,0x38,0x31,0x7a,0x20,0x4d,0x31,0x38,0x2e,0x35, 0x33,0x31,0x2c,0x31,0x36,0x2e,0x33,0x37,0x39,0x63, 0x2d,0x31,0x2e,0x31,0x38,0x36,0x2c,0x30,0x2d,0x32, 0x2e,0x31,0x34,0x39,0x2c,0x30,0x2e,0x39,0x36,0x35, 0x2d,0x32,0x2e,0x31,0x34,0x39,0x2c,0x32,0x2e,0x31, 0x35,0x73,0x30,0x2e,0x39,0x36,0x35,0x2c,0x32,0x2e, 0x31,0x35,0x31,0x2c,0x32,0x2e,0x31,0x34,0x39,0x2c, 0x32,0x2e,0x31,0x35,0x31,0x0d,0x0a,0x09,0x09,0x09, 0x63,0x31,0x2e,0x31,0x38,0x36,0x2c,0x30,0x2c,0x32, 0x2e,0x31,0x35,0x2d,0x30,0x2e,0x39,0x36,0x36,0x2c, 0x32,0x2e,0x31,0x35,0x2d,0x32,0x2e,0x31,0x35,0x31, 0x43,0x32,0x30,0x2e,0x36,0x38,0x32,0x2c,0x31,0x37, 0x2e,0x33,0x34,0x34,0x2c,0x31,0x39,0x2e,0x37,0x31, 0x37,0x2c,0x31,0x36,0x2e,0x33,0x37,0x39,0x2c,0x31, 0x38,0x2e,0x35,0x33,0x31,0x2c,0x31,0x36,0x2e,0x33, 0x37,0x39,0x7a,0x22,0x2f,0x3e,0x0d,0x0a,0x09,0x3c, 0x2f,0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e,0x0d, 0x0a,0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20,0x66, 0x69,0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46,0x46, 0x46,0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x32,0x31, 0x2e,0x35,0x33,0x36,0x2c,0x38,0x2e,0x36,0x31,0x36, 0x68,0x2d,0x36,0x2e,0x30,0x31,0x32,0x63,0x2d,0x30, 0x2e,0x32,0x37,0x33,0x2c,0x30,0x2d,0x30,0x2e,0x35, 0x32,0x35,0x2d,0x30,0x2e,0x31,0x35,0x2d,0x30,0x2e, 0x36,0x35,0x37,0x2d,0x30,0x2e,0x33,0x39,0x63,0x2d, 0x30,0x2e,0x31,0x33,0x32,0x2d,0x30,0x2e,0x32,0x34, 0x31,0x2d,0x30,0x2e,0x31,0x32,0x31,0x2d,0x30,0x2e, 0x35,0x33,0x34,0x2c,0x30,0x2e,0x30,0x32,0x36,0x2d, 0x30,0x2e,0x37,0x36,0x36,0x6c,0x33,0x2e,0x30,0x30, 0x35,0x2d,0x34,0x2e,0x36,0x38,0x34,0x0d,0x0a,0x09, 0x09,0x09,0x63,0x30,0x2e,0x32,0x37,0x36,0x2d,0x30, 0x2e,0x34,0x33,0x31,0x2c,0x30,0x2e,0x39,0x38,0x36, 0x2d,0x30,0x2e,0x34,0x33,0x2c,0x31,0x2e,0x32,0x36, 0x34,0x2c,0x30,0x6c,0x33,0x2e,0x30,0x30,0x35,0x2c, 0x34,0x2e,0x36,0x38,0x34,0x63,0x30,0x2e,0x31,0x34, 0x37,0x2c,0x30,0x2e,0x32,0x33,0x31,0x2c,0x30,0x2e, 0x31,0x35,0x39,0x2c,0x30,0x2e,0x35,0x32,0x34,0x2c, 0x30,0x2e,0x30,0x32,0x36,0x2c,0x30,0x2e,0x37,0x36, 0x36,0x43,0x32,0x32,0x2e,0x30,0x36,0x33,0x2c,0x38, 0x2e,0x34,0x36,0x36,0x2c,0x32,0x31,0x2e,0x38,0x31, 0x31,0x2c,0x38,0x2e,0x36,0x31,0x36,0x2c,0x32,0x31, 0x2e,0x35,0x33,0x36,0x2c,0x38,0x2e,0x36,0x31,0x36, 0x7a,0x0d,0x0a,0x09,0x09,0x09,0x20,0x4d,0x31,0x36, 0x2e,0x38,0x39,0x37,0x2c,0x37,0x2e,0x31,0x31,0x36, 0x68,0x33,0x2e,0x32,0x36,0x38,0x4c,0x31,0x38,0x2e, 0x35,0x33,0x2c,0x34,0x2e,0x35,0x37,0x31,0x4c,0x31, 0x36,0x2e,0x38,0x39,0x37,0x2c,0x37,0x2e,0x31,0x31, 0x36,0x7a,0x22,0x2f,0x3e,0x0d,0x0a,0x09,0x3c,0x2f, 0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e,0x0d,0x0a, 0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20,0x66,0x69, 0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46,0x46,0x46, 0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x37,0x2e,0x38, 0x30,0x39,0x2c,0x32,0x32,0x2e,0x32,0x38,0x34,0x63, 0x2d,0x30,0x2e,0x31,0x34,0x31,0x2c,0x30,0x2d,0x30, 0x2e,0x32,0x38,0x32,0x2d,0x30,0x2e,0x30,0x34,0x2d, 0x30,0x2e,0x34,0x30,0x35,0x2d,0x30,0x2e,0x31,0x31, 0x39,0x4c,0x32,0x2e,0x37,0x32,0x2c,0x31,0x39,0x2e, 0x31,0x36,0x32,0x63,0x2d,0x30,0x2e,0x32,0x31,0x35, 0x2d,0x30,0x2e,0x31,0x33,0x38,0x2d,0x30,0x2e,0x33, 0x34,0x35,0x2d,0x30,0x2e,0x33,0x37,0x36,0x2d,0x30, 0x2e,0x33,0x34,0x35,0x2d,0x30,0x2e,0x36,0x33,0x31, 0x0d,0x0a,0x09,0x09,0x09,0x73,0x30,0x2e,0x31,0x33, 0x2d,0x30,0x2e,0x34,0x39,0x33,0x2c,0x30,0x2e,0x33, 0x34,0x35,0x2d,0x30,0x2e,0x36,0x33,0x31,0x6c,0x34, 0x2e,0x36,0x38,0x34,0x2d,0x33,0x2e,0x30,0x30,0x36, 0x63,0x30,0x2e,0x32,0x33,0x2d,0x30,0x2e,0x31,0x34, 0x38,0x2c,0x30,0x2e,0x35,0x32,0x34,0x2d,0x30,0x2e, 0x31,0x35,0x38,0x2c,0x30,0x2e,0x37,0x36,0x36,0x2d, 0x30,0x2e,0x30,0x32,0x37,0x63,0x30,0x2e,0x32,0x34, 0x2c,0x30,0x2e,0x31,0x33,0x31,0x2c,0x30,0x2e,0x33, 0x39,0x2c,0x30,0x2e,0x33,0x38,0x34,0x2c,0x30,0x2e, 0x33,0x39,0x2c,0x30,0x2e,0x36,0x35,0x38,0x76,0x36, 0x2e,0x30,0x31,0x0d,0x0a,0x09,0x09,0x09,0x63,0x30, 0x2c,0x30,0x2e,0x32,0x37,0x34,0x2d,0x30,0x2e,0x31, 0x34,0x38,0x2c,0x30,0x2e,0x35,0x32,0x36,0x2d,0x30, 0x2e,0x33,0x39,0x2c,0x30,0x2e,0x36,0x35,0x38,0x43, 0x38,0x2e,0x30,0x35,0x36,0x2c,0x32,0x32,0x2e,0x32, 0x35,0x34,0x2c,0x37,0x2e,0x39,0x33,0x32,0x2c,0x32, 0x32,0x2e,0x32,0x38,0x34,0x2c,0x37,0x2e,0x38,0x30, 0x39,0x2c,0x32,0x32,0x2e,0x32,0x38,0x34,0x7a,0x20, 0x4d,0x34,0x2e,0x35,0x31,0x34,0x2c,0x31,0x38,0x2e, 0x35,0x33,0x6c,0x32,0x2e,0x35,0x34,0x35,0x2c,0x31, 0x2e,0x36,0x33,0x32,0x76,0x2d,0x33,0x2e,0x32,0x36, 0x35,0x4c,0x34,0x2e,0x35,0x31,0x34,0x2c,0x31,0x38, 0x2e,0x35,0x33,0x7a,0x22,0x2f,0x3e,0x0d,0x0a,0x09, 0x3c,0x2f,0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e, 0x0d,0x0a,0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20, 0x66,0x69,0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46, 0x46,0x46,0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x33, 0x33,0x2e,0x38,0x37,0x39,0x2c,0x31,0x38,0x2e,0x35, 0x32,0x39,0x6c,0x2d,0x34,0x2e,0x36,0x38,0x35,0x2d, 0x33,0x2e,0x30,0x30,0x35,0x76,0x36,0x2e,0x30,0x31, 0x4c,0x33,0x33,0x2e,0x38,0x37,0x39,0x2c,0x31,0x38, 0x2e,0x35,0x32,0x39,0x7a,0x22,0x2f,0x3e,0x0d,0x0a, 0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20,0x66,0x69, 0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46,0x46,0x46, 0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x32,0x39,0x2e, 0x31,0x39,0x35,0x2c,0x32,0x32,0x2e,0x32,0x38,0x34, 0x63,0x2d,0x30,0x2e,0x31,0x32,0x34,0x2c,0x30,0x2d, 0x30,0x2e,0x32,0x34,0x36,0x2d,0x30,0x2e,0x30,0x33, 0x2d,0x30,0x2e,0x33,0x35,0x38,0x2d,0x30,0x2e,0x30, 0x39,0x32,0x63,0x2d,0x30,0x2e,0x32,0x34,0x31,0x2d, 0x30,0x2e,0x31,0x33,0x32,0x2d,0x30,0x2e,0x33,0x39, 0x32,0x2d,0x30,0x2e,0x33,0x38,0x34,0x2d,0x30,0x2e, 0x33,0x39,0x32,0x2d,0x30,0x2e,0x36,0x35,0x38,0x76, 0x2d,0x36,0x2e,0x30,0x31,0x0d,0x0a,0x09,0x09,0x09, 0x63,0x30,0x2d,0x30,0x2e,0x32,0x37,0x34,0x2c,0x30, 0x2e,0x31,0x34,0x39,0x2d,0x30,0x2e,0x35,0x32,0x36, 0x2c,0x30,0x2e,0x33,0x39,0x32,0x2d,0x30,0x2e,0x36, 0x35,0x38,0x63,0x30,0x2e,0x32,0x33,0x39,0x2d,0x30, 0x2e,0x31,0x33,0x31,0x2c,0x30,0x2e,0x35,0x33,0x33, 0x2d,0x30,0x2e,0x31,0x32,0x33,0x2c,0x30,0x2e,0x37, 0x36,0x35,0x2c,0x30,0x2e,0x30,0x32,0x37,0x6c,0x34, 0x2e,0x36,0x38,0x35,0x2c,0x33,0x2e,0x30,0x30,0x35, 0x63,0x30,0x2e,0x32,0x31,0x35,0x2c,0x30,0x2e,0x31, 0x33,0x38,0x2c,0x30,0x2e,0x33,0x34,0x35,0x2c,0x30, 0x2e,0x33,0x37,0x36,0x2c,0x30,0x2e,0x33,0x34,0x35, 0x2c,0x30,0x2e,0x36,0x33,0x31,0x0d,0x0a,0x09,0x09, 0x09,0x73,0x2d,0x30,0x2e,0x31,0x33,0x2c,0x30,0x2e, 0x34,0x39,0x33,0x2d,0x30,0x2e,0x33,0x34,0x35,0x2c, 0x30,0x2e,0x36,0x33,0x31,0x6c,0x2d,0x34,0x2e,0x36, 0x38,0x35,0x2c,0x33,0x2e,0x30,0x30,0x34,0x43,0x32, 0x39,0x2e,0x34,0x37,0x38,0x2c,0x32,0x32,0x2e,0x32, 0x34,0x34,0x2c,0x32,0x39,0x2e,0x33,0x33,0x36,0x2c, 0x32,0x32,0x2e,0x32,0x38,0x34,0x2c,0x32,0x39,0x2e, 0x31,0x39,0x35,0x2c,0x32,0x32,0x2e,0x32,0x38,0x34, 0x7a,0x20,0x4d,0x32,0x39,0x2e,0x39,0x34,0x35,0x2c, 0x31,0x36,0x2e,0x38,0x39,0x36,0x76,0x33,0x2e,0x32, 0x36,0x36,0x6c,0x32,0x2e,0x35,0x34,0x36,0x2d,0x31, 0x2e,0x36,0x33,0x33,0x0d,0x0a,0x09,0x09,0x09,0x4c, 0x32,0x39,0x2e,0x39,0x34,0x35,0x2c,0x31,0x36,0x2e, 0x38,0x39,0x36,0x7a,0x22,0x2f,0x3e,0x0d,0x0a,0x09, 0x3c,0x2f,0x67,0x3e,0x0d,0x0a,0x09,0x3c,0x67,0x3e, 0x0d,0x0a,0x09,0x09,0x3c,0x70,0x61,0x74,0x68,0x20, 0x66,0x69,0x6c,0x6c,0x3d,0x22,0x23,0x46,0x46,0x46, 0x46,0x46,0x46,0x22,0x20,0x64,0x3d,0x22,0x4d,0x31, 0x38,0x2e,0x35,0x33,0x2c,0x33,0x34,0x2e,0x36,0x32, 0x36,0x4c,0x31,0x38,0x2e,0x35,0x33,0x2c,0x33,0x34, 0x2e,0x36,0x32,0x36,0x63,0x2d,0x30,0x2e,0x32,0x35, 0x35,0x2c,0x30,0x2d,0x30,0x2e,0x34,0x39,0x32,0x2d, 0x30,0x2e,0x31,0x33,0x2d,0x30,0x2e,0x36,0x33,0x31, 0x2d,0x30,0x2e,0x33,0x34,0x35,0x6c,0x2d,0x33,0x2e, 0x30,0x30,0x35,0x2d,0x34,0x2e,0x36,0x38,0x34,0x0d, 0x0a,0x09,0x09,0x09,0x63,0x2d,0x30,0x2e,0x31,0x34, 0x37,0x2d,0x30,0x2e,0x32,0x33,0x31,0x2d,0x30,0x2e, 0x31,0x35,0x38,0x2d,0x30,0x2e,0x35,0x32,0x34,0x2d, 0x30,0x2e,0x30,0x32,0x36,0x2d,0x30,0x2e,0x37,0x36, 0x36,0x73,0x30,0x2e,0x33,0x38,0x34,0x2d,0x30,0x2e, 0x33,0x39,0x31,0x2c,0x30,0x2e,0x36,0x35,0x37,0x2d, 0x30,0x2e,0x33,0x39,0x31,0x68,0x36,0x2e,0x30,0x31, 0x32,0x63,0x30,0x2e,0x32,0x37,0x33,0x2c,0x30,0x2c, 0x30,0x2e,0x35,0x32,0x35,0x2c,0x30,0x2e,0x31,0x34, 0x38,0x2c,0x30,0x2e,0x36,0x35,0x37,0x2c,0x30,0x2e, 0x33,0x39,0x31,0x0d,0x0a,0x09,0x09,0x09,0x63,0x30, 0x2e,0x31,0x33,0x33,0x2c,0x30,0x2e,0x32,0x34,0x2c, 0x30,0x2e,0x31,0x32,0x31,0x2c,0x30,0x2e,0x35,0x33, 0x33,0x2d,0x30,0x2e,0x30,0x32,0x36,0x2c,0x30,0x2e, 0x37,0x36,0x36,0x6c,0x2d,0x33,0x2e,0x30,0x30,0x35, 0x2c,0x34,0x2e,0x36,0x38,0x34,0x43,0x31,0x39,0x2e, 0x30,0x32,0x33,0x2c,0x33,0x34,0x2e,0x34,0x39,0x36, 0x2c,0x31,0x38,0x2e,0x37,0x38,0x36,0x2c,0x33,0x34, 0x2e,0x36,0x32,0x36,0x2c,0x31,0x38,0x2e,0x35,0x33, 0x2c,0x33,0x34,0x2e,0x36,0x32,0x36,0x7a,0x20,0x4d, 0x31,0x36,0x2e,0x38,0x39,0x37,0x2c,0x32,0x39,0x2e, 0x39,0x34,0x32,0x6c,0x31,0x2e,0x36,0x33,0x33,0x2c, 0x32,0x2e,0x35,0x34,0x35,0x0d,0x0a,0x09,0x09,0x09, 0x6c,0x31,0x2e,0x36,0x33,0x35,0x2d,0x32,0x2e,0x35, 0x34,0x35,0x48,0x31,0x36,0x2e,0x38,0x39,0x37,0x7a, 0x22,0x2f,0x3e,0x0d,0x0a,0x09,0x3c,0x2f,0x67,0x3e, 0x0d,0x0a,0x3c,0x2f,0x67,0x3e,0x0d,0x0a,0x3c,0x2f, 0x73,0x76,0x67,0x3e,0x0d,0x0a };
mit
Noah-Huppert/Website-2013
vhosts/www.noahhuppert.com/htdocs/trex/deps/libxslt/tests/docbook/test/docbook.css
87
DIV.TITLEPAGE { text-align: center; } DIV.TITLEPAGE DIV.ABSTRACT { text-align: left; }
mit
chrisdavidmills/express-local-library
node_modules/helmet-csp/lib/is-string.js
116
module.exports = function isString (value) { return Object.prototype.toString.call(value) === '[object String]' }
mit
GeeChao/mockito
test/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java
3508
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockitousage.verification; import static org.mockito.Mockito.*; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; @SuppressWarnings("unchecked") public class NoMoreInteractionsVerificationTest extends TestBase { private LinkedList mock; @Before public void setup() { mock = mock(LinkedList.class); } @Test public void shouldStubbingNotRegisterRedundantInteractions() throws Exception { when(mock.add("one")).thenReturn(true); when(mock.add("two")).thenReturn(true); mock.add("one"); verify(mock).add("one"); verifyNoMoreInteractions(mock); } @Test public void shouldVerifyWhenWantedNumberOfInvocationsUsed() throws Exception { mock.add("one"); mock.add("one"); mock.add("one"); verify(mock, times(3)).add("one"); verifyNoMoreInteractions(mock); } @Test public void shouldVerifyNoInteractionsAsManyTimesAsYouWant() throws Exception { verifyNoMoreInteractions(mock); verifyNoMoreInteractions(mock); verifyZeroInteractions(mock); verifyZeroInteractions(mock); } @Test public void shouldFailZeroInteractionsVerification() throws Exception { mock.clear(); try { verifyZeroInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} } @Test public void shouldFailNoMoreInteractionsVerification() throws Exception { mock.clear(); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) {} } @Test public void shouldPrintAllInvocationsWhenVerifyingNoMoreInvocations() throws Exception { mock.add(1); mock.add(2); mock.clear(); verify(mock).add(2); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertContains("list of all invocations", e.getMessage()); } } @Test public void shouldNotContainAllInvocationsWhenSingleUnwantedFound() throws Exception { mock.add(1); try { verifyNoMoreInteractions(mock); fail(); } catch (NoInteractionsWanted e) { assertNotContains("list of all invocations", e.getMessage()); } } @Test public void shouldVerifyOneMockButFailOnOther() throws Exception { List list = mock(List.class); Map map = mock(Map.class); list.add("one"); list.add("one"); map.put("one", 1); verify(list, times(2)).add("one"); verifyNoMoreInteractions(list); try { verifyZeroInteractions(map); fail(); } catch (NoInteractionsWanted e) {} } @SuppressWarnings("all") @Test(expected=MockitoException.class) public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() throws Exception { verifyNoMoreInteractions((Object[])null); } }
mit
KatharineYe/ews-java-api
src/main/java/microsoft/exchange/webservices/data/core/request/MoveCopyItemRequest.java
3795
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package microsoft.exchange.webservices.data.core.request; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.EwsUtilities; import microsoft.exchange.webservices.data.core.ExchangeService; import microsoft.exchange.webservices.data.core.XmlElementNames; import microsoft.exchange.webservices.data.core.enumeration.service.error.ServiceErrorHandling; import microsoft.exchange.webservices.data.core.response.ServiceResponse; import microsoft.exchange.webservices.data.core.service.item.Item; import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace; import microsoft.exchange.webservices.data.misc.ItemIdWrapperList; /** * Represents an abstract Move/Copy Item request. * * @param <TResponse> The type of the response. */ public abstract class MoveCopyItemRequest<TResponse extends ServiceResponse> extends MoveCopyRequest<Item, TResponse> { private ItemIdWrapperList itemIds = new ItemIdWrapperList(); private Boolean newItemIds; /** * Validates request. * * @throws Exception the exception */ @Override public void validate() throws Exception { super.validate(); EwsUtilities.validateParam(this.getItemIds(), "ItemIds"); } /** * Initializes a new instance of the class. * * @param service the service * @param errorHandlingMode the error handling mode * @throws Exception on error */ protected MoveCopyItemRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode) throws Exception { super(service, errorHandlingMode); } /** * Writes the ids as XML. * * @param writer the writer * @throws Exception the exception */ @Override protected void writeIdsToXml(EwsServiceXmlWriter writer) throws Exception { this.getItemIds().writeToXml(writer, XmlNamespace.Messages, XmlElementNames.ItemIds); if (this.getReturnNewItemIds() != null) { writer.writeElementValue( XmlNamespace.Messages, XmlElementNames.ReturnNewItemIds, this.getReturnNewItemIds()); } } /** * Gets the expected response message count. * * @return Number of expected response messages. */ @Override protected int getExpectedResponseMessageCount() { return this.getItemIds().getCount(); } /** * Gets the item ids. * * @return the item ids */ public ItemIdWrapperList getItemIds() { return this.itemIds; } protected Boolean getReturnNewItemIds() { return this.newItemIds; } public void setReturnNewItemIds(Boolean value) { this.newItemIds = value; } }
mit
georgemarshall/DefinitelyTyped
types/carbon__pictograms-react/lib/teammates/index.d.ts
57
import { Teammates } from "../../"; export = Teammates;
mit
cdnjs/cdnjs
ajax/libs/highlight.js/10.7.3/styles/docco.min.css
817
.hljs{display:block;overflow-x:auto;padding:.5em;color:#000;background:#f8f8ff}.hljs-comment,.hljs-quote{color:#408080;font-style:italic}.hljs-keyword,.hljs-literal,.hljs-selector-tag,.hljs-subst{color:#954121}.hljs-number{color:#40a070}.hljs-doctag,.hljs-string{color:#219161}.hljs-section,.hljs-selector-class,.hljs-selector-id,.hljs-type{color:#19469d}.hljs-params{color:#00f}.hljs-title{color:#458;font-weight:700}.hljs-attribute,.hljs-name,.hljs-tag{color:navy;font-weight:400}.hljs-template-variable,.hljs-variable{color:teal}.hljs-link,.hljs-regexp{color:#b68}.hljs-bullet,.hljs-symbol{color:#990073}.hljs-built_in,.hljs-builtin-name{color:#0086b3}.hljs-meta{color:#999;font-weight:700}.hljs-deletion{background:#fdd}.hljs-addition{background:#dfd}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}
mit
kylon/pacman-fakeroot
test/pacman/tests/sync502.py
513
self.description = "Install a package from a sync db with fnmatch'ed NoExtract" sp = pmpkg("dummy") sp.files = ["bin/dummy", "usr/share/man/man8", "usr/share/man/man1/dummy.1"] self.addpkg2db("sync", sp) self.option["NoExtract"] = ["usr/share/man/*"] self.args = "-S %s" % sp.name self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_EXIST=dummy") self.addrule("FILE_EXIST=bin/dummy") self.addrule("!FILE_EXIST=usr/share/man/man8") self.addrule("!FILE_EXIST=usr/share/man/man1/dummy.1")
gpl-2.0
jmahler/linux-next
fs/pnode.c
15669
/* * linux/fs/pnode.c * * (C) Copyright IBM Corporation 2005. * Released under GPL v2. * Author : Ram Pai (linuxram@us.ibm.com) * */ #include <linux/mnt_namespace.h> #include <linux/mount.h> #include <linux/fs.h> #include <linux/nsproxy.h> #include <uapi/linux/mount.h> #include "internal.h" #include "pnode.h" /* return the next shared peer mount of @p */ static inline struct mount *next_peer(struct mount *p) { return list_entry(p->mnt_share.next, struct mount, mnt_share); } static inline struct mount *first_slave(struct mount *p) { return list_entry(p->mnt_slave_list.next, struct mount, mnt_slave); } static inline struct mount *last_slave(struct mount *p) { return list_entry(p->mnt_slave_list.prev, struct mount, mnt_slave); } static inline struct mount *next_slave(struct mount *p) { return list_entry(p->mnt_slave.next, struct mount, mnt_slave); } static struct mount *get_peer_under_root(struct mount *mnt, struct mnt_namespace *ns, const struct path *root) { struct mount *m = mnt; do { /* Check the namespace first for optimization */ if (m->mnt_ns == ns && is_path_reachable(m, m->mnt.mnt_root, root)) return m; m = next_peer(m); } while (m != mnt); return NULL; } /* * Get ID of closest dominating peer group having a representative * under the given root. * * Caller must hold namespace_sem */ int get_dominating_id(struct mount *mnt, const struct path *root) { struct mount *m; for (m = mnt->mnt_master; m != NULL; m = m->mnt_master) { struct mount *d = get_peer_under_root(m, mnt->mnt_ns, root); if (d) return d->mnt_group_id; } return 0; } static int do_make_slave(struct mount *mnt) { struct mount *master, *slave_mnt; if (list_empty(&mnt->mnt_share)) { if (IS_MNT_SHARED(mnt)) { mnt_release_group_id(mnt); CLEAR_MNT_SHARED(mnt); } master = mnt->mnt_master; if (!master) { struct list_head *p = &mnt->mnt_slave_list; while (!list_empty(p)) { slave_mnt = list_first_entry(p, struct mount, mnt_slave); list_del_init(&slave_mnt->mnt_slave); slave_mnt->mnt_master = NULL; } return 0; } } else { struct mount *m; /* * slave 'mnt' to a peer mount that has the * same root dentry. If none is available then * slave it to anything that is available. */ for (m = master = next_peer(mnt); m != mnt; m = next_peer(m)) { if (m->mnt.mnt_root == mnt->mnt.mnt_root) { master = m; break; } } list_del_init(&mnt->mnt_share); mnt->mnt_group_id = 0; CLEAR_MNT_SHARED(mnt); } list_for_each_entry(slave_mnt, &mnt->mnt_slave_list, mnt_slave) slave_mnt->mnt_master = master; list_move(&mnt->mnt_slave, &master->mnt_slave_list); list_splice(&mnt->mnt_slave_list, master->mnt_slave_list.prev); INIT_LIST_HEAD(&mnt->mnt_slave_list); mnt->mnt_master = master; return 0; } /* * vfsmount lock must be held for write */ void change_mnt_propagation(struct mount *mnt, int type) { if (type == MS_SHARED) { set_mnt_shared(mnt); return; } do_make_slave(mnt); if (type != MS_SLAVE) { list_del_init(&mnt->mnt_slave); mnt->mnt_master = NULL; if (type == MS_UNBINDABLE) mnt->mnt.mnt_flags |= MNT_UNBINDABLE; else mnt->mnt.mnt_flags &= ~MNT_UNBINDABLE; } } /* * get the next mount in the propagation tree. * @m: the mount seen last * @origin: the original mount from where the tree walk initiated * * Note that peer groups form contiguous segments of slave lists. * We rely on that in get_source() to be able to find out if * vfsmount found while iterating with propagation_next() is * a peer of one we'd found earlier. */ static struct mount *propagation_next(struct mount *m, struct mount *origin) { /* are there any slaves of this mount? */ if (!IS_MNT_NEW(m) && !list_empty(&m->mnt_slave_list)) return first_slave(m); while (1) { struct mount *master = m->mnt_master; if (master == origin->mnt_master) { struct mount *next = next_peer(m); return (next == origin) ? NULL : next; } else if (m->mnt_slave.next != &master->mnt_slave_list) return next_slave(m); /* back at master */ m = master; } } static struct mount *skip_propagation_subtree(struct mount *m, struct mount *origin) { /* * Advance m such that propagation_next will not return * the slaves of m. */ if (!IS_MNT_NEW(m) && !list_empty(&m->mnt_slave_list)) m = last_slave(m); return m; } static struct mount *next_group(struct mount *m, struct mount *origin) { while (1) { while (1) { struct mount *next; if (!IS_MNT_NEW(m) && !list_empty(&m->mnt_slave_list)) return first_slave(m); next = next_peer(m); if (m->mnt_group_id == origin->mnt_group_id) { if (next == origin) return NULL; } else if (m->mnt_slave.next != &next->mnt_slave) break; m = next; } /* m is the last peer */ while (1) { struct mount *master = m->mnt_master; if (m->mnt_slave.next != &master->mnt_slave_list) return next_slave(m); m = next_peer(master); if (master->mnt_group_id == origin->mnt_group_id) break; if (master->mnt_slave.next == &m->mnt_slave) break; m = master; } if (m == origin) return NULL; } } /* all accesses are serialized by namespace_sem */ static struct user_namespace *user_ns; static struct mount *last_dest, *first_source, *last_source, *dest_master; static struct mountpoint *mp; static struct hlist_head *list; static inline bool peers(struct mount *m1, struct mount *m2) { return m1->mnt_group_id == m2->mnt_group_id && m1->mnt_group_id; } static int propagate_one(struct mount *m) { struct mount *child; int type; /* skip ones added by this propagate_mnt() */ if (IS_MNT_NEW(m)) return 0; /* skip if mountpoint isn't covered by it */ if (!is_subdir(mp->m_dentry, m->mnt.mnt_root)) return 0; if (peers(m, last_dest)) { type = CL_MAKE_SHARED; } else { struct mount *n, *p; bool done; for (n = m; ; n = p) { p = n->mnt_master; if (p == dest_master || IS_MNT_MARKED(p)) break; } do { struct mount *parent = last_source->mnt_parent; if (last_source == first_source) break; done = parent->mnt_master == p; if (done && peers(n, parent)) break; last_source = last_source->mnt_master; } while (!done); type = CL_SLAVE; /* beginning of peer group among the slaves? */ if (IS_MNT_SHARED(m)) type |= CL_MAKE_SHARED; } /* Notice when we are propagating across user namespaces */ if (m->mnt_ns->user_ns != user_ns) type |= CL_UNPRIVILEGED; child = copy_tree(last_source, last_source->mnt.mnt_root, type); if (IS_ERR(child)) return PTR_ERR(child); child->mnt.mnt_flags &= ~MNT_LOCKED; mnt_set_mountpoint(m, mp, child); last_dest = m; last_source = child; if (m->mnt_master != dest_master) { read_seqlock_excl(&mount_lock); SET_MNT_MARK(m->mnt_master); read_sequnlock_excl(&mount_lock); } hlist_add_head(&child->mnt_hash, list); return count_mounts(m->mnt_ns, child); } /* * mount 'source_mnt' under the destination 'dest_mnt' at * dentry 'dest_dentry'. And propagate that mount to * all the peer and slave mounts of 'dest_mnt'. * Link all the new mounts into a propagation tree headed at * source_mnt. Also link all the new mounts using ->mnt_list * headed at source_mnt's ->mnt_list * * @dest_mnt: destination mount. * @dest_dentry: destination dentry. * @source_mnt: source mount. * @tree_list : list of heads of trees to be attached. */ int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; first_source = source_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; } static struct mount *find_topper(struct mount *mnt) { /* If there is exactly one mount covering mnt completely return it. */ struct mount *child; if (!list_is_singular(&mnt->mnt_mounts)) return NULL; child = list_first_entry(&mnt->mnt_mounts, struct mount, mnt_child); if (child->mnt_mountpoint != mnt->mnt.mnt_root) return NULL; return child; } /* * return true if the refcount is greater than count */ static inline int do_refcount_check(struct mount *mnt, int count) { return mnt_get_count(mnt) > count; } /* * check if the mount 'mnt' can be unmounted successfully. * @mnt: the mount to be checked for unmount * NOTE: unmounting 'mnt' would naturally propagate to all * other mounts its parent propagates to. * Check if any of these mounts that **do not have submounts** * have more references than 'refcnt'. If so return busy. * * vfsmount lock must be held for write */ int propagate_mount_busy(struct mount *mnt, int refcnt) { struct mount *m, *child, *topper; struct mount *parent = mnt->mnt_parent; if (mnt == parent) return do_refcount_check(mnt, refcnt); /* * quickly check if the current mount can be unmounted. * If not, we don't have to go checking for all other * mounts */ if (!list_empty(&mnt->mnt_mounts) || do_refcount_check(mnt, refcnt)) return 1; for (m = propagation_next(parent, parent); m; m = propagation_next(m, parent)) { int count = 1; child = __lookup_mnt(&m->mnt, mnt->mnt_mountpoint); if (!child) continue; /* Is there exactly one mount on the child that covers * it completely whose reference should be ignored? */ topper = find_topper(child); if (topper) count += 1; else if (!list_empty(&child->mnt_mounts)) continue; if (do_refcount_check(child, count)) return 1; } return 0; } /* * Clear MNT_LOCKED when it can be shown to be safe. * * mount_lock lock must be held for write */ void propagate_mount_unlock(struct mount *mnt) { struct mount *parent = mnt->mnt_parent; struct mount *m, *child; BUG_ON(parent == mnt); for (m = propagation_next(parent, parent); m; m = propagation_next(m, parent)) { child = __lookup_mnt(&m->mnt, mnt->mnt_mountpoint); if (child) child->mnt.mnt_flags &= ~MNT_LOCKED; } } static void umount_one(struct mount *mnt, struct list_head *to_umount) { CLEAR_MNT_MARK(mnt); mnt->mnt.mnt_flags |= MNT_UMOUNT; list_del_init(&mnt->mnt_child); list_del_init(&mnt->mnt_umounting); list_move_tail(&mnt->mnt_list, to_umount); } /* * NOTE: unmounting 'mnt' naturally propagates to all other mounts its * parent propagates to. */ static bool __propagate_umount(struct mount *mnt, struct list_head *to_umount, struct list_head *to_restore) { bool progress = false; struct mount *child; /* * The state of the parent won't change if this mount is * already unmounted or marked as without children. */ if (mnt->mnt.mnt_flags & (MNT_UMOUNT | MNT_MARKED)) goto out; /* Verify topper is the only grandchild that has not been * speculatively unmounted. */ list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { if (child->mnt_mountpoint == mnt->mnt.mnt_root) continue; if (!list_empty(&child->mnt_umounting) && IS_MNT_MARKED(child)) continue; /* Found a mounted child */ goto children; } /* Mark mounts that can be unmounted if not locked */ SET_MNT_MARK(mnt); progress = true; /* If a mount is without children and not locked umount it. */ if (!IS_MNT_LOCKED(mnt)) { umount_one(mnt, to_umount); } else { children: list_move_tail(&mnt->mnt_umounting, to_restore); } out: return progress; } static void umount_list(struct list_head *to_umount, struct list_head *to_restore) { struct mount *mnt, *child, *tmp; list_for_each_entry(mnt, to_umount, mnt_list) { list_for_each_entry_safe(child, tmp, &mnt->mnt_mounts, mnt_child) { /* topper? */ if (child->mnt_mountpoint == mnt->mnt.mnt_root) list_move_tail(&child->mnt_umounting, to_restore); else umount_one(child, to_umount); } } } static void restore_mounts(struct list_head *to_restore) { /* Restore mounts to a clean working state */ while (!list_empty(to_restore)) { struct mount *mnt, *parent; struct mountpoint *mp; mnt = list_first_entry(to_restore, struct mount, mnt_umounting); CLEAR_MNT_MARK(mnt); list_del_init(&mnt->mnt_umounting); /* Should this mount be reparented? */ mp = mnt->mnt_mp; parent = mnt->mnt_parent; while (parent->mnt.mnt_flags & MNT_UMOUNT) { mp = parent->mnt_mp; parent = parent->mnt_parent; } if (parent != mnt->mnt_parent) mnt_change_mountpoint(parent, mp, mnt); } } static void cleanup_umount_visitations(struct list_head *visited) { while (!list_empty(visited)) { struct mount *mnt = list_first_entry(visited, struct mount, mnt_umounting); list_del_init(&mnt->mnt_umounting); } } /* * collect all mounts that receive propagation from the mount in @list, * and return these additional mounts in the same list. * @list: the list of mounts to be unmounted. * * vfsmount lock must be held for write */ int propagate_umount(struct list_head *list) { struct mount *mnt; LIST_HEAD(to_restore); LIST_HEAD(to_umount); LIST_HEAD(visited); /* Find candidates for unmounting */ list_for_each_entry_reverse(mnt, list, mnt_list) { struct mount *parent = mnt->mnt_parent; struct mount *m; /* * If this mount has already been visited it is known that it's * entire peer group and all of their slaves in the propagation * tree for the mountpoint has already been visited and there is * no need to visit them again. */ if (!list_empty(&mnt->mnt_umounting)) continue; list_add_tail(&mnt->mnt_umounting, &visited); for (m = propagation_next(parent, parent); m; m = propagation_next(m, parent)) { struct mount *child = __lookup_mnt(&m->mnt, mnt->mnt_mountpoint); if (!child) continue; if (!list_empty(&child->mnt_umounting)) { /* * If the child has already been visited it is * know that it's entire peer group and all of * their slaves in the propgation tree for the * mountpoint has already been visited and there * is no need to visit this subtree again. */ m = skip_propagation_subtree(m, parent); continue; } else if (child->mnt.mnt_flags & MNT_UMOUNT) { /* * We have come accross an partially unmounted * mount in list that has not been visited yet. * Remember it has been visited and continue * about our merry way. */ list_add_tail(&child->mnt_umounting, &visited); continue; } /* Check the child and parents while progress is made */ while (__propagate_umount(child, &to_umount, &to_restore)) { /* Is the parent a umount candidate? */ child = child->mnt_parent; if (list_empty(&child->mnt_umounting)) break; } } } umount_list(&to_umount, &to_restore); restore_mounts(&to_restore); cleanup_umount_visitations(&visited); list_splice_tail(&to_umount, list); return 0; }
gpl-2.0
qtekfun/htcDesire820Kernel
external/chromium_org/content/browser/renderer_host/media/audio_sync_reader.cc
6518
// 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. #include "content/browser/renderer_host/media/audio_sync_reader.h" #include <algorithm> #include "base/command_line.h" #include "base/memory/shared_memory.h" #include "base/metrics/histogram.h" #include "content/public/common/content_switches.h" #include "media/audio/audio_buffers_state.h" #include "media/audio/audio_parameters.h" using media::AudioBus; namespace content { AudioSyncReader::AudioSyncReader(base::SharedMemory* shared_memory, const media::AudioParameters& params, int input_channels) : shared_memory_(shared_memory), input_channels_(input_channels), mute_audio_(CommandLine::ForCurrentProcess()->HasSwitch( switches::kMuteAudio)), packet_size_(shared_memory_->requested_size()), renderer_callback_count_(0), renderer_missed_callback_count_(0), #if defined(OS_MACOSX) maximum_wait_time_(params.GetBufferDuration() / 2), #else // TODO(dalecurtis): Investigate if we can reduce this on all platforms. maximum_wait_time_(base::TimeDelta::FromMilliseconds(20)), #endif buffer_index_(0) { int input_memory_size = 0; int output_memory_size = AudioBus::CalculateMemorySize(params); if (input_channels_ > 0) { // The input storage is after the output storage. int frames = params.frames_per_buffer(); input_memory_size = AudioBus::CalculateMemorySize(input_channels_, frames); char* input_data = static_cast<char*>(shared_memory_->memory()) + output_memory_size; input_bus_ = AudioBus::WrapMemory(input_channels_, frames, input_data); input_bus_->Zero(); } DCHECK_EQ(packet_size_, output_memory_size + input_memory_size); output_bus_ = AudioBus::WrapMemory(params, shared_memory->memory()); output_bus_->Zero(); } AudioSyncReader::~AudioSyncReader() { if (!renderer_callback_count_) return; // Recording the percentage of deadline misses gives us a rough overview of // how many users might be running into audio glitches. int percentage_missed = 100.0 * renderer_missed_callback_count_ / renderer_callback_count_; UMA_HISTOGRAM_PERCENTAGE( "Media.AudioRendererMissedDeadline", percentage_missed); } // media::AudioOutputController::SyncReader implementations. void AudioSyncReader::UpdatePendingBytes(uint32 bytes) { // Zero out the entire output buffer to avoid stuttering/repeating-buffers // in the anomalous case if the renderer is unable to keep up with real-time. output_bus_->Zero(); socket_->Send(&bytes, sizeof(bytes)); ++buffer_index_; } void AudioSyncReader::Read(const AudioBus* source, AudioBus* dest) { ++renderer_callback_count_; if (!WaitUntilDataIsReady()) { ++renderer_missed_callback_count_; dest->Zero(); return; } // Copy optional synchronized live audio input for consumption by renderer // process. if (input_bus_) { if (source) source->CopyTo(input_bus_.get()); else input_bus_->Zero(); } if (mute_audio_) dest->Zero(); else output_bus_->CopyTo(dest); } void AudioSyncReader::Close() { socket_->Close(); } bool AudioSyncReader::Init() { socket_.reset(new base::CancelableSyncSocket()); foreign_socket_.reset(new base::CancelableSyncSocket()); return base::CancelableSyncSocket::CreatePair(socket_.get(), foreign_socket_.get()); } #if defined(OS_WIN) bool AudioSyncReader::PrepareForeignSocketHandle( base::ProcessHandle process_handle, base::SyncSocket::Handle* foreign_handle) { ::DuplicateHandle(GetCurrentProcess(), foreign_socket_->handle(), process_handle, foreign_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); return (*foreign_handle != 0); } #else bool AudioSyncReader::PrepareForeignSocketHandle( base::ProcessHandle process_handle, base::FileDescriptor* foreign_handle) { foreign_handle->fd = foreign_socket_->handle(); foreign_handle->auto_close = false; return (foreign_handle->fd != -1); } #endif bool AudioSyncReader::WaitUntilDataIsReady() { base::TimeDelta timeout = maximum_wait_time_; const base::TimeTicks start_time = base::TimeTicks::Now(); const base::TimeTicks finish_time = start_time + timeout; // Check if data is ready and if not, wait a reasonable amount of time for it. // // Data readiness is achieved via parallel counters, one on the renderer side // and one here. Every time a buffer is requested via UpdatePendingBytes(), // |buffer_index_| is incremented. Subsequently every time the renderer has a // buffer ready it increments its counter and sends the counter value over the // SyncSocket. Data is ready when |buffer_index_| matches the counter value // received from the renderer. // // The counter values may temporarily become out of sync if the renderer is // unable to deliver audio fast enough. It's assumed that the renderer will // catch up at some point, which means discarding counter values read from the // SyncSocket which don't match our current buffer index. size_t bytes_received = 0; uint32 renderer_buffer_index = 0; while (timeout.InMicroseconds() > 0) { bytes_received = socket_->ReceiveWithTimeout( &renderer_buffer_index, sizeof(renderer_buffer_index), timeout); if (!bytes_received) break; DCHECK_EQ(bytes_received, sizeof(renderer_buffer_index)); if (renderer_buffer_index == buffer_index_) break; // Reduce the timeout value as receives succeed, but aren't the right index. timeout = finish_time - base::TimeTicks::Now(); } // Receive timed out or another error occurred. Receive can timeout if the // renderer is unable to deliver audio data within the allotted time. if (!bytes_received || renderer_buffer_index != buffer_index_) { DVLOG(2) << "AudioSyncReader::WaitUntilDataIsReady() timed out."; base::TimeDelta time_since_start = base::TimeTicks::Now() - start_time; UMA_HISTOGRAM_CUSTOM_TIMES("Media.AudioOutputControllerDataNotReady", time_since_start, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(1000), 50); return false; } return true; } } // namespace content
gpl-2.0
kidmaple/CoolWall
linux-2.6.x/drivers/char/agp/parisc-agp.c
10130
/* * HP Quicksilver AGP GART routines * * Copyright (c) 2006, Kyle McMartin <kyle@parisc-linux.org> * * Based on drivers/char/agpgart/hp-agp.c which is * (c) Copyright 2002, 2003 Hewlett-Packard Development Company, L.P. * Bjorn Helgaas <bjorn.helgaas@hp.com> * * 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/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/klist.h> #include <linux/agp_backend.h> #include <asm-parisc/parisc-device.h> #include <asm-parisc/ropes.h> #include "agp.h" #define DRVNAME "quicksilver" #define DRVPFX DRVNAME ": " #ifndef log2 #define log2(x) ffz(~(x)) #endif #define AGP8X_MODE_BIT 3 #define AGP8X_MODE (1 << AGP8X_MODE_BIT) static struct _parisc_agp_info { void __iomem *ioc_regs; void __iomem *lba_regs; int lba_cap_offset; u64 *gatt; u64 gatt_entries; u64 gart_base; u64 gart_size; int io_page_size; int io_pages_per_kpage; } parisc_agp_info; static struct gatt_mask parisc_agp_masks[] = { { .mask = SBA_PDIR_VALID_BIT, .type = 0 } }; static struct aper_size_info_fixed parisc_agp_sizes[] = { {0, 0, 0}, /* filled in by parisc_agp_fetch_size() */ }; static int parisc_agp_fetch_size(void) { int size; size = parisc_agp_info.gart_size / MB(1); parisc_agp_sizes[0].size = size; agp_bridge->current_size = (void *) &parisc_agp_sizes[0]; return size; } static int parisc_agp_configure(void) { struct _parisc_agp_info *info = &parisc_agp_info; agp_bridge->gart_bus_addr = info->gart_base; agp_bridge->capndx = info->lba_cap_offset; agp_bridge->mode = readl(info->lba_regs+info->lba_cap_offset+PCI_AGP_STATUS); return 0; } static void parisc_agp_tlbflush(struct agp_memory *mem) { struct _parisc_agp_info *info = &parisc_agp_info; writeq(info->gart_base | log2(info->gart_size), info->ioc_regs+IOC_PCOM); readq(info->ioc_regs+IOC_PCOM); /* flush */ } static int parisc_agp_create_gatt_table(struct agp_bridge_data *bridge) { struct _parisc_agp_info *info = &parisc_agp_info; int i; for (i = 0; i < info->gatt_entries; i++) { info->gatt[i] = (unsigned long)agp_bridge->scratch_page; } return 0; } static int parisc_agp_free_gatt_table(struct agp_bridge_data *bridge) { struct _parisc_agp_info *info = &parisc_agp_info; info->gatt[0] = SBA_AGPGART_COOKIE; return 0; } static int parisc_agp_insert_memory(struct agp_memory *mem, off_t pg_start, int type) { struct _parisc_agp_info *info = &parisc_agp_info; int i, k; off_t j, io_pg_start; int io_pg_count; if (type != 0 || mem->type != 0) { return -EINVAL; } io_pg_start = info->io_pages_per_kpage * pg_start; io_pg_count = info->io_pages_per_kpage * mem->page_count; if ((io_pg_start + io_pg_count) > info->gatt_entries) { return -EINVAL; } j = io_pg_start; while (j < (io_pg_start + io_pg_count)) { if (info->gatt[j]) return -EBUSY; j++; } if (mem->is_flushed == FALSE) { global_cache_flush(); mem->is_flushed = TRUE; } for (i = 0, j = io_pg_start; i < mem->page_count; i++) { unsigned long paddr; paddr = mem->memory[i]; for (k = 0; k < info->io_pages_per_kpage; k++, j++, paddr += info->io_page_size) { info->gatt[j] = agp_bridge->driver->mask_memory(agp_bridge, paddr, type); } } agp_bridge->driver->tlb_flush(mem); return 0; } static int parisc_agp_remove_memory(struct agp_memory *mem, off_t pg_start, int type) { struct _parisc_agp_info *info = &parisc_agp_info; int i, io_pg_start, io_pg_count; if (type != 0 || mem->type != 0) { return -EINVAL; } io_pg_start = info->io_pages_per_kpage * pg_start; io_pg_count = info->io_pages_per_kpage * mem->page_count; for (i = io_pg_start; i < io_pg_count + io_pg_start; i++) { info->gatt[i] = agp_bridge->scratch_page; } agp_bridge->driver->tlb_flush(mem); return 0; } static unsigned long parisc_agp_mask_memory(struct agp_bridge_data *bridge, unsigned long addr, int type) { return SBA_PDIR_VALID_BIT | addr; } static void parisc_agp_enable(struct agp_bridge_data *bridge, u32 mode) { struct _parisc_agp_info *info = &parisc_agp_info; u32 command; command = readl(info->lba_regs + info->lba_cap_offset + PCI_AGP_STATUS); command = agp_collect_device_status(bridge, mode, command); command |= 0x00000100; writel(command, info->lba_regs + info->lba_cap_offset + PCI_AGP_COMMAND); agp_device_command(command, (mode & AGP8X_MODE) != 0); } static const struct agp_bridge_driver parisc_agp_driver = { .owner = THIS_MODULE, .size_type = FIXED_APER_SIZE, .configure = parisc_agp_configure, .fetch_size = parisc_agp_fetch_size, .tlb_flush = parisc_agp_tlbflush, .mask_memory = parisc_agp_mask_memory, .masks = parisc_agp_masks, .agp_enable = parisc_agp_enable, .cache_flush = global_cache_flush, .create_gatt_table = parisc_agp_create_gatt_table, .free_gatt_table = parisc_agp_free_gatt_table, .insert_memory = parisc_agp_insert_memory, .remove_memory = parisc_agp_remove_memory, .alloc_by_type = agp_generic_alloc_by_type, .free_by_type = agp_generic_free_by_type, .agp_alloc_page = agp_generic_alloc_page, .agp_destroy_page = agp_generic_destroy_page, .agp_type_to_mask_type = agp_generic_type_to_mask_type, .cant_use_aperture = 1, }; static int __init agp_ioc_init(void __iomem *ioc_regs) { struct _parisc_agp_info *info = &parisc_agp_info; u64 iova_base, *io_pdir, io_tlb_ps; int io_tlb_shift; printk(KERN_INFO DRVPFX "IO PDIR shared with sba_iommu\n"); info->ioc_regs = ioc_regs; io_tlb_ps = readq(info->ioc_regs+IOC_TCNFG); switch (io_tlb_ps) { case 0: io_tlb_shift = 12; break; case 1: io_tlb_shift = 13; break; case 2: io_tlb_shift = 14; break; case 3: io_tlb_shift = 16; break; default: printk(KERN_ERR DRVPFX "Invalid IOTLB page size " "configuration 0x%llx\n", io_tlb_ps); info->gatt = NULL; info->gatt_entries = 0; return -ENODEV; } info->io_page_size = 1 << io_tlb_shift; info->io_pages_per_kpage = PAGE_SIZE / info->io_page_size; iova_base = readq(info->ioc_regs+IOC_IBASE) & ~0x1; info->gart_base = iova_base + PLUTO_IOVA_SIZE - PLUTO_GART_SIZE; info->gart_size = PLUTO_GART_SIZE; info->gatt_entries = info->gart_size / info->io_page_size; io_pdir = phys_to_virt(readq(info->ioc_regs+IOC_PDIR_BASE)); info->gatt = &io_pdir[(PLUTO_IOVA_SIZE/2) >> PAGE_SHIFT]; if (info->gatt[0] != SBA_AGPGART_COOKIE) { info->gatt = NULL; info->gatt_entries = 0; printk(KERN_ERR DRVPFX "No reserved IO PDIR entry found; " "GART disabled\n"); return -ENODEV; } return 0; } static int lba_find_capability(int cap) { struct _parisc_agp_info *info = &parisc_agp_info; u16 status; u8 pos, id; int ttl = 48; status = readw(info->lba_regs + PCI_STATUS); if (!(status & PCI_STATUS_CAP_LIST)) return 0; pos = readb(info->lba_regs + PCI_CAPABILITY_LIST); while (ttl-- && pos >= 0x40) { pos &= ~3; id = readb(info->lba_regs + pos + PCI_CAP_LIST_ID); if (id == 0xff) break; if (id == cap) return pos; pos = readb(info->lba_regs + pos + PCI_CAP_LIST_NEXT); } return 0; } static int __init agp_lba_init(void __iomem *lba_hpa) { struct _parisc_agp_info *info = &parisc_agp_info; int cap; info->lba_regs = lba_hpa; info->lba_cap_offset = lba_find_capability(PCI_CAP_ID_AGP); cap = readl(lba_hpa + info->lba_cap_offset) & 0xff; if (cap != PCI_CAP_ID_AGP) { printk(KERN_ERR DRVPFX "Invalid capability ID 0x%02x at 0x%x\n", cap, info->lba_cap_offset); return -ENODEV; } return 0; } static int __init parisc_agp_setup(void __iomem *ioc_hpa, void __iomem *lba_hpa) { struct pci_dev *fake_bridge_dev = NULL; struct agp_bridge_data *bridge; int error = 0; fake_bridge_dev = alloc_pci_dev(); if (!fake_bridge_dev) { error = -ENOMEM; goto fail; } error = agp_ioc_init(ioc_hpa); if (error) goto fail; error = agp_lba_init(lba_hpa); if (error) goto fail; bridge = agp_alloc_bridge(); if (!bridge) { error = -ENOMEM; goto fail; } bridge->driver = &parisc_agp_driver; fake_bridge_dev->vendor = PCI_VENDOR_ID_HP; fake_bridge_dev->device = PCI_DEVICE_ID_HP_PCIX_LBA; bridge->dev = fake_bridge_dev; error = agp_add_bridge(bridge); fail: return error; } static struct device *next_device(struct klist_iter *i) { struct klist_node * n = klist_next(i); return n ? container_of(n, struct device, knode_parent) : NULL; } static int parisc_agp_init(void) { extern struct sba_device *sba_list; int err = -1; struct parisc_device *sba = NULL, *lba = NULL; struct lba_device *lbadev = NULL; struct device *dev = NULL; struct klist_iter i; if (!sba_list) goto out; /* Find our parent Pluto */ sba = sba_list->dev; if (!IS_PLUTO(sba)) { printk(KERN_INFO DRVPFX "No Pluto found, so no AGPGART for you.\n"); goto out; } /* Now search our Pluto for our precious AGP device... */ klist_iter_init(&sba->dev.klist_children, &i); while ((dev = next_device(&i))) { struct parisc_device *padev = to_parisc_device(dev); if (IS_QUICKSILVER(padev)) lba = padev; } klist_iter_exit(&i); if (!lba) { printk(KERN_INFO DRVPFX "No AGP devices found.\n"); goto out; } lbadev = parisc_get_drvdata(lba); /* w00t, let's go find our cookies... */ parisc_agp_setup(sba_list->ioc[0].ioc_hpa, lbadev->hba.base_addr); return 0; out: return err; } module_init(parisc_agp_init); MODULE_AUTHOR("Kyle McMartin <kyle@parisc-linux.org>"); MODULE_LICENSE("GPL");
gpl-2.0
gazoo74/linux
drivers/gpu/drm/i915/intel_workarounds.h
942
/* * SPDX-License-Identifier: MIT * * Copyright © 2014-2018 Intel Corporation */ #ifndef _I915_WORKAROUNDS_H_ #define _I915_WORKAROUNDS_H_ #include <linux/slab.h> #include "intel_workarounds_types.h" static inline void intel_wa_list_free(struct i915_wa_list *wal) { kfree(wal->list); memset(wal, 0, sizeof(*wal)); } void intel_engine_init_ctx_wa(struct intel_engine_cs *engine); int intel_engine_emit_ctx_wa(struct i915_request *rq); void intel_gt_init_workarounds(struct drm_i915_private *i915); void intel_gt_apply_workarounds(struct drm_i915_private *i915); bool intel_gt_verify_workarounds(struct drm_i915_private *i915, const char *from); void intel_engine_init_whitelist(struct intel_engine_cs *engine); void intel_engine_apply_whitelist(struct intel_engine_cs *engine); void intel_engine_init_workarounds(struct intel_engine_cs *engine); void intel_engine_apply_workarounds(struct intel_engine_cs *engine); #endif
gpl-2.0
ghmajx/asuswrt-merlin
release/src/router/openpam/lib/libpam/openpam_impl.h
4165
/*- * Copyright (c) 2001-2003 Networks Associates Technology, Inc. * Copyright (c) 2004-2011 Dag-Erling Smørgrav * All rights reserved. * * This software was developed for the FreeBSD Project by ThinkSec AS and * Network Associates Laboratories, the Security Research Division of * Network Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 * ("CBOSS"), as part of the DARPA CHATS research program. * * 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. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $Id: openpam_impl.h 648 2013-03-05 17:54:27Z des $ */ #ifndef OPENPAM_IMPL_H_INCLUDED #define OPENPAM_IMPL_H_INCLUDED #include <security/openpam.h> extern int openpam_debug; /* * Control flags */ typedef enum { PAM_BINDING, PAM_REQUIRED, PAM_REQUISITE, PAM_SUFFICIENT, PAM_OPTIONAL, PAM_NUM_CONTROL_FLAGS } pam_control_t; /* * Facilities */ typedef enum { PAM_FACILITY_ANY = -1, PAM_AUTH = 0, PAM_ACCOUNT, PAM_SESSION, PAM_PASSWORD, PAM_NUM_FACILITIES } pam_facility_t; /* * Module chains */ typedef struct pam_chain pam_chain_t; struct pam_chain { pam_module_t *module; int flag; int optc; char **optv; pam_chain_t *next; }; /* * Service policies */ #if defined(OPENPAM_EMBEDDED) typedef struct pam_policy pam_policy_t; struct pam_policy { const char *service; pam_chain_t *chains[PAM_NUM_FACILITIES]; }; extern pam_policy_t *pam_embedded_policies[]; #endif /* * Module-specific data */ typedef struct pam_data pam_data_t; struct pam_data { char *name; void *data; void (*cleanup)(pam_handle_t *, void *, int); pam_data_t *next; }; /* * PAM context */ struct pam_handle { char *service; /* chains */ pam_chain_t *chains[PAM_NUM_FACILITIES]; pam_chain_t *current; int primitive; /* items and data */ void *item[PAM_NUM_ITEMS]; pam_data_t *module_data; /* environment list */ char **env; int env_count; int env_size; }; /* * Default policy */ #define PAM_OTHER "other" /* * Internal functions */ int openpam_configure(pam_handle_t *, const char *); int openpam_dispatch(pam_handle_t *, int, int); int openpam_findenv(pam_handle_t *, const char *, size_t); pam_module_t *openpam_load_module(const char *); void openpam_clear_chains(pam_chain_t **); int openpam_check_desc_owner_perms(const char *, int); int openpam_check_path_owner_perms(const char *); #ifdef OPENPAM_STATIC_MODULES pam_module_t *openpam_static(const char *); #endif pam_module_t *openpam_dynamic(const char *); #define FREE(p) \ do { \ free(p); \ (p) = NULL; \ } while (0) #define FREEV(c, v) \ do { \ while (c) { \ --(c); \ FREE((v)[(c)]); \ } \ FREE(v); \ } while (0) #include "openpam_constants.h" #include "openpam_debug.h" #include "openpam_features.h" #endif
gpl-2.0
koct9i/linux
drivers/watchdog/da9052_wdt.c
4824
// SPDX-License-Identifier: GPL-2.0+ /* * System monitoring driver for DA9052 PMICs. * * Copyright(c) 2012 Dialog Semiconductor Ltd. * * Author: Anthony Olech <Anthony.Olech@diasemi.com> * */ #include <linux/module.h> #include <linux/delay.h> #include <linux/uaccess.h> #include <linux/platform_device.h> #include <linux/time.h> #include <linux/watchdog.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/mfd/da9052/reg.h> #include <linux/mfd/da9052/da9052.h> #define DA9052_DEF_TIMEOUT 4 #define DA9052_TWDMIN 256 struct da9052_wdt_data { struct watchdog_device wdt; struct da9052 *da9052; unsigned long jpast; }; static const struct { u8 reg_val; int time; /* Seconds */ } da9052_wdt_maps[] = { { 1, 2 }, { 2, 4 }, { 3, 8 }, { 4, 16 }, { 5, 32 }, { 5, 33 }, /* Actual time 32.768s so included both 32s and 33s */ { 6, 65 }, { 6, 66 }, /* Actual time 65.536s so include both, 65s and 66s */ { 7, 131 }, }; static int da9052_wdt_set_timeout(struct watchdog_device *wdt_dev, unsigned int timeout) { struct da9052_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev); struct da9052 *da9052 = driver_data->da9052; int ret, i; /* * Disable the Watchdog timer before setting * new time out. */ ret = da9052_reg_update(da9052, DA9052_CONTROL_D_REG, DA9052_CONTROLD_TWDSCALE, 0); if (ret < 0) { dev_err(da9052->dev, "Failed to disable watchdog bit, %d\n", ret); return ret; } if (timeout) { /* * To change the timeout, da9052 needs to * be disabled for at least 150 us. */ udelay(150); /* Set the desired timeout */ for (i = 0; i < ARRAY_SIZE(da9052_wdt_maps); i++) if (da9052_wdt_maps[i].time == timeout) break; if (i == ARRAY_SIZE(da9052_wdt_maps)) ret = -EINVAL; else ret = da9052_reg_update(da9052, DA9052_CONTROL_D_REG, DA9052_CONTROLD_TWDSCALE, da9052_wdt_maps[i].reg_val); if (ret < 0) { dev_err(da9052->dev, "Failed to update timescale bit, %d\n", ret); return ret; } wdt_dev->timeout = timeout; driver_data->jpast = jiffies; } return 0; } static int da9052_wdt_start(struct watchdog_device *wdt_dev) { return da9052_wdt_set_timeout(wdt_dev, wdt_dev->timeout); } static int da9052_wdt_stop(struct watchdog_device *wdt_dev) { return da9052_wdt_set_timeout(wdt_dev, 0); } static int da9052_wdt_ping(struct watchdog_device *wdt_dev) { struct da9052_wdt_data *driver_data = watchdog_get_drvdata(wdt_dev); struct da9052 *da9052 = driver_data->da9052; unsigned long msec, jnow = jiffies; int ret; /* * We have a minimum time for watchdog window called TWDMIN. A write * to the watchdog before this elapsed time should cause an error. */ msec = (jnow - driver_data->jpast) * 1000/HZ; if (msec < DA9052_TWDMIN) mdelay(msec); /* Reset the watchdog timer */ ret = da9052_reg_update(da9052, DA9052_CONTROL_D_REG, DA9052_CONTROLD_WATCHDOG, 1 << 7); if (ret < 0) return ret; /* * FIXME: Reset the watchdog core, in general PMIC * is supposed to do this */ return da9052_reg_update(da9052, DA9052_CONTROL_D_REG, DA9052_CONTROLD_WATCHDOG, 0 << 7); } static const struct watchdog_info da9052_wdt_info = { .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING, .identity = "DA9052 Watchdog", }; static const struct watchdog_ops da9052_wdt_ops = { .owner = THIS_MODULE, .start = da9052_wdt_start, .stop = da9052_wdt_stop, .ping = da9052_wdt_ping, .set_timeout = da9052_wdt_set_timeout, }; static int da9052_wdt_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct da9052 *da9052 = dev_get_drvdata(dev->parent); struct da9052_wdt_data *driver_data; struct watchdog_device *da9052_wdt; int ret; driver_data = devm_kzalloc(dev, sizeof(*driver_data), GFP_KERNEL); if (!driver_data) return -ENOMEM; driver_data->da9052 = da9052; da9052_wdt = &driver_data->wdt; da9052_wdt->timeout = DA9052_DEF_TIMEOUT; da9052_wdt->info = &da9052_wdt_info; da9052_wdt->ops = &da9052_wdt_ops; da9052_wdt->parent = dev; watchdog_set_drvdata(da9052_wdt, driver_data); ret = da9052_reg_update(da9052, DA9052_CONTROL_D_REG, DA9052_CONTROLD_TWDSCALE, 0); if (ret < 0) { dev_err(dev, "Failed to disable watchdog bits, %d\n", ret); return ret; } ret = devm_watchdog_register_device(dev, &driver_data->wdt); if (ret != 0) { dev_err(da9052->dev, "watchdog_register_device() failed: %d\n", ret); return ret; } return ret; } static struct platform_driver da9052_wdt_driver = { .probe = da9052_wdt_probe, .driver = { .name = "da9052-watchdog", }, }; module_platform_driver(da9052_wdt_driver); MODULE_AUTHOR("Anthony Olech <Anthony.Olech@diasemi.com>"); MODULE_DESCRIPTION("DA9052 SM Device Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:da9052-watchdog");
gpl-2.0
bourroush/blog-17aout
wp-content/themes/thematic/library/extensions/discussion.php
2891
<?php /** * Discussion * * @package ThematicCoreLibrary * @subpackage Discussion */ /** * Custom callback function to list comments in the Thematic style. * * If you want to use your own comments callback for wp_list_comments, filter list_comments_arg * * @param object $comment * @param array $args * @param int $depth */ function thematic_comments($comment, $args, $depth) { $GLOBALS['comment'] = $comment; $GLOBALS['comment_depth'] = $depth; ?> <li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>> <?php // action hook for inserting content above #comment thematic_abovecomment(); ?> <div class="comment-author vcard"><?php thematic_commenter_link() ?></div> <?php thematic_commentmeta(TRUE); ?> <?php if ( $comment->comment_approved == '0' ) { echo "\t\t\t\t\t" . '<span class="unapproved">'; _e( 'Your comment is awaiting moderation', 'thematic' ); echo ".</span>\n"; } ?> <div class="comment-content"> <?php comment_text() ?> </div> <?php // echo the comment reply link with help from Justin Tadlock http://justintadlock.com/ and Will Norris http://willnorris.com/ if( $args['type'] == 'all' || get_comment_type() == 'comment' ) : comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply','thematic' ), 'login_text' => __( 'Log in to reply.','thematic' ), 'depth' => $depth, 'before' => '<div class="comment-reply-link">', 'after' => '</div>' ))); endif; ?> <?php // action hook for inserting content above #comment thematic_belowcomment() ?> <?php } /** * Custom callback to list pings in the Thematic style * * @param object $comment * @param array $args * @param int $depth */ function thematic_pings($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>> <div class="comment-author"><?php printf(_x('By %1$s on %2$s at %3$s', 'By {$authorlink} on {$date} at {$time}', 'thematic'), get_comment_author_link(), get_comment_date(), get_comment_time() ); edit_comment_link(__('Edit', 'thematic'), ' <span class="meta-sep">|</span>' . "\n\n\t\t\t\t\t\t" . '<span class="edit-link">', '</span>'); ?> </div> <?php if ($comment->comment_approved == '0') { echo "\t\t\t\t\t" . '<span class="unapproved">'; _e( 'Your trackback is awaiting moderation', 'thematic' ); echo ".</span>\n"; } ?> <div class="comment-content"> <?php comment_text() ?> </div> <?php }
gpl-2.0
BPI-SINOVOIP/BPI-Mainline-kernel
linux-5.4/drivers/gpu/drm/i915/gt/intel_gt.c
6838
// SPDX-License-Identifier: MIT /* * Copyright © 2019 Intel Corporation */ #include "i915_drv.h" #include "intel_gt.h" #include "intel_gt_pm.h" #include "intel_uncore.h" void intel_gt_init_early(struct intel_gt *gt, struct drm_i915_private *i915) { gt->i915 = i915; gt->uncore = &i915->uncore; spin_lock_init(&gt->irq_lock); INIT_LIST_HEAD(&gt->closed_vma); spin_lock_init(&gt->closed_lock); intel_gt_init_hangcheck(gt); intel_gt_init_reset(gt); intel_gt_pm_init_early(gt); intel_uc_init_early(&gt->uc); } void intel_gt_init_hw(struct drm_i915_private *i915) { i915->gt.ggtt = &i915->ggtt; } static void rmw_set(struct intel_uncore *uncore, i915_reg_t reg, u32 set) { intel_uncore_rmw(uncore, reg, 0, set); } static void rmw_clear(struct intel_uncore *uncore, i915_reg_t reg, u32 clr) { intel_uncore_rmw(uncore, reg, clr, 0); } static void clear_register(struct intel_uncore *uncore, i915_reg_t reg) { intel_uncore_rmw(uncore, reg, 0, 0); } static void gen8_clear_engine_error_register(struct intel_engine_cs *engine) { GEN6_RING_FAULT_REG_RMW(engine, RING_FAULT_VALID, 0); GEN6_RING_FAULT_REG_POSTING_READ(engine); } void intel_gt_clear_error_registers(struct intel_gt *gt, intel_engine_mask_t engine_mask) { struct drm_i915_private *i915 = gt->i915; struct intel_uncore *uncore = gt->uncore; u32 eir; if (!IS_GEN(i915, 2)) clear_register(uncore, PGTBL_ER); if (INTEL_GEN(i915) < 4) clear_register(uncore, IPEIR(RENDER_RING_BASE)); else clear_register(uncore, IPEIR_I965); clear_register(uncore, EIR); eir = intel_uncore_read(uncore, EIR); if (eir) { /* * some errors might have become stuck, * mask them. */ DRM_DEBUG_DRIVER("EIR stuck: 0x%08x, masking\n", eir); rmw_set(uncore, EMR, eir); intel_uncore_write(uncore, GEN2_IIR, I915_MASTER_ERROR_INTERRUPT); } if (INTEL_GEN(i915) >= 12) { rmw_clear(uncore, GEN12_RING_FAULT_REG, RING_FAULT_VALID); intel_uncore_posting_read(uncore, GEN12_RING_FAULT_REG); } else if (INTEL_GEN(i915) >= 8) { rmw_clear(uncore, GEN8_RING_FAULT_REG, RING_FAULT_VALID); intel_uncore_posting_read(uncore, GEN8_RING_FAULT_REG); } else if (INTEL_GEN(i915) >= 6) { struct intel_engine_cs *engine; enum intel_engine_id id; for_each_engine_masked(engine, i915, engine_mask, id) gen8_clear_engine_error_register(engine); } } static void gen6_check_faults(struct intel_gt *gt) { struct intel_engine_cs *engine; enum intel_engine_id id; u32 fault; for_each_engine(engine, gt->i915, id) { fault = GEN6_RING_FAULT_REG_READ(engine); if (fault & RING_FAULT_VALID) { DRM_DEBUG_DRIVER("Unexpected fault\n" "\tAddr: 0x%08lx\n" "\tAddress space: %s\n" "\tSource ID: %d\n" "\tType: %d\n", fault & PAGE_MASK, fault & RING_FAULT_GTTSEL_MASK ? "GGTT" : "PPGTT", RING_FAULT_SRCID(fault), RING_FAULT_FAULT_TYPE(fault)); } } } static void gen8_check_faults(struct intel_gt *gt) { struct intel_uncore *uncore = gt->uncore; i915_reg_t fault_reg, fault_data0_reg, fault_data1_reg; u32 fault; if (INTEL_GEN(gt->i915) >= 12) { fault_reg = GEN12_RING_FAULT_REG; fault_data0_reg = GEN12_FAULT_TLB_DATA0; fault_data1_reg = GEN12_FAULT_TLB_DATA1; } else { fault_reg = GEN8_RING_FAULT_REG; fault_data0_reg = GEN8_FAULT_TLB_DATA0; fault_data1_reg = GEN8_FAULT_TLB_DATA1; } fault = intel_uncore_read(uncore, fault_reg); if (fault & RING_FAULT_VALID) { u32 fault_data0, fault_data1; u64 fault_addr; fault_data0 = intel_uncore_read(uncore, fault_data0_reg); fault_data1 = intel_uncore_read(uncore, fault_data1_reg); fault_addr = ((u64)(fault_data1 & FAULT_VA_HIGH_BITS) << 44) | ((u64)fault_data0 << 12); DRM_DEBUG_DRIVER("Unexpected fault\n" "\tAddr: 0x%08x_%08x\n" "\tAddress space: %s\n" "\tEngine ID: %d\n" "\tSource ID: %d\n" "\tType: %d\n", upper_32_bits(fault_addr), lower_32_bits(fault_addr), fault_data1 & FAULT_GTT_SEL ? "GGTT" : "PPGTT", GEN8_RING_FAULT_ENGINE_ID(fault), RING_FAULT_SRCID(fault), RING_FAULT_FAULT_TYPE(fault)); } } void intel_gt_check_and_clear_faults(struct intel_gt *gt) { struct drm_i915_private *i915 = gt->i915; /* From GEN8 onwards we only have one 'All Engine Fault Register' */ if (INTEL_GEN(i915) >= 8) gen8_check_faults(gt); else if (INTEL_GEN(i915) >= 6) gen6_check_faults(gt); else return; intel_gt_clear_error_registers(gt, ALL_ENGINES); } void intel_gt_flush_ggtt_writes(struct intel_gt *gt) { struct drm_i915_private *i915 = gt->i915; intel_wakeref_t wakeref; /* * No actual flushing is required for the GTT write domain for reads * from the GTT domain. Writes to it "immediately" go to main memory * as far as we know, so there's no chipset flush. It also doesn't * land in the GPU render cache. * * However, we do have to enforce the order so that all writes through * the GTT land before any writes to the device, such as updates to * the GATT itself. * * We also have to wait a bit for the writes to land from the GTT. * An uncached read (i.e. mmio) seems to be ideal for the round-trip * timing. This issue has only been observed when switching quickly * between GTT writes and CPU reads from inside the kernel on recent hw, * and it appears to only affect discrete GTT blocks (i.e. on LLC * system agents we cannot reproduce this behaviour, until Cannonlake * that was!). */ wmb(); if (INTEL_INFO(i915)->has_coherent_ggtt) return; intel_gt_chipset_flush(gt); with_intel_runtime_pm(&i915->runtime_pm, wakeref) { struct intel_uncore *uncore = gt->uncore; spin_lock_irq(&uncore->lock); intel_uncore_posting_read_fw(uncore, RING_HEAD(RENDER_RING_BASE)); spin_unlock_irq(&uncore->lock); } } void intel_gt_chipset_flush(struct intel_gt *gt) { wmb(); if (INTEL_GEN(gt->i915) < 6) intel_gtt_chipset_flush(); } int intel_gt_init_scratch(struct intel_gt *gt, unsigned int size) { struct drm_i915_private *i915 = gt->i915; struct drm_i915_gem_object *obj; struct i915_vma *vma; int ret; obj = i915_gem_object_create_stolen(i915, size); if (!obj) obj = i915_gem_object_create_internal(i915, size); if (IS_ERR(obj)) { DRM_ERROR("Failed to allocate scratch page\n"); return PTR_ERR(obj); } vma = i915_vma_instance(obj, &gt->ggtt->vm, NULL); if (IS_ERR(vma)) { ret = PTR_ERR(vma); goto err_unref; } ret = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH); if (ret) goto err_unref; gt->scratch = i915_vma_make_unshrinkable(vma); return 0; err_unref: i915_gem_object_put(obj); return ret; } void intel_gt_fini_scratch(struct intel_gt *gt) { i915_vma_unpin_and_release(&gt->scratch, 0); } void intel_gt_driver_late_release(struct intel_gt *gt) { intel_uc_driver_late_release(&gt->uc); intel_gt_fini_reset(gt); }
gpl-2.0
mekinney/transparica
webapp/node_modules/express.io/compiled/request.js
1285
// Generated by CoffeeScript 1.4.0 (function() { var RoomIO; RoomIO = require('./room').RoomIO; exports.RequestIO = (function() { function RequestIO(socket, request, io) { this.socket = socket; this.request = request; this.manager = io; } RequestIO.prototype.broadcast = function(event, message) { return this.socket.broadcast.emit(event, message); }; RequestIO.prototype.emit = function(event, message) { return this.socket.emit(event, message); }; RequestIO.prototype.room = function(room) { return new RoomIO(room, this.socket); }; RequestIO.prototype.join = function(room) { return this.socket.join(room); }; RequestIO.prototype.route = function(route) { return this.manager.route(route, this.request, { trigger: true }); }; RequestIO.prototype.leave = function(room) { return this.socket.leave(room); }; RequestIO.prototype.on = function() { var args; args = Array.prototype.slice.call(arguments, 0); return this.sockets.on.apply(this.socket, args); }; RequestIO.prototype.disconnect = function(callback) { return this.socket.disconnect(callback); }; return RequestIO; })(); }).call(this);
gpl-2.0
md-5/jdk10
test/jdk/java/awt/datatransfer/DataFlavor/MimeTypeSerializationTest.java
3301
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @bug 4116781 @summary Tests that long (more than 64K) MimeType can be serialized and deserialized. @author gas@sparc.spb.su area=datatransfer @modules java.datatransfer @run main MimeTypeSerializationTest */ import java.awt.datatransfer.DataFlavor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; public class MimeTypeSerializationTest { public static void main(String[] args) throws Exception { boolean failed = false; try { int len = 70000; char[] longValue = new char[len]; Arrays.fill(longValue, 'v'); DataFlavor longdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=java.lang.String; longParameter=" + new String(longValue)); DataFlavor shortdf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=java.lang.String"); ByteArrayOutputStream baos = new ByteArrayOutputStream(100000); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(longdf); oos.writeObject(shortdf); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); DataFlavor longdf2 = (DataFlavor) ois.readObject(); DataFlavor shortdf2 = (DataFlavor) ois.readObject(); ois.close(); failed = !( longdf.getMimeType().equals(longdf2.getMimeType()) && shortdf.getMimeType().equals(shortdf2.getMimeType()) ); if (failed) { System.err.println("deserialized MIME type does not match original one"); } } catch (IOException e) { failed = true; e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (failed) { throw new RuntimeException("test failed: serialization attempt failed"); } else { System.err.println("test passed"); } } }
gpl-2.0
muet/Espruino
libs/filesystem/fat_sd/fattime.c
424
/* Martin Thomas 4/2009 */ #include "integer.h" #include "fattime.h" //#include "rtc.h" DWORD get_fattime (void) { DWORD res; /*RTC_t rtc; rtc_gettime( &rtc );*/ res = (((DWORD)2012/*rtc.year*/ - 1980) << 25) | ((DWORD)1/*rtc.month*/ << 21) | ((DWORD)1/*rtc.mday*/ << 16) | (WORD)(0/*rtc.hour*/ << 11) | (WORD)(0/*rtc.min*/ << 5) | (WORD)(0/*rtc.sec*/ >> 1); return res; }
mpl-2.0
mjs/juju
cmd/juju/interact/package_test.go
211
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package interact import ( "testing" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) }
agpl-3.0
sergiocorato/project-service
project_sla/__init__.py
191
# -*- coding: utf-8 -*- from . import project_sla from . import analytic_account from . import project_sla_control from . import project_issue from . import project_task from . import report
agpl-3.0
zhushuchen/Ocean
组件/zookeeper-3.3.6/src/c/include/recordio.h
2912
/** * 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. */ #ifndef __RECORDIO_H__ #define __RECORDIO_H__ #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif struct buffer { int32_t len; char *buff; }; void deallocate_String(char **s); void deallocate_Buffer(struct buffer *b); void deallocate_vector(void *d); struct iarchive { int (*start_record)(struct iarchive *ia, const char *tag); int (*end_record)(struct iarchive *ia, const char *tag); int (*start_vector)(struct iarchive *ia, const char *tag, int32_t *count); int (*end_vector)(struct iarchive *ia, const char *tag); int (*deserialize_Bool)(struct iarchive *ia, const char *name, int32_t *); int (*deserialize_Int)(struct iarchive *ia, const char *name, int32_t *); int (*deserialize_Long)(struct iarchive *ia, const char *name, int64_t *); int (*deserialize_Buffer)(struct iarchive *ia, const char *name, struct buffer *); int (*deserialize_String)(struct iarchive *ia, const char *name, char **); void *priv; }; struct oarchive { int (*start_record)(struct oarchive *oa, const char *tag); int (*end_record)(struct oarchive *oa, const char *tag); int (*start_vector)(struct oarchive *oa, const char *tag, const int32_t *count); int (*end_vector)(struct oarchive *oa, const char *tag); int (*serialize_Bool)(struct oarchive *oa, const char *name, const int32_t *); int (*serialize_Int)(struct oarchive *oa, const char *name, const int32_t *); int (*serialize_Long)(struct oarchive *oa, const char *name, const int64_t *); int (*serialize_Buffer)(struct oarchive *oa, const char *name, const struct buffer *); int (*serialize_String)(struct oarchive *oa, const char *name, char **); void *priv; }; struct oarchive *create_buffer_oarchive(void); void close_buffer_oarchive(struct oarchive **oa, int free_buffer); struct iarchive *create_buffer_iarchive(char *buffer, int len); void close_buffer_iarchive(struct iarchive **ia); char *get_buffer(struct oarchive *); int get_buffer_len(struct oarchive *); int64_t htonll(int64_t v); #ifdef __cplusplus } #endif #endif
agpl-3.0
rdhyee/osf.io
scripts/tests/test_remove_wiki_title_forward_slashes.py
1335
from nose.tools import * from framework.mongo import database as db from scripts.remove_wiki_title_forward_slashes import main from tests.base import OsfTestCase from tests.factories import NodeWikiFactory, ProjectFactory class TestRemoveWikiTitleForwardSlashes(OsfTestCase): def test_forward_slash_is_removed_from_wiki_title(self): project = ProjectFactory() wiki = NodeWikiFactory(node=project) invalid_name = 'invalid/name' db.nodewikipage.update({'_id': wiki._id}, {'$set': {'page_name': invalid_name}}) project.wiki_pages_current['invalid/name'] = project.wiki_pages_current[wiki.page_name] project.wiki_pages_versions['invalid/name'] = project.wiki_pages_versions[wiki.page_name] project.save() main() wiki.reload() assert_equal(wiki.page_name, 'invalidname') assert_in('invalidname', project.wiki_pages_current) assert_in('invalidname', project.wiki_pages_versions) def test_valid_wiki_title(self): project = ProjectFactory() wiki = NodeWikiFactory(node=project) page_name = wiki.page_name main() wiki.reload() assert_equal(page_name, wiki.page_name) assert_in(page_name, project.wiki_pages_current) assert_in(page_name, project.wiki_pages_versions)
apache-2.0
dialoghq/runit
test/kitchen/cookbooks/runit_test/metadata.rb
258
name "runit_test" maintainer "Opscode, Inc." maintainer_email "cookbooks@opscode.com" license "Apache 2.0" description "This cookbook is used with test-kitchen to test the parent, runit cookbok" version "1.0.0"
apache-2.0
JasOXIII/sagetv
third_party/ffmpeg/libavcodec/i386/mathops.h
1481
/* * simple math operations * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> et al * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FFMPEG_I386_MATHOPS_H #define FFMPEG_I386_MATHOPS_H #ifdef FRAC_BITS # define MULL(ra, rb) \ ({ int rt, dummy; asm (\ "imull %3 \n\t"\ "shrdl %4, %%edx, %%eax \n\t"\ : "=a"(rt), "=d"(dummy)\ : "a" (ra), "rm" (rb), "i"(FRAC_BITS));\ rt; }) #endif #define MULH(ra, rb) \ ({ int rt, dummy;\ asm ("imull %3\n\t" : "=d"(rt), "=a"(dummy): "a" (ra), "rm" (rb));\ rt; }) #define MUL64(ra, rb) \ ({ int64_t rt;\ asm ("imull %2\n\t" : "=A"(rt) : "a" (ra), "g" (rb));\ rt; }) #endif /* FFMPEG_I386_MATHOPS_H */
apache-2.0
xanzy/terraform-provider-cosmic
vendor/github.com/hashicorp/go-hclog/int.go
11348
package hclog import ( "bufio" "bytes" "encoding" "encoding/json" "fmt" "log" "os" "reflect" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" ) var ( _levelToBracket = map[Level]string{ Debug: "[DEBUG]", Trace: "[TRACE]", Info: "[INFO] ", Warn: "[WARN] ", Error: "[ERROR]", } ) // Given the options (nil for defaults), create a new Logger func New(opts *LoggerOptions) Logger { if opts == nil { opts = &LoggerOptions{} } output := opts.Output if output == nil { output = os.Stderr } level := opts.Level if level == NoLevel { level = DefaultLevel } mtx := opts.Mutex if mtx == nil { mtx = new(sync.Mutex) } ret := &intLogger{ m: mtx, json: opts.JSONFormat, caller: opts.IncludeLocation, name: opts.Name, timeFormat: TimeFormat, w: bufio.NewWriter(output), level: new(int32), } if opts.TimeFormat != "" { ret.timeFormat = opts.TimeFormat } atomic.StoreInt32(ret.level, int32(level)) return ret } // The internal logger implementation. Internal in that it is defined entirely // by this package. type intLogger struct { json bool caller bool name string timeFormat string // this is a pointer so that it's shared by any derived loggers, since // those derived loggers share the bufio.Writer as well. m *sync.Mutex w *bufio.Writer level *int32 implied []interface{} } // Make sure that intLogger is a Logger var _ Logger = &intLogger{} // The time format to use for logging. This is a version of RFC3339 that // contains millisecond precision const TimeFormat = "2006-01-02T15:04:05.000Z0700" // Log a message and a set of key/value pairs if the given level is at // or more severe that the threshold configured in the Logger. func (z *intLogger) Log(level Level, msg string, args ...interface{}) { if level < Level(atomic.LoadInt32(z.level)) { return } t := time.Now() z.m.Lock() defer z.m.Unlock() if z.json { z.logJson(t, level, msg, args...) } else { z.log(t, level, msg, args...) } z.w.Flush() } // Cleanup a path by returning the last 2 segments of the path only. func trimCallerPath(path string) string { // lovely borrowed from zap // nb. To make sure we trim the path correctly on Windows too, we // counter-intuitively need to use '/' and *not* os.PathSeparator here, // because the path given originates from Go stdlib, specifically // runtime.Caller() which (as of Mar/17) returns forward slashes even on // Windows. // // See https://github.com/golang/go/issues/3335 // and https://github.com/golang/go/issues/18151 // // for discussion on the issue on Go side. // // Find the last separator. // idx := strings.LastIndexByte(path, '/') if idx == -1 { return path } // Find the penultimate separator. idx = strings.LastIndexByte(path[:idx], '/') if idx == -1 { return path } return path[idx+1:] } // Non-JSON logging format function func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) { z.w.WriteString(t.Format(z.timeFormat)) z.w.WriteByte(' ') s, ok := _levelToBracket[level] if ok { z.w.WriteString(s) } else { z.w.WriteString("[?????]") } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { z.w.WriteByte(' ') z.w.WriteString(trimCallerPath(file)) z.w.WriteByte(':') z.w.WriteString(strconv.Itoa(line)) z.w.WriteByte(':') } } z.w.WriteByte(' ') if z.name != "" { z.w.WriteString(z.name) z.w.WriteString(": ") } z.w.WriteString(msg) args = append(z.implied, args...) var stacktrace CapturedStacktrace if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] stacktrace = cs } else { args = append(args, "<unknown>") } } z.w.WriteByte(':') FOR: for i := 0; i < len(args); i = i + 2 { var ( val string raw bool ) switch st := args[i+1].(type) { case string: val = st case int: val = strconv.FormatInt(int64(st), 10) case int64: val = strconv.FormatInt(int64(st), 10) case int32: val = strconv.FormatInt(int64(st), 10) case int16: val = strconv.FormatInt(int64(st), 10) case int8: val = strconv.FormatInt(int64(st), 10) case uint: val = strconv.FormatUint(uint64(st), 10) case uint64: val = strconv.FormatUint(uint64(st), 10) case uint32: val = strconv.FormatUint(uint64(st), 10) case uint16: val = strconv.FormatUint(uint64(st), 10) case uint8: val = strconv.FormatUint(uint64(st), 10) case CapturedStacktrace: stacktrace = st continue FOR case Format: val = fmt.Sprintf(st[0].(string), st[1:]...) default: v := reflect.ValueOf(st) if v.Kind() == reflect.Slice { val = z.renderSlice(v) raw = true } else { val = fmt.Sprintf("%v", st) } } z.w.WriteByte(' ') z.w.WriteString(args[i].(string)) z.w.WriteByte('=') if !raw && strings.ContainsAny(val, " \t\n\r") { z.w.WriteByte('"') z.w.WriteString(val) z.w.WriteByte('"') } else { z.w.WriteString(val) } } } z.w.WriteString("\n") if stacktrace != "" { z.w.WriteString(string(stacktrace)) } } func (z *intLogger) renderSlice(v reflect.Value) string { var buf bytes.Buffer buf.WriteRune('[') for i := 0; i < v.Len(); i++ { if i > 0 { buf.WriteString(", ") } sv := v.Index(i) var val string switch sv.Kind() { case reflect.String: val = sv.String() case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64: val = strconv.FormatInt(sv.Int(), 10) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: val = strconv.FormatUint(sv.Uint(), 10) default: val = fmt.Sprintf("%v", sv.Interface()) } if strings.ContainsAny(val, " \t\n\r") { buf.WriteByte('"') buf.WriteString(val) buf.WriteByte('"') } else { buf.WriteString(val) } } buf.WriteRune(']') return buf.String() } // JSON logging function func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) { vals := map[string]interface{}{ "@message": msg, "@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"), } var levelStr string switch level { case Error: levelStr = "error" case Warn: levelStr = "warn" case Info: levelStr = "info" case Debug: levelStr = "debug" case Trace: levelStr = "trace" default: levelStr = "all" } vals["@level"] = levelStr if z.name != "" { vals["@module"] = z.name } if z.caller { if _, file, line, ok := runtime.Caller(3); ok { vals["@caller"] = fmt.Sprintf("%s:%d", file, line) } } args = append(z.implied, args...) if args != nil && len(args) > 0 { if len(args)%2 != 0 { cs, ok := args[len(args)-1].(CapturedStacktrace) if ok { args = args[:len(args)-1] vals["stacktrace"] = cs } else { args = append(args, "<unknown>") } } for i := 0; i < len(args); i = i + 2 { if _, ok := args[i].(string); !ok { // As this is the logging function not much we can do here // without injecting into logs... continue } val := args[i+1] switch sv := val.(type) { case error: // Check if val is of type error. If error type doesn't // implement json.Marshaler or encoding.TextMarshaler // then set val to err.Error() so that it gets marshaled switch sv.(type) { case json.Marshaler, encoding.TextMarshaler: default: val = sv.Error() } case Format: val = fmt.Sprintf(sv[0].(string), sv[1:]...) } vals[args[i].(string)] = val } } err := json.NewEncoder(z.w).Encode(vals) if err != nil { panic(err) } } // Emit the message and args at DEBUG level func (z *intLogger) Debug(msg string, args ...interface{}) { z.Log(Debug, msg, args...) } // Emit the message and args at TRACE level func (z *intLogger) Trace(msg string, args ...interface{}) { z.Log(Trace, msg, args...) } // Emit the message and args at INFO level func (z *intLogger) Info(msg string, args ...interface{}) { z.Log(Info, msg, args...) } // Emit the message and args at WARN level func (z *intLogger) Warn(msg string, args ...interface{}) { z.Log(Warn, msg, args...) } // Emit the message and args at ERROR level func (z *intLogger) Error(msg string, args ...interface{}) { z.Log(Error, msg, args...) } // Indicate that the logger would emit TRACE level logs func (z *intLogger) IsTrace() bool { return Level(atomic.LoadInt32(z.level)) == Trace } // Indicate that the logger would emit DEBUG level logs func (z *intLogger) IsDebug() bool { return Level(atomic.LoadInt32(z.level)) <= Debug } // Indicate that the logger would emit INFO level logs func (z *intLogger) IsInfo() bool { return Level(atomic.LoadInt32(z.level)) <= Info } // Indicate that the logger would emit WARN level logs func (z *intLogger) IsWarn() bool { return Level(atomic.LoadInt32(z.level)) <= Warn } // Indicate that the logger would emit ERROR level logs func (z *intLogger) IsError() bool { return Level(atomic.LoadInt32(z.level)) <= Error } // Return a sub-Logger for which every emitted log message will contain // the given key/value pairs. This is used to create a context specific // Logger. func (z *intLogger) With(args ...interface{}) Logger { if len(args)%2 != 0 { panic("With() call requires paired arguments") } var nz intLogger = *z result := make(map[string]interface{}, len(z.implied)+len(args)) keys := make([]string, 0, len(z.implied)+len(args)) // Read existing args, store map and key for consistent sorting for i := 0; i < len(z.implied); i += 2 { key := z.implied[i].(string) keys = append(keys, key) result[key] = z.implied[i+1] } // Read new args, store map and key for consistent sorting for i := 0; i < len(args); i += 2 { key := args[i].(string) _, exists := result[key] if !exists { keys = append(keys, key) } result[key] = args[i+1] } // Sort keys to be consistent sort.Strings(keys) nz.implied = make([]interface{}, 0, len(z.implied)+len(args)) for _, k := range keys { nz.implied = append(nz.implied, k) nz.implied = append(nz.implied, result[k]) } return &nz } // Create a new sub-Logger that a name decending from the current name. // This is used to create a subsystem specific Logger. func (z *intLogger) Named(name string) Logger { var nz intLogger = *z if nz.name != "" { nz.name = nz.name + "." + name } else { nz.name = name } return &nz } // Create a new sub-Logger with an explicit name. This ignores the current // name. This is used to create a standalone logger that doesn't fall // within the normal hierarchy. func (z *intLogger) ResetNamed(name string) Logger { var nz intLogger = *z nz.name = name return &nz } // Update the logging level on-the-fly. This will affect all subloggers as // well. func (z *intLogger) SetLevel(level Level) { atomic.StoreInt32(z.level, int32(level)) } // Create a *log.Logger that will send it's data through this Logger. This // allows packages that expect to be using the standard library log to actually // use this logger. func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger { if opts == nil { opts = &StandardLoggerOptions{} } return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0) }
apache-2.0
paladique/roslyn
src/Compilers/Test/Resources/Core/SymbolsTests/V2/V2.Designer.vb
6546
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18326 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace TestResources.SymbolsTests 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Public Class V2 Private Shared resourceMan As Global.System.Resources.ResourceManager Private Shared resourceCulture As Global.System.Globalization.CultureInfo <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend Sub New() MyBase.New End Sub '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Public Shared ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("V2", GetType(V2).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Public Shared Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' Looks up a localized resource of type System.Byte[]. '''</summary> Public Shared ReadOnly Property MTTestLib1() As Byte() Get Dim obj As Object = ResourceManager.GetObject("MTTestLib1", resourceCulture) Return CType(obj,Byte()) End Get End Property '''<summary> ''' Looks up a localized string similar to &apos;vbc /t:library /out:MTTestLib1.Dll MTTestLib1_V2.vb '''&apos;vbc /t:module /out:MTTestModule1.netmodule MTTestLib1_V2.vb ''' '''&lt;Assembly: System.Reflection.AssemblyVersion(&quot;2.0.0.0&quot;)&gt; '''&lt;Assembly: System.Reflection.AssemblyFileVersion(&quot;2.0.0.0&quot;)&gt; ''' '''Public Class Class1 ''' '''End Class ''' '''Public Class Class2 ''' '''End Class ''' '''Public Delegate Sub Delegate1() ''' '''Public Interface Interface1 ''' Sub Method1() &apos; same as V1 ''' &apos; Sub Method2() &apos; removed since V1 ''' Sub Method3(x As Integer) &apos; different param type in V2 ''' [rest of string was truncated]&quot;;. '''</summary> Public Shared ReadOnly Property MTTestLib1_V2() As String Get Return ResourceManager.GetString("MTTestLib1_V2", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Byte[]. '''</summary> Public Shared ReadOnly Property MTTestLib3() As Byte() Get Dim obj As Object = ResourceManager.GetObject("MTTestLib3", resourceCulture) Return CType(obj,Byte()) End Get End Property '''<summary> ''' Looks up a localized string similar to &apos; vbc /t:Library /out:MTTestLib3.Dll MTTestLib3_V2.vb /r:MTTestLib1.Dll /r:..\V1\MTTestLib2.Dll '''&apos; vbc /t:module /out:MTTestModule3.netmodule MTTestLib3_V2.vb /r:MTTestLib1.Dll /r:..\V1\MTTestLib2.Dll ''' '''Public Class Class5 ''' Function Foo1() As Class1 ''' Return Nothing ''' End Function ''' ''' Function Foo2() As Class2 ''' Return Nothing ''' End Function ''' ''' Function Foo3() As Class4 ''' Return Nothing ''' End Function ''' ''' Public Bar1 As Class1 ''' Public Bar2 As Class2 ''' Publ [rest of string was truncated]&quot;;. '''</summary> Public Shared ReadOnly Property MTTestLib3_V2() As String Get Return ResourceManager.GetString("MTTestLib3_V2", resourceCulture) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Byte[]. '''</summary> Public Shared ReadOnly Property MTTestModule1() As Byte() Get Dim obj As Object = ResourceManager.GetObject("MTTestModule1", resourceCulture) Return CType(obj,Byte()) End Get End Property '''<summary> ''' Looks up a localized resource of type System.Byte[]. '''</summary> Public Shared ReadOnly Property MTTestModule3() As Byte() Get Dim obj As Object = ResourceManager.GetObject("MTTestModule3", resourceCulture) Return CType(obj,Byte()) End Get End Property End Class End Namespace
apache-2.0
victorgp/kubernetes
pkg/controller/podautoscaler/horizontal.go
33818
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package podautoscaler import ( "fmt" "math" "time" "github.com/golang/glog" autoscalingv1 "k8s.io/api/autoscaling/v1" autoscalingv2 "k8s.io/api/autoscaling/v2beta1" "k8s.io/api/core/v1" apiequality "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" autoscalinginformers "k8s.io/client-go/informers/autoscaling/v1" "k8s.io/client-go/kubernetes/scheme" autoscalingclient "k8s.io/client-go/kubernetes/typed/autoscaling/v1" v1core "k8s.io/client-go/kubernetes/typed/core/v1" autoscalinglisters "k8s.io/client-go/listers/autoscaling/v1" scaleclient "k8s.io/client-go/scale" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/record" "k8s.io/client-go/util/workqueue" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/controller" ) var ( scaleUpLimitFactor = 2.0 scaleUpLimitMinimum = 4.0 ) // HorizontalController is responsible for the synchronizing HPA objects stored // in the system with the actual deployments/replication controllers they // control. type HorizontalController struct { scaleNamespacer scaleclient.ScalesGetter hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter mapper apimeta.RESTMapper replicaCalc *ReplicaCalculator eventRecorder record.EventRecorder upscaleForbiddenWindow time.Duration downscaleForbiddenWindow time.Duration // hpaLister is able to list/get HPAs from the shared cache from the informer passed in to // NewHorizontalController. hpaLister autoscalinglisters.HorizontalPodAutoscalerLister hpaListerSynced cache.InformerSynced // Controllers that need to be synced queue workqueue.RateLimitingInterface } // NewHorizontalController creates a new HorizontalController. func NewHorizontalController( evtNamespacer v1core.EventsGetter, scaleNamespacer scaleclient.ScalesGetter, hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter, mapper apimeta.RESTMapper, replicaCalc *ReplicaCalculator, hpaInformer autoscalinginformers.HorizontalPodAutoscalerInformer, resyncPeriod time.Duration, upscaleForbiddenWindow time.Duration, downscaleForbiddenWindow time.Duration, ) *HorizontalController { broadcaster := record.NewBroadcaster() broadcaster.StartLogging(glog.Infof) broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: evtNamespacer.Events("")}) recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "horizontal-pod-autoscaler"}) hpaController := &HorizontalController{ replicaCalc: replicaCalc, eventRecorder: recorder, scaleNamespacer: scaleNamespacer, hpaNamespacer: hpaNamespacer, upscaleForbiddenWindow: upscaleForbiddenWindow, downscaleForbiddenWindow: downscaleForbiddenWindow, queue: workqueue.NewNamedRateLimitingQueue(NewDefaultHPARateLimiter(resyncPeriod), "horizontalpodautoscaler"), mapper: mapper, } hpaInformer.Informer().AddEventHandlerWithResyncPeriod( cache.ResourceEventHandlerFuncs{ AddFunc: hpaController.enqueueHPA, UpdateFunc: hpaController.updateHPA, DeleteFunc: hpaController.deleteHPA, }, resyncPeriod, ) hpaController.hpaLister = hpaInformer.Lister() hpaController.hpaListerSynced = hpaInformer.Informer().HasSynced return hpaController } // Run begins watching and syncing. func (a *HorizontalController) Run(stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer a.queue.ShutDown() glog.Infof("Starting HPA controller") defer glog.Infof("Shutting down HPA controller") if !controller.WaitForCacheSync("HPA", stopCh, a.hpaListerSynced) { return } // start a single worker (we may wish to start more in the future) go wait.Until(a.worker, time.Second, stopCh) <-stopCh } // obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item. func (a *HorizontalController) updateHPA(old, cur interface{}) { a.enqueueHPA(cur) } // obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item. func (a *HorizontalController) enqueueHPA(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err)) return } // always add rate-limitted so we don't fetch metrics more that once per resync interval a.queue.AddRateLimited(key) } func (a *HorizontalController) deleteHPA(obj interface{}) { key, err := controller.KeyFunc(obj) if err != nil { utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err)) return } // TODO: could we leak if we fail to get the key? a.queue.Forget(key) } func (a *HorizontalController) worker() { for a.processNextWorkItem() { } glog.Infof("horizontal pod autoscaler controller worker shutting down") } func (a *HorizontalController) processNextWorkItem() bool { key, quit := a.queue.Get() if quit { return false } defer a.queue.Done(key) err := a.reconcileKey(key.(string)) if err == nil { // don't "forget" here because we want to only process a given HPA once per resync interval return true } a.queue.AddRateLimited(key) utilruntime.HandleError(err) return true } // Computes the desired number of replicas for the metric specifications listed in the HPA, returning the maximum // of the computed replica counts, a description of the associated metric, and the statuses of all metrics // computed. func (a *HorizontalController) computeReplicasForMetrics(hpa *autoscalingv2.HorizontalPodAutoscaler, scale *autoscalingv1.Scale, metricSpecs []autoscalingv2.MetricSpec) (replicas int32, metric string, statuses []autoscalingv2.MetricStatus, timestamp time.Time, err error) { currentReplicas := scale.Status.Replicas statuses = make([]autoscalingv2.MetricStatus, len(metricSpecs)) for i, metricSpec := range metricSpecs { if scale.Status.Selector == "" { errMsg := "selector is required" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "SelectorRequired", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", "the HPA target's scale is missing a selector") return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } selector, err := labels.Parse(scale.Status.Selector) if err != nil { errMsg := fmt.Sprintf("couldn't convert selector into a corresponding internal selector object: %v", err) a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidSelector", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } var replicaCountProposal int32 var utilizationProposal int64 var timestampProposal time.Time var metricNameProposal string switch metricSpec.Type { case autoscalingv2.ObjectMetricSourceType: replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetObjectMetricReplicas(currentReplicas, metricSpec.Object.TargetValue.MilliValue(), metricSpec.Object.MetricName, hpa.Namespace, &metricSpec.Object.Target, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetObjectMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetObjectMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get object metric value: %v", err) } metricNameProposal = fmt.Sprintf("%s metric %s", metricSpec.Object.Target.Kind, metricSpec.Object.MetricName) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ObjectMetricSourceType, Object: &autoscalingv2.ObjectMetricStatus{ Target: metricSpec.Object.Target, MetricName: metricSpec.Object.MetricName, CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } case autoscalingv2.PodsMetricSourceType: replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetMetricReplicas(currentReplicas, metricSpec.Pods.TargetAverageValue.MilliValue(), metricSpec.Pods.MetricName, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetPodsMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetPodsMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get pods metric value: %v", err) } metricNameProposal = fmt.Sprintf("pods metric %s", metricSpec.Pods.MetricName) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.PodsMetricSourceType, Pods: &autoscalingv2.PodsMetricStatus{ MetricName: metricSpec.Pods.MetricName, CurrentAverageValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } case autoscalingv2.ResourceMetricSourceType: if metricSpec.Resource.TargetAverageValue != nil { var rawProposal int64 replicaCountProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetRawResourceReplicas(currentReplicas, metricSpec.Resource.TargetAverageValue.MilliValue(), metricSpec.Resource.Name, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err) } metricNameProposal = fmt.Sprintf("%s resource", metricSpec.Resource.Name) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ResourceMetricSourceType, Resource: &autoscalingv2.ResourceMetricStatus{ Name: metricSpec.Resource.Name, CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI), }, } } else { // set a default utilization percentage if none is set if metricSpec.Resource.TargetAverageUtilization == nil { errMsg := "invalid resource metric source: neither a utilization target nor a value target was set" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %s", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } targetUtilization := *metricSpec.Resource.TargetAverageUtilization var percentageProposal int32 var rawProposal int64 replicaCountProposal, percentageProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetResourceReplicas(currentReplicas, targetUtilization, metricSpec.Resource.Name, hpa.Namespace, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err) } metricNameProposal = fmt.Sprintf("%s resource utilization (percentage of request)", metricSpec.Resource.Name) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ResourceMetricSourceType, Resource: &autoscalingv2.ResourceMetricStatus{ Name: metricSpec.Resource.Name, CurrentAverageUtilization: &percentageProposal, CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI), }, } } case autoscalingv2.ExternalMetricSourceType: if metricSpec.External.TargetAverageValue != nil { replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalPerPodMetricReplicas(currentReplicas, metricSpec.External.TargetAverageValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s external metric: %v", metricSpec.External.MetricName, err) } metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ExternalMetricSourceType, External: &autoscalingv2.ExternalMetricStatus{ MetricSelector: metricSpec.External.MetricSelector, MetricName: metricSpec.External.MetricName, CurrentAverageValue: resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } } else if metricSpec.External.TargetValue != nil { replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalMetricReplicas(currentReplicas, metricSpec.External.TargetValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector, selector) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error()) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf("failed to get external metric %s: %v", metricSpec.External.MetricName, err) } metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector) statuses[i] = autoscalingv2.MetricStatus{ Type: autoscalingv2.ExternalMetricSourceType, External: &autoscalingv2.ExternalMetricStatus{ MetricSelector: metricSpec.External.MetricSelector, MetricName: metricSpec.External.MetricName, CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI), }, } } else { errMsg := "invalid external metric source: neither a value target nor an average value target was set" a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } default: errMsg := fmt.Sprintf("unknown metric source type %q", string(metricSpec.Type)) a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidMetricSourceType", errMsg) setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidMetricSourceType", "the HPA was unable to compute the replica count: %s", errMsg) return 0, "", nil, time.Time{}, fmt.Errorf(errMsg) } if replicas == 0 || replicaCountProposal > replicas { timestamp = timestampProposal replicas = replicaCountProposal metric = metricNameProposal } } setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionTrue, "ValidMetricFound", "the HPA was able to successfully calculate a replica count from %s", metric) return replicas, metric, statuses, timestamp, nil } func (a *HorizontalController) reconcileKey(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { return err } hpa, err := a.hpaLister.HorizontalPodAutoscalers(namespace).Get(name) if errors.IsNotFound(err) { glog.Infof("Horizontal Pod Autoscaler has been deleted %v", key) return nil } return a.reconcileAutoscaler(hpa) } func (a *HorizontalController) reconcileAutoscaler(hpav1Shared *autoscalingv1.HorizontalPodAutoscaler) error { // make a copy so that we never mutate the shared informer cache (conversion can mutate the object) hpav1 := hpav1Shared.DeepCopy() // then, convert to autoscaling/v2, which makes our lives easier when calculating metrics hpaRaw, err := unsafeConvertToVersionVia(hpav1, autoscalingv2.SchemeGroupVersion) if err != nil { a.eventRecorder.Event(hpav1, v1.EventTypeWarning, "FailedConvertHPA", err.Error()) return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err) } hpa := hpaRaw.(*autoscalingv2.HorizontalPodAutoscaler) hpaStatusOriginal := hpa.Status.DeepCopy() reference := fmt.Sprintf("%s/%s/%s", hpa.Spec.ScaleTargetRef.Kind, hpa.Namespace, hpa.Spec.ScaleTargetRef.Name) targetGV, err := schema.ParseGroupVersion(hpa.Spec.ScaleTargetRef.APIVersion) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("invalid API version in scale target reference: %v", err) } targetGK := schema.GroupKind{ Group: targetGV.Group, Kind: hpa.Spec.ScaleTargetRef.Kind, } mappings, err := a.mapper.RESTMappings(targetGK) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("unable to determine resource for scale target reference: %v", err) } scale, targetGR, err := a.scaleForResourceMappings(hpa.Namespace, hpa.Spec.ScaleTargetRef.Name, mappings) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err) a.updateStatusIfNeeded(hpaStatusOriginal, hpa) return fmt.Errorf("failed to query scale subresource for %s: %v", reference, err) } setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededGetScale", "the HPA controller was able to get the target's current scale") currentReplicas := scale.Status.Replicas var metricStatuses []autoscalingv2.MetricStatus metricDesiredReplicas := int32(0) metricName := "" metricTimestamp := time.Time{} desiredReplicas := int32(0) rescaleReason := "" timestamp := time.Now() rescale := true if scale.Spec.Replicas == 0 { // Autoscaling is disabled for this resource desiredReplicas = 0 rescale = false setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "ScalingDisabled", "scaling is disabled since the replica count of the target is zero") } else if currentReplicas > hpa.Spec.MaxReplicas { rescaleReason = "Current number of replicas above Spec.MaxReplicas" desiredReplicas = hpa.Spec.MaxReplicas } else if hpa.Spec.MinReplicas != nil && currentReplicas < *hpa.Spec.MinReplicas { rescaleReason = "Current number of replicas below Spec.MinReplicas" desiredReplicas = *hpa.Spec.MinReplicas } else if currentReplicas == 0 { rescaleReason = "Current number of replicas must be greater than 0" desiredReplicas = 1 } else { metricDesiredReplicas, metricName, metricStatuses, metricTimestamp, err = a.computeReplicasForMetrics(hpa, scale, hpa.Spec.Metrics) if err != nil { a.setCurrentReplicasInStatus(hpa, currentReplicas) if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil { utilruntime.HandleError(err) } a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedComputeMetricsReplicas", err.Error()) return fmt.Errorf("failed to compute desired number of replicas based on listed metrics for %s: %v", reference, err) } glog.V(4).Infof("proposing %v desired replicas (based on %s from %s) for %s", metricDesiredReplicas, metricName, timestamp, reference) rescaleMetric := "" if metricDesiredReplicas > desiredReplicas { desiredReplicas = metricDesiredReplicas timestamp = metricTimestamp rescaleMetric = metricName } if desiredReplicas > currentReplicas { rescaleReason = fmt.Sprintf("%s above target", rescaleMetric) } if desiredReplicas < currentReplicas { rescaleReason = "All metrics below target" } desiredReplicas = a.normalizeDesiredReplicas(hpa, currentReplicas, desiredReplicas) rescale = a.shouldScale(hpa, currentReplicas, desiredReplicas, timestamp) backoffDown := false backoffUp := false if hpa.Status.LastScaleTime != nil { if !hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffDownscale", "the time since the previous scale is still within the downscale forbidden window") backoffDown = true } if !hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) { backoffUp = true if backoffDown { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffBoth", "the time since the previous scale is still within both the downscale and upscale forbidden windows") } else { setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffUpscale", "the time since the previous scale is still within the upscale forbidden window") } } } if !backoffDown && !backoffUp { // mark that we're not backing off setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "ReadyForNewScale", "the last scale time was sufficiently old as to warrant a new scale") } } if rescale { scale.Spec.Replicas = desiredReplicas _, err = a.scaleNamespacer.Scales(hpa.Namespace).Update(targetGR, scale) if err != nil { a.eventRecorder.Eventf(hpa, v1.EventTypeWarning, "FailedRescale", "New size: %d; reason: %s; error: %v", desiredReplicas, rescaleReason, err.Error()) setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedUpdateScale", "the HPA controller was unable to update the target scale: %v", err) a.setCurrentReplicasInStatus(hpa, currentReplicas) if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil { utilruntime.HandleError(err) } return fmt.Errorf("failed to rescale %s: %v", reference, err) } setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededRescale", "the HPA controller was able to update the target scale to %d", desiredReplicas) a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "SuccessfulRescale", "New size: %d; reason: %s", desiredReplicas, rescaleReason) glog.Infof("Successful rescale of %s, old size: %d, new size: %d, reason: %s", hpa.Name, currentReplicas, desiredReplicas, rescaleReason) } else { glog.V(4).Infof("decided not to scale %s to %v (last scale time was %s)", reference, desiredReplicas, hpa.Status.LastScaleTime) desiredReplicas = currentReplicas } a.setStatus(hpa, currentReplicas, desiredReplicas, metricStatuses, rescale) return a.updateStatusIfNeeded(hpaStatusOriginal, hpa) } // normalizeDesiredReplicas takes the metrics desired replicas value and normalizes it based on the appropriate conditions (i.e. < maxReplicas, > // minReplicas, etc...) func (a *HorizontalController) normalizeDesiredReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32, prenormalizedDesiredReplicas int32) int32 { var minReplicas int32 if hpa.Spec.MinReplicas != nil { minReplicas = *hpa.Spec.MinReplicas } else { minReplicas = 0 } desiredReplicas, condition, reason := convertDesiredReplicasWithRules(currentReplicas, prenormalizedDesiredReplicas, minReplicas, hpa.Spec.MaxReplicas) if desiredReplicas == prenormalizedDesiredReplicas { setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionFalse, condition, reason) } else { setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, condition, reason) } return desiredReplicas } // convertDesiredReplicas performs the actual normalization, without depending on `HorizontalController` or `HorizontalPodAutoscaler` func convertDesiredReplicasWithRules(currentReplicas, desiredReplicas, hpaMinReplicas, hpaMaxReplicas int32) (int32, string, string) { var minimumAllowedReplicas int32 var maximumAllowedReplicas int32 var possibleLimitingCondition string var possibleLimitingReason string if hpaMinReplicas == 0 { minimumAllowedReplicas = 1 possibleLimitingReason = "the desired replica count is zero" } else { minimumAllowedReplicas = hpaMinReplicas possibleLimitingReason = "the desired replica count is less than the minimum replica count" } // Do not upscale too much to prevent incorrect rapid increase of the number of master replicas caused by // bogus CPU usage report from heapster/kubelet (like in issue #32304). scaleUpLimit := calculateScaleUpLimit(currentReplicas) if hpaMaxReplicas > scaleUpLimit { maximumAllowedReplicas = scaleUpLimit possibleLimitingCondition = "ScaleUpLimit" possibleLimitingReason = "the desired replica count is increasing faster than the maximum scale rate" } else { maximumAllowedReplicas = hpaMaxReplicas possibleLimitingCondition = "TooManyReplicas" possibleLimitingReason = "the desired replica count is more than the maximum replica count" } if desiredReplicas < minimumAllowedReplicas { possibleLimitingCondition = "TooFewReplicas" return minimumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason } else if desiredReplicas > maximumAllowedReplicas { return maximumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason } return desiredReplicas, "DesiredWithinRange", "the desired count is within the acceptable range" } func calculateScaleUpLimit(currentReplicas int32) int32 { return int32(math.Max(scaleUpLimitFactor*float64(currentReplicas), scaleUpLimitMinimum)) } func (a *HorizontalController) shouldScale(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, timestamp time.Time) bool { if desiredReplicas == currentReplicas { return false } if hpa.Status.LastScaleTime == nil { return true } // Going down only if the usageRatio dropped significantly below the target // and there was no rescaling in the last downscaleForbiddenWindow. if desiredReplicas < currentReplicas && hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) { return true } // Going up only if the usage ratio increased significantly above the target // and there was no rescaling in the last upscaleForbiddenWindow. if desiredReplicas > currentReplicas && hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) { return true } return false } // scaleForResourceMappings attempts to fetch the scale for the // resource with the given name and namespace, trying each RESTMapping // in turn until a working one is found. If none work, the first error // is returned. It returns both the scale, as well as the group-resource from // the working mapping. func (a *HorizontalController) scaleForResourceMappings(namespace, name string, mappings []*apimeta.RESTMapping) (*autoscalingv1.Scale, schema.GroupResource, error) { var firstErr error for i, mapping := range mappings { targetGR := mapping.Resource.GroupResource() scale, err := a.scaleNamespacer.Scales(namespace).Get(targetGR, name) if err == nil { return scale, targetGR, nil } // if this is the first error, remember it, // then go on and try other mappings until we find a good one if i == 0 { firstErr = err } } // make sure we handle an empty set of mappings if firstErr == nil { firstErr = fmt.Errorf("unrecognized resource") } return nil, schema.GroupResource{}, firstErr } // setCurrentReplicasInStatus sets the current replica count in the status of the HPA. func (a *HorizontalController) setCurrentReplicasInStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32) { a.setStatus(hpa, currentReplicas, hpa.Status.DesiredReplicas, hpa.Status.CurrentMetrics, false) } // setStatus recreates the status of the given HPA, updating the current and // desired replicas, as well as the metric statuses func (a *HorizontalController) setStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, metricStatuses []autoscalingv2.MetricStatus, rescale bool) { hpa.Status = autoscalingv2.HorizontalPodAutoscalerStatus{ CurrentReplicas: currentReplicas, DesiredReplicas: desiredReplicas, LastScaleTime: hpa.Status.LastScaleTime, CurrentMetrics: metricStatuses, Conditions: hpa.Status.Conditions, } if rescale { now := metav1.NewTime(time.Now()) hpa.Status.LastScaleTime = &now } } // updateStatusIfNeeded calls updateStatus only if the status of the new HPA is not the same as the old status func (a *HorizontalController) updateStatusIfNeeded(oldStatus *autoscalingv2.HorizontalPodAutoscalerStatus, newHPA *autoscalingv2.HorizontalPodAutoscaler) error { // skip a write if we wouldn't need to update if apiequality.Semantic.DeepEqual(oldStatus, &newHPA.Status) { return nil } return a.updateStatus(newHPA) } // updateStatus actually does the update request for the status of the given HPA func (a *HorizontalController) updateStatus(hpa *autoscalingv2.HorizontalPodAutoscaler) error { // convert back to autoscalingv1 hpaRaw, err := unsafeConvertToVersionVia(hpa, autoscalingv1.SchemeGroupVersion) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedConvertHPA", err.Error()) return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err) } hpav1 := hpaRaw.(*autoscalingv1.HorizontalPodAutoscaler) _, err = a.hpaNamespacer.HorizontalPodAutoscalers(hpav1.Namespace).UpdateStatus(hpav1) if err != nil { a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedUpdateStatus", err.Error()) return fmt.Errorf("failed to update status for %s: %v", hpa.Name, err) } glog.V(2).Infof("Successfully updated status for %s", hpa.Name) return nil } // unsafeConvertToVersionVia is like Scheme.UnsafeConvertToVersion, but it does so via an internal version first. // We use it since working with v2alpha1 is convenient here, but we want to use the v1 client (and // can't just use the internal version). Note that conversion mutates the object, so you need to deepcopy // *before* you call this if the input object came out of a shared cache. func unsafeConvertToVersionVia(obj runtime.Object, externalVersion schema.GroupVersion) (runtime.Object, error) { objInt, err := legacyscheme.Scheme.UnsafeConvertToVersion(obj, schema.GroupVersion{Group: externalVersion.Group, Version: runtime.APIVersionInternal}) if err != nil { return nil, fmt.Errorf("failed to convert the given object to the internal version: %v", err) } objExt, err := legacyscheme.Scheme.UnsafeConvertToVersion(objInt, externalVersion) if err != nil { return nil, fmt.Errorf("failed to convert the given object back to the external version: %v", err) } return objExt, err } // setCondition sets the specific condition type on the given HPA to the specified value with the given reason // and message. The message and args are treated like a format string. The condition will be added if it is // not present. func setCondition(hpa *autoscalingv2.HorizontalPodAutoscaler, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) { hpa.Status.Conditions = setConditionInList(hpa.Status.Conditions, conditionType, status, reason, message, args...) } // setConditionInList sets the specific condition type on the given HPA to the specified value with the given // reason and message. The message and args are treated like a format string. The condition will be added if // it is not present. The new list will be returned. func setConditionInList(inputList []autoscalingv2.HorizontalPodAutoscalerCondition, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) []autoscalingv2.HorizontalPodAutoscalerCondition { resList := inputList var existingCond *autoscalingv2.HorizontalPodAutoscalerCondition for i, condition := range resList { if condition.Type == conditionType { // can't take a pointer to an iteration variable existingCond = &resList[i] break } } if existingCond == nil { resList = append(resList, autoscalingv2.HorizontalPodAutoscalerCondition{ Type: conditionType, }) existingCond = &resList[len(resList)-1] } if existingCond.Status != status { existingCond.LastTransitionTime = metav1.Now() } existingCond.Status = status existingCond.Reason = reason existingCond.Message = fmt.Sprintf(message, args...) return resList }
apache-2.0
usakey/kafka
core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala
27361
/** * 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 kafka.server import java.util.Properties import junit.framework.Assert._ import kafka.api.{ApiVersion, KAFKA_082} import kafka.message._ import kafka.utils.{TestUtils, CoreUtils} import org.apache.kafka.common.config.ConfigException import org.apache.kafka.common.protocol.SecurityProtocol import org.junit.{Assert, Test} import org.scalatest.Assertions.intercept class KafkaConfigTest { @Test def testLogRetentionTimeHoursProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRetentionTimeHoursProp, "1") val cfg = KafkaConfig.fromProps(props) assertEquals(60L * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionTimeMinutesProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRetentionTimeMinutesProp, "30") val cfg = KafkaConfig.fromProps(props) assertEquals(30 * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionTimeMsProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRetentionTimeMillisProp, "1800000") val cfg = KafkaConfig.fromProps(props) assertEquals(30 * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionTimeNoConfigProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val cfg = KafkaConfig.fromProps(props) assertEquals(24 * 7 * 60L * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionTimeBothMinutesAndHoursProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRetentionTimeMinutesProp, "30") props.put(KafkaConfig.LogRetentionTimeHoursProp, "1") val cfg = KafkaConfig.fromProps(props) assertEquals( 30 * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionTimeBothMinutesAndMsProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRetentionTimeMillisProp, "1800000") props.put(KafkaConfig.LogRetentionTimeMinutesProp, "10") val cfg = KafkaConfig.fromProps(props) assertEquals( 30 * 60L * 1000L, cfg.logRetentionTimeMillis) } @Test def testLogRetentionUnlimited() { val props1 = TestUtils.createBrokerConfig(0,TestUtils.MockZkConnect, port = 8181) val props2 = TestUtils.createBrokerConfig(0,TestUtils.MockZkConnect, port = 8181) val props3 = TestUtils.createBrokerConfig(0,TestUtils.MockZkConnect, port = 8181) val props4 = TestUtils.createBrokerConfig(0,TestUtils.MockZkConnect, port = 8181) val props5 = TestUtils.createBrokerConfig(0,TestUtils.MockZkConnect, port = 8181) props1.put("log.retention.ms", "-1") props2.put("log.retention.minutes", "-1") props3.put("log.retention.hours", "-1") val cfg1 = KafkaConfig.fromProps(props1) val cfg2 = KafkaConfig.fromProps(props2) val cfg3 = KafkaConfig.fromProps(props3) assertEquals("Should be -1", -1, cfg1.logRetentionTimeMillis) assertEquals("Should be -1", -1, cfg2.logRetentionTimeMillis) assertEquals("Should be -1", -1, cfg3.logRetentionTimeMillis) props4.put("log.retention.ms", "-1") props4.put("log.retention.minutes", "30") val cfg4 = KafkaConfig.fromProps(props4) assertEquals("Should be -1", -1, cfg4.logRetentionTimeMillis) props5.put("log.retention.ms", "0") intercept[IllegalArgumentException] { val cfg5 = KafkaConfig.fromProps(props5) } } @Test def testLogRetentionValid { val props1 = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val props2 = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val props3 = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props1.put("log.retention.ms", "0") props2.put("log.retention.minutes", "0") props3.put("log.retention.hours", "0") intercept[IllegalArgumentException] { val cfg1 = KafkaConfig.fromProps(props1) } intercept[IllegalArgumentException] { val cfg2 = KafkaConfig.fromProps(props2) } intercept[IllegalArgumentException] { val cfg3 = KafkaConfig.fromProps(props3) } } @Test def testAdvertiseDefaults() { val port = "9999" val hostName = "fake-host" val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect) props.remove(KafkaConfig.ListenersProp) props.put(KafkaConfig.HostNameProp, hostName) props.put(KafkaConfig.PortProp, port) val serverConfig = KafkaConfig.fromProps(props) val endpoints = serverConfig.advertisedListeners val endpoint = endpoints.get(SecurityProtocol.PLAINTEXT).get assertEquals(endpoint.host, hostName) assertEquals(endpoint.port, port.toInt) } @Test def testAdvertiseConfigured() { val advertisedHostName = "routable-host" val advertisedPort = "1234" val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect) props.put(KafkaConfig.AdvertisedHostNameProp, advertisedHostName) props.put(KafkaConfig.AdvertisedPortProp, advertisedPort) val serverConfig = KafkaConfig.fromProps(props) val endpoints = serverConfig.advertisedListeners val endpoint = endpoints.get(SecurityProtocol.PLAINTEXT).get assertEquals(endpoint.host, advertisedHostName) assertEquals(endpoint.port, advertisedPort.toInt) } @Test def testAdvertisePortDefault() { val advertisedHostName = "routable-host" val port = "9999" val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect) props.put(KafkaConfig.AdvertisedHostNameProp, advertisedHostName) props.put(KafkaConfig.PortProp, port) val serverConfig = KafkaConfig.fromProps(props) val endpoints = serverConfig.advertisedListeners val endpoint = endpoints.get(SecurityProtocol.PLAINTEXT).get assertEquals(endpoint.host, advertisedHostName) assertEquals(endpoint.port, port.toInt) } @Test def testAdvertiseHostNameDefault() { val hostName = "routable-host" val advertisedPort = "9999" val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect) props.put(KafkaConfig.HostNameProp, hostName) props.put(KafkaConfig.AdvertisedPortProp, advertisedPort) val serverConfig = KafkaConfig.fromProps(props) val endpoints = serverConfig.advertisedListeners val endpoint = endpoints.get(SecurityProtocol.PLAINTEXT).get assertEquals(endpoint.host, hostName) assertEquals(endpoint.port, advertisedPort.toInt) } @Test def testDuplicateListeners() { val props = new Properties() props.put(KafkaConfig.BrokerIdProp, "1") props.put(KafkaConfig.ZkConnectProp, "localhost:2181") // listeners with duplicate port props.put(KafkaConfig.ListenersProp, "PLAINTEXT://localhost:9091,TRACE://localhost:9091") assert(!isValidKafkaConfig(props)) // listeners with duplicate protocol props.put(KafkaConfig.ListenersProp, "PLAINTEXT://localhost:9091,PLAINTEXT://localhost:9092") assert(!isValidKafkaConfig(props)) // advertised listeners with duplicate port props.put(KafkaConfig.AdvertisedListenersProp, "PLAINTEXT://localhost:9091,TRACE://localhost:9091") assert(!isValidKafkaConfig(props)) } @Test def testBadListenerProtocol() { val props = new Properties() props.put(KafkaConfig.BrokerIdProp, "1") props.put(KafkaConfig.ZkConnectProp, "localhost:2181") props.put(KafkaConfig.ListenersProp, "BAD://localhost:9091") assert(!isValidKafkaConfig(props)) } @Test def testListenerDefaults() { val props = new Properties() props.put(KafkaConfig.BrokerIdProp, "1") props.put(KafkaConfig.ZkConnectProp, "localhost:2181") // configuration with host and port, but no listeners props.put(KafkaConfig.HostNameProp, "myhost") props.put(KafkaConfig.PortProp, "1111") val conf = KafkaConfig.fromProps(props) assertEquals(CoreUtils.listenerListToEndPoints("PLAINTEXT://myhost:1111"), conf.listeners) // configuration with null host props.remove(KafkaConfig.HostNameProp) val conf2 = KafkaConfig.fromProps(props) assertEquals(CoreUtils.listenerListToEndPoints("PLAINTEXT://:1111"), conf2.listeners) assertEquals(CoreUtils.listenerListToEndPoints("PLAINTEXT://:1111"), conf2.advertisedListeners) assertEquals(null, conf2.listeners(SecurityProtocol.PLAINTEXT).host) // configuration with advertised host and port, and no advertised listeners props.put(KafkaConfig.AdvertisedHostNameProp, "otherhost") props.put(KafkaConfig.AdvertisedPortProp, "2222") val conf3 = KafkaConfig.fromProps(props) assertEquals(conf3.advertisedListeners, CoreUtils.listenerListToEndPoints("PLAINTEXT://otherhost:2222")) } @Test def testVersionConfiguration() { val props = new Properties() props.put(KafkaConfig.BrokerIdProp, "1") props.put(KafkaConfig.ZkConnectProp, "localhost:2181") val conf = KafkaConfig.fromProps(props) assertEquals(ApiVersion.latestVersion, conf.interBrokerProtocolVersion) props.put(KafkaConfig.InterBrokerProtocolVersionProp,"0.8.2.0") val conf2 = KafkaConfig.fromProps(props) assertEquals(KAFKA_082, conf2.interBrokerProtocolVersion) // check that 0.8.2.0 is the same as 0.8.2.1 props.put(KafkaConfig.InterBrokerProtocolVersionProp,"0.8.2.1") val conf3 = KafkaConfig.fromProps(props) assertEquals(KAFKA_082, conf3.interBrokerProtocolVersion) //check that latest is newer than 0.8.2 assert(ApiVersion.latestVersion.onOrAfter(conf3.interBrokerProtocolVersion)) } private def isValidKafkaConfig(props: Properties): Boolean = { try { KafkaConfig.fromProps(props) true } catch { case e: IllegalArgumentException => false } } @Test def testUncleanLeaderElectionDefault() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val serverConfig = KafkaConfig.fromProps(props) assertEquals(serverConfig.uncleanLeaderElectionEnable, true) } @Test def testUncleanElectionDisabled() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.UncleanLeaderElectionEnableProp, String.valueOf(false)) val serverConfig = KafkaConfig.fromProps(props) assertEquals(serverConfig.uncleanLeaderElectionEnable, false) } @Test def testUncleanElectionEnabled() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.UncleanLeaderElectionEnableProp, String.valueOf(true)) val serverConfig = KafkaConfig.fromProps(props) assertEquals(serverConfig.uncleanLeaderElectionEnable, true) } @Test def testUncleanElectionInvalid() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.UncleanLeaderElectionEnableProp, "invalid") intercept[ConfigException] { KafkaConfig.fromProps(props) } } @Test def testLogRollTimeMsProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRollTimeMillisProp, "1800000") val cfg = KafkaConfig.fromProps(props) assertEquals(30 * 60L * 1000L, cfg.logRollTimeMillis) } @Test def testLogRollTimeBothMsAndHoursProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.LogRollTimeMillisProp, "1800000") props.put(KafkaConfig.LogRollTimeHoursProp, "1") val cfg = KafkaConfig.fromProps(props) assertEquals( 30 * 60L * 1000L, cfg.logRollTimeMillis) } @Test def testLogRollTimeNoConfigProvided() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val cfg = KafkaConfig.fromProps(props) assertEquals(24 * 7 * 60L * 60L * 1000L, cfg.logRollTimeMillis ) } @Test def testDefaultCompressionType() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) val serverConfig = KafkaConfig.fromProps(props) assertEquals(serverConfig.compressionType, "producer") } @Test def testValidCompressionType() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put("compression.type", "gzip") val serverConfig = KafkaConfig.fromProps(props) assertEquals(serverConfig.compressionType, "gzip") } @Test def testInvalidCompressionType() { val props = TestUtils.createBrokerConfig(0, TestUtils.MockZkConnect, port = 8181) props.put(KafkaConfig.CompressionTypeProp, "abc") intercept[IllegalArgumentException] { KafkaConfig.fromProps(props) } } @Test def testFromPropsInvalid() { def getBaseProperties(): Properties = { val validRequiredProperties = new Properties() validRequiredProperties.put(KafkaConfig.ZkConnectProp, "127.0.0.1:2181") validRequiredProperties } // to ensure a basis is valid - bootstraps all needed validation KafkaConfig.fromProps(getBaseProperties()) KafkaConfig.configNames().foreach(name => { name match { case KafkaConfig.ZkConnectProp => // ignore string case KafkaConfig.ZkSessionTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ZkConnectionTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ZkSyncTimeMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.BrokerIdProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.NumNetworkThreadsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.NumIoThreadsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.BackgroundThreadsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.QueuedMaxRequestsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.AuthorizerClassNameProp => //ignore string case KafkaConfig.PortProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.HostNameProp => // ignore string case KafkaConfig.AdvertisedHostNameProp => //ignore string case KafkaConfig.AdvertisedPortProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.SocketSendBufferBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.SocketReceiveBufferBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.MaxConnectionsPerIpOverridesProp => assertPropertyInvalid(getBaseProperties(), name, "127.0.0.1:not_a_number") case KafkaConfig.ConnectionsMaxIdleMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.NumPartitionsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogDirsProp => // ignore string case KafkaConfig.LogDirProp => // ignore string case KafkaConfig.LogSegmentBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", Message.MinHeaderSize - 1) case KafkaConfig.LogRollTimeMillisProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogRollTimeHoursProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogRetentionTimeMillisProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogRetentionTimeMinutesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogRetentionTimeHoursProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogRetentionBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogCleanupIntervalMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogCleanupPolicyProp => assertPropertyInvalid(getBaseProperties(), name, "unknown_policy", "0") case KafkaConfig.LogCleanerIoMaxBytesPerSecondProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogCleanerDedupeBufferSizeProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "1024") case KafkaConfig.LogCleanerDedupeBufferLoadFactorProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogCleanerEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean") case KafkaConfig.LogCleanerDeleteRetentionMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogCleanerMinCleanRatioProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogIndexSizeMaxBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "3") case KafkaConfig.LogFlushIntervalMessagesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.LogFlushSchedulerIntervalMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LogFlushIntervalMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.NumRecoveryThreadsPerDataDirProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.AutoCreateTopicsEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean", "0") case KafkaConfig.MinInSyncReplicasProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.ControllerSocketTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.DefaultReplicationFactorProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaLagTimeMaxMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaSocketTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "-2") case KafkaConfig.ReplicaSocketReceiveBufferBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaFetchMaxBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaFetchWaitMaxMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaFetchMinBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.NumReplicaFetchersProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ReplicaHighWatermarkCheckpointIntervalMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.FetchPurgatoryPurgeIntervalRequestsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ProducerPurgatoryPurgeIntervalRequestsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.AutoLeaderRebalanceEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean", "0") case KafkaConfig.LeaderImbalancePerBrokerPercentageProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.LeaderImbalanceCheckIntervalSecondsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.UncleanLeaderElectionEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean", "0") case KafkaConfig.ControlledShutdownMaxRetriesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ControlledShutdownRetryBackoffMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ControlledShutdownEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean", "0") case KafkaConfig.ConsumerMinSessionTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.ConsumerMaxSessionTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.OffsetMetadataMaxSizeProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number") case KafkaConfig.OffsetsLoadBufferSizeProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetsTopicReplicationFactorProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetsTopicPartitionsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetsTopicSegmentBytesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetsTopicCompressionCodecProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "-1") case KafkaConfig.OffsetsRetentionMinutesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetsRetentionCheckIntervalMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetCommitTimeoutMsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.OffsetCommitRequiredAcksProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "-2") case KafkaConfig.ProducerQuotaBytesPerSecondDefaultProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.ConsumerQuotaBytesPerSecondDefaultProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.ProducerQuotaBytesPerSecondOverridesProp => // ignore string case KafkaConfig.ConsumerQuotaBytesPerSecondOverridesProp => // ignore string case KafkaConfig.NumQuotaSamplesProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.QuotaWindowSizeSecondsProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "0") case KafkaConfig.DeleteTopicEnableProp => assertPropertyInvalid(getBaseProperties(), name, "not_a_boolean", "0") case KafkaConfig.MetricNumSamplesProp => assertPropertyInvalid(getBaseProperties, name, "not_a_number", "-1", "0") case KafkaConfig.MetricSampleWindowMsProp => assertPropertyInvalid(getBaseProperties, name, "not_a_number", "-1", "0") case KafkaConfig.MetricReporterClassesProp => // ignore string //SSL Configs case KafkaConfig.PrincipalBuilderClassProp => case KafkaConfig.SSLProtocolProp => // ignore string case KafkaConfig.SSLProviderProp => // ignore string case KafkaConfig.SSLEnabledProtocolsProp => case KafkaConfig.SSLKeystoreTypeProp => // ignore string case KafkaConfig.SSLKeystoreLocationProp => // ignore string case KafkaConfig.SSLKeystorePasswordProp => // ignore string case KafkaConfig.SSLKeyPasswordProp => // ignore string case KafkaConfig.SSLTruststoreTypeProp => // ignore string case KafkaConfig.SSLTruststorePasswordProp => // ignore string case KafkaConfig.SSLTruststoreLocationProp => // ignore string case KafkaConfig.SSLKeyManagerAlgorithmProp => case KafkaConfig.SSLTrustManagerAlgorithmProp => case KafkaConfig.SSLClientAuthProp => // ignore string case nonNegativeIntProperty => assertPropertyInvalid(getBaseProperties(), name, "not_a_number", "-1") } }) } @Test def testSpecificProperties(): Unit = { val defaults = new Properties() defaults.put(KafkaConfig.ZkConnectProp, "127.0.0.1:2181") // For ZkConnectionTimeoutMs defaults.put(KafkaConfig.ZkSessionTimeoutMsProp, "1234") defaults.put(KafkaConfig.MaxReservedBrokerIdProp, "1") defaults.put(KafkaConfig.BrokerIdProp, "1") defaults.put(KafkaConfig.HostNameProp, "127.0.0.1") defaults.put(KafkaConfig.PortProp, "1122") defaults.put(KafkaConfig.MaxConnectionsPerIpOverridesProp, "127.0.0.1:2, 127.0.0.2:3") defaults.put(KafkaConfig.LogDirProp, "/tmp1,/tmp2") defaults.put(KafkaConfig.LogRollTimeHoursProp, "12") defaults.put(KafkaConfig.LogRollTimeJitterHoursProp, "11") defaults.put(KafkaConfig.LogRetentionTimeHoursProp, "10") //For LogFlushIntervalMsProp defaults.put(KafkaConfig.LogFlushSchedulerIntervalMsProp, "123") defaults.put(KafkaConfig.OffsetsTopicCompressionCodecProp, SnappyCompressionCodec.codec.toString) val config = KafkaConfig.fromProps(defaults) Assert.assertEquals("127.0.0.1:2181", config.zkConnect) Assert.assertEquals(1234, config.zkConnectionTimeoutMs) Assert.assertEquals(1, config.maxReservedBrokerId) Assert.assertEquals(1, config.brokerId) Assert.assertEquals("127.0.0.1", config.hostName) Assert.assertEquals(1122, config.advertisedPort) Assert.assertEquals("127.0.0.1", config.advertisedHostName) Assert.assertEquals(Map("127.0.0.1" -> 2, "127.0.0.2" -> 3), config.maxConnectionsPerIpOverrides) Assert.assertEquals(List("/tmp1", "/tmp2"), config.logDirs) Assert.assertEquals(12 * 60L * 1000L * 60, config.logRollTimeMillis) Assert.assertEquals(11 * 60L * 1000L * 60, config.logRollTimeJitterMillis) Assert.assertEquals(10 * 60L * 1000L * 60, config.logRetentionTimeMillis) Assert.assertEquals(123L, config.logFlushIntervalMs) Assert.assertEquals(SnappyCompressionCodec, config.offsetsTopicCompressionCodec) } private def assertPropertyInvalid(validRequiredProps: => Properties, name: String, values: Any*) { values.foreach((value) => { val props = validRequiredProps props.setProperty(name, value.toString) intercept[Exception] { KafkaConfig.fromProps(props) } }) } }
apache-2.0
aospx-kitkat/platform_external_chromium_org
chrome/browser/ui/global_error/global_error_service.cc
3238
// 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. #include "chrome/browser/ui/global_error/global_error_service.h" #include <algorithm> #include "base/stl_util.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/global_error/global_error.h" #include "chrome/browser/ui/global_error/global_error_bubble_view_base.h" #include "content/public/browser/notification_service.h" GlobalErrorService::GlobalErrorService(Profile* profile) : profile_(profile) { } GlobalErrorService::~GlobalErrorService() { STLDeleteElements(&errors_); } void GlobalErrorService::AddGlobalError(GlobalError* error) { errors_.push_back(error); NotifyErrorsChanged(error); } void GlobalErrorService::RemoveGlobalError(GlobalError* error) { errors_.erase(std::find(errors_.begin(), errors_.end(), error)); GlobalErrorBubbleViewBase* bubble = error->GetBubbleView(); if (bubble) bubble->CloseBubbleView(); NotifyErrorsChanged(error); } GlobalError* GlobalErrorService::GetGlobalErrorByMenuItemCommandID( int command_id) const { for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasMenuItem() && command_id == error->MenuItemCommandID()) return error; } return NULL; } GlobalError* GlobalErrorService::GetHighestSeverityGlobalErrorWithWrenchMenuItem() const { GlobalError::Severity highest_severity = GlobalError::SEVERITY_LOW; GlobalError* highest_severity_error = NULL; for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasMenuItem()) { if (!highest_severity_error || error->GetSeverity() > highest_severity) { highest_severity = error->GetSeverity(); highest_severity_error = error; } } } return highest_severity_error; } GlobalError* GlobalErrorService::GetFirstGlobalErrorWithBubbleView() const { for (GlobalErrorList::const_iterator it = errors_.begin(); it != errors_.end(); ++it) { GlobalError* error = *it; if (error->HasBubbleView() && !error->HasShownBubbleView()) return error; } return NULL; } void GlobalErrorService::NotifyErrorsChanged(GlobalError* error) { // GlobalErrorService is bound only to original profile so we need to send // notifications to both it and its off-the-record profile to update // incognito windows as well. std::vector<Profile*> profiles_to_notify; if (profile_ != NULL) { profiles_to_notify.push_back(profile_); if (profile_->IsOffTheRecord()) profiles_to_notify.push_back(profile_->GetOriginalProfile()); else if (profile_->HasOffTheRecordProfile()) profiles_to_notify.push_back(profile_->GetOffTheRecordProfile()); for (size_t i = 0; i < profiles_to_notify.size(); ++i) { content::NotificationService::current()->Notify( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::Source<Profile>(profiles_to_notify[i]), content::Details<GlobalError>(error)); } } }
bsd-3-clause
Gateworks/platform-external-chromium_org
google_apis/gaia/gaia_oauth_client.cc
13657
// 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. #include "google_apis/gaia/gaia_oauth_client.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_util.h" #include "base/values.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "net/url_request/url_request_context_getter.h" #include "url/gurl.h" namespace { const char kAccessTokenValue[] = "access_token"; const char kRefreshTokenValue[] = "refresh_token"; const char kExpiresInValue[] = "expires_in"; } namespace gaia { // Use a non-zero number, so unit tests can differentiate the URLFetcher used by // this class from other fetchers (most other code just hardcodes the ID to 0). const int GaiaOAuthClient::kUrlFetcherId = 17109006; class GaiaOAuthClient::Core : public base::RefCountedThreadSafe<GaiaOAuthClient::Core>, public net::URLFetcherDelegate { public: Core(net::URLRequestContextGetter* request_context_getter) : num_retries_(0), request_context_getter_(request_context_getter), delegate_(NULL), request_type_(NO_PENDING_REQUEST) { } void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate); void RefreshToken(const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, GaiaOAuthClient::Delegate* delegate); void GetUserEmail(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void GetUserId(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void GetTokenInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate); // net::URLFetcherDelegate implementation. virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE; private: friend class base::RefCountedThreadSafe<Core>; enum RequestType { NO_PENDING_REQUEST, TOKENS_FROM_AUTH_CODE, REFRESH_TOKEN, TOKEN_INFO, USER_EMAIL, USER_ID, }; virtual ~Core() {} void GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate); void MakeGaiaRequest(const GURL& url, const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate); void HandleResponse(const net::URLFetcher* source, bool* should_retry_request); int num_retries_; scoped_refptr<net::URLRequestContextGetter> request_context_getter_; GaiaOAuthClient::Delegate* delegate_; scoped_ptr<net::URLFetcher> request_; RequestType request_type_; }; void GaiaOAuthClient::Core::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = TOKENS_FROM_AUTH_CODE; std::string post_body = "code=" + net::EscapeUrlEncodedData(auth_code, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&redirect_uri=" + net::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) + "&grant_type=authorization_code"; MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); request_type_ = REFRESH_TOKEN; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; if (!scopes.empty()) { std::string scopes_string = JoinString(scopes, ' '); post_body += "&scope=" + net::EscapeUrlEncodedData(scopes_string, true); } MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserEmail(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = USER_EMAIL; GetUserInfo(oauth_access_token, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserId(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = USER_ID; GetUserInfo(oauth_access_token, max_retries, delegate); } void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( kUrlFetcherId, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()), net::URLFetcher::GET, this)); request_->SetRequestContext(request_context_getter_.get()); request_->AddExtraRequestHeader("Authorization: OAuth " + oauth_access_token); request_->SetMaxRetriesOn5xx(max_retries); request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); // Fetchers are sometimes cancelled because a network change was detected, // especially at startup and after sign-in on ChromeOS. Retrying once should // be enough in those cases; let the fetcher retry up to 3 times just in case. // http://crbug.com/163710 request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } void GaiaOAuthClient::Core::GetTokenInfo(const std::string& oauth_access_token, int max_retries, Delegate* delegate) { DCHECK_EQ(request_type_, NO_PENDING_REQUEST); DCHECK(!request_.get()); request_type_ = TOKEN_INFO; std::string post_body = "access_token=" + net::EscapeUrlEncodedData(oauth_access_token, true); MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()), post_body, max_retries, delegate); } void GaiaOAuthClient::Core::MakeGaiaRequest( const GURL& url, const std::string& post_body, int max_retries, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; num_retries_ = 0; request_.reset(net::URLFetcher::Create( kUrlFetcherId, url, net::URLFetcher::POST, this)); request_->SetRequestContext(request_context_getter_.get()); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->SetMaxRetriesOn5xx(max_retries); request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); // See comment on SetAutomaticallyRetryOnNetworkChanges() above. request_->SetAutomaticallyRetryOnNetworkChanges(3); request_->Start(); } // URLFetcher::Delegate implementation. void GaiaOAuthClient::Core::OnURLFetchComplete( const net::URLFetcher* source) { bool should_retry = false; HandleResponse(source, &should_retry); if (should_retry) { // Explicitly call ReceivedContentWasMalformed() to ensure the current // request gets counted as a failure for calculation of the back-off // period. If it was already a failure by status code, this call will // be ignored. request_->ReceivedContentWasMalformed(); num_retries_++; // We must set our request_context_getter_ again because // URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL... request_->SetRequestContext(request_context_getter_.get()); request_->Start(); } } void GaiaOAuthClient::Core::HandleResponse( const net::URLFetcher* source, bool* should_retry_request) { // Move ownership of the request fetcher into a local scoped_ptr which // will be nuked when we're done handling the request, unless we need // to retry, in which case ownership will be returned to request_. scoped_ptr<net::URLFetcher> old_request = request_.Pass(); DCHECK_EQ(source, old_request.get()); // RC_BAD_REQUEST means the arguments are invalid. No point retrying. We are // done here. if (source->GetResponseCode() == net::HTTP_BAD_REQUEST) { delegate_->OnOAuthError(); return; } scoped_ptr<base::DictionaryValue> response_dict; if (source->GetResponseCode() == net::HTTP_OK) { std::string data; source->GetResponseAsString(&data); scoped_ptr<base::Value> message_value(base::JSONReader::Read(data)); if (message_value.get() && message_value->IsType(base::Value::TYPE_DICTIONARY)) { response_dict.reset( static_cast<base::DictionaryValue*>(message_value.release())); } } if (!response_dict.get()) { // If we don't have an access token yet and the the error was not // RC_BAD_REQUEST, we may need to retry. if ((source->GetMaxRetriesOn5xx() != -1) && (num_retries_ >= source->GetMaxRetriesOn5xx())) { // Retry limit reached. Give up. delegate_->OnNetworkError(source->GetResponseCode()); } else { request_ = old_request.Pass(); *should_retry_request = true; } return; } RequestType type = request_type_; request_type_ = NO_PENDING_REQUEST; switch (type) { case USER_EMAIL: { std::string email; response_dict->GetString("email", &email); delegate_->OnGetUserEmailResponse(email); break; } case USER_ID: { std::string id; response_dict->GetString("id", &id); delegate_->OnGetUserIdResponse(id); break; } case TOKEN_INFO: { delegate_->OnGetTokenInfoResponse(response_dict.Pass()); break; } case TOKENS_FROM_AUTH_CODE: case REFRESH_TOKEN: { std::string access_token; std::string refresh_token; int expires_in_seconds = 0; response_dict->GetString(kAccessTokenValue, &access_token); response_dict->GetString(kRefreshTokenValue, &refresh_token); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds); if (access_token.empty()) { delegate_->OnOAuthError(); return; } if (type == REFRESH_TOKEN) { delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds); } else { delegate_->OnGetTokensResponse(refresh_token, access_token, expires_in_seconds); } break; } default: NOTREACHED(); } } GaiaOAuthClient::GaiaOAuthClient(net::URLRequestContextGetter* context_getter) { core_ = new Core(context_getter); } GaiaOAuthClient::~GaiaOAuthClient() { } void GaiaOAuthClient::GetTokensFromAuthCode( const OAuthClientInfo& oauth_client_info, const std::string& auth_code, int max_retries, Delegate* delegate) { return core_->GetTokensFromAuthCode(oauth_client_info, auth_code, max_retries, delegate); } void GaiaOAuthClient::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, const std::vector<std::string>& scopes, int max_retries, Delegate* delegate) { return core_->RefreshToken(oauth_client_info, refresh_token, scopes, max_retries, delegate); } void GaiaOAuthClient::GetUserEmail(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetUserEmail(access_token, max_retries, delegate); } void GaiaOAuthClient::GetUserId(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetUserId(access_token, max_retries, delegate); } void GaiaOAuthClient::GetTokenInfo(const std::string& access_token, int max_retries, Delegate* delegate) { return core_->GetTokenInfo(access_token, max_retries, delegate); } } // namespace gaia
bsd-3-clause
endlessm/chromium-browser
chrome/browser/usb/usb_chooser_context_factory.cc
1559
// Copyright 2015 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 "chrome/browser/usb/usb_chooser_context_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/usb/usb_chooser_context.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" UsbChooserContextFactory::UsbChooserContextFactory() : BrowserContextKeyedServiceFactory( "UsbChooserContext", BrowserContextDependencyManager::GetInstance()) { DependsOn(HostContentSettingsMapFactory::GetInstance()); } UsbChooserContextFactory::~UsbChooserContextFactory() {} KeyedService* UsbChooserContextFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { return new UsbChooserContext(Profile::FromBrowserContext(context)); } // static UsbChooserContextFactory* UsbChooserContextFactory::GetInstance() { return base::Singleton<UsbChooserContextFactory>::get(); } // static UsbChooserContext* UsbChooserContextFactory::GetForProfile(Profile* profile) { return static_cast<UsbChooserContext*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } content::BrowserContext* UsbChooserContextFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); }
bsd-3-clause
stanleyxu2005/zrender
doc/api/module-zrender_shape_Ring.html
259267
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Module: zrender/shape/Ring</title> <meta property="og:title" content=""/> <meta property="og:type" content="website"/> <meta property="og:image" content=""/> <meta property="og:url" content=""/> <script src="scripts/prettify/prettify.js"></script> <script src="scripts/prettify/lang-css.js"></script> <script src="scripts/jquery.min.js"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css"> <link type="text/css" rel="stylesheet" href="styles/jaguar.css"> <script> var config = {"monospaceLinks":false,"cleverLinks":false,"applicationName":"ZRender","disqus":"","googleAnalytics":"","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"","description":"","keyword":""},"default":{}}; </script> </head> <body> <div id="wrap" class="clearfix"> <div class="navigation"> <h3 class="applicationName"><a href="index.html">ZRender</a></h3> <div class="search"> <input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations"> </div> <ul class="list"> <li class="item" data-name="module:zrender"> <span class="title"> <a href="module-zrender.html">module:zrender</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender.version"><a href="module-zrender.html#.version">version</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender.delInstance"><a href="module-zrender.html#.delInstance">delInstance</a></li> <li data-name="module:zrender.dispose"><a href="module-zrender.html#.dispose">dispose</a></li> <li data-name="module:zrender.getInstance"><a href="module-zrender.html#.getInstance">getInstance</a></li> <li data-name="module:zrender.init"><a href="module-zrender.html#.init">init</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/animation/Animation"> <span class="title"> <a href="module-zrender_animation_Animation.html">module:zrender/animation/Animation</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/animation/Animation~IZRenderStage"><a href="module-zrender_animation_Animation.html#~IZRenderStage">IZRenderStage</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/animation/Animation#add"><a href="module-zrender_animation_Animation.html#add">add</a></li> <li data-name="module:zrender/animation/Animation#animate"><a href="module-zrender_animation_Animation.html#animate">animate</a></li> <li data-name="module:zrender/animation/Animation#clear"><a href="module-zrender_animation_Animation.html#clear">clear</a></li> <li data-name="module:zrender/animation/Animation#remove"><a href="module-zrender_animation_Animation.html#remove">remove</a></li> <li data-name="module:zrender/animation/Animation#start"><a href="module-zrender_animation_Animation.html#start">start</a></li> <li data-name="module:zrender/animation/Animation#stop"><a href="module-zrender_animation_Animation.html#stop">stop</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/animation/easing"> <span class="title"> <a href="module-zrender_animation_easing.html">module:zrender/animation/easing</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/animation/easing.BackIn"><a href="module-zrender_animation_easing.html#.BackIn">BackIn</a></li> <li data-name="module:zrender/animation/easing.BackInOut"><a href="module-zrender_animation_easing.html#.BackInOut">BackInOut</a></li> <li data-name="module:zrender/animation/easing.BackOut"><a href="module-zrender_animation_easing.html#.BackOut">BackOut</a></li> <li data-name="module:zrender/animation/easing.BounceIn"><a href="module-zrender_animation_easing.html#.BounceIn">BounceIn</a></li> <li data-name="module:zrender/animation/easing.BounceInOut"><a href="module-zrender_animation_easing.html#.BounceInOut">BounceInOut</a></li> <li data-name="module:zrender/animation/easing.BounceOut"><a href="module-zrender_animation_easing.html#.BounceOut">BounceOut</a></li> <li data-name="module:zrender/animation/easing.CircularIn"><a href="module-zrender_animation_easing.html#.CircularIn">CircularIn</a></li> <li data-name="module:zrender/animation/easing.CircularInOut"><a href="module-zrender_animation_easing.html#.CircularInOut">CircularInOut</a></li> <li data-name="module:zrender/animation/easing.CircularOut"><a href="module-zrender_animation_easing.html#.CircularOut">CircularOut</a></li> <li data-name="module:zrender/animation/easing.CubicIn"><a href="module-zrender_animation_easing.html#.CubicIn">CubicIn</a></li> <li data-name="module:zrender/animation/easing.CubicInOut"><a href="module-zrender_animation_easing.html#.CubicInOut">CubicInOut</a></li> <li data-name="module:zrender/animation/easing.CubicOut"><a href="module-zrender_animation_easing.html#.CubicOut">CubicOut</a></li> <li data-name="module:zrender/animation/easing.ElasticIn"><a href="module-zrender_animation_easing.html#.ElasticIn">ElasticIn</a></li> <li data-name="module:zrender/animation/easing.ElasticInOut"><a href="module-zrender_animation_easing.html#.ElasticInOut">ElasticInOut</a></li> <li data-name="module:zrender/animation/easing.ElasticOut"><a href="module-zrender_animation_easing.html#.ElasticOut">ElasticOut</a></li> <li data-name="module:zrender/animation/easing.ExponentialIn"><a href="module-zrender_animation_easing.html#.ExponentialIn">ExponentialIn</a></li> <li data-name="module:zrender/animation/easing.ExponentialInOut"><a href="module-zrender_animation_easing.html#.ExponentialInOut">ExponentialInOut</a></li> <li data-name="module:zrender/animation/easing.ExponentialOut"><a href="module-zrender_animation_easing.html#.ExponentialOut">ExponentialOut</a></li> <li data-name="module:zrender/animation/easing.Linear"><a href="module-zrender_animation_easing.html#.Linear">Linear</a></li> <li data-name="module:zrender/animation/easing.QuadraticIn"><a href="module-zrender_animation_easing.html#.QuadraticIn">QuadraticIn</a></li> <li data-name="module:zrender/animation/easing.QuadraticInOut"><a href="module-zrender_animation_easing.html#.QuadraticInOut">QuadraticInOut</a></li> <li data-name="module:zrender/animation/easing.QuadraticOut"><a href="module-zrender_animation_easing.html#.QuadraticOut">QuadraticOut</a></li> <li data-name="module:zrender/animation/easing.QuarticIn"><a href="module-zrender_animation_easing.html#.QuarticIn">QuarticIn</a></li> <li data-name="module:zrender/animation/easing.QuarticInOut"><a href="module-zrender_animation_easing.html#.QuarticInOut">QuarticInOut</a></li> <li data-name="module:zrender/animation/easing.QuarticOut"><a href="module-zrender_animation_easing.html#.QuarticOut">QuarticOut</a></li> <li data-name="module:zrender/animation/easing.QuinticIn"><a href="module-zrender_animation_easing.html#.QuinticIn">QuinticIn</a></li> <li data-name="module:zrender/animation/easing.QuinticInOut"><a href="module-zrender_animation_easing.html#.QuinticInOut">QuinticInOut</a></li> <li data-name="module:zrender/animation/easing.QuinticOut"><a href="module-zrender_animation_easing.html#.QuinticOut">QuinticOut</a></li> <li data-name="module:zrender/animation/easing.SinusoidalIn"><a href="module-zrender_animation_easing.html#.SinusoidalIn">SinusoidalIn</a></li> <li data-name="module:zrender/animation/easing.SinusoidalInOut"><a href="module-zrender_animation_easing.html#.SinusoidalInOut">SinusoidalInOut</a></li> <li data-name="module:zrender/animation/easing.SinusoidalOut"><a href="module-zrender_animation_easing.html#.SinusoidalOut">SinusoidalOut</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/config"> <span class="title"> <a href="module-zrender_config.html">module:zrender/config</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/config.debugMode"><a href="module-zrender_config.html#.debugMode">debugMode</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/Group"> <span class="title"> <a href="module-zrender_Group.html">module:zrender/Group</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/Group#clipShape"><a href="module-zrender_Group.html#clipShape">clipShape</a></li> <li data-name="module:zrender/Group#id"><a href="module-zrender_Group.html#id">id</a></li> <li data-name="module:zrender/Group#ignore"><a href="module-zrender_Group.html#ignore">ignore</a></li> <li data-name="module:zrender/Group#type"><a href="module-zrender_Group.html#type">type</a></li> <li data-name="module:zrender/Group#position"><a href="module-zrender_Group.html#position">position</a></li> <li data-name="module:zrender/Group#rotation"><a href="module-zrender_Group.html#rotation">rotation</a></li> <li data-name="module:zrender/Group#scale"><a href="module-zrender_Group.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/Group#addChild"><a href="module-zrender_Group.html#addChild">addChild</a></li> <li data-name="module:zrender/Group#childAt"><a href="module-zrender_Group.html#childAt">childAt</a></li> <li data-name="module:zrender/Group#children"><a href="module-zrender_Group.html#children">children</a></li> <li data-name="module:zrender/Group#clearChildren"><a href="module-zrender_Group.html#clearChildren">clearChildren</a></li> <li data-name="module:zrender/Group#eachChild"><a href="module-zrender_Group.html#eachChild">eachChild</a></li> <li data-name="module:zrender/Group#removeChild"><a href="module-zrender_Group.html#removeChild">removeChild</a></li> <li data-name="module:zrender/Group#traverse"><a href="module-zrender_Group.html#traverse">traverse</a></li> <li data-name="module:zrender/Group#bind"><a href="module-zrender_Group.html#bind">bind</a></li> <li data-name="module:zrender/Group#decomposeTransform"><a href="module-zrender_Group.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/Group#dispatch"><a href="module-zrender_Group.html#dispatch">dispatch</a></li> <li data-name="module:zrender/Group#dispatchWithContext"><a href="module-zrender_Group.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/Group#lookAt"><a href="module-zrender_Group.html#lookAt">lookAt</a></li> <li data-name="module:zrender/Group#one"><a href="module-zrender_Group.html#one">one</a></li> <li data-name="module:zrender/Group#setTransform"><a href="module-zrender_Group.html#setTransform">setTransform</a></li> <li data-name="module:zrender/Group#transformCoordToLocal"><a href="module-zrender_Group.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/Group#unbind"><a href="module-zrender_Group.html#unbind">unbind</a></li> <li data-name="module:zrender/Group#updateTransform"><a href="module-zrender_Group.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/Group#event:onclick"><a href="module-zrender_Group.html#event:onclick">onclick</a></li> <li data-name="module:zrender/Group#event:ondragend"><a href="module-zrender_Group.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/Group#event:ondragenter"><a href="module-zrender_Group.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/Group#event:ondragleave"><a href="module-zrender_Group.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/Group#event:ondragover"><a href="module-zrender_Group.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/Group#event:ondragstart"><a href="module-zrender_Group.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/Group#event:ondrop"><a href="module-zrender_Group.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/Group#event:onmousedown"><a href="module-zrender_Group.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/Group#event:onmousemove"><a href="module-zrender_Group.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/Group#event:onmouseout"><a href="module-zrender_Group.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/Group#event:onmouseover"><a href="module-zrender_Group.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/Group#event:onmouseup"><a href="module-zrender_Group.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/Group#event:onmousewheel"><a href="module-zrender_Group.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/Handler"> <span class="title"> <a href="module-zrender_Handler.html">module:zrender/Handler</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/Handler#dispose"><a href="module-zrender_Handler.html#dispose">dispose</a></li> <li data-name="module:zrender/Handler#on"><a href="module-zrender_Handler.html#on">on</a></li> <li data-name="module:zrender/Handler#trigger"><a href="module-zrender_Handler.html#trigger">trigger</a></li> <li data-name="module:zrender/Handler#un"><a href="module-zrender_Handler.html#un">un</a></li> <li data-name="module:zrender/Handler#bind"><a href="module-zrender_Handler.html#bind">bind</a></li> <li data-name="module:zrender/Handler#dispatch"><a href="module-zrender_Handler.html#dispatch">dispatch</a></li> <li data-name="module:zrender/Handler#dispatchWithContext"><a href="module-zrender_Handler.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/Handler#one"><a href="module-zrender_Handler.html#one">one</a></li> <li data-name="module:zrender/Handler#unbind"><a href="module-zrender_Handler.html#unbind">unbind</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/Handler#event:onclick"><a href="module-zrender_Handler.html#event:onclick">onclick</a></li> <li data-name="module:zrender/Handler#event:ondragend"><a href="module-zrender_Handler.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/Handler#event:ondragenter"><a href="module-zrender_Handler.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/Handler#event:ondragleave"><a href="module-zrender_Handler.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/Handler#event:ondragover"><a href="module-zrender_Handler.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/Handler#event:ondragstart"><a href="module-zrender_Handler.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/Handler#event:ondrop"><a href="module-zrender_Handler.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/Handler#event:onmousedown"><a href="module-zrender_Handler.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/Handler#event:onmousemove"><a href="module-zrender_Handler.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/Handler#event:onmouseout"><a href="module-zrender_Handler.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/Handler#event:onmouseover"><a href="module-zrender_Handler.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/Handler#event:onmouseup"><a href="module-zrender_Handler.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/Handler#event:onmousewheel"><a href="module-zrender_Handler.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/Layer"> <span class="title"> <a href="module-zrender_Layer.html">module:zrender/Layer</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/Layer#clearColor"><a href="module-zrender_Layer.html#clearColor">clearColor</a></li> <li data-name="module:zrender/Layer#lastFrameAlpha"><a href="module-zrender_Layer.html#lastFrameAlpha">lastFrameAlpha</a></li> <li data-name="module:zrender/Layer#motionBlur"><a href="module-zrender_Layer.html#motionBlur">motionBlur</a></li> <li data-name="module:zrender/Layer#panable"><a href="module-zrender_Layer.html#panable">panable</a></li> <li data-name="module:zrender/Layer#zoomable"><a href="module-zrender_Layer.html#zoomable">zoomable</a></li> <li data-name="module:zrender/Layer#position"><a href="module-zrender_Layer.html#position">position</a></li> <li data-name="module:zrender/Layer#rotation"><a href="module-zrender_Layer.html#rotation">rotation</a></li> <li data-name="module:zrender/Layer#scale"><a href="module-zrender_Layer.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/Layer#clear"><a href="module-zrender_Layer.html#clear">clear</a></li> <li data-name="module:zrender/Layer#resize"><a href="module-zrender_Layer.html#resize">resize</a></li> <li data-name="module:zrender/Layer#decomposeTransform"><a href="module-zrender_Layer.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/Layer#lookAt"><a href="module-zrender_Layer.html#lookAt">lookAt</a></li> <li data-name="module:zrender/Layer#setTransform"><a href="module-zrender_Layer.html#setTransform">setTransform</a></li> <li data-name="module:zrender/Layer#transformCoordToLocal"><a href="module-zrender_Layer.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/Layer#updateTransform"><a href="module-zrender_Layer.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/mixin/Eventful"> <span class="title"> <a href="module-zrender_mixin_Eventful.html">module:zrender/mixin/Eventful</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/mixin/Eventful#bind"><a href="module-zrender_mixin_Eventful.html#bind">bind</a></li> <li data-name="module:zrender/mixin/Eventful#dispatch"><a href="module-zrender_mixin_Eventful.html#dispatch">dispatch</a></li> <li data-name="module:zrender/mixin/Eventful#dispatchWithContext"><a href="module-zrender_mixin_Eventful.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/mixin/Eventful#one"><a href="module-zrender_mixin_Eventful.html#one">one</a></li> <li data-name="module:zrender/mixin/Eventful#unbind"><a href="module-zrender_mixin_Eventful.html#unbind">unbind</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/mixin/Eventful#event:onclick"><a href="module-zrender_mixin_Eventful.html#event:onclick">onclick</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondragend"><a href="module-zrender_mixin_Eventful.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondragenter"><a href="module-zrender_mixin_Eventful.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondragleave"><a href="module-zrender_mixin_Eventful.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondragover"><a href="module-zrender_mixin_Eventful.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondragstart"><a href="module-zrender_mixin_Eventful.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/mixin/Eventful#event:ondrop"><a href="module-zrender_mixin_Eventful.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmousedown"><a href="module-zrender_mixin_Eventful.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmousemove"><a href="module-zrender_mixin_Eventful.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmouseout"><a href="module-zrender_mixin_Eventful.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmouseover"><a href="module-zrender_mixin_Eventful.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmouseup"><a href="module-zrender_mixin_Eventful.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/mixin/Eventful#event:onmousewheel"><a href="module-zrender_mixin_Eventful.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/mixin/Transformable"> <span class="title"> <a href="module-zrender_mixin_Transformable.html">module:zrender/mixin/Transformable</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/mixin/Transformable#needTransform"><a href="module-zrender_mixin_Transformable.html#needTransform">needTransform</a></li> <li data-name="module:zrender/mixin/Transformable#position"><a href="module-zrender_mixin_Transformable.html#position">position</a></li> <li data-name="module:zrender/mixin/Transformable#rotation"><a href="module-zrender_mixin_Transformable.html#rotation">rotation</a></li> <li data-name="module:zrender/mixin/Transformable#scale"><a href="module-zrender_mixin_Transformable.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/mixin/Transformable#decomposeTransform"><a href="module-zrender_mixin_Transformable.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/mixin/Transformable#lookAt"><a href="module-zrender_mixin_Transformable.html#lookAt">lookAt</a></li> <li data-name="module:zrender/mixin/Transformable#setTransform"><a href="module-zrender_mixin_Transformable.html#setTransform">setTransform</a></li> <li data-name="module:zrender/mixin/Transformable#transformCoordToLocal"><a href="module-zrender_mixin_Transformable.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/mixin/Transformable#updateTransform"><a href="module-zrender_mixin_Transformable.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/Painter"> <span class="title"> <a href="module-zrender_Painter.html">module:zrender/Painter</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/Painter#root"><a href="module-zrender_Painter.html#root">root</a></li> <li data-name="module:zrender/Painter#storage"><a href="module-zrender_Painter.html#storage">storage</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/Painter#clear"><a href="module-zrender_Painter.html#clear">clear</a></li> <li data-name="module:zrender/Painter#clearHover"><a href="module-zrender_Painter.html#clearHover">clearHover</a></li> <li data-name="module:zrender/Painter#clearLayer"><a href="module-zrender_Painter.html#clearLayer">clearLayer</a></li> <li data-name="module:zrender/Painter#delLayer"><a href="module-zrender_Painter.html#delLayer">delLayer</a></li> <li data-name="module:zrender/Painter#dispose"><a href="module-zrender_Painter.html#dispose">dispose</a></li> <li data-name="module:zrender/Painter#getHeight"><a href="module-zrender_Painter.html#getHeight">getHeight</a></li> <li data-name="module:zrender/Painter#getLayer"><a href="module-zrender_Painter.html#getLayer">getLayer</a></li> <li data-name="module:zrender/Painter#getLayers"><a href="module-zrender_Painter.html#getLayers">getLayers</a></li> <li data-name="module:zrender/Painter#getWidth"><a href="module-zrender_Painter.html#getWidth">getWidth</a></li> <li data-name="module:zrender/Painter#hideLoading"><a href="module-zrender_Painter.html#hideLoading">hideLoading</a></li> <li data-name="module:zrender/Painter#isLoading"><a href="module-zrender_Painter.html#isLoading">isLoading</a></li> <li data-name="module:zrender/Painter#modLayer"><a href="module-zrender_Painter.html#modLayer">modLayer</a></li> <li data-name="module:zrender/Painter#refresh"><a href="module-zrender_Painter.html#refresh">refresh</a></li> <li data-name="module:zrender/Painter#refreshHover"><a href="module-zrender_Painter.html#refreshHover">refreshHover</a></li> <li data-name="module:zrender/Painter#refreshShapes"><a href="module-zrender_Painter.html#refreshShapes">refreshShapes</a></li> <li data-name="module:zrender/Painter#render"><a href="module-zrender_Painter.html#render">render</a></li> <li data-name="module:zrender/Painter#resize"><a href="module-zrender_Painter.html#resize">resize</a></li> <li data-name="module:zrender/Painter#setLoadingEffect"><a href="module-zrender_Painter.html#setLoadingEffect">setLoadingEffect</a></li> <li data-name="module:zrender/Painter#showLoading"><a href="module-zrender_Painter.html#showLoading">showLoading</a></li> <li data-name="module:zrender/Painter#toDataURL"><a href="module-zrender_Painter.html#toDataURL">toDataURL</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/Base"> <span class="title"> <a href="module-zrender_shape_Base.html">module:zrender/shape/Base</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Base#clickable"><a href="module-zrender_shape_Base.html#clickable">clickable</a></li> <li data-name="module:zrender/shape/Base#draggable"><a href="module-zrender_shape_Base.html#draggable">draggable</a></li> <li data-name="module:zrender/shape/Base#highlightStyle"><a href="module-zrender_shape_Base.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Base#hoverable"><a href="module-zrender_shape_Base.html#hoverable">hoverable</a></li> <li data-name="module:zrender/shape/Base#id"><a href="module-zrender_shape_Base.html#id">id</a></li> <li data-name="module:zrender/shape/Base#ignore"><a href="module-zrender_shape_Base.html#ignore">ignore</a></li> <li data-name="module:zrender/shape/Base#invisible"><a href="module-zrender_shape_Base.html#invisible">invisible</a></li> <li data-name="module:zrender/shape/Base#parent"><a href="module-zrender_shape_Base.html#parent">parent</a></li> <li data-name="module:zrender/shape/Base#style"><a href="module-zrender_shape_Base.html#style">style</a></li> <li data-name="module:zrender/shape/Base#z"><a href="module-zrender_shape_Base.html#z">z</a></li> <li data-name="module:zrender/shape/Base#zlevel"><a href="module-zrender_shape_Base.html#zlevel">zlevel</a></li> <li data-name="module:zrender/shape/Base#position"><a href="module-zrender_shape_Base.html#position">position</a></li> <li data-name="module:zrender/shape/Base#rotation"><a href="module-zrender_shape_Base.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Base#scale"><a href="module-zrender_shape_Base.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Base~IBaseShapeStyle"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">IBaseShapeStyle</a></li> <li data-name="module:zrender/shape/Base~IBoundingRect"><a href="module-zrender_shape_Base.html#~IBoundingRect">IBoundingRect</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Base#afterBrush"><a href="module-zrender_shape_Base.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Base#beforeBrush"><a href="module-zrender_shape_Base.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Base#brush"><a href="module-zrender_shape_Base.html#brush">brush</a></li> <li data-name="module:zrender/shape/Base#buildPath"><a href="module-zrender_shape_Base.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Base#drawText"><a href="module-zrender_shape_Base.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Base#drift"><a href="module-zrender_shape_Base.html#drift">drift</a></li> <li data-name="module:zrender/shape/Base#getHighlightStyle"><a href="module-zrender_shape_Base.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Base#getRect"><a href="module-zrender_shape_Base.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Base#isCover"><a href="module-zrender_shape_Base.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Base#isSilent"><a href="module-zrender_shape_Base.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Base#setContext"><a href="module-zrender_shape_Base.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Base#bind"><a href="module-zrender_shape_Base.html#bind">bind</a></li> <li data-name="module:zrender/shape/Base#decomposeTransform"><a href="module-zrender_shape_Base.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Base#dispatch"><a href="module-zrender_shape_Base.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Base#dispatchWithContext"><a href="module-zrender_shape_Base.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Base#lookAt"><a href="module-zrender_shape_Base.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Base#one"><a href="module-zrender_shape_Base.html#one">one</a></li> <li data-name="module:zrender/shape/Base#setTransform"><a href="module-zrender_shape_Base.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Base#transformCoordToLocal"><a href="module-zrender_shape_Base.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Base#unbind"><a href="module-zrender_shape_Base.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Base#updateTransform"><a href="module-zrender_shape_Base.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Base#event:onclick"><a href="module-zrender_shape_Base.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Base#event:ondragend"><a href="module-zrender_shape_Base.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Base#event:ondragenter"><a href="module-zrender_shape_Base.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Base#event:ondragleave"><a href="module-zrender_shape_Base.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Base#event:ondragover"><a href="module-zrender_shape_Base.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Base#event:ondragstart"><a href="module-zrender_shape_Base.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Base#event:ondrop"><a href="module-zrender_shape_Base.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Base#event:onmousedown"><a href="module-zrender_shape_Base.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Base#event:onmousemove"><a href="module-zrender_shape_Base.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Base#event:onmouseout"><a href="module-zrender_shape_Base.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Base#event:onmouseover"><a href="module-zrender_shape_Base.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Base#event:onmouseup"><a href="module-zrender_shape_Base.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Base#event:onmousewheel"><a href="module-zrender_shape_Base.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/BezierCurve"> <span class="title"> <a href="module-zrender_shape_BezierCurve.html">module:zrender/shape/BezierCurve</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/BezierCurve#highlightStyle"><a href="module-zrender_shape_BezierCurve.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/BezierCurve#style"><a href="module-zrender_shape_BezierCurve.html#style">style</a></li> <li data-name="module:zrender/shape/BezierCurve#id"><a href="module-zrender_shape_BezierCurve.html#id">id</a></li> <li data-name="module:zrender/shape/BezierCurve#parent"><a href="module-zrender_shape_BezierCurve.html#parent">parent</a></li> <li data-name="module:zrender/shape/BezierCurve#position"><a href="module-zrender_shape_BezierCurve.html#position">position</a></li> <li data-name="module:zrender/shape/BezierCurve#rotation"><a href="module-zrender_shape_BezierCurve.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/BezierCurve#scale"><a href="module-zrender_shape_BezierCurve.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/BezierCurve~IBezierCurveStyle"><a href="module-zrender_shape_BezierCurve.html#~IBezierCurveStyle">IBezierCurveStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/BezierCurve#buildPath"><a href="module-zrender_shape_BezierCurve.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/BezierCurve#getRect"><a href="module-zrender_shape_BezierCurve.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/BezierCurve#afterBrush"><a href="module-zrender_shape_BezierCurve.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/BezierCurve#beforeBrush"><a href="module-zrender_shape_BezierCurve.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/BezierCurve#bind"><a href="module-zrender_shape_BezierCurve.html#bind">bind</a></li> <li data-name="module:zrender/shape/BezierCurve#brush"><a href="module-zrender_shape_BezierCurve.html#brush">brush</a></li> <li data-name="module:zrender/shape/BezierCurve#decomposeTransform"><a href="module-zrender_shape_BezierCurve.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/BezierCurve#dispatch"><a href="module-zrender_shape_BezierCurve.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/BezierCurve#dispatchWithContext"><a href="module-zrender_shape_BezierCurve.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/BezierCurve#drawText"><a href="module-zrender_shape_BezierCurve.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/BezierCurve#drift"><a href="module-zrender_shape_BezierCurve.html#drift">drift</a></li> <li data-name="module:zrender/shape/BezierCurve#getHighlightStyle"><a href="module-zrender_shape_BezierCurve.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/BezierCurve#isCover"><a href="module-zrender_shape_BezierCurve.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/BezierCurve#isSilent"><a href="module-zrender_shape_BezierCurve.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/BezierCurve#lookAt"><a href="module-zrender_shape_BezierCurve.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/BezierCurve#one"><a href="module-zrender_shape_BezierCurve.html#one">one</a></li> <li data-name="module:zrender/shape/BezierCurve#setContext"><a href="module-zrender_shape_BezierCurve.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/BezierCurve#setTransform"><a href="module-zrender_shape_BezierCurve.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/BezierCurve#transformCoordToLocal"><a href="module-zrender_shape_BezierCurve.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/BezierCurve#unbind"><a href="module-zrender_shape_BezierCurve.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/BezierCurve#updateTransform"><a href="module-zrender_shape_BezierCurve.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/BezierCurve#event:onclick"><a href="module-zrender_shape_BezierCurve.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondragend"><a href="module-zrender_shape_BezierCurve.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondragenter"><a href="module-zrender_shape_BezierCurve.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondragleave"><a href="module-zrender_shape_BezierCurve.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondragover"><a href="module-zrender_shape_BezierCurve.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondragstart"><a href="module-zrender_shape_BezierCurve.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/BezierCurve#event:ondrop"><a href="module-zrender_shape_BezierCurve.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmousedown"><a href="module-zrender_shape_BezierCurve.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmousemove"><a href="module-zrender_shape_BezierCurve.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmouseout"><a href="module-zrender_shape_BezierCurve.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmouseover"><a href="module-zrender_shape_BezierCurve.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmouseup"><a href="module-zrender_shape_BezierCurve.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/BezierCurve#event:onmousewheel"><a href="module-zrender_shape_BezierCurve.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Circle"> <span class="title"> <a href="module-zrender_shape_Circle.html">module:zrender/shape/Circle</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Circle#highlightStyle"><a href="module-zrender_shape_Circle.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Circle#style"><a href="module-zrender_shape_Circle.html#style">style</a></li> <li data-name="module:zrender/shape/Circle#id"><a href="module-zrender_shape_Circle.html#id">id</a></li> <li data-name="module:zrender/shape/Circle#parent"><a href="module-zrender_shape_Circle.html#parent">parent</a></li> <li data-name="module:zrender/shape/Circle#position"><a href="module-zrender_shape_Circle.html#position">position</a></li> <li data-name="module:zrender/shape/Circle#rotation"><a href="module-zrender_shape_Circle.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Circle#scale"><a href="module-zrender_shape_Circle.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Circle~ICircleStyle"><a href="module-zrender_shape_Circle.html#~ICircleStyle">ICircleStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Circle#buildPath"><a href="module-zrender_shape_Circle.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Circle#getRect"><a href="module-zrender_shape_Circle.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Circle#afterBrush"><a href="module-zrender_shape_Circle.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Circle#beforeBrush"><a href="module-zrender_shape_Circle.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Circle#bind"><a href="module-zrender_shape_Circle.html#bind">bind</a></li> <li data-name="module:zrender/shape/Circle#brush"><a href="module-zrender_shape_Circle.html#brush">brush</a></li> <li data-name="module:zrender/shape/Circle#decomposeTransform"><a href="module-zrender_shape_Circle.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Circle#dispatch"><a href="module-zrender_shape_Circle.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Circle#dispatchWithContext"><a href="module-zrender_shape_Circle.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Circle#drawText"><a href="module-zrender_shape_Circle.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Circle#drift"><a href="module-zrender_shape_Circle.html#drift">drift</a></li> <li data-name="module:zrender/shape/Circle#getHighlightStyle"><a href="module-zrender_shape_Circle.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Circle#isCover"><a href="module-zrender_shape_Circle.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Circle#isSilent"><a href="module-zrender_shape_Circle.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Circle#lookAt"><a href="module-zrender_shape_Circle.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Circle#one"><a href="module-zrender_shape_Circle.html#one">one</a></li> <li data-name="module:zrender/shape/Circle#setContext"><a href="module-zrender_shape_Circle.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Circle#setTransform"><a href="module-zrender_shape_Circle.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Circle#transformCoordToLocal"><a href="module-zrender_shape_Circle.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Circle#unbind"><a href="module-zrender_shape_Circle.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Circle#updateTransform"><a href="module-zrender_shape_Circle.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Circle#event:onclick"><a href="module-zrender_shape_Circle.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Circle#event:ondragend"><a href="module-zrender_shape_Circle.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Circle#event:ondragenter"><a href="module-zrender_shape_Circle.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Circle#event:ondragleave"><a href="module-zrender_shape_Circle.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Circle#event:ondragover"><a href="module-zrender_shape_Circle.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Circle#event:ondragstart"><a href="module-zrender_shape_Circle.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Circle#event:ondrop"><a href="module-zrender_shape_Circle.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Circle#event:onmousedown"><a href="module-zrender_shape_Circle.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Circle#event:onmousemove"><a href="module-zrender_shape_Circle.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Circle#event:onmouseout"><a href="module-zrender_shape_Circle.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Circle#event:onmouseover"><a href="module-zrender_shape_Circle.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Circle#event:onmouseup"><a href="module-zrender_shape_Circle.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Circle#event:onmousewheel"><a href="module-zrender_shape_Circle.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Droplet"> <span class="title"> <a href="module-zrender_shape_Droplet.html">module:zrender/shape/Droplet</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Droplet#highlightStyle"><a href="module-zrender_shape_Droplet.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Droplet#style"><a href="module-zrender_shape_Droplet.html#style">style</a></li> <li data-name="module:zrender/shape/Droplet#id"><a href="module-zrender_shape_Droplet.html#id">id</a></li> <li data-name="module:zrender/shape/Droplet#parent"><a href="module-zrender_shape_Droplet.html#parent">parent</a></li> <li data-name="module:zrender/shape/Droplet#position"><a href="module-zrender_shape_Droplet.html#position">position</a></li> <li data-name="module:zrender/shape/Droplet#rotation"><a href="module-zrender_shape_Droplet.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Droplet#scale"><a href="module-zrender_shape_Droplet.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Droplet~IDropletStyle"><a href="module-zrender_shape_Droplet.html#~IDropletStyle">IDropletStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Droplet#buildPath"><a href="module-zrender_shape_Droplet.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Droplet#getRect"><a href="module-zrender_shape_Droplet.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Droplet#afterBrush"><a href="module-zrender_shape_Droplet.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Droplet#beforeBrush"><a href="module-zrender_shape_Droplet.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Droplet#bind"><a href="module-zrender_shape_Droplet.html#bind">bind</a></li> <li data-name="module:zrender/shape/Droplet#brush"><a href="module-zrender_shape_Droplet.html#brush">brush</a></li> <li data-name="module:zrender/shape/Droplet#decomposeTransform"><a href="module-zrender_shape_Droplet.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Droplet#dispatch"><a href="module-zrender_shape_Droplet.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Droplet#dispatchWithContext"><a href="module-zrender_shape_Droplet.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Droplet#drawText"><a href="module-zrender_shape_Droplet.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Droplet#drift"><a href="module-zrender_shape_Droplet.html#drift">drift</a></li> <li data-name="module:zrender/shape/Droplet#getHighlightStyle"><a href="module-zrender_shape_Droplet.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Droplet#isCover"><a href="module-zrender_shape_Droplet.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Droplet#isSilent"><a href="module-zrender_shape_Droplet.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Droplet#lookAt"><a href="module-zrender_shape_Droplet.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Droplet#one"><a href="module-zrender_shape_Droplet.html#one">one</a></li> <li data-name="module:zrender/shape/Droplet#setContext"><a href="module-zrender_shape_Droplet.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Droplet#setTransform"><a href="module-zrender_shape_Droplet.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Droplet#transformCoordToLocal"><a href="module-zrender_shape_Droplet.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Droplet#unbind"><a href="module-zrender_shape_Droplet.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Droplet#updateTransform"><a href="module-zrender_shape_Droplet.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Droplet#event:onclick"><a href="module-zrender_shape_Droplet.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Droplet#event:ondragend"><a href="module-zrender_shape_Droplet.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Droplet#event:ondragenter"><a href="module-zrender_shape_Droplet.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Droplet#event:ondragleave"><a href="module-zrender_shape_Droplet.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Droplet#event:ondragover"><a href="module-zrender_shape_Droplet.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Droplet#event:ondragstart"><a href="module-zrender_shape_Droplet.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Droplet#event:ondrop"><a href="module-zrender_shape_Droplet.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Droplet#event:onmousedown"><a href="module-zrender_shape_Droplet.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Droplet#event:onmousemove"><a href="module-zrender_shape_Droplet.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Droplet#event:onmouseout"><a href="module-zrender_shape_Droplet.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Droplet#event:onmouseover"><a href="module-zrender_shape_Droplet.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Droplet#event:onmouseup"><a href="module-zrender_shape_Droplet.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Droplet#event:onmousewheel"><a href="module-zrender_shape_Droplet.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Ellipse"> <span class="title"> <a href="module-zrender_shape_Ellipse.html">module:zrender/shape/Ellipse</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Ellipse#highlightStyle"><a href="module-zrender_shape_Ellipse.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Ellipse#style"><a href="module-zrender_shape_Ellipse.html#style">style</a></li> <li data-name="module:zrender/shape/Ellipse#id"><a href="module-zrender_shape_Ellipse.html#id">id</a></li> <li data-name="module:zrender/shape/Ellipse#parent"><a href="module-zrender_shape_Ellipse.html#parent">parent</a></li> <li data-name="module:zrender/shape/Ellipse#position"><a href="module-zrender_shape_Ellipse.html#position">position</a></li> <li data-name="module:zrender/shape/Ellipse#rotation"><a href="module-zrender_shape_Ellipse.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Ellipse#scale"><a href="module-zrender_shape_Ellipse.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Ellipse~IEllipseStyle"><a href="module-zrender_shape_Ellipse.html#~IEllipseStyle">IEllipseStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Ellipse#buildPath"><a href="module-zrender_shape_Ellipse.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Ellipse#getRect"><a href="module-zrender_shape_Ellipse.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Ellipse#afterBrush"><a href="module-zrender_shape_Ellipse.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Ellipse#beforeBrush"><a href="module-zrender_shape_Ellipse.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Ellipse#bind"><a href="module-zrender_shape_Ellipse.html#bind">bind</a></li> <li data-name="module:zrender/shape/Ellipse#brush"><a href="module-zrender_shape_Ellipse.html#brush">brush</a></li> <li data-name="module:zrender/shape/Ellipse#decomposeTransform"><a href="module-zrender_shape_Ellipse.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Ellipse#dispatch"><a href="module-zrender_shape_Ellipse.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Ellipse#dispatchWithContext"><a href="module-zrender_shape_Ellipse.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Ellipse#drawText"><a href="module-zrender_shape_Ellipse.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Ellipse#drift"><a href="module-zrender_shape_Ellipse.html#drift">drift</a></li> <li data-name="module:zrender/shape/Ellipse#getHighlightStyle"><a href="module-zrender_shape_Ellipse.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Ellipse#isCover"><a href="module-zrender_shape_Ellipse.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Ellipse#isSilent"><a href="module-zrender_shape_Ellipse.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Ellipse#lookAt"><a href="module-zrender_shape_Ellipse.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Ellipse#one"><a href="module-zrender_shape_Ellipse.html#one">one</a></li> <li data-name="module:zrender/shape/Ellipse#setContext"><a href="module-zrender_shape_Ellipse.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Ellipse#setTransform"><a href="module-zrender_shape_Ellipse.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Ellipse#transformCoordToLocal"><a href="module-zrender_shape_Ellipse.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Ellipse#unbind"><a href="module-zrender_shape_Ellipse.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Ellipse#updateTransform"><a href="module-zrender_shape_Ellipse.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Ellipse#event:onclick"><a href="module-zrender_shape_Ellipse.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondragend"><a href="module-zrender_shape_Ellipse.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondragenter"><a href="module-zrender_shape_Ellipse.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondragleave"><a href="module-zrender_shape_Ellipse.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondragover"><a href="module-zrender_shape_Ellipse.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondragstart"><a href="module-zrender_shape_Ellipse.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Ellipse#event:ondrop"><a href="module-zrender_shape_Ellipse.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmousedown"><a href="module-zrender_shape_Ellipse.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmousemove"><a href="module-zrender_shape_Ellipse.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmouseout"><a href="module-zrender_shape_Ellipse.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmouseover"><a href="module-zrender_shape_Ellipse.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmouseup"><a href="module-zrender_shape_Ellipse.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Ellipse#event:onmousewheel"><a href="module-zrender_shape_Ellipse.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Heart"> <span class="title"> <a href="module-zrender_shape_Heart.html">module:zrender/shape/Heart</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Heart#highlightStyle"><a href="module-zrender_shape_Heart.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Heart#style"><a href="module-zrender_shape_Heart.html#style">style</a></li> <li data-name="module:zrender/shape/Heart#id"><a href="module-zrender_shape_Heart.html#id">id</a></li> <li data-name="module:zrender/shape/Heart#parent"><a href="module-zrender_shape_Heart.html#parent">parent</a></li> <li data-name="module:zrender/shape/Heart#position"><a href="module-zrender_shape_Heart.html#position">position</a></li> <li data-name="module:zrender/shape/Heart#rotation"><a href="module-zrender_shape_Heart.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Heart#scale"><a href="module-zrender_shape_Heart.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Heart~IHeartStyle"><a href="module-zrender_shape_Heart.html#~IHeartStyle">IHeartStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Heart#buildPath"><a href="module-zrender_shape_Heart.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Heart#getRect"><a href="module-zrender_shape_Heart.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Heart#afterBrush"><a href="module-zrender_shape_Heart.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Heart#beforeBrush"><a href="module-zrender_shape_Heart.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Heart#bind"><a href="module-zrender_shape_Heart.html#bind">bind</a></li> <li data-name="module:zrender/shape/Heart#brush"><a href="module-zrender_shape_Heart.html#brush">brush</a></li> <li data-name="module:zrender/shape/Heart#decomposeTransform"><a href="module-zrender_shape_Heart.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Heart#dispatch"><a href="module-zrender_shape_Heart.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Heart#dispatchWithContext"><a href="module-zrender_shape_Heart.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Heart#drawText"><a href="module-zrender_shape_Heart.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Heart#drift"><a href="module-zrender_shape_Heart.html#drift">drift</a></li> <li data-name="module:zrender/shape/Heart#getHighlightStyle"><a href="module-zrender_shape_Heart.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Heart#isCover"><a href="module-zrender_shape_Heart.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Heart#isSilent"><a href="module-zrender_shape_Heart.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Heart#lookAt"><a href="module-zrender_shape_Heart.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Heart#one"><a href="module-zrender_shape_Heart.html#one">one</a></li> <li data-name="module:zrender/shape/Heart#setContext"><a href="module-zrender_shape_Heart.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Heart#setTransform"><a href="module-zrender_shape_Heart.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Heart#transformCoordToLocal"><a href="module-zrender_shape_Heart.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Heart#unbind"><a href="module-zrender_shape_Heart.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Heart#updateTransform"><a href="module-zrender_shape_Heart.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Heart#event:onclick"><a href="module-zrender_shape_Heart.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Heart#event:ondragend"><a href="module-zrender_shape_Heart.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Heart#event:ondragenter"><a href="module-zrender_shape_Heart.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Heart#event:ondragleave"><a href="module-zrender_shape_Heart.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Heart#event:ondragover"><a href="module-zrender_shape_Heart.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Heart#event:ondragstart"><a href="module-zrender_shape_Heart.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Heart#event:ondrop"><a href="module-zrender_shape_Heart.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Heart#event:onmousedown"><a href="module-zrender_shape_Heart.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Heart#event:onmousemove"><a href="module-zrender_shape_Heart.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Heart#event:onmouseout"><a href="module-zrender_shape_Heart.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Heart#event:onmouseover"><a href="module-zrender_shape_Heart.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Heart#event:onmouseup"><a href="module-zrender_shape_Heart.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Heart#event:onmousewheel"><a href="module-zrender_shape_Heart.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Image"> <span class="title"> <a href="module-zrender_shape_Image.html">module:zrender/shape/Image</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Image#highlightStyle"><a href="module-zrender_shape_Image.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Image#style"><a href="module-zrender_shape_Image.html#style">style</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Image~IImageStyle"><a href="module-zrender_shape_Image.html#~IImageStyle">IImageStyle</a></li> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/Isogon"> <span class="title"> <a href="module-zrender_shape_Isogon.html">module:zrender/shape/Isogon</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Isogon#highlightStyle"><a href="module-zrender_shape_Isogon.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Isogon#style"><a href="module-zrender_shape_Isogon.html#style">style</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Isogon~IIsogonStyle"><a href="module-zrender_shape_Isogon.html#~IIsogonStyle">IIsogonStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Isogon#buildPath"><a href="module-zrender_shape_Isogon.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Isogon#getRect"><a href="module-zrender_shape_Isogon.html#getRect">getRect</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/Line"> <span class="title"> <a href="module-zrender_shape_Line.html">module:zrender/shape/Line</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Line#highlightStyle"><a href="module-zrender_shape_Line.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Line#style"><a href="module-zrender_shape_Line.html#style">style</a></li> <li data-name="module:zrender/shape/Line#id"><a href="module-zrender_shape_Line.html#id">id</a></li> <li data-name="module:zrender/shape/Line#parent"><a href="module-zrender_shape_Line.html#parent">parent</a></li> <li data-name="module:zrender/shape/Line#position"><a href="module-zrender_shape_Line.html#position">position</a></li> <li data-name="module:zrender/shape/Line#rotation"><a href="module-zrender_shape_Line.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Line#scale"><a href="module-zrender_shape_Line.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Line~ILineStyle"><a href="module-zrender_shape_Line.html#~ILineStyle">ILineStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Line#buildPath"><a href="module-zrender_shape_Line.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Line#getRect"><a href="module-zrender_shape_Line.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Line#afterBrush"><a href="module-zrender_shape_Line.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Line#beforeBrush"><a href="module-zrender_shape_Line.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Line#bind"><a href="module-zrender_shape_Line.html#bind">bind</a></li> <li data-name="module:zrender/shape/Line#brush"><a href="module-zrender_shape_Line.html#brush">brush</a></li> <li data-name="module:zrender/shape/Line#decomposeTransform"><a href="module-zrender_shape_Line.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Line#dispatch"><a href="module-zrender_shape_Line.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Line#dispatchWithContext"><a href="module-zrender_shape_Line.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Line#drawText"><a href="module-zrender_shape_Line.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Line#drift"><a href="module-zrender_shape_Line.html#drift">drift</a></li> <li data-name="module:zrender/shape/Line#getHighlightStyle"><a href="module-zrender_shape_Line.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Line#isCover"><a href="module-zrender_shape_Line.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Line#isSilent"><a href="module-zrender_shape_Line.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Line#lookAt"><a href="module-zrender_shape_Line.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Line#one"><a href="module-zrender_shape_Line.html#one">one</a></li> <li data-name="module:zrender/shape/Line#setContext"><a href="module-zrender_shape_Line.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Line#setTransform"><a href="module-zrender_shape_Line.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Line#transformCoordToLocal"><a href="module-zrender_shape_Line.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Line#unbind"><a href="module-zrender_shape_Line.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Line#updateTransform"><a href="module-zrender_shape_Line.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Line#event:onclick"><a href="module-zrender_shape_Line.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Line#event:ondragend"><a href="module-zrender_shape_Line.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Line#event:ondragenter"><a href="module-zrender_shape_Line.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Line#event:ondragleave"><a href="module-zrender_shape_Line.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Line#event:ondragover"><a href="module-zrender_shape_Line.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Line#event:ondragstart"><a href="module-zrender_shape_Line.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Line#event:ondrop"><a href="module-zrender_shape_Line.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Line#event:onmousedown"><a href="module-zrender_shape_Line.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Line#event:onmousemove"><a href="module-zrender_shape_Line.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Line#event:onmouseout"><a href="module-zrender_shape_Line.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Line#event:onmouseover"><a href="module-zrender_shape_Line.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Line#event:onmouseup"><a href="module-zrender_shape_Line.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Line#event:onmousewheel"><a href="module-zrender_shape_Line.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Path"> <span class="title"> <a href="module-zrender_shape_Path.html">module:zrender/shape/Path</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Path#highlightStyle"><a href="module-zrender_shape_Path.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Path#style"><a href="module-zrender_shape_Path.html#style">style</a></li> <li data-name="module:zrender/shape/Path#id"><a href="module-zrender_shape_Path.html#id">id</a></li> <li data-name="module:zrender/shape/Path#parent"><a href="module-zrender_shape_Path.html#parent">parent</a></li> <li data-name="module:zrender/shape/Path#position"><a href="module-zrender_shape_Path.html#position">position</a></li> <li data-name="module:zrender/shape/Path#rotation"><a href="module-zrender_shape_Path.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Path#scale"><a href="module-zrender_shape_Path.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Path~IPathStyle"><a href="module-zrender_shape_Path.html#~IPathStyle">IPathStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Path#buildPath"><a href="module-zrender_shape_Path.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Path#getRect"><a href="module-zrender_shape_Path.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Path#afterBrush"><a href="module-zrender_shape_Path.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Path#beforeBrush"><a href="module-zrender_shape_Path.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Path#bind"><a href="module-zrender_shape_Path.html#bind">bind</a></li> <li data-name="module:zrender/shape/Path#brush"><a href="module-zrender_shape_Path.html#brush">brush</a></li> <li data-name="module:zrender/shape/Path#decomposeTransform"><a href="module-zrender_shape_Path.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Path#dispatch"><a href="module-zrender_shape_Path.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Path#dispatchWithContext"><a href="module-zrender_shape_Path.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Path#drawText"><a href="module-zrender_shape_Path.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Path#drift"><a href="module-zrender_shape_Path.html#drift">drift</a></li> <li data-name="module:zrender/shape/Path#getHighlightStyle"><a href="module-zrender_shape_Path.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Path#isCover"><a href="module-zrender_shape_Path.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Path#isSilent"><a href="module-zrender_shape_Path.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Path#lookAt"><a href="module-zrender_shape_Path.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Path#one"><a href="module-zrender_shape_Path.html#one">one</a></li> <li data-name="module:zrender/shape/Path#setContext"><a href="module-zrender_shape_Path.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Path#setTransform"><a href="module-zrender_shape_Path.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Path#transformCoordToLocal"><a href="module-zrender_shape_Path.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Path#unbind"><a href="module-zrender_shape_Path.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Path#updateTransform"><a href="module-zrender_shape_Path.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Path#event:onclick"><a href="module-zrender_shape_Path.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Path#event:ondragend"><a href="module-zrender_shape_Path.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Path#event:ondragenter"><a href="module-zrender_shape_Path.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Path#event:ondragleave"><a href="module-zrender_shape_Path.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Path#event:ondragover"><a href="module-zrender_shape_Path.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Path#event:ondragstart"><a href="module-zrender_shape_Path.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Path#event:ondrop"><a href="module-zrender_shape_Path.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Path#event:onmousedown"><a href="module-zrender_shape_Path.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Path#event:onmousemove"><a href="module-zrender_shape_Path.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Path#event:onmouseout"><a href="module-zrender_shape_Path.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Path#event:onmouseover"><a href="module-zrender_shape_Path.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Path#event:onmouseup"><a href="module-zrender_shape_Path.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Path#event:onmousewheel"><a href="module-zrender_shape_Path.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Polygon"> <span class="title"> <a href="module-zrender_shape_Polygon.html">module:zrender/shape/Polygon</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Polygon#highlightStyle"><a href="module-zrender_shape_Polygon.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Polygon#style"><a href="module-zrender_shape_Polygon.html#style">style</a></li> <li data-name="module:zrender/shape/Polygon#id"><a href="module-zrender_shape_Polygon.html#id">id</a></li> <li data-name="module:zrender/shape/Polygon#parent"><a href="module-zrender_shape_Polygon.html#parent">parent</a></li> <li data-name="module:zrender/shape/Polygon#position"><a href="module-zrender_shape_Polygon.html#position">position</a></li> <li data-name="module:zrender/shape/Polygon#rotation"><a href="module-zrender_shape_Polygon.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Polygon#scale"><a href="module-zrender_shape_Polygon.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Polygon~IPolygonStyle"><a href="module-zrender_shape_Polygon.html#~IPolygonStyle">IPolygonStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Polygon#buildPath"><a href="module-zrender_shape_Polygon.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Polygon#getRect"><a href="module-zrender_shape_Polygon.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Polygon#afterBrush"><a href="module-zrender_shape_Polygon.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Polygon#beforeBrush"><a href="module-zrender_shape_Polygon.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Polygon#bind"><a href="module-zrender_shape_Polygon.html#bind">bind</a></li> <li data-name="module:zrender/shape/Polygon#brush"><a href="module-zrender_shape_Polygon.html#brush">brush</a></li> <li data-name="module:zrender/shape/Polygon#decomposeTransform"><a href="module-zrender_shape_Polygon.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Polygon#dispatch"><a href="module-zrender_shape_Polygon.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Polygon#dispatchWithContext"><a href="module-zrender_shape_Polygon.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Polygon#drawText"><a href="module-zrender_shape_Polygon.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Polygon#drift"><a href="module-zrender_shape_Polygon.html#drift">drift</a></li> <li data-name="module:zrender/shape/Polygon#getHighlightStyle"><a href="module-zrender_shape_Polygon.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Polygon#isCover"><a href="module-zrender_shape_Polygon.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Polygon#isSilent"><a href="module-zrender_shape_Polygon.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Polygon#lookAt"><a href="module-zrender_shape_Polygon.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Polygon#one"><a href="module-zrender_shape_Polygon.html#one">one</a></li> <li data-name="module:zrender/shape/Polygon#setContext"><a href="module-zrender_shape_Polygon.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Polygon#setTransform"><a href="module-zrender_shape_Polygon.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Polygon#transformCoordToLocal"><a href="module-zrender_shape_Polygon.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Polygon#unbind"><a href="module-zrender_shape_Polygon.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Polygon#updateTransform"><a href="module-zrender_shape_Polygon.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Polygon#event:onclick"><a href="module-zrender_shape_Polygon.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Polygon#event:ondragend"><a href="module-zrender_shape_Polygon.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Polygon#event:ondragenter"><a href="module-zrender_shape_Polygon.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Polygon#event:ondragleave"><a href="module-zrender_shape_Polygon.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Polygon#event:ondragover"><a href="module-zrender_shape_Polygon.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Polygon#event:ondragstart"><a href="module-zrender_shape_Polygon.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Polygon#event:ondrop"><a href="module-zrender_shape_Polygon.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Polygon#event:onmousedown"><a href="module-zrender_shape_Polygon.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Polygon#event:onmousemove"><a href="module-zrender_shape_Polygon.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Polygon#event:onmouseout"><a href="module-zrender_shape_Polygon.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Polygon#event:onmouseover"><a href="module-zrender_shape_Polygon.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Polygon#event:onmouseup"><a href="module-zrender_shape_Polygon.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Polygon#event:onmousewheel"><a href="module-zrender_shape_Polygon.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Polyline"> <span class="title"> <a href="module-zrender_shape_Polyline.html">module:zrender/shape/Polyline</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Polyline#highlightStyle"><a href="module-zrender_shape_Polyline.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Polyline#style"><a href="module-zrender_shape_Polyline.html#style">style</a></li> <li data-name="module:zrender/shape/Polyline#id"><a href="module-zrender_shape_Polyline.html#id">id</a></li> <li data-name="module:zrender/shape/Polyline#parent"><a href="module-zrender_shape_Polyline.html#parent">parent</a></li> <li data-name="module:zrender/shape/Polyline#position"><a href="module-zrender_shape_Polyline.html#position">position</a></li> <li data-name="module:zrender/shape/Polyline#rotation"><a href="module-zrender_shape_Polyline.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Polyline#scale"><a href="module-zrender_shape_Polyline.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Polyline~IPolylineStyle"><a href="module-zrender_shape_Polyline.html#~IPolylineStyle">IPolylineStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Polyline#buildPath"><a href="module-zrender_shape_Polyline.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Polyline#getRect"><a href="module-zrender_shape_Polyline.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Polyline#afterBrush"><a href="module-zrender_shape_Polyline.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Polyline#beforeBrush"><a href="module-zrender_shape_Polyline.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Polyline#bind"><a href="module-zrender_shape_Polyline.html#bind">bind</a></li> <li data-name="module:zrender/shape/Polyline#brush"><a href="module-zrender_shape_Polyline.html#brush">brush</a></li> <li data-name="module:zrender/shape/Polyline#decomposeTransform"><a href="module-zrender_shape_Polyline.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Polyline#dispatch"><a href="module-zrender_shape_Polyline.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Polyline#dispatchWithContext"><a href="module-zrender_shape_Polyline.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Polyline#drawText"><a href="module-zrender_shape_Polyline.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Polyline#drift"><a href="module-zrender_shape_Polyline.html#drift">drift</a></li> <li data-name="module:zrender/shape/Polyline#getHighlightStyle"><a href="module-zrender_shape_Polyline.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Polyline#isCover"><a href="module-zrender_shape_Polyline.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Polyline#isSilent"><a href="module-zrender_shape_Polyline.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Polyline#lookAt"><a href="module-zrender_shape_Polyline.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Polyline#one"><a href="module-zrender_shape_Polyline.html#one">one</a></li> <li data-name="module:zrender/shape/Polyline#setContext"><a href="module-zrender_shape_Polyline.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Polyline#setTransform"><a href="module-zrender_shape_Polyline.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Polyline#transformCoordToLocal"><a href="module-zrender_shape_Polyline.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Polyline#unbind"><a href="module-zrender_shape_Polyline.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Polyline#updateTransform"><a href="module-zrender_shape_Polyline.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Polyline#event:onclick"><a href="module-zrender_shape_Polyline.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Polyline#event:ondragend"><a href="module-zrender_shape_Polyline.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Polyline#event:ondragenter"><a href="module-zrender_shape_Polyline.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Polyline#event:ondragleave"><a href="module-zrender_shape_Polyline.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Polyline#event:ondragover"><a href="module-zrender_shape_Polyline.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Polyline#event:ondragstart"><a href="module-zrender_shape_Polyline.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Polyline#event:ondrop"><a href="module-zrender_shape_Polyline.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Polyline#event:onmousedown"><a href="module-zrender_shape_Polyline.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Polyline#event:onmousemove"><a href="module-zrender_shape_Polyline.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Polyline#event:onmouseout"><a href="module-zrender_shape_Polyline.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Polyline#event:onmouseover"><a href="module-zrender_shape_Polyline.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Polyline#event:onmouseup"><a href="module-zrender_shape_Polyline.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Polyline#event:onmousewheel"><a href="module-zrender_shape_Polyline.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Rectangle"> <span class="title"> <a href="module-zrender_shape_Rectangle.html">module:zrender/shape/Rectangle</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Rectangle#highlightStyle"><a href="module-zrender_shape_Rectangle.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Rectangle#style"><a href="module-zrender_shape_Rectangle.html#style">style</a></li> <li data-name="module:zrender/shape/Rectangle#id"><a href="module-zrender_shape_Rectangle.html#id">id</a></li> <li data-name="module:zrender/shape/Rectangle#parent"><a href="module-zrender_shape_Rectangle.html#parent">parent</a></li> <li data-name="module:zrender/shape/Rectangle#position"><a href="module-zrender_shape_Rectangle.html#position">position</a></li> <li data-name="module:zrender/shape/Rectangle#rotation"><a href="module-zrender_shape_Rectangle.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Rectangle#scale"><a href="module-zrender_shape_Rectangle.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Rectangle~IRectangleStyle"><a href="module-zrender_shape_Rectangle.html#~IRectangleStyle">IRectangleStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Rectangle#buildPath"><a href="module-zrender_shape_Rectangle.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Rectangle#getRect"><a href="module-zrender_shape_Rectangle.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Rectangle#afterBrush"><a href="module-zrender_shape_Rectangle.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Rectangle#beforeBrush"><a href="module-zrender_shape_Rectangle.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Rectangle#bind"><a href="module-zrender_shape_Rectangle.html#bind">bind</a></li> <li data-name="module:zrender/shape/Rectangle#brush"><a href="module-zrender_shape_Rectangle.html#brush">brush</a></li> <li data-name="module:zrender/shape/Rectangle#decomposeTransform"><a href="module-zrender_shape_Rectangle.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Rectangle#dispatch"><a href="module-zrender_shape_Rectangle.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Rectangle#dispatchWithContext"><a href="module-zrender_shape_Rectangle.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Rectangle#drawText"><a href="module-zrender_shape_Rectangle.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Rectangle#drift"><a href="module-zrender_shape_Rectangle.html#drift">drift</a></li> <li data-name="module:zrender/shape/Rectangle#getHighlightStyle"><a href="module-zrender_shape_Rectangle.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Rectangle#isCover"><a href="module-zrender_shape_Rectangle.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Rectangle#isSilent"><a href="module-zrender_shape_Rectangle.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Rectangle#lookAt"><a href="module-zrender_shape_Rectangle.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Rectangle#one"><a href="module-zrender_shape_Rectangle.html#one">one</a></li> <li data-name="module:zrender/shape/Rectangle#setContext"><a href="module-zrender_shape_Rectangle.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Rectangle#setTransform"><a href="module-zrender_shape_Rectangle.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Rectangle#transformCoordToLocal"><a href="module-zrender_shape_Rectangle.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Rectangle#unbind"><a href="module-zrender_shape_Rectangle.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Rectangle#updateTransform"><a href="module-zrender_shape_Rectangle.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Rectangle#event:onclick"><a href="module-zrender_shape_Rectangle.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondragend"><a href="module-zrender_shape_Rectangle.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondragenter"><a href="module-zrender_shape_Rectangle.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondragleave"><a href="module-zrender_shape_Rectangle.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondragover"><a href="module-zrender_shape_Rectangle.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondragstart"><a href="module-zrender_shape_Rectangle.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Rectangle#event:ondrop"><a href="module-zrender_shape_Rectangle.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmousedown"><a href="module-zrender_shape_Rectangle.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmousemove"><a href="module-zrender_shape_Rectangle.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmouseout"><a href="module-zrender_shape_Rectangle.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmouseover"><a href="module-zrender_shape_Rectangle.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmouseup"><a href="module-zrender_shape_Rectangle.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Rectangle#event:onmousewheel"><a href="module-zrender_shape_Rectangle.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Ring"> <span class="title"> <a href="module-zrender_shape_Ring.html">module:zrender/shape/Ring</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Ring#highlightStyle"><a href="module-zrender_shape_Ring.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Ring#style"><a href="module-zrender_shape_Ring.html#style">style</a></li> <li data-name="module:zrender/shape/Ring#id"><a href="module-zrender_shape_Ring.html#id">id</a></li> <li data-name="module:zrender/shape/Ring#parent"><a href="module-zrender_shape_Ring.html#parent">parent</a></li> <li data-name="module:zrender/shape/Ring#position"><a href="module-zrender_shape_Ring.html#position">position</a></li> <li data-name="module:zrender/shape/Ring#rotation"><a href="module-zrender_shape_Ring.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Ring#scale"><a href="module-zrender_shape_Ring.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Ring~IRingStyle"><a href="module-zrender_shape_Ring.html#~IRingStyle">IRingStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Ring#buildPath"><a href="module-zrender_shape_Ring.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Ring#getRect"><a href="module-zrender_shape_Ring.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Ring#afterBrush"><a href="module-zrender_shape_Ring.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Ring#beforeBrush"><a href="module-zrender_shape_Ring.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Ring#bind"><a href="module-zrender_shape_Ring.html#bind">bind</a></li> <li data-name="module:zrender/shape/Ring#brush"><a href="module-zrender_shape_Ring.html#brush">brush</a></li> <li data-name="module:zrender/shape/Ring#decomposeTransform"><a href="module-zrender_shape_Ring.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Ring#dispatch"><a href="module-zrender_shape_Ring.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Ring#dispatchWithContext"><a href="module-zrender_shape_Ring.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Ring#drawText"><a href="module-zrender_shape_Ring.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Ring#drift"><a href="module-zrender_shape_Ring.html#drift">drift</a></li> <li data-name="module:zrender/shape/Ring#getHighlightStyle"><a href="module-zrender_shape_Ring.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Ring#isCover"><a href="module-zrender_shape_Ring.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Ring#isSilent"><a href="module-zrender_shape_Ring.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Ring#lookAt"><a href="module-zrender_shape_Ring.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Ring#one"><a href="module-zrender_shape_Ring.html#one">one</a></li> <li data-name="module:zrender/shape/Ring#setContext"><a href="module-zrender_shape_Ring.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Ring#setTransform"><a href="module-zrender_shape_Ring.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Ring#transformCoordToLocal"><a href="module-zrender_shape_Ring.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Ring#unbind"><a href="module-zrender_shape_Ring.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Ring#updateTransform"><a href="module-zrender_shape_Ring.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Ring#event:onclick"><a href="module-zrender_shape_Ring.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Ring#event:ondragend"><a href="module-zrender_shape_Ring.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Ring#event:ondragenter"><a href="module-zrender_shape_Ring.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Ring#event:ondragleave"><a href="module-zrender_shape_Ring.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Ring#event:ondragover"><a href="module-zrender_shape_Ring.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Ring#event:ondragstart"><a href="module-zrender_shape_Ring.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Ring#event:ondrop"><a href="module-zrender_shape_Ring.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Ring#event:onmousedown"><a href="module-zrender_shape_Ring.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Ring#event:onmousemove"><a href="module-zrender_shape_Ring.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Ring#event:onmouseout"><a href="module-zrender_shape_Ring.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Ring#event:onmouseover"><a href="module-zrender_shape_Ring.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Ring#event:onmouseup"><a href="module-zrender_shape_Ring.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Ring#event:onmousewheel"><a href="module-zrender_shape_Ring.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Rose"> <span class="title"> <a href="module-zrender_shape_Rose.html">module:zrender/shape/Rose</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Rose#highlightStyle"><a href="module-zrender_shape_Rose.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Rose#style"><a href="module-zrender_shape_Rose.html#style">style</a></li> <li data-name="module:zrender/shape/Rose#id"><a href="module-zrender_shape_Rose.html#id">id</a></li> <li data-name="module:zrender/shape/Rose#parent"><a href="module-zrender_shape_Rose.html#parent">parent</a></li> <li data-name="module:zrender/shape/Rose#position"><a href="module-zrender_shape_Rose.html#position">position</a></li> <li data-name="module:zrender/shape/Rose#rotation"><a href="module-zrender_shape_Rose.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Rose#scale"><a href="module-zrender_shape_Rose.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Rose~IRoseStyle"><a href="module-zrender_shape_Rose.html#~IRoseStyle">IRoseStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Rose#buildPath"><a href="module-zrender_shape_Rose.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Rose#getRect"><a href="module-zrender_shape_Rose.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Rose#afterBrush"><a href="module-zrender_shape_Rose.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Rose#beforeBrush"><a href="module-zrender_shape_Rose.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Rose#bind"><a href="module-zrender_shape_Rose.html#bind">bind</a></li> <li data-name="module:zrender/shape/Rose#brush"><a href="module-zrender_shape_Rose.html#brush">brush</a></li> <li data-name="module:zrender/shape/Rose#decomposeTransform"><a href="module-zrender_shape_Rose.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Rose#dispatch"><a href="module-zrender_shape_Rose.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Rose#dispatchWithContext"><a href="module-zrender_shape_Rose.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Rose#drawText"><a href="module-zrender_shape_Rose.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Rose#drift"><a href="module-zrender_shape_Rose.html#drift">drift</a></li> <li data-name="module:zrender/shape/Rose#getHighlightStyle"><a href="module-zrender_shape_Rose.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Rose#isCover"><a href="module-zrender_shape_Rose.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Rose#isSilent"><a href="module-zrender_shape_Rose.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Rose#lookAt"><a href="module-zrender_shape_Rose.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Rose#one"><a href="module-zrender_shape_Rose.html#one">one</a></li> <li data-name="module:zrender/shape/Rose#setContext"><a href="module-zrender_shape_Rose.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Rose#setTransform"><a href="module-zrender_shape_Rose.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Rose#transformCoordToLocal"><a href="module-zrender_shape_Rose.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Rose#unbind"><a href="module-zrender_shape_Rose.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Rose#updateTransform"><a href="module-zrender_shape_Rose.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Rose#event:onclick"><a href="module-zrender_shape_Rose.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Rose#event:ondragend"><a href="module-zrender_shape_Rose.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Rose#event:ondragenter"><a href="module-zrender_shape_Rose.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Rose#event:ondragleave"><a href="module-zrender_shape_Rose.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Rose#event:ondragover"><a href="module-zrender_shape_Rose.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Rose#event:ondragstart"><a href="module-zrender_shape_Rose.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Rose#event:ondrop"><a href="module-zrender_shape_Rose.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Rose#event:onmousedown"><a href="module-zrender_shape_Rose.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Rose#event:onmousemove"><a href="module-zrender_shape_Rose.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Rose#event:onmouseout"><a href="module-zrender_shape_Rose.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Rose#event:onmouseover"><a href="module-zrender_shape_Rose.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Rose#event:onmouseup"><a href="module-zrender_shape_Rose.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Rose#event:onmousewheel"><a href="module-zrender_shape_Rose.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Sector"> <span class="title"> <a href="module-zrender_shape_Sector.html">module:zrender/shape/Sector</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Sector#highlightStyle"><a href="module-zrender_shape_Sector.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Sector#style"><a href="module-zrender_shape_Sector.html#style">style</a></li> <li data-name="module:zrender/shape/Sector#id"><a href="module-zrender_shape_Sector.html#id">id</a></li> <li data-name="module:zrender/shape/Sector#parent"><a href="module-zrender_shape_Sector.html#parent">parent</a></li> <li data-name="module:zrender/shape/Sector#position"><a href="module-zrender_shape_Sector.html#position">position</a></li> <li data-name="module:zrender/shape/Sector#rotation"><a href="module-zrender_shape_Sector.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Sector#scale"><a href="module-zrender_shape_Sector.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Sector~ISectorStyle"><a href="module-zrender_shape_Sector.html#~ISectorStyle">ISectorStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Sector#buildPath"><a href="module-zrender_shape_Sector.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Sector#getRect"><a href="module-zrender_shape_Sector.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Sector#afterBrush"><a href="module-zrender_shape_Sector.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Sector#beforeBrush"><a href="module-zrender_shape_Sector.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Sector#bind"><a href="module-zrender_shape_Sector.html#bind">bind</a></li> <li data-name="module:zrender/shape/Sector#brush"><a href="module-zrender_shape_Sector.html#brush">brush</a></li> <li data-name="module:zrender/shape/Sector#decomposeTransform"><a href="module-zrender_shape_Sector.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Sector#dispatch"><a href="module-zrender_shape_Sector.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Sector#dispatchWithContext"><a href="module-zrender_shape_Sector.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Sector#drawText"><a href="module-zrender_shape_Sector.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Sector#drift"><a href="module-zrender_shape_Sector.html#drift">drift</a></li> <li data-name="module:zrender/shape/Sector#getHighlightStyle"><a href="module-zrender_shape_Sector.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Sector#isCover"><a href="module-zrender_shape_Sector.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Sector#isSilent"><a href="module-zrender_shape_Sector.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Sector#lookAt"><a href="module-zrender_shape_Sector.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Sector#one"><a href="module-zrender_shape_Sector.html#one">one</a></li> <li data-name="module:zrender/shape/Sector#setContext"><a href="module-zrender_shape_Sector.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Sector#setTransform"><a href="module-zrender_shape_Sector.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Sector#transformCoordToLocal"><a href="module-zrender_shape_Sector.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Sector#unbind"><a href="module-zrender_shape_Sector.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Sector#updateTransform"><a href="module-zrender_shape_Sector.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Sector#event:onclick"><a href="module-zrender_shape_Sector.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Sector#event:ondragend"><a href="module-zrender_shape_Sector.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Sector#event:ondragenter"><a href="module-zrender_shape_Sector.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Sector#event:ondragleave"><a href="module-zrender_shape_Sector.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Sector#event:ondragover"><a href="module-zrender_shape_Sector.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Sector#event:ondragstart"><a href="module-zrender_shape_Sector.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Sector#event:ondrop"><a href="module-zrender_shape_Sector.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Sector#event:onmousedown"><a href="module-zrender_shape_Sector.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Sector#event:onmousemove"><a href="module-zrender_shape_Sector.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Sector#event:onmouseout"><a href="module-zrender_shape_Sector.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Sector#event:onmouseover"><a href="module-zrender_shape_Sector.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Sector#event:onmouseup"><a href="module-zrender_shape_Sector.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Sector#event:onmousewheel"><a href="module-zrender_shape_Sector.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/ShapeBundle"> <span class="title"> <a href="module-zrender_shape_ShapeBundle.html">module:zrender/shape/ShapeBundle</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/ShapeBundle#highlightStyle"><a href="module-zrender_shape_ShapeBundle.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/ShapeBundle#style"><a href="module-zrender_shape_ShapeBundle.html#style">style</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/ShapeBundle~IShapeBundleStyle"><a href="module-zrender_shape_ShapeBundle.html#~IShapeBundleStyle">IShapeBundleStyle</a></li> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/Star"> <span class="title"> <a href="module-zrender_shape_Star.html">module:zrender/shape/Star</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Star#highlightStyle"><a href="module-zrender_shape_Star.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Star#style"><a href="module-zrender_shape_Star.html#style">style</a></li> <li data-name="module:zrender/shape/Star#id"><a href="module-zrender_shape_Star.html#id">id</a></li> <li data-name="module:zrender/shape/Star#parent"><a href="module-zrender_shape_Star.html#parent">parent</a></li> <li data-name="module:zrender/shape/Star#position"><a href="module-zrender_shape_Star.html#position">position</a></li> <li data-name="module:zrender/shape/Star#rotation"><a href="module-zrender_shape_Star.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Star#scale"><a href="module-zrender_shape_Star.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Star~IStarStyle"><a href="module-zrender_shape_Star.html#~IStarStyle">IStarStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Star#buildPath"><a href="module-zrender_shape_Star.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Star#getRect"><a href="module-zrender_shape_Star.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Star#afterBrush"><a href="module-zrender_shape_Star.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Star#beforeBrush"><a href="module-zrender_shape_Star.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Star#bind"><a href="module-zrender_shape_Star.html#bind">bind</a></li> <li data-name="module:zrender/shape/Star#brush"><a href="module-zrender_shape_Star.html#brush">brush</a></li> <li data-name="module:zrender/shape/Star#decomposeTransform"><a href="module-zrender_shape_Star.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Star#dispatch"><a href="module-zrender_shape_Star.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Star#dispatchWithContext"><a href="module-zrender_shape_Star.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Star#drawText"><a href="module-zrender_shape_Star.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Star#drift"><a href="module-zrender_shape_Star.html#drift">drift</a></li> <li data-name="module:zrender/shape/Star#getHighlightStyle"><a href="module-zrender_shape_Star.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Star#isCover"><a href="module-zrender_shape_Star.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Star#isSilent"><a href="module-zrender_shape_Star.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Star#lookAt"><a href="module-zrender_shape_Star.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Star#one"><a href="module-zrender_shape_Star.html#one">one</a></li> <li data-name="module:zrender/shape/Star#setContext"><a href="module-zrender_shape_Star.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Star#setTransform"><a href="module-zrender_shape_Star.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Star#transformCoordToLocal"><a href="module-zrender_shape_Star.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Star#unbind"><a href="module-zrender_shape_Star.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Star#updateTransform"><a href="module-zrender_shape_Star.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Star#event:onclick"><a href="module-zrender_shape_Star.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Star#event:ondragend"><a href="module-zrender_shape_Star.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Star#event:ondragenter"><a href="module-zrender_shape_Star.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Star#event:ondragleave"><a href="module-zrender_shape_Star.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Star#event:ondragover"><a href="module-zrender_shape_Star.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Star#event:ondragstart"><a href="module-zrender_shape_Star.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Star#event:ondrop"><a href="module-zrender_shape_Star.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Star#event:onmousedown"><a href="module-zrender_shape_Star.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Star#event:onmousemove"><a href="module-zrender_shape_Star.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Star#event:onmouseout"><a href="module-zrender_shape_Star.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Star#event:onmouseover"><a href="module-zrender_shape_Star.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Star#event:onmouseup"><a href="module-zrender_shape_Star.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Star#event:onmousewheel"><a href="module-zrender_shape_Star.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/Text"> <span class="title"> <a href="module-zrender_shape_Text.html">module:zrender/shape/Text</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Text#highlightStyle"><a href="module-zrender_shape_Text.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Text#style"><a href="module-zrender_shape_Text.html#style">style</a></li> <li data-name="module:zrender/shape/Text#id"><a href="module-zrender_shape_Text.html#id">id</a></li> <li data-name="module:zrender/shape/Text#parent"><a href="module-zrender_shape_Text.html#parent">parent</a></li> <li data-name="module:zrender/shape/Text#position"><a href="module-zrender_shape_Text.html#position">position</a></li> <li data-name="module:zrender/shape/Text#rotation"><a href="module-zrender_shape_Text.html#rotation">rotation</a></li> <li data-name="module:zrender/shape/Text#scale"><a href="module-zrender_shape_Text.html#scale">scale</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Text~ITextStyle"><a href="module-zrender_shape_Text.html#~ITextStyle">ITextStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Text#getRect"><a href="module-zrender_shape_Text.html#getRect">getRect</a></li> <li data-name="module:zrender/shape/Text#afterBrush"><a href="module-zrender_shape_Text.html#afterBrush">afterBrush</a></li> <li data-name="module:zrender/shape/Text#beforeBrush"><a href="module-zrender_shape_Text.html#beforeBrush">beforeBrush</a></li> <li data-name="module:zrender/shape/Text#bind"><a href="module-zrender_shape_Text.html#bind">bind</a></li> <li data-name="module:zrender/shape/Text#brush"><a href="module-zrender_shape_Text.html#brush">brush</a></li> <li data-name="module:zrender/shape/Text#buildPath"><a href="module-zrender_shape_Text.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Text#decomposeTransform"><a href="module-zrender_shape_Text.html#decomposeTransform">decomposeTransform</a></li> <li data-name="module:zrender/shape/Text#dispatch"><a href="module-zrender_shape_Text.html#dispatch">dispatch</a></li> <li data-name="module:zrender/shape/Text#dispatchWithContext"><a href="module-zrender_shape_Text.html#dispatchWithContext">dispatchWithContext</a></li> <li data-name="module:zrender/shape/Text#drawText"><a href="module-zrender_shape_Text.html#drawText">drawText</a></li> <li data-name="module:zrender/shape/Text#drift"><a href="module-zrender_shape_Text.html#drift">drift</a></li> <li data-name="module:zrender/shape/Text#getHighlightStyle"><a href="module-zrender_shape_Text.html#getHighlightStyle">getHighlightStyle</a></li> <li data-name="module:zrender/shape/Text#isCover"><a href="module-zrender_shape_Text.html#isCover">isCover</a></li> <li data-name="module:zrender/shape/Text#isSilent"><a href="module-zrender_shape_Text.html#isSilent">isSilent</a></li> <li data-name="module:zrender/shape/Text#lookAt"><a href="module-zrender_shape_Text.html#lookAt">lookAt</a></li> <li data-name="module:zrender/shape/Text#one"><a href="module-zrender_shape_Text.html#one">one</a></li> <li data-name="module:zrender/shape/Text#setContext"><a href="module-zrender_shape_Text.html#setContext">setContext</a></li> <li data-name="module:zrender/shape/Text#setTransform"><a href="module-zrender_shape_Text.html#setTransform">setTransform</a></li> <li data-name="module:zrender/shape/Text#transformCoordToLocal"><a href="module-zrender_shape_Text.html#transformCoordToLocal">transformCoordToLocal</a></li> <li data-name="module:zrender/shape/Text#unbind"><a href="module-zrender_shape_Text.html#unbind">unbind</a></li> <li data-name="module:zrender/shape/Text#updateTransform"><a href="module-zrender_shape_Text.html#updateTransform">updateTransform</a></li> </ul> <ul class="events itemMembers"> <span class="subtitle">Events</span> <li data-name="module:zrender/shape/Text#event:onclick"><a href="module-zrender_shape_Text.html#event:onclick">onclick</a></li> <li data-name="module:zrender/shape/Text#event:ondragend"><a href="module-zrender_shape_Text.html#event:ondragend">ondragend</a></li> <li data-name="module:zrender/shape/Text#event:ondragenter"><a href="module-zrender_shape_Text.html#event:ondragenter">ondragenter</a></li> <li data-name="module:zrender/shape/Text#event:ondragleave"><a href="module-zrender_shape_Text.html#event:ondragleave">ondragleave</a></li> <li data-name="module:zrender/shape/Text#event:ondragover"><a href="module-zrender_shape_Text.html#event:ondragover">ondragover</a></li> <li data-name="module:zrender/shape/Text#event:ondragstart"><a href="module-zrender_shape_Text.html#event:ondragstart">ondragstart</a></li> <li data-name="module:zrender/shape/Text#event:ondrop"><a href="module-zrender_shape_Text.html#event:ondrop">ondrop</a></li> <li data-name="module:zrender/shape/Text#event:onmousedown"><a href="module-zrender_shape_Text.html#event:onmousedown">onmousedown</a></li> <li data-name="module:zrender/shape/Text#event:onmousemove"><a href="module-zrender_shape_Text.html#event:onmousemove">onmousemove</a></li> <li data-name="module:zrender/shape/Text#event:onmouseout"><a href="module-zrender_shape_Text.html#event:onmouseout">onmouseout</a></li> <li data-name="module:zrender/shape/Text#event:onmouseover"><a href="module-zrender_shape_Text.html#event:onmouseover">onmouseover</a></li> <li data-name="module:zrender/shape/Text#event:onmouseup"><a href="module-zrender_shape_Text.html#event:onmouseup">onmouseup</a></li> <li data-name="module:zrender/shape/Text#event:onmousewheel"><a href="module-zrender_shape_Text.html#event:onmousewheel">onmousewheel</a></li> </ul> </li> <li class="item" data-name="module:zrender/shape/tool/PathProxy"> <span class="title"> <a href="module-zrender_shape_tool_PathProxy.html">module:zrender/shape/tool/PathProxy</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/tool/PathProxy#pathCommands"><a href="module-zrender_shape_tool_PathProxy.html#pathCommands">pathCommands</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/tool/PathProxy#arc"><a href="module-zrender_shape_tool_PathProxy.html#arc">arc</a></li> <li data-name="module:zrender/shape/tool/PathProxy#begin"><a href="module-zrender_shape_tool_PathProxy.html#begin">begin</a></li> <li data-name="module:zrender/shape/tool/PathProxy#bezierCurveTo"><a href="module-zrender_shape_tool_PathProxy.html#bezierCurveTo">bezierCurveTo</a></li> <li data-name="module:zrender/shape/tool/PathProxy#closePath"><a href="module-zrender_shape_tool_PathProxy.html#closePath">closePath</a></li> <li data-name="module:zrender/shape/tool/PathProxy#fastBoundingRect"><a href="module-zrender_shape_tool_PathProxy.html#fastBoundingRect">fastBoundingRect</a></li> <li data-name="module:zrender/shape/tool/PathProxy#isEmpty"><a href="module-zrender_shape_tool_PathProxy.html#isEmpty">isEmpty</a></li> <li data-name="module:zrender/shape/tool/PathProxy#lineTo"><a href="module-zrender_shape_tool_PathProxy.html#lineTo">lineTo</a></li> <li data-name="module:zrender/shape/tool/PathProxy#moveTo"><a href="module-zrender_shape_tool_PathProxy.html#moveTo">moveTo</a></li> <li data-name="module:zrender/shape/tool/PathProxy#quadraticCurveTo"><a href="module-zrender_shape_tool_PathProxy.html#quadraticCurveTo">quadraticCurveTo</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/Trochold"> <span class="title"> <a href="module-zrender_shape_Trochold.html">module:zrender/shape/Trochold</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/shape/Trochold#highlightStyle"><a href="module-zrender_shape_Trochold.html#highlightStyle">highlightStyle</a></li> <li data-name="module:zrender/shape/Trochold#style"><a href="module-zrender_shape_Trochold.html#style">style</a></li> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/shape/Trochold~ITrocholdStyle"><a href="module-zrender_shape_Trochold.html#~ITrocholdStyle">ITrocholdStyle</a></li> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/shape/Trochold#buildPath"><a href="module-zrender_shape_Trochold.html#buildPath">buildPath</a></li> <li data-name="module:zrender/shape/Trochold#getRect"><a href="module-zrender_shape_Trochold.html#getRect">getRect</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/util/smoothBezier"> <span class="title"> <a href="module-zrender_shape_util_smoothBezier.html">module:zrender/shape/util/smoothBezier</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/shape/util/smoothSpline"> <span class="title"> <a href="module-zrender_shape_util_smoothSpline.html">module:zrender/shape/util/smoothSpline</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/Storage"> <span class="title"> <a href="module-zrender_Storage.html">module:zrender/Storage</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/Storage#addHover"><a href="module-zrender_Storage.html#addHover">addHover</a></li> <li data-name="module:zrender/Storage#addRoot"><a href="module-zrender_Storage.html#addRoot">addRoot</a></li> <li data-name="module:zrender/Storage#delHover"><a href="module-zrender_Storage.html#delHover">delHover</a></li> <li data-name="module:zrender/Storage#delRoot"><a href="module-zrender_Storage.html#delRoot">delRoot</a></li> <li data-name="module:zrender/Storage#dispose"><a href="module-zrender_Storage.html#dispose">dispose</a></li> <li data-name="module:zrender/Storage#drift"><a href="module-zrender_Storage.html#drift">drift</a></li> <li data-name="module:zrender/Storage#getHoverShapes"><a href="module-zrender_Storage.html#getHoverShapes">getHoverShapes</a></li> <li data-name="module:zrender/Storage#getShapeList"><a href="module-zrender_Storage.html#getShapeList">getShapeList</a></li> <li data-name="module:zrender/Storage#hasHoverShape"><a href="module-zrender_Storage.html#hasHoverShape">hasHoverShape</a></li> <li data-name="module:zrender/Storage#iterShape"><a href="module-zrender_Storage.html#iterShape">iterShape</a></li> <li data-name="module:zrender/Storage#mod"><a href="module-zrender_Storage.html#mod">mod</a></li> <li data-name="module:zrender/Storage#updateShapeList"><a href="module-zrender_Storage.html#updateShapeList">updateShapeList</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/color"> <span class="title"> <a href="module-zrender_tool_color.html">module:zrender/tool/color</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/color.alpha"><a href="module-zrender_tool_color.html#.alpha">alpha</a></li> <li data-name="module:zrender/tool/color.getColor"><a href="module-zrender_tool_color.html#.getColor">getColor</a></li> <li data-name="module:zrender/tool/color.getGradientColors"><a href="module-zrender_tool_color.html#.getGradientColors">getGradientColors</a></li> <li data-name="module:zrender/tool/color.getRadialGradient"><a href="module-zrender_tool_color.html#.getRadialGradient">getRadialGradient</a></li> <li data-name="module:zrender/tool/color.lift"><a href="module-zrender_tool_color.html#.lift">lift</a></li> <li data-name="module:zrender/tool/color.mix"><a href="module-zrender_tool_color.html#.mix">mix</a></li> <li data-name="module:zrender/tool/color.normalize"><a href="module-zrender_tool_color.html#.normalize">normalize</a></li> <li data-name="module:zrender/tool/color.reverse"><a href="module-zrender_tool_color.html#.reverse">reverse</a></li> <li data-name="module:zrender/tool/color.toArray"><a href="module-zrender_tool_color.html#.toArray">toArray</a></li> <li data-name="module:zrender/tool/color.toHSB"><a href="module-zrender_tool_color.html#.toHSB">toHSB</a></li> <li data-name="module:zrender/tool/color.toHSBA"><a href="module-zrender_tool_color.html#.toHSBA">toHSBA</a></li> <li data-name="module:zrender/tool/color.toHSL"><a href="module-zrender_tool_color.html#.toHSL">toHSL</a></li> <li data-name="module:zrender/tool/color.toHSLA"><a href="module-zrender_tool_color.html#.toHSLA">toHSLA</a></li> <li data-name="module:zrender/tool/color.toHSV"><a href="module-zrender_tool_color.html#.toHSV">toHSV</a></li> <li data-name="module:zrender/tool/color.toHSVA"><a href="module-zrender_tool_color.html#.toHSVA">toHSVA</a></li> <li data-name="module:zrender/tool/color.toHex"><a href="module-zrender_tool_color.html#.toHex">toHex</a></li> <li data-name="module:zrender/tool/color.toRGB"><a href="module-zrender_tool_color.html#.toRGB">toRGB</a></li> <li data-name="module:zrender/tool/color.toRGBA"><a href="module-zrender_tool_color.html#.toRGBA">toRGBA</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/computeBoundingBox"> <span class="title"> <a href="module-zrender_tool_computeBoundingBox.html">module:zrender/tool/computeBoundingBox</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/computeBoundingBox.computeArcBoundingBox"><a href="module-zrender_tool_computeBoundingBox.html#.computeArcBoundingBox">computeArcBoundingBox</a></li> <li data-name="module:zrender/tool/computeBoundingBox.computeCubeBezierBoundingBox"><a href="module-zrender_tool_computeBoundingBox.html#.computeCubeBezierBoundingBox">computeCubeBezierBoundingBox</a></li> <li data-name="module:zrender/tool/computeBoundingBox.computeQuadraticBezierBoundingBox"><a href="module-zrender_tool_computeBoundingBox.html#.computeQuadraticBezierBoundingBox">computeQuadraticBezierBoundingBox</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/curve"> <span class="title"> <a href="module-zrender_tool_curve.html">module:zrender/tool/curve</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/curve.cubicAt"><a href="module-zrender_tool_curve.html#.cubicAt">cubicAt</a></li> <li data-name="module:zrender/tool/curve.cubicDerivativeAt"><a href="module-zrender_tool_curve.html#.cubicDerivativeAt">cubicDerivativeAt</a></li> <li data-name="module:zrender/tool/curve.cubicExtrema"><a href="module-zrender_tool_curve.html#.cubicExtrema">cubicExtrema</a></li> <li data-name="module:zrender/tool/curve.cubicRootAt"><a href="module-zrender_tool_curve.html#.cubicRootAt">cubicRootAt</a></li> <li data-name="module:zrender/tool/curve.cubicSubdivide"><a href="module-zrender_tool_curve.html#.cubicSubdivide">cubicSubdivide</a></li> <li data-name="module:zrender/tool/curve.quadraticExtremum"><a href="module-zrender_tool_curve.html#.quadraticExtremum">quadraticExtremum</a></li> <li data-name="module:zrender/tool/curve.quadraticSubdivide"><a href="module-zrender_tool_curve.html#.quadraticSubdivide">quadraticSubdivide</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/event"> <span class="title"> <a href="module-zrender_tool_event.html">module:zrender/tool/event</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/event.getDelta"><a href="module-zrender_tool_event.html#.getDelta">getDelta</a></li> <li data-name="module:zrender/tool/event.getX"><a href="module-zrender_tool_event.html#.getX">getX</a></li> <li data-name="module:zrender/tool/event.getY"><a href="module-zrender_tool_event.html#.getY">getY</a></li> <li data-name="module:zrender/tool/event.stop"><a href="module-zrender_tool_event.html#.stop">stop</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/http"> <span class="title"> <a href="module-zrender_tool_http.html">module:zrender/tool/http</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> <span class="subtitle">Typedefs</span> <li data-name="module:zrender/tool/http~IHTTPGetOption"><a href="module-zrender_tool_http.html#~IHTTPGetOption">IHTTPGetOption</a></li> </ul> <ul class="methods itemMembers"> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/matrix"> <span class="title"> <a href="module-zrender_tool_matrix.html">module:zrender/tool/matrix</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/matrix.copy"><a href="module-zrender_tool_matrix.html#.copy">copy</a></li> <li data-name="module:zrender/tool/matrix.create"><a href="module-zrender_tool_matrix.html#.create">create</a></li> <li data-name="module:zrender/tool/matrix.identity"><a href="module-zrender_tool_matrix.html#.identity">identity</a></li> <li data-name="module:zrender/tool/matrix.invert"><a href="module-zrender_tool_matrix.html#.invert">invert</a></li> <li data-name="module:zrender/tool/matrix.mul"><a href="module-zrender_tool_matrix.html#.mul">mul</a></li> <li data-name="module:zrender/tool/matrix.rotate"><a href="module-zrender_tool_matrix.html#.rotate">rotate</a></li> <li data-name="module:zrender/tool/matrix.scale"><a href="module-zrender_tool_matrix.html#.scale">scale</a></li> <li data-name="module:zrender/tool/matrix.translate"><a href="module-zrender_tool_matrix.html#.translate">translate</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/util"> <span class="title"> <a href="module-zrender_tool_util.html">module:zrender/tool/util</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/util.clone"><a href="module-zrender_tool_util.html#.clone">clone</a></li> <li data-name="module:zrender/tool/util.each"><a href="module-zrender_tool_util.html#.each">each</a></li> <li data-name="module:zrender/tool/util.filter"><a href="module-zrender_tool_util.html#.filter">filter</a></li> <li data-name="module:zrender/tool/util.indexOf"><a href="module-zrender_tool_util.html#.indexOf">indexOf</a></li> <li data-name="module:zrender/tool/util.inherits"><a href="module-zrender_tool_util.html#.inherits">inherits</a></li> <li data-name="module:zrender/tool/util.map"><a href="module-zrender_tool_util.html#.map">map</a></li> <li data-name="module:zrender/tool/util.merge"><a href="module-zrender_tool_util.html#.merge">merge</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/tool/vector"> <span class="title"> <a href="module-zrender_tool_vector.html">module:zrender/tool/vector</a> </span> <ul class="members itemMembers"> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/tool/vector.add"><a href="module-zrender_tool_vector.html#.add">add</a></li> <li data-name="module:zrender/tool/vector.applyTransform"><a href="module-zrender_tool_vector.html#.applyTransform">applyTransform</a></li> <li data-name="module:zrender/tool/vector.clone"><a href="module-zrender_tool_vector.html#.clone">clone</a></li> <li data-name="module:zrender/tool/vector.copy"><a href="module-zrender_tool_vector.html#.copy">copy</a></li> <li data-name="module:zrender/tool/vector.create"><a href="module-zrender_tool_vector.html#.create">create</a></li> <li data-name="module:zrender/tool/vector.distance"><a href="module-zrender_tool_vector.html#.distance">distance</a></li> <li data-name="module:zrender/tool/vector.distanceSquare"><a href="module-zrender_tool_vector.html#.distanceSquare">distanceSquare</a></li> <li data-name="module:zrender/tool/vector.div"><a href="module-zrender_tool_vector.html#.div">div</a></li> <li data-name="module:zrender/tool/vector.dot"><a href="module-zrender_tool_vector.html#.dot">dot</a></li> <li data-name="module:zrender/tool/vector.len"><a href="module-zrender_tool_vector.html#.len">len</a></li> <li data-name="module:zrender/tool/vector.lenSquare"><a href="module-zrender_tool_vector.html#.lenSquare">lenSquare</a></li> <li data-name="module:zrender/tool/vector.lerp"><a href="module-zrender_tool_vector.html#.lerp">lerp</a></li> <li data-name="module:zrender/tool/vector.max"><a href="module-zrender_tool_vector.html#.max">max</a></li> <li data-name="module:zrender/tool/vector.min"><a href="module-zrender_tool_vector.html#.min">min</a></li> <li data-name="module:zrender/tool/vector.mul"><a href="module-zrender_tool_vector.html#.mul">mul</a></li> <li data-name="module:zrender/tool/vector.negate"><a href="module-zrender_tool_vector.html#.negate">negate</a></li> <li data-name="module:zrender/tool/vector.normalize"><a href="module-zrender_tool_vector.html#.normalize">normalize</a></li> <li data-name="module:zrender/tool/vector.scale"><a href="module-zrender_tool_vector.html#.scale">scale</a></li> <li data-name="module:zrender/tool/vector.scaleAndAdd"><a href="module-zrender_tool_vector.html#.scaleAndAdd">scaleAndAdd</a></li> <li data-name="module:zrender/tool/vector.set"><a href="module-zrender_tool_vector.html#.set">set</a></li> <li data-name="module:zrender/tool/vector.sub"><a href="module-zrender_tool_vector.html#.sub">sub</a></li> </ul> <ul class="events itemMembers"> </ul> </li> <li class="item" data-name="module:zrender/ZRender"> <span class="title"> <a href="module-zrender_ZRender.html">module:zrender/ZRender</a> </span> <ul class="members itemMembers"> <span class="subtitle">Members</span> <li data-name="module:zrender/ZRender#animation"><a href="module-zrender_ZRender.html#animation">animation</a></li> <li data-name="module:zrender/ZRender#id"><a href="module-zrender_ZRender.html#id">id</a></li> </ul> <ul class="typedefs itemMembers"> </ul> <ul class="methods itemMembers"> <span class="subtitle">Methods</span> <li data-name="module:zrender/ZRender#addElement"><a href="module-zrender_ZRender.html#addElement">addElement</a></li> <li data-name="module:zrender/ZRender#addGroup"><a href="module-zrender_ZRender.html#addGroup">addGroup</a></li> <li data-name="module:zrender/ZRender#addHoverShape"><a href="module-zrender_ZRender.html#addHoverShape">addHoverShape</a></li> <li data-name="module:zrender/ZRender#addShape"><a href="module-zrender_ZRender.html#addShape">addShape</a></li> <li data-name="module:zrender/ZRender#animate"><a href="module-zrender_ZRender.html#animate">animate</a></li> <li data-name="module:zrender/ZRender#clear"><a href="module-zrender_ZRender.html#clear">clear</a></li> <li data-name="module:zrender/ZRender#clearAnimation"><a href="module-zrender_ZRender.html#clearAnimation">clearAnimation</a></li> <li data-name="module:zrender/ZRender#delElement"><a href="module-zrender_ZRender.html#delElement">delElement</a></li> <li data-name="module:zrender/ZRender#delGroup"><a href="module-zrender_ZRender.html#delGroup">delGroup</a></li> <li data-name="module:zrender/ZRender#delShape"><a href="module-zrender_ZRender.html#delShape">delShape</a></li> <li data-name="module:zrender/ZRender#dispose"><a href="module-zrender_ZRender.html#dispose">dispose</a></li> <li data-name="module:zrender/ZRender#getHeight"><a href="module-zrender_ZRender.html#getHeight">getHeight</a></li> <li data-name="module:zrender/ZRender#getId"><a href="module-zrender_ZRender.html#getId">getId</a></li> <li data-name="module:zrender/ZRender#getWidth"><a href="module-zrender_ZRender.html#getWidth">getWidth</a></li> <li data-name="module:zrender/ZRender#hideLoading"><a href="module-zrender_ZRender.html#hideLoading">hideLoading</a></li> <li data-name="module:zrender/ZRender#modElement"><a href="module-zrender_ZRender.html#modElement">modElement</a></li> <li data-name="module:zrender/ZRender#modGroup"><a href="module-zrender_ZRender.html#modGroup">modGroup</a></li> <li data-name="module:zrender/ZRender#modLayer"><a href="module-zrender_ZRender.html#modLayer">modLayer</a></li> <li data-name="module:zrender/ZRender#modShape"><a href="module-zrender_ZRender.html#modShape">modShape</a></li> <li data-name="module:zrender/ZRender#on"><a href="module-zrender_ZRender.html#on">on</a></li> <li data-name="module:zrender/ZRender#refresh"><a href="module-zrender_ZRender.html#refresh">refresh</a></li> <li data-name="module:zrender/ZRender#refreshHover"><a href="module-zrender_ZRender.html#refreshHover">refreshHover</a></li> <li data-name="module:zrender/ZRender#refreshNextFrame"><a href="module-zrender_ZRender.html#refreshNextFrame">refreshNextFrame</a></li> <li data-name="module:zrender/ZRender#refreshShapes"><a href="module-zrender_ZRender.html#refreshShapes">refreshShapes</a></li> <li data-name="module:zrender/ZRender#render"><a href="module-zrender_ZRender.html#render">render</a></li> <li data-name="module:zrender/ZRender#resize"><a href="module-zrender_ZRender.html#resize">resize</a></li> <li data-name="module:zrender/ZRender#shapeToImage"><a href="module-zrender_ZRender.html#shapeToImage">shapeToImage</a></li> <li data-name="module:zrender/ZRender#showLoading"><a href="module-zrender_ZRender.html#showLoading">showLoading</a></li> <li data-name="module:zrender/ZRender#stopAnimation"><a href="module-zrender_ZRender.html#stopAnimation">stopAnimation</a></li> <li data-name="module:zrender/ZRender#toDataURL"><a href="module-zrender_ZRender.html#toDataURL">toDataURL</a></li> <li data-name="module:zrender/ZRender#trigger"><a href="module-zrender_ZRender.html#trigger">trigger</a></li> <li data-name="module:zrender/ZRender#un"><a href="module-zrender_ZRender.html#un">un</a></li> </ul> <ul class="events itemMembers"> </ul> </li> </ul> </div> <div class="main"> <h1 class="page-title" data-filename="module-zrender_shape_Ring.html">Module: zrender/shape/Ring</h1> <section> <header> <h2> zrender/shape/Ring </h2> </header> <article> <div class="container-overview"> <dt> <div class="nameContainer"> <h4 class="name" id="module:zrender/shape/Ring"> new require("zrender/shape/Ring")<span class="signature">(options)</span> </h4> <div class="tag-source"> shape/Ring.js, line 53 </div> </div> </dt> <dd> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>options</code></td> <td class="type"> <span class="param-type">Object</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <div class="description"><p>圆环</p></div> <dl class="details"> <dt class="tag-author">Author:</dt> <dd class="tag-author"> <ul> <li>Kener (@Kener-林峰, kener.linfeng@gmail.com)</li> </ul> </dd> </dl> <h3>Example</h3> <pre class="prettyprint"><code>var Ring = require('zrender/shape/Ring'); var shape = new Ring({ style: { x: 100, y: 100, r0: 30, r: 50 } }); zr.addShape(shape);</code></pre> </div> <h3 class="subsection-title">Members</h3> <dl> <dt> <div class="nameContainer"> <h4 class="name" id="highlightStyle"> highlightStyle<span class="type-signature type module:zrender/shape/ring~iringstyle"><a href="module-zrender_shape_Ring.html#~IRingStyle">module:zrender/shape/Ring~IRingStyle</a></span> </h4> </div> </dt> <dd> <div class="description"> <p>圆环高亮绘制样式</p> </div> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer"> <h4 class="name" id="style"> style<span class="type-signature type module:zrender/shape/ring~iringstyle"><a href="module-zrender_shape_Ring.html#~IRingStyle">module:zrender/shape/Ring~IRingStyle</a></span> </h4> </div> </dt> <dd> <div class="description"> <p>圆环绘制样式</p> </div> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="id"> <span class="inherited"><a href="module-zrender_shape_Base.html#id">inherited</a></span> id<span class="type-signature type string">string</span> </h4> </div> </dt> <dd> <div class="description"> <p>Shape id, 全局唯一</p> </div> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="parent"> <span class="inherited"><a href="module-zrender_shape_Base.html#parent">inherited</a></span> <span class="type-signature ">readonly</span>parent<span class="type-signature type module:zrender/group"><a href="module-zrender_Group.html">module:zrender/Group</a></span> </h4> </div> </dt> <dd> <div class="description"> <p>父节点</p> </div> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="position"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#position">inherited</a></span> position<span class="type-signature type array.<number>">Array.&lt;number></span> </h4> </div> </dt> <dd> <div class="description"> <p>平移</p> </div> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>[0, 0]</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="rotation"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#rotation">inherited</a></span> rotation<span class="type-signature type array.<number>">Array.&lt;number></span> </h4> </div> </dt> <dd> <div class="description"> <p>旋转,可以通过数组二三项指定旋转的原点</p> </div> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>[0, 0, 0]</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="scale"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#scale">inherited</a></span> scale<span class="type-signature type array.<number>">Array.&lt;number></span> </h4> </div> </dt> <dd> <div class="description"> <p>缩放,可以通过数组三四项指定缩放的原点</p> </div> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>[1, 1, 0, 0]</li></ul></dd> </dl> </dd> </dl> <h3 class="subsection-title">Methods</h3> <dl> <dt> <div class="nameContainer"> <h4 class="name" id="buildPath"> buildPath<span class="signature">(ctx, style)</span> </h4> <div class="tag-source"> shape/Ring.js, line 75 </div> </div> </dt> <dd> <div class="description"> <p>创建圆环路径</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>style</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Ring.html#~IRingStyle">module:zrender/shape/Ring~IRingStyle</a></span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer"> <h4 class="name" id="getRect"> getRect<span class="signature">(style)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{<a href="module-zrender_shape_Base.html#~IBoundingRect">module:zrender/shape/Base~IBoundingRect</a>}</span> </h4> <div class="tag-source"> shape/Ring.js, line 88 </div> </div> </dt> <dd> <div class="description"> <p>计算返回圆环包围盒矩阵</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>style</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Ring.html#~IRingStyle">module:zrender/shape/Ring~IRingStyle</a></span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="afterBrush"> <span class="inherited"><a href="module-zrender_shape_Base.html#afterBrush">inherited</a></span> afterBrush<span class="signature">(ctx)</span> </h4> <div class="tag-source"> shape/Base.js, line 306 </div> </div> </dt> <dd> <div class="description"> <p>绘制后的处理</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="beforeBrush"> <span class="inherited"><a href="module-zrender_shape_Base.html#beforeBrush">inherited</a></span> beforeBrush<span class="signature">(ctx, <span class="optional">isHighlight</span>)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{Object}</span> </h4> <div class="tag-source"> shape/Base.js, line 270 </div> </div> </dt> <dd> <div class="description"> <p>具体绘制操作前的一些公共操作</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="default"> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>isHighlight</code></td> <td class="type"> <span class="param-type">boolean</span> </td> <td class="default"> false </td> <td class="description last"> <span class="optional">optional</span> <p>是否使用高亮属性</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="bind"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#bind">inherited</a></span> bind<span class="signature">(event, handler, <span class="optional">context</span>)</span> </h4> <div class="tag-source"> mixin/Eventful.js, line 50 </div> </div> </dt> <dd> <div class="description"> <p>绑定事件</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>event</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>事件名</p></td> </tr> <tr> <td class="name"><code>handler</code></td> <td class="type"> <span class="param-type">function</span> </td> <td class="description last"> <p>事件处理函数</p></td> </tr> <tr> <td class="name"><code>context</code></td> <td class="type"> <span class="param-type">Object</span> </td> <td class="description last"> <span class="optional">optional</span> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="brush"> <span class="inherited"><a href="module-zrender_shape_Base.html#brush">inherited</a></span> brush<span class="signature">(ctx, <span class="optional">isHighlight</span>, <span class="optional">updateCallback</span>)</span> </h4> <div class="tag-source"> shape/Base.js, line 240 </div> </div> </dt> <dd> <div class="description"> <p>绘制图形</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="default"> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>isHighlight</code></td> <td class="type"> <span class="param-type">boolean</span> </td> <td class="default"> false </td> <td class="description last"> <span class="optional">optional</span> <p>是否使用高亮属性</p></td> </tr> <tr> <td class="name"><code>updateCallback</code></td> <td class="type"> <span class="param-type">function</span> </td> <td class="default"> </td> <td class="description last"> <span class="optional">optional</span> <p>需要异步加载资源的shape可以通过这个callback(e), 让painter更新视图,base.brush没用,需要的话重载brush</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="decomposeTransform"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#decomposeTransform">inherited</a></span> decomposeTransform<span class="signature">()</span> </h4> <div class="tag-source"> mixin/Transformable.js, line 207 </div> </div> </dt> <dd> <div class="description"> <p>分解<code>transform</code>矩阵到<code>position</code>, <code>rotation</code>, <code>scale</code></p> </div> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="dispatch"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#dispatch">inherited</a></span> dispatch<span class="signature">(type)</span> </h4> <div class="tag-source"> mixin/Eventful.js, line 110 </div> </div> </dt> <dd> <div class="description"> <p>事件分发</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>type</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>事件类型</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="dispatchWithContext"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#dispatchWithContext">inherited</a></span> dispatchWithContext<span class="signature">(type)</span> </h4> <div class="tag-source"> mixin/Eventful.js, line 156 </div> </div> </dt> <dd> <div class="description"> <p>带有context的事件分发, 最后一个参数是事件回调的context</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>type</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>事件类型</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="drawText"> <span class="inherited"><a href="module-zrender_shape_Base.html#drawText">inherited</a></span> drawText<span class="signature">(ctx, style, normalStyle)</span> </h4> <div class="tag-source"> shape/Base.js, line 493 </div> </div> </dt> <dd> <div class="description"> <p>绘制附加文本</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>style</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">module:zrender/shape/Base~IBaseShapeStyle</a></span> </td> <td class="description last"> <p>样式</p></td> </tr> <tr> <td class="name"><code>normalStyle</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">module:zrender/shape/Base~IBaseShapeStyle</a></span> </td> <td class="description last"> <p>默认样式,用于定位文字显示</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="drift"> <span class="inherited"><a href="module-zrender_shape_Base.html#drift">inherited</a></span> drift<span class="signature">(dx, dy)</span> </h4> <div class="tag-source"> shape/Base.js, line 432 </div> </div> </dt> <dd> <div class="description"> <p>移动位置</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>dx</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>横坐标变化</p></td> </tr> <tr> <td class="name"><code>dy</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>纵坐标变化</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="getHighlightStyle"> <span class="inherited"><a href="module-zrender_shape_Base.html#getHighlightStyle">inherited</a></span> getHighlightStyle<span class="signature">(style, highlightStyle, brushTypeOnly)</span> </h4> <div class="tag-source"> shape/Base.js, line 378 </div> </div> </dt> <dd> <div class="description"> <p>根据默认样式扩展高亮样式</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>style</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">module:zrender/shape/Base~IBaseShapeStyle</a></span> </td> <td class="description last"> <p>默认样式</p></td> </tr> <tr> <td class="name"><code>highlightStyle</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">module:zrender/shape/Base~IBaseShapeStyle</a></span> </td> <td class="description last"> <p>高亮样式</p></td> </tr> <tr> <td class="name"><code>brushTypeOnly</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="isCover"> <span class="inherited"><a href="module-zrender_shape_Base.html#isCover">inherited</a></span> isCover<span class="signature">(x, y)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{boolean}</span> </h4> <div class="tag-source"> shape/Base.js, line 461 </div> </div> </dt> <dd> <div class="description"> <p>判断鼠标位置是否在图形内</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>x</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>y</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="isSilent"> <span class="inherited"><a href="module-zrender_shape_Base.html#isSilent">inherited</a></span> isSilent<span class="signature">()</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{boolean}</span> </h4> <div class="tag-source"> shape/Base.js, line 659 </div> </div> </dt> <dd> <div class="description"> <p>图形是否会触发事件</p> </div> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="lookAt"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#lookAt">inherited</a></span> lookAt<span class="signature">(target)</span> </h4> <div class="tag-source"> mixin/Transformable.js, line 177 </div> </div> </dt> <dd> <div class="description"> <p>设置图形的朝向</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>target</code></td> <td class="type"> <span class="param-type">Array.&lt;number></span> | <span class="param-type">Float32Array</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="one"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#one">inherited</a></span> one<span class="signature">(event, handler, context)</span> </h4> <div class="tag-source"> mixin/Eventful.js, line 24 </div> </div> </dt> <dd> <div class="description"> <p>单次触发绑定,dispatch后销毁</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>event</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>事件名</p></td> </tr> <tr> <td class="name"><code>handler</code></td> <td class="type"> <span class="param-type">function</span> </td> <td class="description last"> <p>响应函数</p></td> </tr> <tr> <td class="name"><code>context</code></td> <td class="type"> <span class="param-type">Object</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="setContext"> <span class="inherited"><a href="module-zrender_shape_Base.html#setContext">inherited</a></span> setContext<span class="signature">(ctx, style)</span> </h4> <div class="tag-source"> shape/Base.js, line 329 </div> </div> </dt> <dd> <div class="description"> <p>设置 fillStyle, strokeStyle, shadow 等通用绘制样式</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">CanvasRenderingContext2D</span> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>style</code></td> <td class="type"> <span class="param-type"><a href="module-zrender_shape_Base.html#~IBaseShapeStyle">module:zrender/shape/Base~IBaseShapeStyle</a></span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="setTransform"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#setTransform">inherited</a></span> setTransform<span class="signature">(ctx)</span> </h4> <div class="tag-source"> mixin/Transformable.js, line 166 </div> </div> </dt> <dd> <div class="description"> <p>将自己的transform应用到context上</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">Context2D</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="transformCoordToLocal"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#transformCoordToLocal">inherited</a></span> transformCoordToLocal<span class="signature">(x, y)</span><span class="glyphicon glyphicon-circle-arrow-right"></span><span class="type-signature returnType">{Array.&lt;number>}</span> </h4> <div class="tag-source"> mixin/Transformable.js, line 239 </div> </div> </dt> <dd> <div class="description"> <p>变换坐标位置到 shape 的局部坐标空间</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>x</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> </td> </tr> <tr> <td class="name"><code>y</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> </td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="unbind"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#unbind">inherited</a></span> unbind<span class="signature">(event, <span class="optional">handler</span>)</span> </h4> <div class="tag-source"> mixin/Eventful.js, line 75 </div> </div> </dt> <dd> <div class="description"> <p>解绑事件</p> </div> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>event</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>事件名</p></td> </tr> <tr> <td class="name"><code>handler</code></td> <td class="type"> <span class="param-type">function</span> </td> <td class="description last"> <span class="optional">optional</span> <p>事件处理函数</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="updateTransform"> <span class="inherited"><a href="module-zrender_mixin_Transformable.html#updateTransform">inherited</a></span> updateTransform<span class="signature">()</span> </h4> <div class="tag-source"> mixin/Transformable.js, line 82 </div> </div> </dt> <dd> <div class="description"> <p>判断是否需要有坐标变换,更新needTransform属性。 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵</p> </div> <dl class="details"> </dl> </dd> </dl> <h3 class="subsection-title">Type Definitions</h3> <dl> <dt> <div class="nameContainer"> <h4 class="name" id="~IRingStyle"> IRingStyle<span class="type-signature type object">Object</span> </h4> </div> </dt> <dd> <dl class="details"> <h5 class="subsection-title">Properties:</h5> <dl> <table class="props"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Argument</th> <th>Default</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>x</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>圆心x坐标</p></td> </tr> <tr> <td class="name"><code>y</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>圆心y坐标</p></td> </tr> <tr> <td class="name"><code>r0</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>内圆半径</p></td> </tr> <tr> <td class="name"><code>r</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> </td> <td class="default"> </td> <td class="description last"><p>外圆半径</p></td> </tr> <tr> <td class="name"><code>color</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> '#000000' </td> <td class="description last"><p>填充颜色</p></td> </tr> <tr> <td class="name"><code>strokeColor</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> '#000000' </td> <td class="description last"><p>描边颜色</p></td> </tr> <tr> <td class="name"><code>lineCape</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 'butt' </td> <td class="description last"><p>线帽样式,可以是 butt, round, square</p></td> </tr> <tr> <td class="name"><code>lineWidth</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 1 </td> <td class="description last"><p>描边宽度</p></td> </tr> <tr> <td class="name"><code>opacity</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 1 </td> <td class="description last"><p>绘制透明度</p></td> </tr> <tr> <td class="name"><code>shadowBlur</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>阴影模糊度,大于0有效</p></td> </tr> <tr> <td class="name"><code>shadowColor</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> '#000000' </td> <td class="description last"><p>阴影颜色</p></td> </tr> <tr> <td class="name"><code>shadowOffsetX</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>阴影横向偏移</p></td> </tr> <tr> <td class="name"><code>shadowOffsetY</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 0 </td> <td class="description last"><p>阴影纵向偏移</p></td> </tr> <tr> <td class="name"><code>text</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> </td> <td class="description last"><p>图形中的附加文本</p></td> </tr> <tr> <td class="name"><code>textColor</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> '#000000' </td> <td class="description last"><p>文本颜色</p></td> </tr> <tr> <td class="name"><code>textFont</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> </td> <td class="description last"><p>附加文本样式,eg:'bold 18px verdana'</p></td> </tr> <tr> <td class="name"><code>textPosition</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> 'end' </td> <td class="description last"><p>附加文本位置, 可以是 inside, left, right, top, bottom</p></td> </tr> <tr> <td class="name"><code>textAlign</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> </td> <td class="description last"><p>默认根据textPosition自动设置,附加文本水平对齐。 可以是start, end, left, right, center</p></td> </tr> <tr> <td class="name"><code>textBaseline</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="default"> </td> <td class="description last"><p>默认根据textPosition自动设置,附加文本垂直对齐。 可以是top, bottom, middle, alphabetic, hanging, ideographic</p></td> </tr> </tbody> </table></dl> </dl> </dd> </dl> <h3 class="subsection-title">Events</h3> <dl> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onclick"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onclick">inherited</a></span> onclick </h4> <div class="tag-source"> mixin/Eventful.js, line 200 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondragend"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondragend">inherited</a></span> ondragend </h4> <div class="tag-source"> mixin/Eventful.js, line 240 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondragenter"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondragenter">inherited</a></span> ondragenter </h4> <div class="tag-source"> mixin/Eventful.js, line 245 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondragleave"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondragleave">inherited</a></span> ondragleave </h4> <div class="tag-source"> mixin/Eventful.js, line 250 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondragover"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondragover">inherited</a></span> ondragover </h4> <div class="tag-source"> mixin/Eventful.js, line 255 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondragstart"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondragstart">inherited</a></span> ondragstart </h4> <div class="tag-source"> mixin/Eventful.js, line 235 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:ondrop"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:ondrop">inherited</a></span> ondrop </h4> <div class="tag-source"> mixin/Eventful.js, line 260 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmousedown"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmousedown">inherited</a></span> onmousedown </h4> <div class="tag-source"> mixin/Eventful.js, line 225 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmousemove"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmousemove">inherited</a></span> onmousemove </h4> <div class="tag-source"> mixin/Eventful.js, line 215 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmouseout"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmouseout">inherited</a></span> onmouseout </h4> <div class="tag-source"> mixin/Eventful.js, line 210 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmouseover"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmouseover">inherited</a></span> onmouseover </h4> <div class="tag-source"> mixin/Eventful.js, line 205 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmouseup"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmouseup">inherited</a></span> onmouseup </h4> <div class="tag-source"> mixin/Eventful.js, line 230 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> <dt> <div class="nameContainer inherited"> <h4 class="name" id="event:onmousewheel"> <span class="inherited"><a href="module-zrender_mixin_Eventful.html#event:onmousewheel">inherited</a></span> onmousewheel </h4> <div class="tag-source"> mixin/Eventful.js, line 220 </div> </div> </dt> <dd> <h5>Type:</h5> <ul> <li> <span class="param-type">function</span> </li> </ul> <dl class="details"> <dt class="tag-default">Default Value:</dt> <dd class="tag-default"><ul class="dummy"><li>null</li></ul></dd> </dl> </dd> </dl> </article> </section> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-beta1</a> on Thu May 28 2015 14:42:44 GMT+0800 (CST) </footer> </div> </div> <script>prettyPrint();</script> <script src="scripts/linenumber.js"></script> <script src="scripts/main.js"></script> </body> </html>
bsd-3-clause
ae6rt/decap
web/vendor/github.com/gogo/protobuf/test/oneof3/combos/both/one.pb.go
99707
// Code generated by protoc-gen-gogo. // source: combos/both/one.proto // DO NOT EDIT! /* Package one is a generated protocol buffer package. It is generated from these files: combos/both/one.proto It has these top-level messages: Subby SampleOneOf */ package one import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" import compress_gzip "compress/gzip" import bytes "bytes" import io_ioutil "io/ioutil" import strings "strings" import reflect "reflect" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Subby struct { Sub string `protobuf:"bytes,1,opt,name=sub,proto3" json:"sub,omitempty"` } func (m *Subby) Reset() { *m = Subby{} } func (*Subby) ProtoMessage() {} func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} } type SampleOneOf struct { // Types that are valid to be assigned to TestOneof: // *SampleOneOf_Field1 // *SampleOneOf_Field2 // *SampleOneOf_Field3 // *SampleOneOf_Field4 // *SampleOneOf_Field5 // *SampleOneOf_Field6 // *SampleOneOf_Field7 // *SampleOneOf_Field8 // *SampleOneOf_Field9 // *SampleOneOf_Field10 // *SampleOneOf_Field11 // *SampleOneOf_Field12 // *SampleOneOf_Field13 // *SampleOneOf_Field14 // *SampleOneOf_Field15 // *SampleOneOf_SubMessage TestOneof isSampleOneOf_TestOneof `protobuf_oneof:"test_oneof"` } func (m *SampleOneOf) Reset() { *m = SampleOneOf{} } func (*SampleOneOf) ProtoMessage() {} func (*SampleOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} } type isSampleOneOf_TestOneof interface { isSampleOneOf_TestOneof() Equal(interface{}) bool VerboseEqual(interface{}) error MarshalTo([]byte) (int, error) Size() int } type SampleOneOf_Field1 struct { Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,proto3,oneof"` } type SampleOneOf_Field2 struct { Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,proto3,oneof"` } type SampleOneOf_Field3 struct { Field3 int32 `protobuf:"varint,3,opt,name=Field3,proto3,oneof"` } type SampleOneOf_Field4 struct { Field4 int64 `protobuf:"varint,4,opt,name=Field4,proto3,oneof"` } type SampleOneOf_Field5 struct { Field5 uint32 `protobuf:"varint,5,opt,name=Field5,proto3,oneof"` } type SampleOneOf_Field6 struct { Field6 uint64 `protobuf:"varint,6,opt,name=Field6,proto3,oneof"` } type SampleOneOf_Field7 struct { Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,proto3,oneof"` } type SampleOneOf_Field8 struct { Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,proto3,oneof"` } type SampleOneOf_Field9 struct { Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,proto3,oneof"` } type SampleOneOf_Field10 struct { Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,proto3,oneof"` } type SampleOneOf_Field11 struct { Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,proto3,oneof"` } type SampleOneOf_Field12 struct { Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,proto3,oneof"` } type SampleOneOf_Field13 struct { Field13 bool `protobuf:"varint,13,opt,name=Field13,proto3,oneof"` } type SampleOneOf_Field14 struct { Field14 string `protobuf:"bytes,14,opt,name=Field14,proto3,oneof"` } type SampleOneOf_Field15 struct { Field15 []byte `protobuf:"bytes,15,opt,name=Field15,proto3,oneof"` } type SampleOneOf_SubMessage struct { SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"` } func (*SampleOneOf_Field1) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field2) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field3) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field4) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field5) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field6) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field7) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field8) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field9) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field10) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field11) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field12) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field13) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field14) isSampleOneOf_TestOneof() {} func (*SampleOneOf_Field15) isSampleOneOf_TestOneof() {} func (*SampleOneOf_SubMessage) isSampleOneOf_TestOneof() {} func (m *SampleOneOf) GetTestOneof() isSampleOneOf_TestOneof { if m != nil { return m.TestOneof } return nil } func (m *SampleOneOf) GetField1() float64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field1); ok { return x.Field1 } return 0 } func (m *SampleOneOf) GetField2() float32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field2); ok { return x.Field2 } return 0 } func (m *SampleOneOf) GetField3() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field3); ok { return x.Field3 } return 0 } func (m *SampleOneOf) GetField4() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field4); ok { return x.Field4 } return 0 } func (m *SampleOneOf) GetField5() uint32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field5); ok { return x.Field5 } return 0 } func (m *SampleOneOf) GetField6() uint64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field6); ok { return x.Field6 } return 0 } func (m *SampleOneOf) GetField7() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field7); ok { return x.Field7 } return 0 } func (m *SampleOneOf) GetField8() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field8); ok { return x.Field8 } return 0 } func (m *SampleOneOf) GetField9() uint32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field9); ok { return x.Field9 } return 0 } func (m *SampleOneOf) GetField10() int32 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field10); ok { return x.Field10 } return 0 } func (m *SampleOneOf) GetField11() uint64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field11); ok { return x.Field11 } return 0 } func (m *SampleOneOf) GetField12() int64 { if x, ok := m.GetTestOneof().(*SampleOneOf_Field12); ok { return x.Field12 } return 0 } func (m *SampleOneOf) GetField13() bool { if x, ok := m.GetTestOneof().(*SampleOneOf_Field13); ok { return x.Field13 } return false } func (m *SampleOneOf) GetField14() string { if x, ok := m.GetTestOneof().(*SampleOneOf_Field14); ok { return x.Field14 } return "" } func (m *SampleOneOf) GetField15() []byte { if x, ok := m.GetTestOneof().(*SampleOneOf_Field15); ok { return x.Field15 } return nil } func (m *SampleOneOf) GetSubMessage() *Subby { if x, ok := m.GetTestOneof().(*SampleOneOf_SubMessage); ok { return x.SubMessage } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*SampleOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _SampleOneOf_OneofMarshaler, _SampleOneOf_OneofUnmarshaler, _SampleOneOf_OneofSizer, []interface{}{ (*SampleOneOf_Field1)(nil), (*SampleOneOf_Field2)(nil), (*SampleOneOf_Field3)(nil), (*SampleOneOf_Field4)(nil), (*SampleOneOf_Field5)(nil), (*SampleOneOf_Field6)(nil), (*SampleOneOf_Field7)(nil), (*SampleOneOf_Field8)(nil), (*SampleOneOf_Field9)(nil), (*SampleOneOf_Field10)(nil), (*SampleOneOf_Field11)(nil), (*SampleOneOf_Field12)(nil), (*SampleOneOf_Field13)(nil), (*SampleOneOf_Field14)(nil), (*SampleOneOf_Field15)(nil), (*SampleOneOf_SubMessage)(nil), } } func _SampleOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*SampleOneOf) // test_oneof switch x := m.TestOneof.(type) { case *SampleOneOf_Field1: _ = b.EncodeVarint(1<<3 | proto.WireFixed64) _ = b.EncodeFixed64(math.Float64bits(x.Field1)) case *SampleOneOf_Field2: _ = b.EncodeVarint(2<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2))) case *SampleOneOf_Field3: _ = b.EncodeVarint(3<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field3)) case *SampleOneOf_Field4: _ = b.EncodeVarint(4<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field4)) case *SampleOneOf_Field5: _ = b.EncodeVarint(5<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field5)) case *SampleOneOf_Field6: _ = b.EncodeVarint(6<<3 | proto.WireVarint) _ = b.EncodeVarint(uint64(x.Field6)) case *SampleOneOf_Field7: _ = b.EncodeVarint(7<<3 | proto.WireVarint) _ = b.EncodeZigzag32(uint64(x.Field7)) case *SampleOneOf_Field8: _ = b.EncodeVarint(8<<3 | proto.WireVarint) _ = b.EncodeZigzag64(uint64(x.Field8)) case *SampleOneOf_Field9: _ = b.EncodeVarint(9<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field9)) case *SampleOneOf_Field10: _ = b.EncodeVarint(10<<3 | proto.WireFixed32) _ = b.EncodeFixed32(uint64(x.Field10)) case *SampleOneOf_Field11: _ = b.EncodeVarint(11<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field11)) case *SampleOneOf_Field12: _ = b.EncodeVarint(12<<3 | proto.WireFixed64) _ = b.EncodeFixed64(uint64(x.Field12)) case *SampleOneOf_Field13: t := uint64(0) if x.Field13 { t = 1 } _ = b.EncodeVarint(13<<3 | proto.WireVarint) _ = b.EncodeVarint(t) case *SampleOneOf_Field14: _ = b.EncodeVarint(14<<3 | proto.WireBytes) _ = b.EncodeStringBytes(x.Field14) case *SampleOneOf_Field15: _ = b.EncodeVarint(15<<3 | proto.WireBytes) _ = b.EncodeRawBytes(x.Field15) case *SampleOneOf_SubMessage: _ = b.EncodeVarint(16<<3 | proto.WireBytes) if err := b.EncodeMessage(x.SubMessage); err != nil { return err } case nil: default: return fmt.Errorf("SampleOneOf.TestOneof has unexpected type %T", x) } return nil } func _SampleOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*SampleOneOf) switch tag { case 1: // test_oneof.Field1 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field1{math.Float64frombits(x)} return true, err case 2: // test_oneof.Field2 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field2{math.Float32frombits(uint32(x))} return true, err case 3: // test_oneof.Field3 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field3{int32(x)} return true, err case 4: // test_oneof.Field4 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field4{int64(x)} return true, err case 5: // test_oneof.Field5 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field5{uint32(x)} return true, err case 6: // test_oneof.Field6 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field6{x} return true, err case 7: // test_oneof.Field7 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.TestOneof = &SampleOneOf_Field7{int32(x)} return true, err case 8: // test_oneof.Field8 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag64() m.TestOneof = &SampleOneOf_Field8{int64(x)} return true, err case 9: // test_oneof.Field9 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field9{uint32(x)} return true, err case 10: // test_oneof.Field10 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.TestOneof = &SampleOneOf_Field10{int32(x)} return true, err case 11: // test_oneof.Field11 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field11{x} return true, err case 12: // test_oneof.Field12 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.TestOneof = &SampleOneOf_Field12{int64(x)} return true, err case 13: // test_oneof.Field13 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.TestOneof = &SampleOneOf_Field13{x != 0} return true, err case 14: // test_oneof.Field14 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.TestOneof = &SampleOneOf_Field14{x} return true, err case 15: // test_oneof.Field15 if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.TestOneof = &SampleOneOf_Field15{x} return true, err case 16: // test_oneof.sub_message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Subby) err := b.DecodeMessage(msg) m.TestOneof = &SampleOneOf_SubMessage{msg} return true, err default: return false, nil } } func _SampleOneOf_OneofSizer(msg proto.Message) (n int) { m := msg.(*SampleOneOf) // test_oneof switch x := m.TestOneof.(type) { case *SampleOneOf_Field1: n += proto.SizeVarint(1<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field2: n += proto.SizeVarint(2<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field3: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field3)) case *SampleOneOf_Field4: n += proto.SizeVarint(4<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field4)) case *SampleOneOf_Field5: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field5)) case *SampleOneOf_Field6: n += proto.SizeVarint(6<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Field6)) case *SampleOneOf_Field7: n += proto.SizeVarint(7<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31)))) case *SampleOneOf_Field8: n += proto.SizeVarint(8<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63)))) case *SampleOneOf_Field9: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field10: n += proto.SizeVarint(10<<3 | proto.WireFixed32) n += 4 case *SampleOneOf_Field11: n += proto.SizeVarint(11<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field12: n += proto.SizeVarint(12<<3 | proto.WireFixed64) n += 8 case *SampleOneOf_Field13: n += proto.SizeVarint(13<<3 | proto.WireVarint) n += 1 case *SampleOneOf_Field14: n += proto.SizeVarint(14<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field14))) n += len(x.Field14) case *SampleOneOf_Field15: n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Field15))) n += len(x.Field15) case *SampleOneOf_SubMessage: s := proto.Size(x.SubMessage) n += proto.SizeVarint(16<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } func init() { proto.RegisterType((*Subby)(nil), "one.Subby") proto.RegisterType((*SampleOneOf)(nil), "one.SampleOneOf") } func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func (this *SampleOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { return OneDescription() } func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) { d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{} var gzipped = []byte{ // 3749 bytes of a gzipped FileDescriptorSet 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x5b, 0x6c, 0xe4, 0xe6, 0x75, 0x16, 0xe7, 0xa6, 0x99, 0x33, 0xa3, 0x11, 0xf5, 0x4b, 0x5e, 0x73, 0xe5, 0x78, 0x56, 0xab, 0xd8, 0xb1, 0x6c, 0xd7, 0x5a, 0x5b, 0x97, 0xbd, 0xcc, 0x36, 0x31, 0x46, 0xd2, 0x58, 0xab, 0x85, 0x6e, 0xe1, 0x48, 0x89, 0x9d, 0x3c, 0x10, 0x1c, 0xce, 0x3f, 0x23, 0xee, 0x72, 0xc8, 0x29, 0xc9, 0x59, 0x5b, 0x7e, 0xda, 0xc0, 0xbd, 0x20, 0x08, 0x7a, 0x4d, 0x81, 0x26, 0x8e, 0xe3, 0xa6, 0x01, 0x5a, 0xa7, 0xe9, 0x2d, 0xe9, 0x25, 0x0d, 0xfa, 0xd4, 0x97, 0xb4, 0x7e, 0x2a, 0x92, 0xb7, 0x3e, 0xe4, 0x21, 0xab, 0x1a, 0x68, 0xda, 0xba, 0xad, 0xdb, 0x18, 0x68, 0x80, 0x7d, 0x29, 0xfe, 0x1b, 0xc9, 0xb9, 0x68, 0x39, 0x0a, 0x90, 0x38, 0x4f, 0x12, 0xcf, 0x39, 0xdf, 0xc7, 0xc3, 0xf3, 0x9f, 0xff, 0x9c, 0xc3, 0x7f, 0x08, 0x9f, 0x59, 0x81, 0xb9, 0x96, 0xe3, 0xb4, 0x2c, 0x7c, 0xa9, 0xe3, 0x3a, 0xbe, 0x53, 0xef, 0x36, 0x2f, 0x35, 0xb0, 0x67, 0xb8, 0x66, 0xc7, 0x77, 0xdc, 0x45, 0x2a, 0x43, 0x93, 0xcc, 0x62, 0x51, 0x58, 0xcc, 0xef, 0xc0, 0xd4, 0x0b, 0xa6, 0x85, 0x37, 0x02, 0xc3, 0x1a, 0xf6, 0xd1, 0x55, 0x48, 0x35, 0x4d, 0x0b, 0x2b, 0xd2, 0x5c, 0x72, 0x21, 0xbf, 0xf4, 0xd8, 0x62, 0x1f, 0x68, 0xb1, 0x17, 0xb1, 0x4f, 0xc4, 0x2a, 0x45, 0xcc, 0xbf, 0x93, 0x82, 0xe9, 0x21, 0x5a, 0x84, 0x20, 0x65, 0xeb, 0x6d, 0xc2, 0x28, 0x2d, 0xe4, 0x54, 0xfa, 0x3f, 0x52, 0x60, 0xbc, 0xa3, 0x1b, 0xb7, 0xf5, 0x16, 0x56, 0x12, 0x54, 0x2c, 0x2e, 0x51, 0x09, 0xa0, 0x81, 0x3b, 0xd8, 0x6e, 0x60, 0xdb, 0x38, 0x56, 0x92, 0x73, 0xc9, 0x85, 0x9c, 0x1a, 0x91, 0xa0, 0xa7, 0x61, 0xaa, 0xd3, 0xad, 0x5b, 0xa6, 0xa1, 0x45, 0xcc, 0x60, 0x2e, 0xb9, 0x90, 0x56, 0x65, 0xa6, 0xd8, 0x08, 0x8d, 0x9f, 0x80, 0xc9, 0x97, 0xb1, 0x7e, 0x3b, 0x6a, 0x9a, 0xa7, 0xa6, 0x45, 0x22, 0x8e, 0x18, 0xae, 0x43, 0xa1, 0x8d, 0x3d, 0x4f, 0x6f, 0x61, 0xcd, 0x3f, 0xee, 0x60, 0x25, 0x45, 0x9f, 0x7e, 0x6e, 0xe0, 0xe9, 0xfb, 0x9f, 0x3c, 0xcf, 0x51, 0x07, 0xc7, 0x1d, 0x8c, 0x2a, 0x90, 0xc3, 0x76, 0xb7, 0xcd, 0x18, 0xd2, 0xa7, 0xc4, 0xaf, 0x6a, 0x77, 0xdb, 0xfd, 0x2c, 0x59, 0x02, 0xe3, 0x14, 0xe3, 0x1e, 0x76, 0xef, 0x98, 0x06, 0x56, 0x32, 0x94, 0xe0, 0x89, 0x01, 0x82, 0x1a, 0xd3, 0xf7, 0x73, 0x08, 0x1c, 0x5a, 0x87, 0x1c, 0x7e, 0xc5, 0xc7, 0xb6, 0x67, 0x3a, 0xb6, 0x32, 0x4e, 0x49, 0x1e, 0x1f, 0xb2, 0x8a, 0xd8, 0x6a, 0xf4, 0x53, 0x84, 0x38, 0x74, 0x19, 0xc6, 0x9d, 0x8e, 0x6f, 0x3a, 0xb6, 0xa7, 0x64, 0xe7, 0xa4, 0x85, 0xfc, 0xd2, 0x87, 0x86, 0x26, 0xc2, 0x1e, 0xb3, 0x51, 0x85, 0x31, 0xda, 0x02, 0xd9, 0x73, 0xba, 0xae, 0x81, 0x35, 0xc3, 0x69, 0x60, 0xcd, 0xb4, 0x9b, 0x8e, 0x92, 0xa3, 0x04, 0x17, 0x06, 0x1f, 0x84, 0x1a, 0xae, 0x3b, 0x0d, 0xbc, 0x65, 0x37, 0x1d, 0xb5, 0xe8, 0xf5, 0x5c, 0xa3, 0x73, 0x90, 0xf1, 0x8e, 0x6d, 0x5f, 0x7f, 0x45, 0x29, 0xd0, 0x0c, 0xe1, 0x57, 0xf3, 0xff, 0x97, 0x86, 0xc9, 0x51, 0x52, 0xec, 0x3a, 0xa4, 0x9b, 0xe4, 0x29, 0x95, 0xc4, 0x59, 0x62, 0xc0, 0x30, 0xbd, 0x41, 0xcc, 0xfc, 0x84, 0x41, 0xac, 0x40, 0xde, 0xc6, 0x9e, 0x8f, 0x1b, 0x2c, 0x23, 0x92, 0x23, 0xe6, 0x14, 0x30, 0xd0, 0x60, 0x4a, 0xa5, 0x7e, 0xa2, 0x94, 0x7a, 0x11, 0x26, 0x03, 0x97, 0x34, 0x57, 0xb7, 0x5b, 0x22, 0x37, 0x2f, 0xc5, 0x79, 0xb2, 0x58, 0x15, 0x38, 0x95, 0xc0, 0xd4, 0x22, 0xee, 0xb9, 0x46, 0x1b, 0x00, 0x8e, 0x8d, 0x9d, 0xa6, 0xd6, 0xc0, 0x86, 0xa5, 0x64, 0x4f, 0x89, 0xd2, 0x1e, 0x31, 0x19, 0x88, 0x92, 0xc3, 0xa4, 0x86, 0x85, 0xae, 0x85, 0xa9, 0x36, 0x7e, 0x4a, 0xa6, 0xec, 0xb0, 0x4d, 0x36, 0x90, 0x6d, 0x87, 0x50, 0x74, 0x31, 0xc9, 0x7b, 0xdc, 0xe0, 0x4f, 0x96, 0xa3, 0x4e, 0x2c, 0xc6, 0x3e, 0x99, 0xca, 0x61, 0xec, 0xc1, 0x26, 0xdc, 0xe8, 0x25, 0xfa, 0x30, 0x04, 0x02, 0x8d, 0xa6, 0x15, 0xd0, 0x2a, 0x54, 0x10, 0xc2, 0x5d, 0xbd, 0x8d, 0x67, 0xaf, 0x42, 0xb1, 0x37, 0x3c, 0x68, 0x06, 0xd2, 0x9e, 0xaf, 0xbb, 0x3e, 0xcd, 0xc2, 0xb4, 0xca, 0x2e, 0x90, 0x0c, 0x49, 0x6c, 0x37, 0x68, 0x95, 0x4b, 0xab, 0xe4, 0xdf, 0xd9, 0x2b, 0x30, 0xd1, 0x73, 0xfb, 0x51, 0x81, 0xf3, 0x5f, 0xc8, 0xc0, 0xcc, 0xb0, 0x9c, 0x1b, 0x9a, 0xfe, 0xe7, 0x20, 0x63, 0x77, 0xdb, 0x75, 0xec, 0x2a, 0x49, 0xca, 0xc0, 0xaf, 0x50, 0x05, 0xd2, 0x96, 0x5e, 0xc7, 0x96, 0x92, 0x9a, 0x93, 0x16, 0x8a, 0x4b, 0x4f, 0x8f, 0x94, 0xd5, 0x8b, 0xdb, 0x04, 0xa2, 0x32, 0x24, 0xfa, 0x18, 0xa4, 0x78, 0x89, 0x23, 0x0c, 0x4f, 0x8d, 0xc6, 0x40, 0x72, 0x51, 0xa5, 0x38, 0xf4, 0x08, 0xe4, 0xc8, 0x5f, 0x16, 0xdb, 0x0c, 0xf5, 0x39, 0x4b, 0x04, 0x24, 0xae, 0x68, 0x16, 0xb2, 0x34, 0xcd, 0x1a, 0x58, 0xb4, 0x86, 0xe0, 0x9a, 0x2c, 0x4c, 0x03, 0x37, 0xf5, 0xae, 0xe5, 0x6b, 0x77, 0x74, 0xab, 0x8b, 0x69, 0xc2, 0xe4, 0xd4, 0x02, 0x17, 0x7e, 0x82, 0xc8, 0xd0, 0x05, 0xc8, 0xb3, 0xac, 0x34, 0xed, 0x06, 0x7e, 0x85, 0x56, 0x9f, 0xb4, 0xca, 0x12, 0x75, 0x8b, 0x48, 0xc8, 0xed, 0x6f, 0x79, 0x8e, 0x2d, 0x96, 0x96, 0xde, 0x82, 0x08, 0xe8, 0xed, 0xaf, 0xf4, 0x17, 0xbe, 0x47, 0x87, 0x3f, 0x5e, 0x7f, 0x2e, 0xce, 0x7f, 0x2b, 0x01, 0x29, 0xba, 0xdf, 0x26, 0x21, 0x7f, 0xf0, 0xd2, 0x7e, 0x55, 0xdb, 0xd8, 0x3b, 0x5c, 0xdb, 0xae, 0xca, 0x12, 0x2a, 0x02, 0x50, 0xc1, 0x0b, 0xdb, 0x7b, 0x95, 0x03, 0x39, 0x11, 0x5c, 0x6f, 0xed, 0x1e, 0x5c, 0x5e, 0x91, 0x93, 0x01, 0xe0, 0x90, 0x09, 0x52, 0x51, 0x83, 0xe5, 0x25, 0x39, 0x8d, 0x64, 0x28, 0x30, 0x82, 0xad, 0x17, 0xab, 0x1b, 0x97, 0x57, 0xe4, 0x4c, 0xaf, 0x64, 0x79, 0x49, 0x1e, 0x47, 0x13, 0x90, 0xa3, 0x92, 0xb5, 0xbd, 0xbd, 0x6d, 0x39, 0x1b, 0x70, 0xd6, 0x0e, 0xd4, 0xad, 0xdd, 0x4d, 0x39, 0x17, 0x70, 0x6e, 0xaa, 0x7b, 0x87, 0xfb, 0x32, 0x04, 0x0c, 0x3b, 0xd5, 0x5a, 0xad, 0xb2, 0x59, 0x95, 0xf3, 0x81, 0xc5, 0xda, 0x4b, 0x07, 0xd5, 0x9a, 0x5c, 0xe8, 0x71, 0x6b, 0x79, 0x49, 0x9e, 0x08, 0x6e, 0x51, 0xdd, 0x3d, 0xdc, 0x91, 0x8b, 0x68, 0x0a, 0x26, 0xd8, 0x2d, 0x84, 0x13, 0x93, 0x7d, 0xa2, 0xcb, 0x2b, 0xb2, 0x1c, 0x3a, 0xc2, 0x58, 0xa6, 0x7a, 0x04, 0x97, 0x57, 0x64, 0x34, 0xbf, 0x0e, 0x69, 0x9a, 0x5d, 0x08, 0x41, 0x71, 0xbb, 0xb2, 0x56, 0xdd, 0xd6, 0xf6, 0xf6, 0x0f, 0xb6, 0xf6, 0x76, 0x2b, 0xdb, 0xb2, 0x14, 0xca, 0xd4, 0xea, 0xc7, 0x0f, 0xb7, 0xd4, 0xea, 0x86, 0x9c, 0x88, 0xca, 0xf6, 0xab, 0x95, 0x83, 0xea, 0x86, 0x9c, 0x9c, 0x37, 0x60, 0x66, 0x58, 0x9d, 0x19, 0xba, 0x33, 0x22, 0x4b, 0x9c, 0x38, 0x65, 0x89, 0x29, 0xd7, 0xc0, 0x12, 0x7f, 0x55, 0x82, 0xe9, 0x21, 0xb5, 0x76, 0xe8, 0x4d, 0x9e, 0x87, 0x34, 0x4b, 0x51, 0xd6, 0x7d, 0x9e, 0x1c, 0x5a, 0xb4, 0x69, 0xc2, 0x0e, 0x74, 0x20, 0x8a, 0x8b, 0x76, 0xe0, 0xe4, 0x29, 0x1d, 0x98, 0x50, 0x0c, 0x38, 0xf9, 0x9a, 0x04, 0xca, 0x69, 0xdc, 0x31, 0x85, 0x22, 0xd1, 0x53, 0x28, 0xae, 0xf7, 0x3b, 0x70, 0xf1, 0xf4, 0x67, 0x18, 0xf0, 0xe2, 0x2d, 0x09, 0xce, 0x0d, 0x1f, 0x54, 0x86, 0xfa, 0xf0, 0x31, 0xc8, 0xb4, 0xb1, 0x7f, 0xe4, 0x88, 0x66, 0xfd, 0x91, 0x21, 0x2d, 0x80, 0xa8, 0xfb, 0x63, 0xc5, 0x51, 0xd1, 0x1e, 0x92, 0x3c, 0x6d, 0xda, 0x60, 0xde, 0x0c, 0x78, 0xfa, 0xd9, 0x04, 0x3c, 0x34, 0x94, 0x7c, 0xa8, 0xa3, 0x8f, 0x02, 0x98, 0x76, 0xa7, 0xeb, 0xb3, 0x86, 0xcc, 0xea, 0x53, 0x8e, 0x4a, 0xe8, 0xde, 0x27, 0xb5, 0xa7, 0xeb, 0x07, 0xfa, 0x24, 0xd5, 0x03, 0x13, 0x51, 0x83, 0xab, 0xa1, 0xa3, 0x29, 0xea, 0x68, 0xe9, 0x94, 0x27, 0x1d, 0xe8, 0x75, 0xcf, 0x82, 0x6c, 0x58, 0x26, 0xb6, 0x7d, 0xcd, 0xf3, 0x5d, 0xac, 0xb7, 0x4d, 0xbb, 0x45, 0x0b, 0x70, 0xb6, 0x9c, 0x6e, 0xea, 0x96, 0x87, 0xd5, 0x49, 0xa6, 0xae, 0x09, 0x2d, 0x41, 0xd0, 0x2e, 0xe3, 0x46, 0x10, 0x99, 0x1e, 0x04, 0x53, 0x07, 0x88, 0xf9, 0xcf, 0x8d, 0x43, 0x3e, 0x32, 0xd6, 0xa1, 0x8b, 0x50, 0xb8, 0xa5, 0xdf, 0xd1, 0x35, 0x31, 0xaa, 0xb3, 0x48, 0xe4, 0x89, 0x6c, 0x9f, 0x8f, 0xeb, 0xcf, 0xc2, 0x0c, 0x35, 0x71, 0xba, 0x3e, 0x76, 0x35, 0xc3, 0xd2, 0x3d, 0x8f, 0x06, 0x2d, 0x4b, 0x4d, 0x11, 0xd1, 0xed, 0x11, 0xd5, 0xba, 0xd0, 0xa0, 0x55, 0x98, 0xa6, 0x88, 0x76, 0xd7, 0xf2, 0xcd, 0x8e, 0x85, 0x35, 0xf2, 0xf2, 0xe0, 0xd1, 0x42, 0x1c, 0x78, 0x36, 0x45, 0x2c, 0x76, 0xb8, 0x01, 0xf1, 0xc8, 0x43, 0x9b, 0xf0, 0x28, 0x85, 0xb5, 0xb0, 0x8d, 0x5d, 0xdd, 0xc7, 0x1a, 0xfe, 0xa5, 0xae, 0x6e, 0x79, 0x9a, 0x6e, 0x37, 0xb4, 0x23, 0xdd, 0x3b, 0x52, 0x66, 0xa2, 0x04, 0xe7, 0x89, 0xed, 0x26, 0x37, 0xad, 0x52, 0xcb, 0x8a, 0xdd, 0xb8, 0xa1, 0x7b, 0x47, 0xa8, 0x0c, 0xe7, 0x28, 0x91, 0xe7, 0xbb, 0xa6, 0xdd, 0xd2, 0x8c, 0x23, 0x6c, 0xdc, 0xd6, 0xba, 0x7e, 0xf3, 0xaa, 0xf2, 0x48, 0x94, 0x81, 0x3a, 0x59, 0xa3, 0x36, 0xeb, 0xc4, 0xe4, 0xd0, 0x6f, 0x5e, 0x45, 0x35, 0x28, 0x90, 0xf5, 0x68, 0x9b, 0xaf, 0x62, 0xad, 0xe9, 0xb8, 0xb4, 0xb9, 0x14, 0x87, 0x6c, 0xee, 0x48, 0x10, 0x17, 0xf7, 0x38, 0x60, 0xc7, 0x69, 0xe0, 0x72, 0xba, 0xb6, 0x5f, 0xad, 0x6e, 0xa8, 0x79, 0xc1, 0xf2, 0x82, 0xe3, 0x92, 0x9c, 0x6a, 0x39, 0x41, 0x8c, 0xf3, 0x2c, 0xa7, 0x5a, 0x8e, 0x88, 0xf0, 0x2a, 0x4c, 0x1b, 0x06, 0x7b, 0x6c, 0xd3, 0xd0, 0xf8, 0x94, 0xef, 0x29, 0x72, 0x4f, 0xbc, 0x0c, 0x63, 0x93, 0x19, 0xf0, 0x34, 0xf7, 0xd0, 0x35, 0x78, 0x28, 0x8c, 0x57, 0x14, 0x38, 0x35, 0xf0, 0x94, 0xfd, 0xd0, 0x55, 0x98, 0xee, 0x1c, 0x0f, 0x02, 0x51, 0xcf, 0x1d, 0x3b, 0xc7, 0xfd, 0xb0, 0xc7, 0xe9, 0x9b, 0x9b, 0x8b, 0x0d, 0xdd, 0xc7, 0x0d, 0xe5, 0xe1, 0xa8, 0x75, 0x44, 0x81, 0x2e, 0x81, 0x6c, 0x18, 0x1a, 0xb6, 0xf5, 0xba, 0x85, 0x35, 0xdd, 0xc5, 0xb6, 0xee, 0x29, 0x17, 0xa2, 0xc6, 0x45, 0xc3, 0xa8, 0x52, 0x6d, 0x85, 0x2a, 0xd1, 0x53, 0x30, 0xe5, 0xd4, 0x6f, 0x19, 0x2c, 0xb9, 0xb4, 0x8e, 0x8b, 0x9b, 0xe6, 0x2b, 0xca, 0x63, 0x34, 0x4c, 0x93, 0x44, 0x41, 0x53, 0x6b, 0x9f, 0x8a, 0xd1, 0x93, 0x20, 0x1b, 0xde, 0x91, 0xee, 0x76, 0x68, 0x77, 0xf7, 0x3a, 0xba, 0x81, 0x95, 0xc7, 0x99, 0x29, 0x93, 0xef, 0x0a, 0x31, 0x7a, 0x11, 0x66, 0xba, 0xb6, 0x69, 0xfb, 0xd8, 0xed, 0xb8, 0x98, 0x0c, 0xe9, 0x6c, 0xa7, 0x29, 0xff, 0x3a, 0x7e, 0xca, 0x98, 0x7d, 0x18, 0xb5, 0x66, 0xab, 0xab, 0x4e, 0x77, 0x07, 0x85, 0xf3, 0x65, 0x28, 0x44, 0x17, 0x1d, 0xe5, 0x80, 0x2d, 0xbb, 0x2c, 0x91, 0x1e, 0xba, 0xbe, 0xb7, 0x41, 0xba, 0xdf, 0xa7, 0xaa, 0x72, 0x82, 0x74, 0xe1, 0xed, 0xad, 0x83, 0xaa, 0xa6, 0x1e, 0xee, 0x1e, 0x6c, 0xed, 0x54, 0xe5, 0xe4, 0x53, 0xb9, 0xec, 0x0f, 0xc7, 0xe5, 0xbb, 0x77, 0xef, 0xde, 0x4d, 0xcc, 0x7f, 0x27, 0x01, 0xc5, 0xde, 0xc9, 0x17, 0xfd, 0x22, 0x3c, 0x2c, 0x5e, 0x53, 0x3d, 0xec, 0x6b, 0x2f, 0x9b, 0x2e, 0xcd, 0xc3, 0xb6, 0xce, 0x66, 0xc7, 0x20, 0x84, 0x33, 0xdc, 0xaa, 0x86, 0xfd, 0x4f, 0x9a, 0x2e, 0xc9, 0xb2, 0xb6, 0xee, 0xa3, 0x6d, 0xb8, 0x60, 0x3b, 0x9a, 0xe7, 0xeb, 0x76, 0x43, 0x77, 0x1b, 0x5a, 0x78, 0x40, 0xa0, 0xe9, 0x86, 0x81, 0x3d, 0xcf, 0x61, 0x2d, 0x20, 0x60, 0xf9, 0x90, 0xed, 0xd4, 0xb8, 0x71, 0x58, 0x1b, 0x2b, 0xdc, 0xb4, 0x6f, 0xb9, 0x93, 0xa7, 0x2d, 0xf7, 0x23, 0x90, 0x6b, 0xeb, 0x1d, 0x0d, 0xdb, 0xbe, 0x7b, 0x4c, 0xe7, 0xb5, 0xac, 0x9a, 0x6d, 0xeb, 0x9d, 0x2a, 0xb9, 0xfe, 0xe9, 0xad, 0x41, 0x34, 0x8e, 0xdf, 0x4f, 0x42, 0x21, 0x3a, 0xb3, 0x91, 0x11, 0xd8, 0xa0, 0xf5, 0x59, 0xa2, 0xdb, 0xf7, 0xc3, 0x0f, 0x9c, 0xf0, 0x16, 0xd7, 0x49, 0xe1, 0x2e, 0x67, 0xd8, 0x24, 0xa5, 0x32, 0x24, 0x69, 0x9a, 0x64, 0xc3, 0x62, 0x36, 0x9f, 0x67, 0x55, 0x7e, 0x85, 0x36, 0x21, 0x73, 0xcb, 0xa3, 0xdc, 0x19, 0xca, 0xfd, 0xd8, 0x83, 0xb9, 0x6f, 0xd6, 0x28, 0x79, 0xee, 0x66, 0x4d, 0xdb, 0xdd, 0x53, 0x77, 0x2a, 0xdb, 0x2a, 0x87, 0xa3, 0xf3, 0x90, 0xb2, 0xf4, 0x57, 0x8f, 0x7b, 0x4b, 0x3c, 0x15, 0x8d, 0x1a, 0xf8, 0xf3, 0x90, 0x7a, 0x19, 0xeb, 0xb7, 0x7b, 0x0b, 0x2b, 0x15, 0xfd, 0x14, 0x53, 0xff, 0x12, 0xa4, 0x69, 0xbc, 0x10, 0x00, 0x8f, 0x98, 0x3c, 0x86, 0xb2, 0x90, 0x5a, 0xdf, 0x53, 0x49, 0xfa, 0xcb, 0x50, 0x60, 0x52, 0x6d, 0x7f, 0xab, 0xba, 0x5e, 0x95, 0x13, 0xf3, 0xab, 0x90, 0x61, 0x41, 0x20, 0x5b, 0x23, 0x08, 0x83, 0x3c, 0xc6, 0x2f, 0x39, 0x87, 0x24, 0xb4, 0x87, 0x3b, 0x6b, 0x55, 0x55, 0x4e, 0x44, 0x97, 0xd7, 0x83, 0x42, 0x74, 0x5c, 0xfb, 0xd9, 0xe4, 0xd4, 0xdf, 0x49, 0x90, 0x8f, 0x8c, 0x5f, 0xa4, 0xf1, 0xeb, 0x96, 0xe5, 0xbc, 0xac, 0xe9, 0x96, 0xa9, 0x7b, 0x3c, 0x29, 0x80, 0x8a, 0x2a, 0x44, 0x32, 0xea, 0xa2, 0xfd, 0x4c, 0x9c, 0x7f, 0x53, 0x02, 0xb9, 0x7f, 0x74, 0xeb, 0x73, 0x50, 0xfa, 0x40, 0x1d, 0x7c, 0x43, 0x82, 0x62, 0xef, 0xbc, 0xd6, 0xe7, 0xde, 0xc5, 0x0f, 0xd4, 0xbd, 0x2f, 0x49, 0x30, 0xd1, 0x33, 0xa5, 0xfd, 0x5c, 0x79, 0xf7, 0x7a, 0x12, 0xa6, 0x87, 0xe0, 0x50, 0x85, 0x8f, 0xb3, 0x6c, 0xc2, 0x7e, 0x66, 0x94, 0x7b, 0x2d, 0x92, 0x6e, 0xb9, 0xaf, 0xbb, 0x3e, 0x9f, 0x7e, 0x9f, 0x04, 0xd9, 0x6c, 0x60, 0xdb, 0x37, 0x9b, 0x26, 0x76, 0xf9, 0x2b, 0x38, 0x9b, 0x71, 0x27, 0x43, 0x39, 0x7b, 0x0b, 0xff, 0x05, 0x40, 0x1d, 0xc7, 0x33, 0x7d, 0xf3, 0x0e, 0xd6, 0x4c, 0x5b, 0xbc, 0xaf, 0x93, 0x99, 0x37, 0xa5, 0xca, 0x42, 0xb3, 0x65, 0xfb, 0x81, 0xb5, 0x8d, 0x5b, 0x7a, 0x9f, 0x35, 0xa9, 0x7d, 0x49, 0x55, 0x16, 0x9a, 0xc0, 0xfa, 0x22, 0x14, 0x1a, 0x4e, 0x97, 0x8c, 0x0f, 0xcc, 0x8e, 0x94, 0x5a, 0x49, 0xcd, 0x33, 0x59, 0x60, 0xc2, 0xe7, 0xbb, 0xf0, 0xa0, 0xa0, 0xa0, 0xe6, 0x99, 0x8c, 0x99, 0x3c, 0x01, 0x93, 0x7a, 0xab, 0xe5, 0x12, 0x72, 0x41, 0xc4, 0x86, 0xd6, 0x62, 0x20, 0xa6, 0x86, 0xb3, 0x37, 0x21, 0x2b, 0xe2, 0x40, 0xba, 0x19, 0x89, 0x84, 0xd6, 0x61, 0xc7, 0x35, 0x89, 0x85, 0x9c, 0x9a, 0xb5, 0x85, 0xf2, 0x22, 0x14, 0x4c, 0x4f, 0x0b, 0xcf, 0x0d, 0x13, 0x73, 0x89, 0x85, 0xac, 0x9a, 0x37, 0xbd, 0xe0, 0xa0, 0x68, 0xfe, 0xad, 0x04, 0x14, 0x7b, 0xcf, 0x3d, 0xd1, 0x06, 0x64, 0x2d, 0xc7, 0xd0, 0x69, 0x22, 0xb0, 0x43, 0xf7, 0x85, 0x98, 0xa3, 0xd2, 0xc5, 0x6d, 0x6e, 0xaf, 0x06, 0xc8, 0xd9, 0x7f, 0x92, 0x20, 0x2b, 0xc4, 0xe8, 0x1c, 0xa4, 0x3a, 0xba, 0x7f, 0x44, 0xe9, 0xd2, 0x6b, 0x09, 0x59, 0x52, 0xe9, 0x35, 0x91, 0x7b, 0x1d, 0xdd, 0xa6, 0x29, 0xc0, 0xe5, 0xe4, 0x9a, 0xac, 0xab, 0x85, 0xf5, 0x06, 0x1d, 0x87, 0x9d, 0x76, 0x1b, 0xdb, 0xbe, 0x27, 0xd6, 0x95, 0xcb, 0xd7, 0xb9, 0x18, 0x3d, 0x0d, 0x53, 0xbe, 0xab, 0x9b, 0x56, 0x8f, 0x6d, 0x8a, 0xda, 0xca, 0x42, 0x11, 0x18, 0x97, 0xe1, 0xbc, 0xe0, 0x6d, 0x60, 0x5f, 0x37, 0x8e, 0x70, 0x23, 0x04, 0x65, 0xe8, 0xa1, 0xda, 0xc3, 0xdc, 0x60, 0x83, 0xeb, 0x05, 0x76, 0xfe, 0x7b, 0x12, 0x4c, 0x89, 0x01, 0xbe, 0x11, 0x04, 0x6b, 0x07, 0x40, 0xb7, 0x6d, 0xc7, 0x8f, 0x86, 0x6b, 0x30, 0x95, 0x07, 0x70, 0x8b, 0x95, 0x00, 0xa4, 0x46, 0x08, 0x66, 0xdb, 0x00, 0xa1, 0xe6, 0xd4, 0xb0, 0x5d, 0x80, 0x3c, 0x3f, 0xd4, 0xa6, 0xbf, 0x8c, 0xb0, 0xb7, 0x3e, 0x60, 0x22, 0x32, 0xe9, 0xa3, 0x19, 0x48, 0xd7, 0x71, 0xcb, 0xb4, 0xf9, 0x51, 0x1b, 0xbb, 0x10, 0x07, 0x78, 0xa9, 0xe0, 0x00, 0x6f, 0xed, 0xd3, 0x30, 0x6d, 0x38, 0xed, 0x7e, 0x77, 0xd7, 0xe4, 0xbe, 0x37, 0x4f, 0xef, 0x86, 0xf4, 0x29, 0x08, 0xa7, 0xb3, 0xaf, 0x48, 0xd2, 0x57, 0x13, 0xc9, 0xcd, 0xfd, 0xb5, 0xaf, 0x27, 0x66, 0x37, 0x19, 0x74, 0x5f, 0x3c, 0xa9, 0x8a, 0x9b, 0x16, 0x36, 0x88, 0xf7, 0xf0, 0xa3, 0x8f, 0xc0, 0x33, 0x2d, 0xd3, 0x3f, 0xea, 0xd6, 0x17, 0x0d, 0xa7, 0x7d, 0xa9, 0xe5, 0xb4, 0x9c, 0xf0, 0xc7, 0x20, 0x72, 0x45, 0x2f, 0xe8, 0x7f, 0xfc, 0x07, 0xa1, 0x5c, 0x20, 0x9d, 0x8d, 0xfd, 0xf5, 0xa8, 0xbc, 0x0b, 0xd3, 0xdc, 0x58, 0xa3, 0x27, 0xd2, 0x6c, 0x0e, 0x47, 0x0f, 0x3c, 0x95, 0x50, 0xbe, 0xf9, 0x0e, 0xed, 0x74, 0xea, 0x14, 0x87, 0x12, 0x1d, 0x9b, 0xd4, 0xcb, 0x2a, 0x3c, 0xd4, 0xc3, 0xc7, 0xb6, 0x26, 0x76, 0x63, 0x18, 0xbf, 0xc3, 0x19, 0xa7, 0x23, 0x8c, 0x35, 0x0e, 0x2d, 0xaf, 0xc3, 0xc4, 0x59, 0xb8, 0xfe, 0x81, 0x73, 0x15, 0x70, 0x94, 0x64, 0x13, 0x26, 0x29, 0x89, 0xd1, 0xf5, 0x7c, 0xa7, 0x4d, 0xeb, 0xde, 0x83, 0x69, 0xfe, 0xf1, 0x1d, 0xb6, 0x57, 0x8a, 0x04, 0xb6, 0x1e, 0xa0, 0xca, 0x65, 0xa0, 0x87, 0xf0, 0x0d, 0x6c, 0x58, 0x31, 0x0c, 0x6f, 0x73, 0x47, 0x02, 0xfb, 0xf2, 0x27, 0x60, 0x86, 0xfc, 0x4f, 0xcb, 0x52, 0xd4, 0x93, 0xf8, 0x33, 0x18, 0xe5, 0x7b, 0xaf, 0xb1, 0xed, 0x38, 0x1d, 0x10, 0x44, 0x7c, 0x8a, 0xac, 0x62, 0x0b, 0xfb, 0x3e, 0x76, 0x3d, 0x4d, 0xb7, 0x86, 0xb9, 0x17, 0x79, 0x83, 0x55, 0xbe, 0xf8, 0x6e, 0xef, 0x2a, 0x6e, 0x32, 0x64, 0xc5, 0xb2, 0xca, 0x87, 0xf0, 0xf0, 0x90, 0xac, 0x18, 0x81, 0xf3, 0x75, 0xce, 0x39, 0x33, 0x90, 0x19, 0x84, 0x76, 0x1f, 0x84, 0x3c, 0x58, 0xcb, 0x11, 0x38, 0xbf, 0xc4, 0x39, 0x11, 0xc7, 0x8a, 0x25, 0x25, 0x8c, 0x37, 0x61, 0xea, 0x0e, 0x76, 0xeb, 0x8e, 0xc7, 0x0f, 0x0e, 0x46, 0xa0, 0x7b, 0x83, 0xd3, 0x4d, 0x72, 0x20, 0x3d, 0x46, 0x20, 0x5c, 0xd7, 0x20, 0xdb, 0xd4, 0x0d, 0x3c, 0x02, 0xc5, 0x97, 0x39, 0xc5, 0x38, 0xb1, 0x27, 0xd0, 0x0a, 0x14, 0x5a, 0x0e, 0xef, 0x4c, 0xf1, 0xf0, 0x37, 0x39, 0x3c, 0x2f, 0x30, 0x9c, 0xa2, 0xe3, 0x74, 0xba, 0x16, 0x69, 0x5b, 0xf1, 0x14, 0xbf, 0x2f, 0x28, 0x04, 0x86, 0x53, 0x9c, 0x21, 0xac, 0x5f, 0x11, 0x14, 0x5e, 0x24, 0x9e, 0xcf, 0x43, 0xde, 0xb1, 0xad, 0x63, 0xc7, 0x1e, 0xc5, 0x89, 0x3f, 0xe0, 0x0c, 0xc0, 0x21, 0x84, 0xe0, 0x3a, 0xe4, 0x46, 0x5d, 0x88, 0x3f, 0x7c, 0x57, 0x6c, 0x0f, 0xb1, 0x02, 0x9b, 0x30, 0x29, 0x0a, 0x94, 0xe9, 0xd8, 0x23, 0x50, 0xfc, 0x11, 0xa7, 0x28, 0x46, 0x60, 0xfc, 0x31, 0x7c, 0xec, 0xf9, 0x2d, 0x3c, 0x0a, 0xc9, 0x5b, 0xe2, 0x31, 0x38, 0x84, 0x87, 0xb2, 0x8e, 0x6d, 0xe3, 0x68, 0x34, 0x86, 0xaf, 0x89, 0x50, 0x0a, 0x0c, 0xa1, 0x58, 0x87, 0x89, 0xb6, 0xee, 0x7a, 0x47, 0xba, 0x35, 0xd2, 0x72, 0xfc, 0x31, 0xe7, 0x28, 0x04, 0x20, 0x1e, 0x91, 0xae, 0x7d, 0x16, 0x9a, 0xaf, 0x8b, 0x88, 0x44, 0x60, 0x7c, 0xeb, 0x79, 0x3e, 0x3d, 0x9b, 0x39, 0x0b, 0xdb, 0x9f, 0x88, 0xad, 0xc7, 0xb0, 0x3b, 0x51, 0xc6, 0xeb, 0x90, 0xf3, 0xcc, 0x57, 0x47, 0xa2, 0xf9, 0x53, 0xb1, 0xd2, 0x14, 0x40, 0xc0, 0x2f, 0xc1, 0xf9, 0xa1, 0x6d, 0x62, 0x04, 0xb2, 0x3f, 0xe3, 0x64, 0xe7, 0x86, 0xb4, 0x0a, 0x5e, 0x12, 0xce, 0x4a, 0xf9, 0xe7, 0xa2, 0x24, 0xe0, 0x3e, 0xae, 0x7d, 0x32, 0xd9, 0x7b, 0x7a, 0xf3, 0x6c, 0x51, 0xfb, 0x0b, 0x11, 0x35, 0x86, 0xed, 0x89, 0xda, 0x01, 0x9c, 0xe3, 0x8c, 0x67, 0x5b, 0xd7, 0x6f, 0x88, 0xc2, 0xca, 0xd0, 0x87, 0xbd, 0xab, 0xfb, 0x69, 0x98, 0x0d, 0xc2, 0x29, 0x86, 0x52, 0x4f, 0x6b, 0xeb, 0x9d, 0x11, 0x98, 0xbf, 0xc9, 0x99, 0x45, 0xc5, 0x0f, 0xa6, 0x5a, 0x6f, 0x47, 0xef, 0x10, 0xf2, 0x17, 0x41, 0x11, 0xe4, 0x5d, 0xdb, 0xc5, 0x86, 0xd3, 0xb2, 0xcd, 0x57, 0x71, 0x63, 0x04, 0xea, 0xbf, 0xec, 0x5b, 0xaa, 0xc3, 0x08, 0x9c, 0x30, 0x6f, 0x81, 0x1c, 0xcc, 0x2a, 0x9a, 0xd9, 0xee, 0x38, 0xae, 0x1f, 0xc3, 0xf8, 0x57, 0x62, 0xa5, 0x02, 0xdc, 0x16, 0x85, 0x95, 0xab, 0x50, 0xa4, 0x97, 0xa3, 0xa6, 0xe4, 0x5f, 0x73, 0xa2, 0x89, 0x10, 0xc5, 0x0b, 0x87, 0xe1, 0xb4, 0x3b, 0xba, 0x3b, 0x4a, 0xfd, 0xfb, 0x1b, 0x51, 0x38, 0x38, 0x84, 0x17, 0x0e, 0xff, 0xb8, 0x83, 0x49, 0xb7, 0x1f, 0x81, 0xe1, 0x5b, 0xa2, 0x70, 0x08, 0x0c, 0xa7, 0x10, 0x03, 0xc3, 0x08, 0x14, 0x7f, 0x2b, 0x28, 0x04, 0x86, 0x50, 0x7c, 0x3c, 0x6c, 0xb4, 0x2e, 0x6e, 0x99, 0x9e, 0xef, 0xb2, 0x51, 0xf8, 0xc1, 0x54, 0xdf, 0x7e, 0xb7, 0x77, 0x08, 0x53, 0x23, 0xd0, 0xf2, 0x4d, 0x98, 0xec, 0x1b, 0x31, 0x50, 0xdc, 0x2f, 0xfa, 0xca, 0x67, 0xde, 0xe7, 0xc5, 0xa8, 0x77, 0xc2, 0x28, 0x6f, 0x93, 0x75, 0xef, 0x9d, 0x03, 0xe2, 0xc9, 0x5e, 0x7b, 0x3f, 0x58, 0xfa, 0x9e, 0x31, 0xa0, 0xfc, 0x02, 0x4c, 0xf4, 0xcc, 0x00, 0xf1, 0x54, 0xbf, 0xcc, 0xa9, 0x0a, 0xd1, 0x11, 0xa0, 0xbc, 0x0a, 0x29, 0xd2, 0xcf, 0xe3, 0xe1, 0xbf, 0xc2, 0xe1, 0xd4, 0xbc, 0xfc, 0x51, 0xc8, 0x8a, 0x3e, 0x1e, 0x0f, 0xfd, 0x55, 0x0e, 0x0d, 0x20, 0x04, 0x2e, 0x7a, 0x78, 0x3c, 0xfc, 0xd7, 0x04, 0x5c, 0x40, 0x08, 0x7c, 0xf4, 0x10, 0xfe, 0xfd, 0xe7, 0x52, 0xbc, 0x0e, 0x8b, 0xd8, 0x5d, 0x87, 0x71, 0xde, 0xbc, 0xe3, 0xd1, 0x9f, 0xe5, 0x37, 0x17, 0x88, 0xf2, 0x15, 0x48, 0x8f, 0x18, 0xf0, 0x5f, 0xe7, 0x50, 0x66, 0x5f, 0x5e, 0x87, 0x7c, 0xa4, 0x61, 0xc7, 0xc3, 0x7f, 0x83, 0xc3, 0xa3, 0x28, 0xe2, 0x3a, 0x6f, 0xd8, 0xf1, 0x04, 0xbf, 0x29, 0x5c, 0xe7, 0x08, 0x12, 0x36, 0xd1, 0xab, 0xe3, 0xd1, 0xbf, 0x25, 0xa2, 0x2e, 0x20, 0xe5, 0xe7, 0x21, 0x17, 0xd4, 0xdf, 0x78, 0xfc, 0x6f, 0x73, 0x7c, 0x88, 0x21, 0x11, 0x88, 0xd4, 0xff, 0x78, 0x8a, 0xdf, 0x11, 0x11, 0x88, 0xa0, 0xc8, 0x36, 0xea, 0xef, 0xe9, 0xf1, 0x4c, 0x9f, 0x17, 0xdb, 0xa8, 0xaf, 0xa5, 0x93, 0xd5, 0xa4, 0x65, 0x30, 0x9e, 0xe2, 0x77, 0xc5, 0x6a, 0x52, 0x7b, 0xe2, 0x46, 0x7f, 0x93, 0x8c, 0xe7, 0xf8, 0x3d, 0xe1, 0x46, 0x5f, 0x8f, 0x2c, 0xef, 0x03, 0x1a, 0x6c, 0x90, 0xf1, 0x7c, 0x5f, 0xe0, 0x7c, 0x53, 0x03, 0xfd, 0xb1, 0xfc, 0x49, 0x38, 0x37, 0xbc, 0x39, 0xc6, 0xb3, 0x7e, 0xf1, 0xfd, 0xbe, 0xd7, 0x99, 0x68, 0x6f, 0x2c, 0x1f, 0x84, 0x55, 0x36, 0xda, 0x18, 0xe3, 0x69, 0x5f, 0x7f, 0xbf, 0xb7, 0xd0, 0x46, 0xfb, 0x62, 0xb9, 0x02, 0x10, 0xf6, 0xa4, 0x78, 0xae, 0x37, 0x38, 0x57, 0x04, 0x44, 0xb6, 0x06, 0x6f, 0x49, 0xf1, 0xf8, 0x2f, 0x8b, 0xad, 0xc1, 0x11, 0x64, 0x6b, 0x88, 0x6e, 0x14, 0x8f, 0x7e, 0x53, 0x6c, 0x0d, 0x01, 0x29, 0x5f, 0x87, 0xac, 0xdd, 0xb5, 0x2c, 0x92, 0x5b, 0xe8, 0xc1, 0x1f, 0xd9, 0x28, 0xff, 0x76, 0x9f, 0x83, 0x05, 0xa0, 0xbc, 0x0a, 0x69, 0xdc, 0xae, 0xe3, 0x46, 0x1c, 0xf2, 0xdf, 0xef, 0x8b, 0x7a, 0x42, 0xac, 0xcb, 0xcf, 0x03, 0xb0, 0x97, 0x69, 0xfa, 0x1b, 0x4b, 0x0c, 0xf6, 0x3f, 0xee, 0xf3, 0xdf, 0xef, 0x43, 0x48, 0x48, 0xc0, 0xbe, 0x06, 0x78, 0x30, 0xc1, 0xbb, 0xbd, 0x04, 0xf4, 0x05, 0xfc, 0x1a, 0x8c, 0xdf, 0xf2, 0x1c, 0xdb, 0xd7, 0x5b, 0x71, 0xe8, 0xff, 0xe4, 0x68, 0x61, 0x4f, 0x02, 0xd6, 0x76, 0x5c, 0xec, 0xeb, 0x2d, 0x2f, 0x0e, 0xfb, 0x5f, 0x1c, 0x1b, 0x00, 0x08, 0xd8, 0xd0, 0x3d, 0x7f, 0x94, 0xe7, 0xfe, 0x6f, 0x01, 0x16, 0x00, 0xe2, 0x34, 0xf9, 0xff, 0x36, 0x3e, 0x8e, 0xc3, 0xbe, 0x27, 0x9c, 0xe6, 0xf6, 0xe5, 0x8f, 0x42, 0x8e, 0xfc, 0xcb, 0xbe, 0x69, 0x89, 0x01, 0xff, 0x0f, 0x07, 0x87, 0x08, 0x72, 0x67, 0xcf, 0x6f, 0xf8, 0x66, 0x7c, 0xb0, 0xff, 0x97, 0xaf, 0xb4, 0xb0, 0x2f, 0x57, 0x20, 0xef, 0xf9, 0x8d, 0x46, 0x97, 0x4f, 0x34, 0x31, 0xf0, 0x1f, 0xdd, 0x0f, 0x5e, 0x72, 0x03, 0xcc, 0xda, 0xc5, 0xe1, 0xe7, 0x75, 0xb0, 0xe9, 0x6c, 0x3a, 0xec, 0xa4, 0x0e, 0x3e, 0x9f, 0x86, 0x87, 0x0c, 0xa7, 0x5d, 0x77, 0xbc, 0x4b, 0x75, 0xc7, 0x3f, 0xba, 0xe4, 0xd8, 0xdc, 0x10, 0x25, 0x1d, 0x1b, 0xcf, 0x9e, 0xed, 0x44, 0x6e, 0xfe, 0x3c, 0xa4, 0x6b, 0xdd, 0x7a, 0xfd, 0x18, 0xc9, 0x90, 0xf4, 0xba, 0x75, 0xfe, 0xc1, 0x05, 0xf9, 0x77, 0xfe, 0xfb, 0x49, 0xc8, 0xd7, 0xf4, 0x76, 0xc7, 0xc2, 0x7b, 0x36, 0xde, 0x6b, 0x22, 0x05, 0x32, 0xf4, 0x01, 0x9e, 0xa3, 0x46, 0xd2, 0x8d, 0x31, 0x95, 0x5f, 0x07, 0x9a, 0x25, 0x7a, 0x52, 0x99, 0x08, 0x34, 0x4b, 0x81, 0x66, 0x99, 0x1d, 0x54, 0x06, 0x9a, 0xe5, 0x40, 0xb3, 0x42, 0x8f, 0x2b, 0x93, 0x81, 0x66, 0x25, 0xd0, 0xac, 0xd2, 0xe3, 0xf8, 0x89, 0x40, 0xb3, 0x1a, 0x68, 0x2e, 0xd3, 0x03, 0xf8, 0x54, 0xa0, 0xb9, 0x1c, 0x68, 0xae, 0xd0, 0x73, 0xf7, 0xa9, 0x40, 0x73, 0x25, 0xd0, 0x5c, 0xa5, 0x67, 0xed, 0x28, 0xd0, 0x5c, 0x0d, 0x34, 0xd7, 0xe8, 0x47, 0x15, 0xe3, 0x81, 0xe6, 0x1a, 0x9a, 0x85, 0x71, 0xf6, 0x64, 0xcf, 0xd2, 0xdf, 0x32, 0x27, 0x6f, 0x8c, 0xa9, 0x42, 0x10, 0xea, 0x9e, 0xa3, 0x1f, 0x4e, 0x64, 0x42, 0xdd, 0x73, 0xa1, 0x6e, 0x89, 0x7e, 0x41, 0x2c, 0x87, 0xba, 0xa5, 0x50, 0xb7, 0xac, 0x4c, 0x90, 0x75, 0x0f, 0x75, 0xcb, 0xa1, 0x6e, 0x45, 0x29, 0x92, 0xf8, 0x87, 0xba, 0x95, 0x50, 0xb7, 0xaa, 0x4c, 0xce, 0x49, 0x0b, 0x85, 0x50, 0xb7, 0x8a, 0x9e, 0x81, 0xbc, 0xd7, 0xad, 0x6b, 0xfc, 0xa7, 0x77, 0xfa, 0x81, 0x46, 0x7e, 0x09, 0x16, 0x49, 0x46, 0xd0, 0x45, 0xbd, 0x31, 0xa6, 0x82, 0xd7, 0xad, 0xf3, 0xc2, 0xb8, 0x56, 0x00, 0x7a, 0x8e, 0xa0, 0xd1, 0x2f, 0x13, 0xd7, 0x36, 0xde, 0xbe, 0x57, 0x1a, 0xfb, 0xee, 0xbd, 0xd2, 0xd8, 0x3f, 0xdf, 0x2b, 0x8d, 0xfd, 0xe0, 0x5e, 0x49, 0x7a, 0xef, 0x5e, 0x49, 0xfa, 0xf1, 0xbd, 0x92, 0x74, 0xf7, 0xa4, 0x24, 0x7d, 0xed, 0xa4, 0x24, 0x7d, 0xe3, 0xa4, 0x24, 0x7d, 0xfb, 0xa4, 0x24, 0xbd, 0x7d, 0x52, 0x92, 0xbe, 0x7b, 0x52, 0x92, 0x7e, 0x70, 0x52, 0x92, 0x7e, 0x78, 0x52, 0x1a, 0x7b, 0xef, 0xa4, 0x24, 0xfd, 0xf8, 0xa4, 0x34, 0x76, 0xf7, 0x5f, 0x4a, 0x63, 0xf5, 0x0c, 0x4d, 0xa3, 0xe5, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x34, 0x19, 0xac, 0x3a, 0x10, 0x30, 0x00, 0x00, } r := bytes.NewReader(gzipped) gzipr, err := compress_gzip.NewReader(r) if err != nil { panic(err) } ungzipped, err := io_ioutil.ReadAll(gzipr) if err != nil { panic(err) } if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil { panic(err) } return d } func (this *Subby) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *Subby") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *Subby but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *Subby but is not nil && this == nil") } if this.Sub != that1.Sub { return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub) } return nil } func (this *Subby) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*Subby) if !ok { that2, ok := that.(Subby) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Sub != that1.Sub { return false } return true } func (this *SampleOneOf) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf) if !ok { that2, ok := that.(SampleOneOf) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf but is not nil && this == nil") } if that1.TestOneof == nil { if this.TestOneof != nil { return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil") } } else if this.TestOneof == nil { return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil") } else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil { return err } return nil } func (this *SampleOneOf_Field1) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field1) if !ok { that2, ok := that.(SampleOneOf_Field1) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field1") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field1 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field1 but is not nil && this == nil") } if this.Field1 != that1.Field1 { return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1) } return nil } func (this *SampleOneOf_Field2) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field2) if !ok { that2, ok := that.(SampleOneOf_Field2) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field2") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field2 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field2 but is not nil && this == nil") } if this.Field2 != that1.Field2 { return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2) } return nil } func (this *SampleOneOf_Field3) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field3) if !ok { that2, ok := that.(SampleOneOf_Field3) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field3") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field3 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field3 but is not nil && this == nil") } if this.Field3 != that1.Field3 { return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3) } return nil } func (this *SampleOneOf_Field4) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field4) if !ok { that2, ok := that.(SampleOneOf_Field4) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field4") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field4 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field4 but is not nil && this == nil") } if this.Field4 != that1.Field4 { return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4) } return nil } func (this *SampleOneOf_Field5) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field5) if !ok { that2, ok := that.(SampleOneOf_Field5) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field5") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field5 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field5 but is not nil && this == nil") } if this.Field5 != that1.Field5 { return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5) } return nil } func (this *SampleOneOf_Field6) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field6) if !ok { that2, ok := that.(SampleOneOf_Field6) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field6") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field6 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field6 but is not nil && this == nil") } if this.Field6 != that1.Field6 { return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6) } return nil } func (this *SampleOneOf_Field7) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field7) if !ok { that2, ok := that.(SampleOneOf_Field7) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field7") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field7 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field7 but is not nil && this == nil") } if this.Field7 != that1.Field7 { return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7) } return nil } func (this *SampleOneOf_Field8) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field8) if !ok { that2, ok := that.(SampleOneOf_Field8) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field8") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field8 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field8 but is not nil && this == nil") } if this.Field8 != that1.Field8 { return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8) } return nil } func (this *SampleOneOf_Field9) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field9) if !ok { that2, ok := that.(SampleOneOf_Field9) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field9") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field9 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field9 but is not nil && this == nil") } if this.Field9 != that1.Field9 { return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9) } return nil } func (this *SampleOneOf_Field10) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field10) if !ok { that2, ok := that.(SampleOneOf_Field10) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field10") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field10 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field10 but is not nil && this == nil") } if this.Field10 != that1.Field10 { return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10) } return nil } func (this *SampleOneOf_Field11) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field11) if !ok { that2, ok := that.(SampleOneOf_Field11) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field11") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field11 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field11 but is not nil && this == nil") } if this.Field11 != that1.Field11 { return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11) } return nil } func (this *SampleOneOf_Field12) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field12) if !ok { that2, ok := that.(SampleOneOf_Field12) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field12") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field12 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field12 but is not nil && this == nil") } if this.Field12 != that1.Field12 { return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12) } return nil } func (this *SampleOneOf_Field13) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field13) if !ok { that2, ok := that.(SampleOneOf_Field13) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field13") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field13 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field13 but is not nil && this == nil") } if this.Field13 != that1.Field13 { return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13) } return nil } func (this *SampleOneOf_Field14) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field14) if !ok { that2, ok := that.(SampleOneOf_Field14) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field14") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field14 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field14 but is not nil && this == nil") } if this.Field14 != that1.Field14 { return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14) } return nil } func (this *SampleOneOf_Field15) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_Field15) if !ok { that2, ok := that.(SampleOneOf_Field15) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_Field15") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_Field15 but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_Field15 but is not nil && this == nil") } if !bytes.Equal(this.Field15, that1.Field15) { return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15) } return nil } func (this *SampleOneOf_SubMessage) VerboseEqual(that interface{}) error { if that == nil { if this == nil { return nil } return fmt.Errorf("that == nil && this != nil") } that1, ok := that.(*SampleOneOf_SubMessage) if !ok { that2, ok := that.(SampleOneOf_SubMessage) if ok { that1 = &that2 } else { return fmt.Errorf("that is not of type *SampleOneOf_SubMessage") } } if that1 == nil { if this == nil { return nil } return fmt.Errorf("that is type *SampleOneOf_SubMessage but is nil && this != nil") } else if this == nil { return fmt.Errorf("that is type *SampleOneOf_SubMessage but is not nil && this == nil") } if !this.SubMessage.Equal(that1.SubMessage) { return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage) } return nil } func (this *SampleOneOf) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf) if !ok { that2, ok := that.(SampleOneOf) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if that1.TestOneof == nil { if this.TestOneof != nil { return false } } else if this.TestOneof == nil { return false } else if !this.TestOneof.Equal(that1.TestOneof) { return false } return true } func (this *SampleOneOf_Field1) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field1) if !ok { that2, ok := that.(SampleOneOf_Field1) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field1 != that1.Field1 { return false } return true } func (this *SampleOneOf_Field2) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field2) if !ok { that2, ok := that.(SampleOneOf_Field2) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field2 != that1.Field2 { return false } return true } func (this *SampleOneOf_Field3) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field3) if !ok { that2, ok := that.(SampleOneOf_Field3) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field3 != that1.Field3 { return false } return true } func (this *SampleOneOf_Field4) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field4) if !ok { that2, ok := that.(SampleOneOf_Field4) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field4 != that1.Field4 { return false } return true } func (this *SampleOneOf_Field5) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field5) if !ok { that2, ok := that.(SampleOneOf_Field5) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field5 != that1.Field5 { return false } return true } func (this *SampleOneOf_Field6) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field6) if !ok { that2, ok := that.(SampleOneOf_Field6) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field6 != that1.Field6 { return false } return true } func (this *SampleOneOf_Field7) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field7) if !ok { that2, ok := that.(SampleOneOf_Field7) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field7 != that1.Field7 { return false } return true } func (this *SampleOneOf_Field8) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field8) if !ok { that2, ok := that.(SampleOneOf_Field8) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field8 != that1.Field8 { return false } return true } func (this *SampleOneOf_Field9) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field9) if !ok { that2, ok := that.(SampleOneOf_Field9) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field9 != that1.Field9 { return false } return true } func (this *SampleOneOf_Field10) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field10) if !ok { that2, ok := that.(SampleOneOf_Field10) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field10 != that1.Field10 { return false } return true } func (this *SampleOneOf_Field11) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field11) if !ok { that2, ok := that.(SampleOneOf_Field11) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field11 != that1.Field11 { return false } return true } func (this *SampleOneOf_Field12) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field12) if !ok { that2, ok := that.(SampleOneOf_Field12) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field12 != that1.Field12 { return false } return true } func (this *SampleOneOf_Field13) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field13) if !ok { that2, ok := that.(SampleOneOf_Field13) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field13 != that1.Field13 { return false } return true } func (this *SampleOneOf_Field14) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field14) if !ok { that2, ok := that.(SampleOneOf_Field14) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if this.Field14 != that1.Field14 { return false } return true } func (this *SampleOneOf_Field15) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_Field15) if !ok { that2, ok := that.(SampleOneOf_Field15) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !bytes.Equal(this.Field15, that1.Field15) { return false } return true } func (this *SampleOneOf_SubMessage) Equal(that interface{}) bool { if that == nil { if this == nil { return true } return false } that1, ok := that.(*SampleOneOf_SubMessage) if !ok { that2, ok := that.(SampleOneOf_SubMessage) if ok { that1 = &that2 } else { return false } } if that1 == nil { if this == nil { return true } return false } else if this == nil { return false } if !this.SubMessage.Equal(that1.SubMessage) { return false } return true } func (this *Subby) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 5) s = append(s, "&one.Subby{") s = append(s, "Sub: "+fmt.Sprintf("%#v", this.Sub)+",\n") s = append(s, "}") return strings.Join(s, "") } func (this *SampleOneOf) GoString() string { if this == nil { return "nil" } s := make([]string, 0, 20) s = append(s, "&one.SampleOneOf{") if this.TestOneof != nil { s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n") } s = append(s, "}") return strings.Join(s, "") } func (this *SampleOneOf_Field1) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field1{` + `Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ") return s } func (this *SampleOneOf_Field2) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field2{` + `Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ") return s } func (this *SampleOneOf_Field3) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field3{` + `Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ") return s } func (this *SampleOneOf_Field4) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field4{` + `Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ") return s } func (this *SampleOneOf_Field5) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field5{` + `Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ") return s } func (this *SampleOneOf_Field6) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field6{` + `Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ") return s } func (this *SampleOneOf_Field7) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field7{` + `Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ") return s } func (this *SampleOneOf_Field8) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field8{` + `Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ") return s } func (this *SampleOneOf_Field9) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field9{` + `Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ") return s } func (this *SampleOneOf_Field10) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field10{` + `Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ") return s } func (this *SampleOneOf_Field11) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field11{` + `Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ") return s } func (this *SampleOneOf_Field12) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field12{` + `Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ") return s } func (this *SampleOneOf_Field13) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field13{` + `Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ") return s } func (this *SampleOneOf_Field14) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field14{` + `Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ") return s } func (this *SampleOneOf_Field15) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_Field15{` + `Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ") return s } func (this *SampleOneOf_SubMessage) GoString() string { if this == nil { return "nil" } s := strings.Join([]string{`&one.SampleOneOf_SubMessage{` + `SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ") return s } func valueToGoStringOne(v interface{}, typ string) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } func (m *Subby) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Subby) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if len(m.Sub) > 0 { dAtA[i] = 0xa i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Sub))) i += copy(dAtA[i:], m.Sub) } return i, nil } func (m *SampleOneOf) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *SampleOneOf) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.TestOneof != nil { nn1, err := m.TestOneof.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += nn1 } return i, nil } func (m *SampleOneOf_Field1) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x9 i++ i = encodeFixed64One(dAtA, i, uint64(math.Float64bits(float64(m.Field1)))) return i, nil } func (m *SampleOneOf_Field2) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x15 i++ i = encodeFixed32One(dAtA, i, uint32(math.Float32bits(float32(m.Field2)))) return i, nil } func (m *SampleOneOf_Field3) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x18 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field3)) return i, nil } func (m *SampleOneOf_Field4) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x20 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field4)) return i, nil } func (m *SampleOneOf_Field5) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x28 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field5)) return i, nil } func (m *SampleOneOf_Field6) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x30 i++ i = encodeVarintOne(dAtA, i, uint64(m.Field6)) return i, nil } func (m *SampleOneOf_Field7) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x38 i++ i = encodeVarintOne(dAtA, i, uint64((uint32(m.Field7)<<1)^uint32((m.Field7>>31)))) return i, nil } func (m *SampleOneOf_Field8) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x40 i++ i = encodeVarintOne(dAtA, i, uint64((uint64(m.Field8)<<1)^uint64((m.Field8>>63)))) return i, nil } func (m *SampleOneOf_Field9) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x4d i++ i = encodeFixed32One(dAtA, i, uint32(m.Field9)) return i, nil } func (m *SampleOneOf_Field10) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x55 i++ i = encodeFixed32One(dAtA, i, uint32(m.Field10)) return i, nil } func (m *SampleOneOf_Field11) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x59 i++ i = encodeFixed64One(dAtA, i, uint64(m.Field11)) return i, nil } func (m *SampleOneOf_Field12) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x61 i++ i = encodeFixed64One(dAtA, i, uint64(m.Field12)) return i, nil } func (m *SampleOneOf_Field13) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x68 i++ if m.Field13 { dAtA[i] = 1 } else { dAtA[i] = 0 } i++ return i, nil } func (m *SampleOneOf_Field14) MarshalTo(dAtA []byte) (int, error) { i := 0 dAtA[i] = 0x72 i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field14))) i += copy(dAtA[i:], m.Field14) return i, nil } func (m *SampleOneOf_Field15) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.Field15 != nil { dAtA[i] = 0x7a i++ i = encodeVarintOne(dAtA, i, uint64(len(m.Field15))) i += copy(dAtA[i:], m.Field15) } return i, nil } func (m *SampleOneOf_SubMessage) MarshalTo(dAtA []byte) (int, error) { i := 0 if m.SubMessage != nil { dAtA[i] = 0x82 i++ dAtA[i] = 0x1 i++ i = encodeVarintOne(dAtA, i, uint64(m.SubMessage.Size())) n2, err := m.SubMessage.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 } return i, nil } func encodeFixed64One(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) dAtA[offset+4] = uint8(v >> 32) dAtA[offset+5] = uint8(v >> 40) dAtA[offset+6] = uint8(v >> 48) dAtA[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32One(dAtA []byte, offset int, v uint32) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintOne(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func NewPopulatedSubby(r randyOne, easy bool) *Subby { this := &Subby{} this.Sub = string(randStringOne(r)) if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedSampleOneOf(r randyOne, easy bool) *SampleOneOf { this := &SampleOneOf{} oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)] switch oneofNumber_TestOneof { case 1: this.TestOneof = NewPopulatedSampleOneOf_Field1(r, easy) case 2: this.TestOneof = NewPopulatedSampleOneOf_Field2(r, easy) case 3: this.TestOneof = NewPopulatedSampleOneOf_Field3(r, easy) case 4: this.TestOneof = NewPopulatedSampleOneOf_Field4(r, easy) case 5: this.TestOneof = NewPopulatedSampleOneOf_Field5(r, easy) case 6: this.TestOneof = NewPopulatedSampleOneOf_Field6(r, easy) case 7: this.TestOneof = NewPopulatedSampleOneOf_Field7(r, easy) case 8: this.TestOneof = NewPopulatedSampleOneOf_Field8(r, easy) case 9: this.TestOneof = NewPopulatedSampleOneOf_Field9(r, easy) case 10: this.TestOneof = NewPopulatedSampleOneOf_Field10(r, easy) case 11: this.TestOneof = NewPopulatedSampleOneOf_Field11(r, easy) case 12: this.TestOneof = NewPopulatedSampleOneOf_Field12(r, easy) case 13: this.TestOneof = NewPopulatedSampleOneOf_Field13(r, easy) case 14: this.TestOneof = NewPopulatedSampleOneOf_Field14(r, easy) case 15: this.TestOneof = NewPopulatedSampleOneOf_Field15(r, easy) case 16: this.TestOneof = NewPopulatedSampleOneOf_SubMessage(r, easy) } if !easy && r.Intn(10) != 0 { } return this } func NewPopulatedSampleOneOf_Field1(r randyOne, easy bool) *SampleOneOf_Field1 { this := &SampleOneOf_Field1{} this.Field1 = float64(r.Float64()) if r.Intn(2) == 0 { this.Field1 *= -1 } return this } func NewPopulatedSampleOneOf_Field2(r randyOne, easy bool) *SampleOneOf_Field2 { this := &SampleOneOf_Field2{} this.Field2 = float32(r.Float32()) if r.Intn(2) == 0 { this.Field2 *= -1 } return this } func NewPopulatedSampleOneOf_Field3(r randyOne, easy bool) *SampleOneOf_Field3 { this := &SampleOneOf_Field3{} this.Field3 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field3 *= -1 } return this } func NewPopulatedSampleOneOf_Field4(r randyOne, easy bool) *SampleOneOf_Field4 { this := &SampleOneOf_Field4{} this.Field4 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field4 *= -1 } return this } func NewPopulatedSampleOneOf_Field5(r randyOne, easy bool) *SampleOneOf_Field5 { this := &SampleOneOf_Field5{} this.Field5 = uint32(r.Uint32()) return this } func NewPopulatedSampleOneOf_Field6(r randyOne, easy bool) *SampleOneOf_Field6 { this := &SampleOneOf_Field6{} this.Field6 = uint64(uint64(r.Uint32())) return this } func NewPopulatedSampleOneOf_Field7(r randyOne, easy bool) *SampleOneOf_Field7 { this := &SampleOneOf_Field7{} this.Field7 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field7 *= -1 } return this } func NewPopulatedSampleOneOf_Field8(r randyOne, easy bool) *SampleOneOf_Field8 { this := &SampleOneOf_Field8{} this.Field8 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field8 *= -1 } return this } func NewPopulatedSampleOneOf_Field9(r randyOne, easy bool) *SampleOneOf_Field9 { this := &SampleOneOf_Field9{} this.Field9 = uint32(r.Uint32()) return this } func NewPopulatedSampleOneOf_Field10(r randyOne, easy bool) *SampleOneOf_Field10 { this := &SampleOneOf_Field10{} this.Field10 = int32(r.Int31()) if r.Intn(2) == 0 { this.Field10 *= -1 } return this } func NewPopulatedSampleOneOf_Field11(r randyOne, easy bool) *SampleOneOf_Field11 { this := &SampleOneOf_Field11{} this.Field11 = uint64(uint64(r.Uint32())) return this } func NewPopulatedSampleOneOf_Field12(r randyOne, easy bool) *SampleOneOf_Field12 { this := &SampleOneOf_Field12{} this.Field12 = int64(r.Int63()) if r.Intn(2) == 0 { this.Field12 *= -1 } return this } func NewPopulatedSampleOneOf_Field13(r randyOne, easy bool) *SampleOneOf_Field13 { this := &SampleOneOf_Field13{} this.Field13 = bool(bool(r.Intn(2) == 0)) return this } func NewPopulatedSampleOneOf_Field14(r randyOne, easy bool) *SampleOneOf_Field14 { this := &SampleOneOf_Field14{} this.Field14 = string(randStringOne(r)) return this } func NewPopulatedSampleOneOf_Field15(r randyOne, easy bool) *SampleOneOf_Field15 { this := &SampleOneOf_Field15{} v1 := r.Intn(100) this.Field15 = make([]byte, v1) for i := 0; i < v1; i++ { this.Field15[i] = byte(r.Intn(256)) } return this } func NewPopulatedSampleOneOf_SubMessage(r randyOne, easy bool) *SampleOneOf_SubMessage { this := &SampleOneOf_SubMessage{} this.SubMessage = NewPopulatedSubby(r, easy) return this } type randyOne interface { Float32() float32 Float64() float64 Int63() int64 Int31() int32 Uint32() uint32 Intn(n int) int } func randUTF8RuneOne(r randyOne) rune { ru := r.Intn(62) if ru < 10 { return rune(ru + 48) } else if ru < 36 { return rune(ru + 55) } return rune(ru + 61) } func randStringOne(r randyOne) string { v2 := r.Intn(100) tmps := make([]rune, v2) for i := 0; i < v2; i++ { tmps[i] = randUTF8RuneOne(r) } return string(tmps) } func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) { l := r.Intn(5) for i := 0; i < l; i++ { wire := r.Intn(4) if wire == 3 { wire = 5 } fieldNumber := maxFieldNumber + r.Intn(100) dAtA = randFieldOne(dAtA, r, fieldNumber, wire) } return dAtA } func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte { key := uint32(fieldNumber)<<3 | uint32(wire) switch wire { case 0: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) v3 := r.Int63() if r.Intn(2) == 0 { v3 *= -1 } dAtA = encodeVarintPopulateOne(dAtA, uint64(v3)) case 1: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) case 2: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) ll := r.Intn(100) dAtA = encodeVarintPopulateOne(dAtA, uint64(ll)) for j := 0; j < ll; j++ { dAtA = append(dAtA, byte(r.Intn(256))) } default: dAtA = encodeVarintPopulateOne(dAtA, uint64(key)) dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) } return dAtA } func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte { for v >= 1<<7 { dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80)) v >>= 7 } dAtA = append(dAtA, uint8(v)) return dAtA } func (m *Subby) Size() (n int) { var l int _ = l l = len(m.Sub) if l > 0 { n += 1 + l + sovOne(uint64(l)) } return n } func (m *SampleOneOf) Size() (n int) { var l int _ = l if m.TestOneof != nil { n += m.TestOneof.Size() } return n } func (m *SampleOneOf_Field1) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field2) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field3) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field3)) return n } func (m *SampleOneOf_Field4) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field4)) return n } func (m *SampleOneOf_Field5) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field5)) return n } func (m *SampleOneOf_Field6) Size() (n int) { var l int _ = l n += 1 + sovOne(uint64(m.Field6)) return n } func (m *SampleOneOf_Field7) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field7)) return n } func (m *SampleOneOf_Field8) Size() (n int) { var l int _ = l n += 1 + sozOne(uint64(m.Field8)) return n } func (m *SampleOneOf_Field9) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field10) Size() (n int) { var l int _ = l n += 5 return n } func (m *SampleOneOf_Field11) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field12) Size() (n int) { var l int _ = l n += 9 return n } func (m *SampleOneOf_Field13) Size() (n int) { var l int _ = l n += 2 return n } func (m *SampleOneOf_Field14) Size() (n int) { var l int _ = l l = len(m.Field14) n += 1 + l + sovOne(uint64(l)) return n } func (m *SampleOneOf_Field15) Size() (n int) { var l int _ = l if m.Field15 != nil { l = len(m.Field15) n += 1 + l + sovOne(uint64(l)) } return n } func (m *SampleOneOf_SubMessage) Size() (n int) { var l int _ = l if m.SubMessage != nil { l = m.SubMessage.Size() n += 2 + l + sovOne(uint64(l)) } return n } func sovOne(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozOne(x uint64) (n int) { return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (this *Subby) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&Subby{`, `Sub:` + fmt.Sprintf("%v", this.Sub) + `,`, `}`, }, "") return s } func (this *SampleOneOf) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf{`, `TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field1) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field1{`, `Field1:` + fmt.Sprintf("%v", this.Field1) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field2) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field2{`, `Field2:` + fmt.Sprintf("%v", this.Field2) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field3) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field3{`, `Field3:` + fmt.Sprintf("%v", this.Field3) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field4) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field4{`, `Field4:` + fmt.Sprintf("%v", this.Field4) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field5) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field5{`, `Field5:` + fmt.Sprintf("%v", this.Field5) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field6) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field6{`, `Field6:` + fmt.Sprintf("%v", this.Field6) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field7) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field7{`, `Field7:` + fmt.Sprintf("%v", this.Field7) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field8) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field8{`, `Field8:` + fmt.Sprintf("%v", this.Field8) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field9) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field9{`, `Field9:` + fmt.Sprintf("%v", this.Field9) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field10) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field10{`, `Field10:` + fmt.Sprintf("%v", this.Field10) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field11) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field11{`, `Field11:` + fmt.Sprintf("%v", this.Field11) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field12) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field12{`, `Field12:` + fmt.Sprintf("%v", this.Field12) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field13) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field13{`, `Field13:` + fmt.Sprintf("%v", this.Field13) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field14) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field14{`, `Field14:` + fmt.Sprintf("%v", this.Field14) + `,`, `}`, }, "") return s } func (this *SampleOneOf_Field15) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_Field15{`, `Field15:` + fmt.Sprintf("%v", this.Field15) + `,`, `}`, }, "") return s } func (this *SampleOneOf_SubMessage) String() string { if this == nil { return "nil" } s := strings.Join([]string{`&SampleOneOf_SubMessage{`, `SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`, `}`, }, "") return s } func valueToStringOne(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("*%v", pv) } func (m *Subby) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Subby: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Sub = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOne(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func (m *SampleOneOf) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: SampleOneOf: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: SampleOneOf: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = uint64(dAtA[iNdEx-8]) v |= uint64(dAtA[iNdEx-7]) << 8 v |= uint64(dAtA[iNdEx-6]) << 16 v |= uint64(dAtA[iNdEx-5]) << 24 v |= uint64(dAtA[iNdEx-4]) << 32 v |= uint64(dAtA[iNdEx-3]) << 40 v |= uint64(dAtA[iNdEx-2]) << 48 v |= uint64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field1{float64(math.Float64frombits(v))} case 2: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType) } var v uint32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = uint32(dAtA[iNdEx-4]) v |= uint32(dAtA[iNdEx-3]) << 8 v |= uint32(dAtA[iNdEx-2]) << 16 v |= uint32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field2{float32(math.Float32frombits(v))} case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field3{v} case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field4", wireType) } var v int64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field4{v} case 5: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field5", wireType) } var v uint32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint32(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field5{v} case 6: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field6", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } m.TestOneof = &SampleOneOf_Field6{v} case 7: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field7", wireType) } var v int32 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } v = int32((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31)) m.TestOneof = &SampleOneOf_Field7{v} case 8: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field8", wireType) } var v uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63) m.TestOneof = &SampleOneOf_Field8{int64(v)} case 9: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field9", wireType) } var v uint32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = uint32(dAtA[iNdEx-4]) v |= uint32(dAtA[iNdEx-3]) << 8 v |= uint32(dAtA[iNdEx-2]) << 16 v |= uint32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field9{v} case 10: if wireType != 5 { return fmt.Errorf("proto: wrong wireType = %d for field Field10", wireType) } var v int32 if (iNdEx + 4) > l { return io.ErrUnexpectedEOF } iNdEx += 4 v = int32(dAtA[iNdEx-4]) v |= int32(dAtA[iNdEx-3]) << 8 v |= int32(dAtA[iNdEx-2]) << 16 v |= int32(dAtA[iNdEx-1]) << 24 m.TestOneof = &SampleOneOf_Field10{v} case 11: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field11", wireType) } var v uint64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = uint64(dAtA[iNdEx-8]) v |= uint64(dAtA[iNdEx-7]) << 8 v |= uint64(dAtA[iNdEx-6]) << 16 v |= uint64(dAtA[iNdEx-5]) << 24 v |= uint64(dAtA[iNdEx-4]) << 32 v |= uint64(dAtA[iNdEx-3]) << 40 v |= uint64(dAtA[iNdEx-2]) << 48 v |= uint64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field11{v} case 12: if wireType != 1 { return fmt.Errorf("proto: wrong wireType = %d for field Field12", wireType) } var v int64 if (iNdEx + 8) > l { return io.ErrUnexpectedEOF } iNdEx += 8 v = int64(dAtA[iNdEx-8]) v |= int64(dAtA[iNdEx-7]) << 8 v |= int64(dAtA[iNdEx-6]) << 16 v |= int64(dAtA[iNdEx-5]) << 24 v |= int64(dAtA[iNdEx-4]) << 32 v |= int64(dAtA[iNdEx-3]) << 40 v |= int64(dAtA[iNdEx-2]) << 48 v |= int64(dAtA[iNdEx-1]) << 56 m.TestOneof = &SampleOneOf_Field12{v} case 13: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Field13", wireType) } var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ v |= (int(b) & 0x7F) << shift if b < 0x80 { break } } b := bool(v != 0) m.TestOneof = &SampleOneOf_Field13{b} case 14: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field14", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.TestOneof = &SampleOneOf_Field14{string(dAtA[iNdEx:postIndex])} iNdEx = postIndex case 15: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Field15", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ byteLen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if byteLen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + byteLen if postIndex > l { return io.ErrUnexpectedEOF } v := make([]byte, postIndex-iNdEx) copy(v, dAtA[iNdEx:postIndex]) m.TestOneof = &SampleOneOf_Field15{v} iNdEx = postIndex case 16: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field SubMessage", wireType) } var msglen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowOne } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ msglen |= (int(b) & 0x7F) << shift if b < 0x80 { break } } if msglen < 0 { return ErrInvalidLengthOne } postIndex := iNdEx + msglen if postIndex > l { return io.ErrUnexpectedEOF } v := &Subby{} if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } m.TestOneof = &SampleOneOf_SubMessage{v} iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipOne(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthOne } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipOne(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthOne } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowOne } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipOne(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthOne = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowOne = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("combos/both/one.proto", fileDescriptorOne) } var fileDescriptorOne = []byte{ // 404 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0xd2, 0xbf, 0x4f, 0x1b, 0x31, 0x14, 0x07, 0x70, 0x3f, 0x8e, 0x24, 0xe0, 0x84, 0x92, 0x9e, 0x54, 0xe9, 0x95, 0xe1, 0xc9, 0x62, 0xf2, 0x42, 0xd2, 0xdc, 0x25, 0xfc, 0x58, 0x51, 0x55, 0x65, 0xa9, 0x90, 0xc2, 0x1f, 0x80, 0x30, 0x75, 0x0e, 0x24, 0xee, 0x8c, 0x7a, 0x77, 0x43, 0x37, 0xfe, 0x9c, 0x8e, 0x1d, 0xfb, 0x27, 0x30, 0x32, 0x76, 0xe8, 0xc0, 0xb9, 0x4b, 0x47, 0x46, 0xc6, 0x2a, 0x97, 0xf2, 0xbc, 0xbd, 0xaf, 0x3f, 0xf6, 0x60, 0xfb, 0x2b, 0xdf, 0x5d, 0xb9, 0xdc, 0xb8, 0x72, 0x6c, 0x5c, 0x75, 0x3d, 0x76, 0x85, 0x1d, 0xdd, 0x7d, 0x75, 0x95, 0x8b, 0x23, 0x57, 0xd8, 0xbd, 0x83, 0xec, 0xa6, 0xba, 0xae, 0xcd, 0xe8, 0xca, 0xe5, 0xe3, 0xcc, 0x65, 0x6e, 0xdc, 0x9a, 0xa9, 0x97, 0x6d, 0x6a, 0x43, 0x3b, 0xad, 0xcf, 0xec, 0xbf, 0x97, 0x9d, 0xf3, 0xda, 0x98, 0x6f, 0xf1, 0x50, 0x46, 0x65, 0x6d, 0x10, 0x14, 0xe8, 0xed, 0xc5, 0x6a, 0xdc, 0xff, 0x1d, 0xc9, 0xfe, 0xf9, 0x65, 0x7e, 0x77, 0x6b, 0xcf, 0x0a, 0x7b, 0xb6, 0x8c, 0x51, 0x76, 0x3f, 0xdd, 0xd8, 0xdb, 0x2f, 0x93, 0x76, 0x13, 0xcc, 0xc5, 0xe2, 0x7f, 0x66, 0x49, 0x70, 0x43, 0x81, 0xde, 0x60, 0x49, 0x58, 0x52, 0x8c, 0x14, 0xe8, 0x0e, 0x4b, 0xca, 0x32, 0xc5, 0x4d, 0x05, 0x3a, 0x62, 0x99, 0xb2, 0xcc, 0xb0, 0xa3, 0x40, 0xef, 0xb0, 0xcc, 0x58, 0x0e, 0xb1, 0xab, 0x40, 0x6f, 0xb2, 0x1c, 0xb2, 0x1c, 0x61, 0x4f, 0x81, 0x7e, 0xcb, 0x72, 0xc4, 0x72, 0x8c, 0x5b, 0x0a, 0x74, 0xcc, 0x72, 0xcc, 0x72, 0x82, 0xdb, 0x0a, 0x74, 0x8f, 0xe5, 0x24, 0xde, 0x93, 0xbd, 0xf5, 0xcd, 0x3e, 0xa0, 0x54, 0xa0, 0x77, 0xe7, 0x62, 0xf1, 0xba, 0x10, 0x6c, 0x82, 0x7d, 0x05, 0xba, 0x1b, 0x6c, 0x12, 0x2c, 0xc1, 0x81, 0x02, 0x3d, 0x0c, 0x96, 0x04, 0x4b, 0x71, 0x47, 0x81, 0xde, 0x0a, 0x96, 0x06, 0x9b, 0xe2, 0x9b, 0xd5, 0xfb, 0x07, 0x9b, 0x06, 0x9b, 0xe1, 0xae, 0x02, 0x3d, 0x08, 0x36, 0x8b, 0x0f, 0x64, 0xbf, 0xac, 0xcd, 0x45, 0x6e, 0xcb, 0xf2, 0x32, 0xb3, 0x38, 0x54, 0xa0, 0xfb, 0x89, 0x1c, 0xad, 0x1a, 0xd1, 0x7e, 0xea, 0x5c, 0x2c, 0x64, 0x59, 0x9b, 0xcf, 0x6b, 0x3f, 0x1d, 0x48, 0x59, 0xd9, 0xb2, 0xba, 0x70, 0x85, 0x75, 0xcb, 0xd3, 0x8f, 0x0f, 0x0d, 0x89, 0xc7, 0x86, 0xc4, 0xaf, 0x86, 0xc4, 0x53, 0x43, 0xf0, 0xdc, 0x10, 0xbc, 0x34, 0x04, 0xf7, 0x9e, 0xe0, 0xbb, 0x27, 0xf8, 0xe1, 0x09, 0x7e, 0x7a, 0x82, 0x07, 0x4f, 0xf0, 0xe8, 0x09, 0x9e, 0x3c, 0xc1, 0x5f, 0x4f, 0xe2, 0xd9, 0x13, 0xbc, 0x78, 0x12, 0xf7, 0x7f, 0x48, 0x98, 0x6e, 0x5b, 0xa3, 0xf4, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x42, 0xd6, 0x88, 0x93, 0x02, 0x00, 0x00, }
mit
visi0nary/P8000-Kernel
drivers/misc/mediatek/mach/mt6735/include/mach/camera_isp_D2.h
21235
/* * Copyright (C) 2011-2014 MediaTek 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. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. * If not, see <http://www.gnu.org/licenses/>. */ #ifndef _MT_ISP_H #define _MT_ISP_H #include <linux/ioctl.h> #ifdef CONFIG_COMPAT //64 bit #include <linux/fs.h> #include <linux/compat.h> #endif //89serial IC , for HW FBC #define _89SERIAL_ /******************************************************************************* * ********************************************************************************/ #define ISP_DEV_MAJOR_NUMBER 251 #define ISP_MAGIC 'k' /******************************************************************************* * ********************************************************************************/ //CAM_CTL_INT_STATUS #define ISP_IRQ_INT_STATUS_VS1_ST ((unsigned int)1 << 0) #define ISP_IRQ_INT_STATUS_TG1_ST1 ((unsigned int)1 << 1) #define ISP_IRQ_INT_STATUS_TG1_ST2 ((unsigned int)1 << 2) #define ISP_IRQ_INT_STATUS_EXPDON1_ST ((unsigned int)1 << 3) #define ISP_IRQ_INT_STATUS_TG1_ERR_ST ((unsigned int)1 << 4) #define ISP_IRQ_INT_STATUS_PASS1_TG1_DON_ST ((unsigned int)1 << 10) #define ISP_IRQ_INT_STATUS_SOF1_INT_ST ((unsigned int)1 << 12) #define ISP_IRQ_INT_STATUS_CQ_ERR_ST ((unsigned int)1 << 13) #define ISP_IRQ_INT_STATUS_PASS2_DON_ST ((unsigned int)1 << 14) #define ISP_IRQ_INT_STATUS_TPIPE_DON_ST ((unsigned int)1 << 15) #define ISP_IRQ_INT_STATUS_AF_DON_ST ((unsigned int)1 << 16) #define ISP_IRQ_INT_STATUS_FLK_DON_ST ((unsigned int)1 << 17) #define ISP_IRQ_INT_STATUS_CQ_DON_ST ((unsigned int)1 << 19) #define ISP_IRQ_INT_STATUS_IMGO_ERR_ST ((unsigned int)1 << 20) #define ISP_IRQ_INT_STATUS_AAO_ERR_ST ((unsigned int)1 << 21) #define ISP_IRQ_INT_STATUS_IMG2O_ERR_ST ((unsigned int)1 << 23) #define ISP_IRQ_INT_STATUS_ESFKO_ERR_ST ((unsigned int)1 << 24) #define ISP_IRQ_INT_STATUS_FLK_ERR_ST ((unsigned int)1 << 25) #define ISP_IRQ_INT_STATUS_LSC_ERR_ST ((unsigned int)1 << 26) #define ISP_IRQ_INT_STATUS_FBC_IMGO_DONE_ST ((unsigned int)1 << 28) #define ISP_IRQ_INT_STATUS_DMA_ERR_ST ((unsigned int)1 << 30) //CAM_CTL_DMA_INT #define ISP_IRQ_DMA_INT_IMGO_DONE_ST ((unsigned int)1 << 0) #define ISP_IRQ_DMA_INT_IMG2O_DONE_ST ((unsigned int)1 << 1) #define ISP_IRQ_DMA_INT_AAO_DONE_ST ((unsigned int)1 << 2) //#define ISP_IRQ_DMA_INT_LCSO_DONE_ST ((unsigned int)1 << 3) #define ISP_IRQ_DMA_INT_ESFKO_DONE_ST ((unsigned int)1 << 4) //#define ISP_IRQ_DMA_INT_DISPO_DONE_ST ((unsigned int)1 << 5) //#define ISP_IRQ_DMA_INT_VIDO_DONE_ST ((unsigned int)1 << 6) //#define ISP_IRQ_DMA_INT_VRZO_DONE_ST ((unsigned int)1 << 7) #define ISP_IRQ_DMA_INT_CQ0_ERR_ST ((unsigned int)1 << 8) #define ISP_IRQ_DMA_INT_CQ0_DONE_ST ((unsigned int)1 << 9) //#define ISP_IRQ_DMA_INT_SOF2_INT_ST ((unsigned int)1 << 10) //#define ISP_IRQ_DMA_INT_BUF_OVL_ST ((unsigned int)1 << 11) #define ISP_IRQ_DMA_INT_TG1_GBERR_ST ((unsigned int)1 << 12) //#define ISP_IRQ_DMA_INT_TG2_GBERR_ST ((unsigned int)1 << 13) #define ISP_IRQ_DMA_INT_CQ0C_DONE_ST ((unsigned int)1 << 14) #define ISP_IRQ_DMA_INT_CQ0B_DONE_ST ((unsigned int)1 << 15) //CAM_CTL_INTB_STATUS #define ISP_IRQ_INTB_STATUS_CQ_ERR_ST ((unsigned int)1 << 13) #define ISP_IRQ_INTB_STATUS_PASS2_DON_ST ((unsigned int)1 << 14) #define ISP_IRQ_INTB_STATUS_TPIPE_DON_ST ((unsigned int)1 << 15) #define ISP_IRQ_INTB_STATUS_CQ_DON_ST ((unsigned int)1 << 19) #define ISP_IRQ_INTB_STATUS_IMGO_ERR_ST ((unsigned int)1 << 20) #define ISP_IRQ_INTB_STATUS_LCSO_ERR_ST ((unsigned int)1 << 22) #define ISP_IRQ_INTB_STATUS_IMG2O_ERR_ST ((unsigned int)1 << 23) #define ISP_IRQ_INTB_STATUS_LSC_ERR_ST ((unsigned int)1 << 26) #define ISP_IRQ_INTB_STATUS_BPC_ERR_ST ((unsigned int)1 << 28) #define ISP_IRQ_INTB_STATUS_LCE_ERR_ST ((unsigned int)1 << 29) #define ISP_IRQ_INTB_STATUS_DMA_ERR_ST ((unsigned int)1 << 30) #define ISP_IRQ_INTB_STATUS_INT_WCLR_ST ((unsigned int)1 << 31) //CAM_CTL_DMAB_INT #define ISP_IRQ_DMAB_INT_IMGO_DONE_ST ((unsigned int)1 << 0) #define ISP_IRQ_DMAB_INT_IMG2O_DONE_ST ((unsigned int)1 << 1) #define ISP_IRQ_DMAB_INT_AAO_DONE_ST ((unsigned int)1 << 2) #define ISP_IRQ_DMAB_INT_LCSO_DONE_ST ((unsigned int)1 << 3) #define ISP_IRQ_DMAB_INT_ESFKO_DONE_ST ((unsigned int)1 << 4) #define ISP_IRQ_DMAB_INT_DISPO_DONE_ST ((unsigned int)1 << 5) #define ISP_IRQ_DMAB_INT_VIDO_DONE_ST ((unsigned int)1 << 6) //#define ISP_IRQ_DMAB_INT_VRZO_DONE_ST ((unsigned int)1 << 7) //#define ISP_IRQ_DMAB_INT_NR3O_DONE_ST ((unsigned int)1 << 8) //#define ISP_IRQ_DMAB_INT_NR3O_ERR_ST ((unsigned int)1 << 9) //CAM_CTL_INTC_STATUS #define ISP_IRQ_INTC_STATUS_CQ_ERR_ST ((unsigned int)1 << 13) #define ISP_IRQ_INTC_STATUS_PASS2_DON_ST ((unsigned int)1 << 14) #define ISP_IRQ_INTC_STATUS_TPIPE_DON_ST ((unsigned int)1 << 15) #define ISP_IRQ_INTC_STATUS_CQ_DON_ST ((unsigned int)1 << 19) #define ISP_IRQ_INTC_STATUS_IMGO_ERR_ST ((unsigned int)1 << 20) #define ISP_IRQ_INTC_STATUS_LCSO_ERR_ST ((unsigned int)1 << 22) #define ISP_IRQ_INTC_STATUS_IMG2O_ERR_ST ((unsigned int)1 << 23) #define ISP_IRQ_INTC_STATUS_LSC_ERR_ST ((unsigned int)1 << 26) #define ISP_IRQ_INTC_STATUS_BPC_ERR_ST ((unsigned int)1 << 28) #define ISP_IRQ_INTC_STATUS_LCE_ERR_ST ((unsigned int)1 << 29) #define ISP_IRQ_INTC_STATUS_DMA_ERR_ST ((unsigned int)1 << 30) //CAM_CTL_DMAC_INT #define ISP_IRQ_DMAC_INT_IMGO_DONE_ST ((unsigned int)1 << 0) #define ISP_IRQ_DMAC_INT_IMG2O_DONE_ST ((unsigned int)1 << 1) #define ISP_IRQ_DMAC_INT_AAO_DONE_ST ((unsigned int)1 << 2) #define ISP_IRQ_DMAC_INT_LCSO_DONE_ST ((unsigned int)1 << 3) #define ISP_IRQ_DMAC_INT_ESFKO_DONE_ST ((unsigned int)1 << 4) #define ISP_IRQ_DMAC_INT_DISPO_DONE_ST ((unsigned int)1 << 5) #define ISP_IRQ_DMAC_INT_VIDO_DONE_ST ((unsigned int)1 << 6) //#define ISP_IRQ_DMAC_INT_VRZO_DONE_ST ((unsigned int)1 << 7) //#define ISP_IRQ_DMAC_INT_NR3O_DONE_ST ((unsigned int)1 << 8) //#define ISP_IRQ_DMAC_INT_NR3O_ERR_ST ((unsigned int)1 << 9) //CAM_CTL_INT_STATUSX #define ISP_IRQ_INTX_STATUS_VS1_ST ((unsigned int)1 << 0) #define ISP_IRQ_INTX_STATUS_TG1_ST1 ((unsigned int)1 << 1) #define ISP_IRQ_INTX_STATUS_TG1_ST2 ((unsigned int)1 << 2) #define ISP_IRQ_INTX_STATUS_EXPDON1_ST ((unsigned int)1 << 3) #define ISP_IRQ_INTX_STATUS_TG1_ERR_ST ((unsigned int)1 << 4) #define ISP_IRQ_INTX_STATUS_VS2_ST ((unsigned int)1 << 5) #define ISP_IRQ_INTX_STATUS_TG2_ST1 ((unsigned int)1 << 6) #define ISP_IRQ_INTX_STATUS_TG2_ST2 ((unsigned int)1 << 7) #define ISP_IRQ_INTX_STATUS_EXPDON2_ST ((unsigned int)1 << 8) #define ISP_IRQ_INTX_STATUS_TG2_ERR_ST ((unsigned int)1 << 9) #define ISP_IRQ_INTX_STATUS_PASS1_TG1_DON_ST ((unsigned int)1 << 10) #define ISP_IRQ_INTX_STATUS_PASS1_TG2_DON_ST ((unsigned int)1 << 11) //#define ISP_IRQ_INTX_STATUS_VEC_DON_ST ((unsigned int)1 << 12) #define ISP_IRQ_INTX_STATUS_CQ_ERR_ST ((unsigned int)1 << 13) #define ISP_IRQ_INTX_STATUS_PASS2_DON_ST ((unsigned int)1 << 14) #define ISP_IRQ_INTX_STATUS_TPIPE_DON_ST ((unsigned int)1 << 15) #define ISP_IRQ_INTX_STATUS_AF_DON_ST ((unsigned int)1 << 16) #define ISP_IRQ_INTX_STATUS_FLK_DON_ST ((unsigned int)1 << 17) #define ISP_IRQ_INTX_STATUS_FMT_DON_ST ((unsigned int)1 << 18) #define ISP_IRQ_INTX_STATUS_CQ_DON_ST ((unsigned int)1 << 19) #define ISP_IRQ_INTX_STATUS_IMGO_ERR_ST ((unsigned int)1 << 20) #define ISP_IRQ_INTX_STATUS_AAO_ERR_ST ((unsigned int)1 << 21) #define ISP_IRQ_INTX_STATUS_LCSO_ERR_ST ((unsigned int)1 << 22) #define ISP_IRQ_INTX_STATUS_IMG2O_ERR_ST ((unsigned int)1 << 23) #define ISP_IRQ_INTX_STATUS_ESFKO_ERR_ST ((unsigned int)1 << 24) #define ISP_IRQ_INTX_STATUS_FLK_ERR_ST ((unsigned int)1 << 25) #define ISP_IRQ_INTX_STATUS_LSC_ERR_ST ((unsigned int)1 << 26) //#define ISP_IRQ_INTX_STATUS_LSC2_ERR_ST ((unsigned int)1 << 27) #define ISP_IRQ_INTX_STATUS_BPC_ERR_ST ((unsigned int)1 << 28) #define ISP_IRQ_INTX_STATUS_LCE_ERR_ST ((unsigned int)1 << 29) #define ISP_IRQ_INTX_STATUS_DMA_ERR_ST ((unsigned int)1 << 30) //CAM_CTL_DMA_INTX #define ISP_IRQ_DMAX_INT_IMGO_DONE_ST ((unsigned int)1 << 0) #define ISP_IRQ_DMAX_INT_IMG2O_DONE_ST ((unsigned int)1 << 1) #define ISP_IRQ_DMAX_INT_AAO_DONE_ST ((unsigned int)1 << 2) #define ISP_IRQ_DMAX_INT_LCSO_DONE_ST ((unsigned int)1 << 3) #define ISP_IRQ_DMAX_INT_ESFKO_DONE_ST ((unsigned int)1 << 4) #define ISP_IRQ_DMAX_INT_DISPO_DONE_ST ((unsigned int)1 << 5) #define ISP_IRQ_DMAX_INT_VIDO_DONE_ST ((unsigned int)1 << 6) #define ISP_IRQ_DMAX_INT_VRZO_DONE_ST ((unsigned int)1 << 7) #define ISP_IRQ_DMAX_INT_NR3O_DONE_ST ((unsigned int)1 << 8) #define ISP_IRQ_DMAX_INT_NR3O_ERR_ST ((unsigned int)1 << 9) #define ISP_IRQ_DMAX_INT_CQ_ERR_ST ((unsigned int)1 << 10) #define ISP_IRQ_DMAX_INT_BUF_OVL_ST ((unsigned int)1 << 11) #define ISP_IRQ_DMAX_INT_TG1_GBERR_ST ((unsigned int)1 << 12) #define ISP_IRQ_DMAX_INT_TG2_GBERR_ST ((unsigned int)1 << 13) /******************************************************************************* * ********************************************************************************/ typedef enum { ISP_IRQ_CLEAR_NONE, ISP_IRQ_CLEAR_WAIT, ISP_IRQ_CLEAR_ALL }ISP_IRQ_CLEAR_ENUM; typedef enum { ISP_IRQ_TYPE_INT, ISP_IRQ_TYPE_DMA, ISP_IRQ_TYPE_INTB, ISP_IRQ_TYPE_DMAB, ISP_IRQ_TYPE_INTC, ISP_IRQ_TYPE_DMAC, ISP_IRQ_TYPE_INTX, ISP_IRQ_TYPE_DMAX, ISP_IRQ_TYPE_AMOUNT }ISP_IRQ_TYPE_ENUM; typedef struct { ISP_IRQ_CLEAR_ENUM Clear; ISP_IRQ_TYPE_ENUM Type; unsigned int Status; unsigned int Timeout; }ISP_WAIT_IRQ_STRUCT; typedef struct { ISP_IRQ_TYPE_ENUM Type; unsigned int Status; }ISP_READ_IRQ_STRUCT; typedef struct { ISP_IRQ_TYPE_ENUM Type; unsigned int Status; }ISP_CLEAR_IRQ_STRUCT; typedef enum { ISP_HOLD_TIME_VD, ISP_HOLD_TIME_EXPDONE }ISP_HOLD_TIME_ENUM; typedef struct { unsigned int Addr; // register's addr unsigned int Val; // register's value }ISP_REG_STRUCT; typedef struct { //unsigned int Data; // pointer to ISP_REG_STRUCT ISP_REG_STRUCT *pData; // pointer to ISP_REG_STRUCT unsigned int Count; // count }ISP_REG_IO_STRUCT; typedef void (*pIspCallback)(void); typedef enum { //Work queue. It is interruptible, so there can be "Sleep" in work queue function. ISP_CALLBACK_WORKQUEUE_VD, ISP_CALLBACK_WORKQUEUE_EXPDONE, ISP_CALLBACK_WORKQUEUE_SENINF, //Tasklet. It is uninterrupted, so there can NOT be "Sleep" in tasklet function. ISP_CALLBACK_TASKLET_VD, ISP_CALLBACK_TASKLET_EXPDONE, ISP_CALLBACK_TASKLET_SENINF, ISP_CALLBACK_AMOUNT }ISP_CALLBACK_ENUM; typedef struct { ISP_CALLBACK_ENUM Type; pIspCallback Func; }ISP_CALLBACK_STRUCT; // // length of the two memory areas #define RT_BUF_TBL_NPAGES 16 #define ISP_RT_BUF_SIZE 16 //#define ISP_RT_CQ0C_BUF_SIZE (ISP_RT_BUF_SIZE>>2) #define ISP_RT_CQ0C_BUF_SIZE (6) //special for 6582 // typedef enum { _imgi_ = 0, _imgci_, // 1 _vipi_ , // 2 _vip2i_, // 3 _imgo_, // 4 _img2o_, // 5 _dispo_, // 6 _vido_, // 7 _fdo_, // 8 _lsci_, // 9 _lcei_, // 10 _rt_dma_max_ }_isp_dma_enum_; // typedef struct { unsigned int memID; unsigned int size; long long base_vAddr; unsigned int base_pAddr; unsigned int timeStampS; unsigned int timeStampUs; unsigned int bFilled; }ISP_RT_BUF_INFO_STRUCT; // typedef struct { unsigned int count; ISP_RT_BUF_INFO_STRUCT data[ISP_RT_BUF_SIZE]; }ISP_DEQUE_BUF_INFO_STRUCT; // typedef struct { unsigned int start; //current DMA accessing buffer unsigned int total_count; //total buffer number.Include Filled and empty unsigned int empty_count; //total empty buffer number include current DMA accessing buffer unsigned int pre_empty_count;//previous total empty buffer number include current DMA accessing buffer unsigned int active; ISP_RT_BUF_INFO_STRUCT data[ISP_RT_BUF_SIZE]; }ISP_RT_RING_BUF_INFO_STRUCT; // typedef enum { ISP_RT_BUF_CTRL_ENQUE, // 0 ISP_RT_BUF_CTRL_EXCHANGE_ENQUE, // 1 ISP_RT_BUF_CTRL_DEQUE, // 2 ISP_RT_BUF_CTRL_IS_RDY, // 3 ISP_RT_BUF_CTRL_GET_SIZE, // 4 ISP_RT_BUF_CTRL_CLEAR, // 5 ISP_RT_BUF_CTRL_MAX }ISP_RT_BUF_CTRL_ENUM; // typedef enum { ISP_RTBC_STATE_INIT, // 0 ISP_RTBC_STATE_SOF, ISP_RTBC_STATE_DONE, ISP_RTBC_STATE_MAX }ISP_RTBC_STATE_ENUM; // typedef enum { ISP_RTBC_BUF_EMPTY, // 0 ISP_RTBC_BUF_FILLED,// 1 ISP_RTBC_BUF_LOCKED,// 2 }ISP_RTBC_BUF_STATE_ENUM; // typedef struct { ISP_RTBC_STATE_ENUM state; unsigned long dropCnt; ISP_RT_RING_BUF_INFO_STRUCT ring_buf[_rt_dma_max_]; }ISP_RT_BUF_STRUCT; // typedef struct { ISP_RT_BUF_CTRL_ENUM ctrl; _isp_dma_enum_ buf_id; //unsigned int data_ptr; //unsigned int ex_data_ptr; //exchanged buffer ISP_RT_BUF_INFO_STRUCT *data_ptr; ISP_RT_BUF_INFO_STRUCT *ex_data_ptr; //exchanged buffer unsigned char *pExtend; }ISP_BUFFER_CTRL_STRUCT; // //reference count #define _use_kernel_ref_cnt_ // typedef enum { ISP_REF_CNT_GET, // 0 ISP_REF_CNT_INC, // 1 ISP_REF_CNT_DEC, // 2 ISP_REF_CNT_DEC_AND_RESET_IF_LAST_ONE, // 3 ISP_REF_CNT_MAX }ISP_REF_CNT_CTRL_ENUM; // typedef enum { ISP_REF_CNT_ID_IMEM, // 0 ISP_REF_CNT_ID_ISP_FUNC, // 1 ISP_REF_CNT_ID_GLOBAL_PIPE, // 2 ISP_REF_CNT_ID_MAX, }ISP_REF_CNT_ID_ENUM; // typedef struct { ISP_REF_CNT_CTRL_ENUM ctrl; ISP_REF_CNT_ID_ENUM id; signed int* data_ptr; }ISP_REF_CNT_CTRL_STRUCT; /******************************************************************************************** pass1 real time buffer control use cq0c ********************************************************************************************/ // #define _rtbc_use_cq0c_ #if defined(_rtbc_use_cq0c_) // typedef volatile union _CQ_RTBC_FBC_ { volatile struct { unsigned long FBC_CNT : 4; unsigned long DROP_INT_EN : 1; unsigned long rsv_5 : 6; unsigned long RCNT_INC : 1; unsigned long rsv_12 : 2; unsigned long FBC_EN : 1; unsigned long LOCK_EN : 1; unsigned long FB_NUM : 4; unsigned long RCNT : 4; unsigned long WCNT : 4; unsigned long DROP_CNT : 4; } Bits; unsigned long Reg_val; }CQ_RTBC_FBC; typedef struct _cq_cmd_st_ { unsigned int inst; unsigned int data_ptr_pa; }CQ_CMD_ST; /* typedef struct _cq_cmd_rtbc_st_ { CQ_CMD_ST imgo; CQ_CMD_ST img2o; CQ_CMD_ST cq0ci; CQ_CMD_ST end; }CQ_CMD_RTBC_ST; */ typedef struct _cq_info_rtbc_st_ { CQ_CMD_ST imgo; CQ_CMD_ST img2o; CQ_CMD_ST next_cq0ci; CQ_CMD_ST end; unsigned int imgo_base_pAddr; unsigned int img2o_base_pAddr; }CQ_INFO_RTBC_ST; typedef struct _cq_ring_cmd_st_ { CQ_INFO_RTBC_ST cq_rtbc; unsigned long next_pa; struct _cq_ring_cmd_st_ *pNext; }CQ_RING_CMD_ST; typedef struct _cq_rtbc_ring_st_ { CQ_RING_CMD_ST rtbc_ring[ISP_RT_CQ0C_BUF_SIZE]; unsigned int imgo_ring_size; unsigned int img2o_ring_size; }CQ_RTBC_RING_ST; #endif #ifdef CONFIG_COMPAT typedef struct { compat_uptr_t pData; unsigned int Count; // count } compat_ISP_REG_IO_STRUCT; typedef struct { ISP_RT_BUF_CTRL_ENUM ctrl; _isp_dma_enum_ buf_id; compat_uptr_t data_ptr; compat_uptr_t ex_data_ptr; //exchanged buffer compat_uptr_t pExtend; } compat_ISP_BUFFER_CTRL_STRUCT; typedef struct { ISP_REF_CNT_CTRL_ENUM ctrl; ISP_REF_CNT_ID_ENUM id; compat_uptr_t data_ptr; } compat_ISP_REF_CNT_CTRL_STRUCT; #endif // /******************************************************************************************** ********************************************************************************************/ /******************************************************************************* * ********************************************************************************/ typedef enum { ISP_CMD_RESET, //Reset ISP_CMD_RESET_BUF, ISP_CMD_READ_REG, //Read register from driver ISP_CMD_WRITE_REG, //Write register to driver ISP_CMD_HOLD_TIME, ISP_CMD_HOLD_REG, //Hold reg write to hw, on/off ISP_CMD_WAIT_IRQ, //Wait IRQ ISP_CMD_READ_IRQ, //Read IRQ ISP_CMD_CLEAR_IRQ, //Clear IRQ ISP_CMD_DUMP_REG, //Dump ISP registers , for debug usage ISP_CMD_SET_USER_PID, //for signal ISP_CMD_RT_BUF_CTRL, //for pass buffer control ISP_CMD_REF_CNT, //get imem reference count ISP_CMD_DEBUG_FLAG, //Dump message level ISP_CMD_WAKELOCK_CTRL, //isp wakelock control ISP_CMD_SENSOR_FREQ_CTRL // sensor frequence control }ISP_CMD_ENUM; // #define ISP_RESET _IO (ISP_MAGIC, ISP_CMD_RESET) #define ISP_RESET_BUF _IO (ISP_MAGIC, ISP_CMD_RESET_BUF) #define ISP_READ_REGISTER _IOWR(ISP_MAGIC, ISP_CMD_READ_REG, ISP_REG_IO_STRUCT) #define ISP_WRITE_REGISTER _IOWR(ISP_MAGIC, ISP_CMD_WRITE_REG, ISP_REG_IO_STRUCT) #define ISP_HOLD_REG_TIME _IOW (ISP_MAGIC, ISP_CMD_HOLD_TIME, ISP_HOLD_TIME_ENUM) #define ISP_HOLD_REG _IOW (ISP_MAGIC, ISP_CMD_HOLD_REG, bool) #define ISP_WAIT_IRQ _IOW (ISP_MAGIC, ISP_CMD_WAIT_IRQ, ISP_WAIT_IRQ_STRUCT) #define ISP_READ_IRQ _IOR (ISP_MAGIC, ISP_CMD_READ_IRQ, ISP_READ_IRQ_STRUCT) #define ISP_CLEAR_IRQ _IOW (ISP_MAGIC, ISP_CMD_CLEAR_IRQ, ISP_CLEAR_IRQ_STRUCT) #define ISP_DUMP_REG _IO (ISP_MAGIC, ISP_CMD_DUMP_REG) #define ISP_SET_USER_PID _IOW (ISP_MAGIC, ISP_CMD_SET_USER_PID, unsigned long) #define ISP_BUFFER_CTRL _IOWR(ISP_MAGIC, ISP_CMD_RT_BUF_CTRL, ISP_BUFFER_CTRL_STRUCT) #define ISP_REF_CNT_CTRL _IOWR(ISP_MAGIC, ISP_CMD_REF_CNT, ISP_REF_CNT_CTRL_STRUCT) #define ISP_DEBUG_FLAG _IOW (ISP_MAGIC, ISP_CMD_DEBUG_FLAG, unsigned long) #define ISP_WAKELOCK_CTRL _IOWR (ISP_MAGIC, ISP_CMD_WAKELOCK_CTRL,unsigned long) #define ISP_SENSOR_FREQ_CTRL _IOW (ISP_MAGIC, ISP_CMD_SENSOR_FREQ_CTRL, unsigned long) #ifdef CONFIG_COMPAT #define COMPAT_ISP_READ_REGISTER _IOWR(ISP_MAGIC, ISP_CMD_READ_REG, compat_ISP_REG_IO_STRUCT) #define COMPAT_ISP_WRITE_REGISTER _IOWR(ISP_MAGIC, ISP_CMD_WRITE_REG, compat_ISP_REG_IO_STRUCT) #define COMPAT_ISP_BUFFER_CTRL _IOWR(ISP_MAGIC, ISP_CMD_RT_BUF_CTRL, compat_ISP_BUFFER_CTRL_STRUCT) #define COMPAT_ISP_REF_CNT_CTRL _IOWR(ISP_MAGIC, ISP_CMD_REF_CNT, compat_ISP_REF_CNT_CTRL_STRUCT) #define COMPAT_ISP_SET_USER_PID _IOW (ISP_MAGIC, ISP_CMD_SET_USER_PID, compat_uptr_t) #define COMPAT_ISP_DEBUG_FLAG _IOW (ISP_MAGIC, ISP_CMD_DEBUG_FLAG, compat_uptr_t) #define COMPAT_ISP_WAKELOCK_CTRL _IOWR(ISP_MAGIC, ISP_CMD_WAKELOCK_CTRL, compat_uptr_t) #define COMPAT_ISP_SENSOR_FREQ_CTRL _IOW(ISP_MAGIC, ISP_CMD_SENSOR_FREQ_CTRL, compat_uptr_t) #endif // bool ISP_RegCallback(ISP_CALLBACK_STRUCT* pCallback); bool ISP_UnregCallback(ISP_CALLBACK_ENUM Type); bool ISP_ControlMdpClock(bool en); int32_t ISP_MDPClockOnCallback(uint64_t engineFlag); int32_t ISP_MDPDumpCallback(uint64_t engineFlag, int level); int32_t ISP_MDPResetCallback(uint64_t engineFlag); int32_t ISP_MDPClockOffCallback(uint64_t engineFlag); // #endif
gpl-2.0
embecosm/gcc
gcc/testsuite/gcc.dg/ipa/inline-7.c
417
/* Check that early inliner works out that a is empty of parameter 0. */ /* { dg-do compile } */ /* { dg-options "-O2 -fdump-tree-einline -fno-partial-inlining" } */ void t(void); int a (int b) { if (!b) { t(); t(); t(); t(); t(); t(); t(); } } void m() { a(1); a(0); } /* { dg-final { scan-tree-dump-times "Inlining a into m" 1 "einline" } } */ /* { dg-final { cleanup-tree-dump "einline" } } */
gpl-2.0
yiendos/pomander
tests/unit/suites/libraries/joomla/filesystem/JFolderTest.php
10715
<?php /** * @package Joomla.UnitTest * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ JLoader::register('JFolder', JPATH_PLATFORM . '/joomla/filesystem/folder.php'); /** * Test class for JFolder. * Generated by PHPUnit on 2011-10-26 at 19:32:37. * * @package Joomla.UnitTest * @subpackage Event * @since 11.1 */ class JFolderTest extends TestCase { /** * Test... * * @todo Implement testCopy(). * * @return void */ public function testCopy() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @todo Implement testCreate(). * * @return void */ public function testCreate() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @todo Implement testDelete(). * * @return void */ public function testDelete() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Tests the JFolder::delete method with an array as an input * * @return void * * @expectedException UnexpectedValueException * @since 11.3 */ public function testDeleteArrayPath() { JFolder::delete(array('/path/to/folder') ); } /** * Test... * * @todo Implement testMove(). * * @return void */ public function testMove() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Test... * * @return void */ public function testExists() { $this->assertTrue( JFolder::exists(__DIR__) ); } /** * Tests the JFolder::files method. * * @return void * * @since 12.1 */ public function testFiles() { // Make sure previous test files are cleaned up $this->_cleanupTestFiles(); // Make some test files and folders mkdir(JPath::clean(JPATH_TESTS . '/tmp/test'), 0777, true); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/index.html'), 'test'); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/index.txt'), 'test'); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/test'), 0777, true); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html'), 'test'); file_put_contents(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt'), 'test'); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.*', true, true, array('index.html')); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.txt'), JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt') ), $result, 'Line: ' . __LINE__ . ' Should exclude index.html files' ); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.html'), JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html') ), $result, 'Line: ' . __LINE__ . ' Should include full path of both index.html files' ); $this->assertEquals( array( JPath::clean('index.html'), JPath::clean('index.html') ), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', true, false), 'Line: ' . __LINE__ . ' Should include only file names of both index.html files' ); // Use of realpath to ensure test works for on all platforms $result = JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', false, true); $result[0] = realpath($result[0]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/index.html') ), $result, 'Line: ' . __LINE__ . ' Non-recursive should only return top folder file full path' ); $this->assertEquals( array( JPath::clean('index.html') ), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'index.html', false, false), 'Line: ' . __LINE__ . ' non-recursive should return only file name of top folder file' ); $this->assertFalse( JFolder::files('/this/is/not/a/path'), 'Line: ' . __LINE__ . ' Non-existent path should return false' ); $this->assertEquals( array(), JFolder::files(JPath::clean(JPATH_TESTS . '/tmp/test'), 'nothing.here', true, true, array(), array()), 'Line: ' . __LINE__ . ' When nothing matches the filter, should return empty array' ); // Clean up our files $this->_cleanupTestFiles(); } /** * Tests the JFolder::folders method. * * @return void * * @since 12.1 */ public function testFolders() { // Make sure previous test files are cleaned up $this->_cleanupTestFiles(); // Create the test folders mkdir(JPath::clean(JPATH_TESTS . '/tmp/test'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), 0777, true); mkdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), 0777, true); $this->assertEquals( array(), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true, array('foo1', 'foo2')) ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true, array('foo1')); $result[0] = realpath($result[0]); $this->assertEquals( array(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1')), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar1', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), ), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), 'bar', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $result[2] = realpath($result[2]); $result[3] = realpath($result[3]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), ), $result ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', true, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $result[2] = realpath($result[2]); $result[3] = realpath($result[3]); $result[4] = realpath($result[4]); $result[5] = realpath($result[5]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2'), ), $result ); $this->assertEquals( array( JPath::clean('bar1'), JPath::clean('bar1'), JPath::clean('bar2'), JPath::clean('bar2'), JPath::clean('foo1'), JPath::clean('foo2'), ), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', true, false) ); // Use of realpath to ensure test works for on all platforms $result = JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', false, true); $result[0] = realpath($result[0]); $result[1] = realpath($result[1]); $this->assertEquals( array( JPath::clean(JPATH_TESTS . '/tmp/test/foo1'), JPath::clean(JPATH_TESTS . '/tmp/test/foo2'), ), $result ); $this->assertEquals( array( JPath::clean('foo1'), JPath::clean('foo2'), ), JFolder::folders(JPath::clean(JPATH_TESTS . '/tmp/test'), '.', false, false, array(), array()) ); $this->assertFalse( JFolder::folders('this/is/not/a/path'), 'Line: ' . __LINE__ . ' Non-existent path should return false' ); // Clean up the folders rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2/bar1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar2')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1/bar1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test/foo1')); rmdir(JPath::clean(JPATH_TESTS . '/tmp/test')); } /** * Test... * * @todo Implement testListFolderTree(). * * @return void */ public function testListFolderTree() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Tests the JFolder::makeSafe method. * * @return void * * @since 12.1 */ public function testMakeSafe() { $actual = JFolder::makeSafe('test1/testdirectory'); $this->assertEquals('test1/testdirectory', $actual); } /** * Convenience method to cleanup before and after testFiles * * @return void * * @since 12.1 */ private function _cleanupTestFiles() { $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.html')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test/index.txt')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/test')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/index.html')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test/index.txt')); $this->_cleanupFile(JPath::clean(JPATH_TESTS . '/tmp/test')); } /** * Convenience method to clean up for files test * * @param string $path The path to clean * * @return void * * @since 12.1 */ private function _cleanupFile($path) { if (file_exists($path)) { if (is_file($path)) { unlink($path); } elseif (is_dir($path)) { rmdir($path); } } } }
gpl-2.0
mseaborn/nacl-glibc
sysdeps/pthread/aio_notify.c
4961
/* Notify initiator of AIO request. Copyright (C) 1997-2001, 2003, 2004, 2006 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <aio_misc.h> #ifndef aio_start_notify_thread # define aio_start_notify_thread() do { } while (0) #endif struct notify_func { void (*func) (sigval_t); sigval_t value; }; static void * notify_func_wrapper (void *arg) { aio_start_notify_thread (); struct notify_func *const n = arg; void (*func) (sigval_t) = n->func; sigval_t value = n->value; free (n); (*func) (value); return NULL; } int internal_function #ifdef BROKEN_THREAD_SIGNALS __aio_notify_only (struct sigevent *sigev, pid_t caller_pid) #else __aio_notify_only (struct sigevent *sigev) #endif { int result = 0; /* Send the signal to notify about finished processing of the request. */ if (__builtin_expect (sigev->sigev_notify == SIGEV_THREAD, 0)) { /* We have to start a thread. */ pthread_t tid; pthread_attr_t attr, *pattr; pattr = (pthread_attr_t *) sigev->sigev_notify_attributes; if (pattr == NULL) { pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); pattr = &attr; } /* SIGEV may be freed as soon as we return, so we cannot let the notification thread use that pointer. Even though a sigval_t is only one word and the same size as a void *, we cannot just pass the value through pthread_create as the argument and have the new thread run the user's function directly, because on some machines the calling convention for a union like sigval_t is different from that for a pointer type like void *. */ struct notify_func *nf = malloc (sizeof *nf); if (nf == NULL) result = -1; else { nf->func = sigev->sigev_notify_function; nf->value = sigev->sigev_value; if (pthread_create (&tid, pattr, notify_func_wrapper, nf) < 0) { free (nf); result = -1; } } } else if (sigev->sigev_notify == SIGEV_SIGNAL) { /* We have to send a signal. */ #if _POSIX_REALTIME_SIGNALS /* Note that the standard gives us the option of using a plain non-queuing signal here when SA_SIGINFO is not set for the signal. */ # ifdef BROKEN_THREAD_SIGNALS if (__aio_sigqueue (sigev->sigev_signo, sigev->sigev_value, caller_pid) < 0) result = -1; # else if (__aio_sigqueue (sigev->sigev_signo, sigev->sigev_value, getpid ()) < 0) result = -1; # endif #else /* There are no queued signals on this system at all. */ result = raise (sigev->sigev_signo); #endif } return result; } void internal_function __aio_notify (struct requestlist *req) { struct waitlist *waitlist; struct aiocb *aiocbp = &req->aiocbp->aiocb; #ifdef BROKEN_THREAD_SIGNALS if (__aio_notify_only (&aiocbp->aio_sigevent, req->caller_pid) != 0) #else if (__aio_notify_only (&aiocbp->aio_sigevent) != 0) #endif { /* XXX What shall we do if already an error is set by read/write/fsync? */ aiocbp->__error_code = errno; aiocbp->__return_value = -1; } /* Now also notify possibly waiting threads. */ waitlist = req->waiting; while (waitlist != NULL) { struct waitlist *next = waitlist->next; if (waitlist->sigevp == NULL) { if (waitlist->result != NULL && aiocbp->__return_value == -1) *waitlist->result = -1; #ifdef DONT_NEED_AIO_MISC_COND AIO_MISC_NOTIFY (waitlist); #else /* Decrement the counter. */ --*waitlist->counterp; pthread_cond_signal (waitlist->cond); #endif } else /* This is part of a asynchronous `lio_listio' operation. If this request is the last one, send the signal. */ if (--*waitlist->counterp == 0) { #ifdef BROKEN_THREAD_SIGNALS __aio_notify_only (waitlist->sigevp, waitlist->caller_pid); #else __aio_notify_only (waitlist->sigevp); #endif /* This is tricky. See lio_listio.c for the reason why this works. */ free ((void *) waitlist->counterp); } waitlist = next; } }
gpl-2.0
ligfx/dolphin
Source/Core/DolphinWX/Config/GameCubeConfigPane.h
1282
// Copyright 2015 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #pragma once #include <wx/arrstr.h> #include <wx/panel.h> class wxButton; class wxCheckBox; class wxChoice; class wxString; namespace ExpansionInterface { enum TEXIDevices : int; } class GameCubeConfigPane final : public wxPanel { public: GameCubeConfigPane(wxWindow* parent, wxWindowID id); private: void InitializeGUI(); void LoadGUIValues(); void BindEvents(); void OnSystemLanguageChange(wxCommandEvent&); void OnOverrideLanguageCheckBoxChanged(wxCommandEvent&); void OnSkipIPLCheckBoxChanged(wxCommandEvent&); void OnSlotAChanged(wxCommandEvent&); void OnSlotBChanged(wxCommandEvent&); void OnSP1Changed(wxCommandEvent&); void OnSlotAButtonClick(wxCommandEvent&); void OnSlotBButtonClick(wxCommandEvent&); void ChooseEXIDevice(const wxString& device_name, int device_id); void HandleEXISlotChange(int slot, const wxString& title); void ChooseSlotPath(bool is_slot_a, ExpansionInterface::TEXIDevices device_type); wxArrayString m_ipl_language_strings; wxChoice* m_system_lang_choice; wxCheckBox* m_override_lang_checkbox; wxCheckBox* m_skip_ipl_checkbox; wxChoice* m_exi_devices[3]; wxButton* m_memcard_path[2]; };
gpl-2.0
rduivenvoorde/QGIS
src/core/classification/qgsclassificationprettybreaks.h
1751
/*************************************************************************** qgsclassificationprettybreaks.h --------------------- begin : September 2019 copyright : (C) 2019 by Denis Rouzaud email : denis@opengis.ch *************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef QGSCLASSIFICATIONPRETTYBREAKS_H #define QGSCLASSIFICATIONPRETTYBREAKS_H #include "qgis_core.h" #include "qgsclassificationmethod.h" /** * \ingroup core * \brief QgsClassificationPrettyBreaks is an implementation of QgsClassificationMethod * for pretty breaks * \since QGIS 3.10 */ class CORE_EXPORT QgsClassificationPrettyBreaks : public QgsClassificationMethod { public: QgsClassificationPrettyBreaks(); QString name() const override; QString id() const override; QgsClassificationMethod *clone() const override; QIcon icon() const override; bool valuesRequired() const override {return false;} private: QList<double> calculateBreaks( double &minimum, double &maximum, const QList<double> &values, int nclasses ) override; }; #endif // QGSCLASSIFICATIONPRETTYBREAKS_H
gpl-2.0
ngwese/mod
xdk-asf-3.17.0/common/services/spi/master_example/at32uc3b0256_evk1101/iar/asf.h
2906
/** * \file * * \brief Autogenerated API include file for the Atmel Software Framework (ASF) * * Copyright (c) 2012 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * 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. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ #ifndef ASF_H #define ASF_H /* * This file includes all API header files for the selected drivers from ASF. * Note: There might be duplicate includes required by more than one driver. * * The file is automatically generated and will be re-written when * running the ASF driver selector tool. Any changes will be discarded. */ // From module: Compiler abstraction layer and code utilities #include <compiler.h> #include <status_codes.h> // From module: EVK1101 #include <led.h> // From module: FLASHC - Flash Controller #include <flashc.h> // From module: GPIO - General-Purpose Input/Output #include <gpio.h> // From module: Generic board support #include <board.h> // From module: Interrupt management - UC3 implementation #include <interrupt.h> // From module: Part identification macros #include <parts.h> // From module: SPI - Serial Peripheral Interface #include <spi.h> // From module: SPI - UC3 implementation #include <spi_master.h> #include <spi_master.h> // From module: System Clock Control - UC3 B0 implementation #include <sysclk.h> #endif // ASF_H
gpl-2.0
ssuthiku/linux
tools/perf/util/thread_map.c
8344
#include <dirent.h> #include <limits.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "strlist.h" #include <string.h> #include <api/fs/fs.h> #include "asm/bug.h" #include "thread_map.h" #include "util.h" #include "debug.h" /* Skip "." and ".." directories */ static int filter(const struct dirent *dir) { if (dir->d_name[0] == '.') return 0; else return 1; } static void thread_map__reset(struct thread_map *map, int start, int nr) { size_t size = (nr - start) * sizeof(map->map[0]); memset(&map->map[start], 0, size); } static struct thread_map *thread_map__realloc(struct thread_map *map, int nr) { size_t size = sizeof(*map) + sizeof(map->map[0]) * nr; int start = map ? map->nr : 0; map = realloc(map, size); /* * We only realloc to add more items, let's reset new items. */ if (map) thread_map__reset(map, start, nr); return map; } #define thread_map__alloc(__nr) thread_map__realloc(NULL, __nr) struct thread_map *thread_map__new_by_pid(pid_t pid) { struct thread_map *threads; char name[256]; int items; struct dirent **namelist = NULL; int i; sprintf(name, "/proc/%d/task", pid); items = scandir(name, &namelist, filter, NULL); if (items <= 0) return NULL; threads = thread_map__alloc(items); if (threads != NULL) { for (i = 0; i < items; i++) thread_map__set_pid(threads, i, atoi(namelist[i]->d_name)); threads->nr = items; atomic_set(&threads->refcnt, 1); } for (i=0; i<items; i++) zfree(&namelist[i]); free(namelist); return threads; } struct thread_map *thread_map__new_by_tid(pid_t tid) { struct thread_map *threads = thread_map__alloc(1); if (threads != NULL) { thread_map__set_pid(threads, 0, tid); threads->nr = 1; atomic_set(&threads->refcnt, 1); } return threads; } struct thread_map *thread_map__new_by_uid(uid_t uid) { DIR *proc; int max_threads = 32, items, i; char path[256]; struct dirent dirent, *next, **namelist = NULL; struct thread_map *threads = thread_map__alloc(max_threads); if (threads == NULL) goto out; proc = opendir("/proc"); if (proc == NULL) goto out_free_threads; threads->nr = 0; atomic_set(&threads->refcnt, 1); while (!readdir_r(proc, &dirent, &next) && next) { char *end; bool grow = false; struct stat st; pid_t pid = strtol(dirent.d_name, &end, 10); if (*end) /* only interested in proper numerical dirents */ continue; snprintf(path, sizeof(path), "/proc/%s", dirent.d_name); if (stat(path, &st) != 0) continue; if (st.st_uid != uid) continue; snprintf(path, sizeof(path), "/proc/%d/task", pid); items = scandir(path, &namelist, filter, NULL); if (items <= 0) goto out_free_closedir; while (threads->nr + items >= max_threads) { max_threads *= 2; grow = true; } if (grow) { struct thread_map *tmp; tmp = realloc(threads, (sizeof(*threads) + max_threads * sizeof(pid_t))); if (tmp == NULL) goto out_free_namelist; threads = tmp; } for (i = 0; i < items; i++) { thread_map__set_pid(threads, threads->nr + i, atoi(namelist[i]->d_name)); } for (i = 0; i < items; i++) zfree(&namelist[i]); free(namelist); threads->nr += items; } out_closedir: closedir(proc); out: return threads; out_free_threads: free(threads); return NULL; out_free_namelist: for (i = 0; i < items; i++) zfree(&namelist[i]); free(namelist); out_free_closedir: zfree(&threads); goto out_closedir; } struct thread_map *thread_map__new(pid_t pid, pid_t tid, uid_t uid) { if (pid != -1) return thread_map__new_by_pid(pid); if (tid == -1 && uid != UINT_MAX) return thread_map__new_by_uid(uid); return thread_map__new_by_tid(tid); } static struct thread_map *thread_map__new_by_pid_str(const char *pid_str) { struct thread_map *threads = NULL, *nt; char name[256]; int items, total_tasks = 0; struct dirent **namelist = NULL; int i, j = 0; pid_t pid, prev_pid = INT_MAX; char *end_ptr; struct str_node *pos; struct strlist *slist = strlist__new(false, pid_str); if (!slist) return NULL; strlist__for_each(pos, slist) { pid = strtol(pos->s, &end_ptr, 10); if (pid == INT_MIN || pid == INT_MAX || (*end_ptr != '\0' && *end_ptr != ',')) goto out_free_threads; if (pid == prev_pid) continue; sprintf(name, "/proc/%d/task", pid); items = scandir(name, &namelist, filter, NULL); if (items <= 0) goto out_free_threads; total_tasks += items; nt = thread_map__realloc(threads, total_tasks); if (nt == NULL) goto out_free_namelist; threads = nt; for (i = 0; i < items; i++) { thread_map__set_pid(threads, j++, atoi(namelist[i]->d_name)); zfree(&namelist[i]); } threads->nr = total_tasks; free(namelist); } out: strlist__delete(slist); if (threads) atomic_set(&threads->refcnt, 1); return threads; out_free_namelist: for (i = 0; i < items; i++) zfree(&namelist[i]); free(namelist); out_free_threads: zfree(&threads); goto out; } struct thread_map *thread_map__new_dummy(void) { struct thread_map *threads = thread_map__alloc(1); if (threads != NULL) { thread_map__set_pid(threads, 0, -1); threads->nr = 1; atomic_set(&threads->refcnt, 1); } return threads; } static struct thread_map *thread_map__new_by_tid_str(const char *tid_str) { struct thread_map *threads = NULL, *nt; int ntasks = 0; pid_t tid, prev_tid = INT_MAX; char *end_ptr; struct str_node *pos; struct strlist *slist; /* perf-stat expects threads to be generated even if tid not given */ if (!tid_str) return thread_map__new_dummy(); slist = strlist__new(false, tid_str); if (!slist) return NULL; strlist__for_each(pos, slist) { tid = strtol(pos->s, &end_ptr, 10); if (tid == INT_MIN || tid == INT_MAX || (*end_ptr != '\0' && *end_ptr != ',')) goto out_free_threads; if (tid == prev_tid) continue; ntasks++; nt = thread_map__realloc(threads, ntasks); if (nt == NULL) goto out_free_threads; threads = nt; thread_map__set_pid(threads, ntasks - 1, tid); threads->nr = ntasks; } out: if (threads) atomic_set(&threads->refcnt, 1); return threads; out_free_threads: zfree(&threads); goto out; } struct thread_map *thread_map__new_str(const char *pid, const char *tid, uid_t uid) { if (pid) return thread_map__new_by_pid_str(pid); if (!tid && uid != UINT_MAX) return thread_map__new_by_uid(uid); return thread_map__new_by_tid_str(tid); } static void thread_map__delete(struct thread_map *threads) { if (threads) { int i; WARN_ONCE(atomic_read(&threads->refcnt) != 0, "thread map refcnt unbalanced\n"); for (i = 0; i < threads->nr; i++) free(thread_map__comm(threads, i)); free(threads); } } struct thread_map *thread_map__get(struct thread_map *map) { if (map) atomic_inc(&map->refcnt); return map; } void thread_map__put(struct thread_map *map) { if (map && atomic_dec_and_test(&map->refcnt)) thread_map__delete(map); } size_t thread_map__fprintf(struct thread_map *threads, FILE *fp) { int i; size_t printed = fprintf(fp, "%d thread%s: ", threads->nr, threads->nr > 1 ? "s" : ""); for (i = 0; i < threads->nr; ++i) printed += fprintf(fp, "%s%d", i ? ", " : "", thread_map__pid(threads, i)); return printed + fprintf(fp, "\n"); } static int get_comm(char **comm, pid_t pid) { char *path; size_t size; int err; if (asprintf(&path, "%s/%d/comm", procfs__mountpoint(), pid) == -1) return -ENOMEM; err = filename__read_str(path, comm, &size); if (!err) { /* * We're reading 16 bytes, while filename__read_str * allocates data per BUFSIZ bytes, so we can safely * mark the end of the string. */ (*comm)[size] = 0; rtrim(*comm); } free(path); return err; } static void comm_init(struct thread_map *map, int i) { pid_t pid = thread_map__pid(map, i); char *comm = NULL; /* dummy pid comm initialization */ if (pid == -1) { map->map[i].comm = strdup("dummy"); return; } /* * The comm name is like extra bonus ;-), * so just warn if we fail for any reason. */ if (get_comm(&comm, pid)) pr_warning("Couldn't resolve comm name for pid %d\n", pid); map->map[i].comm = comm; } void thread_map__read_comms(struct thread_map *threads) { int i; for (i = 0; i < threads->nr; ++i) comm_init(threads, i); }
gpl-2.0
FauxFaux/jdk9-langtools
test/tools/javac/enum/6350057/T6350057.java
3605
/* * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 6350057 7025809 * @summary Test that parameters on implicit enum methods have the right kind * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler * @build JavacTestingAbstractProcessor T6350057 * @compile -processor T6350057 -proc:only TestEnum.java */ import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.*; import javax.lang.model.util.*; import static javax.tools.Diagnostic.Kind.*; public class T6350057 extends JavacTestingAbstractProcessor { static class LocalVarAllergy extends ElementKindVisitor<Boolean, Void> { @Override public Boolean visitTypeAsEnum(TypeElement e, Void v) { System.out.println("visitTypeAsEnum: " + e.getSimpleName().toString()); for(Element el: e.getEnclosedElements() ) this.visit(el); return true; } @Override public Boolean visitVariableAsLocalVariable(VariableElement e, Void v){ throw new IllegalStateException("Should not see any local variables!"); } @Override public Boolean visitVariableAsParameter(VariableElement e, Void v){ String senclm=e.getEnclosingElement().getEnclosingElement().getSimpleName().toString(); String sEncl = senclm+"."+e.getEnclosingElement().getSimpleName().toString(); String stype = e.asType().toString(); String name = e.getSimpleName().toString(); System.out.println("visitVariableAsParameter: " +sEncl+"." + stype + " " + name); return true; } @Override public Boolean visitExecutableAsMethod(ExecutableElement e, Void v){ String name=e.getEnclosingElement().getSimpleName().toString(); name = name + "."+e.getSimpleName().toString(); System.out.println("visitExecutableAsMethod: " + name); for (VariableElement ve: e.getParameters()) this.visit(ve); return true; } } public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) { if (!roundEnvironment.processingOver()) for(Element element : roundEnvironment.getRootElements()) element.accept(new LocalVarAllergy(), null); return true; } }
gpl-2.0