repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Shine-/xbmc
xbmc/pvr/dialogs/GUIDialogPVRGuideOSD.cpp
3993
/* * Copyright (C) 2012-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "FileItem.h" #include "epg/Epg.h" #include "guilib/GUIWindowManager.h" #include "input/Key.h" #include "view/ViewState.h" #include "pvr/PVRManager.h" #include "GUIDialogPVRGuideInfo.h" #include "GUIDialogPVRGuideOSD.h" using namespace PVR; #define CONTROL_LIST 11 CGUIDialogPVRGuideOSD::CGUIDialogPVRGuideOSD() : CGUIDialog(WINDOW_DIALOG_PVR_OSD_GUIDE, "DialogPVRGuideOSD.xml") { m_vecItems = new CFileItemList; } CGUIDialogPVRGuideOSD::~CGUIDialogPVRGuideOSD() { delete m_vecItems; } bool CGUIDialogPVRGuideOSD::OnMessage(CGUIMessage& message) { switch (message.GetMessage()) { case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (m_viewControl.HasControl(iControl)) // list/thumb control { int iItem = m_viewControl.GetSelectedItem(); int iAction = message.GetParam1(); if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK) { ShowInfo(iItem); return true; } } } break; } return CGUIDialog::OnMessage(message); } void CGUIDialogPVRGuideOSD::OnInitWindow() { /* Close dialog immediately if no TV or radio channel is playing */ if (!g_PVRManager.IsPlaying()) { Close(); return; } // lock our display, as this window is rendered from the player thread g_graphicsContext.Lock(); m_viewControl.SetCurrentView(DEFAULT_VIEW_LIST); // empty the list ready for population Clear(); g_PVRManager.GetCurrentEpg(*m_vecItems); m_viewControl.SetItems(*m_vecItems); g_graphicsContext.Unlock(); // call init CGUIDialog::OnInitWindow(); // select the active entry unsigned int iSelectedItem = 0; for (int iEpgPtr = 0; iEpgPtr < m_vecItems->Size(); ++iEpgPtr) { CFileItemPtr entry = m_vecItems->Get(iEpgPtr); if (entry->HasEPGInfoTag() && entry->GetEPGInfoTag()->IsActive()) { iSelectedItem = iEpgPtr; break; } } m_viewControl.SetSelectedItem(iSelectedItem); } void CGUIDialogPVRGuideOSD::OnDeinitWindow(int nextWindowID) { CGUIDialog::OnDeinitWindow(nextWindowID); Clear(); } void CGUIDialogPVRGuideOSD::Clear() { m_viewControl.Clear(); m_vecItems->Clear(); } void CGUIDialogPVRGuideOSD::ShowInfo(int item) { /* Check file item is in list range and get his pointer */ if (item < 0 || item >= (int)m_vecItems->Size()) return; CFileItemPtr pItem = m_vecItems->Get(item); /* Load programme info dialog */ CGUIDialogPVRGuideInfo* pDlgInfo = (CGUIDialogPVRGuideInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_GUIDE_INFO); if (!pDlgInfo) return; /* inform dialog about the file item and open dialog window */ pDlgInfo->SetProgInfo(pItem->GetEPGInfoTag()); pDlgInfo->Open(); } void CGUIDialogPVRGuideOSD::OnWindowLoaded() { CGUIDialog::OnWindowLoaded(); m_viewControl.Reset(); m_viewControl.SetParentWindow(GetID()); m_viewControl.AddView(GetControl(CONTROL_LIST)); } void CGUIDialogPVRGuideOSD::OnWindowUnload() { CGUIDialog::OnWindowUnload(); m_viewControl.Reset(); } CGUIControl *CGUIDialogPVRGuideOSD::GetFirstFocusableControl(int id) { if (m_viewControl.HasControl(id)) id = m_viewControl.GetCurrentControl(); return CGUIWindow::GetFirstFocusableControl(id); }
gpl-2.0
NetworkNub/librenms
includes/alerts/transport.victorops.php
1967
/* Copyright (C) 2015 Daniel Preussker <[email protected]> * 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/>. */ /** * VictorOps Generic-API Transport - Based on PagerDuty transport * @author f0o <[email protected]> * @author laf <[email protected]> * @copyright 2015 f0o, laf, LibreNMS * @license GPL * @package LibreNMS * @subpackage Alerts */ $url = $opts['url']; $protocol = array( 'entity_id' => ($obj['id'] ? $obj['id'] : $obj['uid']), 'state_start_time' => strtotime($obj['timestamp']), 'monitoring_tool' => 'librenms', ); if( $obj['state'] == 0 ) { $protocol['message_type'] = 'recovery'; } elseif( $obj['state'] == 2 ) { $protocol['message_type'] = 'acknowledgement'; } elseif ($obj['state'] == 1) { $protocol['message_type'] = 'critical'; } foreach( $obj['faults'] as $fault=>$data ) { $protocol['state_message'] .= $data['string']; } $curl = curl_init(); set_curl_proxy($curl); curl_setopt($curl, CURLOPT_URL, $url ); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type'=> 'application/json')); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($protocol)); $ret = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if( $code != 200 ) { var_dump("VictorOps returned Error, retry later"); //FIXME: propper debuging return false; } return true;
gpl-3.0
zneext/mtasa-blue
Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp
2217
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp * PURPOSE: Player statistics packet class * DEVELOPERS: Jax <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #include "StdInc.h" CPlayerStatsPacket::~CPlayerStatsPacket ( void ) { Clear ( ); } bool CPlayerStatsPacket::Write ( NetBitStreamInterface& BitStream ) const { // Write the source player. if ( m_pSourceElement ) { ElementID ID = m_pSourceElement->GetID (); BitStream.Write ( ID ); // Write the stats unsigned short usNumStats = static_cast < unsigned short >( m_List.size () ); BitStream.WriteCompressed ( usNumStats ); map < unsigned short, sPlayerStat > ::const_iterator iter = m_List.begin (); for ( ; iter != m_List.end () ; ++iter ) { const sPlayerStat& playerStat = (*iter).second; BitStream.Write ( playerStat.id ); BitStream.Write ( playerStat.value ); } return true; } return false; } void CPlayerStatsPacket::Add ( unsigned short usID, float fValue ) { map < unsigned short, sPlayerStat > ::iterator iter = m_List.find ( usID ); if ( iter != m_List.end ( ) ) { if ( fValue == 0.0f ) { m_List.erase ( iter ); } else { sPlayerStat& stat = (*iter).second; stat.value = fValue; } } else { sPlayerStat stat; stat.id = usID; stat.value = fValue; m_List[ usID ] = stat; } } void CPlayerStatsPacket::Remove ( unsigned short usID, float fValue ) { map < unsigned short, sPlayerStat > ::iterator iter = m_List.find ( usID ); if ( iter != m_List.end ( ) ) { m_List.erase ( iter ); } } void CPlayerStatsPacket::Clear ( void ) { m_List.clear (); }
gpl-3.0
anthgur/servo
tests/wpt/web-platform-tests/requestidlecallback/basic.html
2769
<!DOCTYPE html> <title>window.requestIdleCallback exists</title> <link rel="author" title="Ross McIlroy" href="mailto:[email protected]" /> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> test(function() { assert_equals(typeof window.requestIdleCallback, "function"); }, "window.requestIdleCallback is defined", {assert: "The window.requestIdleCallback function is used to request callbacks during browser-defined idle time."}); test(function() { assert_equals(typeof window.cancelIdleCallback, "function"); }, "window.cancelIdleCallback is defined", {assert: "The window.cancelIdleCallback function is used to cancel callbacks scheduled via requestIdleCallback."}); test(function() { assert_equals(typeof window.requestIdleCallback(function() {}), "number"); }, "window.requestIdleCallback() returns a number", {assert: "The requestIdleCallback method MUST return a long"}); test(function() { assert_equals(typeof window.cancelIdleCallback(1), "undefined"); }, "window.cancelIdleCallback() returns undefined", {assert: "The cancelIdleCallback method MUST return void"}); async_test(function() { // Check whether requestIdleCallback schedules a callback which gets executed // and the deadline argument is passed correctly. requestIdleCallback(this.step_func_done(function(deadline) { assert_equals(arguments.length, 1, "Only one argument should be passed to callback."); assert_class_string(deadline, "IdleDeadline"); assert_equals(typeof deadline.timeRemaining, "function", "IdleDeadline.timeRemaining MUST be a function which returns the time remaining in milliseconds"); assert_equals(typeof deadline.timeRemaining(), "number", "IdleDeadline.timeRemaining MUST return a double of the time remaining in milliseconds"); assert_true(deadline.timeRemaining() <= 50, "IdleDeadline.timeRemaining() MUST be less than or equal to 50ms in the future."); assert_equals(typeof deadline.didTimeout, "boolean", "IdleDeadline.didTimeout MUST be a boolean"); assert_false(deadline.didTimeout, "IdleDeadline.didTimeout MUST be false if requestIdleCallback wasn't scheduled due to a timeout"); })); }, 'requestIdleCallback schedules callbacks'); async_test(function() { // Check whether requestIdleCallback schedules a callback which gets executed // and the deadline argument is passed correctly. var handle = requestIdleCallback(this.step_func(function(deadline) { assert_unreached("callback should not be called if canceled with cancelIdleCallback"); })); cancelIdleCallback(handle); step_timeout(this.step_func_done(), 200); }, 'cancelIdleCallback cancels callbacks'); </script> <h1>Basic requestIdleCallback Tests</h1> <div id="log"></div>
mpl-2.0
dennishuo/hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketHeader.java
7020
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.protocol.datatransfer; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.PacketHeaderProto; import org.apache.hadoop.hdfs.util.ByteBufferOutputStream; import com.google.common.base.Preconditions; import com.google.common.primitives.Shorts; import com.google.common.primitives.Ints; import com.google.protobuf.InvalidProtocolBufferException; /** * Header data for each packet that goes through the read/write pipelines. * Includes all of the information about the packet, excluding checksums and * actual data. * * This data includes: * - the offset in bytes into the HDFS block of the data in this packet * - the sequence number of this packet in the pipeline * - whether or not this is the last packet in the pipeline * - the length of the data in this packet * - whether or not this packet should be synced by the DNs. * * When serialized, this header is written out as a protocol buffer, preceded * by a 4-byte integer representing the full packet length, and a 2-byte short * representing the header length. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class PacketHeader { private static final int MAX_PROTO_SIZE = PacketHeaderProto.newBuilder() .setOffsetInBlock(0) .setSeqno(0) .setLastPacketInBlock(false) .setDataLen(0) .setSyncBlock(false) .build().getSerializedSize(); public static final int PKT_LENGTHS_LEN = Ints.BYTES + Shorts.BYTES; public static final int PKT_MAX_HEADER_LEN = PKT_LENGTHS_LEN + MAX_PROTO_SIZE; private int packetLen; private PacketHeaderProto proto; public PacketHeader() { } public PacketHeader(int packetLen, long offsetInBlock, long seqno, boolean lastPacketInBlock, int dataLen, boolean syncBlock) { this.packetLen = packetLen; Preconditions.checkArgument(packetLen >= Ints.BYTES, "packet len %s should always be at least 4 bytes", packetLen); PacketHeaderProto.Builder builder = PacketHeaderProto.newBuilder() .setOffsetInBlock(offsetInBlock) .setSeqno(seqno) .setLastPacketInBlock(lastPacketInBlock) .setDataLen(dataLen); if (syncBlock) { // Only set syncBlock if it is specified. // This is wire-incompatible with Hadoop 2.0.0-alpha due to HDFS-3721 // because it changes the length of the packet header, and BlockReceiver // in that version did not support variable-length headers. builder.setSyncBlock(true); } proto = builder.build(); } public int getDataLen() { return proto.getDataLen(); } public boolean isLastPacketInBlock() { return proto.getLastPacketInBlock(); } public long getSeqno() { return proto.getSeqno(); } public long getOffsetInBlock() { return proto.getOffsetInBlock(); } public int getPacketLen() { return packetLen; } public boolean getSyncBlock() { return proto.getSyncBlock(); } @Override public String toString() { return "PacketHeader with packetLen=" + packetLen + " header data: " + proto.toString(); } public void setFieldsFromData( int packetLen, byte[] headerData) throws InvalidProtocolBufferException { this.packetLen = packetLen; proto = PacketHeaderProto.parseFrom(headerData); } public void readFields(ByteBuffer buf) throws IOException { packetLen = buf.getInt(); short protoLen = buf.getShort(); byte[] data = new byte[protoLen]; buf.get(data); proto = PacketHeaderProto.parseFrom(data); } public void readFields(DataInputStream in) throws IOException { this.packetLen = in.readInt(); short protoLen = in.readShort(); byte[] data = new byte[protoLen]; in.readFully(data); proto = PacketHeaderProto.parseFrom(data); } /** * @return the number of bytes necessary to write out this header, * including the length-prefixing of the payload and header */ public int getSerializedSize() { return PKT_LENGTHS_LEN + proto.getSerializedSize(); } /** * Write the header into the buffer. * This requires that PKT_HEADER_LEN bytes are available. */ public void putInBuffer(final ByteBuffer buf) { assert proto.getSerializedSize() <= MAX_PROTO_SIZE : "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize(); try { buf.putInt(packetLen); buf.putShort((short) proto.getSerializedSize()); proto.writeTo(new ByteBufferOutputStream(buf)); } catch (IOException e) { throw new RuntimeException(e); } } public void write(DataOutputStream out) throws IOException { assert proto.getSerializedSize() <= MAX_PROTO_SIZE : "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize(); out.writeInt(packetLen); out.writeShort(proto.getSerializedSize()); proto.writeTo(out); } public byte[] getBytes() { ByteBuffer buf = ByteBuffer.allocate(getSerializedSize()); putInBuffer(buf); return buf.array(); } /** * Perform a sanity check on the packet, returning true if it is sane. * @param lastSeqNo the previous sequence number received - we expect the * current sequence number to be larger by 1. */ public boolean sanityCheck(long lastSeqNo) { // We should only have a non-positive data length for the last packet if (proto.getDataLen() <= 0 && !proto.getLastPacketInBlock()) return false; // The last packet should not contain data if (proto.getLastPacketInBlock() && proto.getDataLen() != 0) return false; // Seqnos should always increase by 1 with each packet received return proto.getSeqno() == lastSeqNo + 1; } @Override public boolean equals(Object o) { if (!(o instanceof PacketHeader)) return false; PacketHeader other = (PacketHeader)o; return this.proto.equals(other.proto); } @Override public int hashCode() { return (int)proto.getSeqno(); } }
apache-2.0
mericon/Xp_Kernel_LGH850
virt/arch/powerpc/kvm/book3s_hv.c
69751
/* * Copyright 2011 Paul Mackerras, IBM Corp. <[email protected]> * Copyright (C) 2009. SUSE Linux Products GmbH. All rights reserved. * * Authors: * Paul Mackerras <[email protected]> * Alexander Graf <[email protected]> * Kevin Wolf <[email protected]> * * Description: KVM functions specific to running on Book 3S * processors in hypervisor mode (specifically POWER7 and later). * * This file is derived from arch/powerpc/kvm/book3s.c, * by Alexander Graf <[email protected]>. * * 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/kvm_host.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/preempt.h> #include <linux/sched.h> #include <linux/delay.h> #include <linux/export.h> #include <linux/fs.h> #include <linux/anon_inodes.h> #include <linux/cpumask.h> #include <linux/spinlock.h> #include <linux/page-flags.h> #include <linux/srcu.h> #include <linux/miscdevice.h> #include <asm/reg.h> #include <asm/cputable.h> #include <asm/cache.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> #include <asm/uaccess.h> #include <asm/io.h> #include <asm/kvm_ppc.h> #include <asm/kvm_book3s.h> #include <asm/mmu_context.h> #include <asm/lppaca.h> #include <asm/processor.h> #include <asm/cputhreads.h> #include <asm/page.h> #include <asm/hvcall.h> #include <asm/switch_to.h> #include <asm/smp.h> #include <linux/gfp.h> #include <linux/vmalloc.h> #include <linux/highmem.h> #include <linux/hugetlb.h> #include <linux/module.h> #include "book3s.h" /* #define EXIT_DEBUG */ /* #define EXIT_DEBUG_SIMPLE */ /* #define EXIT_DEBUG_INT */ /* Used to indicate that a guest page fault needs to be handled */ #define RESUME_PAGE_FAULT (RESUME_GUEST | RESUME_FLAG_ARCH1) /* Used as a "null" value for timebase values */ #define TB_NIL (~(u64)0) static DECLARE_BITMAP(default_enabled_hcalls, MAX_HCALL_OPCODE/4 + 1); #if defined(CONFIG_PPC_64K_PAGES) #define MPP_BUFFER_ORDER 0 #elif defined(CONFIG_PPC_4K_PAGES) #define MPP_BUFFER_ORDER 3 #endif static void kvmppc_end_cede(struct kvm_vcpu *vcpu); static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu); static void kvmppc_fast_vcpu_kick_hv(struct kvm_vcpu *vcpu) { int me; int cpu = vcpu->cpu; wait_queue_head_t *wqp; wqp = kvm_arch_vcpu_wq(vcpu); if (waitqueue_active(wqp)) { wake_up_interruptible(wqp); ++vcpu->stat.halt_wakeup; } me = get_cpu(); /* CPU points to the first thread of the core */ if (cpu != me && cpu >= 0 && cpu < nr_cpu_ids) { #ifdef CONFIG_PPC_ICP_NATIVE int real_cpu = cpu + vcpu->arch.ptid; if (paca[real_cpu].kvm_hstate.xics_phys) xics_wake_cpu(real_cpu); else #endif if (cpu_online(cpu)) smp_send_reschedule(cpu); } put_cpu(); } /* * We use the vcpu_load/put functions to measure stolen time. * Stolen time is counted as time when either the vcpu is able to * run as part of a virtual core, but the task running the vcore * is preempted or sleeping, or when the vcpu needs something done * in the kernel by the task running the vcpu, but that task is * preempted or sleeping. Those two things have to be counted * separately, since one of the vcpu tasks will take on the job * of running the core, and the other vcpu tasks in the vcore will * sleep waiting for it to do that, but that sleep shouldn't count * as stolen time. * * Hence we accumulate stolen time when the vcpu can run as part of * a vcore using vc->stolen_tb, and the stolen time when the vcpu * needs its task to do other things in the kernel (for example, * service a page fault) in busy_stolen. We don't accumulate * stolen time for a vcore when it is inactive, or for a vcpu * when it is in state RUNNING or NOTREADY. NOTREADY is a bit of * a misnomer; it means that the vcpu task is not executing in * the KVM_VCPU_RUN ioctl, i.e. it is in userspace or elsewhere in * the kernel. We don't have any way of dividing up that time * between time that the vcpu is genuinely stopped, time that * the task is actively working on behalf of the vcpu, and time * that the task is preempted, so we don't count any of it as * stolen. * * Updates to busy_stolen are protected by arch.tbacct_lock; * updates to vc->stolen_tb are protected by the arch.tbacct_lock * of the vcpu that has taken responsibility for running the vcore * (i.e. vc->runner). The stolen times are measured in units of * timebase ticks. (Note that the != TB_NIL checks below are * purely defensive; they should never fail.) */ static void kvmppc_core_vcpu_load_hv(struct kvm_vcpu *vcpu, int cpu) { struct kvmppc_vcore *vc = vcpu->arch.vcore; unsigned long flags; spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags); if (vc->runner == vcpu && vc->vcore_state != VCORE_INACTIVE && vc->preempt_tb != TB_NIL) { vc->stolen_tb += mftb() - vc->preempt_tb; vc->preempt_tb = TB_NIL; } if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST && vcpu->arch.busy_preempt != TB_NIL) { vcpu->arch.busy_stolen += mftb() - vcpu->arch.busy_preempt; vcpu->arch.busy_preempt = TB_NIL; } spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags); } static void kvmppc_core_vcpu_put_hv(struct kvm_vcpu *vcpu) { struct kvmppc_vcore *vc = vcpu->arch.vcore; unsigned long flags; spin_lock_irqsave(&vcpu->arch.tbacct_lock, flags); if (vc->runner == vcpu && vc->vcore_state != VCORE_INACTIVE) vc->preempt_tb = mftb(); if (vcpu->arch.state == KVMPPC_VCPU_BUSY_IN_HOST) vcpu->arch.busy_preempt = mftb(); spin_unlock_irqrestore(&vcpu->arch.tbacct_lock, flags); } static void kvmppc_set_msr_hv(struct kvm_vcpu *vcpu, u64 msr) { vcpu->arch.shregs.msr = msr; kvmppc_end_cede(vcpu); } void kvmppc_set_pvr_hv(struct kvm_vcpu *vcpu, u32 pvr) { vcpu->arch.pvr = pvr; } int kvmppc_set_arch_compat(struct kvm_vcpu *vcpu, u32 arch_compat) { unsigned long pcr = 0; struct kvmppc_vcore *vc = vcpu->arch.vcore; if (arch_compat) { if (!cpu_has_feature(CPU_FTR_ARCH_206)) return -EINVAL; /* 970 has no compat mode support */ switch (arch_compat) { case PVR_ARCH_205: /* * If an arch bit is set in PCR, all the defined * higher-order arch bits also have to be set. */ pcr = PCR_ARCH_206 | PCR_ARCH_205; break; case PVR_ARCH_206: case PVR_ARCH_206p: pcr = PCR_ARCH_206; break; case PVR_ARCH_207: break; default: return -EINVAL; } if (!cpu_has_feature(CPU_FTR_ARCH_207S)) { /* POWER7 can't emulate POWER8 */ if (!(pcr & PCR_ARCH_206)) return -EINVAL; pcr &= ~PCR_ARCH_206; } } spin_lock(&vc->lock); vc->arch_compat = arch_compat; vc->pcr = pcr; spin_unlock(&vc->lock); return 0; } void kvmppc_dump_regs(struct kvm_vcpu *vcpu) { int r; pr_err("vcpu %p (%d):\n", vcpu, vcpu->vcpu_id); pr_err("pc = %.16lx msr = %.16llx trap = %x\n", vcpu->arch.pc, vcpu->arch.shregs.msr, vcpu->arch.trap); for (r = 0; r < 16; ++r) pr_err("r%2d = %.16lx r%d = %.16lx\n", r, kvmppc_get_gpr(vcpu, r), r+16, kvmppc_get_gpr(vcpu, r+16)); pr_err("ctr = %.16lx lr = %.16lx\n", vcpu->arch.ctr, vcpu->arch.lr); pr_err("srr0 = %.16llx srr1 = %.16llx\n", vcpu->arch.shregs.srr0, vcpu->arch.shregs.srr1); pr_err("sprg0 = %.16llx sprg1 = %.16llx\n", vcpu->arch.shregs.sprg0, vcpu->arch.shregs.sprg1); pr_err("sprg2 = %.16llx sprg3 = %.16llx\n", vcpu->arch.shregs.sprg2, vcpu->arch.shregs.sprg3); pr_err("cr = %.8x xer = %.16lx dsisr = %.8x\n", vcpu->arch.cr, vcpu->arch.xer, vcpu->arch.shregs.dsisr); pr_err("dar = %.16llx\n", vcpu->arch.shregs.dar); pr_err("fault dar = %.16lx dsisr = %.8x\n", vcpu->arch.fault_dar, vcpu->arch.fault_dsisr); pr_err("SLB (%d entries):\n", vcpu->arch.slb_max); for (r = 0; r < vcpu->arch.slb_max; ++r) pr_err(" ESID = %.16llx VSID = %.16llx\n", vcpu->arch.slb[r].orige, vcpu->arch.slb[r].origv); pr_err("lpcr = %.16lx sdr1 = %.16lx last_inst = %.8x\n", vcpu->arch.vcore->lpcr, vcpu->kvm->arch.sdr1, vcpu->arch.last_inst); } struct kvm_vcpu *kvmppc_find_vcpu(struct kvm *kvm, int id) { int r; struct kvm_vcpu *v, *ret = NULL; mutex_lock(&kvm->lock); kvm_for_each_vcpu(r, v, kvm) { if (v->vcpu_id == id) { ret = v; break; } } mutex_unlock(&kvm->lock); return ret; } static void init_vpa(struct kvm_vcpu *vcpu, struct lppaca *vpa) { vpa->__old_status |= LPPACA_OLD_SHARED_PROC; vpa->yield_count = cpu_to_be32(1); } static int set_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *v, unsigned long addr, unsigned long len) { /* check address is cacheline aligned */ if (addr & (L1_CACHE_BYTES - 1)) return -EINVAL; spin_lock(&vcpu->arch.vpa_update_lock); if (v->next_gpa != addr || v->len != len) { v->next_gpa = addr; v->len = addr ? len : 0; v->update_pending = 1; } spin_unlock(&vcpu->arch.vpa_update_lock); return 0; } /* Length for a per-processor buffer is passed in at offset 4 in the buffer */ struct reg_vpa { u32 dummy; union { __be16 hword; __be32 word; } length; }; static int vpa_is_registered(struct kvmppc_vpa *vpap) { if (vpap->update_pending) return vpap->next_gpa != 0; return vpap->pinned_addr != NULL; } static unsigned long do_h_register_vpa(struct kvm_vcpu *vcpu, unsigned long flags, unsigned long vcpuid, unsigned long vpa) { struct kvm *kvm = vcpu->kvm; unsigned long len, nb; void *va; struct kvm_vcpu *tvcpu; int err; int subfunc; struct kvmppc_vpa *vpap; tvcpu = kvmppc_find_vcpu(kvm, vcpuid); if (!tvcpu) return H_PARAMETER; subfunc = (flags >> H_VPA_FUNC_SHIFT) & H_VPA_FUNC_MASK; if (subfunc == H_VPA_REG_VPA || subfunc == H_VPA_REG_DTL || subfunc == H_VPA_REG_SLB) { /* Registering new area - address must be cache-line aligned */ if ((vpa & (L1_CACHE_BYTES - 1)) || !vpa) return H_PARAMETER; /* convert logical addr to kernel addr and read length */ va = kvmppc_pin_guest_page(kvm, vpa, &nb); if (va == NULL) return H_PARAMETER; if (subfunc == H_VPA_REG_VPA) len = be16_to_cpu(((struct reg_vpa *)va)->length.hword); else len = be32_to_cpu(((struct reg_vpa *)va)->length.word); kvmppc_unpin_guest_page(kvm, va, vpa, false); /* Check length */ if (len > nb || len < sizeof(struct reg_vpa)) return H_PARAMETER; } else { vpa = 0; len = 0; } err = H_PARAMETER; vpap = NULL; spin_lock(&tvcpu->arch.vpa_update_lock); switch (subfunc) { case H_VPA_REG_VPA: /* register VPA */ if (len < sizeof(struct lppaca)) break; vpap = &tvcpu->arch.vpa; err = 0; break; case H_VPA_REG_DTL: /* register DTL */ if (len < sizeof(struct dtl_entry)) break; len -= len % sizeof(struct dtl_entry); /* Check that they have previously registered a VPA */ err = H_RESOURCE; if (!vpa_is_registered(&tvcpu->arch.vpa)) break; vpap = &tvcpu->arch.dtl; err = 0; break; case H_VPA_REG_SLB: /* register SLB shadow buffer */ /* Check that they have previously registered a VPA */ err = H_RESOURCE; if (!vpa_is_registered(&tvcpu->arch.vpa)) break; vpap = &tvcpu->arch.slb_shadow; err = 0; break; case H_VPA_DEREG_VPA: /* deregister VPA */ /* Check they don't still have a DTL or SLB buf registered */ err = H_RESOURCE; if (vpa_is_registered(&tvcpu->arch.dtl) || vpa_is_registered(&tvcpu->arch.slb_shadow)) break; vpap = &tvcpu->arch.vpa; err = 0; break; case H_VPA_DEREG_DTL: /* deregister DTL */ vpap = &tvcpu->arch.dtl; err = 0; break; case H_VPA_DEREG_SLB: /* deregister SLB shadow buffer */ vpap = &tvcpu->arch.slb_shadow; err = 0; break; } if (vpap) { vpap->next_gpa = vpa; vpap->len = len; vpap->update_pending = 1; } spin_unlock(&tvcpu->arch.vpa_update_lock); return err; } static void kvmppc_update_vpa(struct kvm_vcpu *vcpu, struct kvmppc_vpa *vpap) { struct kvm *kvm = vcpu->kvm; void *va; unsigned long nb; unsigned long gpa; /* * We need to pin the page pointed to by vpap->next_gpa, * but we can't call kvmppc_pin_guest_page under the lock * as it does get_user_pages() and down_read(). So we * have to drop the lock, pin the page, then get the lock * again and check that a new area didn't get registered * in the meantime. */ for (;;) { gpa = vpap->next_gpa; spin_unlock(&vcpu->arch.vpa_update_lock); va = NULL; nb = 0; if (gpa) va = kvmppc_pin_guest_page(kvm, gpa, &nb); spin_lock(&vcpu->arch.vpa_update_lock); if (gpa == vpap->next_gpa) break; /* sigh... unpin that one and try again */ if (va) kvmppc_unpin_guest_page(kvm, va, gpa, false); } vpap->update_pending = 0; if (va && nb < vpap->len) { /* * If it's now too short, it must be that userspace * has changed the mappings underlying guest memory, * so unregister the region. */ kvmppc_unpin_guest_page(kvm, va, gpa, false); va = NULL; } if (vpap->pinned_addr) kvmppc_unpin_guest_page(kvm, vpap->pinned_addr, vpap->gpa, vpap->dirty); vpap->gpa = gpa; vpap->pinned_addr = va; vpap->dirty = false; if (va) vpap->pinned_end = va + vpap->len; } static void kvmppc_update_vpas(struct kvm_vcpu *vcpu) { if (!(vcpu->arch.vpa.update_pending || vcpu->arch.slb_shadow.update_pending || vcpu->arch.dtl.update_pending)) return; spin_lock(&vcpu->arch.vpa_update_lock); if (vcpu->arch.vpa.update_pending) { kvmppc_update_vpa(vcpu, &vcpu->arch.vpa); if (vcpu->arch.vpa.pinned_addr) init_vpa(vcpu, vcpu->arch.vpa.pinned_addr); } if (vcpu->arch.dtl.update_pending) { kvmppc_update_vpa(vcpu, &vcpu->arch.dtl); vcpu->arch.dtl_ptr = vcpu->arch.dtl.pinned_addr; vcpu->arch.dtl_index = 0; } if (vcpu->arch.slb_shadow.update_pending) kvmppc_update_vpa(vcpu, &vcpu->arch.slb_shadow); spin_unlock(&vcpu->arch.vpa_update_lock); } /* * Return the accumulated stolen time for the vcore up until `now'. * The caller should hold the vcore lock. */ static u64 vcore_stolen_time(struct kvmppc_vcore *vc, u64 now) { u64 p; /* * If we are the task running the vcore, then since we hold * the vcore lock, we can't be preempted, so stolen_tb/preempt_tb * can't be updated, so we don't need the tbacct_lock. * If the vcore is inactive, it can't become active (since we * hold the vcore lock), so the vcpu load/put functions won't * update stolen_tb/preempt_tb, and we don't need tbacct_lock. */ if (vc->vcore_state != VCORE_INACTIVE && vc->runner->arch.run_task != current) { spin_lock_irq(&vc->runner->arch.tbacct_lock); p = vc->stolen_tb; if (vc->preempt_tb != TB_NIL) p += now - vc->preempt_tb; spin_unlock_irq(&vc->runner->arch.tbacct_lock); } else { p = vc->stolen_tb; } return p; } static void kvmppc_create_dtl_entry(struct kvm_vcpu *vcpu, struct kvmppc_vcore *vc) { struct dtl_entry *dt; struct lppaca *vpa; unsigned long stolen; unsigned long core_stolen; u64 now; dt = vcpu->arch.dtl_ptr; vpa = vcpu->arch.vpa.pinned_addr; now = mftb(); core_stolen = vcore_stolen_time(vc, now); stolen = core_stolen - vcpu->arch.stolen_logged; vcpu->arch.stolen_logged = core_stolen; spin_lock_irq(&vcpu->arch.tbacct_lock); stolen += vcpu->arch.busy_stolen; vcpu->arch.busy_stolen = 0; spin_unlock_irq(&vcpu->arch.tbacct_lock); if (!dt || !vpa) return; memset(dt, 0, sizeof(struct dtl_entry)); dt->dispatch_reason = 7; dt->processor_id = cpu_to_be16(vc->pcpu + vcpu->arch.ptid); dt->timebase = cpu_to_be64(now + vc->tb_offset); dt->enqueue_to_dispatch_time = cpu_to_be32(stolen); dt->srr0 = cpu_to_be64(kvmppc_get_pc(vcpu)); dt->srr1 = cpu_to_be64(vcpu->arch.shregs.msr); ++dt; if (dt == vcpu->arch.dtl.pinned_end) dt = vcpu->arch.dtl.pinned_addr; vcpu->arch.dtl_ptr = dt; /* order writing *dt vs. writing vpa->dtl_idx */ smp_wmb(); vpa->dtl_idx = cpu_to_be64(++vcpu->arch.dtl_index); vcpu->arch.dtl.dirty = true; } static bool kvmppc_power8_compatible(struct kvm_vcpu *vcpu) { if (vcpu->arch.vcore->arch_compat >= PVR_ARCH_207) return true; if ((!vcpu->arch.vcore->arch_compat) && cpu_has_feature(CPU_FTR_ARCH_207S)) return true; return false; } static int kvmppc_h_set_mode(struct kvm_vcpu *vcpu, unsigned long mflags, unsigned long resource, unsigned long value1, unsigned long value2) { switch (resource) { case H_SET_MODE_RESOURCE_SET_CIABR: if (!kvmppc_power8_compatible(vcpu)) return H_P2; if (value2) return H_P4; if (mflags) return H_UNSUPPORTED_FLAG_START; /* Guests can't breakpoint the hypervisor */ if ((value1 & CIABR_PRIV) == CIABR_PRIV_HYPER) return H_P3; vcpu->arch.ciabr = value1; return H_SUCCESS; case H_SET_MODE_RESOURCE_SET_DAWR: if (!kvmppc_power8_compatible(vcpu)) return H_P2; if (mflags) return H_UNSUPPORTED_FLAG_START; if (value2 & DABRX_HYP) return H_P4; vcpu->arch.dawr = value1; vcpu->arch.dawrx = value2; return H_SUCCESS; default: return H_TOO_HARD; } } int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu) { unsigned long req = kvmppc_get_gpr(vcpu, 3); unsigned long target, ret = H_SUCCESS; struct kvm_vcpu *tvcpu; int idx, rc; if (req <= MAX_HCALL_OPCODE && !test_bit(req/4, vcpu->kvm->arch.enabled_hcalls)) return RESUME_HOST; switch (req) { case H_ENTER: idx = srcu_read_lock(&vcpu->kvm->srcu); ret = kvmppc_virtmode_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4), kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6), kvmppc_get_gpr(vcpu, 7)); srcu_read_unlock(&vcpu->kvm->srcu, idx); break; case H_CEDE: break; case H_PROD: target = kvmppc_get_gpr(vcpu, 4); tvcpu = kvmppc_find_vcpu(vcpu->kvm, target); if (!tvcpu) { ret = H_PARAMETER; break; } tvcpu->arch.prodded = 1; smp_mb(); if (vcpu->arch.ceded) { if (waitqueue_active(&vcpu->wq)) { wake_up_interruptible(&vcpu->wq); vcpu->stat.halt_wakeup++; } } break; case H_CONFER: target = kvmppc_get_gpr(vcpu, 4); if (target == -1) break; tvcpu = kvmppc_find_vcpu(vcpu->kvm, target); if (!tvcpu) { ret = H_PARAMETER; break; } kvm_vcpu_yield_to(tvcpu); break; case H_REGISTER_VPA: ret = do_h_register_vpa(vcpu, kvmppc_get_gpr(vcpu, 4), kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6)); break; case H_RTAS: if (list_empty(&vcpu->kvm->arch.rtas_tokens)) return RESUME_HOST; idx = srcu_read_lock(&vcpu->kvm->srcu); rc = kvmppc_rtas_hcall(vcpu); srcu_read_unlock(&vcpu->kvm->srcu, idx); if (rc == -ENOENT) return RESUME_HOST; else if (rc == 0) break; /* Send the error out to userspace via KVM_RUN */ return rc; case H_SET_MODE: ret = kvmppc_h_set_mode(vcpu, kvmppc_get_gpr(vcpu, 4), kvmppc_get_gpr(vcpu, 5), kvmppc_get_gpr(vcpu, 6), kvmppc_get_gpr(vcpu, 7)); if (ret == H_TOO_HARD) return RESUME_HOST; break; case H_XIRR: case H_CPPR: case H_EOI: case H_IPI: case H_IPOLL: case H_XIRR_X: if (kvmppc_xics_enabled(vcpu)) { ret = kvmppc_xics_hcall(vcpu, req); break; } /* fallthrough */ default: return RESUME_HOST; } kvmppc_set_gpr(vcpu, 3, ret); vcpu->arch.hcall_needed = 0; return RESUME_GUEST; } static int kvmppc_hcall_impl_hv(unsigned long cmd) { switch (cmd) { case H_CEDE: case H_PROD: case H_CONFER: case H_REGISTER_VPA: case H_SET_MODE: #ifdef CONFIG_KVM_XICS case H_XIRR: case H_CPPR: case H_EOI: case H_IPI: case H_IPOLL: case H_XIRR_X: #endif return 1; } /* See if it's in the real-mode table */ return kvmppc_hcall_impl_hv_realmode(cmd); } static int kvmppc_emulate_debug_inst(struct kvm_run *run, struct kvm_vcpu *vcpu) { u32 last_inst; if (kvmppc_get_last_inst(vcpu, INST_GENERIC, &last_inst) != EMULATE_DONE) { /* * Fetch failed, so return to guest and * try executing it again. */ return RESUME_GUEST; } if (last_inst == KVMPPC_INST_SW_BREAKPOINT) { run->exit_reason = KVM_EXIT_DEBUG; run->debug.arch.address = kvmppc_get_pc(vcpu); return RESUME_HOST; } else { kvmppc_core_queue_program(vcpu, SRR1_PROGILL); return RESUME_GUEST; } } static int kvmppc_handle_exit_hv(struct kvm_run *run, struct kvm_vcpu *vcpu, struct task_struct *tsk) { int r = RESUME_HOST; vcpu->stat.sum_exits++; run->exit_reason = KVM_EXIT_UNKNOWN; run->ready_for_interrupt_injection = 1; switch (vcpu->arch.trap) { /* We're good on these - the host merely wanted to get our attention */ case BOOK3S_INTERRUPT_HV_DECREMENTER: vcpu->stat.dec_exits++; r = RESUME_GUEST; break; case BOOK3S_INTERRUPT_EXTERNAL: case BOOK3S_INTERRUPT_H_DOORBELL: vcpu->stat.ext_intr_exits++; r = RESUME_GUEST; break; case BOOK3S_INTERRUPT_PERFMON: r = RESUME_GUEST; break; case BOOK3S_INTERRUPT_MACHINE_CHECK: /* * Deliver a machine check interrupt to the guest. * We have to do this, even if the host has handled the * machine check, because machine checks use SRR0/1 and * the interrupt might have trashed guest state in them. */ kvmppc_book3s_queue_irqprio(vcpu, BOOK3S_INTERRUPT_MACHINE_CHECK); r = RESUME_GUEST; break; case BOOK3S_INTERRUPT_PROGRAM: { ulong flags; /* * Normally program interrupts are delivered directly * to the guest by the hardware, but we can get here * as a result of a hypervisor emulation interrupt * (e40) getting turned into a 700 by BML RTAS. */ flags = vcpu->arch.shregs.msr & 0x1f0000ull; kvmppc_core_queue_program(vcpu, flags); r = RESUME_GUEST; break; } case BOOK3S_INTERRUPT_SYSCALL: { /* hcall - punt to userspace */ int i; /* hypercall with MSR_PR has already been handled in rmode, * and never reaches here. */ run->papr_hcall.nr = kvmppc_get_gpr(vcpu, 3); for (i = 0; i < 9; ++i) run->papr_hcall.args[i] = kvmppc_get_gpr(vcpu, 4 + i); run->exit_reason = KVM_EXIT_PAPR_HCALL; vcpu->arch.hcall_needed = 1; r = RESUME_HOST; break; } /* * We get these next two if the guest accesses a page which it thinks * it has mapped but which is not actually present, either because * it is for an emulated I/O device or because the corresonding * host page has been paged out. Any other HDSI/HISI interrupts * have been handled already. */ case BOOK3S_INTERRUPT_H_DATA_STORAGE: r = RESUME_PAGE_FAULT; break; case BOOK3S_INTERRUPT_H_INST_STORAGE: vcpu->arch.fault_dar = kvmppc_get_pc(vcpu); vcpu->arch.fault_dsisr = 0; r = RESUME_PAGE_FAULT; break; /* * This occurs if the guest executes an illegal instruction. * If the guest debug is disabled, generate a program interrupt * to the guest. If guest debug is enabled, we need to check * whether the instruction is a software breakpoint instruction. * Accordingly return to Guest or Host. */ case BOOK3S_INTERRUPT_H_EMUL_ASSIST: if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) { r = kvmppc_emulate_debug_inst(run, vcpu); } else { kvmppc_core_queue_program(vcpu, SRR1_PROGILL); r = RESUME_GUEST; } break; /* * This occurs if the guest (kernel or userspace), does something that * is prohibited by HFSCR. We just generate a program interrupt to * the guest. */ case BOOK3S_INTERRUPT_H_FAC_UNAVAIL: kvmppc_core_queue_program(vcpu, SRR1_PROGILL); r = RESUME_GUEST; break; default: kvmppc_dump_regs(vcpu); printk(KERN_EMERG "trap=0x%x | pc=0x%lx | msr=0x%llx\n", vcpu->arch.trap, kvmppc_get_pc(vcpu), vcpu->arch.shregs.msr); run->hw.hardware_exit_reason = vcpu->arch.trap; r = RESUME_HOST; break; } return r; } static int kvm_arch_vcpu_ioctl_get_sregs_hv(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { int i; memset(sregs, 0, sizeof(struct kvm_sregs)); sregs->pvr = vcpu->arch.pvr; for (i = 0; i < vcpu->arch.slb_max; i++) { sregs->u.s.ppc64.slb[i].slbe = vcpu->arch.slb[i].orige; sregs->u.s.ppc64.slb[i].slbv = vcpu->arch.slb[i].origv; } return 0; } static int kvm_arch_vcpu_ioctl_set_sregs_hv(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { int i, j; /* Only accept the same PVR as the host's, since we can't spoof it */ if (sregs->pvr != vcpu->arch.pvr) return -EINVAL; j = 0; for (i = 0; i < vcpu->arch.slb_nr; i++) { if (sregs->u.s.ppc64.slb[i].slbe & SLB_ESID_V) { vcpu->arch.slb[j].orige = sregs->u.s.ppc64.slb[i].slbe; vcpu->arch.slb[j].origv = sregs->u.s.ppc64.slb[i].slbv; ++j; } } vcpu->arch.slb_max = j; return 0; } static void kvmppc_set_lpcr(struct kvm_vcpu *vcpu, u64 new_lpcr, bool preserve_top32) { struct kvmppc_vcore *vc = vcpu->arch.vcore; u64 mask; spin_lock(&vc->lock); /* * If ILE (interrupt little-endian) has changed, update the * MSR_LE bit in the intr_msr for each vcpu in this vcore. */ if ((new_lpcr & LPCR_ILE) != (vc->lpcr & LPCR_ILE)) { struct kvm *kvm = vcpu->kvm; struct kvm_vcpu *vcpu; int i; mutex_lock(&kvm->lock); kvm_for_each_vcpu(i, vcpu, kvm) { if (vcpu->arch.vcore != vc) continue; if (new_lpcr & LPCR_ILE) vcpu->arch.intr_msr |= MSR_LE; else vcpu->arch.intr_msr &= ~MSR_LE; } mutex_unlock(&kvm->lock); } /* * Userspace can only modify DPFD (default prefetch depth), * ILE (interrupt little-endian) and TC (translation control). * On POWER8 userspace can also modify AIL (alt. interrupt loc.) */ mask = LPCR_DPFD | LPCR_ILE | LPCR_TC; if (cpu_has_feature(CPU_FTR_ARCH_207S)) mask |= LPCR_AIL; /* Broken 32-bit version of LPCR must not clear top bits */ if (preserve_top32) mask &= 0xFFFFFFFF; vc->lpcr = (vc->lpcr & ~mask) | (new_lpcr & mask); spin_unlock(&vc->lock); } static int kvmppc_get_one_reg_hv(struct kvm_vcpu *vcpu, u64 id, union kvmppc_one_reg *val) { int r = 0; long int i; switch (id) { case KVM_REG_PPC_DEBUG_INST: *val = get_reg_val(id, KVMPPC_INST_SW_BREAKPOINT); break; case KVM_REG_PPC_HIOR: *val = get_reg_val(id, 0); break; case KVM_REG_PPC_DABR: *val = get_reg_val(id, vcpu->arch.dabr); break; case KVM_REG_PPC_DABRX: *val = get_reg_val(id, vcpu->arch.dabrx); break; case KVM_REG_PPC_DSCR: *val = get_reg_val(id, vcpu->arch.dscr); break; case KVM_REG_PPC_PURR: *val = get_reg_val(id, vcpu->arch.purr); break; case KVM_REG_PPC_SPURR: *val = get_reg_val(id, vcpu->arch.spurr); break; case KVM_REG_PPC_AMR: *val = get_reg_val(id, vcpu->arch.amr); break; case KVM_REG_PPC_UAMOR: *val = get_reg_val(id, vcpu->arch.uamor); break; case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS: i = id - KVM_REG_PPC_MMCR0; *val = get_reg_val(id, vcpu->arch.mmcr[i]); break; case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8: i = id - KVM_REG_PPC_PMC1; *val = get_reg_val(id, vcpu->arch.pmc[i]); break; case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2: i = id - KVM_REG_PPC_SPMC1; *val = get_reg_val(id, vcpu->arch.spmc[i]); break; case KVM_REG_PPC_SIAR: *val = get_reg_val(id, vcpu->arch.siar); break; case KVM_REG_PPC_SDAR: *val = get_reg_val(id, vcpu->arch.sdar); break; case KVM_REG_PPC_SIER: *val = get_reg_val(id, vcpu->arch.sier); break; case KVM_REG_PPC_IAMR: *val = get_reg_val(id, vcpu->arch.iamr); break; case KVM_REG_PPC_PSPB: *val = get_reg_val(id, vcpu->arch.pspb); break; case KVM_REG_PPC_DPDES: *val = get_reg_val(id, vcpu->arch.vcore->dpdes); break; case KVM_REG_PPC_DAWR: *val = get_reg_val(id, vcpu->arch.dawr); break; case KVM_REG_PPC_DAWRX: *val = get_reg_val(id, vcpu->arch.dawrx); break; case KVM_REG_PPC_CIABR: *val = get_reg_val(id, vcpu->arch.ciabr); break; case KVM_REG_PPC_CSIGR: *val = get_reg_val(id, vcpu->arch.csigr); break; case KVM_REG_PPC_TACR: *val = get_reg_val(id, vcpu->arch.tacr); break; case KVM_REG_PPC_TCSCR: *val = get_reg_val(id, vcpu->arch.tcscr); break; case KVM_REG_PPC_PID: *val = get_reg_val(id, vcpu->arch.pid); break; case KVM_REG_PPC_ACOP: *val = get_reg_val(id, vcpu->arch.acop); break; case KVM_REG_PPC_WORT: *val = get_reg_val(id, vcpu->arch.wort); break; case KVM_REG_PPC_VPA_ADDR: spin_lock(&vcpu->arch.vpa_update_lock); *val = get_reg_val(id, vcpu->arch.vpa.next_gpa); spin_unlock(&vcpu->arch.vpa_update_lock); break; case KVM_REG_PPC_VPA_SLB: spin_lock(&vcpu->arch.vpa_update_lock); val->vpaval.addr = vcpu->arch.slb_shadow.next_gpa; val->vpaval.length = vcpu->arch.slb_shadow.len; spin_unlock(&vcpu->arch.vpa_update_lock); break; case KVM_REG_PPC_VPA_DTL: spin_lock(&vcpu->arch.vpa_update_lock); val->vpaval.addr = vcpu->arch.dtl.next_gpa; val->vpaval.length = vcpu->arch.dtl.len; spin_unlock(&vcpu->arch.vpa_update_lock); break; case KVM_REG_PPC_TB_OFFSET: *val = get_reg_val(id, vcpu->arch.vcore->tb_offset); break; case KVM_REG_PPC_LPCR: case KVM_REG_PPC_LPCR_64: *val = get_reg_val(id, vcpu->arch.vcore->lpcr); break; case KVM_REG_PPC_PPR: *val = get_reg_val(id, vcpu->arch.ppr); break; #ifdef CONFIG_PPC_TRANSACTIONAL_MEM case KVM_REG_PPC_TFHAR: *val = get_reg_val(id, vcpu->arch.tfhar); break; case KVM_REG_PPC_TFIAR: *val = get_reg_val(id, vcpu->arch.tfiar); break; case KVM_REG_PPC_TEXASR: *val = get_reg_val(id, vcpu->arch.texasr); break; case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31: i = id - KVM_REG_PPC_TM_GPR0; *val = get_reg_val(id, vcpu->arch.gpr_tm[i]); break; case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63: { int j; i = id - KVM_REG_PPC_TM_VSR0; if (i < 32) for (j = 0; j < TS_FPRWIDTH; j++) val->vsxval[j] = vcpu->arch.fp_tm.fpr[i][j]; else { if (cpu_has_feature(CPU_FTR_ALTIVEC)) val->vval = vcpu->arch.vr_tm.vr[i-32]; else r = -ENXIO; } break; } case KVM_REG_PPC_TM_CR: *val = get_reg_val(id, vcpu->arch.cr_tm); break; case KVM_REG_PPC_TM_LR: *val = get_reg_val(id, vcpu->arch.lr_tm); break; case KVM_REG_PPC_TM_CTR: *val = get_reg_val(id, vcpu->arch.ctr_tm); break; case KVM_REG_PPC_TM_FPSCR: *val = get_reg_val(id, vcpu->arch.fp_tm.fpscr); break; case KVM_REG_PPC_TM_AMR: *val = get_reg_val(id, vcpu->arch.amr_tm); break; case KVM_REG_PPC_TM_PPR: *val = get_reg_val(id, vcpu->arch.ppr_tm); break; case KVM_REG_PPC_TM_VRSAVE: *val = get_reg_val(id, vcpu->arch.vrsave_tm); break; case KVM_REG_PPC_TM_VSCR: if (cpu_has_feature(CPU_FTR_ALTIVEC)) *val = get_reg_val(id, vcpu->arch.vr_tm.vscr.u[3]); else r = -ENXIO; break; case KVM_REG_PPC_TM_DSCR: *val = get_reg_val(id, vcpu->arch.dscr_tm); break; case KVM_REG_PPC_TM_TAR: *val = get_reg_val(id, vcpu->arch.tar_tm); break; #endif case KVM_REG_PPC_ARCH_COMPAT: *val = get_reg_val(id, vcpu->arch.vcore->arch_compat); break; default: r = -EINVAL; break; } return r; } static int kvmppc_set_one_reg_hv(struct kvm_vcpu *vcpu, u64 id, union kvmppc_one_reg *val) { int r = 0; long int i; unsigned long addr, len; switch (id) { case KVM_REG_PPC_HIOR: /* Only allow this to be set to zero */ if (set_reg_val(id, *val)) r = -EINVAL; break; case KVM_REG_PPC_DABR: vcpu->arch.dabr = set_reg_val(id, *val); break; case KVM_REG_PPC_DABRX: vcpu->arch.dabrx = set_reg_val(id, *val) & ~DABRX_HYP; break; case KVM_REG_PPC_DSCR: vcpu->arch.dscr = set_reg_val(id, *val); break; case KVM_REG_PPC_PURR: vcpu->arch.purr = set_reg_val(id, *val); break; case KVM_REG_PPC_SPURR: vcpu->arch.spurr = set_reg_val(id, *val); break; case KVM_REG_PPC_AMR: vcpu->arch.amr = set_reg_val(id, *val); break; case KVM_REG_PPC_UAMOR: vcpu->arch.uamor = set_reg_val(id, *val); break; case KVM_REG_PPC_MMCR0 ... KVM_REG_PPC_MMCRS: i = id - KVM_REG_PPC_MMCR0; vcpu->arch.mmcr[i] = set_reg_val(id, *val); break; case KVM_REG_PPC_PMC1 ... KVM_REG_PPC_PMC8: i = id - KVM_REG_PPC_PMC1; vcpu->arch.pmc[i] = set_reg_val(id, *val); break; case KVM_REG_PPC_SPMC1 ... KVM_REG_PPC_SPMC2: i = id - KVM_REG_PPC_SPMC1; vcpu->arch.spmc[i] = set_reg_val(id, *val); break; case KVM_REG_PPC_SIAR: vcpu->arch.siar = set_reg_val(id, *val); break; case KVM_REG_PPC_SDAR: vcpu->arch.sdar = set_reg_val(id, *val); break; case KVM_REG_PPC_SIER: vcpu->arch.sier = set_reg_val(id, *val); break; case KVM_REG_PPC_IAMR: vcpu->arch.iamr = set_reg_val(id, *val); break; case KVM_REG_PPC_PSPB: vcpu->arch.pspb = set_reg_val(id, *val); break; case KVM_REG_PPC_DPDES: vcpu->arch.vcore->dpdes = set_reg_val(id, *val); break; case KVM_REG_PPC_DAWR: vcpu->arch.dawr = set_reg_val(id, *val); break; case KVM_REG_PPC_DAWRX: vcpu->arch.dawrx = set_reg_val(id, *val) & ~DAWRX_HYP; break; case KVM_REG_PPC_CIABR: vcpu->arch.ciabr = set_reg_val(id, *val); /* Don't allow setting breakpoints in hypervisor code */ if ((vcpu->arch.ciabr & CIABR_PRIV) == CIABR_PRIV_HYPER) vcpu->arch.ciabr &= ~CIABR_PRIV; /* disable */ break; case KVM_REG_PPC_CSIGR: vcpu->arch.csigr = set_reg_val(id, *val); break; case KVM_REG_PPC_TACR: vcpu->arch.tacr = set_reg_val(id, *val); break; case KVM_REG_PPC_TCSCR: vcpu->arch.tcscr = set_reg_val(id, *val); break; case KVM_REG_PPC_PID: vcpu->arch.pid = set_reg_val(id, *val); break; case KVM_REG_PPC_ACOP: vcpu->arch.acop = set_reg_val(id, *val); break; case KVM_REG_PPC_WORT: vcpu->arch.wort = set_reg_val(id, *val); break; case KVM_REG_PPC_VPA_ADDR: addr = set_reg_val(id, *val); r = -EINVAL; if (!addr && (vcpu->arch.slb_shadow.next_gpa || vcpu->arch.dtl.next_gpa)) break; r = set_vpa(vcpu, &vcpu->arch.vpa, addr, sizeof(struct lppaca)); break; case KVM_REG_PPC_VPA_SLB: addr = val->vpaval.addr; len = val->vpaval.length; r = -EINVAL; if (addr && !vcpu->arch.vpa.next_gpa) break; r = set_vpa(vcpu, &vcpu->arch.slb_shadow, addr, len); break; case KVM_REG_PPC_VPA_DTL: addr = val->vpaval.addr; len = val->vpaval.length; r = -EINVAL; if (addr && (len < sizeof(struct dtl_entry) || !vcpu->arch.vpa.next_gpa)) break; len -= len % sizeof(struct dtl_entry); r = set_vpa(vcpu, &vcpu->arch.dtl, addr, len); break; case KVM_REG_PPC_TB_OFFSET: /* round up to multiple of 2^24 */ vcpu->arch.vcore->tb_offset = ALIGN(set_reg_val(id, *val), 1UL << 24); break; case KVM_REG_PPC_LPCR: kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), true); break; case KVM_REG_PPC_LPCR_64: kvmppc_set_lpcr(vcpu, set_reg_val(id, *val), false); break; case KVM_REG_PPC_PPR: vcpu->arch.ppr = set_reg_val(id, *val); break; #ifdef CONFIG_PPC_TRANSACTIONAL_MEM case KVM_REG_PPC_TFHAR: vcpu->arch.tfhar = set_reg_val(id, *val); break; case KVM_REG_PPC_TFIAR: vcpu->arch.tfiar = set_reg_val(id, *val); break; case KVM_REG_PPC_TEXASR: vcpu->arch.texasr = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_GPR0 ... KVM_REG_PPC_TM_GPR31: i = id - KVM_REG_PPC_TM_GPR0; vcpu->arch.gpr_tm[i] = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_VSR0 ... KVM_REG_PPC_TM_VSR63: { int j; i = id - KVM_REG_PPC_TM_VSR0; if (i < 32) for (j = 0; j < TS_FPRWIDTH; j++) vcpu->arch.fp_tm.fpr[i][j] = val->vsxval[j]; else if (cpu_has_feature(CPU_FTR_ALTIVEC)) vcpu->arch.vr_tm.vr[i-32] = val->vval; else r = -ENXIO; break; } case KVM_REG_PPC_TM_CR: vcpu->arch.cr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_LR: vcpu->arch.lr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_CTR: vcpu->arch.ctr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_FPSCR: vcpu->arch.fp_tm.fpscr = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_AMR: vcpu->arch.amr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_PPR: vcpu->arch.ppr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_VRSAVE: vcpu->arch.vrsave_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_VSCR: if (cpu_has_feature(CPU_FTR_ALTIVEC)) vcpu->arch.vr.vscr.u[3] = set_reg_val(id, *val); else r = - ENXIO; break; case KVM_REG_PPC_TM_DSCR: vcpu->arch.dscr_tm = set_reg_val(id, *val); break; case KVM_REG_PPC_TM_TAR: vcpu->arch.tar_tm = set_reg_val(id, *val); break; #endif case KVM_REG_PPC_ARCH_COMPAT: r = kvmppc_set_arch_compat(vcpu, set_reg_val(id, *val)); break; default: r = -EINVAL; break; } return r; } static struct kvmppc_vcore *kvmppc_vcore_create(struct kvm *kvm, int core) { struct kvmppc_vcore *vcore; vcore = kzalloc(sizeof(struct kvmppc_vcore), GFP_KERNEL); if (vcore == NULL) return NULL; INIT_LIST_HEAD(&vcore->runnable_threads); spin_lock_init(&vcore->lock); init_waitqueue_head(&vcore->wq); vcore->preempt_tb = TB_NIL; vcore->lpcr = kvm->arch.lpcr; vcore->first_vcpuid = core * threads_per_subcore; vcore->kvm = kvm; vcore->mpp_buffer_is_valid = false; if (cpu_has_feature(CPU_FTR_ARCH_207S)) vcore->mpp_buffer = (void *)__get_free_pages( GFP_KERNEL|__GFP_ZERO, MPP_BUFFER_ORDER); return vcore; } static struct kvm_vcpu *kvmppc_core_vcpu_create_hv(struct kvm *kvm, unsigned int id) { struct kvm_vcpu *vcpu; int err = -EINVAL; int core; struct kvmppc_vcore *vcore; core = id / threads_per_subcore; if (core >= KVM_MAX_VCORES) goto out; err = -ENOMEM; vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL); if (!vcpu) goto out; err = kvm_vcpu_init(vcpu, kvm, id); if (err) goto free_vcpu; vcpu->arch.shared = &vcpu->arch.shregs; #ifdef CONFIG_KVM_BOOK3S_PR_POSSIBLE /* * The shared struct is never shared on HV, * so we can always use host endianness */ #ifdef __BIG_ENDIAN__ vcpu->arch.shared_big_endian = true; #else vcpu->arch.shared_big_endian = false; #endif #endif vcpu->arch.mmcr[0] = MMCR0_FC; vcpu->arch.ctrl = CTRL_RUNLATCH; /* default to host PVR, since we can't spoof it */ kvmppc_set_pvr_hv(vcpu, mfspr(SPRN_PVR)); spin_lock_init(&vcpu->arch.vpa_update_lock); spin_lock_init(&vcpu->arch.tbacct_lock); vcpu->arch.busy_preempt = TB_NIL; vcpu->arch.intr_msr = MSR_SF | MSR_ME; kvmppc_mmu_book3s_hv_init(vcpu); vcpu->arch.state = KVMPPC_VCPU_NOTREADY; init_waitqueue_head(&vcpu->arch.cpu_run); mutex_lock(&kvm->lock); vcore = kvm->arch.vcores[core]; if (!vcore) { vcore = kvmppc_vcore_create(kvm, core); kvm->arch.vcores[core] = vcore; kvm->arch.online_vcores++; } mutex_unlock(&kvm->lock); if (!vcore) goto free_vcpu; spin_lock(&vcore->lock); ++vcore->num_threads; spin_unlock(&vcore->lock); vcpu->arch.vcore = vcore; vcpu->arch.ptid = vcpu->vcpu_id - vcore->first_vcpuid; vcpu->arch.cpu_type = KVM_CPU_3S_64; kvmppc_sanity_check(vcpu); return vcpu; free_vcpu: kmem_cache_free(kvm_vcpu_cache, vcpu); out: return ERR_PTR(err); } static void unpin_vpa(struct kvm *kvm, struct kvmppc_vpa *vpa) { if (vpa->pinned_addr) kvmppc_unpin_guest_page(kvm, vpa->pinned_addr, vpa->gpa, vpa->dirty); } static void kvmppc_core_vcpu_free_hv(struct kvm_vcpu *vcpu) { spin_lock(&vcpu->arch.vpa_update_lock); unpin_vpa(vcpu->kvm, &vcpu->arch.dtl); unpin_vpa(vcpu->kvm, &vcpu->arch.slb_shadow); unpin_vpa(vcpu->kvm, &vcpu->arch.vpa); spin_unlock(&vcpu->arch.vpa_update_lock); kvm_vcpu_uninit(vcpu); kmem_cache_free(kvm_vcpu_cache, vcpu); } static int kvmppc_core_check_requests_hv(struct kvm_vcpu *vcpu) { /* Indicate we want to get back into the guest */ return 1; } static void kvmppc_set_timer(struct kvm_vcpu *vcpu) { unsigned long dec_nsec, now; now = get_tb(); if (now > vcpu->arch.dec_expires) { /* decrementer has already gone negative */ kvmppc_core_queue_dec(vcpu); kvmppc_core_prepare_to_enter(vcpu); return; } dec_nsec = (vcpu->arch.dec_expires - now) * NSEC_PER_SEC / tb_ticks_per_sec; hrtimer_start(&vcpu->arch.dec_timer, ktime_set(0, dec_nsec), HRTIMER_MODE_REL); vcpu->arch.timer_running = 1; } static void kvmppc_end_cede(struct kvm_vcpu *vcpu) { vcpu->arch.ceded = 0; if (vcpu->arch.timer_running) { hrtimer_try_to_cancel(&vcpu->arch.dec_timer); vcpu->arch.timer_running = 0; } } extern void __kvmppc_vcore_entry(void); static void kvmppc_remove_runnable(struct kvmppc_vcore *vc, struct kvm_vcpu *vcpu) { u64 now; if (vcpu->arch.state != KVMPPC_VCPU_RUNNABLE) return; spin_lock_irq(&vcpu->arch.tbacct_lock); now = mftb(); vcpu->arch.busy_stolen += vcore_stolen_time(vc, now) - vcpu->arch.stolen_logged; vcpu->arch.busy_preempt = now; vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST; spin_unlock_irq(&vcpu->arch.tbacct_lock); --vc->n_runnable; list_del(&vcpu->arch.run_list); } static int kvmppc_grab_hwthread(int cpu) { struct paca_struct *tpaca; long timeout = 10000; tpaca = &paca[cpu]; /* Ensure the thread won't go into the kernel if it wakes */ tpaca->kvm_hstate.hwthread_req = 1; tpaca->kvm_hstate.kvm_vcpu = NULL; /* * If the thread is already executing in the kernel (e.g. handling * a stray interrupt), wait for it to get back to nap mode. * The smp_mb() is to ensure that our setting of hwthread_req * is visible before we look at hwthread_state, so if this * races with the code at system_reset_pSeries and the thread * misses our setting of hwthread_req, we are sure to see its * setting of hwthread_state, and vice versa. */ smp_mb(); while (tpaca->kvm_hstate.hwthread_state == KVM_HWTHREAD_IN_KERNEL) { if (--timeout <= 0) { pr_err("KVM: couldn't grab cpu %d\n", cpu); return -EBUSY; } udelay(1); } return 0; } static void kvmppc_release_hwthread(int cpu) { struct paca_struct *tpaca; tpaca = &paca[cpu]; tpaca->kvm_hstate.hwthread_req = 0; tpaca->kvm_hstate.kvm_vcpu = NULL; } static void kvmppc_start_thread(struct kvm_vcpu *vcpu) { int cpu; struct paca_struct *tpaca; struct kvmppc_vcore *vc = vcpu->arch.vcore; if (vcpu->arch.timer_running) { hrtimer_try_to_cancel(&vcpu->arch.dec_timer); vcpu->arch.timer_running = 0; } cpu = vc->pcpu + vcpu->arch.ptid; tpaca = &paca[cpu]; tpaca->kvm_hstate.kvm_vcpu = vcpu; tpaca->kvm_hstate.kvm_vcore = vc; tpaca->kvm_hstate.ptid = vcpu->arch.ptid; vcpu->cpu = vc->pcpu; smp_wmb(); #if defined(CONFIG_PPC_ICP_NATIVE) && defined(CONFIG_SMP) if (cpu != smp_processor_id()) { xics_wake_cpu(cpu); if (vcpu->arch.ptid) ++vc->n_woken; } #endif } static void kvmppc_wait_for_nap(struct kvmppc_vcore *vc) { int i; HMT_low(); i = 0; while (vc->nap_count < vc->n_woken) { if (++i >= 1000000) { pr_err("kvmppc_wait_for_nap timeout %d %d\n", vc->nap_count, vc->n_woken); break; } cpu_relax(); } HMT_medium(); } /* * Check that we are on thread 0 and that any other threads in * this core are off-line. Then grab the threads so they can't * enter the kernel. */ static int on_primary_thread(void) { int cpu = smp_processor_id(); int thr; /* Are we on a primary subcore? */ if (cpu_thread_in_subcore(cpu)) return 0; thr = 0; while (++thr < threads_per_subcore) if (cpu_online(cpu + thr)) return 0; /* Grab all hw threads so they can't go into the kernel */ for (thr = 1; thr < threads_per_subcore; ++thr) { if (kvmppc_grab_hwthread(cpu + thr)) { /* Couldn't grab one; let the others go */ do { kvmppc_release_hwthread(cpu + thr); } while (--thr > 0); return 0; } } return 1; } static void kvmppc_start_saving_l2_cache(struct kvmppc_vcore *vc) { phys_addr_t phy_addr, mpp_addr; phy_addr = (phys_addr_t)virt_to_phys(vc->mpp_buffer); mpp_addr = phy_addr & PPC_MPPE_ADDRESS_MASK; mtspr(SPRN_MPPR, mpp_addr | PPC_MPPR_FETCH_ABORT); logmpp(mpp_addr | PPC_LOGMPP_LOG_L2); vc->mpp_buffer_is_valid = true; } static void kvmppc_start_restoring_l2_cache(const struct kvmppc_vcore *vc) { phys_addr_t phy_addr, mpp_addr; phy_addr = virt_to_phys(vc->mpp_buffer); mpp_addr = phy_addr & PPC_MPPE_ADDRESS_MASK; /* We must abort any in-progress save operations to ensure * the table is valid so that prefetch engine knows when to * stop prefetching. */ logmpp(mpp_addr | PPC_LOGMPP_LOG_ABORT); mtspr(SPRN_MPPR, mpp_addr | PPC_MPPR_FETCH_WHOLE_TABLE); } /* * Run a set of guest threads on a physical core. * Called with vc->lock held. */ static void kvmppc_run_core(struct kvmppc_vcore *vc) { struct kvm_vcpu *vcpu, *vnext; long ret; u64 now; int i, need_vpa_update; int srcu_idx; struct kvm_vcpu *vcpus_to_update[threads_per_core]; /* don't start if any threads have a signal pending */ need_vpa_update = 0; list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) { if (signal_pending(vcpu->arch.run_task)) return; if (vcpu->arch.vpa.update_pending || vcpu->arch.slb_shadow.update_pending || vcpu->arch.dtl.update_pending) vcpus_to_update[need_vpa_update++] = vcpu; } /* * Initialize *vc, in particular vc->vcore_state, so we can * drop the vcore lock if necessary. */ vc->n_woken = 0; vc->nap_count = 0; vc->entry_exit_count = 0; vc->vcore_state = VCORE_STARTING; vc->in_guest = 0; vc->napping_threads = 0; /* * Updating any of the vpas requires calling kvmppc_pin_guest_page, * which can't be called with any spinlocks held. */ if (need_vpa_update) { spin_unlock(&vc->lock); for (i = 0; i < need_vpa_update; ++i) kvmppc_update_vpas(vcpus_to_update[i]); spin_lock(&vc->lock); } /* * Make sure we are running on primary threads, and that secondary * threads are offline. Also check if the number of threads in this * guest are greater than the current system threads per guest. */ if ((threads_per_core > 1) && ((vc->num_threads > threads_per_subcore) || !on_primary_thread())) { list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) vcpu->arch.ret = -EBUSY; goto out; } vc->pcpu = smp_processor_id(); list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) { kvmppc_start_thread(vcpu); kvmppc_create_dtl_entry(vcpu, vc); } /* Set this explicitly in case thread 0 doesn't have a vcpu */ get_paca()->kvm_hstate.kvm_vcore = vc; get_paca()->kvm_hstate.ptid = 0; vc->vcore_state = VCORE_RUNNING; preempt_disable(); spin_unlock(&vc->lock); kvm_guest_enter(); srcu_idx = srcu_read_lock(&vc->kvm->srcu); if (vc->mpp_buffer_is_valid) kvmppc_start_restoring_l2_cache(vc); __kvmppc_vcore_entry(); spin_lock(&vc->lock); if (vc->mpp_buffer) kvmppc_start_saving_l2_cache(vc); /* disable sending of IPIs on virtual external irqs */ list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) vcpu->cpu = -1; /* wait for secondary threads to finish writing their state to memory */ if (vc->nap_count < vc->n_woken) kvmppc_wait_for_nap(vc); for (i = 0; i < threads_per_subcore; ++i) kvmppc_release_hwthread(vc->pcpu + i); /* prevent other vcpu threads from doing kvmppc_start_thread() now */ vc->vcore_state = VCORE_EXITING; spin_unlock(&vc->lock); srcu_read_unlock(&vc->kvm->srcu, srcu_idx); /* make sure updates to secondary vcpu structs are visible now */ smp_mb(); kvm_guest_exit(); preempt_enable(); cond_resched(); spin_lock(&vc->lock); now = get_tb(); list_for_each_entry(vcpu, &vc->runnable_threads, arch.run_list) { /* cancel pending dec exception if dec is positive */ if (now < vcpu->arch.dec_expires && kvmppc_core_pending_dec(vcpu)) kvmppc_core_dequeue_dec(vcpu); ret = RESUME_GUEST; if (vcpu->arch.trap) ret = kvmppc_handle_exit_hv(vcpu->arch.kvm_run, vcpu, vcpu->arch.run_task); vcpu->arch.ret = ret; vcpu->arch.trap = 0; if (vcpu->arch.ceded) { if (!is_kvmppc_resume_guest(ret)) kvmppc_end_cede(vcpu); else kvmppc_set_timer(vcpu); } } out: vc->vcore_state = VCORE_INACTIVE; list_for_each_entry_safe(vcpu, vnext, &vc->runnable_threads, arch.run_list) { if (!is_kvmppc_resume_guest(vcpu->arch.ret)) { kvmppc_remove_runnable(vc, vcpu); wake_up(&vcpu->arch.cpu_run); } } } /* * Wait for some other vcpu thread to execute us, and * wake us up when we need to handle something in the host. */ static void kvmppc_wait_for_exec(struct kvm_vcpu *vcpu, int wait_state) { DEFINE_WAIT(wait); prepare_to_wait(&vcpu->arch.cpu_run, &wait, wait_state); if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) schedule(); finish_wait(&vcpu->arch.cpu_run, &wait); } /* * All the vcpus in this vcore are idle, so wait for a decrementer * or external interrupt to one of the vcpus. vc->lock is held. */ static void kvmppc_vcore_blocked(struct kvmppc_vcore *vc) { DEFINE_WAIT(wait); prepare_to_wait(&vc->wq, &wait, TASK_INTERRUPTIBLE); vc->vcore_state = VCORE_SLEEPING; spin_unlock(&vc->lock); schedule(); finish_wait(&vc->wq, &wait); spin_lock(&vc->lock); vc->vcore_state = VCORE_INACTIVE; } static int kvmppc_run_vcpu(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu) { int n_ceded; struct kvmppc_vcore *vc; struct kvm_vcpu *v, *vn; kvm_run->exit_reason = 0; vcpu->arch.ret = RESUME_GUEST; vcpu->arch.trap = 0; kvmppc_update_vpas(vcpu); /* * Synchronize with other threads in this virtual core */ vc = vcpu->arch.vcore; spin_lock(&vc->lock); vcpu->arch.ceded = 0; vcpu->arch.run_task = current; vcpu->arch.kvm_run = kvm_run; vcpu->arch.stolen_logged = vcore_stolen_time(vc, mftb()); vcpu->arch.state = KVMPPC_VCPU_RUNNABLE; vcpu->arch.busy_preempt = TB_NIL; list_add_tail(&vcpu->arch.run_list, &vc->runnable_threads); ++vc->n_runnable; /* * This happens the first time this is called for a vcpu. * If the vcore is already running, we may be able to start * this thread straight away and have it join in. */ if (!signal_pending(current)) { if (vc->vcore_state == VCORE_RUNNING && VCORE_EXIT_COUNT(vc) == 0) { kvmppc_create_dtl_entry(vcpu, vc); kvmppc_start_thread(vcpu); } else if (vc->vcore_state == VCORE_SLEEPING) { wake_up(&vc->wq); } } while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE && !signal_pending(current)) { if (vc->vcore_state != VCORE_INACTIVE) { spin_unlock(&vc->lock); kvmppc_wait_for_exec(vcpu, TASK_INTERRUPTIBLE); spin_lock(&vc->lock); continue; } list_for_each_entry_safe(v, vn, &vc->runnable_threads, arch.run_list) { kvmppc_core_prepare_to_enter(v); if (signal_pending(v->arch.run_task)) { kvmppc_remove_runnable(vc, v); v->stat.signal_exits++; v->arch.kvm_run->exit_reason = KVM_EXIT_INTR; v->arch.ret = -EINTR; wake_up(&v->arch.cpu_run); } } if (!vc->n_runnable || vcpu->arch.state != KVMPPC_VCPU_RUNNABLE) break; vc->runner = vcpu; n_ceded = 0; list_for_each_entry(v, &vc->runnable_threads, arch.run_list) { if (!v->arch.pending_exceptions) n_ceded += v->arch.ceded; else v->arch.ceded = 0; } if (n_ceded == vc->n_runnable) kvmppc_vcore_blocked(vc); else kvmppc_run_core(vc); vc->runner = NULL; } while (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE && (vc->vcore_state == VCORE_RUNNING || vc->vcore_state == VCORE_EXITING)) { spin_unlock(&vc->lock); kvmppc_wait_for_exec(vcpu, TASK_UNINTERRUPTIBLE); spin_lock(&vc->lock); } if (vcpu->arch.state == KVMPPC_VCPU_RUNNABLE) { kvmppc_remove_runnable(vc, vcpu); vcpu->stat.signal_exits++; kvm_run->exit_reason = KVM_EXIT_INTR; vcpu->arch.ret = -EINTR; } if (vc->n_runnable && vc->vcore_state == VCORE_INACTIVE) { /* Wake up some vcpu to run the core */ v = list_first_entry(&vc->runnable_threads, struct kvm_vcpu, arch.run_list); wake_up(&v->arch.cpu_run); } spin_unlock(&vc->lock); return vcpu->arch.ret; } static int kvmppc_vcpu_run_hv(struct kvm_run *run, struct kvm_vcpu *vcpu) { int r; int srcu_idx; if (!vcpu->arch.sane) { run->exit_reason = KVM_EXIT_INTERNAL_ERROR; return -EINVAL; } kvmppc_core_prepare_to_enter(vcpu); /* No need to go into the guest when all we'll do is come back out */ if (signal_pending(current)) { run->exit_reason = KVM_EXIT_INTR; return -EINTR; } atomic_inc(&vcpu->kvm->arch.vcpus_running); /* Order vcpus_running vs. rma_setup_done, see kvmppc_alloc_reset_hpt */ smp_mb(); /* On the first time here, set up HTAB and VRMA or RMA */ if (!vcpu->kvm->arch.rma_setup_done) { r = kvmppc_hv_setup_htab_rma(vcpu); if (r) goto out; } flush_fp_to_thread(current); flush_altivec_to_thread(current); flush_vsx_to_thread(current); vcpu->arch.wqp = &vcpu->arch.vcore->wq; vcpu->arch.pgdir = current->mm->pgd; vcpu->arch.state = KVMPPC_VCPU_BUSY_IN_HOST; do { r = kvmppc_run_vcpu(run, vcpu); if (run->exit_reason == KVM_EXIT_PAPR_HCALL && !(vcpu->arch.shregs.msr & MSR_PR)) { r = kvmppc_pseries_do_hcall(vcpu); kvmppc_core_prepare_to_enter(vcpu); } else if (r == RESUME_PAGE_FAULT) { srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); r = kvmppc_book3s_hv_page_fault(run, vcpu, vcpu->arch.fault_dar, vcpu->arch.fault_dsisr); srcu_read_unlock(&vcpu->kvm->srcu, srcu_idx); } } while (is_kvmppc_resume_guest(r)); out: vcpu->arch.state = KVMPPC_VCPU_NOTREADY; atomic_dec(&vcpu->kvm->arch.vcpus_running); return r; } /* Work out RMLS (real mode limit selector) field value for a given RMA size. Assumes POWER7 or PPC970. */ static inline int lpcr_rmls(unsigned long rma_size) { switch (rma_size) { case 32ul << 20: /* 32 MB */ if (cpu_has_feature(CPU_FTR_ARCH_206)) return 8; /* only supported on POWER7 */ return -1; case 64ul << 20: /* 64 MB */ return 3; case 128ul << 20: /* 128 MB */ return 7; case 256ul << 20: /* 256 MB */ return 4; case 1ul << 30: /* 1 GB */ return 2; case 16ul << 30: /* 16 GB */ return 1; case 256ul << 30: /* 256 GB */ return 0; default: return -1; } } static int kvm_rma_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page; struct kvm_rma_info *ri = vma->vm_file->private_data; if (vmf->pgoff >= kvm_rma_pages) return VM_FAULT_SIGBUS; page = pfn_to_page(ri->base_pfn + vmf->pgoff); get_page(page); vmf->page = page; return 0; } static const struct vm_operations_struct kvm_rma_vm_ops = { .fault = kvm_rma_fault, }; static int kvm_rma_mmap(struct file *file, struct vm_area_struct *vma) { vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP; vma->vm_ops = &kvm_rma_vm_ops; return 0; } static int kvm_rma_release(struct inode *inode, struct file *filp) { struct kvm_rma_info *ri = filp->private_data; kvm_release_rma(ri); return 0; } static const struct file_operations kvm_rma_fops = { .mmap = kvm_rma_mmap, .release = kvm_rma_release, }; static long kvm_vm_ioctl_allocate_rma(struct kvm *kvm, struct kvm_allocate_rma *ret) { long fd; struct kvm_rma_info *ri; /* * Only do this on PPC970 in HV mode */ if (!cpu_has_feature(CPU_FTR_HVMODE) || !cpu_has_feature(CPU_FTR_ARCH_201)) return -EINVAL; if (!kvm_rma_pages) return -EINVAL; ri = kvm_alloc_rma(); if (!ri) return -ENOMEM; fd = anon_inode_getfd("kvm-rma", &kvm_rma_fops, ri, O_RDWR | O_CLOEXEC); if (fd < 0) kvm_release_rma(ri); ret->rma_size = kvm_rma_pages << PAGE_SHIFT; return fd; } static void kvmppc_add_seg_page_size(struct kvm_ppc_one_seg_page_size **sps, int linux_psize) { struct mmu_psize_def *def = &mmu_psize_defs[linux_psize]; if (!def->shift) return; (*sps)->page_shift = def->shift; (*sps)->slb_enc = def->sllp; (*sps)->enc[0].page_shift = def->shift; (*sps)->enc[0].pte_enc = def->penc[linux_psize]; /* * Add 16MB MPSS support if host supports it */ if (linux_psize != MMU_PAGE_16M && def->penc[MMU_PAGE_16M] != -1) { (*sps)->enc[1].page_shift = 24; (*sps)->enc[1].pte_enc = def->penc[MMU_PAGE_16M]; } (*sps)++; } static int kvm_vm_ioctl_get_smmu_info_hv(struct kvm *kvm, struct kvm_ppc_smmu_info *info) { struct kvm_ppc_one_seg_page_size *sps; info->flags = KVM_PPC_PAGE_SIZES_REAL; if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) info->flags |= KVM_PPC_1T_SEGMENTS; info->slb_size = mmu_slb_size; /* We only support these sizes for now, and no muti-size segments */ sps = &info->sps[0]; kvmppc_add_seg_page_size(&sps, MMU_PAGE_4K); kvmppc_add_seg_page_size(&sps, MMU_PAGE_64K); kvmppc_add_seg_page_size(&sps, MMU_PAGE_16M); return 0; } /* * Get (and clear) the dirty memory log for a memory slot. */ static int kvm_vm_ioctl_get_dirty_log_hv(struct kvm *kvm, struct kvm_dirty_log *log) { struct kvm_memory_slot *memslot; int r; unsigned long n; mutex_lock(&kvm->slots_lock); r = -EINVAL; if (log->slot >= KVM_USER_MEM_SLOTS) goto out; memslot = id_to_memslot(kvm->memslots, log->slot); r = -ENOENT; if (!memslot->dirty_bitmap) goto out; n = kvm_dirty_bitmap_bytes(memslot); memset(memslot->dirty_bitmap, 0, n); r = kvmppc_hv_get_dirty_log(kvm, memslot, memslot->dirty_bitmap); if (r) goto out; r = -EFAULT; if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n)) goto out; r = 0; out: mutex_unlock(&kvm->slots_lock); return r; } static void unpin_slot(struct kvm_memory_slot *memslot) { unsigned long *physp; unsigned long j, npages, pfn; struct page *page; physp = memslot->arch.slot_phys; npages = memslot->npages; if (!physp) return; for (j = 0; j < npages; j++) { if (!(physp[j] & KVMPPC_GOT_PAGE)) continue; pfn = physp[j] >> PAGE_SHIFT; page = pfn_to_page(pfn); SetPageDirty(page); put_page(page); } } static void kvmppc_core_free_memslot_hv(struct kvm_memory_slot *free, struct kvm_memory_slot *dont) { if (!dont || free->arch.rmap != dont->arch.rmap) { vfree(free->arch.rmap); free->arch.rmap = NULL; } if (!dont || free->arch.slot_phys != dont->arch.slot_phys) { unpin_slot(free); vfree(free->arch.slot_phys); free->arch.slot_phys = NULL; } } static int kvmppc_core_create_memslot_hv(struct kvm_memory_slot *slot, unsigned long npages) { slot->arch.rmap = vzalloc(npages * sizeof(*slot->arch.rmap)); if (!slot->arch.rmap) return -ENOMEM; slot->arch.slot_phys = NULL; return 0; } static int kvmppc_core_prepare_memory_region_hv(struct kvm *kvm, struct kvm_memory_slot *memslot, struct kvm_userspace_memory_region *mem) { unsigned long *phys; /* Allocate a slot_phys array if needed */ phys = memslot->arch.slot_phys; if (!kvm->arch.using_mmu_notifiers && !phys && memslot->npages) { phys = vzalloc(memslot->npages * sizeof(unsigned long)); if (!phys) return -ENOMEM; memslot->arch.slot_phys = phys; } return 0; } static void kvmppc_core_commit_memory_region_hv(struct kvm *kvm, struct kvm_userspace_memory_region *mem, const struct kvm_memory_slot *old) { unsigned long npages = mem->memory_size >> PAGE_SHIFT; struct kvm_memory_slot *memslot; if (npages && old->npages) { /* * If modifying a memslot, reset all the rmap dirty bits. * If this is a new memslot, we don't need to do anything * since the rmap array starts out as all zeroes, * i.e. no pages are dirty. */ memslot = id_to_memslot(kvm->memslots, mem->slot); kvmppc_hv_get_dirty_log(kvm, memslot, NULL); } } /* * Update LPCR values in kvm->arch and in vcores. * Caller must hold kvm->lock. */ void kvmppc_update_lpcr(struct kvm *kvm, unsigned long lpcr, unsigned long mask) { long int i; u32 cores_done = 0; if ((kvm->arch.lpcr & mask) == lpcr) return; kvm->arch.lpcr = (kvm->arch.lpcr & ~mask) | lpcr; for (i = 0; i < KVM_MAX_VCORES; ++i) { struct kvmppc_vcore *vc = kvm->arch.vcores[i]; if (!vc) continue; spin_lock(&vc->lock); vc->lpcr = (vc->lpcr & ~mask) | lpcr; spin_unlock(&vc->lock); if (++cores_done >= kvm->arch.online_vcores) break; } } static void kvmppc_mmu_destroy_hv(struct kvm_vcpu *vcpu) { return; } static int kvmppc_hv_setup_htab_rma(struct kvm_vcpu *vcpu) { int err = 0; struct kvm *kvm = vcpu->kvm; struct kvm_rma_info *ri = NULL; unsigned long hva; struct kvm_memory_slot *memslot; struct vm_area_struct *vma; unsigned long lpcr = 0, senc; unsigned long lpcr_mask = 0; unsigned long psize, porder; unsigned long rma_size; unsigned long rmls; unsigned long *physp; unsigned long i, npages; int srcu_idx; mutex_lock(&kvm->lock); if (kvm->arch.rma_setup_done) goto out; /* another vcpu beat us to it */ /* Allocate hashed page table (if not done already) and reset it */ if (!kvm->arch.hpt_virt) { err = kvmppc_alloc_hpt(kvm, NULL); if (err) { pr_err("KVM: Couldn't alloc HPT\n"); goto out; } } /* Look up the memslot for guest physical address 0 */ srcu_idx = srcu_read_lock(&kvm->srcu); memslot = gfn_to_memslot(kvm, 0); /* We must have some memory at 0 by now */ err = -EINVAL; if (!memslot || (memslot->flags & KVM_MEMSLOT_INVALID)) goto out_srcu; /* Look up the VMA for the start of this memory slot */ hva = memslot->userspace_addr; down_read(&current->mm->mmap_sem); vma = find_vma(current->mm, hva); if (!vma || vma->vm_start > hva || (vma->vm_flags & VM_IO)) goto up_out; psize = vma_kernel_pagesize(vma); porder = __ilog2(psize); /* Is this one of our preallocated RMAs? */ if (vma->vm_file && vma->vm_file->f_op == &kvm_rma_fops && hva == vma->vm_start) ri = vma->vm_file->private_data; up_read(&current->mm->mmap_sem); if (!ri) { /* On POWER7, use VRMA; on PPC970, give up */ err = -EPERM; if (cpu_has_feature(CPU_FTR_ARCH_201)) { pr_err("KVM: CPU requires an RMO\n"); goto out_srcu; } /* We can handle 4k, 64k or 16M pages in the VRMA */ err = -EINVAL; if (!(psize == 0x1000 || psize == 0x10000 || psize == 0x1000000)) goto out_srcu; /* Update VRMASD field in the LPCR */ senc = slb_pgsize_encoding(psize); kvm->arch.vrma_slb_v = senc | SLB_VSID_B_1T | (VRMA_VSID << SLB_VSID_SHIFT_1T); lpcr_mask = LPCR_VRMASD; /* the -4 is to account for senc values starting at 0x10 */ lpcr = senc << (LPCR_VRMASD_SH - 4); /* Create HPTEs in the hash page table for the VRMA */ kvmppc_map_vrma(vcpu, memslot, porder); } else { /* Set up to use an RMO region */ rma_size = kvm_rma_pages; if (rma_size > memslot->npages) rma_size = memslot->npages; rma_size <<= PAGE_SHIFT; rmls = lpcr_rmls(rma_size); err = -EINVAL; if ((long)rmls < 0) { pr_err("KVM: Can't use RMA of 0x%lx bytes\n", rma_size); goto out_srcu; } atomic_inc(&ri->use_count); kvm->arch.rma = ri; /* Update LPCR and RMOR */ if (cpu_has_feature(CPU_FTR_ARCH_201)) { /* PPC970; insert RMLS value (split field) in HID4 */ lpcr_mask = (1ul << HID4_RMLS0_SH) | (3ul << HID4_RMLS2_SH) | HID4_RMOR; lpcr = ((rmls >> 2) << HID4_RMLS0_SH) | ((rmls & 3) << HID4_RMLS2_SH); /* RMOR is also in HID4 */ lpcr |= ((ri->base_pfn >> (26 - PAGE_SHIFT)) & 0xffff) << HID4_RMOR_SH; } else { /* POWER7 */ lpcr_mask = LPCR_VPM0 | LPCR_VRMA_L | LPCR_RMLS; lpcr = rmls << LPCR_RMLS_SH; kvm->arch.rmor = ri->base_pfn << PAGE_SHIFT; } pr_info("KVM: Using RMO at %lx size %lx (LPCR = %lx)\n", ri->base_pfn << PAGE_SHIFT, rma_size, lpcr); /* Initialize phys addrs of pages in RMO */ npages = kvm_rma_pages; porder = __ilog2(npages); physp = memslot->arch.slot_phys; if (physp) { if (npages > memslot->npages) npages = memslot->npages; spin_lock(&kvm->arch.slot_phys_lock); for (i = 0; i < npages; ++i) physp[i] = ((ri->base_pfn + i) << PAGE_SHIFT) + porder; spin_unlock(&kvm->arch.slot_phys_lock); } } kvmppc_update_lpcr(kvm, lpcr, lpcr_mask); /* Order updates to kvm->arch.lpcr etc. vs. rma_setup_done */ smp_wmb(); kvm->arch.rma_setup_done = 1; err = 0; out_srcu: srcu_read_unlock(&kvm->srcu, srcu_idx); out: mutex_unlock(&kvm->lock); return err; up_out: up_read(&current->mm->mmap_sem); goto out_srcu; } static int kvmppc_core_init_vm_hv(struct kvm *kvm) { unsigned long lpcr, lpid; /* Allocate the guest's logical partition ID */ lpid = kvmppc_alloc_lpid(); if ((long)lpid < 0) return -ENOMEM; kvm->arch.lpid = lpid; /* * Since we don't flush the TLB when tearing down a VM, * and this lpid might have previously been used, * make sure we flush on each core before running the new VM. */ cpumask_setall(&kvm->arch.need_tlb_flush); /* Start out with the default set of hcalls enabled */ memcpy(kvm->arch.enabled_hcalls, default_enabled_hcalls, sizeof(kvm->arch.enabled_hcalls)); kvm->arch.rma = NULL; kvm->arch.host_sdr1 = mfspr(SPRN_SDR1); if (cpu_has_feature(CPU_FTR_ARCH_201)) { /* PPC970; HID4 is effectively the LPCR */ kvm->arch.host_lpid = 0; kvm->arch.host_lpcr = lpcr = mfspr(SPRN_HID4); lpcr &= ~((3 << HID4_LPID1_SH) | (0xful << HID4_LPID5_SH)); lpcr |= ((lpid >> 4) << HID4_LPID1_SH) | ((lpid & 0xf) << HID4_LPID5_SH); } else { /* POWER7; init LPCR for virtual RMA mode */ kvm->arch.host_lpid = mfspr(SPRN_LPID); kvm->arch.host_lpcr = lpcr = mfspr(SPRN_LPCR); lpcr &= LPCR_PECE | LPCR_LPES; lpcr |= (4UL << LPCR_DPFD_SH) | LPCR_HDICE | LPCR_VPM0 | LPCR_VPM1; kvm->arch.vrma_slb_v = SLB_VSID_B_1T | (VRMA_VSID << SLB_VSID_SHIFT_1T); /* On POWER8 turn on online bit to enable PURR/SPURR */ if (cpu_has_feature(CPU_FTR_ARCH_207S)) lpcr |= LPCR_ONL; } kvm->arch.lpcr = lpcr; kvm->arch.using_mmu_notifiers = !!cpu_has_feature(CPU_FTR_ARCH_206); spin_lock_init(&kvm->arch.slot_phys_lock); /* * Track that we now have a HV mode VM active. This blocks secondary * CPU threads from coming online. */ kvm_hv_vm_activated(); return 0; } static void kvmppc_free_vcores(struct kvm *kvm) { long int i; for (i = 0; i < KVM_MAX_VCORES; ++i) { if (kvm->arch.vcores[i] && kvm->arch.vcores[i]->mpp_buffer) { struct kvmppc_vcore *vc = kvm->arch.vcores[i]; free_pages((unsigned long)vc->mpp_buffer, MPP_BUFFER_ORDER); } kfree(kvm->arch.vcores[i]); } kvm->arch.online_vcores = 0; } static void kvmppc_core_destroy_vm_hv(struct kvm *kvm) { kvm_hv_vm_deactivated(); kvmppc_free_vcores(kvm); if (kvm->arch.rma) { kvm_release_rma(kvm->arch.rma); kvm->arch.rma = NULL; } kvmppc_free_hpt(kvm); } /* We don't need to emulate any privileged instructions or dcbz */ static int kvmppc_core_emulate_op_hv(struct kvm_run *run, struct kvm_vcpu *vcpu, unsigned int inst, int *advance) { return EMULATE_FAIL; } static int kvmppc_core_emulate_mtspr_hv(struct kvm_vcpu *vcpu, int sprn, ulong spr_val) { return EMULATE_FAIL; } static int kvmppc_core_emulate_mfspr_hv(struct kvm_vcpu *vcpu, int sprn, ulong *spr_val) { return EMULATE_FAIL; } static int kvmppc_core_check_processor_compat_hv(void) { if (!cpu_has_feature(CPU_FTR_HVMODE)) return -EIO; return 0; } static long kvm_arch_vm_ioctl_hv(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm *kvm __maybe_unused = filp->private_data; void __user *argp = (void __user *)arg; long r; switch (ioctl) { case KVM_ALLOCATE_RMA: { struct kvm_allocate_rma rma; struct kvm *kvm = filp->private_data; r = kvm_vm_ioctl_allocate_rma(kvm, &rma); if (r >= 0 && copy_to_user(argp, &rma, sizeof(rma))) r = -EFAULT; break; } case KVM_PPC_ALLOCATE_HTAB: { u32 htab_order; r = -EFAULT; if (get_user(htab_order, (u32 __user *)argp)) break; r = kvmppc_alloc_reset_hpt(kvm, &htab_order); if (r) break; r = -EFAULT; if (put_user(htab_order, (u32 __user *)argp)) break; r = 0; break; } case KVM_PPC_GET_HTAB_FD: { struct kvm_get_htab_fd ghf; r = -EFAULT; if (copy_from_user(&ghf, argp, sizeof(ghf))) break; r = kvm_vm_ioctl_get_htab_fd(kvm, &ghf); break; } default: r = -ENOTTY; } return r; } /* * List of hcall numbers to enable by default. * For compatibility with old userspace, we enable by default * all hcalls that were implemented before the hcall-enabling * facility was added. Note this list should not include H_RTAS. */ static unsigned int default_hcall_list[] = { H_REMOVE, H_ENTER, H_READ, H_PROTECT, H_BULK_REMOVE, H_GET_TCE, H_PUT_TCE, H_SET_DABR, H_SET_XDABR, H_CEDE, H_PROD, H_CONFER, H_REGISTER_VPA, #ifdef CONFIG_KVM_XICS H_EOI, H_CPPR, H_IPI, H_IPOLL, H_XIRR, H_XIRR_X, #endif 0 }; static void init_default_hcalls(void) { int i; unsigned int hcall; for (i = 0; default_hcall_list[i]; ++i) { hcall = default_hcall_list[i]; WARN_ON(!kvmppc_hcall_impl_hv(hcall)); __set_bit(hcall / 4, default_enabled_hcalls); } } static struct kvmppc_ops kvm_ops_hv = { .get_sregs = kvm_arch_vcpu_ioctl_get_sregs_hv, .set_sregs = kvm_arch_vcpu_ioctl_set_sregs_hv, .get_one_reg = kvmppc_get_one_reg_hv, .set_one_reg = kvmppc_set_one_reg_hv, .vcpu_load = kvmppc_core_vcpu_load_hv, .vcpu_put = kvmppc_core_vcpu_put_hv, .set_msr = kvmppc_set_msr_hv, .vcpu_run = kvmppc_vcpu_run_hv, .vcpu_create = kvmppc_core_vcpu_create_hv, .vcpu_free = kvmppc_core_vcpu_free_hv, .check_requests = kvmppc_core_check_requests_hv, .get_dirty_log = kvm_vm_ioctl_get_dirty_log_hv, .flush_memslot = kvmppc_core_flush_memslot_hv, .prepare_memory_region = kvmppc_core_prepare_memory_region_hv, .commit_memory_region = kvmppc_core_commit_memory_region_hv, .unmap_hva = kvm_unmap_hva_hv, .unmap_hva_range = kvm_unmap_hva_range_hv, .age_hva = kvm_age_hva_hv, .test_age_hva = kvm_test_age_hva_hv, .set_spte_hva = kvm_set_spte_hva_hv, .mmu_destroy = kvmppc_mmu_destroy_hv, .free_memslot = kvmppc_core_free_memslot_hv, .create_memslot = kvmppc_core_create_memslot_hv, .init_vm = kvmppc_core_init_vm_hv, .destroy_vm = kvmppc_core_destroy_vm_hv, .get_smmu_info = kvm_vm_ioctl_get_smmu_info_hv, .emulate_op = kvmppc_core_emulate_op_hv, .emulate_mtspr = kvmppc_core_emulate_mtspr_hv, .emulate_mfspr = kvmppc_core_emulate_mfspr_hv, .fast_vcpu_kick = kvmppc_fast_vcpu_kick_hv, .arch_vm_ioctl = kvm_arch_vm_ioctl_hv, .hcall_implemented = kvmppc_hcall_impl_hv, }; static int kvmppc_book3s_init_hv(void) { int r; /* * FIXME!! Do we need to check on all cpus ? */ r = kvmppc_core_check_processor_compat_hv(); if (r < 0) return -ENODEV; kvm_ops_hv.owner = THIS_MODULE; kvmppc_hv_ops = &kvm_ops_hv; init_default_hcalls(); r = kvmppc_mmu_hv_init(); return r; } static void kvmppc_book3s_exit_hv(void) { kvmppc_hv_ops = NULL; } module_init(kvmppc_book3s_init_hv); module_exit(kvmppc_book3s_exit_hv); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(KVM_MINOR); MODULE_ALIAS("devname:kvm");
gpl-2.0
joeyparrish/cdnjs
ajax/libs/opentype.js/0.6.7/opentype.js
295992
/** * Modules in this bundle * @license * * opentype.js: * license: MIT (http://opensource.org/licenses/MIT) * author: Frederik De Bleser <[email protected]> * version: 0.6.7 * * tiny-inflate: * license: MIT (http://opensource.org/licenses/MIT) * author: Devon Govett <[email protected]> * maintainers: devongovett <[email protected]> * homepage: https://github.com/devongovett/tiny-inflate * version: 1.0.2 * * This header is generated by licensify (https://github.com/twada/licensify) */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.opentype = f()}})(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 TINF_OK = 0; var TINF_DATA_ERROR = -3; function Tree() { this.table = new Uint16Array(16); /* table of code length counts */ this.trans = new Uint16Array(288); /* code -> symbol translation table */ } function Data(source, dest) { this.source = source; this.sourceIndex = 0; this.tag = 0; this.bitcount = 0; this.dest = dest; this.destLen = 0; this.ltree = new Tree(); /* dynamic length/symbol tree */ this.dtree = new Tree(); /* dynamic distance tree */ } /* --------------------------------------------------- * * -- uninitialized global data (static structures) -- * * --------------------------------------------------- */ var sltree = new Tree(); var sdtree = new Tree(); /* extra bits and base tables for length codes */ var length_bits = new Uint8Array(30); var length_base = new Uint16Array(30); /* extra bits and base tables for distance codes */ var dist_bits = new Uint8Array(30); var dist_base = new Uint16Array(30); /* special ordering of code length codes */ var clcidx = new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); /* used by tinf_decode_trees, avoids allocations every call */ var code_tree = new Tree(); var lengths = new Uint8Array(288 + 32); /* ----------------------- * * -- utility functions -- * * ----------------------- */ /* build extra bits and base tables */ function tinf_build_bits_base(bits, base, delta, first) { var i, sum; /* build bits table */ for (i = 0; i < delta; ++i) bits[i] = 0; for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0; /* build base table */ for (sum = first, i = 0; i < 30; ++i) { base[i] = sum; sum += 1 << bits[i]; } } /* build the fixed huffman trees */ function tinf_build_fixed_trees(lt, dt) { var i; /* build fixed length tree */ for (i = 0; i < 7; ++i) lt.table[i] = 0; lt.table[7] = 24; lt.table[8] = 152; lt.table[9] = 112; for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i; for (i = 0; i < 144; ++i) lt.trans[24 + i] = i; for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i; for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i; /* build fixed distance tree */ for (i = 0; i < 5; ++i) dt.table[i] = 0; dt.table[5] = 32; for (i = 0; i < 32; ++i) dt.trans[i] = i; } /* given an array of code lengths, build a tree */ var offs = new Uint16Array(16); function tinf_build_tree(t, lengths, off, num) { var i, sum; /* clear code length count table */ for (i = 0; i < 16; ++i) t.table[i] = 0; /* scan symbol lengths, and sum code length counts */ for (i = 0; i < num; ++i) t.table[lengths[off + i]]++; t.table[0] = 0; /* compute offset table for distribution sort */ for (sum = 0, i = 0; i < 16; ++i) { offs[i] = sum; sum += t.table[i]; } /* create code->symbol translation table (symbols sorted by code) */ for (i = 0; i < num; ++i) { if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i; } } /* ---------------------- * * -- decode functions -- * * ---------------------- */ /* get one bit from source stream */ function tinf_getbit(d) { /* check if tag is empty */ if (!d.bitcount--) { /* load next tag */ d.tag = d.source[d.sourceIndex++]; d.bitcount = 7; } /* shift bit out of tag */ var bit = d.tag & 1; d.tag >>>= 1; return bit; } /* read a num bit value from a stream and add base */ function tinf_read_bits(d, num, base) { if (!num) return base; while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var val = d.tag & (0xffff >>> (16 - num)); d.tag >>>= num; d.bitcount -= num; return val + base; } /* given a data stream and a tree, decode a symbol */ function tinf_decode_symbol(d, t) { while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var sum = 0, cur = 0, len = 0; var tag = d.tag; /* get more bits while code value is above sum */ do { cur = 2 * cur + (tag & 1); tag >>>= 1; ++len; sum += t.table[len]; cur -= t.table[len]; } while (cur >= 0); d.tag = tag; d.bitcount -= len; return t.trans[sum + cur]; } /* given a data stream, decode dynamic trees from it */ function tinf_decode_trees(d, lt, dt) { var hlit, hdist, hclen; var i, num, length; /* get 5 bits HLIT (257-286) */ hlit = tinf_read_bits(d, 5, 257); /* get 5 bits HDIST (1-32) */ hdist = tinf_read_bits(d, 5, 1); /* get 4 bits HCLEN (4-19) */ hclen = tinf_read_bits(d, 4, 4); for (i = 0; i < 19; ++i) lengths[i] = 0; /* read code lengths for code length alphabet */ for (i = 0; i < hclen; ++i) { /* get 3 bits code length (0-7) */ var clen = tinf_read_bits(d, 3, 0); lengths[clcidx[i]] = clen; } /* build code length tree */ tinf_build_tree(code_tree, lengths, 0, 19); /* decode code lengths for the dynamic trees */ for (num = 0; num < hlit + hdist;) { var sym = tinf_decode_symbol(d, code_tree); switch (sym) { case 16: /* copy previous code length 3-6 times (read 2 bits) */ var prev = lengths[num - 1]; for (length = tinf_read_bits(d, 2, 3); length; --length) { lengths[num++] = prev; } break; case 17: /* repeat code length 0 for 3-10 times (read 3 bits) */ for (length = tinf_read_bits(d, 3, 3); length; --length) { lengths[num++] = 0; } break; case 18: /* repeat code length 0 for 11-138 times (read 7 bits) */ for (length = tinf_read_bits(d, 7, 11); length; --length) { lengths[num++] = 0; } break; default: /* values 0-15 represent the actual code lengths */ lengths[num++] = sym; break; } } /* build dynamic trees */ tinf_build_tree(lt, lengths, 0, hlit); tinf_build_tree(dt, lengths, hlit, hdist); } /* ----------------------------- * * -- block inflate functions -- * * ----------------------------- */ /* given a stream and two trees, inflate a block of data */ function tinf_inflate_block_data(d, lt, dt) { while (1) { var sym = tinf_decode_symbol(d, lt); /* check for end of block */ if (sym === 256) { return TINF_OK; } if (sym < 256) { d.dest[d.destLen++] = sym; } else { var length, dist, offs; var i; sym -= 257; /* possibly get more bits from length code */ length = tinf_read_bits(d, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d, dt); /* possibly get more bits from distance code */ offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); /* copy match */ for (i = offs; i < offs + length; ++i) { d.dest[d.destLen++] = d.dest[i]; } } } } /* inflate an uncompressed block of data */ function tinf_inflate_uncompressed_block(d) { var length, invlength; var i; /* unread from bitbuffer */ while (d.bitcount > 8) { d.sourceIndex--; d.bitcount -= 8; } /* get length */ length = d.source[d.sourceIndex + 1]; length = 256 * length + d.source[d.sourceIndex]; /* get one's complement of length */ invlength = d.source[d.sourceIndex + 3]; invlength = 256 * invlength + d.source[d.sourceIndex + 2]; /* check length */ if (length !== (~invlength & 0x0000ffff)) return TINF_DATA_ERROR; d.sourceIndex += 4; /* copy block */ for (i = length; i; --i) d.dest[d.destLen++] = d.source[d.sourceIndex++]; /* make sure we start next block on a byte boundary */ d.bitcount = 0; return TINF_OK; } /* inflate stream from source to dest */ function tinf_uncompress(source, dest) { var d = new Data(source, dest); var bfinal, btype, res; do { /* read final block flag */ bfinal = tinf_getbit(d); /* read block type (2 bits) */ btype = tinf_read_bits(d, 2, 0); /* decompress block */ switch (btype) { case 0: /* decompress uncompressed block */ res = tinf_inflate_uncompressed_block(d); break; case 1: /* decompress block with fixed huffman trees */ res = tinf_inflate_block_data(d, sltree, sdtree); break; case 2: /* decompress block with dynamic huffman trees */ tinf_decode_trees(d, d.ltree, d.dtree); res = tinf_inflate_block_data(d, d.ltree, d.dtree); break; default: res = TINF_DATA_ERROR; } if (res !== TINF_OK) throw new Error('Data error'); } while (!bfinal); if (d.destLen < d.dest.length) { if (typeof d.dest.slice === 'function') return d.dest.slice(0, d.destLen); else return d.dest.subarray(0, d.destLen); } return d.dest; } /* -------------------- * * -- initialization -- * * -------------------- */ /* build fixed huffman trees */ tinf_build_fixed_trees(sltree, sdtree); /* build extra bits and base tables */ tinf_build_bits_base(length_bits, length_base, 4, 3); tinf_build_bits_base(dist_bits, dist_base, 2, 1); /* fix a special case */ length_bits[28] = 0; length_base[28] = 258; module.exports = tinf_uncompress; },{}],2:[function(require,module,exports){ // Run-time checking of preconditions. 'use strict'; exports.fail = function(message) { throw new Error(message); }; // Precondition function that checks if the given predicate is true. // If not, it will throw an error. exports.argument = function(predicate, message) { if (!predicate) { exports.fail(message); } }; // Precondition function that checks if the given assertion is true. // If not, it will throw an error. exports.assert = exports.argument; },{}],3:[function(require,module,exports){ // Drawing utility functions. 'use strict'; // Draw a line on the given context from point `x1,y1` to point `x2,y2`. function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } exports.line = line; },{}],4:[function(require,module,exports){ // Glyph encoding 'use strict'; var cffStandardStrings = [ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; var cffStandardEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls']; var cffExpertEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; var standardNames = [ '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; /** * This is the encoding used for fonts created from scratch. * It loops through all glyphs and finds the appropriate unicode value. * Since it's linear time, other encodings will be faster. * @exports opentype.DefaultEncoding * @class * @constructor * @param {opentype.Font} */ function DefaultEncoding(font) { this.font = font; } DefaultEncoding.prototype.charToGlyphIndex = function(c) { var code = c.charCodeAt(0); var glyphs = this.font.glyphs; if (glyphs) { for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { if (glyph.unicodes[j] === code) { return i; } } } } else { return null; } }; /** * @exports opentype.CmapEncoding * @class * @constructor * @param {Object} cmap - a object with the cmap encoded data */ function CmapEncoding(cmap) { this.cmap = cmap; } /** * @param {string} c - the character * @return {number} The glyph index. */ CmapEncoding.prototype.charToGlyphIndex = function(c) { return this.cmap.glyphIndexMap[c.charCodeAt(0)] || 0; }; /** * @exports opentype.CffEncoding * @class * @constructor * @param {string} encoding - The encoding * @param {Array} charset - The charcater set. */ function CffEncoding(encoding, charset) { this.encoding = encoding; this.charset = charset; } /** * @param {string} s - The character * @return {number} The index. */ CffEncoding.prototype.charToGlyphIndex = function(s) { var code = s.charCodeAt(0); var charName = this.encoding[code]; return this.charset.indexOf(charName); }; /** * @exports opentype.GlyphNames * @class * @constructor * @param {Object} post */ function GlyphNames(post) { var i; switch (post.version) { case 1: this.names = exports.standardNames.slice(); break; case 2: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] < exports.standardNames.length) { this.names[i] = exports.standardNames[post.glyphNameIndex[i]]; } else { this.names[i] = post.names[post.glyphNameIndex[i] - exports.standardNames.length]; } } break; case 2.5: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { this.names[i] = exports.standardNames[i + post.glyphNameIndex[i]]; } break; case 3: this.names = []; break; } } /** * Gets the index of a glyph by name. * @param {string} name - The glyph name * @return {number} The index */ GlyphNames.prototype.nameToGlyphIndex = function(name) { return this.names.indexOf(name); }; /** * @param {number} gid * @return {string} */ GlyphNames.prototype.glyphIndexToName = function(gid) { return this.names[gid]; }; /** * @alias opentype.addGlyphNames * @param {opentype.Font} */ function addGlyphNames(font) { var glyph; var glyphIndexMap = font.tables.cmap.glyphIndexMap; var charCodes = Object.keys(glyphIndexMap); for (var i = 0; i < charCodes.length; i += 1) { var c = charCodes[i]; var glyphIndex = glyphIndexMap[c]; glyph = font.glyphs.get(glyphIndex); glyph.addUnicode(parseInt(c)); } for (i = 0; i < font.glyphs.length; i += 1) { glyph = font.glyphs.get(i); if (font.cffEncoding) { glyph.name = font.cffEncoding.charset[i]; } else if (font.glyphNames.names) { glyph.name = font.glyphNames.glyphIndexToName(i); } } } exports.cffStandardStrings = cffStandardStrings; exports.cffStandardEncoding = cffStandardEncoding; exports.cffExpertEncoding = cffExpertEncoding; exports.standardNames = standardNames; exports.DefaultEncoding = DefaultEncoding; exports.CmapEncoding = CmapEncoding; exports.CffEncoding = CffEncoding; exports.GlyphNames = GlyphNames; exports.addGlyphNames = addGlyphNames; },{}],5:[function(require,module,exports){ // The Font object 'use strict'; var path = require('./path'); var sfnt = require('./tables/sfnt'); var encoding = require('./encoding'); var glyphset = require('./glyphset'); var Substitution = require('./substitution'); var util = require('./util'); /** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection */ /** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */ function Font(options) { options = options || {}; if (!options.empty) { // Check that we've provided the minimum set of names. util.checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); util.checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); util.checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); util.checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); util.checkArgument(options.descender, 'When creating a new Font object, descender is required.'); util.checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); // OS X will complain if the names are empty, so we put a single space everywhere by default. this.names = { fontFamily: {en: options.familyName || ' '}, fontSubfamily: {en: options.styleName || ' '}, fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, postScriptName: {en: options.postScriptName || options.familyName + options.styleName}, designer: {en: options.designer || ' '}, designerURL: {en: options.designerURL || ' '}, manufacturer: {en: options.manufacturer || ' '}, manufacturerURL: {en: options.manufacturerURL || ' '}, license: {en: options.license || ' '}, licenseURL: {en: options.licenseURL || ' '}, version: {en: options.version || 'Version 0.1'}, description: {en: options.description || ' '}, copyright: {en: options.copyright || ' '}, trademark: {en: options.trademark || ' '} }; this.unitsPerEm = options.unitsPerEm || 1000; this.ascender = options.ascender; this.descender = options.descender; this.createdTimestamp = options.createdTimestamp; this.tables = { os2: { usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR } }; } this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); this.encoding = new encoding.DefaultEncoding(this); this.substitution = new Substitution(this); this.tables = this.tables || {}; } /** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */ Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; /** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */ Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; /** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */ Font.prototype.charToGlyph = function(c) { var glyphIndex = this.charToGlyphIndex(c); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @return {opentype.Glyph[]} */ Font.prototype.stringToGlyphs = function(s) { var glyphs = []; for (var i = 0; i < s.length; i += 1) { var c = s[i]; glyphs.push(this.charToGlyph(c)); } return glyphs; }; /** * @param {string} * @return {Number} */ Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; /** * @param {string} * @return {opentype.Glyph} */ Font.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * @param {Number} * @return {String} */ Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) { return ''; } return this.glyphNames.glyphIndexToName(gid); }; /** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */ Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; var gposKerning = this.getGposKerningValue; return gposKerning ? gposKerning(leftGlyph, rightGlyph) : (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0); }; /** * @typedef GlyphRenderOptions * @type Object * @property {boolean} [kerning] - whether to include kerning values */ /** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */ Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; options = options || {}; var kerning = options.kerning === undefined ? true : options.kerning; var fontScale = 1 / this.unitsPerEm * fontSize; var glyphs = this.stringToGlyphs(text); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs[i]; callback(glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (kerning && i < glyphs.length - 1) { var kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += (options.tracking / 1000) * fontSize; } } }; /** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */ Font.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new path.Path(); this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize); fullPath.extend(glyphPath); }); return fullPath; }; /** * Create an array of Path objects that represent the glyps of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */ Font.prototype.getPaths = function(text, x, y, fontSize, options) { var glyphPaths = []; this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize); glyphPaths.push(glyphPath); }); return glyphPaths; }; /** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; /** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; /** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; /** * @param {string} * @return {string} */ Font.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) { return translations.en; } }; /** * Validate */ Font.prototype.validate = function() { var warnings = []; var _this = this; function assert(predicate, message) { if (!predicate) { warnings.push(message); } } function assertNamePresent(name) { var englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); assertNamePresent('version'); // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */ Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; /** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */ Font.prototype.toBuffer = function() { console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); return this.toArrayBuffer(); }; /** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */ Font.prototype.toArrayBuffer = function() { var sfntTable = this.toTables(); var bytes = sfntTable.encode(); var buffer = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < bytes.length; i++) { intArray[i] = bytes[i]; } return buffer; }; /** * Initiate a download of the OpenType font. */ Font.prototype.download = function(fileName) { var familyName = this.getEnglishName('fontFamily'); var styleName = this.getEnglishName('fontSubfamily'); fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; var arrayBuffer = this.toArrayBuffer(); if (util.isBrowser()) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) { fs.root.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { var dataView = new DataView(arrayBuffer); var blob = new Blob([dataView], {type: 'font/opentype'}); writer.write(blob); writer.addEventListener('writeend', function() { // Navigating to the file will download it. location.href = fileEntry.toURL(); }, false); }); }); }, function(err) { throw new Error(err.name + ': ' + err.message); }); } else { var fs = require('fs'); var buffer = util.arrayBufferToNodeBuffer(arrayBuffer); fs.writeFileSync(fileName, buffer); } }; /** * @private */ Font.prototype.fsSelectionValues = { ITALIC: 0x001, //1 UNDERSCORE: 0x002, //2 NEGATIVE: 0x004, //4 OUTLINED: 0x008, //8 STRIKEOUT: 0x010, //16 BOLD: 0x020, //32 REGULAR: 0x040, //64 USER_TYPO_METRICS: 0x080, //128 WWS: 0x100, //256 OBLIQUE: 0x200 //512 }; /** * @private */ Font.prototype.usWidthClasses = { ULTRA_CONDENSED: 1, EXTRA_CONDENSED: 2, CONDENSED: 3, SEMI_CONDENSED: 4, MEDIUM: 5, SEMI_EXPANDED: 6, EXPANDED: 7, EXTRA_EXPANDED: 8, ULTRA_EXPANDED: 9 }; /** * @private */ Font.prototype.usWeightClasses = { THIN: 100, EXTRA_LIGHT: 200, LIGHT: 300, NORMAL: 400, MEDIUM: 500, SEMI_BOLD: 600, BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 }; exports.Font = Font; },{"./encoding":4,"./glyphset":7,"./path":11,"./substitution":12,"./tables/sfnt":31,"./util":33,"fs":undefined}],6:[function(require,module,exports){ // The Glyph object 'use strict'; var check = require('./check'); var draw = require('./draw'); var path = require('./path'); function getPathDefinition(glyph, path) { var _path = path || { commands: [] }; return { configurable: true, get: function() { if (typeof _path === 'function') { _path = _path(); } return _path; }, set: function(p) { _path = p; } }; } /** * @typedef GlyphOptions * @type Object * @property {string} [name] - The glyph name * @property {number} [unicode] * @property {Array} [unicodes] * @property {number} [xMin] * @property {number} [yMin] * @property {number} [xMax] * @property {number} [yMax] * @property {number} [advanceWidth] */ // A Glyph is an individual mark that often corresponds to a character. // Some glyphs, such as ligatures, are a combination of many characters. // Glyphs are the basic building blocks of a font. // // The `Glyph` class contains utility methods for drawing the path and its points. /** * @exports opentype.Glyph * @class * @param {GlyphOptions} * @constructor */ function Glyph(options) { // By putting all the code on a prototype function (which is only declared once) // we reduce the memory requirements for larger fonts by some 2% this.bindConstructorValues(options); } /** * @param {GlyphOptions} */ Glyph.prototype.bindConstructorValues = function(options) { this.index = options.index || 0; // These three values cannnot be deferred for memory optimization: this.name = options.name || null; this.unicode = options.unicode || undefined; this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; // But by binding these values only when necessary, we reduce can // the memory requirements by almost 3% for larger fonts. if (options.xMin) { this.xMin = options.xMin; } if (options.yMin) { this.yMin = options.yMin; } if (options.xMax) { this.xMax = options.xMax; } if (options.yMax) { this.yMax = options.yMax; } if (options.advanceWidth) { this.advanceWidth = options.advanceWidth; } // The path for a glyph is the most memory intensive, and is bound as a value // with a getter/setter to ensure we actually do path parsing only once the // path is actually needed by anything. Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); }; /** * @param {number} */ Glyph.prototype.addUnicode = function(unicode) { if (this.unicodes.length === 0) { this.unicode = unicode; } this.unicodes.push(unicode); }; /** * Convert the glyph to a Path we can draw on a drawing context. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. * @return {opentype.Path} */ Glyph.prototype.getPath = function(x, y, fontSize, options) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; options = options !== undefined ? options : {xScale: 1.0, yScale: 1.0}; fontSize = fontSize !== undefined ? fontSize : 72; var scale = 1 / this.path.unitsPerEm * fontSize; var xScale = options.xScale * scale; var yScale = options.yScale * scale; var p = new path.Path(); var commands = this.path.commands; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type === 'M') { p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'L') { p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Q') { p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'C') { p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Z') { p.closePath(); } } return p; }; /** * Split the glyph into contours. * This function is here for backwards compatibility, and to * provide raw access to the TrueType glyph outlines. * @return {Array} */ Glyph.prototype.getContours = function() { if (this.points === undefined) { return []; } var contours = []; var currentContour = []; for (var i = 0; i < this.points.length; i += 1) { var pt = this.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; }; /** * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. * @return {Object} */ Glyph.prototype.getMetrics = function() { var commands = this.path.commands; var xCoords = []; var yCoords = []; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type !== 'Z') { xCoords.push(cmd.x); yCoords.push(cmd.y); } if (cmd.type === 'Q' || cmd.type === 'C') { xCoords.push(cmd.x1); yCoords.push(cmd.y1); } if (cmd.type === 'C') { xCoords.push(cmd.x2); yCoords.push(cmd.y2); } } var metrics = { xMin: Math.min.apply(null, xCoords), yMin: Math.min.apply(null, yCoords), xMax: Math.max.apply(null, xCoords), yMax: Math.max.apply(null, yCoords), leftSideBearing: this.leftSideBearing }; if (!isFinite(metrics.xMin)) { metrics.xMin = 0; } if (!isFinite(metrics.xMax)) { metrics.xMax = this.advanceWidth; } if (!isFinite(metrics.yMin)) { metrics.yMin = 0; } if (!isFinite(metrics.yMax)) { metrics.yMax = 0; } metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); return metrics; }; /** * Draw the glyph on the given context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. */ Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { this.getPath(x, y, fontSize, options).draw(ctx); }; /** * Draw the points of the glyph. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { function drawCircles(l, x, y, scale) { var PI_SQ = Math.PI * 2; ctx.beginPath(); for (var j = 0; j < l.length; j += 1) { ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, PI_SQ, false); } ctx.closePath(); ctx.fill(); } x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; var scale = 1 / this.path.unitsPerEm * fontSize; var blueCircles = []; var redCircles = []; var path = this.path; for (var i = 0; i < path.commands.length; i += 1) { var cmd = path.commands[i]; if (cmd.x !== undefined) { blueCircles.push({x: cmd.x, y: -cmd.y}); } if (cmd.x1 !== undefined) { redCircles.push({x: cmd.x1, y: -cmd.y1}); } if (cmd.x2 !== undefined) { redCircles.push({x: cmd.x2, y: -cmd.y2}); } } ctx.fillStyle = 'blue'; drawCircles(blueCircles, x, y, scale); ctx.fillStyle = 'red'; drawCircles(redCircles, x, y, scale); }; /** * Draw lines indicating important font measurements. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { var scale; x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; scale = 1 / this.path.unitsPerEm * fontSize; ctx.lineWidth = 1; // Draw the origin ctx.strokeStyle = 'black'; draw.line(ctx, x, -10000, x, 10000); draw.line(ctx, -10000, y, 10000, y); // This code is here due to memory optimization: by not using // defaults in the constructor, we save a notable amount of memory. var xMin = this.xMin || 0; var yMin = this.yMin || 0; var xMax = this.xMax || 0; var yMax = this.yMax || 0; var advanceWidth = this.advanceWidth || 0; // Draw the glyph box ctx.strokeStyle = 'blue'; draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); // Draw the advance width ctx.strokeStyle = 'green'; draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); }; exports.Glyph = Glyph; },{"./check":2,"./draw":3,"./path":11}],7:[function(require,module,exports){ // The GlyphSet object 'use strict'; var _glyph = require('./glyph'); // Define a property on the glyph that depends on the path being loaded. function defineDependentProperty(glyph, externalName, internalName) { Object.defineProperty(glyph, externalName, { get: function() { // Request the path property to make sure the path is loaded. glyph.path; // jshint ignore:line return glyph[internalName]; }, set: function(newValue) { glyph[internalName] = newValue; }, enumerable: true, configurable: true }); } /** * A GlyphSet represents all glyphs available in the font, but modelled using * a deferred glyph loader, for retrieving glyphs only once they are absolutely * necessary, to keep the memory footprint down. * @exports opentype.GlyphSet * @class * @param {opentype.Font} * @param {Array} */ function GlyphSet(font, glyphs) { this.font = font; this.glyphs = {}; if (Array.isArray(glyphs)) { for (var i = 0; i < glyphs.length; i++) { this.glyphs[i] = glyphs[i]; } } this.length = (glyphs && glyphs.length) || 0; } /** * @param {number} index * @return {opentype.Glyph} */ GlyphSet.prototype.get = function(index) { if (typeof this.glyphs[index] === 'function') { this.glyphs[index] = this.glyphs[index](); } return this.glyphs[index]; }; /** * @param {number} index * @param {Object} */ GlyphSet.prototype.push = function(index, loader) { this.glyphs[index] = loader; this.length++; }; /** * @alias opentype.glyphLoader * @param {opentype.Font} font * @param {number} index * @return {opentype.Glyph} */ function glyphLoader(font, index) { return new _glyph.Glyph({index: index, font: font}); } /** * Generate a stub glyph that can be filled with all metadata *except* * the "points" and "path" properties, which must be loaded only once * the glyph's path is actually requested for text shaping. * @alias opentype.ttfGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseGlyph * @param {Object} data * @param {number} position * @param {Function} buildPath * @return {opentype.Glyph} */ function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { parseGlyph(glyph, data, position); var path = buildPath(font.glyphs, glyph); path.unitsPerEm = font.unitsPerEm; return path; }; defineDependentProperty(glyph, 'xMin', '_xMin'); defineDependentProperty(glyph, 'xMax', '_xMax'); defineDependentProperty(glyph, 'yMin', '_yMin'); defineDependentProperty(glyph, 'yMax', '_yMax'); return glyph; }; } /** * @alias opentype.cffGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseCFFCharstring * @param {string} charstring * @return {opentype.Glyph} */ function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { var path = parseCFFCharstring(font, glyph, charstring); path.unitsPerEm = font.unitsPerEm; return path; }; return glyph; }; } exports.GlyphSet = GlyphSet; exports.glyphLoader = glyphLoader; exports.ttfGlyphLoader = ttfGlyphLoader; exports.cffGlyphLoader = cffGlyphLoader; },{"./glyph":6}],8:[function(require,module,exports){ // The Layout object is the prototype of Substition objects, and provides utility methods to manipulate // common layout tables (GPOS, GSUB, GDEF...) 'use strict'; var check = require('./check'); function searchTag(arr, tag) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid].tag; if (val === tag) { return imid; } else if (val < tag) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } function binSearch(arr, value) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid]; if (val === value) { return imid; } else if (val < value) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } /** * @exports opentype.Layout * @class */ var Layout = { /** * Binary search an object by "tag" property * @instance * @function searchTag * @memberof opentype.Layout * @param {Array} arr * @param {string} tag * @return {number} */ searchTag: searchTag, /** * Binary search in a list of numbers * @instance * @function binSearch * @memberof opentype.Layout * @param {Array} arr * @param {number} value * @return {number} */ binSearch: binSearch, /** * Returns all scripts in the substitution table. * @instance * @return {Array} */ getScriptNames: function() { var gsub = this.getGsubTable(); if (!gsub) { return []; } return gsub.scripts.map(function(script) { return script.tag; }); }, /** * Returns all LangSysRecords in the given script. * @instance * @param {string} script - Use 'DFLT' for default script * @param {boolean} create - forces the creation of this script table if it doesn't exist. * @return {Object} An object with tag and script properties. */ getScriptTable: function(script, create) { var gsub = this.getGsubTable(create); if (gsub) { var scripts = gsub.scripts; var pos = searchTag(gsub.scripts, script); if (pos >= 0) { return scripts[pos].script; } else { var scr = { tag: script, script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, langSysRecords: [] } }; scripts.splice(-1 - pos, 0, scr.script); return scr; } } }, /** * Returns a language system table * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. * @return {Object} */ getLangSysTable: function(script, language, create) { var scriptTable = this.getScriptTable(script, create); if (scriptTable) { if (language === 'DFLT') { return scriptTable.defaultLangSys; } var pos = searchTag(scriptTable.langSysRecords, language); if (pos >= 0) { return scriptTable.langSysRecords[pos].langSys; } else if (create) { var langSysRecord = { tag: language, langSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] } }; scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); return langSysRecord.langSys; } } }, /** * Get a specific feature table. * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm * @param {boolean} create - forces the creation of the feature table if it doesn't exist. * @return {Object} */ getFeatureTable: function(script, language, feature, create) { var langSysTable = this.getLangSysTable(script, language, create); if (langSysTable) { var featureRecord; var featIndexes = langSysTable.featureIndexes; var allFeatures = this.font.tables.gsub.features; // The FeatureIndex array of indices is in arbitrary order, // even if allFeatures is sorted alphabetically by feature tag. for (var i = 0; i < featIndexes.length; i++) { featureRecord = allFeatures[featIndexes[i]]; if (featureRecord.tag === feature) { return featureRecord.feature; } } if (create) { var index = allFeatures.length; // Automatic ordering of features would require to shift feature indexes in the script list. check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); featureRecord = { tag: feature, feature: { params: 0, lookupListIndexes: [] } }; allFeatures.push(featureRecord); featIndexes.push(index); return featureRecord.feature; } } }, /** * Get the first lookup table of a given type for a script/language/feature. * @instance * @param {string} script - Use 'DFLT' for default script * @param {string} language - Use 'DFLT' for default language * @param {string} feature - 4-letter feature code * @param {number} lookupType - 1 to 8 * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. * @return {Object} */ getLookupTable: function(script, language, feature, lookupType, create) { var featureTable = this.getFeatureTable(script, language, feature, create); if (featureTable) { var lookupTable; var lookupListIndexes = featureTable.lookupListIndexes; var allLookups = this.font.tables.gsub.lookups; // lookupListIndexes are in no particular order, so use naïve search. for (var i = 0; i < lookupListIndexes.length; i++) { lookupTable = allLookups[lookupListIndexes[i]]; if (lookupTable.lookupType === lookupType) { return lookupTable; } } if (create) { lookupTable = { lookupType: lookupType, lookupFlag: 0, subtables: [], markFilteringSet: undefined }; var index = allLookups.length; allLookups.push(lookupTable); lookupListIndexes.push(index); return lookupTable; } } }, /** * Returns the list of glyph indexes of a coverage table. * Format 1: the list is stored raw * Format 2: compact list as range records. * @instance * @param {Object} coverageTable * @return {Array} */ expandCoverage: function(coverageTable) { if (coverageTable.format === 1) { return coverageTable.glyphs; } else { var glyphs = []; var ranges = coverageTable.ranges; for (var i = 0; i < ranges; i++) { var range = ranges[i]; var start = range.start; var end = range.end; for (var j = start; j <= end; j++) { glyphs.push(j); } } return glyphs; } } }; module.exports = Layout; },{"./check":2}],9:[function(require,module,exports){ // opentype.js // https://github.com/nodebox/opentype.js // (c) 2015 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /* global DataView, Uint8Array, XMLHttpRequest */ 'use strict'; var inflate = require('tiny-inflate'); var encoding = require('./encoding'); var _font = require('./font'); var glyph = require('./glyph'); var parse = require('./parse'); var path = require('./path'); var util = require('./util'); var cmap = require('./tables/cmap'); var cff = require('./tables/cff'); var fvar = require('./tables/fvar'); var glyf = require('./tables/glyf'); var gpos = require('./tables/gpos'); var gsub = require('./tables/gsub'); var head = require('./tables/head'); var hhea = require('./tables/hhea'); var hmtx = require('./tables/hmtx'); var kern = require('./tables/kern'); var ltag = require('./tables/ltag'); var loca = require('./tables/loca'); var maxp = require('./tables/maxp'); var _name = require('./tables/name'); var os2 = require('./tables/os2'); var post = require('./tables/post'); var meta = require('./tables/meta'); /** * The opentype library. * @namespace opentype */ // File loaders ///////////////////////////////////////////////////////// /** * Loads a font from a file. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} path - The path of the file * @param {Function} callback - The function to call when the font load completes */ function loadFromFile(path, callback) { var fs = require('fs'); fs.readFile(path, function(err, buffer) { if (err) { return callback(err.message); } callback(null, util.nodeBufferToArrayBuffer(buffer)); }); } /** * Loads a font from a URL. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} url - The URL of the font file. * @param {Function} callback - The function to call when the font load completes */ function loadFromUrl(url, callback) { var request = new XMLHttpRequest(); request.open('get', url, true); request.responseType = 'arraybuffer'; request.onload = function() { if (request.status !== 200) { return callback('Font could not be loaded: ' + request.statusText); } return callback(null, request.response); }; request.send(); } // Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p = 12; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var checksum = parse.getULong(data, p + 4); var offset = parse.getULong(data, p + 8); var length = parse.getULong(data, p + 12); tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false}); p += 16; } return tableEntries; } /** * Parses WOFF table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p = 44; // offset to the first table directory entry. for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var offset = parse.getULong(data, p + 4); var compLength = parse.getULong(data, p + 8); var origLength = parse.getULong(data, p + 12); var compression; if (compLength < origLength) { compression = 'WOFF'; } else { compression = false; } tableEntries.push({tag: tag, offset: offset, compression: compression, compressedLength: compLength, originalLength: origLength}); p += 20; } return tableEntries; } /** * @typedef TableData * @type Object * @property {DataView} data - The DataView * @property {number} offset - The data offset. */ /** * @param {DataView} * @param {Object} * @return {TableData} */ function uncompressTable(data, tableEntry) { if (tableEntry.compression === 'WOFF') { var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); var outBuffer = new Uint8Array(tableEntry.originalLength); inflate(inBuffer, outBuffer); if (outBuffer.byteLength !== tableEntry.originalLength) { throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); } var view = new DataView(outBuffer.buffer, 0); return {data: view, offset: 0}; } else { return {data: data, offset: tableEntry.offset}; } } // Public API /////////////////////////////////////////////////////////// /** * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. * Throws an error if the font could not be parsed. * @param {ArrayBuffer} * @return {opentype.Font} */ function parseBuffer(buffer) { var indexToLocFormat; var ltagTable; // Since the constructor can also be called to create new fonts from scratch, we indicate this // should be an empty font that we'll fill with our own data. var font = new _font.Font({empty: true}); // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. var data = new DataView(buffer, 0); var numTables; var tableEntries = []; var signature = parse.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'OTTO') { font.outlinesFormat = 'cff'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'wOFF') { var flavor = parse.getTag(data, 4); if (flavor === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; } else if (flavor === 'OTTO') { font.outlinesFormat = 'cff'; } else { throw new Error('Unsupported OpenType flavor ' + signature); } numTables = parse.getUShort(data, 12); tableEntries = parseWOFFTableEntries(data, numTables); } else { throw new Error('Unsupported OpenType signature ' + signature); } var cffTableEntry; var fvarTableEntry; var glyfTableEntry; var gposTableEntry; var gsubTableEntry; var hmtxTableEntry; var kernTableEntry; var locaTableEntry; var nameTableEntry; var metaTableEntry; for (var i = 0; i < numTables; i += 1) { var tableEntry = tableEntries[i]; var table; switch (tableEntry.tag) { case 'cmap': table = uncompressTable(data, tableEntry); font.tables.cmap = cmap.parse(table.data, table.offset); font.encoding = new encoding.CmapEncoding(font.tables.cmap); break; case 'fvar': fvarTableEntry = tableEntry; break; case 'head': table = uncompressTable(data, tableEntry); font.tables.head = head.parse(table.data, table.offset); font.unitsPerEm = font.tables.head.unitsPerEm; indexToLocFormat = font.tables.head.indexToLocFormat; break; case 'hhea': table = uncompressTable(data, tableEntry); font.tables.hhea = hhea.parse(table.data, table.offset); font.ascender = font.tables.hhea.ascender; font.descender = font.tables.hhea.descender; font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; break; case 'hmtx': hmtxTableEntry = tableEntry; break; case 'ltag': table = uncompressTable(data, tableEntry); ltagTable = ltag.parse(table.data, table.offset); break; case 'maxp': table = uncompressTable(data, tableEntry); font.tables.maxp = maxp.parse(table.data, table.offset); font.numGlyphs = font.tables.maxp.numGlyphs; break; case 'name': nameTableEntry = tableEntry; break; case 'OS/2': table = uncompressTable(data, tableEntry); font.tables.os2 = os2.parse(table.data, table.offset); break; case 'post': table = uncompressTable(data, tableEntry); font.tables.post = post.parse(table.data, table.offset); font.glyphNames = new encoding.GlyphNames(font.tables.post); break; case 'glyf': glyfTableEntry = tableEntry; break; case 'loca': locaTableEntry = tableEntry; break; case 'CFF ': cffTableEntry = tableEntry; break; case 'kern': kernTableEntry = tableEntry; break; case 'GPOS': gposTableEntry = tableEntry; break; case 'GSUB': gsubTableEntry = tableEntry; break; case 'meta': metaTableEntry = tableEntry; break; } } var nameTable = uncompressTable(data, nameTableEntry); font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); font.names = font.tables.name; if (glyfTableEntry && locaTableEntry) { var shortVersion = indexToLocFormat === 0; var locaTable = uncompressTable(data, locaTableEntry); var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); var glyfTable = uncompressTable(data, glyfTableEntry); font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font); } else if (cffTableEntry) { var cffTable = uncompressTable(data, cffTableEntry); cff.parse(cffTable.data, cffTable.offset, font); } else { throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); } var hmtxTable = uncompressTable(data, hmtxTableEntry); hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); encoding.addGlyphNames(font); if (kernTableEntry) { var kernTable = uncompressTable(data, kernTableEntry); font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); } else { font.kerningPairs = {}; } if (gposTableEntry) { var gposTable = uncompressTable(data, gposTableEntry); gpos.parse(gposTable.data, gposTable.offset, font); } if (gsubTableEntry) { var gsubTable = uncompressTable(data, gsubTableEntry); font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); } if (fvarTableEntry) { var fvarTable = uncompressTable(data, fvarTableEntry); font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); } if (metaTableEntry) { var metaTable = uncompressTable(data, metaTableEntry); font.tables.meta = meta.parse(metaTable.data, metaTable.offset); font.metas = font.tables.meta; } return font; } /** * Asynchronously load the font from a URL or a filesystem. When done, call the callback * with two arguments `(err, font)`. The `err` will be null on success, * the `font` is a Font object. * We use the node.js callback convention so that * opentype.js can integrate with frameworks like async.js. * @alias opentype.load * @param {string} url - The URL of the font to load. * @param {Function} callback - The callback. */ function load(url, callback) { var isNode = typeof window === 'undefined'; var loadFn = isNode ? loadFromFile : loadFromUrl; loadFn(url, function(err, arrayBuffer) { if (err) { return callback(err); } var font; try { font = parseBuffer(arrayBuffer); } catch (e) { return callback(e, null); } return callback(null, font); }); } /** * Synchronously load the font from a URL or file. * When done, returns the font object or throws an error. * @alias opentype.loadSync * @param {string} url - The URL of the font to load. * @return {opentype.Font} */ function loadSync(url) { var fs = require('fs'); var buffer = fs.readFileSync(url); return parseBuffer(util.nodeBufferToArrayBuffer(buffer)); } exports._parse = parse; exports.Font = _font.Font; exports.Glyph = glyph.Glyph; exports.Path = path.Path; exports.parse = parseBuffer; exports.load = load; exports.loadSync = loadSync; },{"./encoding":4,"./font":5,"./glyph":6,"./parse":10,"./path":11,"./tables/cff":14,"./tables/cmap":15,"./tables/fvar":16,"./tables/glyf":17,"./tables/gpos":18,"./tables/gsub":19,"./tables/head":20,"./tables/hhea":21,"./tables/hmtx":22,"./tables/kern":23,"./tables/loca":24,"./tables/ltag":25,"./tables/maxp":26,"./tables/meta":27,"./tables/name":28,"./tables/os2":29,"./tables/post":30,"./util":33,"fs":undefined,"tiny-inflate":1}],10:[function(require,module,exports){ // Parsing utility functions 'use strict'; var check = require('./check'); // Retrieve an unsigned byte from the DataView. exports.getByte = function getByte(dataView, offset) { return dataView.getUint8(offset); }; exports.getCard8 = exports.getByte; // Retrieve an unsigned 16-bit short from the DataView. // The value is stored in big endian. function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } exports.getUShort = exports.getCard16 = getUShort; // Retrieve a signed 16-bit short from the DataView. // The value is stored in big endian. exports.getShort = function(dataView, offset) { return dataView.getInt16(offset, false); }; // Retrieve an unsigned 32-bit long from the DataView. // The value is stored in big endian. exports.getULong = function(dataView, offset) { return dataView.getUint32(offset, false); }; // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. // The value is stored in big endian. exports.getFixed = function(dataView, offset) { var decimal = dataView.getInt16(offset, false); var fraction = dataView.getUint16(offset + 2, false); return decimal + fraction / 65535; }; // Retrieve a 4-character tag from the DataView. // Tags are used to identify tables. exports.getTag = function(dataView, offset) { var tag = ''; for (var i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(dataView.getInt8(i)); } return tag; }; // Retrieve an offset from the DataView. // Offsets are 1 to 4 bytes in length, depending on the offSize argument. exports.getOffset = function(dataView, offset, offSize) { var v = 0; for (var i = 0; i < offSize; i += 1) { v <<= 8; v += dataView.getUint8(offset + i); } return v; }; // Retrieve a number of bytes from start offset to the end offset from the DataView. exports.getBytes = function(dataView, startOffset, endOffset) { var bytes = []; for (var i = startOffset; i < endOffset; i += 1) { bytes.push(dataView.getUint8(i)); } return bytes; }; // Convert the list of bytes to a string. exports.bytesToString = function(bytes) { var s = ''; for (var i = 0; i < bytes.length; i += 1) { s += String.fromCharCode(bytes[i]); } return s; }; var typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; // A stateful parser that changes the offset whenever a value is retrieved. // The data is a DataView. function Parser(data, offset) { this.data = data; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parseByte = function() { var v = this.data.getUint8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseChar = function() { var v = this.data.getInt8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseCard8 = Parser.prototype.parseByte; Parser.prototype.parseUShort = function() { var v = this.data.getUint16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseCard16 = Parser.prototype.parseUShort; Parser.prototype.parseSID = Parser.prototype.parseUShort; Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; Parser.prototype.parseShort = function() { var v = this.data.getInt16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseF2Dot14 = function() { var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseFixed = function() { var v = exports.getFixed(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseString = function(length) { var dataView = this.data; var offset = this.offset + this.relativeOffset; var string = ''; this.relativeOffset += length; for (var i = 0; i < length; i++) { string += String.fromCharCode(dataView.getUint8(offset + i)); } return string; }; Parser.prototype.parseTag = function() { return this.parseString(4); }; // LONGDATETIME is a 64-bit integer. // JavaScript and unix timestamps traditionally use 32 bits, so we // only take the last 32 bits. // + Since until 2038 those bits will be filled by zeros we can ignore them. Parser.prototype.parseLongDateTime = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset + 4); // Subtract seconds between 01/01/1904 and 01/01/1970 // to convert Apple Mac timstamp to Standard Unix timestamp v -= 2082844800; this.relativeOffset += 8; return v; }; Parser.prototype.parseVersion = function() { var major = getUShort(this.data, this.offset + this.relativeOffset); // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 // This returns the correct number if minor = 0xN000 where N is 0-9 var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); this.relativeOffset += 4; return major + minor / 0x1000 / 10; }; Parser.prototype.skip = function(type, amount) { if (amount === undefined) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; ///// Parsing lists and records /////////////////////////////// // Parse a list of 16 bit integers. The length of the list can be read on the stream // or provided as an argument. Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { if (count === undefined) { count = this.parseUShort(); } var offsets = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { offsets[i] = dataView.getUint16(offset); offset += 2; } this.relativeOffset += count * 2; return offsets; }; /** * Parse a list of items. * Record count is optional, if omitted it is read from the stream. * itemCallback is one of the Parser methods. */ Parser.prototype.parseList = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseUShort(); } var list = new Array(count); for (var i = 0; i < count; i++) { list[i] = itemCallback.call(this); } return list; }; /** * Parse a list of records. * Record count is optional, if omitted it is read from the stream. * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } */ Parser.prototype.parseRecordList = function(count, recordDescription) { // If the count argument is absent, read it in the stream. if (!recordDescription) { recordDescription = count; count = this.parseUShort(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i = 0; i < count; i++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = recordDescription[fieldName]; rec[fieldName] = fieldType.call(this); } records[i] = rec; } return records; }; // Parse a data structure into an object // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } Parser.prototype.parseStruct = function(description) { if (typeof description === 'function') { return description.call(this); } else { var fields = Object.keys(description); var struct = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = description[fieldName]; struct[fieldName] = fieldType.call(this); } return struct; } }; Parser.prototype.parsePointer = function(description) { var structOffset = this.parseOffset16(); if (structOffset > 0) { // NULL offset => return indefined return new Parser(this.data, this.offset + structOffset).parseStruct(description); } }; /** * Parse a list of offsets to lists of 16-bit integers, * or a list of offsets to lists of offsets to any kind of items. * If itemCallback is not provided, a list of list of UShort is assumed. * If provided, itemCallback is called on each item and must parse the item. * See examples in tables/gsub.js */ Parser.prototype.parseListOfLists = function(itemCallback) { var offsets = this.parseOffset16List(); var count = offsets.length; var relativeOffset = this.relativeOffset; var list = new Array(count); for (var i = 0; i < count; i++) { var start = offsets[i]; if (start === 0) { // NULL offset list[i] = undefined; // Add i as owned property to list. Convenient with assert. continue; } this.relativeOffset = start; if (itemCallback) { var subOffsets = this.parseOffset16List(); var subList = new Array(subOffsets.length); for (var j = 0; j < subOffsets.length; j++) { this.relativeOffset = start + subOffsets[j]; subList[j] = itemCallback.call(this); } list[i] = subList; } else { list[i] = this.parseUShortList(); } } this.relativeOffset = relativeOffset; return list; }; ///// Complex tables parsing ////////////////////////////////// // Parse a coverage table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm // parser.offset must point to the start of the table containing the coverage. Parser.prototype.parseCoverage = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); var count = this.parseUShort(); if (format === 1) { return { format: 1, glyphs: this.parseUShortList(count) }; } else if (format === 2) { var ranges = new Array(count); for (var i = 0; i < count; i++) { ranges[i] = { start: this.parseUShort(), end: this.parseUShort(), index: this.parseUShort() }; } return { format: 2, ranges: ranges }; } check.assert(false, '0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); }; // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Parser.prototype.parseClassDef = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); if (format === 1) { return { format: 1, startGlyph: this.parseUShort(), classes: this.parseUShortList() }; } else if (format === 2) { return { format: 2, ranges: this.parseRecordList({ start: Parser.uShort, end: Parser.uShort, classId: Parser.uShort }) }; } check.assert(false, '0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); }; ///// Static methods /////////////////////////////////// // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. Parser.list = function(count, itemCallback) { return function() { return this.parseList(count, itemCallback); }; }; Parser.recordList = function(count, recordDescription) { return function() { return this.parseRecordList(count, recordDescription); }; }; Parser.pointer = function(description) { return function() { return this.parsePointer(description); }; }; Parser.tag = Parser.prototype.parseTag; Parser.byte = Parser.prototype.parseByte; Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; Parser.uShortList = Parser.prototype.parseUShortList; Parser.struct = Parser.prototype.parseStruct; Parser.coverage = Parser.prototype.parseCoverage; Parser.classDef = Parser.prototype.parseClassDef; ///// Script, Feature, Lookup lists /////////////////////////////////////////////// // https://www.microsoft.com/typography/OTSPEC/chapter2.htm var langSysTable = { reserved: Parser.uShort, reqFeatureIndex: Parser.uShort, featureIndexes: Parser.uShortList }; Parser.prototype.parseScriptList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, script: Parser.pointer({ defaultLangSys: Parser.pointer(langSysTable), langSysRecords: Parser.recordList({ tag: Parser.tag, langSys: Parser.pointer(langSysTable) }) }) })); }; Parser.prototype.parseFeatureList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, feature: Parser.pointer({ featureParams: Parser.offset16, lookupListIndexes: Parser.uShortList }) })); }; Parser.prototype.parseLookupList = function(lookupTableParsers) { return this.parsePointer(Parser.list(Parser.pointer(function() { var lookupType = this.parseUShort(); check.argument(1 <= lookupType && lookupType <= 8, 'GSUB lookup type ' + lookupType + ' unknown.'); var lookupFlag = this.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; return { lookupType: lookupType, lookupFlag: lookupFlag, subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined }; }))); }; exports.Parser = Parser; },{"./check":2}],11:[function(require,module,exports){ // Geometric objects 'use strict'; /** * A bézier path containing a set of path commands similar to a SVG path. * Paths can be drawn on a context using `draw`. * @exports opentype.Path * @class * @constructor */ function Path() { this.commands = []; this.fill = 'black'; this.stroke = null; this.strokeWidth = 1; } /** * @param {number} x * @param {number} y */ Path.prototype.moveTo = function(x, y) { this.commands.push({ type: 'M', x: x, y: y }); }; /** * @param {number} x * @param {number} y */ Path.prototype.lineTo = function(x, y) { this.commands.push({ type: 'L', x: x, y: y }); }; /** * Draws cubic curve * @function * curveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws cubic curve * @function * bezierCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point * @see curveTo */ Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { this.commands.push({ type: 'C', x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }); }; /** * Draws quadratic curve * @function * quadraticCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws quadratic curve * @function * quadTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { this.commands.push({ type: 'Q', x1: x1, y1: y1, x: x, y: y }); }; /** * Closes the path * @function closePath * @memberof opentype.Path.prototype */ /** * Close the path * @function close * @memberof opentype.Path.prototype */ Path.prototype.close = Path.prototype.closePath = function() { this.commands.push({ type: 'Z' }); }; /** * Add the given path or list of commands to the commands of this path. * @param {Array} */ Path.prototype.extend = function(pathOrCommands) { if (pathOrCommands.commands) { pathOrCommands = pathOrCommands.commands; } Array.prototype.push.apply(this.commands, pathOrCommands); }; /** * Draw the path to a 2D context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. */ Path.prototype.draw = function(ctx) { ctx.beginPath(); for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; /** * Convert the Path to a string of path data instructions * See http://www.w3.org/TR/SVG/paths.html#PathData * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toPathData = function(decimalPlaces) { decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; function floatToString(v) { if (Math.round(v) === v) { return '' + Math.round(v); } else { return v.toFixed(decimalPlaces); } } function packValues() { var s = ''; for (var i = 0; i < arguments.length; i += 1) { var v = arguments[i]; if (v >= 0 && i > 0) { s += ' '; } s += floatToString(v); } return s; } var d = ''; for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { d += 'M' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'L') { d += 'L' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'C') { d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { d += 'Z'; } } return d; }; /** * Convert the path to an SVG <path> element, as a string. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toSVG = function(decimalPlaces) { var svg = '<path d="'; svg += this.toPathData(decimalPlaces); svg += '"'; if (this.fill && this.fill !== 'black') { if (this.fill === null) { svg += ' fill="none"'; } else { svg += ' fill="' + this.fill + '"'; } } if (this.stroke) { svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"'; } svg += '/>'; return svg; }; exports.Path = Path; },{}],12:[function(require,module,exports){ // The Substitution object provides utility methods to manipulate // the GSUB substitution table. 'use strict'; var check = require('./check'); var Layout = require('./layout'); /** * @exports opentype.Substitution * @class * @extends opentype.Layout * @param {opentype.Font} * @constructor */ var Substitution = function(font) { this.font = font; }; // Check if 2 arrays of primitives are equal. function arraysEqual(ar1, ar2) { var n = ar1.length; if (n !== ar2.length) { return false; } for (var i = 0; i < n; i++) { if (ar1[i] !== ar2[i]) { return false; } } return true; } // Find the first subtable of a lookup table in a particular format. function getSubstFormat(lookupTable, format, defaultSubtable) { var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; if (subtable.substFormat === format) { return subtable; } } if (defaultSubtable) { subtables.push(defaultSubtable); return defaultSubtable; } } Substitution.prototype = Layout; /** * Get or create the GSUB table. * @param {boolean} create - Whether to create a new one. * @return {Object} gsub - The GSUB table. */ Substitution.prototype.getGsubTable = function(create) { var gsub = this.font.tables.gsub; if (!gsub && create) { // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. this.font.tables.gsub = gsub = { version: 1, scripts: [{ tag: 'DFLT', script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, langSysRecords: [] } }], features: [], lookups: [] }; } return gsub; }; /** * List all single substitutions (lookup type 1) for a given script, language, and feature. * @param {string} script * @param {string} language * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) * @return {Array} substitutions - The list of substitutions. */ Substitution.prototype.getSingle = function(feature, script, language) { var substitutions = []; var lookupTable = this.getLookupTable(script, language, feature, 1); if (!lookupTable) { return substitutions; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var j; if (subtable.substFormat === 1) { var delta = subtable.deltaGlyphId; for (j = 0; j < glyphs.length; j++) { var glyph = glyphs[j]; substitutions.push({ sub: glyph, by: glyph + delta }); } } else { var substitute = subtable.substitute; for (j = 0; j < glyphs.length; j++) { substitutions.push({ sub: glyphs[j], by: substitute[j] }); } } } return substitutions; }; /** * List all alternates (lookup type 3) for a given script, language, and feature. * @param {string} script * @param {string} language * @param {string} feature - 4-character feature name ('aalt', 'salt'...) * @return {Array} alternates - The list of alternates */ Substitution.prototype.getAlternates = function(feature, script, language) { var alternates = []; var lookupTable = this.getLookupTable(script, language, feature, 3); if (!lookupTable) { return alternates; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var alternateSets = subtable.alternateSets; for (var j = 0; j < glyphs.length; j++) { alternates.push({ sub: glyphs[j], by: alternateSets[j] }); } } return alternates; }; /** * List all ligatures (lookup type 4) for a given script, language, and feature. * The result is an array of ligature objects like { sub: [ids], by: id } * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {string} script * @param {string} language * @return {Array} ligatures - The list of ligatures. */ Substitution.prototype.getLigatures = function(feature, script, language) { var ligatures = []; var lookupTable = this.getLookupTable(script, language, feature, 4); if (!lookupTable) { return []; } var subtables = lookupTable.subtables; for (var i = 0; i < subtables.length; i++) { var subtable = subtables[i]; var glyphs = this.expandCoverage(subtable.coverage); var ligatureSets = subtable.ligatureSets; for (var j = 0; j < glyphs.length; j++) { var startGlyph = glyphs[j]; var ligSet = ligatureSets[j]; for (var k = 0; k < ligSet.length; k++) { var lig = ligSet[k]; ligatures.push({ sub: [startGlyph].concat(lig.components), by: lig.ligGlyph }); } } } return ligatures; }; /** * Add or modify a single substitution (lookup type 1) * Format 2, more flexible, is always used. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2. * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addSingle = function(feature, substitution, script, language) { var lookupTable = this.getLookupTable(script, language, feature, 1, true); var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1 substFormat: 2, coverage: { format: 1, glyphs: [] }, substitute: [] }); check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = substitution.sub; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos < 0) { pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.substitute.splice(pos, 0, 0); } subtable.substitute[pos] = substitution.by; }; /** * Add or modify an alternate substitution (lookup type 1) * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, by: [ids] } * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addAlternate = function(feature, substitution, script, language) { var lookupTable = this.getLookupTable(script, language, feature, 3, true); var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1 substFormat: 1, coverage: { format: 1, glyphs: [] }, alternateSets: [] }); check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = substitution.sub; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos < 0) { pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.alternateSets.splice(pos, 0, 0); } subtable.alternateSets[pos] = substitution.by; }; /** * Add a ligature (lookup type 4) * Ligatures with more components must be stored ahead of those with fewer components in order to be found * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} ligature - { sub: [ids], by: id } * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.addLigature = function(feature, ligature, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; var lookupTable = this.getLookupTable(script, language, feature, 4, true); var subtable = lookupTable.subtables[0]; if (!subtable) { subtable = { // lookup type 4 subtable, format 1, coverage format 1 substFormat: 1, coverage: { format: 1, glyphs: [] }, ligatureSets: [] }; lookupTable.subtables[0] = subtable; } check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); var coverageGlyph = ligature.sub[0]; var ligComponents = ligature.sub.slice(1); var ligatureTable = { ligGlyph: ligature.by, components: ligComponents }; var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); if (pos >= 0) { // ligatureSet already exists var ligatureSet = subtable.ligatureSets[pos]; for (var i = 0; i < ligatureSet.length; i++) { // If ligature already exists, return. if (arraysEqual(ligatureSet[i].components, ligComponents)) { return; } } // ligature does not exist: add it. ligatureSet.push(ligatureTable); } else { // Create a new ligatureSet and add coverage for the first glyph. pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.ligatureSets.splice(pos, 0, [ligatureTable]); } }; /** * List all feature data for a given script and language. * @param {string} feature - 4-letter feature name * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] * @return {Array} substitutions - The list of substitutions. */ Substitution.prototype.getFeature = function(feature, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.getSingle(feature, script, language); } switch (feature) { case 'aalt': case 'salt': return this.getSingle(feature, script, language) .concat(this.getAlternates(feature, script, language)); case 'dlig': case 'liga': case 'rlig': return this.getLigatures(feature, script, language); } }; /** * Add a substitution to a feature for a given script and language. * @param {string} feature - 4-letter feature name * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) * @param {string} [script='DFLT'] * @param {string} [language='DFLT'] */ Substitution.prototype.add = function(feature, sub, script, language) { script = script || 'DFLT'; language = language || 'DFLT'; if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.addSingle(feature, sub, script, language); } switch (feature) { case 'aalt': case 'salt': if (typeof sub.by === 'number') { return this.addSingle(feature, sub, script, language); } return this.addAlternate(feature, sub, script, language); case 'dlig': case 'liga': case 'rlig': return this.addLigature(feature, sub, script, language); } }; module.exports = Substitution; },{"./check":2,"./layout":8}],13:[function(require,module,exports){ // Table metadata 'use strict'; var check = require('./check'); var encode = require('./types').encode; var sizeOf = require('./types').sizeOf; /** * @exports opentype.Table * @class * @param {string} tableName * @param {Array} fields * @param {Object} options * @constructor */ function Table(tableName, fields, options) { var i; for (i = 0; i < fields.length; i += 1) { var field = fields[i]; this[field.name] = field.value; } this.tableName = tableName; this.fields = fields; if (options) { var optionKeys = Object.keys(options); for (i = 0; i < optionKeys.length; i += 1) { var k = optionKeys[i]; var v = options[k]; if (this[k] !== undefined) { this[k] = v; } } } } /** * Encodes the table and returns an array of bytes * @return {Array} */ Table.prototype.encode = function() { return encode.TABLE(this); }; /** * Get the size of the table. * @return {number} */ Table.prototype.sizeOf = function() { return sizeOf.TABLE(this); }; /** * @private */ function ushortList(itemName, list, count) { if (count === undefined) { count = list.length; } var fields = new Array(list.length + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < list.length; i++) { fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; } return fields; } /** * @private */ function tableList(itemName, records, itemCallback) { var count = records.length; var fields = new Array(count + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; } return fields; } /** * @private */ function recordList(itemName, records, itemCallback) { var count = records.length; var fields = []; fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields = fields.concat(itemCallback(records[i], i)); } return fields; } // Common Layout Tables /** * @exports opentype.Coverage * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function Coverage(coverageTable) { if (coverageTable.format === 1) { Table.call(this, 'coverageTable', [{name: 'coverageFormat', type: 'USHORT', value: 1}] .concat(ushortList('glyph', coverageTable.glyphs)) ); } else { check.assert(false, 'Can\'t create coverage table format 2 yet.'); } } Coverage.prototype = Object.create(Table.prototype); Coverage.prototype.constructor = Coverage; function ScriptList(scriptListTable) { Table.call(this, 'scriptListTable', recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { var script = scriptRecord.script; var defaultLangSys = script.defaultLangSys; check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); return [ {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { var langSys = langSysRecord.langSys; return [ {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} ].concat(ushortList('featureIndex', langSys.featureIndexes)))} ]; })))} ]; }) ); } ScriptList.prototype = Object.create(Table.prototype); ScriptList.prototype.constructor = ScriptList; /** * @exports opentype.FeatureList * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function FeatureList(featureListTable) { Table.call(this, 'featureListTable', recordList('featureRecord', featureListTable, function(featureRecord, i) { var feature = featureRecord.feature; return [ {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ {name: 'featureParams', type: 'USHORT', value: feature.featureParams}, ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} ]; }) ); } FeatureList.prototype = Object.create(Table.prototype); FeatureList.prototype.constructor = FeatureList; /** * @exports opentype.LookupList * @class * @param {opentype.Table} * @param {Object} * @constructor * @extends opentype.Table */ function LookupList(lookupListTable, subtableMakers) { Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { var subtableCallback = subtableMakers[lookupTable.lookupType]; check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); return new Table('lookupTable', [ {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); })); } LookupList.prototype = Object.create(Table.prototype); LookupList.prototype.constructor = LookupList; // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) // Don't use offsets inside Records (probable bug), only in Tables. exports.Record = exports.Table = Table; exports.Coverage = Coverage; exports.ScriptList = ScriptList; exports.FeatureList = FeatureList; exports.LookupList = LookupList; exports.ushortList = ushortList; exports.tableList = tableList; exports.recordList = recordList; },{"./check":2,"./types":32}],14:[function(require,module,exports){ // The `CFF` table contains the glyph outlines in PostScript format. // https://www.microsoft.com/typography/OTSPEC/cff.htm // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf 'use strict'; var encoding = require('../encoding'); var glyphset = require('../glyphset'); var parse = require('../parse'); var path = require('../path'); var table = require('../table'); // Custom equals function that can also check lists. function equals(a, b) { if (a === b) { return true; } else if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (var i = 0; i < a.length; i += 1) { if (!equals(a[i], b[i])) { return false; } } return true; } else { return false; } } // Parse a `CFF` INDEX array. // An index array consists of a list of offsets, then a list of objects at those offsets. function parseCFFIndex(data, start, conversionFn) { //var i, objectOffset, endOffset; var offsets = []; var objects = []; var count = parse.getCard16(data, start); var i; var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + ((count + 1) * offsetSize) + 2; var pos = start + 3; for (i = 0; i < count + 1; i += 1) { offsets.push(parse.getOffset(data, pos, offsetSize)); pos += offsetSize; } // The total size of the index array is 4 header bytes + the value of the last offset. endOffset = objectOffset + offsets[count]; } else { endOffset = start + 2; } for (i = 0; i < offsets.length - 1; i += 1) { var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); if (conversionFn) { value = conversionFn(value); } objects.push(value); } return {objects: objects, startOffset: start, endOffset: endOffset}; } // Parse a `CFF` DICT real value. function parseFloatOperand(parser) { var s = ''; var eof = 15; var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; while (true) { var b = parser.parseByte(); var n1 = b >> 4; var n2 = b & 15; if (n1 === eof) { break; } s += lookup[n1]; if (n2 === eof) { break; } s += lookup[n2]; } return parseFloat(s); } // Parse a `CFF` DICT operand. function parseOperand(parser, b0) { var b1; var b2; var b3; var b4; if (b0 === 28) { b1 = parser.parseByte(); b2 = parser.parseByte(); return b1 << 8 | b2; } if (b0 === 29) { b1 = parser.parseByte(); b2 = parser.parseByte(); b3 = parser.parseByte(); b4 = parser.parseByte(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } if (b0 === 30) { return parseFloatOperand(parser); } if (b0 >= 32 && b0 <= 246) { return b0 - 139; } if (b0 >= 247 && b0 <= 250) { b1 = parser.parseByte(); return (b0 - 247) * 256 + b1 + 108; } if (b0 >= 251 && b0 <= 254) { b1 = parser.parseByte(); return -(b0 - 251) * 256 - b1 - 108; } throw new Error('Invalid b0 ' + b0); } // Convert the entries returned by `parseDict` to a proper dictionary. // If a value is a list of one, it is unpacked. function entriesToObject(entries) { var o = {}; for (var i = 0; i < entries.length; i += 1) { var key = entries[i][0]; var values = entries[i][1]; var value; if (values.length === 1) { value = values[0]; } else { value = values; } if (o.hasOwnProperty(key)) { throw new Error('Object ' + o + ' already has key ' + key); } o[key] = value; } return o; } // Parse a `CFF` DICT object. // A dictionary contains key-value pairs in a compact tokenized format. function parseCFFDict(data, start, size) { start = start !== undefined ? start : 0; var parser = new parse.Parser(data, start); var entries = []; var operands = []; size = size !== undefined ? size : data.length; while (parser.relativeOffset < size) { var op = parser.parseByte(); // The first byte for each dict item distinguishes between operator (key) and operand (value). // Values <= 21 are operators. if (op <= 21) { // Two-byte operators have an initial escape byte of 12. if (op === 12) { op = 1200 + parser.parseByte(); } entries.push([op, operands]); operands = []; } else { // Since the operands (values) come before the operators (keys), we store all operands in a list // until we encounter an operator. operands.push(parseOperand(parser, op)); } } return entriesToObject(entries); } // Given a String Index (SID), return the value of the string. // Strings below index 392 are standard CFF strings and are not encoded in the font. function getCFFString(strings, index) { if (index <= 390) { index = encoding.cffStandardStrings[index]; } else { index = strings[index - 391]; } return index; } // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. function interpretDict(dict, meta, strings) { var newDict = {}; // Because we also want to include missing values, we start out from the meta list // and lookup values in the dict. for (var i = 0; i < meta.length; i += 1) { var m = meta[i]; var value = dict[m.op]; if (value === undefined) { value = m.value !== undefined ? m.value : null; } if (m.type === 'SID') { value = getCFFString(strings, value); } newDict[m.name] = value; } return newDict; } // Parse the CFF header. function parseCFFHeader(data, start) { var header = {}; header.formatMajor = parse.getCard8(data, start); header.formatMinor = parse.getCard8(data, start + 1); header.size = parse.getCard8(data, start + 2); header.offsetSize = parse.getCard8(data, start + 3); header.startOffset = start; header.endOffset = start + 4; return header; } var TOP_DICT_META = [ {name: 'version', op: 0, type: 'SID'}, {name: 'notice', op: 1, type: 'SID'}, {name: 'copyright', op: 1200, type: 'SID'}, {name: 'fullName', op: 2, type: 'SID'}, {name: 'familyName', op: 3, type: 'SID'}, {name: 'weight', op: 4, type: 'SID'}, {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, {name: 'italicAngle', op: 1202, type: 'number', value: 0}, {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, {name: 'paintType', op: 1205, type: 'number', value: 0}, {name: 'charstringType', op: 1206, type: 'number', value: 2}, {name: 'fontMatrix', op: 1207, type: ['real', 'real', 'real', 'real', 'real', 'real'], value: [0.001, 0, 0, 0.001, 0, 0]}, {name: 'uniqueId', op: 13, type: 'number'}, {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, {name: 'xuid', op: 14, type: [], value: null}, {name: 'charset', op: 15, type: 'offset', value: 0}, {name: 'encoding', op: 16, type: 'offset', value: 0}, {name: 'charStrings', op: 17, type: 'offset', value: 0}, {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]} ]; var PRIVATE_DICT_META = [ {name: 'subrs', op: 19, type: 'offset', value: 0}, {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, {name: 'nominalWidthX', op: 21, type: 'number', value: 0} ]; // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. // The top dictionary contains the essential metadata for the font, together with the private dictionary. function parseCFFTopDict(data, strings) { var dict = parseCFFDict(data, 0, data.byteLength); return interpretDict(dict, TOP_DICT_META, strings); } // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. function parseCFFPrivateDict(data, start, size, strings) { var dict = parseCFFDict(data, start, size); return interpretDict(dict, PRIVATE_DICT_META, strings); } // Parse the CFF charset table, which contains internal names for all the glyphs. // This function will return a list of glyph names. // See Adobe TN #5176 chapter 13, "Charsets". function parseCFFCharset(data, start, nGlyphs, strings) { var i; var sid; var count; var parser = new parse.Parser(data, start); // The .notdef glyph is not included, so subtract 1. nGlyphs -= 1; var charset = ['.notdef']; var format = parser.parseCard8(); if (format === 0) { for (i = 0; i < nGlyphs; i += 1) { sid = parser.parseSID(); charset.push(getCFFString(strings, sid)); } } else if (format === 1) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard8(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else if (format === 2) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard16(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else { throw new Error('Unknown charset format ' + format); } return charset; } // Parse the CFF encoding data. Only one encoding can be specified per font. // See Adobe TN #5176 chapter 12, "Encodings". function parseCFFEncoding(data, start, charset) { var i; var code; var enc = {}; var parser = new parse.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { var nCodes = parser.parseCard8(); for (i = 0; i < nCodes; i += 1) { code = parser.parseCard8(); enc[code] = i; } } else if (format === 1) { var nRanges = parser.parseCard8(); code = 1; for (i = 0; i < nRanges; i += 1) { var first = parser.parseCard8(); var nLeft = parser.parseCard8(); for (var j = first; j <= first + nLeft; j += 1) { enc[j] = code; code += 1; } } } else { throw new Error('Unknown encoding format ' + format); } return new encoding.CffEncoding(enc, charset); } // Take in charstring code and return a Glyph object. // The encoding is described in the Type 2 Charstring Format // https://www.microsoft.com/typography/OTSPEC/charstr2.htm function parseCFFCharstring(font, glyph, code) { var c1x; var c1y; var c2x; var c2y; var p = new path.Path(); var stack = []; var nStems = 0; var haveWidth = false; var width = font.defaultWidthX; var open = false; var x = 0; var y = 0; function newContour(x, y) { if (open) { p.closePath(); } p.moveTo(x, y); open = true; } function parseStems() { var hasWidthArg; // The number of stem operators on the stack is always even. // If the value is uneven, that means a width is specified. hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + font.nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse(code) { var b1; var b2; var b3; var b4; var codeIndex; var subrCode; var jpx; var jpy; var c3x; var c3y; var c4x; var c4y; var i = 0; while (i < code.length) { var v = code[i]; i += 1; switch (v) { case 1: // hstem parseStems(); break; case 3: // vstem parseStems(); break; case 4: // vmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); newContour(x, y); break; case 5: // rlineto while (stack.length > 0) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } break; case 6: // hlineto while (stack.length > 0) { x += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } y += stack.shift(); p.lineTo(x, y); } break; case 7: // vlineto while (stack.length > 0) { y += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } x += stack.shift(); p.lineTo(x, y); } break; case 8: // rrcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: // callsubr codeIndex = stack.pop() + font.subrsBias; subrCode = font.subrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 11: // return return; case 12: // flex operators v = code[i]; i += 1; switch (v) { case 35: // flex // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 y = c4y + stack.shift(); // dy6 stack.shift(); // flex depth p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 34: // hflex // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- c1x = x + stack.shift(); // dx1 c1y = y; // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = y; // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 36: // hflex1 // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 37: // flex1 // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 if (Math.abs(c4x - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); stack.length = 0; } break; case 14: // endchar if (stack.length > 0 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } if (open) { p.closePath(); open = false; } break; case 18: // hstemhm parseStems(); break; case 19: // hintmask case 20: // cntrmask parseStems(); i += (nStems + 7) >> 3; break; case 21: // rmoveto if (stack.length > 2 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); newContour(x, y); break; case 22: // hmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + font.nominalWidthX; haveWidth = true; } x += stack.pop(); newContour(x, y); break; case 23: // vstemhm parseStems(); break; case 24: // rcurveline while (stack.length > 2) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); p.lineTo(x, y); break; case 25: // rlinecurve while (stack.length > 6) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); break; case 26: // vvcurveto if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 27: // hhcurveto if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: // shortint b1 = code[i]; b2 = code[i + 1]; stack.push(((b1 << 24) | (b2 << 16)) >> 16); i += 2; break; case 29: // callgsubr codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 30: // vhcurveto while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 31: // hvcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v < 32) { console.log('Glyph ' + glyph.index + ': unknown operator ' + v); } else if (v < 247) { stack.push(v - 139); } else if (v < 251) { b1 = code[i]; i += 1; stack.push((v - 247) * 256 + b1 + 108); } else if (v < 255) { b1 = code[i]; i += 1; stack.push(-(v - 251) * 256 - b1 - 108); } else { b1 = code[i]; b2 = code[i + 1]; b3 = code[i + 2]; b4 = code[i + 3]; i += 4; stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); } } } } parse(code); glyph.advanceWidth = width; return p; } // Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs) { var bias; if (subrs.length < 1240) { bias = 107; } else if (subrs.length < 33900) { bias = 1131; } else { bias = 32768; } return bias; } // Parse the `CFF` table, which contains the glyph outlines in PostScript format. function parseCFFTable(data, start, font) { font.tables.cff = {}; var header = parseCFFHeader(data, start); var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); font.gsubrs = globalSubrIndex.objects; font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); var topDictData = new DataView(new Uint8Array(topDictIndex.objects[0]).buffer); var topDict = parseCFFTopDict(topDictData, stringIndex.objects); font.tables.cff.topDict = topDict; var privateDictOffset = start + topDict['private'][1]; var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict['private'][0], stringIndex.objects); font.defaultWidthX = privateDict.defaultWidthX; font.nominalWidthX = privateDict.nominalWidthX; if (privateDict.subrs !== 0) { var subrOffset = privateDictOffset + privateDict.subrs; var subrIndex = parseCFFIndex(data, subrOffset); font.subrs = subrIndex.objects; font.subrsBias = calcCFFSubroutineBias(font.subrs); } else { font.subrs = []; font.subrsBias = 0; } // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); font.nGlyphs = charStringsIndex.objects.length; var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); if (topDict.encoding === 0) { // Standard encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffStandardEncoding, charset); } else if (topDict.encoding === 1) { // Expert encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffExpertEncoding, charset); } else { font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); } // Prefer the CMAP encoding to the CFF encoding. font.encoding = font.encoding || font.cffEncoding; font.glyphs = new glyphset.GlyphSet(font); for (var i = 0; i < font.nGlyphs; i += 1) { var charString = charStringsIndex.objects[i]; font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); } } // Convert a string to a String ID (SID). // The list of strings is modified in place. function encodeString(s, strings) { var sid; // Is the string in the CFF standard strings? var i = encoding.cffStandardStrings.indexOf(s); if (i >= 0) { sid = i; } // Is the string already in the string index? i = strings.indexOf(s); if (i >= 0) { sid = i + encoding.cffStandardStrings.length; } else { sid = encoding.cffStandardStrings.length + strings.length; strings.push(s); } return sid; } function makeHeader() { return new table.Record('Header', [ {name: 'major', type: 'Card8', value: 1}, {name: 'minor', type: 'Card8', value: 0}, {name: 'hdrSize', type: 'Card8', value: 4}, {name: 'major', type: 'Card8', value: 1} ]); } function makeNameIndex(fontNames) { var t = new table.Record('Name INDEX', [ {name: 'names', type: 'INDEX', value: []} ]); t.names = []; for (var i = 0; i < fontNames.length; i += 1) { t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); } return t; } // Given a dictionary's metadata, create a DICT structure. function makeDict(meta, attrs, strings) { var m = {}; for (var i = 0; i < meta.length; i += 1) { var entry = meta[i]; var value = attrs[entry.name]; if (value !== undefined && !equals(value, entry.value)) { if (entry.type === 'SID') { value = encodeString(value, strings); } m[entry.op] = {name: entry.name, type: entry.type, value: value}; } } return m; } // The Top DICT houses the global font attributes. function makeTopDict(attrs, strings) { var t = new table.Record('Top DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(TOP_DICT_META, attrs, strings); return t; } function makeTopDictIndex(topDict) { var t = new table.Record('Top DICT INDEX', [ {name: 'topDicts', type: 'INDEX', value: []} ]); t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; return t; } function makeStringIndex(strings) { var t = new table.Record('String INDEX', [ {name: 'strings', type: 'INDEX', value: []} ]); t.strings = []; for (var i = 0; i < strings.length; i += 1) { t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); } return t; } function makeGlobalSubrIndex() { // Currently we don't use subroutines. return new table.Record('Global Subr INDEX', [ {name: 'subrs', type: 'INDEX', value: []} ]); } function makeCharsets(glyphNames, strings) { var t = new table.Record('Charsets', [ {name: 'format', type: 'Card8', value: 0} ]); for (var i = 0; i < glyphNames.length; i += 1) { var glyphName = glyphNames[i]; var glyphSID = encodeString(glyphName, strings); t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); } return t; } function glyphToOps(glyph) { var ops = []; var path = glyph.path; ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); var x = 0; var y = 0; for (var i = 0; i < path.commands.length; i += 1) { var dx; var dy; var cmd = path.commands[i]; if (cmd.type === 'Q') { // CFF only supports bézier curves, so convert the quad to a bézier. var _13 = 1 / 3; var _23 = 2 / 3; // We're going to create a new command so we don't change the original path. cmd = { type: 'C', x: cmd.x, y: cmd.y, x1: _13 * x + _23 * cmd.x1, y1: _13 * y + _23 * cmd.y1, x2: _13 * cmd.x + _23 * cmd.x1, y2: _13 * cmd.y + _23 * cmd.y1 }; } if (cmd.type === 'M') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rmoveto', type: 'OP', value: 21}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'L') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rlineto', type: 'OP', value: 5}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'C') { var dx1 = Math.round(cmd.x1 - x); var dy1 = Math.round(cmd.y1 - y); var dx2 = Math.round(cmd.x2 - cmd.x1); var dy2 = Math.round(cmd.y2 - cmd.y1); dx = Math.round(cmd.x - cmd.x2); dy = Math.round(cmd.y - cmd.y2); ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rrcurveto', type: 'OP', value: 8}); x = Math.round(cmd.x); y = Math.round(cmd.y); } // Contours are closed automatically. } ops.push({name: 'endchar', type: 'OP', value: 14}); return ops; } function makeCharStringsIndex(glyphs) { var t = new table.Record('CharStrings INDEX', [ {name: 'charStrings', type: 'INDEX', value: []} ]); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var ops = glyphToOps(glyph); t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); } return t; } function makePrivateDict(attrs, strings) { var t = new table.Record('Private DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); return t; } function makeCFFTable(glyphs, options) { var t = new table.Table('CFF ', [ {name: 'header', type: 'RECORD'}, {name: 'nameIndex', type: 'RECORD'}, {name: 'topDictIndex', type: 'RECORD'}, {name: 'stringIndex', type: 'RECORD'}, {name: 'globalSubrIndex', type: 'RECORD'}, {name: 'charsets', type: 'RECORD'}, {name: 'charStringsIndex', type: 'RECORD'}, {name: 'privateDict', type: 'RECORD'} ]); var fontScale = 1 / options.unitsPerEm; // We use non-zero values for the offsets so that the DICT encodes them. // This is important because the size of the Top DICT plays a role in offset calculation, // and the size shouldn't change after we've written correct offsets. var attrs = { version: options.version, fullName: options.fullName, familyName: options.familyName, weight: options.weightName, fontBBox: options.fontBBox || [0, 0, 0, 0], fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], charset: 999, encoding: 0, charStrings: 999, private: [0, 999] }; var privateAttrs = {}; var glyphNames = []; var glyph; // Skip first glyph (.notdef) for (var i = 1; i < glyphs.length; i += 1) { glyph = glyphs.get(i); glyphNames.push(glyph.name); } var strings = []; t.header = makeHeader(); t.nameIndex = makeNameIndex([options.postScriptName]); var topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); t.globalSubrIndex = makeGlobalSubrIndex(); t.charsets = makeCharsets(glyphNames, strings); t.charStringsIndex = makeCharStringsIndex(glyphs); t.privateDict = makePrivateDict(privateAttrs, strings); // Needs to come at the end, to encode all custom strings used in the font. t.stringIndex = makeStringIndex(strings); var startOffset = t.header.sizeOf() + t.nameIndex.sizeOf() + t.topDictIndex.sizeOf() + t.stringIndex.sizeOf() + t.globalSubrIndex.sizeOf(); attrs.charset = startOffset; // We use the CFF standard encoding; proper encoding will be handled in cmap. attrs.encoding = 0; attrs.charStrings = attrs.charset + t.charsets.sizeOf(); attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); // Recreate the Top DICT INDEX with the correct offsets. topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); return t; } exports.parse = parseCFFTable; exports.make = makeCFFTable; },{"../encoding":4,"../glyphset":7,"../parse":10,"../path":11,"../table":13}],15:[function(require,module,exports){ // The `cmap` table stores the mappings from characters to glyphs. // https://www.microsoft.com/typography/OTSPEC/cmap.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function parseCmapTableFormat12(cmap, p) { var i; //Skip reserved. p.parseUShort(); // Length in bytes of the sub-tables. cmap.length = p.parseULong(); cmap.language = p.parseULong(); var groupCount; cmap.groupCount = groupCount = p.parseULong(); cmap.glyphIndexMap = {}; for (i = 0; i < groupCount; i += 1) { var startCharCode = p.parseULong(); var endCharCode = p.parseULong(); var startGlyphId = p.parseULong(); for (var c = startCharCode; c <= endCharCode; c += 1) { cmap.glyphIndexMap[c] = startGlyphId; startGlyphId++; } } } function parseCmapTableFormat4(cmap, p, data, start, offset) { var i; // Length in bytes of the sub-tables. cmap.length = p.parseUShort(); cmap.language = p.parseUShort(); // segCount is stored x 2. var segCount; cmap.segCount = segCount = p.parseUShort() >> 1; // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); // The "unrolled" mapping from character codes to glyph indices. cmap.glyphIndexMap = {}; var endCountParser = new parse.Parser(data, start + offset + 14); var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); var glyphIndexOffset = start + offset + 16 + segCount * 8; for (i = 0; i < segCount - 1; i += 1) { var glyphIndex; var endCount = endCountParser.parseUShort(); var startCount = startCountParser.parseUShort(); var idDelta = idDeltaParser.parseShort(); var idRangeOffset = idRangeOffsetParser.parseUShort(); for (var c = startCount; c <= endCount; c += 1) { if (idRangeOffset !== 0) { // The idRangeOffset is relative to the current position in the idRangeOffset array. // Take the current offset in the idRangeOffset array. glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); // Add the value of the idRangeOffset, which will move us into the glyphIndex array. glyphIndexOffset += idRangeOffset; // Then add the character index of the current segment, multiplied by 2 for USHORTs. glyphIndexOffset += (c - startCount) * 2; glyphIndex = parse.getUShort(data, glyphIndexOffset); if (glyphIndex !== 0) { glyphIndex = (glyphIndex + idDelta) & 0xFFFF; } } else { glyphIndex = (c + idDelta) & 0xFFFF; } cmap.glyphIndexMap[c] = glyphIndex; } } } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4 and 12. // This function returns a `CmapEncoding` object or null if no supported format could be found. function parseCmapTable(data, start) { var i; var cmap = {}; cmap.version = parse.getUShort(data, start); check.argument(cmap.version === 0, 'cmap table version should be 0.'); // The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 3" table. This is a Windows format. cmap.numTables = parse.getUShort(data, start + 2); var offset = -1; for (i = cmap.numTables - 1; i >= 0; i -= 1) { var platformId = parse.getUShort(data, start + 4 + (i * 8)); var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) { offset = parse.getULong(data, start + 4 + (i * 8) + 4); break; } } if (offset === -1) { // There is no cmap table in the font that we support, so return null. // This font will be marked as unsupported. return null; } var p = new parse.Parser(data, start + offset); cmap.format = p.parseUShort(); if (cmap.format === 12) { parseCmapTableFormat12(cmap, p); } else if (cmap.format === 4) { parseCmapTableFormat4(cmap, p, data, start, offset); } else { throw new Error('Only format 4 and 12 cmap tables are supported.'); } return cmap; } function addSegment(t, code, glyphIndex) { t.segments.push({ end: code, start: code, delta: -(code - glyphIndex), offset: 0 }); } function addTerminatorSegment(t) { t.segments.push({ end: 0xFFFF, start: 0xFFFF, delta: 1, offset: 0 }); } function makeCmapTable(glyphs) { var i; var t = new table.Table('cmap', [ {name: 'version', type: 'USHORT', value: 0}, {name: 'numTables', type: 'USHORT', value: 1}, {name: 'platformID', type: 'USHORT', value: 3}, {name: 'encodingID', type: 'USHORT', value: 1}, {name: 'offset', type: 'ULONG', value: 12}, {name: 'format', type: 'USHORT', value: 4}, {name: 'length', type: 'USHORT', value: 0}, {name: 'language', type: 'USHORT', value: 0}, {name: 'segCountX2', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); t.segments = []; for (i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { addSegment(t, glyph.unicodes[j], i); } t.segments = t.segments.sort(function(a, b) { return a.start - b.start; }); } addTerminatorSegment(t); var segCount; segCount = t.segments.length; t.segCountX2 = segCount * 2; t.searchRange = Math.pow(2, Math.floor(Math.log(segCount) / Math.log(2))) * 2; t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); t.rangeShift = t.segCountX2 - t.searchRange; // Set up parallel segment arrays. var endCounts = []; var startCounts = []; var idDeltas = []; var idRangeOffsets = []; var glyphIds = []; for (i = 0; i < segCount; i += 1) { var segment = t.segments[i]; endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); if (segment.glyphId !== undefined) { glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); } } t.fields = t.fields.concat(endCounts); t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); t.fields = t.fields.concat(startCounts); t.fields = t.fields.concat(idDeltas); t.fields = t.fields.concat(idRangeOffsets); t.fields = t.fields.concat(glyphIds); t.length = 14 + // Subtable header endCounts.length * 2 + 2 + // reservedPad startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; return t; } exports.parse = parseCmapTable; exports.make = makeCmapTable; },{"../check":2,"../parse":10,"../table":13}],16:[function(require,module,exports){ // The `fvar` table stores font variation axes and instances. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function addName(name, names) { var nameString = JSON.stringify(name); var nameID = 256; for (var nameKey in names) { var n = parseInt(nameKey); if (!n || n < 256) { continue; } if (JSON.stringify(names[nameKey]) === nameString) { return n; } if (nameID <= n) { nameID = n + 1; } } names[nameID] = name; return nameID; } function makeFvarAxis(n, axis, names) { var nameID = addName(axis.name, names); return [ {name: 'tag_' + n, type: 'TAG', value: axis.tag}, {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16}, {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16}, {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16}, {name: 'flags_' + n, type: 'USHORT', value: 0}, {name: 'nameID_' + n, type: 'USHORT', value: nameID} ]; } function parseFvarAxis(data, start, names) { var axis = {}; var p = new parse.Parser(data, start); axis.tag = p.parseTag(); axis.minValue = p.parseFixed(); axis.defaultValue = p.parseFixed(); axis.maxValue = p.parseFixed(); p.skip('uShort', 1); // reserved for flags; no values defined axis.name = names[p.parseUShort()] || {}; return axis; } function makeFvarInstance(n, inst, axes, names) { var nameID = addName(inst.name, names); var fields = [ {name: 'nameID_' + n, type: 'USHORT', value: nameID}, {name: 'flags_' + n, type: 'USHORT', value: 0} ]; for (var i = 0; i < axes.length; ++i) { var axisTag = axes[i].tag; fields.push({ name: 'axis_' + n + ' ' + axisTag, type: 'FIXED', value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p = new parse.Parser(data, start); inst.name = names[p.parseUShort()] || {}; p.skip('uShort', 1); // reserved for flags; no values defined inst.coordinates = {}; for (var i = 0; i < axes.length; ++i) { inst.coordinates[axes[i].tag] = p.parseFixed(); } return inst; } function makeFvarTable(fvar, names) { var result = new table.Table('fvar', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'offsetToData', type: 'USHORT', value: 0}, {name: 'countSizePairs', type: 'USHORT', value: 2}, {name: 'axisCount', type: 'USHORT', value: fvar.axes.length}, {name: 'axisSize', type: 'USHORT', value: 20}, {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length}, {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4} ]); result.offsetToData = result.sizeOf(); for (var i = 0; i < fvar.axes.length; i++) { result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); } for (var j = 0; j < fvar.instances.length; j++) { result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); } return result; } function parseFvarTable(data, start, names) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.'); var offsetToData = p.parseOffset16(); // Skip countSizePairs. p.skip('uShort', 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); var instanceCount = p.parseUShort(); var instanceSize = p.parseUShort(); var axes = []; for (var i = 0; i < axisCount; i++) { axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); } var instances = []; var instanceStart = start + offsetToData + axisCount * axisSize; for (var j = 0; j < instanceCount; j++) { instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); } return {axes: axes, instances: instances}; } exports.make = makeFvarTable; exports.parse = parseFvarTable; },{"../check":2,"../parse":10,"../table":13}],17:[function(require,module,exports){ // The `glyf` table describes the glyphs in TrueType outline format. // http://www.microsoft.com/typography/otspec/glyf.htm 'use strict'; var check = require('../check'); var glyphset = require('../glyphset'); var parse = require('../parse'); var path = require('../path'); // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; } // Parse a TrueType glyph. function parseGlyph(glyph, data, start) { var p = new parse.Parser(data, start); glyph.numberOfContours = p.parseShort(); glyph._xMin = p.parseShort(); glyph._yMin = p.parseShort(); glyph._xMax = p.parseShort(); glyph._yMax = p.parseShort(); var flags; var flag; if (glyph.numberOfContours > 0) { var i; // This glyph is not a composite. var endPointIndices = glyph.endPointIndices = []; for (i = 0; i < glyph.numberOfContours; i += 1) { endPointIndices.push(p.parseUShort()); } glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (i = 0; i < numberOfCoordinates; i += 1) { flag = p.parseByte(); flags.push(flag); // If bit 3 is set, we repeat this flag n times, where n is the next byte. if ((flag & 8) > 0) { var repeatCount = p.parseByte(); for (var j = 0; j < repeatCount; j += 1) { flags.push(flag); i += 1; } } } check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); if (endPointIndices.length > 0) { var points = []; var point; // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if (numberOfCoordinates > 0) { for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = {}; point.onCurve = !!(flag & 1); point.lastPointOfContour = endPointIndices.indexOf(i) >= 0; points.push(point); } var px = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.x = parseGlyphCoordinate(p, flag, px, 2, 16); px = point.x; } var py = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.y = parseGlyphCoordinate(p, flag, py, 4, 32); py = point.y; } } glyph.points = points; } else { glyph.points = []; } } else if (glyph.numberOfContours === 0) { glyph.points = []; } else { glyph.isComposite = true; glyph.points = []; glyph.components = []; var moreComponents = true; while (moreComponents) { flags = p.parseUShort(); var component = { glyphIndex: p.parseUShort(), xScale: 1, scale01: 0, scale10: 0, yScale: 1, dx: 0, dy: 0 }; if ((flags & 1) > 0) { // The arguments are words if ((flags & 2) > 0) { // values are offset component.dx = p.parseShort(); component.dy = p.parseShort(); } else { // values are matched points component.matchedPoints = [p.parseUShort(), p.parseUShort()]; } } else { // The arguments are bytes if ((flags & 2) > 0) { // values are offset component.dx = p.parseChar(); component.dy = p.parseChar(); } else { // values are matched points component.matchedPoints = [p.parseByte(), p.parseByte()]; } } if ((flags & 8) > 0) { // We have a scale component.xScale = component.yScale = p.parseF2Dot14(); } else if ((flags & 64) > 0) { // We have an X / Y scale component.xScale = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } else if ((flags & 128) > 0) { // We have a 2x2 transformation component.xScale = p.parseF2Dot14(); component.scale01 = p.parseF2Dot14(); component.scale10 = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } glyph.components.push(component); moreComponents = !!(flags & 32); } } } // Transform an array of points and return a new array. function transformPoints(points, transform) { var newPoints = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; var newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } function getContours(points) { var contours = []; var currentContour = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; } // Convert the TrueType glyph outline to a Path. function getPath(points) { var p = new path.Path(); if (!points) { return p; } var contours = getContours(points); for (var i = 0; i < contours.length; i += 1) { var contour = contours[i]; var firstPt = contour[0]; var lastPt = contour[contour.length - 1]; var curvePt; var realFirstPoint; if (firstPt.onCurve) { curvePt = null; // The first point will be consumed by the moveTo command, // so skip it in the loop. realFirstPoint = true; } else { if (lastPt.onCurve) { // If the first point is off-curve and the last point is on-curve, // start at the last point. firstPt = lastPt; } else { // If both first and last points are off-curve, start at their middle. firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 }; } curvePt = firstPt; // The first point is synthesized, so don't skip the real first point. realFirstPoint = false; } p.moveTo(firstPt.x, firstPt.y); for (var j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) { var pt = contour[j]; var prevPt = j === 0 ? firstPt : contour[j - 1]; if (prevPt.onCurve && pt.onCurve) { // This is a straight line. p.lineTo(pt.x, pt.y); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { var midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); curvePt = null; } else { throw new Error('Invalid state.'); } } if (firstPt !== lastPt) { // Connect the last and first points if (curvePt) { p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); } else { p.lineTo(firstPt.x, firstPt.y); } } } p.closePath(); return p; } function buildPath(glyphs, glyph) { if (glyph.isComposite) { for (var j = 0; j < glyph.components.length; j += 1) { var component = glyph.components[j]; var componentGlyph = glyphs.get(component.glyphIndex); // Force the ttfGlyphLoader to parse the glyph. componentGlyph.getPath(); if (componentGlyph.points) { var transformedPoints; if (component.matchedPoints === undefined) { // component positioned by offset transformedPoints = transformPoints(componentGlyph.points, component); } else { // component positioned by matched points if ((component.matchedPoints[0] > glyph.points.length - 1) || (component.matchedPoints[1] > componentGlyph.points.length - 1)) { throw Error('Matched points out of range in ' + glyph.name); } var firstPt = glyph.points[component.matchedPoints[0]]; var secondPt = componentGlyph.points[component.matchedPoints[1]]; var transform = { xScale: component.xScale, scale01: component.scale01, scale10: component.scale10, yScale: component.yScale, dx: 0, dy: 0 }; secondPt = transformPoints([secondPt], transform)[0]; transform.dx = firstPt.x - secondPt.x; transform.dy = firstPt.y - secondPt.y; transformedPoints = transformPoints(componentGlyph.points, transform); } glyph.points = glyph.points.concat(transformedPoints); } } } return getPath(glyph.points); } // Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data, start, loca, font) { var glyphs = new glyphset.GlyphSet(font); var i; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { var offset = loca[i]; var nextOffset = loca[i + 1]; if (offset !== nextOffset) { glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); } else { glyphs.push(i, glyphset.glyphLoader(font, i)); } } return glyphs; } exports.parse = parseGlyfTable; },{"../check":2,"../glyphset":7,"../parse":10,"../path":11}],18:[function(require,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); // Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables. // These lists are unused by now, this function is just the basis for a real parsing. function parseTaggedListTable(data, start) { var p = new parse.Parser(data, start); var n = p.parseUShort(); var list = []; for (var i = 0; i < n; i++) { list[p.parseTag()] = { offset: p.parseUShort() }; } return list; } // Parse a coverage table in a GSUB, GPOS or GDEF table. // Format 1 is a simple list of glyph ids, // Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea. function parseCoverageTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); if (format === 1) { return p.parseUShortList(count); } else if (format === 2) { var coverage = []; for (; count--;) { var begin = p.parseUShort(); var end = p.parseUShort(); var index = p.parseUShort(); for (var i = begin; i <= end; i++) { coverage[index++] = i; } } return coverage; } } // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // Returns a function that gets a class value from a glyph ID. function parseClassDefTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); if (format === 1) { // Format 1 specifies a range of consecutive glyph indices, one class per glyph ID. var startGlyph = p.parseUShort(); var glyphCount = p.parseUShort(); var classes = p.parseUShortList(glyphCount); return function(glyphID) { return classes[glyphID - startGlyph] || 0; }; } else if (format === 2) { // Format 2 defines multiple groups of glyph indices that belong to the same class. var rangeCount = p.parseUShort(); var startGlyphs = []; var endGlyphs = []; var classValues = []; for (var i = 0; i < rangeCount; i++) { startGlyphs[i] = p.parseUShort(); endGlyphs[i] = p.parseUShort(); classValues[i] = p.parseUShort(); } return function(glyphID) { var l = 0; var r = startGlyphs.length - 1; while (l < r) { var c = (l + r + 1) >> 1; if (glyphID < startGlyphs[c]) { r = c - 1; } else { l = c; } } if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) { return classValues[l] || 0; } return 0; }; } } // Parse a pair adjustment positioning subtable, format 1 or format 2 // The subtable is returned in the form of a lookup function. function parsePairPosSubTable(data, start) { var p = new parse.Parser(data, start); // This part is common to format 1 and format 2 subtables var format = p.parseUShort(); var coverageOffset = p.parseUShort(); var coverage = parseCoverageTable(data, start + coverageOffset); // valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph // Only valueFormat1=4 and valueFormat2=0 is supported. var valueFormat1 = p.parseUShort(); var valueFormat2 = p.parseUShort(); var value1; var value2; if (valueFormat1 !== 4 || valueFormat2 !== 0) return; var sharedPairSets = {}; if (format === 1) { // Pair Positioning Adjustment: Format 1 var pairSetCount = p.parseUShort(); var pairSet = []; // Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index var pairSetOffsets = p.parseOffset16List(pairSetCount); for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) { var pairSetOffset = pairSetOffsets[firstGlyph]; var sharedPairSet = sharedPairSets[pairSetOffset]; if (!sharedPairSet) { // Parse a pairset table in a pair adjustment subtable format 1 sharedPairSet = {}; p.relativeOffset = pairSetOffset; var pairValueCount = p.parseUShort(); for (; pairValueCount--;) { var secondGlyph = p.parseUShort(); if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. sharedPairSet[secondGlyph] = value1; } } pairSet[coverage[firstGlyph]] = sharedPairSet; } return function(leftGlyph, rightGlyph) { var pairs = pairSet[leftGlyph]; if (pairs) return pairs[rightGlyph]; }; } else if (format === 2) { // Pair Positioning Adjustment: Format 2 var classDef1Offset = p.parseUShort(); var classDef2Offset = p.parseUShort(); var class1Count = p.parseUShort(); var class2Count = p.parseUShort(); var getClass1 = parseClassDefTable(data, start + classDef1Offset); var getClass2 = parseClassDefTable(data, start + classDef2Offset); // Parse kerning values by class pair. var kerningMatrix = []; for (var i = 0; i < class1Count; i++) { var kerningRow = kerningMatrix[i] = []; for (var j = 0; j < class2Count; j++) { if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. kerningRow[j] = value1; } } // Convert coverage list to a hash var covered = {}; for (i = 0; i < coverage.length; i++) covered[coverage[i]] = 1; // Get the kerning value for a specific glyph pair. return function(leftGlyph, rightGlyph) { if (!covered[leftGlyph]) return; var class1 = getClass1(leftGlyph); var class2 = getClass2(rightGlyph); var kerningRow = kerningMatrix[class1]; if (kerningRow) { return kerningRow[class2]; } }; } } // Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables). function parseLookupTable(data, start) { var p = new parse.Parser(data, start); var lookupType = p.parseUShort(); var lookupFlag = p.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; var subTableCount = p.parseUShort(); var subTableOffsets = p.parseOffset16List(subTableCount); var table = { lookupType: lookupType, lookupFlag: lookupFlag, markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1 }; // LookupType 2, Pair adjustment if (lookupType === 2) { var subtables = []; for (var i = 0; i < subTableCount; i++) { subtables.push(parsePairPosSubTable(data, start + subTableOffsets[i])); } // Return a function which finds the kerning values in the subtables. table.getKerningValue = function(leftGlyph, rightGlyph) { for (var i = subtables.length; i--;) { var value = subtables[i](leftGlyph, rightGlyph); if (value !== undefined) return value; } return 0; }; } return table; } // Parse the `GPOS` table which contains, among other things, kerning pairs. // https://www.microsoft.com/typography/OTSPEC/gpos.htm function parseGposTable(data, start, font) { var p = new parse.Parser(data, start); var tableVersion = p.parseFixed(); check.argument(tableVersion === 1, 'Unsupported GPOS table version.'); // ScriptList and FeatureList - ignored for now parseTaggedListTable(data, start + p.parseUShort()); // 'kern' is the feature we are looking for. parseTaggedListTable(data, start + p.parseUShort()); // LookupList var lookupListOffset = p.parseUShort(); p.relativeOffset = lookupListOffset; var lookupCount = p.parseUShort(); var lookupTableOffsets = p.parseOffset16List(lookupCount); var lookupListAbsoluteOffset = start + lookupListOffset; for (var i = 0; i < lookupCount; i++) { var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]); if (table.lookupType === 2 && !font.getGposKerningValue) font.getGposKerningValue = table.getKerningValue; } } exports.parse = parseGposTable; },{"../check":2,"../parse":10}],19:[function(require,module,exports){ // The `GSUB` table contains ligatures, among other things. // https://www.microsoft.com/typography/OTSPEC/gsub.htm 'use strict'; var check = require('../check'); var Parser = require('../parse').Parser; var subtableParsers = new Array(9); // subtableParsers[0] is unused var table = require('../table'); // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS subtableParsers[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), deltaGlyphId: this.parseUShort() }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), substitute: this.parseOffset16List() }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS subtableParsers[2] = function parseLookup2() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), sequences: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS subtableParsers[3] = function parseLookup3() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), alternateSets: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS subtableParsers[4] = function parseLookup4() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ligatureSets: this.parseListOfLists(function() { return { ligGlyph: this.parseUShort(), components: this.parseUShortList(this.parseUShort() - 1) }; }) }; }; var lookupRecordDesc = { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ruleSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { input: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), classDef: this.parsePointer(Parser.classDef), classSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { classes: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 3) { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { substFormat: substFormat, coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC subtableParsers[6] = function parseLookup6() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), chainRuleSets: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), backtrackClassDef: this.parsePointer(Parser.classDef), inputClassDef: this.parsePointer(Parser.classDef), lookaheadClassDef: this.parsePointer(Parser.classDef), chainClassSet: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 3) { return { substFormat: 3, backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES subtableParsers[7] = function parseLookup7() { // Extension Substitution subtable var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); var extensionLookupType = this.parseUShort(); var extensionParser = new Parser(this.data, this.offset + this.parseULong()); return { substFormat: 1, lookupType: extensionLookupType, extension: subtableParsers[extensionLookupType].call(extensionParser) }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS subtableParsers[8] = function parseLookup8() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), substitutes: this.parseUShortList() }; }; // https://www.microsoft.com/typography/OTSPEC/gsub.htm function parseGsubTable(data, start) { start = start || 0; var p = new Parser(data, start); var tableVersion = p.parseVersion(); check.argument(tableVersion === 1, 'Unsupported GSUB table version.'); return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers) }; } // GSUB Writing ////////////////////////////////////////////// var subtableMakers = new Array(9); subtableMakers[1] = function makeLookup1(subtable) { if (subtable.substFormat === 1) { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} ]); } else { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 2}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.ushortList('substitute', subtable.substitute))); } check.fail('Lookup type 1 substFormat must be 1 or 2.'); }; subtableMakers[3] = function makeLookup3(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); }))); }; subtableMakers[4] = function makeLookup4(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { return new table.Table('ligatureTable', [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) ); })); }))); }; function makeGsubTable(gsub) { return new table.Table('GSUB', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} ]); } exports.parse = parseGsubTable; exports.make = makeGsubTable; },{"../check":2,"../parse":10,"../table":13}],20:[function(require,module,exports){ // The `head` table contains global information about the font. // https://www.microsoft.com/typography/OTSPEC/head.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); // Parse the header `head` table function parseHeadTable(data, start) { var head = {}; var p = new parse.Parser(data, start); head.version = p.parseVersion(); head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; head.checkSumAdjustment = p.parseULong(); head.magicNumber = p.parseULong(); check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); head.flags = p.parseUShort(); head.unitsPerEm = p.parseUShort(); head.created = p.parseLongDateTime(); head.modified = p.parseLongDateTime(); head.xMin = p.parseShort(); head.yMin = p.parseShort(); head.xMax = p.parseShort(); head.yMax = p.parseShort(); head.macStyle = p.parseUShort(); head.lowestRecPPEM = p.parseUShort(); head.fontDirectionHint = p.parseShort(); head.indexToLocFormat = p.parseShort(); head.glyphDataFormat = p.parseShort(); return head; } function makeHeadTable(options) { // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; var createdTimestamp = timestamp; if (options.createdTimestamp) { createdTimestamp = options.createdTimestamp + 2082844800; } return new table.Table('head', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, {name: 'flags', type: 'USHORT', value: 0}, {name: 'unitsPerEm', type: 'USHORT', value: 1000}, {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, {name: 'modified', type: 'LONGDATETIME', value: timestamp}, {name: 'xMin', type: 'SHORT', value: 0}, {name: 'yMin', type: 'SHORT', value: 0}, {name: 'xMax', type: 'SHORT', value: 0}, {name: 'yMax', type: 'SHORT', value: 0}, {name: 'macStyle', type: 'USHORT', value: 0}, {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, {name: 'fontDirectionHint', type: 'SHORT', value: 2}, {name: 'indexToLocFormat', type: 'SHORT', value: 0}, {name: 'glyphDataFormat', type: 'SHORT', value: 0} ], options); } exports.parse = parseHeadTable; exports.make = makeHeadTable; },{"../check":2,"../parse":10,"../table":13}],21:[function(require,module,exports){ // The `hhea` table contains information for horizontal layout. // https://www.microsoft.com/typography/OTSPEC/hhea.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the horizontal header `hhea` table function parseHheaTable(data, start) { var hhea = {}; var p = new parse.Parser(data, start); hhea.version = p.parseVersion(); hhea.ascender = p.parseShort(); hhea.descender = p.parseShort(); hhea.lineGap = p.parseShort(); hhea.advanceWidthMax = p.parseUShort(); hhea.minLeftSideBearing = p.parseShort(); hhea.minRightSideBearing = p.parseShort(); hhea.xMaxExtent = p.parseShort(); hhea.caretSlopeRise = p.parseShort(); hhea.caretSlopeRun = p.parseShort(); hhea.caretOffset = p.parseShort(); p.relativeOffset += 8; hhea.metricDataFormat = p.parseShort(); hhea.numberOfHMetrics = p.parseUShort(); return hhea; } function makeHheaTable(options) { return new table.Table('hhea', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'ascender', type: 'FWORD', value: 0}, {name: 'descender', type: 'FWORD', value: 0}, {name: 'lineGap', type: 'FWORD', value: 0}, {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, {name: 'minRightSideBearing', type: 'FWORD', value: 0}, {name: 'xMaxExtent', type: 'FWORD', value: 0}, {name: 'caretSlopeRise', type: 'SHORT', value: 1}, {name: 'caretSlopeRun', type: 'SHORT', value: 0}, {name: 'caretOffset', type: 'SHORT', value: 0}, {name: 'reserved1', type: 'SHORT', value: 0}, {name: 'reserved2', type: 'SHORT', value: 0}, {name: 'reserved3', type: 'SHORT', value: 0}, {name: 'reserved4', type: 'SHORT', value: 0}, {name: 'metricDataFormat', type: 'SHORT', value: 0}, {name: 'numberOfHMetrics', type: 'USHORT', value: 0} ], options); } exports.parse = parseHheaTable; exports.make = makeHheaTable; },{"../parse":10,"../table":13}],22:[function(require,module,exports){ // The `hmtx` table contains the horizontal metrics for all glyphs. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { var advanceWidth; var leftSideBearing; var p = new parse.Parser(data, start); for (var i = 0; i < numGlyphs; i += 1) { // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } var glyph = glyphs.get(i); glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } function makeHmtxTable(glyphs) { var t = new table.Table('hmtx', []); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var advanceWidth = glyph.advanceWidth || 0; var leftSideBearing = glyph.leftSideBearing || 0; t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); } return t; } exports.parse = parseHmtxTable; exports.make = makeHmtxTable; },{"../parse":10,"../table":13}],23:[function(require,module,exports){ // The `kern` table contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm 'use strict'; var check = require('../check'); var parse = require('../parse'); function parseWindowsKernTable(p) { var pairs = {}; // Skip nTables. p.skip('uShort'); var subtableVersion = p.parseUShort(); check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); // Skip subtableLength, subtableCoverage p.skip('uShort', 2); var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } function parseMacKernTable(p) { var pairs = {}; // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. // Skip the rest. p.skip('uShort'); var nTables = p.parseULong(); //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); if (nTables > 1) { console.warn('Only the first kern subtable is supported.'); } p.skip('uLong'); var coverage = p.parseUShort(); var subtableVersion = coverage & 0xFF; p.skip('uShort'); if (subtableVersion === 0) { var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } } return pairs; } // Parse the `kern` table which contains kerning pairs. function parseKernTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseUShort(); if (tableVersion === 0) { return parseWindowsKernTable(p); } else if (tableVersion === 1) { return parseMacKernTable(p); } else { throw new Error('Unsupported kern table version (' + tableVersion + ').'); } } exports.parse = parseKernTable; },{"../check":2,"../parse":10}],24:[function(require,module,exports){ // The `loca` table stores the offsets to the locations of the glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/loca.htm 'use strict'; var parse = require('../parse'); // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). function parseLocaTable(data, start, numGlyphs, shortVersion) { var p = new parse.Parser(data, start); var parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. var glyphOffsets = []; for (var i = 0; i < numGlyphs + 1; i += 1) { var glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } exports.parse = parseLocaTable; },{"../parse":10}],25:[function(require,module,exports){ // The `ltag` table stores IETF BCP-47 language tags. It allows supporting // languages for which TrueType does not assign a numeric code. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html // http://www.w3.org/International/articles/language-tags/ // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry 'use strict'; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); function makeLtagTable(tags) { var result = new table.Table('ltag', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'numTags', type: 'ULONG', value: tags.length} ]); var stringPool = ''; var stringPoolOffset = 12 + tags.length * 4; for (var i = 0; i < tags.length; ++i) { var pos = stringPool.indexOf(tags[i]); if (pos < 0) { pos = stringPool.length; stringPool += tags[i]; } result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } function parseLtagTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported ltag table version.'); // The 'ltag' specification does not define any flags; skip the field. p.skip('uLong', 1); var numTags = p.parseULong(); var tags = []; for (var i = 0; i < numTags; i++) { var tag = ''; var offset = start + p.parseUShort(); var length = p.parseUShort(); for (var j = offset; j < offset + length; ++j) { tag += String.fromCharCode(data.getInt8(j)); } tags.push(tag); } return tags; } exports.make = makeLtagTable; exports.parse = parseLtagTable; },{"../check":2,"../parse":10,"../table":13}],26:[function(require,module,exports){ // The `maxp` table establishes the memory requirements for the font. // We need it just to get the number of glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/maxp.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); // Parse the maximum profile `maxp` table. function parseMaxpTable(data, start) { var maxp = {}; var p = new parse.Parser(data, start); maxp.version = p.parseVersion(); maxp.numGlyphs = p.parseUShort(); if (maxp.version === 1.0) { maxp.maxPoints = p.parseUShort(); maxp.maxContours = p.parseUShort(); maxp.maxCompositePoints = p.parseUShort(); maxp.maxCompositeContours = p.parseUShort(); maxp.maxZones = p.parseUShort(); maxp.maxTwilightPoints = p.parseUShort(); maxp.maxStorage = p.parseUShort(); maxp.maxFunctionDefs = p.parseUShort(); maxp.maxInstructionDefs = p.parseUShort(); maxp.maxStackElements = p.parseUShort(); maxp.maxSizeOfInstructions = p.parseUShort(); maxp.maxComponentElements = p.parseUShort(); maxp.maxComponentDepth = p.parseUShort(); } return maxp; } function makeMaxpTable(numGlyphs) { return new table.Table('maxp', [ {name: 'version', type: 'FIXED', value: 0x00005000}, {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} ]); } exports.parse = parseMaxpTable; exports.make = makeMaxpTable; },{"../parse":10,"../table":13}],27:[function(require,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var types = require('../types'); var decode = types.decode; var check = require('../check'); var parse = require('../parse'); var table = require('../table'); // Parse the metadata `meta` table. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html function parseMetaTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported META table version.'); p.parseULong(); // flags - currently unused and set to 0 p.parseULong(); // tableOffset var numDataMaps = p.parseULong(); var tags = {}; for (var i = 0; i < numDataMaps; i++) { var tag = p.parseTag(); var dataOffset = p.parseULong(); var dataLength = p.parseULong(); var text = decode.UTF8(data, start + dataOffset, dataLength); tags[tag] = text; } return tags; } function makeMetaTable(tags) { var numTags = Object.keys(tags).length; var stringPool = ''; var stringPoolOffset = 16 + numTags * 12; var result = new table.Table('meta', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'offset', type: 'ULONG', value: stringPoolOffset}, {name: 'numTags', type: 'ULONG', value: numTags} ]); for (var tag in tags) { var pos = stringPool.length; stringPool += tags[tag]; result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } exports.parse = parseMetaTable; exports.make = makeMetaTable; },{"../check":2,"../parse":10,"../table":13,"../types":32}],28:[function(require,module,exports){ // The `name` naming table. // https://www.microsoft.com/typography/OTSPEC/name.htm 'use strict'; var types = require('../types'); var decode = types.decode; var encode = types.encode; var parse = require('../parse'); var table = require('../table'); // NameIDs for the name table. var nameTableNames = [ 'copyright', // 0 'fontFamily', // 1 'fontSubfamily', // 2 'uniqueID', // 3 'fullName', // 4 'version', // 5 'postScriptName', // 6 'trademark', // 7 'manufacturer', // 8 'designer', // 9 'description', // 10 'manufacturerURL', // 11 'designerURL', // 12 'license', // 13 'licenseURL', // 14 'reserved', // 15 'preferredFamily', // 16 'preferredSubfamily', // 17 'compatibleFullName', // 18 'sampleText', // 19 'postScriptFindFontName', // 20 'wwsFamily', // 21 'wwsSubfamily' // 22 ]; var macLanguages = { 0: 'en', 1: 'fr', 2: 'de', 3: 'it', 4: 'nl', 5: 'sv', 6: 'es', 7: 'da', 8: 'pt', 9: 'no', 10: 'he', 11: 'ja', 12: 'ar', 13: 'fi', 14: 'el', 15: 'is', 16: 'mt', 17: 'tr', 18: 'hr', 19: 'zh-Hant', 20: 'ur', 21: 'hi', 22: 'th', 23: 'ko', 24: 'lt', 25: 'pl', 26: 'hu', 27: 'es', 28: 'lv', 29: 'se', 30: 'fo', 31: 'fa', 32: 'ru', 33: 'zh', 34: 'nl-BE', 35: 'ga', 36: 'sq', 37: 'ro', 38: 'cz', 39: 'sk', 40: 'si', 41: 'yi', 42: 'sr', 43: 'mk', 44: 'bg', 45: 'uk', 46: 'be', 47: 'uz', 48: 'kk', 49: 'az-Cyrl', 50: 'az-Arab', 51: 'hy', 52: 'ka', 53: 'mo', 54: 'ky', 55: 'tg', 56: 'tk', 57: 'mn-CN', 58: 'mn', 59: 'ps', 60: 'ks', 61: 'ku', 62: 'sd', 63: 'bo', 64: 'ne', 65: 'sa', 66: 'mr', 67: 'bn', 68: 'as', 69: 'gu', 70: 'pa', 71: 'or', 72: 'ml', 73: 'kn', 74: 'ta', 75: 'te', 76: 'si', 77: 'my', 78: 'km', 79: 'lo', 80: 'vi', 81: 'id', 82: 'tl', 83: 'ms', 84: 'ms-Arab', 85: 'am', 86: 'ti', 87: 'om', 88: 'so', 89: 'sw', 90: 'rw', 91: 'rn', 92: 'ny', 93: 'mg', 94: 'eo', 128: 'cy', 129: 'eu', 130: 'ca', 131: 'la', 132: 'qu', 133: 'gn', 134: 'ay', 135: 'tt', 136: 'ug', 137: 'dz', 138: 'jv', 139: 'su', 140: 'gl', 141: 'af', 142: 'br', 143: 'iu', 144: 'gd', 145: 'gv', 146: 'ga', 147: 'to', 148: 'el-polyton', 149: 'kl', 150: 'az', 151: 'nn' }; // MacOS language ID → MacOS script ID // // Note that the script ID is not sufficient to determine what encoding // to use in TrueType files. For some languages, MacOS used a modification // of a mainstream script. For example, an Icelandic name would be stored // with smRoman in the TrueType naming table, but the actual encoding // is a special Icelandic version of the normal Macintosh Roman encoding. // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal // Syllables but MacOS had run out of available script codes, so this was // done as a (pretty radical) "modification" of Ethiopic. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageToScript = { 0: 0, // langEnglish → smRoman 1: 0, // langFrench → smRoman 2: 0, // langGerman → smRoman 3: 0, // langItalian → smRoman 4: 0, // langDutch → smRoman 5: 0, // langSwedish → smRoman 6: 0, // langSpanish → smRoman 7: 0, // langDanish → smRoman 8: 0, // langPortuguese → smRoman 9: 0, // langNorwegian → smRoman 10: 5, // langHebrew → smHebrew 11: 1, // langJapanese → smJapanese 12: 4, // langArabic → smArabic 13: 0, // langFinnish → smRoman 14: 6, // langGreek → smGreek 15: 0, // langIcelandic → smRoman (modified) 16: 0, // langMaltese → smRoman 17: 0, // langTurkish → smRoman (modified) 18: 0, // langCroatian → smRoman (modified) 19: 2, // langTradChinese → smTradChinese 20: 4, // langUrdu → smArabic 21: 9, // langHindi → smDevanagari 22: 21, // langThai → smThai 23: 3, // langKorean → smKorean 24: 29, // langLithuanian → smCentralEuroRoman 25: 29, // langPolish → smCentralEuroRoman 26: 29, // langHungarian → smCentralEuroRoman 27: 29, // langEstonian → smCentralEuroRoman 28: 29, // langLatvian → smCentralEuroRoman 29: 0, // langSami → smRoman 30: 0, // langFaroese → smRoman (modified) 31: 4, // langFarsi → smArabic (modified) 32: 7, // langRussian → smCyrillic 33: 25, // langSimpChinese → smSimpChinese 34: 0, // langFlemish → smRoman 35: 0, // langIrishGaelic → smRoman (modified) 36: 0, // langAlbanian → smRoman 37: 0, // langRomanian → smRoman (modified) 38: 29, // langCzech → smCentralEuroRoman 39: 29, // langSlovak → smCentralEuroRoman 40: 0, // langSlovenian → smRoman (modified) 41: 5, // langYiddish → smHebrew 42: 7, // langSerbian → smCyrillic 43: 7, // langMacedonian → smCyrillic 44: 7, // langBulgarian → smCyrillic 45: 7, // langUkrainian → smCyrillic (modified) 46: 7, // langByelorussian → smCyrillic 47: 7, // langUzbek → smCyrillic 48: 7, // langKazakh → smCyrillic 49: 7, // langAzerbaijani → smCyrillic 50: 4, // langAzerbaijanAr → smArabic 51: 24, // langArmenian → smArmenian 52: 23, // langGeorgian → smGeorgian 53: 7, // langMoldavian → smCyrillic 54: 7, // langKirghiz → smCyrillic 55: 7, // langTajiki → smCyrillic 56: 7, // langTurkmen → smCyrillic 57: 27, // langMongolian → smMongolian 58: 7, // langMongolianCyr → smCyrillic 59: 4, // langPashto → smArabic 60: 4, // langKurdish → smArabic 61: 4, // langKashmiri → smArabic 62: 4, // langSindhi → smArabic 63: 26, // langTibetan → smTibetan 64: 9, // langNepali → smDevanagari 65: 9, // langSanskrit → smDevanagari 66: 9, // langMarathi → smDevanagari 67: 13, // langBengali → smBengali 68: 13, // langAssamese → smBengali 69: 11, // langGujarati → smGujarati 70: 10, // langPunjabi → smGurmukhi 71: 12, // langOriya → smOriya 72: 17, // langMalayalam → smMalayalam 73: 16, // langKannada → smKannada 74: 14, // langTamil → smTamil 75: 15, // langTelugu → smTelugu 76: 18, // langSinhalese → smSinhalese 77: 19, // langBurmese → smBurmese 78: 20, // langKhmer → smKhmer 79: 22, // langLao → smLao 80: 30, // langVietnamese → smVietnamese 81: 0, // langIndonesian → smRoman 82: 0, // langTagalog → smRoman 83: 0, // langMalayRoman → smRoman 84: 4, // langMalayArabic → smArabic 85: 28, // langAmharic → smEthiopic 86: 28, // langTigrinya → smEthiopic 87: 28, // langOromo → smEthiopic 88: 0, // langSomali → smRoman 89: 0, // langSwahili → smRoman 90: 0, // langKinyarwanda → smRoman 91: 0, // langRundi → smRoman 92: 0, // langNyanja → smRoman 93: 0, // langMalagasy → smRoman 94: 0, // langEsperanto → smRoman 128: 0, // langWelsh → smRoman (modified) 129: 0, // langBasque → smRoman 130: 0, // langCatalan → smRoman 131: 0, // langLatin → smRoman 132: 0, // langQuechua → smRoman 133: 0, // langGuarani → smRoman 134: 0, // langAymara → smRoman 135: 7, // langTatar → smCyrillic 136: 4, // langUighur → smArabic 137: 26, // langDzongkha → smTibetan 138: 0, // langJavaneseRom → smRoman 139: 0, // langSundaneseRom → smRoman 140: 0, // langGalician → smRoman 141: 0, // langAfrikaans → smRoman 142: 0, // langBreton → smRoman (modified) 143: 28, // langInuktitut → smEthiopic (modified) 144: 0, // langScottishGaelic → smRoman (modified) 145: 0, // langManxGaelic → smRoman (modified) 146: 0, // langIrishGaelicScript → smRoman (modified) 147: 0, // langTongan → smRoman 148: 6, // langGreekAncient → smRoman 149: 0, // langGreenlandic → smRoman 150: 0, // langAzerbaijanRoman → smRoman 151: 0 // langNynorsk → smRoman }; // While Microsoft indicates a region/country for all its language // IDs, we omit the region code if it's equal to the "most likely // region subtag" according to Unicode CLDR. For scripts, we omit // the subtag if it is equal to the Suppress-Script entry in the // IANA language subtag registry for IETF BCP 47. // // For example, Microsoft states that its language code 0x041A is // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' // and not 'hr-HR' because Croatia is the default country for Croatian, // according to Unicode CLDR. As another example, Microsoft states // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script // for the Croatian language, according to IANA. // // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry var windowsLanguages = { 0x0436: 'af', 0x041C: 'sq', 0x0484: 'gsw', 0x045E: 'am', 0x1401: 'ar-DZ', 0x3C01: 'ar-BH', 0x0C01: 'ar', 0x0801: 'ar-IQ', 0x2C01: 'ar-JO', 0x3401: 'ar-KW', 0x3001: 'ar-LB', 0x1001: 'ar-LY', 0x1801: 'ary', 0x2001: 'ar-OM', 0x4001: 'ar-QA', 0x0401: 'ar-SA', 0x2801: 'ar-SY', 0x1C01: 'aeb', 0x3801: 'ar-AE', 0x2401: 'ar-YE', 0x042B: 'hy', 0x044D: 'as', 0x082C: 'az-Cyrl', 0x042C: 'az', 0x046D: 'ba', 0x042D: 'eu', 0x0423: 'be', 0x0845: 'bn', 0x0445: 'bn-IN', 0x201A: 'bs-Cyrl', 0x141A: 'bs', 0x047E: 'br', 0x0402: 'bg', 0x0403: 'ca', 0x0C04: 'zh-HK', 0x1404: 'zh-MO', 0x0804: 'zh', 0x1004: 'zh-SG', 0x0404: 'zh-TW', 0x0483: 'co', 0x041A: 'hr', 0x101A: 'hr-BA', 0x0405: 'cs', 0x0406: 'da', 0x048C: 'prs', 0x0465: 'dv', 0x0813: 'nl-BE', 0x0413: 'nl', 0x0C09: 'en-AU', 0x2809: 'en-BZ', 0x1009: 'en-CA', 0x2409: 'en-029', 0x4009: 'en-IN', 0x1809: 'en-IE', 0x2009: 'en-JM', 0x4409: 'en-MY', 0x1409: 'en-NZ', 0x3409: 'en-PH', 0x4809: 'en-SG', 0x1C09: 'en-ZA', 0x2C09: 'en-TT', 0x0809: 'en-GB', 0x0409: 'en', 0x3009: 'en-ZW', 0x0425: 'et', 0x0438: 'fo', 0x0464: 'fil', 0x040B: 'fi', 0x080C: 'fr-BE', 0x0C0C: 'fr-CA', 0x040C: 'fr', 0x140C: 'fr-LU', 0x180C: 'fr-MC', 0x100C: 'fr-CH', 0x0462: 'fy', 0x0456: 'gl', 0x0437: 'ka', 0x0C07: 'de-AT', 0x0407: 'de', 0x1407: 'de-LI', 0x1007: 'de-LU', 0x0807: 'de-CH', 0x0408: 'el', 0x046F: 'kl', 0x0447: 'gu', 0x0468: 'ha', 0x040D: 'he', 0x0439: 'hi', 0x040E: 'hu', 0x040F: 'is', 0x0470: 'ig', 0x0421: 'id', 0x045D: 'iu', 0x085D: 'iu-Latn', 0x083C: 'ga', 0x0434: 'xh', 0x0435: 'zu', 0x0410: 'it', 0x0810: 'it-CH', 0x0411: 'ja', 0x044B: 'kn', 0x043F: 'kk', 0x0453: 'km', 0x0486: 'quc', 0x0487: 'rw', 0x0441: 'sw', 0x0457: 'kok', 0x0412: 'ko', 0x0440: 'ky', 0x0454: 'lo', 0x0426: 'lv', 0x0427: 'lt', 0x082E: 'dsb', 0x046E: 'lb', 0x042F: 'mk', 0x083E: 'ms-BN', 0x043E: 'ms', 0x044C: 'ml', 0x043A: 'mt', 0x0481: 'mi', 0x047A: 'arn', 0x044E: 'mr', 0x047C: 'moh', 0x0450: 'mn', 0x0850: 'mn-CN', 0x0461: 'ne', 0x0414: 'nb', 0x0814: 'nn', 0x0482: 'oc', 0x0448: 'or', 0x0463: 'ps', 0x0415: 'pl', 0x0416: 'pt', 0x0816: 'pt-PT', 0x0446: 'pa', 0x046B: 'qu-BO', 0x086B: 'qu-EC', 0x0C6B: 'qu', 0x0418: 'ro', 0x0417: 'rm', 0x0419: 'ru', 0x243B: 'smn', 0x103B: 'smj-NO', 0x143B: 'smj', 0x0C3B: 'se-FI', 0x043B: 'se', 0x083B: 'se-SE', 0x203B: 'sms', 0x183B: 'sma-NO', 0x1C3B: 'sms', 0x044F: 'sa', 0x1C1A: 'sr-Cyrl-BA', 0x0C1A: 'sr', 0x181A: 'sr-Latn-BA', 0x081A: 'sr-Latn', 0x046C: 'nso', 0x0432: 'tn', 0x045B: 'si', 0x041B: 'sk', 0x0424: 'sl', 0x2C0A: 'es-AR', 0x400A: 'es-BO', 0x340A: 'es-CL', 0x240A: 'es-CO', 0x140A: 'es-CR', 0x1C0A: 'es-DO', 0x300A: 'es-EC', 0x440A: 'es-SV', 0x100A: 'es-GT', 0x480A: 'es-HN', 0x080A: 'es-MX', 0x4C0A: 'es-NI', 0x180A: 'es-PA', 0x3C0A: 'es-PY', 0x280A: 'es-PE', 0x500A: 'es-PR', // Microsoft has defined two different language codes for // “Spanish with modern sorting” and “Spanish with traditional // sorting”. This makes sense for collation APIs, and it would be // possible to express this in BCP 47 language tags via Unicode // extensions (eg., es-u-co-trad is Spanish with traditional // sorting). However, for storing names in fonts, the distinction // does not make sense, so we give “es” in both cases. 0x0C0A: 'es', 0x040A: 'es', 0x540A: 'es-US', 0x380A: 'es-UY', 0x200A: 'es-VE', 0x081D: 'sv-FI', 0x041D: 'sv', 0x045A: 'syr', 0x0428: 'tg', 0x085F: 'tzm', 0x0449: 'ta', 0x0444: 'tt', 0x044A: 'te', 0x041E: 'th', 0x0451: 'bo', 0x041F: 'tr', 0x0442: 'tk', 0x0480: 'ug', 0x0422: 'uk', 0x042E: 'hsb', 0x0420: 'ur', 0x0843: 'uz-Cyrl', 0x0443: 'uz', 0x042A: 'vi', 0x0452: 'cy', 0x0488: 'wo', 0x0485: 'sah', 0x0478: 'ii', 0x046A: 'yo' }; // Returns a IETF BCP 47 language code, for example 'zh-Hant' // for 'Chinese in the traditional script'. function getLanguageCode(platformID, languageID, ltag) { switch (platformID) { case 0: // Unicode if (languageID === 0xFFFF) { return 'und'; } else if (ltag) { return ltag[languageID]; } break; case 1: // Macintosh return macLanguages[languageID]; case 3: // Windows return windowsLanguages[languageID]; } return undefined; } var utf16 = 'utf-16'; // MacOS script ID → encoding. This table stores the default case, // which can be overridden by macLanguageEncodings. var macScriptEncodings = { 0: 'macintosh', // smRoman 1: 'x-mac-japanese', // smJapanese 2: 'x-mac-chinesetrad', // smTradChinese 3: 'x-mac-korean', // smKorean 6: 'x-mac-greek', // smGreek 7: 'x-mac-cyrillic', // smCyrillic 9: 'x-mac-devanagai', // smDevanagari 10: 'x-mac-gurmukhi', // smGurmukhi 11: 'x-mac-gujarati', // smGujarati 12: 'x-mac-oriya', // smOriya 13: 'x-mac-bengali', // smBengali 14: 'x-mac-tamil', // smTamil 15: 'x-mac-telugu', // smTelugu 16: 'x-mac-kannada', // smKannada 17: 'x-mac-malayalam', // smMalayalam 18: 'x-mac-sinhalese', // smSinhalese 19: 'x-mac-burmese', // smBurmese 20: 'x-mac-khmer', // smKhmer 21: 'x-mac-thai', // smThai 22: 'x-mac-lao', // smLao 23: 'x-mac-georgian', // smGeorgian 24: 'x-mac-armenian', // smArmenian 25: 'x-mac-chinesesimp', // smSimpChinese 26: 'x-mac-tibetan', // smTibetan 27: 'x-mac-mongolian', // smMongolian 28: 'x-mac-ethiopic', // smEthiopic 29: 'x-mac-ce', // smCentralEuroRoman 30: 'x-mac-vietnamese', // smVietnamese 31: 'x-mac-extarabic' // smExtArabic }; // MacOS language ID → encoding. This table stores the exceptional // cases, which override macScriptEncodings. For writing MacOS naming // tables, we need to emit a MacOS script ID. Therefore, we cannot // merge macScriptEncodings into macLanguageEncodings. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageEncodings = { 15: 'x-mac-icelandic', // langIcelandic 17: 'x-mac-turkish', // langTurkish 18: 'x-mac-croatian', // langCroatian 24: 'x-mac-ce', // langLithuanian 25: 'x-mac-ce', // langPolish 26: 'x-mac-ce', // langHungarian 27: 'x-mac-ce', // langEstonian 28: 'x-mac-ce', // langLatvian 30: 'x-mac-icelandic', // langFaroese 37: 'x-mac-romanian', // langRomanian 38: 'x-mac-ce', // langCzech 39: 'x-mac-ce', // langSlovak 40: 'x-mac-ce', // langSlovenian 143: 'x-mac-inuit', // langInuktitut 146: 'x-mac-gaelic' // langIrishGaelicScript }; function getEncoding(platformID, encodingID, languageID) { switch (platformID) { case 0: // Unicode return utf16; case 1: // Apple Macintosh return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; case 3: // Microsoft Windows if (encodingID === 1 || encodingID === 10) { return utf16; } break; } return undefined; } // Parse the naming `name` table. // FIXME: Format 1 additional fields are not supported yet. // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. function parseNameTable(data, start, ltag) { var name = {}; var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); var stringOffset = p.offset + p.parseUShort(); for (var i = 0; i < count; i++) { var platformID = p.parseUShort(); var encodingID = p.parseUShort(); var languageID = p.parseUShort(); var nameID = p.parseUShort(); var property = nameTableNames[nameID] || nameID; var byteLength = p.parseUShort(); var offset = p.parseUShort(); var language = getLanguageCode(platformID, languageID, ltag); var encoding = getEncoding(platformID, encodingID, languageID); if (encoding !== undefined && language !== undefined) { var text; if (encoding === utf16) { text = decode.UTF16(data, stringOffset + offset, byteLength); } else { text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); } if (text) { var translations = name[property]; if (translations === undefined) { translations = name[property] = {}; } translations[language] = text; } } } var langTagCount = 0; if (format === 1) { // FIXME: Also handle Microsoft's 'name' table 1. langTagCount = p.parseUShort(); } return name; } // {23: 'foo'} → {'foo': 23} // ['bar', 'baz'] → {'bar': 0, 'baz': 1} function reverseDict(dict) { var result = {}; for (var key in dict) { result[dict[key]] = parseInt(key); } return result; } function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { return new table.Record('NameRecord', [ {name: 'platformID', type: 'USHORT', value: platformID}, {name: 'encodingID', type: 'USHORT', value: encodingID}, {name: 'languageID', type: 'USHORT', value: languageID}, {name: 'nameID', type: 'USHORT', value: nameID}, {name: 'length', type: 'USHORT', value: length}, {name: 'offset', type: 'USHORT', value: offset} ]); } // Finds the position of needle in haystack, or -1 if not there. // Like String.indexOf(), but for arrays. function findSubArray(needle, haystack) { var needleLength = needle.length; var limit = haystack.length - needleLength + 1; loop: for (var pos = 0; pos < limit; pos++) { for (; pos < limit; pos++) { for (var k = 0; k < needleLength; k++) { if (haystack[pos + k] !== needle[k]) { continue loop; } } return pos; } } return -1; } function addStringToPool(s, pool) { var offset = findSubArray(s, pool); if (offset < 0) { offset = pool.length; for (var i = 0, len = s.length; i < len; ++i) { pool.push(s[i]); } } return offset; } function makeNameTable(names, ltag) { var nameID; var nameIDs = []; var namesWithNumericKeys = {}; var nameTableIds = reverseDict(nameTableNames); for (var key in names) { var id = nameTableIds[key]; if (id === undefined) { id = key; } nameID = parseInt(id); if (isNaN(nameID)) { throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); } namesWithNumericKeys[nameID] = names[key]; nameIDs.push(nameID); } var macLanguageIds = reverseDict(macLanguages); var windowsLanguageIds = reverseDict(windowsLanguages); var nameRecords = []; var stringPool = []; for (var i = 0; i < nameIDs.length; i++) { nameID = nameIDs[i]; var translations = namesWithNumericKeys[nameID]; for (var lang in translations) { var text = translations[lang]; // For MacOS, we try to emit the name in the form that was introduced // in the initial version of the TrueType spec (in the late 1980s). // However, this can fail for various reasons: the requested BCP 47 // language code might not have an old-style Mac equivalent; // we might not have a codec for the needed character encoding; // or the name might contain characters that cannot be expressed // in the old-style Macintosh encoding. In case of failure, we emit // the name in a more modern fashion (Unicode encoding with BCP 47 // language tags) that is recognized by MacOS 10.5, released in 2009. // If fonts were only read by operating systems, we could simply // emit all names in the modern form; this would be much easier. // However, there are many applications and libraries that read // 'name' tables directly, and these will usually only recognize // the ancient form (silently skipping the unrecognized names). var macPlatform = 1; // Macintosh var macLanguage = macLanguageIds[lang]; var macScript = macLanguageToScript[macLanguage]; var macEncoding = getEncoding(macPlatform, macScript, macLanguage); var macName = encode.MACSTRING(text, macEncoding); if (macName === undefined) { macPlatform = 0; // Unicode macLanguage = ltag.indexOf(lang); if (macLanguage < 0) { macLanguage = ltag.length; ltag.push(lang); } macScript = 4; // Unicode 2.0 and later macName = encode.UTF16(text); } var macNameOffset = addStringToPool(macName, stringPool); nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); var winLanguage = windowsLanguageIds[lang]; if (winLanguage !== undefined) { var winName = encode.UTF16(text); var winNameOffset = addStringToPool(winName, stringPool); nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); } } } nameRecords.sort(function(a, b) { return ((a.platformID - b.platformID) || (a.encodingID - b.encodingID) || (a.languageID - b.languageID) || (a.nameID - b.nameID)); }); var t = new table.Table('name', [ {name: 'format', type: 'USHORT', value: 0}, {name: 'count', type: 'USHORT', value: nameRecords.length}, {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} ]); for (var r = 0; r < nameRecords.length; r++) { t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); } t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); return t; } exports.parse = parseNameTable; exports.make = makeNameTable; },{"../parse":10,"../table":13,"../types":32}],29:[function(require,module,exports){ // The `OS/2` table contains metrics required in OpenType fonts. // https://www.microsoft.com/typography/OTSPEC/os2.htm 'use strict'; var parse = require('../parse'); var table = require('../table'); var unicodeRanges = [ {begin: 0x0000, end: 0x007F}, // Basic Latin {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement {begin: 0x0100, end: 0x017F}, // Latin Extended-A {begin: 0x0180, end: 0x024F}, // Latin Extended-B {begin: 0x0250, end: 0x02AF}, // IPA Extensions {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks {begin: 0x0370, end: 0x03FF}, // Greek and Coptic {begin: 0x2C80, end: 0x2CFF}, // Coptic {begin: 0x0400, end: 0x04FF}, // Cyrillic {begin: 0x0530, end: 0x058F}, // Armenian {begin: 0x0590, end: 0x05FF}, // Hebrew {begin: 0xA500, end: 0xA63F}, // Vai {begin: 0x0600, end: 0x06FF}, // Arabic {begin: 0x07C0, end: 0x07FF}, // NKo {begin: 0x0900, end: 0x097F}, // Devanagari {begin: 0x0980, end: 0x09FF}, // Bengali {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi {begin: 0x0A80, end: 0x0AFF}, // Gujarati {begin: 0x0B00, end: 0x0B7F}, // Oriya {begin: 0x0B80, end: 0x0BFF}, // Tamil {begin: 0x0C00, end: 0x0C7F}, // Telugu {begin: 0x0C80, end: 0x0CFF}, // Kannada {begin: 0x0D00, end: 0x0D7F}, // Malayalam {begin: 0x0E00, end: 0x0E7F}, // Thai {begin: 0x0E80, end: 0x0EFF}, // Lao {begin: 0x10A0, end: 0x10FF}, // Georgian {begin: 0x1B00, end: 0x1B7F}, // Balinese {begin: 0x1100, end: 0x11FF}, // Hangul Jamo {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional {begin: 0x1F00, end: 0x1FFF}, // Greek Extended {begin: 0x2000, end: 0x206F}, // General Punctuation {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts {begin: 0x20A0, end: 0x20CF}, // Currency Symbol {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols {begin: 0x2100, end: 0x214F}, // Letterlike Symbols {begin: 0x2150, end: 0x218F}, // Number Forms {begin: 0x2190, end: 0x21FF}, // Arrows {begin: 0x2200, end: 0x22FF}, // Mathematical Operators {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical {begin: 0x2400, end: 0x243F}, // Control Pictures {begin: 0x2440, end: 0x245F}, // Optical Character Recognition {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics {begin: 0x2500, end: 0x257F}, // Box Drawing {begin: 0x2580, end: 0x259F}, // Block Elements {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols {begin: 0x2700, end: 0x27BF}, // Dingbats {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation {begin: 0x3040, end: 0x309F}, // Hiragana {begin: 0x30A0, end: 0x30FF}, // Katakana {begin: 0x3100, end: 0x312F}, // Bopomofo {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo {begin: 0xA840, end: 0xA87F}, // Phags-pa {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months {begin: 0x3300, end: 0x33FF}, // CJK Compatibility {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * {begin: 0x10900, end: 0x1091F}, // Phoenicia {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) {begin: 0x31C0, end: 0x31EF}, // CJK Strokes {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms {begin: 0xFFF0, end: 0xFFFF}, // Specials {begin: 0x0F00, end: 0x0FFF}, // Tibetan {begin: 0x0700, end: 0x074F}, // Syriac {begin: 0x0780, end: 0x07BF}, // Thaana {begin: 0x0D80, end: 0x0DFF}, // Sinhala {begin: 0x1000, end: 0x109F}, // Myanmar {begin: 0x1200, end: 0x137F}, // Ethiopic {begin: 0x13A0, end: 0x13FF}, // Cherokee {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics {begin: 0x1680, end: 0x169F}, // Ogham {begin: 0x16A0, end: 0x16FF}, // Runic {begin: 0x1780, end: 0x17FF}, // Khmer {begin: 0x1800, end: 0x18AF}, // Mongolian {begin: 0x2800, end: 0x28FF}, // Braille Patterns {begin: 0xA000, end: 0xA48F}, // Yi Syllables {begin: 0x1700, end: 0x171F}, // Tagalog {begin: 0x10300, end: 0x1032F}, // Old Italic {begin: 0x10330, end: 0x1034F}, // Gothic {begin: 0x10400, end: 0x1044F}, // Deseret {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors {begin: 0xE0000, end: 0xE007F}, // Tags {begin: 0x1900, end: 0x194F}, // Limbu {begin: 0x1950, end: 0x197F}, // Tai Le {begin: 0x1980, end: 0x19DF}, // New Tai Lue {begin: 0x1A00, end: 0x1A1F}, // Buginese {begin: 0x2C00, end: 0x2C5F}, // Glagolitic {begin: 0x2D30, end: 0x2D7F}, // Tifinagh {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols {begin: 0xA800, end: 0xA82F}, // Syloti Nagri {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers {begin: 0x10380, end: 0x1039F}, // Ugaritic {begin: 0x103A0, end: 0x103DF}, // Old Persian {begin: 0x10450, end: 0x1047F}, // Shavian {begin: 0x10480, end: 0x104AF}, // Osmanya {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols {begin: 0x12000, end: 0x123FF}, // Cuneiform {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals {begin: 0x1B80, end: 0x1BBF}, // Sundanese {begin: 0x1C00, end: 0x1C4F}, // Lepcha {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki {begin: 0xA880, end: 0xA8DF}, // Saurashtra {begin: 0xA900, end: 0xA92F}, // Kayah Li {begin: 0xA930, end: 0xA95F}, // Rejang {begin: 0xAA00, end: 0xAA5F}, // Cham {begin: 0x10190, end: 0x101CF}, // Ancient Symbols {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc {begin: 0x102A0, end: 0x102DF}, // Carian {begin: 0x1F030, end: 0x1F09F} // Domino Tiles ]; function getUnicodeRange(unicode) { for (var i = 0; i < unicodeRanges.length; i += 1) { var range = unicodeRanges[i]; if (unicode >= range.begin && unicode < range.end) { return i; } } return -1; } // Parse the OS/2 and Windows metrics `OS/2` table function parseOS2Table(data, start) { var os2 = {}; var p = new parse.Parser(data, start); os2.version = p.parseUShort(); os2.xAvgCharWidth = p.parseShort(); os2.usWeightClass = p.parseUShort(); os2.usWidthClass = p.parseUShort(); os2.fsType = p.parseUShort(); os2.ySubscriptXSize = p.parseShort(); os2.ySubscriptYSize = p.parseShort(); os2.ySubscriptXOffset = p.parseShort(); os2.ySubscriptYOffset = p.parseShort(); os2.ySuperscriptXSize = p.parseShort(); os2.ySuperscriptYSize = p.parseShort(); os2.ySuperscriptXOffset = p.parseShort(); os2.ySuperscriptYOffset = p.parseShort(); os2.yStrikeoutSize = p.parseShort(); os2.yStrikeoutPosition = p.parseShort(); os2.sFamilyClass = p.parseShort(); os2.panose = []; for (var i = 0; i < 10; i++) { os2.panose[i] = p.parseByte(); } os2.ulUnicodeRange1 = p.parseULong(); os2.ulUnicodeRange2 = p.parseULong(); os2.ulUnicodeRange3 = p.parseULong(); os2.ulUnicodeRange4 = p.parseULong(); os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); os2.fsSelection = p.parseUShort(); os2.usFirstCharIndex = p.parseUShort(); os2.usLastCharIndex = p.parseUShort(); os2.sTypoAscender = p.parseShort(); os2.sTypoDescender = p.parseShort(); os2.sTypoLineGap = p.parseShort(); os2.usWinAscent = p.parseUShort(); os2.usWinDescent = p.parseUShort(); if (os2.version >= 1) { os2.ulCodePageRange1 = p.parseULong(); os2.ulCodePageRange2 = p.parseULong(); } if (os2.version >= 2) { os2.sxHeight = p.parseShort(); os2.sCapHeight = p.parseShort(); os2.usDefaultChar = p.parseUShort(); os2.usBreakChar = p.parseUShort(); os2.usMaxContent = p.parseUShort(); } return os2; } function makeOS2Table(options) { return new table.Table('OS/2', [ {name: 'version', type: 'USHORT', value: 0x0003}, {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, {name: 'usWeightClass', type: 'USHORT', value: 0}, {name: 'usWidthClass', type: 'USHORT', value: 0}, {name: 'fsType', type: 'USHORT', value: 0}, {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, {name: 'sFamilyClass', type: 'SHORT', value: 0}, {name: 'bFamilyType', type: 'BYTE', value: 0}, {name: 'bSerifStyle', type: 'BYTE', value: 0}, {name: 'bWeight', type: 'BYTE', value: 0}, {name: 'bProportion', type: 'BYTE', value: 0}, {name: 'bContrast', type: 'BYTE', value: 0}, {name: 'bStrokeVariation', type: 'BYTE', value: 0}, {name: 'bArmStyle', type: 'BYTE', value: 0}, {name: 'bLetterform', type: 'BYTE', value: 0}, {name: 'bMidline', type: 'BYTE', value: 0}, {name: 'bXHeight', type: 'BYTE', value: 0}, {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, {name: 'fsSelection', type: 'USHORT', value: 0}, {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, {name: 'usLastCharIndex', type: 'USHORT', value: 0}, {name: 'sTypoAscender', type: 'SHORT', value: 0}, {name: 'sTypoDescender', type: 'SHORT', value: 0}, {name: 'sTypoLineGap', type: 'SHORT', value: 0}, {name: 'usWinAscent', type: 'USHORT', value: 0}, {name: 'usWinDescent', type: 'USHORT', value: 0}, {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, {name: 'sxHeight', type: 'SHORT', value: 0}, {name: 'sCapHeight', type: 'SHORT', value: 0}, {name: 'usDefaultChar', type: 'USHORT', value: 0}, {name: 'usBreakChar', type: 'USHORT', value: 0}, {name: 'usMaxContext', type: 'USHORT', value: 0} ], options); } exports.unicodeRanges = unicodeRanges; exports.getUnicodeRange = getUnicodeRange; exports.parse = parseOS2Table; exports.make = makeOS2Table; },{"../parse":10,"../table":13}],30:[function(require,module,exports){ // The `post` table stores additional PostScript information, such as glyph names. // https://www.microsoft.com/typography/OTSPEC/post.htm 'use strict'; var encoding = require('../encoding'); var parse = require('../parse'); var table = require('../table'); // Parse the PostScript `post` table function parsePostTable(data, start) { var post = {}; var p = new parse.Parser(data, start); var i; post.version = p.parseVersion(); post.italicAngle = p.parseFixed(); post.underlinePosition = p.parseShort(); post.underlineThickness = p.parseShort(); post.isFixedPitch = p.parseULong(); post.minMemType42 = p.parseULong(); post.maxMemType42 = p.parseULong(); post.minMemType1 = p.parseULong(); post.maxMemType1 = p.parseULong(); switch (post.version) { case 1: post.names = encoding.standardNames.slice(); break; case 2: post.numberOfGlyphs = p.parseUShort(); post.glyphNameIndex = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.glyphNameIndex[i] = p.parseUShort(); } post.names = []; for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] >= encoding.standardNames.length) { var nameLength = p.parseChar(); post.names.push(p.parseString(nameLength)); } } break; case 2.5: post.numberOfGlyphs = p.parseUShort(); post.offset = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.offset[i] = p.parseChar(); } break; } return post; } function makePostTable() { return new table.Table('post', [ {name: 'version', type: 'FIXED', value: 0x00030000}, {name: 'italicAngle', type: 'FIXED', value: 0}, {name: 'underlinePosition', type: 'FWORD', value: 0}, {name: 'underlineThickness', type: 'FWORD', value: 0}, {name: 'isFixedPitch', type: 'ULONG', value: 0}, {name: 'minMemType42', type: 'ULONG', value: 0}, {name: 'maxMemType42', type: 'ULONG', value: 0}, {name: 'minMemType1', type: 'ULONG', value: 0}, {name: 'maxMemType1', type: 'ULONG', value: 0} ]); } exports.parse = parsePostTable; exports.make = makePostTable; },{"../encoding":4,"../parse":10,"../table":13}],31:[function(require,module,exports){ // The `sfnt` wrapper provides organization for the tables in the font. // It is the top-level data structure in a font. // https://www.microsoft.com/typography/OTSPEC/otff.htm // Recommendations for creating OpenType Fonts: // http://www.microsoft.com/typography/otspec140/recom.htm 'use strict'; var check = require('../check'); var table = require('../table'); var cmap = require('./cmap'); var cff = require('./cff'); var head = require('./head'); var hhea = require('./hhea'); var hmtx = require('./hmtx'); var ltag = require('./ltag'); var maxp = require('./maxp'); var _name = require('./name'); var os2 = require('./os2'); var post = require('./post'); var gsub = require('./gsub'); var meta = require('./meta'); function log2(v) { return Math.log(v) / Math.log(2) | 0; } function computeCheckSum(bytes) { while (bytes.length % 4 !== 0) { bytes.push(0); } var sum = 0; for (var i = 0; i < bytes.length; i += 4) { sum += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + (bytes[i + 3]); } sum %= Math.pow(2, 32); return sum; } function makeTableRecord(tag, checkSum, offset, length) { return new table.Record('Table Record', [ {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} ]); } function makeSfntTable(tables) { var sfnt = new table.Table('sfnt', [ {name: 'version', type: 'TAG', value: 'OTTO'}, {name: 'numTables', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); sfnt.tables = tables; sfnt.numTables = tables.length; var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); sfnt.searchRange = 16 * highestPowerOf2; sfnt.entrySelector = log2(highestPowerOf2); sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; var recordFields = []; var tableFields = []; var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } for (var i = 0; i < tables.length; i += 1) { var t = tables[i]; check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); var tableLength = t.sizeOf(); var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); offset += tableLength; check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } } // Table records need to be sorted alphabetically. recordFields.sort(function(r1, r2) { if (r1.value.tag > r2.value.tag) { return 1; } else { return -1; } }); sfnt.fields = sfnt.fields.concat(recordFields); sfnt.fields = sfnt.fields.concat(tableFields); return sfnt; } // Get the metrics for a character. If the string has more than one character // this function returns metrics for the first available character. // You can provide optional fallback metrics if no characters are available. function metricsForChar(font, chars, notFoundMetrics) { for (var i = 0; i < chars.length; i += 1) { var glyphIndex = font.charToGlyphIndex(chars[i]); if (glyphIndex > 0) { var glyph = font.glyphs.get(glyphIndex); return glyph.getMetrics(); } } return notFoundMetrics; } function average(vs) { var sum = 0; for (var i = 0; i < vs.length; i += 1) { sum += vs[i]; } return sum / vs.length; } // Convert the font object to a SFNT data structure. // This structure contains all the necessary tables and metadata to create a binary OTF file. function fontToSfntTable(font) { var xMins = []; var yMins = []; var xMaxs = []; var yMaxs = []; var advanceWidths = []; var leftSideBearings = []; var rightSideBearings = []; var firstCharIndex; var lastCharIndex = 0; var ulUnicodeRange1 = 0; var ulUnicodeRange2 = 0; var ulUnicodeRange3 = 0; var ulUnicodeRange4 = 0; for (var i = 0; i < font.glyphs.length; i += 1) { var glyph = font.glyphs.get(i); var unicode = glyph.unicode | 0; if (isNaN(glyph.advanceWidth)) { throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); } if (firstCharIndex > unicode || firstCharIndex === undefined) { // ignore .notdef char if (unicode > 0) { firstCharIndex = unicode; } } if (lastCharIndex < unicode) { lastCharIndex = unicode; } var position = os2.getUnicodeRange(unicode); if (position < 32) { ulUnicodeRange1 |= 1 << position; } else if (position < 64) { ulUnicodeRange2 |= 1 << position - 32; } else if (position < 96) { ulUnicodeRange3 |= 1 << position - 64; } else if (position < 123) { ulUnicodeRange4 |= 1 << position - 96; } else { throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); } // Skip non-important characters. if (glyph.name === '.notdef') continue; var metrics = glyph.getMetrics(); xMins.push(metrics.xMin); yMins.push(metrics.yMin); xMaxs.push(metrics.xMax); yMaxs.push(metrics.yMax); leftSideBearings.push(metrics.leftSideBearing); rightSideBearings.push(metrics.rightSideBearing); advanceWidths.push(glyph.advanceWidth); } var globals = { xMin: Math.min.apply(null, xMins), yMin: Math.min.apply(null, yMins), xMax: Math.max.apply(null, xMaxs), yMax: Math.max.apply(null, yMaxs), advanceWidthMax: Math.max.apply(null, advanceWidths), advanceWidthAvg: average(advanceWidths), minLeftSideBearing: Math.min.apply(null, leftSideBearings), maxLeftSideBearing: Math.max.apply(null, leftSideBearings), minRightSideBearing: Math.min.apply(null, rightSideBearings) }; globals.ascender = font.ascender; globals.descender = font.descender; var headTable = head.make({ flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) unitsPerEm: font.unitsPerEm, xMin: globals.xMin, yMin: globals.yMin, xMax: globals.xMax, yMax: globals.yMax, lowestRecPPEM: 3, createdTimestamp: font.createdTimestamp }); var hheaTable = hhea.make({ ascender: globals.ascender, descender: globals.descender, advanceWidthMax: globals.advanceWidthMax, minLeftSideBearing: globals.minLeftSideBearing, minRightSideBearing: globals.minRightSideBearing, xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), numberOfHMetrics: font.glyphs.length }); var maxpTable = maxp.make(font.glyphs.length); var os2Table = os2.make({ xAvgCharWidth: Math.round(globals.advanceWidthAvg), usWeightClass: font.tables.os2.usWeightClass, usWidthClass: font.tables.os2.usWidthClass, usFirstCharIndex: firstCharIndex, usLastCharIndex: lastCharIndex, ulUnicodeRange1: ulUnicodeRange1, ulUnicodeRange2: ulUnicodeRange2, ulUnicodeRange3: ulUnicodeRange3, ulUnicodeRange4: ulUnicodeRange4, fsSelection: font.tables.os2.fsSelection, // REGULAR // See http://typophile.com/node/13081 for more info on vertical metrics. // We get metrics for typical characters (such as "x" for xHeight). // We provide some fallback characters if characters are unavailable: their // ordering was chosen experimentally. sTypoAscender: globals.ascender, sTypoDescender: globals.descender, sTypoLineGap: 0, usWinAscent: globals.yMax, usWinDescent: Math.abs(globals.yMin), ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available. }); var hmtxTable = hmtx.make(font.glyphs); var cmapTable = cmap.make(font.glyphs); var englishFamilyName = font.getEnglishName('fontFamily'); var englishStyleName = font.getEnglishName('fontSubfamily'); var englishFullName = englishFamilyName + ' ' + englishStyleName; var postScriptName = font.getEnglishName('postScriptName'); if (!postScriptName) { postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; } var names = {}; for (var n in font.names) { names[n] = font.names[n]; } if (!names.uniqueID) { names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; } if (!names.postScriptName) { names.postScriptName = {en: postScriptName}; } if (!names.preferredFamily) { names.preferredFamily = font.names.fontFamily; } if (!names.preferredSubfamily) { names.preferredSubfamily = font.names.fontSubfamily; } var languageTags = []; var nameTable = _name.make(names, languageTags); var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); var postTable = post.make(); var cffTable = cff.make(font.glyphs, { version: font.getEnglishName('version'), fullName: englishFullName, familyName: englishFamilyName, weightName: englishStyleName, postScriptName: postScriptName, unitsPerEm: font.unitsPerEm, fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] }); var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; // The order does not matter because makeSfntTable() will sort them. var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; if (ltagTable) { tables.push(ltagTable); } // Optional tables if (font.tables.gsub) { tables.push(gsub.make(font.tables.gsub)); } if (metaTable) { tables.push(metaTable); } var sfntTable = makeSfntTable(tables); // Compute the font's checkSum and store it in head.checkSumAdjustment. var bytes = sfntTable.encode(); var checkSum = computeCheckSum(bytes); var tableFields = sfntTable.fields; var checkSumAdjusted = false; for (i = 0; i < tableFields.length; i += 1) { if (tableFields[i].name === 'head table') { tableFields[i].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; checkSumAdjusted = true; break; } } if (!checkSumAdjusted) { throw new Error('Could not find head table with checkSum to adjust.'); } return sfntTable; } exports.computeCheckSum = computeCheckSum; exports.make = makeSfntTable; exports.fontToTable = fontToSfntTable; },{"../check":2,"../table":13,"./cff":14,"./cmap":15,"./gsub":19,"./head":20,"./hhea":21,"./hmtx":22,"./ltag":25,"./maxp":26,"./meta":27,"./name":28,"./os2":29,"./post":30}],32:[function(require,module,exports){ // Data types used in the OpenType font file. // All OpenType fonts use Motorola-style byte ordering (Big Endian) /* global WeakMap */ 'use strict'; var check = require('./check'); var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15 var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31 /** * @exports opentype.decode * @class */ var decode = {}; /** * @exports opentype.encode * @class */ var encode = {}; /** * @exports opentype.sizeOf * @class */ var sizeOf = {}; // Return a function that always returns the same value. function constant(v) { return function() { return v; }; } // OpenType data types ////////////////////////////////////////////////////// /** * Convert an 8-bit unsigned integer to a list of 1 byte. * @param {number} * @returns {Array} */ encode.BYTE = function(v) { check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.'); return [v]; }; /** * @constant * @type {number} */ sizeOf.BYTE = constant(1); /** * Convert a 8-bit signed integer to a list of 1 byte. * @param {string} * @returns {Array} */ encode.CHAR = function(v) { return [v.charCodeAt(0)]; }; /** * @constant * @type {number} */ sizeOf.CHAR = constant(1); /** * Convert an ASCII string to a list of bytes. * @param {string} * @returns {Array} */ encode.CHARARRAY = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { b[i] = v.charCodeAt(i); } return b; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARARRAY = function(v) { return v.length; }; /** * Convert a 16-bit unsigned integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.USHORT = function(v) { return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.USHORT = constant(2); /** * Convert a 16-bit signed integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.SHORT = function(v) { // Two's complement if (v >= LIMIT16) { v = -(2 * LIMIT16 - v); } return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.SHORT = constant(2); /** * Convert a 24-bit unsigned integer to a list of 3 bytes. * @param {number} * @returns {Array} */ encode.UINT24 = function(v) { return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.UINT24 = constant(3); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.ULONG = function(v) { return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.ULONG = constant(4); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.LONG = function(v) { // Two's complement if (v >= LIMIT32) { v = -(2 * LIMIT32 - v); } return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONG = constant(4); encode.FIXED = encode.ULONG; sizeOf.FIXED = sizeOf.ULONG; encode.FWORD = encode.SHORT; sizeOf.FWORD = sizeOf.SHORT; encode.UFWORD = encode.USHORT; sizeOf.UFWORD = sizeOf.USHORT; /** * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. * @param {number} * @returns {Array} */ encode.LONGDATETIME = function(v) { return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONGDATETIME = constant(8); /** * Convert a 4-char tag to a list of 4 bytes. * @param {string} * @returns {Array} */ encode.TAG = function(v) { check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); return [v.charCodeAt(0), v.charCodeAt(1), v.charCodeAt(2), v.charCodeAt(3)]; }; /** * @constant * @type {number} */ sizeOf.TAG = constant(4); // CFF data types /////////////////////////////////////////////////////////// encode.Card8 = encode.BYTE; sizeOf.Card8 = sizeOf.BYTE; encode.Card16 = encode.USHORT; sizeOf.Card16 = sizeOf.USHORT; encode.OffSize = encode.BYTE; sizeOf.OffSize = sizeOf.BYTE; encode.SID = encode.USHORT; sizeOf.SID = sizeOf.USHORT; // Convert a numeric operand or charstring number to a variable-size list of bytes. /** * Convert a numeric operand or charstring number to a variable-size list of bytes. * @param {number} * @returns {Array} */ encode.NUMBER = function(v) { if (v >= -107 && v <= 107) { return [v + 139]; } else if (v >= 108 && v <= 1131) { v = v - 108; return [(v >> 8) + 247, v & 0xFF]; } else if (v >= -1131 && v <= -108) { v = -v - 108; return [(v >> 8) + 251, v & 0xFF]; } else if (v >= -32768 && v <= 32767) { return encode.NUMBER16(v); } else { return encode.NUMBER32(v); } }; /** * @param {number} * @returns {number} */ sizeOf.NUMBER = function(v) { return encode.NUMBER(v).length; }; /** * Convert a signed number between -32768 and +32767 to a three-byte value. * This ensures we always use three bytes, but is not the most compact format. * @param {number} * @returns {Array} */ encode.NUMBER16 = function(v) { return [28, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER16 = constant(3); /** * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. * This is useful if you want to be sure you always use four bytes, * at the expense of wasting a few bytes for smaller numbers. * @param {number} * @returns {Array} */ encode.NUMBER32 = function(v) { return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER32 = constant(5); /** * @param {number} * @returns {Array} */ encode.REAL = function(v) { var value = v.toString(); // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) // This code converts it back to a number without the epsilon. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); if (m) { var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(v * epsilon) / epsilon).toString(); } var nibbles = ''; var i; var ii; for (i = 0, ii = value.length; i < ii; i += 1) { var c = value[i]; if (c === 'e') { nibbles += value[++i] === '-' ? 'c' : 'b'; } else if (c === '.') { nibbles += 'a'; } else if (c === '-') { nibbles += 'e'; } else { nibbles += c; } } nibbles += (nibbles.length & 1) ? 'f' : 'ff'; var out = [30]; for (i = 0, ii = nibbles.length; i < ii; i += 2) { out.push(parseInt(nibbles.substr(i, 2), 16)); } return out; }; /** * @param {number} * @returns {number} */ sizeOf.REAL = function(v) { return encode.REAL(v).length; }; encode.NAME = encode.CHARARRAY; sizeOf.NAME = sizeOf.CHARARRAY; encode.STRING = encode.CHARARRAY; sizeOf.STRING = sizeOf.CHARARRAY; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF8 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes; for (var j = 0; j < numChars; j++, offset += 1) { codePoints[j] = data.getUint8(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF16 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes / 2; for (var j = 0; j < numChars; j++, offset += 2) { codePoints[j] = data.getUint16(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * Convert a JavaScript string to UTF16-BE. * @param {string} * @returns {Array} */ encode.UTF16 = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { var codepoint = v.charCodeAt(i); b[b.length] = (codepoint >> 8) & 0xFF; b[b.length] = codepoint & 0xFF; } return b; }; /** * @param {string} * @returns {number} */ sizeOf.UTF16 = function(v) { return v.length * 2; }; // Data for converting old eight-bit Macintosh encodings to Unicode. // This representation is optimized for decoding; encoding is slower // and needs more memory. The assumption is that all opentype.js users // want to open fonts, but saving a font will be comperatively rare // so it can be more expensive. Keyed by IANA character set name. // // Python script for generating these strings: // // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) // print(s.encode('utf-8')) /** * @private */ var eightBitMacEncodings = { 'x-mac-croatian': // Python: 'mac_croatian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', 'x-mac-cyrillic': // Python: 'mac_cyrillic' 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', 'x-mac-greek': // Python: 'mac_greek' 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', 'x-mac-icelandic': // Python: 'mac_iceland' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', 'x-mac-ce': // Python: 'mac_latin2' 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', macintosh: // Python: 'mac_roman' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-romanian': // Python: 'mac_romanian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-turkish': // Python: 'mac_turkish' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' }; /** * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript * string, or 'undefined' if the encoding is unsupported. For example, we do * not support Chinese, Japanese or Korean because these would need large * mapping tables. * @param {DataView} dataView * @param {number} offset * @param {number} dataLength * @param {string} encoding * @returns {string} */ decode.MACSTRING = function(dataView, offset, dataLength, encoding) { var table = eightBitMacEncodings[encoding]; if (table === undefined) { return undefined; } var result = ''; for (var i = 0; i < dataLength; i++) { var c = dataView.getUint8(offset + i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c <= 0x7F) { result += String.fromCharCode(c); } else { result += table[c & 0x7F]; } } return result; }; // Helper function for encode.MACSTRING. Returns a dictionary for mapping // Unicode character codes to their 8-bit MacOS equivalent. This table // is not exactly a super cheap data structure, but we do not care because // encoding Macintosh strings is only rarely needed in typical applications. var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); var macEncodingCacheKeys; var getMacEncodingTable = function(encoding) { // Since we use encoding as a cache key for WeakMap, it has to be // a String object and not a literal. And at least on NodeJS 2.10.1, // WeakMap requires that the same String instance is passed for cache hits. if (!macEncodingCacheKeys) { macEncodingCacheKeys = {}; for (var e in eightBitMacEncodings) { /*jshint -W053 */ // Suppress "Do not use String as a constructor." macEncodingCacheKeys[e] = new String(e); } } var cacheKey = macEncodingCacheKeys[encoding]; if (cacheKey === undefined) { return undefined; } // We can't do "if (cache.has(key)) {return cache.get(key)}" here: // since garbage collection may run at any time, it could also kick in // between the calls to cache.has() and cache.get(). In that case, // we would return 'undefined' even though we do support the encoding. if (macEncodingTableCache) { var cachedTable = macEncodingTableCache.get(cacheKey); if (cachedTable !== undefined) { return cachedTable; } } var decodingTable = eightBitMacEncodings[encoding]; if (decodingTable === undefined) { return undefined; } var encodingTable = {}; for (var i = 0; i < decodingTable.length; i++) { encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; } if (macEncodingTableCache) { macEncodingTableCache.set(cacheKey, encodingTable); } return encodingTable; }; /** * Encodes an old-style Macintosh string. Returns a byte array upon success. * If the requested encoding is unsupported, or if the input string contains * a character that cannot be expressed in the encoding, the function returns * 'undefined'. * @param {string} str * @param {string} encoding * @returns {Array} */ encode.MACSTRING = function(str, encoding) { var table = getMacEncodingTable(encoding); if (table === undefined) { return undefined; } var result = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c >= 0x80) { c = table[c]; if (c === undefined) { // str contains a Unicode character that cannot be encoded // in the requested encoding. return undefined; } } result[i] = c; // result.push(c); } return result; }; /** * @param {string} str * @param {string} encoding * @returns {number} */ sizeOf.MACSTRING = function(str, encoding) { var b = encode.MACSTRING(str, encoding); if (b !== undefined) { return b.length; } else { return 0; } }; // Convert a list of values to a CFF INDEX structure. // The values should be objects containing name / type / value. /** * @param {Array} l * @returns {Array} */ encode.INDEX = function(l) { var i; //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, // i, v; // Because we have to know which data type to use to encode the offsets, // we have to go through the values twice: once to encode the data and // calculate the offets, then again to encode the offsets using the fitting data type. var offset = 1; // First offset is always 1. var offsets = [offset]; var data = []; for (i = 0; i < l.length; i += 1) { var v = encode.OBJECT(l[i]); Array.prototype.push.apply(data, v); offset += v.length; offsets.push(offset); } if (data.length === 0) { return [0, 0]; } var encodedOffsets = []; var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; for (i = 0; i < offsets.length; i += 1) { var encodedOffset = offsetEncoder(offsets[i]); Array.prototype.push.apply(encodedOffsets, encodedOffset); } return Array.prototype.concat(encode.Card16(l.length), encode.OffSize(offSize), encodedOffsets, data); }; /** * @param {Array} * @returns {number} */ sizeOf.INDEX = function(v) { return encode.INDEX(v).length; }; /** * Convert an object to a CFF DICT structure. * The keys should be numeric. * The values should be objects containing name / type / value. * @param {Object} m * @returns {Array} */ encode.DICT = function(m) { var d = []; var keys = Object.keys(m); var length = keys.length; for (var i = 0; i < length; i += 1) { // Object.keys() return string keys, but our keys are always numeric. var k = parseInt(keys[i], 0); var v = m[k]; // Value comes before the key. d = d.concat(encode.OPERAND(v.value, v.type)); d = d.concat(encode.OPERATOR(k)); } return d; }; /** * @param {Object} * @returns {number} */ sizeOf.DICT = function(m) { return encode.DICT(m).length; }; /** * @param {number} * @returns {Array} */ encode.OPERATOR = function(v) { if (v < 1200) { return [v]; } else { return [12, v - 1200]; } }; /** * @param {Array} v * @param {string} * @returns {Array} */ encode.OPERAND = function(v, type) { var d = []; if (Array.isArray(type)) { for (var i = 0; i < type.length; i += 1) { check.argument(v.length === type.length, 'Not enough arguments given for type' + type); d = d.concat(encode.OPERAND(v[i], type[i])); } } else { if (type === 'SID') { d = d.concat(encode.NUMBER(v)); } else if (type === 'offset') { // We make it easy for ourselves and always encode offsets as // 4 bytes. This makes offset calculation for the top dict easier. d = d.concat(encode.NUMBER32(v)); } else if (type === 'number') { d = d.concat(encode.NUMBER(v)); } else if (type === 'real') { d = d.concat(encode.REAL(v)); } else { throw new Error('Unknown operand type ' + type); // FIXME Add support for booleans } } return d; }; encode.OP = encode.BYTE; sizeOf.OP = sizeOf.BYTE; // memoize charstring encoding using WeakMap if available var wmm = typeof WeakMap === 'function' && new WeakMap(); /** * Convert a list of CharString operations to bytes. * @param {Array} * @returns {Array} */ encode.CHARSTRING = function(ops) { // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". if (wmm) { var cachedValue = wmm.get(ops); if (cachedValue !== undefined) { return cachedValue; } } var d = []; var length = ops.length; for (var i = 0; i < length; i += 1) { var op = ops[i]; d = d.concat(encode[op.type](op.value)); } if (wmm) { wmm.set(ops, d); } return d; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARSTRING = function(ops) { return encode.CHARSTRING(ops).length; }; // Utility functions //////////////////////////////////////////////////////// /** * Convert an object containing name / type / value to bytes. * @param {Object} * @returns {Array} */ encode.OBJECT = function(v) { var encodingFunction = encode[v.type]; check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); return encodingFunction(v.value); }; /** * @param {Object} * @returns {number} */ sizeOf.OBJECT = function(v) { var sizeOfFunction = sizeOf[v.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); return sizeOfFunction(v.value); }; /** * Convert a table object to bytes. * A table contains a list of fields containing the metadata (name, type and default value). * The table itself has the field values set as attributes. * @param {opentype.Table} * @returns {Array} */ encode.TABLE = function(table) { var d = []; var length = table.fields.length; var subtables = []; var subtableOffsets = []; var i; for (i = 0; i < length; i += 1) { var field = table.fields[i]; var encodingFunction = encode[field.type]; check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } var bytes = encodingFunction(value); if (field.type === 'TABLE') { subtableOffsets.push(d.length); d = d.concat([0, 0]); subtables.push(bytes); } else { d = d.concat(bytes); } } for (i = 0; i < subtables.length; i += 1) { var o = subtableOffsets[i]; var offset = d.length; check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); d[o] = offset >> 8; d[o + 1] = offset & 0xff; d = d.concat(subtables[i]); } return d; }; /** * @param {opentype.Table} * @returns {number} */ sizeOf.TABLE = function(table) { var numBytes = 0; var length = table.fields.length; for (var i = 0; i < length; i += 1) { var field = table.fields[i]; var sizeOfFunction = sizeOf[field.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } numBytes += sizeOfFunction(value); // Subtables take 2 more bytes for offsets. if (field.type === 'TABLE') { numBytes += 2; } } return numBytes; }; encode.RECORD = encode.TABLE; sizeOf.RECORD = sizeOf.TABLE; // Merge in a list of bytes. encode.LITERAL = function(v) { return v; }; sizeOf.LITERAL = function(v) { return v.length; }; exports.decode = decode; exports.encode = encode; exports.sizeOf = sizeOf; },{"./check":2}],33:[function(require,module,exports){ 'use strict'; exports.isBrowser = function() { return typeof window !== 'undefined'; }; exports.isNode = function() { return typeof window === 'undefined'; }; exports.nodeBufferToArrayBuffer = function(buffer) { var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { view[i] = buffer[i]; } return ab; }; exports.arrayBufferToNodeBuffer = function(ab) { var buffer = new Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; }; exports.checkArgument = function(expression, message) { if (!expression) { throw message; } }; },{}]},{},[9])(9) });
mit
FauxFaux/jdk9-nashorn
test/src/jdk/nashorn/test/models/VarArgConsumer.java
1400
/* * Copyright (c) 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ package jdk.nashorn.test.models; /** * Simple function interface with a varargs SAM method. */ @FunctionalInterface public interface VarArgConsumer { public void apply(Object... o); }
gpl-2.0
carbamide/Einstein
_Build_/Xcode4/XADMaster/Crypto/aestab.h
5332
/* --------------------------------------------------------------------------- Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved. The redistribution and use of this software (with or without changes) is allowed without the payment of fees or royalties provided that: source code distributions include the above copyright notice, this list of conditions and the following disclaimer; binary distributions include the above copyright notice, this list of conditions and the following disclaimer in their documentation. This software is provided 'as is' with no explicit or implied warranties in respect of its operation, including, but not limited to, correctness and fitness for purpose. --------------------------------------------------------------------------- Issue Date: 20/12/2007 This file contains the code for declaring the tables needed to implement AES. The file aesopt.h is assumed to be included before this header file. If there are no global variables, the definitions here can be used to put the AES tables in a structure so that a pointer can then be added to the AES context to pass them to the AES routines that need them. If this facility is used, the calling program has to ensure that this pointer is managed appropriately. In particular, the value of the t_dec(in,it) item in the table structure must be set to zero in order to ensure that the tables are initialised. In practice the three code sequences in aeskey.c that control the calls to aes_init() and the aes_init() routine itself will have to be changed for a specific implementation. If global variables are available it will generally be preferable to use them with the precomputed FIXED_TABLES option that uses static global tables. The following defines can be used to control the way the tables are defined, initialised and used in embedded environments that require special features for these purposes the 't_dec' construction is used to declare fixed table arrays the 't_set' construction is used to set fixed table values the 't_use' construction is used to access fixed table values 256 byte tables: t_xxx(s,box) => forward S box t_xxx(i,box) => inverse S box 256 32-bit word OR 4 x 256 32-bit word tables: t_xxx(f,n) => forward normal round t_xxx(f,l) => forward last round t_xxx(i,n) => inverse normal round t_xxx(i,l) => inverse last round t_xxx(l,s) => key schedule table t_xxx(i,m) => key schedule table Other variables and tables: t_xxx(r,c) => the rcon table */ #if !defined( _AESTAB_H ) #define _AESTAB_H #if defined(__cplusplus) extern "C" { #endif #define t_dec(m,n) t_##m##n #define t_set(m,n) t_##m##n #define t_use(m,n) t_##m##n #if defined(FIXED_TABLES) # if !defined( __GNUC__ ) && (defined( __MSDOS__ ) || defined( __WIN16__ )) /* make tables far data to avoid using too much DGROUP space (PG) */ # define CONST const far # else # define CONST const # endif #else # define CONST #endif #if defined(DO_TABLES) # define EXTERN #else # define EXTERN extern #endif #if defined(_MSC_VER) && defined(TABLE_ALIGN) #define ALIGN __declspec(align(TABLE_ALIGN)) #else #define ALIGN #endif #if defined( __WATCOMC__ ) && ( __WATCOMC__ >= 1100 ) # define XP_DIR __cdecl #else # define XP_DIR #endif #if defined(DO_TABLES) && defined(FIXED_TABLES) #define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] = b(e) #define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] = { b(e), b(f), b(g), b(h) } EXTERN ALIGN CONST uint32_t t_dec(r,c)[RC_LENGTH] = rc_data(w0); #else #define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] #define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] EXTERN ALIGN CONST uint32_t t_dec(r,c)[RC_LENGTH]; #endif #if defined( SBX_SET ) d_1(uint_8t, t_dec(s,box), sb_data, h0); #endif #if defined( ISB_SET ) d_1(uint_8t, t_dec(i,box), isb_data, h0); #endif #if defined( FT1_SET ) d_1(uint32_t, t_dec(f,n), sb_data, u0); #endif #if defined( FT4_SET ) d_4(uint32_t, t_dec(f,n), sb_data, u0, u1, u2, u3); #endif #if defined( FL1_SET ) d_1(uint32_t, t_dec(f,l), sb_data, w0); #endif #if defined( FL4_SET ) d_4(uint32_t, t_dec(f,l), sb_data, w0, w1, w2, w3); #endif #if defined( IT1_SET ) d_1(uint32_t, t_dec(i,n), isb_data, v0); #endif #if defined( IT4_SET ) d_4(uint32_t, t_dec(i,n), isb_data, v0, v1, v2, v3); #endif #if defined( IL1_SET ) d_1(uint32_t, t_dec(i,l), isb_data, w0); #endif #if defined( IL4_SET ) d_4(uint32_t, t_dec(i,l), isb_data, w0, w1, w2, w3); #endif #if defined( LS1_SET ) #if defined( FL1_SET ) #undef LS1_SET #else d_1(uint32_t, t_dec(l,s), sb_data, w0); #endif #endif #if defined( LS4_SET ) #if defined( FL4_SET ) #undef LS4_SET #else d_4(uint32_t, t_dec(l,s), sb_data, w0, w1, w2, w3); #endif #endif #if defined( IM1_SET ) d_1(uint32_t, t_dec(i,m), mm_data, v0); #endif #if defined( IM4_SET ) d_4(uint32_t, t_dec(i,m), mm_data, v0, v1, v2, v3); #endif #if defined(__cplusplus) } #endif #endif
gpl-2.0
rpaleari/qtrace
src/dtc/tests/path_offset.c
3735
/* * libfdt - Flat Device Tree manipulation * Testcase for fdt_path_offset() * Copyright (C) 2006 David Gibson, IBM Corporation. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <fdt.h> #include <libfdt.h> #include "tests.h" #include "testdata.h" static int check_subnode(void *fdt, int parent, const char *name) { int offset; const struct fdt_node_header *nh; uint32_t tag; verbose_printf("Checking subnode \"%s\" of %d...", name, parent); offset = fdt_subnode_offset(fdt, parent, name); verbose_printf("offset %d...", offset); if (offset < 0) FAIL("fdt_subnode_offset(\"%s\"): %s", name, fdt_strerror(offset)); nh = fdt_offset_ptr(fdt, offset, sizeof(*nh)); verbose_printf("pointer %p\n", nh); if (! nh) FAIL("NULL retrieving subnode \"%s\"", name); tag = fdt32_to_cpu(nh->tag); if (tag != FDT_BEGIN_NODE) FAIL("Incorrect tag 0x%08x on property \"%s\"", tag, name); if (!nodename_eq(nh->name, name)) FAIL("Subnode name mismatch \"%s\" instead of \"%s\"", nh->name, name); return offset; } int main(int argc, char *argv[]) { void *fdt; int root_offset; int subnode1_offset, subnode2_offset; int subnode1_offset_p, subnode2_offset_p; int subsubnode1_offset, subsubnode2_offset, subsubnode2_offset2; int subsubnode1_offset_p, subsubnode2_offset_p, subsubnode2_offset2_p; test_init(argc, argv); fdt = load_blob_arg(argc, argv); root_offset = fdt_path_offset(fdt, "/"); if (root_offset < 0) FAIL("fdt_path_offset(\"/\") failed: %s", fdt_strerror(root_offset)); else if (root_offset != 0) FAIL("fdt_path_offset(\"/\") returns incorrect offset %d", root_offset); subnode1_offset = check_subnode(fdt, 0, "subnode@1"); subnode2_offset = check_subnode(fdt, 0, "subnode@2"); subnode1_offset_p = fdt_path_offset(fdt, "/subnode@1"); subnode2_offset_p = fdt_path_offset(fdt, "/subnode@2"); if (subnode1_offset != subnode1_offset_p) FAIL("Mismatch between subnode_offset (%d) and path_offset (%d)", subnode1_offset, subnode1_offset_p); if (subnode2_offset != subnode2_offset_p) FAIL("Mismatch between subnode_offset (%d) and path_offset (%d)", subnode2_offset, subnode2_offset_p); subsubnode1_offset = check_subnode(fdt, subnode1_offset, "subsubnode"); subsubnode2_offset = check_subnode(fdt, subnode2_offset, "subsubnode@0"); subsubnode2_offset2 = check_subnode(fdt, subnode2_offset, "subsubnode"); subsubnode1_offset_p = fdt_path_offset(fdt, "/subnode@1/subsubnode"); subsubnode2_offset_p = fdt_path_offset(fdt, "/subnode@2/subsubnode@0"); subsubnode2_offset2_p = fdt_path_offset(fdt, "/subnode@2/subsubnode"); if (subsubnode1_offset != subsubnode1_offset_p) FAIL("Mismatch between subnode_offset (%d) and path_offset (%d)", subsubnode1_offset, subsubnode1_offset_p); if (subsubnode2_offset != subsubnode2_offset_p) FAIL("Mismatch between subnode_offset (%d) and path_offset (%d)", subsubnode2_offset, subsubnode2_offset_p); PASS(); }
gpl-2.0
AfrikaBurn/Main
web/libraries/codemirror/src/edit/options.js
6874
import { onBlur } from "../display/focus" import { setGuttersForLineNumbers, updateGutters } from "../display/gutters" import { alignHorizontally } from "../display/line_numbers" import { loadMode, resetModeState } from "../display/mode_state" import { initScrollbars, updateScrollbars } from "../display/scrollbars" import { updateSelection } from "../display/selection" import { regChange } from "../display/view_tracking" import { getKeyMap } from "../input/keymap" import { defaultSpecialCharPlaceholder } from "../line/line_data" import { Pos } from "../line/pos" import { findMaxLine } from "../line/spans" import { clearCaches, compensateForHScroll, estimateLineHeights } from "../measurement/position_measurement" import { replaceRange } from "../model/changes" import { mobile, windows } from "../util/browser" import { addClass, rmClass } from "../util/dom" import { off, on } from "../util/event" import { themeChanged } from "./utils" export let Init = {toString: function(){return "CodeMirror.Init"}} export let defaults = {} export let optionHandlers = {} export function defineOptions(CodeMirror) { let optionHandlers = CodeMirror.optionHandlers function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt if (handle) optionHandlers[name] = notOnInit ? (cm, val, old) => {if (old != Init) handle(cm, val, old)} : handle } CodeMirror.defineOption = option // Passed to option handlers when there is no old value. CodeMirror.Init = Init // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", (cm, val) => cm.setValue(val), true) option("mode", null, (cm, val) => { cm.doc.modeOption = val loadMode(cm) }, true) option("indentUnit", 2, loadMode, true) option("indentWithTabs", false) option("smartIndent", true) option("tabSize", 4, cm => { resetModeState(cm) clearCaches(cm) regChange(cm) }, true) option("lineSeparator", null, (cm, val) => { cm.doc.lineSep = val if (!val) return let newBreaks = [], lineNo = cm.doc.first cm.doc.iter(line => { for (let pos = 0;;) { let found = line.text.indexOf(val, pos) if (found == -1) break pos = found + val.length newBreaks.push(Pos(lineNo, found)) } lineNo++ }) for (let i = newBreaks.length - 1; i >= 0; i--) replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }) option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, (cm, val, old) => { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") if (old != Init) cm.refresh() }) option("specialCharPlaceholder", defaultSpecialCharPlaceholder, cm => cm.refresh(), true) option("electricChars", true) option("inputStyle", mobile ? "contenteditable" : "textarea", () => { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true) option("spellcheck", false, (cm, val) => cm.getInputField().spellcheck = val, true) option("rtlMoveVisually", !windows) option("wholeLineUpdateBefore", true) option("theme", "default", cm => { themeChanged(cm) guttersChanged(cm) }, true) option("keyMap", "default", (cm, val, old) => { let next = getKeyMap(val) let prev = old != Init && getKeyMap(old) if (prev && prev.detach) prev.detach(cm, next) if (next.attach) next.attach(cm, prev || null) }) option("extraKeys", null) option("configureMouse", null) option("lineWrapping", false, wrappingChanged, true) option("gutters", [], cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("fixedGutter", true, (cm, val) => { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" cm.refresh() }, true) option("coverGutterNextToScrollbar", false, cm => updateScrollbars(cm), true) option("scrollbarStyle", "native", cm => { initScrollbars(cm) updateScrollbars(cm) cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) }, true) option("lineNumbers", false, cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("firstLineNumber", 1, guttersChanged, true) option("lineNumberFormatter", integer => integer, guttersChanged, true) option("showCursorWhenSelecting", false, updateSelection, true) option("resetSelectionOnContextMenu", true) option("lineWiseCopyCut", true) option("pasteLinesPerSelection", true) option("readOnly", false, (cm, val) => { if (val == "nocursor") { onBlur(cm) cm.display.input.blur() } cm.display.input.readOnlyChanged(val) }) option("disableInput", false, (cm, val) => {if (!val) cm.display.input.reset()}, true) option("dragDrop", true, dragDropChanged) option("allowDropFileTypes", null) option("cursorBlinkRate", 530) option("cursorScrollMargin", 0) option("cursorHeight", 1, updateSelection, true) option("singleCursorHeightPerLine", true, updateSelection, true) option("workTime", 100) option("workDelay", 100) option("flattenSpans", true, resetModeState, true) option("addModeClass", false, resetModeState, true) option("pollInterval", 100) option("undoDepth", 200, (cm, val) => cm.doc.history.undoDepth = val) option("historyEventDelay", 1250) option("viewportMargin", 10, cm => cm.refresh(), true) option("maxHighlightLength", 10000, resetModeState, true) option("moveInputWithCursor", true, (cm, val) => { if (!val) cm.display.input.resetPosition() }) option("tabindex", null, (cm, val) => cm.display.input.getField().tabIndex = val || "") option("autofocus", null) option("direction", "ltr", (cm, val) => cm.doc.setDirection(val), true) } function guttersChanged(cm) { updateGutters(cm) regChange(cm) alignHorizontally(cm) } function dragDropChanged(cm, value, old) { let wasOn = old && old != Init if (!value != !wasOn) { let funcs = cm.display.dragFunctions let toggle = value ? on : off toggle(cm.display.scroller, "dragstart", funcs.start) toggle(cm.display.scroller, "dragenter", funcs.enter) toggle(cm.display.scroller, "dragover", funcs.over) toggle(cm.display.scroller, "dragleave", funcs.leave) toggle(cm.display.scroller, "drop", funcs.drop) } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap") cm.display.sizer.style.minWidth = "" cm.display.sizerWidth = null } else { rmClass(cm.display.wrapper, "CodeMirror-wrap") findMaxLine(cm) } estimateLineHeights(cm) regChange(cm) clearCaches(cm) setTimeout(() => updateScrollbars(cm), 100) }
gpl-2.0
noskill/Firesoft
src/main/webapp/ckeditor/lang/sr.js
3935
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Serbian (Cyrillic) language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang[ 'sr' ] = { // ARIA description. editor: 'Rich Text Editor', // MISSING editorPanel: 'Rich Text Editor panel', // MISSING // Common messages and labels. common: { // Screenreader titles. Please note that screenreaders are not always capable // of reading non-English words. So be careful while translating it. editorHelp: 'Press ALT 0 for help', // MISSING browseServer: 'Претражи сервер', url: 'УРЛ', protocol: 'Протокол', upload: 'Пошаљи', uploadSubmit: 'Пошаљи на сервер', image: 'Слика', flash: 'Флеш елемент', form: 'Форма', checkbox: 'Поље за потврду', radio: 'Радио-дугме', textField: 'Текстуално поље', textarea: 'Зона текста', hiddenField: 'Скривено поље', button: 'Дугме', select: 'Изборно поље', imageButton: 'Дугме са сликом', notSet: '<није постављено>', id: 'Ид', name: 'Назив', langDir: 'Смер језика', langDirLtr: 'С лева на десно (LTR)', langDirRtl: 'С десна на лево (RTL)', langCode: 'Kôд језика', longDescr: 'Пун опис УРЛ', cssClass: 'Stylesheet класе', advisoryTitle: 'Advisory наслов', cssStyle: 'Стил', ok: 'OK', cancel: 'Oткажи', close: 'Затвори', preview: 'Изглед странице', resize: 'Resize', // MISSING generalTab: 'Опште', advancedTab: 'Напредни тагови', validateNumberFailed: 'Ова вредност није цигра.', confirmNewPage: 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING confirmCancel: 'You have changed some options. Are you sure you want to close the dialog window?', // MISSING options: 'Опције', target: 'Meтa', targetNew: 'New Window (_blank)', // MISSING targetTop: 'Topmost Window (_top)', // MISSING targetSelf: 'Same Window (_self)', // MISSING targetParent: 'Parent Window (_parent)', // MISSING langDirLTR: 'С лева на десно (LTR)', langDirRTL: 'С десна на лево (RTL)', styles: 'Стил', cssClasses: 'Stylesheet класе', width: 'Ширина', height: 'Висина', align: 'Равнање', alignLeft: 'Лево', alignRight: 'Десно', alignCenter: 'Средина', alignJustify: 'Обострано равнање', alignTop: 'Врх', alignMiddle: 'Средина', alignBottom: 'Доле', alignNone: 'None', // MISSING invalidValue : 'Invalid value.', // MISSING invalidHeight: 'Height must be a number.', // MISSING invalidWidth: 'Width must be a number.', // MISSING invalidCssLength: 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength: 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING invalidInlineStyle: 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', // MISSING cssLengthTooltip: 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING // Put the voice-only part of the label in the span. unavailable: '%1<span class="cke_accessibility">, unavailable</span>' // MISSING } };
gpl-3.0
Shangxz/HackIllinois2017
tone-analysis/fftw-3.3.6-pl1/mpi/rdft-rank-geq2.c
5293
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * 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 * */ /* Complex RDFTs of rank >= 2, for the case where we are distributed across the first dimension only, and the output is not transposed. */ #include "mpi-rdft.h" typedef struct { solver super; int preserve_input; /* preserve input even if DESTROY_INPUT was passed */ } S; typedef struct { plan_mpi_rdft super; plan *cld1, *cld2; int preserve_input; } P; static void apply(const plan *ego_, R *I, R *O) { const P *ego = (const P *) ego_; plan_rdft *cld1, *cld2; /* RDFT local dimensions */ cld1 = (plan_rdft *) ego->cld1; if (ego->preserve_input) { cld1->apply(ego->cld1, I, O); I = O; } else cld1->apply(ego->cld1, I, I); /* RDFT non-local dimension (via rdft-rank1-bigvec, usually): */ cld2 = (plan_rdft *) ego->cld2; cld2->apply(ego->cld2, I, O); } static int applicable(const S *ego, const problem *p_, const planner *plnr) { const problem_mpi_rdft *p = (const problem_mpi_rdft *) p_; return (1 && p->sz->rnk > 1 && p->flags == 0 /* TRANSPOSED/SCRAMBLED_IN/OUT not supported */ && (!ego->preserve_input || (!NO_DESTROY_INPUTP(plnr) && p->I != p->O)) && XM(is_local_after)(1, p->sz, IB) && XM(is_local_after)(1, p->sz, OB) && (!NO_SLOWP(plnr) /* slow if rdft-serial is applicable */ || !XM(rdft_serial_applicable)(p)) ); } static void awake(plan *ego_, enum wakefulness wakefulness) { P *ego = (P *) ego_; X(plan_awake)(ego->cld1, wakefulness); X(plan_awake)(ego->cld2, wakefulness); } static void destroy(plan *ego_) { P *ego = (P *) ego_; X(plan_destroy_internal)(ego->cld2); X(plan_destroy_internal)(ego->cld1); } static void print(const plan *ego_, printer *p) { const P *ego = (const P *) ego_; p->print(p, "(mpi-rdft-rank-geq2%s%(%p%)%(%p%))", ego->preserve_input==2 ?"/p":"", ego->cld1, ego->cld2); } static plan *mkplan(const solver *ego_, const problem *p_, planner *plnr) { const S *ego = (const S *) ego_; const problem_mpi_rdft *p; P *pln; plan *cld1 = 0, *cld2 = 0; R *I, *O, *I2; tensor *sz; dtensor *sz2; int i, my_pe, n_pes; INT nrest; static const plan_adt padt = { XM(rdft_solve), awake, print, destroy }; UNUSED(ego); if (!applicable(ego, p_, plnr)) return (plan *) 0; p = (const problem_mpi_rdft *) p_; I2 = I = p->I; O = p->O; if (ego->preserve_input || NO_DESTROY_INPUTP(plnr)) I = O; MPI_Comm_rank(p->comm, &my_pe); MPI_Comm_size(p->comm, &n_pes); sz = X(mktensor)(p->sz->rnk - 1); /* tensor of last rnk-1 dimensions */ i = p->sz->rnk - 2; A(i >= 0); sz->dims[i].n = p->sz->dims[i+1].n; sz->dims[i].is = sz->dims[i].os = p->vn; for (--i; i >= 0; --i) { sz->dims[i].n = p->sz->dims[i+1].n; sz->dims[i].is = sz->dims[i].os = sz->dims[i+1].n * sz->dims[i+1].is; } nrest = X(tensor_sz)(sz); { INT is = sz->dims[0].n * sz->dims[0].is; INT b = XM(block)(p->sz->dims[0].n, p->sz->dims[0].b[IB], my_pe); cld1 = X(mkplan_d)(plnr, X(mkproblem_rdft_d)(sz, X(mktensor_2d)(b, is, is, p->vn, 1, 1), I2, I, p->kind + 1)); if (XM(any_true)(!cld1, p->comm)) goto nada; } sz2 = XM(mkdtensor)(1); /* tensor for first (distributed) dimension */ sz2->dims[0] = p->sz->dims[0]; cld2 = X(mkplan_d)(plnr, XM(mkproblem_rdft_d)(sz2, nrest * p->vn, I, O, p->comm, p->kind, RANK1_BIGVEC_ONLY)); if (XM(any_true)(!cld2, p->comm)) goto nada; pln = MKPLAN_MPI_RDFT(P, &padt, apply); pln->cld1 = cld1; pln->cld2 = cld2; pln->preserve_input = ego->preserve_input ? 2 : NO_DESTROY_INPUTP(plnr); X(ops_add)(&cld1->ops, &cld2->ops, &pln->super.super.ops); return &(pln->super.super); nada: X(plan_destroy_internal)(cld2); X(plan_destroy_internal)(cld1); return (plan *) 0; } static solver *mksolver(int preserve_input) { static const solver_adt sadt = { PROBLEM_MPI_RDFT, mkplan, 0 }; S *slv = MKSOLVER(S, &sadt); slv->preserve_input = preserve_input; return &(slv->super); } void XM(rdft_rank_geq2_register)(planner *p) { int preserve_input; for (preserve_input = 0; preserve_input <= 1; ++preserve_input) REGISTER_SOLVER(p, mksolver(preserve_input)); }
gpl-3.0
gtison/kf
src/main/resources/static/js/jquery.darktooltip.js
6675
/* * DarkTooltip v0.4.0 * Simple customizable tooltip with confirm option and 3d effects * (c)2014 Rubén Torres - [email protected] * Released under the MIT license */ (function($) { function DarkTooltip(element, options){ this.bearer = element; this.options = options; this.hideEvent; this.mouseOverMode=(this.options.trigger == "hover" || this.options.trigger == "mouseover" || this.options.trigger == "onmouseover"); } DarkTooltip.prototype = { show: function(){ var dt = this; if(this.options.modal){ this.modalLayer.css('display', 'block'); } //Close all other tooltips this.tooltip.css('display', 'block'); //Set event to prevent tooltip from closig when mouse is over the tooltip if(dt.mouseOverMode){ this.tooltip.mouseover( function(){ clearTimeout(dt.hideEvent); }); this.tooltip.mouseout( function(){ clearTimeout(dt.hideEvent); dt.hide(); }); } }, hide: function(){ var dt=this; this.hideEvent = setTimeout( function(){ dt.tooltip.hide(); }, 100); if(dt.options.modal){ dt.modalLayer.hide(); } this.options.onClose(); }, toggle: function(){ if(this.tooltip.is(":visible")){ this.hide(); }else{ this.show(); } }, addAnimation: function(){ switch(this.options.animation){ case 'none': break; case 'fadeIn': this.tooltip.addClass('animated'); this.tooltip.addClass('fadeIn'); break; case 'flipIn': this.tooltip.addClass('animated'); this.tooltip.addClass('flipIn'); break; } }, setContent: function(){ $(this.bearer).css('cursor', 'pointer'); //Get tooltip content if(this.options.content){ this.content = this.options.content; }else if(this.bearer.attr("data-tooltip")){ this.content = this.bearer.attr("data-tooltip"); }else{ // console.log("No content for tooltip: " + this.bearer.selector); return; } if(this.content.charAt(0) == '#'){ if (this.options.delete_content){ var content = $(this.content).html(); $(this.content).html(''); this.content = content; delete content; } else{ $(this.content).hide(); this.content = $(this.content).html(); } this.contentType='html'; }else{ this.contentType='text'; } tooltipId = ""; if(this.bearer.attr("id") != ""){ tooltipId = "id='darktooltip-" + this.bearer.attr("id") + "'"; } //Create modal layer this.modalLayer = $("<ins class='darktooltip-modal-layer'></ins>"); //Create tooltip container this.tooltip = $("<ins " + tooltipId + " class = 'dark-tooltip " + this.options.theme + " " + this.options.size + " " + this.options.gravity + "'><div>" + this.content + "</div><div class = 'tip'></div></ins>"); this.tip = this.tooltip.find(".tip"); $("body").append(this.modalLayer); $("body").append(this.tooltip); //Adjust size for html tooltip if(this.contentType == 'html'){ this.tooltip.css('max-width','none'); } this.tooltip.css('opacity', this.options.opacity); this.addAnimation(); if(this.options.confirm){ this.addConfirm(); } }, setPositions: function(){ var leftPos = this.bearer.offset().left; var topPos = this.bearer.offset().top; switch(this.options.gravity){ case 'south': leftPos += this.bearer.outerWidth()/2 - this.tooltip.outerWidth()/2; topPos += -this.tooltip.outerHeight() - this.tip.outerHeight()/2; break; case 'west': leftPos += this.bearer.outerWidth() + this.tip.outerWidth()/2; topPos += this.bearer.outerHeight()/2 - (this.tooltip.outerHeight()/2); break; case 'north': leftPos += this.bearer.outerWidth()/2 - (this.tooltip.outerWidth()/2); topPos += this.bearer.outerHeight() + this.tip.outerHeight()/2; break; case 'east': leftPos += -this.tooltip.outerWidth() - this.tip.outerWidth()/2; topPos += this.bearer.outerHeight()/2 - this.tooltip.outerHeight()/2; break; } if(this.options.autoLeft){ this.tooltip.css('left', leftPos); } if(this.options.autoTop){ this.tooltip.css('top', topPos); } }, setEvents: function(){ var dt = this; var delay = dt.options.hoverDelay; var setTimeoutConst; if(dt.mouseOverMode){ this.bearer.mouseenter( function(){ //Timeout for hover mouse delay setTimeoutConst = setTimeout( function(){ dt.setPositions(); dt.show(); }, delay); }).mouseleave( function(){ clearTimeout(setTimeoutConst ); dt.hide(); }); }else if(this.options.trigger == "click" || this.options.trigger == "onclik"){ this.tooltip.click( function(e){ e.stopPropagation(); }); this.bearer.click( function(e){ e.preventDefault(); dt.setPositions(); dt.toggle(); e.stopPropagation(); }); $('html').click(function(){ dt.hide(); }) } }, activate: function(){ this.setContent(); if(this.content){ this.setEvents(); } }, addConfirm: function(){ this.tooltip.append("<ul class = 'confirm'><li class = 'darktooltip-yes'>" + this.options.yes +"</li><li class = 'darktooltip-no'>"+ this.options.no +"</li></ul>"); this.setConfirmEvents(); }, setConfirmEvents: function(){ var dt = this; this.tooltip.find('li.darktooltip-yes').click( function(e){ dt.onYes(); e.stopPropagation(); }); this.tooltip.find('li.darktooltip-no').click( function(e){ dt.onNo(); e.stopPropagation(); }); }, finalMessage: function(){ if(this.options.finalMessage){ var dt = this; dt.tooltip.find('div:first').html(this.options.finalMessage); dt.tooltip.find('ul').remove(); dt.setPositions(); setTimeout( function(){ dt.hide(); dt.setContent(); }, dt.options.finalMessageDuration); }else{ this.hide(); } }, onYes: function(){ this.options.onYes(this.bearer); this.finalMessage(); }, onNo: function(){ this.options.onNo(this.bearer); this.hide(); } } $.fn.darkTooltip = function(options) { return this.each(function(){ options = $.extend({}, $.fn.darkTooltip.defaults, options); var tooltip = new DarkTooltip($(this), options); tooltip.activate(); }); } $.fn.darkTooltip.defaults = { animation: 'none', confirm: false, content:'', finalMessage: '', finalMessageDuration: 1000, gravity: 'south', hoverDelay: 0, modal: false, no: 'No', onNo: function(){}, onYes: function(){}, opacity: 0.9, size: 'medium', theme: 'dark', trigger: 'hover', yes: 'Yes', autoTop: true, autoLeft: true, onClose: function(){} }; })(jQuery);
apache-2.0
Guavus/hbase
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/compactions/StoreFileListGenerator.java
1237
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver.compactions; import java.util.List; import org.apache.hadoop.hbase.regionserver.StoreFile; public abstract class StoreFileListGenerator extends MockStoreFileGenerator implements Iterable<List<StoreFile>> { public static final int MAX_FILE_GEN_ITERS = 10; public static final int NUM_FILES_GEN = 1000; StoreFileListGenerator(final Class klass) { super(klass); } }
apache-2.0
mcgilman/nifi
nifi-nar-bundles/nifi-extension-utils/nifi-record-utils/nifi-standard-record-utils/src/main/java/org/apache/nifi/schema/validation/StandardSchemaValidationResult.java
1648
/* * 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.schema.validation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.nifi.serialization.record.validation.SchemaValidationResult; import org.apache.nifi.serialization.record.validation.ValidationError; public class StandardSchemaValidationResult implements SchemaValidationResult { private final List<ValidationError> validationErrors = new ArrayList<>(); @Override public boolean isValid() { return validationErrors.isEmpty(); } @Override public Collection<ValidationError> getValidationErrors() { return Collections.unmodifiableList(validationErrors); } public void addValidationError(final ValidationError validationError) { this.validationErrors.add(validationError); } }
apache-2.0
gfyoung/elasticsearch
server/src/test/java/org/elasticsearch/action/admin/indices/forcemerge/ForceMergeResponseTests.java
1679
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.forcemerge; import org.elasticsearch.action.support.DefaultShardOperationFailedException; import org.elasticsearch.action.support.broadcast.AbstractBroadcastResponseTestCase; import org.elasticsearch.common.xcontent.XContentParser; import java.util.List; public class ForceMergeResponseTests extends AbstractBroadcastResponseTestCase<ForceMergeResponse> { @Override protected ForceMergeResponse createTestInstance(int totalShards, int successfulShards, int failedShards, List<DefaultShardOperationFailedException> failures) { return new ForceMergeResponse(totalShards, successfulShards, failedShards, failures); } @Override protected ForceMergeResponse doParseInstance(XContentParser parser) { return ForceMergeResponse.fromXContent(parser); } }
apache-2.0
alexzaitzev/ignite
modules/core/src/main/java/org/apache/ignite/configuration/OdbcConfiguration.java
7131
/* * 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.configuration; import org.apache.ignite.internal.util.typedef.internal.S; /** * ODBC configuration. * <p> * Deprecated as of Apache Ignite 2.1. Please use {@link ClientConnectorConfiguration} and * {@link IgniteConfiguration#setClientConnectorConfiguration(ClientConnectorConfiguration)} instead. */ @Deprecated public class OdbcConfiguration { /** Default TCP host. */ public static final String DFLT_TCP_HOST = "0.0.0.0"; /** Default minimum TCP port range value. */ public static final int DFLT_TCP_PORT_FROM = 10800; /** Default maximum TCP port range value. */ public static final int DFLT_TCP_PORT_TO = 10810; /** Default socket send and receive buffer size. */ public static final int DFLT_SOCK_BUF_SIZE = 0; /** Default max number of open cursors per connection. */ public static final int DFLT_MAX_OPEN_CURSORS = 128; /** Default size of thread pool. */ public static final int DFLT_THREAD_POOL_SIZE = IgniteConfiguration.DFLT_PUBLIC_THREAD_CNT; /** Endpoint address. */ private String endpointAddr; /** Socket send buffer size. */ private int sockSndBufSize = DFLT_SOCK_BUF_SIZE; /** Socket receive buffer size. */ private int sockRcvBufSize = DFLT_SOCK_BUF_SIZE; /** Max number of opened cursors per connection. */ private int maxOpenCursors = DFLT_MAX_OPEN_CURSORS; /** Thread pool size. */ private int threadPoolSize = DFLT_THREAD_POOL_SIZE; /** * Creates ODBC server configuration with all default values. */ public OdbcConfiguration() { // No-op. } /** * Creates ODBC server configuration by copying all properties from given configuration. * * @param cfg ODBC server configuration. */ public OdbcConfiguration(OdbcConfiguration cfg) { assert cfg != null; endpointAddr = cfg.getEndpointAddress(); maxOpenCursors = cfg.getMaxOpenCursors(); sockRcvBufSize = cfg.getSocketReceiveBufferSize(); sockSndBufSize = cfg.getSocketSendBufferSize(); threadPoolSize = cfg.getThreadPoolSize(); } /** * Get ODBC endpoint address. Ignite will listen for incoming TCP connections on this address. Either single port * or port range could be used. In the latter case Ignite will start listening on the first available port * form the range. * <p> * The following address formats are permitted: * <ul> * <li>{@code hostname} - will use provided hostname and default port range;</li> * <li>{@code hostname:port} - will use provided hostname and port;</li> * <li>{@code hostname:port_from..port_to} - will use provided hostname and port range.</li> * </ul> * <p> * When set to {@code null}, ODBC processor will be bound to {@link #DFLT_TCP_HOST} host and default port range. * <p> * Default port range is from {@link #DFLT_TCP_PORT_FROM} to {@link #DFLT_TCP_PORT_TO}. * * @return ODBC endpoint address. */ public String getEndpointAddress() { return endpointAddr; } /** * Set ODBC endpoint address. See {@link #getEndpointAddress()} for more information. * * @param addr ODBC endpoint address. * @return This instance for chaining. */ public OdbcConfiguration setEndpointAddress(String addr) { this.endpointAddr = addr; return this; } /** * Gets maximum number of opened cursors per connection. * <p> * Defaults to {@link #DFLT_MAX_OPEN_CURSORS}. * * @return Maximum number of opened cursors. */ public int getMaxOpenCursors() { return maxOpenCursors; } /** * Sets maximum number of opened cursors per connection. See {@link #getMaxOpenCursors()}. * * @param maxOpenCursors Maximum number of opened cursors. * @return This instance for chaining. */ public OdbcConfiguration setMaxOpenCursors(int maxOpenCursors) { this.maxOpenCursors = maxOpenCursors; return this; } /** * Gets socket send buffer size. When set to zero, operation system default will be used. * <p> * Defaults to {@link #DFLT_SOCK_BUF_SIZE} * * @return Socket send buffer size in bytes. */ public int getSocketSendBufferSize() { return sockSndBufSize; } /** * Sets socket send buffer size. See {@link #getSocketSendBufferSize()} for more information. * * @param sockSndBufSize Socket send buffer size in bytes. * @return This instance for chaining. */ public OdbcConfiguration setSocketSendBufferSize(int sockSndBufSize) { this.sockSndBufSize = sockSndBufSize; return this; } /** * Gets socket receive buffer size. When set to zero, operation system default will be used. * <p> * Defaults to {@link #DFLT_SOCK_BUF_SIZE}. * * @return Socket receive buffer size in bytes. */ public int getSocketReceiveBufferSize() { return sockRcvBufSize; } /** * Sets socket receive buffer size. See {@link #getSocketReceiveBufferSize()} for more information. * * @param sockRcvBufSize Socket receive buffer size in bytes. * @return This instance for chaining. */ public OdbcConfiguration setSocketReceiveBufferSize(int sockRcvBufSize) { this.sockRcvBufSize = sockRcvBufSize; return this; } /** * Size of thread pool that is in charge of processing ODBC tasks. * <p> * Defaults {@link #DFLT_THREAD_POOL_SIZE}. * * @return Thread pool that is in charge of processing ODBC tasks. */ public int getThreadPoolSize() { return threadPoolSize; } /** * Sets thread pool that is in charge of processing ODBC tasks. See {@link #getThreadPoolSize()} for more * information. * * @param threadPoolSize Thread pool that is in charge of processing ODBC tasks. * @return This instance for chaining. */ public OdbcConfiguration setThreadPoolSize(int threadPoolSize) { this.threadPoolSize = threadPoolSize; return this; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(OdbcConfiguration.class, this); } }
apache-2.0
afk11/bitcoin
test/functional/feature_minchainwork.py
4122
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test logic for setting nMinimumChainWork on command line. Nodes don't consider themselves out of "initial block download" until their active chain has more work than nMinimumChainWork. Nodes don't download blocks from a peer unless the peer's best known block has more work than nMinimumChainWork. While in initial block download, nodes won't relay blocks to their peers, so test that this parameter functions as intended by verifying that block relay only succeeds past a given node once its nMinimumChainWork has been exceeded. """ import time from test_framework.test_framework import BitcoinTestFramework from test_framework.util import connect_nodes, assert_equal # 2 hashes required per regtest block (with no difficulty adjustment) REGTEST_WORK_PER_BLOCK = 2 class MinimumChainWorkTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [[], ["-minimumchainwork=0x65"], ["-minimumchainwork=0x65"]] self.node_min_work = [0, 101, 101] def setup_network(self): # This test relies on the chain setup being: # node0 <- node1 <- node2 # Before leaving IBD, nodes prefer to download blocks from outbound # peers, so ensure that we're mining on an outbound peer and testing # block relay to inbound peers. self.setup_nodes() for i in range(self.num_nodes-1): connect_nodes(self.nodes[i+1], i) def run_test(self): # Start building a chain on node0. node2 shouldn't be able to sync until node1's # minchainwork is exceeded starting_chain_work = REGTEST_WORK_PER_BLOCK # Genesis block's work self.log.info("Testing relay across node %d (minChainWork = %d)", 1, self.node_min_work[1]) starting_blockcount = self.nodes[2].getblockcount() num_blocks_to_generate = int((self.node_min_work[1] - starting_chain_work) / REGTEST_WORK_PER_BLOCK) self.log.info("Generating %d blocks on node0", num_blocks_to_generate) hashes = self.nodes[0].generatetoaddress(num_blocks_to_generate, self.nodes[0].get_deterministic_priv_key().address) self.log.info("Node0 current chain work: %s", self.nodes[0].getblockheader(hashes[-1])['chainwork']) # Sleep a few seconds and verify that node2 didn't get any new blocks # or headers. We sleep, rather than sync_blocks(node0, node1) because # it's reasonable either way for node1 to get the blocks, or not get # them (since they're below node1's minchainwork). time.sleep(3) self.log.info("Verifying node 2 has no more blocks than before") self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) # Node2 shouldn't have any new headers yet, because node1 should not # have relayed anything. assert_equal(len(self.nodes[2].getchaintips()), 1) assert_equal(self.nodes[2].getchaintips()[0]['height'], 0) assert self.nodes[1].getbestblockhash() != self.nodes[0].getbestblockhash() assert_equal(self.nodes[2].getblockcount(), starting_blockcount) self.log.info("Generating one more block") self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address) self.log.info("Verifying nodes are all synced") # Because nodes in regtest are all manual connections (eg using # addnode), node1 should not have disconnected node0. If not for that, # we'd expect node1 to have disconnected node0 for serving an # insufficient work chain, in which case we'd need to reconnect them to # continue the test. self.sync_all() self.log.info("Blockcounts: %s", [n.getblockcount() for n in self.nodes]) if __name__ == '__main__': MinimumChainWorkTest().main()
mit
markogresak/DefinitelyTyped
types/hawk/lib/utils.d.ts
1362
import * as Boom from '@hapi/boom'; import * as http from 'http'; import * as https from 'https'; export interface Host { name: string; port: number; } export interface CustomRequest { authorization: string; contentType: string; host: string; method: string; port: number; url: string; } export interface ParseRequestOptions { host?: string | undefined; hostHeaderName?: string | undefined; name?: string | undefined; port?: number | undefined; } export const version: string; export const limits: { /** Limit the length of uris and headers to avoid a DoS attack on string matching */ maxMatchLength: number; }; export function now(localtimeOffsetMsec: number): number; export function nowSecs(localtimeOffsetMsec: number): number; export function parseAuthorizationHeader(header: string, keys?: string[]): Record<string, string>; export function parseContentType(header?: string): string; export function parseHost(req: http.RequestOptions | https.RequestOptions, hostHeaderName?: string): Host | null; export function parseRequest( req: http.RequestOptions | https.RequestOptions, options?: ParseRequestOptions, ): CustomRequest; export function unauthorized( message?: string, attributes?: string | Boom.unauthorized.Attributes, ): Boom.Boom & Boom.unauthorized.MissingAuth;
mit
rokn/Count_Words_2015
testing/openjdk/jdk/test/sun/nio/cs/X11CNS11643P2.java
1335
/* * Copyright (c) 1996, 2005, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ public class X11CNS11643P2 extends X11CNS11643 { public X11CNS11643P2() { super(2, "X11CNS11643P2"); } }
mit
miguelangel6/nightwatchbamboo
tests/extra/pageobjects/SimplePageFn.js
142
module.exports = function(client, test) { test.ok(typeof client == 'object'); this.testPageAction = function() { return this; }; };
mit
eva-oss/linux
lib/test_bitmap.c
10167
/* * Test cases for printf facility. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/bitmap.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/printk.h> #include <linux/slab.h> #include <linux/string.h> static unsigned total_tests __initdata; static unsigned failed_tests __initdata; static char pbl_buffer[PAGE_SIZE] __initdata; static bool __init __check_eq_uint(const char *srcfile, unsigned int line, const unsigned int exp_uint, unsigned int x) { if (exp_uint != x) { pr_warn("[%s:%u] expected %u, got %u\n", srcfile, line, exp_uint, x); return false; } return true; } static bool __init __check_eq_bitmap(const char *srcfile, unsigned int line, const unsigned long *exp_bmap, unsigned int exp_nbits, const unsigned long *bmap, unsigned int nbits) { if (exp_nbits != nbits) { pr_warn("[%s:%u] bitmap length mismatch: expected %u, got %u\n", srcfile, line, exp_nbits, nbits); return false; } if (!bitmap_equal(exp_bmap, bmap, nbits)) { pr_warn("[%s:%u] bitmaps contents differ: expected \"%*pbl\", got \"%*pbl\"\n", srcfile, line, exp_nbits, exp_bmap, nbits, bmap); return false; } return true; } static bool __init __check_eq_pbl(const char *srcfile, unsigned int line, const char *expected_pbl, const unsigned long *bitmap, unsigned int nbits) { snprintf(pbl_buffer, sizeof(pbl_buffer), "%*pbl", nbits, bitmap); if (strcmp(expected_pbl, pbl_buffer)) { pr_warn("[%s:%u] expected \"%s\", got \"%s\"\n", srcfile, line, expected_pbl, pbl_buffer); return false; } return true; } static bool __init __check_eq_u32_array(const char *srcfile, unsigned int line, const u32 *exp_arr, unsigned int exp_len, const u32 *arr, unsigned int len) { if (exp_len != len) { pr_warn("[%s:%u] array length differ: expected %u, got %u\n", srcfile, line, exp_len, len); return false; } if (memcmp(exp_arr, arr, len*sizeof(*arr))) { pr_warn("[%s:%u] array contents differ\n", srcfile, line); print_hex_dump(KERN_WARNING, " exp: ", DUMP_PREFIX_OFFSET, 32, 4, exp_arr, exp_len*sizeof(*exp_arr), false); print_hex_dump(KERN_WARNING, " got: ", DUMP_PREFIX_OFFSET, 32, 4, arr, len*sizeof(*arr), false); return false; } return true; } #define __expect_eq(suffix, ...) \ ({ \ int result = 0; \ total_tests++; \ if (!__check_eq_ ## suffix(__FILE__, __LINE__, \ ##__VA_ARGS__)) { \ failed_tests++; \ result = 1; \ } \ result; \ }) #define expect_eq_uint(...) __expect_eq(uint, ##__VA_ARGS__) #define expect_eq_bitmap(...) __expect_eq(bitmap, ##__VA_ARGS__) #define expect_eq_pbl(...) __expect_eq(pbl, ##__VA_ARGS__) #define expect_eq_u32_array(...) __expect_eq(u32_array, ##__VA_ARGS__) static void __init test_zero_fill_copy(void) { DECLARE_BITMAP(bmap1, 1024); DECLARE_BITMAP(bmap2, 1024); bitmap_zero(bmap1, 1024); bitmap_zero(bmap2, 1024); /* single-word bitmaps */ expect_eq_pbl("", bmap1, 23); bitmap_fill(bmap1, 19); expect_eq_pbl("0-18", bmap1, 1024); bitmap_copy(bmap2, bmap1, 23); expect_eq_pbl("0-18", bmap2, 1024); bitmap_fill(bmap2, 23); expect_eq_pbl("0-22", bmap2, 1024); bitmap_copy(bmap2, bmap1, 23); expect_eq_pbl("0-18", bmap2, 1024); bitmap_zero(bmap1, 23); expect_eq_pbl("", bmap1, 1024); /* multi-word bitmaps */ bitmap_zero(bmap1, 1024); expect_eq_pbl("", bmap1, 1024); bitmap_fill(bmap1, 109); expect_eq_pbl("0-108", bmap1, 1024); bitmap_copy(bmap2, bmap1, 1024); expect_eq_pbl("0-108", bmap2, 1024); bitmap_fill(bmap2, 1024); expect_eq_pbl("0-1023", bmap2, 1024); bitmap_copy(bmap2, bmap1, 1024); expect_eq_pbl("0-108", bmap2, 1024); /* the following tests assume a 32- or 64-bit arch (even 128b * if we care) */ bitmap_fill(bmap2, 1024); bitmap_copy(bmap2, bmap1, 109); /* ... but 0-padded til word length */ expect_eq_pbl("0-108,128-1023", bmap2, 1024); bitmap_fill(bmap2, 1024); bitmap_copy(bmap2, bmap1, 97); /* ... but aligned on word length */ expect_eq_pbl("0-108,128-1023", bmap2, 1024); bitmap_zero(bmap2, 97); /* ... but 0-padded til word length */ expect_eq_pbl("128-1023", bmap2, 1024); } static void __init test_bitmap_u32_array_conversions(void) { DECLARE_BITMAP(bmap1, 1024); DECLARE_BITMAP(bmap2, 1024); u32 exp_arr[32], arr[32]; unsigned nbits; for (nbits = 0 ; nbits < 257 ; ++nbits) { const unsigned int used_u32s = DIV_ROUND_UP(nbits, 32); unsigned int i, rv; bitmap_zero(bmap1, nbits); bitmap_set(bmap1, nbits, 1024 - nbits); /* garbage */ memset(arr, 0xff, sizeof(arr)); rv = bitmap_to_u32array(arr, used_u32s, bmap1, nbits); expect_eq_uint(nbits, rv); memset(exp_arr, 0xff, sizeof(exp_arr)); memset(exp_arr, 0, used_u32s*sizeof(*exp_arr)); expect_eq_u32_array(exp_arr, 32, arr, 32); bitmap_fill(bmap2, 1024); rv = bitmap_from_u32array(bmap2, nbits, arr, used_u32s); expect_eq_uint(nbits, rv); expect_eq_bitmap(bmap1, 1024, bmap2, 1024); for (i = 0 ; i < nbits ; ++i) { /* * test conversion bitmap -> u32[] */ bitmap_zero(bmap1, 1024); __set_bit(i, bmap1); bitmap_set(bmap1, nbits, 1024 - nbits); /* garbage */ memset(arr, 0xff, sizeof(arr)); rv = bitmap_to_u32array(arr, used_u32s, bmap1, nbits); expect_eq_uint(nbits, rv); /* 1st used u32 words contain expected bit set, the * remaining words are left unchanged (0xff) */ memset(exp_arr, 0xff, sizeof(exp_arr)); memset(exp_arr, 0, used_u32s*sizeof(*exp_arr)); exp_arr[i/32] = (1U<<(i%32)); expect_eq_u32_array(exp_arr, 32, arr, 32); /* same, with longer array to fill */ memset(arr, 0xff, sizeof(arr)); rv = bitmap_to_u32array(arr, 32, bmap1, nbits); expect_eq_uint(nbits, rv); /* 1st used u32 words contain expected bit set, the * remaining words are all 0s */ memset(exp_arr, 0, sizeof(exp_arr)); exp_arr[i/32] = (1U<<(i%32)); expect_eq_u32_array(exp_arr, 32, arr, 32); /* * test conversion u32[] -> bitmap */ /* the 1st nbits of bmap2 are identical to * bmap1, the remaining bits of bmap2 are left * unchanged (all 1s) */ bitmap_fill(bmap2, 1024); rv = bitmap_from_u32array(bmap2, nbits, exp_arr, used_u32s); expect_eq_uint(nbits, rv); expect_eq_bitmap(bmap1, 1024, bmap2, 1024); /* same, with more bits to fill */ memset(arr, 0xff, sizeof(arr)); /* garbage */ memset(arr, 0, used_u32s*sizeof(u32)); arr[i/32] = (1U<<(i%32)); bitmap_fill(bmap2, 1024); rv = bitmap_from_u32array(bmap2, 1024, arr, used_u32s); expect_eq_uint(used_u32s*32, rv); /* the 1st nbits of bmap2 are identical to * bmap1, the remaining bits of bmap2 are cleared */ bitmap_zero(bmap1, 1024); __set_bit(i, bmap1); expect_eq_bitmap(bmap1, 1024, bmap2, 1024); /* * test short conversion bitmap -> u32[] (1 * word too short) */ if (used_u32s > 1) { bitmap_zero(bmap1, 1024); __set_bit(i, bmap1); bitmap_set(bmap1, nbits, 1024 - nbits); /* garbage */ memset(arr, 0xff, sizeof(arr)); rv = bitmap_to_u32array(arr, used_u32s - 1, bmap1, nbits); expect_eq_uint((used_u32s - 1)*32, rv); /* 1st used u32 words contain expected * bit set, the remaining words are * left unchanged (0xff) */ memset(exp_arr, 0xff, sizeof(exp_arr)); memset(exp_arr, 0, (used_u32s-1)*sizeof(*exp_arr)); if ((i/32) < (used_u32s - 1)) exp_arr[i/32] = (1U<<(i%32)); expect_eq_u32_array(exp_arr, 32, arr, 32); } /* * test short conversion u32[] -> bitmap (3 * bits too short) */ if (nbits > 3) { memset(arr, 0xff, sizeof(arr)); /* garbage */ memset(arr, 0, used_u32s*sizeof(*arr)); arr[i/32] = (1U<<(i%32)); bitmap_zero(bmap1, 1024); rv = bitmap_from_u32array(bmap1, nbits - 3, arr, used_u32s); expect_eq_uint(nbits - 3, rv); /* we are expecting the bit < nbits - * 3 (none otherwise), and the rest of * bmap1 unchanged (0-filled) */ bitmap_zero(bmap2, 1024); if (i < nbits - 3) __set_bit(i, bmap2); expect_eq_bitmap(bmap2, 1024, bmap1, 1024); /* do the same with bmap1 initially * 1-filled */ bitmap_fill(bmap1, 1024); rv = bitmap_from_u32array(bmap1, nbits - 3, arr, used_u32s); expect_eq_uint(nbits - 3, rv); /* we are expecting the bit < nbits - * 3 (none otherwise), and the rest of * bmap1 unchanged (1-filled) */ bitmap_zero(bmap2, 1024); if (i < nbits - 3) __set_bit(i, bmap2); bitmap_set(bmap2, nbits-3, 1024 - nbits + 3); expect_eq_bitmap(bmap2, 1024, bmap1, 1024); } } } } static void noinline __init test_mem_optimisations(void) { DECLARE_BITMAP(bmap1, 1024); DECLARE_BITMAP(bmap2, 1024); unsigned int start, nbits; for (start = 0; start < 1024; start += 8) { memset(bmap1, 0x5a, sizeof(bmap1)); memset(bmap2, 0x5a, sizeof(bmap2)); for (nbits = 0; nbits < 1024 - start; nbits += 8) { bitmap_set(bmap1, start, nbits); __bitmap_set(bmap2, start, nbits); if (!bitmap_equal(bmap1, bmap2, 1024)) printk("set not equal %d %d\n", start, nbits); if (!__bitmap_equal(bmap1, bmap2, 1024)) printk("set not __equal %d %d\n", start, nbits); bitmap_clear(bmap1, start, nbits); __bitmap_clear(bmap2, start, nbits); if (!bitmap_equal(bmap1, bmap2, 1024)) printk("clear not equal %d %d\n", start, nbits); if (!__bitmap_equal(bmap1, bmap2, 1024)) printk("clear not __equal %d %d\n", start, nbits); } } } static int __init test_bitmap_init(void) { test_zero_fill_copy(); test_bitmap_u32_array_conversions(); test_mem_optimisations(); if (failed_tests == 0) pr_info("all %u tests passed\n", total_tests); else pr_warn("failed %u out of %u tests\n", failed_tests, total_tests); return failed_tests ? -EINVAL : 0; } static void __exit test_bitmap_cleanup(void) { } module_init(test_bitmap_init); module_exit(test_bitmap_cleanup); MODULE_AUTHOR("david decotigny <[email protected]>"); MODULE_LICENSE("GPL");
gpl-2.0
maxfu/android_kernel_samsung_exynos5410
include/linux/msm_rmnet.h
2050
/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _MSM_RMNET_H_ #define _MSM_RMNET_H_ /* Bitmap macros for RmNET driver operation mode. */ #define RMNET_MODE_NONE (0x00) #define RMNET_MODE_LLP_ETH (0x01) #define RMNET_MODE_LLP_IP (0x02) #define RMNET_MODE_QOS (0x04) #define RMNET_MODE_MASK (RMNET_MODE_LLP_ETH | \ RMNET_MODE_LLP_IP | \ RMNET_MODE_QOS) #define RMNET_IS_MODE_QOS(mode) \ ((mode & RMNET_MODE_QOS) == RMNET_MODE_QOS) #define RMNET_IS_MODE_IP(mode) \ ((mode & RMNET_MODE_LLP_IP) == RMNET_MODE_LLP_IP) /* IOCTL command enum * Values chosen to not conflict with other drivers in the ecosystem */ enum rmnet_ioctl_cmds_e { RMNET_IOCTL_SET_LLP_ETHERNET = 0x000089F1, /* Set Ethernet protocol */ RMNET_IOCTL_SET_LLP_IP = 0x000089F2, /* Set RAWIP protocol */ RMNET_IOCTL_GET_LLP = 0x000089F3, /* Get link protocol */ RMNET_IOCTL_SET_QOS_ENABLE = 0x000089F4, /* Set QoS header enabled */ RMNET_IOCTL_SET_QOS_DISABLE = 0x000089F5, /* Set QoS header disabled*/ RMNET_IOCTL_GET_QOS = 0x000089F6, /* Get QoS header state */ RMNET_IOCTL_GET_OPMODE = 0x000089F7, /* Get operation mode */ RMNET_IOCTL_OPEN = 0x000089F8, /* Open transport port */ RMNET_IOCTL_CLOSE = 0x000089F9, /* Close transport port */ RMNET_IOCTL_MAX }; /* QMI QoS header definition */ #define QMI_QOS_HDR_S qmi_qos_hdr_s struct QMI_QOS_HDR_S { unsigned char version; unsigned char flags; unsigned long flow_id; } __packed; #endif /* _MSM_RMNET_H_ */
gpl-2.0
iAlios/openwrt-fl2440
target/linux/xburst/files/sound/soc/codecs/jzcodec.h
631
/* * Copyright (C) 2009, Lars-Peter Clausen <[email protected]> * * 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. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 675 Mass Ave, Cambridge, MA 02139, USA. * */ #ifndef _ICODEC_H #define _ICODEC_H #define JZCODEC_SYSCLK 0 extern struct snd_soc_dai jz_codec_dai; extern struct snd_soc_codec_device soc_codec_dev_jzcodec; #endif
gpl-2.0
rawlingsj/gofabric8
vendor/github.com/openshift/origin/pkg/cmd/infra/builder/builder.go
1590
package builder import ( "os" "github.com/spf13/cobra" kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/openshift/origin/pkg/build/builder/cmd" ocmd "github.com/openshift/origin/pkg/cmd/cli/cmd" "github.com/openshift/origin/pkg/cmd/templates" ) var ( s2iBuilderLong = templates.LongDesc(` Perform a Source-to-Image build This command executes a Source-to-Image build using arguments passed via the environment. It expects to be run inside of a container.`) dockerBuilderLong = templates.LongDesc(` Perform a Docker build This command executes a Docker build using arguments passed via the environment. It expects to be run inside of a container.`) ) // NewCommandS2IBuilder provides a CLI handler for S2I build type func NewCommandS2IBuilder(name string) *cobra.Command { cmd := &cobra.Command{ Use: name, Short: "Run a Source-to-Image build", Long: s2iBuilderLong, Run: func(c *cobra.Command, args []string) { err := cmd.RunS2IBuild(c.OutOrStderr()) kcmdutil.CheckErr(err) }, } cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{})) return cmd } // NewCommandDockerBuilder provides a CLI handler for Docker build type func NewCommandDockerBuilder(name string) *cobra.Command { cmd := &cobra.Command{ Use: name, Short: "Run a Docker build", Long: dockerBuilderLong, Run: func(c *cobra.Command, args []string) { err := cmd.RunDockerBuild(c.OutOrStderr()) kcmdutil.CheckErr(err) }, } cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{})) return cmd }
apache-2.0
young-zhang/Lean
Common/Util/ReaderWriterLockSlimExtensions.cs
3963
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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; using System.Threading; namespace QuantConnect.Util { /// <summary> /// Provides extension methods to make working with the <see cref="ReaderWriterLockSlim"/> class easier /// </summary> public static class ReaderWriterLockSlimExtensions { /// <summary> /// Opens the read lock /// </summary> /// <param name="readerWriterLockSlim">The lock to open for read</param> /// <returns>A disposable reference which will release the lock upon disposal</returns> public static IDisposable Read(this ReaderWriterLockSlim readerWriterLockSlim) { return new ReaderLockToken(readerWriterLockSlim); } /// <summary> /// Opens the write lock /// </summary> /// <param name="readerWriterLockSlim">The lock to open for write</param> /// <returns>A disposale reference which will release thelock upon disposal</returns> public static IDisposable Write(this ReaderWriterLockSlim readerWriterLockSlim) { return new WriteLockToken(readerWriterLockSlim); } private sealed class ReaderLockToken : ReaderWriterLockSlimToken { public ReaderLockToken(ReaderWriterLockSlim readerWriterLockSlim) : base(readerWriterLockSlim) { } protected override void EnterLock(ReaderWriterLockSlim readerWriterLockSlim) { readerWriterLockSlim.EnterReadLock(); } protected override void ExitLock(ReaderWriterLockSlim readerWriterLockSlim) { readerWriterLockSlim.ExitReadLock(); } } private sealed class WriteLockToken : ReaderWriterLockSlimToken { public WriteLockToken(ReaderWriterLockSlim readerWriterLockSlim) : base(readerWriterLockSlim) { } protected override void EnterLock(ReaderWriterLockSlim readerWriterLockSlim) { readerWriterLockSlim.EnterWriteLock(); } protected override void ExitLock(ReaderWriterLockSlim readerWriterLockSlim) { readerWriterLockSlim.ExitWriteLock(); } } private abstract class ReaderWriterLockSlimToken : IDisposable { private ReaderWriterLockSlim _readerWriterLockSlim; public ReaderWriterLockSlimToken(ReaderWriterLockSlim readerWriterLockSlim) { _readerWriterLockSlim = readerWriterLockSlim; // ReSharper disable once DoNotCallOverridableMethodsInConstructor -- we control the subclasses, this is fine EnterLock(_readerWriterLockSlim); } protected abstract void EnterLock(ReaderWriterLockSlim readerWriterLockSlim); protected abstract void ExitLock(ReaderWriterLockSlim readerWriterLockSlim); public void Dispose() { if (_readerWriterLockSlim != null) { ExitLock(_readerWriterLockSlim); _readerWriterLockSlim = null; } } } } }
apache-2.0
ractive/spring-security
test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithUserDetailsClassLevelAuthenticationTests.java
4216
/* * Copyright 2002-2014 the original author or 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 org.springframework.security.test.web.servlet.showcase.secured; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = WithUserDetailsClassLevelAuthenticationTests.Config.class) @WebAppConfiguration @WithUserDetails("admin") public class WithUserDetailsClassLevelAuthenticationTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setup() { mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test public void requestRootUrlWithAdmin() throws Exception { mvc.perform(get("/")) // Ensure we got past Security .andExpect(status().isNotFound()) // Ensure it appears we are authenticated with user .andExpect( authenticated().withUsername("admin").withRoles("ADMIN", "USER")); } @Test public void requestProtectedUrlWithAdmin() throws Exception { mvc.perform(get("/admin")) // Ensure we got past Security .andExpect(status().isNotFound()) // Ensure it appears we are authenticated with user .andExpect( authenticated().withUsername("admin").withRoles("ADMIN", "USER")); } @EnableWebSecurity @EnableWebMvc static class Config extends WebSecurityConfigurerAdapter { // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin(); } // @formatter:on @Bean @Override public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); } // @formatter:off @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER","ADMIN"); } // @formatter:on } }
apache-2.0
weiyuliang/rt-thread
bsp/imx6sx/iMX6_Platform_SDK/sdk/include/mx6dq/registers/regspgc.h
28478
/* * Copyright (c) 2012, Freescale Semiconductor, Inc. * All rights reserved. * * THIS SOFTWARE IS PROVIDED BY FREESCALE "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 FREESCALE 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. */ /* * WARNING! DO NOT EDIT THIS FILE DIRECTLY! * * This file was generated automatically and any changes may be lost. */ #ifndef __HW_PGC_REGISTERS_H__ #define __HW_PGC_REGISTERS_H__ #include "regs.h" /* * i.MX6DQ PGC * * PGC * * Registers defined in this header file: * - HW_PGC_GPU_CTRL - PGC Control Register * - HW_PGC_GPU_PUPSCR - Power Up Sequence Control Register * - HW_PGC_GPU_PDNSCR - Pull Down Sequence Control Register * - HW_PGC_GPU_SR - Power Gating Controller Status Register * - HW_PGC_CPU_CTRL - PGC Control Register * - HW_PGC_CPU_PUPSCR - Power Up Sequence Control Register * - HW_PGC_CPU_PDNSCR - Pull Down Sequence Control Register * - HW_PGC_CPU_SR - Power Gating Controller Status Register * * - hw_pgc_t - Struct containing all module registers. */ //! @name Module base addresses //@{ #ifndef REGS_PGC_BASE #define HW_PGC_INSTANCE_COUNT (1) //!< Number of instances of the PGC module. #define REGS_PGC_BASE (0x020dc000) //!< Base address for PGC. #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_GPU_CTRL - PGC Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_GPU_CTRL - PGC Control Register (RW) * * Reset value: 0x00000000 * * The PGCR enables the response to a power-down request. */ typedef union _hw_pgc_gpu_ctrl { reg32_t U; struct _hw_pgc_gpu_ctrl_bitfields { unsigned PCR : 1; //!< [0] Power Control unsigned RESERVED0 : 31; //!< [31:1] Reserved. } B; } hw_pgc_gpu_ctrl_t; #endif /*! * @name Constants and macros for entire PGC_GPU_CTRL register */ //@{ #define HW_PGC_GPU_CTRL_ADDR (REGS_PGC_BASE + 0x260) #ifndef __LANGUAGE_ASM__ #define HW_PGC_GPU_CTRL (*(volatile hw_pgc_gpu_ctrl_t *) HW_PGC_GPU_CTRL_ADDR) #define HW_PGC_GPU_CTRL_RD() (HW_PGC_GPU_CTRL.U) #define HW_PGC_GPU_CTRL_WR(v) (HW_PGC_GPU_CTRL.U = (v)) #define HW_PGC_GPU_CTRL_SET(v) (HW_PGC_GPU_CTRL_WR(HW_PGC_GPU_CTRL_RD() | (v))) #define HW_PGC_GPU_CTRL_CLR(v) (HW_PGC_GPU_CTRL_WR(HW_PGC_GPU_CTRL_RD() & ~(v))) #define HW_PGC_GPU_CTRL_TOG(v) (HW_PGC_GPU_CTRL_WR(HW_PGC_GPU_CTRL_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_GPU_CTRL bitfields */ /*! @name Register PGC_GPU_CTRL, field PCR[0] (RW) * * Power Control PCR must not change from power-down request (pdn_req) assertion until the target * subsystem is completely powered up. * * Values: * - 0 - Do not switch off power even if pdn_req is asserted. * - 1 - Switch off power when pdn_req is asserted. */ //@{ #define BP_PGC_GPU_CTRL_PCR (0) //!< Bit position for PGC_GPU_CTRL_PCR. #define BM_PGC_GPU_CTRL_PCR (0x00000001) //!< Bit mask for PGC_GPU_CTRL_PCR. //! @brief Get value of PGC_GPU_CTRL_PCR from a register value. #define BG_PGC_GPU_CTRL_PCR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_CTRL_PCR) >> BP_PGC_GPU_CTRL_PCR) //! @brief Format value for bitfield PGC_GPU_CTRL_PCR. #define BF_PGC_GPU_CTRL_PCR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_CTRL_PCR) & BM_PGC_GPU_CTRL_PCR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PCR field to a new value. #define BW_PGC_GPU_CTRL_PCR(v) (HW_PGC_GPU_CTRL_WR((HW_PGC_GPU_CTRL_RD() & ~BM_PGC_GPU_CTRL_PCR) | BF_PGC_GPU_CTRL_PCR(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_GPU_PUPSCR - Power Up Sequence Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_GPU_PUPSCR - Power Up Sequence Control Register (RW) * * Reset value: 0x00000f01 * * The PUPSCR contains the power-up timing parameters. See . */ typedef union _hw_pgc_gpu_pupscr { reg32_t U; struct _hw_pgc_gpu_pupscr_bitfields { unsigned SW : 6; //!< [5:0] After a power-up request (pup_req assertion), the PGC waits a number of clocks equal to the value of SW before asserting switch_b. unsigned RESERVED0 : 2; //!< [7:6] Reserved. unsigned SW2ISO : 6; //!< [13:8] After asserting switch_b, the PGC waits a number of clocks equal to the value of SW2ISO before negating isolation. unsigned RESERVED1 : 18; //!< [31:14] Reserved. } B; } hw_pgc_gpu_pupscr_t; #endif /*! * @name Constants and macros for entire PGC_GPU_PUPSCR register */ //@{ #define HW_PGC_GPU_PUPSCR_ADDR (REGS_PGC_BASE + 0x264) #ifndef __LANGUAGE_ASM__ #define HW_PGC_GPU_PUPSCR (*(volatile hw_pgc_gpu_pupscr_t *) HW_PGC_GPU_PUPSCR_ADDR) #define HW_PGC_GPU_PUPSCR_RD() (HW_PGC_GPU_PUPSCR.U) #define HW_PGC_GPU_PUPSCR_WR(v) (HW_PGC_GPU_PUPSCR.U = (v)) #define HW_PGC_GPU_PUPSCR_SET(v) (HW_PGC_GPU_PUPSCR_WR(HW_PGC_GPU_PUPSCR_RD() | (v))) #define HW_PGC_GPU_PUPSCR_CLR(v) (HW_PGC_GPU_PUPSCR_WR(HW_PGC_GPU_PUPSCR_RD() & ~(v))) #define HW_PGC_GPU_PUPSCR_TOG(v) (HW_PGC_GPU_PUPSCR_WR(HW_PGC_GPU_PUPSCR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_GPU_PUPSCR bitfields */ /*! @name Register PGC_GPU_PUPSCR, field SW[5:0] (RW) * * After a power-up request (pup_req assertion), the PGC waits a number of clocks equal to the value * of SW before asserting switch_b. SW must not be programmed to zero. The PGC clock is generated * from the IPG_CLK_ROOT. for frequency configuration of the IPG_CLK_ROOT. See . */ //@{ #define BP_PGC_GPU_PUPSCR_SW (0) //!< Bit position for PGC_GPU_PUPSCR_SW. #define BM_PGC_GPU_PUPSCR_SW (0x0000003f) //!< Bit mask for PGC_GPU_PUPSCR_SW. //! @brief Get value of PGC_GPU_PUPSCR_SW from a register value. #define BG_PGC_GPU_PUPSCR_SW(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_PUPSCR_SW) >> BP_PGC_GPU_PUPSCR_SW) //! @brief Format value for bitfield PGC_GPU_PUPSCR_SW. #define BF_PGC_GPU_PUPSCR_SW(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_PUPSCR_SW) & BM_PGC_GPU_PUPSCR_SW) #ifndef __LANGUAGE_ASM__ //! @brief Set the SW field to a new value. #define BW_PGC_GPU_PUPSCR_SW(v) (HW_PGC_GPU_PUPSCR_WR((HW_PGC_GPU_PUPSCR_RD() & ~BM_PGC_GPU_PUPSCR_SW) | BF_PGC_GPU_PUPSCR_SW(v))) #endif //@} /*! @name Register PGC_GPU_PUPSCR, field SW2ISO[13:8] (RW) * * After asserting switch_b, the PGC waits a number of clocks equal to the value of SW2ISO before * negating isolation. SW2ISO must not be programmed to zero. */ //@{ #define BP_PGC_GPU_PUPSCR_SW2ISO (8) //!< Bit position for PGC_GPU_PUPSCR_SW2ISO. #define BM_PGC_GPU_PUPSCR_SW2ISO (0x00003f00) //!< Bit mask for PGC_GPU_PUPSCR_SW2ISO. //! @brief Get value of PGC_GPU_PUPSCR_SW2ISO from a register value. #define BG_PGC_GPU_PUPSCR_SW2ISO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_PUPSCR_SW2ISO) >> BP_PGC_GPU_PUPSCR_SW2ISO) //! @brief Format value for bitfield PGC_GPU_PUPSCR_SW2ISO. #define BF_PGC_GPU_PUPSCR_SW2ISO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_PUPSCR_SW2ISO) & BM_PGC_GPU_PUPSCR_SW2ISO) #ifndef __LANGUAGE_ASM__ //! @brief Set the SW2ISO field to a new value. #define BW_PGC_GPU_PUPSCR_SW2ISO(v) (HW_PGC_GPU_PUPSCR_WR((HW_PGC_GPU_PUPSCR_RD() & ~BM_PGC_GPU_PUPSCR_SW2ISO) | BF_PGC_GPU_PUPSCR_SW2ISO(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_GPU_PDNSCR - Pull Down Sequence Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_GPU_PDNSCR - Pull Down Sequence Control Register (RW) * * Reset value: 0x00000101 * * The PDNSCR contains the power-down timing parameters. See . */ typedef union _hw_pgc_gpu_pdnscr { reg32_t U; struct _hw_pgc_gpu_pdnscr_bitfields { unsigned ISO : 6; //!< [5:0] After a power-down request (pdn_req assertion), the PGC waits a number of clocks equal to the value of ISO before asserting isolation. unsigned RESERVED0 : 2; //!< [7:6] Reserved. unsigned ISO2SW : 6; //!< [13:8] After asserting isolation, the PGC waits a number of clocks equal to the value of ISO2SW before negating switch_b. unsigned RESERVED1 : 18; //!< [31:14] Reserved. } B; } hw_pgc_gpu_pdnscr_t; #endif /*! * @name Constants and macros for entire PGC_GPU_PDNSCR register */ //@{ #define HW_PGC_GPU_PDNSCR_ADDR (REGS_PGC_BASE + 0x268) #ifndef __LANGUAGE_ASM__ #define HW_PGC_GPU_PDNSCR (*(volatile hw_pgc_gpu_pdnscr_t *) HW_PGC_GPU_PDNSCR_ADDR) #define HW_PGC_GPU_PDNSCR_RD() (HW_PGC_GPU_PDNSCR.U) #define HW_PGC_GPU_PDNSCR_WR(v) (HW_PGC_GPU_PDNSCR.U = (v)) #define HW_PGC_GPU_PDNSCR_SET(v) (HW_PGC_GPU_PDNSCR_WR(HW_PGC_GPU_PDNSCR_RD() | (v))) #define HW_PGC_GPU_PDNSCR_CLR(v) (HW_PGC_GPU_PDNSCR_WR(HW_PGC_GPU_PDNSCR_RD() & ~(v))) #define HW_PGC_GPU_PDNSCR_TOG(v) (HW_PGC_GPU_PDNSCR_WR(HW_PGC_GPU_PDNSCR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_GPU_PDNSCR bitfields */ /*! @name Register PGC_GPU_PDNSCR, field ISO[5:0] (RW) * * After a power-down request (pdn_req assertion), the PGC waits a number of clocks equal to the * value of ISO before asserting isolation. ISO must not be programmed to zero. */ //@{ #define BP_PGC_GPU_PDNSCR_ISO (0) //!< Bit position for PGC_GPU_PDNSCR_ISO. #define BM_PGC_GPU_PDNSCR_ISO (0x0000003f) //!< Bit mask for PGC_GPU_PDNSCR_ISO. //! @brief Get value of PGC_GPU_PDNSCR_ISO from a register value. #define BG_PGC_GPU_PDNSCR_ISO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_PDNSCR_ISO) >> BP_PGC_GPU_PDNSCR_ISO) //! @brief Format value for bitfield PGC_GPU_PDNSCR_ISO. #define BF_PGC_GPU_PDNSCR_ISO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_PDNSCR_ISO) & BM_PGC_GPU_PDNSCR_ISO) #ifndef __LANGUAGE_ASM__ //! @brief Set the ISO field to a new value. #define BW_PGC_GPU_PDNSCR_ISO(v) (HW_PGC_GPU_PDNSCR_WR((HW_PGC_GPU_PDNSCR_RD() & ~BM_PGC_GPU_PDNSCR_ISO) | BF_PGC_GPU_PDNSCR_ISO(v))) #endif //@} /*! @name Register PGC_GPU_PDNSCR, field ISO2SW[13:8] (RW) * * After asserting isolation, the PGC waits a number of clocks equal to the value of ISO2SW before * negating switch_b. ISO2SW must not be programmed to zero. */ //@{ #define BP_PGC_GPU_PDNSCR_ISO2SW (8) //!< Bit position for PGC_GPU_PDNSCR_ISO2SW. #define BM_PGC_GPU_PDNSCR_ISO2SW (0x00003f00) //!< Bit mask for PGC_GPU_PDNSCR_ISO2SW. //! @brief Get value of PGC_GPU_PDNSCR_ISO2SW from a register value. #define BG_PGC_GPU_PDNSCR_ISO2SW(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_PDNSCR_ISO2SW) >> BP_PGC_GPU_PDNSCR_ISO2SW) //! @brief Format value for bitfield PGC_GPU_PDNSCR_ISO2SW. #define BF_PGC_GPU_PDNSCR_ISO2SW(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_PDNSCR_ISO2SW) & BM_PGC_GPU_PDNSCR_ISO2SW) #ifndef __LANGUAGE_ASM__ //! @brief Set the ISO2SW field to a new value. #define BW_PGC_GPU_PDNSCR_ISO2SW(v) (HW_PGC_GPU_PDNSCR_WR((HW_PGC_GPU_PDNSCR_RD() & ~BM_PGC_GPU_PDNSCR_ISO2SW) | BF_PGC_GPU_PDNSCR_ISO2SW(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_GPU_SR - Power Gating Controller Status Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_GPU_SR - Power Gating Controller Status Register (RW) * * Reset value: 0x00000000 * * The PDNSCR contains the power-down timing parameters. See . */ typedef union _hw_pgc_gpu_sr { reg32_t U; struct _hw_pgc_gpu_sr_bitfields { unsigned PSR : 1; //!< [0] Power status. unsigned RESERVED0 : 31; //!< [31:1] Reserved. } B; } hw_pgc_gpu_sr_t; #endif /*! * @name Constants and macros for entire PGC_GPU_SR register */ //@{ #define HW_PGC_GPU_SR_ADDR (REGS_PGC_BASE + 0x26c) #ifndef __LANGUAGE_ASM__ #define HW_PGC_GPU_SR (*(volatile hw_pgc_gpu_sr_t *) HW_PGC_GPU_SR_ADDR) #define HW_PGC_GPU_SR_RD() (HW_PGC_GPU_SR.U) #define HW_PGC_GPU_SR_WR(v) (HW_PGC_GPU_SR.U = (v)) #define HW_PGC_GPU_SR_SET(v) (HW_PGC_GPU_SR_WR(HW_PGC_GPU_SR_RD() | (v))) #define HW_PGC_GPU_SR_CLR(v) (HW_PGC_GPU_SR_WR(HW_PGC_GPU_SR_RD() & ~(v))) #define HW_PGC_GPU_SR_TOG(v) (HW_PGC_GPU_SR_WR(HW_PGC_GPU_SR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_GPU_SR bitfields */ /*! @name Register PGC_GPU_SR, field PSR[0] (RW) * * Power status. When in functional (or software-controlled debug) mode, PGC hardware sets PSR as * soon as any of the power control output changes its state to one. Write one to clear this bit. * Software should clear this bit after power up; otherwise, PSR continues to reflect the power * status of the initial power down. * * Values: * - 0 - The target subsystem was not powered down for the previous power-down request. * - 1 - The target subsystem was powered down for the previous power-down request. */ //@{ #define BP_PGC_GPU_SR_PSR (0) //!< Bit position for PGC_GPU_SR_PSR. #define BM_PGC_GPU_SR_PSR (0x00000001) //!< Bit mask for PGC_GPU_SR_PSR. //! @brief Get value of PGC_GPU_SR_PSR from a register value. #define BG_PGC_GPU_SR_PSR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_GPU_SR_PSR) >> BP_PGC_GPU_SR_PSR) //! @brief Format value for bitfield PGC_GPU_SR_PSR. #define BF_PGC_GPU_SR_PSR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_GPU_SR_PSR) & BM_PGC_GPU_SR_PSR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PSR field to a new value. #define BW_PGC_GPU_SR_PSR(v) (HW_PGC_GPU_SR_WR((HW_PGC_GPU_SR_RD() & ~BM_PGC_GPU_SR_PSR) | BF_PGC_GPU_SR_PSR(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_CPU_CTRL - PGC Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_CPU_CTRL - PGC Control Register (RW) * * Reset value: 0x00000000 * * The PGCR enables the response to a power-down request. */ typedef union _hw_pgc_cpu_ctrl { reg32_t U; struct _hw_pgc_cpu_ctrl_bitfields { unsigned PCR : 1; //!< [0] Power Control unsigned RESERVED0 : 31; //!< [31:1] Reserved. } B; } hw_pgc_cpu_ctrl_t; #endif /*! * @name Constants and macros for entire PGC_CPU_CTRL register */ //@{ #define HW_PGC_CPU_CTRL_ADDR (REGS_PGC_BASE + 0x2a0) #ifndef __LANGUAGE_ASM__ #define HW_PGC_CPU_CTRL (*(volatile hw_pgc_cpu_ctrl_t *) HW_PGC_CPU_CTRL_ADDR) #define HW_PGC_CPU_CTRL_RD() (HW_PGC_CPU_CTRL.U) #define HW_PGC_CPU_CTRL_WR(v) (HW_PGC_CPU_CTRL.U = (v)) #define HW_PGC_CPU_CTRL_SET(v) (HW_PGC_CPU_CTRL_WR(HW_PGC_CPU_CTRL_RD() | (v))) #define HW_PGC_CPU_CTRL_CLR(v) (HW_PGC_CPU_CTRL_WR(HW_PGC_CPU_CTRL_RD() & ~(v))) #define HW_PGC_CPU_CTRL_TOG(v) (HW_PGC_CPU_CTRL_WR(HW_PGC_CPU_CTRL_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_CPU_CTRL bitfields */ /*! @name Register PGC_CPU_CTRL, field PCR[0] (RW) * * Power Control PCR must not change from power-down request (pdn_req) assertion until the target * subsystem is completely powered up. * * Values: * - 0 - Do not switch off power even if pdn_req is asserted. * - 1 - Switch off power when pdn_req is asserted. */ //@{ #define BP_PGC_CPU_CTRL_PCR (0) //!< Bit position for PGC_CPU_CTRL_PCR. #define BM_PGC_CPU_CTRL_PCR (0x00000001) //!< Bit mask for PGC_CPU_CTRL_PCR. //! @brief Get value of PGC_CPU_CTRL_PCR from a register value. #define BG_PGC_CPU_CTRL_PCR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_CTRL_PCR) >> BP_PGC_CPU_CTRL_PCR) //! @brief Format value for bitfield PGC_CPU_CTRL_PCR. #define BF_PGC_CPU_CTRL_PCR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_CTRL_PCR) & BM_PGC_CPU_CTRL_PCR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PCR field to a new value. #define BW_PGC_CPU_CTRL_PCR(v) (HW_PGC_CPU_CTRL_WR((HW_PGC_CPU_CTRL_RD() & ~BM_PGC_CPU_CTRL_PCR) | BF_PGC_CPU_CTRL_PCR(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_CPU_PUPSCR - Power Up Sequence Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_CPU_PUPSCR - Power Up Sequence Control Register (RW) * * Reset value: 0x00000f01 * * The PUPSCR contains the power-up timing parameters. See . */ typedef union _hw_pgc_cpu_pupscr { reg32_t U; struct _hw_pgc_cpu_pupscr_bitfields { unsigned SW : 6; //!< [5:0] After a power-up request (pup_req assertion), the PGC waits a number of clocks equal to the value of SW before asserting switch_b. unsigned RESERVED0 : 2; //!< [7:6] Reserved. unsigned SW2ISO : 6; //!< [13:8] After asserting switch_b, the PGC waits a number of clocks equal to the value of SW2ISO before negating isolation. unsigned RESERVED1 : 18; //!< [31:14] Reserved. } B; } hw_pgc_cpu_pupscr_t; #endif /*! * @name Constants and macros for entire PGC_CPU_PUPSCR register */ //@{ #define HW_PGC_CPU_PUPSCR_ADDR (REGS_PGC_BASE + 0x2a4) #ifndef __LANGUAGE_ASM__ #define HW_PGC_CPU_PUPSCR (*(volatile hw_pgc_cpu_pupscr_t *) HW_PGC_CPU_PUPSCR_ADDR) #define HW_PGC_CPU_PUPSCR_RD() (HW_PGC_CPU_PUPSCR.U) #define HW_PGC_CPU_PUPSCR_WR(v) (HW_PGC_CPU_PUPSCR.U = (v)) #define HW_PGC_CPU_PUPSCR_SET(v) (HW_PGC_CPU_PUPSCR_WR(HW_PGC_CPU_PUPSCR_RD() | (v))) #define HW_PGC_CPU_PUPSCR_CLR(v) (HW_PGC_CPU_PUPSCR_WR(HW_PGC_CPU_PUPSCR_RD() & ~(v))) #define HW_PGC_CPU_PUPSCR_TOG(v) (HW_PGC_CPU_PUPSCR_WR(HW_PGC_CPU_PUPSCR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_CPU_PUPSCR bitfields */ /*! @name Register PGC_CPU_PUPSCR, field SW[5:0] (RW) * * After a power-up request (pup_req assertion), the PGC waits a number of clocks equal to the value * of SW before asserting switch_b. SW must not be programmed to zero. The PGC clock is generated * from the IPG_CLK_ROOT. for frequency configuration of the IPG_CLK_ROOT. See . */ //@{ #define BP_PGC_CPU_PUPSCR_SW (0) //!< Bit position for PGC_CPU_PUPSCR_SW. #define BM_PGC_CPU_PUPSCR_SW (0x0000003f) //!< Bit mask for PGC_CPU_PUPSCR_SW. //! @brief Get value of PGC_CPU_PUPSCR_SW from a register value. #define BG_PGC_CPU_PUPSCR_SW(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_PUPSCR_SW) >> BP_PGC_CPU_PUPSCR_SW) //! @brief Format value for bitfield PGC_CPU_PUPSCR_SW. #define BF_PGC_CPU_PUPSCR_SW(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_PUPSCR_SW) & BM_PGC_CPU_PUPSCR_SW) #ifndef __LANGUAGE_ASM__ //! @brief Set the SW field to a new value. #define BW_PGC_CPU_PUPSCR_SW(v) (HW_PGC_CPU_PUPSCR_WR((HW_PGC_CPU_PUPSCR_RD() & ~BM_PGC_CPU_PUPSCR_SW) | BF_PGC_CPU_PUPSCR_SW(v))) #endif //@} /*! @name Register PGC_CPU_PUPSCR, field SW2ISO[13:8] (RW) * * After asserting switch_b, the PGC waits a number of clocks equal to the value of SW2ISO before * negating isolation. SW2ISO must not be programmed to zero. */ //@{ #define BP_PGC_CPU_PUPSCR_SW2ISO (8) //!< Bit position for PGC_CPU_PUPSCR_SW2ISO. #define BM_PGC_CPU_PUPSCR_SW2ISO (0x00003f00) //!< Bit mask for PGC_CPU_PUPSCR_SW2ISO. //! @brief Get value of PGC_CPU_PUPSCR_SW2ISO from a register value. #define BG_PGC_CPU_PUPSCR_SW2ISO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_PUPSCR_SW2ISO) >> BP_PGC_CPU_PUPSCR_SW2ISO) //! @brief Format value for bitfield PGC_CPU_PUPSCR_SW2ISO. #define BF_PGC_CPU_PUPSCR_SW2ISO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_PUPSCR_SW2ISO) & BM_PGC_CPU_PUPSCR_SW2ISO) #ifndef __LANGUAGE_ASM__ //! @brief Set the SW2ISO field to a new value. #define BW_PGC_CPU_PUPSCR_SW2ISO(v) (HW_PGC_CPU_PUPSCR_WR((HW_PGC_CPU_PUPSCR_RD() & ~BM_PGC_CPU_PUPSCR_SW2ISO) | BF_PGC_CPU_PUPSCR_SW2ISO(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_CPU_PDNSCR - Pull Down Sequence Control Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_CPU_PDNSCR - Pull Down Sequence Control Register (RW) * * Reset value: 0x00000101 * * The PDNSCR contains the power-down timing parameters. See . */ typedef union _hw_pgc_cpu_pdnscr { reg32_t U; struct _hw_pgc_cpu_pdnscr_bitfields { unsigned ISO : 6; //!< [5:0] After a power-down request (pdn_req assertion), the PGC waits a number of clocks equal to the value of ISO before asserting isolation. unsigned RESERVED0 : 2; //!< [7:6] Reserved. unsigned ISO2SW : 6; //!< [13:8] After asserting isolation, the PGC waits a number of clocks equal to the value of ISO2SW before negating switch_b. unsigned RESERVED1 : 18; //!< [31:14] Reserved. } B; } hw_pgc_cpu_pdnscr_t; #endif /*! * @name Constants and macros for entire PGC_CPU_PDNSCR register */ //@{ #define HW_PGC_CPU_PDNSCR_ADDR (REGS_PGC_BASE + 0x2a8) #ifndef __LANGUAGE_ASM__ #define HW_PGC_CPU_PDNSCR (*(volatile hw_pgc_cpu_pdnscr_t *) HW_PGC_CPU_PDNSCR_ADDR) #define HW_PGC_CPU_PDNSCR_RD() (HW_PGC_CPU_PDNSCR.U) #define HW_PGC_CPU_PDNSCR_WR(v) (HW_PGC_CPU_PDNSCR.U = (v)) #define HW_PGC_CPU_PDNSCR_SET(v) (HW_PGC_CPU_PDNSCR_WR(HW_PGC_CPU_PDNSCR_RD() | (v))) #define HW_PGC_CPU_PDNSCR_CLR(v) (HW_PGC_CPU_PDNSCR_WR(HW_PGC_CPU_PDNSCR_RD() & ~(v))) #define HW_PGC_CPU_PDNSCR_TOG(v) (HW_PGC_CPU_PDNSCR_WR(HW_PGC_CPU_PDNSCR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_CPU_PDNSCR bitfields */ /*! @name Register PGC_CPU_PDNSCR, field ISO[5:0] (RW) * * After a power-down request (pdn_req assertion), the PGC waits a number of clocks equal to the * value of ISO before asserting isolation. ISO must not be programmed to zero. */ //@{ #define BP_PGC_CPU_PDNSCR_ISO (0) //!< Bit position for PGC_CPU_PDNSCR_ISO. #define BM_PGC_CPU_PDNSCR_ISO (0x0000003f) //!< Bit mask for PGC_CPU_PDNSCR_ISO. //! @brief Get value of PGC_CPU_PDNSCR_ISO from a register value. #define BG_PGC_CPU_PDNSCR_ISO(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_PDNSCR_ISO) >> BP_PGC_CPU_PDNSCR_ISO) //! @brief Format value for bitfield PGC_CPU_PDNSCR_ISO. #define BF_PGC_CPU_PDNSCR_ISO(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_PDNSCR_ISO) & BM_PGC_CPU_PDNSCR_ISO) #ifndef __LANGUAGE_ASM__ //! @brief Set the ISO field to a new value. #define BW_PGC_CPU_PDNSCR_ISO(v) (HW_PGC_CPU_PDNSCR_WR((HW_PGC_CPU_PDNSCR_RD() & ~BM_PGC_CPU_PDNSCR_ISO) | BF_PGC_CPU_PDNSCR_ISO(v))) #endif //@} /*! @name Register PGC_CPU_PDNSCR, field ISO2SW[13:8] (RW) * * After asserting isolation, the PGC waits a number of clocks equal to the value of ISO2SW before * negating switch_b. ISO2SW must not be programmed to zero. */ //@{ #define BP_PGC_CPU_PDNSCR_ISO2SW (8) //!< Bit position for PGC_CPU_PDNSCR_ISO2SW. #define BM_PGC_CPU_PDNSCR_ISO2SW (0x00003f00) //!< Bit mask for PGC_CPU_PDNSCR_ISO2SW. //! @brief Get value of PGC_CPU_PDNSCR_ISO2SW from a register value. #define BG_PGC_CPU_PDNSCR_ISO2SW(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_PDNSCR_ISO2SW) >> BP_PGC_CPU_PDNSCR_ISO2SW) //! @brief Format value for bitfield PGC_CPU_PDNSCR_ISO2SW. #define BF_PGC_CPU_PDNSCR_ISO2SW(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_PDNSCR_ISO2SW) & BM_PGC_CPU_PDNSCR_ISO2SW) #ifndef __LANGUAGE_ASM__ //! @brief Set the ISO2SW field to a new value. #define BW_PGC_CPU_PDNSCR_ISO2SW(v) (HW_PGC_CPU_PDNSCR_WR((HW_PGC_CPU_PDNSCR_RD() & ~BM_PGC_CPU_PDNSCR_ISO2SW) | BF_PGC_CPU_PDNSCR_ISO2SW(v))) #endif //@} //------------------------------------------------------------------------------------------- // HW_PGC_CPU_SR - Power Gating Controller Status Register //------------------------------------------------------------------------------------------- #ifndef __LANGUAGE_ASM__ /*! * @brief HW_PGC_CPU_SR - Power Gating Controller Status Register (RW) * * Reset value: 0x00000000 * * The PDNSCR contains the power-down timing parameters. See . */ typedef union _hw_pgc_cpu_sr { reg32_t U; struct _hw_pgc_cpu_sr_bitfields { unsigned PSR : 1; //!< [0] Power status. unsigned RESERVED0 : 31; //!< [31:1] Reserved. } B; } hw_pgc_cpu_sr_t; #endif /*! * @name Constants and macros for entire PGC_CPU_SR register */ //@{ #define HW_PGC_CPU_SR_ADDR (REGS_PGC_BASE + 0x2ac) #ifndef __LANGUAGE_ASM__ #define HW_PGC_CPU_SR (*(volatile hw_pgc_cpu_sr_t *) HW_PGC_CPU_SR_ADDR) #define HW_PGC_CPU_SR_RD() (HW_PGC_CPU_SR.U) #define HW_PGC_CPU_SR_WR(v) (HW_PGC_CPU_SR.U = (v)) #define HW_PGC_CPU_SR_SET(v) (HW_PGC_CPU_SR_WR(HW_PGC_CPU_SR_RD() | (v))) #define HW_PGC_CPU_SR_CLR(v) (HW_PGC_CPU_SR_WR(HW_PGC_CPU_SR_RD() & ~(v))) #define HW_PGC_CPU_SR_TOG(v) (HW_PGC_CPU_SR_WR(HW_PGC_CPU_SR_RD() ^ (v))) #endif //@} /* * constants & macros for individual PGC_CPU_SR bitfields */ /*! @name Register PGC_CPU_SR, field PSR[0] (RW) * * Power status. When in functional (or software-controlled debug) mode, PGC hardware sets PSR as * soon as any of the power control output changes its state to one. Write one to clear this bit. * Software should clear this bit after power up; otherwise, PSR continues to reflect the power * status of the initial power down. * * Values: * - 0 - The target subsystem was not powered down for the previous power-down request. * - 1 - The target subsystem was powered down for the previous power-down request. */ //@{ #define BP_PGC_CPU_SR_PSR (0) //!< Bit position for PGC_CPU_SR_PSR. #define BM_PGC_CPU_SR_PSR (0x00000001) //!< Bit mask for PGC_CPU_SR_PSR. //! @brief Get value of PGC_CPU_SR_PSR from a register value. #define BG_PGC_CPU_SR_PSR(r) ((__REG_VALUE_TYPE((r), reg32_t) & BM_PGC_CPU_SR_PSR) >> BP_PGC_CPU_SR_PSR) //! @brief Format value for bitfield PGC_CPU_SR_PSR. #define BF_PGC_CPU_SR_PSR(v) ((__REG_VALUE_TYPE((v), reg32_t) << BP_PGC_CPU_SR_PSR) & BM_PGC_CPU_SR_PSR) #ifndef __LANGUAGE_ASM__ //! @brief Set the PSR field to a new value. #define BW_PGC_CPU_SR_PSR(v) (HW_PGC_CPU_SR_WR((HW_PGC_CPU_SR_RD() & ~BM_PGC_CPU_SR_PSR) | BF_PGC_CPU_SR_PSR(v))) #endif //@} //------------------------------------------------------------------------------------------- // hw_pgc_t - module struct //------------------------------------------------------------------------------------------- /*! * @brief All PGC module registers. */ #ifndef __LANGUAGE_ASM__ #pragma pack(1) typedef struct _hw_pgc { reg32_t _reserved0[152]; volatile hw_pgc_gpu_ctrl_t GPU_CTRL; //!< PGC Control Register volatile hw_pgc_gpu_pupscr_t GPU_PUPSCR; //!< Power Up Sequence Control Register volatile hw_pgc_gpu_pdnscr_t GPU_PDNSCR; //!< Pull Down Sequence Control Register volatile hw_pgc_gpu_sr_t GPU_SR; //!< Power Gating Controller Status Register reg32_t _reserved1[12]; volatile hw_pgc_cpu_ctrl_t CPU_CTRL; //!< PGC Control Register volatile hw_pgc_cpu_pupscr_t CPU_PUPSCR; //!< Power Up Sequence Control Register volatile hw_pgc_cpu_pdnscr_t CPU_PDNSCR; //!< Pull Down Sequence Control Register volatile hw_pgc_cpu_sr_t CPU_SR; //!< Power Gating Controller Status Register } hw_pgc_t; #pragma pack() //! @brief Macro to access all PGC registers. //! @return Reference (not a pointer) to the registers struct. To get a pointer to the struct, //! use the '&' operator, like <code>&HW_PGC</code>. #define HW_PGC (*(hw_pgc_t *) REGS_PGC_BASE) #endif #endif // __HW_PGC_REGISTERS_H__ // v18/121106/1.2.2 // EOF
apache-2.0
ssaroha/node-webrtc
third_party/webrtc/include/chromium/src/media/filters/ivf_parser.h
2935
// 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. #ifndef MEDIA_FILTERS_IVF_PARSER_H_ #define MEDIA_FILTERS_IVF_PARSER_H_ #include <stddef.h> #include <stdint.h> #include "base/macros.h" #include "media/base/media_export.h" namespace media { const char kIvfHeaderSignature[] = "DKIF"; #pragma pack(push, 1) struct MEDIA_EXPORT IvfFileHeader { // Byte swap interger fields between native and (on disk) little endian. void ByteSwap(); char signature[4]; // signature: 'DKIF' uint16_t version; // version (should be 0) uint16_t header_size; // size of header in bytes uint32_t fourcc; // codec FourCC (e.g., 'VP80') uint16_t width; // width in pixels uint16_t height; // height in pixels uint32_t timebase_denum; // timebase denumerator uint32_t timebase_num; // timebase numerator. For example, if // timebase_denum is 30 and timebase_num is 2, the // unit of IvfFrameHeader.timestamp is 2/30 // seconds. uint32_t num_frames; // number of frames in file uint32_t unused; // unused }; static_assert( sizeof(IvfFileHeader) == 32, "sizeof(IvfFileHeader) must be fixed since it will be used with file IO"); struct MEDIA_EXPORT IvfFrameHeader { // Byte swap interger fields between native and (on disk) little endian. void ByteSwap(); uint32_t frame_size; // Size of frame in bytes (not including the header) uint64_t timestamp; // 64-bit presentation timestamp in unit timebase, // which is defined in IvfFileHeader. }; static_assert( sizeof(IvfFrameHeader) == 12, "sizeof(IvfFrameHeader) must be fixed since it will be used with file IO"); #pragma pack(pop) // IVF is a simple container format for video frame. It is used by libvpx to // transport VP8 and VP9 bitstream. class MEDIA_EXPORT IvfParser { public: IvfParser(); // Initializes the parser for IVF |stream| with size |size| and parses the // file header. Returns true on success. bool Initialize(const uint8_t* stream, size_t size, IvfFileHeader* file_header); // Parses the next frame. Returns true if the next frame is parsed without // error. |frame_header| will be filled with the frame header and |payload| // will point to frame payload (inside the |stream| buffer given to // Initialize.) bool ParseNextFrame(IvfFrameHeader* frame_header, const uint8_t** payload); private: bool ParseFileHeader(IvfFileHeader* file_header); // Current reading position of input stream. const uint8_t* ptr_; // The end position of input stream. const uint8_t* end_; DISALLOW_COPY_AND_ASSIGN(IvfParser); }; } // namespace media #endif // MEDIA_FILTERS_IVF_PARSER_H_
bsd-2-clause
codestation/go
test/mergemul.go
3236
// runoutput // Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import "fmt" // Check that expressions like (c*n + d*(n+k)) get correctly merged by // the compiler into (c+d)*n + d*k (with c+d and d*k computed at // compile time). // // The merging is performed by a combination of the multiplication // merge rules // (c*n + d*n) -> (c+d)*n // and the distributive multiplication rules // c * (d+x) -> c*d + c*x // Generate a MergeTest that looks like this: // // a8, b8 = m1*n8 + m2*(n8+k), (m1+m2)*n8 + m2*k // if a8 != b8 { // // print error msg and panic // } func makeMergeAddTest(m1, m2, k int, size string) string { model := " a" + size + ", b" + size model += fmt.Sprintf(" = %%d*n%s + %%d*(n%s+%%d), (%%d+%%d)*n%s + (%%d*%%d)", size, size, size) test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k) test += fmt.Sprintf(` if a%s != b%s { fmt.Printf("MergeAddTest(%d, %d, %d, %s) failed\n") fmt.Printf("%%d != %%d\n", a%s, b%s) panic("FAIL") } `, size, size, m1, m2, k, size, size, size) return test + "\n" } // Check that expressions like (c*n - d*(n+k)) get correctly merged by // the compiler into (c-d)*n - d*k (with c-d and d*k computed at // compile time). // // The merging is performed by a combination of the multiplication // merge rules // (c*n - d*n) -> (c-d)*n // and the distributive multiplication rules // c * (d-x) -> c*d - c*x // Generate a MergeTest that looks like this: // // a8, b8 = m1*n8 - m2*(n8+k), (m1-m2)*n8 - m2*k // if a8 != b8 { // // print error msg and panic // } func makeMergeSubTest(m1, m2, k int, size string) string { model := " a" + size + ", b" + size model += fmt.Sprintf(" = %%d*n%s - %%d*(n%s+%%d), (%%d-%%d)*n%s - (%%d*%%d)", size, size, size) test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k) test += fmt.Sprintf(` if a%s != b%s { fmt.Printf("MergeSubTest(%d, %d, %d, %s) failed\n") fmt.Printf("%%d != %%d\n", a%s, b%s) panic("FAIL") } `, size, size, m1, m2, k, size, size, size) return test + "\n" } func makeAllSizes(m1, m2, k int) string { var tests string tests += makeMergeAddTest(m1, m2, k, "8") tests += makeMergeAddTest(m1, m2, k, "16") tests += makeMergeAddTest(m1, m2, k, "32") tests += makeMergeAddTest(m1, m2, k, "64") tests += makeMergeSubTest(m1, m2, k, "8") tests += makeMergeSubTest(m1, m2, k, "16") tests += makeMergeSubTest(m1, m2, k, "32") tests += makeMergeSubTest(m1, m2, k, "64") tests += "\n" return tests } func main() { fmt.Println(`package main import "fmt" var n8 int8 = 42 var n16 int16 = 42 var n32 int32 = 42 var n64 int64 = 42 func main() { var a8, b8 int8 var a16, b16 int16 var a32, b32 int32 var a64, b64 int64 `) fmt.Println(makeAllSizes(03, 05, 0)) // 3*n + 5*n fmt.Println(makeAllSizes(17, 33, 0)) fmt.Println(makeAllSizes(80, 45, 0)) fmt.Println(makeAllSizes(32, 64, 0)) fmt.Println(makeAllSizes(7, 11, +1)) // 7*n + 11*(n+1) fmt.Println(makeAllSizes(9, 13, +2)) fmt.Println(makeAllSizes(11, 16, -1)) fmt.Println(makeAllSizes(17, 9, -2)) fmt.Println("}") }
bsd-3-clause
itsmemz53/Project-DB
www/lib/ngmap/testapp/circle-simple.html
1746
<!DOCTYPE html> <html ng-app="myApp"> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script src="https://maps.google.com/maps/api/js?sensor=false"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script> <!-- <script src="../build/scripts/ng-map.min.js"></script> --> <script src="../app.js"></script> <script src="../directives/map_controller.js"></script> <script src="../directives/map.js"></script> <script src="../directives/marker.js"></script> <script src="../directives/shape.js"></script> <script src="../services/geo_coder.js"></script> <script src="../services/navigator_geolocation.js"></script> <script src="../services/attr2_options.js"></script> <script> var app = angular.module('myApp', ['ngMap']); app.controller('CircleSimpleCtrl', function($scope) { $scope.cities = { chicago: {population:2714856, position: [41.878113, -87.629798]}, newyork: {population:8405837, position: [40.714352, -74.005973]}, losangeles: {population:3857799, position: [34.052234, -118.243684]}, vancouver: {population:603502, position: [49.25, -123.1]}, } $scope.getRadius = function(num) { return Math.sqrt(num) * 100; } }); </script> </head> <body> <div ng-controller="CircleSimpleCtrl"> <map center="37.09024, -95.712891" zoom="4" mayTypeId="TERRAIN"> <shape name="circle" ng-repeat="city in cities" stroke-color="#FF0000" stroke-opacity="0.8" stroke-weight="2" fill-color="#FF0000" fill-opacity="0.35" center="{{city.position}}" radius="{{getRadius(city.population)}}"> </shape> </map> </div> </body> </html>
mit
lafriks/gitea
docs/content/doc/features/webhooks.zh-tw.md
234
--- date: "2016-12-01T16:00:00+02:00" title: "Webhooks" slug: "webhooks" weight: 10 toc: true draft: false menu: sidebar: parent: "features" name: "Webhooks" weight: 30 identifier: "webhooks" --- # Webhooks ## TBD
mit
iamjasonp/corefx
src/System.Dynamic.Runtime/src/System/Dynamic/IDynamicMetaObjectProvider.cs
1145
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; namespace System.Dynamic { /// <summary> /// Represents a dynamic object, that can have its operations bound at runtime. /// </summary> /// <remarks> /// Objects that want to participate in the binding process should implement an IDynamicMetaObjectProvider interface, /// and implement <see cref="IDynamicMetaObjectProvider.GetMetaObject" /> to return a <see cref="DynamicMetaObject" />. /// </remarks> public interface IDynamicMetaObjectProvider { /// <summary> /// Returns the <see cref="DynamicMetaObject" /> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns>The <see cref="DynamicMetaObject" /> to bind this object.</returns> DynamicMetaObject GetMetaObject(Expression parameter); } }
mit
markogresak/DefinitelyTyped
types/wordpress__block-editor/components/color-palette/with-color-context.d.ts
777
// tslint:disable:no-unnecessary-generics import { ComponentType } from 'react'; import { EditorColor } from '../../'; declare namespace withColorContext { interface Props { colors: EditorColor[]; disableCustomColors: boolean; hasColorsToChoose: boolean; } } // prettier-ignore declare function withColorContext< ProvidedProps extends Partial<withColorContext.Props>, OwnProps extends any = any, T extends ComponentType<ProvidedProps & OwnProps> = ComponentType<ProvidedProps & OwnProps> >(component: T): T extends ComponentType<infer U> ? ComponentType< Omit<U, 'colors' | 'disableCustomColors' | 'hasColorsToChoose'> & Omit<ProvidedProps, 'hasColorsToChoose'>> : never; export default withColorContext;
mit
upsoft/Atlas
src/network-mysqld-lua.c
24067
/* $%BEGINLICENSE%$ Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef _WIN32 #include <winsock2.h> /* mysql.h needs SOCKET */ #endif #include <mysql.h> #include <mysqld_error.h> #include <errno.h> #include <string.h> #include "network-backend.h" #include "glib-ext.h" #include "lua-env.h" #include "network-mysqld.h" #include "network-mysqld-proto.h" #include "network-mysqld-lua.h" #include "network-socket-lua.h" #include "network-backend-lua.h" #include "network-conn-pool.h" #include "network-conn-pool-lua.h" #include "network-injection-lua.h" #define C(x) x, sizeof(x) - 1 network_mysqld_con_lua_t *network_mysqld_con_lua_new() { network_mysqld_con_lua_t *st; st = g_new0(network_mysqld_con_lua_t, 1); st->injected.queries = network_injection_queue_new(); return st; } void network_mysqld_con_lua_free(network_mysqld_con_lua_t *st) { if (!st) return; network_injection_queue_free(st->injected.queries); g_free(st); } /** * get the connection information * * note: might be called in connect_server() before con->server is set */ static int proxy_connection_get(lua_State *L) { network_mysqld_con *con = *(network_mysqld_con **)luaL_checkself(L); network_mysqld_con_lua_t *st; gsize keysize = 0; const char *key = luaL_checklstring(L, 2, &keysize); st = con->plugin_con_state; /** * we to split it in .client and .server here */ if (strleq(key, keysize, C("default_db"))) { return luaL_error(L, "proxy.connection.default_db is deprecated, use proxy.connection.client.default_db or proxy.connection.server.default_db instead"); } else if (strleq(key, keysize, C("thread_id"))) { return luaL_error(L, "proxy.connection.thread_id is deprecated, use proxy.connection.server.thread_id instead"); } else if (strleq(key, keysize, C("mysqld_version"))) { return luaL_error(L, "proxy.connection.mysqld_version is deprecated, use proxy.connection.server.mysqld_version instead"); } else if (strleq(key, keysize, C("backend_ndx"))) { lua_pushinteger(L, st->backend_ndx + 1); } else if ((con->server && (strleq(key, keysize, C("server")))) || (con->client && (strleq(key, keysize, C("client"))))) { network_socket **socket_p; socket_p = lua_newuserdata(L, sizeof(network_socket)); /* the table underneat proxy.socket */ if (key[0] == 's') { *socket_p = con->server; } else { *socket_p = con->client; } network_socket_lua_getmetatable(L); lua_setmetatable(L, -2); /* tie the metatable to the table (sp -= 1) */ } else { lua_pushnil(L); } return 1; } /** * set the connection information * * note: might be called in connect_server() before con->server is set */ static int proxy_connection_set(lua_State *L) { network_mysqld_con *con = *(network_mysqld_con **)luaL_checkself(L); network_mysqld_con_lua_t *st; gsize keysize = 0; const char *key = luaL_checklstring(L, 2, &keysize); st = con->plugin_con_state; if (strleq(key, keysize, C("backend_ndx"))) { /** * in lua-land the ndx is based on 1, in C-land on 0 */ int backend_ndx = luaL_checkinteger(L, 3) - 1; network_socket *send_sock; if (backend_ndx == -1) { /** drop the backend for now */ network_connection_pool_lua_add_connection(con); } else if (NULL != (send_sock = network_connection_pool_lua_swap(con, backend_ndx, NULL))) { con->server = send_sock; } else if (backend_ndx == -2) { if (st->backend != NULL) { st->backend->connected_clients--; st->backend = NULL; } st->backend_ndx = -1; network_socket_free(con->server); con->server = NULL; } else { st->backend_ndx = backend_ndx; } } else if (0 == strcmp(key, "connection_close")) { luaL_checktype(L, 3, LUA_TBOOLEAN); st->connection_close = lua_toboolean(L, 3); } else { return luaL_error(L, "proxy.connection.%s is not writable", key); } return 0; } int network_mysqld_con_getmetatable(lua_State *L) { static const struct luaL_reg methods[] = { { "__index", proxy_connection_get }, { "__newindex", proxy_connection_set }, { NULL, NULL }, }; return proxy_getmetatable(L, methods); } /** * Set up the global structures for a script. * * @see lua_register_callback - for connection local setup */ void network_mysqld_lua_setup_global(lua_State *L , chassis *chas) { network_backends_t **backends_p; int stack_top = lua_gettop(L); /* TODO: if we share "proxy." with other plugins, this may fail to initialize it correctly, * because maybe they already have registered stuff in there. * It would be better to have different namespaces, or any other way to make sure we initialize correctly. */ lua_getglobal(L, "proxy"); if (lua_isnil(L, -1)) { lua_pop(L, 1); network_mysqld_lua_init_global_fenv(L); lua_getglobal(L, "proxy"); } g_assert(lua_istable(L, -1)); /* at this point we have set up: * - the script * - _G.proxy and a bunch of constants in that table * - _G.proxy.global */ /** * register proxy.global.backends[] * * @see proxy_backends_get() */ lua_getfield(L, -1, "global"); // set instance name // proxy.global.config.instance , value assigned when cmd start use --instance lua_getfield(L, -1, "config"); lua_pushstring(L, chas->instance_name); lua_setfield(L, -2, "instance"); lua_pushstring(L, chas->log_path); lua_setfield(L, -2, "logpath"); lua_pop(L, 1); // backends_p = lua_newuserdata(L, sizeof(network_backends_t *)); *backends_p = chas->backends; network_backends_lua_getmetatable(L); lua_setmetatable(L, -2); /* tie the metatable to the table (sp -= 1) */ lua_setfield(L, -2, "backends"); GPtrArray **raw_ips_p = lua_newuserdata(L, sizeof(GPtrArray *)); *raw_ips_p = chas->backends->raw_ips; network_clients_lua_getmetatable(L); lua_setmetatable(L, -2); lua_setfield(L, -2, "clients"); GPtrArray **raw_pwds_p = lua_newuserdata(L, sizeof(GPtrArray *)); *raw_pwds_p = chas->backends->raw_pwds; network_pwds_lua_getmetatable(L); lua_setmetatable(L, -2); lua_setfield(L, -2, "pwds"); lua_pop(L, 2); /* _G.proxy.global and _G.proxy */ g_assert(lua_gettop(L) == stack_top); } /** * Load a lua script and leave the wrapper function on the stack. * * @return 0 on success, -1 on error */ int network_mysqld_lua_load_script(lua_scope *sc, const char *lua_script) { int stack_top = lua_gettop(sc->L); if (!lua_script) return -1; /* a script cache * * we cache the scripts globally in the registry and move a copy of it * to the new script scope on success. */ lua_scope_load_script(sc, lua_script); if (lua_isstring(sc->L, -1)) { g_critical("%s: lua_load_file(%s) failed: %s", G_STRLOC, lua_script, lua_tostring(sc->L, -1)); lua_pop(sc->L, 1); /* remove the error-msg from the stack */ return -1; } else if (!lua_isfunction(sc->L, -1)) { g_error("%s: luaL_loadfile(%s): returned a %s", G_STRLOC, lua_script, lua_typename(sc->L, lua_type(sc->L, -1))); } g_assert(lua_gettop(sc->L) - stack_top == 1); return 0; } /** * setup the local script environment before we call the hook function * * has to be called before any lua_pcall() is called to start a hook function * * - we use a global lua_State which is split into child-states with lua_newthread() * - luaL_ref() moves the state into the registry and cleans up the global stack * - on connection close we call luaL_unref() to hand the thread to the GC * * @see proxy_lua_free_script * * * if the script is cached we have to point the global proxy object * * @retval 0 success (even if we do not have a script) * @retval -1 The script failed to load, most likely because of a syntax error. * @retval -2 The script failed to execute. */ network_mysqld_register_callback_ret network_mysqld_con_lua_register_callback(network_mysqld_con *con, const char *lua_script) { lua_State *L = NULL; network_mysqld_con_lua_t *st = con->plugin_con_state; lua_scope *sc = con->srv->sc; GQueue **q_p; network_mysqld_con **con_p; int stack_top; if (!lua_script) return REGISTER_CALLBACK_SUCCESS; if (st->L) { /* we have to rewrite _G.proxy to point to the local proxy */ L = st->L; g_assert(lua_isfunction(L, -1)); lua_getfenv(L, -1); g_assert(lua_istable(L, -1)); lua_getglobal(L, "proxy"); lua_getmetatable(L, -1); /* meta(_G.proxy) */ lua_getfield(L, -3, "__proxy"); /* fenv.__proxy */ lua_setfield(L, -2, "__index"); /* meta[_G.proxy].__index = fenv.__proxy */ lua_getfield(L, -3, "__proxy"); /* fenv.__proxy */ lua_setfield(L, -2, "__newindex"); /* meta[_G.proxy].__newindex = fenv.__proxy */ lua_pop(L, 3); g_assert(lua_isfunction(L, -1)); return REGISTER_CALLBACK_SUCCESS; /* the script-env already setup, get out of here */ } /* handles loading the file from disk/cache*/ if (0 != network_mysqld_lua_load_script(sc, lua_script)) { /* loading script failed */ return REGISTER_CALLBACK_LOAD_FAILED; } /* sets up global tables */ network_mysqld_lua_setup_global(sc->L, con->srv); /** * create a side thread for this connection * * (this is not pre-emptive, it is just a new stack in the global env) */ L = lua_newthread(sc->L); st->L_ref = luaL_ref(sc->L, LUA_REGISTRYINDEX); stack_top = lua_gettop(L); /* get the script from the global stack */ lua_xmove(sc->L, L, 1); g_assert(lua_isfunction(L, -1)); lua_newtable(L); /* my empty environment aka {} (sp += 1) 1 */ lua_newtable(L); /* the meta-table for the new env (sp += 1) 2 */ lua_pushvalue(L, LUA_GLOBALSINDEX); /* (sp += 1) 3 */ lua_setfield(L, -2, "__index"); /* { __index = _G } (sp -= 1) 2 */ lua_setmetatable(L, -2); /* setmetatable({}, {__index = _G}) (sp -= 1) 1 */ lua_newtable(L); /* __proxy = { } (sp += 1) 2 */ g_assert(lua_istable(L, -1)); q_p = lua_newuserdata(L, sizeof(GQueue *)); /* (sp += 1) 3 */ *q_p = st->injected.queries; /* * proxy.queries * * implement a queue * * - append(type, query) * - prepend(type, query) * - reset() * - len() and #proxy.queue * */ proxy_getqueuemetatable(L); lua_pushvalue(L, -1); /* meta.__index = meta */ lua_setfield(L, -2, "__index"); lua_setmetatable(L, -2); lua_setfield(L, -2, "queries"); /* proxy.queries = <userdata> */ /* * proxy.connection is (mostly) read-only * * .thread_id = ... thread-id against this server * .backend_id = ... index into proxy.global.backends[ndx] * */ con_p = lua_newuserdata(L, sizeof(con)); /* (sp += 1) */ *con_p = con; network_mysqld_con_getmetatable(L); lua_setmetatable(L, -2); /* tie the metatable to the udata (sp -= 1) */ lua_setfield(L, -2, "connection"); /* proxy.connection = <udata> (sp -= 1) */ /* * proxy.response knows 3 fields with strict types: * * .type = <int> * .errmsg = <string> * .resultset = { * fields = { * { type = <int>, name = <string > }, * { ... } }, * rows = { * { ..., ... }, * { ..., ... } } * } */ lua_newtable(L); #if 0 lua_newtable(L); /* the meta-table for the response-table (sp += 1) */ lua_pushcfunction(L, response_get); /* (sp += 1) */ lua_setfield(L, -2, "__index"); /* (sp -= 1) */ lua_pushcfunction(L, response_set); /* (sp += 1) */ lua_setfield(L, -2, "__newindex"); /* (sp -= 1) */ lua_setmetatable(L, -2); /* tie the metatable to response (sp -= 1) */ #endif lua_setfield(L, -2, "response"); lua_setfield(L, -2, "__proxy"); /* patch the _G.proxy to point here */ lua_getglobal(L, "proxy"); g_assert(lua_istable(L, -1)); if (0 == lua_getmetatable(L, -1)) { /* meta(_G.proxy) */ /* no metatable yet */ lua_newtable(L); } g_assert(lua_istable(L, -1)); lua_getfield(L, -3, "__proxy"); /* fenv.__proxy */ g_assert(lua_istable(L, -1)); lua_setfield(L, -2, "__index"); /* meta[_G.proxy].__index = fenv.__proxy */ lua_getfield(L, -3, "__proxy"); /* fenv.__proxy */ lua_setfield(L, -2, "__newindex"); /* meta[_G.proxy].__newindex = fenv.__proxy */ lua_setmetatable(L, -2); lua_pop(L, 1); /* _G.proxy */ g_assert(lua_isfunction(L, -2)); g_assert(lua_istable(L, -1)); lua_setfenv(L, -2); /* on the stack should be a modified env (sp -= 1) */ /* cache the script in this connection */ g_assert(lua_isfunction(L, -1)); lua_pushvalue(L, -1); /* run the script once to get the functions set in the global scope */ if (lua_pcall(L, 0, 0, 0) != 0) { g_critical("(lua-error) [%s]\n%s", lua_script, lua_tostring(L, -1)); lua_pop(L, 1); /* errmsg */ luaL_unref(sc->L, LUA_REGISTRYINDEX, st->L_ref); return REGISTER_CALLBACK_EXECUTE_FAILED; } st->L = L; g_assert(lua_isfunction(L, -1)); g_assert(lua_gettop(L) - stack_top == 1); return REGISTER_CALLBACK_SUCCESS; } /** * init the global proxy object */ void network_mysqld_lua_init_global_fenv(lua_State *L) { lua_newtable(L); /* my empty environment aka {} (sp += 1) */ #define DEF(x) \ lua_pushinteger(L, x); \ lua_setfield(L, -2, #x); DEF(PROXY_SEND_QUERY); DEF(PROXY_SEND_RESULT); DEF(PROXY_IGNORE_RESULT); DEF(MYSQLD_PACKET_OK); DEF(MYSQLD_PACKET_ERR); DEF(MYSQLD_PACKET_RAW); DEF(BACKEND_STATE_UNKNOWN); DEF(BACKEND_STATE_UP); DEF(BACKEND_STATE_DOWN); DEF(BACKEND_STATE_OFFLINE); DEF(BACKEND_TYPE_UNKNOWN); DEF(BACKEND_TYPE_RW); DEF(BACKEND_TYPE_RO); DEF(COM_SLEEP); DEF(COM_QUIT); DEF(COM_INIT_DB); DEF(COM_QUERY); DEF(COM_FIELD_LIST); DEF(COM_CREATE_DB); DEF(COM_DROP_DB); DEF(COM_REFRESH); DEF(COM_SHUTDOWN); DEF(COM_STATISTICS); DEF(COM_PROCESS_INFO); DEF(COM_CONNECT); DEF(COM_PROCESS_KILL); DEF(COM_DEBUG); DEF(COM_PING); DEF(COM_TIME); DEF(COM_DELAYED_INSERT); DEF(COM_CHANGE_USER); DEF(COM_BINLOG_DUMP); DEF(COM_TABLE_DUMP); DEF(COM_CONNECT_OUT); DEF(COM_REGISTER_SLAVE); DEF(COM_STMT_PREPARE); DEF(COM_STMT_EXECUTE); DEF(COM_STMT_SEND_LONG_DATA); DEF(COM_STMT_CLOSE); DEF(COM_STMT_RESET); DEF(COM_SET_OPTION); #if MYSQL_VERSION_ID >= 50000 DEF(COM_STMT_FETCH); #if MYSQL_VERSION_ID >= 50100 DEF(COM_DAEMON); #endif #endif DEF(MYSQL_TYPE_DECIMAL); #if MYSQL_VERSION_ID >= 50000 DEF(MYSQL_TYPE_NEWDECIMAL); #endif DEF(MYSQL_TYPE_TINY); DEF(MYSQL_TYPE_SHORT); DEF(MYSQL_TYPE_LONG); DEF(MYSQL_TYPE_FLOAT); DEF(MYSQL_TYPE_DOUBLE); DEF(MYSQL_TYPE_NULL); DEF(MYSQL_TYPE_TIMESTAMP); DEF(MYSQL_TYPE_LONGLONG); DEF(MYSQL_TYPE_INT24); DEF(MYSQL_TYPE_DATE); DEF(MYSQL_TYPE_TIME); DEF(MYSQL_TYPE_DATETIME); DEF(MYSQL_TYPE_YEAR); DEF(MYSQL_TYPE_NEWDATE); DEF(MYSQL_TYPE_ENUM); DEF(MYSQL_TYPE_SET); DEF(MYSQL_TYPE_TINY_BLOB); DEF(MYSQL_TYPE_MEDIUM_BLOB); DEF(MYSQL_TYPE_LONG_BLOB); DEF(MYSQL_TYPE_BLOB); DEF(MYSQL_TYPE_VAR_STRING); DEF(MYSQL_TYPE_STRING); DEF(MYSQL_TYPE_GEOMETRY); #if MYSQL_VERSION_ID >= 50000 DEF(MYSQL_TYPE_BIT); #endif /* cheat with DEF() a bit :) */ #define PROXY_VERSION PACKAGE_VERSION_ID DEF(PROXY_VERSION); #undef DEF /** * create * - proxy.global * - proxy.global.config */ lua_newtable(L); lua_newtable(L); lua_setfield(L, -2, "config"); lua_setfield(L, -2, "global"); lua_setglobal(L, "proxy"); } /** * handle the proxy.response.* table from the lua script * * proxy.response * .type can be either ERR, OK or RAW * .resultset (in case of OK) * .fields * .rows * .errmsg (in case of ERR) * .packet (in case of nil) * */ int network_mysqld_con_lua_handle_proxy_response(network_mysqld_con *con, const gchar *lua_script) { network_mysqld_con_lua_t *st = con->plugin_con_state; int resp_type = 1; const char *str; size_t str_len; lua_State *L = st->L; /** * on the stack should be the fenv of our function */ g_assert(lua_istable(L, -1)); lua_getfield(L, -1, "proxy"); /* proxy.* from the env */ g_assert(lua_istable(L, -1)); lua_getfield(L, -1, "response"); /* proxy.response */ if (lua_isnil(L, -1)) { g_message("%s.%d: proxy.response isn't set in %s", __FILE__, __LINE__, lua_script); lua_pop(L, 2); /* proxy + nil */ return -1; } else if (!lua_istable(L, -1)) { g_message("%s.%d: proxy.response has to be a table, is %s in %s", __FILE__, __LINE__, lua_typename(L, lua_type(L, -1)), lua_script); lua_pop(L, 2); /* proxy + response */ return -1; } lua_getfield(L, -1, "type"); /* proxy.response.type */ if (lua_isnil(L, -1)) { /** * nil is fine, we expect to get a raw packet in that case */ g_message("%s.%d: proxy.response.type isn't set in %s", __FILE__, __LINE__, lua_script); lua_pop(L, 3); /* proxy + nil */ return -1; } else if (!lua_isnumber(L, -1)) { g_message("%s.%d: proxy.response.type has to be a number, is %s in %s", __FILE__, __LINE__, lua_typename(L, lua_type(L, -1)), lua_script); lua_pop(L, 3); /* proxy + response + type */ return -1; } else { resp_type = lua_tonumber(L, -1); } lua_pop(L, 1); switch(resp_type) { case MYSQLD_PACKET_OK: { GPtrArray *fields = NULL; GPtrArray *rows = NULL; gsize field_count = 0; lua_getfield(L, -1, "resultset"); /* proxy.response.resultset */ if (lua_istable(L, -1)) { guint i; lua_getfield(L, -1, "fields"); /* proxy.response.resultset.fields */ g_assert(lua_istable(L, -1)); fields = network_mysqld_proto_fielddefs_new(); for (i = 1, field_count = 0; ; i++, field_count++) { lua_rawgeti(L, -1, i); if (lua_istable(L, -1)) { /** proxy.response.resultset.fields[i] */ MYSQL_FIELD *field; field = network_mysqld_proto_fielddef_new(); lua_getfield(L, -1, "name"); /* proxy.response.resultset.fields[].name */ if (!lua_isstring(L, -1)) { field->name = g_strdup("no-field-name"); g_warning("%s.%d: proxy.response.type = OK, " "but proxy.response.resultset.fields[%u].name is not a string (is %s), " "using default", __FILE__, __LINE__, i, lua_typename(L, lua_type(L, -1))); } else { field->name = g_strdup(lua_tostring(L, -1)); } lua_pop(L, 1); lua_getfield(L, -1, "type"); /* proxy.response.resultset.fields[].type */ if (!lua_isnumber(L, -1)) { g_warning("%s.%d: proxy.response.type = OK, " "but proxy.response.resultset.fields[%u].type is not a integer (is %s), " "using MYSQL_TYPE_STRING", __FILE__, __LINE__, i, lua_typename(L, lua_type(L, -1))); field->type = MYSQL_TYPE_STRING; } else { field->type = lua_tonumber(L, -1); } lua_pop(L, 1); field->flags = PRI_KEY_FLAG; field->length = 32; g_ptr_array_add(fields, field); lua_pop(L, 1); /* pop key + value */ } else if (lua_isnil(L, -1)) { lua_pop(L, 1); /* pop the nil and leave the loop */ break; } else { g_error("proxy.response.resultset.fields[%d] should be a table, but is a %s", i, lua_typename(L, lua_type(L, -1))); } } lua_pop(L, 1); rows = g_ptr_array_new(); lua_getfield(L, -1, "rows"); /* proxy.response.resultset.rows */ g_assert(lua_istable(L, -1)); for (i = 1; ; i++) { lua_rawgeti(L, -1, i); if (lua_istable(L, -1)) { /** proxy.response.resultset.rows[i] */ GPtrArray *row; gsize j; row = g_ptr_array_new(); /* we should have as many columns as we had fields */ for (j = 1; j < field_count + 1; j++) { lua_rawgeti(L, -1, j); if (lua_isnil(L, -1)) { g_ptr_array_add(row, NULL); } else { g_ptr_array_add(row, g_strdup(lua_tostring(L, -1))); } lua_pop(L, 1); } g_ptr_array_add(rows, row); lua_pop(L, 1); /* pop value */ } else if (lua_isnil(L, -1)) { lua_pop(L, 1); /* pop the nil and leave the loop */ break; } else { g_error("proxy.response.resultset.rows[%d] should be a table, but is a %s", i, lua_typename(L, lua_type(L, -1))); } } lua_pop(L, 1); network_mysqld_con_send_resultset(con->client, fields, rows); } else { guint64 affected_rows = 0; guint64 insert_id = 0; lua_getfield(L, -2, "affected_rows"); /* proxy.response.affected_rows */ if (lua_isnumber(L, -1)) { affected_rows = lua_tonumber(L, -1); } lua_pop(L, 1); lua_getfield(L, -2, "insert_id"); /* proxy.response.affected_rows */ if (lua_isnumber(L, -1)) { insert_id = lua_tonumber(L, -1); } lua_pop(L, 1); network_mysqld_con_send_ok_full(con->client, affected_rows, insert_id, 0x0002, 0); } /** * someone should cleanup */ if (fields) { network_mysqld_proto_fielddefs_free(fields); fields = NULL; } if (rows) { guint i; for (i = 0; i < rows->len; i++) { GPtrArray *row = rows->pdata[i]; guint j; for (j = 0; j < row->len; j++) { if (row->pdata[j]) g_free(row->pdata[j]); } g_ptr_array_free(row, TRUE); } g_ptr_array_free(rows, TRUE); rows = NULL; } lua_pop(L, 1); /* .resultset */ break; } case MYSQLD_PACKET_ERR: { gint errorcode = ER_UNKNOWN_ERROR; const gchar *sqlstate = "07000"; /** let's call ourself Dynamic SQL ... 07000 is "dynamic SQL error" */ lua_getfield(L, -1, "errcode"); /* proxy.response.errcode */ if (lua_isnumber(L, -1)) { errorcode = lua_tonumber(L, -1); } lua_pop(L, 1); lua_getfield(L, -1, "sqlstate"); /* proxy.response.sqlstate */ sqlstate = lua_tostring(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "errmsg"); /* proxy.response.errmsg */ if (lua_isstring(L, -1)) { str = lua_tolstring(L, -1, &str_len); network_mysqld_con_send_error_full(con->client, str, str_len, errorcode, sqlstate); } else { network_mysqld_con_send_error(con->client, C("(lua) proxy.response.errmsg is nil")); } lua_pop(L, 1); break; } case MYSQLD_PACKET_RAW: { guint i; /** * iterate over the packet table and add each packet to the send-queue */ lua_getfield(L, -1, "packets"); /* proxy.response.packets */ if (lua_isnil(L, -1)) { g_message("%s.%d: proxy.response.packets isn't set in %s", __FILE__, __LINE__, lua_script); lua_pop(L, 2 + 1); /* proxy + response + nil */ return -1; } else if (!lua_istable(L, -1)) { g_message("%s.%d: proxy.response.packets has to be a table, is %s in %s", __FILE__, __LINE__, lua_typename(L, lua_type(L, -1)), lua_script); lua_pop(L, 2 + 1); /* proxy + response + packets */ return -1; } for (i = 1; ; i++) { lua_rawgeti(L, -1, i); if (lua_isstring(L, -1)) { /** proxy.response.packets[i] */ str = lua_tolstring(L, -1, &str_len); network_mysqld_queue_append(con->client, con->client->send_queue, str, str_len); lua_pop(L, 1); /* pop value */ } else if (lua_isnil(L, -1)) { lua_pop(L, 1); /* pop the nil and leave the loop */ break; } else { g_error("%s.%d: proxy.response.packets should be array of strings, field %u was %s", __FILE__, __LINE__, i, lua_typename(L, lua_type(L, -1))); } } lua_pop(L, 1); /* .packets */ network_mysqld_queue_reset(con->client); /* reset the packet-id checks */ break; } default: g_message("proxy.response.type is unknown: %d", resp_type); lua_pop(L, 2); /* proxy + response */ return -1; } lua_pop(L, 2); return 0; }
gpl-2.0
mwhitlaw/openemr
phpmyadmin/lang/italian-iso-8859-1.inc.php
70896
<?php /* $Id$ */ /** * translated by: Pietro Danesi <danone at users.sourceforge.net> 2002-03-29 * Revised by: "DPhantom" <dphantom at users.sourceforge.net> 2002-04-16 * Revised by: "Luca Rebellato" <rebeluca at users.sourceforge.net> 2007-07-26 */ $charset = 'iso-8859-1'; $text_dir = 'ltr'; $number_thousands_separator = '.'; $number_decimal_separator = ','; // shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa $byteUnits = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'); $day_of_week = array('Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'); //italian days $month = array('Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'); //italian months // See http://www.php.net/manual/en/function.strftime.php to define the // variable below $datefmt = '%d %B, %Y at %I:%M %p'; //italian time $timespanfmt = '%s giorni, %s ore, %s minuti e %s secondi'; $strAbortedClients = 'Fallito'; $strAccessDenied = 'Accesso negato'; $strAccessDeniedCreateConfig = 'La ragione di questo è che probabilmente non hai creato alcun file di configurazione. Potresti voler usare %1$ssetup script%2$s per crearne uno.'; $strAccessDeniedExplanation = 'phpMyAdmin ha provato a connettersi al server MySQL, e il server ha rifiutato la connessione. Si dovrebbe controllare il nome dell\'host, l\'username e la password nel file config.inc.php ed assicurarsi che corrispondano alle informazioni fornite dall\'amministratore del server MySQL.'; $strAction = 'Azione'; $strAddAutoIncrement = 'Aggiungi valore AUTO_INCREMENT'; $strAddClause = 'Aggiungi %s'; $strAddConstraints = 'Aggiungi vincoli'; $strAddDeleteColumn = 'Aggiungi/Cancella campo'; $strAddDeleteRow = 'Aggiungi/Cancella criterio'; $strAddFields = 'Aggiungi %s campo(i)'; $strAddHeaderComment = 'Aggiunge un commento personalizzato all\'header (\\n per tornare a capo)'; $strAddIntoComments = 'Aggiungi nei commenti'; $strAddNewField = 'Aggiungi un nuovo campo'; $strAddPrivilegesOnDb = 'Aggiungi privilegi sul seguente database'; $strAddPrivilegesOnTbl = 'Aggiungi privilegi sulla seguente tabella'; $strAddSearchConditions = 'Aggiungi condizioni di ricerca (corpo della clausola "where"):'; $strAddToIndex = 'Aggiungi all\'indice&nbsp;%s&nbsp;colonna/e'; $strAddUser = 'Aggiungi un nuovo utente'; $strAddUserMessage = 'Hai aggiunto un nuovo utente.'; $strAdministration = 'Amministrazione'; $strAffectedRows = 'Righe interessate:'; $strAfter = 'Dopo %s'; $strAfterInsertBack = 'Indietro'; $strAfterInsertNewInsert = 'Inserisci un nuovo record'; $strAfterInsertNext = 'Modifica il record successivo'; $strAfterInsertSame = 'Torna a questa pagina'; $strAllowInterrupt = 'Permette di interrompere il processo di importazione nel caso lo script rilevi che è troppo vicino al tempo limite. Questo potrebbe essere un buon modo di importare grandi file, tuttavia potrebbe interrompere la transazione.'; $strAllTableSameWidth = 'mostra tutte le Tabelle con la stessa larghezza?'; $strAll = 'Tutti'; $strAlterOrderBy = 'Altera tabella ordinata per'; $strAnalyzeTable = 'Analizza tabella'; $strAnd = 'e'; $strAndThen = 'e quindi'; $strAngularLinks = 'Link angolari'; $strAnIndex = 'Un indice è stato aggiunto in %s'; $strAnyHost = 'Qualsiasi host'; $strAny = 'Qualsiasi'; $strAnyUser = 'Qualsiasi utente'; $strApproximateCount = 'Può essere approssimato. Vedere FAQ 3.11'; $strAPrimaryKey = 'Una chiave primaria è stata aggiunta in %s'; $strArabic = 'Arabo'; $strArmenian = 'Armeno'; $strAscending = 'Crescente'; $strAtBeginningOfTable = 'All\'inizio della tabella'; $strAtEndOfTable = 'Alla fine della tabella'; $strAttr = 'Attributi'; $strAutomaticLayout = 'Impaginazione automatica'; $strBack = 'Indietro'; $strBaltic = 'Baltico'; $strBeginCut = 'INIZIO CUT'; $strBeginRaw = 'INIZIO RAW'; $strBinary = 'Binario'; $strBinaryDoNotEdit = 'Tipo di dato Binario - non modificare'; $strBinaryLog = 'Log binario'; $strBinLogEventType = 'Tipo di evento'; $strBinLogInfo = 'Informazioni'; $strBinLogName = 'Nome del Log'; $strBinLogOriginalPosition = 'Posizione originale'; $strBinLogPosition = 'Posizione'; $strBinLogServerId = 'ID del server'; $strBookmarkAllUsers = 'Permetti ad ogni utente di accedere a questo bookmark'; $strBookmarkCreated = 'Segnalibro %s creato'; $strBookmarkDeleted = 'Il bookmark è stato cancellato.'; $strBookmarkLabel = 'Etichetta'; $strBookmarkQuery = 'Query SQL aggiunte ai preferiti'; $strBookmarkReplace = 'Sostituzione dei segnalibri esistenti con lo stesso nome'; $strBookmarkThis = 'Aggiungi ai preferiti questa query SQL'; $strBookmarkView = 'Visualizza solo'; $strBrowseDistinctValues = 'Naviga tra i valori DISTINCT'; $strBrowseForeignValues = 'Sfoglia le opzioni straniere'; $strBrowse = 'Mostra'; $strBufferPoolActivity = 'Attività del Buffer Pool'; $strBufferPool = 'Buffer Pool'; $strBufferPoolUsage = 'Utilizzo del Buffer Pool'; $strBufferReadMissesInPercent = 'Non letto in %'; $strBufferReadMisses = 'Non letto'; $strBufferWriteWaits = 'In attesa di scrittura'; $strBufferWriteWaitsInPercent = 'In attesa di scrittura in %'; $strBulgarian = 'Bulgaro'; $strBusyPages = 'Pagine occupate'; $strBzError = 'phpMyAdmin non è capace di comprimere il dump a causa dell\'estensione Bz2 errata in questa versione di PHP. Vi raccomandiamo vivamente di settare il parametro <code>$cfg[\'BZipDump\']</code> nel vostro file di configurazione di phpMyAdmin a <code>FALSE</code>. Se volete utilizzare le capacità di compressione Bz2, dovreste aggiornare il PHP all\'ultima versione. Date un\'occhiata al bug report %s per uteriori dettagli.'; $strBzip = '"compresso con bzip2"'; $strCalendar = 'Calendario'; $strCancel = 'Annulla'; $strCanNotLoadExportPlugins = 'Non posso caricare i plugins di esportazione. Controlla l\'installazione!'; $strCanNotLoadImportPlugins = 'Non posso caricare i plugins di importazione, controlla la tua configurazione!'; $strCannotLogin = 'Impossibile eseguire il login nel server MySQL'; $strCantLoad = 'Impossibile caricare l\'estensione %s,<br />prego controllare la configurazione di PHP'; $strCantLoadRecodeIconv = 'Impossibile caricare l\'estensione iconv o recode necessaria per la conversione del set di caratteri, configurare il PHP per permettere di utilizzare queste estenzioni o disabilitare la conversione dei set di caratteri in phpMyAdmin.'; $strCantRenameIdxToPrimary = 'Impossibile rinominare l\'indice a PRIMARIO!'; $strCantUseRecodeIconv = 'Impossibile utilizzare le funzioni iconv o libiconv o recode_string in quanto l\'estensione deve essere caricata. Controllare la configurazione del PHP.'; $strCardinality = 'Cardinalità'; $strCaseInsensitive = 'case-insensitive'; $strCaseSensitive = 'case-sensitive'; $strCentralEuropean = 'Europeo Centrale'; $strChangeCopyModeCopy = '... mantieni quello vecchio.'; $strChangeCopyMode = 'Crea un nuovo utente con gli stessi privilegi e ...'; $strChangeCopyModeDeleteAndReload = ' ... cancella quello vecchio dalla tabella degli utenti e in seguito ricarica i privilegi.'; $strChangeCopyModeJustDelete = ' ... cancella quello vecchio dalla tabella degli utenti.'; $strChangeCopyModeRevoke = ' ... revoca tutti i privilegi attivi da quello vecchio e in seguito cancellalo.'; $strChangeCopyUser = 'Cambia le Informazioni di Login / Copia Utente'; $strChangeDisplay = 'Scegli il campo da mostrare'; $strChange = 'Modifica'; $strChangePassword = 'Cambia password'; $strCharsetOfFile = 'Set di caratteri del file:'; $strCharsetsAndCollations = 'Set di Caratteri e Collations'; $strCharset = 'Set di caratteri'; $strCharsets = 'Set di caratteri'; $strCheckAll = 'Seleziona tutti'; $strCheckOverhead = 'Controllo addizionale'; $strCheckPrivs = 'Controlla i privilegi'; $strCheckPrivsLong = 'Controlla i privilegi per il database &quot;%s&quot;.'; $strCheckTable = 'Controlla tabella'; $strChoosePage = 'Prego scegliere una Page da modificare'; $strColComFeat = 'Visualizzazione commenti delle colonne'; $strCollation = 'Collation'; $strColumnNames = 'Nomi delle colonne'; $strColumnPrivileges = 'Privilegi relativi alle colonne'; $strCommand = 'Comando'; $strComments = 'Commenti'; $strCommentsForTable = 'Commenti per la tabella'; $strCompatibleHashing = 'Compatibile con MySQL 4.0'; $strCompleteInserts = 'Inserimenti completi'; $strCompression = 'Compressione'; $strCompressionWillBeDetected = 'Il tipo di compressione del file importato sarà automaticamente rilevato da: %s'; $strConfigDefaultFileError = 'Non posso leggere la configurazione da: "%1$s"'; $strConfigFileError = 'phpMyAdmin non riesce a leggere il file di configurazione!<br />Questo può accadere se il php trova un parse error in esso oppure il php non trova il file.<br />Richiamate il file di configurazione direttamente utilizzando il link sotto e leggete il/i messaggio/i di errore del php che ricevete. Nella maggior parte dei casi ci sono un apostrofo o una virgoletta mancanti.<br />Se ricevete una pagina bianca, allora è tutto a posto.'; $strConfigureTableCoord = 'Prego, configurare le coordinate per la tabella %s'; $strConnectionError = 'Impossibile connettersi: impostazioni non valide.'; $strConnections = 'Connessioni'; $strConstraintsForDumped = 'Limiti per le tabelle scaricate'; $strConstraintsForTable = 'Limiti per la tabella'; $strControluserFailed = 'Connessione per controluser come definito nella configurazione fallita.'; $strCookiesRequired = 'Da questo punto in poi, i cookies devono essere abilitati.'; $strCopy = 'Copia'; $strCopyDatabaseOK = 'Il Database %s è stato copiato in %s'; $strCopyTable = 'Copia la tabella nel (database<b>.</b>tabella):'; $strCopyTableOK = 'La tabella %s è stata copiata su %s.'; $strCopyTableSameNames = 'Impossibile copiare la tabella su se stessa!'; $strCouldNotKill = 'phpMyAdmin non è in grado di terminare il thread %s. Probabilmente è già stato terminato.'; $strCreate = 'Crea'; $strCreateDatabaseBeforeCopying = 'CREATE DATABASE prima di copiare'; $strCreateIndex = 'Crea un indice su&nbsp;%s&nbsp;columns'; $strCreateIndexTopic = 'Crea un nuovo indice'; $strCreateNewDatabase = 'Crea un nuovo database'; $strCreateNewTable = 'Crea una nuova tabella nel database %s'; $strCreatePage = 'Crea una nuova pagina'; $strCreatePdfFeat = 'Creazione di PDF'; $strCreateRelation = 'Crea relazioni'; $strCreateTable = 'Crea tabelle'; $strCreateUserDatabase = 'Database per l\'utente'; $strCreateUserDatabaseName = 'Crea un database con lo stesso nome e concedi tutti i privilegi'; $strCreateUserDatabaseNone = 'None'; $strCreateUserDatabaseWildcard = 'Concedi tutti i privilegi al nome con caratteri jolly (username\_%)'; $strCreationDates = 'Creazione/Aggiornamento/Controllo date'; $strCriteria = 'Criterio'; $strCroatian = 'Croato'; $strCSV = 'CSV'; $strCyrillic = 'Cirillico'; $strCzech = 'Ceco'; $strCzechSlovak = 'Ceco-Slovacco'; $strDanish = 'Danese'; $strDatabase = 'Database'; $strDatabaseEmpty = 'Il nome del DataBase è vuoto!'; $strDatabaseExportOptions = 'Opzioni di esportazione del database'; $strDatabaseHasBeenDropped = 'Il Database %s è stato eliminato.'; $strDatabases = 'Database'; $strDatabasesDropped = '%s databases sono stati cancellati correttamente.'; $strDatabasesStatsDisable = 'Disabilita le Statistiche'; $strDatabasesStatsEnable = 'Abilita le Statistiche'; $strDatabasesStatsHeavyTraffic = 'N.B.: Abilitare qui le statistiche del Database potrebbe causare del traffico intenso fra il server web e MySQL.'; $strDatabasesStats = 'Statistiche dei databases'; $strData = 'Dati'; $strDataDict = 'Data Dictionary'; $strDataOnly = 'Solo dati'; $strDataPages = 'Pagine contenenti dati'; $strDBComment = 'Commento al Database: '; $strDBCopy = 'Copia il Database in'; $strDbIsEmpty = 'Il databse sembra essere vuoto!'; $strDbPrivileges = 'Privilegi specifici al database'; $strDBRename = 'Rinomina il DataBase in'; $strDbSpecific = 'specifico del database'; $strDefaultEngine = '%s è il motore di memorizzazione predefinito su questo server MySQL.'; $strDefault = 'Predefinito'; $strDefaultValueHelp = 'Per i valori predefiniti, prego inserire un singolo valore, senza backslashes escaping o virgolette, utilizzando questo formato: a'; $strDefragment = 'Deframmenta la tabella'; $strDelayedInserts = 'Utilizza inserimenti ritardati'; $strDeleteAndFlush = 'Cancella gli utenti e dopo ricarica i privilegi.'; $strDeleteAndFlushDescr = 'Questa è la vita più giusta, ma il caricamento dei privilegi può durare qualche secondo.'; $strDeleted = 'La riga è stata cancellata'; $strDeletedRows = 'Righe cancellate:'; $strDelete = 'Elimina'; $strDeleteNoUsersSelected = 'Nessun utente selezionato per la cancellazione!'; $strDeleteRelation = 'Elimina relazione'; $strDeleting = 'Cancellazione in corso di %s'; $strDelimiter = 'Delimitatori'; $strDelOld = 'La Pagina corrente contiene Riferimenti a Tabelle che non esistono più. Volete cancellare questi Riferimenti?'; $strDescending = 'Decrescente'; $strDescription = 'Descrizione'; $strDesigner = 'Designer'; $strDesignerHelpDisplayField = 'Il campi da mostrare sono in colore rosa. Per impostare/togliere un campo come campo da mostrare, clicca l\'icona "Scegli il campo da mostrare", e poi clicca sul nome appropriato del campo.'; $strDictionary = 'dizionario'; $strDirectLinks = 'Link diretti'; $strDirtyPages = 'Pagine sporche'; $strDisabled = 'Disabilitata'; $strDisableForeignChecks = 'Disabilita i controlli sulle chiavi straniere'; $strDisplayFeat = 'Mostra Caratteristiche'; $strDisplayOrder = 'Ordine di visualizzazione:'; $strDisplayPDF = 'Mostra lo schema del PDF'; $strDoAQuery = 'Esegui "query da esempio" (carattere jolly: "%")'; $strDocSQL = 'DocSQL'; $strDocu = 'Documentazione'; $strDoYouReally = 'Confermi: '; $strDropDatabaseStrongWarning = 'Si sta per DISTRUGGERE COMPLETAMENTE un intero DataBase!'; $strDrop = 'Elimina'; $strDropUsersDb = 'Elimina i databases gli stessi nomi degli utenti.'; $strDumpingData = 'Dump dei dati per la tabella'; $strDumpSaved = 'Il dump è stato salvato sul file %s.'; $strDumpXRows = 'Dump di %s righe a partire dalla riga %s.'; $strDynamic = 'dinamico'; $strEdit = 'Modifica'; $strEditPDFPages = 'Modifica pagine PDF'; $strEditPrivileges = 'Modifica Privilegi'; $strEffective = 'Effettivo'; $strEmptyResultSet = 'MySQL ha restituito un insieme vuoto (i.e. zero righe).'; $strEmpty = 'Svuota'; $strEnabled = 'Abilitata'; $strEncloseInTransaction = 'Includi export in una transazione'; $strEndCut = 'FINE CUT'; $strEnd = 'Fine'; $strEndRaw = 'FINE RAW'; $strEngineAvailable = '%s è disponibile su questo server MySQL.'; $strEngineDisabled = '%s è stato disabilitato su questo server MySQL.'; $strEngines = 'Motori'; $strEngineUnsupported = 'Questo server MySQL non supporta il motore di memorizzazione %s.'; $strEnglish = 'Inglese'; $strEnglishPrivileges = 'Nota: i nomi dei privilegi di MySQL sono in Inglese'; $strError = 'Errore'; $strErrorInZipFile = 'Errore nell\'archivio ZIP:'; $strErrorRelationAdded = 'Errore: relazione non aggiunta.'; $strErrorRelationExists = 'Errore: relazione già esistente.'; $strErrorRenamingTable = 'Errore nel rinominare la tabella %1$s in %2$s'; $strErrorSaveTable = 'Errore nel salvare le coordinate per il Designer.'; $strEscapeWildcards = 'I caratteri jolly _ e % dovrebbero essere preceduti da un \ per l\'utilizzo letterale'; $strEsperanto = 'Esperanto'; $strEstonian = 'Estone'; $strEvent = 'Eventi'; $strExcelEdition = 'Edizione Excel'; $strExecuteBookmarked = 'Esegue la query dalle preferite'; $strExplain = 'Spiega SQL'; $strExport = 'Esporta'; $strExportImportToScale = 'Importa/esporta alla dimensione'; $strExportMustBeFile = 'Il tipo di esportazione selezionato necessita di essere salvato in un file!'; $strExtendedInserts = 'Inserimenti estesi'; $strExtra = 'Extra'; $strFailedAttempts = 'Tentativi falliti'; $strField = 'Campo'; $strFieldHasBeenDropped = 'Il campo %s è stato eliminato'; $strFieldInsertFromFileTempDirNotExists = 'Errore nello spostare il file caricato, vedi FAQ 1.11'; $strFields = 'Campi'; $strFieldsEnclosedBy = 'Campo composto da'; $strFieldsEscapedBy = 'Campo impedito da'; $strFieldsTerminatedBy = 'Campo terminato da'; $strFileAlreadyExists = 'Il file %s esiste già sul server: prego, cambiare nome del file o selezionare l\'opzione "sovrascrivi".'; $strFileCouldNotBeRead = 'Il file non può essere letto'; $strFileNameTemplateDescriptionDatabase = 'nome database'; $strFileNameTemplateDescription = 'Questo valore è interpretato usando %1$sstrftime%2$s, in questo modo puoi usare stringhe di formattazione per le date/tempi. Verranno anche aggiunte le seguenti trasformazioni: %3$s. Il testo rimanente resterà invariato.'; $strFileNameTemplateDescriptionServer = 'nome server'; $strFileNameTemplateDescriptionTable = 'nome tabella'; $strFileNameTemplate = 'Nome file template'; $strFileNameTemplateRemember = 'ricorda il template'; $strFiles = 'File'; $strFileToImport = 'File importato'; $strFixed = 'fisso'; $strFlushPrivilegesNote = 'N.B.: phpMyAdmin legge i privilegi degli utenti direttamente nella tabella dei privilegi di MySQL. Il contenuto di questa tabella può differire dai privilegi usati dal server se sono stati fatti cambiamenti manuali. In questo caso, Si dovrebbero %srinfrescare i privilegi%s prima di continuare.'; $strFlushQueryCache = 'Rinfresca la cache delle query'; $strFlushTable = 'Inizializza ("FLUSH") la tabella'; $strFlushTables = 'Rinfresca (chiudi) tutte le tabelle'; $strFontSize = 'Dimensione font'; $strForeignKeyError = 'Errore creando una foreign key (controlla il tipo di dati)'; $strFormat = 'Formato'; $strFormEmpty = 'Valore mancante nel form!'; $strFreePages = 'Pagine libere'; $strFullText = 'Testo completo'; $strFunction = 'Funzione'; $strFunctions = 'Funzioni'; $strGenBy = 'Generato da'; $strGeneralRelationFeat = 'Caratteristiche Generali di Relazione'; $strGenerate = 'Genera'; $strGeneratePassword = 'Genera Password'; $strGenTime = 'Generato il'; $strGeorgian = 'Georgiano'; $strGerman = 'Tedesco'; $strGlobal = 'globale'; $strGlobalPrivileges = 'Privilegi globali'; $strGlobalValue = 'Valore globale'; $strGo = 'Esegui'; $strGrantOption = 'Grant'; $strGreek = 'Greco'; $strGzip = '"compresso con gzip"'; $strHandler = 'Handler'; $strHasBeenAltered = 'è stato modificato.'; $strHasBeenCreated = 'è stato creato.'; $strHaveToShow = 'Devi scegliere almeno una Colonna da mostrare'; $strHebrew = 'Ebreo'; $strHelp = 'Aiuto'; $strHexForBLOB = 'Usa dati esadecimali per BLOB'; $strHide = 'Nascondi'; $strHideShowAll = 'Mostra/nascondi tutto'; $strHideShowNoRelation = 'Mostra/nascondi tabella senza relazioni'; $strHome = 'Home'; $strHomepageOfficial = 'Home page ufficiale di phpMyAdmin'; $strHostEmpty = 'Il nome di host è vuoto!'; $strHost = 'Host'; $strHTMLExcel = 'Microsoft Excel 2000'; $strHTMLWord = 'Microsoft Word 2000'; $strHungarian = 'Ungherese'; $strIcelandic = 'Islandese'; $strId = 'ID'; $strIdxFulltext = 'Testo completo'; $strIEUnsupported = 'Internet explorer non supporta questa funzione.'; $strIgnoreDuplicates = 'Ignora le righe duplicate'; $strIgnore = 'Ignora'; $strIgnoreInserts = 'Utilizza gli IGNORE INSERTS'; $strImportExportCoords = 'Importa/esporta le coordinate per PDF schema'; $strImportFiles = 'Importa file'; $strImportFormat = 'Formato del file importato'; $strImport = 'Importa'; $strImportSuccessfullyFinished = 'Importazione eseguita con successo, %d query eseguite.'; $strIndexes = 'Indici'; $strIndexesSeemEqual = 'I seguenti indici sembrano essere uguali e uno di essi deve essere rimosso:'; $strIndexHasBeenDropped = 'L\'indice %s è stato eliminato'; $strIndex = 'Indice'; $strIndexName = 'Nome dell\'indice&nbsp;:'; $strIndexType = 'Tipo di indice&nbsp;:'; $strIndexWarningTable = 'Problemi con gli indici della tabella `%s`'; $strInnoDBAutoextendIncrementDesc = ' La dimensione di incremento per aumentare la dimensione di una tabella autoextending quando diventa piena.'; $strInnoDBAutoextendIncrement = 'Incremento autoextend'; $strInnoDBBufferPoolSizeDesc = 'La dimensione del buffer di memoria InnoDB cacha dati e indici delle proprie tabelle.'; $strInnoDBBufferPoolSize = 'Dimensione del Buffer pool'; $strInnoDBDataFilePath = 'File dati'; $strInnoDBDataHomeDirDesc = 'La parte comune del path della directory per tutti i file dati InnoDB.'; $strInnoDBDataHomeDir = 'Home directory dei dati'; $strInnoDBPages = 'pagine'; $strInnoDBRelationAdded = 'Aggiunta relazione InnoDB'; $strInnodbStat = 'Stato InnoDB'; $strInsecureMySQL = 'Il file di configurazione in uso contiene impostazioni (root con nessuna password) che corrispondono ai privilegi dell\'account MySQL predefinito. Un server MySQL funzionante con queste impostazioni è aperto a intrusioni, e si dovrebbe realmente riparare a questa falla nella sicurezza.'; $strInsertAsNewRow = 'Inserisci come nuova riga'; $strInsertedRowId = 'Inserito id riga:'; $strInsertedRows = 'Righe inserite:'; $strInsert = 'Inserisci'; $strInternalNotNecessary = '* Non è necessaria una relazione interna quando già esiste in InnoDB.'; $strInternalRelationAdded = 'Aggiunte relazioni internet'; $strInternalRelations = 'Relazioni interne'; $strInUse = 'in uso'; $strInvalidAuthMethod = 'Metodo di autenticazione settato nella configurazione non valido:'; $strInvalidColumn = 'Colonna specificata (%s) invalida!'; $strInvalidColumnCount = 'Il contatore delle colonne deve essere superiore a 0.'; $strInvalidCSVFieldCount = 'Contatore di campo non valido nell\'input CSV alla linea %d.'; $strInvalidCSVFormat = 'Formato non valido per l\'input CSV alla linea %d.'; $strInvalidCSVParameter = 'Parametro non valido per importazione CSV: %s'; $strInvalidDatabase = 'Database non valido'; $strInvalidFieldAddCount = 'Deviaggiungere come minimo un campo.'; $strInvalidFieldCount = 'la tabella deve avere come minimo un dato.'; $strInvalidLDIImport = 'Questo plugin non supporta importazioni di dati compressi!'; $strInvalidRowNumber = '%d non è un numero valido di righe.'; $strInvalidServerHostname = 'Nome host per il server %1$s non valido. Controlla la tua configurazione.'; $strInvalidServerIndex = 'Server index non valido: "%s"'; $strInvalidTableName = 'Nome tabella non valido'; $strJapanese = 'Giapponese'; $strJoins = 'Joins'; $strJumpToDB = 'Passa al database &quot;%s&quot;.'; $strJustDelete = 'Cancella soltanto gli utenti dalle tabelle dei privilegi.'; $strJustDeleteDescr = 'Gli utenti &quot;cancellati&quot; saranno ancora in grado di accedere al servercome al solito finché i privilegi non verraanno ricaricati.'; $strKeepPass = 'Non cambiare la password'; $strKeyCache = 'Key cache'; $strKeyname = 'Nome chiave'; $strKill = 'Rimuovi'; $strKnownExternalBug = 'La %s funzionalità è affetta da un bug noto, vedi %s'; $strKorean = 'Coreano'; $strLandscape = 'Orizzontale'; $strLanguage = 'Lingua'; $strLanguageUnknown = 'Lingua non conosciuta : %1$s.'; $strLatchedPages = 'Latched pages'; $strLatexCaption = 'Sottotitolo della tabella'; $strLatexContent = 'Contenuto della tabella __TABLE__'; $strLatexContinuedCaption = 'Sottotitolo della tabella continuato'; $strLatexContinued = '(continua)'; $strLatexIncludeCaption = 'Includi sottotitolo della tabella'; $strLatexLabel = 'Chiave etichetta'; $strLaTeX = 'LaTeX'; $strLatexStructure = 'Struttura della tabella __TABLE__'; $strLatvian = 'Lituano'; $strLDI = 'CSV usando LOAD DATA'; $strLDILocal = 'Usa LOCAL keyword'; $strLengthSet = 'Lunghezza/Set*'; $strLimitNumRows = 'record per pagina'; $strLinesTerminatedBy = 'Linee terminate da'; $strLinkNotFound = 'Link non trovato'; $strLinksTo = 'Collegamenti a'; $strLithuanian = 'Lituano'; $strLocalhost = 'Locale'; $strLocationTextfile = 'Percorso del file'; $strLogin = 'Connetti'; $strLoginInformation = 'Informazioni di Login'; $strLogout = 'Disconnetti'; $strLogPassword = 'Password:'; $strLogServer = 'Server'; $strLogUsername = 'Nome utente:'; $strLongOperation = 'Questa operazione potrebbe impiegare molto tempo. Procedere comunque?'; $strMaxConnects = 'max. connessioni contemporanee'; $strMaximalQueryLength = 'Lunghezza massima di una query creata'; $strMaximumSize = 'Dimensione massima: %s%s'; $strMbExtensionMissing = 'L\'estensione PHP mbstring non è stata trovata e sembra che si stia utilizzando un set di caratteri multibyte. Senza l\'estensione mbstring, phpMyAdmin non è in grado di dividere correttamente le stringhe di caratteri e questo può portare a risultati inaspettati.'; $strMbOverloadWarning = 'Avete abilitato mbstring.func_overload nella configurazione del PHP. Questa opzione è incompatibile con phpMyAdmin e potrebbe causare la corruzione di alcuni dati!'; $strMIME_available_mime = 'Tipi-MIME disponibili'; $strMIME_available_transform = 'Trasformazioni disponibili'; $strMIME_description = 'Descrizione'; $strMIME_MIMEtype = 'tipo MIME'; $strMIME_nodescription = 'Nessuna descrizione è disponibile per questa trasformazione.<br />Prego, chiedere all\'autore cosa %s faccia.'; $strMIME_transformation_note = 'Per una lista di opzioni di trasformazione disponibili e le loro rispettive trasformazioni di tipi-MIME, cliccate su %strasformazione descrizioni%s'; $strMIME_transformation_options_note = 'Prego, immettere i valori per le opzioni di trasformazioneutilizzando questo formato: \'a\', 100, b,\'c\'...<br />Se c\'è la necessità di immettere un backslash ("\") o un apostrofo ("\'") tra questi valori, essi vanno backslashati (per es. \'\\\\xyz\' or \'a\\\'b\').'; $strMIME_transformation_options = 'Opzioni di Transformation'; $strMIME_transformation = 'Trasformazione del Browser'; $strMIMETypesForTable = 'MIME TYPES FOR TABLE'; $strMIME_without = 'Tipi-MIME stampati in italics non hanno una funzione di trasformazione separata'; $strModifications = 'Le modifiche sono state salvate'; $strModifyIndexTopic = 'Modifica un indice'; $strModify = 'Modifica'; $strMoveMenu = 'Muovi menù'; $strMoveTableOK = 'La tabella %s è stata spostata in %s.'; $strMoveTableSameNames = 'Impossibile spostare la tabella su se stessa!'; $strMoveTable = 'Sposta la tabella nel (database<b>.</b>tabella):'; $strMultilingual = 'multilingua'; $strMyISAMDataPointerSizeDesc = 'Dimensione del puntatore predefinito in Bytes, che deve essere usata da CREATE TABLE per le tabelle MyISAM quando non è stata specificata l\'opzione MAX_ROWS.'; $strMyISAMDataPointerSize = 'Domensione del puntatore dati'; $strMyISAMMaxExtraSortFileSizeDesc = 'Se il file temporaneo è usato per la creazione veloce di un indice MyISAM, occuperebbe più spazio dell\'utilizzo del metodo key cache con la quantità ivi specificata: perciò si deve prediligere il metodo key cache.'; $strMyISAMMaxExtraSortFileSize = 'Dimensione massima per i file temporanei nella creazione di un indice'; $strMyISAMMaxSortFileSizeDesc = 'La dimensione massima dei file temporanei MySQL può essere utilizzata nella rigenerazione di un indice MyISAM (durante un REPAIR TABLE, ALTER TABLE, o LOAD DATA INFILE).'; $strMyISAMMaxSortFileSize = 'Dimensione massima dei file temporanei di ordinamento'; $strMyISAMRecoverOptionsDesc = 'La modalità di irppristino automatico di tabelle MyISAM corrotte, come impostato tramite l\'opzione di lan cio del server --myisam-recover.'; $strMyISAMRecoverOptions = 'Modalità di ripristino automatico'; $strMyISAMRepairThreadsDesc = 'Se questo valore è maggiore di 1, gli indici della tabella MyISAM vengono creati in parallelo (ogni indice nel suo thread) durante il processo di ordinamento Repair by.'; $strMyISAMRepairThreads = 'Thread di riparazione'; $strMyISAMSortBufferSizeDesc = 'Il buffer che viene allocato nell\'ordinamento degli indici MyISAM durante un REPAIR TABLE o nella creazione degli indici con CREATE INDEX o ALTER TABLE.'; $strMyISAMSortBufferSize = 'Ordina la dimensione del buffer'; $strMySQLCharset = 'Set di caratteri MySQL'; $strMysqlClientVersion = 'Versione MySQL client'; $strMySQLConnectionCollation = 'collazione della connessione di MySQL'; $strMysqlLibDiffersServerVersion = 'Le tue librerie di PHP per MySQL versione %s sono diverse dalla versione di MySQL server %s. Potrebbe causare comportamenti imprevedibili.'; $strMySQLSaid = 'Messaggio di MySQL: '; $strMySQLShowProcess = 'Visualizza processi in esecuzione'; $strMySQLShowStatus = 'Visualizza informazioni di runtime di MySQL'; $strMySQLShowVars = 'Visualizza variabili di sistema di MySQL'; $strName = 'Nome'; $strNext = 'Prossimo'; $strNoActivity = 'Nessuna attività da %s secondi o più, si prega di autenticarsi nuovamente'; $strNoDatabases = 'Nessun database'; $strNoDatabasesSelected = 'Nessun database selezionato.'; $strNoDataReceived = 'Non sono stati ricevuti dati da importare. O non è stato indicato alcun nome file, oppure è stato superata la dimensione massima consentita per il file, impostata nella configurazione di PHP. Vedi FAQ 1.16.'; $strNoDescription = 'nessuna Description'; $strNoDetailsForEngine = 'Non è disponibile nessuna informazione dettagliata sullo stato di questo motore di memorizzazione.'; $strNoDropDatabases = 'I comandi "DROP DATABASE" sono disabilitati.'; $strNoExplain = 'Non Spiegare SQL'; $strNoFilesFoundInZip = 'Non sono stati trovati file ZIP all\'interno dell\'archivio!'; $strNoFrames = 'phpMyAdmin funziona meglio con browser che supportano frames'; $strNoIndex = 'Nessun indice definito!'; $strNoIndexPartsDefined = 'Nessuna parte di indice definita!'; $strNoModification = 'Nessun cambiamento'; $strNone = 'Nessuno'; $strNo = ' No '; $strNoOptions = 'Questo formato non ha opzioni'; $strNoPassword = 'Nessuna Password'; $strNoPermission = 'Il server web non possiede i privilegi per salvare il file %s.'; $strNoPhp = 'senza codice PHP'; $strNoPrivileges = 'Nessun Privilegio'; $strNoRights = 'Non hai i permessi per effettuare questa operazione!'; $strNoRowsSelected = 'Nessuna riga selezionata'; $strNoSpace = 'Spazio insufficiente per salvare il file %s.'; $strNoTablesFound = 'Non ci sono tabelle nel database.'; $strNoThemeSupport = 'Nessun supporto per i temi, si prega di controllare la configurazione e/o i temi nella cartella %s.'; $strNotNumber = 'Questo non è un numero!'; $strNotOK = 'non OK'; $strNotSet = '<b>%s</b> tabella non trovata o non settata in %s'; $strNoUsersFound = 'Nessun utente trovato.'; $strNoValidateSQL = 'Non Validare SQL'; $strNull = 'Null'; $strNumberOfFields = 'Numero di campi'; $strNumberOfTables = 'Numero di tabelle'; $strNumSearchResultsInTable = '%s corrisponde/ono nella tabella <i>%s</i>'; $strNumSearchResultsTotal = '<b>Totale:</b> <i>%s</i> corrispondenza/e'; $strNumTables = 'Tabelle'; $strOK = 'OK'; $strOpenDocumentSpreadsheet = 'Foglio di calcolo nel formato Open Document'; $strOpenDocumentText = 'Testo nel formato Open Document'; $strOpenNewWindow = 'Apri una nuova finestra di PhpMyAdmin'; $strOperations = 'Operazioni'; $strOperator = 'Operatore'; $strOptimizeTable = 'Ottimizza tabella'; $strOptions = 'Opzioni'; $strOr = 'Oppure'; $strOverhead = 'In eccesso'; $strOverwriteExisting = 'Sovrascrivi file(s) esistente/i'; $strPageNumber = 'Numero pagina:'; $strPagesToBeFlushed = 'Pagine che devono essere flushate'; $strPaperSize = 'Dimensioni carta'; $strPartialImport = 'Importazione parziale'; $strPartialText = 'Testo parziale'; $strPasswordChanged = 'La password per l\'utente %s è cambiata con successo.'; $strPasswordEmpty = 'La password è vuota!'; $strPasswordHashing = 'Password Hashing'; $strPasswordNotSame = 'La password non coincide!'; $strPassword = 'Password'; $strPdfDbSchema = 'Schema del database "%s" - Pagina %s'; $strPdfInvalidTblName = 'La tabella "%s" non esiste!'; $strPdfNoTables = 'Nessuna Tabella'; $strPDF = 'PDF'; $strPDFReportExplanation = '(Genera un report contenete i dati di una singola tabella)'; $strPDFReportTitle = 'Titolo del Report'; $strPerHour = 'all\'ora'; $strPerMinute = 'al minuto'; $strPerSecond = 'al secondo'; $strPersian = 'Persiano'; $strPhoneBook = 'rubrica'; $strPHP40203 = 'Si sta utilizzando PHP 4.2.3, che presenta un serio bug con le stringhe multi-byte (mbstring). Vedi report PHP 19404. Questa versione di PHP non è raccomandata per l\'utilizzo con phpMyAdmin.'; $strPhp = 'Crea il codice PHP'; $strPHPVersion = 'Versione PHP'; $strPleaseSelectPrimaryOrUniqueKey = 'Seleziona la chiave primaria o una chiave univoca'; $strPmaDocumentation = 'Documentazione di phpMyAdmin'; $strPmaUriError = 'La direttiva <tt>$cfg[\'PmaAbsoluteUri\']</tt> DEVE essere impostata nel file di configurazione!'; $strPmaWiki = 'phpMyAdmin wiki'; $strPolish = 'Polacco'; $strPortrait = 'Verticale'; $strPos1 = 'Inizio'; $strPrevious = 'Precedente'; $strPrimaryKeyHasBeenDropped = 'La chiave primaria è stata eliminata'; $strPrimaryKeyName = 'Il nome della chiave primaria deve essere... PRIMARY!'; $strPrimaryKeyWarning = '("PRIMARY" <b>deve</b> essere il nome di, e <b>solo di</b>, una chiave primaria!)'; $strPrimary = 'Primaria'; $strPrint = 'Stampa'; $strPrintViewFull = 'Vista stampa (con full text)'; $strPrintView = 'Visualizza per stampa'; $strPrivDescAllPrivileges = 'Comprende tutti i privilegi tranne GRANT.'; $strPrivDescAlter = 'Permette di alterare la struttura di tabelle esistenti.'; $strPrivDescAlterRoutine = 'Permette l\'alterazione e l\'eliminazione di routines memorizzate.'; $strPrivDescCreateDb = 'Permette di creare nuove tabelle e nuovi databases.'; $strPrivDescCreateRoutine = 'Permette la creazione di routines memorizzate.'; $strPrivDescCreateTbl = 'Permette di creare nuove tabelle.'; $strPrivDescCreateTmpTable = 'Permette di creare tabelle temporanee.'; $strPrivDescCreateUser = 'Permette di creare, cancellare e rinominare gli account utente.'; $strPrivDescCreateView = 'Permette la creazione di nuove viste.'; $strPrivDescDelete = 'Permette di cancellare dati.'; $strPrivDescDropDb = 'Permette di eliminare databases e tabelle.'; $strPrivDescDropTbl = 'Permette di eliminare tabelle.'; $strPrivDescExecute5 = 'Permette l\'esecuzione di routines memorizzate.'; $strPrivDescExecute = 'Permette di eseguire procedure memorizzate; Non ha effetto in questa versione di MySQL.'; $strPrivDescFile = 'Permette di importare dati da e esportare dati in file.'; $strPrivDescGrant = 'Permette di aggiungere utenti e privilegi senza ricaricare le tabelle dei privilegi.'; $strPrivDescIndex = 'Permette di creare ed eliminare gli indici.'; $strPrivDescInsert = 'Permette di inserire e sovrascrivere dati.'; $strPrivDescLockTables = 'Permette di bloccare le tabelle per il thread corrente.'; $strPrivDescMaxConnections = 'Limita il numero di nuove connessioni che un utente può aprire in un\'ora.'; $strPrivDescMaxQuestions = 'Limita il numero di query che un utente può mandare al server in un\'ora.'; $strPrivDescMaxUpdates = 'Limita il numero di comandi che possono cambiare una tabella o un database che un utente può eseguire in un\'ora.'; $strPrivDescMaxUserConnections = 'Limite di connessioni simultanee che un utente può fare.'; $strPrivDescProcess3 = 'Permette di killare i processi di altri utenti.'; $strPrivDescProcess4 = 'Permette di vedere le query complete nella lista dei processi.'; $strPrivDescReferences = 'Non ha alcun effetto in questa versione di MySQL.'; $strPrivDescReload = 'Permette di ricaricare i parametri del server e di resettare la cache del server.'; $strPrivDescReplClient = 'Accorda il diritto ad un utente di domandare dove sono i masters/slaves.'; $strPrivDescReplSlave = 'Necessario per la replicazione degli slaves.'; $strPrivDescSelect = 'Permette di leggere i dati.'; $strPrivDescShowDb = 'Accorda l\'accesso alla lista completa dei databases.'; $strPrivDescShowView = 'Permette di effettuare query del tipo SHOW CREATE VIEW.'; $strPrivDescShutdown = 'Permette di chiudere il server.'; $strPrivDescSuper = 'Permette altre connessioni, anche se è stato raggiunto il massimo numero di connessioni; Necessario per molte operazioni di amministrazione come il settaggio di variabili globali o la cancellazione dei threads di altri utenti.'; $strPrivDescUpdate = 'Permette di cambiare i dati.'; $strPrivDescUsage = 'Nessun privilegio.'; $strPrivileges = 'Privilegi'; $strPrivilegesReloaded = 'I privilegi sono stati ricaricati con successo.'; $strProcedures = 'Procedure'; $strProcesses = 'Processi'; $strProcesslist = 'Lista Processi'; $strProfiling = 'Profiling'; $strProtocolVersion = 'Versione protocollo'; $strPutColNames = 'Mette i nomi delle colonne alla prima riga'; $strQBEDel = 'Elimina'; $strQBEIns = 'Aggiungi'; $strQBE = 'Query da esempio'; $strQueryCache = 'Cache delle query'; $strQueryFrame = 'Finestra della Query'; $strQueryOnDb = 'SQL-query sul database <b>%s</b>:'; $strQueryResultsOperations = 'Risultato delle operazioni di Query'; $strQuerySQLHistory = 'Storico dell\'SQL'; $strQueryStatistics = '<b>Query delle Statistiche</b>: Dall\'avvio, %s query sono state effettuate sul server.'; $strQueryTime = 'La query ha impiegato %01.4f sec'; $strQueryType = 'Tipo di Query'; $strQueryWindowLock = 'Non sovrascrivere questa query da fuori della finestra'; $strReadRequests = 'Richieste di lettura'; $strReceived = 'Ricevuti'; $strRecommended = 'raccomandato'; $strRecords = 'Record'; $strReferentialIntegrity = 'Controlla l\'integrità delle referenze:'; $strRefresh = 'Aggiorna'; $strRelationalSchema = 'Schema relazionale'; $strRelationDeleted = 'Relazione cancellata'; $strRelationNotWorking = 'Le caratteristiche aggiuntive sono state disattivate per funzionare con le tabelle linkate. Per scoprire perché clicca %squi%s.'; $strRelationsForTable = 'RELATIONS FOR TABLE'; $strRelations = 'Relazioni'; $strRelationView = 'Vedi relazioni'; $strReloadingThePrivileges = 'Caricamento dei privilegi in corso'; $strReloadPrivileges = 'Ricarica i privilegi'; $strReload = 'Ricarica'; $strRemoveSelectedUsers = 'Rimuove gli utenti selezionati'; $strRenameDatabaseOK = 'Il DataBase %s è stato rinominato in %s'; $strRenameTableOK = 'La tabella %s è stata rinominata %s'; $strRenameTable = 'Rinomina la tabella in'; $strRepairTable = 'Ripara tabella'; $strReplaceNULLBy = 'Sostituisci NULL con'; $strReplaceTable = 'Sostituisci i dati della tabella col file'; $strReplication = 'Replicazione'; $strReset = 'Riavvia'; $strResourceLimits = 'Limiti di risorse'; $strRestartInsertion = 'Riprendi inserimento con la riga %s'; $strReType = 'Reinserisci'; $strRevokeAndDeleteDescr = 'Gli utenti UTILIZZERANNO comunque il privilegio finché i privilegi non saranno ricaricati.'; $strRevokeAndDelete = 'Revoca tutti i privilegi attivi agli utenti e dopo li cancella.'; $strRevokeMessage = 'Hai revocato i privilegi per %s'; $strRevoke = 'Revoca'; $strRomanian = 'Rumeno'; $strRoutineReturnType = 'Tipo di risultato'; $strRoutines = 'Routines'; $strRowLength = 'Lunghezza riga'; $strRowsFrom = 'righe a partire da'; $strRowSize = 'Dimensione riga'; $strRowsModeFlippedHorizontal = 'orizzontale (headers ruotati)'; $strRowsModeHorizontal = ' orizzontale '; $strRowsModeOptions = ' in modalità %s e ripeti gli headers dopo %s celle '; $strRowsModeVertical = ' verticale '; $strRows = 'Righe'; $strRowsStatistic = 'Statistiche righe'; $strRunning = 'in esecuzione su %s'; $strRunQuery = 'Invia Query'; $strRunSQLQuery = 'Esegui la/e query SQL sul database %s'; $strRunSQLQueryOnServer = 'Eseguendo query SQL sul server %s'; $strRussian = 'Russo'; $strSaveOnServer = 'Salva sul server nella directory %s'; $strSavePosition = 'Salva la posizione'; $strSave = 'Salva'; $strScaleFactorSmall = 'Il fattore di scala è troppo piccolo per riempire lo schema nella pagina'; $strSearch = 'Cerca'; $strSearchFormTitle = 'Cerca nel database'; $strSearchInTables = 'Nella/e tabella/e:'; $strSearchNeedle = 'parola/e o valore/i da cercare (carattere jolly: "%"):'; $strSearchOption1 = 'almeno una delle parole'; $strSearchOption2 = 'tutte le parole'; $strSearchOption3 = 'la frase esatta'; $strSearchOption4 = 'come espressione regolare'; $strSearchResultsFor = 'Cerca i risultati per "<i>%s</i>" %s:'; $strSearchType = 'Trova:'; $strSecretRequired = 'Adesso c\'è bisogno di una password per il file di configurazione (blowfish_secret).'; $strSelectADb = 'Prego, selezionare un database'; $strSelectAll = 'Seleziona Tutto'; $strSelectBinaryLog = 'Selezionare il log binario da visualizzare'; $strSelectFields = 'Seleziona campi (almeno uno):'; $strSelectForeignKey = 'Seleziona Foreign Key'; $strSelectNumRows = 'nella query'; $strSelectReferencedKey = 'Seleziona le chiavi referenziali'; $strSelectTables = 'Seleziona Tables'; $strSend = 'Salva con nome...'; $strSent = 'Spediti'; $strServerChoice = 'Scelta del server'; $strServerNotResponding = 'Il server non risponde'; $strServer = 'Server'; $strServers = 'Servers'; $strServerStatusDelayedInserts = 'Inserimento ritardato'; $strServerStatus = 'Informazioni di Runtime'; $strServerStatusUptime = 'Questo server MySQL sta girando da %s. E\' stato avviato il %s.'; $strServerTabVariables = 'Variabili'; $strServerTrafficNotes = '<b>Traffico del server</b>: Queste tabelle mostrano le statistiche del traffico di retedi questo server MySQL dal momento del suo avvio.'; $strServerVars = 'Variabili e parametri del Server'; $strServerVersion = 'Versione MySQL'; $strSessionStartupErrorGeneral = 'Non posso far partire la sessione senza errori, controlla gli errori nel log di PHP e/o del tuo server web e configura correttamente la tua installazione di PHP.'; $strSessionValue = 'Valore sessione'; $strSetEnumVal = 'Se il tipo di campo è "enum" o "set", immettere i valori usando il formato: \'a\',\'b\',\'c\'...<br />Se comunque dovete mettere dei backslashes ("\") o dei single quote ("\'") davanti a questi valori, backslashateli (per esempio \'\\\\xyz\' o \'a\\\'b\').'; $strShowAll = 'Mostra tutti'; $strShowColor = 'Mostra il colore'; $strShowDatadictAs = 'Formato del Data Dictionary'; $strShowFullQueries = 'Mostra query complete'; $strShowGrid = 'Mostra la griglia'; $strShowHideLeftMenu = 'Mostra/nascondi il menù di sinistra'; $strShowingBookmark = 'Mostrando i segnalibri'; $strShowingPhp = 'Mostrando il codice PHP'; $strShowingRecords = 'Visualizzazione record '; $strShowingSQL = 'Mostrando la query SQL'; $strShow = 'Mostra'; $strShowOpenTables = 'Mostra le tabelle aperte'; $strShowPHPInfo = 'Mostra le info sul PHP'; $strShowSlaveHosts = 'Mostra gli hosts slave'; $strShowSlaveStatus = 'Mostra lo stato degli slave'; $strShowStatusBinlog_cache_disk_useDescr = 'Il numero delle transazioni che usano la cache temporanea del log binario, ma che oltrepassano il valore di binlog_cache_size e usano un file temporaneo per salvare gli statements dalle transazioni.'; $strShowStatusBinlog_cache_useDescr = 'Il numero delle transazioni che usano la cache temporanea del log binario.'; $strShowStatusCreated_tmp_disk_tablesDescr = 'Il numero delle tabelle temporanee create automaticamente sul disco dal server mentre esegue i comandi. Se il valore Created_tmp_disk_tables è grande, potresti voler aumentare il valore tmp_table_size, per fare im modo che le tabelle temporanee siano memory-based anzichè disk-based.'; $strShowStatusCreated_tmp_filesDescr = 'Numero di file temporanei che mysqld ha creato.'; $strShowStatusCreated_tmp_tablesDescr = 'Il numero di tabelle temporanee create automaticamente in memoria dal server durante l\'esecuzione dei comandi.'; $strShowStatusDelayed_errorsDescr = 'Numero di righe scritte con INSERT DELAYED in cui ci sono stati degli errori (probabilmete chiave dublicata).'; $strShowStatusDelayed_insert_threadsDescr = 'Il numero di processi INSERT DELAYED in uso. Ciascuna tabella su cui è usato INSERT DELAYED occupa un thread.'; $strShowStatusDelayed_writesDescr = 'Il numero di righe INSERT DELAYED scritte.'; $strShowStatusFlush_commandsDescr = 'Il numero di comandi FLUSH eseguiti.'; $strShowStatusHandler_commitDescr = 'Il numero di comandi interni COMMIT eseguiti.'; $strShowStatusHandler_deleteDescr = 'Il numero di volte in cui una riga è stata cancellata da una tabella.'; $strShowStatusHandler_discoverDescr = 'Il server MySQL può chiedere al motore di storage NDB Cluster se conosce una tabella sulla base di un nome dato. Questo è chaiamto discovery. Handler_discover indica il numero di volte che una tabella è stata trovata.'; $strShowStatusHandler_read_firstDescr = 'Il numero di volte che il primo valore è stato letto da un indice. Se è troppo alto è probabile che il server stia facendo molte scansioni complete degli indici; per esempio, SELECT col1 FROM foo, assumento che col1 sia indicizzata.'; $strShowStatusHandler_read_keyDescr = 'Il numero di richieste per leggere una riga basata su di una chiave. Se è alta, è un buon indice che le tue query e le tue tabelle sono correttamente indicizzate.'; $strShowStatusHandler_read_nextDescr = 'Il numero di richieste per leggere la riga successiva nell\'ordine delle chiavi. Questo valore è incrementato se stai facendo una query su di una colonna indice con un range costante, oppure se stai facendo una scansione degli indici.'; $strShowStatusHandler_read_prevDescr = 'Il numero di richieste per leggere la riga precedente nell\'ordine delle chiavi. Questo metodo di lettura è principalmente utilizzato per ottimizzare ORDER BY ... DESC.'; $strShowStatusHandler_read_rndDescr = 'Il numero di richieste per leggere una riga basata su una posizione fissa. Questo valore è alto se stai facendo molte richieste che richiedono un ordinamento dei risultati. Probabilmente hai molte query che che richiedono a MySQL di leggere l\'intera tabella oppure ci sono dei joins che non usano le chiavi correttamente.'; $strShowStatusHandler_read_rnd_nextDescr = 'Il numero di richieste per leggere la riga successiva in un file di dati. Questo valore è alto se stai facendo molte scansioni della tabella. Generalmente è un segnale che le tue tabelle non sono correttamente indicizzate, o che le query non sono state scritte per trarre vantaggi dagli indici che hai.'; $strShowStatusHandler_rollbackDescr = 'Il numero di comandi ROLLBACK interni.'; $strShowStatusHandler_updateDescr = 'Il numero di richieste per aggiornare una riga in una tabella.'; $strShowStatusHandler_writeDescr = 'Il numero di richieste per inserire una riga in una tabella.'; $strShowStatusInnodb_buffer_pool_pages_dataDescr = 'Il numero di pagine che contengono dati (sporchi o puliti).'; $strShowStatusInnodb_buffer_pool_pages_dirtyDescr = 'Il numero di pagine attualmente sporche.'; $strShowStatusInnodb_buffer_pool_pages_flushedDescr = 'Il numero di buffer pool pages che hanno avuto richiesta di essere aggiornate.'; $strShowStatusInnodb_buffer_pool_pages_freeDescr = 'Il numero di pagine libere.'; $strShowStatusInnodb_buffer_pool_pages_latchedDescr = 'Il numero di pagine bloccate in un InnoDB buffer pool. Queste pagine sono attualmente in lettura o in scittura e non possono essere aggiornate o rimosse per altre ragioni.'; $strShowStatusInnodb_buffer_pool_pages_miscDescr = 'Il numero di pagine occupate perchè sono state allocate per amministrazione, come row locks o per hash index adattivi. Questo valore può essere calcolato come Innodb_buffer_pool_pages_total - Innodb_buffer_pool_pages_free - Innodb_buffer_pool_pages_data.'; $strShowStatusInnodb_buffer_pool_pages_totalDescr = 'Il numero totale di buffer pool, in pagine.'; $strShowStatusInnodb_buffer_pool_read_ahead_rndDescr = 'Il numero di read-aheads "random" InnoDB iniziate. Questo accade quando una query legge una porzione di una tabella, ma in ordine casuale.'; $strShowStatusInnodb_buffer_pool_read_ahead_seqDescr = 'Il numero di read-aheads InnoDB sequanziali. Questo accade quando InnoDB esegue una scansione completa sequenziale di una tabella.'; $strShowStatusInnodb_buffer_pool_read_requestsDescr = 'Il numero di richieste logiche che InnoDb ha fatto.'; $strShowStatusInnodb_buffer_pool_readsDescr = 'Il numero di richieste logiche che InnoDB non può soddisfare dal buffer pool e che devono fare una lettura di una pagina singola.'; $strShowStatusInnodb_buffer_pool_wait_freeDescr = 'Normalmente le sritture nel buffer pool InnoDB vengono effettuate in background. Tuttavia se è necessario leggere o creare una pagina, e non sono disponibile pagine pulite è necessario attendere che le pagine siano aggiornate prima. Questo contatore conta le istanze di queste attese. Se la dimesione del buffer pool è stata settata correttamente questo valore dovrebbe essere basso.'; $strShowStatusInnodb_buffer_pool_write_requestsDescr = 'Il numero di scritture effettuate nel buffer pool InnoDB.'; $strShowStatusInnodb_data_fsyncsDescr = 'Il numero delle operazioni fsync() fino ad ora.'; $strShowStatusInnodb_data_pending_fsyncsDescr = 'Il numero di operazioni fsync() in attesa.'; $strShowStatusInnodb_data_pending_readsDescr = 'Il numero di letture in attesa.'; $strShowStatusInnodb_data_pending_writesDescr = 'Il numero di scritture in attesa.'; $strShowStatusInnodb_data_readDescr = 'La quantità di dati letti fino ad ora, in bytes.'; $strShowStatusInnodb_data_readsDescr = 'Il numero totale di dati letti.'; $strShowStatusInnodb_data_writesDescr = 'Il numero totale di dati scritti.'; $strShowStatusInnodb_data_writtenDescr = 'La quantità di dati scritti fino ad ora, in bytes.'; $strShowStatusInnodb_dblwr_pages_writtenDescr = 'Il numero di scritture doublewrite che sono state eseguite ed il numero che sono state scritte a questo scopo.'; $strShowStatusInnodb_dblwr_writesDescr = 'Il numero di scritture doublewrite che sono state eseguite ed il numero che sono state scritte a questo scopo.'; $strShowStatusInnodb_log_waitsDescr = 'Il numero di attese che abbiamo avuto perchè il buffer di log era troppo piccolo e abbiamo duvuto attendere che fosse aggiornato prima di continuare.'; $strShowStatusInnodb_log_write_requestsDescr = 'Il numero di richieste di scrittura dei log.'; $strShowStatusInnodb_log_writesDescr = 'Il numero scritture fisiche del log file.'; $strShowStatusInnodb_os_log_fsyncsDescr = 'Il numero di scritture fsync fatte sul log file.'; $strShowStatusInnodb_os_log_pending_fsyncsDescr = 'Il numero degli fsyncs in sospeso sul log file.'; $strShowStatusInnodb_os_log_pending_writesDescr = 'Il numero di scritture in sospeso sul log file.'; $strShowStatusInnodb_os_log_writtenDescr = 'Il numero di bytes scritti sul log file.'; $strShowStatusInnodb_pages_createdDescr = 'Il numero di pagine create.'; $strShowStatusInnodb_page_sizeDescr = 'La dimesione di-compilazione delle pagine InnoDB (default 16KB). Molti valori sono conteggiati nelle pagine; la dimesione delle pagine permette di convertirli facilmente in bytes.'; $strShowStatusInnodb_pages_readDescr = 'Il numero di pagine lette.'; $strShowStatusInnodb_pages_writtenDescr = 'Il numero di pagine scritte.'; $strShowStatusInnodb_row_lock_current_waitsDescr = 'Il numero di row locks attualmente in attesa.'; $strShowStatusInnodb_row_lock_time_avgDescr = 'Il tempo medio per l\'acquisizione di un row lock, in millisecondi.'; $strShowStatusInnodb_row_lock_timeDescr = 'Il tempo totale per l\'acquisizione di un row locks, in millisecondi.'; $strShowStatusInnodb_row_lock_time_maxDescr = 'Il tempo massimo per l\'acquisizione di un row lock, in millisecondi.'; $strShowStatusInnodb_row_lock_waitsDescr = 'Il numero di volte che un row lock ha dovuto attendere.'; $strShowStatusInnodb_rows_deletedDescr = 'Il numero di righe cancellate da una tabella InnoDB.'; $strShowStatusInnodb_rows_insertedDescr = 'Il numero di righe inserite da una tabella InnoDB.'; $strShowStatusInnodb_rows_readDescr = 'Il numero di righe lette da una tabella InnoDB.'; $strShowStatusInnodb_rows_updatedDescr = 'Il numero di righe aggiornate da una tabella InnoDB.'; $strShowStatusKey_blocks_not_flushedDescr = 'Il numero di blocchi chaive aggiunti nella cache chiave che sono stati cambiati, ma che non sono stai aggiornati su disco. E\' conosciuto con il nome di Not_flushed_key_blocks.'; $strShowStatusKey_blocks_unusedDescr = 'Il numero di blocchi non usati nella cache chiave. Puoi usare questo valore per determinare quanta cache chiave è in uso.'; $strShowStatusKey_blocks_usedDescr = 'Il numero di blocchi usati nella cache chiave. The number of used blocks in the key cache. Questo valore è un\'importante segnale che indica il numero massimo di blocchi che sono stati in uso contemporaneamente.'; $strShowStatusKey_read_requestsDescr = 'Il numero di richieste per le ggere un blocco chiave dalla cache.'; $strShowStatusKey_readsDescr = 'Il numero di letture fisiche dal disco di un blocco chiave. Se Key_reads è grande allora il valore key_buffer_size è probabilmente troppo piccolo. IIl rapporto di cache miss rate può essere calcolato come Key_reads/Key_read_requests.'; $strShowStatusKey_write_requestsDescr = 'Il numero di richieste per scrivere una blocco chiave nella cache.'; $strShowStatusKey_writesDescr = 'Il numero di scritture fisiche di un blocco chiave sul disco.'; $strShowStatusLast_query_costDescr = 'Il costo totale dell\'ultima query compilata così come computato dall\'ottimizzatore delle query. Utile per comparare il costo di differenti query per la stessa operazione di query. Il valore di default è 0, che significa che nessuna query è stata ancora compilata.'; $strShowStatusNot_flushed_delayed_rowsDescr = 'In numero di righe in attesa di essere scritte nella coda INSERT DELAYED.'; $strShowStatusOpened_tablesDescr = 'Il numero di tabelle che sono state aperte. Se il valore opened_tables è grande, probabilmente il valore di table cache è troppo piccolo.'; $strShowStatusOpen_filesDescr = 'Il numero di file che sono aperti.'; $strShowStatusOpen_streamsDescr = 'il numero di stream che sono aperti (usato principalmente per il logging).'; $strShowStatusOpen_tablesDescr = 'Il numero di tabelle che sono aperte.'; $strShowStatusQcache_free_blocksDescr = 'Il numero di blocchi di memoria liberi nella cache delle query.'; $strShowStatusQcache_free_memoryDescr = 'L\'ammontare di memoria libera nella cache delle query.'; $strShowStatusQcache_hitsDescr = 'Il numero di cache hits.'; $strShowStatusQcache_insertsDescr = 'Il numero di query aggiunte alla cache.'; $strShowStatusQcache_lowmem_prunesDescr = 'Il numero di query che sono state rimosse dalla cache per liberare memoria per la cache di nuove query. Questa informazione può aiutarti per parametrare la dimensione della cache delle query. La cache delle query usa una strategia di "meno usate recentemente" (LRU - least recently used) per decidere quali query rimuovere dalla cache.'; $strShowStatusQcache_not_cachedDescr = 'Il numero di query non in cache (impossibilità di inserirle nella cache oppure non inserite per i settaggi del parametro query_cache_type).'; $strShowStatusQcache_queries_in_cacheDescr = 'Il numero di query registrate nella cache.'; $strShowStatusQcache_total_blocksDescr = 'Il numero totale di blocchi nella cache delle query.'; $strShowStatusReset = 'Reset'; $strShowStatusRpl_statusDescr = 'Lo sato delle repliche failsafe (non ancora implementato).'; $strShowStatusSelect_full_joinDescr = 'Il numero di joins che non usano gli indici. (Se questo valore non è 0, dovresti controllare attentamente gli indici delle tue tabelle.)'; $strShowStatusSelect_full_range_joinDescr = 'Il numero di joins che usano una ricerca limitata su di una tabella di riferimento.'; $strShowStatusSelect_range_checkDescr = 'Il numero di joins senza chiavi che controllano per l\'uso di una chiave dopo ogni riga. (Se questo valore non è 0, dovresti controllare attentamente gli indici delle tue tabelle.)'; $strShowStatusSelect_rangeDescr = 'Il numero di joins che usano un range sulla prima tabella. (Non è, solitamente, un valore critico anche se è grande.)'; $strShowStatusSelect_scanDescr = 'Il numero di join che hanno effettuato una scansione completa della prima tabella.'; $strShowStatusSlave_open_temp_tablesDescr = 'Il numero di tabelle temporaneamente aperte da processi SQL slave.'; $strShowStatusSlave_retried_transactionsDescr = 'Numero totale di volte (dalla partenza) in cui la replica slave SQL ha ritentato una transazione.'; $strShowStatusSlave_runningDescr = 'Questa chiave è ON se questo è un server slave connesso ad un server master.'; $strShowStatusSlow_launch_threadsDescr = 'Numero di processi che hanno impiegato più di "slow_launch_time" secondi per partire.'; $strShowStatusSlow_queriesDescr = 'Numero di query che hanno impiegato più di "long_query_time" seconds.'; $strShowStatusSort_merge_passesDescr = 'Il numero di fusioni passate all\'algoritmo di ordianemento che sono state fatte. Se questo valore è grande, dovresti incrementare la variabile di sistema sort_buffer_size.'; $strShowStatusSort_rangeDescr = 'Il numero di ordinamenti che sono stati eseguiti in un intervallo.'; $strShowStatusSort_rowsDescr = 'Il numero di righe ordinate.'; $strShowStatusSort_scanDescr = 'Il numero di ordinamenti che sono stati fatti leggendo la tabella.'; $strShowStatusTable_locks_immediateDescr = 'Il numero di volte che un table lock è stato eseguito immediatamente.'; $strShowStatusTable_locks_waitedDescr = 'Il numero di volte che un table lock è stato eseguito immediatamente ed era necessaria un\'attesa. Se è alto, potresti avere dei problemi con le performance, dovresti prima ottimizzare le query, oppure sia utilizzare le repliche, sia dividere le tabelle.'; $strShowStatusThreads_cachedDescr = 'Il numero dei processi nella cache dei processi. L\'hit rate della cache può essere calcolato come processi_creati/connessioni. Se questo valore è rosso devi aumentare la tua thread_cache_size.'; $strShowStatusThreads_connectedDescr = 'Il numero di connessioni correntemente aperte.'; $strShowStatusThreads_createdDescr = 'Il numero di processi creati per gestire le connessioni. Se Threads_created è grosso, devi probabilmente aumentare il valore thread_cache_size. (Normalmente questo non fornisce un significatico incremento delle performace se hai una buona implementazione dei processi.)'; $strShowStatusThreads_runningDescr = 'Il numero di processi non in attesa.'; $strShowTableDimension = 'Mostra la dimensione delle tabelle'; $strShowTables = 'Mostra le tabelle'; $strShowThisQuery = 'Mostra questa query di nuovo'; $strSimplifiedChinese = 'Cinese Semplificato'; $strSingly = '(singolarmente)'; $strSize = 'Dimensione'; $strSkipQueries = 'Numero di record (query) da saltare a partire dall\'inizio'; $strSlovak = 'Slovacco'; $strSlovenian = 'Sloveno'; $strSmallBigAll = 'Piccolo/grande'; $strSnapToGrid = 'Calamita alla griglia'; $strSocketProblem = '(o il socket del server locale MySQL non è correttamente configurato)'; $strSortByKey = 'Ordina per chiave'; $strSorting = 'Ordinando'; $strSort = 'Ordinamento'; $strSpaceUsage = 'Spazio utilizzato'; $strSpanish = 'Spagnolo'; $strSplitWordsWithSpace = 'Le parole sono spezzate sulle spaziature (" ").'; $strSQLCompatibility = 'Modo di compatibilità SQL'; $strSQLExportType = 'Tipo di esportazione'; $strSQLParserBugMessage = 'C\'è la possibilità che ci sia un bug nel parser SQL. Per favore, esaminate la query accuratamente, e controllate che le virgolette siano corrette e non sbagliate. Altre possibili cause d\'errori possono essere che si stia cercando di uploadare un file binario al di fuori di un\'area di testo virgolettata. Si può anche provare la query MySQL dalla riga di comando di MySQL. L\'errore qui sotto restituito dal server MySQL, se ce n\'è uno, può anche aiutare nella diagnostica del problema. Se ci sono ancora problemi, o se il parser SQL di phpMyAdmin sbaglia quando invece l\'interfaccia a riga di comando non mostra problemi, si può ridurre la query SQL in ingresso alla singola query che causa problemi, e inviare un bug report con i dati riportati nella sezione CUT qui sotto:'; $strSQLParserUserError = 'Pare che ci sia un errore nella query SQL immessa. L\'errore del server MySQL mostrato qui sotto, se c\'è, può anche aiutare nella risoluzione del problema'; $strSQLQuery = 'query SQL'; $strSQLResult = 'Risultato SQL'; $strSQL = 'SQL'; $strSQPBugInvalidIdentifer = 'Identificatore Non Valido'; $strSQPBugUnclosedQuote = 'Virgolette Non Chiuse'; $strSQPBugUnknownPunctuation = 'Stringa di Punctuation Sconosciuta'; $strStandInStructureForView = 'Struttura Stand-in per le viste'; $strStatCheckTime = 'Ultimo controllo'; $strStatCreateTime = 'Creazione'; $strStatement = 'Istruzioni'; $strStatisticsOverrun = 'Su di un server sovraccarico, il contatore dei bytes potrebbe incrementarsi, e per questa ragione le statistiche riportate dal server MySQL potrebbero non essere corrette.'; $strStatUpdateTime = 'Ultimo cambiamento'; $strStatus = 'Stato'; $strStorageEngine = 'Motore di Memorizzazione'; $strStorageEngines = 'Motori di Memorizzazione'; $strStrucCSV = 'dati CSV'; $strStrucData = 'Struttura e dati'; $strStrucExcelCSV = 'CSV per dati MS Excel'; $strStrucNativeExcel = 'Dati nativi di MS Excel'; $strStrucOnly = 'Solo struttura'; $strStructPropose = 'Proponi la struttura della tabella'; $strStructureForView = 'Struttura per la vista'; $strStructure = 'Struttura'; $strSubmit = 'Invia'; $strSuccess = 'La query è stata eseguita con successo'; $strSuhosin = 'Sul server è in esecuzione Suhosin. Controlla la documentazione: %sdocumentation%s per possibili problemi.'; $strSum = 'Totali'; $strSwedish = 'Svedese'; $strSwitchToDatabase = 'Passare al Database copiato'; $strSwitchToTable = 'Passa alla tabella copiata'; $strTableAlreadyExists = 'La tabella %s esiste già!'; $strTableComments = 'Commenti sulla tabella'; $strTableEmpty = 'Il nome della tabella è vuoto!'; $strTableHasBeenDropped = 'La tabella %s è stata eliminata'; $strTableHasBeenEmptied = 'La tabella %s è stata svuotata'; $strTableHasBeenFlushed = 'La tabella %s è stata inizializzata'; $strTableIsEmpty = 'La tabella sembra essere vuota!'; $strTableMaintenance = 'Amministrazione tabella'; $strTableName = 'Nome tabella'; $strTableOfContents = 'Tabella dei contenuti'; $strTableOptions = 'Opzioni della tabella'; $strTables = '%s tabella(e)'; $strTableStructure = 'Struttura della tabella'; $strTable = 'Tabella'; $strTakeIt = 'prendilo'; $strTblPrivileges = 'Privilegi relativi alle tabelle'; $strTempData = 'Dati temporanei'; $strTextAreaLength = ' A causa della sua lunghezza,<br /> questo campo non può essere modificato '; $strThai = 'Thai'; $strThemeDefaultNotFound = 'Tema di default %s non trovato!'; $strThemeNoPreviewAvailable = 'Nessuna preview disponibile.'; $strThemeNotFound = 'Tema %s non trovato!'; $strThemeNoValidImgPath = 'Nessun percorso per le immagini per il tema %s trovato!'; $strThemePathNotFound = 'Percorso per il tema non trovato %s!'; $strTheme = 'Tema / Stile'; $strThisHost = 'Questo Host'; $strThreads = 'Processi'; $strThreadSuccessfullyKilled = 'Il thread %s è stato terminato con successo.'; $strTimeoutInfo = 'Una precedente importazione è entrata in timeout, dopo un nuovo inoltro riprenderà dalla posizione: %d.'; $strTimeoutNothingParsed = 'Nell\'ultima esecuzione nessun dato è stato processato, questo, solitamente, vuole dire che che phpMyAdmin non è in grado di ultimare l\'operazione fino a che non verrà aumentato il parametro php time limits.'; $strTimeoutPassed = 'Superato il tempo limite dello script, se vuoi finire l\'importazione inoltra nuovamente il file e il processo riprenderà.'; $strTime = 'Tempo'; $strToFromPage = 'da/per pagina'; $strToggleScratchboard = '(dis)attiva scratchboard'; $strToggleSmallBig = 'Cambia grande/piccolo'; $strToSelectRelation = 'Per selezionare una relazione, click :'; $strTotal = 'Totali'; $strTotalUC = 'Totale'; $strTraditionalChinese = 'Cinese Tradizionale'; $strTraditionalSpanish = 'Spagnolo tradizionale'; $strTraffic = 'Traffico'; $strTransactionCoordinator = 'Coordinatore delle transazioni'; $strTransformation_application_octetstream__download = 'Visualizza un collegamento per trasferire i dati di un campo in formato binario. La prima opzione è il nome del file binario. La seconda opzione è un nome di campo possibile di una riga della tabella che contiene il nome di schedario. Se fornite una seconda opzione dovete avere la prima opzione settata ad una stringa vuota'; $strTransformation_application_octetstream__hex = 'Mostra una rappresentazione esadecimale dei dati. Il primo parametro, opzionale, specifica ogni quanto deve essere aggiunto uno spazio (default a 2 nibbles).'; $strTransformation_image_jpeg__inline = 'Mostra un thumbnalil cliccabile; opzioni: larghezza,altezza in pixel (mantiere la proporzione iniziale)'; $strTransformation_image_jpeg__link = 'Mostra un link a questa immagine (download blob diretto, i.e.).'; $strTransformation_image_png__inline = 'Vedi immagine/jpeg: inline'; $strTransformation_text_plain__dateformat = 'Mostra i campi TIME, TIMESTAMP, DATETIME o il TIMESTAMP UNIX come data formattata. La prima opzione è l\'offset (in ore) che verrà aggiunto all\'ora (Default: 0). Usare la seconda opzione per specificare un differente formato di data/ora. La terza opzione determina se vuoi vedere l\'ora locale o UTC (usa "local" o "utc" per questo). In relazione a questo, il formato data ha differenti valori - per "local" guarda la documentazione della funzione PHP strftime(); per "utc" viene usata la funzione gmdate().'; $strTransformation_text_plain__external = 'SOLO PER LINUX: Lancia un\'applicazione esterna e riempie i dati dei campi tramite lo standard input. Restituisce lo standard output dell\'applicazione. L\'impostazione predefinita è Tidy, per stampare in maniera corretta il codice HTML. Per motivi di sicurezza, dovete editare manualmente il file libraries/transformations/text_plain__external.inc.php e inserire gli strumenti che permettete di utilizzare. La prima opzione è così il numero del programma che volete utilizzare e la seconda sono i parametri per il programma. Il terzo parametro, se impostato a 1 convertirà l\'output utilizzando htmlspecialchars() (Predefinito: 1). Un quarto parametro, se impostato a 1 inserirà un NOWRAP al contenuto della cella così che l\'intero output sarà mostrato senza essere riformattato (Predefinito: 1)'; $strTransformation_text_plain__formatted = 'Preserva l\'originale formattazione del campo. Nessun Escaping viene applicato.'; $strTransformation_text_plain__imagelink = 'Mostra un collegamento ad una immagine esterna; il campo contiene il nome del file; la prima opzione è un prefisso come "http://tuodominio.com/", la seconda opzione è la larghezza in pixel, la terza è l\'altezza.'; $strTransformation_text_plain__link = 'Mostra un collegamento, il campo contiene il nome del file; la prima opzione è un prefisso come "http://tuodominio.com/", la seconda opzione è un titolo per il collegamento.'; $strTransformation_text_plain__sql = 'Formatta il testo come query SQL con evidenziazione della sintassi.'; $strTransformation_text_plain__substr = 'Mostra soltanto una parte della stringa. La prima opzione è l\'offset che serve a definire dove inizia l\'output del vostro testo (Prefinito: 0). La seconda opzione è un offset che indica quanto testo viene restituito. Se vuoto, restituisce tutto il testo rimanente. La terza opzione definisce quali caratteri saranno aggiunti in fondo all\'output quando una soptto-stringa viene restituita (Predefinito: ...) .'; $strTriggers = 'Triggers'; $strTruncateQueries = 'Tronca le Query Mostrate'; $strTurkish = 'Turco'; $strType = 'Tipo'; $strUkrainian = 'Ucraino'; $strUncheckAll = 'Deseleziona tutti'; $strUnicode = 'Unicode'; $strUnique = 'Unica'; $strUnknown = 'sconosciuto'; $strUnselectAll = 'Deseleziona Tutto'; $strUnsupportedCompressionDetected = 'Stai cercando di importare un file con un tipo di compressione non supportato. Altrimenti il supporto per questo tipo di compressione non è stato ancora implementato o è stato disabilitato dalla tua configurazione.'; $strUpdatePrivMessage = 'Hai aggiornato i permessi per %s.'; $strUpdateProfileMessage = 'Il profilo è stato aggiornato.'; $strUpdateQuery = 'Aggiorna Query'; $strUpdComTab = 'Prego leggere la documentazione su come aggiornare la vostra tabella Column_comments'; $strUpgrade = 'Si dovrebbe aggiornare %s alla versione %s o successiva.'; $strUploadErrorCantWrite = 'Non riesco a scrivere il file su disco.'; $strUploadErrorExtension = 'Caricamento del file interrotto per estensione errata.'; $strUploadErrorFormSize = 'Il file caricato eccede il parametro MAX_FILE_SIZE specificato nel form HTML.'; $strUploadErrorIniSize = 'Il file caricato eccede il parametro upload_max_filesize in php.ini.'; $strUploadErrorNoTempDir = 'Non trovo la cartella temporanea.'; $strUploadErrorPartial = 'Il file è stato solo parzialmente caricato.'; $strUploadErrorUnknown = 'Errore sconosciuto nel caricamento del file.'; $strUploadLimit = 'Stai probabilmente cercando di uplodare un file troppo grosso. Fai riferimento alla documentazione %sdocumentation%s Per i modi di aggirare questo limite.'; $strUploadsNotAllowed = 'Non è permesso l\'upload dei file su questo server.'; $strUsage = 'Utilizzo'; $strUseBackquotes = 'Usa i backquotes con i nomi delle tabelle e dei campi'; $strUsedPhpExtensions = 'Estensioni PHP usate'; $strUseHostTable = 'Utilizza la Tabella dell\'Host'; $strUserAlreadyExists = 'L\'utente %s esiste già!'; $strUserEmpty = 'Il nome utente è vuoto!'; $strUserName = 'Nome utente'; $strUserNotFound = 'L\'utente selezionato non è stato trovato nella tabella dei privilegi.'; $strUserOverview = 'Vista d\'insieme dell\'utente'; $strUsersDeleted = 'Gli utenti selezionati sono stati cancellati con successo.'; $strUsersHavingAccessToDb = 'Utenti che hanno accesso a &quot;%s&quot;'; $strUser = 'Utente'; $strUseTabKey = 'Usare il tasto TAB per spostare il cursore di valore in valore, o CTRL+frecce per spostarlo altrove'; $strUseTables = 'Utilizza tabelle'; $strUseTextField = 'Utilizza campo text'; $strUseThisValue = 'Usa questa opzione'; $strValidateSQL = 'Valida SQL'; $strValidatorError = 'L\' SQL validator non può essere inizializzato. Prego controllare di avere installato le estensioni php necessarie come descritto nella %sdocumentazione%s.'; $strValue = 'Valore'; $strVar = 'Variabile'; $strVersionInformation = 'Informazioni sulla versione'; $strViewDumpDatabases = 'Visualizza il dump (schema) dei databases'; $strViewDumpDB = 'Visualizza dump (schema) del database'; $strViewDump = 'Visualizza dump (schema) della tabella'; $strViewHasBeenDropped = 'La vista %s è stata eliminata'; $strViewMaxExactCount = 'Questa vista ha più di %d righe. Per informazioni fare riferimento a %sdocumentation%s.'; $strViewName = 'Nome VISTA'; $strView = 'Vista'; $strWebServerUploadDirectory = 'directory di upload del web-server'; $strWebServerUploadDirectoryError = 'La directory impostata per l\'upload non può essere trovata'; $strWelcome = 'Benvenuto in %s'; $strWestEuropean = 'Europeo Occidentale'; $strWildcard = 'wildcard'; $strWindowNotFound = 'La finestra destinataria del browser non può essere aggiornata. Può darsi che sia stata chiusa la finestra madre o che il vostro browser stia bloccando gli aggiornamenti fra browsers a causa di qualche impostazione di sicurezza'; $strWithChecked = 'Se selezionati:'; $strWriteRequests = 'Richieste di scrittura'; $strWrongUser = 'Nome utente o password errati. Accesso negato.'; $strXML = 'XML'; $strYes = 'Sì'; $strZeroRemovesTheLimit = 'N.B.: 0 (zero) significa nessun limite.'; $strZip = '"compresso con zip"'; ?>
gpl-2.0
fengshao0907/mysql
storage/ndb/test/odbc/client/SQLTransactTest.cpp
8798
/* Copyright (c) 2003, 2005 MySQL AB Use is subject to license terms This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 */ /** * @file SQLTransactTest.cpp */ #include <common.hpp> #define STR_MESSAGE_LENGTH 200 #define STR_NAME_LEN 20 #define STR_PHONE_LEN 20 #define STR_ADDRESS_LEN 20 using namespace std; SQLHDBC STR_hdbc; SQLHSTMT STR_hstmt; SQLHENV STR_henv; SQLHDESC STR_hdesc; void Transact_DisplayError(SQLSMALLINT STR_HandleType, SQLHSTMT STR_InputHandle); int STR_Display_Result(SQLHSTMT EXDR_InputHandle); /** * Test: * -#Test to request a commit or a rollback operation for * all active transactions associated with a specific * environment or connection handle * * @return Zero, if test succeeded */ int SQLTransactTest() { SQLRETURN STR_ret; ndbout << endl << "Start SQLTransact Testing" << endl; //************************************ //** Allocate An Environment Handle ** //************************************ STR_ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &STR_henv); if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO) ndbout << "Allocated an environment Handle!" << endl; //********************************************* //** Set the ODBC application Version to 3.x ** //********************************************* STR_ret = SQLSetEnvAttr(STR_henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_UINTEGER); if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO) ndbout << "Set the ODBC application Version to 3.x!" << endl; //********************************** //** Allocate A Connection Handle ** //********************************** STR_ret = SQLAllocHandle(SQL_HANDLE_DBC, STR_henv, &STR_hdbc); if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO) ndbout << "Allocated a connection Handle!" << endl; // ******************* // ** Connect to DB ** // ******************* STR_ret = SQLConnect(STR_hdbc, (SQLCHAR *) connectString(), SQL_NTS, (SQLCHAR *) "", SQL_NTS, (SQLCHAR *) "", SQL_NTS); if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO) ndbout << "Connected to DB : OK!" << endl; else { ndbout << "Failure to Connect DB!" << endl; return NDBT_FAILED; } //******************************* //** Allocate statement handle ** //******************************* STR_ret = SQLAllocHandle(SQL_HANDLE_STMT, STR_hdbc, &STR_hstmt); if(STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO) ndbout << "Allocated a statement handle!" << endl; //******************************** //** Turn Manual-Commit Mode On ** //******************************** STR_ret = SQLSetConnectOption(STR_hdbc, SQL_AUTOCOMMIT, (UDWORD) SQL_AUTOCOMMIT_OFF); //********************************************** //** Prepare and Execute a prepared statement ** //********************************************** STR_ret = SQLExecDirect(STR_hstmt, (SQLCHAR*)"SELECT * FROM Customers", SQL_NTS); if (STR_ret == SQL_INVALID_HANDLE) { ndbout << "Handle Type is SQL_HANDLE_STMT, but SQL_INVALID_HANDLE" << endl; ndbout << "still appeared. Please check program" << endl; } if (STR_ret == SQL_ERROR || STR_ret == SQL_SUCCESS_WITH_INFO) Transact_DisplayError(SQL_HANDLE_STMT, STR_hstmt); //************************* //** Display the results ** //************************* STR_Display_Result(STR_hstmt); //**************************** //** Commit the transaction ** //**************************** STR_ret = SQLTransact(STR_henv, STR_hdbc, SQL_COMMIT); //**************** // Free Handles ** //**************** SQLDisconnect(STR_hdbc); SQLFreeHandle(SQL_HANDLE_STMT, STR_hstmt); SQLFreeHandle(SQL_HANDLE_DBC, STR_hdbc); SQLFreeHandle(SQL_HANDLE_ENV, STR_henv); return NDBT_OK; } void Transact_DisplayError(SQLSMALLINT STR_HandleType, SQLHSTMT STR_InputHandle) { SQLCHAR STR_Sqlstate[5]; SQLINTEGER STR_NativeError; SQLSMALLINT STR_i, STR_MsgLen; SQLCHAR STR_Msg[STR_MESSAGE_LENGTH]; SQLRETURN SQLSTATEs; STR_i = 1; ndbout << "-------------------------------------------------" << endl; ndbout << "Error diagnostics:" << endl; while ((SQLSTATEs = SQLGetDiagRec(STR_HandleType, STR_InputHandle, STR_i, STR_Sqlstate, &STR_NativeError, STR_Msg, sizeof(STR_Msg), &STR_MsgLen)) != SQL_NO_DATA) { ndbout << "the HandleType is:" << STR_HandleType << endl; ndbout << "the InputHandle is :" << (long)STR_InputHandle << endl; ndbout << "the STR_Msg is: " << (char *) STR_Msg << endl; ndbout << "the output state is:" << (char *)STR_Sqlstate << endl; STR_i ++; // break; } ndbout << "-------------------------------------------------" << endl; } int STR_Display_Result(SQLHSTMT STR_InputHandle) { SQLRETURN STR_retcode; unsigned long STR_CustID; SQLCHAR STR_Name[STR_NAME_LEN], STR_Phone[STR_PHONE_LEN]; SQLCHAR STR_Address[STR_ADDRESS_LEN]; //********************* //** Bind columns 1 ** //********************* STR_retcode =SQLBindCol(STR_InputHandle, 1, SQL_C_ULONG, &STR_CustID, sizeof(STR_CustID), NULL); if (STR_retcode == SQL_ERROR) { ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); return NDBT_FAILED; } //********************* //** Bind columns 2 ** //********************* STR_retcode =SQLBindCol(STR_InputHandle, 2, SQL_C_CHAR, &STR_Name, STR_NAME_LEN, NULL); if (STR_retcode == SQL_ERROR) { ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); return NDBT_FAILED; } //********************* //** Bind columns 3 ** //********************* STR_retcode = SQLBindCol(STR_InputHandle, 3, SQL_C_CHAR, &STR_Address, STR_ADDRESS_LEN, NULL); if (STR_retcode == SQL_ERROR) { ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); return NDBT_FAILED; } //********************* //** Bind columns 4 ** //********************* STR_retcode = SQLBindCol(STR_InputHandle, 4, SQL_C_CHAR, &STR_Phone, STR_PHONE_LEN, NULL); if (STR_retcode == SQL_ERROR) { ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); return NDBT_FAILED; } //***************************************** //* Fetch and print each row of data. On ** //* an error, display a message and exit ** //***************************************** if (STR_retcode != SQL_ERROR) STR_retcode = SQLFetch(STR_InputHandle); ndbout << endl << "STR_retcode = SQLFetch(STR_InputHandle) = " << STR_retcode << endl; if (STR_retcode == SQL_ERROR) { ndbout << "Executing SQLFetch, SQL_ERROR happened!" << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); return NDBT_FAILED; } else if (STR_retcode == SQL_SUCCESS_WITH_INFO) { ndbout << "CustID = " << (int)STR_CustID << endl; ndbout << "Name = " << (char *)STR_Name << endl; ndbout << "Address = " << (char *)STR_Address << endl; ndbout << "Phone = " << (char *)STR_Phone << endl; Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle); } else { ndbout << "CustID = " << (int)STR_CustID << endl; ndbout << "Name = " << (char *)STR_Name << endl; ndbout << "Address = " << (char *)STR_Address << endl; ndbout << "Phone = " << (char *)STR_Phone << endl; } return 0; }
gpl-2.0
zneext/mtasa-blue
Server/mods/deathmatch/logic/CLogger.h
2412
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: mods/deathmatch/logic/CLogger.h * PURPOSE: Server logger class * DEVELOPERS: Christian Myhre Lundheim <> * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #ifndef __CLOGGER_H #define __CLOGGER_H #include <cstdio> #include "../Config.h" enum eLogLevel { LOGLEVEL_LOW = 1, LOGLEVEL_MEDIUM = 2, }; class CLogger { public: static void LogPrintf ( const char* szFormat, ... ); static void LogPrint ( const char* szText ); static void LogPrintf ( eLogLevel logLevel, const char* szFormat, ... ); static void LogPrint ( eLogLevel logLevel, const char* szText ); static void LogPrintfNoStamp ( const char* szFormat, ... ); static void LogPrintNoStamp ( const char* szText ); static void ErrorPrintf ( const char* szFormat, ... ); static void DebugPrintf ( const char* szFormat, ... ); static void AuthPrintf ( const char* szFormat, ... ); static bool SetLogFile ( const char* szLogFile ); static bool SetAuthFile ( const char* szAuthFile ); static void SetMinLogLevel ( eLogLevel logLevel ); static void ProgressDotsBegin ( void ); static void ProgressDotsUpdate ( void ); static void ProgressDotsEnd ( void ); static void BeginConsoleOutputCapture ( void ); static SString EndConsoleOutputCapture ( void ); private: static void HandleLogPrint ( bool bTimeStamp, const char* szPrePend, const char* szMessage, bool bToConsole, bool bToLogFile, bool bToAuthFile, eLogLevel logLevel = LOGLEVEL_MEDIUM ); static FILE* m_pLogFile; static FILE* m_pAuthFile; static eLogLevel m_MinLogLevel; static bool m_bPrintingDots; static SString m_strCaptureBuffer; static bool m_bCaptureConsole; static CCriticalSection m_CaptureBufferMutex; }; #endif
gpl-3.0
ssadedin/seqr
static/admin/css/responsive_rtl.css
1741
/* TABLETS */ @media (max-width: 1024px) { [dir="rtl"] .colMS { margin-right: 0; } [dir="rtl"] #user-tools { text-align: right; } [dir="rtl"] #changelist .actions label { padding-left: 10px; padding-right: 0; } [dir="rtl"] #changelist .actions select { margin-left: 0; margin-right: 15px; } [dir="rtl"] .change-list .filtered .results, [dir="rtl"] .change-list .filtered .paginator, [dir="rtl"] .filtered #toolbar, [dir="rtl"] .filtered div.xfull, [dir="rtl"] .filtered .actions, [dir="rtl"] #changelist-filter { margin-left: 0; } [dir="rtl"] .inline-group ul.tools a.add, [dir="rtl"] .inline-group div.add-row a, [dir="rtl"] .inline-group .tabular tr.add-row td a { padding: 8px 26px 8px 10px; background-position: calc(100% - 8px) 9px; } [dir="rtl"] .related-widget-wrapper-link + .selector { margin-right: 0; margin-left: 15px; } [dir="rtl"] .selector .selector-filter label { margin-right: 0; margin-left: 8px; } [dir="rtl"] .object-tools li { float: right; } [dir="rtl"] .object-tools li + li { margin-left: 0; margin-right: 15px; } [dir="rtl"] .dashboard .module table td a { padding-left: 0; padding-right: 16px; } } /* MOBILE */ @media (max-width: 767px) { [dir="rtl"] .aligned .related-lookup, [dir="rtl"] .aligned .datetimeshortcuts { margin-left: 0; margin-right: 15px; } [dir="rtl"] .aligned ul { margin-right: 0; } [dir="rtl"] #changelist-filter { margin-left: 0; margin-right: 0; } }
agpl-3.0
c1728p9/mbed-os
targets/TARGET_STM/TARGET_STM32F1/device/stm32f1xx_hal_eth.h
102370
/** ****************************************************************************** * @file stm32f1xx_hal_eth.h * @author MCD Application Team * @brief Header file of ETH HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_ETH_H #define __STM32F1xx_HAL_ETH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal_def.h" /** @addtogroup STM32F1xx_HAL_Driver * @{ */ #if defined (STM32F107xC) /** @addtogroup ETH * @{ */ /** @addtogroup ETH_Private_Macros * @{ */ #define IS_ETH_PHY_ADDRESS(ADDRESS) ((ADDRESS) <= 0x20U) #define IS_ETH_AUTONEGOTIATION(CMD) (((CMD) == ETH_AUTONEGOTIATION_ENABLE) || \ ((CMD) == ETH_AUTONEGOTIATION_DISABLE)) #define IS_ETH_SPEED(SPEED) (((SPEED) == ETH_SPEED_10M) || \ ((SPEED) == ETH_SPEED_100M)) #define IS_ETH_DUPLEX_MODE(MODE) (((MODE) == ETH_MODE_FULLDUPLEX) || \ ((MODE) == ETH_MODE_HALFDUPLEX)) #define IS_ETH_RX_MODE(MODE) (((MODE) == ETH_RXPOLLING_MODE) || \ ((MODE) == ETH_RXINTERRUPT_MODE)) #define IS_ETH_CHECKSUM_MODE(MODE) (((MODE) == ETH_CHECKSUM_BY_HARDWARE) || \ ((MODE) == ETH_CHECKSUM_BY_SOFTWARE)) #define IS_ETH_MEDIA_INTERFACE(MODE) (((MODE) == ETH_MEDIA_INTERFACE_MII) || \ ((MODE) == ETH_MEDIA_INTERFACE_RMII)) #define IS_ETH_WATCHDOG(CMD) (((CMD) == ETH_WATCHDOG_ENABLE) || \ ((CMD) == ETH_WATCHDOG_DISABLE)) #define IS_ETH_JABBER(CMD) (((CMD) == ETH_JABBER_ENABLE) || \ ((CMD) == ETH_JABBER_DISABLE)) #define IS_ETH_INTER_FRAME_GAP(GAP) (((GAP) == ETH_INTERFRAMEGAP_96BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_88BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_80BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_72BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_64BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_56BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_48BIT) || \ ((GAP) == ETH_INTERFRAMEGAP_40BIT)) #define IS_ETH_CARRIER_SENSE(CMD) (((CMD) == ETH_CARRIERSENCE_ENABLE) || \ ((CMD) == ETH_CARRIERSENCE_DISABLE)) #define IS_ETH_RECEIVE_OWN(CMD) (((CMD) == ETH_RECEIVEOWN_ENABLE) || \ ((CMD) == ETH_RECEIVEOWN_DISABLE)) #define IS_ETH_LOOPBACK_MODE(CMD) (((CMD) == ETH_LOOPBACKMODE_ENABLE) || \ ((CMD) == ETH_LOOPBACKMODE_DISABLE)) #define IS_ETH_CHECKSUM_OFFLOAD(CMD) (((CMD) == ETH_CHECKSUMOFFLAOD_ENABLE) || \ ((CMD) == ETH_CHECKSUMOFFLAOD_DISABLE)) #define IS_ETH_RETRY_TRANSMISSION(CMD) (((CMD) == ETH_RETRYTRANSMISSION_ENABLE) || \ ((CMD) == ETH_RETRYTRANSMISSION_DISABLE)) #define IS_ETH_AUTOMATIC_PADCRC_STRIP(CMD) (((CMD) == ETH_AUTOMATICPADCRCSTRIP_ENABLE) || \ ((CMD) == ETH_AUTOMATICPADCRCSTRIP_DISABLE)) #define IS_ETH_BACKOFF_LIMIT(LIMIT) (((LIMIT) == ETH_BACKOFFLIMIT_10) || \ ((LIMIT) == ETH_BACKOFFLIMIT_8) || \ ((LIMIT) == ETH_BACKOFFLIMIT_4) || \ ((LIMIT) == ETH_BACKOFFLIMIT_1)) #define IS_ETH_DEFERRAL_CHECK(CMD) (((CMD) == ETH_DEFFERRALCHECK_ENABLE) || \ ((CMD) == ETH_DEFFERRALCHECK_DISABLE)) #define IS_ETH_RECEIVE_ALL(CMD) (((CMD) == ETH_RECEIVEALL_ENABLE) || \ ((CMD) == ETH_RECEIVEAll_DISABLE)) #define IS_ETH_SOURCE_ADDR_FILTER(CMD) (((CMD) == ETH_SOURCEADDRFILTER_NORMAL_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_INVERSE_ENABLE) || \ ((CMD) == ETH_SOURCEADDRFILTER_DISABLE)) #define IS_ETH_CONTROL_FRAMES(PASS) (((PASS) == ETH_PASSCONTROLFRAMES_BLOCKALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDALL) || \ ((PASS) == ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER)) #define IS_ETH_BROADCAST_FRAMES_RECEPTION(CMD) (((CMD) == ETH_BROADCASTFRAMESRECEPTION_ENABLE) || \ ((CMD) == ETH_BROADCASTFRAMESRECEPTION_DISABLE)) #define IS_ETH_DESTINATION_ADDR_FILTER(FILTER) (((FILTER) == ETH_DESTINATIONADDRFILTER_NORMAL) || \ ((FILTER) == ETH_DESTINATIONADDRFILTER_INVERSE)) #define IS_ETH_PROMISCUOUS_MODE(CMD) (((CMD) == ETH_PROMISCUOUS_MODE_ENABLE) || \ ((CMD) == ETH_PROMISCUOUS_MODE_DISABLE)) #define IS_ETH_MULTICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_PERFECT) || \ ((FILTER) == ETH_MULTICASTFRAMESFILTER_NONE)) #define IS_ETH_UNICAST_FRAMES_FILTER(FILTER) (((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_HASHTABLE) || \ ((FILTER) == ETH_UNICASTFRAMESFILTER_PERFECT)) #define IS_ETH_PAUSE_TIME(TIME) ((TIME) <= 0xFFFFU) #define IS_ETH_ZEROQUANTA_PAUSE(CMD) (((CMD) == ETH_ZEROQUANTAPAUSE_ENABLE) || \ ((CMD) == ETH_ZEROQUANTAPAUSE_DISABLE)) #define IS_ETH_PAUSE_LOW_THRESHOLD(THRESHOLD) (((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS4) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS28) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS144) || \ ((THRESHOLD) == ETH_PAUSELOWTHRESHOLD_MINUS256)) #define IS_ETH_UNICAST_PAUSE_FRAME_DETECT(CMD) (((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_ENABLE) || \ ((CMD) == ETH_UNICASTPAUSEFRAMEDETECT_DISABLE)) #define IS_ETH_RECEIVE_FLOWCONTROL(CMD) (((CMD) == ETH_RECEIVEFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_RECEIVEFLOWCONTROL_DISABLE)) #define IS_ETH_TRANSMIT_FLOWCONTROL(CMD) (((CMD) == ETH_TRANSMITFLOWCONTROL_ENABLE) || \ ((CMD) == ETH_TRANSMITFLOWCONTROL_DISABLE)) #define IS_ETH_VLAN_TAG_COMPARISON(COMPARISON) (((COMPARISON) == ETH_VLANTAGCOMPARISON_12BIT) || \ ((COMPARISON) == ETH_VLANTAGCOMPARISON_16BIT)) #define IS_ETH_VLAN_TAG_IDENTIFIER(IDENTIFIER) ((IDENTIFIER) <= 0xFFFFU) #define IS_ETH_MAC_ADDRESS0123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS0) || \ ((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS123(ADDRESS) (((ADDRESS) == ETH_MAC_ADDRESS1) || \ ((ADDRESS) == ETH_MAC_ADDRESS2) || \ ((ADDRESS) == ETH_MAC_ADDRESS3)) #define IS_ETH_MAC_ADDRESS_FILTER(FILTER) (((FILTER) == ETH_MAC_ADDRESSFILTER_SA) || \ ((FILTER) == ETH_MAC_ADDRESSFILTER_DA)) #define IS_ETH_MAC_ADDRESS_MASK(MASK) (((MASK) == ETH_MAC_ADDRESSMASK_BYTE6) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE5) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE4) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE3) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE2) || \ ((MASK) == ETH_MAC_ADDRESSMASK_BYTE1)) #define IS_ETH_DROP_TCPIP_CHECKSUM_FRAME(CMD) (((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE) || \ ((CMD) == ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE)) #define IS_ETH_RECEIVE_STORE_FORWARD(CMD) (((CMD) == ETH_RECEIVESTOREFORWARD_ENABLE) || \ ((CMD) == ETH_RECEIVESTOREFORWARD_DISABLE)) #define IS_ETH_FLUSH_RECEIVE_FRAME(CMD) (((CMD) == ETH_FLUSHRECEIVEDFRAME_ENABLE) || \ ((CMD) == ETH_FLUSHRECEIVEDFRAME_DISABLE)) #define IS_ETH_TRANSMIT_STORE_FORWARD(CMD) (((CMD) == ETH_TRANSMITSTOREFORWARD_ENABLE) || \ ((CMD) == ETH_TRANSMITSTOREFORWARD_DISABLE)) #define IS_ETH_TRANSMIT_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_128BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_192BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_256BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_40BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_24BYTES) || \ ((THRESHOLD) == ETH_TRANSMITTHRESHOLDCONTROL_16BYTES)) #define IS_ETH_FORWARD_ERROR_FRAMES(CMD) (((CMD) == ETH_FORWARDERRORFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDERRORFRAMES_DISABLE)) #define IS_ETH_FORWARD_UNDERSIZED_GOOD_FRAMES(CMD) (((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE) || \ ((CMD) == ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE)) #define IS_ETH_RECEIVE_THRESHOLD_CONTROL(THRESHOLD) (((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES) || \ ((THRESHOLD) == ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES)) #define IS_ETH_SECOND_FRAME_OPERATE(CMD) (((CMD) == ETH_SECONDFRAMEOPERARTE_ENABLE) || \ ((CMD) == ETH_SECONDFRAMEOPERARTE_DISABLE)) #define IS_ETH_ADDRESS_ALIGNED_BEATS(CMD) (((CMD) == ETH_ADDRESSALIGNEDBEATS_ENABLE) || \ ((CMD) == ETH_ADDRESSALIGNEDBEATS_DISABLE)) #define IS_ETH_FIXED_BURST(CMD) (((CMD) == ETH_FIXEDBURST_ENABLE) || \ ((CMD) == ETH_FIXEDBURST_DISABLE)) #define IS_ETH_RXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_RXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_RXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_TXDMA_BURST_LENGTH(LENGTH) (((LENGTH) == ETH_TXDMABURSTLENGTH_1BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_2BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_4BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_8BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_16BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_32BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_64BEAT) || \ ((LENGTH) == ETH_TXDMABURSTLENGTH_4XPBL_128BEAT)) #define IS_ETH_DMA_DESC_SKIP_LENGTH(LENGTH) ((LENGTH) <= 0x1FU) #define IS_ETH_DMA_ARBITRATION_ROUNDROBIN_RXTX(RATIO) (((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1) || \ ((RATIO) == ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1) || \ ((RATIO) == ETH_DMAARBITRATION_RXPRIORTX)) #define IS_ETH_DMATXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMATXDESC_OWN) || \ ((FLAG) == ETH_DMATXDESC_IC) || \ ((FLAG) == ETH_DMATXDESC_LS) || \ ((FLAG) == ETH_DMATXDESC_FS) || \ ((FLAG) == ETH_DMATXDESC_DC) || \ ((FLAG) == ETH_DMATXDESC_DP) || \ ((FLAG) == ETH_DMATXDESC_TTSE) || \ ((FLAG) == ETH_DMATXDESC_TER) || \ ((FLAG) == ETH_DMATXDESC_TCH) || \ ((FLAG) == ETH_DMATXDESC_TTSS) || \ ((FLAG) == ETH_DMATXDESC_IHE) || \ ((FLAG) == ETH_DMATXDESC_ES) || \ ((FLAG) == ETH_DMATXDESC_JT) || \ ((FLAG) == ETH_DMATXDESC_FF) || \ ((FLAG) == ETH_DMATXDESC_PCE) || \ ((FLAG) == ETH_DMATXDESC_LCA) || \ ((FLAG) == ETH_DMATXDESC_NC) || \ ((FLAG) == ETH_DMATXDESC_LCO) || \ ((FLAG) == ETH_DMATXDESC_EC) || \ ((FLAG) == ETH_DMATXDESC_VF) || \ ((FLAG) == ETH_DMATXDESC_CC) || \ ((FLAG) == ETH_DMATXDESC_ED) || \ ((FLAG) == ETH_DMATXDESC_UF) || \ ((FLAG) == ETH_DMATXDESC_DB)) #define IS_ETH_DMA_TXDESC_SEGMENT(SEGMENT) (((SEGMENT) == ETH_DMATXDESC_LASTSEGMENTS) || \ ((SEGMENT) == ETH_DMATXDESC_FIRSTSEGMENT)) #define IS_ETH_DMA_TXDESC_CHECKSUM(CHECKSUM) (((CHECKSUM) == ETH_DMATXDESC_CHECKSUMBYPASS) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMIPV4HEADER) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT) || \ ((CHECKSUM) == ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL)) #define IS_ETH_DMATXDESC_BUFFER_SIZE(SIZE) ((SIZE) <= 0x1FFFU) #define IS_ETH_DMARXDESC_GET_FLAG(FLAG) (((FLAG) == ETH_DMARXDESC_OWN) || \ ((FLAG) == ETH_DMARXDESC_AFM) || \ ((FLAG) == ETH_DMARXDESC_ES) || \ ((FLAG) == ETH_DMARXDESC_DE) || \ ((FLAG) == ETH_DMARXDESC_SAF) || \ ((FLAG) == ETH_DMARXDESC_LE) || \ ((FLAG) == ETH_DMARXDESC_OE) || \ ((FLAG) == ETH_DMARXDESC_VLAN) || \ ((FLAG) == ETH_DMARXDESC_FS) || \ ((FLAG) == ETH_DMARXDESC_LS) || \ ((FLAG) == ETH_DMARXDESC_IPV4HCE) || \ ((FLAG) == ETH_DMARXDESC_LC) || \ ((FLAG) == ETH_DMARXDESC_FT) || \ ((FLAG) == ETH_DMARXDESC_RWT) || \ ((FLAG) == ETH_DMARXDESC_RE) || \ ((FLAG) == ETH_DMARXDESC_DBE) || \ ((FLAG) == ETH_DMARXDESC_CE) || \ ((FLAG) == ETH_DMARXDESC_MAMPCE)) #define IS_ETH_DMA_RXDESC_BUFFER(BUFFER) (((BUFFER) == ETH_DMARXDESC_BUFFER1) || \ ((BUFFER) == ETH_DMARXDESC_BUFFER2)) #define IS_ETH_PMT_GET_FLAG(FLAG) (((FLAG) == ETH_PMT_FLAG_WUFR) || \ ((FLAG) == ETH_PMT_FLAG_MPR)) #define IS_ETH_DMA_FLAG(FLAG) ((((FLAG) & 0xC7FE1800U) == 0x00U) && ((FLAG) != 0x00U)) #define IS_ETH_DMA_GET_FLAG(FLAG) (((FLAG) == ETH_DMA_FLAG_TST) || ((FLAG) == ETH_DMA_FLAG_PMT) || \ ((FLAG) == ETH_DMA_FLAG_MMC) || ((FLAG) == ETH_DMA_FLAG_DATATRANSFERERROR) || \ ((FLAG) == ETH_DMA_FLAG_READWRITEERROR) || ((FLAG) == ETH_DMA_FLAG_ACCESSERROR) || \ ((FLAG) == ETH_DMA_FLAG_NIS) || ((FLAG) == ETH_DMA_FLAG_AIS) || \ ((FLAG) == ETH_DMA_FLAG_ER) || ((FLAG) == ETH_DMA_FLAG_FBE) || \ ((FLAG) == ETH_DMA_FLAG_ET) || ((FLAG) == ETH_DMA_FLAG_RWT) || \ ((FLAG) == ETH_DMA_FLAG_RPS) || ((FLAG) == ETH_DMA_FLAG_RBU) || \ ((FLAG) == ETH_DMA_FLAG_R) || ((FLAG) == ETH_DMA_FLAG_TU) || \ ((FLAG) == ETH_DMA_FLAG_RO) || ((FLAG) == ETH_DMA_FLAG_TJT) || \ ((FLAG) == ETH_DMA_FLAG_TBU) || ((FLAG) == ETH_DMA_FLAG_TPS) || \ ((FLAG) == ETH_DMA_FLAG_T)) #define IS_ETH_MAC_IT(IT) ((((IT) & 0xFFFFFDF1U) == 0x00U) && ((IT) != 0x00U)) #define IS_ETH_MAC_GET_IT(IT) (((IT) == ETH_MAC_IT_TST) || ((IT) == ETH_MAC_IT_MMCT) || \ ((IT) == ETH_MAC_IT_MMCR) || ((IT) == ETH_MAC_IT_MMC) || \ ((IT) == ETH_MAC_IT_PMT)) #define IS_ETH_MAC_GET_FLAG(FLAG) (((FLAG) == ETH_MAC_FLAG_TST) || ((FLAG) == ETH_MAC_FLAG_MMCT) || \ ((FLAG) == ETH_MAC_FLAG_MMCR) || ((FLAG) == ETH_MAC_FLAG_MMC) || \ ((FLAG) == ETH_MAC_FLAG_PMT)) #define IS_ETH_DMA_IT(IT) ((((IT) & 0xC7FE1800U) == 0x00U) && ((IT) != 0x00U)) #define IS_ETH_DMA_GET_IT(IT) (((IT) == ETH_DMA_IT_TST) || ((IT) == ETH_DMA_IT_PMT) || \ ((IT) == ETH_DMA_IT_MMC) || ((IT) == ETH_DMA_IT_NIS) || \ ((IT) == ETH_DMA_IT_AIS) || ((IT) == ETH_DMA_IT_ER) || \ ((IT) == ETH_DMA_IT_FBE) || ((IT) == ETH_DMA_IT_ET) || \ ((IT) == ETH_DMA_IT_RWT) || ((IT) == ETH_DMA_IT_RPS) || \ ((IT) == ETH_DMA_IT_RBU) || ((IT) == ETH_DMA_IT_R) || \ ((IT) == ETH_DMA_IT_TU) || ((IT) == ETH_DMA_IT_RO) || \ ((IT) == ETH_DMA_IT_TJT) || ((IT) == ETH_DMA_IT_TBU) || \ ((IT) == ETH_DMA_IT_TPS) || ((IT) == ETH_DMA_IT_T)) #define IS_ETH_DMA_GET_OVERFLOW(OVERFLOW) (((OVERFLOW) == ETH_DMA_OVERFLOW_RXFIFOCOUNTER) || \ ((OVERFLOW) == ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER)) #define IS_ETH_MMC_IT(IT) (((((IT) & 0xFFDF3FFFU) == 0x00U) || (((IT) & 0xEFFDFF9FU) == 0x00U)) && \ ((IT) != 0x00U)) #define IS_ETH_MMC_GET_IT(IT) (((IT) == ETH_MMC_IT_TGF) || ((IT) == ETH_MMC_IT_TGFMSC) || \ ((IT) == ETH_MMC_IT_TGFSC) || ((IT) == ETH_MMC_IT_RGUF) || \ ((IT) == ETH_MMC_IT_RFAE) || ((IT) == ETH_MMC_IT_RFCE)) #define IS_ETH_ENHANCED_DESCRIPTOR_FORMAT(CMD) (((CMD) == ETH_DMAENHANCEDDESCRIPTOR_ENABLE) || \ ((CMD) == ETH_DMAENHANCEDDESCRIPTOR_DISABLE)) /** * @} */ /** @addtogroup ETH_Private_Defines * @{ */ /* Delay to wait when writing to some Ethernet registers */ #define ETH_REG_WRITE_DELAY 0x00000001U /* ETHERNET Errors */ #define ETH_SUCCESS 0U #define ETH_ERROR 1U /* ETHERNET DMA Tx descriptors Collision Count Shift */ #define ETH_DMATXDESC_COLLISION_COUNTSHIFT 3U /* ETHERNET DMA Tx descriptors Buffer2 Size Shift */ #define ETH_DMATXDESC_BUFFER2_SIZESHIFT 16U /* ETHERNET DMA Rx descriptors Frame Length Shift */ #define ETH_DMARXDESC_FRAME_LENGTHSHIFT 16U /* ETHERNET DMA Rx descriptors Buffer2 Size Shift */ #define ETH_DMARXDESC_BUFFER2_SIZESHIFT 16U /* ETHERNET DMA Rx descriptors Frame length Shift */ #define ETH_DMARXDESC_FRAMELENGTHSHIFT 16U /* ETHERNET MAC address offsets */ #define ETH_MAC_ADDR_HBASE (uint32_t)(ETH_MAC_BASE + 0x40U) /* ETHERNET MAC address high offset */ #define ETH_MAC_ADDR_LBASE (uint32_t)(ETH_MAC_BASE + 0x44U) /* ETHERNET MAC address low offset */ /* ETHERNET MACMIIAR register Mask */ #define ETH_MACMIIAR_CR_MASK 0xFFFFFFE3U /* ETHERNET MACCR register Mask */ #define ETH_MACCR_CLEAR_MASK 0xFF20810FU /* ETHERNET MACFCR register Mask */ #define ETH_MACFCR_CLEAR_MASK 0x0000FF41U /* ETHERNET DMAOMR register Mask */ #define ETH_DMAOMR_CLEAR_MASK 0xF8DE3F23U /* ETHERNET Remote Wake-up frame register length */ #define ETH_WAKEUP_REGISTER_LENGTH 8U /* ETHERNET Missed frames counter Shift */ #define ETH_DMA_RX_OVERFLOW_MISSEDFRAMES_COUNTERSHIFT 17U /** * @} */ /* Exported types ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Types ETH Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_ETH_STATE_RESET = 0x00U, /*!< Peripheral not yet Initialized or disabled */ HAL_ETH_STATE_READY = 0x01U, /*!< Peripheral Initialized and ready for use */ HAL_ETH_STATE_BUSY = 0x02U, /*!< an internal process is ongoing */ HAL_ETH_STATE_BUSY_TX = 0x12U, /*!< Data Transmission process is ongoing */ HAL_ETH_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing */ HAL_ETH_STATE_BUSY_TX_RX = 0x32U, /*!< Data Transmission and Reception process is ongoing */ HAL_ETH_STATE_BUSY_WR = 0x42U, /*!< Write process is ongoing */ HAL_ETH_STATE_BUSY_RD = 0x82U, /*!< Read process is ongoing */ HAL_ETH_STATE_TIMEOUT = 0x03U, /*!< Timeout state */ HAL_ETH_STATE_ERROR = 0x04U /*!< Reception process is ongoing */ } HAL_ETH_StateTypeDef; /** * @brief ETH Init Structure definition */ typedef struct { uint32_t AutoNegotiation; /*!< Selects or not the AutoNegotiation mode for the external PHY The AutoNegotiation allows an automatic setting of the Speed (10/100Mbps) and the mode (half/full-duplex). This parameter can be a value of @ref ETH_AutoNegotiation */ uint32_t Speed; /*!< Sets the Ethernet speed: 10/100 Mbps. This parameter can be a value of @ref ETH_Speed */ uint32_t DuplexMode; /*!< Selects the MAC duplex mode: Half-Duplex or Full-Duplex mode This parameter can be a value of @ref ETH_Duplex_Mode */ uint16_t PhyAddress; /*!< Ethernet PHY address. This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint8_t *MACAddr; /*!< MAC Address of used Hardware: must be pointer on an array of 6 bytes */ uint32_t RxMode; /*!< Selects the Ethernet Rx mode: Polling mode, Interrupt mode. This parameter can be a value of @ref ETH_Rx_Mode */ uint32_t ChecksumMode; /*!< Selects if the checksum is check by hardware or by software. This parameter can be a value of @ref ETH_Checksum_Mode */ uint32_t MediaInterface; /*!< Selects the media-independent interface or the reduced media-independent interface. This parameter can be a value of @ref ETH_Media_Interface */ } ETH_InitTypeDef; /** * @brief ETH MAC Configuration Structure definition */ typedef struct { uint32_t Watchdog; /*!< Selects or not the Watchdog timer When enabled, the MAC allows no more then 2048 bytes to be received. When disabled, the MAC can receive up to 16384 bytes. This parameter can be a value of @ref ETH_Watchdog */ uint32_t Jabber; /*!< Selects or not Jabber timer When enabled, the MAC allows no more then 2048 bytes to be sent. When disabled, the MAC can send up to 16384 bytes. This parameter can be a value of @ref ETH_Jabber */ uint32_t InterFrameGap; /*!< Selects the minimum IFG between frames during transmission. This parameter can be a value of @ref ETH_Inter_Frame_Gap */ uint32_t CarrierSense; /*!< Selects or not the Carrier Sense. This parameter can be a value of @ref ETH_Carrier_Sense */ uint32_t ReceiveOwn; /*!< Selects or not the ReceiveOwn, ReceiveOwn allows the reception of frames when the TX_EN signal is asserted in Half-Duplex mode. This parameter can be a value of @ref ETH_Receive_Own */ uint32_t LoopbackMode; /*!< Selects or not the internal MAC MII Loopback mode. This parameter can be a value of @ref ETH_Loop_Back_Mode */ uint32_t ChecksumOffload; /*!< Selects or not the IPv4 checksum checking for received frame payloads' TCP/UDP/ICMP headers. This parameter can be a value of @ref ETH_Checksum_Offload */ uint32_t RetryTransmission; /*!< Selects or not the MAC attempt retries transmission, based on the settings of BL, when a collision occurs (Half-Duplex mode). This parameter can be a value of @ref ETH_Retry_Transmission */ uint32_t AutomaticPadCRCStrip; /*!< Selects or not the Automatic MAC Pad/CRC Stripping. This parameter can be a value of @ref ETH_Automatic_Pad_CRC_Strip */ uint32_t BackOffLimit; /*!< Selects the BackOff limit value. This parameter can be a value of @ref ETH_Back_Off_Limit */ uint32_t DeferralCheck; /*!< Selects or not the deferral check function (Half-Duplex mode). This parameter can be a value of @ref ETH_Deferral_Check */ uint32_t ReceiveAll; /*!< Selects or not all frames reception by the MAC (No filtering). This parameter can be a value of @ref ETH_Receive_All */ uint32_t SourceAddrFilter; /*!< Selects the Source Address Filter mode. This parameter can be a value of @ref ETH_Source_Addr_Filter */ uint32_t PassControlFrames; /*!< Sets the forwarding mode of the control frames (including unicast and multicast PAUSE frames) This parameter can be a value of @ref ETH_Pass_Control_Frames */ uint32_t BroadcastFramesReception; /*!< Selects or not the reception of Broadcast Frames. This parameter can be a value of @ref ETH_Broadcast_Frames_Reception */ uint32_t DestinationAddrFilter; /*!< Sets the destination filter mode for both unicast and multicast frames. This parameter can be a value of @ref ETH_Destination_Addr_Filter */ uint32_t PromiscuousMode; /*!< Selects or not the Promiscuous Mode This parameter can be a value of @ref ETH_Promiscuous_Mode */ uint32_t MulticastFramesFilter; /*!< Selects the Multicast Frames filter mode: None/HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Multicast_Frames_Filter */ uint32_t UnicastFramesFilter; /*!< Selects the Unicast Frames filter mode: HashTableFilter/PerfectFilter/PerfectHashTableFilter. This parameter can be a value of @ref ETH_Unicast_Frames_Filter */ uint32_t HashTableHigh; /*!< This field holds the higher 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFFU */ uint32_t HashTableLow; /*!< This field holds the lower 32 bits of Hash table. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFFFFFU */ uint32_t PauseTime; /*!< This field holds the value to be used in the Pause Time field in the transmit control frame. This parameter must be a number between Min_Data = 0x0 and Max_Data = 0xFFFFU */ uint32_t ZeroQuantaPause; /*!< Selects or not the automatic generation of Zero-Quanta Pause Control frames. This parameter can be a value of @ref ETH_Zero_Quanta_Pause */ uint32_t PauseLowThreshold; /*!< This field configures the threshold of the PAUSE to be checked for automatic retransmission of PAUSE Frame. This parameter can be a value of @ref ETH_Pause_Low_Threshold */ uint32_t UnicastPauseFrameDetect; /*!< Selects or not the MAC detection of the Pause frames (with MAC Address0 unicast address and unique multicast address). This parameter can be a value of @ref ETH_Unicast_Pause_Frame_Detect */ uint32_t ReceiveFlowControl; /*!< Enables or disables the MAC to decode the received Pause frame and disable its transmitter for a specified time (Pause Time) This parameter can be a value of @ref ETH_Receive_Flow_Control */ uint32_t TransmitFlowControl; /*!< Enables or disables the MAC to transmit Pause frames (Full-Duplex mode) or the MAC back-pressure operation (Half-Duplex mode) This parameter can be a value of @ref ETH_Transmit_Flow_Control */ uint32_t VLANTagComparison; /*!< Selects the 12-bit VLAN identifier or the complete 16-bit VLAN tag for comparison and filtering. This parameter can be a value of @ref ETH_VLAN_Tag_Comparison */ uint32_t VLANTagIdentifier; /*!< Holds the VLAN tag identifier for receive frames */ } ETH_MACInitTypeDef; /** * @brief ETH DMA Configuration Structure definition */ typedef struct { uint32_t DropTCPIPChecksumErrorFrame; /*!< Selects or not the Dropping of TCP/IP Checksum Error Frames. This parameter can be a value of @ref ETH_Drop_TCP_IP_Checksum_Error_Frame */ uint32_t ReceiveStoreForward; /*!< Enables or disables the Receive store and forward mode. This parameter can be a value of @ref ETH_Receive_Store_Forward */ uint32_t FlushReceivedFrame; /*!< Enables or disables the flushing of received frames. This parameter can be a value of @ref ETH_Flush_Received_Frame */ uint32_t TransmitStoreForward; /*!< Enables or disables Transmit store and forward mode. This parameter can be a value of @ref ETH_Transmit_Store_Forward */ uint32_t TransmitThresholdControl; /*!< Selects or not the Transmit Threshold Control. This parameter can be a value of @ref ETH_Transmit_Threshold_Control */ uint32_t ForwardErrorFrames; /*!< Selects or not the forward to the DMA of erroneous frames. This parameter can be a value of @ref ETH_Forward_Error_Frames */ uint32_t ForwardUndersizedGoodFrames; /*!< Enables or disables the Rx FIFO to forward Undersized frames (frames with no Error and length less than 64 bytes) including pad-bytes and CRC) This parameter can be a value of @ref ETH_Forward_Undersized_Good_Frames */ uint32_t ReceiveThresholdControl; /*!< Selects the threshold level of the Receive FIFO. This parameter can be a value of @ref ETH_Receive_Threshold_Control */ uint32_t SecondFrameOperate; /*!< Selects or not the Operate on second frame mode, which allows the DMA to process a second frame of Transmit data even before obtaining the status for the first frame. This parameter can be a value of @ref ETH_Second_Frame_Operate */ uint32_t AddressAlignedBeats; /*!< Enables or disables the Address Aligned Beats. This parameter can be a value of @ref ETH_Address_Aligned_Beats */ uint32_t FixedBurst; /*!< Enables or disables the AHB Master interface fixed burst transfers. This parameter can be a value of @ref ETH_Fixed_Burst */ uint32_t RxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Rx DMA transaction. This parameter can be a value of @ref ETH_Rx_DMA_Burst_Length */ uint32_t TxDMABurstLength; /*!< Indicates the maximum number of beats to be transferred in one Tx DMA transaction. This parameter can be a value of @ref ETH_Tx_DMA_Burst_Length */ uint32_t DescriptorSkipLength; /*!< Specifies the number of word to skip between two unchained descriptors (Ring mode) This parameter must be a number between Min_Data = 0 and Max_Data = 32 */ uint32_t DMAArbitration; /*!< Selects the DMA Tx/Rx arbitration. This parameter can be a value of @ref ETH_DMA_Arbitration */ } ETH_DMAInitTypeDef; /** * @brief ETH DMA Descriptors data structure definition */ typedef struct { __IO uint32_t Status; /*!< Status */ uint32_t ControlBufferSize; /*!< Control and Buffer1, Buffer2 lengths */ uint32_t Buffer1Addr; /*!< Buffer1 address pointer */ uint32_t Buffer2NextDescAddr; /*!< Buffer2 or next descriptor address pointer */ } ETH_DMADescTypeDef; /** * @brief Received Frame Informations structure definition */ typedef struct { ETH_DMADescTypeDef *FSRxDesc; /*!< First Segment Rx Desc */ ETH_DMADescTypeDef *LSRxDesc; /*!< Last Segment Rx Desc */ uint32_t SegCount; /*!< Segment count */ uint32_t length; /*!< Frame length */ uint32_t buffer; /*!< Frame buffer */ } ETH_DMARxFrameInfos; /** * @brief ETH Handle Structure definition */ typedef struct { ETH_TypeDef *Instance; /*!< Register base address */ ETH_InitTypeDef Init; /*!< Ethernet Init Configuration */ uint32_t LinkStatus; /*!< Ethernet link status */ ETH_DMADescTypeDef *RxDesc; /*!< Rx descriptor to Get */ ETH_DMADescTypeDef *TxDesc; /*!< Tx descriptor to Set */ ETH_DMARxFrameInfos RxFrameInfos; /*!< last Rx frame infos */ __IO HAL_ETH_StateTypeDef State; /*!< ETH communication state */ HAL_LockTypeDef Lock; /*!< ETH Lock */ } ETH_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup ETH_Exported_Constants ETH Exported Constants * @{ */ /** @defgroup ETH_Buffers_setting ETH Buffers setting * @{ */ #define ETH_MAX_PACKET_SIZE 1524U /*!< ETH_HEADER + ETH_EXTRA + ETH_VLAN_TAG + ETH_MAX_ETH_PAYLOAD + ETH_CRC */ #define ETH_HEADER 14U /*!< 6 byte Dest addr, 6 byte Src addr, 2 byte length/type */ #define ETH_CRC 4U /*!< Ethernet CRC */ #define ETH_EXTRA 2U /*!< Extra bytes in some cases */ #define ETH_VLAN_TAG 4U /*!< optional 802.1q VLAN Tag */ #define ETH_MIN_ETH_PAYLOAD 46U /*!< Minimum Ethernet payload size */ #define ETH_MAX_ETH_PAYLOAD 1500U /*!< Maximum Ethernet payload size */ #define ETH_JUMBO_FRAME_PAYLOAD 9000U /*!< Jumbo frame payload size */ /* Ethernet driver receive buffers are organized in a chained linked-list, when an ethernet packet is received, the Rx-DMA will transfer the packet from RxFIFO to the driver receive buffers memory. Depending on the size of the received ethernet packet and the size of each ethernet driver receive buffer, the received packet can take one or more ethernet driver receive buffer. In below are defined the size of one ethernet driver receive buffer ETH_RX_BUF_SIZE and the total count of the driver receive buffers ETH_RXBUFNB. The configured value for ETH_RX_BUF_SIZE and ETH_RXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver receive buffer to fit the Max size Ethernet packet */ #ifndef ETH_RX_BUF_SIZE #define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 Ethernet driver receive buffers are used (in a chained linked list)*/ #ifndef ETH_RXBUFNB #define ETH_RXBUFNB 5U /* 5 Rx buffers of size ETH_RX_BUF_SIZE */ #endif /* Ethernet driver transmit buffers are organized in a chained linked-list, when an ethernet packet is transmitted, Tx-DMA will transfer the packet from the driver transmit buffers memory to the TxFIFO. Depending on the size of the Ethernet packet to be transmitted and the size of each ethernet driver transmit buffer, the packet to be transmitted can take one or more ethernet driver transmit buffer. In below are defined the size of one ethernet driver transmit buffer ETH_TX_BUF_SIZE and the total count of the driver transmit buffers ETH_TXBUFNB. The configured value for ETH_TX_BUF_SIZE and ETH_TXBUFNB are only provided as example, they can be reconfigured in the application layer to fit the application needs */ /* Here we configure each Ethernet driver transmit buffer to fit the Max size Ethernet packet */ #ifndef ETH_TX_BUF_SIZE #define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE #endif /* 5 ethernet driver transmit buffers are used (in a chained linked list)*/ #ifndef ETH_TXBUFNB #define ETH_TXBUFNB 5U /* 5 Tx buffers of size ETH_TX_BUF_SIZE */ #endif /** * @} */ /** @defgroup ETH_DMA_TX_Descriptor ETH DMA TX Descriptor * @{ */ /* DMA Tx Descriptor ----------------------------------------------------------------------------------------------- TDES0 | OWN(31) | CTRL[30:26] | Reserved[25:24] | CTRL[23:20] | Reserved[19:17] | Status[16:0] | ----------------------------------------------------------------------------------------------- TDES1 | Reserved[31:29] | Buffer2 ByteCount[28:16] | Reserved[15:13] | Buffer1 ByteCount[12:0] | ----------------------------------------------------------------------------------------------- TDES2 | Buffer1 Address [31:0] | ----------------------------------------------------------------------------------------------- TDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | ----------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of TDES0 register: DMA Tx descriptor status register */ #define ETH_DMATXDESC_OWN 0x80000000U /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMATXDESC_IC 0x40000000U /*!< Interrupt on Completion */ #define ETH_DMATXDESC_LS 0x20000000U /*!< Last Segment */ #define ETH_DMATXDESC_FS 0x10000000U /*!< First Segment */ #define ETH_DMATXDESC_DC 0x08000000U /*!< Disable CRC */ #define ETH_DMATXDESC_DP 0x04000000U /*!< Disable Padding */ #define ETH_DMATXDESC_TTSE 0x02000000U /*!< Transmit Time Stamp Enable */ #define ETH_DMATXDESC_CIC 0x00C00000U /*!< Checksum Insertion Control: 4 cases */ #define ETH_DMATXDESC_CIC_BYPASS 0x00000000U /*!< Do Nothing: Checksum Engine is bypassed */ #define ETH_DMATXDESC_CIC_IPV4HEADER 0x00400000U /*!< IPV4 header Checksum Insertion */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_SEGMENT 0x00800000U /*!< TCP/UDP/ICMP Checksum Insertion calculated over segment only */ #define ETH_DMATXDESC_CIC_TCPUDPICMP_FULL 0x00C00000U /*!< TCP/UDP/ICMP Checksum Insertion fully calculated */ #define ETH_DMATXDESC_TER 0x00200000U /*!< Transmit End of Ring */ #define ETH_DMATXDESC_TCH 0x00100000U /*!< Second Address Chained */ #define ETH_DMATXDESC_TTSS 0x00020000U /*!< Tx Time Stamp Status */ #define ETH_DMATXDESC_IHE 0x00010000U /*!< IP Header Error */ #define ETH_DMATXDESC_ES 0x00008000U /*!< Error summary: OR of the following bits: UE || ED || EC || LCO || NC || LCA || FF || JT */ #define ETH_DMATXDESC_JT 0x00004000U /*!< Jabber Timeout */ #define ETH_DMATXDESC_FF 0x00002000U /*!< Frame Flushed: DMA/MTL flushed the frame due to SW flush */ #define ETH_DMATXDESC_PCE 0x00001000U /*!< Payload Checksum Error */ #define ETH_DMATXDESC_LCA 0x00000800U /*!< Loss of Carrier: carrier lost during transmission */ #define ETH_DMATXDESC_NC 0x00000400U /*!< No Carrier: no carrier signal from the transceiver */ #define ETH_DMATXDESC_LCO 0x00000200U /*!< Late Collision: transmission aborted due to collision */ #define ETH_DMATXDESC_EC 0x00000100U /*!< Excessive Collision: transmission aborted after 16 collisions */ #define ETH_DMATXDESC_VF 0x00000080U /*!< VLAN Frame */ #define ETH_DMATXDESC_CC 0x00000078U /*!< Collision Count */ #define ETH_DMATXDESC_ED 0x00000004U /*!< Excessive Deferral */ #define ETH_DMATXDESC_UF 0x00000002U /*!< Underflow Error: late data arrival from the memory */ #define ETH_DMATXDESC_DB 0x00000001U /*!< Deferred Bit */ /** * @brief Bit definition of TDES1 register */ #define ETH_DMATXDESC_TBS2 0x1FFF0000U /*!< Transmit Buffer2 Size */ #define ETH_DMATXDESC_TBS1 0x00001FFFU /*!< Transmit Buffer1 Size */ /** * @brief Bit definition of TDES2 register */ #define ETH_DMATXDESC_B1AP 0xFFFFFFFFU /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of TDES3 register */ #define ETH_DMATXDESC_B2AP 0xFFFFFFFFU /*!< Buffer2 Address Pointer */ /** * @} */ /** @defgroup ETH_DMA_RX_Descriptor ETH DMA RX Descriptor * @{ */ /* DMA Rx Descriptor -------------------------------------------------------------------------------------------------------------------- RDES0 | OWN(31) | Status [30:0] | --------------------------------------------------------------------------------------------------------------------- RDES1 | CTRL(31) | Reserved[30:29] | Buffer2 ByteCount[28:16] | CTRL[15:14] | Reserved(13) | Buffer1 ByteCount[12:0] | --------------------------------------------------------------------------------------------------------------------- RDES2 | Buffer1 Address [31:0] | --------------------------------------------------------------------------------------------------------------------- RDES3 | Buffer2 Address [31:0] / Next Descriptor Address [31:0] | --------------------------------------------------------------------------------------------------------------------- */ /** * @brief Bit definition of RDES0 register: DMA Rx descriptor status register */ #define ETH_DMARXDESC_OWN 0x80000000U /*!< OWN bit: descriptor is owned by DMA engine */ #define ETH_DMARXDESC_AFM 0x40000000U /*!< DA Filter Fail for the rx frame */ #define ETH_DMARXDESC_FL 0x3FFF0000U /*!< Receive descriptor frame length */ #define ETH_DMARXDESC_ES 0x00008000U /*!< Error summary: OR of the following bits: DE || OE || IPC || LC || RWT || RE || CE */ #define ETH_DMARXDESC_DE 0x00004000U /*!< Descriptor error: no more descriptors for receive frame */ #define ETH_DMARXDESC_SAF 0x00002000U /*!< SA Filter Fail for the received frame */ #define ETH_DMARXDESC_LE 0x00001000U /*!< Frame size not matching with length field */ #define ETH_DMARXDESC_OE 0x00000800U /*!< Overflow Error: Frame was damaged due to buffer overflow */ #define ETH_DMARXDESC_VLAN 0x00000400U /*!< VLAN Tag: received frame is a VLAN frame */ #define ETH_DMARXDESC_FS 0x00000200U /*!< First descriptor of the frame */ #define ETH_DMARXDESC_LS 0x00000100U /*!< Last descriptor of the frame */ #define ETH_DMARXDESC_IPV4HCE 0x00000080U /*!< IPC Checksum Error: Rx Ipv4 header checksum error */ #define ETH_DMARXDESC_LC 0x00000040U /*!< Late collision occurred during reception */ #define ETH_DMARXDESC_FT 0x00000020U /*!< Frame type - Ethernet, otherwise 802.3 */ #define ETH_DMARXDESC_RWT 0x00000010U /*!< Receive Watchdog Timeout: watchdog timer expired during reception */ #define ETH_DMARXDESC_RE 0x00000008U /*!< Receive error: error reported by MII interface */ #define ETH_DMARXDESC_DBE 0x00000004U /*!< Dribble bit error: frame contains non int multiple of 8 bits */ #define ETH_DMARXDESC_CE 0x00000002U /*!< CRC error */ #define ETH_DMARXDESC_MAMPCE 0x00000001U /*!< Rx MAC Address/Payload Checksum Error: Rx MAC address matched/ Rx Payload Checksum Error */ /** * @brief Bit definition of RDES1 register */ #define ETH_DMARXDESC_DIC 0x80000000U /*!< Disable Interrupt on Completion */ #define ETH_DMARXDESC_RBS2 0x1FFF0000U /*!< Receive Buffer2 Size */ #define ETH_DMARXDESC_RER 0x00008000U /*!< Receive End of Ring */ #define ETH_DMARXDESC_RCH 0x00004000U /*!< Second Address Chained */ #define ETH_DMARXDESC_RBS1 0x00001FFFU /*!< Receive Buffer1 Size */ /** * @brief Bit definition of RDES2 register */ #define ETH_DMARXDESC_B1AP 0xFFFFFFFFU /*!< Buffer1 Address Pointer */ /** * @brief Bit definition of RDES3 register */ #define ETH_DMARXDESC_B2AP 0xFFFFFFFFU /*!< Buffer2 Address Pointer */ /** * @} */ /** @defgroup ETH_AutoNegotiation ETH AutoNegotiation * @{ */ #define ETH_AUTONEGOTIATION_ENABLE 0x00000001U #define ETH_AUTONEGOTIATION_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Speed ETH Speed * @{ */ #define ETH_SPEED_10M 0x00000000U #define ETH_SPEED_100M 0x00004000U /** * @} */ /** @defgroup ETH_Duplex_Mode ETH Duplex Mode * @{ */ #define ETH_MODE_FULLDUPLEX 0x00000800U #define ETH_MODE_HALFDUPLEX 0x00000000U /** * @} */ /** @defgroup ETH_Rx_Mode ETH Rx Mode * @{ */ #define ETH_RXPOLLING_MODE 0x00000000U #define ETH_RXINTERRUPT_MODE 0x00000001U /** * @} */ /** @defgroup ETH_Checksum_Mode ETH Checksum Mode * @{ */ #define ETH_CHECKSUM_BY_HARDWARE 0x00000000U #define ETH_CHECKSUM_BY_SOFTWARE 0x00000001U /** * @} */ /** @defgroup ETH_Media_Interface ETH Media Interface * @{ */ #define ETH_MEDIA_INTERFACE_MII 0x00000000U #define ETH_MEDIA_INTERFACE_RMII ((uint32_t)AFIO_MAPR_MII_RMII_SEL) /** * @} */ /** @defgroup ETH_Watchdog ETH Watchdog * @{ */ #define ETH_WATCHDOG_ENABLE 0x00000000U #define ETH_WATCHDOG_DISABLE 0x00800000U /** * @} */ /** @defgroup ETH_Jabber ETH Jabber * @{ */ #define ETH_JABBER_ENABLE 0x00000000U #define ETH_JABBER_DISABLE 0x00400000U /** * @} */ /** @defgroup ETH_Inter_Frame_Gap ETH Inter Frame Gap * @{ */ #define ETH_INTERFRAMEGAP_96BIT 0x00000000U /*!< minimum IFG between frames during transmission is 96Bit */ #define ETH_INTERFRAMEGAP_88BIT 0x00020000U /*!< minimum IFG between frames during transmission is 88Bit */ #define ETH_INTERFRAMEGAP_80BIT 0x00040000U /*!< minimum IFG between frames during transmission is 80Bit */ #define ETH_INTERFRAMEGAP_72BIT 0x00060000U /*!< minimum IFG between frames during transmission is 72Bit */ #define ETH_INTERFRAMEGAP_64BIT 0x00080000U /*!< minimum IFG between frames during transmission is 64Bit */ #define ETH_INTERFRAMEGAP_56BIT 0x000A0000U /*!< minimum IFG between frames during transmission is 56Bit */ #define ETH_INTERFRAMEGAP_48BIT 0x000C0000U /*!< minimum IFG between frames during transmission is 48Bit */ #define ETH_INTERFRAMEGAP_40BIT 0x000E0000U /*!< minimum IFG between frames during transmission is 40Bit */ /** * @} */ /** @defgroup ETH_Carrier_Sense ETH Carrier Sense * @{ */ #define ETH_CARRIERSENCE_ENABLE 0x00000000U #define ETH_CARRIERSENCE_DISABLE 0x00010000U /** * @} */ /** @defgroup ETH_Receive_Own ETH Receive Own * @{ */ #define ETH_RECEIVEOWN_ENABLE 0x00000000U #define ETH_RECEIVEOWN_DISABLE 0x00002000U /** * @} */ /** @defgroup ETH_Loop_Back_Mode ETH Loop Back Mode * @{ */ #define ETH_LOOPBACKMODE_ENABLE 0x00001000U #define ETH_LOOPBACKMODE_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Checksum_Offload ETH Checksum Offload * @{ */ #define ETH_CHECKSUMOFFLAOD_ENABLE 0x00000400U #define ETH_CHECKSUMOFFLAOD_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Retry_Transmission ETH Retry Transmission * @{ */ #define ETH_RETRYTRANSMISSION_ENABLE 0x00000000U #define ETH_RETRYTRANSMISSION_DISABLE 0x00000200U /** * @} */ /** @defgroup ETH_Automatic_Pad_CRC_Strip ETH Automatic Pad CRC Strip * @{ */ #define ETH_AUTOMATICPADCRCSTRIP_ENABLE 0x00000080U #define ETH_AUTOMATICPADCRCSTRIP_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Back_Off_Limit ETH Back Off Limit * @{ */ #define ETH_BACKOFFLIMIT_10 0x00000000U #define ETH_BACKOFFLIMIT_8 0x00000020U #define ETH_BACKOFFLIMIT_4 0x00000040U #define ETH_BACKOFFLIMIT_1 0x00000060U /** * @} */ /** @defgroup ETH_Deferral_Check ETH Deferral Check * @{ */ #define ETH_DEFFERRALCHECK_ENABLE 0x00000010U #define ETH_DEFFERRALCHECK_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Receive_All ETH Receive All * @{ */ #define ETH_RECEIVEALL_ENABLE 0x80000000U #define ETH_RECEIVEAll_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Source_Addr_Filter ETH Source Addr Filter * @{ */ #define ETH_SOURCEADDRFILTER_NORMAL_ENABLE 0x00000200U #define ETH_SOURCEADDRFILTER_INVERSE_ENABLE 0x00000300U #define ETH_SOURCEADDRFILTER_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Pass_Control_Frames ETH Pass Control Frames * @{ */ #define ETH_PASSCONTROLFRAMES_BLOCKALL 0x00000040U /*!< MAC filters all control frames from reaching the application */ #define ETH_PASSCONTROLFRAMES_FORWARDALL 0x00000080U /*!< MAC forwards all control frames to application even if they fail the Address Filter */ #define ETH_PASSCONTROLFRAMES_FORWARDPASSEDADDRFILTER 0x000000C0U /*!< MAC forwards control frames that pass the Address Filter. */ /** * @} */ /** @defgroup ETH_Broadcast_Frames_Reception ETH Broadcast Frames Reception * @{ */ #define ETH_BROADCASTFRAMESRECEPTION_ENABLE 0x00000000U #define ETH_BROADCASTFRAMESRECEPTION_DISABLE 0x00000020U /** * @} */ /** @defgroup ETH_Destination_Addr_Filter ETH Destination Addr Filter * @{ */ #define ETH_DESTINATIONADDRFILTER_NORMAL 0x00000000U #define ETH_DESTINATIONADDRFILTER_INVERSE 0x00000008U /** * @} */ /** @defgroup ETH_Promiscuous_Mode ETH Promiscuous Mode * @{ */ #define ETH_PROMISCUOUS_MODE_ENABLE 0x00000001U #define ETH_PROMISCUOUS_MODE_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Multicast_Frames_Filter ETH Multicast Frames Filter * @{ */ #define ETH_MULTICASTFRAMESFILTER_PERFECTHASHTABLE 0x00000404U #define ETH_MULTICASTFRAMESFILTER_HASHTABLE 0x00000004U #define ETH_MULTICASTFRAMESFILTER_PERFECT 0x00000000U #define ETH_MULTICASTFRAMESFILTER_NONE 0x00000010U /** * @} */ /** @defgroup ETH_Unicast_Frames_Filter ETH Unicast Frames Filter * @{ */ #define ETH_UNICASTFRAMESFILTER_PERFECTHASHTABLE 0x00000402U #define ETH_UNICASTFRAMESFILTER_HASHTABLE 0x00000002U #define ETH_UNICASTFRAMESFILTER_PERFECT 0x00000000U /** * @} */ /** @defgroup ETH_Zero_Quanta_Pause ETH Zero Quanta Pause * @{ */ #define ETH_ZEROQUANTAPAUSE_ENABLE 0x00000000U #define ETH_ZEROQUANTAPAUSE_DISABLE 0x00000080U /** * @} */ /** @defgroup ETH_Pause_Low_Threshold ETH Pause Low Threshold * @{ */ #define ETH_PAUSELOWTHRESHOLD_MINUS4 0x00000000U /*!< Pause time minus 4 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS28 0x00000010U /*!< Pause time minus 28 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS144 0x00000020U /*!< Pause time minus 144 slot times */ #define ETH_PAUSELOWTHRESHOLD_MINUS256 0x00000030U /*!< Pause time minus 256 slot times */ /** * @} */ /** @defgroup ETH_Unicast_Pause_Frame_Detect ETH Unicast Pause Frame Detect * @{ */ #define ETH_UNICASTPAUSEFRAMEDETECT_ENABLE 0x00000008U #define ETH_UNICASTPAUSEFRAMEDETECT_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Receive_Flow_Control ETH Receive Flow Control * @{ */ #define ETH_RECEIVEFLOWCONTROL_ENABLE 0x00000004U #define ETH_RECEIVEFLOWCONTROL_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Transmit_Flow_Control ETH Transmit Flow Control * @{ */ #define ETH_TRANSMITFLOWCONTROL_ENABLE 0x00000002U #define ETH_TRANSMITFLOWCONTROL_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_VLAN_Tag_Comparison ETH VLAN Tag Comparison * @{ */ #define ETH_VLANTAGCOMPARISON_12BIT 0x00010000U #define ETH_VLANTAGCOMPARISON_16BIT 0x00000000U /** * @} */ /** @defgroup ETH_MAC_addresses ETH MAC addresses * @{ */ #define ETH_MAC_ADDRESS0 0x00000000U #define ETH_MAC_ADDRESS1 0x00000008U #define ETH_MAC_ADDRESS2 0x00000010U #define ETH_MAC_ADDRESS3 0x00000018U /** * @} */ /** @defgroup ETH_MAC_addresses_filter_SA_DA ETH MAC addresses filter SA DA * @{ */ #define ETH_MAC_ADDRESSFILTER_SA 0x00000000U #define ETH_MAC_ADDRESSFILTER_DA 0x00000008U /** * @} */ /** @defgroup ETH_MAC_addresses_filter_Mask_bytes ETH MAC addresses filter Mask bytes * @{ */ #define ETH_MAC_ADDRESSMASK_BYTE6 0x20000000U /*!< Mask MAC Address high reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE5 0x10000000U /*!< Mask MAC Address high reg bits [7:0] */ #define ETH_MAC_ADDRESSMASK_BYTE4 0x08000000U /*!< Mask MAC Address low reg bits [31:24] */ #define ETH_MAC_ADDRESSMASK_BYTE3 0x04000000U /*!< Mask MAC Address low reg bits [23:16] */ #define ETH_MAC_ADDRESSMASK_BYTE2 0x02000000U /*!< Mask MAC Address low reg bits [15:8] */ #define ETH_MAC_ADDRESSMASK_BYTE1 0x01000000U /*!< Mask MAC Address low reg bits [70] */ /** * @} */ /** @defgroup ETH_Drop_TCP_IP_Checksum_Error_Frame ETH Drop TCP IP Checksum Error Frame * @{ */ #define ETH_DROPTCPIPCHECKSUMERRORFRAME_ENABLE 0x00000000U #define ETH_DROPTCPIPCHECKSUMERRORFRAME_DISABLE 0x04000000U /** * @} */ /** @defgroup ETH_Receive_Store_Forward ETH Receive Store Forward * @{ */ #define ETH_RECEIVESTOREFORWARD_ENABLE 0x02000000U #define ETH_RECEIVESTOREFORWARD_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Flush_Received_Frame ETH Flush Received Frame * @{ */ #define ETH_FLUSHRECEIVEDFRAME_ENABLE 0x00000000U #define ETH_FLUSHRECEIVEDFRAME_DISABLE 0x01000000U /** * @} */ /** @defgroup ETH_Transmit_Store_Forward ETH Transmit Store Forward * @{ */ #define ETH_TRANSMITSTOREFORWARD_ENABLE 0x00200000U #define ETH_TRANSMITSTOREFORWARD_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Transmit_Threshold_Control ETH Transmit Threshold Control * @{ */ #define ETH_TRANSMITTHRESHOLDCONTROL_64BYTES 0x00000000U /*!< threshold level of the MTL Transmit FIFO is 64 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_128BYTES 0x00004000U /*!< threshold level of the MTL Transmit FIFO is 128 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_192BYTES 0x00008000U /*!< threshold level of the MTL Transmit FIFO is 192 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_256BYTES 0x0000C000U /*!< threshold level of the MTL Transmit FIFO is 256 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_40BYTES 0x00010000U /*!< threshold level of the MTL Transmit FIFO is 40 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_32BYTES 0x00014000U /*!< threshold level of the MTL Transmit FIFO is 32 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_24BYTES 0x00018000U /*!< threshold level of the MTL Transmit FIFO is 24 Bytes */ #define ETH_TRANSMITTHRESHOLDCONTROL_16BYTES 0x0001C000U /*!< threshold level of the MTL Transmit FIFO is 16 Bytes */ /** * @} */ /** @defgroup ETH_Forward_Error_Frames ETH Forward Error Frames * @{ */ #define ETH_FORWARDERRORFRAMES_ENABLE 0x00000080U #define ETH_FORWARDERRORFRAMES_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Forward_Undersized_Good_Frames ETH Forward Undersized Good Frames * @{ */ #define ETH_FORWARDUNDERSIZEDGOODFRAMES_ENABLE 0x00000040U #define ETH_FORWARDUNDERSIZEDGOODFRAMES_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Receive_Threshold_Control ETH Receive Threshold Control * @{ */ #define ETH_RECEIVEDTHRESHOLDCONTROL_64BYTES 0x00000000U /*!< threshold level of the MTL Receive FIFO is 64 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_32BYTES 0x00000008U /*!< threshold level of the MTL Receive FIFO is 32 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_96BYTES 0x00000010U /*!< threshold level of the MTL Receive FIFO is 96 Bytes */ #define ETH_RECEIVEDTHRESHOLDCONTROL_128BYTES 0x00000018U /*!< threshold level of the MTL Receive FIFO is 128 Bytes */ /** * @} */ /** @defgroup ETH_Second_Frame_Operate ETH Second Frame Operate * @{ */ #define ETH_SECONDFRAMEOPERARTE_ENABLE 0x00000004U #define ETH_SECONDFRAMEOPERARTE_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Address_Aligned_Beats ETH Address Aligned Beats * @{ */ #define ETH_ADDRESSALIGNEDBEATS_ENABLE 0x02000000U #define ETH_ADDRESSALIGNEDBEATS_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Fixed_Burst ETH Fixed Burst * @{ */ #define ETH_FIXEDBURST_ENABLE 0x00010000U #define ETH_FIXEDBURST_DISABLE 0x00000000U /** * @} */ /** @defgroup ETH_Rx_DMA_Burst_Length ETH Rx DMA Burst Length * @{ */ #define ETH_RXDMABURSTLENGTH_1BEAT 0x00020000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 1 */ #define ETH_RXDMABURSTLENGTH_2BEAT 0x00040000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 2 */ #define ETH_RXDMABURSTLENGTH_4BEAT 0x00080000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_8BEAT 0x00100000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_16BEAT 0x00200000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_32BEAT 0x00400000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_4BEAT 0x01020000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 4 */ #define ETH_RXDMABURSTLENGTH_4XPBL_8BEAT 0x01040000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 8 */ #define ETH_RXDMABURSTLENGTH_4XPBL_16BEAT 0x01080000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 16 */ #define ETH_RXDMABURSTLENGTH_4XPBL_32BEAT 0x01100000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 32 */ #define ETH_RXDMABURSTLENGTH_4XPBL_64BEAT 0x01200000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 64 */ #define ETH_RXDMABURSTLENGTH_4XPBL_128BEAT 0x01400000U /*!< maximum number of beats to be transferred in one RxDMA transaction is 128 */ /** * @} */ /** @defgroup ETH_Tx_DMA_Burst_Length ETH Tx DMA Burst Length * @{ */ #define ETH_TXDMABURSTLENGTH_1BEAT 0x00000100U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 1 */ #define ETH_TXDMABURSTLENGTH_2BEAT 0x00000200U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 2 */ #define ETH_TXDMABURSTLENGTH_4BEAT 0x00000400U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_8BEAT 0x00000800U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_16BEAT 0x00001000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_32BEAT 0x00002000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_4BEAT 0x01000100U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 4 */ #define ETH_TXDMABURSTLENGTH_4XPBL_8BEAT 0x01000200U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 8 */ #define ETH_TXDMABURSTLENGTH_4XPBL_16BEAT 0x01000400U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 16 */ #define ETH_TXDMABURSTLENGTH_4XPBL_32BEAT 0x01000800U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 32 */ #define ETH_TXDMABURSTLENGTH_4XPBL_64BEAT 0x01001000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 64 */ #define ETH_TXDMABURSTLENGTH_4XPBL_128BEAT 0x01002000U /*!< maximum number of beats to be transferred in one TxDMA (or both) transaction is 128 */ /** * @} */ /** @defgroup ETH_DMA_Arbitration ETH DMA Arbitration * @{ */ #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1 0x00000000U #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_2_1 0x00004000U #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_3_1 0x00008000U #define ETH_DMAARBITRATION_ROUNDROBIN_RXTX_4_1 0x0000C000U #define ETH_DMAARBITRATION_RXPRIORTX 0x00000002U /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_segment ETH DMA Tx descriptor segment * @{ */ #define ETH_DMATXDESC_LASTSEGMENTS 0x40000000U /*!< Last Segment */ #define ETH_DMATXDESC_FIRSTSEGMENT 0x20000000U /*!< First Segment */ /** * @} */ /** @defgroup ETH_DMA_Tx_descriptor_Checksum_Insertion_Control ETH DMA Tx descriptor Checksum Insertion Control * @{ */ #define ETH_DMATXDESC_CHECKSUMBYPASS 0x00000000U /*!< Checksum engine bypass */ #define ETH_DMATXDESC_CHECKSUMIPV4HEADER 0x00400000U /*!< IPv4 header checksum insertion */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT 0x00800000U /*!< TCP/UDP/ICMP checksum insertion. Pseudo header checksum is assumed to be present */ #define ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL 0x00C00000U /*!< TCP/UDP/ICMP checksum fully in hardware including pseudo header */ /** * @} */ /** @defgroup ETH_DMA_Rx_descriptor_buffers ETH DMA Rx descriptor buffers * @{ */ #define ETH_DMARXDESC_BUFFER1 0x00000000U /*!< DMA Rx Desc Buffer1 */ #define ETH_DMARXDESC_BUFFER2 0x00000001U /*!< DMA Rx Desc Buffer2 */ /** * @} */ /** @defgroup ETH_PMT_Flags ETH PMT Flags * @{ */ #define ETH_PMT_FLAG_WUFFRPR 0x80000000U /*!< Wake-Up Frame Filter Register Pointer Reset */ #define ETH_PMT_FLAG_WUFR 0x00000040U /*!< Wake-Up Frame Received */ #define ETH_PMT_FLAG_MPR 0x00000020U /*!< Magic Packet Received */ /** * @} */ /** @defgroup ETH_MMC_Tx_Interrupts ETH MMC Tx Interrupts * @{ */ #define ETH_MMC_IT_TGF 0x00200000U /*!< When Tx good frame counter reaches half the maximum value */ #define ETH_MMC_IT_TGFMSC 0x00008000U /*!< When Tx good multi col counter reaches half the maximum value */ #define ETH_MMC_IT_TGFSC 0x00004000U /*!< When Tx good single col counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MMC_Rx_Interrupts ETH MMC Rx Interrupts * @{ */ #define ETH_MMC_IT_RGUF 0x10020000U /*!< When Rx good unicast frames counter reaches half the maximum value */ #define ETH_MMC_IT_RFAE 0x10000040U /*!< When Rx alignment error counter reaches half the maximum value */ #define ETH_MMC_IT_RFCE 0x10000020U /*!< When Rx crc error counter reaches half the maximum value */ /** * @} */ /** @defgroup ETH_MAC_Flags ETH MAC Flags * @{ */ #define ETH_MAC_FLAG_TST 0x00000200U /*!< Time stamp trigger flag (on MAC) */ #define ETH_MAC_FLAG_MMCT 0x00000040U /*!< MMC transmit flag */ #define ETH_MAC_FLAG_MMCR 0x00000020U /*!< MMC receive flag */ #define ETH_MAC_FLAG_MMC 0x00000010U /*!< MMC flag (on MAC) */ #define ETH_MAC_FLAG_PMT 0x00000008U /*!< PMT flag (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Flags ETH DMA Flags * @{ */ #define ETH_DMA_FLAG_TST 0x20000000U /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_FLAG_PMT 0x10000000U /*!< PMT interrupt (on DMA) */ #define ETH_DMA_FLAG_MMC 0x08000000U /*!< MMC interrupt (on DMA) */ #define ETH_DMA_FLAG_DATATRANSFERERROR 0x00800000U /*!< Error bits 0-Rx DMA, 1-Tx DMA */ #define ETH_DMA_FLAG_READWRITEERROR 0x01000000U /*!< Error bits 0-write transfer, 1-read transfer */ #define ETH_DMA_FLAG_ACCESSERROR 0x02000000U /*!< Error bits 0-data buffer, 1-desc. access */ #define ETH_DMA_FLAG_NIS 0x00010000U /*!< Normal interrupt summary flag */ #define ETH_DMA_FLAG_AIS 0x00008000U /*!< Abnormal interrupt summary flag */ #define ETH_DMA_FLAG_ER 0x00004000U /*!< Early receive flag */ #define ETH_DMA_FLAG_FBE 0x00002000U /*!< Fatal bus error flag */ #define ETH_DMA_FLAG_ET 0x00000400U /*!< Early transmit flag */ #define ETH_DMA_FLAG_RWT 0x00000200U /*!< Receive watchdog timeout flag */ #define ETH_DMA_FLAG_RPS 0x00000100U /*!< Receive process stopped flag */ #define ETH_DMA_FLAG_RBU 0x00000080U /*!< Receive buffer unavailable flag */ #define ETH_DMA_FLAG_R 0x00000040U /*!< Receive flag */ #define ETH_DMA_FLAG_TU 0x00000020U /*!< Underflow flag */ #define ETH_DMA_FLAG_RO 0x00000010U /*!< Overflow flag */ #define ETH_DMA_FLAG_TJT 0x00000008U /*!< Transmit jabber timeout flag */ #define ETH_DMA_FLAG_TBU 0x00000004U /*!< Transmit buffer unavailable flag */ #define ETH_DMA_FLAG_TPS 0x00000002U /*!< Transmit process stopped flag */ #define ETH_DMA_FLAG_T 0x00000001U /*!< Transmit flag */ /** * @} */ /** @defgroup ETH_MAC_Interrupts ETH MAC Interrupts * @{ */ #define ETH_MAC_IT_TST 0x00000200U /*!< Time stamp trigger interrupt (on MAC) */ #define ETH_MAC_IT_MMCT 0x00000040U /*!< MMC transmit interrupt */ #define ETH_MAC_IT_MMCR 0x00000020U /*!< MMC receive interrupt */ #define ETH_MAC_IT_MMC 0x00000010U /*!< MMC interrupt (on MAC) */ #define ETH_MAC_IT_PMT 0x00000008U /*!< PMT interrupt (on MAC) */ /** * @} */ /** @defgroup ETH_DMA_Interrupts ETH DMA Interrupts * @{ */ #define ETH_DMA_IT_TST 0x20000000U /*!< Time-stamp trigger interrupt (on DMA) */ #define ETH_DMA_IT_PMT 0x10000000U /*!< PMT interrupt (on DMA) */ #define ETH_DMA_IT_MMC 0x08000000U /*!< MMC interrupt (on DMA) */ #define ETH_DMA_IT_NIS 0x00010000U /*!< Normal interrupt summary */ #define ETH_DMA_IT_AIS 0x00008000U /*!< Abnormal interrupt summary */ #define ETH_DMA_IT_ER 0x00004000U /*!< Early receive interrupt */ #define ETH_DMA_IT_FBE 0x00002000U /*!< Fatal bus error interrupt */ #define ETH_DMA_IT_ET 0x00000400U /*!< Early transmit interrupt */ #define ETH_DMA_IT_RWT 0x00000200U /*!< Receive watchdog timeout interrupt */ #define ETH_DMA_IT_RPS 0x00000100U /*!< Receive process stopped interrupt */ #define ETH_DMA_IT_RBU 0x00000080U /*!< Receive buffer unavailable interrupt */ #define ETH_DMA_IT_R 0x00000040U /*!< Receive interrupt */ #define ETH_DMA_IT_TU 0x00000020U /*!< Underflow interrupt */ #define ETH_DMA_IT_RO 0x00000010U /*!< Overflow interrupt */ #define ETH_DMA_IT_TJT 0x00000008U /*!< Transmit jabber timeout interrupt */ #define ETH_DMA_IT_TBU 0x00000004U /*!< Transmit buffer unavailable interrupt */ #define ETH_DMA_IT_TPS 0x00000002U /*!< Transmit process stopped interrupt */ #define ETH_DMA_IT_T 0x00000001U /*!< Transmit interrupt */ /** * @} */ /** @defgroup ETH_DMA_transmit_process_state ETH DMA transmit process state * @{ */ #define ETH_DMA_TRANSMITPROCESS_STOPPED 0x00000000U /*!< Stopped - Reset or Stop Tx Command issued */ #define ETH_DMA_TRANSMITPROCESS_FETCHING 0x00100000U /*!< Running - fetching the Tx descriptor */ #define ETH_DMA_TRANSMITPROCESS_WAITING 0x00200000U /*!< Running - waiting for status */ #define ETH_DMA_TRANSMITPROCESS_READING 0x00300000U /*!< Running - reading the data from host memory */ #define ETH_DMA_TRANSMITPROCESS_SUSPENDED 0x00600000U /*!< Suspended - Tx Descriptor unavailable */ #define ETH_DMA_TRANSMITPROCESS_CLOSING 0x00700000U /*!< Running - closing Rx descriptor */ /** * @} */ /** @defgroup ETH_DMA_receive_process_state ETH DMA receive process state * @{ */ #define ETH_DMA_RECEIVEPROCESS_STOPPED 0x00000000U /*!< Stopped - Reset or Stop Rx Command issued */ #define ETH_DMA_RECEIVEPROCESS_FETCHING 0x00020000U /*!< Running - fetching the Rx descriptor */ #define ETH_DMA_RECEIVEPROCESS_WAITING 0x00060000U /*!< Running - waiting for packet */ #define ETH_DMA_RECEIVEPROCESS_SUSPENDED 0x00080000U /*!< Suspended - Rx Descriptor unavailable */ #define ETH_DMA_RECEIVEPROCESS_CLOSING 0x000A0000U /*!< Running - closing descriptor */ #define ETH_DMA_RECEIVEPROCESS_QUEUING 0x000E0000U /*!< Running - queuing the receive frame into host memory */ /** * @} */ /** @defgroup ETH_DMA_overflow ETH DMA overflow * @{ */ #define ETH_DMA_OVERFLOW_RXFIFOCOUNTER 0x10000000U /*!< Overflow bit for FIFO overflow counter */ #define ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER 0x00010000U /*!< Overflow bit for missed frame counter */ /** * @} */ /** @defgroup ETH_EXTI_LINE_WAKEUP ETH EXTI LINE WAKEUP * @{ */ #define ETH_EXTI_LINE_WAKEUP 0x00080000U /*!< External interrupt line 19 Connected to the ETH EXTI Line */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup ETH_Exported_Macros ETH Exported Macros * @brief macros to handle interrupts and specific clock configurations * @{ */ /** @brief Reset ETH handle state * @param __HANDLE__: specifies the ETH handle. * @retval None */ #define __HAL_ETH_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ETH_STATE_RESET) /** * @brief Checks whether the specified ETHERNET DMA Tx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of TDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMATXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->TxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA Rx Desc flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag of RDES0 to check. * @retval the ETH_DMATxDescFlag (SET or RESET). */ #define __HAL_ETH_DMARXDESC_GET_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->RxDesc->Status & (__FLAG__) == (__FLAG__)) /** * @brief Enables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize &=(~(uint32_t)ETH_DMARXDESC_DIC)) /** * @brief Disables the specified DMA Rx Desc receive interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->RxDesc->ControlBufferSize |= ETH_DMARXDESC_DIC) /** * @brief Set the specified DMA Rx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMARXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->RxDesc->Status |= ETH_DMARXDESC_OWN) /** * @brief Returns the specified ETHERNET DMA Tx Desc collision count. * @param __HANDLE__: ETH Handle * @retval The Transmit descriptor collision counter value. */ #define __HAL_ETH_DMATXDESC_GET_COLLISION_COUNT(__HANDLE__) (((__HANDLE__)->TxDesc->Status & ETH_DMATXDESC_CC) >> ETH_DMATXDESC_COLLISION_COUNTSHIFT) /** * @brief Set the specified DMA Tx Desc Own bit. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SET_OWN_BIT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_OWN) /** * @brief Enables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_ENABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_IC) /** * @brief Disables the specified DMA Tx Desc Transmit interrupt. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_DISABLE_IT(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_IC) /** * @brief Selects the specified ETHERNET DMA Tx Desc Checksum Insertion. * @param __HANDLE__: ETH Handle * @param __CHECKSUM__: specifies is the DMA Tx desc checksum insertion. * This parameter can be one of the following values: * @arg ETH_DMATXDESC_CHECKSUMBYPASS : Checksum bypass * @arg ETH_DMATXDESC_CHECKSUMIPV4HEADER : IPv4 header checksum * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPSEGMENT : TCP/UDP/ICMP checksum. Pseudo header checksum is assumed to be present * @arg ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL : TCP/UDP/ICMP checksum fully in hardware including pseudo header * @retval None */ #define __HAL_ETH_DMATXDESC_CHECKSUM_INSERTION(__HANDLE__, __CHECKSUM__) ((__HANDLE__)->TxDesc->Status |= (__CHECKSUM__)) /** * @brief Enables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DC) /** * @brief Disables the DMA Tx Desc CRC. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_CRC_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DC) /** * @brief Enables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_ENABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status &= ~ETH_DMATXDESC_DP) /** * @brief Disables the DMA Tx Desc padding for frame shorter than 64 bytes. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_DMATXDESC_SHORT_FRAME_PADDING_DISABLE(__HANDLE__) ((__HANDLE__)->TxDesc->Status |= ETH_DMATXDESC_DP) /** * @brief Enables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MAC interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET MAC interrupt sources to be * enabled or disabled. * This parameter can be any combination of the following values: * @arg ETH_MAC_IT_TST : Time stamp trigger interrupt * @arg ETH_MAC_IT_PMT : PMT interrupt * @retval None */ #define __HAL_ETH_MAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MACIMR &= ~(__INTERRUPT__)) /** * @brief Initiate a Pause Control Frame (Full-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_INITIATE_PAUSE_CONTROL_FRAME(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Checks whether the ETHERNET flow control busy bit is set or not. * @param __HANDLE__: ETH Handle * @retval The new state of flow control busy status bit (SET or RESET). */ #define __HAL_ETH_GET_FLOW_CONTROL_BUSY_STATUS(__HANDLE__) (((__HANDLE__)->Instance->MACFCR & ETH_MACFCR_FCBBPA) == ETH_MACFCR_FCBBPA) /** * @brief Enables the MAC Back Pressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR |= ETH_MACFCR_FCBBPA) /** * @brief Disables the MAC BackPressure operation activation (Half-duplex only). * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_BACK_PRESSURE_ACTIVATION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACFCR &= ~ETH_MACFCR_FCBBPA) /** * @brief Checks whether the specified ETHERNET MAC flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_MAC_FLAG_TST : Time stamp trigger flag * @arg ETH_MAC_FLAG_MMCT : MMC transmit flag * @arg ETH_MAC_FLAG_MMCR : MMC receive flag * @arg ETH_MAC_FLAG_MMC : MMC flag * @arg ETH_MAC_FLAG_PMT : PMT flag * @retval The state of ETHERNET MAC flag. */ #define __HAL_ETH_MAC_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Enables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * enabled @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER |= (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET DMA interrupts. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the ETHERNET DMA interrupt sources to be * disabled. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMAIER &= ~(__INTERRUPT__)) /** * @brief Clears the ETHERNET DMA IT pending bit. * @param __HANDLE__ : ETH Handle * @param __INTERRUPT__: specifies the interrupt pending bit to clear. @ref ETH_DMA_Interrupts * @retval None */ #define __HAL_ETH_DMA_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DMASR =(__INTERRUPT__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to check. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->DMASR &( __FLAG__)) == ( __FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA flag is set or not. * @param __HANDLE__: ETH Handle * @param __FLAG__: specifies the flag to clear. @ref ETH_DMA_Flags * @retval The new state of ETH_DMA_FLAG (SET or RESET). */ #define __HAL_ETH_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->DMASR = (__FLAG__)) /** * @brief Checks whether the specified ETHERNET DMA overflow flag is set or not. * @param __HANDLE__: ETH Handle * @param __OVERFLOW__: specifies the DMA overflow flag to check. * This parameter can be one of the following values: * @arg ETH_DMA_OVERFLOW_RXFIFOCOUNTER : Overflow for FIFO Overflows Counter * @arg ETH_DMA_OVERFLOW_MISSEDFRAMECOUNTER : Overflow for Buffer Unavailable Missed Frame Counter * @retval The state of ETHERNET DMA overflow Flag (SET or RESET). */ #define __HAL_ETH_GET_DMA_OVERFLOW_STATUS(__HANDLE__, __OVERFLOW__) (((__HANDLE__)->Instance->DMAMFBOCR & (__OVERFLOW__)) == (__OVERFLOW__)) /** * @brief Set the DMA Receive status watchdog timer register value * @param __HANDLE__: ETH Handle * @param __VALUE__: DMA Receive status watchdog timer register value * @retval None */ #define __HAL_ETH_SET_RECEIVE_WATCHDOG_TIMER(__HANDLE__, __VALUE__) ((__HANDLE__)->Instance->DMARSWTR = (__VALUE__)) /** * @brief Enables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_GU) /** * @brief Disables any unicast packet filtered by the MAC address * recognition to be a wake-up frame. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_GLOBAL_UNICAST_WAKEUP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_GU) /** * @brief Enables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_WFE) /** * @brief Disables the MAC Wake-Up Frame Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_WAKEUP_FRAME_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_MPE) /** * @brief Disables the MAC Magic Packet Detection. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MAGIC_PACKET_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_WFE) /** * @brief Enables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR |= ETH_MACPMTCSR_PD) /** * @brief Disables the MAC Power Down. * @param __HANDLE__: ETH Handle * @retval None */ #define __HAL_ETH_POWER_DOWN_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MACPMTCSR &= ~ETH_MACPMTCSR_PD) /** * @brief Checks whether the specified ETHERNET PMT flag is set or not. * @param __HANDLE__: ETH Handle. * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg ETH_PMT_FLAG_WUFFRPR : Wake-Up Frame Filter Register Pointer Reset * @arg ETH_PMT_FLAG_WUFR : Wake-Up Frame Received * @arg ETH_PMT_FLAG_MPR : Magic Packet Received * @retval The new state of ETHERNET PMT Flag (SET or RESET). */ #define __HAL_ETH_GET_PMT_FLAG_STATUS(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->MACPMTCSR &( __FLAG__)) == ( __FLAG__)) /** * @brief Preset and Initialize the MMC counters to almost-full value: 0xFFFF_FFF0 (full - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FULL_PRESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= (ETH_MMCCR_MCFHP | ETH_MMCCR_MCP)) /** * @brief Preset and Initialize the MMC counters to almost-half value: 0x7FFF_FFF0 (half - 16) * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_HALF_PRESET(__HANDLE__) do{(__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCFHP;\ (__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCP;} while(0U) /** * @brief Enables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_MCF) /** * @brief Disables the MMC Counter Freeze. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTER_FREEZE_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_MCF) /** * @brief Enables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_ROR) /** * @brief Disables the MMC Reset On Read. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_RESET_ONREAD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_ROR) /** * @brief Enables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR &= ~ETH_MMCCR_CSR) /** * @brief Disables the MMC Counter Stop Rollover. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_ETH_MMC_COUNTER_ROLLOVER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CSR) /** * @brief Resets the MMC Counters. * @param __HANDLE__: ETH Handle. * @retval None */ #define __HAL_ETH_MMC_COUNTERS_RESET(__HANDLE__) ((__HANDLE__)->Instance->MMCCR |= ETH_MMCCR_CR) /** * @brief Enables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_ENABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR &= ~((__INTERRUPT__) & 0xEFFFFFFFU) /** * @brief Disables the specified ETHERNET MMC Rx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_RGUF : When Rx good unicast frames counter reaches half the maximum value * @arg ETH_MMC_IT_RFAE : When Rx alignment error counter reaches half the maximum value * @arg ETH_MMC_IT_RFCE : When Rx crc error counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_RX_IT_DISABLE(__HANDLE__, __INTERRUPT__) (__HANDLE__)->Instance->MMCRIMR |= ((__INTERRUPT__) & 0xEFFFFFFFU) /** * @brief Enables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_ENABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR &= ~ (__INTERRUPT__)) /** * @brief Disables the specified ETHERNET MMC Tx interrupts. * @param __HANDLE__: ETH Handle. * @param __INTERRUPT__: specifies the ETHERNET MMC interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * @arg ETH_MMC_IT_TGF : When Tx good frame counter reaches half the maximum value * @arg ETH_MMC_IT_TGFMSC: When Tx good multi col counter reaches half the maximum value * @arg ETH_MMC_IT_TGFSC : When Tx good single col counter reaches half the maximum value * @retval None */ #define __HAL_ETH_MMC_TX_IT_DISABLE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->MMCRIMR |= (__INTERRUPT__)) /** * @brief Enables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_IT() EXTI->IMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_IT() EXTI->IMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enable event on ETH External event line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_EVENT() EXTI->EMR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disable event on ETH External event line * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_EVENT() EXTI->EMR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Get flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_GET_FLAG() EXTI->PR & (ETH_EXTI_LINE_WAKEUP) /** * @brief Clear flag of the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_CLEAR_FLAG() EXTI->PR = (ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_RISING_EDGE_TRIGGER() EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP /** * @brief Disables the rising edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_RISING_EDGE_TRIGGER() EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR |= (ETH_EXTI_LINE_WAKEUP) /** * @brief Disables falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLING_EDGE_TRIGGER() EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP) /** * @brief Enables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_ENABLE_FALLINGRISING_TRIGGER() do{EXTI->RTSR |= ETH_EXTI_LINE_WAKEUP;\ EXTI->FTSR |= ETH_EXTI_LINE_WAKEUP;\ }while(0U) /** * @brief Disables rising/falling edge trigger to the ETH External interrupt line. * @retval None */ #define __HAL_ETH_WAKEUP_EXTI_DISABLE_FALLINGRISING_TRIGGER() do{EXTI->RTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ EXTI->FTSR &= ~(ETH_EXTI_LINE_WAKEUP);\ }while(0U) /** * @brief Generate a Software interrupt on selected EXTI line. * @retval None. */ #define __HAL_ETH_WAKEUP_EXTI_GENERATE_SWIT() EXTI->SWIER|= ETH_EXTI_LINE_WAKEUP /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup ETH_Exported_Functions * @{ */ /* Initialization and de-initialization functions ****************************/ /** @addtogroup ETH_Exported_Functions_Group1 * @{ */ HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DeInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspInit(ETH_HandleTypeDef *heth); void HAL_ETH_MspDeInit(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMATxDescTab, uint8_t *TxBuff, uint32_t TxBuffCount); HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *DMARxDescTab, uint8_t *RxBuff, uint32_t RxBuffCount); /** * @} */ /* IO operation functions ****************************************************/ /** @addtogroup ETH_Exported_Functions_Group2 * @{ */ HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength); HAL_StatusTypeDef HAL_ETH_GetReceivedFrame(ETH_HandleTypeDef *heth); /* Communication with PHY functions*/ HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue); HAL_StatusTypeDef HAL_ETH_WritePHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t RegValue); /* Non-Blocking mode: Interrupt */ HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT(ETH_HandleTypeDef *heth); void HAL_ETH_IRQHandler(ETH_HandleTypeDef *heth); /* Callback in non blocking modes (Interrupt) */ void HAL_ETH_TxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth); void HAL_ETH_ErrorCallback(ETH_HandleTypeDef *heth); /** * @} */ /* Peripheral Control functions **********************************************/ /** @addtogroup ETH_Exported_Functions_Group3 * @{ */ HAL_StatusTypeDef HAL_ETH_Start(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_Stop(ETH_HandleTypeDef *heth); HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf); HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf); /** * @} */ /* Peripheral State functions ************************************************/ /** @addtogroup ETH_Exported_Functions_Group4 * @{ */ HAL_ETH_StateTypeDef HAL_ETH_GetState(ETH_HandleTypeDef *heth); /** * @} */ /** * @} */ /** * @} */ #endif /* STM32F107xC */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F1xx_HAL_ETH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
apache-2.0
JREkiwi/sagetv
third_party/mplayer/libfaad2/mdct_tab.h
248974
/* ** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding ** Copyright (C) 2003-2004 M. Bakker, Ahead Software AG, http://www.nero.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, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ** ** Any non-GPL usage of this software or parts of this software is strictly ** forbidden. ** ** Commercial non-GPL licensing of this software is possible. ** For more info contact Ahead Software through [email protected]. ** ** $Id: mdct_tab.h,v 1.2 2005-11-02 17:46:27 Narflex Exp $ **/ #ifndef __MDCT_TAB_H__ #define __MDCT_TAB_H__ #ifdef __cplusplus extern "C" { #endif #ifdef FIXED_POINT /* 256 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_2048[] = { { FRAC_CONST(0.999999926465718), FRAC_CONST(0.000383495187571) }, { FRAC_CONST(0.999994043728986), FRAC_CONST(0.003451449920136) }, { FRAC_CONST(0.999978748667469), FRAC_CONST(0.006519372166339) }, { FRAC_CONST(0.999954041425130), FRAC_CONST(0.009587233049729) }, { FRAC_CONST(0.999919922234523), FRAC_CONST(0.012655003694430) }, { FRAC_CONST(0.999876391416790), FRAC_CONST(0.015722655225417) }, { FRAC_CONST(0.999823449381662), FRAC_CONST(0.018790158768785) }, { FRAC_CONST(0.999761096627447), FRAC_CONST(0.021857485452022) }, { FRAC_CONST(0.999689333741034), FRAC_CONST(0.024924606404281) }, { FRAC_CONST(0.999608161397882), FRAC_CONST(0.027991492756653) }, { FRAC_CONST(0.999517580362017), FRAC_CONST(0.031058115642435) }, { FRAC_CONST(0.999417591486022), FRAC_CONST(0.034124446197403) }, { FRAC_CONST(0.999308195711029), FRAC_CONST(0.037190455560088) }, { FRAC_CONST(0.999189394066715), FRAC_CONST(0.040256114872041) }, { FRAC_CONST(0.999061187671285), FRAC_CONST(0.043321395278110) }, { FRAC_CONST(0.998923577731466), FRAC_CONST(0.046386267926707) }, { FRAC_CONST(0.998776565542496), FRAC_CONST(0.049450703970085) }, { FRAC_CONST(0.998620152488109), FRAC_CONST(0.052514674564603) }, { FRAC_CONST(0.998454340040525), FRAC_CONST(0.055578150871005) }, { FRAC_CONST(0.998279129760433), FRAC_CONST(0.058641104054683) }, { FRAC_CONST(0.998094523296980), FRAC_CONST(0.061703505285957) }, { FRAC_CONST(0.997900522387752), FRAC_CONST(0.064765325740340) }, { FRAC_CONST(0.997697128858759), FRAC_CONST(0.067826536598811) }, { FRAC_CONST(0.997484344624418), FRAC_CONST(0.070887109048088) }, { FRAC_CONST(0.997262171687536), FRAC_CONST(0.073947014280897) }, { FRAC_CONST(0.997030612139289), FRAC_CONST(0.077006223496246) }, { FRAC_CONST(0.996789668159205), FRAC_CONST(0.080064707899691) }, { FRAC_CONST(0.996539342015138), FRAC_CONST(0.083122438703613) }, { FRAC_CONST(0.996279636063255), FRAC_CONST(0.086179387127485) }, { FRAC_CONST(0.996010552748006), FRAC_CONST(0.089235524398144) }, { FRAC_CONST(0.995732094602106), FRAC_CONST(0.092290821750062) }, { FRAC_CONST(0.995444264246510), FRAC_CONST(0.095345250425618) }, { FRAC_CONST(0.995147064390386), FRAC_CONST(0.098398781675364) }, { FRAC_CONST(0.994840497831093), FRAC_CONST(0.101451386758302) }, { FRAC_CONST(0.994524567454152), FRAC_CONST(0.104503036942151) }, { FRAC_CONST(0.994199276233219), FRAC_CONST(0.107553703503616) }, { FRAC_CONST(0.993864627230060), FRAC_CONST(0.110603357728662) }, { FRAC_CONST(0.993520623594518), FRAC_CONST(0.113651970912782) }, { FRAC_CONST(0.993167268564487), FRAC_CONST(0.116699514361268) }, { FRAC_CONST(0.992804565465879), FRAC_CONST(0.119745959389480) }, { FRAC_CONST(0.992432517712594), FRAC_CONST(0.122791277323117) }, { FRAC_CONST(0.992051128806486), FRAC_CONST(0.125835439498487) }, { FRAC_CONST(0.991660402337333), FRAC_CONST(0.128878417262777) }, { FRAC_CONST(0.991260341982802), FRAC_CONST(0.131920181974320) }, { FRAC_CONST(0.990850951508414), FRAC_CONST(0.134960705002869) }, { FRAC_CONST(0.990432234767506), FRAC_CONST(0.137999957729863) }, { FRAC_CONST(0.990004195701201), FRAC_CONST(0.141037911548698) }, { FRAC_CONST(0.989566838338365), FRAC_CONST(0.144074537864995) }, { FRAC_CONST(0.989120166795573), FRAC_CONST(0.147109808096872) }, { FRAC_CONST(0.988664185277066), FRAC_CONST(0.150143693675208) }, { FRAC_CONST(0.988198898074718), FRAC_CONST(0.153176166043918) }, { FRAC_CONST(0.987724309567987), FRAC_CONST(0.156207196660216) }, { FRAC_CONST(0.987240424223882), FRAC_CONST(0.159236756994888) }, { FRAC_CONST(0.986747246596917), FRAC_CONST(0.162264818532558) }, { FRAC_CONST(0.986244781329065), FRAC_CONST(0.165291352771958) }, { FRAC_CONST(0.985733033149723), FRAC_CONST(0.168316331226195) }, { FRAC_CONST(0.985212006875659), FRAC_CONST(0.171339725423019) }, { FRAC_CONST(0.984681707410971), FRAC_CONST(0.174361506905094) }, { FRAC_CONST(0.984142139747039), FRAC_CONST(0.177381647230260) }, { FRAC_CONST(0.983593308962479), FRAC_CONST(0.180400117971807) }, { FRAC_CONST(0.983035220223096), FRAC_CONST(0.183416890718739) }, { FRAC_CONST(0.982467878781833), FRAC_CONST(0.186431937076042) }, { FRAC_CONST(0.981891289978725), FRAC_CONST(0.189445228664950) }, { FRAC_CONST(0.981305459240845), FRAC_CONST(0.192456737123217) }, { FRAC_CONST(0.980710392082254), FRAC_CONST(0.195466434105377) }, { FRAC_CONST(0.980106094103952), FRAC_CONST(0.198474291283016) }, { FRAC_CONST(0.979492570993821), FRAC_CONST(0.201480280345038) }, { FRAC_CONST(0.978869828526574), FRAC_CONST(0.204484372997927) }, { FRAC_CONST(0.978237872563701), FRAC_CONST(0.207486540966021) }, { FRAC_CONST(0.977596709053412), FRAC_CONST(0.210486755991770) }, { FRAC_CONST(0.976946344030582), FRAC_CONST(0.213484989836008) }, { FRAC_CONST(0.976286783616694), FRAC_CONST(0.216481214278217) }, { FRAC_CONST(0.975618034019782), FRAC_CONST(0.219475401116790) }, { FRAC_CONST(0.974940101534372), FRAC_CONST(0.222467522169302) }, { FRAC_CONST(0.974252992541423), FRAC_CONST(0.225457549272769) }, { FRAC_CONST(0.973556713508266), FRAC_CONST(0.228445454283916) }, { FRAC_CONST(0.972851270988544), FRAC_CONST(0.231431209079446) }, { FRAC_CONST(0.972136671622152), FRAC_CONST(0.234414785556295) }, { FRAC_CONST(0.971412922135171), FRAC_CONST(0.237396155631907) }, { FRAC_CONST(0.970680029339806), FRAC_CONST(0.240375291244489) }, { FRAC_CONST(0.969938000134324), FRAC_CONST(0.243352164353285) }, { FRAC_CONST(0.969186841502986), FRAC_CONST(0.246326746938829) }, { FRAC_CONST(0.968426560515983), FRAC_CONST(0.249299011003218) }, { FRAC_CONST(0.967657164329370), FRAC_CONST(0.252268928570371) }, { FRAC_CONST(0.966878660184996), FRAC_CONST(0.255236471686292) }, { FRAC_CONST(0.966091055410439), FRAC_CONST(0.258201612419335) }, { FRAC_CONST(0.965294357418935), FRAC_CONST(0.261164322860466) }, { FRAC_CONST(0.964488573709308), FRAC_CONST(0.264124575123528) }, { FRAC_CONST(0.963673711865903), FRAC_CONST(0.267082341345496) }, { FRAC_CONST(0.962849779558509), FRAC_CONST(0.270037593686751) }, { FRAC_CONST(0.962016784542291), FRAC_CONST(0.272990304331330) }, { FRAC_CONST(0.961174734657714), FRAC_CONST(0.275940445487197) }, { FRAC_CONST(0.960323637830474), FRAC_CONST(0.278887989386500) }, { FRAC_CONST(0.959463502071418), FRAC_CONST(0.281832908285833) }, { FRAC_CONST(0.958594335476470), FRAC_CONST(0.284775174466498) }, { FRAC_CONST(0.957716146226559), FRAC_CONST(0.287714760234765) }, { FRAC_CONST(0.956828942587535), FRAC_CONST(0.290651637922133) }, { FRAC_CONST(0.955932732910098), FRAC_CONST(0.293585779885591) }, { FRAC_CONST(0.955027525629714), FRAC_CONST(0.296517158507877) }, { FRAC_CONST(0.954113329266539), FRAC_CONST(0.299445746197740) }, { FRAC_CONST(0.953190152425337), FRAC_CONST(0.302371515390196) }, { FRAC_CONST(0.952258003795400), FRAC_CONST(0.305294438546792) }, { FRAC_CONST(0.951316892150466), FRAC_CONST(0.308214488155861) }, { FRAC_CONST(0.950366826348636), FRAC_CONST(0.311131636732785) }, { FRAC_CONST(0.949407815332292), FRAC_CONST(0.314045856820251) }, { FRAC_CONST(0.948439868128010), FRAC_CONST(0.316957120988508) }, { FRAC_CONST(0.947462993846478), FRAC_CONST(0.319865401835631) }, { FRAC_CONST(0.946477201682409), FRAC_CONST(0.322770671987771) }, { FRAC_CONST(0.945482500914454), FRAC_CONST(0.325672904099420) }, { FRAC_CONST(0.944478900905116), FRAC_CONST(0.328572070853664) }, { FRAC_CONST(0.943466411100659), FRAC_CONST(0.331468144962441) }, { FRAC_CONST(0.942445041031025), FRAC_CONST(0.334361099166799) }, { FRAC_CONST(0.941414800309736), FRAC_CONST(0.337250906237151) }, { FRAC_CONST(0.940375698633812), FRAC_CONST(0.340137538973532) }, { FRAC_CONST(0.939327745783671), FRAC_CONST(0.343020970205856) }, { FRAC_CONST(0.938270951623047), FRAC_CONST(0.345901172794169) }, { FRAC_CONST(0.937205326098888), FRAC_CONST(0.348778119628908) }, { FRAC_CONST(0.936130879241267), FRAC_CONST(0.351651783631155) }, { FRAC_CONST(0.935047621163287), FRAC_CONST(0.354522137752887) }, { FRAC_CONST(0.933955562060987), FRAC_CONST(0.357389154977241) }, { FRAC_CONST(0.932854712213241), FRAC_CONST(0.360252808318757) }, { FRAC_CONST(0.931745081981669), FRAC_CONST(0.363113070823639) }, { FRAC_CONST(0.930626681810532), FRAC_CONST(0.365969915570009) }, { FRAC_CONST(0.929499522226639), FRAC_CONST(0.368823315668154) }, { FRAC_CONST(0.928363613839244), FRAC_CONST(0.371673244260787) }, { FRAC_CONST(0.927218967339952), FRAC_CONST(0.374519674523293) }, { FRAC_CONST(0.926065593502609), FRAC_CONST(0.377362579663988) }, { FRAC_CONST(0.924903503183211), FRAC_CONST(0.380201932924366) }, { FRAC_CONST(0.923732707319793), FRAC_CONST(0.383037707579352) }, { FRAC_CONST(0.922553216932333), FRAC_CONST(0.385869876937555) }, { FRAC_CONST(0.921365043122642), FRAC_CONST(0.388698414341519) }, { FRAC_CONST(0.920168197074266), FRAC_CONST(0.391523293167972) }, { FRAC_CONST(0.918962690052376), FRAC_CONST(0.394344486828080) }, { FRAC_CONST(0.917748533403661), FRAC_CONST(0.397161968767692) }, { FRAC_CONST(0.916525738556228), FRAC_CONST(0.399975712467595) }, { FRAC_CONST(0.915294317019487), FRAC_CONST(0.402785691443764) }, { FRAC_CONST(0.914054280384047), FRAC_CONST(0.405591879247604) }, { FRAC_CONST(0.912805640321604), FRAC_CONST(0.408394249466208) }, { FRAC_CONST(0.911548408584834), FRAC_CONST(0.411192775722600) }, { FRAC_CONST(0.910282597007282), FRAC_CONST(0.413987431675985) }, { FRAC_CONST(0.909008217503247), FRAC_CONST(0.416778191021998) }, { FRAC_CONST(0.907725282067676), FRAC_CONST(0.419565027492947) }, { FRAC_CONST(0.906433802776045), FRAC_CONST(0.422347914858067) }, { FRAC_CONST(0.905133791784250), FRAC_CONST(0.425126826923762) }, { FRAC_CONST(0.903825261328488), FRAC_CONST(0.427901737533854) }, { FRAC_CONST(0.902508223725146), FRAC_CONST(0.430672620569827) }, { FRAC_CONST(0.901182691370685), FRAC_CONST(0.433439449951074) }, { FRAC_CONST(0.899848676741519), FRAC_CONST(0.436202199635144) }, { FRAC_CONST(0.898506192393902), FRAC_CONST(0.438960843617984) }, { FRAC_CONST(0.897155250963809), FRAC_CONST(0.441715355934187) }, { FRAC_CONST(0.895795865166814), FRAC_CONST(0.444465710657234) }, { FRAC_CONST(0.894428047797974), FRAC_CONST(0.447211881899738) }, { FRAC_CONST(0.893051811731707), FRAC_CONST(0.449953843813691) }, { FRAC_CONST(0.891667169921672), FRAC_CONST(0.452691570590701) }, { FRAC_CONST(0.890274135400645), FRAC_CONST(0.455425036462242) }, { FRAC_CONST(0.888872721280396), FRAC_CONST(0.458154215699893) }, { FRAC_CONST(0.887462940751569), FRAC_CONST(0.460879082615579) }, { FRAC_CONST(0.886044807083556), FRAC_CONST(0.463599611561814) }, { FRAC_CONST(0.884618333624370), FRAC_CONST(0.466315776931944) }, { FRAC_CONST(0.883183533800523), FRAC_CONST(0.469027553160387) }, { FRAC_CONST(0.881740421116898), FRAC_CONST(0.471734914722871) }, { FRAC_CONST(0.880289009156621), FRAC_CONST(0.474437836136679) }, { FRAC_CONST(0.878829311580933), FRAC_CONST(0.477136291960885) }, { FRAC_CONST(0.877361342129065), FRAC_CONST(0.479830256796594) }, { FRAC_CONST(0.875885114618104), FRAC_CONST(0.482519705287184) }, { FRAC_CONST(0.874400642942865), FRAC_CONST(0.485204612118542) }, { FRAC_CONST(0.872907941075761), FRAC_CONST(0.487884952019301) }, { FRAC_CONST(0.871407023066671), FRAC_CONST(0.490560699761082) }, { FRAC_CONST(0.869897903042806), FRAC_CONST(0.493231830158728) }, { FRAC_CONST(0.868380595208580), FRAC_CONST(0.495898318070542) }, { FRAC_CONST(0.866855113845470), FRAC_CONST(0.498560138398525) }, { FRAC_CONST(0.865321473311890), FRAC_CONST(0.501217266088610) }, { FRAC_CONST(0.863779688043047), FRAC_CONST(0.503869676130899) }, { FRAC_CONST(0.862229772550811), FRAC_CONST(0.506517343559899) }, { FRAC_CONST(0.860671741423578), FRAC_CONST(0.509160243454755) }, { FRAC_CONST(0.859105609326130), FRAC_CONST(0.511798350939487) }, { FRAC_CONST(0.857531390999499), FRAC_CONST(0.514431641183223) }, { FRAC_CONST(0.855949101260827), FRAC_CONST(0.517060089400432) }, { FRAC_CONST(0.854358755003227), FRAC_CONST(0.519683670851158) }, { FRAC_CONST(0.852760367195645), FRAC_CONST(0.522302360841255) }, { FRAC_CONST(0.851153952882715), FRAC_CONST(0.524916134722613) }, { FRAC_CONST(0.849539527184621), FRAC_CONST(0.527524967893398) }, { FRAC_CONST(0.847917105296951), FRAC_CONST(0.530128835798279) }, { FRAC_CONST(0.846286702490560), FRAC_CONST(0.532727713928659) }, { FRAC_CONST(0.844648334111418), FRAC_CONST(0.535321577822907) }, { FRAC_CONST(0.843002015580473), FRAC_CONST(0.537910403066589) }, { FRAC_CONST(0.841347762393502), FRAC_CONST(0.540494165292695) }, { FRAC_CONST(0.839685590120966), FRAC_CONST(0.543072840181872) }, { FRAC_CONST(0.838015514407864), FRAC_CONST(0.545646403462649) }, { FRAC_CONST(0.836337550973584), FRAC_CONST(0.548214830911668) }, { FRAC_CONST(0.834651715611756), FRAC_CONST(0.550778098353912) }, { FRAC_CONST(0.832958024190107), FRAC_CONST(0.553336181662932) }, { FRAC_CONST(0.831256492650303), FRAC_CONST(0.555889056761074) }, { FRAC_CONST(0.829547137007809), FRAC_CONST(0.558436699619704) }, { FRAC_CONST(0.827829973351730), FRAC_CONST(0.560979086259438) }, { FRAC_CONST(0.826105017844665), FRAC_CONST(0.563516192750365) }, { FRAC_CONST(0.824372286722551), FRAC_CONST(0.566047995212271) }, { FRAC_CONST(0.822631796294515), FRAC_CONST(0.568574469814869) }, { FRAC_CONST(0.820883562942715), FRAC_CONST(0.571095592778017) }, { FRAC_CONST(0.819127603122188), FRAC_CONST(0.573611340371945) }, { FRAC_CONST(0.817363933360698), FRAC_CONST(0.576121688917478) }, { FRAC_CONST(0.815592570258577), FRAC_CONST(0.578626614786261) }, { FRAC_CONST(0.813813530488567), FRAC_CONST(0.581126094400978) }, { FRAC_CONST(0.812026830795670), FRAC_CONST(0.583620104235573) }, { FRAC_CONST(0.810232487996982), FRAC_CONST(0.586108620815476) }, { FRAC_CONST(0.808430518981543), FRAC_CONST(0.588591620717823) }, { FRAC_CONST(0.806620940710170), FRAC_CONST(0.591069080571671) }, { FRAC_CONST(0.804803770215303), FRAC_CONST(0.593540977058226) }, { FRAC_CONST(0.802979024600843), FRAC_CONST(0.596007286911057) }, { FRAC_CONST(0.801146721041991), FRAC_CONST(0.598467986916314) }, { FRAC_CONST(0.799306876785086), FRAC_CONST(0.600923053912954) }, { FRAC_CONST(0.797459509147442), FRAC_CONST(0.603372464792950) }, { FRAC_CONST(0.795604635517188), FRAC_CONST(0.605816196501515) }, { FRAC_CONST(0.793742273353100), FRAC_CONST(0.608254226037314) }, { FRAC_CONST(0.791872440184440), FRAC_CONST(0.610686530452686) }, { FRAC_CONST(0.789995153610791), FRAC_CONST(0.613113086853855) }, { FRAC_CONST(0.788110431301888), FRAC_CONST(0.615533872401147) }, { FRAC_CONST(0.786218290997456), FRAC_CONST(0.617948864309208) }, { FRAC_CONST(0.784318750507039), FRAC_CONST(0.620358039847214) }, { FRAC_CONST(0.782411827709837), FRAC_CONST(0.622761376339086) }, { FRAC_CONST(0.780497540554532), FRAC_CONST(0.625158851163708) }, { FRAC_CONST(0.778575907059125), FRAC_CONST(0.627550441755132) }, { FRAC_CONST(0.776646945310762), FRAC_CONST(0.629936125602796) }, { FRAC_CONST(0.774710673465566), FRAC_CONST(0.632315880251738) }, { FRAC_CONST(0.772767109748464), FRAC_CONST(0.634689683302798) }, { FRAC_CONST(0.770816272453019), FRAC_CONST(0.637057512412839) }, { FRAC_CONST(0.768858179941253), FRAC_CONST(0.639419345294951) }, { FRAC_CONST(0.766892850643481), FRAC_CONST(0.641775159718664) }, { FRAC_CONST(0.764920303058128), FRAC_CONST(0.644124933510155) }, { FRAC_CONST(0.762940555751566), FRAC_CONST(0.646468644552458) }, { FRAC_CONST(0.760953627357928), FRAC_CONST(0.648806270785673) }, { FRAC_CONST(0.758959536578942), FRAC_CONST(0.651137790207170) }, { FRAC_CONST(0.756958302183750), FRAC_CONST(0.653463180871802) }, { FRAC_CONST(0.754949943008733), FRAC_CONST(0.655782420892106) }, { FRAC_CONST(0.752934477957330), FRAC_CONST(0.658095488438511) }, { FRAC_CONST(0.750911925999868), FRAC_CONST(0.660402361739545) }, { FRAC_CONST(0.748882306173375), FRAC_CONST(0.662703019082037) }, { FRAC_CONST(0.746845637581407), FRAC_CONST(0.664997438811325) }, { FRAC_CONST(0.744801939393863), FRAC_CONST(0.667285599331456) }, { FRAC_CONST(0.742751230846809), FRAC_CONST(0.669567479105392) }, { FRAC_CONST(0.740693531242296), FRAC_CONST(0.671843056655212) }, { FRAC_CONST(0.738628859948175), FRAC_CONST(0.674112310562312) }, { FRAC_CONST(0.736557236397919), FRAC_CONST(0.676375219467612) }, { FRAC_CONST(0.734478680090438), FRAC_CONST(0.678631762071749) }, { FRAC_CONST(0.732393210589896), FRAC_CONST(0.680881917135287) }, { FRAC_CONST(0.730300847525525), FRAC_CONST(0.683125663478909) }, { FRAC_CONST(0.728201610591445), FRAC_CONST(0.685362979983619) }, { FRAC_CONST(0.726095519546471), FRAC_CONST(0.687593845590942) }, { FRAC_CONST(0.723982594213936), FRAC_CONST(0.689818239303122) }, { FRAC_CONST(0.721862854481496), FRAC_CONST(0.692036140183319) }, { FRAC_CONST(0.719736320300951), FRAC_CONST(0.694247527355803) }, { FRAC_CONST(0.717603011688049), FRAC_CONST(0.696452380006158) }, { FRAC_CONST(0.715462948722304), FRAC_CONST(0.698650677381469) }, { FRAC_CONST(0.713316151546803), FRAC_CONST(0.700842398790526) }, { FRAC_CONST(0.711162640368018), FRAC_CONST(0.703027523604011) }, { FRAC_CONST(0.709002435455618), FRAC_CONST(0.705206031254698) }, { FRAC_CONST(0.706835557142274), FRAC_CONST(0.707377901237642) }, { FRAC_CONST(0.704662025823469), FRAC_CONST(0.709543113110377) }, { FRAC_CONST(0.702481861957308), FRAC_CONST(0.711701646493103) }, { FRAC_CONST(0.700295086064324), FRAC_CONST(0.713853481068882) }, { FRAC_CONST(0.698101718727284), FRAC_CONST(0.715998596583829) }, { FRAC_CONST(0.695901780590997), FRAC_CONST(0.718136972847297) }, { FRAC_CONST(0.693695292362118), FRAC_CONST(0.720268589732077) }, { FRAC_CONST(0.691482274808956), FRAC_CONST(0.722393427174578) }, { FRAC_CONST(0.689262748761273), FRAC_CONST(0.724511465175020) }, { FRAC_CONST(0.687036735110096), FRAC_CONST(0.726622683797623) }, { FRAC_CONST(0.684804254807511), FRAC_CONST(0.728727063170794) }, { FRAC_CONST(0.682565328866473), FRAC_CONST(0.730824583487312) }, { FRAC_CONST(0.680319978360607), FRAC_CONST(0.732915225004518) }, { FRAC_CONST(0.678068224424007), FRAC_CONST(0.734998968044497) }, { FRAC_CONST(0.675810088251037), FRAC_CONST(0.737075792994266) }, { FRAC_CONST(0.673545591096136), FRAC_CONST(0.739145680305957) }, { FRAC_CONST(0.671274754273613), FRAC_CONST(0.741208610497004) }, { FRAC_CONST(0.668997599157450), FRAC_CONST(0.743264564150321) }, { FRAC_CONST(0.666714147181098), FRAC_CONST(0.745313521914490) }, { FRAC_CONST(0.664424419837275), FRAC_CONST(0.747355464503940) }, { FRAC_CONST(0.662128438677769), FRAC_CONST(0.749390372699130) }, { FRAC_CONST(0.659826225313227), FRAC_CONST(0.751418227346727) }, { FRAC_CONST(0.657517801412960), FRAC_CONST(0.753439009359794) }, { FRAC_CONST(0.655203188704732), FRAC_CONST(0.755452699717958) }, { FRAC_CONST(0.652882408974559), FRAC_CONST(0.757459279467601) }, { FRAC_CONST(0.650555484066504), FRAC_CONST(0.759458729722028) }, { FRAC_CONST(0.648222435882470), FRAC_CONST(0.761451031661654) }, { FRAC_CONST(0.645883286381996), FRAC_CONST(0.763436166534172) }, { FRAC_CONST(0.643538057582048), FRAC_CONST(0.765414115654738) }, { FRAC_CONST(0.641186771556811), FRAC_CONST(0.767384860406142) }, { FRAC_CONST(0.638829450437486), FRAC_CONST(0.769348382238982) }, { FRAC_CONST(0.636466116412077), FRAC_CONST(0.771304662671845) }, { FRAC_CONST(0.634096791725184), FRAC_CONST(0.773253683291473) }, { FRAC_CONST(0.631721498677792), FRAC_CONST(0.775195425752941) }, { FRAC_CONST(0.629340259627066), FRAC_CONST(0.777129871779832) }, { FRAC_CONST(0.626953096986133), FRAC_CONST(0.779057003164401) }, { FRAC_CONST(0.624560033223877), FRAC_CONST(0.780976801767754) }, { FRAC_CONST(0.622161090864727), FRAC_CONST(0.782889249520015) }, { FRAC_CONST(0.619756292488441), FRAC_CONST(0.784794328420499) }, { FRAC_CONST(0.617345660729897), FRAC_CONST(0.786692020537877) }, { FRAC_CONST(0.614929218278880), FRAC_CONST(0.788582308010347) }, { FRAC_CONST(0.612506987879866), FRAC_CONST(0.790465173045805) }, { FRAC_CONST(0.610078992331810), FRAC_CONST(0.792340597922007) }, { FRAC_CONST(0.607645254487931), FRAC_CONST(0.794208564986741) }, { FRAC_CONST(0.605205797255497), FRAC_CONST(0.796069056657988) }, { FRAC_CONST(0.602760643595607), FRAC_CONST(0.797922055424093) }, { FRAC_CONST(0.600309816522980), FRAC_CONST(0.799767543843926) }, { FRAC_CONST(0.597853339105734), FRAC_CONST(0.801605504547046) }, { FRAC_CONST(0.595391234465169), FRAC_CONST(0.803435920233868) }, { FRAC_CONST(0.592923525775551), FRAC_CONST(0.805258773675822) }, { FRAC_CONST(0.590450236263896), FRAC_CONST(0.807074047715518) }, { FRAC_CONST(0.587971389209745), FRAC_CONST(0.808881725266904) }, { FRAC_CONST(0.585487007944951), FRAC_CONST(0.810681789315431) }, { FRAC_CONST(0.582997115853458), FRAC_CONST(0.812474222918210) }, { FRAC_CONST(0.580501736371077), FRAC_CONST(0.814259009204175) }, { FRAC_CONST(0.578000892985270), FRAC_CONST(0.816036131374237) }, { FRAC_CONST(0.575494609234928), FRAC_CONST(0.817805572701444) }, { FRAC_CONST(0.572982908710149), FRAC_CONST(0.819567316531142) }, { FRAC_CONST(0.570465815052013), FRAC_CONST(0.821321346281127) }, { FRAC_CONST(0.567943351952366), FRAC_CONST(0.823067645441802) }, { FRAC_CONST(0.565415543153590), FRAC_CONST(0.824806197576334) }, { FRAC_CONST(0.562882412448385), FRAC_CONST(0.826536986320810) }, { FRAC_CONST(0.560343983679541), FRAC_CONST(0.828259995384386) }, { FRAC_CONST(0.557800280739717), FRAC_CONST(0.829975208549444) }, { FRAC_CONST(0.555251327571214), FRAC_CONST(0.831682609671745) }, { FRAC_CONST(0.552697148165750), FRAC_CONST(0.833382182680580) }, { FRAC_CONST(0.550137766564234), FRAC_CONST(0.835073911578919) }, { FRAC_CONST(0.547573206856540), FRAC_CONST(0.836757780443567) }, { FRAC_CONST(0.545003493181281), FRAC_CONST(0.838433773425308) }, { FRAC_CONST(0.542428649725581), FRAC_CONST(0.840101874749058) }, { FRAC_CONST(0.539848700724848), FRAC_CONST(0.841762068714012) }, { FRAC_CONST(0.537263670462543), FRAC_CONST(0.843414339693793) }, { FRAC_CONST(0.534673583269956), FRAC_CONST(0.845058672136595) }, { FRAC_CONST(0.532078463525974), FRAC_CONST(0.846695050565337) }, { FRAC_CONST(0.529478335656852), FRAC_CONST(0.848323459577802) }, { FRAC_CONST(0.526873224135985), FRAC_CONST(0.849943883846782) }, { FRAC_CONST(0.524263153483673), FRAC_CONST(0.851556308120229) }, { FRAC_CONST(0.521648148266897), FRAC_CONST(0.853160717221390) }, { FRAC_CONST(0.519028233099081), FRAC_CONST(0.854757096048957) }, { FRAC_CONST(0.516403432639864), FRAC_CONST(0.856345429577204) }, { FRAC_CONST(0.513773771594868), FRAC_CONST(0.857925702856130) }, { FRAC_CONST(0.511139274715464), FRAC_CONST(0.859497901011602) }, { FRAC_CONST(0.508499966798541), FRAC_CONST(0.861062009245491) }, { FRAC_CONST(0.505855872686269), FRAC_CONST(0.862618012835817) }, { FRAC_CONST(0.503207017265869), FRAC_CONST(0.864165897136879) }, { FRAC_CONST(0.500553425469378), FRAC_CONST(0.865705647579402) }, { FRAC_CONST(0.497895122273411), FRAC_CONST(0.867237249670668) }, { FRAC_CONST(0.495232132698931), FRAC_CONST(0.868760688994655) }, { FRAC_CONST(0.492564481811011), FRAC_CONST(0.870275951212172) }, { FRAC_CONST(0.489892194718595), FRAC_CONST(0.871783022060993) }, { FRAC_CONST(0.487215296574269), FRAC_CONST(0.873281887355994) }, { FRAC_CONST(0.484533812574016), FRAC_CONST(0.874772532989284) }, { FRAC_CONST(0.481847767956986), FRAC_CONST(0.876254944930338) }, { FRAC_CONST(0.479157188005253), FRAC_CONST(0.877729109226132) }, { FRAC_CONST(0.476462098043581), FRAC_CONST(0.879195012001267) }, { FRAC_CONST(0.473762523439183), FRAC_CONST(0.880652639458111) }, { FRAC_CONST(0.471058489601483), FRAC_CONST(0.882101977876918) }, { FRAC_CONST(0.468350021981877), FRAC_CONST(0.883543013615962) }, { FRAC_CONST(0.465637146073494), FRAC_CONST(0.884975733111667) }, { FRAC_CONST(0.462919887410955), FRAC_CONST(0.886400122878730) }, { FRAC_CONST(0.460198271570134), FRAC_CONST(0.887816169510255) }, { FRAC_CONST(0.457472324167916), FRAC_CONST(0.889223859677868) }, { FRAC_CONST(0.454742070861955), FRAC_CONST(0.890623180131856) }, { FRAC_CONST(0.452007537350437), FRAC_CONST(0.892014117701280) }, { FRAC_CONST(0.449268749371830), FRAC_CONST(0.893396659294108) }, { FRAC_CONST(0.446525732704651), FRAC_CONST(0.894770791897330) }, { FRAC_CONST(0.443778513167218), FRAC_CONST(0.896136502577087) }, { FRAC_CONST(0.441027116617407), FRAC_CONST(0.897493778478790) }, { FRAC_CONST(0.438271568952410), FRAC_CONST(0.898842606827242) }, { FRAC_CONST(0.435511896108492), FRAC_CONST(0.900182974926757) }, { FRAC_CONST(0.432748124060744), FRAC_CONST(0.901514870161279) }, { FRAC_CONST(0.429980278822841), FRAC_CONST(0.902838279994503) }, { FRAC_CONST(0.427208386446796), FRAC_CONST(0.904153191969992) }, { FRAC_CONST(0.424432473022717), FRAC_CONST(0.905459593711293) }, { FRAC_CONST(0.421652564678558), FRAC_CONST(0.906757472922057) }, { FRAC_CONST(0.418868687579875), FRAC_CONST(0.908046817386148) }, { FRAC_CONST(0.416080867929579), FRAC_CONST(0.909327614967767) }, { FRAC_CONST(0.413289131967691), FRAC_CONST(0.910599853611559) }, { FRAC_CONST(0.410493505971093), FRAC_CONST(0.911863521342729) }, { FRAC_CONST(0.407694016253280), FRAC_CONST(0.913118606267154) }, { FRAC_CONST(0.404890689164118), FRAC_CONST(0.914365096571498) }, { FRAC_CONST(0.402083551089587), FRAC_CONST(0.915602980523320) }, { FRAC_CONST(0.399272628451541), FRAC_CONST(0.916832246471184) }, { FRAC_CONST(0.396457947707454), FRAC_CONST(0.918052882844770) }, { FRAC_CONST(0.393639535350173), FRAC_CONST(0.919264878154985) }, { FRAC_CONST(0.390817417907669), FRAC_CONST(0.920468220994067) }, { FRAC_CONST(0.387991621942785), FRAC_CONST(0.921662900035695) }, { FRAC_CONST(0.385162174052990), FRAC_CONST(0.922848904035094) }, { FRAC_CONST(0.382329100870125), FRAC_CONST(0.924026221829144) }, { FRAC_CONST(0.379492429060153), FRAC_CONST(0.925194842336480) }, { FRAC_CONST(0.376652185322910), FRAC_CONST(0.926354754557603) }, { FRAC_CONST(0.373808396391851), FRAC_CONST(0.927505947574975) }, { FRAC_CONST(0.370961089033802), FRAC_CONST(0.928648410553131) }, { FRAC_CONST(0.368110290048703), FRAC_CONST(0.929782132738772) }, { FRAC_CONST(0.365256026269360), FRAC_CONST(0.930907103460875) }, { FRAC_CONST(0.362398324561191), FRAC_CONST(0.932023312130786) }, { FRAC_CONST(0.359537211821973), FRAC_CONST(0.933130748242325) }, { FRAC_CONST(0.356672714981588), FRAC_CONST(0.934229401371881) }, { FRAC_CONST(0.353804861001772), FRAC_CONST(0.935319261178512) }, { FRAC_CONST(0.350933676875858), FRAC_CONST(0.936400317404042) }, { FRAC_CONST(0.348059189628526), FRAC_CONST(0.937472559873159) }, { FRAC_CONST(0.345181426315543), FRAC_CONST(0.938535978493509) }, { FRAC_CONST(0.342300414023514), FRAC_CONST(0.939590563255789) }, { FRAC_CONST(0.339416179869623), FRAC_CONST(0.940636304233848) }, { FRAC_CONST(0.336528751001382), FRAC_CONST(0.941673191584771) }, { FRAC_CONST(0.333638154596371), FRAC_CONST(0.942701215548982) }, { FRAC_CONST(0.330744417861983), FRAC_CONST(0.943720366450326) }, { FRAC_CONST(0.327847568035171), FRAC_CONST(0.944730634696168) }, { FRAC_CONST(0.324947632382188), FRAC_CONST(0.945732010777477) }, { FRAC_CONST(0.322044638198335), FRAC_CONST(0.946724485268921) }, { FRAC_CONST(0.319138612807696), FRAC_CONST(0.947708048828952) }, { FRAC_CONST(0.316229583562890), FRAC_CONST(0.948682692199895) }, { FRAC_CONST(0.313317577844809), FRAC_CONST(0.949648406208035) }, { FRAC_CONST(0.310402623062359), FRAC_CONST(0.950605181763705) }, { FRAC_CONST(0.307484746652204), FRAC_CONST(0.951553009861369) }, { FRAC_CONST(0.304563976078509), FRAC_CONST(0.952491881579706) }, { FRAC_CONST(0.301640338832679), FRAC_CONST(0.953421788081700) }, { FRAC_CONST(0.298713862433100), FRAC_CONST(0.954342720614716) }, { FRAC_CONST(0.295784574424884), FRAC_CONST(0.955254670510587) }, { FRAC_CONST(0.292852502379605), FRAC_CONST(0.956157629185692) }, { FRAC_CONST(0.289917673895041), FRAC_CONST(0.957051588141041) }, { FRAC_CONST(0.286980116594916), FRAC_CONST(0.957936538962351) }, { FRAC_CONST(0.284039858128637), FRAC_CONST(0.958812473320129) }, { FRAC_CONST(0.281096926171038), FRAC_CONST(0.959679382969747) }, { FRAC_CONST(0.278151348422115), FRAC_CONST(0.960537259751520) }, { FRAC_CONST(0.275203152606767), FRAC_CONST(0.961386095590786) }, { FRAC_CONST(0.272252366474537), FRAC_CONST(0.962225882497979) }, { FRAC_CONST(0.269299017799346), FRAC_CONST(0.963056612568704) }, { FRAC_CONST(0.266343134379238), FRAC_CONST(0.963878277983814) }, { FRAC_CONST(0.263384744036113), FRAC_CONST(0.964690871009481) }, { FRAC_CONST(0.260423874615468), FRAC_CONST(0.965494383997270) }, { FRAC_CONST(0.257460553986133), FRAC_CONST(0.966288809384210) }, { FRAC_CONST(0.254494810040011), FRAC_CONST(0.967074139692867) }, { FRAC_CONST(0.251526670691813), FRAC_CONST(0.967850367531414) }, { FRAC_CONST(0.248556163878797), FRAC_CONST(0.968617485593698) }, { FRAC_CONST(0.245583317560504), FRAC_CONST(0.969375486659311) }, { FRAC_CONST(0.242608159718497), FRAC_CONST(0.970124363593660) }, { FRAC_CONST(0.239630718356094), FRAC_CONST(0.970864109348029) }, { FRAC_CONST(0.236651021498106), FRAC_CONST(0.971594716959650) }, { FRAC_CONST(0.233669097190577), FRAC_CONST(0.972316179551765) }, { FRAC_CONST(0.230684973500512), FRAC_CONST(0.973028490333694) }, { FRAC_CONST(0.227698678515621), FRAC_CONST(0.973731642600896) }, { FRAC_CONST(0.224710240344050), FRAC_CONST(0.974425629735035) }, { FRAC_CONST(0.221719687114115), FRAC_CONST(0.975110445204039) }, { FRAC_CONST(0.218727046974045), FRAC_CONST(0.975786082562164) }, { FRAC_CONST(0.215732348091706), FRAC_CONST(0.976452535450054) }, { FRAC_CONST(0.212735618654346), FRAC_CONST(0.977109797594801) }, { FRAC_CONST(0.209736886868323), FRAC_CONST(0.977757862810003) }, { FRAC_CONST(0.206736180958844), FRAC_CONST(0.978396724995823) }, { FRAC_CONST(0.203733529169694), FRAC_CONST(0.979026378139048) }, { FRAC_CONST(0.200728959762976), FRAC_CONST(0.979646816313141) }, { FRAC_CONST(0.197722501018842), FRAC_CONST(0.980258033678304) }, { FRAC_CONST(0.194714181235226), FRAC_CONST(0.980860024481524) }, { FRAC_CONST(0.191704028727580), FRAC_CONST(0.981452783056636) }, { FRAC_CONST(0.188692071828605), FRAC_CONST(0.982036303824369) }, { FRAC_CONST(0.185678338887988), FRAC_CONST(0.982610581292405) }, { FRAC_CONST(0.182662858272129), FRAC_CONST(0.983175610055424) }, { FRAC_CONST(0.179645658363882), FRAC_CONST(0.983731384795162) }, { FRAC_CONST(0.176626767562281), FRAC_CONST(0.984277900280454) }, { FRAC_CONST(0.173606214282275), FRAC_CONST(0.984815151367289) }, { FRAC_CONST(0.170584026954464), FRAC_CONST(0.985343132998855) }, { FRAC_CONST(0.167560234024824), FRAC_CONST(0.985861840205587) }, { FRAC_CONST(0.164534863954446), FRAC_CONST(0.986371268105216) }, { FRAC_CONST(0.161507945219266), FRAC_CONST(0.986871411902812) }, { FRAC_CONST(0.158479506309796), FRAC_CONST(0.987362266890832) }, { FRAC_CONST(0.155449575730856), FRAC_CONST(0.987843828449162) }, { FRAC_CONST(0.152418182001307), FRAC_CONST(0.988316092045160) }, { FRAC_CONST(0.149385353653780), FRAC_CONST(0.988779053233702) }, { FRAC_CONST(0.146351119234411), FRAC_CONST(0.989232707657220) }, { FRAC_CONST(0.143315507302572), FRAC_CONST(0.989677051045747) }, { FRAC_CONST(0.140278546430595), FRAC_CONST(0.990112079216954) }, { FRAC_CONST(0.137240265203516), FRAC_CONST(0.990537788076189) }, { FRAC_CONST(0.134200692218792), FRAC_CONST(0.990954173616519) }, { FRAC_CONST(0.131159856086043), FRAC_CONST(0.991361231918763) }, { FRAC_CONST(0.128117785426777), FRAC_CONST(0.991758959151536) }, { FRAC_CONST(0.125074508874121), FRAC_CONST(0.992147351571276) }, { FRAC_CONST(0.122030055072553), FRAC_CONST(0.992526405522286) }, { FRAC_CONST(0.118984452677633), FRAC_CONST(0.992896117436766) }, { FRAC_CONST(0.115937730355728), FRAC_CONST(0.993256483834846) }, { FRAC_CONST(0.112889916783750), FRAC_CONST(0.993607501324622) }, { FRAC_CONST(0.109841040648883), FRAC_CONST(0.993949166602181) }, { FRAC_CONST(0.106791130648307), FRAC_CONST(0.994281476451642) }, { FRAC_CONST(0.103740215488939), FRAC_CONST(0.994604427745176) }, { FRAC_CONST(0.100688323887154), FRAC_CONST(0.994918017443043) }, { FRAC_CONST(0.097635484568517), FRAC_CONST(0.995222242593618) }, { FRAC_CONST(0.094581726267515), FRAC_CONST(0.995517100333418) }, { FRAC_CONST(0.091527077727285), FRAC_CONST(0.995802587887129) }, { FRAC_CONST(0.088471567699341), FRAC_CONST(0.996078702567634) }, { FRAC_CONST(0.085415224943307), FRAC_CONST(0.996345441776036) }, { FRAC_CONST(0.082358078226647), FRAC_CONST(0.996602803001684) }, { FRAC_CONST(0.079300156324388), FRAC_CONST(0.996850783822197) }, { FRAC_CONST(0.076241488018856), FRAC_CONST(0.997089381903483) }, { FRAC_CONST(0.073182102099403), FRAC_CONST(0.997318594999769) }, { FRAC_CONST(0.070122027362134), FRAC_CONST(0.997538420953611) }, { FRAC_CONST(0.067061292609637), FRAC_CONST(0.997748857695926) }, { FRAC_CONST(0.063999926650714), FRAC_CONST(0.997949903246001) }, { FRAC_CONST(0.060937958300107), FRAC_CONST(0.998141555711521) }, { FRAC_CONST(0.057875416378229), FRAC_CONST(0.998323813288578) }, { FRAC_CONST(0.054812329710890), FRAC_CONST(0.998496674261695) }, { FRAC_CONST(0.051748727129028), FRAC_CONST(0.998660137003838) }, { FRAC_CONST(0.048684637468439), FRAC_CONST(0.998814199976435) }, { FRAC_CONST(0.045620089569500), FRAC_CONST(0.998958861729386) }, { FRAC_CONST(0.042555112276904), FRAC_CONST(0.999094120901079) }, { FRAC_CONST(0.039489734439384), FRAC_CONST(0.999219976218404) }, { FRAC_CONST(0.036423984909444), FRAC_CONST(0.999336426496761) }, { FRAC_CONST(0.033357892543086), FRAC_CONST(0.999443470640078) }, { FRAC_CONST(0.030291486199539), FRAC_CONST(0.999541107640813) }, { FRAC_CONST(0.027224794740988), FRAC_CONST(0.999629336579970) }, { FRAC_CONST(0.024157847032300), FRAC_CONST(0.999708156627105) }, { FRAC_CONST(0.021090671940755), FRAC_CONST(0.999777567040333) }, { FRAC_CONST(0.018023298335774), FRAC_CONST(0.999837567166337) }, { FRAC_CONST(0.014955755088644), FRAC_CONST(0.999888156440373) }, { FRAC_CONST(0.011888071072252), FRAC_CONST(0.999929334386276) }, { FRAC_CONST(0.008820275160808), FRAC_CONST(0.999961100616463) }, { FRAC_CONST(0.005752396229574), FRAC_CONST(0.999983454831938) }, { FRAC_CONST(0.002684463154596), FRAC_CONST(0.999996396822294) } }; /* 64 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_256[] = { { FRAC_CONST(0.999995293809576), FRAC_CONST(0.003067956762966) }, { FRAC_CONST(0.999618822495179), FRAC_CONST(0.027608145778966) }, { FRAC_CONST(0.998640218180265), FRAC_CONST(0.052131704680283) }, { FRAC_CONST(0.997060070339483), FRAC_CONST(0.076623861392031) }, { FRAC_CONST(0.994879330794806), FRAC_CONST(0.101069862754828) }, { FRAC_CONST(0.992099313142192), FRAC_CONST(0.125454983411546) }, { FRAC_CONST(0.988721691960324), FRAC_CONST(0.149764534677322) }, { FRAC_CONST(0.984748501801904), FRAC_CONST(0.173983873387464) }, { FRAC_CONST(0.980182135968117), FRAC_CONST(0.198098410717954) }, { FRAC_CONST(0.975025345066994), FRAC_CONST(0.222093620973204) }, { FRAC_CONST(0.969281235356549), FRAC_CONST(0.245955050335795) }, { FRAC_CONST(0.962953266873684), FRAC_CONST(0.269668325572915) }, { FRAC_CONST(0.956045251349996), FRAC_CONST(0.293219162694259) }, { FRAC_CONST(0.948561349915730), FRAC_CONST(0.316593375556166) }, { FRAC_CONST(0.940506070593268), FRAC_CONST(0.339776884406827) }, { FRAC_CONST(0.931884265581668), FRAC_CONST(0.362755724367397) }, { FRAC_CONST(0.922701128333879), FRAC_CONST(0.385516053843919) }, { FRAC_CONST(0.912962190428398), FRAC_CONST(0.408044162864979) }, { FRAC_CONST(0.902673318237259), FRAC_CONST(0.430326481340083) }, { FRAC_CONST(0.891840709392343), FRAC_CONST(0.452349587233771) }, { FRAC_CONST(0.880470889052161), FRAC_CONST(0.474100214650550) }, { FRAC_CONST(0.868570705971341), FRAC_CONST(0.495565261825773) }, { FRAC_CONST(0.856147328375194), FRAC_CONST(0.516731799017650) }, { FRAC_CONST(0.843208239641845), FRAC_CONST(0.537587076295645) }, { FRAC_CONST(0.829761233794523), FRAC_CONST(0.558118531220556) }, { FRAC_CONST(0.815814410806734), FRAC_CONST(0.578313796411656) }, { FRAC_CONST(0.801376171723140), FRAC_CONST(0.598160706996342) }, { FRAC_CONST(0.786455213599086), FRAC_CONST(0.617647307937804) }, { FRAC_CONST(0.771060524261814), FRAC_CONST(0.636761861236284) }, { FRAC_CONST(0.755201376896537), FRAC_CONST(0.655492852999615) }, { FRAC_CONST(0.738887324460615), FRAC_CONST(0.673829000378756) }, { FRAC_CONST(0.722128193929215), FRAC_CONST(0.691759258364158) }, { FRAC_CONST(0.704934080375905), FRAC_CONST(0.709272826438866) }, { FRAC_CONST(0.687315340891759), FRAC_CONST(0.726359155084346) }, { FRAC_CONST(0.669282588346636), FRAC_CONST(0.743007952135122) }, { FRAC_CONST(0.650846684996381), FRAC_CONST(0.759209188978388) }, { FRAC_CONST(0.632018735939809), FRAC_CONST(0.774953106594874) }, { FRAC_CONST(0.612810082429410), FRAC_CONST(0.790230221437310) }, { FRAC_CONST(0.593232295039800), FRAC_CONST(0.805031331142964) }, { FRAC_CONST(0.573297166698042), FRAC_CONST(0.819347520076797) }, { FRAC_CONST(0.553016705580028), FRAC_CONST(0.833170164701913) }, { FRAC_CONST(0.532403127877198), FRAC_CONST(0.846490938774052) }, { FRAC_CONST(0.511468850437971), FRAC_CONST(0.859301818357008) }, { FRAC_CONST(0.490226483288291), FRAC_CONST(0.871595086655951) }, { FRAC_CONST(0.468688822035828), FRAC_CONST(0.883363338665732) }, { FRAC_CONST(0.446868840162374), FRAC_CONST(0.894599485631383) }, { FRAC_CONST(0.424779681209109), FRAC_CONST(0.905296759318119) }, { FRAC_CONST(0.402434650859419), FRAC_CONST(0.915448716088268) }, { FRAC_CONST(0.379847208924051), FRAC_CONST(0.925049240782678) }, { FRAC_CONST(0.357030961233430), FRAC_CONST(0.934092550404259) }, { FRAC_CONST(0.333999651442009), FRAC_CONST(0.942573197601447) }, { FRAC_CONST(0.310767152749611), FRAC_CONST(0.950486073949482) }, { FRAC_CONST(0.287347459544730), FRAC_CONST(0.957826413027533) }, { FRAC_CONST(0.263754678974832), FRAC_CONST(0.964589793289813) }, { FRAC_CONST(0.240003022448742), FRAC_CONST(0.970772140728950) }, { FRAC_CONST(0.216106797076220), FRAC_CONST(0.976369731330021) }, { FRAC_CONST(0.192080397049892), FRAC_CONST(0.981379193313755) }, { FRAC_CONST(0.167938294974731), FRAC_CONST(0.985797509167567) }, { FRAC_CONST(0.143695033150295), FRAC_CONST(0.989622017463201) }, { FRAC_CONST(0.119365214810991), FRAC_CONST(0.992850414459865) }, { FRAC_CONST(0.094963495329639), FRAC_CONST(0.995480755491927) }, { FRAC_CONST(0.070504573389614), FRAC_CONST(0.997511456140303) }, { FRAC_CONST(0.046003182130915), FRAC_CONST(0.998941293186857) }, { FRAC_CONST(0.021474080275470), FRAC_CONST(0.999769405351215) } }; #ifdef LD_DEC /* 256 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_1024[] = { { FRAC_CONST(0.999999705862882), FRAC_CONST(0.000766990318743) }, { FRAC_CONST(0.999976174986898), FRAC_CONST(0.006902858724730) }, { FRAC_CONST(0.999914995573113), FRAC_CONST(0.013038467241987) }, { FRAC_CONST(0.999816169924900), FRAC_CONST(0.019173584868323) }, { FRAC_CONST(0.999679701762988), FRAC_CONST(0.025307980620025) }, { FRAC_CONST(0.999505596225325), FRAC_CONST(0.031441423540560) }, { FRAC_CONST(0.999293859866888), FRAC_CONST(0.037573682709270) }, { FRAC_CONST(0.999044500659429), FRAC_CONST(0.043704527250063) }, { FRAC_CONST(0.998757527991183), FRAC_CONST(0.049833726340107) }, { FRAC_CONST(0.998432952666508), FRAC_CONST(0.055961049218521) }, { FRAC_CONST(0.998070786905482), FRAC_CONST(0.062086265195060) }, { FRAC_CONST(0.997671044343441), FRAC_CONST(0.068209143658806) }, { FRAC_CONST(0.997233740030466), FRAC_CONST(0.074329454086846) }, { FRAC_CONST(0.996758890430818), FRAC_CONST(0.080446966052950) }, { FRAC_CONST(0.996246513422316), FRAC_CONST(0.086561449236251) }, { FRAC_CONST(0.995696628295664), FRAC_CONST(0.092672673429913) }, { FRAC_CONST(0.995109255753726), FRAC_CONST(0.098780408549800) }, { FRAC_CONST(0.994484417910748), FRAC_CONST(0.104884424643135) }, { FRAC_CONST(0.993822138291520), FRAC_CONST(0.110984491897163) }, { FRAC_CONST(0.993122441830496), FRAC_CONST(0.117080380647801) }, { FRAC_CONST(0.992385354870852), FRAC_CONST(0.123171861388280) }, { FRAC_CONST(0.991610905163495), FRAC_CONST(0.129258704777796) }, { FRAC_CONST(0.990799121866020), FRAC_CONST(0.135340681650134) }, { FRAC_CONST(0.989950035541609), FRAC_CONST(0.141417563022303) }, { FRAC_CONST(0.989063678157882), FRAC_CONST(0.147489120103154) }, { FRAC_CONST(0.988140083085693), FRAC_CONST(0.153555124301993) }, { FRAC_CONST(0.987179285097874), FRAC_CONST(0.159615347237193) }, { FRAC_CONST(0.986181320367928), FRAC_CONST(0.165669560744784) }, { FRAC_CONST(0.985146226468662), FRAC_CONST(0.171717536887050) }, { FRAC_CONST(0.984074042370776), FRAC_CONST(0.177759047961107) }, { FRAC_CONST(0.982964808441396), FRAC_CONST(0.183793866507478) }, { FRAC_CONST(0.981818566442553), FRAC_CONST(0.189821765318656) }, { FRAC_CONST(0.980635359529608), FRAC_CONST(0.195842517447658) }, { FRAC_CONST(0.979415232249635), FRAC_CONST(0.201855896216568) }, { FRAC_CONST(0.978158230539735), FRAC_CONST(0.207861675225075) }, { FRAC_CONST(0.976864401725313), FRAC_CONST(0.213859628358994) }, { FRAC_CONST(0.975533794518291), FRAC_CONST(0.219849529798779) }, { FRAC_CONST(0.974166459015280), FRAC_CONST(0.225831154028026) }, { FRAC_CONST(0.972762446695689), FRAC_CONST(0.231804275841965) }, { FRAC_CONST(0.971321810419786), FRAC_CONST(0.237768670355934) }, { FRAC_CONST(0.969844604426715), FRAC_CONST(0.243724113013852) }, { FRAC_CONST(0.968330884332445), FRAC_CONST(0.249670379596669) }, { FRAC_CONST(0.966780707127683), FRAC_CONST(0.255607246230807) }, { FRAC_CONST(0.965194131175725), FRAC_CONST(0.261534489396596) }, { FRAC_CONST(0.963571216210257), FRAC_CONST(0.267451885936678) }, { FRAC_CONST(0.961912023333112), FRAC_CONST(0.273359213064419) }, { FRAC_CONST(0.960216615011963), FRAC_CONST(0.279256248372291) }, { FRAC_CONST(0.958485055077976), FRAC_CONST(0.285142769840249) }, { FRAC_CONST(0.956717408723403), FRAC_CONST(0.291018555844085) }, { FRAC_CONST(0.954913742499131), FRAC_CONST(0.296883385163778) }, { FRAC_CONST(0.953074124312172), FRAC_CONST(0.302737036991819) }, { FRAC_CONST(0.951198623423113), FRAC_CONST(0.308579290941525) }, { FRAC_CONST(0.949287310443502), FRAC_CONST(0.314409927055337) }, { FRAC_CONST(0.947340257333192), FRAC_CONST(0.320228725813100) }, { FRAC_CONST(0.945357537397632), FRAC_CONST(0.326035468140330) }, { FRAC_CONST(0.943339225285108), FRAC_CONST(0.331829935416461) }, { FRAC_CONST(0.941285396983929), FRAC_CONST(0.337611909483075) }, { FRAC_CONST(0.939196129819570), FRAC_CONST(0.343381172652115) }, { FRAC_CONST(0.937071502451759), FRAC_CONST(0.349137507714085) }, { FRAC_CONST(0.934911594871516), FRAC_CONST(0.354880697946223) }, { FRAC_CONST(0.932716488398140), FRAC_CONST(0.360610527120662) }, { FRAC_CONST(0.930486265676150), FRAC_CONST(0.366326779512574) }, { FRAC_CONST(0.928221010672169), FRAC_CONST(0.372029239908285) }, { FRAC_CONST(0.925920808671770), FRAC_CONST(0.377717693613386) }, { FRAC_CONST(0.923585746276257), FRAC_CONST(0.383391926460809) }, { FRAC_CONST(0.921215911399409), FRAC_CONST(0.389051724818894) }, { FRAC_CONST(0.918811393264170), FRAC_CONST(0.394696875599434) }, { FRAC_CONST(0.916372282399289), FRAC_CONST(0.400327166265690) }, { FRAC_CONST(0.913898670635912), FRAC_CONST(0.405942384840403) }, { FRAC_CONST(0.911390651104122), FRAC_CONST(0.411542319913765) }, { FRAC_CONST(0.908848318229439), FRAC_CONST(0.417126760651388) }, { FRAC_CONST(0.906271767729258), FRAC_CONST(0.422695496802233) }, { FRAC_CONST(0.903661096609248), FRAC_CONST(0.428248318706532) }, { FRAC_CONST(0.901016403159702), FRAC_CONST(0.433785017303679) }, { FRAC_CONST(0.898337786951834), FRAC_CONST(0.439305384140100) }, { FRAC_CONST(0.895625348834030), FRAC_CONST(0.444809211377105) }, { FRAC_CONST(0.892879190928052), FRAC_CONST(0.450296291798709) }, { FRAC_CONST(0.890099416625192), FRAC_CONST(0.455766418819435) }, { FRAC_CONST(0.887286130582383), FRAC_CONST(0.461219386492092) }, { FRAC_CONST(0.884439438718254), FRAC_CONST(0.466654989515531) }, { FRAC_CONST(0.881559448209144), FRAC_CONST(0.472073023242369) }, { FRAC_CONST(0.878646267485068), FRAC_CONST(0.477473283686698) }, { FRAC_CONST(0.875700006225635), FRAC_CONST(0.482855567531766) }, { FRAC_CONST(0.872720775355914), FRAC_CONST(0.488219672137627) }, { FRAC_CONST(0.869708687042266), FRAC_CONST(0.493565395548775) }, { FRAC_CONST(0.866663854688111), FRAC_CONST(0.498892536501745) }, { FRAC_CONST(0.863586392929668), FRAC_CONST(0.504200894432690) }, { FRAC_CONST(0.860476417631632), FRAC_CONST(0.509490269484936) }, { FRAC_CONST(0.857334045882816), FRAC_CONST(0.514760462516501) }, { FRAC_CONST(0.854159395991739), FRAC_CONST(0.520011275107596) }, { FRAC_CONST(0.850952587482176), FRAC_CONST(0.525242509568095) }, { FRAC_CONST(0.847713741088654), FRAC_CONST(0.530453968944976) }, { FRAC_CONST(0.844442978751911), FRAC_CONST(0.535645457029741) }, { FRAC_CONST(0.841140423614298), FRAC_CONST(0.540816778365797) }, { FRAC_CONST(0.837806200015151), FRAC_CONST(0.545967738255818) }, { FRAC_CONST(0.834440433486103), FRAC_CONST(0.551098142769075) }, { FRAC_CONST(0.831043250746362), FRAC_CONST(0.556207798748740) }, { FRAC_CONST(0.827614779697938), FRAC_CONST(0.561296513819151) }, { FRAC_CONST(0.824155149420829), FRAC_CONST(0.566364096393064) }, { FRAC_CONST(0.820664490168157), FRAC_CONST(0.571410355678857) }, { FRAC_CONST(0.817142933361273), FRAC_CONST(0.576435101687722) }, { FRAC_CONST(0.813590611584799), FRAC_CONST(0.581438145240810) }, { FRAC_CONST(0.810007658581641), FRAC_CONST(0.586419297976361) }, { FRAC_CONST(0.806394209247956), FRAC_CONST(0.591378372356788) }, { FRAC_CONST(0.802750399628069), FRAC_CONST(0.596315181675744) }, { FRAC_CONST(0.799076366909352), FRAC_CONST(0.601229540065149) }, { FRAC_CONST(0.795372249417061), FRAC_CONST(0.606121262502186) }, { FRAC_CONST(0.791638186609126), FRAC_CONST(0.610990164816272) }, { FRAC_CONST(0.787874319070900), FRAC_CONST(0.615836063695985) }, { FRAC_CONST(0.784080788509870), FRAC_CONST(0.620658776695972) }, { FRAC_CONST(0.780257737750317), FRAC_CONST(0.625458122243814) }, { FRAC_CONST(0.776405310727940), FRAC_CONST(0.630233919646864) }, { FRAC_CONST(0.772523652484441), FRAC_CONST(0.634985989099049) }, { FRAC_CONST(0.768612909162058), FRAC_CONST(0.639714151687640) }, { FRAC_CONST(0.764673227998067), FRAC_CONST(0.644418229399988) }, { FRAC_CONST(0.760704757319237), FRAC_CONST(0.649098045130226) }, { FRAC_CONST(0.756707646536246), FRAC_CONST(0.653753422685936) }, { FRAC_CONST(0.752682046138055), FRAC_CONST(0.658384186794785) }, { FRAC_CONST(0.748628107686245), FRAC_CONST(0.662990163111121) }, { FRAC_CONST(0.744545983809307), FRAC_CONST(0.667571178222540) }, { FRAC_CONST(0.740435828196898), FRAC_CONST(0.672127059656412) }, { FRAC_CONST(0.736297795594053), FRAC_CONST(0.676657635886375) }, { FRAC_CONST(0.732132041795361), FRAC_CONST(0.681162736338795) }, { FRAC_CONST(0.727938723639099), FRAC_CONST(0.685642191399187) }, { FRAC_CONST(0.723717999001324), FRAC_CONST(0.690095832418600) }, { FRAC_CONST(0.719470026789933), FRAC_CONST(0.694523491719966) }, { FRAC_CONST(0.715194966938680), FRAC_CONST(0.698925002604414) }, { FRAC_CONST(0.710892980401152), FRAC_CONST(0.703300199357549) }, { FRAC_CONST(0.706564229144710), FRAC_CONST(0.707648917255684) }, { FRAC_CONST(0.702208876144392), FRAC_CONST(0.711970992572050) }, { FRAC_CONST(0.697827085376777), FRAC_CONST(0.716266262582953) }, { FRAC_CONST(0.693419021813812), FRAC_CONST(0.720534565573905) }, { FRAC_CONST(0.688984851416597), FRAC_CONST(0.724775740845711) }, { FRAC_CONST(0.684524741129142), FRAC_CONST(0.728989628720519) }, { FRAC_CONST(0.680038858872079), FRAC_CONST(0.733176070547833) }, { FRAC_CONST(0.675527373536339), FRAC_CONST(0.737334908710483) }, { FRAC_CONST(0.670990454976794), FRAC_CONST(0.741465986630563) }, { FRAC_CONST(0.666428274005865), FRAC_CONST(0.745569148775325) }, { FRAC_CONST(0.661841002387087), FRAC_CONST(0.749644240663033) }, { FRAC_CONST(0.657228812828643), FRAC_CONST(0.753691108868781) }, { FRAC_CONST(0.652591878976863), FRAC_CONST(0.757709601030268) }, { FRAC_CONST(0.647930375409685), FRAC_CONST(0.761699565853535) }, { FRAC_CONST(0.643244477630086), FRAC_CONST(0.765660853118662) }, { FRAC_CONST(0.638534362059467), FRAC_CONST(0.769593313685423) }, { FRAC_CONST(0.633800206031017), FRAC_CONST(0.773496799498899) }, { FRAC_CONST(0.629042187783036), FRAC_CONST(0.777371163595056) }, { FRAC_CONST(0.624260486452221), FRAC_CONST(0.781216260106276) }, { FRAC_CONST(0.619455282066924), FRAC_CONST(0.785031944266848) }, { FRAC_CONST(0.614626755540375), FRAC_CONST(0.788818072418420) }, { FRAC_CONST(0.609775088663868), FRAC_CONST(0.792574502015408) }, { FRAC_CONST(0.604900464099920), FRAC_CONST(0.796301091630359) }, { FRAC_CONST(0.600003065375389), FRAC_CONST(0.799997700959282) }, { FRAC_CONST(0.595083076874570), FRAC_CONST(0.803664190826924) }, { FRAC_CONST(0.590140683832249), FRAC_CONST(0.807300423192014) }, { FRAC_CONST(0.585176072326730), FRAC_CONST(0.810906261152460) }, { FRAC_CONST(0.580189429272832), FRAC_CONST(0.814481568950499) }, { FRAC_CONST(0.575180942414845), FRAC_CONST(0.818026211977813) }, { FRAC_CONST(0.570150800319470), FRAC_CONST(0.821540056780598) }, { FRAC_CONST(0.565099192368714), FRAC_CONST(0.825022971064580) }, { FRAC_CONST(0.560026308752760), FRAC_CONST(0.828474823700007) }, { FRAC_CONST(0.554932340462810), FRAC_CONST(0.831895484726578) }, { FRAC_CONST(0.549817479283891), FRAC_CONST(0.835284825358337) }, { FRAC_CONST(0.544681917787635), FRAC_CONST(0.838642717988527) }, { FRAC_CONST(0.539525849325029), FRAC_CONST(0.841969036194388) }, { FRAC_CONST(0.534349468019138), FRAC_CONST(0.845263654741918) }, { FRAC_CONST(0.529152968757791), FRAC_CONST(0.848526449590593) }, { FRAC_CONST(0.523936547186249), FRAC_CONST(0.851757297898029) }, { FRAC_CONST(0.518700399699835), FRAC_CONST(0.854956078024615) }, { FRAC_CONST(0.513444723436544), FRAC_CONST(0.858122669538086) }, { FRAC_CONST(0.508169716269615), FRAC_CONST(0.861256953218062) }, { FRAC_CONST(0.502875576800087), FRAC_CONST(0.864358811060534) }, { FRAC_CONST(0.497562504349319), FRAC_CONST(0.867428126282307) }, { FRAC_CONST(0.492230698951486), FRAC_CONST(0.870464783325398) }, { FRAC_CONST(0.486880361346047), FRAC_CONST(0.873468667861385) }, { FRAC_CONST(0.481511692970190), FRAC_CONST(0.876439666795714) }, { FRAC_CONST(0.476124895951244), FRAC_CONST(0.879377668271953) }, { FRAC_CONST(0.470720173099072), FRAC_CONST(0.882282561676009) }, { FRAC_CONST(0.465297727898435), FRAC_CONST(0.885154237640285) }, { FRAC_CONST(0.459857764501330), FRAC_CONST(0.887992588047806) }, { FRAC_CONST(0.454400487719304), FRAC_CONST(0.890797506036281) }, { FRAC_CONST(0.448926103015743), FRAC_CONST(0.893568886002136) }, { FRAC_CONST(0.443434816498138), FRAC_CONST(0.896306623604480) }, { FRAC_CONST(0.437926834910323), FRAC_CONST(0.899010615769039) }, { FRAC_CONST(0.432402365624690), FRAC_CONST(0.901680760692038) }, { FRAC_CONST(0.426861616634386), FRAC_CONST(0.904316957844028) }, { FRAC_CONST(0.421304796545480), FRAC_CONST(0.906919107973678) }, { FRAC_CONST(0.415732114569105), FRAC_CONST(0.909487113111505) }, { FRAC_CONST(0.410143780513590), FRAC_CONST(0.912020876573568) }, { FRAC_CONST(0.404540004776553), FRAC_CONST(0.914520302965104) }, { FRAC_CONST(0.398920998336983), FRAC_CONST(0.916985298184123) }, { FRAC_CONST(0.393286972747297), FRAC_CONST(0.919415769424947) }, { FRAC_CONST(0.387638140125373), FRAC_CONST(0.921811625181708) }, { FRAC_CONST(0.381974713146567), FRAC_CONST(0.924172775251791) }, { FRAC_CONST(0.376296905035705), FRAC_CONST(0.926499130739231) }, { FRAC_CONST(0.370604929559052), FRAC_CONST(0.928790604058057) }, { FRAC_CONST(0.364899001016267), FRAC_CONST(0.931047108935595) }, { FRAC_CONST(0.359179334232337), FRAC_CONST(0.933268560415712) }, { FRAC_CONST(0.353446144549481), FRAC_CONST(0.935454874862015) }, { FRAC_CONST(0.347699647819051), FRAC_CONST(0.937605969961000) }, { FRAC_CONST(0.341940060393402), FRAC_CONST(0.939721764725153) }, { FRAC_CONST(0.336167599117745), FRAC_CONST(0.941802179495998) }, { FRAC_CONST(0.330382481321983), FRAC_CONST(0.943847135947093) }, { FRAC_CONST(0.324584924812532), FRAC_CONST(0.945856557086984) }, { FRAC_CONST(0.318775147864118), FRAC_CONST(0.947830367262101) }, { FRAC_CONST(0.312953369211560), FRAC_CONST(0.949768492159607) }, { FRAC_CONST(0.307119808041533), FRAC_CONST(0.951670858810194) }, { FRAC_CONST(0.301274683984318), FRAC_CONST(0.953537395590833) }, { FRAC_CONST(0.295418217105532), FRAC_CONST(0.955368032227470) }, { FRAC_CONST(0.289550627897843), FRAC_CONST(0.957162699797670) }, { FRAC_CONST(0.283672137272669), FRAC_CONST(0.958921330733213) }, { FRAC_CONST(0.277782966551858), FRAC_CONST(0.960643858822638) }, { FRAC_CONST(0.271883337459360), FRAC_CONST(0.962330219213737) }, { FRAC_CONST(0.265973472112876), FRAC_CONST(0.963980348415994) }, { FRAC_CONST(0.260053593015495), FRAC_CONST(0.965594184302977) }, { FRAC_CONST(0.254123923047321), FRAC_CONST(0.967171666114677) }, { FRAC_CONST(0.248184685457075), FRAC_CONST(0.968712734459795) }, { FRAC_CONST(0.242236103853696), FRAC_CONST(0.970217331317979) }, { FRAC_CONST(0.236278402197920), FRAC_CONST(0.971685400042009) }, { FRAC_CONST(0.230311804793846), FRAC_CONST(0.973116885359925) }, { FRAC_CONST(0.224336536280494), FRAC_CONST(0.974511733377116) }, { FRAC_CONST(0.218352821623346), FRAC_CONST(0.975869891578341) }, { FRAC_CONST(0.212360886105879), FRAC_CONST(0.977191308829712) }, { FRAC_CONST(0.206360955321076), FRAC_CONST(0.978475935380617) }, { FRAC_CONST(0.200353255162940), FRAC_CONST(0.979723722865591) }, { FRAC_CONST(0.194338011817989), FRAC_CONST(0.980934624306142) }, { FRAC_CONST(0.188315451756732), FRAC_CONST(0.982108594112514) }, { FRAC_CONST(0.182285801725153), FRAC_CONST(0.983245588085407) }, { FRAC_CONST(0.176249288736168), FRAC_CONST(0.984345563417642) }, { FRAC_CONST(0.170206140061078), FRAC_CONST(0.985408478695768) }, { FRAC_CONST(0.164156583221016), FRAC_CONST(0.986434293901627) }, { FRAC_CONST(0.158100845978377), FRAC_CONST(0.987422970413855) }, { FRAC_CONST(0.152039156328246), FRAC_CONST(0.988374471009341) }, { FRAC_CONST(0.145971742489812), FRAC_CONST(0.989288759864625) }, { FRAC_CONST(0.139898832897777), FRAC_CONST(0.990165802557248) }, { FRAC_CONST(0.133820656193755), FRAC_CONST(0.991005566067049) }, { FRAC_CONST(0.127737441217662), FRAC_CONST(0.991808018777406) }, { FRAC_CONST(0.121649416999106), FRAC_CONST(0.992573130476429) }, { FRAC_CONST(0.115556812748755), FRAC_CONST(0.993300872358093) }, { FRAC_CONST(0.109459857849718), FRAC_CONST(0.993991217023329) }, { FRAC_CONST(0.103358781848900), FRAC_CONST(0.994644138481051) }, { FRAC_CONST(0.097253814448363), FRAC_CONST(0.995259612149133) }, { FRAC_CONST(0.091145185496681), FRAC_CONST(0.995837614855342) }, { FRAC_CONST(0.085033124980280), FRAC_CONST(0.996378124838200) }, { FRAC_CONST(0.078917863014785), FRAC_CONST(0.996881121747814) }, { FRAC_CONST(0.072799629836352), FRAC_CONST(0.997346586646633) }, { FRAC_CONST(0.066678655793002), FRAC_CONST(0.997774502010168) }, { FRAC_CONST(0.060555171335948), FRAC_CONST(0.998164851727646) }, { FRAC_CONST(0.054429407010919), FRAC_CONST(0.998517621102622) }, { FRAC_CONST(0.048301593449480), FRAC_CONST(0.998832796853528) }, { FRAC_CONST(0.042171961360348), FRAC_CONST(0.999110367114175) }, { FRAC_CONST(0.036040741520706), FRAC_CONST(0.999350321434199) }, { FRAC_CONST(0.029908164767517), FRAC_CONST(0.999552650779457) }, { FRAC_CONST(0.023774461988828), FRAC_CONST(0.999717347532362) }, { FRAC_CONST(0.017639864115082), FRAC_CONST(0.999844405492175) }, { FRAC_CONST(0.011504602110423), FRAC_CONST(0.999933819875236) }, { FRAC_CONST(0.005368906963996), FRAC_CONST(0.999985587315143) } }; #endif // LD_DEC #ifdef ALLOW_SMALL_FRAMELENGTH /* 480 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_1920[] = { { FRAC_CONST(0.999999916334328), FRAC_CONST(0.000409061532028) }, { FRAC_CONST(0.999993223088129), FRAC_CONST(0.003681545574400) }, { FRAC_CONST(0.999975820717897), FRAC_CONST(0.006953990190376) }, { FRAC_CONST(0.999947709409999), FRAC_CONST(0.010226360334704) }, { FRAC_CONST(0.999908889465485), FRAC_CONST(0.013498620962929) }, { FRAC_CONST(0.999859361300084), FRAC_CONST(0.016770737031768) }, { FRAC_CONST(0.999799125444203), FRAC_CONST(0.020042673499487) }, { FRAC_CONST(0.999728182542920), FRAC_CONST(0.023314395326274) }, { FRAC_CONST(0.999646533355977), FRAC_CONST(0.026585867474619) }, { FRAC_CONST(0.999554178757770), FRAC_CONST(0.029857054909681) }, { FRAC_CONST(0.999451119737344), FRAC_CONST(0.033127922599673) }, { FRAC_CONST(0.999337357398377), FRAC_CONST(0.036398435516228) }, { FRAC_CONST(0.999212892959173), FRAC_CONST(0.039668558634781) }, { FRAC_CONST(0.999077727752645), FRAC_CONST(0.042938256934941) }, { FRAC_CONST(0.998931863226306), FRAC_CONST(0.046207495400865) }, { FRAC_CONST(0.998775300942246), FRAC_CONST(0.049476239021636) }, { FRAC_CONST(0.998608042577122), FRAC_CONST(0.052744452791636) }, { FRAC_CONST(0.998430089922136), FRAC_CONST(0.056012101710921) }, { FRAC_CONST(0.998241444883019), FRAC_CONST(0.059279150785597) }, { FRAC_CONST(0.998042109480008), FRAC_CONST(0.062545565028192) }, { FRAC_CONST(0.997832085847824), FRAC_CONST(0.065811309458034) }, { FRAC_CONST(0.997611376235651), FRAC_CONST(0.069076349101624) }, { FRAC_CONST(0.997379983007114), FRAC_CONST(0.072340648993011) }, { FRAC_CONST(0.997137908640245), FRAC_CONST(0.075604174174166) }, { FRAC_CONST(0.996885155727469), FRAC_CONST(0.078866889695354) }, { FRAC_CONST(0.996621726975566), FRAC_CONST(0.082128760615515) }, { FRAC_CONST(0.996347625205645), FRAC_CONST(0.085389752002632) }, { FRAC_CONST(0.996062853353117), FRAC_CONST(0.088649828934106) }, { FRAC_CONST(0.995767414467660), FRAC_CONST(0.091908956497133) }, { FRAC_CONST(0.995461311713186), FRAC_CONST(0.095167099789075) }, { FRAC_CONST(0.995144548367810), FRAC_CONST(0.098424223917834) }, { FRAC_CONST(0.994817127823813), FRAC_CONST(0.101680294002229) }, { FRAC_CONST(0.994479053587606), FRAC_CONST(0.104935275172364) }, { FRAC_CONST(0.994130329279692), FRAC_CONST(0.108189132570007) }, { FRAC_CONST(0.993770958634630), FRAC_CONST(0.111441831348957) }, { FRAC_CONST(0.993400945500988), FRAC_CONST(0.114693336675426) }, { FRAC_CONST(0.993020293841312), FRAC_CONST(0.117943613728403) }, { FRAC_CONST(0.992629007732074), FRAC_CONST(0.121192627700032) }, { FRAC_CONST(0.992227091363634), FRAC_CONST(0.124440343795983) }, { FRAC_CONST(0.991814549040194), FRAC_CONST(0.127686727235827) }, { FRAC_CONST(0.991391385179751), FRAC_CONST(0.130931743253405) }, { FRAC_CONST(0.990957604314048), FRAC_CONST(0.134175357097202) }, { FRAC_CONST(0.990513211088533), FRAC_CONST(0.137417534030720) }, { FRAC_CONST(0.990058210262297), FRAC_CONST(0.140658239332849) }, { FRAC_CONST(0.989592606708036), FRAC_CONST(0.143897438298239) }, { FRAC_CONST(0.989116405411988), FRAC_CONST(0.147135096237670) }, { FRAC_CONST(0.988629611473887), FRAC_CONST(0.150371178478428) }, { FRAC_CONST(0.988132230106905), FRAC_CONST(0.153605650364672) }, { FRAC_CONST(0.987624266637598), FRAC_CONST(0.156838477257806) }, { FRAC_CONST(0.987105726505845), FRAC_CONST(0.160069624536852) }, { FRAC_CONST(0.986576615264794), FRAC_CONST(0.163299057598817) }, { FRAC_CONST(0.986036938580803), FRAC_CONST(0.166526741859069) }, { FRAC_CONST(0.985486702233375), FRAC_CONST(0.169752642751702) }, { FRAC_CONST(0.984925912115099), FRAC_CONST(0.172976725729910) }, { FRAC_CONST(0.984354574231587), FRAC_CONST(0.176198956266353) }, { FRAC_CONST(0.983772694701407), FRAC_CONST(0.179419299853531) }, { FRAC_CONST(0.983180279756024), FRAC_CONST(0.182637722004152) }, { FRAC_CONST(0.982577335739725), FRAC_CONST(0.185854188251500) }, { FRAC_CONST(0.981963869109555), FRAC_CONST(0.189068664149806) }, { FRAC_CONST(0.981339886435250), FRAC_CONST(0.192281115274616) }, { FRAC_CONST(0.980705394399163), FRAC_CONST(0.195491507223158) }, { FRAC_CONST(0.980060399796194), FRAC_CONST(0.198699805614714) }, { FRAC_CONST(0.979404909533716), FRAC_CONST(0.201905976090986) }, { FRAC_CONST(0.978738930631504), FRAC_CONST(0.205109984316464) }, { FRAC_CONST(0.978062470221657), FRAC_CONST(0.208311795978794) }, { FRAC_CONST(0.977375535548522), FRAC_CONST(0.211511376789145) }, { FRAC_CONST(0.976678133968618), FRAC_CONST(0.214708692482577) }, { FRAC_CONST(0.975970272950556), FRAC_CONST(0.217903708818409) }, { FRAC_CONST(0.975251960074958), FRAC_CONST(0.221096391580581) }, { FRAC_CONST(0.974523203034377), FRAC_CONST(0.224286706578026) }, { FRAC_CONST(0.973784009633218), FRAC_CONST(0.227474619645035) }, { FRAC_CONST(0.973034387787646), FRAC_CONST(0.230660096641619) }, { FRAC_CONST(0.972274345525510), FRAC_CONST(0.233843103453878) }, { FRAC_CONST(0.971503890986252), FRAC_CONST(0.237023605994367) }, { FRAC_CONST(0.970723032420820), FRAC_CONST(0.240201570202459) }, { FRAC_CONST(0.969931778191584), FRAC_CONST(0.243376962044711) }, { FRAC_CONST(0.969130136772239), FRAC_CONST(0.246549747515226) }, { FRAC_CONST(0.968318116747721), FRAC_CONST(0.249719892636022) }, { FRAC_CONST(0.967495726814114), FRAC_CONST(0.252887363457390) }, { FRAC_CONST(0.966662975778551), FRAC_CONST(0.256052126058264) }, { FRAC_CONST(0.965819872559127), FRAC_CONST(0.259214146546579) }, { FRAC_CONST(0.964966426184802), FRAC_CONST(0.262373391059634) }, { FRAC_CONST(0.964102645795299), FRAC_CONST(0.265529825764461) }, { FRAC_CONST(0.963228540641012), FRAC_CONST(0.268683416858178) }, { FRAC_CONST(0.962344120082907), FRAC_CONST(0.271834130568359) }, { FRAC_CONST(0.961449393592416), FRAC_CONST(0.274981933153391) }, { FRAC_CONST(0.960544370751341), FRAC_CONST(0.278126790902837) }, { FRAC_CONST(0.959629061251750), FRAC_CONST(0.281268670137799) }, { FRAC_CONST(0.958703474895872), FRAC_CONST(0.284407537211272) }, { FRAC_CONST(0.957767621595993), FRAC_CONST(0.287543358508512) }, { FRAC_CONST(0.956821511374351), FRAC_CONST(0.290676100447394) }, { FRAC_CONST(0.955865154363025), FRAC_CONST(0.293805729478766) }, { FRAC_CONST(0.954898560803832), FRAC_CONST(0.296932212086818) }, { FRAC_CONST(0.953921741048211), FRAC_CONST(0.300055514789431) }, { FRAC_CONST(0.952934705557117), FRAC_CONST(0.303175604138543) }, { FRAC_CONST(0.951937464900908), FRAC_CONST(0.306292446720504) }, { FRAC_CONST(0.950930029759229), FRAC_CONST(0.309406009156434) }, { FRAC_CONST(0.949912410920903), FRAC_CONST(0.312516258102580) }, { FRAC_CONST(0.948884619283808), FRAC_CONST(0.315623160250676) }, { FRAC_CONST(0.947846665854767), FRAC_CONST(0.318726682328294) }, { FRAC_CONST(0.946798561749429), FRAC_CONST(0.321826791099207) }, { FRAC_CONST(0.945740318192145), FRAC_CONST(0.324923453363742) }, { FRAC_CONST(0.944671946515855), FRAC_CONST(0.328016635959131) }, { FRAC_CONST(0.943593458161960), FRAC_CONST(0.331106305759876) }, { FRAC_CONST(0.942504864680205), FRAC_CONST(0.334192429678095) }, { FRAC_CONST(0.941406177728551), FRAC_CONST(0.337274974663880) }, { FRAC_CONST(0.940297409073052), FRAC_CONST(0.340353907705650) }, { FRAC_CONST(0.939178570587730), FRAC_CONST(0.343429195830507) }, { FRAC_CONST(0.938049674254446), FRAC_CONST(0.346500806104585) }, { FRAC_CONST(0.936910732162774), FRAC_CONST(0.349568705633406) }, { FRAC_CONST(0.935761756509868), FRAC_CONST(0.352632861562230) }, { FRAC_CONST(0.934602759600334), FRAC_CONST(0.355693241076410) }, { FRAC_CONST(0.933433753846097), FRAC_CONST(0.358749811401739) }, { FRAC_CONST(0.932254751766271), FRAC_CONST(0.361802539804806) }, { FRAC_CONST(0.931065765987021), FRAC_CONST(0.364851393593340) }, { FRAC_CONST(0.929866809241428), FRAC_CONST(0.367896340116568) }, { FRAC_CONST(0.928657894369357), FRAC_CONST(0.370937346765559) }, { FRAC_CONST(0.927439034317314), FRAC_CONST(0.373974380973575) }, { FRAC_CONST(0.926210242138311), FRAC_CONST(0.377007410216418) }, { FRAC_CONST(0.924971530991726), FRAC_CONST(0.380036402012783) }, { FRAC_CONST(0.923722914143160), FRAC_CONST(0.383061323924602) }, { FRAC_CONST(0.922464404964295), FRAC_CONST(0.386082143557389) }, { FRAC_CONST(0.921196016932755), FRAC_CONST(0.389098828560595) }, { FRAC_CONST(0.919917763631956), FRAC_CONST(0.392111346627946) }, { FRAC_CONST(0.918629658750963), FRAC_CONST(0.395119665497795) }, { FRAC_CONST(0.917331716084346), FRAC_CONST(0.398123752953462) }, { FRAC_CONST(0.916023949532027), FRAC_CONST(0.401123576823585) }, { FRAC_CONST(0.914706373099136), FRAC_CONST(0.404119104982459) }, { FRAC_CONST(0.913379000895858), FRAC_CONST(0.407110305350386) }, { FRAC_CONST(0.912041847137282), FRAC_CONST(0.410097145894012) }, { FRAC_CONST(0.910694926143251), FRAC_CONST(0.413079594626675) }, { FRAC_CONST(0.909338252338207), FRAC_CONST(0.416057619608744) }, { FRAC_CONST(0.907971840251037), FRAC_CONST(0.419031188947965) }, { FRAC_CONST(0.906595704514915), FRAC_CONST(0.422000270799800) }, { FRAC_CONST(0.905209859867151), FRAC_CONST(0.424964833367766) }, { FRAC_CONST(0.903814321149027), FRAC_CONST(0.427924844903780) }, { FRAC_CONST(0.902409103305641), FRAC_CONST(0.430880273708497) }, { FRAC_CONST(0.900994221385748), FRAC_CONST(0.433831088131649) }, { FRAC_CONST(0.899569690541596), FRAC_CONST(0.436777256572384) }, { FRAC_CONST(0.898135526028766), FRAC_CONST(0.439718747479604) }, { FRAC_CONST(0.896691743206008), FRAC_CONST(0.442655529352306) }, { FRAC_CONST(0.895238357535076), FRAC_CONST(0.445587570739915) }, { FRAC_CONST(0.893775384580563), FRAC_CONST(0.448514840242624) }, { FRAC_CONST(0.892302840009734), FRAC_CONST(0.451437306511726) }, { FRAC_CONST(0.890820739592359), FRAC_CONST(0.454354938249958) }, { FRAC_CONST(0.889329099200541), FRAC_CONST(0.457267704211826) }, { FRAC_CONST(0.887827934808551), FRAC_CONST(0.460175573203949) }, { FRAC_CONST(0.886317262492655), FRAC_CONST(0.463078514085383) }, { FRAC_CONST(0.884797098430938), FRAC_CONST(0.465976495767966) }, { FRAC_CONST(0.883267458903136), FRAC_CONST(0.468869487216642) }, { FRAC_CONST(0.881728360290461), FRAC_CONST(0.471757457449795) }, { FRAC_CONST(0.880179819075421), FRAC_CONST(0.474640375539586) }, { FRAC_CONST(0.878621851841649), FRAC_CONST(0.477518210612278) }, { FRAC_CONST(0.877054475273722), FRAC_CONST(0.480390931848569) }, { FRAC_CONST(0.875477706156984), FRAC_CONST(0.483258508483922) }, { FRAC_CONST(0.873891561377366), FRAC_CONST(0.486120909808896) }, { FRAC_CONST(0.872296057921204), FRAC_CONST(0.488978105169472) }, { FRAC_CONST(0.870691212875058), FRAC_CONST(0.491830063967383) }, { FRAC_CONST(0.869077043425529), FRAC_CONST(0.494676755660442) }, { FRAC_CONST(0.867453566859076), FRAC_CONST(0.497518149762867) }, { FRAC_CONST(0.865820800561827), FRAC_CONST(0.500354215845611) }, { FRAC_CONST(0.864178762019399), FRAC_CONST(0.503184923536685) }, { FRAC_CONST(0.862527468816704), FRAC_CONST(0.506010242521482) }, { FRAC_CONST(0.860866938637767), FRAC_CONST(0.508830142543107) }, { FRAC_CONST(0.859197189265532), FRAC_CONST(0.511644593402696) }, { FRAC_CONST(0.857518238581672), FRAC_CONST(0.514453564959741) }, { FRAC_CONST(0.855830104566401), FRAC_CONST(0.517257027132414) }, { FRAC_CONST(0.854132805298278), FRAC_CONST(0.520054949897887) }, { FRAC_CONST(0.852426358954015), FRAC_CONST(0.522847303292655) }, { FRAC_CONST(0.850710783808280), FRAC_CONST(0.525634057412856) }, { FRAC_CONST(0.848986098233506), FRAC_CONST(0.528415182414593) }, { FRAC_CONST(0.847252320699689), FRAC_CONST(0.531190648514252) }, { FRAC_CONST(0.845509469774194), FRAC_CONST(0.533960425988819) }, { FRAC_CONST(0.843757564121554), FRAC_CONST(0.536724485176205) }, { FRAC_CONST(0.841996622503271), FRAC_CONST(0.539482796475555) }, { FRAC_CONST(0.840226663777615), FRAC_CONST(0.542235330347571) }, { FRAC_CONST(0.838447706899422), FRAC_CONST(0.544982057314827) }, { FRAC_CONST(0.836659770919891), FRAC_CONST(0.547722947962084) }, { FRAC_CONST(0.834862874986380), FRAC_CONST(0.550457972936605) }, { FRAC_CONST(0.833057038342201), FRAC_CONST(0.553187102948470) }, { FRAC_CONST(0.831242280326413), FRAC_CONST(0.555910308770889) }, { FRAC_CONST(0.829418620373617), FRAC_CONST(0.558627561240515) }, { FRAC_CONST(0.827586078013746), FRAC_CONST(0.561338831257758) }, { FRAC_CONST(0.825744672871856), FRAC_CONST(0.564044089787093) }, { FRAC_CONST(0.823894424667918), FRAC_CONST(0.566743307857377) }, { FRAC_CONST(0.822035353216601), FRAC_CONST(0.569436456562150) }, { FRAC_CONST(0.820167478427070), FRAC_CONST(0.572123507059955) }, { FRAC_CONST(0.818290820302761), FRAC_CONST(0.574804430574639) }, { FRAC_CONST(0.816405398941175), FRAC_CONST(0.577479198395666) }, { FRAC_CONST(0.814511234533661), FRAC_CONST(0.580147781878420) }, { FRAC_CONST(0.812608347365198), FRAC_CONST(0.582810152444517) }, { FRAC_CONST(0.810696757814178), FRAC_CONST(0.585466281582107) }, { FRAC_CONST(0.808776486352191), FRAC_CONST(0.588116140846181) }, { FRAC_CONST(0.806847553543799), FRAC_CONST(0.590759701858874) }, { FRAC_CONST(0.804909980046325), FRAC_CONST(0.593396936309773) }, { FRAC_CONST(0.802963786609623), FRAC_CONST(0.596027815956215) }, { FRAC_CONST(0.801008994075862), FRAC_CONST(0.598652312623592) }, { FRAC_CONST(0.799045623379300), FRAC_CONST(0.601270398205654) }, { FRAC_CONST(0.797073695546059), FRAC_CONST(0.603882044664808) }, { FRAC_CONST(0.795093231693901), FRAC_CONST(0.606487224032418) }, { FRAC_CONST(0.793104253032005), FRAC_CONST(0.609085908409106) }, { FRAC_CONST(0.791106780860733), FRAC_CONST(0.611678069965050) }, { FRAC_CONST(0.789100836571407), FRAC_CONST(0.614263680940283) }, { FRAC_CONST(0.787086441646080), FRAC_CONST(0.616842713644988) }, { FRAC_CONST(0.785063617657302), FRAC_CONST(0.619415140459796) }, { FRAC_CONST(0.783032386267894), FRAC_CONST(0.621980933836084) }, { FRAC_CONST(0.780992769230711), FRAC_CONST(0.624540066296266) }, { FRAC_CONST(0.778944788388414), FRAC_CONST(0.627092510434089) }, { FRAC_CONST(0.776888465673232), FRAC_CONST(0.629638238914927) }, { FRAC_CONST(0.774823823106730), FRAC_CONST(0.632177224476073) }, { FRAC_CONST(0.772750882799570), FRAC_CONST(0.634709439927031) }, { FRAC_CONST(0.770669666951277), FRAC_CONST(0.637234858149809) }, { FRAC_CONST(0.768580197850002), FRAC_CONST(0.639753452099206) }, { FRAC_CONST(0.766482497872280), FRAC_CONST(0.642265194803105) }, { FRAC_CONST(0.764376589482793), FRAC_CONST(0.644770059362758) }, { FRAC_CONST(0.762262495234126), FRAC_CONST(0.647268018953079) }, { FRAC_CONST(0.760140237766532), FRAC_CONST(0.649759046822928) }, { FRAC_CONST(0.758009839807683), FRAC_CONST(0.652243116295397) }, { FRAC_CONST(0.755871324172429), FRAC_CONST(0.654720200768098) }, { FRAC_CONST(0.753724713762555), FRAC_CONST(0.657190273713446) }, { FRAC_CONST(0.751570031566534), FRAC_CONST(0.659653308678945) }, { FRAC_CONST(0.749407300659280), FRAC_CONST(0.662109279287469) }, { FRAC_CONST(0.747236544201905), FRAC_CONST(0.664558159237545) }, { FRAC_CONST(0.745057785441466), FRAC_CONST(0.666999922303638) }, { FRAC_CONST(0.742871047710719), FRAC_CONST(0.669434542336425) }, { FRAC_CONST(0.740676354427868), FRAC_CONST(0.671861993263083) }, { FRAC_CONST(0.738473729096316), FRAC_CONST(0.674282249087562) }, { FRAC_CONST(0.736263195304409), FRAC_CONST(0.676695283890867) }, { FRAC_CONST(0.734044776725190), FRAC_CONST(0.679101071831334) }, { FRAC_CONST(0.731818497116138), FRAC_CONST(0.681499587144906) }, { FRAC_CONST(0.729584380318920), FRAC_CONST(0.683890804145412) }, { FRAC_CONST(0.727342450259131), FRAC_CONST(0.686274697224838) }, { FRAC_CONST(0.725092730946042), FRAC_CONST(0.688651240853606) }, { FRAC_CONST(0.722835246472338), FRAC_CONST(0.691020409580841) }, { FRAC_CONST(0.720570021013866), FRAC_CONST(0.693382178034651) }, { FRAC_CONST(0.718297078829369), FRAC_CONST(0.695736520922392) }, { FRAC_CONST(0.716016444260233), FRAC_CONST(0.698083413030944) }, { FRAC_CONST(0.713728141730222), FRAC_CONST(0.700422829226978) }, { FRAC_CONST(0.711432195745216), FRAC_CONST(0.702754744457225) }, { FRAC_CONST(0.709128630892954), FRAC_CONST(0.705079133748748) }, { FRAC_CONST(0.706817471842764), FRAC_CONST(0.707395972209203) }, { FRAC_CONST(0.704498743345302), FRAC_CONST(0.709705235027113) }, { FRAC_CONST(0.702172470232289), FRAC_CONST(0.712006897472128) }, { FRAC_CONST(0.699838677416240), FRAC_CONST(0.714300934895292) }, { FRAC_CONST(0.697497389890200), FRAC_CONST(0.716587322729308) }, { FRAC_CONST(0.695148632727480), FRAC_CONST(0.718866036488799) }, { FRAC_CONST(0.692792431081381), FRAC_CONST(0.721137051770570) }, { FRAC_CONST(0.690428810184929), FRAC_CONST(0.723400344253874) }, { FRAC_CONST(0.688057795350606), FRAC_CONST(0.725655889700665) }, { FRAC_CONST(0.685679411970075), FRAC_CONST(0.727903663955865) }, { FRAC_CONST(0.683293685513912), FRAC_CONST(0.730143642947616) }, { FRAC_CONST(0.680900641531330), FRAC_CONST(0.732375802687543) }, { FRAC_CONST(0.678500305649909), FRAC_CONST(0.734600119271009) }, { FRAC_CONST(0.676092703575316), FRAC_CONST(0.736816568877370) }, { FRAC_CONST(0.673677861091036), FRAC_CONST(0.739025127770231) }, { FRAC_CONST(0.671255804058092), FRAC_CONST(0.741225772297702) }, { FRAC_CONST(0.668826558414768), FRAC_CONST(0.743418478892647) }, { FRAC_CONST(0.666390150176334), FRAC_CONST(0.745603224072940) }, { FRAC_CONST(0.663946605434765), FRAC_CONST(0.747779984441716) }, { FRAC_CONST(0.661495950358462), FRAC_CONST(0.749948736687619) }, { FRAC_CONST(0.659038211191971), FRAC_CONST(0.752109457585056) }, { FRAC_CONST(0.656573414255705), FRAC_CONST(0.754262123994441) }, { FRAC_CONST(0.654101585945659), FRAC_CONST(0.756406712862448) }, { FRAC_CONST(0.651622752733128), FRAC_CONST(0.758543201222251) }, { FRAC_CONST(0.649136941164425), FRAC_CONST(0.760671566193777) }, { FRAC_CONST(0.646644177860593), FRAC_CONST(0.762791784983948) }, { FRAC_CONST(0.644144489517126), FRAC_CONST(0.764903834886923) }, { FRAC_CONST(0.641637902903677), FRAC_CONST(0.767007693284345) }, { FRAC_CONST(0.639124444863776), FRAC_CONST(0.769103337645580) }, { FRAC_CONST(0.636604142314538), FRAC_CONST(0.771190745527961) }, { FRAC_CONST(0.634077022246379), FRAC_CONST(0.773269894577026) }, { FRAC_CONST(0.631543111722725), FRAC_CONST(0.775340762526760) }, { FRAC_CONST(0.629002437879721), FRAC_CONST(0.777403327199831) }, { FRAC_CONST(0.626455027925944), FRAC_CONST(0.779457566507828) }, { FRAC_CONST(0.623900909142107), FRAC_CONST(0.781503458451498) }, { FRAC_CONST(0.621340108880771), FRAC_CONST(0.783540981120982) }, { FRAC_CONST(0.618772654566049), FRAC_CONST(0.785570112696050) }, { FRAC_CONST(0.616198573693314), FRAC_CONST(0.787590831446332) }, { FRAC_CONST(0.613617893828905), FRAC_CONST(0.789603115731555) }, { FRAC_CONST(0.611030642609828), FRAC_CONST(0.791606944001769) }, { FRAC_CONST(0.608436847743468), FRAC_CONST(0.793602294797585) }, { FRAC_CONST(0.605836537007281), FRAC_CONST(0.795589146750397) }, { FRAC_CONST(0.603229738248508), FRAC_CONST(0.797567478582619) }, { FRAC_CONST(0.600616479383869), FRAC_CONST(0.799537269107905) }, { FRAC_CONST(0.597996788399267), FRAC_CONST(0.801498497231381) }, { FRAC_CONST(0.595370693349487), FRAC_CONST(0.803451141949871) }, { FRAC_CONST(0.592738222357898), FRAC_CONST(0.805395182352117) }, { FRAC_CONST(0.590099403616149), FRAC_CONST(0.807330597619008) }, { FRAC_CONST(0.587454265383869), FRAC_CONST(0.809257367023803) }, { FRAC_CONST(0.584802835988364), FRAC_CONST(0.811175469932349) }, { FRAC_CONST(0.582145143824311), FRAC_CONST(0.813084885803304) }, { FRAC_CONST(0.579481217353460), FRAC_CONST(0.814985594188359) }, { FRAC_CONST(0.576811085104321), FRAC_CONST(0.816877574732454) }, { FRAC_CONST(0.574134775671867), FRAC_CONST(0.818760807173997) }, { FRAC_CONST(0.571452317717222), FRAC_CONST(0.820635271345081) }, { FRAC_CONST(0.568763739967354), FRAC_CONST(0.822500947171703) }, { FRAC_CONST(0.566069071214772), FRAC_CONST(0.824357814673971) }, { FRAC_CONST(0.563368340317214), FRAC_CONST(0.826205853966327) }, { FRAC_CONST(0.560661576197336), FRAC_CONST(0.828045045257756) }, { FRAC_CONST(0.557948807842409), FRAC_CONST(0.829875368851995) }, { FRAC_CONST(0.555230064304002), FRAC_CONST(0.831696805147750) }, { FRAC_CONST(0.552505374697674), FRAC_CONST(0.833509334638900) }, { FRAC_CONST(0.549774768202663), FRAC_CONST(0.835312937914713) }, { FRAC_CONST(0.547038274061568), FRAC_CONST(0.837107595660044) }, { FRAC_CONST(0.544295921580046), FRAC_CONST(0.838893288655553) }, { FRAC_CONST(0.541547740126486), FRAC_CONST(0.840669997777901) }, { FRAC_CONST(0.538793759131706), FRAC_CONST(0.842437703999961) }, { FRAC_CONST(0.536034008088628), FRAC_CONST(0.844196388391019) }, { FRAC_CONST(0.533268516551970), FRAC_CONST(0.845946032116980) }, { FRAC_CONST(0.530497314137923), FRAC_CONST(0.847686616440563) }, { FRAC_CONST(0.527720430523840), FRAC_CONST(0.849418122721510) }, { FRAC_CONST(0.524937895447912), FRAC_CONST(0.851140532416778) }, { FRAC_CONST(0.522149738708856), FRAC_CONST(0.852853827080745) }, { FRAC_CONST(0.519355990165590), FRAC_CONST(0.854557988365401) }, { FRAC_CONST(0.516556679736915), FRAC_CONST(0.856252998020546) }, { FRAC_CONST(0.513751837401199), FRAC_CONST(0.857938837893991) }, { FRAC_CONST(0.510941493196049), FRAC_CONST(0.859615489931744) }, { FRAC_CONST(0.508125677217994), FRAC_CONST(0.861282936178208) }, { FRAC_CONST(0.505304419622159), FRAC_CONST(0.862941158776375) }, { FRAC_CONST(0.502477750621949), FRAC_CONST(0.864590139968012) }, { FRAC_CONST(0.499645700488717), FRAC_CONST(0.866229862093855) }, { FRAC_CONST(0.496808299551444), FRAC_CONST(0.867860307593799) }, { FRAC_CONST(0.493965578196415), FRAC_CONST(0.869481459007080) }, { FRAC_CONST(0.491117566866892), FRAC_CONST(0.871093298972471) }, { FRAC_CONST(0.488264296062789), FRAC_CONST(0.872695810228461) }, { FRAC_CONST(0.485405796340343), FRAC_CONST(0.874288975613440) }, { FRAC_CONST(0.482542098311789), FRAC_CONST(0.875872778065888) }, { FRAC_CONST(0.479673232645033), FRAC_CONST(0.877447200624553) }, { FRAC_CONST(0.476799230063322), FRAC_CONST(0.879012226428633) }, { FRAC_CONST(0.473920121344914), FRAC_CONST(0.880567838717962) }, { FRAC_CONST(0.471035937322751), FRAC_CONST(0.882114020833179) }, { FRAC_CONST(0.468146708884125), FRAC_CONST(0.883650756215917) }, { FRAC_CONST(0.465252466970353), FRAC_CONST(0.885178028408975) }, { FRAC_CONST(0.462353242576441), FRAC_CONST(0.886695821056495) }, { FRAC_CONST(0.459449066750752), FRAC_CONST(0.888204117904136) }, { FRAC_CONST(0.456539970594675), FRAC_CONST(0.889702902799251) }, { FRAC_CONST(0.453625985262295), FRAC_CONST(0.891192159691058) }, { FRAC_CONST(0.450707141960053), FRAC_CONST(0.892671872630812) }, { FRAC_CONST(0.447783471946415), FRAC_CONST(0.894142025771977) }, { FRAC_CONST(0.444855006531538), FRAC_CONST(0.895602603370393) }, { FRAC_CONST(0.441921777076935), FRAC_CONST(0.897053589784447) }, { FRAC_CONST(0.438983814995137), FRAC_CONST(0.898494969475242) }, { FRAC_CONST(0.436041151749356), FRAC_CONST(0.899926727006758) }, { FRAC_CONST(0.433093818853152), FRAC_CONST(0.901348847046022) }, { FRAC_CONST(0.430141847870093), FRAC_CONST(0.902761314363272) }, { FRAC_CONST(0.427185270413416), FRAC_CONST(0.904164113832116) }, { FRAC_CONST(0.424224118145690), FRAC_CONST(0.905557230429701) }, { FRAC_CONST(0.421258422778478), FRAC_CONST(0.906940649236866) }, { FRAC_CONST(0.418288216071994), FRAC_CONST(0.908314355438308) }, { FRAC_CONST(0.415313529834766), FRAC_CONST(0.909678334322736) }, { FRAC_CONST(0.412334395923293), FRAC_CONST(0.911032571283032) }, { FRAC_CONST(0.409350846241706), FRAC_CONST(0.912377051816407) }, { FRAC_CONST(0.406362912741425), FRAC_CONST(0.913711761524555) }, { FRAC_CONST(0.403370627420818), FRAC_CONST(0.915036686113806) }, { FRAC_CONST(0.400374022324857), FRAC_CONST(0.916351811395282) }, { FRAC_CONST(0.397373129544774), FRAC_CONST(0.917657123285050) }, { FRAC_CONST(0.394367981217720), FRAC_CONST(0.918952607804266) }, { FRAC_CONST(0.391358609526420), FRAC_CONST(0.920238251079332) }, { FRAC_CONST(0.388345046698826), FRAC_CONST(0.921514039342042) }, { FRAC_CONST(0.385327325007776), FRAC_CONST(0.922779958929729) }, { FRAC_CONST(0.382305476770645), FRAC_CONST(0.924035996285410) }, { FRAC_CONST(0.379279534348999), FRAC_CONST(0.925282137957935) }, { FRAC_CONST(0.376249530148250), FRAC_CONST(0.926518370602127) }, { FRAC_CONST(0.373215496617310), FRAC_CONST(0.927744680978929) }, { FRAC_CONST(0.370177466248239), FRAC_CONST(0.928961055955541) }, { FRAC_CONST(0.367135471575903), FRAC_CONST(0.930167482505564) }, { FRAC_CONST(0.364089545177621), FRAC_CONST(0.931363947709140) }, { FRAC_CONST(0.361039719672816), FRAC_CONST(0.932550438753087) }, { FRAC_CONST(0.357986027722671), FRAC_CONST(0.933726942931039) }, { FRAC_CONST(0.354928502029772), FRAC_CONST(0.934893447643582) }, { FRAC_CONST(0.351867175337763), FRAC_CONST(0.936049940398387) }, { FRAC_CONST(0.348802080430994), FRAC_CONST(0.937196408810347) }, { FRAC_CONST(0.345733250134169), FRAC_CONST(0.938332840601705) }, { FRAC_CONST(0.342660717311994), FRAC_CONST(0.939459223602190) }, { FRAC_CONST(0.339584514868829), FRAC_CONST(0.940575545749145) }, { FRAC_CONST(0.336504675748328), FRAC_CONST(0.941681795087657) }, { FRAC_CONST(0.333421232933097), FRAC_CONST(0.942777959770684) }, { FRAC_CONST(0.330334219444328), FRAC_CONST(0.943864028059183) }, { FRAC_CONST(0.327243668341457), FRAC_CONST(0.944939988322235) }, { FRAC_CONST(0.324149612721804), FRAC_CONST(0.946005829037171) }, { FRAC_CONST(0.321052085720218), FRAC_CONST(0.947061538789691) }, { FRAC_CONST(0.317951120508725), FRAC_CONST(0.948107106273994) }, { FRAC_CONST(0.314846750296171), FRAC_CONST(0.949142520292891) }, { FRAC_CONST(0.311739008327867), FRAC_CONST(0.950167769757930) }, { FRAC_CONST(0.308627927885232), FRAC_CONST(0.951182843689513) }, { FRAC_CONST(0.305513542285440), FRAC_CONST(0.952187731217013) }, { FRAC_CONST(0.302395884881056), FRAC_CONST(0.953182421578893) }, { FRAC_CONST(0.299274989059689), FRAC_CONST(0.954166904122818) }, { FRAC_CONST(0.296150888243624), FRAC_CONST(0.955141168305771) }, { FRAC_CONST(0.293023615889471), FRAC_CONST(0.956105203694164) }, { FRAC_CONST(0.289893205487806), FRAC_CONST(0.957058999963955) }, { FRAC_CONST(0.286759690562807), FRAC_CONST(0.958002546900750) }, { FRAC_CONST(0.283623104671904), FRAC_CONST(0.958935834399920) }, { FRAC_CONST(0.280483481405410), FRAC_CONST(0.959858852466706) }, { FRAC_CONST(0.277340854386169), FRAC_CONST(0.960771591216325) }, { FRAC_CONST(0.274195257269191), FRAC_CONST(0.961674040874080) }, { FRAC_CONST(0.271046723741295), FRAC_CONST(0.962566191775459) }, { FRAC_CONST(0.267895287520743), FRAC_CONST(0.963448034366243) }, { FRAC_CONST(0.264740982356888), FRAC_CONST(0.964319559202607) }, { FRAC_CONST(0.261583842029803), FRAC_CONST(0.965180756951218) }, { FRAC_CONST(0.258423900349924), FRAC_CONST(0.966031618389343) }, { FRAC_CONST(0.255261191157689), FRAC_CONST(0.966872134404937) }, { FRAC_CONST(0.252095748323171), FRAC_CONST(0.967702295996750) }, { FRAC_CONST(0.248927605745720), FRAC_CONST(0.968522094274417) }, { FRAC_CONST(0.245756797353599), FRAC_CONST(0.969331520458559) }, { FRAC_CONST(0.242583357103617), FRAC_CONST(0.970130565880871) }, { FRAC_CONST(0.239407318980770), FRAC_CONST(0.970919221984218) }, { FRAC_CONST(0.236228716997876), FRAC_CONST(0.971697480322728) }, { FRAC_CONST(0.233047585195206), FRAC_CONST(0.972465332561878) }, { FRAC_CONST(0.229863957640129), FRAC_CONST(0.973222770478587) }, { FRAC_CONST(0.226677868426735), FRAC_CONST(0.973969785961306) }, { FRAC_CONST(0.223489351675482), FRAC_CONST(0.974706371010097) }, { FRAC_CONST(0.220298441532823), FRAC_CONST(0.975432517736727) }, { FRAC_CONST(0.217105172170841), FRAC_CONST(0.976148218364747) }, { FRAC_CONST(0.213909577786886), FRAC_CONST(0.976853465229579) }, { FRAC_CONST(0.210711692603206), FRAC_CONST(0.977548250778596) }, { FRAC_CONST(0.207511550866582), FRAC_CONST(0.978232567571202) }, { FRAC_CONST(0.204309186847962), FRAC_CONST(0.978906408278914) }, { FRAC_CONST(0.201104634842092), FRAC_CONST(0.979569765685441) }, { FRAC_CONST(0.197897929167148), FRAC_CONST(0.980222632686756) }, { FRAC_CONST(0.194689104164373), FRAC_CONST(0.980865002291179) }, { FRAC_CONST(0.191478194197704), FRAC_CONST(0.981496867619447) }, { FRAC_CONST(0.188265233653407), FRAC_CONST(0.982118221904791) }, { FRAC_CONST(0.185050256939710), FRAC_CONST(0.982729058493005) }, { FRAC_CONST(0.181833298486427), FRAC_CONST(0.983329370842520) }, { FRAC_CONST(0.178614392744603), FRAC_CONST(0.983919152524473) }, { FRAC_CONST(0.175393574186129), FRAC_CONST(0.984498397222776) }, { FRAC_CONST(0.172170877303385), FRAC_CONST(0.985067098734184) }, { FRAC_CONST(0.168946336608867), FRAC_CONST(0.985625250968360) }, { FRAC_CONST(0.165719986634814), FRAC_CONST(0.986172847947943) }, { FRAC_CONST(0.162491861932842), FRAC_CONST(0.986709883808609) }, { FRAC_CONST(0.159261997073573), FRAC_CONST(0.987236352799134) }, { FRAC_CONST(0.156030426646266), FRAC_CONST(0.987752249281460) }, { FRAC_CONST(0.152797185258443), FRAC_CONST(0.988257567730749) }, { FRAC_CONST(0.149562307535523), FRAC_CONST(0.988752302735447) }, { FRAC_CONST(0.146325828120446), FRAC_CONST(0.989236448997339) }, { FRAC_CONST(0.143087781673307), FRAC_CONST(0.989710001331608) }, { FRAC_CONST(0.139848202870981), FRAC_CONST(0.990172954666889) }, { FRAC_CONST(0.136607126406757), FRAC_CONST(0.990625304045323) }, { FRAC_CONST(0.133364586989957), FRAC_CONST(0.991067044622612) }, { FRAC_CONST(0.130120619345575), FRAC_CONST(0.991498171668069) }, { FRAC_CONST(0.126875258213898), FRAC_CONST(0.991918680564670) }, { FRAC_CONST(0.123628538350136), FRAC_CONST(0.992328566809103) }, { FRAC_CONST(0.120380494524051), FRAC_CONST(0.992727826011815) }, { FRAC_CONST(0.117131161519582), FRAC_CONST(0.993116453897061) }, { FRAC_CONST(0.113880574134475), FRAC_CONST(0.993494446302948) }, { FRAC_CONST(0.110628767179910), FRAC_CONST(0.993861799181482) }, { FRAC_CONST(0.107375775480128), FRAC_CONST(0.994218508598608) }, { FRAC_CONST(0.104121633872055), FRAC_CONST(0.994564570734255) }, { FRAC_CONST(0.100866377204933), FRAC_CONST(0.994899981882376) }, { FRAC_CONST(0.097610040339947), FRAC_CONST(0.995224738450986) }, { FRAC_CONST(0.094352658149849), FRAC_CONST(0.995538836962204) }, { FRAC_CONST(0.091094265518583), FRAC_CONST(0.995842274052287) }, { FRAC_CONST(0.087834897340919), FRAC_CONST(0.996135046471667) }, { FRAC_CONST(0.084574588522070), FRAC_CONST(0.996417151084987) }, { FRAC_CONST(0.081313373977324), FRAC_CONST(0.996688584871134) }, { FRAC_CONST(0.078051288631670), FRAC_CONST(0.996949344923269) }, { FRAC_CONST(0.074788367419420), FRAC_CONST(0.997199428448862) }, { FRAC_CONST(0.071524645283840), FRAC_CONST(0.997438832769720) }, { FRAC_CONST(0.068260157176771), FRAC_CONST(0.997667555322013) }, { FRAC_CONST(0.064994938058259), FRAC_CONST(0.997885593656308) }, { FRAC_CONST(0.061729022896176), FRAC_CONST(0.998092945437590) }, { FRAC_CONST(0.058462446665851), FRAC_CONST(0.998289608445286) }, { FRAC_CONST(0.055195244349690), FRAC_CONST(0.998475580573295) }, { FRAC_CONST(0.051927450936806), FRAC_CONST(0.998650859830004) }, { FRAC_CONST(0.048659101422640), FRAC_CONST(0.998815444338313) }, { FRAC_CONST(0.045390230808591), FRAC_CONST(0.998969332335654) }, { FRAC_CONST(0.042120874101635), FRAC_CONST(0.999112522174011) }, { FRAC_CONST(0.038851066313958), FRAC_CONST(0.999245012319936) }, { FRAC_CONST(0.035580842462574), FRAC_CONST(0.999366801354564) }, { FRAC_CONST(0.032310237568951), FRAC_CONST(0.999477887973635) }, { FRAC_CONST(0.029039286658643), FRAC_CONST(0.999578270987499) }, { FRAC_CONST(0.025768024760904), FRAC_CONST(0.999667949321134) }, { FRAC_CONST(0.022496486908322), FRAC_CONST(0.999746922014158) }, { FRAC_CONST(0.019224708136438), FRAC_CONST(0.999815188220837) }, { FRAC_CONST(0.015952723483375), FRAC_CONST(0.999872747210095) }, { FRAC_CONST(0.012680567989461), FRAC_CONST(0.999919598365521) }, { FRAC_CONST(0.009408276696850), FRAC_CONST(0.999955741185376) }, { FRAC_CONST(0.006135884649155), FRAC_CONST(0.999981175282601) }, { FRAC_CONST(0.002863426891064), FRAC_CONST(0.999995900384816) } }; #ifdef LD_DEC /* 240 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_960[] = { { FRAC_CONST(0.999999665337326), FRAC_CONST(0.000818122995607) }, { FRAC_CONST(0.999972892444367), FRAC_CONST(0.007363041249780) }, { FRAC_CONST(0.999903284040864), FRAC_CONST(0.013907644095771) }, { FRAC_CONST(0.999790843108610), FRAC_CONST(0.020451651184577) }, { FRAC_CONST(0.999635574464198), FRAC_CONST(0.026994782192715) }, { FRAC_CONST(0.999437484758823), FRAC_CONST(0.033536756834230) }, { FRAC_CONST(0.999196582477986), FRAC_CONST(0.040077294872701) }, { FRAC_CONST(0.998912877941140), FRAC_CONST(0.046616116133247) }, { FRAC_CONST(0.998586383301244), FRAC_CONST(0.053152940514528) }, { FRAC_CONST(0.998217112544241), FRAC_CONST(0.059687488000744) }, { FRAC_CONST(0.997805081488460), FRAC_CONST(0.066219478673630) }, { FRAC_CONST(0.997350307783942), FRAC_CONST(0.072748632724445) }, { FRAC_CONST(0.996852810911678), FRAC_CONST(0.079274670465961) }, { FRAC_CONST(0.996312612182778), FRAC_CONST(0.085797312344440) }, { FRAC_CONST(0.995729734737558), FRAC_CONST(0.092316278951614) }, { FRAC_CONST(0.995104203544548), FRAC_CONST(0.098831291036650) }, { FRAC_CONST(0.994436045399422), FRAC_CONST(0.105342069518114) }, { FRAC_CONST(0.993725288923851), FRAC_CONST(0.111848335495926) }, { FRAC_CONST(0.992971964564277), FRAC_CONST(0.118349810263305) }, { FRAC_CONST(0.992176104590608), FRAC_CONST(0.124846215318711) }, { FRAC_CONST(0.991337743094838), FRAC_CONST(0.131337272377774) }, { FRAC_CONST(0.990456915989581), FRAC_CONST(0.137822703385212) }, { FRAC_CONST(0.989533661006540), FRAC_CONST(0.144302230526747) }, { FRAC_CONST(0.988568017694885), FRAC_CONST(0.150775576241001) }, { FRAC_CONST(0.987560027419562), FRAC_CONST(0.157242463231389) }, { FRAC_CONST(0.986509733359519), FRAC_CONST(0.163702614477995) }, { FRAC_CONST(0.985417180505858), FRAC_CONST(0.170155753249442) }, { FRAC_CONST(0.984282415659907), FRAC_CONST(0.176601603114742) }, { FRAC_CONST(0.983105487431216), FRAC_CONST(0.183039887955141) }, { FRAC_CONST(0.981886446235473), FRAC_CONST(0.189470331975943) }, { FRAC_CONST(0.980625344292344), FRAC_CONST(0.195892659718330) }, { FRAC_CONST(0.979322235623241), FRAC_CONST(0.202306596071156) }, { FRAC_CONST(0.977977176049000), FRAC_CONST(0.208711866282735) }, { FRAC_CONST(0.976590223187499), FRAC_CONST(0.215108195972610) }, { FRAC_CONST(0.975161436451181), FRAC_CONST(0.221495311143304) }, { FRAC_CONST(0.973690877044515), FRAC_CONST(0.227872938192063) }, { FRAC_CONST(0.972178607961371), FRAC_CONST(0.234240803922570) }, { FRAC_CONST(0.970624693982323), FRAC_CONST(0.240598635556650) }, { FRAC_CONST(0.969029201671875), FRAC_CONST(0.246946160745958) }, { FRAC_CONST(0.967392199375607), FRAC_CONST(0.253283107583640) }, { FRAC_CONST(0.965713757217249), FRAC_CONST(0.259609204615985) }, { FRAC_CONST(0.963993947095677), FRAC_CONST(0.265924180854051) }, { FRAC_CONST(0.962232842681832), FRAC_CONST(0.272227765785273) }, { FRAC_CONST(0.960430519415566), FRAC_CONST(0.278519689385053) }, { FRAC_CONST(0.958587054502409), FRAC_CONST(0.284799682128326) }, { FRAC_CONST(0.956702526910263), FRAC_CONST(0.291067475001103) }, { FRAC_CONST(0.954777017366017), FRAC_CONST(0.297322799511998) }, { FRAC_CONST(0.952810608352092), FRAC_CONST(0.303565387703730) }, { FRAC_CONST(0.950803384102905), FRAC_CONST(0.309794972164597) }, { FRAC_CONST(0.948755430601263), FRAC_CONST(0.316011286039934) }, { FRAC_CONST(0.946666835574676), FRAC_CONST(0.322214063043544) }, { FRAC_CONST(0.944537688491606), FRAC_CONST(0.328403037469105) }, { FRAC_CONST(0.942368080557626), FRAC_CONST(0.334577944201551) }, { FRAC_CONST(0.940158104711519), FRAC_CONST(0.340738518728429) }, { FRAC_CONST(0.937907855621296), FRAC_CONST(0.346884497151231) }, { FRAC_CONST(0.935617429680138), FRAC_CONST(0.353015616196696) }, { FRAC_CONST(0.933286925002268), FRAC_CONST(0.359131613228090) }, { FRAC_CONST(0.930916441418752), FRAC_CONST(0.365232226256457) }, { FRAC_CONST(0.928506080473216), FRAC_CONST(0.371317193951838) }, { FRAC_CONST(0.926055945417500), FRAC_CONST(0.377386255654469) }, { FRAC_CONST(0.923566141207236), FRAC_CONST(0.383439151385947) }, { FRAC_CONST(0.921036774497350), FRAC_CONST(0.389475621860365) }, { FRAC_CONST(0.918467953637492), FRAC_CONST(0.395495408495417) }, { FRAC_CONST(0.915859788667400), FRAC_CONST(0.401498253423481) }, { FRAC_CONST(0.913212391312179), FRAC_CONST(0.407483899502658) }, { FRAC_CONST(0.910525874977521), FRAC_CONST(0.413452090327791) }, { FRAC_CONST(0.907800354744844), FRAC_CONST(0.419402570241451) }, { FRAC_CONST(0.905035947366364), FRAC_CONST(0.425335084344881) }, { FRAC_CONST(0.902232771260093), FRAC_CONST(0.431249378508924) }, { FRAC_CONST(0.899390946504764), FRAC_CONST(0.437145199384900) }, { FRAC_CONST(0.896510594834693), FRAC_CONST(0.443022294415467) }, { FRAC_CONST(0.893591839634558), FRAC_CONST(0.448880411845433) }, { FRAC_CONST(0.890634805934118), FRAC_CONST(0.454719300732547) }, { FRAC_CONST(0.887639620402854), FRAC_CONST(0.460538710958240) }, { FRAC_CONST(0.884606411344546), FRAC_CONST(0.466338393238348) }, { FRAC_CONST(0.881535308691775), FRAC_CONST(0.472118099133784) }, { FRAC_CONST(0.878426444000357), FRAC_CONST(0.477877581061184) }, { FRAC_CONST(0.875279950443708), FRAC_CONST(0.483616592303511) }, { FRAC_CONST(0.872095962807140), FRAC_CONST(0.489334887020625) }, { FRAC_CONST(0.868874617482085), FRAC_CONST(0.495032220259813) }, { FRAC_CONST(0.865616052460258), FRAC_CONST(0.500708347966279) }, { FRAC_CONST(0.862320407327736), FRAC_CONST(0.506363026993605) }, { FRAC_CONST(0.858987823258990), FRAC_CONST(0.511996015114162) }, { FRAC_CONST(0.855618443010829), FRAC_CONST(0.517607071029487) }, { FRAC_CONST(0.852212410916289), FRAC_CONST(0.523195954380619) }, { FRAC_CONST(0.848769872878448), FRAC_CONST(0.528762425758396) }, { FRAC_CONST(0.845290976364179), FRAC_CONST(0.534306246713712) }, { FRAC_CONST(0.841775870397828), FRAC_CONST(0.539827179767727) }, { FRAC_CONST(0.838224705554838), FRAC_CONST(0.545324988422046) }, { FRAC_CONST(0.834637633955290), FRAC_CONST(0.550799437168844) }, { FRAC_CONST(0.831014809257393), FRAC_CONST(0.556250291500956) }, { FRAC_CONST(0.827356386650900), FRAC_CONST(0.561677317921925) }, { FRAC_CONST(0.823662522850458), FRAC_CONST(0.567080283956001) }, { FRAC_CONST(0.819933376088899), FRAC_CONST(0.572458958158102) }, { FRAC_CONST(0.816169106110459), FRAC_CONST(0.577813110123727) }, { FRAC_CONST(0.812369874163934), FRAC_CONST(0.583142510498826) }, { FRAC_CONST(0.808535842995778), FRAC_CONST(0.588446930989624) }, { FRAC_CONST(0.804667176843123), FRAC_CONST(0.593726144372402) }, { FRAC_CONST(0.800764041426753), FRAC_CONST(0.598979924503229) }, { FRAC_CONST(0.796826603943998), FRAC_CONST(0.604208046327650) }, { FRAC_CONST(0.792855033061574), FRAC_CONST(0.609410285890327) }, { FRAC_CONST(0.788849498908361), FRAC_CONST(0.614586420344631) }, { FRAC_CONST(0.784810173068109), FRAC_CONST(0.619736227962191) }, { FRAC_CONST(0.780737228572094), FRAC_CONST(0.624859488142386) }, { FRAC_CONST(0.776630839891703), FRAC_CONST(0.629955981421804) }, { FRAC_CONST(0.772491182930959), FRAC_CONST(0.635025489483633) }, { FRAC_CONST(0.768318435018988), FRAC_CONST(0.640067795167023) }, { FRAC_CONST(0.764112774902423), FRAC_CONST(0.645082682476378) }, { FRAC_CONST(0.759874382737746), FRAC_CONST(0.650069936590618) }, { FRAC_CONST(0.755603440083571), FRAC_CONST(0.655029343872374) }, { FRAC_CONST(0.751300129892866), FRAC_CONST(0.659960691877147) }, { FRAC_CONST(0.746964636505118), FRAC_CONST(0.664863769362399) }, { FRAC_CONST(0.742597145638433), FRAC_CONST(0.669738366296610) }, { FRAC_CONST(0.738197844381584), FRAC_CONST(0.674584273868271) }, { FRAC_CONST(0.733766921185995), FRAC_CONST(0.679401284494831) }, { FRAC_CONST(0.729304565857668), FRAC_CONST(0.684189191831585) }, { FRAC_CONST(0.724810969549055), FRAC_CONST(0.688947790780520) }, { FRAC_CONST(0.720286324750863), FRAC_CONST(0.693676877499095) }, { FRAC_CONST(0.715730825283819), FRAC_CONST(0.698376249408973) }, { FRAC_CONST(0.711144666290356), FRAC_CONST(0.703045705204703) }, { FRAC_CONST(0.706528044226263), FRAC_CONST(0.707685044862340) }, { FRAC_CONST(0.701881156852263), FRAC_CONST(0.712294069648014) }, { FRAC_CONST(0.697204203225545), FRAC_CONST(0.716872582126442) }, { FRAC_CONST(0.692497383691237), FRAC_CONST(0.721420386169390) }, { FRAC_CONST(0.687760899873822), FRAC_CONST(0.725937286964068) }, { FRAC_CONST(0.682994954668502), FRAC_CONST(0.730423091021479) }, { FRAC_CONST(0.678199752232508), FRAC_CONST(0.734877606184707) }, { FRAC_CONST(0.673375497976352), FRAC_CONST(0.739300641637149) }, { FRAC_CONST(0.668522398555031), FRAC_CONST(0.743692007910687) }, { FRAC_CONST(0.663640661859171), FRAC_CONST(0.748051516893805) }, { FRAC_CONST(0.658730497006124), FRAC_CONST(0.752378981839648) }, { FRAC_CONST(0.653792114331011), FRAC_CONST(0.756674217374021) }, { FRAC_CONST(0.648825725377709), FRAC_CONST(0.760937039503328) }, { FRAC_CONST(0.643831542889792), FRAC_CONST(0.765167265622459) }, { FRAC_CONST(0.638809780801414), FRAC_CONST(0.769364714522605) }, { FRAC_CONST(0.633760654228152), FRAC_CONST(0.773529206399025) }, { FRAC_CONST(0.628684379457781), FRAC_CONST(0.777660562858748) }, { FRAC_CONST(0.623581173941019), FRAC_CONST(0.781758606928213) }, { FRAC_CONST(0.618451256282204), FRAC_CONST(0.785823163060853) }, { FRAC_CONST(0.613294846229936), FRAC_CONST(0.789854057144609) }, { FRAC_CONST(0.608112164667659), FRAC_CONST(0.793851116509396) }, { FRAC_CONST(0.602903433604202), FRAC_CONST(0.797814169934493) }, { FRAC_CONST(0.597668876164268), FRAC_CONST(0.801743047655882) }, { FRAC_CONST(0.592408716578875), FRAC_CONST(0.805637581373517) }, { FRAC_CONST(0.587123180175754), FRAC_CONST(0.809497604258536) }, { FRAC_CONST(0.581812493369691), FRAC_CONST(0.813322950960406) }, { FRAC_CONST(0.576476883652835), FRAC_CONST(0.817113457614006) }, { FRAC_CONST(0.571116579584947), FRAC_CONST(0.820868961846646) }, { FRAC_CONST(0.565731810783613), FRAC_CONST(0.824589302785025) }, { FRAC_CONST(0.560322807914407), FRAC_CONST(0.828274321062119) }, { FRAC_CONST(0.554889802681009), FRAC_CONST(0.831923858824010) }, { FRAC_CONST(0.549433027815281), FRAC_CONST(0.835537759736646) }, { FRAC_CONST(0.543952717067296), FRAC_CONST(0.839115868992540) }, { FRAC_CONST(0.538449105195327), FRAC_CONST(0.842658033317402) }, { FRAC_CONST(0.532922427955790), FRAC_CONST(0.846164100976699) }, { FRAC_CONST(0.527372922093142), FRAC_CONST(0.849633921782164) }, { FRAC_CONST(0.521800825329746), FRAC_CONST(0.853067347098221) }, { FRAC_CONST(0.516206376355680), FRAC_CONST(0.856464229848356) }, { FRAC_CONST(0.510589814818519), FRAC_CONST(0.859824424521420) }, { FRAC_CONST(0.504951381313066), FRAC_CONST(0.863147787177854) }, { FRAC_CONST(0.499291317371047), FRAC_CONST(0.866434175455865) }, { FRAC_CONST(0.493609865450762), FRAC_CONST(0.869683448577516) }, { FRAC_CONST(0.487907268926702), FRAC_CONST(0.872895467354761) }, { FRAC_CONST(0.482183772079123), FRAC_CONST(0.876070094195407) }, { FRAC_CONST(0.476439620083580), FRAC_CONST(0.879207193109004) }, { FRAC_CONST(0.470675059000427), FRAC_CONST(0.882306629712678) }, { FRAC_CONST(0.464890335764274), FRAC_CONST(0.885368271236879) }, { FRAC_CONST(0.459085698173413), FRAC_CONST(0.888391986531075) }, { FRAC_CONST(0.453261394879198), FRAC_CONST(0.891377646069366) }, { FRAC_CONST(0.447417675375397), FRAC_CONST(0.894325121956035) }, { FRAC_CONST(0.441554789987504), FRAC_CONST(0.897234287931024) }, { FRAC_CONST(0.435672989862017), FRAC_CONST(0.900105019375345) }, { FRAC_CONST(0.429772526955677), FRAC_CONST(0.902937193316419) }, { FRAC_CONST(0.423853654024676), FRAC_CONST(0.905730688433339) }, { FRAC_CONST(0.417916624613831), FRAC_CONST(0.908485385062073) }, { FRAC_CONST(0.411961693045722), FRAC_CONST(0.911201165200584) }, { FRAC_CONST(0.405989114409798), FRAC_CONST(0.913877912513892) }, { FRAC_CONST(0.399999144551449), FRAC_CONST(0.916515512339049) }, { FRAC_CONST(0.393992040061048), FRAC_CONST(0.919113851690058) }, { FRAC_CONST(0.387968058262959), FRAC_CONST(0.921672819262709) }, { FRAC_CONST(0.381927457204511), FRAC_CONST(0.924192305439348) }, { FRAC_CONST(0.375870495644949), FRAC_CONST(0.926672202293573) }, { FRAC_CONST(0.369797433044349), FRAC_CONST(0.929112403594856) }, { FRAC_CONST(0.363708529552499), FRAC_CONST(0.931512804813095) }, { FRAC_CONST(0.357604045997758), FRAC_CONST(0.933873303123091) }, { FRAC_CONST(0.351484243875885), FRAC_CONST(0.936193797408954) }, { FRAC_CONST(0.345349385338836), FRAC_CONST(0.938474188268430) }, { FRAC_CONST(0.339199733183530), FRAC_CONST(0.940714378017165) }, { FRAC_CONST(0.333035550840599), FRAC_CONST(0.942914270692887) }, { FRAC_CONST(0.326857102363098), FRAC_CONST(0.945073772059514) }, { FRAC_CONST(0.320664652415198), FRAC_CONST(0.947192789611197) }, { FRAC_CONST(0.314458466260842), FRAC_CONST(0.949271232576274) }, { FRAC_CONST(0.308238809752391), FRAC_CONST(0.951309011921168) }, { FRAC_CONST(0.302005949319228), FRAC_CONST(0.953306040354194) }, { FRAC_CONST(0.295760151956351), FRAC_CONST(0.955262232329299) }, { FRAC_CONST(0.289501685212929), FRAC_CONST(0.957177504049732) }, { FRAC_CONST(0.283230817180850), FRAC_CONST(0.959051773471624) }, { FRAC_CONST(0.276947816483228), FRAC_CONST(0.960884960307514) }, { FRAC_CONST(0.270652952262902), FRAC_CONST(0.962676986029777) }, { FRAC_CONST(0.264346494170904), FRAC_CONST(0.964427773873996) }, { FRAC_CONST(0.258028712354909), FRAC_CONST(0.966137248842248) }, { FRAC_CONST(0.251699877447663), FRAC_CONST(0.967805337706313) }, { FRAC_CONST(0.245360260555389), FRAC_CONST(0.969431969010818) }, { FRAC_CONST(0.239010133246176), FRAC_CONST(0.971017073076290) }, { FRAC_CONST(0.232649767538342), FRAC_CONST(0.972560582002147) }, { FRAC_CONST(0.226279435888785), FRAC_CONST(0.974062429669605) }, { FRAC_CONST(0.219899411181310), FRAC_CONST(0.975522551744506) }, { FRAC_CONST(0.213509966714943), FRAC_CONST(0.976940885680082) }, { FRAC_CONST(0.207111376192219), FRAC_CONST(0.978317370719628) }, { FRAC_CONST(0.200703913707458), FRAC_CONST(0.979651947899104) }, { FRAC_CONST(0.194287853735029), FRAC_CONST(0.980944560049668) }, { FRAC_CONST(0.187863471117585), FRAC_CONST(0.982195151800116) }, { FRAC_CONST(0.181431041054297), FRAC_CONST(0.983403669579260) }, { FRAC_CONST(0.174990839089060), FRAC_CONST(0.984570061618221) }, { FRAC_CONST(0.168543141098691), FRAC_CONST(0.985694277952645) }, { FRAC_CONST(0.162088223281113), FRAC_CONST(0.986776270424848) }, { FRAC_CONST(0.155626362143520), FRAC_CONST(0.987815992685872) }, { FRAC_CONST(0.149157834490539), FRAC_CONST(0.988813400197476) }, { FRAC_CONST(0.142682917412363), FRAC_CONST(0.989768450234042) }, { FRAC_CONST(0.136201888272891), FRAC_CONST(0.990681101884405) }, { FRAC_CONST(0.129715024697841), FRAC_CONST(0.991551316053606) }, { FRAC_CONST(0.123222604562857), FRAC_CONST(0.992379055464567) }, { FRAC_CONST(0.116724905981611), FRAC_CONST(0.993164284659685) }, { FRAC_CONST(0.110222207293883), FRAC_CONST(0.993906970002356) }, { FRAC_CONST(0.103714787053643), FRAC_CONST(0.994607079678411) }, { FRAC_CONST(0.097202924017115), FRAC_CONST(0.995264583697482) }, { FRAC_CONST(0.090686897130838), FRAC_CONST(0.995879453894286) }, { FRAC_CONST(0.084166985519718), FRAC_CONST(0.996451663929828) }, { FRAC_CONST(0.077643468475068), FRAC_CONST(0.996981189292537) }, { FRAC_CONST(0.071116625442645), FRAC_CONST(0.997468007299307) }, { FRAC_CONST(0.064586736010684), FRAC_CONST(0.997912097096476) }, { FRAC_CONST(0.058054079897912), FRAC_CONST(0.998313439660714) }, { FRAC_CONST(0.051518936941578), FRAC_CONST(0.998672017799843) }, { FRAC_CONST(0.044981587085452), FRAC_CONST(0.998987816153567) }, { FRAC_CONST(0.038442310367847), FRAC_CONST(0.999260821194138) }, { FRAC_CONST(0.031901386909611), FRAC_CONST(0.999491021226926) }, { FRAC_CONST(0.025359096902136), FRAC_CONST(0.999678406390929) }, { FRAC_CONST(0.018815720595351), FRAC_CONST(0.999822968659191) }, { FRAC_CONST(0.012271538285720), FRAC_CONST(0.999924701839145) }, { FRAC_CONST(0.005726830304231), FRAC_CONST(0.999983601572879) } }; #endif // LD_DEC /* 60 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_240[] = { { FRAC_CONST(0.999994645401696), FRAC_CONST(0.003272486506527) }, { FRAC_CONST(0.999566308502021), FRAC_CONST(0.029448173247963) }, { FRAC_CONST(0.998452918783950), FRAC_CONST(0.055603677682425) }, { FRAC_CONST(0.996655239309180), FRAC_CONST(0.081721074133668) }, { FRAC_CONST(0.994174502117428), FRAC_CONST(0.107782463042759) }, { FRAC_CONST(0.991012407382049), FRAC_CONST(0.133769983235535) }, { FRAC_CONST(0.987171122244825), FRAC_CONST(0.159665824163761) }, { FRAC_CONST(0.982653279330712), FRAC_CONST(0.185452238111591) }, { FRAC_CONST(0.977461974943572), FRAC_CONST(0.211111552358965) }, { FRAC_CONST(0.971600766944121), FRAC_CONST(0.236626181293610) }, { FRAC_CONST(0.965073672311547), FRAC_CONST(0.261978638463337) }, { FRAC_CONST(0.957885164390477), FRAC_CONST(0.287151548560387) }, { FRAC_CONST(0.950040169825165), FRAC_CONST(0.312127659329594) }, { FRAC_CONST(0.941544065183021), FRAC_CONST(0.336889853392220) }, { FRAC_CONST(0.932402673269775), FRAC_CONST(0.361421159977355) }, { FRAC_CONST(0.922622259138823), FRAC_CONST(0.385704766552831) }, { FRAC_CONST(0.912209525797468), FRAC_CONST(0.409724030347695) }, { FRAC_CONST(0.901171609613013), FRAC_CONST(0.433462489758331) }, { FRAC_CONST(0.889516075421856), FRAC_CONST(0.456903875630421) }, { FRAC_CONST(0.877250911344924), FRAC_CONST(0.480032122409011) }, { FRAC_CONST(0.864384523313017), FRAC_CONST(0.502831379149042) }, { FRAC_CONST(0.850925729305802), FRAC_CONST(0.525286020378792) }, { FRAC_CONST(0.836883753308409), FRAC_CONST(0.547380656808797) }, { FRAC_CONST(0.822268218989775), FRAC_CONST(0.569100145878898) }, { FRAC_CONST(0.807089143107059), FRAC_CONST(0.590429602136201) }, { FRAC_CONST(0.791356928640660), FRAC_CONST(0.611354407436816) }, { FRAC_CONST(0.775082357664531), FRAC_CONST(0.631860220964409) }, { FRAC_CONST(0.758276583956687), FRAC_CONST(0.651932989058674) }, { FRAC_CONST(0.740951125354959), FRAC_CONST(0.671558954847018) }, { FRAC_CONST(0.723117855863248), FRAC_CONST(0.690724667672829) }, { FRAC_CONST(0.704788997513670), FRAC_CONST(0.709416992313883) }, { FRAC_CONST(0.685977111990193), FRAC_CONST(0.727623117984575) }, { FRAC_CONST(0.666695092019479), FRAC_CONST(0.745330567115786) }, { FRAC_CONST(0.646956152534857), FRAC_CONST(0.762527203906388) }, { FRAC_CONST(0.626773821619469), FRAC_CONST(0.779201242640517) }, { FRAC_CONST(0.606161931234795), FRAC_CONST(0.795341255764910) }, { FRAC_CONST(0.585134607740916), FRAC_CONST(0.810936181720784) }, { FRAC_CONST(0.563706262215017), FRAC_CONST(0.825975332524873) }, { FRAC_CONST(0.541891580574752), FRAC_CONST(0.840448401094438) }, { FRAC_CONST(0.519705513513249), FRAC_CONST(0.854345468311227) }, { FRAC_CONST(0.497163266252654), FRAC_CONST(0.867657009819544) }, { FRAC_CONST(0.474280288123229), FRAC_CONST(0.880373902553765) }, { FRAC_CONST(0.451072261975153), FRAC_CONST(0.892487430990834) }, { FRAC_CONST(0.427555093430282), FRAC_CONST(0.903989293123443) }, { FRAC_CONST(0.403744899981227), FRAC_CONST(0.914871606149819) }, { FRAC_CONST(0.379657999945233), FRAC_CONST(0.925126911876195) }, { FRAC_CONST(0.355310901280416), FRAC_CONST(0.934748181828292) }, { FRAC_CONST(0.330720290272038), FRAC_CONST(0.943728822068278) }, { FRAC_CONST(0.305903020096554), FRAC_CONST(0.952062677713924) }, { FRAC_CONST(0.280876099271292), FRAC_CONST(0.959744037156857) }, { FRAC_CONST(0.255656679997665), FRAC_CONST(0.966767635977008) }, { FRAC_CONST(0.230262046405902), FRAC_CONST(0.973128660550580) }, { FRAC_CONST(0.204709602709380), FRAC_CONST(0.978822751349072) }, { FRAC_CONST(0.179016861276633), FRAC_CONST(0.983846005927077) }, { FRAC_CONST(0.153201430629259), FRAC_CONST(0.988194981596825) }, { FRAC_CONST(0.127281003373913), FRAC_CONST(0.991866697787626) }, { FRAC_CONST(0.101273344076683), FRAC_CONST(0.994858638088611) }, { FRAC_CONST(0.075196277088140), FRAC_CONST(0.997168751973348) }, { FRAC_CONST(0.049067674327418), FRAC_CONST(0.998795456205172) }, { FRAC_CONST(0.022905443033697), FRAC_CONST(0.999737635922260) } }; #endif // ALLOW_SMALL_FRAMELENGTH #ifdef SSR_DEC /* 128 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_512[] = { { FRAC_CONST(0.999998823451702), FRAC_CONST(0.001533980186285) }, { FRAC_CONST(0.999904701082853), FRAC_CONST(0.013805388528060) }, { FRAC_CONST(0.999659996743959), FRAC_CONST(0.026074717829104) }, { FRAC_CONST(0.999264747286594), FRAC_CONST(0.038340120373553) }, { FRAC_CONST(0.998719012233873), FRAC_CONST(0.050599749036899) }, { FRAC_CONST(0.998022873771486), FRAC_CONST(0.062851757564161) }, { FRAC_CONST(0.997176436735326), FRAC_CONST(0.075094300847921) }, { FRAC_CONST(0.996179828595697), FRAC_CONST(0.087325535206192) }, { FRAC_CONST(0.995033199438119), FRAC_CONST(0.099543618660069) }, { FRAC_CONST(0.993736721940725), FRAC_CONST(0.111746711211127) }, { FRAC_CONST(0.992290591348257), FRAC_CONST(0.123932975118512) }, { FRAC_CONST(0.990695025442665), FRAC_CONST(0.136100575175706) }, { FRAC_CONST(0.988950264510303), FRAC_CONST(0.148247678986896) }, { FRAC_CONST(0.987056571305751), FRAC_CONST(0.160372457242928) }, { FRAC_CONST(0.985014231012240), FRAC_CONST(0.172473083996796) }, { FRAC_CONST(0.982823551198705), FRAC_CONST(0.184547736938620) }, { FRAC_CONST(0.980484861773469), FRAC_CONST(0.196594597670080) }, { FRAC_CONST(0.977998514934557), FRAC_CONST(0.208611851978263) }, { FRAC_CONST(0.975364885116657), FRAC_CONST(0.220597690108874) }, { FRAC_CONST(0.972584368934732), FRAC_CONST(0.232550307038775) }, { FRAC_CONST(0.969657385124292), FRAC_CONST(0.244467902747824) }, { FRAC_CONST(0.966584374478333), FRAC_CONST(0.256348682489943) }, { FRAC_CONST(0.963365799780954), FRAC_CONST(0.268190857063403) }, { FRAC_CONST(0.960002145737666), FRAC_CONST(0.279992643080273) }, { FRAC_CONST(0.956493918902395), FRAC_CONST(0.291752263234989) }, { FRAC_CONST(0.952841647601199), FRAC_CONST(0.303467946572011) }, { FRAC_CONST(0.949045881852701), FRAC_CONST(0.315137928752522) }, { FRAC_CONST(0.945107193285261), FRAC_CONST(0.326760452320132) }, { FRAC_CONST(0.941026175050889), FRAC_CONST(0.338333766965541) }, { FRAC_CONST(0.936803441735922), FRAC_CONST(0.349856129790135) }, { FRAC_CONST(0.932439629268462), FRAC_CONST(0.361325805568454) }, { FRAC_CONST(0.927935394822618), FRAC_CONST(0.372741067009516) }, { FRAC_CONST(0.923291416719528), FRAC_CONST(0.384100195016935) }, { FRAC_CONST(0.918508394325212), FRAC_CONST(0.395401478947816) }, { FRAC_CONST(0.913587047945251), FRAC_CONST(0.406643216870369) }, { FRAC_CONST(0.908528118716306), FRAC_CONST(0.417823715820212) }, { FRAC_CONST(0.903332368494512), FRAC_CONST(0.428941292055329) }, { FRAC_CONST(0.898000579740740), FRAC_CONST(0.439994271309633) }, { FRAC_CONST(0.892533555402765), FRAC_CONST(0.450980989045104) }, { FRAC_CONST(0.886932118794342), FRAC_CONST(0.461899790702463) }, { FRAC_CONST(0.881197113471222), FRAC_CONST(0.472749031950343) }, { FRAC_CONST(0.875329403104111), FRAC_CONST(0.483527078932919) }, { FRAC_CONST(0.869329871348607), FRAC_CONST(0.494232308515960) }, { FRAC_CONST(0.863199421712124), FRAC_CONST(0.504863108531268) }, { FRAC_CONST(0.856938977417829), FRAC_CONST(0.515417878019463) }, { FRAC_CONST(0.850549481265603), FRAC_CONST(0.525895027471085) }, { FRAC_CONST(0.844031895490066), FRAC_CONST(0.536292979065963) }, { FRAC_CONST(0.837387201615662), FRAC_CONST(0.546610166910835) }, { FRAC_CONST(0.830616400308846), FRAC_CONST(0.556845037275160) }, { FRAC_CONST(0.823720511227391), FRAC_CONST(0.566996048825109) }, { FRAC_CONST(0.816700572866828), FRAC_CONST(0.577061672855679) }, { FRAC_CONST(0.809557642404051), FRAC_CONST(0.587040393520918) }, { FRAC_CONST(0.802292795538116), FRAC_CONST(0.596930708062197) }, { FRAC_CONST(0.794907126328237), FRAC_CONST(0.606731127034524) }, { FRAC_CONST(0.787401747029031), FRAC_CONST(0.616440174530854) }, { FRAC_CONST(0.779777787923015), FRAC_CONST(0.626056388404344) }, { FRAC_CONST(0.772036397150385), FRAC_CONST(0.635578320488556) }, { FRAC_CONST(0.764178740536117), FRAC_CONST(0.645004536815544) }, { FRAC_CONST(0.756206001414395), FRAC_CONST(0.654333617831800) }, { FRAC_CONST(0.748119380450404), FRAC_CONST(0.663564158612040) }, { FRAC_CONST(0.739920095459516), FRAC_CONST(0.672694769070773) }, { FRAC_CONST(0.731609381223893), FRAC_CONST(0.681724074171650) }, { FRAC_CONST(0.723188489306527), FRAC_CONST(0.690650714134535) }, { FRAC_CONST(0.714658687862769), FRAC_CONST(0.699473344640284) }, { FRAC_CONST(0.706021261449340), FRAC_CONST(0.708190637033195) }, { FRAC_CONST(0.697277510830887), FRAC_CONST(0.716801278521100) }, { FRAC_CONST(0.688428752784091), FRAC_CONST(0.725303972373061) }, { FRAC_CONST(0.679476319899365), FRAC_CONST(0.733697438114660) }, { FRAC_CONST(0.670421560380173), FRAC_CONST(0.741980411720831) }, { FRAC_CONST(0.661265837839992), FRAC_CONST(0.750151645806215) }, { FRAC_CONST(0.652010531096960), FRAC_CONST(0.758209909813015) }, { FRAC_CONST(0.642657033966227), FRAC_CONST(0.766153990196313) }, { FRAC_CONST(0.633206755050057), FRAC_CONST(0.773982690606823) }, { FRAC_CONST(0.623661117525695), FRAC_CONST(0.781694832071059) }, { FRAC_CONST(0.614021558931038), FRAC_CONST(0.789289253168886) }, { FRAC_CONST(0.604289530948156), FRAC_CONST(0.796764810208419) }, { FRAC_CONST(0.594466499184665), FRAC_CONST(0.804120377398266) }, { FRAC_CONST(0.584553942953015), FRAC_CONST(0.811354847017064) }, { FRAC_CONST(0.574553355047716), FRAC_CONST(0.818467129580299) }, { FRAC_CONST(0.564466241520520), FRAC_CONST(0.825456154004377) }, { FRAC_CONST(0.554294121453620), FRAC_CONST(0.832320867767930) }, { FRAC_CONST(0.544038526730884), FRAC_CONST(0.839060237070313) }, { FRAC_CONST(0.533701001807153), FRAC_CONST(0.845673246987299) }, { FRAC_CONST(0.523283103475656), FRAC_CONST(0.852158901623920) }, { FRAC_CONST(0.512786400633563), FRAC_CONST(0.858516224264443) }, { FRAC_CONST(0.502212474045711), FRAC_CONST(0.864744257519462) }, { FRAC_CONST(0.491562916106550), FRAC_CONST(0.870842063470079) }, { FRAC_CONST(0.480839330600334), FRAC_CONST(0.876808723809146) }, { FRAC_CONST(0.470043332459596), FRAC_CONST(0.882643339979563) }, { FRAC_CONST(0.459176547521944), FRAC_CONST(0.888345033309596) }, { FRAC_CONST(0.448240612285220), FRAC_CONST(0.893912945145203) }, { FRAC_CONST(0.437237173661044), FRAC_CONST(0.899346236979341) }, { FRAC_CONST(0.426167888726800), FRAC_CONST(0.904644090578246) }, { FRAC_CONST(0.415034424476082), FRAC_CONST(0.909805708104652) }, { FRAC_CONST(0.403838457567654), FRAC_CONST(0.914830312237946) }, { FRAC_CONST(0.392581674072952), FRAC_CONST(0.919717146291227) }, { FRAC_CONST(0.381265769222162), FRAC_CONST(0.924465474325263) }, { FRAC_CONST(0.369892447148934), FRAC_CONST(0.929074581259316) }, { FRAC_CONST(0.358463420633737), FRAC_CONST(0.933543772978836) }, { FRAC_CONST(0.346980410845924), FRAC_CONST(0.937872376439990) }, { FRAC_CONST(0.335445147084532), FRAC_CONST(0.942059739771017) }, { FRAC_CONST(0.323859366517853), FRAC_CONST(0.946105232370403) }, { FRAC_CONST(0.312224813921825), FRAC_CONST(0.950008245001843) }, { FRAC_CONST(0.300543241417273), FRAC_CONST(0.953768189885990) }, { FRAC_CONST(0.288816408206049), FRAC_CONST(0.957384500788976) }, { FRAC_CONST(0.277046080306100), FRAC_CONST(0.960856633107680) }, { FRAC_CONST(0.265234030285512), FRAC_CONST(0.964184063951746) }, { FRAC_CONST(0.253382036995570), FRAC_CONST(0.967366292222329) }, { FRAC_CONST(0.241491885302869), FRAC_CONST(0.970402838687556) }, { FRAC_CONST(0.229565365820519), FRAC_CONST(0.973293246054698) }, { FRAC_CONST(0.217604274638484), FRAC_CONST(0.976037079039039) }, { FRAC_CONST(0.205610413053099), FRAC_CONST(0.978633924429423) }, { FRAC_CONST(0.193585587295804), FRAC_CONST(0.981083391150487) }, { FRAC_CONST(0.181531608261125), FRAC_CONST(0.983385110321551) }, { FRAC_CONST(0.169450291233968), FRAC_CONST(0.985538735312176) }, { FRAC_CONST(0.157343455616238), FRAC_CONST(0.987543941794359) }, { FRAC_CONST(0.145212924652848), FRAC_CONST(0.989400427791380) }, { FRAC_CONST(0.133060525157139), FRAC_CONST(0.991107913723277) }, { FRAC_CONST(0.120888087235777), FRAC_CONST(0.992666142448948) }, { FRAC_CONST(0.108697444013139), FRAC_CONST(0.994074879304879) }, { FRAC_CONST(0.096490431355253), FRAC_CONST(0.995333912140482) }, { FRAC_CONST(0.084268887593324), FRAC_CONST(0.996443051350043) }, { FRAC_CONST(0.072034653246889), FRAC_CONST(0.997402129901275) }, { FRAC_CONST(0.059789570746640), FRAC_CONST(0.998211003360478) }, { FRAC_CONST(0.047535484156959), FRAC_CONST(0.998869549914284) }, { FRAC_CONST(0.035274238898214), FRAC_CONST(0.999377670388003) }, { FRAC_CONST(0.023007681468839), FRAC_CONST(0.999735288260562) }, { FRAC_CONST(0.010737659167265), FRAC_CONST(0.999942349676024) } }; /* 16 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_64[] = { { FRAC_CONST(0.999924701839145), FRAC_CONST(0.012271538285720) }, { FRAC_CONST(0.993906970002356), FRAC_CONST(0.110222207293883) }, { FRAC_CONST(0.978317370719628), FRAC_CONST(0.207111376192219) }, { FRAC_CONST(0.953306040354194), FRAC_CONST(0.302005949319228) }, { FRAC_CONST(0.919113851690058), FRAC_CONST(0.393992040061048) }, { FRAC_CONST(0.876070094195407), FRAC_CONST(0.482183772079123) }, { FRAC_CONST(0.824589302785025), FRAC_CONST(0.565731810783613) }, { FRAC_CONST(0.765167265622459), FRAC_CONST(0.643831542889791) }, { FRAC_CONST(0.698376249408973), FRAC_CONST(0.715730825283819) }, { FRAC_CONST(0.624859488142386), FRAC_CONST(0.780737228572094) }, { FRAC_CONST(0.545324988422046), FRAC_CONST(0.838224705554838) }, { FRAC_CONST(0.460538710958240), FRAC_CONST(0.887639620402854) }, { FRAC_CONST(0.371317193951838), FRAC_CONST(0.928506080473215) }, { FRAC_CONST(0.278519689385053), FRAC_CONST(0.960430519415566) }, { FRAC_CONST(0.183039887955141), FRAC_CONST(0.983105487431216) }, { FRAC_CONST(0.085797312344440), FRAC_CONST(0.996312612182778) } }; #endif // SSR_DEC #else // FIXED_POINT /* 256 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_2048[] = { { FRAC_CONST(0.031249997702054), FRAC_CONST(0.000011984224612) }, { FRAC_CONST(0.031249813866531), FRAC_CONST(0.000107857810004) }, { FRAC_CONST(0.031249335895858), FRAC_CONST(0.000203730380198) }, { FRAC_CONST(0.031248563794535), FRAC_CONST(0.000299601032804) }, { FRAC_CONST(0.031247497569829), FRAC_CONST(0.000395468865451) }, { FRAC_CONST(0.031246137231775), FRAC_CONST(0.000491332975794) }, { FRAC_CONST(0.031244482793177), FRAC_CONST(0.000587192461525) }, { FRAC_CONST(0.031242534269608), FRAC_CONST(0.000683046420376) }, { FRAC_CONST(0.031240291679407), FRAC_CONST(0.000778893950134) }, { FRAC_CONST(0.031237755043684), FRAC_CONST(0.000874734148645) }, { FRAC_CONST(0.031234924386313), FRAC_CONST(0.000970566113826) }, { FRAC_CONST(0.031231799733938), FRAC_CONST(0.001066388943669) }, { FRAC_CONST(0.031228381115970), FRAC_CONST(0.001162201736253) }, { FRAC_CONST(0.031224668564585), FRAC_CONST(0.001258003589751) }, { FRAC_CONST(0.031220662114728), FRAC_CONST(0.001353793602441) }, { FRAC_CONST(0.031216361804108), FRAC_CONST(0.001449570872710) }, { FRAC_CONST(0.031211767673203), FRAC_CONST(0.001545334499065) }, { FRAC_CONST(0.031206879765253), FRAC_CONST(0.001641083580144) }, { FRAC_CONST(0.031201698126266), FRAC_CONST(0.001736817214719) }, { FRAC_CONST(0.031196222805014), FRAC_CONST(0.001832534501709) }, { FRAC_CONST(0.031190453853031), FRAC_CONST(0.001928234540186) }, { FRAC_CONST(0.031184391324617), FRAC_CONST(0.002023916429386) }, { FRAC_CONST(0.031178035276836), FRAC_CONST(0.002119579268713) }, { FRAC_CONST(0.031171385769513), FRAC_CONST(0.002215222157753) }, { FRAC_CONST(0.031164442865236), FRAC_CONST(0.002310844196278) }, { FRAC_CONST(0.031157206629353), FRAC_CONST(0.002406444484258) }, { FRAC_CONST(0.031149677129975), FRAC_CONST(0.002502022121865) }, { FRAC_CONST(0.031141854437973), FRAC_CONST(0.002597576209488) }, { FRAC_CONST(0.031133738626977), FRAC_CONST(0.002693105847734) }, { FRAC_CONST(0.031125329773375), FRAC_CONST(0.002788610137442) }, { FRAC_CONST(0.031116627956316), FRAC_CONST(0.002884088179689) }, { FRAC_CONST(0.031107633257703), FRAC_CONST(0.002979539075801) }, { FRAC_CONST(0.031098345762200), FRAC_CONST(0.003074961927355) }, { FRAC_CONST(0.031088765557222), FRAC_CONST(0.003170355836197) }, { FRAC_CONST(0.031078892732942), FRAC_CONST(0.003265719904442) }, { FRAC_CONST(0.031068727382288), FRAC_CONST(0.003361053234488) }, { FRAC_CONST(0.031058269600939), FRAC_CONST(0.003456354929021) }, { FRAC_CONST(0.031047519487329), FRAC_CONST(0.003551624091024) }, { FRAC_CONST(0.031036477142640), FRAC_CONST(0.003646859823790) }, { FRAC_CONST(0.031025142670809), FRAC_CONST(0.003742061230921) }, { FRAC_CONST(0.031013516178519), FRAC_CONST(0.003837227416347) }, { FRAC_CONST(0.031001597775203), FRAC_CONST(0.003932357484328) }, { FRAC_CONST(0.030989387573042), FRAC_CONST(0.004027450539462) }, { FRAC_CONST(0.030976885686963), FRAC_CONST(0.004122505686697) }, { FRAC_CONST(0.030964092234638), FRAC_CONST(0.004217522031340) }, { FRAC_CONST(0.030951007336485), FRAC_CONST(0.004312498679058) }, { FRAC_CONST(0.030937631115663), FRAC_CONST(0.004407434735897) }, { FRAC_CONST(0.030923963698074), FRAC_CONST(0.004502329308281) }, { FRAC_CONST(0.030910005212362), FRAC_CONST(0.004597181503027) }, { FRAC_CONST(0.030895755789908), FRAC_CONST(0.004691990427350) }, { FRAC_CONST(0.030881215564835), FRAC_CONST(0.004786755188872) }, { FRAC_CONST(0.030866384674000), FRAC_CONST(0.004881474895632) }, { FRAC_CONST(0.030851263256996), FRAC_CONST(0.004976148656090) }, { FRAC_CONST(0.030835851456154), FRAC_CONST(0.005070775579142) }, { FRAC_CONST(0.030820149416533), FRAC_CONST(0.005165354774124) }, { FRAC_CONST(0.030804157285929), FRAC_CONST(0.005259885350819) }, { FRAC_CONST(0.030787875214864), FRAC_CONST(0.005354366419469) }, { FRAC_CONST(0.030771303356593), FRAC_CONST(0.005448797090784) }, { FRAC_CONST(0.030754441867095), FRAC_CONST(0.005543176475946) }, { FRAC_CONST(0.030737290905077), FRAC_CONST(0.005637503686619) }, { FRAC_CONST(0.030719850631972), FRAC_CONST(0.005731777834961) }, { FRAC_CONST(0.030702121211932), FRAC_CONST(0.005825998033626) }, { FRAC_CONST(0.030684102811835), FRAC_CONST(0.005920163395780) }, { FRAC_CONST(0.030665795601276), FRAC_CONST(0.006014273035101) }, { FRAC_CONST(0.030647199752570), FRAC_CONST(0.006108326065793) }, { FRAC_CONST(0.030628315440748), FRAC_CONST(0.006202321602594) }, { FRAC_CONST(0.030609142843557), FRAC_CONST(0.006296258760782) }, { FRAC_CONST(0.030589682141455), FRAC_CONST(0.006390136656185) }, { FRAC_CONST(0.030569933517616), FRAC_CONST(0.006483954405188) }, { FRAC_CONST(0.030549897157919), FRAC_CONST(0.006577711124743) }, { FRAC_CONST(0.030529573250956), FRAC_CONST(0.006671405932375) }, { FRAC_CONST(0.030508961988022), FRAC_CONST(0.006765037946194) }, { FRAC_CONST(0.030488063563118), FRAC_CONST(0.006858606284900) }, { FRAC_CONST(0.030466878172949), FRAC_CONST(0.006952110067791) }, { FRAC_CONST(0.030445406016919), FRAC_CONST(0.007045548414774) }, { FRAC_CONST(0.030423647297133), FRAC_CONST(0.007138920446372) }, { FRAC_CONST(0.030401602218392), FRAC_CONST(0.007232225283733) }, { FRAC_CONST(0.030379270988192), FRAC_CONST(0.007325462048634) }, { FRAC_CONST(0.030356653816724), FRAC_CONST(0.007418629863497) }, { FRAC_CONST(0.030333750916869), FRAC_CONST(0.007511727851390) }, { FRAC_CONST(0.030310562504198), FRAC_CONST(0.007604755136040) }, { FRAC_CONST(0.030287088796968), FRAC_CONST(0.007697710841838) }, { FRAC_CONST(0.030263330016124), FRAC_CONST(0.007790594093851) }, { FRAC_CONST(0.030239286385293), FRAC_CONST(0.007883404017824) }, { FRAC_CONST(0.030214958130781), FRAC_CONST(0.007976139740197) }, { FRAC_CONST(0.030190345481576), FRAC_CONST(0.008068800388104) }, { FRAC_CONST(0.030165448669342), FRAC_CONST(0.008161385089390) }, { FRAC_CONST(0.030140267928416), FRAC_CONST(0.008253892972610) }, { FRAC_CONST(0.030114803495809), FRAC_CONST(0.008346323167047) }, { FRAC_CONST(0.030089055611203), FRAC_CONST(0.008438674802711) }, { FRAC_CONST(0.030063024516947), FRAC_CONST(0.008530947010354) }, { FRAC_CONST(0.030036710458054), FRAC_CONST(0.008623138921475) }, { FRAC_CONST(0.030010113682202), FRAC_CONST(0.008715249668328) }, { FRAC_CONST(0.029983234439732), FRAC_CONST(0.008807278383932) }, { FRAC_CONST(0.029956072983640), FRAC_CONST(0.008899224202078) }, { FRAC_CONST(0.029928629569580), FRAC_CONST(0.008991086257336) }, { FRAC_CONST(0.029900904455860), FRAC_CONST(0.009082863685067) }, { FRAC_CONST(0.029872897903441), FRAC_CONST(0.009174555621425) }, { FRAC_CONST(0.029844610175929), FRAC_CONST(0.009266161203371) }, { FRAC_CONST(0.029816041539579), FRAC_CONST(0.009357679568679) }, { FRAC_CONST(0.029787192263292), FRAC_CONST(0.009449109855944) }, { FRAC_CONST(0.029758062618606), FRAC_CONST(0.009540451204587) }, { FRAC_CONST(0.029728652879702), FRAC_CONST(0.009631702754871) }, { FRAC_CONST(0.029698963323395), FRAC_CONST(0.009722863647900) }, { FRAC_CONST(0.029668994229134), FRAC_CONST(0.009813933025633) }, { FRAC_CONST(0.029638745879000), FRAC_CONST(0.009904910030891) }, { FRAC_CONST(0.029608218557702), FRAC_CONST(0.009995793807363) }, { FRAC_CONST(0.029577412552575), FRAC_CONST(0.010086583499618) }, { FRAC_CONST(0.029546328153577), FRAC_CONST(0.010177278253107) }, { FRAC_CONST(0.029514965653285), FRAC_CONST(0.010267877214177) }, { FRAC_CONST(0.029483325346896), FRAC_CONST(0.010358379530076) }, { FRAC_CONST(0.029451407532220), FRAC_CONST(0.010448784348962) }, { FRAC_CONST(0.029419212509679), FRAC_CONST(0.010539090819911) }, { FRAC_CONST(0.029386740582307), FRAC_CONST(0.010629298092923) }, { FRAC_CONST(0.029353992055740), FRAC_CONST(0.010719405318933) }, { FRAC_CONST(0.029320967238220), FRAC_CONST(0.010809411649818) }, { FRAC_CONST(0.029287666440590), FRAC_CONST(0.010899316238403) }, { FRAC_CONST(0.029254089976290), FRAC_CONST(0.010989118238474) }, { FRAC_CONST(0.029220238161353), FRAC_CONST(0.011078816804778) }, { FRAC_CONST(0.029186111314406), FRAC_CONST(0.011168411093039) }, { FRAC_CONST(0.029151709756664), FRAC_CONST(0.011257900259961) }, { FRAC_CONST(0.029117033811927), FRAC_CONST(0.011347283463239) }, { FRAC_CONST(0.029082083806579), FRAC_CONST(0.011436559861563) }, { FRAC_CONST(0.029046860069582), FRAC_CONST(0.011525728614630) }, { FRAC_CONST(0.029011362932476), FRAC_CONST(0.011614788883150) }, { FRAC_CONST(0.028975592729373), FRAC_CONST(0.011703739828853) }, { FRAC_CONST(0.028939549796957), FRAC_CONST(0.011792580614500) }, { FRAC_CONST(0.028903234474475), FRAC_CONST(0.011881310403886) }, { FRAC_CONST(0.028866647103744), FRAC_CONST(0.011969928361855) }, { FRAC_CONST(0.028829788029135), FRAC_CONST(0.012058433654299) }, { FRAC_CONST(0.028792657597583), FRAC_CONST(0.012146825448172) }, { FRAC_CONST(0.028755256158571), FRAC_CONST(0.012235102911499) }, { FRAC_CONST(0.028717584064137), FRAC_CONST(0.012323265213377) }, { FRAC_CONST(0.028679641668864), FRAC_CONST(0.012411311523990) }, { FRAC_CONST(0.028641429329882), FRAC_CONST(0.012499241014612) }, { FRAC_CONST(0.028602947406859), FRAC_CONST(0.012587052857618) }, { FRAC_CONST(0.028564196262001), FRAC_CONST(0.012674746226488) }, { FRAC_CONST(0.028525176260050), FRAC_CONST(0.012762320295819) }, { FRAC_CONST(0.028485887768276), FRAC_CONST(0.012849774241331) }, { FRAC_CONST(0.028446331156478), FRAC_CONST(0.012937107239875) }, { FRAC_CONST(0.028406506796976), FRAC_CONST(0.013024318469437) }, { FRAC_CONST(0.028366415064615), FRAC_CONST(0.013111407109155) }, { FRAC_CONST(0.028326056336751), FRAC_CONST(0.013198372339315) }, { FRAC_CONST(0.028285430993258), FRAC_CONST(0.013285213341368) }, { FRAC_CONST(0.028244539416515), FRAC_CONST(0.013371929297933) }, { FRAC_CONST(0.028203381991411), FRAC_CONST(0.013458519392807) }, { FRAC_CONST(0.028161959105334), FRAC_CONST(0.013544982810971) }, { FRAC_CONST(0.028120271148172), FRAC_CONST(0.013631318738598) }, { FRAC_CONST(0.028078318512309), FRAC_CONST(0.013717526363062) }, { FRAC_CONST(0.028036101592619), FRAC_CONST(0.013803604872943) }, { FRAC_CONST(0.027993620786463), FRAC_CONST(0.013889553458039) }, { FRAC_CONST(0.027950876493687), FRAC_CONST(0.013975371309367) }, { FRAC_CONST(0.027907869116616), FRAC_CONST(0.014061057619178) }, { FRAC_CONST(0.027864599060052), FRAC_CONST(0.014146611580959) }, { FRAC_CONST(0.027821066731270), FRAC_CONST(0.014232032389445) }, { FRAC_CONST(0.027777272540012), FRAC_CONST(0.014317319240622) }, { FRAC_CONST(0.027733216898487), FRAC_CONST(0.014402471331737) }, { FRAC_CONST(0.027688900221361), FRAC_CONST(0.014487487861307) }, { FRAC_CONST(0.027644322925762), FRAC_CONST(0.014572368029123) }, { FRAC_CONST(0.027599485431266), FRAC_CONST(0.014657111036262) }, { FRAC_CONST(0.027554388159903), FRAC_CONST(0.014741716085090) }, { FRAC_CONST(0.027509031536144), FRAC_CONST(0.014826182379271) }, { FRAC_CONST(0.027463415986904), FRAC_CONST(0.014910509123778) }, { FRAC_CONST(0.027417541941533), FRAC_CONST(0.014994695524894) }, { FRAC_CONST(0.027371409831816), FRAC_CONST(0.015078740790225) }, { FRAC_CONST(0.027325020091965), FRAC_CONST(0.015162644128704) }, { FRAC_CONST(0.027278373158618), FRAC_CONST(0.015246404750603) }, { FRAC_CONST(0.027231469470833), FRAC_CONST(0.015330021867534) }, { FRAC_CONST(0.027184309470088), FRAC_CONST(0.015413494692460) }, { FRAC_CONST(0.027136893600268), FRAC_CONST(0.015496822439704) }, { FRAC_CONST(0.027089222307671), FRAC_CONST(0.015580004324954) }, { FRAC_CONST(0.027041296040997), FRAC_CONST(0.015663039565269) }, { FRAC_CONST(0.026993115251345), FRAC_CONST(0.015745927379091) }, { FRAC_CONST(0.026944680392213), FRAC_CONST(0.015828666986247) }, { FRAC_CONST(0.026895991919487), FRAC_CONST(0.015911257607961) }, { FRAC_CONST(0.026847050291442), FRAC_CONST(0.015993698466859) }, { FRAC_CONST(0.026797855968734), FRAC_CONST(0.016075988786976) }, { FRAC_CONST(0.026748409414401), FRAC_CONST(0.016158127793763) }, { FRAC_CONST(0.026698711093851), FRAC_CONST(0.016240114714099) }, { FRAC_CONST(0.026648761474864), FRAC_CONST(0.016321948776289) }, { FRAC_CONST(0.026598561027585), FRAC_CONST(0.016403629210082) }, { FRAC_CONST(0.026548110224519), FRAC_CONST(0.016485155246669) }, { FRAC_CONST(0.026497409540530), FRAC_CONST(0.016566526118696) }, { FRAC_CONST(0.026446459452830), FRAC_CONST(0.016647741060271) }, { FRAC_CONST(0.026395260440982), FRAC_CONST(0.016728799306966) }, { FRAC_CONST(0.026343812986890), FRAC_CONST(0.016809700095831) }, { FRAC_CONST(0.026292117574797), FRAC_CONST(0.016890442665397) }, { FRAC_CONST(0.026240174691280), FRAC_CONST(0.016971026255683) }, { FRAC_CONST(0.026187984825246), FRAC_CONST(0.017051450108208) }, { FRAC_CONST(0.026135548467924), FRAC_CONST(0.017131713465990) }, { FRAC_CONST(0.026082866112867), FRAC_CONST(0.017211815573560) }, { FRAC_CONST(0.026029938255941), FRAC_CONST(0.017291755676967) }, { FRAC_CONST(0.025976765395322), FRAC_CONST(0.017371533023784) }, { FRAC_CONST(0.025923348031494), FRAC_CONST(0.017451146863116) }, { FRAC_CONST(0.025869686667242), FRAC_CONST(0.017530596445607) }, { FRAC_CONST(0.025815781807646), FRAC_CONST(0.017609881023449) }, { FRAC_CONST(0.025761633960080), FRAC_CONST(0.017688999850383) }, { FRAC_CONST(0.025707243634204), FRAC_CONST(0.017767952181715) }, { FRAC_CONST(0.025652611341960), FRAC_CONST(0.017846737274313) }, { FRAC_CONST(0.025597737597568), FRAC_CONST(0.017925354386623) }, { FRAC_CONST(0.025542622917522), FRAC_CONST(0.018003802778671) }, { FRAC_CONST(0.025487267820581), FRAC_CONST(0.018082081712071) }, { FRAC_CONST(0.025431672827768), FRAC_CONST(0.018160190450031) }, { FRAC_CONST(0.025375838462365), FRAC_CONST(0.018238128257362) }, { FRAC_CONST(0.025319765249906), FRAC_CONST(0.018315894400484) }, { FRAC_CONST(0.025263453718173), FRAC_CONST(0.018393488147432) }, { FRAC_CONST(0.025206904397193), FRAC_CONST(0.018470908767865) }, { FRAC_CONST(0.025150117819228), FRAC_CONST(0.018548155533070) }, { FRAC_CONST(0.025093094518776), FRAC_CONST(0.018625227715971) }, { FRAC_CONST(0.025035835032562), FRAC_CONST(0.018702124591135) }, { FRAC_CONST(0.024978339899534), FRAC_CONST(0.018778845434780) }, { FRAC_CONST(0.024920609660858), FRAC_CONST(0.018855389524780) }, { FRAC_CONST(0.024862644859912), FRAC_CONST(0.018931756140672) }, { FRAC_CONST(0.024804446042284), FRAC_CONST(0.019007944563666) }, { FRAC_CONST(0.024746013755764), FRAC_CONST(0.019083954076646) }, { FRAC_CONST(0.024687348550337), FRAC_CONST(0.019159783964183) }, { FRAC_CONST(0.024628450978184), FRAC_CONST(0.019235433512536) }, { FRAC_CONST(0.024569321593670), FRAC_CONST(0.019310902009663) }, { FRAC_CONST(0.024509960953345), FRAC_CONST(0.019386188745225) }, { FRAC_CONST(0.024450369615932), FRAC_CONST(0.019461293010596) }, { FRAC_CONST(0.024390548142329), FRAC_CONST(0.019536214098866) }, { FRAC_CONST(0.024330497095598), FRAC_CONST(0.019610951304848) }, { FRAC_CONST(0.024270217040961), FRAC_CONST(0.019685503925087) }, { FRAC_CONST(0.024209708545799), FRAC_CONST(0.019759871257867) }, { FRAC_CONST(0.024148972179639), FRAC_CONST(0.019834052603212) }, { FRAC_CONST(0.024088008514157), FRAC_CONST(0.019908047262901) }, { FRAC_CONST(0.024026818123164), FRAC_CONST(0.019981854540467) }, { FRAC_CONST(0.023965401582609), FRAC_CONST(0.020055473741208) }, { FRAC_CONST(0.023903759470567), FRAC_CONST(0.020128904172192) }, { FRAC_CONST(0.023841892367236), FRAC_CONST(0.020202145142264) }, { FRAC_CONST(0.023779800854935), FRAC_CONST(0.020275195962052) }, { FRAC_CONST(0.023717485518092), FRAC_CONST(0.020348055943974) }, { FRAC_CONST(0.023654946943242), FRAC_CONST(0.020420724402244) }, { FRAC_CONST(0.023592185719023), FRAC_CONST(0.020493200652878) }, { FRAC_CONST(0.023529202436167), FRAC_CONST(0.020565484013703) }, { FRAC_CONST(0.023465997687496), FRAC_CONST(0.020637573804361) }, { FRAC_CONST(0.023402572067918), FRAC_CONST(0.020709469346314) }, { FRAC_CONST(0.023338926174419), FRAC_CONST(0.020781169962854) }, { FRAC_CONST(0.023275060606058), FRAC_CONST(0.020852674979108) }, { FRAC_CONST(0.023210975963963), FRAC_CONST(0.020923983722044) }, { FRAC_CONST(0.023146672851322), FRAC_CONST(0.020995095520475) }, { FRAC_CONST(0.023082151873380), FRAC_CONST(0.021066009705072) }, { FRAC_CONST(0.023017413637435), FRAC_CONST(0.021136725608363) }, { FRAC_CONST(0.022952458752826), FRAC_CONST(0.021207242564742) }, { FRAC_CONST(0.022887287830934), FRAC_CONST(0.021277559910478) }, { FRAC_CONST(0.022821901485173), FRAC_CONST(0.021347676983716) }, { FRAC_CONST(0.022756300330983), FRAC_CONST(0.021417593124488) }, { FRAC_CONST(0.022690484985827), FRAC_CONST(0.021487307674717) }, { FRAC_CONST(0.022624456069185), FRAC_CONST(0.021556819978223) }, { FRAC_CONST(0.022558214202547), FRAC_CONST(0.021626129380729) }, { FRAC_CONST(0.022491760009405), FRAC_CONST(0.021695235229869) }, { FRAC_CONST(0.022425094115252), FRAC_CONST(0.021764136875192) }, { FRAC_CONST(0.022358217147572), FRAC_CONST(0.021832833668171) }, { FRAC_CONST(0.022291129735838), FRAC_CONST(0.021901324962204) }, { FRAC_CONST(0.022223832511501), FRAC_CONST(0.021969610112625) }, { FRAC_CONST(0.022156326107988), FRAC_CONST(0.022037688476709) }, { FRAC_CONST(0.022088611160696), FRAC_CONST(0.022105559413676) }, { FRAC_CONST(0.022020688306983), FRAC_CONST(0.022173222284699) }, { FRAC_CONST(0.021952558186166), FRAC_CONST(0.022240676452909) }, { FRAC_CONST(0.021884221439510), FRAC_CONST(0.022307921283403) }, { FRAC_CONST(0.021815678710228), FRAC_CONST(0.022374956143245) }, { FRAC_CONST(0.021746930643469), FRAC_CONST(0.022441780401478) }, { FRAC_CONST(0.021677977886316), FRAC_CONST(0.022508393429127) }, { FRAC_CONST(0.021608821087780), FRAC_CONST(0.022574794599206) }, { FRAC_CONST(0.021539460898790), FRAC_CONST(0.022640983286719) }, { FRAC_CONST(0.021469897972190), FRAC_CONST(0.022706958868676) }, { FRAC_CONST(0.021400132962735), FRAC_CONST(0.022772720724087) }, { FRAC_CONST(0.021330166527077), FRAC_CONST(0.022838268233979) }, { FRAC_CONST(0.021259999323769), FRAC_CONST(0.022903600781391) }, { FRAC_CONST(0.021189632013250), FRAC_CONST(0.022968717751391) }, { FRAC_CONST(0.021119065257845), FRAC_CONST(0.023033618531071) }, { FRAC_CONST(0.021048299721754), FRAC_CONST(0.023098302509561) }, { FRAC_CONST(0.020977336071050), FRAC_CONST(0.023162769078031) }, { FRAC_CONST(0.020906174973670), FRAC_CONST(0.023227017629698) }, { FRAC_CONST(0.020834817099409), FRAC_CONST(0.023291047559828) }, { FRAC_CONST(0.020763263119915), FRAC_CONST(0.023354858265748) }, { FRAC_CONST(0.020691513708680), FRAC_CONST(0.023418449146848) }, { FRAC_CONST(0.020619569541038), FRAC_CONST(0.023481819604585) }, { FRAC_CONST(0.020547431294155), FRAC_CONST(0.023544969042494) }, { FRAC_CONST(0.020475099647023), FRAC_CONST(0.023607896866186) }, { FRAC_CONST(0.020402575280455), FRAC_CONST(0.023670602483363) }, { FRAC_CONST(0.020329858877078), FRAC_CONST(0.023733085303813) }, { FRAC_CONST(0.020256951121327), FRAC_CONST(0.023795344739427) }, { FRAC_CONST(0.020183852699437), FRAC_CONST(0.023857380204193) }, { FRAC_CONST(0.020110564299439), FRAC_CONST(0.023919191114211) }, { FRAC_CONST(0.020037086611150), FRAC_CONST(0.023980776887692) }, { FRAC_CONST(0.019963420326171), FRAC_CONST(0.024042136944968) }, { FRAC_CONST(0.019889566137877), FRAC_CONST(0.024103270708495) }, { FRAC_CONST(0.019815524741412), FRAC_CONST(0.024164177602859) }, { FRAC_CONST(0.019741296833681), FRAC_CONST(0.024224857054779) }, { FRAC_CONST(0.019666883113346), FRAC_CONST(0.024285308493120) }, { FRAC_CONST(0.019592284280817), FRAC_CONST(0.024345531348888) }, { FRAC_CONST(0.019517501038246), FRAC_CONST(0.024405525055242) }, { FRAC_CONST(0.019442534089523), FRAC_CONST(0.024465289047500) }, { FRAC_CONST(0.019367384140264), FRAC_CONST(0.024524822763141) }, { FRAC_CONST(0.019292051897809), FRAC_CONST(0.024584125641809) }, { FRAC_CONST(0.019216538071215), FRAC_CONST(0.024643197125323) }, { FRAC_CONST(0.019140843371246), FRAC_CONST(0.024702036657681) }, { FRAC_CONST(0.019064968510369), FRAC_CONST(0.024760643685063) }, { FRAC_CONST(0.018988914202748), FRAC_CONST(0.024819017655836) }, { FRAC_CONST(0.018912681164234), FRAC_CONST(0.024877158020562) }, { FRAC_CONST(0.018836270112363), FRAC_CONST(0.024935064232003) }, { FRAC_CONST(0.018759681766343), FRAC_CONST(0.024992735745123) }, { FRAC_CONST(0.018682916847054), FRAC_CONST(0.025050172017095) }, { FRAC_CONST(0.018605976077037), FRAC_CONST(0.025107372507308) }, { FRAC_CONST(0.018528860180486), FRAC_CONST(0.025164336677369) }, { FRAC_CONST(0.018451569883247), FRAC_CONST(0.025221063991110) }, { FRAC_CONST(0.018374105912805), FRAC_CONST(0.025277553914591) }, { FRAC_CONST(0.018296468998280), FRAC_CONST(0.025333805916107) }, { FRAC_CONST(0.018218659870421), FRAC_CONST(0.025389819466194) }, { FRAC_CONST(0.018140679261596), FRAC_CONST(0.025445594037630) }, { FRAC_CONST(0.018062527905790), FRAC_CONST(0.025501129105445) }, { FRAC_CONST(0.017984206538592), FRAC_CONST(0.025556424146920) }, { FRAC_CONST(0.017905715897192), FRAC_CONST(0.025611478641598) }, { FRAC_CONST(0.017827056720375), FRAC_CONST(0.025666292071285) }, { FRAC_CONST(0.017748229748511), FRAC_CONST(0.025720863920056) }, { FRAC_CONST(0.017669235723550), FRAC_CONST(0.025775193674260) }, { FRAC_CONST(0.017590075389012), FRAC_CONST(0.025829280822525) }, { FRAC_CONST(0.017510749489986), FRAC_CONST(0.025883124855762) }, { FRAC_CONST(0.017431258773116), FRAC_CONST(0.025936725267170) }, { FRAC_CONST(0.017351603986600), FRAC_CONST(0.025990081552242) }, { FRAC_CONST(0.017271785880180), FRAC_CONST(0.026043193208768) }, { FRAC_CONST(0.017191805205132), FRAC_CONST(0.026096059736841) }, { FRAC_CONST(0.017111662714267), FRAC_CONST(0.026148680638861) }, { FRAC_CONST(0.017031359161915), FRAC_CONST(0.026201055419541) }, { FRAC_CONST(0.016950895303924), FRAC_CONST(0.026253183585908) }, { FRAC_CONST(0.016870271897651), FRAC_CONST(0.026305064647313) }, { FRAC_CONST(0.016789489701954), FRAC_CONST(0.026356698115431) }, { FRAC_CONST(0.016708549477186), FRAC_CONST(0.026408083504269) }, { FRAC_CONST(0.016627451985187), FRAC_CONST(0.026459220330167) }, { FRAC_CONST(0.016546197989277), FRAC_CONST(0.026510108111806) }, { FRAC_CONST(0.016464788254250), FRAC_CONST(0.026560746370212) }, { FRAC_CONST(0.016383223546365), FRAC_CONST(0.026611134628757) }, { FRAC_CONST(0.016301504633341), FRAC_CONST(0.026661272413168) }, { FRAC_CONST(0.016219632284346), FRAC_CONST(0.026711159251530) }, { FRAC_CONST(0.016137607269996), FRAC_CONST(0.026760794674288) }, { FRAC_CONST(0.016055430362340), FRAC_CONST(0.026810178214254) }, { FRAC_CONST(0.015973102334858), FRAC_CONST(0.026859309406613) }, { FRAC_CONST(0.015890623962454), FRAC_CONST(0.026908187788922) }, { FRAC_CONST(0.015807996021446), FRAC_CONST(0.026956812901119) }, { FRAC_CONST(0.015725219289558), FRAC_CONST(0.027005184285527) }, { FRAC_CONST(0.015642294545918), FRAC_CONST(0.027053301486856) }, { FRAC_CONST(0.015559222571044), FRAC_CONST(0.027101164052208) }, { FRAC_CONST(0.015476004146842), FRAC_CONST(0.027148771531083) }, { FRAC_CONST(0.015392640056594), FRAC_CONST(0.027196123475380) }, { FRAC_CONST(0.015309131084956), FRAC_CONST(0.027243219439406) }, { FRAC_CONST(0.015225478017946), FRAC_CONST(0.027290058979875) }, { FRAC_CONST(0.015141681642938), FRAC_CONST(0.027336641655915) }, { FRAC_CONST(0.015057742748656), FRAC_CONST(0.027382967029073) }, { FRAC_CONST(0.014973662125164), FRAC_CONST(0.027429034663317) }, { FRAC_CONST(0.014889440563862), FRAC_CONST(0.027474844125040) }, { FRAC_CONST(0.014805078857474), FRAC_CONST(0.027520394983066) }, { FRAC_CONST(0.014720577800046), FRAC_CONST(0.027565686808654) }, { FRAC_CONST(0.014635938186934), FRAC_CONST(0.027610719175499) }, { FRAC_CONST(0.014551160814797), FRAC_CONST(0.027655491659740) }, { FRAC_CONST(0.014466246481592), FRAC_CONST(0.027700003839960) }, { FRAC_CONST(0.014381195986567), FRAC_CONST(0.027744255297195) }, { FRAC_CONST(0.014296010130247), FRAC_CONST(0.027788245614933) }, { FRAC_CONST(0.014210689714436), FRAC_CONST(0.027831974379120) }, { FRAC_CONST(0.014125235542201), FRAC_CONST(0.027875441178165) }, { FRAC_CONST(0.014039648417870), FRAC_CONST(0.027918645602941) }, { FRAC_CONST(0.013953929147020), FRAC_CONST(0.027961587246792) }, { FRAC_CONST(0.013868078536476), FRAC_CONST(0.028004265705534) }, { FRAC_CONST(0.013782097394294), FRAC_CONST(0.028046680577462) }, { FRAC_CONST(0.013695986529763), FRAC_CONST(0.028088831463351) }, { FRAC_CONST(0.013609746753390), FRAC_CONST(0.028130717966461) }, { FRAC_CONST(0.013523378876898), FRAC_CONST(0.028172339692540) }, { FRAC_CONST(0.013436883713214), FRAC_CONST(0.028213696249828) }, { FRAC_CONST(0.013350262076462), FRAC_CONST(0.028254787249062) }, { FRAC_CONST(0.013263514781960), FRAC_CONST(0.028295612303478) }, { FRAC_CONST(0.013176642646205), FRAC_CONST(0.028336171028814) }, { FRAC_CONST(0.013089646486871), FRAC_CONST(0.028376463043317) }, { FRAC_CONST(0.013002527122799), FRAC_CONST(0.028416487967743) }, { FRAC_CONST(0.012915285373990), FRAC_CONST(0.028456245425361) }, { FRAC_CONST(0.012827922061597), FRAC_CONST(0.028495735041960) }, { FRAC_CONST(0.012740438007915), FRAC_CONST(0.028534956445849) }, { FRAC_CONST(0.012652834036379), FRAC_CONST(0.028573909267859) }, { FRAC_CONST(0.012565110971550), FRAC_CONST(0.028612593141354) }, { FRAC_CONST(0.012477269639111), FRAC_CONST(0.028651007702224) }, { FRAC_CONST(0.012389310865858), FRAC_CONST(0.028689152588899) }, { FRAC_CONST(0.012301235479693), FRAC_CONST(0.028727027442343) }, { FRAC_CONST(0.012213044309615), FRAC_CONST(0.028764631906065) }, { FRAC_CONST(0.012124738185712), FRAC_CONST(0.028801965626115) }, { FRAC_CONST(0.012036317939156), FRAC_CONST(0.028839028251097) }, { FRAC_CONST(0.011947784402191), FRAC_CONST(0.028875819432161) }, { FRAC_CONST(0.011859138408130), FRAC_CONST(0.028912338823015) }, { FRAC_CONST(0.011770380791341), FRAC_CONST(0.028948586079925) }, { FRAC_CONST(0.011681512387245), FRAC_CONST(0.028984560861718) }, { FRAC_CONST(0.011592534032306), FRAC_CONST(0.029020262829785) }, { FRAC_CONST(0.011503446564022), FRAC_CONST(0.029055691648087) }, { FRAC_CONST(0.011414250820918), FRAC_CONST(0.029090846983152) }, { FRAC_CONST(0.011324947642537), FRAC_CONST(0.029125728504087) }, { FRAC_CONST(0.011235537869437), FRAC_CONST(0.029160335882573) }, { FRAC_CONST(0.011146022343175), FRAC_CONST(0.029194668792871) }, { FRAC_CONST(0.011056401906305), FRAC_CONST(0.029228726911828) }, { FRAC_CONST(0.010966677402371), FRAC_CONST(0.029262509918876) }, { FRAC_CONST(0.010876849675891), FRAC_CONST(0.029296017496036) }, { FRAC_CONST(0.010786919572361), FRAC_CONST(0.029329249327922) }, { FRAC_CONST(0.010696887938235), FRAC_CONST(0.029362205101743) }, { FRAC_CONST(0.010606755620926), FRAC_CONST(0.029394884507308) }, { FRAC_CONST(0.010516523468793), FRAC_CONST(0.029427287237024) }, { FRAC_CONST(0.010426192331137), FRAC_CONST(0.029459412985906) }, { FRAC_CONST(0.010335763058187), FRAC_CONST(0.029491261451573) }, { FRAC_CONST(0.010245236501099), FRAC_CONST(0.029522832334255) }, { FRAC_CONST(0.010154613511943), FRAC_CONST(0.029554125336796) }, { FRAC_CONST(0.010063894943698), FRAC_CONST(0.029585140164654) }, { FRAC_CONST(0.009973081650240), FRAC_CONST(0.029615876525905) }, { FRAC_CONST(0.009882174486340), FRAC_CONST(0.029646334131247) }, { FRAC_CONST(0.009791174307650), FRAC_CONST(0.029676512694001) }, { FRAC_CONST(0.009700081970699), FRAC_CONST(0.029706411930116) }, { FRAC_CONST(0.009608898332881), FRAC_CONST(0.029736031558168) }, { FRAC_CONST(0.009517624252453), FRAC_CONST(0.029765371299366) }, { FRAC_CONST(0.009426260588521), FRAC_CONST(0.029794430877553) }, { FRAC_CONST(0.009334808201034), FRAC_CONST(0.029823210019210) }, { FRAC_CONST(0.009243267950778), FRAC_CONST(0.029851708453456) }, { FRAC_CONST(0.009151640699363), FRAC_CONST(0.029879925912053) }, { FRAC_CONST(0.009059927309220), FRAC_CONST(0.029907862129408) }, { FRAC_CONST(0.008968128643591), FRAC_CONST(0.029935516842573) }, { FRAC_CONST(0.008876245566520), FRAC_CONST(0.029962889791254) }, { FRAC_CONST(0.008784278942845), FRAC_CONST(0.029989980717805) }, { FRAC_CONST(0.008692229638191), FRAC_CONST(0.030016789367235) }, { FRAC_CONST(0.008600098518961), FRAC_CONST(0.030043315487212) }, { FRAC_CONST(0.008507886452329), FRAC_CONST(0.030069558828062) }, { FRAC_CONST(0.008415594306230), FRAC_CONST(0.030095519142772) }, { FRAC_CONST(0.008323222949351), FRAC_CONST(0.030121196186994) }, { FRAC_CONST(0.008230773251129), FRAC_CONST(0.030146589719046) }, { FRAC_CONST(0.008138246081733), FRAC_CONST(0.030171699499915) }, { FRAC_CONST(0.008045642312067), FRAC_CONST(0.030196525293257) }, { FRAC_CONST(0.007952962813750), FRAC_CONST(0.030221066865402) }, { FRAC_CONST(0.007860208459119), FRAC_CONST(0.030245323985357) }, { FRAC_CONST(0.007767380121212), FRAC_CONST(0.030269296424803) }, { FRAC_CONST(0.007674478673766), FRAC_CONST(0.030292983958103) }, { FRAC_CONST(0.007581504991203), FRAC_CONST(0.030316386362302) }, { FRAC_CONST(0.007488459948628), FRAC_CONST(0.030339503417126) }, { FRAC_CONST(0.007395344421816), FRAC_CONST(0.030362334904989) }, { FRAC_CONST(0.007302159287206), FRAC_CONST(0.030384880610993) }, { FRAC_CONST(0.007208905421891), FRAC_CONST(0.030407140322928) }, { FRAC_CONST(0.007115583703613), FRAC_CONST(0.030429113831278) }, { FRAC_CONST(0.007022195010752), FRAC_CONST(0.030450800929220) }, { FRAC_CONST(0.006928740222316), FRAC_CONST(0.030472201412626) }, { FRAC_CONST(0.006835220217939), FRAC_CONST(0.030493315080068) }, { FRAC_CONST(0.006741635877866), FRAC_CONST(0.030514141732814) }, { FRAC_CONST(0.006647988082948), FRAC_CONST(0.030534681174838) }, { FRAC_CONST(0.006554277714635), FRAC_CONST(0.030554933212813) }, { FRAC_CONST(0.006460505654964), FRAC_CONST(0.030574897656119) }, { FRAC_CONST(0.006366672786553), FRAC_CONST(0.030594574316845) }, { FRAC_CONST(0.006272779992593), FRAC_CONST(0.030613963009786) }, { FRAC_CONST(0.006178828156839), FRAC_CONST(0.030633063552447) }, { FRAC_CONST(0.006084818163601), FRAC_CONST(0.030651875765048) }, { FRAC_CONST(0.005990750897737), FRAC_CONST(0.030670399470520) }, { FRAC_CONST(0.005896627244644), FRAC_CONST(0.030688634494512) }, { FRAC_CONST(0.005802448090250), FRAC_CONST(0.030706580665388) }, { FRAC_CONST(0.005708214321004), FRAC_CONST(0.030724237814232) }, { FRAC_CONST(0.005613926823871), FRAC_CONST(0.030741605774849) }, { FRAC_CONST(0.005519586486321), FRAC_CONST(0.030758684383764) }, { FRAC_CONST(0.005425194196321), FRAC_CONST(0.030775473480228) }, { FRAC_CONST(0.005330750842327), FRAC_CONST(0.030791972906214) }, { FRAC_CONST(0.005236257313276), FRAC_CONST(0.030808182506425) }, { FRAC_CONST(0.005141714498576), FRAC_CONST(0.030824102128288) }, { FRAC_CONST(0.005047123288102), FRAC_CONST(0.030839731621963) }, { FRAC_CONST(0.004952484572181), FRAC_CONST(0.030855070840339) }, { FRAC_CONST(0.004857799241589), FRAC_CONST(0.030870119639036) }, { FRAC_CONST(0.004763068187541), FRAC_CONST(0.030884877876411) }, { FRAC_CONST(0.004668292301681), FRAC_CONST(0.030899345413553) }, { FRAC_CONST(0.004573472476075), FRAC_CONST(0.030913522114288) }, { FRAC_CONST(0.004478609603205), FRAC_CONST(0.030927407845180) }, { FRAC_CONST(0.004383704575956), FRAC_CONST(0.030941002475530) }, { FRAC_CONST(0.004288758287610), FRAC_CONST(0.030954305877381) }, { FRAC_CONST(0.004193771631837), FRAC_CONST(0.030967317925516) }, { FRAC_CONST(0.004098745502689), FRAC_CONST(0.030980038497461) }, { FRAC_CONST(0.004003680794587), FRAC_CONST(0.030992467473486) }, { FRAC_CONST(0.003908578402316), FRAC_CONST(0.031004604736602) }, { FRAC_CONST(0.003813439221017), FRAC_CONST(0.031016450172571) }, { FRAC_CONST(0.003718264146176), FRAC_CONST(0.031028003669899) }, { FRAC_CONST(0.003623054073616), FRAC_CONST(0.031039265119839) }, { FRAC_CONST(0.003527809899492), FRAC_CONST(0.031050234416394) }, { FRAC_CONST(0.003432532520278), FRAC_CONST(0.031060911456318) }, { FRAC_CONST(0.003337222832760), FRAC_CONST(0.031071296139114) }, { FRAC_CONST(0.003241881734029), FRAC_CONST(0.031081388367037) }, { FRAC_CONST(0.003146510121474), FRAC_CONST(0.031091188045095) }, { FRAC_CONST(0.003051108892766), FRAC_CONST(0.031100695081051) }, { FRAC_CONST(0.002955678945860), FRAC_CONST(0.031109909385419) }, { FRAC_CONST(0.002860221178978), FRAC_CONST(0.031118830871473) }, { FRAC_CONST(0.002764736490604), FRAC_CONST(0.031127459455239) }, { FRAC_CONST(0.002669225779478), FRAC_CONST(0.031135795055501) }, { FRAC_CONST(0.002573689944583), FRAC_CONST(0.031143837593803) }, { FRAC_CONST(0.002478129885137), FRAC_CONST(0.031151586994444) }, { FRAC_CONST(0.002382546500589), FRAC_CONST(0.031159043184484) }, { FRAC_CONST(0.002286940690606), FRAC_CONST(0.031166206093743) }, { FRAC_CONST(0.002191313355067), FRAC_CONST(0.031173075654800) }, { FRAC_CONST(0.002095665394051), FRAC_CONST(0.031179651802998) }, { FRAC_CONST(0.001999997707835), FRAC_CONST(0.031185934476438) }, { FRAC_CONST(0.001904311196878), FRAC_CONST(0.031191923615985) }, { FRAC_CONST(0.001808606761820), FRAC_CONST(0.031197619165268) }, { FRAC_CONST(0.001712885303465), FRAC_CONST(0.031203021070678) }, { FRAC_CONST(0.001617147722782), FRAC_CONST(0.031208129281370) }, { FRAC_CONST(0.001521394920889), FRAC_CONST(0.031212943749264) }, { FRAC_CONST(0.001425627799047), FRAC_CONST(0.031217464429043) }, { FRAC_CONST(0.001329847258653), FRAC_CONST(0.031221691278159) }, { FRAC_CONST(0.001234054201231), FRAC_CONST(0.031225624256825) }, { FRAC_CONST(0.001138249528420), FRAC_CONST(0.031229263328024) }, { FRAC_CONST(0.001042434141971), FRAC_CONST(0.031232608457502) }, { FRAC_CONST(0.000946608943736), FRAC_CONST(0.031235659613775) }, { FRAC_CONST(0.000850774835656), FRAC_CONST(0.031238416768124) }, { FRAC_CONST(0.000754932719759), FRAC_CONST(0.031240879894597) }, { FRAC_CONST(0.000659083498149), FRAC_CONST(0.031243048970010) }, { FRAC_CONST(0.000563228072993), FRAC_CONST(0.031244923973948) }, { FRAC_CONST(0.000467367346520), FRAC_CONST(0.031246504888762) }, { FRAC_CONST(0.000371502221008), FRAC_CONST(0.031247791699571) }, { FRAC_CONST(0.000275633598775), FRAC_CONST(0.031248784394264) }, { FRAC_CONST(0.000179762382174), FRAC_CONST(0.031249482963498) }, { FRAC_CONST(0.000083889473581), FRAC_CONST(0.031249887400697) } }; /* 64 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_256[] = { { FRAC_CONST(0.088387931675923), FRAC_CONST(0.000271171628935) }, { FRAC_CONST(0.088354655998507), FRAC_CONST(0.002440238387037) }, { FRAC_CONST(0.088268158780110), FRAC_CONST(0.004607835236780) }, { FRAC_CONST(0.088128492123423), FRAC_CONST(0.006772656498875) }, { FRAC_CONST(0.087935740158418), FRAC_CONST(0.008933398165942) }, { FRAC_CONST(0.087690018991670), FRAC_CONST(0.011088758687994) }, { FRAC_CONST(0.087391476636423), FRAC_CONST(0.013237439756448) }, { FRAC_CONST(0.087040292923427), FRAC_CONST(0.015378147086172) }, { FRAC_CONST(0.086636679392621), FRAC_CONST(0.017509591195118) }, { FRAC_CONST(0.086180879165703), FRAC_CONST(0.019630488181053) }, { FRAC_CONST(0.085673166799686), FRAC_CONST(0.021739560494940) }, { FRAC_CONST(0.085113848121515), FRAC_CONST(0.023835537710479) }, { FRAC_CONST(0.084503260043847), FRAC_CONST(0.025917157289369) }, { FRAC_CONST(0.083841770362110), FRAC_CONST(0.027983165341813) }, { FRAC_CONST(0.083129777532952), FRAC_CONST(0.030032317381813) }, { FRAC_CONST(0.082367710434230), FRAC_CONST(0.032063379076803) }, { FRAC_CONST(0.081556028106671), FRAC_CONST(0.034075126991164) }, { FRAC_CONST(0.080695219477356), FRAC_CONST(0.036066349323177) }, { FRAC_CONST(0.079785803065216), FRAC_CONST(0.038035846634965) }, { FRAC_CONST(0.078828326668693), FRAC_CONST(0.039982432574992) }, { FRAC_CONST(0.077823367035766), FRAC_CONST(0.041904934592675) }, { FRAC_CONST(0.076771529516540), FRAC_CONST(0.043802194644686) }, { FRAC_CONST(0.075673447698606), FRAC_CONST(0.045673069892513) }, { FRAC_CONST(0.074529783025390), FRAC_CONST(0.047516433390863) }, { FRAC_CONST(0.073341224397728), FRAC_CONST(0.049331174766491) }, { FRAC_CONST(0.072108487758894), FRAC_CONST(0.051116200887052) }, { FRAC_CONST(0.070832315663343), FRAC_CONST(0.052870436519557) }, { FRAC_CONST(0.069513476829429), FRAC_CONST(0.054592824978055) }, { FRAC_CONST(0.068152765676348), FRAC_CONST(0.056282328760143) }, { FRAC_CONST(0.066751001845620), FRAC_CONST(0.057937930171918) }, { FRAC_CONST(0.065309029707361), FRAC_CONST(0.059558631940996) }, { FRAC_CONST(0.063827717851668), FRAC_CONST(0.061143457817234) }, { FRAC_CONST(0.062307958565413), FRAC_CONST(0.062691453160784) }, { FRAC_CONST(0.060750667294763), FRAC_CONST(0.064201685517134) }, { FRAC_CONST(0.059156782093749), FRAC_CONST(0.065673245178784) }, { FRAC_CONST(0.057527263059216), FRAC_CONST(0.067105245733220) }, { FRAC_CONST(0.055863091752499), FRAC_CONST(0.068496824596852) }, { FRAC_CONST(0.054165270608165), FRAC_CONST(0.069847143534609) }, { FRAC_CONST(0.052434822330188), FRAC_CONST(0.071155389164853) }, { FRAC_CONST(0.050672789275903), FRAC_CONST(0.072420773449336) }, { FRAC_CONST(0.048880232828135), FRAC_CONST(0.073642534167879) }, { FRAC_CONST(0.047058232755862), FRAC_CONST(0.074819935377512) }, { FRAC_CONST(0.045207886563797), FRAC_CONST(0.075952267855771) }, { FRAC_CONST(0.043330308831298), FRAC_CONST(0.077038849527912) }, { FRAC_CONST(0.041426630540984), FRAC_CONST(0.078079025877766) }, { FRAC_CONST(0.039497998397473), FRAC_CONST(0.079072170341994) }, { FRAC_CONST(0.037545574136653), FRAC_CONST(0.080017684687506) }, { FRAC_CONST(0.035570533825892), FRAC_CONST(0.080914999371817) }, { FRAC_CONST(0.033574067155622), FRAC_CONST(0.081763573886112) }, { FRAC_CONST(0.031557376722714), FRAC_CONST(0.082562897080836) }, { FRAC_CONST(0.029521677306074), FRAC_CONST(0.083312487473584) }, { FRAC_CONST(0.027468195134911), FRAC_CONST(0.084011893539132) }, { FRAC_CONST(0.025398167150101), FRAC_CONST(0.084660693981419) }, { FRAC_CONST(0.023312840259098), FRAC_CONST(0.085258497987320) }, { FRAC_CONST(0.021213470584847), FRAC_CONST(0.085804945462053) }, { FRAC_CONST(0.019101322709138), FRAC_CONST(0.086299707246093) }, { FRAC_CONST(0.016977668910873), FRAC_CONST(0.086742485313442) }, { FRAC_CONST(0.014843788399692), FRAC_CONST(0.087133012951149) }, { FRAC_CONST(0.012700966545425), FRAC_CONST(0.087471054919968) }, { FRAC_CONST(0.010550494103830), FRAC_CONST(0.087756407596056) }, { FRAC_CONST(0.008393666439096), FRAC_CONST(0.087988899093631) }, { FRAC_CONST(0.006231782743558), FRAC_CONST(0.088168389368510) }, { FRAC_CONST(0.004066145255116), FRAC_CONST(0.088294770302461) }, { FRAC_CONST(0.001898058472816), FRAC_CONST(0.088367965768336) } }; #ifdef LD_DEC /* 128 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_1024[] = { { FRAC_CONST(0.044194160825012), FRAC_CONST(0.000033896503468) }, { FRAC_CONST(0.044193120897389), FRAC_CONST(0.000305066138364) }, { FRAC_CONST(0.044190417123742), FRAC_CONST(0.000576224287693) }, { FRAC_CONST(0.044186049605866), FRAC_CONST(0.000847360742503) }, { FRAC_CONST(0.044180018508197), FRAC_CONST(0.001118465294660) }, { FRAC_CONST(0.044172324057802), FRAC_CONST(0.001389527737231) }, { FRAC_CONST(0.044162966544372), FRAC_CONST(0.001660537864867) }, { FRAC_CONST(0.044151946320213), FRAC_CONST(0.001931485474192) }, { FRAC_CONST(0.044139263800230), FRAC_CONST(0.002202360364180) }, { FRAC_CONST(0.044124919461912), FRAC_CONST(0.002473152336546) }, { FRAC_CONST(0.044108913845316), FRAC_CONST(0.002743851196123) }, { FRAC_CONST(0.044091247553044), FRAC_CONST(0.003014446751254) }, { FRAC_CONST(0.044071921250223), FRAC_CONST(0.003284928814169) }, { FRAC_CONST(0.044050935664476), FRAC_CONST(0.003555287201370) }, { FRAC_CONST(0.044028291585898), FRAC_CONST(0.003825511734018) }, { FRAC_CONST(0.044003989867028), FRAC_CONST(0.004095592238311) }, { FRAC_CONST(0.043978031422810), FRAC_CONST(0.004365518545871) }, { FRAC_CONST(0.043950417230565), FRAC_CONST(0.004635280494126) }, { FRAC_CONST(0.043921148329953), FRAC_CONST(0.004904867926689) }, { FRAC_CONST(0.043890225822930), FRAC_CONST(0.005174270693748) }, { FRAC_CONST(0.043857650873712), FRAC_CONST(0.005443478652439) }, { FRAC_CONST(0.043823424708727), FRAC_CONST(0.005712481667236) }, { FRAC_CONST(0.043787548616571), FRAC_CONST(0.005981269610326) }, { FRAC_CONST(0.043750023947958), FRAC_CONST(0.006249832361997) }, { FRAC_CONST(0.043710852115672), FRAC_CONST(0.006518159811011) }, { FRAC_CONST(0.043670034594508), FRAC_CONST(0.006786241854993) }, { FRAC_CONST(0.043627572921225), FRAC_CONST(0.007054068400804) }, { FRAC_CONST(0.043583468694479), FRAC_CONST(0.007321629364927) }, { FRAC_CONST(0.043537723574771), FRAC_CONST(0.007588914673843) }, { FRAC_CONST(0.043490339284377), FRAC_CONST(0.007855914264410) }, { FRAC_CONST(0.043441317607290), FRAC_CONST(0.008122618084246) }, { FRAC_CONST(0.043390660389149), FRAC_CONST(0.008389016092101) }, { FRAC_CONST(0.043338369537168), FRAC_CONST(0.008655098258243) }, { FRAC_CONST(0.043284447020070), FRAC_CONST(0.008920854564826) }, { FRAC_CONST(0.043228894868005), FRAC_CONST(0.009186275006278) }, { FRAC_CONST(0.043171715172482), FRAC_CONST(0.009451349589667) }, { FRAC_CONST(0.043112910086283), FRAC_CONST(0.009716068335087) }, { FRAC_CONST(0.043052481823387), FRAC_CONST(0.009980421276025) }, { FRAC_CONST(0.042990432658884), FRAC_CONST(0.010244398459743) }, { FRAC_CONST(0.042926764928889), FRAC_CONST(0.010507989947649) }, { FRAC_CONST(0.042861481030457), FRAC_CONST(0.010771185815673) }, { FRAC_CONST(0.042794583421490), FRAC_CONST(0.011033976154639) }, { FRAC_CONST(0.042726074620644), FRAC_CONST(0.011296351070639) }, { FRAC_CONST(0.042655957207238), FRAC_CONST(0.011558300685406) }, { FRAC_CONST(0.042584233821153), FRAC_CONST(0.011819815136685) }, { FRAC_CONST(0.042510907162732), FRAC_CONST(0.012080884578604) }, { FRAC_CONST(0.042435979992684), FRAC_CONST(0.012341499182048) }, { FRAC_CONST(0.042359455131975), FRAC_CONST(0.012601649135022) }, { FRAC_CONST(0.042281335461721), FRAC_CONST(0.012861324643029) }, { FRAC_CONST(0.042201623923085), FRAC_CONST(0.013120515929433) }, { FRAC_CONST(0.042120323517160), FRAC_CONST(0.013379213235827) }, { FRAC_CONST(0.042037437304862), FRAC_CONST(0.013637406822406) }, { FRAC_CONST(0.041952968406809), FRAC_CONST(0.013895086968325) }, { FRAC_CONST(0.041866920003207), FRAC_CONST(0.014152243972073) }, { FRAC_CONST(0.041779295333730), FRAC_CONST(0.014408868151835) }, { FRAC_CONST(0.041690097697398), FRAC_CONST(0.014664949845855) }, { FRAC_CONST(0.041599330452450), FRAC_CONST(0.014920479412801) }, { FRAC_CONST(0.041506997016224), FRAC_CONST(0.015175447232131) }, { FRAC_CONST(0.041413100865019), FRAC_CONST(0.015429843704450) }, { FRAC_CONST(0.041317645533974), FRAC_CONST(0.015683659251874) }, { FRAC_CONST(0.041220634616927), FRAC_CONST(0.015936884318392) }, { FRAC_CONST(0.041122071766285), FRAC_CONST(0.016189509370223) }, { FRAC_CONST(0.041021960692883), FRAC_CONST(0.016441524896177) }, { FRAC_CONST(0.040920305165846), FRAC_CONST(0.016692921408010) }, { FRAC_CONST(0.040817109012449), FRAC_CONST(0.016943689440788) }, { FRAC_CONST(0.040712376117967), FRAC_CONST(0.017193819553235) }, { FRAC_CONST(0.040606110425535), FRAC_CONST(0.017443302328094) }, { FRAC_CONST(0.040498315935996), FRAC_CONST(0.017692128372479) }, { FRAC_CONST(0.040388996707752), FRAC_CONST(0.017940288318230) }, { FRAC_CONST(0.040278156856609), FRAC_CONST(0.018187772822267) }, { FRAC_CONST(0.040165800555627), FRAC_CONST(0.018434572566936) }, { FRAC_CONST(0.040051932034955), FRAC_CONST(0.018680678260367) }, { FRAC_CONST(0.039936555581679), FRAC_CONST(0.018926080636820) }, { FRAC_CONST(0.039819675539659), FRAC_CONST(0.019170770457035) }, { FRAC_CONST(0.039701296309360), FRAC_CONST(0.019414738508577) }, { FRAC_CONST(0.039581422347694), FRAC_CONST(0.019657975606187) }, { FRAC_CONST(0.039460058167849), FRAC_CONST(0.019900472592126) }, { FRAC_CONST(0.039337208339116), FRAC_CONST(0.020142220336521) }, { FRAC_CONST(0.039212877486723), FRAC_CONST(0.020383209737704) }, { FRAC_CONST(0.039087070291656), FRAC_CONST(0.020623431722561) }, { FRAC_CONST(0.038959791490485), FRAC_CONST(0.020862877246870) }, { FRAC_CONST(0.038831045875184), FRAC_CONST(0.021101537295642) }, { FRAC_CONST(0.038700838292953), FRAC_CONST(0.021339402883462) }, { FRAC_CONST(0.038569173646034), FRAC_CONST(0.021576465054824) }, { FRAC_CONST(0.038436056891527), FRAC_CONST(0.021812714884472) }, { FRAC_CONST(0.038301493041202), FRAC_CONST(0.022048143477734) }, { FRAC_CONST(0.038165487161312), FRAC_CONST(0.022282741970855) }, { FRAC_CONST(0.038028044372402), FRAC_CONST(0.022516501531335) }, { FRAC_CONST(0.037889169849115), FRAC_CONST(0.022749413358259) }, { FRAC_CONST(0.037748868819998), FRAC_CONST(0.022981468682628) }, { FRAC_CONST(0.037607146567305), FRAC_CONST(0.023212658767690) }, { FRAC_CONST(0.037464008426800), FRAC_CONST(0.023442974909269) }, { FRAC_CONST(0.037319459787553), FRAC_CONST(0.023672408436094) }, { FRAC_CONST(0.037173506091737), FRAC_CONST(0.023900950710120) }, { FRAC_CONST(0.037026152834428), FRAC_CONST(0.024128593126861) }, { FRAC_CONST(0.036877405563392), FRAC_CONST(0.024355327115708) }, { FRAC_CONST(0.036727269878879), FRAC_CONST(0.024581144140255) }, { FRAC_CONST(0.036575751433414), FRAC_CONST(0.024806035698618) }, { FRAC_CONST(0.036422855931580), FRAC_CONST(0.025029993323758) }, { FRAC_CONST(0.036268589129807), FRAC_CONST(0.025253008583796) }, { FRAC_CONST(0.036112956836151), FRAC_CONST(0.025475073082334) }, { FRAC_CONST(0.035955964910083), FRAC_CONST(0.025696178458769) }, { FRAC_CONST(0.035797619262257), FRAC_CONST(0.025916316388609) }, { FRAC_CONST(0.035637925854300), FRAC_CONST(0.026135478583784) }, { FRAC_CONST(0.035476890698576), FRAC_CONST(0.026353656792963) }, { FRAC_CONST(0.035314519857970), FRAC_CONST(0.026570842801858) }, { FRAC_CONST(0.035150819445650), FRAC_CONST(0.026787028433540) }, { FRAC_CONST(0.034985795624846), FRAC_CONST(0.027002205548742) }, { FRAC_CONST(0.034819454608610), FRAC_CONST(0.027216366046166) }, { FRAC_CONST(0.034651802659589), FRAC_CONST(0.027429501862792) }, { FRAC_CONST(0.034482846089783), FRAC_CONST(0.027641604974175) }, { FRAC_CONST(0.034312591260311), FRAC_CONST(0.027852667394755) }, { FRAC_CONST(0.034141044581172), FRAC_CONST(0.028062681178149) }, { FRAC_CONST(0.033968212511001), FRAC_CONST(0.028271638417458) }, { FRAC_CONST(0.033794101556828), FRAC_CONST(0.028479531245560) }, { FRAC_CONST(0.033618718273831), FRAC_CONST(0.028686351835407) }, { FRAC_CONST(0.033442069265093), FRAC_CONST(0.028892092400321) }, { FRAC_CONST(0.033264161181349), FRAC_CONST(0.029096745194286) }, { FRAC_CONST(0.033085000720737), FRAC_CONST(0.029300302512241) }, { FRAC_CONST(0.032904594628548), FRAC_CONST(0.029502756690366) }, { FRAC_CONST(0.032722949696969), FRAC_CONST(0.029704100106376) }, { FRAC_CONST(0.032540072764829), FRAC_CONST(0.029904325179807) }, { FRAC_CONST(0.032355970717341), FRAC_CONST(0.030103424372297) }, { FRAC_CONST(0.032170650485843), FRAC_CONST(0.030301390187873) }, { FRAC_CONST(0.031984119047537), FRAC_CONST(0.030498215173235) }, { FRAC_CONST(0.031796383425227), FRAC_CONST(0.030693891918034) }, { FRAC_CONST(0.031607450687052), FRAC_CONST(0.030888413055150) }, { FRAC_CONST(0.031417327946223), FRAC_CONST(0.031081771260973) }, { FRAC_CONST(0.031226022360754), FRAC_CONST(0.031273959255676) }, { FRAC_CONST(0.031033541133193), FRAC_CONST(0.031464969803488) }, { FRAC_CONST(0.030839891510348), FRAC_CONST(0.031654795712972) }, { FRAC_CONST(0.030645080783018), FRAC_CONST(0.031843429837288) }, { FRAC_CONST(0.030449116285718), FRAC_CONST(0.032030865074469) }, { FRAC_CONST(0.030252005396399), FRAC_CONST(0.032217094367684) }, { FRAC_CONST(0.030053755536176), FRAC_CONST(0.032402110705505) }, { FRAC_CONST(0.029854374169043), FRAC_CONST(0.032585907122172) }, { FRAC_CONST(0.029653868801596), FRAC_CONST(0.032768476697853) }, { FRAC_CONST(0.029452246982750), FRAC_CONST(0.032949812558907) }, { FRAC_CONST(0.029249516303451), FRAC_CONST(0.033129907878142) }, { FRAC_CONST(0.029045684396395), FRAC_CONST(0.033308755875070) }, { FRAC_CONST(0.028840758935738), FRAC_CONST(0.033486349816166) }, { FRAC_CONST(0.028634747636808), FRAC_CONST(0.033662683015118) }, { FRAC_CONST(0.028427658255815), FRAC_CONST(0.033837748833080) }, { FRAC_CONST(0.028219498589555), FRAC_CONST(0.034011540678924) }, { FRAC_CONST(0.028010276475123), FRAC_CONST(0.034184052009485) }, { FRAC_CONST(0.027799999789613), FRAC_CONST(0.034355276329809) }, { FRAC_CONST(0.027588676449824), FRAC_CONST(0.034525207193396) }, { FRAC_CONST(0.027376314411959), FRAC_CONST(0.034693838202447) }, { FRAC_CONST(0.027162921671330), FRAC_CONST(0.034861163008098) }, { FRAC_CONST(0.026948506262053), FRAC_CONST(0.035027175310665) }, { FRAC_CONST(0.026733076256746), FRAC_CONST(0.035191868859880) }, { FRAC_CONST(0.026516639766228), FRAC_CONST(0.035355237455122) }, { FRAC_CONST(0.026299204939210), FRAC_CONST(0.035517274945657) }, { FRAC_CONST(0.026080779961991), FRAC_CONST(0.035677975230865) }, { FRAC_CONST(0.025861373058146), FRAC_CONST(0.035837332260471) }, { FRAC_CONST(0.025640992488223), FRAC_CONST(0.035995340034772) }, { FRAC_CONST(0.025419646549425), FRAC_CONST(0.036151992604866) }, { FRAC_CONST(0.025197343575302), FRAC_CONST(0.036307284072871) }, { FRAC_CONST(0.024974091935435), FRAC_CONST(0.036461208592152) }, { FRAC_CONST(0.024749900035122), FRAC_CONST(0.036613760367538) }, { FRAC_CONST(0.024524776315061), FRAC_CONST(0.036764933655540) }, { FRAC_CONST(0.024298729251033), FRAC_CONST(0.036914722764569) }, { FRAC_CONST(0.024071767353583), FRAC_CONST(0.037063122055150) }, { FRAC_CONST(0.023843899167697), FRAC_CONST(0.037210125940135) }, { FRAC_CONST(0.023615133272485), FRAC_CONST(0.037355728884908) }, { FRAC_CONST(0.023385478280852), FRAC_CONST(0.037499925407603) }, { FRAC_CONST(0.023154942839179), FRAC_CONST(0.037642710079302) }, { FRAC_CONST(0.022923535626995), FRAC_CONST(0.037784077524241) }, { FRAC_CONST(0.022691265356652), FRAC_CONST(0.037924022420018) }, { FRAC_CONST(0.022458140772993), FRAC_CONST(0.038062539497785) }, { FRAC_CONST(0.022224170653027), FRAC_CONST(0.038199623542453) }, { FRAC_CONST(0.021989363805598), FRAC_CONST(0.038335269392885) }, { FRAC_CONST(0.021753729071049), FRAC_CONST(0.038469471942092) }, { FRAC_CONST(0.021517275320897), FRAC_CONST(0.038602226137423) }, { FRAC_CONST(0.021280011457490), FRAC_CONST(0.038733526980758) }, { FRAC_CONST(0.021041946413679), FRAC_CONST(0.038863369528695) }, { FRAC_CONST(0.020803089152479), FRAC_CONST(0.038991748892734) }, { FRAC_CONST(0.020563448666730), FRAC_CONST(0.039118660239466) }, { FRAC_CONST(0.020323033978761), FRAC_CONST(0.039244098790750) }, { FRAC_CONST(0.020081854140050), FRAC_CONST(0.039368059823895) }, { FRAC_CONST(0.019839918230880), FRAC_CONST(0.039490538671839) }, { FRAC_CONST(0.019597235360003), FRAC_CONST(0.039611530723322) }, { FRAC_CONST(0.019353814664291), FRAC_CONST(0.039731031423061) }, { FRAC_CONST(0.019109665308395), FRAC_CONST(0.039849036271924) }, { FRAC_CONST(0.018864796484402), FRAC_CONST(0.039965540827094) }, { FRAC_CONST(0.018619217411483), FRAC_CONST(0.040080540702240) }, { FRAC_CONST(0.018372937335552), FRAC_CONST(0.040194031567683) }, { FRAC_CONST(0.018125965528915), FRAC_CONST(0.040306009150554) }, { FRAC_CONST(0.017878311289921), FRAC_CONST(0.040416469234963) }, { FRAC_CONST(0.017629983942612), FRAC_CONST(0.040525407662148) }, { FRAC_CONST(0.017380992836371), FRAC_CONST(0.040632820330639) }, { FRAC_CONST(0.017131347345575), FRAC_CONST(0.040738703196411) }, { FRAC_CONST(0.016881056869233), FRAC_CONST(0.040843052273033) }, { FRAC_CONST(0.016630130830641), FRAC_CONST(0.040945863631822) }, { FRAC_CONST(0.016378578677023), FRAC_CONST(0.041047133401988) }, { FRAC_CONST(0.016126409879175), FRAC_CONST(0.041146857770781) }, { FRAC_CONST(0.015873633931110), FRAC_CONST(0.041245032983635) }, { FRAC_CONST(0.015620260349699), FRAC_CONST(0.041341655344309) }, { FRAC_CONST(0.015366298674314), FRAC_CONST(0.041436721215026) }, { FRAC_CONST(0.015111758466470), FRAC_CONST(0.041530227016609) }, { FRAC_CONST(0.014856649309460), FRAC_CONST(0.041622169228618) }, { FRAC_CONST(0.014600980808001), FRAC_CONST(0.041712544389481) }, { FRAC_CONST(0.014344762587867), FRAC_CONST(0.041801349096623) }, { FRAC_CONST(0.014088004295529), FRAC_CONST(0.041888580006598) }, { FRAC_CONST(0.013830715597792), FRAC_CONST(0.041974233835211) }, { FRAC_CONST(0.013572906181430), FRAC_CONST(0.042058307357645) }, { FRAC_CONST(0.013314585752822), FRAC_CONST(0.042140797408577) }, { FRAC_CONST(0.013055764037585), FRAC_CONST(0.042221700882306) }, { FRAC_CONST(0.012796450780212), FRAC_CONST(0.042301014732860) }, { FRAC_CONST(0.012536655743699), FRAC_CONST(0.042378735974118) }, { FRAC_CONST(0.012276388709183), FRAC_CONST(0.042454861679919) }, { FRAC_CONST(0.012015659475571), FRAC_CONST(0.042529388984173) }, { FRAC_CONST(0.011754477859172), FRAC_CONST(0.042602315080970) }, { FRAC_CONST(0.011492853693324), FRAC_CONST(0.042673637224683) }, { FRAC_CONST(0.011230796828031), FRAC_CONST(0.042743352730074) }, { FRAC_CONST(0.010968317129584), FRAC_CONST(0.042811458972393) }, { FRAC_CONST(0.010705424480197), FRAC_CONST(0.042877953387479) }, { FRAC_CONST(0.010442128777629), FRAC_CONST(0.042942833471854) }, { FRAC_CONST(0.010178439934815), FRAC_CONST(0.043006096782821) }, { FRAC_CONST(0.009914367879490), FRAC_CONST(0.043067740938551) }, { FRAC_CONST(0.009649922553818), FRAC_CONST(0.043127763618177) }, { FRAC_CONST(0.009385113914016), FRAC_CONST(0.043186162561878) }, { FRAC_CONST(0.009119951929979), FRAC_CONST(0.043242935570968) }, { FRAC_CONST(0.008854446584907), FRAC_CONST(0.043298080507974) }, { FRAC_CONST(0.008588607874926), FRAC_CONST(0.043351595296722) }, { FRAC_CONST(0.008322445808712), FRAC_CONST(0.043403477922409) }, { FRAC_CONST(0.008055970407118), FRAC_CONST(0.043453726431684) }, { FRAC_CONST(0.007789191702791), FRAC_CONST(0.043502338932719) }, { FRAC_CONST(0.007522119739798), FRAC_CONST(0.043549313595281) }, { FRAC_CONST(0.007254764573250), FRAC_CONST(0.043594648650800) }, { FRAC_CONST(0.006987136268915), FRAC_CONST(0.043638342392438) }, { FRAC_CONST(0.006719244902849), FRAC_CONST(0.043680393175148) }, { FRAC_CONST(0.006451100561010), FRAC_CONST(0.043720799415744) }, { FRAC_CONST(0.006182713338881), FRAC_CONST(0.043759559592953) }, { FRAC_CONST(0.005914093341090), FRAC_CONST(0.043796672247476) }, { FRAC_CONST(0.005645250681027), FRAC_CONST(0.043832135982044) }, { FRAC_CONST(0.005376195480466), FRAC_CONST(0.043865949461465) }, { FRAC_CONST(0.005106937869184), FRAC_CONST(0.043898111412683) }, { FRAC_CONST(0.004837487984578), FRAC_CONST(0.043928620624817) }, { FRAC_CONST(0.004567855971284), FRAC_CONST(0.043957475949213) }, { FRAC_CONST(0.004298051980793), FRAC_CONST(0.043984676299484) }, { FRAC_CONST(0.004028086171076), FRAC_CONST(0.044010220651553) }, { FRAC_CONST(0.003757968706190), FRAC_CONST(0.044034108043689) }, { FRAC_CONST(0.003487709755907), FRAC_CONST(0.044056337576546) }, { FRAC_CONST(0.003217319495322), FRAC_CONST(0.044076908413193) }, { FRAC_CONST(0.002946808104477), FRAC_CONST(0.044095819779151) }, { FRAC_CONST(0.002676185767973), FRAC_CONST(0.044113070962418) }, { FRAC_CONST(0.002405462674586), FRAC_CONST(0.044128661313495) }, { FRAC_CONST(0.002134649016890), FRAC_CONST(0.044142590245416) }, { FRAC_CONST(0.001863754990865), FRAC_CONST(0.044154857233763) }, { FRAC_CONST(0.001592790795518), FRAC_CONST(0.044165461816692) }, { FRAC_CONST(0.001321766632497), FRAC_CONST(0.044174403594946) }, { FRAC_CONST(0.001050692705710), FRAC_CONST(0.044181682231873) }, { FRAC_CONST(0.000779579220936), FRAC_CONST(0.044187297453434) }, { FRAC_CONST(0.000508436385446), FRAC_CONST(0.044191249048222) }, { FRAC_CONST(0.000237274407613), FRAC_CONST(0.044193536867459) } }; #endif // LD_DEC #ifdef ALLOW_SMALL_FRAMELENGTH /* 480 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_1920[] = { { FRAC_CONST(0.032274858518097), FRAC_CONST(0.000013202404176) }, { FRAC_CONST(0.032274642494505), FRAC_CONST(0.000118821372483) }, { FRAC_CONST(0.032274080835421), FRAC_CONST(0.000224439068308) }, { FRAC_CONST(0.032273173546860), FRAC_CONST(0.000330054360572) }, { FRAC_CONST(0.032271920638538), FRAC_CONST(0.000435666118218) }, { FRAC_CONST(0.032270322123873), FRAC_CONST(0.000541273210231) }, { FRAC_CONST(0.032268378019984), FRAC_CONST(0.000646874505642) }, { FRAC_CONST(0.032266088347691), FRAC_CONST(0.000752468873546) }, { FRAC_CONST(0.032263453131514), FRAC_CONST(0.000858055183114) }, { FRAC_CONST(0.032260472399674), FRAC_CONST(0.000963632303600) }, { FRAC_CONST(0.032257146184092), FRAC_CONST(0.001069199104358) }, { FRAC_CONST(0.032253474520390), FRAC_CONST(0.001174754454853) }, { FRAC_CONST(0.032249457447888), FRAC_CONST(0.001280297224671) }, { FRAC_CONST(0.032245095009606), FRAC_CONST(0.001385826283535) }, { FRAC_CONST(0.032240387252262), FRAC_CONST(0.001491340501313) }, { FRAC_CONST(0.032235334226272), FRAC_CONST(0.001596838748031) }, { FRAC_CONST(0.032229935985750), FRAC_CONST(0.001702319893890) }, { FRAC_CONST(0.032224192588507), FRAC_CONST(0.001807782809271) }, { FRAC_CONST(0.032218104096050), FRAC_CONST(0.001913226364749) }, { FRAC_CONST(0.032211670573582), FRAC_CONST(0.002018649431111) }, { FRAC_CONST(0.032204892090000), FRAC_CONST(0.002124050879359) }, { FRAC_CONST(0.032197768717898), FRAC_CONST(0.002229429580728) }, { FRAC_CONST(0.032190300533560), FRAC_CONST(0.002334784406698) }, { FRAC_CONST(0.032182487616965), FRAC_CONST(0.002440114229003) }, { FRAC_CONST(0.032174330051782), FRAC_CONST(0.002545417919644) }, { FRAC_CONST(0.032165827925374), FRAC_CONST(0.002650694350905) }, { FRAC_CONST(0.032156981328790), FRAC_CONST(0.002755942395358) }, { FRAC_CONST(0.032147790356771), FRAC_CONST(0.002861160925883) }, { FRAC_CONST(0.032138255107744), FRAC_CONST(0.002966348815672) }, { FRAC_CONST(0.032128375683825), FRAC_CONST(0.003071504938250) }, { FRAC_CONST(0.032118152190814), FRAC_CONST(0.003176628167476) }, { FRAC_CONST(0.032107584738196), FRAC_CONST(0.003281717377568) }, { FRAC_CONST(0.032096673439141), FRAC_CONST(0.003386771443102) }, { FRAC_CONST(0.032085418410500), FRAC_CONST(0.003491789239036) }, { FRAC_CONST(0.032073819772804), FRAC_CONST(0.003596769640711) }, { FRAC_CONST(0.032061877650267), FRAC_CONST(0.003701711523874) }, { FRAC_CONST(0.032049592170778), FRAC_CONST(0.003806613764680) }, { FRAC_CONST(0.032036963465906), FRAC_CONST(0.003911475239711) }, { FRAC_CONST(0.032023991670893), FRAC_CONST(0.004016294825985) }, { FRAC_CONST(0.032010676924657), FRAC_CONST(0.004121071400967) }, { FRAC_CONST(0.031997019369789), FRAC_CONST(0.004225803842586) }, { FRAC_CONST(0.031983019152549), FRAC_CONST(0.004330491029241) }, { FRAC_CONST(0.031968676422869), FRAC_CONST(0.004435131839816) }, { FRAC_CONST(0.031953991334348), FRAC_CONST(0.004539725153692) }, { FRAC_CONST(0.031938964044252), FRAC_CONST(0.004644269850758) }, { FRAC_CONST(0.031923594713510), FRAC_CONST(0.004748764811426) }, { FRAC_CONST(0.031907883506716), FRAC_CONST(0.004853208916638) }, { FRAC_CONST(0.031891830592124), FRAC_CONST(0.004957601047881) }, { FRAC_CONST(0.031875436141648), FRAC_CONST(0.005061940087200) }, { FRAC_CONST(0.031858700330859), FRAC_CONST(0.005166224917208) }, { FRAC_CONST(0.031841623338985), FRAC_CONST(0.005270454421097) }, { FRAC_CONST(0.031824205348907), FRAC_CONST(0.005374627482653) }, { FRAC_CONST(0.031806446547156), FRAC_CONST(0.005478742986267) }, { FRAC_CONST(0.031788347123916), FRAC_CONST(0.005582799816945) }, { FRAC_CONST(0.031769907273017), FRAC_CONST(0.005686796860323) }, { FRAC_CONST(0.031751127191935), FRAC_CONST(0.005790733002674) }, { FRAC_CONST(0.031732007081789), FRAC_CONST(0.005894607130928) }, { FRAC_CONST(0.031712547147340), FRAC_CONST(0.005998418132675) }, { FRAC_CONST(0.031692747596989), FRAC_CONST(0.006102164896182) }, { FRAC_CONST(0.031672608642773), FRAC_CONST(0.006205846310406) }, { FRAC_CONST(0.031652130500364), FRAC_CONST(0.006309461265002) }, { FRAC_CONST(0.031631313389067), FRAC_CONST(0.006413008650337) }, { FRAC_CONST(0.031610157531816), FRAC_CONST(0.006516487357501) }, { FRAC_CONST(0.031588663155172), FRAC_CONST(0.006619896278321) }, { FRAC_CONST(0.031566830489325), FRAC_CONST(0.006723234305370) }, { FRAC_CONST(0.031544659768083), FRAC_CONST(0.006826500331981) }, { FRAC_CONST(0.031522151228878), FRAC_CONST(0.006929693252258) }, { FRAC_CONST(0.031499305112758), FRAC_CONST(0.007032811961088) }, { FRAC_CONST(0.031476121664387), FRAC_CONST(0.007135855354151) }, { FRAC_CONST(0.031452601132040), FRAC_CONST(0.007238822327937) }, { FRAC_CONST(0.031428743767604), FRAC_CONST(0.007341711779751) }, { FRAC_CONST(0.031404549826572), FRAC_CONST(0.007444522607730) }, { FRAC_CONST(0.031380019568042), FRAC_CONST(0.007547253710853) }, { FRAC_CONST(0.031355153254712), FRAC_CONST(0.007649903988952) }, { FRAC_CONST(0.031329951152882), FRAC_CONST(0.007752472342725) }, { FRAC_CONST(0.031304413532445), FRAC_CONST(0.007854957673748) }, { FRAC_CONST(0.031278540666888), FRAC_CONST(0.007957358884484) }, { FRAC_CONST(0.031252332833290), FRAC_CONST(0.008059674878300) }, { FRAC_CONST(0.031225790312316), FRAC_CONST(0.008161904559473) }, { FRAC_CONST(0.031198913388214), FRAC_CONST(0.008264046833205) }, { FRAC_CONST(0.031171702348814), FRAC_CONST(0.008366100605636) }, { FRAC_CONST(0.031144157485525), FRAC_CONST(0.008468064783849) }, { FRAC_CONST(0.031116279093331), FRAC_CONST(0.008569938275893) }, { FRAC_CONST(0.031088067470786), FRAC_CONST(0.008671719990782) }, { FRAC_CONST(0.031059522920014), FRAC_CONST(0.008773408838517) }, { FRAC_CONST(0.031030645746705), FRAC_CONST(0.008875003730092) }, { FRAC_CONST(0.031001436260110), FRAC_CONST(0.008976503577507) }, { FRAC_CONST(0.030971894773039), FRAC_CONST(0.009077907293780) }, { FRAC_CONST(0.030942021601857), FRAC_CONST(0.009179213792959) }, { FRAC_CONST(0.030911817066483), FRAC_CONST(0.009280421990133) }, { FRAC_CONST(0.030881281490382), FRAC_CONST(0.009381530801444) }, { FRAC_CONST(0.030850415200566), FRAC_CONST(0.009482539144097) }, { FRAC_CONST(0.030819218527589), FRAC_CONST(0.009583445936373) }, { FRAC_CONST(0.030787691805541), FRAC_CONST(0.009684250097643) }, { FRAC_CONST(0.030755835372048), FRAC_CONST(0.009784950548375) }, { FRAC_CONST(0.030723649568268), FRAC_CONST(0.009885546210147) }, { FRAC_CONST(0.030691134738883), FRAC_CONST(0.009986036005661) }, { FRAC_CONST(0.030658291232103), FRAC_CONST(0.010086418858753) }, { FRAC_CONST(0.030625119399655), FRAC_CONST(0.010186693694402) }, { FRAC_CONST(0.030591619596781), FRAC_CONST(0.010286859438745) }, { FRAC_CONST(0.030557792182239), FRAC_CONST(0.010386915019088) }, { FRAC_CONST(0.030523637518292), FRAC_CONST(0.010486859363916) }, { FRAC_CONST(0.030489155970710), FRAC_CONST(0.010586691402906) }, { FRAC_CONST(0.030454347908763), FRAC_CONST(0.010686410066936) }, { FRAC_CONST(0.030419213705216), FRAC_CONST(0.010786014288099) }, { FRAC_CONST(0.030383753736329), FRAC_CONST(0.010885502999714) }, { FRAC_CONST(0.030347968381849), FRAC_CONST(0.010984875136338) }, { FRAC_CONST(0.030311858025010), FRAC_CONST(0.011084129633775) }, { FRAC_CONST(0.030275423052523), FRAC_CONST(0.011183265429088) }, { FRAC_CONST(0.030238663854579), FRAC_CONST(0.011282281460612) }, { FRAC_CONST(0.030201580824838), FRAC_CONST(0.011381176667967) }, { FRAC_CONST(0.030164174360430), FRAC_CONST(0.011479949992062) }, { FRAC_CONST(0.030126444861948), FRAC_CONST(0.011578600375117) }, { FRAC_CONST(0.030088392733446), FRAC_CONST(0.011677126760663) }, { FRAC_CONST(0.030050018382430), FRAC_CONST(0.011775528093563) }, { FRAC_CONST(0.030011322219859), FRAC_CONST(0.011873803320018) }, { FRAC_CONST(0.029972304660138), FRAC_CONST(0.011971951387578) }, { FRAC_CONST(0.029932966121114), FRAC_CONST(0.012069971245157) }, { FRAC_CONST(0.029893307024070), FRAC_CONST(0.012167861843041) }, { FRAC_CONST(0.029853327793724), FRAC_CONST(0.012265622132901) }, { FRAC_CONST(0.029813028858222), FRAC_CONST(0.012363251067801) }, { FRAC_CONST(0.029772410649132), FRAC_CONST(0.012460747602215) }, { FRAC_CONST(0.029731473601443), FRAC_CONST(0.012558110692033) }, { FRAC_CONST(0.029690218153558), FRAC_CONST(0.012655339294575) }, { FRAC_CONST(0.029648644747289), FRAC_CONST(0.012752432368600) }, { FRAC_CONST(0.029606753827855), FRAC_CONST(0.012849388874320) }, { FRAC_CONST(0.029564545843872), FRAC_CONST(0.012946207773407) }, { FRAC_CONST(0.029522021247356), FRAC_CONST(0.013042888029011) }, { FRAC_CONST(0.029479180493710), FRAC_CONST(0.013139428605762) }, { FRAC_CONST(0.029436024041725), FRAC_CONST(0.013235828469789) }, { FRAC_CONST(0.029392552353570), FRAC_CONST(0.013332086588727) }, { FRAC_CONST(0.029348765894794), FRAC_CONST(0.013428201931728) }, { FRAC_CONST(0.029304665134313), FRAC_CONST(0.013524173469475) }, { FRAC_CONST(0.029260250544412), FRAC_CONST(0.013620000174189) }, { FRAC_CONST(0.029215522600735), FRAC_CONST(0.013715681019643) }, { FRAC_CONST(0.029170481782283), FRAC_CONST(0.013811214981173) }, { FRAC_CONST(0.029125128571406), FRAC_CONST(0.013906601035686) }, { FRAC_CONST(0.029079463453801), FRAC_CONST(0.014001838161674) }, { FRAC_CONST(0.029033486918505), FRAC_CONST(0.014096925339225) }, { FRAC_CONST(0.028987199457889), FRAC_CONST(0.014191861550031) }, { FRAC_CONST(0.028940601567655), FRAC_CONST(0.014286645777401) }, { FRAC_CONST(0.028893693746829), FRAC_CONST(0.014381277006273) }, { FRAC_CONST(0.028846476497755), FRAC_CONST(0.014475754223221) }, { FRAC_CONST(0.028798950326094), FRAC_CONST(0.014570076416472) }, { FRAC_CONST(0.028751115740811), FRAC_CONST(0.014664242575910) }, { FRAC_CONST(0.028702973254178), FRAC_CONST(0.014758251693091) }, { FRAC_CONST(0.028654523381760), FRAC_CONST(0.014852102761253) }, { FRAC_CONST(0.028605766642418), FRAC_CONST(0.014945794775326) }, { FRAC_CONST(0.028556703558297), FRAC_CONST(0.015039326731945) }, { FRAC_CONST(0.028507334654823), FRAC_CONST(0.015132697629457) }, { FRAC_CONST(0.028457660460698), FRAC_CONST(0.015225906467935) }, { FRAC_CONST(0.028407681507891), FRAC_CONST(0.015318952249187) }, { FRAC_CONST(0.028357398331639), FRAC_CONST(0.015411833976768) }, { FRAC_CONST(0.028306811470432), FRAC_CONST(0.015504550655988) }, { FRAC_CONST(0.028255921466016), FRAC_CONST(0.015597101293927) }, { FRAC_CONST(0.028204728863381), FRAC_CONST(0.015689484899442) }, { FRAC_CONST(0.028153234210760), FRAC_CONST(0.015781700483179) }, { FRAC_CONST(0.028101438059619), FRAC_CONST(0.015873747057582) }, { FRAC_CONST(0.028049340964652), FRAC_CONST(0.015965623636907) }, { FRAC_CONST(0.027996943483779), FRAC_CONST(0.016057329237229) }, { FRAC_CONST(0.027944246178133), FRAC_CONST(0.016148862876456) }, { FRAC_CONST(0.027891249612061), FRAC_CONST(0.016240223574335) }, { FRAC_CONST(0.027837954353113), FRAC_CONST(0.016331410352467) }, { FRAC_CONST(0.027784360972039), FRAC_CONST(0.016422422234315) }, { FRAC_CONST(0.027730470042780), FRAC_CONST(0.016513258245214) }, { FRAC_CONST(0.027676282142466), FRAC_CONST(0.016603917412384) }, { FRAC_CONST(0.027621797851405), FRAC_CONST(0.016694398764938) }, { FRAC_CONST(0.027567017753080), FRAC_CONST(0.016784701333894) }, { FRAC_CONST(0.027511942434143), FRAC_CONST(0.016874824152183) }, { FRAC_CONST(0.027456572484404), FRAC_CONST(0.016964766254662) }, { FRAC_CONST(0.027400908496833), FRAC_CONST(0.017054526678124) }, { FRAC_CONST(0.027344951067546), FRAC_CONST(0.017144104461307) }, { FRAC_CONST(0.027288700795801), FRAC_CONST(0.017233498644904) }, { FRAC_CONST(0.027232158283994), FRAC_CONST(0.017322708271577) }, { FRAC_CONST(0.027175324137651), FRAC_CONST(0.017411732385960) }, { FRAC_CONST(0.027118198965418), FRAC_CONST(0.017500570034678) }, { FRAC_CONST(0.027060783379060), FRAC_CONST(0.017589220266351) }, { FRAC_CONST(0.027003077993454), FRAC_CONST(0.017677682131607) }, { FRAC_CONST(0.026945083426576), FRAC_CONST(0.017765954683088) }, { FRAC_CONST(0.026886800299502), FRAC_CONST(0.017854036975468) }, { FRAC_CONST(0.026828229236397), FRAC_CONST(0.017941928065456) }, { FRAC_CONST(0.026769370864511), FRAC_CONST(0.018029627011808) }, { FRAC_CONST(0.026710225814170), FRAC_CONST(0.018117132875340) }, { FRAC_CONST(0.026650794718768), FRAC_CONST(0.018204444718934) }, { FRAC_CONST(0.026591078214767), FRAC_CONST(0.018291561607551) }, { FRAC_CONST(0.026531076941680), FRAC_CONST(0.018378482608238) }, { FRAC_CONST(0.026470791542075), FRAC_CONST(0.018465206790142) }, { FRAC_CONST(0.026410222661558), FRAC_CONST(0.018551733224515) }, { FRAC_CONST(0.026349370948775), FRAC_CONST(0.018638060984730) }, { FRAC_CONST(0.026288237055398), FRAC_CONST(0.018724189146286) }, { FRAC_CONST(0.026226821636121), FRAC_CONST(0.018810116786819) }, { FRAC_CONST(0.026165125348656), FRAC_CONST(0.018895842986112) }, { FRAC_CONST(0.026103148853718), FRAC_CONST(0.018981366826109) }, { FRAC_CONST(0.026040892815028), FRAC_CONST(0.019066687390916) }, { FRAC_CONST(0.025978357899296), FRAC_CONST(0.019151803766819) }, { FRAC_CONST(0.025915544776223), FRAC_CONST(0.019236715042290) }, { FRAC_CONST(0.025852454118485), FRAC_CONST(0.019321420307998) }, { FRAC_CONST(0.025789086601733), FRAC_CONST(0.019405918656817) }, { FRAC_CONST(0.025725442904582), FRAC_CONST(0.019490209183837) }, { FRAC_CONST(0.025661523708606), FRAC_CONST(0.019574290986376) }, { FRAC_CONST(0.025597329698327), FRAC_CONST(0.019658163163984) }, { FRAC_CONST(0.025532861561211), FRAC_CONST(0.019741824818458) }, { FRAC_CONST(0.025468119987662), FRAC_CONST(0.019825275053848) }, { FRAC_CONST(0.025403105671008), FRAC_CONST(0.019908512976470) }, { FRAC_CONST(0.025337819307501), FRAC_CONST(0.019991537694913) }, { FRAC_CONST(0.025272261596305), FRAC_CONST(0.020074348320047) }, { FRAC_CONST(0.025206433239491), FRAC_CONST(0.020156943965039) }, { FRAC_CONST(0.025140334942028), FRAC_CONST(0.020239323745355) }, { FRAC_CONST(0.025073967411776), FRAC_CONST(0.020321486778774) }, { FRAC_CONST(0.025007331359476), FRAC_CONST(0.020403432185395) }, { FRAC_CONST(0.024940427498748), FRAC_CONST(0.020485159087650) }, { FRAC_CONST(0.024873256546079), FRAC_CONST(0.020566666610309) }, { FRAC_CONST(0.024805819220816), FRAC_CONST(0.020647953880491) }, { FRAC_CONST(0.024738116245157), FRAC_CONST(0.020729020027676) }, { FRAC_CONST(0.024670148344147), FRAC_CONST(0.020809864183709) }, { FRAC_CONST(0.024601916245669), FRAC_CONST(0.020890485482816) }, { FRAC_CONST(0.024533420680433), FRAC_CONST(0.020970883061607) }, { FRAC_CONST(0.024464662381971), FRAC_CONST(0.021051056059087) }, { FRAC_CONST(0.024395642086630), FRAC_CONST(0.021131003616670) }, { FRAC_CONST(0.024326360533561), FRAC_CONST(0.021210724878181) }, { FRAC_CONST(0.024256818464715), FRAC_CONST(0.021290218989868) }, { FRAC_CONST(0.024187016624830), FRAC_CONST(0.021369485100415) }, { FRAC_CONST(0.024116955761430), FRAC_CONST(0.021448522360944) }, { FRAC_CONST(0.024046636624808), FRAC_CONST(0.021527329925030) }, { FRAC_CONST(0.023976059968027), FRAC_CONST(0.021605906948708) }, { FRAC_CONST(0.023905226546906), FRAC_CONST(0.021684252590480) }, { FRAC_CONST(0.023834137120014), FRAC_CONST(0.021762366011328) }, { FRAC_CONST(0.023762792448662), FRAC_CONST(0.021840246374720) }, { FRAC_CONST(0.023691193296893), FRAC_CONST(0.021917892846620) }, { FRAC_CONST(0.023619340431478), FRAC_CONST(0.021995304595495) }, { FRAC_CONST(0.023547234621902), FRAC_CONST(0.022072480792330) }, { FRAC_CONST(0.023474876640361), FRAC_CONST(0.022149420610628) }, { FRAC_CONST(0.023402267261751), FRAC_CONST(0.022226123226426) }, { FRAC_CONST(0.023329407263659), FRAC_CONST(0.022302587818300) }, { FRAC_CONST(0.023256297426359), FRAC_CONST(0.022378813567377) }, { FRAC_CONST(0.023182938532797), FRAC_CONST(0.022454799657339) }, { FRAC_CONST(0.023109331368588), FRAC_CONST(0.022530545274437) }, { FRAC_CONST(0.023035476722006), FRAC_CONST(0.022606049607496) }, { FRAC_CONST(0.022961375383975), FRAC_CONST(0.022681311847926) }, { FRAC_CONST(0.022887028148061), FRAC_CONST(0.022756331189727) }, { FRAC_CONST(0.022812435810462), FRAC_CONST(0.022831106829504) }, { FRAC_CONST(0.022737599170003), FRAC_CONST(0.022905637966469) }, { FRAC_CONST(0.022662519028125), FRAC_CONST(0.022979923802453) }, { FRAC_CONST(0.022587196188874), FRAC_CONST(0.023053963541915) }, { FRAC_CONST(0.022511631458899), FRAC_CONST(0.023127756391950) }, { FRAC_CONST(0.022435825647437), FRAC_CONST(0.023201301562294) }, { FRAC_CONST(0.022359779566306), FRAC_CONST(0.023274598265338) }, { FRAC_CONST(0.022283494029900), FRAC_CONST(0.023347645716133) }, { FRAC_CONST(0.022206969855176), FRAC_CONST(0.023420443132400) }, { FRAC_CONST(0.022130207861645), FRAC_CONST(0.023492989734537) }, { FRAC_CONST(0.022053208871367), FRAC_CONST(0.023565284745628) }, { FRAC_CONST(0.021975973708940), FRAC_CONST(0.023637327391451) }, { FRAC_CONST(0.021898503201489), FRAC_CONST(0.023709116900488) }, { FRAC_CONST(0.021820798178663), FRAC_CONST(0.023780652503931) }, { FRAC_CONST(0.021742859472618), FRAC_CONST(0.023851933435691) }, { FRAC_CONST(0.021664687918017), FRAC_CONST(0.023922958932406) }, { FRAC_CONST(0.021586284352013), FRAC_CONST(0.023993728233451) }, { FRAC_CONST(0.021507649614247), FRAC_CONST(0.024064240580942) }, { FRAC_CONST(0.021428784546832), FRAC_CONST(0.024134495219750) }, { FRAC_CONST(0.021349689994350), FRAC_CONST(0.024204491397504) }, { FRAC_CONST(0.021270366803840), FRAC_CONST(0.024274228364600) }, { FRAC_CONST(0.021190815824791), FRAC_CONST(0.024343705374213) }, { FRAC_CONST(0.021111037909128), FRAC_CONST(0.024412921682298) }, { FRAC_CONST(0.021031033911210), FRAC_CONST(0.024481876547605) }, { FRAC_CONST(0.020950804687815), FRAC_CONST(0.024550569231683) }, { FRAC_CONST(0.020870351098134), FRAC_CONST(0.024618998998889) }, { FRAC_CONST(0.020789674003759), FRAC_CONST(0.024687165116394) }, { FRAC_CONST(0.020708774268678), FRAC_CONST(0.024755066854194) }, { FRAC_CONST(0.020627652759262), FRAC_CONST(0.024822703485116) }, { FRAC_CONST(0.020546310344257), FRAC_CONST(0.024890074284826) }, { FRAC_CONST(0.020464747894775), FRAC_CONST(0.024957178531837) }, { FRAC_CONST(0.020382966284284), FRAC_CONST(0.025024015507516) }, { FRAC_CONST(0.020300966388600), FRAC_CONST(0.025090584496093) }, { FRAC_CONST(0.020218749085876), FRAC_CONST(0.025156884784668) }, { FRAC_CONST(0.020136315256592), FRAC_CONST(0.025222915663218) }, { FRAC_CONST(0.020053665783549), FRAC_CONST(0.025288676424605) }, { FRAC_CONST(0.019970801551857), FRAC_CONST(0.025354166364584) }, { FRAC_CONST(0.019887723448925), FRAC_CONST(0.025419384781811) }, { FRAC_CONST(0.019804432364452), FRAC_CONST(0.025484330977848) }, { FRAC_CONST(0.019720929190419), FRAC_CONST(0.025549004257175) }, { FRAC_CONST(0.019637214821078), FRAC_CONST(0.025613403927192) }, { FRAC_CONST(0.019553290152943), FRAC_CONST(0.025677529298230) }, { FRAC_CONST(0.019469156084779), FRAC_CONST(0.025741379683559) }, { FRAC_CONST(0.019384813517595), FRAC_CONST(0.025804954399392) }, { FRAC_CONST(0.019300263354632), FRAC_CONST(0.025868252764895) }, { FRAC_CONST(0.019215506501354), FRAC_CONST(0.025931274102193) }, { FRAC_CONST(0.019130543865439), FRAC_CONST(0.025994017736379) }, { FRAC_CONST(0.019045376356769), FRAC_CONST(0.026056482995518) }, { FRAC_CONST(0.018960004887419), FRAC_CONST(0.026118669210657) }, { FRAC_CONST(0.018874430371648), FRAC_CONST(0.026180575715833) }, { FRAC_CONST(0.018788653725892), FRAC_CONST(0.026242201848076) }, { FRAC_CONST(0.018702675868750), FRAC_CONST(0.026303546947421) }, { FRAC_CONST(0.018616497720974), FRAC_CONST(0.026364610356909) }, { FRAC_CONST(0.018530120205464), FRAC_CONST(0.026425391422602) }, { FRAC_CONST(0.018443544247254), FRAC_CONST(0.026485889493583) }, { FRAC_CONST(0.018356770773502), FRAC_CONST(0.026546103921965) }, { FRAC_CONST(0.018269800713483), FRAC_CONST(0.026606034062902) }, { FRAC_CONST(0.018182634998576), FRAC_CONST(0.026665679274589) }, { FRAC_CONST(0.018095274562256), FRAC_CONST(0.026725038918274) }, { FRAC_CONST(0.018007720340083), FRAC_CONST(0.026784112358263) }, { FRAC_CONST(0.017919973269692), FRAC_CONST(0.026842898961926) }, { FRAC_CONST(0.017832034290785), FRAC_CONST(0.026901398099707) }, { FRAC_CONST(0.017743904345116), FRAC_CONST(0.026959609145127) }, { FRAC_CONST(0.017655584376488), FRAC_CONST(0.027017531474792) }, { FRAC_CONST(0.017567075330734), FRAC_CONST(0.027075164468401) }, { FRAC_CONST(0.017478378155718), FRAC_CONST(0.027132507508750) }, { FRAC_CONST(0.017389493801313), FRAC_CONST(0.027189559981742) }, { FRAC_CONST(0.017300423219401), FRAC_CONST(0.027246321276391) }, { FRAC_CONST(0.017211167363854), FRAC_CONST(0.027302790784828) }, { FRAC_CONST(0.017121727190533), FRAC_CONST(0.027358967902310) }, { FRAC_CONST(0.017032103657269), FRAC_CONST(0.027414852027226) }, { FRAC_CONST(0.016942297723858), FRAC_CONST(0.027470442561102) }, { FRAC_CONST(0.016852310352050), FRAC_CONST(0.027525738908608) }, { FRAC_CONST(0.016762142505537), FRAC_CONST(0.027580740477564) }, { FRAC_CONST(0.016671795149944), FRAC_CONST(0.027635446678948) }, { FRAC_CONST(0.016581269252819), FRAC_CONST(0.027689856926900) }, { FRAC_CONST(0.016490565783622), FRAC_CONST(0.027743970638730) }, { FRAC_CONST(0.016399685713714), FRAC_CONST(0.027797787234924) }, { FRAC_CONST(0.016308630016347), FRAC_CONST(0.027851306139149) }, { FRAC_CONST(0.016217399666655), FRAC_CONST(0.027904526778260) }, { FRAC_CONST(0.016125995641641), FRAC_CONST(0.027957448582309) }, { FRAC_CONST(0.016034418920170), FRAC_CONST(0.028010070984544) }, { FRAC_CONST(0.015942670482954), FRAC_CONST(0.028062393421421) }, { FRAC_CONST(0.015850751312545), FRAC_CONST(0.028114415332610) }, { FRAC_CONST(0.015758662393324), FRAC_CONST(0.028166136160998) }, { FRAC_CONST(0.015666404711489), FRAC_CONST(0.028217555352697) }, { FRAC_CONST(0.015573979255046), FRAC_CONST(0.028268672357047) }, { FRAC_CONST(0.015481387013797), FRAC_CONST(0.028319486626627) }, { FRAC_CONST(0.015388628979331), FRAC_CONST(0.028369997617257) }, { FRAC_CONST(0.015295706145012), FRAC_CONST(0.028420204788004) }, { FRAC_CONST(0.015202619505968), FRAC_CONST(0.028470107601191) }, { FRAC_CONST(0.015109370059084), FRAC_CONST(0.028519705522399) }, { FRAC_CONST(0.015015958802984), FRAC_CONST(0.028568998020472) }, { FRAC_CONST(0.014922386738030), FRAC_CONST(0.028617984567529) }, { FRAC_CONST(0.014828654866302), FRAC_CONST(0.028666664638963) }, { FRAC_CONST(0.014734764191593), FRAC_CONST(0.028715037713449) }, { FRAC_CONST(0.014640715719398), FRAC_CONST(0.028763103272951) }, { FRAC_CONST(0.014546510456900), FRAC_CONST(0.028810860802724) }, { FRAC_CONST(0.014452149412962), FRAC_CONST(0.028858309791325) }, { FRAC_CONST(0.014357633598114), FRAC_CONST(0.028905449730613) }, { FRAC_CONST(0.014262964024545), FRAC_CONST(0.028952280115756) }, { FRAC_CONST(0.014168141706090), FRAC_CONST(0.028998800445240) }, { FRAC_CONST(0.014073167658220), FRAC_CONST(0.029045010220868) }, { FRAC_CONST(0.013978042898030), FRAC_CONST(0.029090908947771) }, { FRAC_CONST(0.013882768444231), FRAC_CONST(0.029136496134411) }, { FRAC_CONST(0.013787345317136), FRAC_CONST(0.029181771292585) }, { FRAC_CONST(0.013691774538648), FRAC_CONST(0.029226733937433) }, { FRAC_CONST(0.013596057132255), FRAC_CONST(0.029271383587441) }, { FRAC_CONST(0.013500194123014), FRAC_CONST(0.029315719764447) }, { FRAC_CONST(0.013404186537539), FRAC_CONST(0.029359741993647) }, { FRAC_CONST(0.013308035403995), FRAC_CONST(0.029403449803598) }, { FRAC_CONST(0.013211741752084), FRAC_CONST(0.029446842726223) }, { FRAC_CONST(0.013115306613032), FRAC_CONST(0.029489920296820) }, { FRAC_CONST(0.013018731019584), FRAC_CONST(0.029532682054063) }, { FRAC_CONST(0.012922016005985), FRAC_CONST(0.029575127540008) }, { FRAC_CONST(0.012825162607977), FRAC_CONST(0.029617256300097) }, { FRAC_CONST(0.012728171862781), FRAC_CONST(0.029659067883165) }, { FRAC_CONST(0.012631044809089), FRAC_CONST(0.029700561841444) }, { FRAC_CONST(0.012533782487056), FRAC_CONST(0.029741737730567) }, { FRAC_CONST(0.012436385938281), FRAC_CONST(0.029782595109573) }, { FRAC_CONST(0.012338856205805), FRAC_CONST(0.029823133540913) }, { FRAC_CONST(0.012241194334091), FRAC_CONST(0.029863352590452) }, { FRAC_CONST(0.012143401369021), FRAC_CONST(0.029903251827477) }, { FRAC_CONST(0.012045478357878), FRAC_CONST(0.029942830824699) }, { FRAC_CONST(0.011947426349339), FRAC_CONST(0.029982089158259) }, { FRAC_CONST(0.011849246393462), FRAC_CONST(0.030021026407731) }, { FRAC_CONST(0.011750939541676), FRAC_CONST(0.030059642156129) }, { FRAC_CONST(0.011652506846768), FRAC_CONST(0.030097935989909) }, { FRAC_CONST(0.011553949362874), FRAC_CONST(0.030135907498976) }, { FRAC_CONST(0.011455268145464), FRAC_CONST(0.030173556276684) }, { FRAC_CONST(0.011356464251335), FRAC_CONST(0.030210881919845) }, { FRAC_CONST(0.011257538738598), FRAC_CONST(0.030247884028732) }, { FRAC_CONST(0.011158492666665), FRAC_CONST(0.030284562207083) }, { FRAC_CONST(0.011059327096240), FRAC_CONST(0.030320916062102) }, { FRAC_CONST(0.010960043089307), FRAC_CONST(0.030356945204470) }, { FRAC_CONST(0.010860641709118), FRAC_CONST(0.030392649248343) }, { FRAC_CONST(0.010761124020182), FRAC_CONST(0.030428027811361) }, { FRAC_CONST(0.010661491088253), FRAC_CONST(0.030463080514646) }, { FRAC_CONST(0.010561743980319), FRAC_CONST(0.030497806982812) }, { FRAC_CONST(0.010461883764593), FRAC_CONST(0.030532206843968) }, { FRAC_CONST(0.010361911510496), FRAC_CONST(0.030566279729717) }, { FRAC_CONST(0.010261828288652), FRAC_CONST(0.030600025275167) }, { FRAC_CONST(0.010161635170872), FRAC_CONST(0.030633443118931) }, { FRAC_CONST(0.010061333230142), FRAC_CONST(0.030666532903129) }, { FRAC_CONST(0.009960923540617), FRAC_CONST(0.030699294273397) }, { FRAC_CONST(0.009860407177603), FRAC_CONST(0.030731726878888) }, { FRAC_CONST(0.009759785217550), FRAC_CONST(0.030763830372273) }, { FRAC_CONST(0.009659058738038), FRAC_CONST(0.030795604409750) }, { FRAC_CONST(0.009558228817767), FRAC_CONST(0.030827048651045) }, { FRAC_CONST(0.009457296536545), FRAC_CONST(0.030858162759415) }, { FRAC_CONST(0.009356262975275), FRAC_CONST(0.030888946401653) }, { FRAC_CONST(0.009255129215945), FRAC_CONST(0.030919399248091) }, { FRAC_CONST(0.009153896341616), FRAC_CONST(0.030949520972603) }, { FRAC_CONST(0.009052565436412), FRAC_CONST(0.030979311252611) }, { FRAC_CONST(0.008951137585505), FRAC_CONST(0.031008769769084) }, { FRAC_CONST(0.008849613875105), FRAC_CONST(0.031037896206544) }, { FRAC_CONST(0.008747995392451), FRAC_CONST(0.031066690253072) }, { FRAC_CONST(0.008646283225794), FRAC_CONST(0.031095151600306) }, { FRAC_CONST(0.008544478464390), FRAC_CONST(0.031123279943448) }, { FRAC_CONST(0.008442582198486), FRAC_CONST(0.031151074981266) }, { FRAC_CONST(0.008340595519310), FRAC_CONST(0.031178536416098) }, { FRAC_CONST(0.008238519519057), FRAC_CONST(0.031205663953853) }, { FRAC_CONST(0.008136355290878), FRAC_CONST(0.031232457304017) }, { FRAC_CONST(0.008034103928871), FRAC_CONST(0.031258916179656) }, { FRAC_CONST(0.007931766528065), FRAC_CONST(0.031285040297416) }, { FRAC_CONST(0.007829344184412), FRAC_CONST(0.031310829377528) }, { FRAC_CONST(0.007726837994772), FRAC_CONST(0.031336283143813) }, { FRAC_CONST(0.007624249056906), FRAC_CONST(0.031361401323680) }, { FRAC_CONST(0.007521578469457), FRAC_CONST(0.031386183648135) }, { FRAC_CONST(0.007418827331946), FRAC_CONST(0.031410629851778) }, { FRAC_CONST(0.007315996744755), FRAC_CONST(0.031434739672811) }, { FRAC_CONST(0.007213087809115), FRAC_CONST(0.031458512853036) }, { FRAC_CONST(0.007110101627101), FRAC_CONST(0.031481949137863) }, { FRAC_CONST(0.007007039301610), FRAC_CONST(0.031505048276306) }, { FRAC_CONST(0.006903901936357), FRAC_CONST(0.031527810020993) }, { FRAC_CONST(0.006800690635862), FRAC_CONST(0.031550234128164) }, { FRAC_CONST(0.006697406505433), FRAC_CONST(0.031572320357675) }, { FRAC_CONST(0.006594050651161), FRAC_CONST(0.031594068473000) }, { FRAC_CONST(0.006490624179905), FRAC_CONST(0.031615478241233) }, { FRAC_CONST(0.006387128199278), FRAC_CONST(0.031636549433095) }, { FRAC_CONST(0.006283563817639), FRAC_CONST(0.031657281822929) }, { FRAC_CONST(0.006179932144080), FRAC_CONST(0.031677675188707) }, { FRAC_CONST(0.006076234288412), FRAC_CONST(0.031697729312034) }, { FRAC_CONST(0.005972471361157), FRAC_CONST(0.031717443978146) }, { FRAC_CONST(0.005868644473532), FRAC_CONST(0.031736818975914) }, { FRAC_CONST(0.005764754737440), FRAC_CONST(0.031755854097848) }, { FRAC_CONST(0.005660803265456), FRAC_CONST(0.031774549140098) }, { FRAC_CONST(0.005556791170816), FRAC_CONST(0.031792903902453) }, { FRAC_CONST(0.005452719567407), FRAC_CONST(0.031810918188350) }, { FRAC_CONST(0.005348589569753), FRAC_CONST(0.031828591804869) }, { FRAC_CONST(0.005244402293001), FRAC_CONST(0.031845924562742) }, { FRAC_CONST(0.005140158852914), FRAC_CONST(0.031862916276347) }, { FRAC_CONST(0.005035860365855), FRAC_CONST(0.031879566763717) }, { FRAC_CONST(0.004931507948778), FRAC_CONST(0.031895875846539) }, { FRAC_CONST(0.004827102719212), FRAC_CONST(0.031911843350155) }, { FRAC_CONST(0.004722645795254), FRAC_CONST(0.031927469103567) }, { FRAC_CONST(0.004618138295554), FRAC_CONST(0.031942752939435) }, { FRAC_CONST(0.004513581339303), FRAC_CONST(0.031957694694082) }, { FRAC_CONST(0.004408976046222), FRAC_CONST(0.031972294207493) }, { FRAC_CONST(0.004304323536549), FRAC_CONST(0.031986551323320) }, { FRAC_CONST(0.004199624931030), FRAC_CONST(0.032000465888879) }, { FRAC_CONST(0.004094881350902), FRAC_CONST(0.032014037755158) }, { FRAC_CONST(0.003990093917884), FRAC_CONST(0.032027266776813) }, { FRAC_CONST(0.003885263754166), FRAC_CONST(0.032040152812170) }, { FRAC_CONST(0.003780391982394), FRAC_CONST(0.032052695723232) }, { FRAC_CONST(0.003675479725661), FRAC_CONST(0.032064895375674) }, { FRAC_CONST(0.003570528107494), FRAC_CONST(0.032076751638847) }, { FRAC_CONST(0.003465538251839), FRAC_CONST(0.032088264385780) }, { FRAC_CONST(0.003360511283053), FRAC_CONST(0.032099433493181) }, { FRAC_CONST(0.003255448325892), FRAC_CONST(0.032110258841438) }, { FRAC_CONST(0.003150350505494), FRAC_CONST(0.032120740314619) }, { FRAC_CONST(0.003045218947373), FRAC_CONST(0.032130877800478) }, { FRAC_CONST(0.002940054777404), FRAC_CONST(0.032140671190449) }, { FRAC_CONST(0.002834859121810), FRAC_CONST(0.032150120379653) }, { FRAC_CONST(0.002729633107153), FRAC_CONST(0.032159225266897) }, { FRAC_CONST(0.002624377860318), FRAC_CONST(0.032167985754674) }, { FRAC_CONST(0.002519094508504), FRAC_CONST(0.032176401749168) }, { FRAC_CONST(0.002413784179212), FRAC_CONST(0.032184473160250) }, { FRAC_CONST(0.002308448000231), FRAC_CONST(0.032192199901481) }, { FRAC_CONST(0.002203087099626), FRAC_CONST(0.032199581890114) }, { FRAC_CONST(0.002097702605728), FRAC_CONST(0.032206619047093) }, { FRAC_CONST(0.001992295647121), FRAC_CONST(0.032213311297057) }, { FRAC_CONST(0.001886867352628), FRAC_CONST(0.032219658568338) }, { FRAC_CONST(0.001781418851302), FRAC_CONST(0.032225660792960) }, { FRAC_CONST(0.001675951272410), FRAC_CONST(0.032231317906644) }, { FRAC_CONST(0.001570465745428), FRAC_CONST(0.032236629848809) }, { FRAC_CONST(0.001464963400018), FRAC_CONST(0.032241596562566) }, { FRAC_CONST(0.001359445366028), FRAC_CONST(0.032246217994727) }, { FRAC_CONST(0.001253912773470), FRAC_CONST(0.032250494095799) }, { FRAC_CONST(0.001148366752513), FRAC_CONST(0.032254424819990) }, { FRAC_CONST(0.001042808433471), FRAC_CONST(0.032258010125204) }, { FRAC_CONST(0.000937238946789), FRAC_CONST(0.032261249973045) }, { FRAC_CONST(0.000831659423030), FRAC_CONST(0.032264144328817) }, { FRAC_CONST(0.000726070992868), FRAC_CONST(0.032266693161525) }, { FRAC_CONST(0.000620474787068), FRAC_CONST(0.032268896443871) }, { FRAC_CONST(0.000514871936481), FRAC_CONST(0.032270754152261) }, { FRAC_CONST(0.000409263572030), FRAC_CONST(0.032272266266801) }, { FRAC_CONST(0.000303650824695), FRAC_CONST(0.032273432771295) }, { FRAC_CONST(0.000198034825504), FRAC_CONST(0.032274253653254) }, { FRAC_CONST(0.000092416705518), FRAC_CONST(0.032274728903884) } }; #ifdef LD_DEC /* 240 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_960[] = { { FRAC_CONST(0.045643531183573), FRAC_CONST(0.000037342034959) }, { FRAC_CONST(0.045642309173789), FRAC_CONST(0.000336075315362) }, { FRAC_CONST(0.045639131999390), FRAC_CONST(0.000634794199417) }, { FRAC_CONST(0.045633999796474), FRAC_CONST(0.000933485891002) }, { FRAC_CONST(0.045626912784890), FRAC_CONST(0.001232137595157) }, { FRAC_CONST(0.045617871268219), FRAC_CONST(0.001530736518639) }, { FRAC_CONST(0.045606875633772), FRAC_CONST(0.001829269870464) }, { FRAC_CONST(0.045593926352564), FRAC_CONST(0.002127724862455) }, { FRAC_CONST(0.045579023979299), FRAC_CONST(0.002426088709795) }, { FRAC_CONST(0.045562169152346), FRAC_CONST(0.002724348631569) }, { FRAC_CONST(0.045543362593709), FRAC_CONST(0.003022491851315) }, { FRAC_CONST(0.045522605108999), FRAC_CONST(0.003320505597570) }, { FRAC_CONST(0.045499897587396), FRAC_CONST(0.003618377104416) }, { FRAC_CONST(0.045475241001617), FRAC_CONST(0.003916093612031) }, { FRAC_CONST(0.045448636407866), FRAC_CONST(0.004213642367228) }, { FRAC_CONST(0.045420084945797), FRAC_CONST(0.004511010624011) }, { FRAC_CONST(0.045389587838458), FRAC_CONST(0.004808185644112) }, { FRAC_CONST(0.045357146392244), FRAC_CONST(0.005105154697544) }, { FRAC_CONST(0.045322761996840), FRAC_CONST(0.005401905063139) }, { FRAC_CONST(0.045286436125157), FRAC_CONST(0.005698424029100) }, { FRAC_CONST(0.045248170333275), FRAC_CONST(0.005994698893542) }, { FRAC_CONST(0.045207966260374), FRAC_CONST(0.006290716965035) }, { FRAC_CONST(0.045165825628663), FRAC_CONST(0.006586465563151) }, { FRAC_CONST(0.045121750243305), FRAC_CONST(0.006881932019003) }, { FRAC_CONST(0.045075741992343), FRAC_CONST(0.007177103675792) }, { FRAC_CONST(0.045027802846618), FRAC_CONST(0.007471967889347) }, { FRAC_CONST(0.044977934859683), FRAC_CONST(0.007766512028667) }, { FRAC_CONST(0.044926140167717), FRAC_CONST(0.008060723476460) }, { FRAC_CONST(0.044872420989432), FRAC_CONST(0.008354589629687) }, { FRAC_CONST(0.044816779625979), FRAC_CONST(0.008648097900101) }, { FRAC_CONST(0.044759218460849), FRAC_CONST(0.008941235714784) }, { FRAC_CONST(0.044699739959770), FRAC_CONST(0.009233990516688) }, { FRAC_CONST(0.044638346670603), FRAC_CONST(0.009526349765171) }, { FRAC_CONST(0.044575041223233), FRAC_CONST(0.009818300936537) }, { FRAC_CONST(0.044509826329454), FRAC_CONST(0.010109831524568) }, { FRAC_CONST(0.044442704782856), FRAC_CONST(0.010400929041064) }, { FRAC_CONST(0.044373679458701), FRAC_CONST(0.010691581016378) }, { FRAC_CONST(0.044302753313806), FRAC_CONST(0.010981774999945) }, { FRAC_CONST(0.044229929386409), FRAC_CONST(0.011271498560822) }, { FRAC_CONST(0.044155210796046), FRAC_CONST(0.011560739288214) }, { FRAC_CONST(0.044078600743413), FRAC_CONST(0.011849484792012) }, { FRAC_CONST(0.044000102510229), FRAC_CONST(0.012137722703321) }, { FRAC_CONST(0.043919719459097), FRAC_CONST(0.012425440674986) }, { FRAC_CONST(0.043837455033359), FRAC_CONST(0.012712626382127) }, { FRAC_CONST(0.043753312756950), FRAC_CONST(0.012999267522665) }, { FRAC_CONST(0.043667296234245), FRAC_CONST(0.013285351817848) }, { FRAC_CONST(0.043579409149906), FRAC_CONST(0.013570867012776) }, { FRAC_CONST(0.043489655268722), FRAC_CONST(0.013855800876928) }, { FRAC_CONST(0.043398038435451), FRAC_CONST(0.014140141204686) }, { FRAC_CONST(0.043304562574653), FRAC_CONST(0.014423875815857) }, { FRAC_CONST(0.043209231690524), FRAC_CONST(0.014706992556195) }, { FRAC_CONST(0.043112049866720), FRAC_CONST(0.014989479297920) }, { FRAC_CONST(0.043013021266188), FRAC_CONST(0.015271323940241) }, { FRAC_CONST(0.042912150130984), FRAC_CONST(0.015552514409871) }, { FRAC_CONST(0.042809440782090), FRAC_CONST(0.015833038661547) }, { FRAC_CONST(0.042704897619235), FRAC_CONST(0.016112884678543) }, { FRAC_CONST(0.042598525120698), FRAC_CONST(0.016392040473187) }, { FRAC_CONST(0.042490327843124), FRAC_CONST(0.016670494087374) }, { FRAC_CONST(0.042380310421324), FRAC_CONST(0.016948233593079) }, { FRAC_CONST(0.042268477568078), FRAC_CONST(0.017225247092864) }, { FRAC_CONST(0.042154834073934), FRAC_CONST(0.017501522720393) }, { FRAC_CONST(0.042039384807000), FRAC_CONST(0.017777048640940) }, { FRAC_CONST(0.041922134712739), FRAC_CONST(0.018051813051888) }, { FRAC_CONST(0.041803088813754), FRAC_CONST(0.018325804183247) }, { FRAC_CONST(0.041682252209576), FRAC_CONST(0.018599010298148) }, { FRAC_CONST(0.041559630076443), FRAC_CONST(0.018871419693350) }, { FRAC_CONST(0.041435227667079), FRAC_CONST(0.019143020699741) }, { FRAC_CONST(0.041309050310468), FRAC_CONST(0.019413801682838) }, { FRAC_CONST(0.041181103411629), FRAC_CONST(0.019683751043285) }, { FRAC_CONST(0.041051392451382), FRAC_CONST(0.019952857217350) }, { FRAC_CONST(0.040919922986111), FRAC_CONST(0.020221108677421) }, { FRAC_CONST(0.040786700647532), FRAC_CONST(0.020488493932496) }, { FRAC_CONST(0.040651731142446), FRAC_CONST(0.020755001528683) }, { FRAC_CONST(0.040515020252497), FRAC_CONST(0.021020620049682) }, { FRAC_CONST(0.040376573833925), FRAC_CONST(0.021285338117280) }, { FRAC_CONST(0.040236397817314), FRAC_CONST(0.021549144391836) }, { FRAC_CONST(0.040094498207337), FRAC_CONST(0.021812027572768) }, { FRAC_CONST(0.039950881082502), FRAC_CONST(0.022073976399034) }, { FRAC_CONST(0.039805552594888), FRAC_CONST(0.022334979649620) }, { FRAC_CONST(0.039658518969884), FRAC_CONST(0.022595026144014) }, { FRAC_CONST(0.039509786505922), FRAC_CONST(0.022854104742690) }, { FRAC_CONST(0.039359361574204), FRAC_CONST(0.023112204347583) }, { FRAC_CONST(0.039207250618434), FRAC_CONST(0.023369313902565) }, { FRAC_CONST(0.039053460154540), FRAC_CONST(0.023625422393919) }, { FRAC_CONST(0.038897996770393), FRAC_CONST(0.023880518850809) }, { FRAC_CONST(0.038740867125527), FRAC_CONST(0.024134592345752) }, { FRAC_CONST(0.038582077950852), FRAC_CONST(0.024387631995085) }, { FRAC_CONST(0.038421636048370), FRAC_CONST(0.024639626959432) }, { FRAC_CONST(0.038259548290876), FRAC_CONST(0.024890566444167) }, { FRAC_CONST(0.038095821621671), FRAC_CONST(0.025140439699877) }, { FRAC_CONST(0.037930463054261), FRAC_CONST(0.025389236022825) }, { FRAC_CONST(0.037763479672055), FRAC_CONST(0.025636944755403) }, { FRAC_CONST(0.037594878628068), FRAC_CONST(0.025883555286595) }, { FRAC_CONST(0.037424667144605), FRAC_CONST(0.026129057052425) }, { FRAC_CONST(0.037252852512960), FRAC_CONST(0.026373439536415) }, { FRAC_CONST(0.037079442093102), FRAC_CONST(0.026616692270033) }, { FRAC_CONST(0.036904443313354), FRAC_CONST(0.026858804833142) }, { FRAC_CONST(0.036727863670081), FRAC_CONST(0.027099766854444) }, { FRAC_CONST(0.036549710727369), FRAC_CONST(0.027339568011930) }, { FRAC_CONST(0.036369992116697), FRAC_CONST(0.027578198033315) }, { FRAC_CONST(0.036188715536611), FRAC_CONST(0.027815646696484) }, { FRAC_CONST(0.036005888752396), FRAC_CONST(0.028051903829926) }, { FRAC_CONST(0.035821519595745), FRAC_CONST(0.028286959313171) }, { FRAC_CONST(0.035635615964417), FRAC_CONST(0.028520803077226) }, { FRAC_CONST(0.035448185821906), FRAC_CONST(0.028753425105002) }, { FRAC_CONST(0.035259237197095), FRAC_CONST(0.028984815431745) }, { FRAC_CONST(0.035068778183914), FRAC_CONST(0.029214964145465) }, { FRAC_CONST(0.034876816940994), FRAC_CONST(0.029443861387355) }, { FRAC_CONST(0.034683361691315), FRAC_CONST(0.029671497352220) }, { FRAC_CONST(0.034488420721856), FRAC_CONST(0.029897862288892) }, { FRAC_CONST(0.034292002383240), FRAC_CONST(0.030122946500652) }, { FRAC_CONST(0.034094115089375), FRAC_CONST(0.030346740345641) }, { FRAC_CONST(0.033894767317093), FRAC_CONST(0.030569234237276) }, { FRAC_CONST(0.033693967605790), FRAC_CONST(0.030790418644658) }, { FRAC_CONST(0.033491724557057), FRAC_CONST(0.031010284092984) }, { FRAC_CONST(0.033288046834313), FRAC_CONST(0.031228821163949) }, { FRAC_CONST(0.033082943162434), FRAC_CONST(0.031446020496153) }, { FRAC_CONST(0.032876422327378), FRAC_CONST(0.031661872785500) }, { FRAC_CONST(0.032668493175811), FRAC_CONST(0.031876368785596) }, { FRAC_CONST(0.032459164614726), FRAC_CONST(0.032089499308145) }, { FRAC_CONST(0.032248445611061), FRAC_CONST(0.032301255223347) }, { FRAC_CONST(0.032036345191317), FRAC_CONST(0.032511627460281) }, { FRAC_CONST(0.031822872441171), FRAC_CONST(0.032720607007302) }, { FRAC_CONST(0.031608036505083), FRAC_CONST(0.032928184912422) }, { FRAC_CONST(0.031391846585912), FRAC_CONST(0.033134352283693) }, { FRAC_CONST(0.031174311944513), FRAC_CONST(0.033339100289593) }, { FRAC_CONST(0.030955441899347), FRAC_CONST(0.033542420159397) }, { FRAC_CONST(0.030735245826077), FRAC_CONST(0.033744303183559) }, { FRAC_CONST(0.030513733157171), FRAC_CONST(0.033944740714083) }, { FRAC_CONST(0.030290913381494), FRAC_CONST(0.034143724164891) }, { FRAC_CONST(0.030066796043904), FRAC_CONST(0.034341245012195) }, { FRAC_CONST(0.029841390744841), FRAC_CONST(0.034537294794860) }, { FRAC_CONST(0.029614707139919), FRAC_CONST(0.034731865114764) }, { FRAC_CONST(0.029386754939508), FRAC_CONST(0.034924947637164) }, { FRAC_CONST(0.029157543908322), FRAC_CONST(0.035116534091046) }, { FRAC_CONST(0.028927083864999), FRAC_CONST(0.035306616269485) }, { FRAC_CONST(0.028695384681680), FRAC_CONST(0.035495186029992) }, { FRAC_CONST(0.028462456283587), FRAC_CONST(0.035682235294866) }, { FRAC_CONST(0.028228308648598), FRAC_CONST(0.035867756051541) }, { FRAC_CONST(0.027992951806817), FRAC_CONST(0.036051740352923) }, { FRAC_CONST(0.027756395840148), FRAC_CONST(0.036234180317738) }, { FRAC_CONST(0.027518650881862), FRAC_CONST(0.036415068130865) }, { FRAC_CONST(0.027279727116161), FRAC_CONST(0.036594396043672) }, { FRAC_CONST(0.027039634777745), FRAC_CONST(0.036772156374348) }, { FRAC_CONST(0.026798384151369), FRAC_CONST(0.036948341508233) }, { FRAC_CONST(0.026555985571409), FRAC_CONST(0.037122943898140) }, { FRAC_CONST(0.026312449421412), FRAC_CONST(0.037295956064686) }, { FRAC_CONST(0.026067786133656), FRAC_CONST(0.037467370596605) }, { FRAC_CONST(0.025822006188702), FRAC_CONST(0.037637180151068) }, { FRAC_CONST(0.025575120114946), FRAC_CONST(0.037805377454000) }, { FRAC_CONST(0.025327138488165), FRAC_CONST(0.037971955300388) }, { FRAC_CONST(0.025078071931066), FRAC_CONST(0.038136906554591) }, { FRAC_CONST(0.024827931112832), FRAC_CONST(0.038300224150647) }, { FRAC_CONST(0.024576726748663), FRAC_CONST(0.038461901092573) }, { FRAC_CONST(0.024324469599317), FRAC_CONST(0.038621930454668) }, { FRAC_CONST(0.024071170470652), FRAC_CONST(0.038780305381806) }, { FRAC_CONST(0.023816840213160), FRAC_CONST(0.038937019089732) }, { FRAC_CONST(0.023561489721501), FRAC_CONST(0.039092064865353) }, { FRAC_CONST(0.023305129934041), FRAC_CONST(0.039245436067023) }, { FRAC_CONST(0.023047771832380), FRAC_CONST(0.039397126124832) }, { FRAC_CONST(0.022789426440883), FRAC_CONST(0.039547128540881) }, { FRAC_CONST(0.022530104826206), FRAC_CONST(0.039695436889566) }, { FRAC_CONST(0.022269818096825), FRAC_CONST(0.039842044817851) }, { FRAC_CONST(0.022008577402555), FRAC_CONST(0.039986946045542) }, { FRAC_CONST(0.021746393934081), FRAC_CONST(0.040130134365550) }, { FRAC_CONST(0.021483278922467), FRAC_CONST(0.040271603644166) }, { FRAC_CONST(0.021219243638687), FRAC_CONST(0.040411347821316) }, { FRAC_CONST(0.020954299393132), FRAC_CONST(0.040549360910825) }, { FRAC_CONST(0.020688457535133), FRAC_CONST(0.040685637000671) }, { FRAC_CONST(0.020421729452469), FRAC_CONST(0.040820170253240) }, { FRAC_CONST(0.020154126570884), FRAC_CONST(0.040952954905576) }, { FRAC_CONST(0.019885660353596), FRAC_CONST(0.041083985269625) }, { FRAC_CONST(0.019616342300802), FRAC_CONST(0.041213255732484) }, { FRAC_CONST(0.019346183949192), FRAC_CONST(0.041340760756635) }, { FRAC_CONST(0.019075196871451), FRAC_CONST(0.041466494880189) }, { FRAC_CONST(0.018803392675763), FRAC_CONST(0.041590452717113) }, { FRAC_CONST(0.018530783005316), FRAC_CONST(0.041712628957466) }, { FRAC_CONST(0.018257379537800), FRAC_CONST(0.041833018367625) }, { FRAC_CONST(0.017983193984910), FRAC_CONST(0.041951615790509) }, { FRAC_CONST(0.017708238091842), FRAC_CONST(0.042068416145797) }, { FRAC_CONST(0.017432523636792), FRAC_CONST(0.042183414430153) }, { FRAC_CONST(0.017156062430449), FRAC_CONST(0.042296605717432) }, { FRAC_CONST(0.016878866315491), FRAC_CONST(0.042407985158896) }, { FRAC_CONST(0.016600947166078), FRAC_CONST(0.042517547983420) }, { FRAC_CONST(0.016322316887341), FRAC_CONST(0.042625289497698) }, { FRAC_CONST(0.016042987414872), FRAC_CONST(0.042731205086442) }, { FRAC_CONST(0.015762970714219), FRAC_CONST(0.042835290212581) }, { FRAC_CONST(0.015482278780363), FRAC_CONST(0.042937540417454) }, { FRAC_CONST(0.015200923637213), FRAC_CONST(0.043037951321002) }, { FRAC_CONST(0.014918917337087), FRAC_CONST(0.043136518621958) }, { FRAC_CONST(0.014636271960196), FRAC_CONST(0.043233238098025) }, { FRAC_CONST(0.014352999614128), FRAC_CONST(0.043328105606063) }, { FRAC_CONST(0.014069112433327), FRAC_CONST(0.043421117082265) }, { FRAC_CONST(0.013784622578575), FRAC_CONST(0.043512268542327) }, { FRAC_CONST(0.013499542236471), FRAC_CONST(0.043601556081625) }, { FRAC_CONST(0.013213883618907), FRAC_CONST(0.043688975875378) }, { FRAC_CONST(0.012927658962548), FRAC_CONST(0.043774524178812) }, { FRAC_CONST(0.012640880528305), FRAC_CONST(0.043858197327323) }, { FRAC_CONST(0.012353560600813), FRAC_CONST(0.043939991736633) }, { FRAC_CONST(0.012065711487901), FRAC_CONST(0.044019903902940) }, { FRAC_CONST(0.011777345520066), FRAC_CONST(0.044097930403073) }, { FRAC_CONST(0.011488475049948), FRAC_CONST(0.044174067894638) }, { FRAC_CONST(0.011199112451794), FRAC_CONST(0.044248313116156) }, { FRAC_CONST(0.010909270120937), FRAC_CONST(0.044320662887211) }, { FRAC_CONST(0.010618960473257), FRAC_CONST(0.044391114108577) }, { FRAC_CONST(0.010328195944653), FRAC_CONST(0.044459663762361) }, { FRAC_CONST(0.010036988990509), FRAC_CONST(0.044526308912122) }, { FRAC_CONST(0.009745352085163), FRAC_CONST(0.044591046703005) }, { FRAC_CONST(0.009453297721368), FRAC_CONST(0.044653874361857) }, { FRAC_CONST(0.009160838409762), FRAC_CONST(0.044714789197351) }, { FRAC_CONST(0.008867986678328), FRAC_CONST(0.044773788600099) }, { FRAC_CONST(0.008574755071860), FRAC_CONST(0.044830870042761) }, { FRAC_CONST(0.008281156151424), FRAC_CONST(0.044886031080160) }, { FRAC_CONST(0.007987202493820), FRAC_CONST(0.044939269349379) }, { FRAC_CONST(0.007692906691044), FRAC_CONST(0.044990582569869) }, { FRAC_CONST(0.007398281349750), FRAC_CONST(0.045039968543542) }, { FRAC_CONST(0.007103339090706), FRAC_CONST(0.045087425154868) }, { FRAC_CONST(0.006808092548258), FRAC_CONST(0.045132950370962) }, { FRAC_CONST(0.006512554369783), FRAC_CONST(0.045176542241676) }, { FRAC_CONST(0.006216737215155), FRAC_CONST(0.045218198899680) }, { FRAC_CONST(0.005920653756196), FRAC_CONST(0.045257918560541) }, { FRAC_CONST(0.005624316676135), FRAC_CONST(0.045295699522801) }, { FRAC_CONST(0.005327738669067), FRAC_CONST(0.045331540168049) }, { FRAC_CONST(0.005030932439406), FRAC_CONST(0.045365438960992) }, { FRAC_CONST(0.004733910701344), FRAC_CONST(0.045397394449517) }, { FRAC_CONST(0.004436686178303), FRAC_CONST(0.045427405264758) }, { FRAC_CONST(0.004139271602393), FRAC_CONST(0.045455470121152) }, { FRAC_CONST(0.003841679713863), FRAC_CONST(0.045481587816494) }, { FRAC_CONST(0.003543923260561), FRAC_CONST(0.045505757231988) }, { FRAC_CONST(0.003246014997382), FRAC_CONST(0.045527977332297) }, { FRAC_CONST(0.002947967685724), FRAC_CONST(0.045548247165585) }, { FRAC_CONST(0.002649794092941), FRAC_CONST(0.045566565863562) }, { FRAC_CONST(0.002351506991799), FRAC_CONST(0.045582932641515) }, { FRAC_CONST(0.002053119159924), FRAC_CONST(0.045597346798344) }, { FRAC_CONST(0.001754643379257), FRAC_CONST(0.045609807716597) }, { FRAC_CONST(0.001456092435508), FRAC_CONST(0.045620314862489) }, { FRAC_CONST(0.001157479117605), FRAC_CONST(0.045628867785927) }, { FRAC_CONST(0.000858816217149), FRAC_CONST(0.045635466120535) }, { FRAC_CONST(0.000560116527865), FRAC_CONST(0.045640109583661) }, { FRAC_CONST(0.000261392845053), FRAC_CONST(0.045642797976394) } }; #endif // LD_DEC /* 60 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_240[] = { { FRAC_CONST(0.091286604111815), FRAC_CONST(0.000298735779793) }, { FRAC_CONST(0.091247502481454), FRAC_CONST(0.002688238127538) }, { FRAC_CONST(0.091145864370807), FRAC_CONST(0.005075898091152) }, { FRAC_CONST(0.090981759437558), FRAC_CONST(0.007460079287760) }, { FRAC_CONST(0.090755300151030), FRAC_CONST(0.009839147718664) }, { FRAC_CONST(0.090466641715108), FRAC_CONST(0.012211472889198) }, { FRAC_CONST(0.090115981961863), FRAC_CONST(0.014575428926191) }, { FRAC_CONST(0.089703561215976), FRAC_CONST(0.016929395692256) }, { FRAC_CONST(0.089229662130024), FRAC_CONST(0.019271759896156) }, { FRAC_CONST(0.088694609490769), FRAC_CONST(0.021600916198470) }, { FRAC_CONST(0.088098769996564), FRAC_CONST(0.023915268311810) }, { FRAC_CONST(0.087442552006035), FRAC_CONST(0.026213230094844) }, { FRAC_CONST(0.086726405258214), FRAC_CONST(0.028493226639351) }, { FRAC_CONST(0.085950820564309), FRAC_CONST(0.030753695349588) }, { FRAC_CONST(0.085116329471329), FRAC_CONST(0.032993087013213) }, { FRAC_CONST(0.084223503897785), FRAC_CONST(0.035209866863042) }, { FRAC_CONST(0.083272955741727), FRAC_CONST(0.037402515628894) }, { FRAC_CONST(0.082265336461381), FRAC_CONST(0.039569530578832) }, { FRAC_CONST(0.081201336628670), FRAC_CONST(0.041709426549053) }, { FRAC_CONST(0.080081685455930), FRAC_CONST(0.043820736961749) }, { FRAC_CONST(0.078907150296148), FRAC_CONST(0.045902014830227) }, { FRAC_CONST(0.077678536117054), FRAC_CONST(0.047951833750597) }, { FRAC_CONST(0.076396684949434), FRAC_CONST(0.049968788879362) }, { FRAC_CONST(0.075062475310050), FRAC_CONST(0.051951497896226) }, { FRAC_CONST(0.073676821599542), FRAC_CONST(0.053898601951466) }, { FRAC_CONST(0.072240673475749), FRAC_CONST(0.055808766597225) }, { FRAC_CONST(0.070755015202858), FRAC_CONST(0.057680682702068) }, { FRAC_CONST(0.069220864976840), FRAC_CONST(0.059513067348201) }, { FRAC_CONST(0.067639274227625), FRAC_CONST(0.061304664710718) }, { FRAC_CONST(0.066011326898512), FRAC_CONST(0.063054246918278) }, { FRAC_CONST(0.064338138703282), FRAC_CONST(0.064760614894630) }, { FRAC_CONST(0.062620856361546), FRAC_CONST(0.066422599180399) }, { FRAC_CONST(0.060860656812842), FRAC_CONST(0.068039060734572) }, { FRAC_CONST(0.059058746410016), FRAC_CONST(0.069608891715145) }, { FRAC_CONST(0.057216360092450), FRAC_CONST(0.071131016238378) }, { FRAC_CONST(0.055334760539699), FRAC_CONST(0.072604391116154) }, { FRAC_CONST(0.053415237306106), FRAC_CONST(0.074028006570930) }, { FRAC_CONST(0.051459105937014), FRAC_CONST(0.075400886927784) }, { FRAC_CONST(0.049467707067153), FRAC_CONST(0.076722091283096) }, { FRAC_CONST(0.047442405501835), FRAC_CONST(0.077990714149396) }, { FRAC_CONST(0.045384589281588), FRAC_CONST(0.079205886075941) }, { FRAC_CONST(0.043295668730857), FRAC_CONST(0.080366774244592) }, { FRAC_CONST(0.041177075491445), FRAC_CONST(0.081472583040586) }, { FRAC_CONST(0.039030261541332), FRAC_CONST(0.082522554597810) }, { FRAC_CONST(0.036856698199564), FRAC_CONST(0.083515969318206) }, { FRAC_CONST(0.034657875117883), FRAC_CONST(0.084452146364948) }, { FRAC_CONST(0.032435299259796), FRAC_CONST(0.085330444129049) }, { FRAC_CONST(0.030190493867775), FRAC_CONST(0.086150260669096) }, { FRAC_CONST(0.027924997419306), FRAC_CONST(0.086911034123781) }, { FRAC_CONST(0.025640362572491), FRAC_CONST(0.087612243096981) }, { FRAC_CONST(0.023338155101933), FRAC_CONST(0.088253407015092) }, { FRAC_CONST(0.021019952825636), FRAC_CONST(0.088834086456390) }, { FRAC_CONST(0.018687344523641), FRAC_CONST(0.089353883452193) }, { FRAC_CONST(0.016341928849164), FRAC_CONST(0.089812441759604) }, { FRAC_CONST(0.013985313232951), FRAC_CONST(0.090209447105664) }, { FRAC_CONST(0.011619112781631), FRAC_CONST(0.090544627402740) }, { FRAC_CONST(0.009244949170797), FRAC_CONST(0.090817752935000) }, { FRAC_CONST(0.006864449533597), FRAC_CONST(0.091028636515846) }, { FRAC_CONST(0.004479245345574), FRAC_CONST(0.091177133616206) }, { FRAC_CONST(0.002090971306534), FRAC_CONST(0.091263142463585) } }; #endif // ALLOW_SMALL_FRAMELENGTH #ifdef SSR_DEC /* 128 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_512[] = { { FRAC_CONST(0.062499926465731), FRAC_CONST(0.000095873761643) }, { FRAC_CONST(0.062494043817678), FRAC_CONST(0.000862836783004) }, { FRAC_CONST(0.062478749796497), FRAC_CONST(0.001629669864319) }, { FRAC_CONST(0.062454046705412), FRAC_CONST(0.002396257523347) }, { FRAC_CONST(0.062419938264617), FRAC_CONST(0.003162484314806) }, { FRAC_CONST(0.062376429610718), FRAC_CONST(0.003928234847760) }, { FRAC_CONST(0.062323527295958), FRAC_CONST(0.004693393802995) }, { FRAC_CONST(0.062261239287231), FRAC_CONST(0.005457845950387) }, { FRAC_CONST(0.062189574964882), FRAC_CONST(0.006221476166254) }, { FRAC_CONST(0.062108545121295), FRAC_CONST(0.006984169450695) }, { FRAC_CONST(0.062018161959266), FRAC_CONST(0.007745810944907) }, { FRAC_CONST(0.061918439090167), FRAC_CONST(0.008506285948482) }, { FRAC_CONST(0.061809391531894), FRAC_CONST(0.009265479936681) }, { FRAC_CONST(0.061691035706609), FRAC_CONST(0.010023278577683) }, { FRAC_CONST(0.061563389438265), FRAC_CONST(0.010779567749800) }, { FRAC_CONST(0.061426471949919), FRAC_CONST(0.011534233558664) }, { FRAC_CONST(0.061280303860842), FRAC_CONST(0.012287162354380) }, { FRAC_CONST(0.061124907183410), FRAC_CONST(0.013038240748641) }, { FRAC_CONST(0.060960305319791), FRAC_CONST(0.013787355631805) }, { FRAC_CONST(0.060786523058421), FRAC_CONST(0.014534394189923) }, { FRAC_CONST(0.060603586570268), FRAC_CONST(0.015279243921739) }, { FRAC_CONST(0.060411523404896), FRAC_CONST(0.016021792655621) }, { FRAC_CONST(0.060210362486310), FRAC_CONST(0.016761928566463) }, { FRAC_CONST(0.060000134108604), FRAC_CONST(0.017499540192517) }, { FRAC_CONST(0.059780869931400), FRAC_CONST(0.018234516452187) }, { FRAC_CONST(0.059552602975075), FRAC_CONST(0.018966746660751) }, { FRAC_CONST(0.059315367615794), FRAC_CONST(0.019696120547033) }, { FRAC_CONST(0.059069199580329), FRAC_CONST(0.020422528270008) }, { FRAC_CONST(0.058814135940681), FRAC_CONST(0.021145860435346) }, { FRAC_CONST(0.058550215108495), FRAC_CONST(0.021866008111883) }, { FRAC_CONST(0.058277476829279), FRAC_CONST(0.022582862848028) }, { FRAC_CONST(0.057995962176414), FRAC_CONST(0.023296316688095) }, { FRAC_CONST(0.057705713544970), FRAC_CONST(0.024006262188558) }, { FRAC_CONST(0.057406774645326), FRAC_CONST(0.024712592434239) }, { FRAC_CONST(0.057099190496578), FRAC_CONST(0.025415201054398) }, { FRAC_CONST(0.056783007419769), FRAC_CONST(0.026113982238763) }, { FRAC_CONST(0.056458273030907), FRAC_CONST(0.026808830753458) }, { FRAC_CONST(0.056125036233796), FRAC_CONST(0.027499641956852) }, { FRAC_CONST(0.055783347212673), FRAC_CONST(0.028186311815319) }, { FRAC_CONST(0.055433257424646), FRAC_CONST(0.028868736918904) }, { FRAC_CONST(0.055074819591951), FRAC_CONST(0.029546814496896) }, { FRAC_CONST(0.054708087694007), FRAC_CONST(0.030220442433307) }, { FRAC_CONST(0.054333116959288), FRAC_CONST(0.030889519282247) }, { FRAC_CONST(0.053949963857008), FRAC_CONST(0.031553944283204) }, { FRAC_CONST(0.053558686088614), FRAC_CONST(0.032213617376216) }, { FRAC_CONST(0.053159342579100), FRAC_CONST(0.032868439216943) }, { FRAC_CONST(0.052751993468129), FRAC_CONST(0.033518311191623) }, { FRAC_CONST(0.052336700100979), FRAC_CONST(0.034163135431927) }, { FRAC_CONST(0.051913525019303), FRAC_CONST(0.034802814829698) }, { FRAC_CONST(0.051482531951712), FRAC_CONST(0.035437253051569) }, { FRAC_CONST(0.051043785804177), FRAC_CONST(0.036066354553480) }, { FRAC_CONST(0.050597352650253), FRAC_CONST(0.036690024595057) }, { FRAC_CONST(0.050143299721132), FRAC_CONST(0.037308169253887) }, { FRAC_CONST(0.049681695395515), FRAC_CONST(0.037920695439658) }, { FRAC_CONST(0.049212609189314), FRAC_CONST(0.038527510908178) }, { FRAC_CONST(0.048736111745188), FRAC_CONST(0.039128524275271) }, { FRAC_CONST(0.048252274821899), FRAC_CONST(0.039723645030535) }, { FRAC_CONST(0.047761171283507), FRAC_CONST(0.040312783550971) }, { FRAC_CONST(0.047262875088400), FRAC_CONST(0.040895851114488) }, { FRAC_CONST(0.046757461278150), FRAC_CONST(0.041472759913252) }, { FRAC_CONST(0.046245005966220), FRAC_CONST(0.042043423066923) }, { FRAC_CONST(0.045725586326493), FRAC_CONST(0.042607754635728) }, { FRAC_CONST(0.045199280581658), FRAC_CONST(0.043165669633408) }, { FRAC_CONST(0.044666167991423), FRAC_CONST(0.043717084040018) }, { FRAC_CONST(0.044126328840584), FRAC_CONST(0.044261914814575) }, { FRAC_CONST(0.043579844426930), FRAC_CONST(0.044800079907569) }, { FRAC_CONST(0.043026797049006), FRAC_CONST(0.045331498273316) }, { FRAC_CONST(0.042467269993710), FRAC_CONST(0.045856089882166) }, { FRAC_CONST(0.041901347523761), FRAC_CONST(0.046373775732552) }, { FRAC_CONST(0.041329114865000), FRAC_CONST(0.046884477862888) }, { FRAC_CONST(0.040750658193560), FRAC_CONST(0.047388119363313) }, { FRAC_CONST(0.040166064622889), FRAC_CONST(0.047884624387270) }, { FRAC_CONST(0.039575422190629), FRAC_CONST(0.048373918162926) }, { FRAC_CONST(0.038978819845356), FRAC_CONST(0.048855927004441) }, { FRAC_CONST(0.038376347433190), FRAC_CONST(0.049330578323055) }, { FRAC_CONST(0.037768095684260), FRAC_CONST(0.049797800638026) }, { FRAC_CONST(0.037154156199042), FRAC_CONST(0.050257523587392) }, { FRAC_CONST(0.036534621434563), FRAC_CONST(0.050709677938566) }, { FRAC_CONST(0.035909584690482), FRAC_CONST(0.051154195598769) }, { FRAC_CONST(0.035279140095032), FRAC_CONST(0.051591009625274) }, { FRAC_CONST(0.034643382590851), FRAC_CONST(0.052020054235496) }, { FRAC_CONST(0.034002407920680), FRAC_CONST(0.052441264816895) }, { FRAC_CONST(0.033356312612947), FRAC_CONST(0.052854577936706) }, { FRAC_CONST(0.032705193967229), FRAC_CONST(0.053259931351495) }, { FRAC_CONST(0.032049150039598), FRAC_CONST(0.053657264016528) }, { FRAC_CONST(0.031388279627857), FRAC_CONST(0.054046516094966) }, { FRAC_CONST(0.030722682256659), FRAC_CONST(0.054427628966880) }, { FRAC_CONST(0.030052458162521), FRAC_CONST(0.054800545238072) }, { FRAC_CONST(0.029377708278725), FRAC_CONST(0.055165208748723) }, { FRAC_CONST(0.028698534220122), FRAC_CONST(0.055521564581850) }, { FRAC_CONST(0.028015038267826), FRAC_CONST(0.055869559071575) }, { FRAC_CONST(0.027327323353815), FRAC_CONST(0.056209139811209) }, { FRAC_CONST(0.026635493045425), FRAC_CONST(0.056540255661140) }, { FRAC_CONST(0.025939651529755), FRAC_CONST(0.056862856756541) }, { FRAC_CONST(0.025239903597978), FRAC_CONST(0.057176894514872) }, { FRAC_CONST(0.024536354629559), FRAC_CONST(0.057482321643202) }, { FRAC_CONST(0.023829110576385), FRAC_CONST(0.057779092145329) }, { FRAC_CONST(0.023118277946808), FRAC_CONST(0.058067161328707) }, { FRAC_CONST(0.022403963789609), FRAC_CONST(0.058346485811177) }, { FRAC_CONST(0.021686275677870), FRAC_CONST(0.058617023527499) }, { FRAC_CONST(0.020965321692783), FRAC_CONST(0.058878733735689) }, { FRAC_CONST(0.020241210407366), FRAC_CONST(0.059131577023150) }, { FRAC_CONST(0.019514050870114), FRAC_CONST(0.059375515312615) }, { FRAC_CONST(0.018783952588580), FRAC_CONST(0.059610511867874) }, { FRAC_CONST(0.018051025512878), FRAC_CONST(0.059836531299311) }, { FRAC_CONST(0.017315380019131), FRAC_CONST(0.060053539569230) }, { FRAC_CONST(0.016577126892844), FRAC_CONST(0.060261503996984) }, { FRAC_CONST(0.015836377312223), FRAC_CONST(0.060460393263896) }, { FRAC_CONST(0.015093242831429), FRAC_CONST(0.060650177417972) }, { FRAC_CONST(0.014347835363782), FRAC_CONST(0.060830827878419) }, { FRAC_CONST(0.013600267164905), FRAC_CONST(0.061002317439940) }, { FRAC_CONST(0.012850650815819), FRAC_CONST(0.061164620276839) }, { FRAC_CONST(0.012099099205988), FRAC_CONST(0.061317711946905) }, { FRAC_CONST(0.011345725516320), FRAC_CONST(0.061461569395097) }, { FRAC_CONST(0.010590643202123), FRAC_CONST(0.061596170957011) }, { FRAC_CONST(0.009833965976015), FRAC_CONST(0.061721496362147) }, { FRAC_CONST(0.009075807790803), FRAC_CONST(0.061837526736961) }, { FRAC_CONST(0.008316282822321), FRAC_CONST(0.061944244607705) }, { FRAC_CONST(0.007555505452236), FRAC_CONST(0.062041633903059) }, { FRAC_CONST(0.006793590250821), FRAC_CONST(0.062129679956555) }, { FRAC_CONST(0.006030651959703), FRAC_CONST(0.062208369508780) }, { FRAC_CONST(0.005266805474583), FRAC_CONST(0.062277690709378) }, { FRAC_CONST(0.004502165827931), FRAC_CONST(0.062337633118830) }, { FRAC_CONST(0.003736848171665), FRAC_CONST(0.062388187710030) }, { FRAC_CONST(0.002970967759810), FRAC_CONST(0.062429346869643) }, { FRAC_CONST(0.002204639931138), FRAC_CONST(0.062461104399250) }, { FRAC_CONST(0.001437980091802), FRAC_CONST(0.062483455516285) }, { FRAC_CONST(0.000671103697954), FRAC_CONST(0.062496396854751) } }; /* 16 (N/4) complex twiddle factors */ ALIGN static const complex_t mdct_tab_64[] = { { FRAC_CONST(0.176763384336599), FRAC_CONST(0.002169321984356) }, { FRAC_CONST(0.175699589589310), FRAC_CONST(0.019484717553714) }, { FRAC_CONST(0.172943711747111), FRAC_CONST(0.036612464641599) }, { FRAC_CONST(0.168522291420137), FRAC_CONST(0.053387613680577) }, { FRAC_CONST(0.162477909303132), FRAC_CONST(0.069648610815172) }, { FRAC_CONST(0.154868776100077), FRAC_CONST(0.085238853753814) }, { FRAC_CONST(0.145768171923295), FRAC_CONST(0.100008199934509) }, { FRAC_CONST(0.135263740565902), FRAC_CONST(0.113814412479792) }, { FRAC_CONST(0.123456645444178), FRAC_CONST(0.126524530015608) }, { FRAC_CONST(0.110460595338559), FRAC_CONST(0.138016147162030) }, { FRAC_CONST(0.096400749315926), FRAC_CONST(0.148178593363981) }, { FRAC_CONST(0.081412511379371), FRAC_CONST(0.156913998709178) }, { FRAC_CONST(0.065640226453626), FRAC_CONST(0.164138236468888) }, { FRAC_CONST(0.049235790264535), FRAC_CONST(0.169781733284316) }, { FRAC_CONST(0.032357186500177), FRAC_CONST(0.173790139196080) }, { FRAC_CONST(0.015166965341583), FRAC_CONST(0.176124851064031) } }; #endif // SSR_DEC #endif // FIXED_POINT #ifdef __cplusplus } #endif #endif
apache-2.0
Guavus/hbase
hbase-it/src/test/java/org/apache/hadoop/hbase/chaos/actions/RestartRandomRsAction.java
1416
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.chaos.actions; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.chaos.monkies.PolicyBasedChaosMonkey; /** * Action that restarts a random HRegionServer */ public class RestartRandomRsAction extends RestartActionBaseAction { public RestartRandomRsAction(long sleepTime) { super(sleepTime); } @Override public void perform() throws Exception { LOG.info("Performing action: Restart random region server"); ServerName server = PolicyBasedChaosMonkey.selectRandomItem(getCurrentServers()); restartRs(server, sleepTime); } }
apache-2.0
slaff/jerryscript
tests/jerry-test-suite/11/11.07/11.07.02/11.07.02-003.js
674
// Copyright JS Foundation and other contributors, http://js.foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var a = 20; var b = a >> "2"; assert(b == 5)
apache-2.0
jsdosa/TizenRT
os/board/sidk_s5jt200/include/s5jt200_partitions.h
6805
/**************************************************************************** * * Copyright 2016 Samsung Electronics 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. * ****************************************************************************/ #ifndef __ARCH_ARM_SRC_SIDK_S5JT200_INCLUDE_S5JT200_PARTITIONS_H #define __ARCH_ARM_SRC_SIDK_S5JT200_INCLUDE_S5JT200_PARTITIONS_H /****************************************************************************** * Included Files *****************************************************************************/ #include <tinyara/config.h> /****************************************************************************** * Pre-processor Definitions *****************************************************************************/ #define MTD_SFLASH_ADDR (0x04000000) // SFLASH PHY ADDR #define MTD_SFLASH_SIZE (8 * 1024 * 1024) // 8MB Fixed Size #define MTD_1K_SIZE (1024) #define MTD_SFLASH_ERASE_SIZE (64 * 1024) // 64K /* Align flash partition size to erase size(multiple of erase size) */ #define MTD_FLASH_ALIGN_SIZE(size, align) ((((size) + (align - 1)) / align) * align) /* Note : All partition size must be aligned to MTD_SFLASH_ERASE_SIZE */ /* execept below partition's from BL1 -> OTA1 which are fixed for flashing binaries */ /* FLASH Partition Layout */ /* +---------------+ | BL1 | | (16 KB) | +---------------+ | OTA0 (OS) | | (2MB + 960KB) | +---------------+ | LED F/W | | (32KB) | +---------------+ | SSS F/W | | (32 KB) | +---------------+ | WLAN F/W | | (752 KB) | +---------------+ | SSS KEY | | (256KB) | +---------------+ | OTA1(NEW OS) | | (2MB) | +---------------+ | ROMFS | | (512 KB) | +---------------+ | SMARTFS | | (1MB + 320KB) | +---------------+ | RAMDUMP | | (64KB) | +---------------+ | COREDUMP | | (64KB) | +---------------+ | NV | | (32KB) | +---------------+ | BOOTPARAM | | (32KB) | +---------------+ */ /********************* Partition Size's ***************************************/ #define MTD_BLK_MASTER_SIZE MTD_SFLASH_SIZE #define MTD_BLK_BOOTLDR_SIZE (16 * MTD_1K_SIZE) #define MTD_BLK_OTA0_SIZE (3008 * MTD_1K_SIZE) #define MTD_BLK_LEDFW_SIZE (32 * MTD_1K_SIZE) #define MTD_BLK_SSSFW_SIZE (32 * MTD_1K_SIZE) #define MTD_BLK_WLANFW_SIZE (752 * MTD_1K_SIZE) #define MTD_BLK_SSSKEY_SIZE (256 * MTD_1K_SIZE) #define MTD_BLK_OTA1_SIZE (2608 * MTD_1K_SIZE) /* Align above total partition size to multiple of erase size */ #define TOTAL_ALIGNED_SIZE MTD_FLASH_ALIGN_SIZE((MTD_BLK_BOOTLDR_SIZE + \ MTD_BLK_OTA0_SIZE + MTD_BLK_LEDFW_SIZE + \ MTD_BLK_SSSFW_SIZE + MTD_BLK_WLANFW_SIZE + \ MTD_BLK_SSSKEY_SIZE + MTD_BLK_OTA1_SIZE), \ MTD_SFLASH_ERASE_SIZE) #if defined(CONFIG_FS_ROMFS) #define MTD_BLK_ROMFS_SIZE MTD_FLASH_ALIGN_SIZE((512 * MTD_1K_SIZE), \ MTD_SFLASH_ERASE_SIZE) #else #define MTD_BLK_ROMFS_SIZE MTD_FLASH_ALIGN_SIZE((0 * MTD_1K_SIZE), \ MTD_SFLASH_ERASE_SIZE) #endif #define MTD_BLK_RAMDUMP_SIZE MTD_FLASH_ALIGN_SIZE((0 * MTD_1K_SIZE), \ MTD_SFLASH_ERASE_SIZE) #if defined(CONFIG_BOARD_COREDUMP_FLASH) #define MTD_BLK_COREDUMP_SIZE MTD_FLASH_ALIGN_SIZE((64 * MTD_1K_SIZE), \ MTD_SFLASH_ERASE_SIZE) #else #define MTD_BLK_COREDUMP_SIZE MTD_FLASH_ALIGN_SIZE((0 * MTD_1K_SIZE), \ MTD_SFLASH_ERASE_SIZE) #endif #define MTD_BLK_NV_SIZE MTD_FLASH_ALIGN_SIZE((32 * MTD_1K_SIZE), \ (32 * MTD_1K_SIZE)) #define MTD_BLK_BOOTPARAM_SIZE MTD_FLASH_ALIGN_SIZE((32 * MTD_1K_SIZE), \ (32 * MTD_1K_SIZE)) /* Note: Both NV and BOOTPARAM share the last 64KB partition */ /* Align both partition to 32K address */ /* For smartfs, use remainging size */ #define MTD_BLK_SMARTFS_SIZE (MTD_SFLASH_SIZE - (TOTAL_ALIGNED_SIZE + \ MTD_BLK_ROMFS_SIZE + MTD_BLK_RAMDUMP_SIZE + \ MTD_BLK_COREDUMP_SIZE + MTD_BLK_NV_SIZE + \ MTD_BLK_BOOTPARAM_SIZE)) /********************* End of Partition Size's ***********************************/ /********************* Partition Start Offset's ***********************************/ /* Partition[0] : MASTER, SIZE = 8MB */ #define MTD_BLK_MASTER_START (0x0) /* Partition[1] : BOOTLOADER, SIZE = 16KB */ #define MTD_BLK_BOOTLDR_START (0x0) /* Partition[2] : OTA0 (OS), SIZE = 2MB + 960KB*/ #define MTD_BLK_OTA0_START (MTD_BLK_BOOTLDR_START + MTD_BLK_BOOTLDR_SIZE) /* Partition[3] : LED FW, SIZE = 32KB */ #define MTD_BLK_LEDFW_START (MTD_BLK_OTA0_START + MTD_BLK_OTA0_SIZE) /* Partition[4] : SSS FW, SIZE = 32KB */ #define MTD_BLK_SSSFW_START (MTD_BLK_LEDFW_START + MTD_BLK_LEDFW_SIZE) /* Partition[5] : WLAN FW, SIZE = 752KB */ #define MTD_BLK_WLANFW_START (MTD_BLK_SSSFW_START + MTD_BLK_SSSFW_SIZE) /* Partition[6] : SSS KEY, SIZE = 256KB */ #define MTD_BLK_SSSKEY_START (MTD_BLK_WLANFW_START + MTD_BLK_WLANFW_SIZE) /* Partition[7] : OTA1 (OS), SIZE = 2MB */ #define MTD_BLK_OTA1_START (MTD_BLK_SSSKEY_START + MTD_BLK_SSSKEY_SIZE) /* Need ERASE_SIZE aligned partitions from here */ /* Partition[8] : RESOURCE, SIZE = 0K */ #define MTD_BLK_ROMFS_START (MTD_BLK_BOOTLDR_START + TOTAL_ALIGNED_SIZE) /* Partition[9] : SMAERFS, SIZE = 1MB + 320K */ #define MTD_BLK_SMARTFS_START (MTD_BLK_ROMFS_START + MTD_BLK_ROMFS_SIZE) /* Partition[10] : RAMDUMP, SIZE = 0K */ #define MTD_BLK_RAMDUMP_START (MTD_BLK_SMARTFS_START + MTD_BLK_SMARTFS_SIZE) /* Partition[11] : COREDUMP, SIZE = 0K */ #define MTD_BLK_COREDUMP_START (MTD_BLK_RAMDUMP_START + MTD_BLK_RAMDUMP_SIZE) /* Partition[12] : NV, SIZE = 32K */ #define MTD_BLK_NV_START (MTD_BLK_COREDUMP_START + MTD_BLK_COREDUMP_SIZE) /* Partition[13] : BOOTPARAM, SIZE = 32K */ #define MTD_BLK_BOOTPARAM_START (MTD_BLK_NV_START + MTD_BLK_NV_SIZE) /********************* End of Partition Start Offset's ****************************/ #endif /* __ARCH_ARM_SRC_SIDK_S5JT200_INCLUDE_S5JT200_PARTITIONS_H */
apache-2.0
GlenRSmith/elasticsearch
plugins/examples/custom-settings/src/test/java/org/elasticsearch/example/customsettings/ExampleCustomSettingsConfigTests.java
1583
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.example.customsettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.test.ESTestCase; import static org.elasticsearch.example.customsettings.ExampleCustomSettingsConfig.VALIDATED_SETTING; /** * {@link ExampleCustomSettingsConfigTests} is a unit test class for {@link ExampleCustomSettingsConfig}. * <p> * It's a JUnit test class that extends {@link ESTestCase} which provides useful methods for testing. * <p> * The tests can be executed in the IDE or using the command: ./gradlew :example-plugins:custom-settings:test */ public class ExampleCustomSettingsConfigTests extends ESTestCase { public void testValidatedSetting() { final String expected = randomAlphaOfLengthBetween(1, 5); final String actual = VALIDATED_SETTING.get(Settings.builder().put(VALIDATED_SETTING.getKey(), expected).build()); assertEquals(expected, actual); final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> VALIDATED_SETTING.get(Settings.builder().put("custom.validated", "it's forbidden").build())); assertEquals("Setting must not contain [forbidden]", exception.getMessage()); } }
apache-2.0
GlenRSmith/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/package-info.java
490
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ /** * Contains the action definitions for SLM. For the transport and rest action implementations, please see the {@code ilm} module's * {@code org.elasticsearch.xpack.slm} package. */ package org.elasticsearch.xpack.core.slm.action;
apache-2.0
espadrine/opera
chromium/src/chrome/browser/sync/test/integration/performance/typed_urls_sync_perf_test.cc
4017
// 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 "base/basictypes.h" #include "base/strings/stringprintf.h" #include "chrome/browser/sync/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/performance/sync_timing_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/sync/test/integration/typed_urls_helper.h" #include "sync/sessions/sync_session_context.h" using typed_urls_helper::AddUrlToHistory; using typed_urls_helper::AssertAllProfilesHaveSameURLsAsVerifier; using typed_urls_helper::DeleteUrlsFromHistory; using typed_urls_helper::GetTypedUrlsFromClient; // This number should be as far away from a multiple of // kDefaultMaxCommitBatchSize as possible, so that sync cycle counts // for batch operations stay the same even if some batches end up not // being completely full. static const int kNumUrls = 163; // This compile assert basically asserts that kNumUrls is right in the // middle between two multiples of kDefaultMaxCommitBatchSize. COMPILE_ASSERT( ((kNumUrls % syncer::kDefaultMaxCommitBatchSize) >= (syncer::kDefaultMaxCommitBatchSize / 2)) && ((kNumUrls % syncer::kDefaultMaxCommitBatchSize) <= ((syncer::kDefaultMaxCommitBatchSize + 1) / 2)), kNumUrlsShouldBeBetweenTwoMultiplesOfkDefaultMaxCommitBatchSize); class TypedUrlsSyncPerfTest : public SyncTest { public: TypedUrlsSyncPerfTest() : SyncTest(TWO_CLIENT), url_number_(0) {} // Adds |num_urls| new unique typed urls to |profile|. void AddURLs(int profile, int num_urls); // Update all typed urls in |profile| by visiting them once again. void UpdateURLs(int profile); // Removes all typed urls for |profile|. void RemoveURLs(int profile); // Returns the number of typed urls stored in |profile|. int GetURLCount(int profile); private: // Returns a new unique typed URL. GURL NextURL(); // Returns a unique URL according to the integer |n|. GURL IntToURL(int n); int url_number_; DISALLOW_COPY_AND_ASSIGN(TypedUrlsSyncPerfTest); }; void TypedUrlsSyncPerfTest::AddURLs(int profile, int num_urls) { for (int i = 0; i < num_urls; ++i) { AddUrlToHistory(profile, NextURL()); } } void TypedUrlsSyncPerfTest::UpdateURLs(int profile) { history::URLRows urls = GetTypedUrlsFromClient(profile); for (history::URLRows::const_iterator it = urls.begin(); it != urls.end(); ++it) { AddUrlToHistory(profile, it->url()); } } void TypedUrlsSyncPerfTest::RemoveURLs(int profile) { const history::URLRows& urls = GetTypedUrlsFromClient(profile); std::vector<GURL> gurls; for (history::URLRows::const_iterator it = urls.begin(); it != urls.end(); ++it) { gurls.push_back(it->url()); } DeleteUrlsFromHistory(profile, gurls); } int TypedUrlsSyncPerfTest::GetURLCount(int profile) { return GetTypedUrlsFromClient(profile).size(); } GURL TypedUrlsSyncPerfTest::NextURL() { return IntToURL(url_number_++); } GURL TypedUrlsSyncPerfTest::IntToURL(int n) { return GURL(base::StringPrintf("http://history%d.google.com/", n)); } IN_PROC_BROWSER_TEST_F(TypedUrlsSyncPerfTest, P0) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // TCM ID - 7985716. AddURLs(0, kNumUrls); base::TimeDelta dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumUrls, GetURLCount(1)); SyncTimingHelper::PrintResult("typed_urls", "add_typed_urls", dt); // TCM ID - 7981755. UpdateURLs(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(kNumUrls, GetURLCount(1)); SyncTimingHelper::PrintResult("typed_urls", "update_typed_urls", dt); // TCM ID - 7651271. RemoveURLs(0); dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1)); ASSERT_EQ(0, GetURLCount(1)); SyncTimingHelper::PrintResult("typed_urls", "delete_typed_urls", dt); }
bsd-3-clause
ArcherSys/ArcherSys
vendor/sabre/vobject/tests/VObject/Recur/EventIterator/ExpandFloatingTimesTest.php
2389
<?php namespace Sabre\VObject\Recur\EventIterator; use DateTime; use DateTimeZone; use Sabre\VObject\Reader; class ExpandFloatingTimesTest extends \PHPUnit_Framework_TestCase { use \Sabre\VObject\PHPUnitAssertions; function testExpand() { $input = <<<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foo DTSTART:20150109T090000 DTEND:20150109T100000 RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20191002T070000Z;BYDAY=FR END:VEVENT END:VCALENDAR ICS; $vcal = Reader::read($input); $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); $vcal = $vcal->expand(new DateTime('2015-01-01'), new DateTime('2015-01-31')); $output = <<<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foo DTSTART:20150109T090000Z DTEND:20150109T100000Z RECURRENCE-ID:20150109T090000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150116T090000Z DTEND:20150116T100000Z RECURRENCE-ID:20150116T090000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150123T090000Z DTEND:20150123T100000Z RECURRENCE-ID:20150123T090000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150130T090000Z DTEND:20150130T100000Z RECURRENCE-ID:20150130T090000Z END:VEVENT END:VCALENDAR ICS; $this->assertVObjectEqualsVObject($output, $vcal); } function testExpandWithReferenceTimezone() { $input = <<<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foo DTSTART:20150109T090000 DTEND:20150109T100000 RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20191002T070000Z;BYDAY=FR END:VEVENT END:VCALENDAR ICS; $vcal = Reader::read($input); $this->assertInstanceOf('Sabre\\VObject\\Component\\VCalendar', $vcal); $vcal = $vcal->expand( new DateTime('2015-01-01'), new DateTime('2015-01-31'), new DateTimeZone('Europe/Berlin') ); $output = <<<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foo DTSTART:20150109T080000Z DTEND:20150109T090000Z RECURRENCE-ID:20150109T080000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150116T080000Z DTEND:20150116T090000Z RECURRENCE-ID:20150116T080000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150123T080000Z DTEND:20150123T090000Z RECURRENCE-ID:20150123T080000Z END:VEVENT BEGIN:VEVENT UID:foo DTSTART:20150130T080000Z DTEND:20150130T090000Z RECURRENCE-ID:20150130T080000Z END:VEVENT END:VCALENDAR ICS; $this->assertVObjectEqualsVObject($output, $vcal); } }
mit
pragkent/aliyun-disk
vendor/k8s.io/kubernetes/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/well_known_annotations.go
913
/* Copyright 2017 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 v1 const ( // When kubelet is started with the "external" cloud provider, then // it sets this annotation on the node to denote an ip address set from the // cmd line flag. This ip is verified with the cloudprovider as valid by // the cloud-controller-manager AnnotationProvidedIPAddr = "alpha.kubernetes.io/provided-node-ip" )
mit
ichiohta/material-ui
src/svg-icons/places/rv-hookup.js
534
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesRvHookup = (props) => ( <SvgIcon {...props}> <path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/> </SvgIcon> ); PlacesRvHookup = pure(PlacesRvHookup); PlacesRvHookup.displayName = 'PlacesRvHookup'; PlacesRvHookup.muiName = 'SvgIcon'; export default PlacesRvHookup;
mit
DawidMyslak/native-vs-html5_android-performance
www/TakePhoto/touch/src/chart/series/Cartesian.js
3929
/** * @abstract * @class Ext.chart.series.Cartesian * @extends Ext.chart.series.Series * * Common base class for series implementations which plot values using x/y coordinates. * * @constructor */ Ext.define('Ext.chart.series.Cartesian', { extend: 'Ext.chart.series.Series', config: { /** * The field used to access the x axis value from the items from the data * source. * * @cfg {String} xField */ xField: null, /** * The field used to access the y-axis value from the items from the data * source. * * @cfg {String} yField */ yField: null, /** * @cfg {Ext.chart.axis.Axis} xAxis The chart axis bound to the series on the x-axis. */ xAxis: null, /** * @cfg {Ext.chart.axis.Axis} yAxis The chart axis bound to the series on the y-axis. */ yAxis: null }, directions: ['X', 'Y'], fieldCategoryX: ['X'], fieldCategoryY: ['Y'], updateXAxis: function (axis) { axis.processData(this); }, updateYAxis: function (axis) { axis.processData(this); }, coordinateX: function () { return this.coordinate('X', 0, 2); }, coordinateY: function () { return this.coordinate('Y', 1, 2); }, getItemForPoint: function (x, y) { if (this.getSprites()) { var me = this, sprite = me.getSprites()[0], store = me.getStore(), item; if(me.getHidden()) { return null; } if (sprite) { var index = sprite.getIndexNearPoint(x, y); if (index !== -1) { item = { series: this, category: this.getItemInstancing() ? 'items' : 'markers', index: index, record: store.getData().items[index], field: this.getYField(), sprite: sprite }; return item; } } } }, createSprite: function () { var sprite = this.callSuper(), xAxis = this.getXAxis(); sprite.setFlipXY(this.getChart().getFlipXY()); if (sprite.setAggregator && xAxis && xAxis.getAggregator) { if (xAxis.getAggregator) { sprite.setAggregator({strategy: xAxis.getAggregator()}); } else { sprite.setAggregator({}); } } return sprite; }, getSprites: function () { var me = this, chart = this.getChart(), animation = chart && chart.getAnimate(), itemInstancing = me.getItemInstancing(), sprites = me.sprites, sprite; if (!chart) { return []; } if (!sprites.length) { sprite = me.createSprite(); } else { sprite = sprites[0]; } if (animation) { me.getLabel().getTemplate().fx.setConfig(animation); if (itemInstancing) { sprite.itemsMarker.getTemplate().fx.setConfig(animation); } sprite.fx.setConfig(animation); } return sprites; }, provideLegendInfo: function (target) { var style = this.getStyle(); target.push({ name: this.getTitle() || this.getYField() || this.getId(), mark: style.fillStyle || style.strokeStyle || 'black', disabled: false, series: this.getId(), index: 0 }); }, getXRange: function () { return [this.dataRange[0], this.dataRange[2]]; }, getYRange: function () { return [this.dataRange[1], this.dataRange[3]]; } }) ;
mit
askreet/howiroll
vendor/src/github.com/awslabs/aws-sdk-go/service/cloudhsm/service.go
1559
package cloudhsm import ( "github.com/awslabs/aws-sdk-go/aws" "github.com/awslabs/aws-sdk-go/internal/protocol/jsonrpc" "github.com/awslabs/aws-sdk-go/internal/signer/v4" ) // CloudHSM is a client for CloudHSM. type CloudHSM struct { *aws.Service } // Used for custom service initialization logic var initService func(*aws.Service) // Used for custom request initialization logic var initRequest func(*aws.Request) // New returns a new CloudHSM client. func New(config *aws.Config) *CloudHSM { if config == nil { config = &aws.Config{} } service := &aws.Service{ Config: aws.DefaultConfig.Merge(config), ServiceName: "cloudhsm", APIVersion: "2014-05-30", JSONVersion: "1.1", TargetPrefix: "CloudHsmFrontendService", } service.Initialize() // Handlers service.Handlers.Sign.PushBack(v4.Sign) service.Handlers.Build.PushBack(jsonrpc.Build) service.Handlers.Unmarshal.PushBack(jsonrpc.Unmarshal) service.Handlers.UnmarshalMeta.PushBack(jsonrpc.UnmarshalMeta) service.Handlers.UnmarshalError.PushBack(jsonrpc.UnmarshalError) // Run custom service initialization if present if initService != nil { initService(service) } return &CloudHSM{service} } // newRequest creates a new request for a CloudHSM operation and runs any // custom request initialization. func (c *CloudHSM) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { req := aws.NewRequest(c.Service, op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
mit
Originate/exosphere
vendor/github.com/moby/moby/cli/command/registry/search.go
3550
package registry import ( "fmt" "sort" "strings" "text/tabwriter" "golang.org/x/net/context" "github.com/docker/docker/api/types" registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/cli" "github.com/docker/docker/cli/command" "github.com/docker/docker/opts" "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/registry" "github.com/spf13/cobra" ) type searchOptions struct { term string noTrunc bool limit int filter opts.FilterOpt // Deprecated stars uint automated bool } // NewSearchCommand creates a new `docker search` command func NewSearchCommand(dockerCli *command.DockerCli) *cobra.Command { opts := searchOptions{filter: opts.NewFilterOpt()} cmd := &cobra.Command{ Use: "search [OPTIONS] TERM", Short: "Search the Docker Hub for images", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.term = args[0] return runSearch(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output") flags.VarP(&opts.filter, "filter", "f", "Filter output based on conditions provided") flags.IntVar(&opts.limit, "limit", registry.DefaultSearchLimit, "Max number of search results") flags.BoolVar(&opts.automated, "automated", false, "Only show automated builds") flags.UintVarP(&opts.stars, "stars", "s", 0, "Only displays with at least x stars") flags.MarkDeprecated("automated", "use --filter=is-automated=true instead") flags.MarkDeprecated("stars", "use --filter=stars=3 instead") return cmd } func runSearch(dockerCli *command.DockerCli, opts searchOptions) error { indexInfo, err := registry.ParseSearchIndexInfo(opts.term) if err != nil { return err } ctx := context.Background() authConfig := command.ResolveAuthConfig(ctx, dockerCli, indexInfo) requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search") encodedAuth, err := command.EncodeAuthToBase64(authConfig) if err != nil { return err } options := types.ImageSearchOptions{ RegistryAuth: encodedAuth, PrivilegeFunc: requestPrivilege, Filters: opts.filter.Value(), Limit: opts.limit, } clnt := dockerCli.Client() unorderedResults, err := clnt.ImageSearch(ctx, opts.term, options) if err != nil { return err } results := searchResultsByStars(unorderedResults) sort.Sort(results) w := tabwriter.NewWriter(dockerCli.Out(), 10, 1, 3, ' ', 0) fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n") for _, res := range results { // --automated and -s, --stars are deprecated since Docker 1.12 if (opts.automated && !res.IsAutomated) || (int(opts.stars) > res.StarCount) { continue } desc := strings.Replace(res.Description, "\n", " ", -1) desc = strings.Replace(desc, "\r", " ", -1) if !opts.noTrunc { desc = stringutils.Ellipsis(desc, 45) } fmt.Fprintf(w, "%s\t%s\t%d\t", res.Name, desc, res.StarCount) if res.IsOfficial { fmt.Fprint(w, "[OK]") } fmt.Fprint(w, "\t") if res.IsAutomated { fmt.Fprint(w, "[OK]") } fmt.Fprint(w, "\n") } w.Flush() return nil } // searchResultsByStars sorts search results in descending order by number of stars. type searchResultsByStars []registrytypes.SearchResult func (r searchResultsByStars) Len() int { return len(r) } func (r searchResultsByStars) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r searchResultsByStars) Less(i, j int) bool { return r[j].StarCount < r[i].StarCount }
mit
mdxy2010/forlinux-ok6410
u-boot15/include/dm.h
192
/* * Copyright (c) 2013 Google, Inc * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef _DM_H_ #define _DM_H_ #include <dm/device.h> #include <dm/platdata.h> #include <dm/uclass.h> #endif
gpl-2.0
Keldo/TrinityCore
src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_the_maker.cpp
3723
/* * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "blood_furnace.h" enum Yells { SAY_AGGRO = 0, SAY_KILL = 1, SAY_DIE = 2 }; enum Spells { SPELL_ACID_SPRAY = 38153, SPELL_EXPLODING_BREAKER = 30925, SPELL_KNOCKDOWN = 20276, SPELL_DOMINATION = 25772 }; enum Events { EVENT_ACID_SPRAY = 1, EVENT_EXPLODING_BREAKER, EVENT_DOMINATION, EVENT_KNOCKDOWN }; class boss_the_maker : public CreatureScript { public: boss_the_maker() : CreatureScript("boss_the_maker") { } struct boss_the_makerAI : public BossAI { boss_the_makerAI(Creature* creature) : BossAI(creature, DATA_THE_MAKER) { } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_ACID_SPRAY, 15000); events.ScheduleEvent(EVENT_EXPLODING_BREAKER, 6000); events.ScheduleEvent(EVENT_DOMINATION, 120000); events.ScheduleEvent(EVENT_KNOCKDOWN, 10000); } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) Talk(SAY_KILL); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_DIE); } void ExecuteEvent(uint32 eventId) override { switch (eventId) { case EVENT_ACID_SPRAY: DoCastVictim(SPELL_ACID_SPRAY); events.ScheduleEvent(EVENT_ACID_SPRAY, urand(15000, 23000)); break; case EVENT_EXPLODING_BREAKER: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 30.0f, true)) DoCast(target, SPELL_EXPLODING_BREAKER); events.ScheduleEvent(EVENT_EXPLODING_BREAKER, urand(4000, 12000)); break; case EVENT_DOMINATION: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true)) DoCast(target, SPELL_DOMINATION); events.ScheduleEvent(EVENT_DOMINATION, 120000); break; case EVENT_KNOCKDOWN: DoCastVictim(SPELL_KNOCKDOWN); events.ScheduleEvent(EVENT_KNOCKDOWN, urand(4000, 12000)); break; default: break; } } }; CreatureAI* GetAI(Creature* creature) const override { return GetBloodFurnaceAI<boss_the_makerAI>(creature); } }; void AddSC_boss_the_maker() { new boss_the_maker(); }
gpl-2.0
SinxOner/android_kernel_lge_p710
drivers/usb/otg/msm_otg.c
98604
/* Copyright (c) 2009-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/uaccess.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <linux/pm_runtime.h> #include <linux/of.h> #include <linux/dma-mapping.h> #include <linux/usb.h> #include <linux/usb/otg.h> #include <linux/usb/ulpi.h> #include <linux/usb/gadget.h> #include <linux/usb/hcd.h> #include <linux/usb/quirks.h> #include <linux/usb/msm_hsusb.h> #include <linux/usb/msm_hsusb_hw.h> #include <linux/regulator/consumer.h> #include <linux/mfd/pm8xxx/pm8921-charger.h> #include <linux/mfd/pm8xxx/misc.h> #include <linux/power_supply.h> #include <mach/clk.h> #include <mach/msm_xo.h> #include <mach/msm_bus.h> #include <mach/rpm-regulator.h> #define MSM_USB_BASE (motg->regs) #define DRIVER_NAME "msm_otg" #define ID_TIMER_FREQ (jiffies + msecs_to_jiffies(500)) #define ULPI_IO_TIMEOUT_USEC (10 * 1000) #define USB_PHY_3P3_VOL_MIN 3050000 /* uV */ #define USB_PHY_3P3_VOL_MAX 3300000 /* uV */ #define USB_PHY_3P3_HPM_LOAD 50000 /* uA */ #define USB_PHY_3P3_LPM_LOAD 4000 /* uA */ #define USB_PHY_1P8_VOL_MIN 1800000 /* uV */ #define USB_PHY_1P8_VOL_MAX 1800000 /* uV */ #define USB_PHY_1P8_HPM_LOAD 50000 /* uA */ #define USB_PHY_1P8_LPM_LOAD 4000 /* uA */ #define USB_PHY_VDD_DIG_VOL_NONE 0 /*uV */ #define USB_PHY_VDD_DIG_VOL_MIN 1045000 /* uV */ #define USB_PHY_VDD_DIG_VOL_MAX 1320000 /* uV */ static DECLARE_COMPLETION(pmic_vbus_init); static struct msm_otg *the_msm_otg; static bool debug_aca_enabled; static bool debug_bus_voting_enabled; static struct regulator *hsusb_3p3; static struct regulator *hsusb_1p8; static struct regulator *hsusb_vddcx; static struct regulator *vbus_otg; static struct regulator *mhl_usb_hs_switch; static struct power_supply *psy; static bool aca_id_turned_on; static inline bool aca_enabled(void) { #ifdef CONFIG_USB_MSM_ACA return true; #else return debug_aca_enabled; #endif } static const int vdd_val[VDD_TYPE_MAX][VDD_VAL_MAX] = { { /* VDD_CX CORNER Voting */ [VDD_NONE] = RPM_VREG_CORNER_NONE, [VDD_MIN] = RPM_VREG_CORNER_NOMINAL, [VDD_MAX] = RPM_VREG_CORNER_HIGH, }, { /* VDD_CX Voltage Voting */ [VDD_NONE] = USB_PHY_VDD_DIG_VOL_NONE, [VDD_MIN] = USB_PHY_VDD_DIG_VOL_MIN, [VDD_MAX] = USB_PHY_VDD_DIG_VOL_MAX, }, }; static int msm_hsusb_ldo_init(struct msm_otg *motg, int init) { int rc = 0; if (init) { hsusb_3p3 = devm_regulator_get(motg->phy.dev, "HSUSB_3p3"); if (IS_ERR(hsusb_3p3)) { dev_err(motg->phy.dev, "unable to get hsusb 3p3\n"); return PTR_ERR(hsusb_3p3); } rc = regulator_set_voltage(hsusb_3p3, USB_PHY_3P3_VOL_MIN, USB_PHY_3P3_VOL_MAX); if (rc) { dev_err(motg->phy.dev, "unable to set voltage level for" "hsusb 3p3\n"); return rc; } hsusb_1p8 = devm_regulator_get(motg->phy.dev, "HSUSB_1p8"); if (IS_ERR(hsusb_1p8)) { dev_err(motg->phy.dev, "unable to get hsusb 1p8\n"); rc = PTR_ERR(hsusb_1p8); goto put_3p3_lpm; } rc = regulator_set_voltage(hsusb_1p8, USB_PHY_1P8_VOL_MIN, USB_PHY_1P8_VOL_MAX); if (rc) { dev_err(motg->phy.dev, "unable to set voltage level for" "hsusb 1p8\n"); goto put_1p8; } return 0; } put_1p8: regulator_set_voltage(hsusb_1p8, 0, USB_PHY_1P8_VOL_MAX); put_3p3_lpm: regulator_set_voltage(hsusb_3p3, 0, USB_PHY_3P3_VOL_MAX); return rc; } static int msm_hsusb_config_vddcx(int high) { struct msm_otg *motg = the_msm_otg; enum usb_vdd_type vdd_type = motg->vdd_type; int max_vol = vdd_val[vdd_type][VDD_MAX]; int min_vol; int ret; min_vol = vdd_val[vdd_type][!!high]; ret = regulator_set_voltage(hsusb_vddcx, min_vol, max_vol); if (ret) { pr_err("%s: unable to set the voltage for regulator " "HSUSB_VDDCX\n", __func__); return ret; } pr_debug("%s: min_vol:%d max_vol:%d\n", __func__, min_vol, max_vol); return ret; } static int msm_hsusb_ldo_enable(struct msm_otg *motg, int on) { int ret = 0; if (IS_ERR(hsusb_1p8)) { pr_err("%s: HSUSB_1p8 is not initialized\n", __func__); return -ENODEV; } if (IS_ERR(hsusb_3p3)) { pr_err("%s: HSUSB_3p3 is not initialized\n", __func__); return -ENODEV; } if (on) { ret = regulator_set_optimum_mode(hsusb_1p8, USB_PHY_1P8_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator:" "HSUSB_1p8\n", __func__); return ret; } ret = regulator_enable(hsusb_1p8); if (ret) { dev_err(motg->phy.dev, "%s: unable to enable the hsusb 1p8\n", __func__); regulator_set_optimum_mode(hsusb_1p8, 0); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, USB_PHY_3P3_HPM_LOAD); if (ret < 0) { pr_err("%s: Unable to set HPM of the regulator:" "HSUSB_3p3\n", __func__); regulator_set_optimum_mode(hsusb_1p8, 0); regulator_disable(hsusb_1p8); return ret; } ret = regulator_enable(hsusb_3p3); if (ret) { dev_err(motg->phy.dev, "%s: unable to enable the hsusb 3p3\n", __func__); regulator_set_optimum_mode(hsusb_3p3, 0); regulator_set_optimum_mode(hsusb_1p8, 0); regulator_disable(hsusb_1p8); return ret; } } else { ret = regulator_disable(hsusb_1p8); if (ret) { dev_err(motg->phy.dev, "%s: unable to disable the hsusb 1p8\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_1p8, 0); if (ret < 0) pr_err("%s: Unable to set LPM of the regulator:" "HSUSB_1p8\n", __func__); ret = regulator_disable(hsusb_3p3); if (ret) { dev_err(motg->phy.dev, "%s: unable to disable the hsusb 3p3\n", __func__); return ret; } ret = regulator_set_optimum_mode(hsusb_3p3, 0); if (ret < 0) pr_err("%s: Unable to set LPM of the regulator:" "HSUSB_3p3\n", __func__); } pr_debug("reg (%s)\n", on ? "HPM" : "LPM"); return ret < 0 ? ret : 0; } static void msm_hsusb_mhl_switch_enable(struct msm_otg *motg, bool on) { struct msm_otg_platform_data *pdata = motg->pdata; if (!pdata->mhl_enable) return; if (!mhl_usb_hs_switch) { pr_err("%s: mhl_usb_hs_switch is NULL.\n", __func__); return; } if (on) { if (regulator_enable(mhl_usb_hs_switch)) pr_err("unable to enable mhl_usb_hs_switch\n"); } else { regulator_disable(mhl_usb_hs_switch); } } static int ulpi_read(struct usb_phy *phy, u32 reg) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); int cnt = 0; /* initiate read operation */ writel(ULPI_RUN | ULPI_READ | ULPI_ADDR(reg), USB_ULPI_VIEWPORT); /* wait for completion */ while (cnt < ULPI_IO_TIMEOUT_USEC) { if (!(readl(USB_ULPI_VIEWPORT) & ULPI_RUN)) break; udelay(1); cnt++; } if (cnt >= ULPI_IO_TIMEOUT_USEC) { dev_err(phy->dev, "ulpi_read: timeout %08x\n", readl(USB_ULPI_VIEWPORT)); return -ETIMEDOUT; } return ULPI_DATA_READ(readl(USB_ULPI_VIEWPORT)); } static int ulpi_write(struct usb_phy *phy, u32 val, u32 reg) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); int cnt = 0; /* initiate write operation */ writel(ULPI_RUN | ULPI_WRITE | ULPI_ADDR(reg) | ULPI_DATA(val), USB_ULPI_VIEWPORT); /* wait for completion */ while (cnt < ULPI_IO_TIMEOUT_USEC) { if (!(readl(USB_ULPI_VIEWPORT) & ULPI_RUN)) break; udelay(1); cnt++; } if (cnt >= ULPI_IO_TIMEOUT_USEC) { dev_err(phy->dev, "ulpi_write: timeout\n"); return -ETIMEDOUT; } return 0; } static struct usb_phy_io_ops msm_otg_io_ops = { .read = ulpi_read, .write = ulpi_write, }; static void ulpi_init(struct msm_otg *motg) { struct msm_otg_platform_data *pdata = motg->pdata; int *seq = pdata->phy_init_seq; if (!seq) return; while (seq[0] >= 0) { dev_vdbg(motg->phy.dev, "ulpi: write 0x%02x to 0x%02x\n", seq[0], seq[1]); ulpi_write(&motg->phy, seq[0], seq[1]); seq += 2; } } static int msm_otg_link_clk_reset(struct msm_otg *motg, bool assert) { int ret; if (IS_ERR(motg->clk)) return 0; if (assert) { ret = clk_reset(motg->clk, CLK_RESET_ASSERT); if (ret) dev_err(motg->phy.dev, "usb hs_clk assert failed\n"); } else { ret = clk_reset(motg->clk, CLK_RESET_DEASSERT); if (ret) dev_err(motg->phy.dev, "usb hs_clk deassert failed\n"); } return ret; } static int msm_otg_phy_clk_reset(struct msm_otg *motg) { int ret; if (IS_ERR(motg->phy_reset_clk)) return 0; ret = clk_reset(motg->phy_reset_clk, CLK_RESET_ASSERT); if (ret) { dev_err(motg->phy.dev, "usb phy clk assert failed\n"); return ret; } usleep_range(10000, 12000); ret = clk_reset(motg->phy_reset_clk, CLK_RESET_DEASSERT); if (ret) dev_err(motg->phy.dev, "usb phy clk deassert failed\n"); return ret; } static int msm_otg_phy_reset(struct msm_otg *motg) { u32 val; int ret; int retries; ret = msm_otg_link_clk_reset(motg, 1); if (ret) return ret; ret = msm_otg_phy_clk_reset(motg); if (ret) return ret; ret = msm_otg_link_clk_reset(motg, 0); if (ret) return ret; val = readl(USB_PORTSC) & ~PORTSC_PTS_MASK; writel(val | PORTSC_PTS_ULPI, USB_PORTSC); for (retries = 3; retries > 0; retries--) { ret = ulpi_write(&motg->phy, ULPI_FUNC_CTRL_SUSPENDM, ULPI_CLR(ULPI_FUNC_CTRL)); if (!ret) break; ret = msm_otg_phy_clk_reset(motg); if (ret) return ret; } if (!retries) return -ETIMEDOUT; /* This reset calibrates the phy, if the above write succeeded */ ret = msm_otg_phy_clk_reset(motg); if (ret) return ret; for (retries = 3; retries > 0; retries--) { ret = ulpi_read(&motg->phy, ULPI_DEBUG); if (ret != -ETIMEDOUT) break; ret = msm_otg_phy_clk_reset(motg); if (ret) return ret; } if (!retries) return -ETIMEDOUT; dev_info(motg->phy.dev, "phy_reset: success\n"); return 0; } #define LINK_RESET_TIMEOUT_USEC (250 * 1000) static int msm_otg_link_reset(struct msm_otg *motg) { int cnt = 0; writel_relaxed(USBCMD_RESET, USB_USBCMD); while (cnt < LINK_RESET_TIMEOUT_USEC) { if (!(readl_relaxed(USB_USBCMD) & USBCMD_RESET)) break; udelay(1); cnt++; } if (cnt >= LINK_RESET_TIMEOUT_USEC) return -ETIMEDOUT; /* select ULPI phy */ writel_relaxed(0x80000000, USB_PORTSC); writel_relaxed(0x0, USB_AHBBURST); writel_relaxed(0x08, USB_AHBMODE); return 0; } static int msm_otg_reset(struct usb_phy *phy) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; int ret; u32 val = 0; u32 ulpi_val = 0; /* * USB PHY and Link reset also reset the USB BAM. * Thus perform reset operation only once to avoid * USB BAM reset on other cases e.g. USB cable disconnections. */ if (pdata->disable_reset_on_disconnect) { if (motg->reset_counter) return 0; else motg->reset_counter++; } if (!IS_ERR(motg->clk)) clk_prepare_enable(motg->clk); ret = msm_otg_phy_reset(motg); if (ret) { dev_err(phy->dev, "phy_reset failed\n"); return ret; } aca_id_turned_on = false; ret = msm_otg_link_reset(motg); if (ret) { dev_err(phy->dev, "link reset failed\n"); return ret; } msleep(100); ulpi_init(motg); /* Ensure that RESET operation is completed before turning off clock */ mb(); if (!IS_ERR(motg->clk)) clk_disable_unprepare(motg->clk); if (pdata->otg_control == OTG_PHY_CONTROL) { val = readl_relaxed(USB_OTGSC); if (pdata->mode == USB_OTG) { ulpi_val = ULPI_INT_IDGRD | ULPI_INT_SESS_VALID; val |= OTGSC_IDIE | OTGSC_BSVIE; } else if (pdata->mode == USB_PERIPHERAL) { ulpi_val = ULPI_INT_SESS_VALID; val |= OTGSC_BSVIE; } writel_relaxed(val, USB_OTGSC); ulpi_write(phy, ulpi_val, ULPI_USB_INT_EN_RISE); ulpi_write(phy, ulpi_val, ULPI_USB_INT_EN_FALL); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { ulpi_write(phy, OTG_COMP_DISABLE, ULPI_SET(ULPI_PWR_CLK_MNG_REG)); /* Enable PMIC pull-up */ pm8xxx_usb_id_pullup(1); } return 0; } static const char *timer_string(int bit) { switch (bit) { case A_WAIT_VRISE: return "a_wait_vrise"; case A_WAIT_VFALL: return "a_wait_vfall"; case B_SRP_FAIL: return "b_srp_fail"; case A_WAIT_BCON: return "a_wait_bcon"; case A_AIDL_BDIS: return "a_aidl_bdis"; case A_BIDL_ADIS: return "a_bidl_adis"; case B_ASE0_BRST: return "b_ase0_brst"; case A_TST_MAINT: return "a_tst_maint"; case B_TST_SRP: return "b_tst_srp"; case B_TST_CONFIG: return "b_tst_config"; default: return "UNDEFINED"; } } static enum hrtimer_restart msm_otg_timer_func(struct hrtimer *hrtimer) { struct msm_otg *motg = container_of(hrtimer, struct msm_otg, timer); switch (motg->active_tmout) { case A_WAIT_VRISE: /* TODO: use vbus_vld interrupt */ set_bit(A_VBUS_VLD, &motg->inputs); break; case A_TST_MAINT: /* OTG PET: End session after TA_TST_MAINT */ set_bit(A_BUS_DROP, &motg->inputs); break; case B_TST_SRP: /* * OTG PET: Initiate SRP after TB_TST_SRP of * previous session end. */ set_bit(B_BUS_REQ, &motg->inputs); break; case B_TST_CONFIG: clear_bit(A_CONN, &motg->inputs); break; default: set_bit(motg->active_tmout, &motg->tmouts); } pr_debug("expired %s timer\n", timer_string(motg->active_tmout)); queue_work(system_nrt_wq, &motg->sm_work); return HRTIMER_NORESTART; } static void msm_otg_del_timer(struct msm_otg *motg) { int bit = motg->active_tmout; pr_debug("deleting %s timer. remaining %lld msec\n", timer_string(bit), div_s64(ktime_to_us(hrtimer_get_remaining( &motg->timer)), 1000)); hrtimer_cancel(&motg->timer); clear_bit(bit, &motg->tmouts); } static void msm_otg_start_timer(struct msm_otg *motg, int time, int bit) { clear_bit(bit, &motg->tmouts); motg->active_tmout = bit; pr_debug("starting %s timer\n", timer_string(bit)); hrtimer_start(&motg->timer, ktime_set(time / 1000, (time % 1000) * 1000000), HRTIMER_MODE_REL); } static void msm_otg_init_timer(struct msm_otg *motg) { hrtimer_init(&motg->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); motg->timer.function = msm_otg_timer_func; } static int msm_otg_start_hnp(struct usb_otg *otg) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); if (otg->phy->state != OTG_STATE_A_HOST) { pr_err("HNP can not be initiated in %s state\n", otg_state_string(otg->phy->state)); return -EINVAL; } pr_debug("A-Host: HNP initiated\n"); clear_bit(A_BUS_REQ, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); return 0; } static int msm_otg_start_srp(struct usb_otg *otg) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); u32 val; int ret = 0; if (otg->phy->state != OTG_STATE_B_IDLE) { pr_err("SRP can not be initiated in %s state\n", otg_state_string(otg->phy->state)); ret = -EINVAL; goto out; } if ((jiffies - motg->b_last_se0_sess) < msecs_to_jiffies(TB_SRP_INIT)) { pr_debug("initial conditions of SRP are not met. Try again" "after some time\n"); ret = -EAGAIN; goto out; } pr_debug("B-Device SRP started\n"); /* * PHY won't pull D+ high unless it detects Vbus valid. * Since by definition, SRP is only done when Vbus is not valid, * software work-around needs to be used to spoof the PHY into * thinking it is valid. This can be done using the VBUSVLDEXTSEL and * VBUSVLDEXT register bits. */ ulpi_write(otg->phy, 0x03, 0x97); /* * Harware auto assist data pulsing: Data pulse is given * for 7msec; wait for vbus */ val = readl_relaxed(USB_OTGSC); writel_relaxed((val & ~OTGSC_INTSTS_MASK) | OTGSC_HADP, USB_OTGSC); /* VBUS plusing is obsoleted in OTG 2.0 supplement */ out: return ret; } static void msm_otg_host_hnp_enable(struct usb_otg *otg, bool enable) { struct usb_hcd *hcd = bus_to_hcd(otg->host); struct usb_device *rhub = otg->host->root_hub; if (enable) { pm_runtime_disable(&rhub->dev); rhub->state = USB_STATE_NOTATTACHED; hcd->driver->bus_suspend(hcd); clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); } else { usb_remove_hcd(hcd); msm_otg_reset(otg->phy); usb_add_hcd(hcd, hcd->irq, IRQF_SHARED); } } static int msm_otg_set_suspend(struct usb_phy *phy, int suspend) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); if (aca_enabled()) return 0; if (atomic_read(&motg->in_lpm) == suspend) return 0; if (suspend) { switch (phy->state) { case OTG_STATE_A_WAIT_BCON: if (TA_WAIT_BCON > 0) break; /* fall through */ case OTG_STATE_A_HOST: pr_debug("host bus suspend\n"); clear_bit(A_BUS_REQ, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); break; case OTG_STATE_B_PERIPHERAL: pr_debug("peripheral bus suspend\n"); if (!(motg->caps & ALLOW_LPM_ON_DEV_SUSPEND)) break; set_bit(A_BUS_SUSPEND, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); break; default: break; } } else { switch (phy->state) { case OTG_STATE_A_SUSPEND: /* Remote wakeup or resume */ set_bit(A_BUS_REQ, &motg->inputs); phy->state = OTG_STATE_A_HOST; /* ensure hardware is not in low power mode */ pm_runtime_resume(phy->dev); break; case OTG_STATE_B_PERIPHERAL: pr_debug("peripheral bus resume\n"); if (!(motg->caps & ALLOW_LPM_ON_DEV_SUSPEND)) break; clear_bit(A_BUS_SUSPEND, &motg->inputs); queue_work(system_nrt_wq, &motg->sm_work); break; default: break; } } return 0; } #define PHY_SUSPEND_TIMEOUT_USEC (500 * 1000) #define PHY_RESUME_TIMEOUT_USEC (100 * 1000) #ifdef CONFIG_PM_SLEEP static int msm_otg_suspend(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; struct usb_bus *bus = phy->otg->host; struct msm_otg_platform_data *pdata = motg->pdata; int cnt = 0; bool host_bus_suspend, device_bus_suspend, dcp; u32 phy_ctrl_val = 0, cmd_val; unsigned ret; u32 portsc; if (atomic_read(&motg->in_lpm)) return 0; disable_irq(motg->irq); host_bus_suspend = phy->otg->host && !test_bit(ID, &motg->inputs); device_bus_suspend = phy->otg->gadget && test_bit(ID, &motg->inputs) && test_bit(A_BUS_SUSPEND, &motg->inputs) && motg->caps & ALLOW_LPM_ON_DEV_SUSPEND; dcp = motg->chg_type == USB_DCP_CHARGER; /* charging detection in progress due to cable plug-in */ if (test_bit(B_SESS_VLD, &motg->inputs) && !device_bus_suspend && !dcp) { enable_irq(motg->irq); return -EBUSY; } /* * Chipidea 45-nm PHY suspend sequence: * * Interrupt Latch Register auto-clear feature is not present * in all PHY versions. Latch register is clear on read type. * Clear latch register to avoid spurious wakeup from * low power mode (LPM). * * PHY comparators are disabled when PHY enters into low power * mode (LPM). Keep PHY comparators ON in LPM only when we expect * VBUS/Id notifications from USB PHY. Otherwise turn off USB * PHY comparators. This save significant amount of power. * * PLL is not turned off when PHY enters into low power mode (LPM). * Disable PLL for maximum power savings. */ if (motg->pdata->phy_type == CI_45NM_INTEGRATED_PHY) { ulpi_read(phy, 0x14); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(phy, 0x01, 0x30); ulpi_write(phy, 0x08, 0x09); } /* Set the PHCD bit, only if it is not set by the controller. * PHY may take some time or even fail to enter into low power * mode (LPM). Hence poll for 500 msec and reset the PHY and link * in failure case. */ portsc = readl_relaxed(USB_PORTSC); if (!(portsc & PORTSC_PHCD)) { writel_relaxed(portsc | PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_SUSPEND_TIMEOUT_USEC) { if (readl_relaxed(USB_PORTSC) & PORTSC_PHCD) break; udelay(1); cnt++; } } if (cnt >= PHY_SUSPEND_TIMEOUT_USEC) { dev_err(phy->dev, "Unable to suspend PHY\n"); msm_otg_reset(phy); enable_irq(motg->irq); return -ETIMEDOUT; } /* * PHY has capability to generate interrupt asynchronously in low * power mode (LPM). This interrupt is level triggered. So USB IRQ * line must be disabled till async interrupt enable bit is cleared * in USBCMD register. Assert STP (ULPI interface STOP signal) to * block data communication from PHY. * * PHY retention mode is disallowed while entering to LPM with wall * charger connected. But PHY is put into suspend mode. Hence * enable asynchronous interrupt to detect charger disconnection when * PMIC notifications are unavailable. */ cmd_val = readl_relaxed(USB_USBCMD); if (host_bus_suspend || device_bus_suspend || (motg->pdata->otg_control == OTG_PHY_CONTROL && dcp)) cmd_val |= ASYNC_INTR_CTRL | ULPI_STP_CTRL; else cmd_val |= ULPI_STP_CTRL; writel_relaxed(cmd_val, USB_USBCMD); /* * BC1.2 spec mandates PD to enable VDP_SRC when charging from DCP. * PHY retention and collapse can not happen with VDP_SRC enabled. */ if (motg->caps & ALLOW_PHY_RETENTION && !host_bus_suspend && !device_bus_suspend && !dcp) { phy_ctrl_val = readl_relaxed(USB_PHY_CTRL); if (motg->pdata->otg_control == OTG_PHY_CONTROL) /* Enable PHY HV interrupts to wake MPM/Link */ phy_ctrl_val |= (PHY_IDHV_INTEN | PHY_OTGSESSVLDHV_INTEN); writel_relaxed(phy_ctrl_val & ~PHY_RETEN, USB_PHY_CTRL); motg->lpm_flags |= PHY_RETENTIONED; } /* Ensure that above operation is completed before turning off clocks */ mb(); if (!motg->pdata->core_clk_always_on_workaround) { clk_disable_unprepare(motg->pclk); clk_disable_unprepare(motg->core_clk); } /* usb phy no more require TCXO clock, hence vote for TCXO disable */ if (!host_bus_suspend) { ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_OFF); if (ret) dev_err(phy->dev, "%s failed to devote for " "TCXO D0 buffer%d\n", __func__, ret); else motg->lpm_flags |= XO_SHUTDOWN; } if (motg->caps & ALLOW_PHY_POWER_COLLAPSE && !host_bus_suspend && !dcp) { msm_hsusb_ldo_enable(motg, 0); motg->lpm_flags |= PHY_PWR_COLLAPSED; } if (motg->lpm_flags & PHY_RETENTIONED) { msm_hsusb_config_vddcx(0); msm_hsusb_mhl_switch_enable(motg, 0); } if (device_may_wakeup(phy->dev)) { enable_irq_wake(motg->irq); if (motg->pdata->pmic_id_irq) enable_irq_wake(motg->pdata->pmic_id_irq); } if (bus) clear_bit(HCD_FLAG_HW_ACCESSIBLE, &(bus_to_hcd(bus))->flags); atomic_set(&motg->in_lpm, 1); enable_irq(motg->irq); wake_unlock(&motg->wlock); dev_info(phy->dev, "USB in low power mode\n"); return 0; } static int msm_otg_resume(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; struct usb_bus *bus = phy->otg->host; int cnt = 0; unsigned temp; u32 phy_ctrl_val = 0; unsigned ret; if (!atomic_read(&motg->in_lpm)) return 0; wake_lock(&motg->wlock); /* Vote for TCXO when waking up the phy */ if (motg->lpm_flags & XO_SHUTDOWN) { ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_ON); if (ret) dev_err(phy->dev, "%s failed to vote for " "TCXO D0 buffer%d\n", __func__, ret); motg->lpm_flags &= ~XO_SHUTDOWN; } if (!motg->pdata->core_clk_always_on_workaround) { clk_prepare_enable(motg->core_clk); clk_prepare_enable(motg->pclk); } if (motg->lpm_flags & PHY_PWR_COLLAPSED) { msm_hsusb_ldo_enable(motg, 1); motg->lpm_flags &= ~PHY_PWR_COLLAPSED; } if (motg->lpm_flags & PHY_RETENTIONED) { msm_hsusb_mhl_switch_enable(motg, 1); msm_hsusb_config_vddcx(1); phy_ctrl_val = readl_relaxed(USB_PHY_CTRL); phy_ctrl_val |= PHY_RETEN; if (motg->pdata->otg_control == OTG_PHY_CONTROL) /* Disable PHY HV interrupts */ phy_ctrl_val &= ~(PHY_IDHV_INTEN | PHY_OTGSESSVLDHV_INTEN); writel_relaxed(phy_ctrl_val, USB_PHY_CTRL); motg->lpm_flags &= ~PHY_RETENTIONED; } temp = readl(USB_USBCMD); temp &= ~ASYNC_INTR_CTRL; temp &= ~ULPI_STP_CTRL; writel(temp, USB_USBCMD); /* * PHY comes out of low power mode (LPM) in case of wakeup * from asynchronous interrupt. */ if (!(readl(USB_PORTSC) & PORTSC_PHCD)) goto skip_phy_resume; writel(readl(USB_PORTSC) & ~PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_RESUME_TIMEOUT_USEC) { if (!(readl(USB_PORTSC) & PORTSC_PHCD)) break; udelay(1); cnt++; } if (cnt >= PHY_RESUME_TIMEOUT_USEC) { /* * This is a fatal error. Reset the link and * PHY. USB state can not be restored. Re-insertion * of USB cable is the only way to get USB working. */ dev_err(phy->dev, "Unable to resume USB." "Re-plugin the cable\n"); msm_otg_reset(phy); } skip_phy_resume: if (device_may_wakeup(phy->dev)) { disable_irq_wake(motg->irq); if (motg->pdata->pmic_id_irq) disable_irq_wake(motg->pdata->pmic_id_irq); } if (bus) set_bit(HCD_FLAG_HW_ACCESSIBLE, &(bus_to_hcd(bus))->flags); atomic_set(&motg->in_lpm, 0); if (motg->async_int) { motg->async_int = 0; enable_irq(motg->irq); } dev_info(phy->dev, "USB exited from low power mode\n"); return 0; } #endif static int msm_otg_notify_host_mode(struct msm_otg *motg, bool host_mode) { if (!psy) goto psy_not_supported; if (host_mode) power_supply_set_scope(psy, POWER_SUPPLY_SCOPE_SYSTEM); else power_supply_set_scope(psy, POWER_SUPPLY_SCOPE_DEVICE); psy_not_supported: dev_dbg(motg->phy.dev, "Power Supply doesn't support USB charger\n"); return -ENXIO; } static int msm_otg_notify_chg_type(struct msm_otg *motg) { static int charger_type; /* * TODO * Unify OTG driver charger types and power supply charger types */ if (charger_type == motg->chg_type) return 0; if (motg->chg_type == USB_SDP_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB; else if (motg->chg_type == USB_CDP_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB_CDP; else if (motg->chg_type == USB_DCP_CHARGER || motg->chg_type == USB_PROPRIETARY_CHARGER) charger_type = POWER_SUPPLY_TYPE_USB_DCP; else if ((motg->chg_type == USB_ACA_DOCK_CHARGER || motg->chg_type == USB_ACA_A_CHARGER || motg->chg_type == USB_ACA_B_CHARGER || motg->chg_type == USB_ACA_C_CHARGER)) charger_type = POWER_SUPPLY_TYPE_USB_ACA; else charger_type = POWER_SUPPLY_TYPE_BATTERY; return pm8921_set_usb_power_supply_type(charger_type); } static int msm_otg_notify_power_supply(struct msm_otg *motg, unsigned mA) { if (!psy) goto psy_not_supported; if (motg->cur_power == 0 && mA > 0) { /* Enable charging */ if (power_supply_set_online(psy, true)) goto psy_not_supported; } else if (motg->cur_power > 0 && mA == 0) { /* Disable charging */ if (power_supply_set_online(psy, false)) goto psy_not_supported; return 0; } /* Set max current limit */ if (power_supply_set_current_limit(psy, 1000*mA)) goto psy_not_supported; return 0; psy_not_supported: dev_dbg(motg->phy.dev, "Power Supply doesn't support USB charger\n"); return -ENXIO; } static void msm_otg_notify_charger(struct msm_otg *motg, unsigned mA) { struct usb_gadget *g = motg->phy.otg->gadget; if (g && g->is_a_peripheral) return; if ((motg->chg_type == USB_ACA_DOCK_CHARGER || motg->chg_type == USB_ACA_A_CHARGER || motg->chg_type == USB_ACA_B_CHARGER || motg->chg_type == USB_ACA_C_CHARGER) && mA > IDEV_ACA_CHG_LIMIT) mA = IDEV_ACA_CHG_LIMIT; if (msm_otg_notify_chg_type(motg)) dev_err(motg->phy.dev, "Failed notifying %d charger type to PMIC\n", motg->chg_type); if (motg->cur_power == mA) return; dev_info(motg->phy.dev, "Avail curr from USB = %u\n", mA); /* * Use Power Supply API if supported, otherwise fallback * to legacy pm8921 API. */ if (msm_otg_notify_power_supply(motg, mA)) pm8921_charger_vbus_draw(mA); motg->cur_power = mA; } static int msm_otg_set_power(struct usb_phy *phy, unsigned mA) { struct msm_otg *motg = container_of(phy, struct msm_otg, phy); /* * Gadget driver uses set_power method to notify about the * available current based on suspend/configured states. * * IDEV_CHG can be drawn irrespective of suspend/un-configured * states when CDP/ACA is connected. */ if (motg->chg_type == USB_SDP_CHARGER) msm_otg_notify_charger(motg, mA); return 0; } static void msm_otg_start_host(struct usb_otg *otg, int on) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; struct usb_hcd *hcd; if (!otg->host) return; hcd = bus_to_hcd(otg->host); if (on) { dev_dbg(otg->phy->dev, "host on\n"); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(otg->phy, OTG_COMP_DISABLE, ULPI_SET(ULPI_PWR_CLK_MNG_REG)); /* * Some boards have a switch cotrolled by gpio * to enable/disable internal HUB. Enable internal * HUB before kicking the host. */ if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_A_HOST); usb_add_hcd(hcd, hcd->irq, IRQF_SHARED); } else { dev_dbg(otg->phy->dev, "host off\n"); usb_remove_hcd(hcd); /* HCD core reset all bits of PORTSC. select ULPI phy */ writel_relaxed(0x80000000, USB_PORTSC); if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_UNDEFINED); if (pdata->otg_control == OTG_PHY_CONTROL) ulpi_write(otg->phy, OTG_COMP_DISABLE, ULPI_CLR(ULPI_PWR_CLK_MNG_REG)); } } static int msm_otg_usbdev_notify(struct notifier_block *self, unsigned long action, void *priv) { struct msm_otg *motg = container_of(self, struct msm_otg, usbdev_nb); struct usb_otg *otg = motg->phy.otg; struct usb_device *udev = priv; if (action == USB_BUS_ADD || action == USB_BUS_REMOVE) goto out; if (udev->bus != otg->host) goto out; /* * Interested in devices connected directly to the root hub. * ACA dock can supply IDEV_CHG irrespective devices connected * on the accessory port. */ if (!udev->parent || udev->parent->parent || motg->chg_type == USB_ACA_DOCK_CHARGER) goto out; switch (action) { case USB_DEVICE_ADD: if (aca_enabled()) usb_disable_autosuspend(udev); if (otg->phy->state == OTG_STATE_A_WAIT_BCON) { pr_debug("B_CONN set\n"); set_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_HOST; /* * OTG PET: A-device must end session within * 10 sec after PET enumeration. */ if (udev->quirks & USB_QUIRK_OTG_PET) msm_otg_start_timer(motg, TA_TST_MAINT, A_TST_MAINT); } /* fall through */ case USB_DEVICE_CONFIG: if (udev->actconfig) motg->mA_port = udev->actconfig->desc.bMaxPower * 2; else motg->mA_port = IUNIT; if (otg->phy->state == OTG_STATE_B_HOST) msm_otg_del_timer(motg); break; case USB_DEVICE_REMOVE: if ((otg->phy->state == OTG_STATE_A_HOST) || (otg->phy->state == OTG_STATE_A_SUSPEND)) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &motg->inputs); /* * OTG PET: A-device must end session after * PET disconnection if it is enumerated * with bcdDevice[0] = 1. USB core sets * bus->otg_vbus_off for us. clear it here. */ if (udev->bus->otg_vbus_off) { udev->bus->otg_vbus_off = 0; set_bit(A_BUS_DROP, &motg->inputs); } queue_work(system_nrt_wq, &motg->sm_work); } default: break; } if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX - motg->mA_port); out: return NOTIFY_OK; } static void msm_hsusb_vbus_power(struct msm_otg *motg, bool on) { int ret; static bool vbus_is_on; if (vbus_is_on == on) return; if (motg->pdata->vbus_power) { ret = motg->pdata->vbus_power(on); if (!ret) vbus_is_on = on; return; } if (!vbus_otg) { pr_err("vbus_otg is NULL."); return; } /* * if entering host mode tell the charger to not draw any current * from usb before turning on the boost. * if exiting host mode disable the boost before enabling to draw * current from the source. */ if (on) { msm_otg_notify_host_mode(motg, on); ret = regulator_enable(vbus_otg); if (ret) { pr_err("unable to enable vbus_otg\n"); return; } vbus_is_on = true; } else { ret = regulator_disable(vbus_otg); if (ret) { pr_err("unable to disable vbus_otg\n"); return; } msm_otg_notify_host_mode(motg, on); vbus_is_on = false; } } static int msm_otg_set_host(struct usb_otg *otg, struct usb_bus *host) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct usb_hcd *hcd; /* * Fail host registration if this board can support * only peripheral configuration. */ if (motg->pdata->mode == USB_PERIPHERAL) { dev_info(otg->phy->dev, "Host mode is not supported\n"); return -ENODEV; } if (!motg->pdata->vbus_power && host) { vbus_otg = devm_regulator_get(motg->phy.dev, "vbus_otg"); if (IS_ERR(vbus_otg)) { pr_err("Unable to get vbus_otg\n"); return -ENODEV; } } if (!host) { if (otg->phy->state == OTG_STATE_A_HOST) { pm_runtime_get_sync(otg->phy->dev); usb_unregister_notify(&motg->usbdev_nb); msm_otg_start_host(otg, 0); msm_hsusb_vbus_power(motg, 0); otg->host = NULL; otg->phy->state = OTG_STATE_UNDEFINED; queue_work(system_nrt_wq, &motg->sm_work); } else { otg->host = NULL; } return 0; } hcd = bus_to_hcd(host); hcd->power_budget = motg->pdata->power_budget; #ifdef CONFIG_USB_OTG host->otg_port = 1; #endif motg->usbdev_nb.notifier_call = msm_otg_usbdev_notify; usb_register_notify(&motg->usbdev_nb); otg->host = host; dev_dbg(otg->phy->dev, "host driver registered w/ tranceiver\n"); /* * Kick the state machine work, if peripheral is not supported * or peripheral is already registered with us. */ if (motg->pdata->mode == USB_HOST || otg->gadget) { pm_runtime_get_sync(otg->phy->dev); queue_work(system_nrt_wq, &motg->sm_work); } return 0; } static void msm_otg_start_peripheral(struct usb_otg *otg, int on) { int ret; struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); struct msm_otg_platform_data *pdata = motg->pdata; if (!otg->gadget) return; if (on) { dev_dbg(otg->phy->dev, "gadget on\n"); /* * Some boards have a switch cotrolled by gpio * to enable/disable internal HUB. Disable internal * HUB before kicking the gadget. */ if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_B_PERIPHERAL); /* Configure BUS performance parameters for MAX bandwidth */ if (motg->bus_perf_client && debug_bus_voting_enabled) { ret = msm_bus_scale_client_update_request( motg->bus_perf_client, 1); if (ret) dev_err(motg->phy.dev, "%s: Failed to vote for " "bus bandwidth %d\n", __func__, ret); } usb_gadget_vbus_connect(otg->gadget); } else { dev_dbg(otg->phy->dev, "gadget off\n"); usb_gadget_vbus_disconnect(otg->gadget); /* Configure BUS performance parameters to default */ if (motg->bus_perf_client) { ret = msm_bus_scale_client_update_request( motg->bus_perf_client, 0); if (ret) dev_err(motg->phy.dev, "%s: Failed to devote " "for bus bw %d\n", __func__, ret); } if (pdata->setup_gpio) pdata->setup_gpio(OTG_STATE_UNDEFINED); } } static int msm_otg_set_peripheral(struct usb_otg *otg, struct usb_gadget *gadget) { struct msm_otg *motg = container_of(otg->phy, struct msm_otg, phy); /* * Fail peripheral registration if this board can support * only host configuration. */ if (motg->pdata->mode == USB_HOST) { dev_info(otg->phy->dev, "Peripheral mode is not supported\n"); return -ENODEV; } if (!gadget) { if (otg->phy->state == OTG_STATE_B_PERIPHERAL) { pm_runtime_get_sync(otg->phy->dev); msm_otg_start_peripheral(otg, 0); otg->gadget = NULL; otg->phy->state = OTG_STATE_UNDEFINED; queue_work(system_nrt_wq, &motg->sm_work); } else { otg->gadget = NULL; } return 0; } otg->gadget = gadget; dev_dbg(otg->phy->dev, "peripheral driver registered w/ tranceiver\n"); /* * Kick the state machine work, if host is not supported * or host is already registered with us. */ if (motg->pdata->mode == USB_PERIPHERAL || otg->host) { pm_runtime_get_sync(otg->phy->dev); queue_work(system_nrt_wq, &motg->sm_work); } return 0; } static bool msm_chg_aca_detect(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 int_sts; bool ret = false; if (!aca_enabled()) goto out; if (motg->pdata->phy_type == CI_45NM_INTEGRATED_PHY) goto out; int_sts = ulpi_read(phy, 0x87); switch (int_sts & 0x1C) { case 0x08: if (!test_and_set_bit(ID_A, &motg->inputs)) { dev_dbg(phy->dev, "ID_A\n"); motg->chg_type = USB_ACA_A_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_B, &motg->inputs); clear_bit(ID_C, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x0C: if (!test_and_set_bit(ID_B, &motg->inputs)) { dev_dbg(phy->dev, "ID_B\n"); motg->chg_type = USB_ACA_B_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_C, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x10: if (!test_and_set_bit(ID_C, &motg->inputs)) { dev_dbg(phy->dev, "ID_C\n"); motg->chg_type = USB_ACA_C_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_B, &motg->inputs); set_bit(ID, &motg->inputs); ret = true; } break; case 0x04: if (test_and_clear_bit(ID, &motg->inputs)) { dev_dbg(phy->dev, "ID_GND\n"); motg->chg_type = USB_INVALID_CHARGER; motg->chg_state = USB_CHG_STATE_UNDEFINED; clear_bit(ID_A, &motg->inputs); clear_bit(ID_B, &motg->inputs); clear_bit(ID_C, &motg->inputs); ret = true; } break; default: ret = test_and_clear_bit(ID_A, &motg->inputs) | test_and_clear_bit(ID_B, &motg->inputs) | test_and_clear_bit(ID_C, &motg->inputs) | !test_and_set_bit(ID, &motg->inputs); if (ret) { dev_dbg(phy->dev, "ID A/B/C/GND is no more\n"); motg->chg_type = USB_INVALID_CHARGER; motg->chg_state = USB_CHG_STATE_UNDEFINED; } } out: return ret; } static void msm_chg_enable_aca_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: /* Disable ID_GND in link and PHY */ writel_relaxed(readl_relaxed(USB_OTGSC) & ~(OTGSC_IDPU | OTGSC_IDIE), USB_OTGSC); ulpi_write(phy, 0x01, 0x0C); ulpi_write(phy, 0x10, 0x0F); ulpi_write(phy, 0x10, 0x12); /* Disable PMIC ID pull-up */ pm8xxx_usb_id_pullup(0); /* Enable ACA ID detection */ ulpi_write(phy, 0x20, 0x85); aca_id_turned_on = true; break; default: break; } } static void msm_chg_enable_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: /* Enable ACA Detection interrupt (on any RID change) */ ulpi_write(phy, 0x01, 0x94); break; default: break; } } static void msm_chg_disable_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; if (!aca_enabled()) return; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x01, 0x95); break; default: break; } } static bool msm_chg_check_aca_intr(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; bool ret = false; if (!aca_enabled()) return ret; switch (motg->pdata->phy_type) { case SNPS_28NM_INTEGRATED_PHY: if (ulpi_read(phy, 0x91) & 1) { dev_dbg(phy->dev, "RID change\n"); ulpi_write(phy, 0x01, 0x92); ret = msm_chg_aca_detect(motg); } default: break; } return ret; } static void msm_otg_id_timer_func(unsigned long data) { struct msm_otg *motg = (struct msm_otg *) data; if (!aca_enabled()) return; if (atomic_read(&motg->in_lpm)) { dev_dbg(motg->phy.dev, "timer: in lpm\n"); return; } if (motg->phy.state == OTG_STATE_A_SUSPEND) goto out; if (msm_chg_check_aca_intr(motg)) { dev_dbg(motg->phy.dev, "timer: aca work\n"); queue_work(system_nrt_wq, &motg->sm_work); } out: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs)) mod_timer(&motg->id_timer, ID_TIMER_FREQ); } static bool msm_chg_check_secondary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); ret = chg_det & (1 << 4); break; case SNPS_28NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x87); ret = chg_det & 1; break; default: break; } return ret; } static void msm_chg_enable_secondary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); /* Turn off charger block */ chg_det |= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); /* control chg block via ULPI */ chg_det &= ~(1 << 3); ulpi_write(phy, chg_det, 0x34); /* put it in host mode for enabling D- source */ chg_det &= ~(1 << 2); ulpi_write(phy, chg_det, 0x34); /* Turn on chg detect block */ chg_det &= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); /* enable chg detection */ chg_det &= ~(1 << 0); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: /* * Configure DM as current source, DP as current sink * and enable battery charging comparators. */ ulpi_write(phy, 0x8, 0x85); ulpi_write(phy, 0x2, 0x85); ulpi_write(phy, 0x1, 0x85); break; default: break; } } static bool msm_chg_check_primary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); ret = chg_det & (1 << 4); break; case SNPS_28NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x87); ret = chg_det & 1; /* Turn off VDP_SRC */ ulpi_write(phy, 0x3, 0x86); msleep(20); break; default: break; } return ret; } static void msm_chg_enable_primary_det(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); /* enable chg detection */ chg_det &= ~(1 << 0); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: /* * Configure DP as current source, DM as current sink * and enable battery charging comparators. */ ulpi_write(phy, 0x2, 0x85); ulpi_write(phy, 0x1, 0x85); break; default: break; } } static bool msm_chg_check_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 line_state; bool ret = false; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: line_state = ulpi_read(phy, 0x15); ret = !(line_state & 1); break; case SNPS_28NM_INTEGRATED_PHY: line_state = ulpi_read(phy, 0x87); ret = line_state & 2; break; default: break; } return ret; } static void msm_chg_disable_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); chg_det &= ~(1 << 5); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: ulpi_write(phy, 0x10, 0x86); break; default: break; } } static void msm_chg_enable_dcd(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); /* Turn on D+ current source */ chg_det |= (1 << 5); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: /* Data contact detection enable */ ulpi_write(phy, 0x10, 0x85); break; default: break; } } static void msm_chg_block_on(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 func_ctrl, chg_det; /* put the controller in non-driving mode */ func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NONDRIVING; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); /* control chg block via ULPI */ chg_det &= ~(1 << 3); ulpi_write(phy, chg_det, 0x34); /* Turn on chg detect block */ chg_det &= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); udelay(20); break; case SNPS_28NM_INTEGRATED_PHY: /* Clear charger detecting control bits */ ulpi_write(phy, 0x1F, 0x86); /* Clear alt interrupt latch and enable bits */ ulpi_write(phy, 0x1F, 0x92); ulpi_write(phy, 0x1F, 0x95); udelay(100); break; default: break; } } static void msm_chg_block_off(struct msm_otg *motg) { struct usb_phy *phy = &motg->phy; u32 func_ctrl, chg_det; switch (motg->pdata->phy_type) { case CI_45NM_INTEGRATED_PHY: chg_det = ulpi_read(phy, 0x34); /* Turn off charger block */ chg_det |= ~(1 << 1); ulpi_write(phy, chg_det, 0x34); break; case SNPS_28NM_INTEGRATED_PHY: /* Clear charger detecting control bits */ ulpi_write(phy, 0x3F, 0x86); /* Clear alt interrupt latch and enable bits */ ulpi_write(phy, 0x1F, 0x92); ulpi_write(phy, 0x1F, 0x95); break; default: break; } /* put the controller in normal mode */ func_ctrl = ulpi_read(phy, ULPI_FUNC_CTRL); func_ctrl &= ~ULPI_FUNC_CTRL_OPMODE_MASK; func_ctrl |= ULPI_FUNC_CTRL_OPMODE_NORMAL; ulpi_write(phy, func_ctrl, ULPI_FUNC_CTRL); } static const char *chg_to_string(enum usb_chg_type chg_type) { switch (chg_type) { case USB_SDP_CHARGER: return "USB_SDP_CHARGER"; case USB_DCP_CHARGER: return "USB_DCP_CHARGER"; case USB_CDP_CHARGER: return "USB_CDP_CHARGER"; case USB_ACA_A_CHARGER: return "USB_ACA_A_CHARGER"; case USB_ACA_B_CHARGER: return "USB_ACA_B_CHARGER"; case USB_ACA_C_CHARGER: return "USB_ACA_C_CHARGER"; case USB_ACA_DOCK_CHARGER: return "USB_ACA_DOCK_CHARGER"; case USB_PROPRIETARY_CHARGER: return "USB_PROPRIETARY_CHARGER"; default: return "INVALID_CHARGER"; } } #define MSM_CHG_DCD_POLL_TIME (100 * HZ/1000) /* 100 msec */ #define MSM_CHG_DCD_MAX_RETRIES 6 /* Tdcd_tmout = 6 * 100 msec */ #define MSM_CHG_PRIMARY_DET_TIME (50 * HZ/1000) /* TVDPSRC_ON */ #define MSM_CHG_SECONDARY_DET_TIME (50 * HZ/1000) /* TVDMSRC_ON */ static void msm_chg_detect_work(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, chg_work.work); struct usb_phy *phy = &motg->phy; bool is_dcd = false, tmout, vout, is_aca; u32 line_state, dm_vlgc; unsigned long delay; dev_dbg(phy->dev, "chg detection work\n"); switch (motg->chg_state) { case USB_CHG_STATE_UNDEFINED: msm_chg_block_on(motg); if (motg->pdata->enable_dcd) msm_chg_enable_dcd(motg); msm_chg_enable_aca_det(motg); motg->chg_state = USB_CHG_STATE_WAIT_FOR_DCD; motg->dcd_retries = 0; delay = MSM_CHG_DCD_POLL_TIME; break; case USB_CHG_STATE_WAIT_FOR_DCD: is_aca = msm_chg_aca_detect(motg); if (is_aca) { /* * ID_A can be ACA dock too. continue * primary detection after DCD. */ if (test_bit(ID_A, &motg->inputs)) { motg->chg_state = USB_CHG_STATE_WAIT_FOR_DCD; } else { delay = 0; break; } } if (motg->pdata->enable_dcd) is_dcd = msm_chg_check_dcd(motg); tmout = ++motg->dcd_retries == MSM_CHG_DCD_MAX_RETRIES; if (is_dcd || tmout) { if (motg->pdata->enable_dcd) msm_chg_disable_dcd(motg); msm_chg_enable_primary_det(motg); delay = MSM_CHG_PRIMARY_DET_TIME; motg->chg_state = USB_CHG_STATE_DCD_DONE; } else { delay = MSM_CHG_DCD_POLL_TIME; } break; case USB_CHG_STATE_DCD_DONE: vout = msm_chg_check_primary_det(motg); line_state = readl_relaxed(USB_PORTSC) & PORTSC_LS; dm_vlgc = line_state & PORTSC_LS_DM; if (vout && !dm_vlgc) { /* VDAT_REF < DM < VLGC */ if (test_bit(ID_A, &motg->inputs)) { motg->chg_type = USB_ACA_DOCK_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; delay = 0; break; } if (line_state) { /* DP > VLGC */ motg->chg_type = USB_PROPRIETARY_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; delay = 0; } else { msm_chg_enable_secondary_det(motg); delay = MSM_CHG_SECONDARY_DET_TIME; motg->chg_state = USB_CHG_STATE_PRIMARY_DONE; } } else { /* DM < VDAT_REF || DM > VLGC */ if (test_bit(ID_A, &motg->inputs)) { motg->chg_type = USB_ACA_A_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; delay = 0; break; } if (line_state) /* DP > VLGC or/and DM > VLGC */ motg->chg_type = USB_PROPRIETARY_CHARGER; else motg->chg_type = USB_SDP_CHARGER; motg->chg_state = USB_CHG_STATE_DETECTED; delay = 0; } break; case USB_CHG_STATE_PRIMARY_DONE: vout = msm_chg_check_secondary_det(motg); if (vout) motg->chg_type = USB_DCP_CHARGER; else motg->chg_type = USB_CDP_CHARGER; motg->chg_state = USB_CHG_STATE_SECONDARY_DONE; /* fall through */ case USB_CHG_STATE_SECONDARY_DONE: motg->chg_state = USB_CHG_STATE_DETECTED; case USB_CHG_STATE_DETECTED: msm_chg_block_off(motg); msm_chg_enable_aca_det(motg); /* * Spurious interrupt is seen after enabling ACA detection * due to which charger detection fails in case of PET. * Add delay of 100 microsec to avoid that. */ udelay(100); msm_chg_enable_aca_intr(motg); dev_dbg(phy->dev, "chg_type = %s\n", chg_to_string(motg->chg_type)); queue_work(system_nrt_wq, &motg->sm_work); return; default: return; } queue_delayed_work(system_nrt_wq, &motg->chg_work, delay); } /* * We support OTG, Peripheral only and Host only configurations. In case * of OTG, mode switch (host-->peripheral/peripheral-->host) can happen * via Id pin status or user request (debugfs). Id/BSV interrupts are not * enabled when switch is controlled by user and default mode is supplied * by board file, which can be changed by userspace later. */ static void msm_otg_init_sm(struct msm_otg *motg) { struct msm_otg_platform_data *pdata = motg->pdata; u32 otgsc = readl(USB_OTGSC); switch (pdata->mode) { case USB_OTG: if (pdata->otg_control == OTG_USER_CONTROL) { if (pdata->default_mode == USB_HOST) { clear_bit(ID, &motg->inputs); } else if (pdata->default_mode == USB_PERIPHERAL) { set_bit(ID, &motg->inputs); set_bit(B_SESS_VLD, &motg->inputs); } else { set_bit(ID, &motg->inputs); clear_bit(B_SESS_VLD, &motg->inputs); } } else if (pdata->otg_control == OTG_PHY_CONTROL) { if (otgsc & OTGSC_ID) { set_bit(ID, &motg->inputs); } else { clear_bit(ID, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); } if (otgsc & OTGSC_BSV) set_bit(B_SESS_VLD, &motg->inputs); else clear_bit(B_SESS_VLD, &motg->inputs); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { if (pdata->pmic_id_irq) { unsigned long flags; local_irq_save(flags); if (irq_read_line(pdata->pmic_id_irq)) set_bit(ID, &motg->inputs); else clear_bit(ID, &motg->inputs); local_irq_restore(flags); } /* * VBUS initial state is reported after PMIC * driver initialization. Wait for it. */ wait_for_completion(&pmic_vbus_init); } break; case USB_HOST: clear_bit(ID, &motg->inputs); break; case USB_PERIPHERAL: set_bit(ID, &motg->inputs); if (pdata->otg_control == OTG_PHY_CONTROL) { if (otgsc & OTGSC_BSV) set_bit(B_SESS_VLD, &motg->inputs); else clear_bit(B_SESS_VLD, &motg->inputs); } else if (pdata->otg_control == OTG_PMIC_CONTROL) { /* * VBUS initial state is reported after PMIC * driver initialization. Wait for it. */ wait_for_completion(&pmic_vbus_init); } break; default: break; } } #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver extern void trigger_baseline_state_machine(int plug_in, int type); #endif static void msm_otg_sm_work(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, sm_work); struct usb_otg *otg = motg->phy.otg; bool work = 0, srp_reqd; pm_runtime_resume(otg->phy->dev); pr_debug("%s work\n", otg_state_string(otg->phy->state)); switch (otg->phy->state) { case OTG_STATE_UNDEFINED: msm_otg_reset(otg->phy); msm_otg_init_sm(motg); psy = power_supply_get_by_name("usb"); if (!psy) pr_err("couldn't get usb power supply\n"); otg->phy->state = OTG_STATE_B_IDLE; if (!test_bit(B_SESS_VLD, &motg->inputs) && test_bit(ID, &motg->inputs)) { pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); break; } /* FALL THROUGH */ case OTG_STATE_B_IDLE: if ((!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs)) && otg->host) { pr_debug("!id || id_A\n"); #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver trigger_baseline_state_machine(1,2); #endif clear_bit(B_BUS_REQ, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_A_IDLE; work = 1; } else if (test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("b_sess_vld\n"); switch (motg->chg_state) { case USB_CHG_STATE_UNDEFINED: msm_chg_detect_work(&motg->chg_work.work); break; case USB_CHG_STATE_DETECTED: switch (motg->chg_type) { case USB_DCP_CHARGER: #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver trigger_baseline_state_machine(1,0); #endif /* Enable VDP_SRC */ ulpi_write(otg->phy, 0x2, 0x85); /* fall through */ case USB_PROPRIETARY_CHARGER: msm_otg_notify_charger(motg, IDEV_CHG_MAX); pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); break; case USB_ACA_B_CHARGER: msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); /* * (ID_B --> ID_C) PHY_ALT interrupt can * not be detected in LPM. */ break; case USB_CDP_CHARGER: msm_otg_notify_charger(motg, IDEV_CHG_MAX); msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver trigger_baseline_state_machine(1,2); #endif break; case USB_ACA_C_CHARGER: msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; break; case USB_SDP_CHARGER: #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver trigger_baseline_state_machine(1,1); #endif msm_otg_start_peripheral(otg, 1); otg->phy->state = OTG_STATE_B_PERIPHERAL; break; default: break; } break; default: break; } } else if (test_bit(B_BUS_REQ, &motg->inputs)) { pr_debug("b_sess_end && b_bus_req\n"); if (msm_otg_start_srp(otg) < 0) { clear_bit(B_BUS_REQ, &motg->inputs); work = 1; break; } otg->phy->state = OTG_STATE_B_SRP_INIT; msm_otg_start_timer(motg, TB_SRP_FAIL, B_SRP_FAIL); break; } else { pr_debug("chg_work cancel"); cancel_delayed_work_sync(&motg->chg_work); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; #ifdef CONFIG_LGE_TOUCHSCREEN_SYNAPTICS_I2C_RMI4 //to know usb state on touch driver trigger_baseline_state_machine(0,-1); #endif msm_otg_notify_charger(motg, 0); msm_otg_reset(otg->phy); pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); } break; case OTG_STATE_B_SRP_INIT: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_C, &motg->inputs) || (test_bit(B_SESS_VLD, &motg->inputs) && !test_bit(ID_B, &motg->inputs))) { pr_debug("!id || id_a/c || b_sess_vld+!id_b\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_B_IDLE; /* * clear VBUSVLDEXTSEL and VBUSVLDEXT register * bits after SRP initiation. */ ulpi_write(otg->phy, 0x0, 0x98); work = 1; } else if (test_bit(B_SRP_FAIL, &motg->tmouts)) { pr_debug("b_srp_fail\n"); pr_info("A-device did not respond to SRP\n"); clear_bit(B_BUS_REQ, &motg->inputs); clear_bit(B_SRP_FAIL, &motg->tmouts); otg_send_event(OTG_EVENT_NO_RESP_FOR_SRP); ulpi_write(otg->phy, 0x0, 0x98); otg->phy->state = OTG_STATE_B_IDLE; motg->b_last_se0_sess = jiffies; work = 1; } break; case OTG_STATE_B_PERIPHERAL: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_B, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("!id || id_a/b || !b_sess_vld\n"); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); srp_reqd = otg->gadget->otg_srp_reqd; msm_otg_start_peripheral(otg, 0); if (test_bit(ID_B, &motg->inputs)) clear_bit(ID_B, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_B_IDLE; motg->b_last_se0_sess = jiffies; if (srp_reqd) msm_otg_start_timer(motg, TB_TST_SRP, B_TST_SRP); else work = 1; } else if (test_bit(B_BUS_REQ, &motg->inputs) && otg->gadget->b_hnp_enable && test_bit(A_BUS_SUSPEND, &motg->inputs)) { pr_debug("b_bus_req && b_hnp_en && a_bus_suspend\n"); msm_otg_start_timer(motg, TB_ASE0_BRST, B_ASE0_BRST); /* D+ pullup should not be disconnected within 4msec * after A device suspends the bus. Otherwise PET will * fail the compliance test. */ udelay(1000); msm_otg_start_peripheral(otg, 0); otg->phy->state = OTG_STATE_B_WAIT_ACON; /* * start HCD even before A-device enable * pull-up to meet HNP timings. */ otg->host->is_b_host = 1; msm_otg_start_host(otg, 1); } else if (test_bit(A_BUS_SUSPEND, &motg->inputs) && test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("a_bus_suspend && b_sess_vld\n"); if (motg->caps & ALLOW_LPM_ON_DEV_SUSPEND) { pm_runtime_put_noidle(otg->phy->dev); pm_runtime_suspend(otg->phy->dev); } } else if (test_bit(ID_C, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } break; case OTG_STATE_B_WAIT_ACON: if (!test_bit(ID, &motg->inputs) || test_bit(ID_A, &motg->inputs) || test_bit(ID_B, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("!id || id_a/b || !b_sess_vld\n"); msm_otg_del_timer(motg); /* * A-device is physically disconnected during * HNP. Remove HCD. */ msm_otg_start_host(otg, 0); otg->host->is_b_host = 0; clear_bit(B_BUS_REQ, &motg->inputs); clear_bit(A_BUS_SUSPEND, &motg->inputs); motg->b_last_se0_sess = jiffies; otg->phy->state = OTG_STATE_B_IDLE; msm_otg_reset(otg->phy); work = 1; } else if (test_bit(A_CONN, &motg->inputs)) { pr_debug("a_conn\n"); clear_bit(A_BUS_SUSPEND, &motg->inputs); otg->phy->state = OTG_STATE_B_HOST; /* * PET disconnects D+ pullup after reset is generated * by B device in B_HOST role which is not detected by * B device. As workaorund , start timer of 300msec * and stop timer if A device is enumerated else clear * A_CONN. */ msm_otg_start_timer(motg, TB_TST_CONFIG, B_TST_CONFIG); } else if (test_bit(B_ASE0_BRST, &motg->tmouts)) { pr_debug("b_ase0_brst_tmout\n"); pr_info("B HNP fail:No response from A device\n"); msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); otg->host->is_b_host = 0; clear_bit(B_ASE0_BRST, &motg->tmouts); clear_bit(A_BUS_SUSPEND, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); otg_send_event(OTG_EVENT_HNP_FAILED); otg->phy->state = OTG_STATE_B_IDLE; work = 1; } else if (test_bit(ID_C, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } break; case OTG_STATE_B_HOST: if (!test_bit(B_BUS_REQ, &motg->inputs) || !test_bit(A_CONN, &motg->inputs) || !test_bit(B_SESS_VLD, &motg->inputs)) { pr_debug("!b_bus_req || !a_conn || !b_sess_vld\n"); clear_bit(A_CONN, &motg->inputs); clear_bit(B_BUS_REQ, &motg->inputs); msm_otg_start_host(otg, 0); otg->host->is_b_host = 0; otg->phy->state = OTG_STATE_B_IDLE; msm_otg_reset(otg->phy); work = 1; } else if (test_bit(ID_C, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } break; case OTG_STATE_A_IDLE: otg->default_a = 1; if (test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) { pr_debug("id && !id_a\n"); otg->default_a = 0; clear_bit(A_BUS_DROP, &motg->inputs); otg->phy->state = OTG_STATE_B_IDLE; del_timer_sync(&motg->id_timer); msm_otg_link_reset(motg); msm_chg_enable_aca_intr(motg); msm_otg_notify_charger(motg, 0); work = 1; } else if (!test_bit(A_BUS_DROP, &motg->inputs) && (test_bit(A_SRP_DET, &motg->inputs) || test_bit(A_BUS_REQ, &motg->inputs))) { pr_debug("!a_bus_drop && (a_srp_det || a_bus_req)\n"); clear_bit(A_SRP_DET, &motg->inputs); /* Disable SRP detection */ writel_relaxed((readl_relaxed(USB_OTGSC) & ~OTGSC_INTSTS_MASK) & ~OTGSC_DPIE, USB_OTGSC); otg->phy->state = OTG_STATE_A_WAIT_VRISE; /* VBUS should not be supplied before end of SRP pulse * generated by PET, if not complaince test fail. */ usleep_range(10000, 12000); /* ACA: ID_A: Stop charging untill enumeration */ if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, 0); else msm_hsusb_vbus_power(motg, 1); msm_otg_start_timer(motg, TA_WAIT_VRISE, A_WAIT_VRISE); } else { pr_debug("No session requested\n"); clear_bit(A_BUS_DROP, &motg->inputs); if (test_bit(ID_A, &motg->inputs)) { msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); } else if (!test_bit(ID, &motg->inputs)) { msm_otg_notify_charger(motg, 0); /* * A-device is not providing power on VBUS. * Enable SRP detection. */ writel_relaxed(0x13, USB_USBMODE); writel_relaxed((readl_relaxed(USB_OTGSC) & ~OTGSC_INTSTS_MASK) | OTGSC_DPIE, USB_OTGSC); mb(); } } break; case OTG_STATE_A_WAIT_VRISE: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_WAIT_VRISE, &motg->tmouts)) { pr_debug("id || a_bus_drop || a_wait_vrise_tmout\n"); clear_bit(A_BUS_REQ, &motg->inputs); msm_otg_del_timer(motg); msm_hsusb_vbus_power(motg, 0); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (test_bit(A_VBUS_VLD, &motg->inputs)) { pr_debug("a_vbus_vld\n"); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); msm_otg_start_host(otg, 1); msm_chg_enable_aca_det(motg); msm_chg_disable_aca_intr(motg); mod_timer(&motg->id_timer, ID_TIMER_FREQ); if (msm_chg_check_aca_intr(motg)) work = 1; } break; case OTG_STATE_A_WAIT_BCON: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_WAIT_BCON, &motg->tmouts)) { pr_debug("(id && id_a/b/c) || a_bus_drop ||" "a_wait_bcon_tmout\n"); if (test_bit(A_WAIT_BCON, &motg->tmouts)) { pr_info("Device No Response\n"); otg_send_event(OTG_EVENT_DEV_CONN_TMOUT); } msm_otg_del_timer(motg); clear_bit(A_BUS_REQ, &motg->inputs); clear_bit(B_CONN, &motg->inputs); msm_otg_start_host(otg, 0); /* * ACA: ID_A with NO accessory, just the A plug is * attached to ACA: Use IDCHG_MAX for charging */ if (test_bit(ID_A, &motg->inputs)) msm_otg_notify_charger(motg, IDEV_CHG_MIN); else msm_hsusb_vbus_power(motg, 0); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { pr_debug("!a_vbus_vld\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); msm_otg_start_host(otg, 0); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_reset(otg->phy); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); } else if (!test_bit(A_BUS_REQ, &motg->inputs)) { /* * If TA_WAIT_BCON is infinite, we don;t * turn off VBUS. Enter low power mode. */ if (TA_WAIT_BCON < 0) pm_runtime_put_sync(otg->phy->dev); } else if (!test_bit(ID, &motg->inputs)) { msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_HOST: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs)) { pr_debug("id_a/b/c || a_bus_drop\n"); clear_bit(B_CONN, &motg->inputs); clear_bit(A_BUS_REQ, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_host(otg, 0); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { pr_debug("!a_vbus_vld\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); } else if (!test_bit(A_BUS_REQ, &motg->inputs)) { /* * a_bus_req is de-asserted when root hub is * suspended or HNP is in progress. */ pr_debug("!a_bus_req\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_SUSPEND; if (otg->host->b_hnp_enable) msm_otg_start_timer(motg, TA_AIDL_BDIS, A_AIDL_BDIS); else pm_runtime_put_sync(otg->phy->dev); } else if (!test_bit(B_CONN, &motg->inputs)) { pr_debug("!b_conn\n"); msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); if (msm_chg_check_aca_intr(motg)) work = 1; } else if (test_bit(ID_A, &motg->inputs)) { msm_otg_del_timer(motg); msm_hsusb_vbus_power(motg, 0); if (motg->chg_type == USB_ACA_DOCK_CHARGER) msm_otg_notify_charger(motg, IDEV_ACA_CHG_MAX); else msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_SUSPEND: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_AIDL_BDIS, &motg->tmouts)) { pr_debug("id_a/b/c || a_bus_drop ||" "a_aidl_bdis_tmout\n"); msm_otg_del_timer(motg); clear_bit(B_CONN, &motg->inputs); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { pr_debug("!a_vbus_vld\n"); msm_otg_del_timer(motg); clear_bit(B_CONN, &motg->inputs); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); } else if (!test_bit(B_CONN, &motg->inputs) && otg->host->b_hnp_enable) { pr_debug("!b_conn && b_hnp_enable"); otg->phy->state = OTG_STATE_A_PERIPHERAL; msm_otg_host_hnp_enable(otg, 1); otg->gadget->is_a_peripheral = 1; msm_otg_start_peripheral(otg, 1); } else if (!test_bit(B_CONN, &motg->inputs) && !otg->host->b_hnp_enable) { pr_debug("!b_conn && !b_hnp_enable"); /* * bus request is dropped during suspend. * acquire again for next device. */ set_bit(A_BUS_REQ, &motg->inputs); otg->phy->state = OTG_STATE_A_WAIT_BCON; if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_PERIPHERAL: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs)) { pr_debug("id _f/b/c || a_bus_drop\n"); /* Clear BIDL_ADIS timer */ msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_WAIT_VFALL; msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; msm_otg_start_host(otg, 0); msm_otg_reset(otg->phy); if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); } else if (!test_bit(A_VBUS_VLD, &motg->inputs)) { pr_debug("!a_vbus_vld\n"); /* Clear BIDL_ADIS timer */ msm_otg_del_timer(motg); otg->phy->state = OTG_STATE_A_VBUS_ERR; msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; msm_otg_start_host(otg, 0); } else if (test_bit(A_BIDL_ADIS, &motg->tmouts)) { pr_debug("a_bidl_adis_tmout\n"); msm_otg_start_peripheral(otg, 0); otg->gadget->is_a_peripheral = 0; otg->phy->state = OTG_STATE_A_WAIT_BCON; set_bit(A_BUS_REQ, &motg->inputs); msm_otg_host_hnp_enable(otg, 0); if (TA_WAIT_BCON > 0) msm_otg_start_timer(motg, TA_WAIT_BCON, A_WAIT_BCON); } else if (test_bit(ID_A, &motg->inputs)) { msm_hsusb_vbus_power(motg, 0); msm_otg_notify_charger(motg, IDEV_CHG_MIN - motg->mA_port); } else if (!test_bit(ID, &motg->inputs)) { msm_otg_notify_charger(motg, 0); msm_hsusb_vbus_power(motg, 1); } break; case OTG_STATE_A_WAIT_VFALL: if (test_bit(A_WAIT_VFALL, &motg->tmouts)) { clear_bit(A_VBUS_VLD, &motg->inputs); otg->phy->state = OTG_STATE_A_IDLE; work = 1; } break; case OTG_STATE_A_VBUS_ERR: if ((test_bit(ID, &motg->inputs) && !test_bit(ID_A, &motg->inputs)) || test_bit(A_BUS_DROP, &motg->inputs) || test_bit(A_CLR_ERR, &motg->inputs)) { otg->phy->state = OTG_STATE_A_WAIT_VFALL; if (!test_bit(ID_A, &motg->inputs)) msm_hsusb_vbus_power(motg, 0); msm_otg_start_timer(motg, TA_WAIT_VFALL, A_WAIT_VFALL); motg->chg_state = USB_CHG_STATE_UNDEFINED; motg->chg_type = USB_INVALID_CHARGER; msm_otg_notify_charger(motg, 0); } break; default: break; } if (work) queue_work(system_nrt_wq, &motg->sm_work); } static irqreturn_t msm_otg_irq(int irq, void *data) { struct msm_otg *motg = data; struct usb_otg *otg = motg->phy.otg; u32 otgsc = 0, usbsts, pc; bool work = 0; irqreturn_t ret = IRQ_HANDLED; if (atomic_read(&motg->in_lpm)) { pr_debug("OTG IRQ: in LPM\n"); disable_irq_nosync(irq); motg->async_int = 1; if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else pm_request_resume(otg->phy->dev); return IRQ_HANDLED; } usbsts = readl(USB_USBSTS); otgsc = readl(USB_OTGSC); if (!(otgsc & OTG_OTGSTS_MASK) && !(usbsts & OTG_USBSTS_MASK)) return IRQ_NONE; if ((otgsc & OTGSC_IDIS) && (otgsc & OTGSC_IDIE)) { if (otgsc & OTGSC_ID) { pr_debug("Id set\n"); set_bit(ID, &motg->inputs); } else { pr_debug("Id clear\n"); /* * Assert a_bus_req to supply power on * VBUS when Micro/Mini-A cable is connected * with out user intervention. */ set_bit(A_BUS_REQ, &motg->inputs); clear_bit(ID, &motg->inputs); msm_chg_enable_aca_det(motg); } writel_relaxed(otgsc, USB_OTGSC); work = 1; } else if (otgsc & OTGSC_DPIS) { pr_debug("DPIS detected\n"); writel_relaxed(otgsc, USB_OTGSC); set_bit(A_SRP_DET, &motg->inputs); set_bit(A_BUS_REQ, &motg->inputs); work = 1; } else if (otgsc & OTGSC_BSVIS) { writel_relaxed(otgsc, USB_OTGSC); /* * BSV interrupt comes when operating as an A-device * (VBUS on/off). * But, handle BSV when charger is removed from ACA in ID_A */ if ((otg->phy->state >= OTG_STATE_A_IDLE) && !test_bit(ID_A, &motg->inputs)) return IRQ_HANDLED; if (otgsc & OTGSC_BSV) { pr_debug("BSV set\n"); set_bit(B_SESS_VLD, &motg->inputs); } else { pr_debug("BSV clear\n"); clear_bit(B_SESS_VLD, &motg->inputs); clear_bit(A_BUS_SUSPEND, &motg->inputs); msm_chg_check_aca_intr(motg); } work = 1; } else if (usbsts & STS_PCI) { pc = readl_relaxed(USB_PORTSC); pr_debug("portsc = %x\n", pc); ret = IRQ_NONE; /* * HCD Acks PCI interrupt. We use this to switch * between different OTG states. */ work = 1; switch (otg->phy->state) { case OTG_STATE_A_SUSPEND: if (otg->host->b_hnp_enable && (pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("B_CONN clear\n"); clear_bit(B_CONN, &motg->inputs); msm_otg_del_timer(motg); } break; case OTG_STATE_A_PERIPHERAL: /* * A-peripheral observed activity on bus. * clear A_BIDL_ADIS timer. */ msm_otg_del_timer(motg); work = 0; break; case OTG_STATE_B_WAIT_ACON: if ((pc & PORTSC_CSC) && (pc & PORTSC_CCS)) { pr_debug("A_CONN set\n"); set_bit(A_CONN, &motg->inputs); /* Clear ASE0_BRST timer */ msm_otg_del_timer(motg); } break; case OTG_STATE_B_HOST: if ((pc & PORTSC_CSC) && !(pc & PORTSC_CCS)) { pr_debug("A_CONN clear\n"); clear_bit(A_CONN, &motg->inputs); msm_otg_del_timer(motg); } break; case OTG_STATE_A_WAIT_BCON: if (TA_WAIT_BCON < 0) set_bit(A_BUS_REQ, &motg->inputs); default: work = 0; break; } } else if (usbsts & STS_URI) { ret = IRQ_NONE; switch (otg->phy->state) { case OTG_STATE_A_PERIPHERAL: /* * A-peripheral observed activity on bus. * clear A_BIDL_ADIS timer. */ msm_otg_del_timer(motg); work = 0; break; default: work = 0; break; } } else if (usbsts & STS_SLI) { ret = IRQ_NONE; work = 0; switch (otg->phy->state) { case OTG_STATE_B_PERIPHERAL: if (otg->gadget->b_hnp_enable) { set_bit(A_BUS_SUSPEND, &motg->inputs); set_bit(B_BUS_REQ, &motg->inputs); work = 1; } break; case OTG_STATE_A_PERIPHERAL: msm_otg_start_timer(motg, TA_BIDL_ADIS, A_BIDL_ADIS); break; default: break; } } else if ((usbsts & PHY_ALT_INT)) { writel_relaxed(PHY_ALT_INT, USB_USBSTS); if (msm_chg_check_aca_intr(motg)) work = 1; ret = IRQ_HANDLED; } if (work) queue_work(system_nrt_wq, &motg->sm_work); return ret; } static void msm_otg_set_vbus_state(int online) { static bool init; struct msm_otg *motg = the_msm_otg; struct usb_otg *otg = motg->phy.otg; /* In A Host Mode, ignore received BSV interrupts */ if (otg->phy->state >= OTG_STATE_A_IDLE) return; if (online) { pr_debug("PMIC: BSV set\n"); set_bit(B_SESS_VLD, &motg->inputs); } else { pr_debug("PMIC: BSV clear\n"); clear_bit(B_SESS_VLD, &motg->inputs); } if (!init) { init = true; complete(&pmic_vbus_init); pr_debug("PMIC: BSV init complete\n"); return; } if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else queue_work(system_nrt_wq, &motg->sm_work); } static void msm_pmic_id_status_w(struct work_struct *w) { struct msm_otg *motg = container_of(w, struct msm_otg, pmic_id_status_work.work); int work = 0; unsigned long flags; local_irq_save(flags); if (irq_read_line(motg->pdata->pmic_id_irq)) { if (!test_and_set_bit(ID, &motg->inputs)) { pr_debug("PMIC: ID set\n"); work = 1; } } else { if (test_and_clear_bit(ID, &motg->inputs)) { pr_debug("PMIC: ID clear\n"); set_bit(A_BUS_REQ, &motg->inputs); work = 1; } } if (work && (motg->phy.state != OTG_STATE_UNDEFINED)) { if (atomic_read(&motg->pm_suspended)) motg->sm_work_pending = true; else queue_work(system_nrt_wq, &motg->sm_work); } local_irq_restore(flags); } #define MSM_PMIC_ID_STATUS_DELAY 5 /* 5msec */ static irqreturn_t msm_pmic_id_irq(int irq, void *data) { struct msm_otg *motg = data; if (!aca_id_turned_on) /*schedule delayed work for 5msec for ID line state to settle*/ queue_delayed_work(system_nrt_wq, &motg->pmic_id_status_work, msecs_to_jiffies(MSM_PMIC_ID_STATUS_DELAY)); return IRQ_HANDLED; } static int msm_otg_mode_show(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; struct usb_phy *phy = &motg->phy; switch (phy->state) { case OTG_STATE_A_HOST: seq_printf(s, "host\n"); break; case OTG_STATE_B_PERIPHERAL: seq_printf(s, "peripheral\n"); break; default: seq_printf(s, "none\n"); break; } return 0; } static int msm_otg_mode_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_mode_show, inode->i_private); } static ssize_t msm_otg_mode_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { struct seq_file *s = file->private_data; struct msm_otg *motg = s->private; char buf[16]; struct usb_phy *phy = &motg->phy; int status = count; enum usb_mode_type req_mode; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) { status = -EFAULT; goto out; } if (!strncmp(buf, "host", 4)) { req_mode = USB_HOST; } else if (!strncmp(buf, "peripheral", 10)) { req_mode = USB_PERIPHERAL; } else if (!strncmp(buf, "none", 4)) { req_mode = USB_NONE; } else { status = -EINVAL; goto out; } switch (req_mode) { case USB_NONE: switch (phy->state) { case OTG_STATE_A_HOST: case OTG_STATE_B_PERIPHERAL: set_bit(ID, &motg->inputs); clear_bit(B_SESS_VLD, &motg->inputs); break; default: goto out; } break; case USB_PERIPHERAL: switch (phy->state) { case OTG_STATE_B_IDLE: case OTG_STATE_A_HOST: set_bit(ID, &motg->inputs); set_bit(B_SESS_VLD, &motg->inputs); break; default: goto out; } break; case USB_HOST: switch (phy->state) { case OTG_STATE_B_IDLE: case OTG_STATE_B_PERIPHERAL: clear_bit(ID, &motg->inputs); break; default: goto out; } break; default: goto out; } pm_runtime_resume(phy->dev); queue_work(system_nrt_wq, &motg->sm_work); out: return status; } const struct file_operations msm_otg_mode_fops = { .open = msm_otg_mode_open, .read = seq_read, .write = msm_otg_mode_write, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_show_otg_state(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; struct usb_phy *phy = &motg->phy; seq_printf(s, "%s\n", otg_state_string(phy->state)); return 0; } static int msm_otg_otg_state_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_show_otg_state, inode->i_private); } const struct file_operations msm_otg_state_fops = { .open = msm_otg_otg_state_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_show_chg_type(struct seq_file *s, void *unused) { struct msm_otg *motg = s->private; seq_printf(s, "%s\n", chg_to_string(motg->chg_type)); return 0; } static int msm_otg_chg_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_show_chg_type, inode->i_private); } const struct file_operations msm_otg_chg_fops = { .open = msm_otg_chg_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_aca_show(struct seq_file *s, void *unused) { if (debug_aca_enabled) seq_printf(s, "enabled\n"); else seq_printf(s, "disabled\n"); return 0; } static int msm_otg_aca_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_aca_show, inode->i_private); } static ssize_t msm_otg_aca_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { char buf[8]; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) return -EFAULT; if (!strncmp(buf, "enable", 6)) debug_aca_enabled = true; else debug_aca_enabled = false; return count; } const struct file_operations msm_otg_aca_fops = { .open = msm_otg_aca_open, .read = seq_read, .write = msm_otg_aca_write, .llseek = seq_lseek, .release = single_release, }; static int msm_otg_bus_show(struct seq_file *s, void *unused) { if (debug_bus_voting_enabled) seq_printf(s, "enabled\n"); else seq_printf(s, "disabled\n"); return 0; } static int msm_otg_bus_open(struct inode *inode, struct file *file) { return single_open(file, msm_otg_bus_show, inode->i_private); } static ssize_t msm_otg_bus_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) { char buf[8]; int ret; struct seq_file *s = file->private_data; struct msm_otg *motg = s->private; memset(buf, 0x00, sizeof(buf)); if (copy_from_user(&buf, ubuf, min_t(size_t, sizeof(buf) - 1, count))) return -EFAULT; if (!strncmp(buf, "enable", 6)) { /* Do not vote here. Let OTG statemachine decide when to vote */ debug_bus_voting_enabled = true; } else { debug_bus_voting_enabled = false; if (motg->bus_perf_client) { ret = msm_bus_scale_client_update_request( motg->bus_perf_client, 0); if (ret) dev_err(motg->phy.dev, "%s: Failed to devote " "for bus bw %d\n", __func__, ret); } } return count; } const struct file_operations msm_otg_bus_fops = { .open = msm_otg_bus_open, .read = seq_read, .write = msm_otg_bus_write, .llseek = seq_lseek, .release = single_release, }; static struct dentry *msm_otg_dbg_root; static int msm_otg_debugfs_init(struct msm_otg *motg) { struct dentry *msm_otg_dentry; msm_otg_dbg_root = debugfs_create_dir("msm_otg", NULL); if (!msm_otg_dbg_root || IS_ERR(msm_otg_dbg_root)) return -ENODEV; if (motg->pdata->mode == USB_OTG && motg->pdata->otg_control == OTG_USER_CONTROL) { msm_otg_dentry = debugfs_create_file("mode", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_mode_fops); if (!msm_otg_dentry) { debugfs_remove(msm_otg_dbg_root); msm_otg_dbg_root = NULL; return -ENODEV; } } msm_otg_dentry = debugfs_create_file("chg_type", S_IRUGO, msm_otg_dbg_root, motg, &msm_otg_chg_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("aca", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_aca_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("bus_voting", S_IRUGO | S_IWUSR, msm_otg_dbg_root, motg, &msm_otg_bus_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } msm_otg_dentry = debugfs_create_file("otg_state", S_IRUGO, msm_otg_dbg_root, motg, &msm_otg_state_fops); if (!msm_otg_dentry) { debugfs_remove_recursive(msm_otg_dbg_root); return -ENODEV; } return 0; } static void msm_otg_debugfs_cleanup(void) { debugfs_remove_recursive(msm_otg_dbg_root); } static u64 msm_otg_dma_mask = DMA_BIT_MASK(64); static struct platform_device *msm_otg_add_pdev( struct platform_device *ofdev, const char *name) { struct platform_device *pdev; const struct resource *res = ofdev->resource; unsigned int num = ofdev->num_resources; int retval; pdev = platform_device_alloc(name, -1); if (!pdev) { retval = -ENOMEM; goto error; } pdev->dev.coherent_dma_mask = DMA_BIT_MASK(32); pdev->dev.dma_mask = &msm_otg_dma_mask; if (num) { retval = platform_device_add_resources(pdev, res, num); if (retval) goto error; } retval = platform_device_add(pdev); if (retval) goto error; return pdev; error: platform_device_put(pdev); return ERR_PTR(retval); } static int msm_otg_setup_devices(struct platform_device *ofdev, enum usb_mode_type mode, bool init) { const char *gadget_name = "msm_hsusb"; const char *host_name = "msm_hsusb_host"; static struct platform_device *gadget_pdev; static struct platform_device *host_pdev; int retval = 0; if (!init) { if (gadget_pdev) platform_device_unregister(gadget_pdev); if (host_pdev) platform_device_unregister(host_pdev); return 0; } switch (mode) { case USB_OTG: /* fall through */ case USB_PERIPHERAL: gadget_pdev = msm_otg_add_pdev(ofdev, gadget_name); if (IS_ERR(gadget_pdev)) { retval = PTR_ERR(gadget_pdev); break; } if (mode == USB_PERIPHERAL) break; /* fall through */ case USB_HOST: host_pdev = msm_otg_add_pdev(ofdev, host_name); if (IS_ERR(host_pdev)) { retval = PTR_ERR(host_pdev); if (mode == USB_OTG) platform_device_unregister(gadget_pdev); } break; default: break; } return retval; } struct msm_otg_platform_data *msm_otg_dt_to_pdata(struct platform_device *pdev) { struct device_node *node = pdev->dev.of_node; struct msm_otg_platform_data *pdata; int len = 0; pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { pr_err("unable to allocate platform data\n"); return NULL; } of_get_property(node, "qcom,hsusb-otg-phy-init-seq", &len); if (len) { pdata->phy_init_seq = devm_kzalloc(&pdev->dev, len, GFP_KERNEL); if (!pdata->phy_init_seq) return NULL; of_property_read_u32_array(node, "qcom,hsusb-otg-phy-init-seq", pdata->phy_init_seq, len/sizeof(*pdata->phy_init_seq)); } of_property_read_u32(node, "qcom,hsusb-otg-power-budget", &pdata->power_budget); of_property_read_u32(node, "qcom,hsusb-otg-mode", &pdata->mode); of_property_read_u32(node, "qcom,hsusb-otg-otg-control", &pdata->otg_control); of_property_read_u32(node, "qcom,hsusb-otg-default-mode", &pdata->default_mode); of_property_read_u32(node, "qcom,hsusb-otg-phy-type", &pdata->phy_type); of_property_read_u32(node, "qcom,hsusb-otg-pmic-id-irq", &pdata->pmic_id_irq); return pdata; } static int __init msm_otg_probe(struct platform_device *pdev) { int ret = 0; struct resource *res; struct msm_otg *motg; struct usb_phy *phy; struct msm_otg_platform_data *pdata; dev_info(&pdev->dev, "msm_otg probe\n"); if (pdev->dev.of_node) { dev_dbg(&pdev->dev, "device tree enabled\n"); pdata = msm_otg_dt_to_pdata(pdev); if (!pdata) return -ENOMEM; ret = msm_otg_setup_devices(pdev, pdata->mode, true); if (ret) { dev_err(&pdev->dev, "devices setup failed\n"); return ret; } } else if (!pdev->dev.platform_data) { dev_err(&pdev->dev, "No platform data given. Bailing out\n"); return -ENODEV; } else { pdata = pdev->dev.platform_data; } motg = kzalloc(sizeof(struct msm_otg), GFP_KERNEL); if (!motg) { dev_err(&pdev->dev, "unable to allocate msm_otg\n"); return -ENOMEM; } motg->phy.otg = kzalloc(sizeof(struct usb_otg), GFP_KERNEL); if (!motg->phy.otg) { dev_err(&pdev->dev, "unable to allocate usb_otg\n"); ret = -ENOMEM; goto free_motg; } the_msm_otg = motg; motg->pdata = pdata; phy = &motg->phy; phy->dev = &pdev->dev; /* * ACA ID_GND threshold range is overlapped with OTG ID_FLOAT. Hence * PHY treat ACA ID_GND as float and no interrupt is generated. But * PMIC can detect ACA ID_GND and generate an interrupt. */ if (aca_enabled() && motg->pdata->otg_control != OTG_PMIC_CONTROL) { dev_err(&pdev->dev, "ACA can not be enabled without PMIC\n"); ret = -EINVAL; goto free_otg; } /* initialize reset counter */ motg->reset_counter = 0; /* Some targets don't support PHY clock. */ motg->phy_reset_clk = clk_get(&pdev->dev, "phy_clk"); if (IS_ERR(motg->phy_reset_clk)) dev_err(&pdev->dev, "failed to get phy_clk\n"); /* * Targets on which link uses asynchronous reset methodology, * free running clock is not required during the reset. */ motg->clk = clk_get(&pdev->dev, "alt_core_clk"); if (IS_ERR(motg->clk)) dev_dbg(&pdev->dev, "alt_core_clk is not present\n"); else clk_set_rate(motg->clk, 60000000); /* * USB Core is running its protocol engine based on CORE CLK, * CORE CLK must be running at >55Mhz for correct HSUSB * operation and USB core cannot tolerate frequency changes on * CORE CLK. For such USB cores, vote for maximum clk frequency * on pclk source */ motg->core_clk = clk_get(&pdev->dev, "core_clk"); if (IS_ERR(motg->core_clk)) { motg->core_clk = NULL; dev_err(&pdev->dev, "failed to get core_clk\n"); ret = PTR_ERR(motg->core_clk); goto put_clk; } clk_set_rate(motg->core_clk, INT_MAX); motg->pclk = clk_get(&pdev->dev, "iface_clk"); if (IS_ERR(motg->pclk)) { dev_err(&pdev->dev, "failed to get iface_clk\n"); ret = PTR_ERR(motg->pclk); goto put_core_clk; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "failed to get platform resource mem\n"); ret = -ENODEV; goto put_pclk; } motg->regs = ioremap(res->start, resource_size(res)); if (!motg->regs) { dev_err(&pdev->dev, "ioremap failed\n"); ret = -ENOMEM; goto put_pclk; } dev_info(&pdev->dev, "OTG regs = %p\n", motg->regs); motg->irq = platform_get_irq(pdev, 0); if (!motg->irq) { dev_err(&pdev->dev, "platform_get_irq failed\n"); ret = -ENODEV; goto free_regs; } motg->xo_handle = msm_xo_get(MSM_XO_TCXO_D0, "usb"); if (IS_ERR(motg->xo_handle)) { dev_err(&pdev->dev, "%s not able to get the handle " "to vote for TCXO D0 buffer\n", __func__); ret = PTR_ERR(motg->xo_handle); goto free_regs; } ret = msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_ON); if (ret) { dev_err(&pdev->dev, "%s failed to vote for TCXO " "D0 buffer%d\n", __func__, ret); goto free_xo_handle; } clk_prepare_enable(motg->pclk); motg->vdd_type = VDDCX_CORNER; hsusb_vddcx = devm_regulator_get(motg->phy.dev, "hsusb_vdd_dig"); if (IS_ERR(hsusb_vddcx)) { hsusb_vddcx = devm_regulator_get(motg->phy.dev, "HSUSB_VDDCX"); if (IS_ERR(hsusb_vddcx)) { dev_err(motg->phy.dev, "unable to get hsusb vddcx\n"); ret = PTR_ERR(hsusb_vddcx); goto devote_xo_handle; } motg->vdd_type = VDDCX; } ret = msm_hsusb_config_vddcx(1); if (ret) { dev_err(&pdev->dev, "hsusb vddcx configuration failed\n"); goto devote_xo_handle; } ret = regulator_enable(hsusb_vddcx); if (ret) { dev_err(&pdev->dev, "unable to enable the hsusb vddcx\n"); goto free_config_vddcx; } ret = msm_hsusb_ldo_init(motg, 1); if (ret) { dev_err(&pdev->dev, "hsusb vreg configuration failed\n"); goto free_hsusb_vddcx; } if (pdata->mhl_enable) { mhl_usb_hs_switch = devm_regulator_get(motg->phy.dev, "mhl_usb_hs_switch"); if (IS_ERR(mhl_usb_hs_switch)) { dev_err(&pdev->dev, "Unable to get mhl_usb_hs_switch\n"); ret = PTR_ERR(mhl_usb_hs_switch); goto free_ldo_init; } } ret = msm_hsusb_ldo_enable(motg, 1); if (ret) { dev_err(&pdev->dev, "hsusb vreg enable failed\n"); goto free_ldo_init; } clk_prepare_enable(motg->core_clk); writel(0, USB_USBINTR); writel(0, USB_OTGSC); /* Ensure that above STOREs are completed before enabling interrupts */ mb(); wake_lock_init(&motg->wlock, WAKE_LOCK_SUSPEND, "msm_otg"); msm_otg_init_timer(motg); INIT_WORK(&motg->sm_work, msm_otg_sm_work); INIT_DELAYED_WORK(&motg->chg_work, msm_chg_detect_work); INIT_DELAYED_WORK(&motg->pmic_id_status_work, msm_pmic_id_status_w); setup_timer(&motg->id_timer, msm_otg_id_timer_func, (unsigned long) motg); ret = request_irq(motg->irq, msm_otg_irq, IRQF_SHARED, "msm_otg", motg); if (ret) { dev_err(&pdev->dev, "request irq failed\n"); goto destroy_wlock; } phy->init = msm_otg_reset; phy->set_power = msm_otg_set_power; phy->set_suspend = msm_otg_set_suspend; phy->io_ops = &msm_otg_io_ops; phy->otg->phy = &motg->phy; phy->otg->set_host = msm_otg_set_host; phy->otg->set_peripheral = msm_otg_set_peripheral; phy->otg->start_hnp = msm_otg_start_hnp; phy->otg->start_srp = msm_otg_start_srp; ret = usb_set_transceiver(&motg->phy); if (ret) { dev_err(&pdev->dev, "usb_set_transceiver failed\n"); goto free_irq; } if (motg->pdata->mode == USB_OTG && motg->pdata->otg_control == OTG_PMIC_CONTROL) { if (motg->pdata->pmic_id_irq) { ret = request_irq(motg->pdata->pmic_id_irq, msm_pmic_id_irq, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "msm_otg", motg); if (ret) { dev_err(&pdev->dev, "request irq failed for PMIC ID\n"); goto remove_phy; } } else { ret = -ENODEV; dev_err(&pdev->dev, "PMIC IRQ for ID notifications doesn't exist\n"); goto remove_phy; } } msm_hsusb_mhl_switch_enable(motg, 1); platform_set_drvdata(pdev, motg); device_init_wakeup(&pdev->dev, 1); motg->mA_port = IUNIT; ret = msm_otg_debugfs_init(motg); if (ret) dev_dbg(&pdev->dev, "mode debugfs file is" "not available\n"); if (motg->pdata->otg_control == OTG_PMIC_CONTROL) pm8921_charger_register_vbus_sn(&msm_otg_set_vbus_state); if (motg->pdata->phy_type == SNPS_28NM_INTEGRATED_PHY) { if (motg->pdata->otg_control == OTG_PMIC_CONTROL && (!(motg->pdata->mode == USB_OTG) || motg->pdata->pmic_id_irq)) motg->caps = ALLOW_PHY_POWER_COLLAPSE | ALLOW_PHY_RETENTION; if (motg->pdata->otg_control == OTG_PHY_CONTROL) motg->caps = ALLOW_PHY_RETENTION; } if (motg->pdata->enable_lpm_on_dev_suspend) motg->caps |= ALLOW_LPM_ON_DEV_SUSPEND; wake_lock(&motg->wlock); pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); if (motg->pdata->bus_scale_table) { motg->bus_perf_client = msm_bus_scale_register_client(motg->pdata->bus_scale_table); if (!motg->bus_perf_client) dev_err(motg->phy.dev, "%s: Failed to register BUS " "scaling client!!\n", __func__); else debug_bus_voting_enabled = true; } return 0; remove_phy: usb_set_transceiver(NULL); free_irq: free_irq(motg->irq, motg); destroy_wlock: wake_lock_destroy(&motg->wlock); clk_disable_unprepare(motg->core_clk); msm_hsusb_ldo_enable(motg, 0); free_ldo_init: msm_hsusb_ldo_init(motg, 0); free_hsusb_vddcx: regulator_disable(hsusb_vddcx); free_config_vddcx: regulator_set_voltage(hsusb_vddcx, vdd_val[motg->vdd_type][VDD_NONE], vdd_val[motg->vdd_type][VDD_MAX]); devote_xo_handle: clk_disable_unprepare(motg->pclk); msm_xo_mode_vote(motg->xo_handle, MSM_XO_MODE_OFF); free_xo_handle: msm_xo_put(motg->xo_handle); free_regs: iounmap(motg->regs); put_pclk: clk_put(motg->pclk); put_core_clk: clk_put(motg->core_clk); put_clk: if (!IS_ERR(motg->clk)) clk_put(motg->clk); if (!IS_ERR(motg->phy_reset_clk)) clk_put(motg->phy_reset_clk); free_otg: kfree(motg->phy.otg); free_motg: kfree(motg); return ret; } static int __devexit msm_otg_remove(struct platform_device *pdev) { struct msm_otg *motg = platform_get_drvdata(pdev); struct usb_otg *otg = motg->phy.otg; int cnt = 0; if (otg->host || otg->gadget) return -EBUSY; if (pdev->dev.of_node) msm_otg_setup_devices(pdev, motg->pdata->mode, false); if (motg->pdata->otg_control == OTG_PMIC_CONTROL) pm8921_charger_unregister_vbus_sn(0); msm_otg_debugfs_cleanup(); cancel_delayed_work_sync(&motg->chg_work); cancel_delayed_work_sync(&motg->pmic_id_status_work); cancel_work_sync(&motg->sm_work); pm_runtime_resume(&pdev->dev); device_init_wakeup(&pdev->dev, 0); pm_runtime_disable(&pdev->dev); wake_lock_destroy(&motg->wlock); msm_hsusb_mhl_switch_enable(motg, 0); if (motg->pdata->pmic_id_irq) free_irq(motg->pdata->pmic_id_irq, motg); usb_set_transceiver(NULL); free_irq(motg->irq, motg); /* * Put PHY in low power mode. */ ulpi_read(otg->phy, 0x14); ulpi_write(otg->phy, 0x08, 0x09); writel(readl(USB_PORTSC) | PORTSC_PHCD, USB_PORTSC); while (cnt < PHY_SUSPEND_TIMEOUT_USEC) { if (readl(USB_PORTSC) & PORTSC_PHCD) break; udelay(1); cnt++; } if (cnt >= PHY_SUSPEND_TIMEOUT_USEC) dev_err(otg->phy->dev, "Unable to suspend PHY\n"); clk_disable_unprepare(motg->pclk); clk_disable_unprepare(motg->core_clk); msm_xo_put(motg->xo_handle); msm_hsusb_ldo_enable(motg, 0); msm_hsusb_ldo_init(motg, 0); regulator_disable(hsusb_vddcx); regulator_set_voltage(hsusb_vddcx, vdd_val[motg->vdd_type][VDD_NONE], vdd_val[motg->vdd_type][VDD_MAX]); iounmap(motg->regs); pm_runtime_set_suspended(&pdev->dev); if (!IS_ERR(motg->phy_reset_clk)) clk_put(motg->phy_reset_clk); clk_put(motg->pclk); if (!IS_ERR(motg->clk)) clk_put(motg->clk); clk_put(motg->core_clk); if (motg->bus_perf_client) msm_bus_scale_unregister_client(motg->bus_perf_client); kfree(motg->phy.otg); kfree(motg); return 0; } #ifdef CONFIG_PM_RUNTIME static int msm_otg_runtime_idle(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); struct usb_phy *phy = &motg->phy; dev_dbg(dev, "OTG runtime idle\n"); if (phy->state == OTG_STATE_UNDEFINED) return -EAGAIN; else return 0; } static int msm_otg_runtime_suspend(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG runtime suspend\n"); return msm_otg_suspend(motg); } static int msm_otg_runtime_resume(struct device *dev) { struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG runtime resume\n"); pm_runtime_get_noresume(dev); return msm_otg_resume(motg); } #endif #ifdef CONFIG_PM_SLEEP static int msm_otg_pm_suspend(struct device *dev) { int ret = 0; struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG PM suspend\n"); atomic_set(&motg->pm_suspended, 1); ret = msm_otg_suspend(motg); if (ret) atomic_set(&motg->pm_suspended, 0); return ret; } static int msm_otg_pm_resume(struct device *dev) { int ret = 0; struct msm_otg *motg = dev_get_drvdata(dev); dev_dbg(dev, "OTG PM resume\n"); atomic_set(&motg->pm_suspended, 0); if (motg->sm_work_pending) { motg->sm_work_pending = false; pm_runtime_get_noresume(dev); ret = msm_otg_resume(motg); /* Update runtime PM status */ pm_runtime_disable(dev); pm_runtime_set_active(dev); pm_runtime_enable(dev); queue_work(system_nrt_wq, &motg->sm_work); } return ret; } #endif #ifdef CONFIG_PM static const struct dev_pm_ops msm_otg_dev_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(msm_otg_pm_suspend, msm_otg_pm_resume) SET_RUNTIME_PM_OPS(msm_otg_runtime_suspend, msm_otg_runtime_resume, msm_otg_runtime_idle) }; #endif static struct of_device_id msm_otg_dt_match[] = { { .compatible = "qcom,hsusb-otg", }, {} }; static struct platform_driver msm_otg_driver = { .remove = __devexit_p(msm_otg_remove), .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &msm_otg_dev_pm_ops, #endif .of_match_table = msm_otg_dt_match, }, }; static int __init msm_otg_init(void) { return platform_driver_probe(&msm_otg_driver, msm_otg_probe); } static void __exit msm_otg_exit(void) { platform_driver_unregister(&msm_otg_driver); } module_init(msm_otg_init); module_exit(msm_otg_exit); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("MSM USB transceiver driver");
gpl-2.0
trungdovan87/bongda69
wp-content/plugins/loco-translate/lib/test/tests/ResolveFileDomainTest.php
1625
<?php /** * Test LocoAdmin::resolve_file_domain */ class ResolveFileDomainTest extends PHPUnit_Framework_TestCase { public function testDomainOnlySeparatesFromFileExtension(){ $domain = LocoAdmin::resolve_file_domain( '/foo.pot' ); $this->assertEquals( 'foo', $domain ); } public function testFullLocaleSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-en_GB.po' ); $this->assertEquals( 'foo', $domain ); } public function testFullLocaleWithLongLanguageSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-rup_MK.po' ); $this->assertEquals( 'foo', $domain ); } public function testLanguageCodeSeparatesFromDomainByHyphen(){ $domain = LocoAdmin::resolve_file_domain( '/foo-en.po' ); $this->assertEquals( 'foo', $domain ); } public function testValidLanguageCodeNotUsedAsDomain(){ $domain = LocoAdmin::resolve_file_domain( '/fr_FR.po' ); $this->assertSame( '', $domain ); } public function testInvalidLanguageCodeNotUsedAsDomain(){ $domain = LocoAdmin::resolve_file_domain( '/en_EN.po' ); $this->assertSame( '', $domain ); } public function testValidLanguageCodeNotUsedAsDomainWhenPot(){ $domain = LocoAdmin::resolve_file_domain( '/fr_FR.pot' ); $this->assertSame( '', $domain ); } public function testInvalidLanguageCodeNotUsedAsDomainWhenPot(){ $domain = LocoAdmin::resolve_file_domain( '/en_EN.pot' ); $this->assertSame( '', $domain ); } }
gpl-2.0
lojies/kubernetes
cmd/kubeadm/app/util/apiclient/init_dryrun.go
6278
/* Copyright 2017 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 apiclient import ( "strings" "github.com/pkg/errors" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" core "k8s.io/client-go/testing" netutils "k8s.io/utils/net" "k8s.io/kubernetes/cmd/kubeadm/app/constants" ) // InitDryRunGetter implements the DryRunGetter interface and can be used to GET/LIST values in the dryrun fake clientset // Need to handle these routes in a special manner: // - GET /default/services/kubernetes -- must return a valid Service // - GET /clusterrolebindings/system:nodes -- can safely return a NotFound error // - GET /kube-system/secrets/bootstrap-token-* -- can safely return a NotFound error // - GET /nodes/<node-name> -- must return a valid Node // - ...all other, unknown GETs/LISTs will be logged type InitDryRunGetter struct { controlPlaneName string serviceSubnet string } // InitDryRunGetter should implement the DryRunGetter interface var _ DryRunGetter = &InitDryRunGetter{} // NewInitDryRunGetter creates a new instance of the InitDryRunGetter struct func NewInitDryRunGetter(controlPlaneName string, serviceSubnet string) *InitDryRunGetter { return &InitDryRunGetter{ controlPlaneName: controlPlaneName, serviceSubnet: serviceSubnet, } } // HandleGetAction handles GET actions to the dryrun clientset this interface supports func (idr *InitDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error) { funcs := []func(core.GetAction) (bool, runtime.Object, error){ idr.handleKubernetesService, idr.handleGetNode, idr.handleSystemNodesClusterRoleBinding, idr.handleGetBootstrapToken, } for _, f := range funcs { handled, obj, err := f(action) if handled { return handled, obj, err } } return false, nil, nil } // HandleListAction handles GET actions to the dryrun clientset this interface supports. // Currently there are no known LIST calls during kubeadm init this code has to take care of. func (idr *InitDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error) { return false, nil, nil } // handleKubernetesService returns a faked Kubernetes service in order to be able to continue running kubeadm init. // The CoreDNS addon code GETs the Kubernetes service in order to extract the service subnet func (idr *InitDryRunGetter) handleKubernetesService(action core.GetAction) (bool, runtime.Object, error) { if action.GetName() != "kubernetes" || action.GetNamespace() != metav1.NamespaceDefault || action.GetResource().Resource != "services" { // We can't handle this event return false, nil, nil } _, svcSubnet, err := netutils.ParseCIDRSloppy(idr.serviceSubnet) if err != nil { return true, nil, errors.Wrapf(err, "error parsing CIDR %q", idr.serviceSubnet) } internalAPIServerVirtualIP, err := netutils.GetIndexedIP(svcSubnet, 1) if err != nil { return true, nil, errors.Wrapf(err, "unable to get first IP address from the given CIDR (%s)", svcSubnet.String()) } // The only used field of this Service object is the ClusterIP, which CoreDNS uses to calculate its own IP return true, &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "kubernetes", Namespace: metav1.NamespaceDefault, Labels: map[string]string{ "component": "apiserver", "provider": "kubernetes", }, }, Spec: v1.ServiceSpec{ ClusterIP: internalAPIServerVirtualIP.String(), Ports: []v1.ServicePort{ { Name: "https", Port: 443, TargetPort: intstr.FromInt(6443), }, }, }, }, nil } // handleGetNode returns a fake node object for the purpose of moving kubeadm init forwards. func (idr *InitDryRunGetter) handleGetNode(action core.GetAction) (bool, runtime.Object, error) { if action.GetName() != idr.controlPlaneName || action.GetResource().Resource != "nodes" { // We can't handle this event return false, nil, nil } return true, &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: idr.controlPlaneName, Labels: map[string]string{ "kubernetes.io/hostname": idr.controlPlaneName, }, Annotations: map[string]string{}, }, }, nil } // handleSystemNodesClusterRoleBinding handles the GET call to the system:nodes clusterrolebinding func (idr *InitDryRunGetter) handleSystemNodesClusterRoleBinding(action core.GetAction) (bool, runtime.Object, error) { if action.GetName() != constants.NodesClusterRoleBinding || action.GetResource().Resource != "clusterrolebindings" { // We can't handle this event return false, nil, nil } // We can safely return a NotFound error here as the code will just proceed normally and don't care about modifying this clusterrolebinding // This can only happen on an upgrade; and in that case the ClientBackedDryRunGetter impl will be used return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), "clusterrolebinding not found") } // handleGetBootstrapToken handles the case where kubeadm init creates the default token; and the token code GETs the // bootstrap token secret first in order to check if it already exists func (idr *InitDryRunGetter) handleGetBootstrapToken(action core.GetAction) (bool, runtime.Object, error) { if !strings.HasPrefix(action.GetName(), "bootstrap-token-") || action.GetNamespace() != metav1.NamespaceSystem || action.GetResource().Resource != "secrets" { // We can't handle this event return false, nil, nil } // We can safely return a NotFound error here as the code will just proceed normally and create the Bootstrap Token return true, nil, apierrors.NewNotFound(action.GetResource().GroupResource(), "secret not found") }
apache-2.0
wseyler/pentaho-kettle
ui/src/main/java/org/pentaho/di/ui/spoon/SpoonPerspective.java
3197
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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 org.pentaho.di.ui.spoon; import java.io.InputStream; import java.util.List; import java.util.Locale; import org.eclipse.swt.widgets.Composite; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.ui.xul.XulOverlay; import org.pentaho.ui.xul.impl.XulEventHandler; /** * A SpoonPerspective is able to modify the look of the application and display it's own UI. Only one perspective can be * active at a time though they can run concurrently. SpoonPerspectives are most likely to be registered as part of a * SpoonPlugin. * * @author nbaker */ public interface SpoonPerspective { /** * Returns a unique identifier for this perspective * * @return unique ID */ public String getId(); /** * Returns the main UI for the perspective. * * @return UI Composite */ public Composite getUI(); /** * Returns a localized name for the perspective * * @param l * current Locale * @return localized name */ public String getDisplayName( Locale l ); /** * Perspectives will be represented in spoon by an icon on the main toolbar. This method returns the InputStream for * that icon. * * @return icon InputStream */ public InputStream getPerspectiveIcon(); /** * Called by Spoon whenever the active state of a perspective changes. * * @param active */ public void setActive( boolean active ); /** * A list of Xul Overlays to be applied and removed when the perspective is loaded or unloaded * * @return List of XulOverlays. */ public List<XulOverlay> getOverlays(); /** * Returns a list of Xul Event Handlers (controllers) to be added to Xul Containers in Spoon. Perspectives may * overwrite existing event handlers by registering one with the same ID. * * @return list of XulEventHandlers */ public List<XulEventHandler> getEventHandlers(); /** * Allows outside code to register to for activation events for this perspective. * * @param listener */ public void addPerspectiveListener( SpoonPerspectiveListener listener ); /** * Return the active EngineMeta in the case of perspectives with save-able content. * * @return active EngineMetaInterface */ public EngineMetaInterface getActiveMeta(); }
apache-2.0
kaviththiranga/developer-studio-cef-client
windows_64/include/base/cef_bind_helpers.h
19694
// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 // Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the name Chromium Embedded // Framework nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This defines a set of argument wrappers and related factory methods that // can be used specify the refcounting and reference semantics of arguments // that are bound by the Bind() function in base/bind.h. // // It also defines a set of simple functions and utilities that people want // when using Callback<> and Bind(). // // // ARGUMENT BINDING WRAPPERS // // The wrapper functions are base::Unretained(), base::Owned(), base::Passed(), // base::ConstRef(), and base::IgnoreResult(). // // Unretained() allows Bind() to bind a non-refcounted class, and to disable // refcounting on arguments that are refcounted objects. // // Owned() transfers ownership of an object to the Callback resulting from // bind; the object will be deleted when the Callback is deleted. // // Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr) // through a Callback. Logically, this signifies a destructive transfer of // the state of the argument into the target function. Invoking // Callback::Run() twice on a Callback that was created with a Passed() // argument will CHECK() because the first invocation would have already // transferred ownership to the target function. // // ConstRef() allows binding a constant reference to an argument rather // than a copy. // // IgnoreResult() is used to adapt a function or Callback with a return type to // one with a void return. This is most useful if you have a function with, // say, a pesky ignorable bool return that you want to use with PostTask or // something else that expect a Callback with a void return. // // EXAMPLE OF Unretained(): // // class Foo { // public: // void func() { cout << "Foo:f" << endl; } // }; // // // In some function somewhere. // Foo foo; // Closure foo_callback = // Bind(&Foo::func, Unretained(&foo)); // foo_callback.Run(); // Prints "Foo:f". // // Without the Unretained() wrapper on |&foo|, the above call would fail // to compile because Foo does not support the AddRef() and Release() methods. // // // EXAMPLE OF Owned(): // // void foo(int* arg) { cout << *arg << endl } // // int* pn = new int(1); // Closure foo_callback = Bind(&foo, Owned(pn)); // // foo_callback.Run(); // Prints "1" // foo_callback.Run(); // Prints "1" // *n = 2; // foo_callback.Run(); // Prints "2" // // foo_callback.Reset(); // |pn| is deleted. Also will happen when // // |foo_callback| goes out of scope. // // Without Owned(), someone would have to know to delete |pn| when the last // reference to the Callback is deleted. // // // EXAMPLE OF ConstRef(): // // void foo(int arg) { cout << arg << endl } // // int n = 1; // Closure no_ref = Bind(&foo, n); // Closure has_ref = Bind(&foo, ConstRef(n)); // // no_ref.Run(); // Prints "1" // has_ref.Run(); // Prints "1" // // n = 2; // no_ref.Run(); // Prints "1" // has_ref.Run(); // Prints "2" // // Note that because ConstRef() takes a reference on |n|, |n| must outlive all // its bound callbacks. // // // EXAMPLE OF IgnoreResult(): // // int DoSomething(int arg) { cout << arg << endl; } // // // Assign to a Callback with a void return type. // Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething)); // cb->Run(1); // Prints "1". // // // Prints "1" on |ml|. // ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1); // // // EXAMPLE OF Passed(): // // void TakesOwnership(scoped_ptr<Foo> arg) { } // scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); } // // scoped_ptr<Foo> f(new Foo()); // // // |cb| is given ownership of Foo(). |f| is now NULL. // // You can use f.Pass() in place of &f, but it's more verbose. // Closure cb = Bind(&TakesOwnership, Passed(&f)); // // // Run was never called so |cb| still owns Foo() and deletes // // it on Reset(). // cb.Reset(); // // // |cb| is given a new Foo created by CreateFoo(). // cb = Bind(&TakesOwnership, Passed(CreateFoo())); // // // |arg| in TakesOwnership() is given ownership of Foo(). |cb| // // no longer owns Foo() and, if reset, would not delete Foo(). // cb.Run(); // Foo() is now transferred to |arg| and deleted. // cb.Run(); // This CHECK()s since Foo() already been used once. // // Passed() is particularly useful with PostTask() when you are transferring // ownership of an argument into a task, but don't necessarily know if the // task will always be executed. This can happen if the task is cancellable // or if it is posted to a MessageLoopProxy. // // // SIMPLE FUNCTIONS AND UTILITIES. // // DoNothing() - Useful for creating a Closure that does nothing when called. // DeletePointer<T>() - Useful for creating a Closure that will delete a // pointer when invoked. Only use this when necessary. // In most cases MessageLoop::DeleteSoon() is a better // fit. #ifndef CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ #define CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ #pragma once #if defined(BASE_BIND_HELPERS_H_) // Do nothing if the Chromium header has already been included. // This can happen in cases where Chromium code is used directly by the // client application. When using Chromium code directly always include // the Chromium header first to avoid type conflicts. #elif defined(BUILDING_CEF_SHARED) // When building CEF include the Chromium header directly. #include "base/bind_helpers.h" #else // !BUILDING_CEF_SHARED // The following is substantially similar to the Chromium implementation. // If the Chromium implementation diverges the below implementation should be // updated to match. #include "include/base/cef_basictypes.h" #include "include/base/cef_callback.h" #include "include/base/cef_template_util.h" #include "include/base/cef_weak_ptr.h" namespace base { namespace internal { // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T // for the existence of AddRef() and Release() functions of the correct // signature. // // http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence // http://stackoverflow.com/questions/4358584/sfinae-approach-comparison // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions // // The last link in particular show the method used below. // // For SFINAE to work with inherited methods, we need to pull some extra tricks // with multiple inheritance. In the more standard formulation, the overloads // of Check would be: // // template <typename C> // Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*); // // template <typename C> // No NotTheCheckWeWant(...); // // static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes); // // The problem here is that template resolution will not match // C::TargetFunc if TargetFunc does not exist directly in C. That is, if // TargetFunc in inherited from an ancestor, &C::TargetFunc will not match, // |value| will be false. This formulation only checks for whether or // not TargetFunc exist directly in the class being introspected. // // To get around this, we play a dirty trick with multiple inheritance. // First, We create a class BaseMixin that declares each function that we // want to probe for. Then we create a class Base that inherits from both T // (the class we wish to probe) and BaseMixin. Note that the function // signature in BaseMixin does not need to match the signature of the function // we are probing for; thus it's easiest to just use void(void). // // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an // ambiguous resolution between BaseMixin and T. This lets us write the // following: // // template <typename C> // No GoodCheck(Helper<&C::TargetFunc>*); // // template <typename C> // Yes GoodCheck(...); // // static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes); // // Notice here that the variadic version of GoodCheck() returns Yes here // instead of No like the previous one. Also notice that we calculate |value| // by specializing GoodCheck() on Base instead of T. // // We've reversed the roles of the variadic, and Helper overloads. // GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid // substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve // to the variadic version if T has TargetFunc. If T::TargetFunc does not // exist, then &C::TargetFunc is not ambiguous, and the overload resolution // will prefer GoodCheck(Helper<&C::TargetFunc>*). // // This method of SFINAE will correctly probe for inherited names, but it cannot // typecheck those names. It's still a good enough sanity check though. // // Works on gcc-4.2, gcc-4.4, and Visual Studio 2008. // // TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted // this works well. // // TODO(ajwong): Make this check for Release() as well. // See http://crbug.com/82038. template <typename T> class SupportsAddRefAndRelease { typedef char Yes[1]; typedef char No[2]; struct BaseMixin { void AddRef(); }; // MSVC warns when you try to use Base if T has a private destructor, the // common pattern for refcounted types. It does this even though no attempt to // instantiate Base is made. We disable the warning for this definition. #if defined(OS_WIN) #pragma warning(push) #pragma warning(disable:4624) #endif struct Base : public T, public BaseMixin { }; #if defined(OS_WIN) #pragma warning(pop) #endif template <void(BaseMixin::*)(void)> struct Helper {}; template <typename C> static No& Check(Helper<&C::AddRef>*); template <typename > static Yes& Check(...); public: static const bool value = sizeof(Check<Base>(0)) == sizeof(Yes); }; // Helpers to assert that arguments of a recounted type are bound with a // scoped_refptr. template <bool IsClasstype, typename T> struct UnsafeBindtoRefCountedArgHelper : false_type { }; template <typename T> struct UnsafeBindtoRefCountedArgHelper<true, T> : integral_constant<bool, SupportsAddRefAndRelease<T>::value> { }; template <typename T> struct UnsafeBindtoRefCountedArg : false_type { }; template <typename T> struct UnsafeBindtoRefCountedArg<T*> : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> { }; template <typename T> class HasIsMethodTag { typedef char Yes[1]; typedef char No[2]; template <typename U> static Yes& Check(typename U::IsMethod*); template <typename U> static No& Check(...); public: static const bool value = sizeof(Check<T>(0)) == sizeof(Yes); }; template <typename T> class UnretainedWrapper { public: explicit UnretainedWrapper(T* o) : ptr_(o) {} T* get() const { return ptr_; } private: T* ptr_; }; template <typename T> class ConstRefWrapper { public: explicit ConstRefWrapper(const T& o) : ptr_(&o) {} const T& get() const { return *ptr_; } private: const T* ptr_; }; template <typename T> struct IgnoreResultHelper { explicit IgnoreResultHelper(T functor) : functor_(functor) {} T functor_; }; template <typename T> struct IgnoreResultHelper<Callback<T> > { explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {} const Callback<T>& functor_; }; // An alternate implementation is to avoid the destructive copy, and instead // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to // a class that is essentially a scoped_ptr<>. // // The current implementation has the benefit though of leaving ParamTraits<> // fully in callback_internal.h as well as avoiding type conversions during // storage. template <typename T> class OwnedWrapper { public: explicit OwnedWrapper(T* o) : ptr_(o) {} ~OwnedWrapper() { delete ptr_; } T* get() const { return ptr_; } OwnedWrapper(const OwnedWrapper& other) { ptr_ = other.ptr_; other.ptr_ = NULL; } private: mutable T* ptr_; }; // PassedWrapper is a copyable adapter for a scoper that ignores const. // // It is needed to get around the fact that Bind() takes a const reference to // all its arguments. Because Bind() takes a const reference to avoid // unnecessary copies, it is incompatible with movable-but-not-copyable // types; doing a destructive "move" of the type into Bind() would violate // the const correctness. // // This conundrum cannot be solved without either C++11 rvalue references or // a O(2^n) blowup of Bind() templates to handle each combination of regular // types and movable-but-not-copyable types. Thus we introduce a wrapper type // that is copyable to transmit the correct type information down into // BindState<>. Ignoring const in this type makes sense because it is only // created when we are explicitly trying to do a destructive move. // // Two notes: // 1) PassedWrapper supports any type that has a "Pass()" function. // This is intentional. The whitelisting of which specific types we // support is maintained by CallbackParamTraits<>. // 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL" // scoper to a Callback and allow the Callback to execute once. template <typename T> class PassedWrapper { public: explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {} PassedWrapper(const PassedWrapper& other) : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) { } T Pass() const { CHECK(is_valid_); is_valid_ = false; return scoper_.Pass(); } private: mutable bool is_valid_; mutable T scoper_; }; // Unwrap the stored parameters for the wrappers above. template <typename T> struct UnwrapTraits { typedef const T& ForwardType; static ForwardType Unwrap(const T& o) { return o; } }; template <typename T> struct UnwrapTraits<UnretainedWrapper<T> > { typedef T* ForwardType; static ForwardType Unwrap(UnretainedWrapper<T> unretained) { return unretained.get(); } }; template <typename T> struct UnwrapTraits<ConstRefWrapper<T> > { typedef const T& ForwardType; static ForwardType Unwrap(ConstRefWrapper<T> const_ref) { return const_ref.get(); } }; template <typename T> struct UnwrapTraits<scoped_refptr<T> > { typedef T* ForwardType; static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); } }; template <typename T> struct UnwrapTraits<WeakPtr<T> > { typedef const WeakPtr<T>& ForwardType; static ForwardType Unwrap(const WeakPtr<T>& o) { return o; } }; template <typename T> struct UnwrapTraits<OwnedWrapper<T> > { typedef T* ForwardType; static ForwardType Unwrap(const OwnedWrapper<T>& o) { return o.get(); } }; template <typename T> struct UnwrapTraits<PassedWrapper<T> > { typedef T ForwardType; static T Unwrap(PassedWrapper<T>& o) { return o.Pass(); } }; // Utility for handling different refcounting semantics in the Bind() // function. template <bool is_method, typename T> struct MaybeRefcount; template <typename T> struct MaybeRefcount<false, T> { static void AddRef(const T&) {} static void Release(const T&) {} }; template <typename T, size_t n> struct MaybeRefcount<false, T[n]> { static void AddRef(const T*) {} static void Release(const T*) {} }; template <typename T> struct MaybeRefcount<true, T> { static void AddRef(const T&) {} static void Release(const T&) {} }; template <typename T> struct MaybeRefcount<true, T*> { static void AddRef(T* o) { o->AddRef(); } static void Release(T* o) { o->Release(); } }; // No need to additionally AddRef() and Release() since we are storing a // scoped_refptr<> inside the storage object already. template <typename T> struct MaybeRefcount<true, scoped_refptr<T> > { static void AddRef(const scoped_refptr<T>& o) {} static void Release(const scoped_refptr<T>& o) {} }; template <typename T> struct MaybeRefcount<true, const T*> { static void AddRef(const T* o) { o->AddRef(); } static void Release(const T* o) { o->Release(); } }; // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a // method. It is used internally by Bind() to select the correct // InvokeHelper that will no-op itself in the event the WeakPtr<> for // the target object is invalidated. // // P1 should be the type of the object that will be received of the method. template <bool IsMethod, typename P1> struct IsWeakMethod : public false_type {}; template <typename T> struct IsWeakMethod<true, WeakPtr<T> > : public true_type {}; template <typename T> struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T> > > : public true_type {}; } // namespace internal template <typename T> static inline internal::UnretainedWrapper<T> Unretained(T* o) { return internal::UnretainedWrapper<T>(o); } template <typename T> static inline internal::ConstRefWrapper<T> ConstRef(const T& o) { return internal::ConstRefWrapper<T>(o); } template <typename T> static inline internal::OwnedWrapper<T> Owned(T* o) { return internal::OwnedWrapper<T>(o); } // We offer 2 syntaxes for calling Passed(). The first takes a temporary and // is best suited for use with the return value of a function. The second // takes a pointer to the scoper and is just syntactic sugar to avoid having // to write Passed(scoper.Pass()). template <typename T> static inline internal::PassedWrapper<T> Passed(T scoper) { return internal::PassedWrapper<T>(scoper.Pass()); } template <typename T> static inline internal::PassedWrapper<T> Passed(T* scoper) { return internal::PassedWrapper<T>(scoper->Pass()); } template <typename T> static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) { return internal::IgnoreResultHelper<T>(data); } template <typename T> static inline internal::IgnoreResultHelper<Callback<T> > IgnoreResult(const Callback<T>& data) { return internal::IgnoreResultHelper<Callback<T> >(data); } void DoNothing(); template<typename T> void DeletePointer(T* obj) { delete obj; } } // namespace base #endif // !BUILDING_CEF_SHARED #endif // CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_
apache-2.0
tjardo83/liquibase
liquibase-core/src/main/java/liquibase/change/core/supplier/RenameTableChangeSupplier.java
1575
package liquibase.change.core.supplier; import liquibase.change.Change; import liquibase.change.ColumnConfig; import liquibase.change.core.CreateTableChange; import liquibase.change.core.RenameTableChange; import liquibase.diff.DiffResult; import liquibase.sdk.supplier.change.AbstractChangeSupplier; import liquibase.structure.core.Table; import static junit.framework.TestCase.assertNotNull; public class RenameTableChangeSupplier extends AbstractChangeSupplier<RenameTableChange> { public RenameTableChangeSupplier() { super(RenameTableChange.class); } @Override public Change[] prepareDatabase(RenameTableChange change) throws Exception { CreateTableChange createTableChange = new CreateTableChange(); createTableChange.setCatalogName(change.getCatalogName()); createTableChange.setSchemaName(change.getSchemaName()); createTableChange.setTableName(change.getOldTableName()); createTableChange.addColumn(new ColumnConfig().setName("id").setType("int")); createTableChange.addColumn(new ColumnConfig().setName("other_column").setType("varchar(10)")); return new Change[] {createTableChange }; } @Override public void checkDiffResult(DiffResult diffResult, RenameTableChange change) { assertNotNull(diffResult.getMissingObject(new Table(change.getCatalogName(), change.getSchemaName(), change.getOldTableName()))); assertNotNull(diffResult.getUnexpectedObject(new Table(change.getCatalogName(), change.getSchemaName(), change.getNewTableName()))); } }
apache-2.0
hvos234/raspberrypi.home.website
vendor/Adafruit_Python_DHT/source/Beaglebone_Black/bbb_dht_read.c
5379
// Copyright (c) 2014 Adafruit Industries // Author: Tony DiCola // 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. #include <stdlib.h> #include <string.h> #include "bbb_dht_read.h" #include "bbb_mmio.h" // This is the only processor specific magic value, the maximum amount of time to // spin in a loop before bailing out and considering the read a timeout. This should // be a high value, but if you're running on a much faster platform than a Raspberry // Pi or Beaglebone Black then it might need to be increased. #define DHT_MAXCOUNT 32000 // Number of bit pulses to expect from the DHT. Note that this is 41 because // the first pulse is a constant 50 microsecond pulse, with 40 pulses to represent // the data afterwards. #define DHT_PULSES 41 int bbb_dht_read(int type, int gpio_base, int gpio_number, float* humidity, float* temperature) { // Validate humidity and temperature arguments and set them to zero. if (humidity == NULL || temperature == NULL) { return DHT_ERROR_ARGUMENT; } *temperature = 0.0f; *humidity = 0.0f; // Store the count that each DHT bit pulse is low and high. // Make sure array is initialized to start at zero. int pulseCounts[DHT_PULSES*2] = {0}; // Get GPIO pin and set it as an output. gpio_t pin; if (bbb_mmio_get_gpio(gpio_base, gpio_number, &pin) < 0) { return DHT_ERROR_GPIO; } bbb_mmio_set_output(pin); // Bump up process priority and change scheduler to try to try to make process more 'real time'. set_max_priority(); // Set pin high for ~500 milliseconds. bbb_mmio_set_high(pin); sleep_milliseconds(500); // The next calls are timing critical and care should be taken // to ensure no unnecssary work is done below. // Set pin low for ~20 milliseconds. bbb_mmio_set_low(pin); busy_wait_milliseconds(20); // Set pin as input. bbb_mmio_set_input(pin); // Wait for DHT to pull pin low. uint32_t count = 0; while (bbb_mmio_input(pin)) { if (++count >= DHT_MAXCOUNT) { // Timeout waiting for response. set_default_priority(); return DHT_ERROR_TIMEOUT; } } // Record pulse widths for the expected result bits. for (int i=0; i < DHT_PULSES*2; i+=2) { // Count how long pin is low and store in pulseCounts[i] while (!bbb_mmio_input(pin)) { if (++pulseCounts[i] >= DHT_MAXCOUNT) { // Timeout waiting for response. set_default_priority(); return DHT_ERROR_TIMEOUT; } } // Count how long pin is high and store in pulseCounts[i+1] while (bbb_mmio_input(pin)) { if (++pulseCounts[i+1] >= DHT_MAXCOUNT) { // Timeout waiting for response. set_default_priority(); return DHT_ERROR_TIMEOUT; } } } // Done with timing critical code, now interpret the results. // Drop back to normal priority. set_default_priority(); // Compute the average low pulse width to use as a 50 microsecond reference threshold. // Ignore the first two readings because they are a constant 80 microsecond pulse. uint32_t threshold = 0; for (int i=2; i < DHT_PULSES*2; i+=2) { threshold += pulseCounts[i]; } threshold /= DHT_PULSES-1; // Interpret each high pulse as a 0 or 1 by comparing it to the 50us reference. // If the count is less than 50us it must be a ~28us 0 pulse, and if it's higher // then it must be a ~70us 1 pulse. uint8_t data[5] = {0}; for (int i=3; i < DHT_PULSES*2; i+=2) { int index = (i-3)/16; data[index] <<= 1; if (pulseCounts[i] >= threshold) { // One bit for long pulse. data[index] |= 1; } // Else zero bit for short pulse. } // Useful debug info: //printf("Data: 0x%x 0x%x 0x%x 0x%x 0x%x\n", data[0], data[1], data[2], data[3], data[4]); // Verify checksum of received data. if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) { if (type == DHT11) { // Get humidity and temp for DHT11 sensor. *humidity = (float)data[0]; *temperature = (float)data[2]; } else if (type == DHT22) { // Calculate humidity and temp for DHT22 sensor. *humidity = (data[0] * 256 + data[1]) / 10.0f; *temperature = ((data[2] & 0x7F) * 256 + data[3]) / 10.0f; if (data[2] & 0x80) { *temperature *= -1.0f; } } return DHT_SUCCESS; } else { return DHT_ERROR_CHECKSUM; } }
bsd-3-clause
scheib/chromium
third_party/blink/web_tests/external/wpt/css/css-transforms/animation/transform-interpolation-003.html
3888
<!DOCTYPE html> <meta charset="UTF-8"> <title>transform interpolation</title> <link rel="help" href="https://drafts.csswg.org/css-transforms/#transform-property"> <meta name="assert" content="transform supports animation as a transform list"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/css/support/interpolation-testcommon.js"></script> <style> .target { color: white; width: 100px; height: 100px; background-color: black; display: inline-block; overflow: hidden; } .expected { background-color: green; } .target > div { width: 10px; height: 10px; display: inline-block; background: orange; margin: 1px; } .test { overflow: hidden; } </style> <body> <template id="target-template"> <div></div> </template> </body> <script> test_interpolation({ property: 'transform', from: 'skewX(10rad) scaleZ(1)', to: 'skewX(20rad) scaleZ(2)' }, [ {at: -1, expect: 'skewX(0rad) scaleZ(0)'}, {at: 0, expect: 'skewX(10rad) scaleZ(1)'}, {at: 0.25, expect: 'skewX(12.5rad) scaleZ(1.25)'}, {at: 0.75, expect: 'skewX(17.5rad) scaleZ(1.75)'}, {at: 1, expect: 'skewX(20rad) scaleZ(2)'}, {at: 2, expect: 'skewX(30rad) scaleZ(3)'}, ]); test_interpolation({ property: 'transform', from: 'skewX(10rad)', to: 'skewX(20rad) scaleZ(2)' }, [ {at: -1, expect: 'skewX(0rad) scaleZ(0)'}, {at: 0, expect: 'skewX(10rad) scaleZ(1)'}, {at: 0.25, expect: 'skewX(12.5rad) scaleZ(1.25)'}, {at: 0.75, expect: 'skewX(17.5rad) scaleZ(1.75)'}, {at: 1, expect: 'skewX(20rad) scaleZ(2)'}, {at: 2, expect: 'skewX(30rad) scaleZ(3)'}, ]); test_interpolation({ property: 'transform', from: 'scaleZ(3) perspective(400px)', to: 'scaleZ(4) skewX(1rad) perspective(500px)' }, [ {at: -1, expect: 'scaleZ(2) matrix3d(1, 0, 0, 0, -1.55741, 1, 0, 0, 0, 0, 1, -0.003, 0, 0, 0, 1)'}, {at: 0, expect: 'scaleZ(3) matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -0.0025, 0, 0, 0, 1)'}, {at: 0.25, expect: 'scaleZ(3.25) matrix3d(1, 0, 0, 0, 0.389352, 1, 0, 0, 0, 0, 1, -0.002375, 0, 0, 0, 1)'}, {at: 0.75, expect: 'scaleZ(3.75) matrix3d(1, 0, 0, 0, 1.16806, 1, 0, 0, 0, 0, 1, -0.002125, 0, 0, 0, 1)'}, {at: 1, expect: 'scaleZ(4) matrix3d(1, 0, 0, 0, 1.55741, 1, 0, 0, 0, 0, 1, -0.002, 0, 0, 0, 1)'}, {at: 2, expect: 'scaleZ(5) matrix3d(1, 0, 0, 0, 3.11482, 1, 0, 0, 0, 0, 1, -0.0015, 0, 0, 0, 1)'}, ]); test_interpolation({ property: 'transform', from: 'translateY(70%) scaleZ(1)', to: 'translateY(90%) scaleZ(2)' }, [ {at: -1, expect: 'translateY(50%) scaleZ(0)'}, {at: 0, expect: 'translateY(70%) scaleZ(1)'}, {at: 0.25, expect: 'translateY(75%) scaleZ(1.25)'}, {at: 0.75, expect: 'translateY(85%) scaleZ(1.75)'}, {at: 1, expect: 'translateY(90%) scaleZ(2)'}, {at: 2, expect: 'translateY(110%) scaleZ(3)'}, ]); test_interpolation({ property: 'transform', from: 'translateY(70%)', to: 'translateY(90%) scaleZ(2)' }, [ {at: -1, expect: 'translateY(50%) scaleZ(0)'}, {at: 0, expect: 'translateY(70%)'}, {at: 0.25, expect: 'translateY(75%) scaleZ(1.25)'}, {at: 0.75, expect: 'translateY(85%) scaleZ(1.75)'}, {at: 1, expect: 'translateY(90%) scaleZ(2)'}, {at: 2, expect: 'translateY(110%) scaleZ(3)'}, ]); // Skew test_interpolation({ property: 'transform', from: 'skewX(10rad)', to: 'skewX(20rad)' }, [ {at: -1, expect: 'skewX(0rad)'}, {at: 0, expect: 'skewX(10rad)'}, {at: 0.25, expect: 'skewX(12.5rad)'}, {at: 0.75, expect: 'skewX(17.5rad)'}, {at: 1, expect: 'skewX(20rad)'}, {at: 2, expect: 'skewX(30rad)'}, ]); test_interpolation({ property: 'transform', from: 'skewY(10rad)', to: 'skewY(20rad)' }, [ {at: -1, expect: 'skewY(0rad)'}, {at: 0, expect: 'skewY(10rad)'}, {at: 0.25, expect: 'skewY(12.5rad)'}, {at: 0.75, expect: 'skewY(17.5rad)'}, {at: 1, expect: 'skewY(20rad)'}, {at: 2, expect: 'skewY(30rad)'}, ]); </script>
bsd-3-clause
rperier/linux
drivers/interconnect/qcom/sc8180x.h
6366
/* SPDX-License-Identifier: GPL-2.0 */ /* * Qualcomm #define SC8180X interconnect IDs * * Copyright (c) 2020, The Linux Foundation. All rights reserved. */ #ifndef __DRIVERS_INTERCONNECT_QCOM_SC8180X_H #define __DRIVERS_INTERCONNECT_QCOM_SC8180X_H #define SC8180X_MASTER_A1NOC_CFG 1 #define SC8180X_MASTER_UFS_CARD 2 #define SC8180X_MASTER_UFS_GEN4 3 #define SC8180X_MASTER_UFS_MEM 4 #define SC8180X_MASTER_USB3 5 #define SC8180X_MASTER_USB3_1 6 #define SC8180X_MASTER_USB3_2 7 #define SC8180X_MASTER_A2NOC_CFG 8 #define SC8180X_MASTER_QDSS_BAM 9 #define SC8180X_MASTER_QSPI_0 10 #define SC8180X_MASTER_QSPI_1 11 #define SC8180X_MASTER_QUP_0 12 #define SC8180X_MASTER_QUP_1 13 #define SC8180X_MASTER_QUP_2 14 #define SC8180X_MASTER_SENSORS_AHB 15 #define SC8180X_MASTER_CRYPTO_CORE_0 16 #define SC8180X_MASTER_IPA 17 #define SC8180X_MASTER_EMAC 18 #define SC8180X_MASTER_PCIE 19 #define SC8180X_MASTER_PCIE_1 20 #define SC8180X_MASTER_PCIE_2 21 #define SC8180X_MASTER_PCIE_3 22 #define SC8180X_MASTER_QDSS_ETR 23 #define SC8180X_MASTER_SDCC_2 24 #define SC8180X_MASTER_SDCC_4 25 #define SC8180X_MASTER_CAMNOC_HF0_UNCOMP 26 #define SC8180X_MASTER_CAMNOC_HF1_UNCOMP 27 #define SC8180X_MASTER_CAMNOC_SF_UNCOMP 28 #define SC8180X_MASTER_NPU 29 #define SC8180X_SNOC_CNOC_MAS 30 #define SC8180X_MASTER_CNOC_DC_NOC 31 #define SC8180X_MASTER_AMPSS_M0 32 #define SC8180X_MASTER_GPU_TCU 33 #define SC8180X_MASTER_SYS_TCU 34 #define SC8180X_MASTER_GEM_NOC_CFG 35 #define SC8180X_MASTER_COMPUTE_NOC 36 #define SC8180X_MASTER_GRAPHICS_3D 37 #define SC8180X_MASTER_MNOC_HF_MEM_NOC 38 #define SC8180X_MASTER_MNOC_SF_MEM_NOC 39 #define SC8180X_MASTER_GEM_NOC_PCIE_SNOC 40 #define SC8180X_MASTER_SNOC_GC_MEM_NOC 41 #define SC8180X_MASTER_SNOC_SF_MEM_NOC 42 #define SC8180X_MASTER_ECC 43 #define SC8180X_MASTER_IPA_CORE 44 #define SC8180X_MASTER_LLCC 45 #define SC8180X_MASTER_CNOC_MNOC_CFG 46 #define SC8180X_MASTER_CAMNOC_HF0 47 #define SC8180X_MASTER_CAMNOC_HF1 48 #define SC8180X_MASTER_CAMNOC_SF 49 #define SC8180X_MASTER_MDP_PORT0 50 #define SC8180X_MASTER_MDP_PORT1 51 #define SC8180X_MASTER_ROTATOR 52 #define SC8180X_MASTER_VIDEO_P0 53 #define SC8180X_MASTER_VIDEO_P1 54 #define SC8180X_MASTER_VIDEO_PROC 55 #define SC8180X_MASTER_SNOC_CFG 56 #define SC8180X_A1NOC_SNOC_MAS 57 #define SC8180X_A2NOC_SNOC_MAS 58 #define SC8180X_MASTER_GEM_NOC_SNOC 59 #define SC8180X_MASTER_PIMEM 60 #define SC8180X_MASTER_GIC 61 #define SC8180X_MASTER_MNOC_HF_MEM_NOC_DISPLAY 62 #define SC8180X_MASTER_MNOC_SF_MEM_NOC_DISPLAY 63 #define SC8180X_MASTER_LLCC_DISPLAY 64 #define SC8180X_MASTER_MDP_PORT0_DISPLAY 65 #define SC8180X_MASTER_MDP_PORT1_DISPLAY 66 #define SC8180X_MASTER_ROTATOR_DISPLAY 67 #define SC8180X_A1NOC_SNOC_SLV 68 #define SC8180X_SLAVE_SERVICE_A1NOC 69 #define SC8180X_A2NOC_SNOC_SLV 70 #define SC8180X_SLAVE_ANOC_PCIE_GEM_NOC 71 #define SC8180X_SLAVE_SERVICE_A2NOC 72 #define SC8180X_SLAVE_CAMNOC_UNCOMP 73 #define SC8180X_SLAVE_CDSP_MEM_NOC 74 #define SC8180X_SLAVE_A1NOC_CFG 75 #define SC8180X_SLAVE_A2NOC_CFG 76 #define SC8180X_SLAVE_AHB2PHY_CENTER 77 #define SC8180X_SLAVE_AHB2PHY_EAST 78 #define SC8180X_SLAVE_AHB2PHY_WEST 79 #define SC8180X_SLAVE_AHB2PHY_SOUTH 80 #define SC8180X_SLAVE_AOP 81 #define SC8180X_SLAVE_AOSS 82 #define SC8180X_SLAVE_CAMERA_CFG 83 #define SC8180X_SLAVE_CLK_CTL 84 #define SC8180X_SLAVE_CDSP_CFG 85 #define SC8180X_SLAVE_RBCPR_CX_CFG 86 #define SC8180X_SLAVE_RBCPR_MMCX_CFG 87 #define SC8180X_SLAVE_RBCPR_MX_CFG 88 #define SC8180X_SLAVE_CRYPTO_0_CFG 89 #define SC8180X_SLAVE_CNOC_DDRSS 90 #define SC8180X_SLAVE_DISPLAY_CFG 91 #define SC8180X_SLAVE_EMAC_CFG 92 #define SC8180X_SLAVE_GLM 93 #define SC8180X_SLAVE_GRAPHICS_3D_CFG 94 #define SC8180X_SLAVE_IMEM_CFG 95 #define SC8180X_SLAVE_IPA_CFG 96 #define SC8180X_SLAVE_CNOC_MNOC_CFG 97 #define SC8180X_SLAVE_NPU_CFG 98 #define SC8180X_SLAVE_PCIE_0_CFG 99 #define SC8180X_SLAVE_PCIE_1_CFG 100 #define SC8180X_SLAVE_PCIE_2_CFG 101 #define SC8180X_SLAVE_PCIE_3_CFG 102 #define SC8180X_SLAVE_PDM 103 #define SC8180X_SLAVE_PIMEM_CFG 104 #define SC8180X_SLAVE_PRNG 105 #define SC8180X_SLAVE_QDSS_CFG 106 #define SC8180X_SLAVE_QSPI_0 107 #define SC8180X_SLAVE_QSPI_1 108 #define SC8180X_SLAVE_QUP_1 109 #define SC8180X_SLAVE_QUP_2 110 #define SC8180X_SLAVE_QUP_0 111 #define SC8180X_SLAVE_SDCC_2 112 #define SC8180X_SLAVE_SDCC_4 113 #define SC8180X_SLAVE_SECURITY 114 #define SC8180X_SLAVE_SNOC_CFG 115 #define SC8180X_SLAVE_SPSS_CFG 116 #define SC8180X_SLAVE_TCSR 117 #define SC8180X_SLAVE_TLMM_EAST 118 #define SC8180X_SLAVE_TLMM_SOUTH 119 #define SC8180X_SLAVE_TLMM_WEST 120 #define SC8180X_SLAVE_TSIF 121 #define SC8180X_SLAVE_UFS_CARD_CFG 122 #define SC8180X_SLAVE_UFS_MEM_0_CFG 123 #define SC8180X_SLAVE_UFS_MEM_1_CFG 124 #define SC8180X_SLAVE_USB3 125 #define SC8180X_SLAVE_USB3_1 126 #define SC8180X_SLAVE_USB3_2 127 #define SC8180X_SLAVE_VENUS_CFG 128 #define SC8180X_SLAVE_VSENSE_CTRL_CFG 129 #define SC8180X_SLAVE_SERVICE_CNOC 130 #define SC8180X_SLAVE_GEM_NOC_CFG 131 #define SC8180X_SLAVE_LLCC_CFG 132 #define SC8180X_SLAVE_MSS_PROC_MS_MPU_CFG 133 #define SC8180X_SLAVE_ECC 134 #define SC8180X_SLAVE_GEM_NOC_SNOC 135 #define SC8180X_SLAVE_LLCC 136 #define SC8180X_SLAVE_SERVICE_GEM_NOC 137 #define SC8180X_SLAVE_SERVICE_GEM_NOC_1 138 #define SC8180X_SLAVE_IPA_CORE 139 #define SC8180X_SLAVE_EBI_CH0 140 #define SC8180X_SLAVE_MNOC_SF_MEM_NOC 141 #define SC8180X_SLAVE_MNOC_HF_MEM_NOC 142 #define SC8180X_SLAVE_SERVICE_MNOC 143 #define SC8180X_SLAVE_APPSS 144 #define SC8180X_SNOC_CNOC_SLV 145 #define SC8180X_SLAVE_SNOC_GEM_NOC_GC 146 #define SC8180X_SLAVE_SNOC_GEM_NOC_SF 147 #define SC8180X_SLAVE_OCIMEM 148 #define SC8180X_SLAVE_PIMEM 149 #define SC8180X_SLAVE_SERVICE_SNOC 150 #define SC8180X_SLAVE_PCIE_0 151 #define SC8180X_SLAVE_PCIE_1 152 #define SC8180X_SLAVE_PCIE_2 153 #define SC8180X_SLAVE_PCIE_3 154 #define SC8180X_SLAVE_QDSS_STM 155 #define SC8180X_SLAVE_TCU 156 #define SC8180X_SLAVE_LLCC_DISPLAY 157 #define SC8180X_SLAVE_EBI_CH0_DISPLAY 158 #define SC8180X_SLAVE_MNOC_SF_MEM_NOC_DISPLAY 159 #define SC8180X_SLAVE_MNOC_HF_MEM_NOC_DISPLAY 160 #define SC8180X_MASTER_OSM_L3_APPS 161 #define SC8180X_SLAVE_OSM_L3 162 #endif
gpl-2.0
mkautzmann/mithril.js
docs/tools.md
3542
## Tools ### HTML-to-Mithril Template Converter If you already have your HTML written and want to convert it into a Mithril template, you can use the tool below for one-off manual conversion. [Template Converter](tools/template-converter.html) --- ### Automatic HTML-to-Mithril Template Converter There's a tool called [MSX by Jonathan Buchanan](https://github.com/insin/msx) that allows you to write templates using HTML syntax, and then automatically compile them to Javascript when files change. It is useful for teams where styling and functionality are done by different people, and for those who prefer to maintain templates in HTML syntax. The tool allows you to write code like this: ```javascript todo.view = function() { return <html> <body> <input onchange={m.withAttr("value", app.vm.description)} value={app.vm.description()}/> <button onclick={app.vm.add}>Add</button> </body> </html> }; ``` Note, however, that since the code above is not valid Javascript, this syntax can only be used with a preprocessor build tool such as the provided [Gulp.js](http://gulpjs.com) script. This tool is also available as a [Rails gem](https://github.com/mrsweaters/mithril-rails), created by Jordan Humphreys. --- ### Mithril Template Compiler You can pre-compile Mithril templates to make them run faster. For more information see this page: [Compiling Templates](optimizing-performance.md#compiling-templates) --- ### Typescript Support There's a type definition file that you can use to add Mithril support to Typescript [mithril.d.ts](mithril.d.ts) You can use it by adding a reference to your Typescript files. This will allow the compiler to type-check calls to the Mithril API. ```javascript /// <reference path="mithril.d.ts" /> ``` --- ### Internet Explorer Compatibility Mithril relies on some ECMAScript 5 features, namely: `Array::indexOf`, `Array::map` and `Object::keys`, as well as the `JSON` object. Internet Explorer 8 lacks native support for some of these features. The easiest way to polyfill these features is to include this script: ```javascript <script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.3/es5-shim.min.js"></script> ``` This will provide all the polyfills required for the browser. You can alternatively include only specific polyfills: ```markup <script src="http://cdn.polyfill.io/v1/polyfill.min.js?features=Array.prototype.indexOf,Object.keys,Function.prototype.bind,Array.prototype.forEach,JSON"></script> ``` You can also use other polyfills to support these features in IE7. - [ES5 Shim](https://github.com/es-shims/es5-shim) or Mozilla.org's [Array::indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), [Array::map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [Object::keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) - [JSON2.js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) Mithril also has a dependency on XMLHttpRequest. If you wish to support IE6, you'll need [a shim for it](https://gist.github.com/Contra/2709462). IE7 and lower do not support cross-domain AJAX requests. In addition, note that most `m.route` modes rely on `history.pushState` in order to allow moving from one page to another without a browser refresh. [IE9 and lower](http://caniuse.com/#search=pushstate) do not support this feature and will gracefully degrade to page refreshes instead.
mit
swgillespie/coreclr
src/inc/iceefilegen.h
12518
// 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. /***************************************************************************** ** ** ** ICeeFileGen.h - code generator interface. ** ** ** ** This interface provides functionality to create a CLR PE executable. ** ** This will typically be used by compilers to generate their compiled ** ** output executable. ** ** ** ** The implemenation lives in mscorpe.dll ** ** ** *****************************************************************************/ /* This is how this is typically used: // Step #1 ... Get CLR hosting API: #include <mscoree.h> #include <metahost.h> ICLRMetaHost * pMetaHost; CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, &pMetaHost); // defined in mscoree.h ICLRRuntimeInfo * pCLRRuntimeInfo; pMetaHost->GetRuntime(wszClrVersion, IID_ICLRRuntimeInfo, &pCLRRuntimeInfo); // Step #2 ... Load mscorpe.dll and get its entrypoints HMODULE hModule; pCLRRuntimeInfo->LoadLibrary(L"mscorpe.dll", &hModule); PFN_CreateICeeFileGen pfnCreateICeeFileGen = (PFN_CreateICeeFileGen)::GetProcAddress("CreateICeeFileGen"); // Windows API PFN_DestroyICeeFileGen pfnDestroyICeeFileGen = (PFN_DestroyICeeFileGen)::GetProcAddress("DestroyICeeFileGen"); // Windows API // Step #3 ... Use mscorpe.dll APIs pfnCreateICeeFileGen(...); // Get a ICeeFileGen CreateCeeFile(...); // Get a HCEEFILE (called for every output file needed) SetOutputFileName(...); // Set the name for the output file pEmit = IMetaDataEmit object; // Get a metadata emitter GetSectionBlock(...);, AddSectionReloc(...); ... // Get blocks, write non-metadata information, and add necessary relocation EmitMetaDataEx(pEmit); // Write out the metadata GenerateCeeFile(...); // Write out the file. Implicitly calls LinkCeeFile and FixupCeeFile pfnDestroyICeeFileGen(...); // Release the ICeeFileGen object */ #ifndef _ICEEFILEGEN_H_ #define _ICEEFILEGEN_H_ #include <ole2.h> #include "cor.h" class ICeeFileGen; typedef void *HCEEFILE; #ifdef FEATURE_CORECLR EXTERN_C HRESULT __stdcall CreateICeeFileGen(ICeeFileGen** pCeeFileGen); EXTERN_C HRESULT __stdcall DestroyICeeFileGen(ICeeFileGen ** ppCeeFileGen); #endif typedef HRESULT (__stdcall * PFN_CreateICeeFileGen)(ICeeFileGen ** ceeFileGen); // call this to instantiate an ICeeFileGen interface typedef HRESULT (__stdcall * PFN_DestroyICeeFileGen)(ICeeFileGen ** ceeFileGen); // call this to delete an ICeeFileGen #define ICEE_CREATE_FILE_PE32 0x00000001 // Create a PE (32-bit) #define ICEE_CREATE_FILE_PE64 0x00000002 // Create a PE+ (64-bit) #define ICEE_CREATE_FILE_CORMAIN_STUB 0x00000004 // add a mscoree!_Cor___Main call stub #define ICEE_CREATE_FILE_STRIP_RELOCS 0x00000008 // strip the .reloc section #define ICEE_CREATE_FILE_EMIT_FIXUPS 0x00000010 // emit fixups for use by Vulcan #define ICEE_CREATE_MACHINE_MASK 0x0000FF00 // space for up to 256 machine targets #define ICEE_CREATE_MACHINE_ILLEGAL 0x00000000 // An illegal machine name #define ICEE_CREATE_MACHINE_I386 0x00000100 // Create a IMAGE_FILE_MACHINE_I386 #define ICEE_CREATE_MACHINE_IA64 0x00000200 // Create a IMAGE_FILE_MACHINE_IA64 #define ICEE_CREATE_MACHINE_AMD64 0x00000400 // Create a IMAGE_FILE_MACHINE_AMD64 #define ICEE_CREATE_MACHINE_ARM 0x00000800 // Create a IMAGE_FILE_MACHINE_ARMNT // Pass this to CreateCeeFileEx to create a pure IL Exe or DLL #define ICEE_CREATE_FILE_PURE_IL ICEE_CREATE_FILE_PE32 | \ ICEE_CREATE_FILE_CORMAIN_STUB | \ ICEE_CREATE_MACHINE_I386 class ICeeFileGen { public: virtual HRESULT CreateCeeFile(HCEEFILE *ceeFile); // call this to instantiate a file handle // <TODO>@FUTURE: remove this function. We no longer support mdScope.</TODO> virtual HRESULT EmitMetaData (HCEEFILE ceeFile, IMetaDataEmit *emitter, mdScope scope); virtual HRESULT EmitLibraryName (HCEEFILE ceeFile, IMetaDataEmit *emitter, mdScope scope); virtual HRESULT EmitMethod (); // <TODO>@FUTURE: remove</TODO> virtual HRESULT GetMethodRVA (HCEEFILE ceeFile, ULONG codeOffset, ULONG *codeRVA); virtual HRESULT EmitSignature (); // <TODO>@FUTURE: remove</TODO> virtual HRESULT EmitString (HCEEFILE ceeFile,_In_ LPWSTR strValue, ULONG *strRef); virtual HRESULT GenerateCeeFile (HCEEFILE ceeFile); virtual HRESULT SetOutputFileName (HCEEFILE ceeFile, _In_ LPWSTR outputFileName); _Return_type_success_(return == S_OK) virtual HRESULT GetOutputFileName (HCEEFILE ceeFile, _Out_ LPWSTR *outputFileName); virtual HRESULT SetResourceFileName (HCEEFILE ceeFile, _In_ LPWSTR resourceFileName); _Return_type_success_(return == S_OK) virtual HRESULT GetResourceFileName (HCEEFILE ceeFile, _Out_ LPWSTR *resourceFileName); virtual HRESULT SetImageBase(HCEEFILE ceeFile, size_t imageBase); virtual HRESULT SetSubsystem(HCEEFILE ceeFile, DWORD subsystem, DWORD major, DWORD minor); virtual HRESULT SetEntryClassToken (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT GetEntryClassToken (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT SetEntryPointDescr (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT GetEntryPointDescr (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT SetEntryPointFlags (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT GetEntryPointFlags (); //<TODO>@FUTURE: remove</TODO> virtual HRESULT SetDllSwitch (HCEEFILE ceeFile, BOOL dllSwitch); virtual HRESULT GetDllSwitch (HCEEFILE ceeFile, BOOL *dllSwitch); virtual HRESULT SetLibraryName (HCEEFILE ceeFile, _In_ LPWSTR LibraryName); _Return_type_success_( return == S_OK ) virtual HRESULT GetLibraryName (HCEEFILE ceeFile, _Out_ LPWSTR *LibraryName); virtual HRESULT SetLibraryGuid (HCEEFILE ceeFile, _In_ LPWSTR LibraryGuid); virtual HRESULT DestroyCeeFile(HCEEFILE *ceeFile); // call this to delete a file handle virtual HRESULT GetSectionCreate (HCEEFILE ceeFile, const char *name, DWORD flags, HCEESECTION *section); virtual HRESULT GetIlSection (HCEEFILE ceeFile, HCEESECTION *section); virtual HRESULT GetRdataSection (HCEEFILE ceeFile, HCEESECTION *section); virtual HRESULT GetSectionDataLen (HCEESECTION section, ULONG *dataLen); virtual HRESULT GetSectionBlock (HCEESECTION section, ULONG len, ULONG align=1, void **ppBytes=0); virtual HRESULT TruncateSection (HCEESECTION section, ULONG len); virtual HRESULT AddSectionReloc (HCEESECTION section, ULONG offset, HCEESECTION relativeTo, CeeSectionRelocType relocType); // deprecated: use SetDirectoryEntry instead virtual HRESULT SetSectionDirectoryEntry (HCEESECTION section, ULONG num); virtual HRESULT CreateSig (); //<TODO>@FUTURE: Remove</TODO> virtual HRESULT AddSigArg (); //<TODO>@FUTURE: Remove</TODO> virtual HRESULT SetSigReturnType (); //<TODO>@FUTURE: Remove</TODO> virtual HRESULT SetSigCallingConvention (); //<TODO>@FUTURE: Remove</TODO> virtual HRESULT DeleteSig (); //<TODO>@FUTURE: Remove</TODO> virtual HRESULT SetEntryPoint (HCEEFILE ceeFile, mdMethodDef method); virtual HRESULT GetEntryPoint (HCEEFILE ceeFile, mdMethodDef *method); virtual HRESULT SetComImageFlags (HCEEFILE ceeFile, DWORD mask); virtual HRESULT GetComImageFlags (HCEEFILE ceeFile, DWORD *mask); // get IMapToken interface for tracking mapped tokens virtual HRESULT GetIMapTokenIface(HCEEFILE ceeFile, IMetaDataEmit *emitter, IUnknown **pIMapToken); virtual HRESULT SetDirectoryEntry (HCEEFILE ceeFile, HCEESECTION section, ULONG num, ULONG size, ULONG offset = 0); // Write out the metadata in "emitter" to the metadata section in "ceeFile" // Use EmitMetaDataAt() for more control virtual HRESULT EmitMetaDataEx (HCEEFILE ceeFile, IMetaDataEmit *emitter); virtual HRESULT EmitLibraryNameEx (HCEEFILE ceeFile, IMetaDataEmit *emitter); virtual HRESULT GetIMapTokenIfaceEx(HCEEFILE ceeFile, IMetaDataEmit *emitter, IUnknown **pIMapToken); virtual HRESULT EmitMacroDefinitions(HCEEFILE ceeFile, void *pData, DWORD cData); virtual HRESULT CreateCeeFileFromICeeGen( ICeeGen *pFromICeeGen, HCEEFILE *ceeFile, DWORD createFlags = ICEE_CREATE_FILE_PURE_IL); // call this to instantiate a file handle virtual HRESULT SetManifestEntry(HCEEFILE ceeFile, ULONG size, ULONG offset); virtual HRESULT SetEnCRVABase(HCEEFILE ceeFile, ULONG dataBase, ULONG rdataBase); virtual HRESULT GenerateCeeMemoryImage (HCEEFILE ceeFile, void **ppImage); virtual HRESULT ComputeSectionOffset(HCEESECTION section, _In_ char *ptr, unsigned *offset); virtual HRESULT ComputeOffset(HCEEFILE file, _In_ char *ptr, HCEESECTION *pSection, unsigned *offset); virtual HRESULT GetCorHeader(HCEEFILE ceeFile, IMAGE_COR20_HEADER **header); // Layout the sections and assign their starting addresses virtual HRESULT LinkCeeFile (HCEEFILE ceeFile); // Apply relocations to any pointer data. Also generate PE base relocs virtual HRESULT FixupCeeFile (HCEEFILE ceeFile); // Base RVA assinged to the section. To be called only after LinkCeeFile() virtual HRESULT GetSectionRVA (HCEESECTION section, ULONG *rva); _Return_type_success_(return == S_OK) virtual HRESULT ComputeSectionPointer(HCEESECTION section, ULONG offset, _Out_ char **ptr); virtual HRESULT SetObjSwitch (HCEEFILE ceeFile, BOOL objSwitch); virtual HRESULT GetObjSwitch (HCEEFILE ceeFile, BOOL *objSwitch); virtual HRESULT SetVTableEntry(HCEEFILE ceeFile, ULONG size, ULONG offset); // See the end of interface for another overload of AetVTableEntry virtual HRESULT SetStrongNameEntry(HCEEFILE ceeFile, ULONG size, ULONG offset); // Emit the metadata from "emitter". // If 'section != 0, it will put the data in 'buffer'. This // buffer is assumed to be in 'section' at 'offset' and of size 'buffLen' // (should use GetSaveSize to insure that buffer is big enough virtual HRESULT EmitMetaDataAt (HCEEFILE ceeFile, IMetaDataEmit *emitter, HCEESECTION section, DWORD offset, BYTE* buffer, unsigned buffLen); virtual HRESULT GetFileTimeStamp (HCEEFILE ceeFile, DWORD *pTimeStamp); // Add a notification handler. If it implements an interface that // the ICeeFileGen understands, S_OK is returned. Otherwise, // E_NOINTERFACE. virtual HRESULT AddNotificationHandler(HCEEFILE ceeFile, IUnknown *pHandler); virtual HRESULT SetFileAlignment(HCEEFILE ceeFile, ULONG fileAlignment); virtual HRESULT ClearComImageFlags (HCEEFILE ceeFile, DWORD mask); // call this to instantiate a PE+ (64-bit PE file) virtual HRESULT CreateCeeFileEx(HCEEFILE *ceeFile, ULONG createFlags); virtual HRESULT SetImageBase64(HCEEFILE ceeFile, ULONGLONG imageBase); virtual HRESULT GetHeaderInfo (HCEEFILE ceeFile, PIMAGE_NT_HEADERS *ppNtHeaders, PIMAGE_SECTION_HEADER *ppSections, ULONG *pNumSections); // Seed file is a base file which is copied over into the output file // Note that there are restrictions on the seed file (the sections // cannot be relocated), and that the copy is not complete as the new // headers overwrite the seed file headers. virtual HRESULT CreateCeeFileEx2(HCEEFILE *ceeFile, ULONG createFlags, LPCWSTR seedFileName = NULL); virtual HRESULT SetVTableEntry64(HCEEFILE ceeFile, ULONG size, void* ptr); }; #endif
mit
xinchoubiology/gcc
libstdc++-v3/testsuite/27_io/basic_istream/tellg/wchar_t/sstream.cc
2726
// Copyright (C) 2004-2014 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 27.6.1.3 unformatted input functions // NB: ostream has a particular "seeks" category. Adopt this for istreams too. // @require@ %-*.tst %-*.txt // @diff@ %-*.tst %-*.txt #include <istream> #include <sstream> #include <fstream> #include <testsuite_hooks.h> // stringstreams void test05(void) { typedef std::wistream::off_type off_type; bool test __attribute__((unused)) = true; std::wistream::pos_type pos01, pos02, pos03, pos04, pos05, pos06; std::ios_base::iostate state01, state02; const char str_lit01[] = "wistream_seeks-1.tst"; std::wifstream if01(str_lit01); std::wifstream if02(str_lit01); std::wifstream if03(str_lit01); VERIFY( if01.good() ); VERIFY( if02.good() ); VERIFY( if03.good() ); std::wstringbuf strbuf01(std::ios_base::in | std::ios_base::out); if01 >> &strbuf01; // initialize stringbufs that are ios_base::out std::wstringbuf strbuf03(strbuf01.str(), std::ios_base::out); // initialize stringbufs that are ios_base::in std::wstringbuf strbuf02(strbuf01.str(), std::ios_base::in); std::wistream is01(&strbuf01); std::wistream is02(&strbuf02); std::wistream is03(&strbuf03); // pos_type tellg() // in | out pos01 = is01.tellg(); pos02 = is01.tellg(); VERIFY( pos01 == pos02 ); // in pos03 = is02.tellg(); pos04 = is02.tellg(); VERIFY( pos03 == pos04 ); // out pos05 = is03.tellg(); pos06 = is03.tellg(); VERIFY( pos05 == pos06 ); // cur // NB: see library issues list 136. It's the v-3 interp that seekg // only sets the input buffer, or else istreams with buffers that // have _M_mode == ios_base::out will fail to have consistency // between seekg and tellg. state01 = is01.rdstate(); is01.seekg(10, std::ios_base::cur); state02 = is01.rdstate(); pos01 = is01.tellg(); VERIFY( pos01 == pos02 + off_type(10) ); VERIFY( state01 == state02 ); pos02 = is01.tellg(); VERIFY( pos02 == pos01 ); } int main() { test05(); return 0; }
gpl-2.0
9034725985/vlc
src/misc/es_format.c
18794
/***************************************************************************** * es_format.c : es_format_t helpers. ***************************************************************************** * Copyright (C) 2008 VLC authors and VideoLAN * $Id$ * * Author: Laurent Aimar <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <assert.h> #include <vlc_common.h> #include <vlc_es.h> /***************************************************************************** * BinaryLog: computes the base 2 log of a binary value ***************************************************************************** * This functions is used by MaskToShift, to get a bit index from a binary * value. *****************************************************************************/ static int BinaryLog( uint32_t i ) { int i_log = 0; if( i == 0 ) return -31337; if( i & 0xffff0000 ) i_log += 16; if( i & 0xff00ff00 ) i_log += 8; if( i & 0xf0f0f0f0 ) i_log += 4; if( i & 0xcccccccc ) i_log += 2; if( i & 0xaaaaaaaa ) i_log += 1; return i_log; } /** * It transforms a color mask into right and left shifts * FIXME copied from video_output.c */ static void MaskToShift( int *pi_left, int *pi_right, uint32_t i_mask ) { uint32_t i_low, i_high; /* lower and higher bits of the mask */ if( !i_mask ) { *pi_left = *pi_right = 0; return; } /* Get bits */ i_low = i_high = i_mask; i_low &= - (int32_t)i_low; /* lower bit of the mask */ i_high += i_low; /* higher bit of the mask */ /* Transform bits into an index. Also deal with i_high overflow, which * is faster than changing the BinaryLog code to handle 64 bit integers. */ i_low = BinaryLog (i_low); i_high = i_high ? BinaryLog (i_high) : 32; /* Update pointers and return */ *pi_left = i_low; *pi_right = (8 - i_high + i_low); } /* */ void video_format_FixRgb( video_format_t *p_fmt ) { /* FIXME find right default mask */ if( !p_fmt->i_rmask || !p_fmt->i_gmask || !p_fmt->i_bmask ) { switch( p_fmt->i_chroma ) { case VLC_CODEC_RGB15: p_fmt->i_rmask = 0x7c00; p_fmt->i_gmask = 0x03e0; p_fmt->i_bmask = 0x001f; break; case VLC_CODEC_RGB16: p_fmt->i_rmask = 0xf800; p_fmt->i_gmask = 0x07e0; p_fmt->i_bmask = 0x001f; break; case VLC_CODEC_RGB24: p_fmt->i_rmask = 0xff0000; p_fmt->i_gmask = 0x00ff00; p_fmt->i_bmask = 0x0000ff; break; case VLC_CODEC_RGB32: p_fmt->i_rmask = 0x00ff0000; p_fmt->i_gmask = 0x0000ff00; p_fmt->i_bmask = 0x000000ff; break; default: return; } } MaskToShift( &p_fmt->i_lrshift, &p_fmt->i_rrshift, p_fmt->i_rmask ); MaskToShift( &p_fmt->i_lgshift, &p_fmt->i_rgshift, p_fmt->i_gmask ); MaskToShift( &p_fmt->i_lbshift, &p_fmt->i_rbshift, p_fmt->i_bmask ); } void video_format_Setup( video_format_t *p_fmt, vlc_fourcc_t i_chroma, int i_width, int i_height, int i_visible_width, int i_visible_height, int i_sar_num, int i_sar_den ) { p_fmt->i_chroma = vlc_fourcc_GetCodec( VIDEO_ES, i_chroma ); p_fmt->i_width = i_width; p_fmt->i_visible_width = i_visible_width; p_fmt->i_height = i_height; p_fmt->i_visible_height = i_visible_height; p_fmt->i_x_offset = p_fmt->i_y_offset = 0; vlc_ureduce( &p_fmt->i_sar_num, &p_fmt->i_sar_den, i_sar_num, i_sar_den, 0 ); switch( p_fmt->i_chroma ) { case VLC_CODEC_YUVA: p_fmt->i_bits_per_pixel = 32; break; case VLC_CODEC_YUV420A: p_fmt->i_bits_per_pixel = 20; break; case VLC_CODEC_YUV422A: p_fmt->i_bits_per_pixel = 24; break; case VLC_CODEC_I444: case VLC_CODEC_J444: p_fmt->i_bits_per_pixel = 24; break; case VLC_CODEC_I422: case VLC_CODEC_YUYV: case VLC_CODEC_YVYU: case VLC_CODEC_UYVY: case VLC_CODEC_VYUY: case VLC_CODEC_J422: p_fmt->i_bits_per_pixel = 16; break; case VLC_CODEC_I440: case VLC_CODEC_J440: p_fmt->i_bits_per_pixel = 16; break; case VLC_CODEC_I411: case VLC_CODEC_YV12: case VLC_CODEC_I420: case VLC_CODEC_J420: case VLC_CODEC_NV12: p_fmt->i_bits_per_pixel = 12; break; case VLC_CODEC_YV9: case VLC_CODEC_I410: p_fmt->i_bits_per_pixel = 9; break; case VLC_CODEC_Y211: p_fmt->i_bits_per_pixel = 8; break; case VLC_CODEC_YUVP: p_fmt->i_bits_per_pixel = 8; break; case VLC_CODEC_RGB32: case VLC_CODEC_RGBA: case VLC_CODEC_ARGB: case VLC_CODEC_BGRA: p_fmt->i_bits_per_pixel = 32; break; case VLC_CODEC_RGB24: p_fmt->i_bits_per_pixel = 24; break; case VLC_CODEC_RGB15: case VLC_CODEC_RGB16: p_fmt->i_bits_per_pixel = 16; break; case VLC_CODEC_RGB8: p_fmt->i_bits_per_pixel = 8; break; case VLC_CODEC_GREY: case VLC_CODEC_RGBP: p_fmt->i_bits_per_pixel = 8; break; case VLC_CODEC_XYZ12: p_fmt->i_bits_per_pixel = 48; break; default: p_fmt->i_bits_per_pixel = 0; break; } } void video_format_CopyCrop( video_format_t *p_dst, const video_format_t *p_src ) { p_dst->i_x_offset = p_src->i_x_offset; p_dst->i_y_offset = p_src->i_y_offset; p_dst->i_visible_width = p_src->i_visible_width; p_dst->i_visible_height = p_src->i_visible_height; } void video_format_ScaleCropAr( video_format_t *p_dst, const video_format_t *p_src ) { p_dst->i_x_offset = (uint64_t)p_src->i_x_offset * p_dst->i_width / p_src->i_width; p_dst->i_y_offset = (uint64_t)p_src->i_y_offset * p_dst->i_height / p_src->i_height; p_dst->i_visible_width = (uint64_t)p_src->i_visible_width * p_dst->i_width / p_src->i_width; p_dst->i_visible_height = (uint64_t)p_src->i_visible_height * p_dst->i_height / p_src->i_height; p_dst->i_sar_num *= p_src->i_width; p_dst->i_sar_den *= p_dst->i_width; vlc_ureduce(&p_dst->i_sar_num, &p_dst->i_sar_den, p_dst->i_sar_num, p_dst->i_sar_den, 65536); p_dst->i_sar_num *= p_dst->i_height; p_dst->i_sar_den *= p_src->i_height; vlc_ureduce(&p_dst->i_sar_num, &p_dst->i_sar_den, p_dst->i_sar_num, p_dst->i_sar_den, 65536); } //Simplify transforms to have something more managable. Order: angle, hflip. static void transform_GetBasicOps( video_transform_t transform, unsigned *restrict angle, bool *restrict hflip ) { *hflip = ORIENT_IS_MIRROR(transform); switch ( transform ) { case TRANSFORM_R90: case TRANSFORM_TRANSPOSE: *angle = 90; break; case TRANSFORM_R180: case TRANSFORM_VFLIP: *angle = 180; break; case TRANSFORM_R270: case TRANSFORM_ANTI_TRANSPOSE: *angle = 270; break; case TRANSFORM_HFLIP: case TRANSFORM_IDENTITY: *angle = 0; break; default: vlc_assert_unreachable (); } } static video_transform_t transform_FromBasicOps( unsigned angle, bool hflip ) { switch ( angle ) { case 90: return hflip ? TRANSFORM_TRANSPOSE : TRANSFORM_R90; case 180: return hflip ? TRANSFORM_VFLIP : TRANSFORM_R180; case 270: return hflip ? TRANSFORM_ANTI_TRANSPOSE : TRANSFORM_R270; default: return hflip ? TRANSFORM_HFLIP : TRANSFORM_IDENTITY; } } video_transform_t video_format_GetTransform( video_orientation_t src, video_orientation_t dst ) { unsigned angle1, angle2; bool hflip1, hflip2; transform_GetBasicOps( (video_transform_t)src, &angle1, &hflip1 ); transform_GetBasicOps( transform_Inverse( (video_transform_t)dst ), &angle2, &hflip2 ); int angle = (angle1 + angle2) % 360; bool hflip = hflip1 ^ hflip2; return transform_FromBasicOps(angle, hflip); } void video_format_TransformBy( video_format_t *fmt, video_transform_t transform ) { /* Get destination orientation */ unsigned angle1, angle2; bool hflip1, hflip2; transform_GetBasicOps( transform, &angle1, &hflip1 ); transform_GetBasicOps( (video_transform_t)fmt->orientation, &angle2, &hflip2 ); unsigned angle = (angle2 - angle1 + 360) % 360; bool hflip = hflip2 ^ hflip1; video_orientation_t dst_orient = ORIENT_NORMAL; if( hflip ) { if( angle == 0 ) dst_orient = ORIENT_HFLIPPED; else if( angle == 90 ) dst_orient = ORIENT_ANTI_TRANSPOSED; else if( angle == 180 ) dst_orient = ORIENT_VFLIPPED; else if( angle == 270 ) dst_orient = ORIENT_TRANSPOSED; } else { if( angle == 90 ) dst_orient = ORIENT_ROTATED_90; else if( angle == 180 ) dst_orient = ORIENT_ROTATED_180; else if( angle == 270 ) dst_orient = ORIENT_ROTATED_270; } /* Apply transform */ if( ORIENT_IS_SWAP( fmt->orientation ) != ORIENT_IS_SWAP( dst_orient ) ) { video_format_t scratch = *fmt; fmt->i_width = scratch.i_height; fmt->i_visible_width = scratch.i_visible_height; fmt->i_height = scratch.i_width; fmt->i_visible_height = scratch.i_visible_width; fmt->i_x_offset = scratch.i_y_offset; fmt->i_y_offset = scratch.i_x_offset; fmt->i_sar_num = scratch.i_sar_den; fmt->i_sar_den = scratch.i_sar_num; } fmt->orientation = dst_orient; } void video_format_TransformTo( video_format_t *restrict fmt, video_orientation_t dst_orientation ) { video_transform_t transform = video_format_GetTransform(fmt->orientation, dst_orientation); video_format_TransformBy(fmt, transform); } void video_format_ApplyRotation( video_format_t *restrict out, const video_format_t *restrict in ) { *out = *in; video_format_TransformTo(out, ORIENT_NORMAL); } bool video_format_IsSimilar( const video_format_t *f1, const video_format_t *f2 ) { if( f1->i_chroma != f2->i_chroma ) return false; if( f1->i_width != f2->i_width || f1->i_height != f2->i_height || f1->i_visible_width != f2->i_visible_width || f1->i_visible_height != f2->i_visible_height || f1->i_x_offset != f2->i_x_offset || f1->i_y_offset != f2->i_y_offset ) return false; if( f1->i_sar_num * f2->i_sar_den != f2->i_sar_num * f1->i_sar_den ) return false; if( f1->orientation != f2->orientation) return false; if( f1->i_chroma == VLC_CODEC_RGB15 || f1->i_chroma == VLC_CODEC_RGB16 || f1->i_chroma == VLC_CODEC_RGB24 || f1->i_chroma == VLC_CODEC_RGB32 ) { video_format_t v1 = *f1; video_format_t v2 = *f2; video_format_FixRgb( &v1 ); video_format_FixRgb( &v2 ); if( v1.i_rmask != v2.i_rmask || v1.i_gmask != v2.i_gmask || v1.i_bmask != v2.i_bmask ) return false; } return true; } void video_format_Print( vlc_object_t *p_this, const char *psz_text, const video_format_t *fmt ) { msg_Dbg( p_this, "%s sz %ix%i, of (%i,%i), vsz %ix%i, 4cc %4.4s, sar %i:%i, msk r0x%x g0x%x b0x%x", psz_text, fmt->i_width, fmt->i_height, fmt->i_x_offset, fmt->i_y_offset, fmt->i_visible_width, fmt->i_visible_height, (char*)&fmt->i_chroma, fmt->i_sar_num, fmt->i_sar_den, fmt->i_rmask, fmt->i_gmask, fmt->i_bmask ); } void es_format_Init( es_format_t *fmt, int i_cat, vlc_fourcc_t i_codec ) { fmt->i_cat = i_cat; fmt->i_codec = i_codec; fmt->i_original_fourcc = 0; fmt->i_profile = -1; fmt->i_level = -1; fmt->i_id = -1; fmt->i_group = 0; fmt->i_priority = ES_PRIORITY_SELECTABLE_MIN; fmt->psz_language = NULL; fmt->psz_description = NULL; fmt->i_extra_languages = 0; fmt->p_extra_languages = NULL; memset( &fmt->audio, 0, sizeof(audio_format_t) ); memset( &fmt->audio_replay_gain, 0, sizeof(audio_replay_gain_t) ); memset( &fmt->video, 0, sizeof(video_format_t) ); memset( &fmt->subs, 0, sizeof(subs_format_t) ); fmt->b_packetized = true; fmt->i_bitrate = 0; fmt->i_extra = 0; fmt->p_extra = NULL; } void es_format_InitFromVideo( es_format_t *p_es, const video_format_t *p_fmt ) { es_format_Init( p_es, VIDEO_ES, p_fmt->i_chroma ); video_format_Copy( &p_es->video, p_fmt ); } int es_format_Copy(es_format_t *restrict dst, const es_format_t *src) { int ret = VLC_SUCCESS; *dst = *src; if (src->psz_language != NULL) { dst->psz_language = strdup(src->psz_language); if (unlikely(dst->psz_language == NULL)) ret = VLC_ENOMEM; } if (src->psz_description != NULL) { dst->psz_description = strdup(src->psz_description); if (unlikely(dst->psz_description == NULL)) ret = VLC_ENOMEM; } if (src->i_extra > 0) { assert(src->p_extra != NULL); dst->p_extra = malloc( src->i_extra ); if( likely(dst->p_extra != NULL) ) memcpy(dst->p_extra, src->p_extra, src->i_extra); else { dst->i_extra = 0; ret = VLC_ENOMEM; } } if (src->subs.psz_encoding != NULL) { dst->subs.psz_encoding = strdup(src->subs.psz_encoding); if (unlikely(dst->subs.psz_encoding == NULL)) ret = VLC_ENOMEM; } if (src->subs.p_style != NULL) { dst->subs.p_style = text_style_Duplicate(src->subs.p_style); if (unlikely(dst->subs.p_style == NULL)) ret = VLC_ENOMEM; } if (src->video.p_palette != NULL) { dst->video.p_palette = malloc(sizeof (video_palette_t)); if (likely(dst->video.p_palette != NULL)) *dst->video.p_palette = *src->video.p_palette; else ret = VLC_ENOMEM; } if (src->i_extra_languages > 0) { assert(src->p_extra_languages != NULL); dst->p_extra_languages = calloc(dst->i_extra_languages, sizeof (*dst->p_extra_languages)); if (likely(dst->p_extra_languages != NULL)) { for (unsigned i = 0; i < dst->i_extra_languages; i++) { if (src->p_extra_languages[i].psz_language != NULL) dst->p_extra_languages[i].psz_language = strdup(src->p_extra_languages[i].psz_language); if (src->p_extra_languages[i].psz_description != NULL) dst->p_extra_languages[i].psz_description = strdup(src->p_extra_languages[i].psz_description); } dst->i_extra_languages = src->i_extra_languages; } else { dst->i_extra_languages = 0; ret = VLC_ENOMEM; } } return ret; } void es_format_Clean(es_format_t *fmt) { free(fmt->psz_language); free(fmt->psz_description); assert(fmt->i_extra == 0 || fmt->p_extra != NULL); free(fmt->p_extra); free(fmt->video.p_palette); free(fmt->subs.psz_encoding); if (fmt->subs.p_style != NULL) text_style_Delete(fmt->subs.p_style); for (unsigned i = 0; i < fmt->i_extra_languages; i++) { free(fmt->p_extra_languages[i].psz_language); free(fmt->p_extra_languages[i].psz_description); } free(fmt->p_extra_languages); /* es_format_Clean can be called multiple times */ es_format_Init(fmt, UNKNOWN_ES, 0); } bool es_format_IsSimilar( const es_format_t *p_fmt1, const es_format_t *p_fmt2 ) { if( p_fmt1->i_cat != p_fmt2->i_cat || vlc_fourcc_GetCodec( p_fmt1->i_cat, p_fmt1->i_codec ) != vlc_fourcc_GetCodec( p_fmt2->i_cat, p_fmt2->i_codec ) ) return false; switch( p_fmt1->i_cat ) { case AUDIO_ES: { audio_format_t a1 = p_fmt1->audio; audio_format_t a2 = p_fmt2->audio; if( a1.i_format && a2.i_format && a1.i_format != a2.i_format ) return false; if( a1.i_rate != a2.i_rate || a1.i_physical_channels != a2.i_physical_channels || a1.i_original_channels != a2.i_original_channels ) return false; return true; } case VIDEO_ES: { video_format_t v1 = p_fmt1->video; video_format_t v2 = p_fmt2->video; if( !v1.i_chroma ) v1.i_chroma = vlc_fourcc_GetCodec( p_fmt1->i_cat, p_fmt1->i_codec ); if( !v2.i_chroma ) v2.i_chroma = vlc_fourcc_GetCodec( p_fmt2->i_cat, p_fmt2->i_codec ); return video_format_IsSimilar( &p_fmt1->video, &p_fmt2->video ); } case SPU_ES: default: return true; } }
gpl-2.0
TEMadsen/fieldtrip
external/spm2/spm_bwlabel.c
11851
/**************************************************************** ** ** Set of routines implementing a 2D or 3D connected component ** labelling algorithm. Its interface is modelled on bwlabel ** (which is a routine in the image processing toolbox) and ** takes as input a binary image and (optionally) a connectednes ** criterion (6, 18 or 26, in 2D 6 will correspond to 4 and 18 ** and 26 to 8). It will output an image/volume where each ** connected component will have a unique label. ** ** The implementation is not recursive (i.e. will no crash for ** large connected components) and is losely based on ** Thurfjell et al. 1992, A new three-dimensional connected ** components labeling algorithm with simultaneous object ** feature extraction capability. CVGIP: Graphical Models ** and Image Processing 54(4):357-364. ** ***************************************************************/ #ifndef lint static char sccsid[] = "@(#)spm_bwlabel.c 2.1 Jesper Andersson 03/12/16"; #endif #include "mex.h" #include <math.h> #include <limits.h> /* Silly little macros. */ #define index(A,B,C,DIM) ((C)*DIM[0]*DIM[1] + (B)*DIM[0] + (A)) #ifndef MIN #define MIN(A,B) ((A) > (B) ? (B) : (A)) #endif #ifndef MAX #define MAX(A,B) ((A) > (B) ? (A) : (B)) #endif /* Function prototypes. */ unsigned int do_initial_labelling(double *bw, /* Binary map */ unsigned int *dim, /* Dimensions of bw */ unsigned int conn, /* Connectivity criterion */ unsigned int *il, /* Initially labelled map */ unsigned int **tt); /* Translation table */ unsigned int check_previous_slice(unsigned int *il, /* Initial labelling map */ unsigned int r, /* row */ unsigned int c, /* column */ unsigned int sl, /* slice */ unsigned int dim[3], /* dimensions of il */ unsigned int conn, /* Connectivity criterion */ unsigned int *tt, /* Translation table */ unsigned int ttn); /* Size of translation table */ void fill_tratab(unsigned int *tt, /* Translation table */ unsigned int ttn, /* Size of translation table */ unsigned int *nabo, /* Set of neighbours */ unsigned int nr_set); /* Number of neighbours in nabo */ double translate_labels(unsigned int *il, /* Map of initial labels. */ unsigned int dim[3], /* Dimensions of il. */ unsigned int *tt, /* Translation table. */ unsigned int ttn, /* Size of translation table. */ double *l); /* Final map of labels. */ /* Here starts actual code. */ unsigned int do_initial_labelling(double *bw, /* Binary map */ unsigned int *dim, /* Dimensions of bw */ unsigned int conn, /* Connectivity criterion */ unsigned int *il, /* Initially labelled map */ unsigned int **tt) /* Translation table */ { unsigned int i = 0, j = 0; unsigned int nabo[8]; unsigned int label = 1; unsigned int nr_set = 0; unsigned int l = 0; unsigned int sl=0, r=0, c=0; unsigned int ttn = 1000; *tt = (unsigned int *) mxCalloc(ttn,sizeof(unsigned int)); for (sl=0; sl<dim[2]; sl++) { for (c=0; c<dim[1]; c++) { for (r=0; r<dim[0]; r++) { nr_set = 0; if (bw[index(r,c,sl,dim)]) { nabo[0] = check_previous_slice(il,r,c,sl,dim,conn,*tt,ttn); if (nabo[0]) {nr_set += 1;} /* For six(surface)-connectivity */ if (conn >= 6) { if (r) { if (l = il[index(r-1,c,sl,dim)]) {nabo[nr_set++] = l;} } if (c) { if (l = il[index(r,c-1,sl,dim)]) {nabo[nr_set++] = l;} } } /* For 18(edge)-connectivity N.B. In current slice no difference to 26. */ if (conn >= 18) { if (c && r) { if (l = il[index(r-1,c-1,sl,dim)]) {nabo[nr_set++] = l;} } if (c && (r < dim[0]-1)) { if (l = il[index(r+1,c-1,sl,dim)]) {nabo[nr_set++] = l;} } } if (nr_set) { il[index(r,c,sl,dim)] = nabo[0]; fill_tratab(*tt,ttn,nabo,nr_set); } else { il[index(r,c,sl,dim)] = label; if (label >= ttn) {ttn += 1000; *tt = mxRealloc(*tt,ttn*sizeof(unsigned int));} (*tt)[label-1] = label; label++; } } } } } /* Finalise translation table */ for (i=0; i<(label-1); i++) { j = i; while ((*tt)[j] != j+1) { j = (*tt)[j]-1; } (*tt)[i] = j+1; } return(label-1); } unsigned int check_previous_slice(unsigned int *il, /* Initial labelling map */ unsigned int r, /* row */ unsigned int c, /* column */ unsigned int sl, /* slice */ unsigned int dim[3], /* dimensions of il */ unsigned int conn, /* Connectivity criterion */ unsigned int *tt, /* Translation table */ unsigned int ttn) /* Size of translation table */ { unsigned int l=0; unsigned int nabo[9]; unsigned int nr_set = 0; if (!sl) return(0); if (conn >= 6) { if (l = il[index(r,c,sl-1,dim)]) {nabo[nr_set++] = l;} } if (conn >= 18) { if (r) {if (l = il[index(r-1,c,sl-1,dim)]) {nabo[nr_set++] = l;}} if (c) {if (l = il[index(r,c-1,sl-1,dim)]) {nabo[nr_set++] = l;}} if (r < dim[0]-1) {if (l = il[index(r+1,c,sl-1,dim)]) {nabo[nr_set++] = l;}} if (c < dim[1]-1) {if (l = il[index(r,c+1,sl-1,dim)]) {nabo[nr_set++] = l;}} } if (conn == 26) { if (r && c) {if (l = il[index(r-1,c-1,sl-1,dim)]) {nabo[nr_set++] = l;}} if ((r < dim[0]-1) && c) {if (l = il[index(r+1,c-1,sl-1,dim)]) {nabo[nr_set++] = l;}} if (r && (c < dim[1]-1)) {if (l = il[index(r-1,c+1,sl-1,dim)]) {nabo[nr_set++] = l;}} if ((r < dim[0]-1) && (c < dim[1]-1)) {if (l = il[index(r+1,c+1,sl-1,dim)]) {nabo[nr_set++] = l;}} } if (nr_set) { fill_tratab(tt,ttn,nabo,nr_set); return(nabo[0]); } else {return(0);} } void fill_tratab(unsigned int *tt, /* Translation table */ unsigned int ttn, /* Size of translation table */ unsigned int *nabo, /* Set of neighbours */ unsigned int nr_set) /* Number of neighbours in nabo */ { int i = 0, j = 0, cntr = 0; unsigned int tn[9]; unsigned int ltn = UINT_MAX; /* Find smallest terminal number in neighbourhood */ for (i=0; i<nr_set; i++) { j = nabo[i]; cntr=0; while (tt[j-1] != j) { j = tt[j-1]; cntr++; if (cntr>100) {printf("\nOoh no!!"); break;} } tn[i] = j; ltn = MIN(ltn,j); } /* Replace all terminal numbers in neighbourhood by the smallest one */ for (i=0; i<nr_set; i++) { tt[tn[i]-1] = ltn; } return; } double translate_labels(unsigned int *il, /* Map of initial labels. */ unsigned int dim[3], /* Dimensions of il. */ unsigned int *tt, /* Translation table. */ unsigned int ttn, /* Size of translation table. */ double *l) /* Final map of labels. */ { int n=0; int i=0; unsigned int ml=0; double cl = 0.0; double *fl = NULL; n = dim[0]*dim[1]*dim[2]; for (i=0; i<ttn; i++) {ml = MAX(ml,tt[i]);} fl = (double *) mxCalloc(ml,sizeof(double)); for (i=0; i<n; i++) { if (il[i]) { if (!fl[tt[il[i]-1]-1]) { cl += 1.0; fl[tt[il[i]-1]-1] = cl; } l[i] = fl[tt[il[i]-1]-1]; } } mxFree(fl); return(cl); } /* Gateway function with error check. */ void mexFunction(int nlhs, /* No. of output arguments */ mxArray *plhs[], /* Output arguments. */ int nrhs, /* No. of input arguments. */ const mxArray *prhs[]) /* Input arguments. */ { int ndim; int num; int n, i; const int *cdim = NULL; unsigned int conn; unsigned int tmp1; unsigned int tmp2; unsigned int dim[3]; unsigned int ttn = 0; unsigned int *il = NULL; unsigned int *tt = NULL; double *bw = NULL; double *l = NULL; double *tratab = NULL; double dconn = 0.0; double nl = 0.0; if (nrhs == 0) mexErrMsgTxt("usage: [L,NUM]=spm_bwlabel(BW,CONN)"); if (nrhs != 2) mexErrMsgTxt("spm_bwlabel: 2 input arguments required"); if (nlhs != 2) mexErrMsgTxt("spm_bwlabel: 2 output argument required"); /* Get binary map. */ if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0])) { mexErrMsgTxt("spm_bwlabel: BW must be numeric, real, full and double"); } ndim = mxGetNumberOfDimensions(prhs[0]); if ((ndim < 2) || (ndim > 3)) { mexErrMsgTxt("spm_bwlabel: BW must be 2 or 3-dimensional"); } cdim = mxGetDimensions(prhs[0]); dim[0]=cdim[0]; dim[1]=cdim[1]; if (ndim==2) {dim[2]=1; ndim=3;} else {dim[2]=cdim[2];} for (i=0, n=1; i<ndim; i++) { n *= dim[i]; } bw = mxGetPr(prhs[0]); /* Get connectedness criterion. */ if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1])) { mexErrMsgTxt("spm_bwlabel: CONN must be numeric, real, full and double"); } tmp1 = mxGetM(prhs[1]); tmp2 = mxGetN(prhs[1]); dconn = mxGetScalar(prhs[1]); conn = (unsigned int) (dconn + 0.1); /* Truncation or rounding. */ if ((tmp1 != 1) || (tmp2 != 1) || ((conn!=6) && (conn!=18) && (conn!=26))) { mexErrMsgTxt("spm_bwlabel: CONN must be 6, 18 or 26"); } /* Allocate memory for output. */ plhs[0] = mxCreateNumericArray(ndim,dim,mxDOUBLE_CLASS,mxREAL); l = mxGetPr(plhs[0]); /* Initialise output maps to zero. */ memset(l,0,n*sizeof(double)); /* Allocate memory for initial labelling map. */ il = (unsigned int *) mxCalloc(n,sizeof(unsigned int)); /* Do initial labelling and create translation table. */ ttn = do_initial_labelling(bw,dim,conn,il,&tt); /* Translate labels to terminal numbers. */ nl = translate_labels(il,dim,tt,ttn,l); plhs[1] = mxCreateScalarDouble(nl); /* Clean up a bit. */ mxFree(il); mxFree(tt); return; }
gpl-2.0
alexsmander/alexmattorr
wp-content/themes/portfolio/node_modules/grunt-concat-sourcemap/test/concat_sourcemap_test.js
5041
'use strict'; var grunt = require('grunt'); exports.concat_sourcemap = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(2); var actual = grunt.file.read('tmp/default_options.js'); var expected = grunt.file.read('test/expected/default_options.js'); test.equal(actual, expected, 'should join files with default separator.'); var actualMap = grunt.file.read('tmp/default_options.js.map'); var expectedMap = grunt.file.read('test/expected/default_options.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file.'); test.done(); }, options_with_sourceRoot: function(test) { test.expect(2); var actual = grunt.file.read('tmp/options_with_sourceRoot.js'); var expected = grunt.file.read('test/expected/options_with_sourceRoot.js'); test.equal(actual, expected, 'should not affect a output joined file.'); var actualMap = grunt.file.read('tmp/options_with_sourceRoot.js.map'); var expectedMap = grunt.file.read('test/expected/options_with_sourceRoot.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file including `sourceRoot` property.'); test.done(); }, options_with_sourcesContent: function(test) { test.expect(2); var actual = grunt.file.read('tmp/options_with_sourcesContent.js'); var expected = grunt.file.read('test/expected/options_with_sourcesContent.js'); test.equal(actual, expected, 'should not affect a output joined file.'); var actualMap = grunt.file.read('tmp/options_with_sourcesContent.js.map'); var expectedMap = grunt.file.read('test/expected/options_with_sourcesContent.js.map'); test.equal(actualMap, expectedMap, 'should write a source map file including `sourcesContent` property.'); test.done(); }, options_with_process: function(test) { test.expect(1); var actual = grunt.file.read('tmp/options_with_process.js'); var expected = grunt.file.read('test/expected/options_with_process.js'); test.equal(actual, expected, 'should use process function to modify concatenated file'); test.done(); }, with_coffee: function(test) { test.expect(1); var actualMap = grunt.file.read('tmp/with_coffee.js.map'); var expectedMap = grunt.file.read('test/expected/with_coffee.js.map'); test.equal(actualMap, expectedMap, 'should resolve combined source map.'); test.done(); }, css_files: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/css_files.css'); expectedContent = grunt.file.read('test/expected/css_files.css'); test.equal(actualContent, expectedContent, 'should output linking line as `/*# sourceMappingURL=<URL> */`.'); actualMap = grunt.file.read('tmp/css_files.css.map'); expectedMap = grunt.file.read('test/expected/css_files.css.map'); test.equal(actualMap, expectedMap, 'should write a source map.'); test.done(); }, css_files_with_sass_generated: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/css_files_with_sass_generated.css'); expectedContent = grunt.file.read('test/expected/css_files_with_sass_generated.css'); test.equal(actualContent, expectedContent, 'should concatenate contents except for linking lines.'); actualMap = grunt.file.read('tmp/css_files_with_sass_generated.css.map'); expectedMap = grunt.file.read('test/expected/css_files_with_sass_generated.css.map'); test.equal(actualMap, expectedMap, 'should write a source map resolving combined source map.'); test.done(); }, file_with_linking: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/file_with_linking.js'); expectedContent = grunt.file.read('test/expected/file_with_linking.js'); test.equal(actualContent, expectedContent, 'should concatenate contents and resolve the linking.'); actualMap = grunt.file.read('tmp/file_with_linking.js.map'); expectedMap = grunt.file.read('test/expected/file_with_linking.js.map'); test.equal(actualMap, expectedMap, 'should concatenate contents and resolve the linking.'); test.done(); }, file_with_old_linking: function(test) { var actualContent, expectedContent, actualMap, expectedMap; test.expect(2); actualContent = grunt.file.read('tmp/file_with_old_linking.js'); expectedContent = grunt.file.read('test/expected/file_with_old_linking.js'); test.equal(actualContent, expectedContent, 'should concatenate contents and resolve the old linking.'); actualMap = grunt.file.read('tmp/file_with_old_linking.js.map'); expectedMap = grunt.file.read('test/expected/file_with_old_linking.js.map'); test.equal(actualMap, expectedMap, 'should concatenate contents and resolve the old linking.'); test.done(); }, };
gpl-2.0
kadasaikumar/iotivity-1.2.1
service/things-manager/sampleapp/linux/configuration/MaintenanceCollection.h
2998
//****************************************************************** // // Copyright 2014 Samsung Electronics 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// /// This sample shows how one could create a resource (collection) with children. /// #include <functional> #include <thread> #include "OCPlatform.h" #include "OCApi.h" #pragma once using namespace OC; typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler; static std::string defaultMntURI = "/oic/mnt"; static std::string defaultMntResourceType = "oic.wk.mnt"; static std::string defaultFactoryReset = "false"; static std::string defaultReboot = "false"; static std::string defaultStartStatCollection = "false"; class MaintenanceResource { public: // Maintenance members std::string m_maintenanceUri; std::string m_factoryReset; std::string m_reboot; std::string m_startStatCollection; std::vector< std::string > m_maintenanceTypes; std::vector< std::string > m_maintenanceInterfaces; OCResourceHandle m_maintenanceHandle; OCRepresentation m_maintenanceRep; public: /// Constructor MaintenanceResource() : m_factoryReset(defaultFactoryReset), m_reboot(defaultReboot), m_startStatCollection(defaultStartStatCollection) { m_maintenanceUri = defaultMntURI; // URI of the resource m_maintenanceTypes.push_back(defaultMntResourceType); // resource type name. m_maintenanceInterfaces.push_back(DEFAULT_INTERFACE); // resource interface. m_maintenanceRep.setValue("fr", m_factoryReset); m_maintenanceRep.setValue("rb", m_reboot); m_maintenanceRep.setValue("ssc", m_startStatCollection); m_maintenanceRep.setUri(m_maintenanceUri); m_maintenanceRep.setResourceTypes(m_maintenanceTypes); m_maintenanceRep.setResourceInterfaces(m_maintenanceInterfaces); m_maintenanceHandle = NULL; } ; /// This function internally calls registerResource API. void createResources(ResourceEntityHandler callback); void setMaintenanceRepresentation(OCRepresentation& rep); OCRepresentation getMaintenanceRepresentation(); std::string getUri(); void maintenanceMonitor(int second); std::function< void() > factoryReset; };
gpl-3.0
andreaso/ansible
lib/ansible/modules/system/known_hosts.py
12710
#!/usr/bin/python """ Ansible module to manage the ssh known_hosts file. Copyright(c) 2014, Matthew Vernon <[email protected]> This module 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 module 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 module. If not, see <http://www.gnu.org/licenses/>. """ ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: known_hosts short_description: Add or remove a host from the C(known_hosts) file description: - The C(known_hosts) module lets you add or remove a host keys from the C(known_hosts) file. - Starting at Ansible 2.2, multiple entries per host are allowed, but only one for each key type supported by ssh. This is useful if you're going to want to use the M(git) module over ssh, for example. - If you have a very large number of host keys to manage, you will find the M(template) module more useful. version_added: "1.9" options: name: aliases: [ 'host' ] description: - The host to add or remove (must match a host specified in key) required: true default: null key: description: - The SSH public host key, as a string (required if state=present, optional when state=absent, in which case all keys for the host are removed). The key must be in the right format for ssh (see sshd(1), section "SSH_KNOWN_HOSTS FILE FORMAT") required: false default: null path: description: - The known_hosts file to edit required: no default: "(homedir)+/.ssh/known_hosts" hash_host: description: - Hash the hostname in the known_hosts file required: no default: no version_added: "2.3" state: description: - I(present) to add the host key, I(absent) to remove it. choices: [ "present", "absent" ] required: no default: present requirements: [ ] author: "Matthew Vernon (@mcv21)" ''' EXAMPLES = ''' - name: tell the host about our servers it might want to ssh to known_hosts: path: /etc/ssh/ssh_known_hosts name: foo.com.invalid key: "{{ lookup('file', 'pubkeys/foo.com.invalid') }}" ''' # Makes sure public host keys are present or absent in the given known_hosts # file. # # Arguments # ========= # name = hostname whose key should be added (alias: host) # key = line(s) to add to known_hosts file # path = the known_hosts file to edit (default: ~/.ssh/known_hosts) # hash_host = yes|no (default: no) hash the hostname in the known_hosts file # state = absent|present (default: present) import os import os.path import tempfile import errno import re from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.basic import AnsibleModule def enforce_state(module, params): """ Add or remove key. """ host = params["name"] key = params.get("key", None) port = params.get("port", None) path = params.get("path") hash_host = params.get("hash_host") state = params.get("state") # Find the ssh-keygen binary sshkeygen = module.get_bin_path("ssh-keygen", True) # Trailing newline in files gets lost, so re-add if necessary if key and key[-1] != '\n': key += '\n' if key is None and state != "absent": module.fail_json(msg="No key specified when adding a host") sanity_check(module, host, key, sshkeygen) found, replace_or_add, found_line, key = search_for_host_key(module, host, key, hash_host, path, sshkeygen) params['diff'] = compute_diff(path, found_line, replace_or_add, state, key) # We will change state if found==True & state!="present" # or found==False & state=="present" # i.e found XOR (state=="present") # Alternatively, if replace is true (i.e. key present, and we must change # it) if module.check_mode: module.exit_json(changed=replace_or_add or (state == "present") != found, diff=params['diff']) # Now do the work. # Only remove whole host if found and no key provided if found and key is None and state == "absent": module.run_command([sshkeygen, '-R', host, '-f', path], check_rc=True) params['changed'] = True # Next, add a new (or replacing) entry if replace_or_add or found != (state == "present"): try: inf = open(path, "r") except IOError: e = get_exception() if e.errno == errno.ENOENT: inf = None else: module.fail_json(msg="Failed to read %s: %s" % (path, str(e))) try: outf = tempfile.NamedTemporaryFile(mode='w+', dir=os.path.dirname(path)) if inf is not None: for line_number, line in enumerate(inf): if found_line == (line_number + 1) and (replace_or_add or state == 'absent'): continue # skip this line to replace its key outf.write(line) inf.close() if state == 'present': outf.write(key) outf.flush() module.atomic_move(outf.name, path) except (IOError, OSError): e = get_exception() module.fail_json(msg="Failed to write to file %s: %s" % (path, str(e))) try: outf.close() except: pass params['changed'] = True return params def sanity_check(module, host, key, sshkeygen): '''Check supplied key is sensible host and key are parameters provided by the user; If the host provided is inconsistent with the key supplied, then this function quits, providing an error to the user. sshkeygen is the path to ssh-keygen, found earlier with get_bin_path ''' # If no key supplied, we're doing a removal, and have nothing to check here. if key is None: return # Rather than parsing the key ourselves, get ssh-keygen to do it # (this is essential for hashed keys, but otherwise useful, as the # key question is whether ssh-keygen thinks the key matches the host). # The approach is to write the key to a temporary file, # and then attempt to look up the specified host in that file. try: outf = tempfile.NamedTemporaryFile(mode='w+') outf.write(key) outf.flush() except IOError: e = get_exception() module.fail_json(msg="Failed to write to temporary file %s: %s" % (outf.name, str(e))) sshkeygen_command = [sshkeygen, '-F', host, '-f', outf.name] rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=True) try: outf.close() except: pass if stdout == '': # host not found module.fail_json(msg="Host parameter does not match hashed host field in supplied key") def search_for_host_key(module, host, key, hash_host, path, sshkeygen): '''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line) Looks up host and keytype in the known_hosts file path; if it's there, looks to see if one of those entries matches key. Returns: found (Boolean): is host found in path? replace_or_add (Boolean): is the key in path different to that supplied by user? found_line (int or None): the line where a key of the same type was found if found=False, then replace is always False. sshkeygen is the path to ssh-keygen, found earlier with get_bin_path ''' if os.path.exists(path) is False: return False, False, None, key sshkeygen_command = [sshkeygen, '-F', host, '-f', path] # openssh >=6.4 has changed ssh-keygen behaviour such that it returns # 1 if no host is found, whereas previously it returned 0 rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False) if stdout == '' and stderr == '' and (rc == 0 or rc == 1): return False, False, None, key # host not found, no other errors if rc != 0: # something went wrong module.fail_json(msg="ssh-keygen failed (rc=%d, stdout='%s',stderr='%s')" % (rc, stdout, stderr)) # If user supplied no key, we don't want to try and replace anything with it if key is None: return True, False, None, key lines = stdout.split('\n') new_key = normalize_known_hosts_key(key) sshkeygen_command.insert(1, '-H') rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False) if rc not in (0, 1) or stderr != '': # something went wrong module.fail_json(msg="ssh-keygen failed to hash host (rc=%d, stdout='%s',stderr='%s')" % (rc, stdout, stderr)) hashed_lines = stdout.split('\n') for lnum, l in enumerate(lines): if l == '': continue elif l[0] == '#': # info output from ssh-keygen; contains the line number where key was found try: # This output format has been hardcoded in ssh-keygen since at least OpenSSH 4.0 # It always outputs the non-localized comment before the found key found_line = int(re.search(r'found: line (\d+)', l).group(1)) except IndexError: module.fail_json(msg="failed to parse output of ssh-keygen for line number: '%s'" % l) else: found_key = normalize_known_hosts_key(l) if hash_host is True: if found_key['host'][:3] == '|1|': new_key['host'] = found_key['host'] else: hashed_host = normalize_known_hosts_key(hashed_lines[lnum]) found_key['host'] = hashed_host['host'] key = key.replace(host, found_key['host']) if new_key == found_key: # found a match return True, False, found_line, key # found exactly the same key, don't replace elif new_key['type'] == found_key['type']: # found a different key for the same key type return True, True, found_line, key # No match found, return found and replace, but no line return True, True, None, key def normalize_known_hosts_key(key): ''' Transform a key, either taken from a known_host file or provided by the user, into a normalized form. The host part (which might include multiple hostnames or be hashed) gets replaced by the provided host. Also, any spurious information gets removed from the end (like the username@host tag usually present in hostkeys, but absent in known_hosts files) ''' k = key.strip() # trim trailing newline k = key.split() d = dict() # The optional "marker" field, used for @cert-authority or @revoked if k[0][0] == '@': d['options'] = k[0] d['host'] = k[1] d['type'] = k[2] d['key'] = k[3] else: d['host'] = k[0] d['type'] = k[1] d['key'] = k[2] return d def compute_diff(path, found_line, replace_or_add, state, key): diff = { 'before_header': path, 'after_header': path, 'before': '', 'after': '', } try: inf = open(path, "r") except IOError: e = get_exception() if e.errno == errno.ENOENT: diff['before_header'] = '/dev/null' else: diff['before'] = inf.read() inf.close() lines = diff['before'].splitlines(1) if (replace_or_add or state == 'absent') and found_line is not None and 1 <= found_line <= len(lines): del lines[found_line - 1] if state == 'present' and (replace_or_add or found_line is None): lines.append(key) diff['after'] = ''.join(lines) return diff def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str', aliases=['host']), key=dict(required=False, type='str'), path=dict(default="~/.ssh/known_hosts", type='path'), hash_host=dict(required=False, type='bool', default=False), state=dict(default='present', choices=['absent', 'present']), ), supports_check_mode=True ) results = enforce_state(module, module.params) module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
BradErz/kops
vendor/google.golang.org/api/logging/v1beta3/logging-gen.go
174915
// Package logging provides access to the Google Cloud Logging API. // // See https://cloud.google.com/logging/docs/ // // Usage example: // // import "google.golang.org/api/logging/v1beta3" // ... // loggingService, err := logging.New(oauthHttpClient) package logging // import "google.golang.org/api/logging/v1beta3" import ( "bytes" "encoding/json" "errors" "fmt" context "golang.org/x/net/context" ctxhttp "golang.org/x/net/context/ctxhttp" gensupport "google.golang.org/api/gensupport" googleapi "google.golang.org/api/googleapi" "io" "net/http" "net/url" "strconv" "strings" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = ctxhttp.Do const apiId = "logging:v1beta3" const apiName = "logging" const apiVersion = "v1beta3" const basePath = "https://logging.googleapis.com/" // OAuth2 scopes used by this API. const ( // View and manage your data across Google Cloud Platform services CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" // View your data across Google Cloud Platform services CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only" // Administrate log data for your projects LoggingAdminScope = "https://www.googleapis.com/auth/logging.admin" // View log data for your projects LoggingReadScope = "https://www.googleapis.com/auth/logging.read" // Submit log data for your projects LoggingWriteScope = "https://www.googleapis.com/auth/logging.write" ) func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Projects = NewProjectsService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Projects *ProjectsService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewProjectsService(s *Service) *ProjectsService { rs := &ProjectsService{s: s} rs.LogServices = NewProjectsLogServicesService(s) rs.Logs = NewProjectsLogsService(s) rs.Metrics = NewProjectsMetricsService(s) rs.Sinks = NewProjectsSinksService(s) return rs } type ProjectsService struct { s *Service LogServices *ProjectsLogServicesService Logs *ProjectsLogsService Metrics *ProjectsMetricsService Sinks *ProjectsSinksService } func NewProjectsLogServicesService(s *Service) *ProjectsLogServicesService { rs := &ProjectsLogServicesService{s: s} rs.Indexes = NewProjectsLogServicesIndexesService(s) rs.Sinks = NewProjectsLogServicesSinksService(s) return rs } type ProjectsLogServicesService struct { s *Service Indexes *ProjectsLogServicesIndexesService Sinks *ProjectsLogServicesSinksService } func NewProjectsLogServicesIndexesService(s *Service) *ProjectsLogServicesIndexesService { rs := &ProjectsLogServicesIndexesService{s: s} return rs } type ProjectsLogServicesIndexesService struct { s *Service } func NewProjectsLogServicesSinksService(s *Service) *ProjectsLogServicesSinksService { rs := &ProjectsLogServicesSinksService{s: s} return rs } type ProjectsLogServicesSinksService struct { s *Service } func NewProjectsLogsService(s *Service) *ProjectsLogsService { rs := &ProjectsLogsService{s: s} rs.Entries = NewProjectsLogsEntriesService(s) rs.Sinks = NewProjectsLogsSinksService(s) return rs } type ProjectsLogsService struct { s *Service Entries *ProjectsLogsEntriesService Sinks *ProjectsLogsSinksService } func NewProjectsLogsEntriesService(s *Service) *ProjectsLogsEntriesService { rs := &ProjectsLogsEntriesService{s: s} return rs } type ProjectsLogsEntriesService struct { s *Service } func NewProjectsLogsSinksService(s *Service) *ProjectsLogsSinksService { rs := &ProjectsLogsSinksService{s: s} return rs } type ProjectsLogsSinksService struct { s *Service } func NewProjectsMetricsService(s *Service) *ProjectsMetricsService { rs := &ProjectsMetricsService{s: s} return rs } type ProjectsMetricsService struct { s *Service } func NewProjectsSinksService(s *Service) *ProjectsSinksService { rs := &ProjectsSinksService{s: s} return rs } type ProjectsSinksService struct { s *Service } // Empty: A generic empty message that you can re-use to avoid defining // duplicated empty messages in your APIs. A typical example is to use // it as the request or the response type of an API method. For // instance: service Foo { rpc Bar(google.protobuf.Empty) returns // (google.protobuf.Empty); } The JSON representation for `Empty` is // empty JSON object `{}`. type Empty struct { // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` } // HttpRequest: A common proto for logging HTTP requests. type HttpRequest struct { // CacheHit: Whether or not an entity was served from cache (with or // without validation). CacheHit bool `json:"cacheHit,omitempty"` // Referer: Referer (a.k.a. referrer) URL of request, as defined in // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html. Referer string `json:"referer,omitempty"` // RemoteIp: IP address of the client who issues the HTTP request. Could // be either IPv4 or IPv6. RemoteIp string `json:"remoteIp,omitempty"` // RequestMethod: Request method, such as `GET`, `HEAD`, `PUT` or // `POST`. RequestMethod string `json:"requestMethod,omitempty"` // RequestSize: Size of the HTTP request message in bytes, including // request headers and the request body. RequestSize int64 `json:"requestSize,omitempty,string"` // RequestUrl: Contains the scheme (http|https), the host name, the path // and the query portion of the URL that was requested. RequestUrl string `json:"requestUrl,omitempty"` // ResponseSize: Size of the HTTP response message in bytes sent back to // the client, including response headers and response body. ResponseSize int64 `json:"responseSize,omitempty,string"` // Status: A response code indicates the status of response, e.g., 200. Status int64 `json:"status,omitempty"` // UserAgent: User agent sent by the client, e.g., "Mozilla/4.0 // (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)". UserAgent string `json:"userAgent,omitempty"` // ValidatedWithOriginServer: Whether or not the response was validated // with the origin server before being served from cache. This field is // only meaningful if cache_hit is True. ValidatedWithOriginServer bool `json:"validatedWithOriginServer,omitempty"` // ForceSendFields is a list of field names (e.g. "CacheHit") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "CacheHit") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *HttpRequest) MarshalJSON() ([]byte, error) { type noMethod HttpRequest raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogMetricsResponse: Result returned from ListLogMetrics. type ListLogMetricsResponse struct { // Metrics: The list of metrics that was requested. Metrics []*LogMetric `json:"metrics,omitempty"` // NextPageToken: If there are more results, then `nextPageToken` is // returned in the response. To get the next batch of entries, use the // value of `nextPageToken` as `pageToken` in the next call of // `ListLogMetrics`. If `nextPageToken` is empty, then there are no more // results. NextPageToken string `json:"nextPageToken,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Metrics") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Metrics") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogMetricsResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogMetricsResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogServiceIndexesResponse: Result returned from // ListLogServiceIndexesRequest. type ListLogServiceIndexesResponse struct { // NextPageToken: If there are more results, then `nextPageToken` is // returned in the response. To get the next batch of indexes, use the // value of `nextPageToken` as `pageToken` in the next call of // `ListLogServiceIndexes`. If `nextPageToken` is empty, then there are // no more results. NextPageToken string `json:"nextPageToken,omitempty"` // ServiceIndexPrefixes: A list of log service index values. Each index // value has the form "/value1/value2/...", where `value1` is a value // in the primary index, `value2` is a value in the secondary index, and // so forth. ServiceIndexPrefixes []string `json:"serviceIndexPrefixes,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogServiceIndexesResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogServiceIndexesResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogServiceSinksResponse: Result returned from // `ListLogServiceSinks`. type ListLogServiceSinksResponse struct { // Sinks: The requested log service sinks. If a returned `LogSink` // object has an empty `destination` field, the client can retrieve the // complete `LogSink` object by calling `logServices.sinks.get`. Sinks []*LogSink `json:"sinks,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Sinks") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Sinks") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogServiceSinksResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogServiceSinksResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogServicesResponse: Result returned from // `ListLogServicesRequest`. type ListLogServicesResponse struct { // LogServices: A list of log services. LogServices []*LogService `json:"logServices,omitempty"` // NextPageToken: If there are more results, then `nextPageToken` is // returned in the response. To get the next batch of services, use the // value of `nextPageToken` as `pageToken` in the next call of // `ListLogServices`. If `nextPageToken` is empty, then there are no // more results. NextPageToken string `json:"nextPageToken,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "LogServices") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "LogServices") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogServicesResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogServicesResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogSinksResponse: Result returned from `ListLogSinks`. type ListLogSinksResponse struct { // Sinks: The requested log sinks. If a returned `LogSink` object has an // empty `destination` field, the client can retrieve the complete // `LogSink` object by calling `log.sinks.get`. Sinks []*LogSink `json:"sinks,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Sinks") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Sinks") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogSinksResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogSinksResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListLogsResponse: Result returned from ListLogs. type ListLogsResponse struct { // Logs: A list of log descriptions matching the criteria. Logs []*Log `json:"logs,omitempty"` // NextPageToken: If there are more results, then `nextPageToken` is // returned in the response. To get the next batch of logs, use the // value of `nextPageToken` as `pageToken` in the next call of // `ListLogs`. If `nextPageToken` is empty, then there are no more // results. NextPageToken string `json:"nextPageToken,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Logs") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Logs") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListLogsResponse) MarshalJSON() ([]byte, error) { type noMethod ListLogsResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // ListSinksResponse: Result returned from `ListSinks`. type ListSinksResponse struct { // Sinks: The requested sinks. If a returned `LogSink` object has an // empty `destination` field, the client can retrieve the complete // `LogSink` object by calling `projects.sinks.get`. Sinks []*LogSink `json:"sinks,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Sinks") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Sinks") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *ListSinksResponse) MarshalJSON() ([]byte, error) { type noMethod ListSinksResponse raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Log: _Output only._ Describes a log, which is a named stream of log // entries. type Log struct { // DisplayName: _Optional._ The common name of the log. Example: // "request_log". DisplayName string `json:"displayName,omitempty"` // Name: The resource name of the log. Example: // "/projects/my-gcp-project-id/logs/LOG_NAME", where `LOG_NAME` is // the URL-encoded given name of the log. The log includes those log // entries whose `LogEntry.log` field contains this given name. To avoid // name collisions, it is a best practice to prefix the given log name // with the service name, but this is not required. Examples of log // given names: "appengine.googleapis.com/request_log", // "apache-access". Name string `json:"name,omitempty"` // PayloadType: _Optional_. A URI representing the expected payload type // for log entries. PayloadType string `json:"payloadType,omitempty"` // ForceSendFields is a list of field names (e.g. "DisplayName") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "DisplayName") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Log) MarshalJSON() ([]byte, error) { type noMethod Log raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogEntry: An individual entry in a log. type LogEntry struct { // HttpRequest: Information about the HTTP request associated with this // log entry, if applicable. HttpRequest *HttpRequest `json:"httpRequest,omitempty"` // InsertId: A unique ID for the log entry. If you provide this field, // the logging service considers other log entries in the same log with // the same ID as duplicates which can be removed. InsertId string `json:"insertId,omitempty"` // Log: The log to which this entry belongs. When a log entry is // ingested, the value of this field is set by the logging system. Log string `json:"log,omitempty"` // Metadata: Information about the log entry. Metadata *LogEntryMetadata `json:"metadata,omitempty"` // ProtoPayload: The log entry payload, represented as a protocol buffer // that is expressed as a JSON object. You can only pass `protoPayload` // values that belong to a set of approved types. ProtoPayload LogEntryProtoPayload `json:"protoPayload,omitempty"` // StructPayload: The log entry payload, represented as a structure that // is expressed as a JSON object. StructPayload LogEntryStructPayload `json:"structPayload,omitempty"` // TextPayload: The log entry payload, represented as a Unicode string // (UTF-8). TextPayload string `json:"textPayload,omitempty"` // ForceSendFields is a list of field names (e.g. "HttpRequest") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "HttpRequest") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogEntry) MarshalJSON() ([]byte, error) { type noMethod LogEntry raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type LogEntryProtoPayload interface{} type LogEntryStructPayload interface{} // LogEntryMetadata: Additional data that is associated with a log // entry, set by the service creating the log entry. type LogEntryMetadata struct { // Labels: A set of (key, value) data that provides additional // information about the log entry. If the log entry is from one of the // Google Cloud Platform sources listed below, the indicated (key, // value) information must be provided: Google App Engine, service_name // `appengine.googleapis.com`: "appengine.googleapis.com/module_id", // "appengine.googleapis.com/version_id", and one of: // "appengine.googleapis.com/replica_index", // "appengine.googleapis.com/clone_id", or else provide the following // Compute Engine labels: Google Compute Engine, service_name // `compute.googleapis.com`: "compute.googleapis.com/resource_type", // "instance" "compute.googleapis.com/resource_id", Labels map[string]string `json:"labels,omitempty"` // ProjectId: The project ID of the Google Cloud Platform service that // created the log entry. ProjectId string `json:"projectId,omitempty"` // Region: The region name of the Google Cloud Platform service that // created the log entry. For example, "us-central1". Region string `json:"region,omitempty"` // ServiceName: The API name of the Google Cloud Platform service that // created the log entry. For example, "compute.googleapis.com". ServiceName string `json:"serviceName,omitempty"` // Severity: The severity of the log entry. // // Possible values: // "DEFAULT" // "DEBUG" // "INFO" // "NOTICE" // "WARNING" // "ERROR" // "CRITICAL" // "ALERT" // "EMERGENCY" Severity string `json:"severity,omitempty"` // Timestamp: The time the event described by the log entry occurred. // Timestamps must be later than January 1, 1970. Timestamp string `json:"timestamp,omitempty"` // UserId: The fully-qualified email address of the authenticated user // that performed or requested the action represented by the log entry. // If the log entry does not apply to an action taken by an // authenticated user, then the field should be empty. UserId string `json:"userId,omitempty"` // Zone: The zone of the Google Cloud Platform service that created the // log entry. For example, "us-central1-a". Zone string `json:"zone,omitempty"` // ForceSendFields is a list of field names (e.g. "Labels") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Labels") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogEntryMetadata) MarshalJSON() ([]byte, error) { type noMethod LogEntryMetadata raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogError: Describes a problem with a logging resource or operation. type LogError struct { // Resource: A resource name associated with this error. For example, // the name of a Cloud Storage bucket that has insufficient permissions // to be a destination for log entries. Resource string `json:"resource,omitempty"` // Status: The error description, including a classification code, an // error message, and other details. Status *Status `json:"status,omitempty"` // TimeNanos: The time the error was observed, in nanoseconds since the // Unix epoch. TimeNanos int64 `json:"timeNanos,omitempty,string"` // ForceSendFields is a list of field names (e.g. "Resource") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Resource") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogError) MarshalJSON() ([]byte, error) { type noMethod LogError raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogLine: Application log line emitted while processing a request. type LogLine struct { // LogMessage: App provided log message. LogMessage string `json:"logMessage,omitempty"` // Severity: Severity of log. // // Possible values: // "DEFAULT" // "DEBUG" // "INFO" // "NOTICE" // "WARNING" // "ERROR" // "CRITICAL" // "ALERT" // "EMERGENCY" Severity string `json:"severity,omitempty"` // SourceLocation: Line of code that generated this log message. SourceLocation *SourceLocation `json:"sourceLocation,omitempty"` // Time: Time when log entry was made. May be inaccurate. Time string `json:"time,omitempty"` // ForceSendFields is a list of field names (e.g. "LogMessage") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "LogMessage") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogLine) MarshalJSON() ([]byte, error) { type noMethod LogLine raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogMetric: Describes a logs-based metric. The value of the metric is // the number of log entries in your project that match a logs filter. type LogMetric struct { // Description: A description of this metric. Description string `json:"description,omitempty"` // Filter: An [advanced logs // filter](/logging/docs/view/advanced_filters). Example: "log:syslog // AND metadata.severity>=ERROR". Filter string `json:"filter,omitempty"` // Name: The client-assigned name for this metric, such as // "severe_errors". Metric names are limited to 1000 characters and // can include only the following characters: `A-Z`, `a-z`, `0-9`, and // the special characters `_-.,+!*',()%/\`. The slash character (`/`) // denotes a hierarchy of name pieces, and it cannot be the first // character of the name. Name string `json:"name,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Description") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Description") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogMetric) MarshalJSON() ([]byte, error) { type noMethod LogMetric raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogService: _Output only._ Describes a service that writes log // entries. type LogService struct { // IndexKeys: A list of the names of the keys used to index and label // individual log entries from this service. The first two keys are used // as the primary and secondary index, respectively. Additional keys may // be used to label the entries. For example, App Engine indexes its // entries by module and by version, so its `indexKeys` field is the // following: [ "appengine.googleapis.com/module_id", // "appengine.googleapis.com/version_id" ] IndexKeys []string `json:"indexKeys,omitempty"` // Name: The service's name. Example: "appengine.googleapis.com". Log // names beginning with this string are reserved for this service. This // value can appear in the `LogEntry.metadata.serviceName` field of log // entries associated with this log service. Name string `json:"name,omitempty"` // ForceSendFields is a list of field names (e.g. "IndexKeys") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "IndexKeys") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogService) MarshalJSON() ([]byte, error) { type noMethod LogService raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // LogSink: Describes where log entries are written outside of Cloud // Logging. type LogSink struct { // Destination: The resource name of the destination. Cloud Logging // writes designated log entries to this destination. For example, // "storage.googleapis.com/my-output-bucket". Destination string `json:"destination,omitempty"` // Errors: _Output only._ If any errors occur when invoking a sink // method, then this field contains descriptions of the errors. Errors []*LogError `json:"errors,omitempty"` // Filter: An advanced logs filter. If present, only log entries // matching the filter are written. Only project sinks use this field; // log sinks and log service sinks must not include a filter. Filter string `json:"filter,omitempty"` // Name: The client-assigned name of this sink. For example, // "my-syslog-sink". The name must be unique among the sinks of a // similar kind in the project. Name string `json:"name,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Destination") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Destination") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *LogSink) MarshalJSON() ([]byte, error) { type noMethod LogSink raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // RequestLog: Complete log information about a single request to an // application. type RequestLog struct { // AppEngineRelease: App Engine release version string. AppEngineRelease string `json:"appEngineRelease,omitempty"` // AppId: Identifies the application that handled this request. AppId string `json:"appId,omitempty"` // Cost: An indication of the relative cost of serving this request. Cost float64 `json:"cost,omitempty"` // EndTime: Time at which request was known to end processing. EndTime string `json:"endTime,omitempty"` // Finished: If true, represents a finished request. Otherwise, the // request is active. Finished bool `json:"finished,omitempty"` // Host: The Internet host and port number of the resource being // requested. Host string `json:"host,omitempty"` // HttpVersion: HTTP version of request. HttpVersion string `json:"httpVersion,omitempty"` // InstanceId: An opaque identifier for the instance that handled the // request. InstanceId string `json:"instanceId,omitempty"` // InstanceIndex: If the instance that processed this request was // individually addressable (i.e. belongs to a manually scaled module), // this is the index of the instance. InstanceIndex int64 `json:"instanceIndex,omitempty"` // Ip: Origin IP address. Ip string `json:"ip,omitempty"` // Latency: Latency of the request. Latency string `json:"latency,omitempty"` // Line: List of log lines emitted by the application while serving this // request, if requested. Line []*LogLine `json:"line,omitempty"` // MegaCycles: Number of CPU megacycles used to process request. MegaCycles int64 `json:"megaCycles,omitempty,string"` // Method: Request method, such as `GET`, `HEAD`, `PUT`, `POST`, or // `DELETE`. Method string `json:"method,omitempty"` // ModuleId: Identifies the module of the application that handled this // request. ModuleId string `json:"moduleId,omitempty"` // Nickname: A string that identifies a logged-in user who made this // request, or empty if the user is not logged in. Most likely, this is // the part of the user's email before the '@' sign. The field value is // the same for different requests from the same user, but different // users may have a similar name. This information is also available to // the application via Users API. This field will be populated starting // with App Engine 1.9.21. Nickname string `json:"nickname,omitempty"` // PendingTime: Time this request spent in the pending request queue, if // it was pending at all. PendingTime string `json:"pendingTime,omitempty"` // Referrer: Referrer URL of request. Referrer string `json:"referrer,omitempty"` // RequestId: Globally unique identifier for a request, based on request // start time. Request IDs for requests which started later will compare // greater as strings than those for requests which started earlier. RequestId string `json:"requestId,omitempty"` // Resource: Contains the path and query portion of the URL that was // requested. For example, if the URL was // "http://example.com/app?name=val", the resource would be // "/app?name=val". Any trailing fragment (separated by a '#' character) // will not be included. Resource string `json:"resource,omitempty"` // ResponseSize: Size in bytes sent back to client by request. ResponseSize int64 `json:"responseSize,omitempty,string"` // SourceReference: Source code for the application that handled this // request. There can be more than one source reference per deployed // application if source code is distributed among multiple // repositories. SourceReference []*SourceReference `json:"sourceReference,omitempty"` // StartTime: Time at which request was known to have begun processing. StartTime string `json:"startTime,omitempty"` // Status: Response status of request. Status int64 `json:"status,omitempty"` // TaskName: Task name of the request (for an offline request). TaskName string `json:"taskName,omitempty"` // TaskQueueName: Queue name of the request (for an offline request). TaskQueueName string `json:"taskQueueName,omitempty"` // TraceId: Cloud Trace identifier of the trace for this request. TraceId string `json:"traceId,omitempty"` // UrlMapEntry: File or class within URL mapping used for request. // Useful for tracking down the source code which was responsible for // managing request. Especially for multiply mapped handlers. UrlMapEntry string `json:"urlMapEntry,omitempty"` // UserAgent: User agent used for making request. UserAgent string `json:"userAgent,omitempty"` // VersionId: Version of the application that handled this request. VersionId string `json:"versionId,omitempty"` // WasLoadingRequest: Was this request a loading request for this // instance? WasLoadingRequest bool `json:"wasLoadingRequest,omitempty"` // ForceSendFields is a list of field names (e.g. "AppEngineRelease") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AppEngineRelease") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *RequestLog) MarshalJSON() ([]byte, error) { type noMethod RequestLog raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SourceLocation: Specifies a location in a source file. type SourceLocation struct { // File: Source file name. May or may not be a fully qualified name, // depending on the runtime environment. File string `json:"file,omitempty"` // FunctionName: Human-readable name of the function or method being // invoked, with optional context such as the class or package name, for // use in contexts such as the logs viewer where file:line number is // less meaningful. This may vary by language, for example: in Java: // qual.if.ied.Class.method in Go: dir/package.func in Python: function // ... FunctionName string `json:"functionName,omitempty"` // Line: Line within the source file. Line int64 `json:"line,omitempty,string"` // ForceSendFields is a list of field names (e.g. "File") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "File") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SourceLocation) MarshalJSON() ([]byte, error) { type noMethod SourceLocation raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // SourceReference: A reference to a particular snapshot of the source // tree used to build and deploy an application. type SourceReference struct { // Repository: Optional. A URI string identifying the repository. // Example: "https://github.com/GoogleCloudPlatform/kubernetes.git" Repository string `json:"repository,omitempty"` // RevisionId: The canonical (and persistent) identifier of the deployed // revision. Example (git): "0035781c50ec7aa23385dc841529ce8a4b70db1b" RevisionId string `json:"revisionId,omitempty"` // ForceSendFields is a list of field names (e.g. "Repository") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Repository") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *SourceReference) MarshalJSON() ([]byte, error) { type noMethod SourceReference raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // Status: The `Status` type defines a logical error model that is // suitable for different programming environments, including REST APIs // and RPC APIs. It is used by [gRPC](https://github.com/grpc). The // error model is designed to be: - Simple to use and understand for // most users - Flexible enough to meet unexpected needs # Overview The // `Status` message contains three pieces of data: error code, error // message, and error details. The error code should be an enum value of // google.rpc.Code, but it may accept additional error codes if needed. // The error message should be a developer-facing English message that // helps developers *understand* and *resolve* the error. If a localized // user-facing error message is needed, put the localized message in the // error details or localize it in the client. The optional error // details may contain arbitrary information about the error. There is a // predefined set of error detail types in the package `google.rpc` // which can be used for common error conditions. # Language mapping The // `Status` message is the logical representation of the error model, // but it is not necessarily the actual wire format. When the `Status` // message is exposed in different client libraries and different wire // protocols, it can be mapped differently. For example, it will likely // be mapped to some exceptions in Java, but more likely mapped to some // error codes in C. # Other uses The error model and the `Status` // message can be used in a variety of environments, either with or // without APIs, to provide a consistent developer experience across // different environments. Example uses of this error model include: - // Partial errors. If a service needs to return partial errors to the // client, it may embed the `Status` in the normal response to indicate // the partial errors. - Workflow errors. A typical workflow has // multiple steps. Each step may have a `Status` message for error // reporting purpose. - Batch operations. If a client uses batch request // and batch response, the `Status` message should be used directly // inside batch response, one for each error sub-response. - // Asynchronous operations. If an API call embeds asynchronous operation // results in its response, the status of those operations should be // represented directly using the `Status` message. - Logging. If some // API errors are stored in logs, the message `Status` could be used // directly after any stripping needed for security/privacy reasons. type Status struct { // Code: The status code, which should be an enum value of // google.rpc.Code. Code int64 `json:"code,omitempty"` // Details: A list of messages that carry the error details. There will // be a common set of message types for APIs to use. Details []StatusDetails `json:"details,omitempty"` // Message: A developer-facing error message, which should be in // English. Any user-facing error message should be localized and sent // in the google.rpc.Status.details field, or localized by the client. Message string `json:"message,omitempty"` // ForceSendFields is a list of field names (e.g. "Code") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Code") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *Status) MarshalJSON() ([]byte, error) { type noMethod Status raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } type StatusDetails interface{} // WriteLogEntriesRequest: The parameters to WriteLogEntries. type WriteLogEntriesRequest struct { // CommonLabels: Metadata labels that apply to all log entries in this // request, so that you don't have to repeat them in each log entry's // `metadata.labels` field. If any of the log entries contains a (key, // value) with the same key that is in `commonLabels`, then the entry's // (key, value) overrides the one in `commonLabels`. CommonLabels map[string]string `json:"commonLabels,omitempty"` // Entries: Log entries to insert. Entries []*LogEntry `json:"entries,omitempty"` // ForceSendFields is a list of field names (e.g. "CommonLabels") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "CommonLabels") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *WriteLogEntriesRequest) MarshalJSON() ([]byte, error) { type noMethod WriteLogEntriesRequest raw := noMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // WriteLogEntriesResponse: Result returned from WriteLogEntries. empty type WriteLogEntriesResponse struct { // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` } // method id "logging.projects.logServices.list": type ProjectsLogServicesListCall struct { s *Service projectsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists the log services that have log entries in this project. func (r *ProjectsLogServicesService) List(projectsId string) *ProjectsLogServicesListCall { c := &ProjectsLogServicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId return c } // PageSize sets the optional parameter "pageSize": The maximum number // of `LogService` objects to return in one operation. func (c *ProjectsLogServicesListCall) PageSize(pageSize int64) *ProjectsLogServicesListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": An opaque token, // returned as `nextPageToken` by a prior `ListLogServices` operation. // If `pageToken` is supplied, then the other fields of this request are // ignored, and instead the previous `ListLogServices` operation is // continued. func (c *ProjectsLogServicesListCall) PageToken(pageToken string) *ProjectsLogServicesListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesListCall) Fields(s ...googleapi.Field) *ProjectsLogServicesListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogServicesListCall) IfNoneMatch(entityTag string) *ProjectsLogServicesListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesListCall) Context(ctx context.Context) *ProjectsLogServicesListCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.list" call. // Exactly one of *ListLogServicesResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListLogServicesResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogServicesListCall) Do(opts ...googleapi.CallOption) (*ListLogServicesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogServicesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists the log services that have log entries in this project.", // "httpMethod": "GET", // "id": "logging.projects.logServices.list", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "pageSize": { // "description": "The maximum number of `LogService` objects to return in one operation.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "An opaque token, returned as `nextPageToken` by a prior `ListLogServices` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServices` operation is continued.", // "location": "query", // "type": "string" // }, // "projectsId": { // "description": "Part of `projectName`. The resource name of the project whose services are to be listed.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices", // "response": { // "$ref": "ListLogServicesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsLogServicesListCall) Pages(ctx context.Context, f func(*ListLogServicesResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "logging.projects.logServices.indexes.list": type ProjectsLogServicesIndexesListCall struct { s *Service projectsId string logServicesId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists the current index values for a log service. func (r *ProjectsLogServicesIndexesService) List(projectsId string, logServicesId string) *ProjectsLogServicesIndexesListCall { c := &ProjectsLogServicesIndexesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId return c } // Depth sets the optional parameter "depth": A non-negative integer // that limits the number of levels of the index hierarchy that are // returned. If `depth` is 1 (default), only the first index key value // is returned. If `depth` is 2, both primary and secondary key values // are returned. If `depth` is 0, the depth is the number of // slash-separators in the `indexPrefix` field, not counting a slash // appearing as the last character of the prefix. If the `indexPrefix` // field is empty, the default depth is 1. It is an error for `depth` to // be any positive value less than the number of components in // `indexPrefix`. func (c *ProjectsLogServicesIndexesListCall) Depth(depth int64) *ProjectsLogServicesIndexesListCall { c.urlParams_.Set("depth", fmt.Sprint(depth)) return c } // IndexPrefix sets the optional parameter "indexPrefix": Restricts the // index values returned to be those with a specified prefix for each // index key. This field has the form "/prefix1/prefix2/...", in order // corresponding to the `LogService indexKeys`. Non-empty prefixes must // begin with `/`. For example, App Engine's two keys are the module ID // and the version ID. Following is the effect of using various values // for `indexPrefix`: + "/Mod/" retrieves `/Mod/10` and `/Mod/11` but // not `/ModA/10`. + "/Mod` retrieves `/Mod/10`, `/Mod/11` and // `/ModA/10` but not `/XXX/33`. + "/Mod/1" retrieves `/Mod/10` and // `/Mod/11` but not `/ModA/10`. + "/Mod/10/" retrieves `/Mod/10` // only. + An empty prefix or "/" retrieves all values. func (c *ProjectsLogServicesIndexesListCall) IndexPrefix(indexPrefix string) *ProjectsLogServicesIndexesListCall { c.urlParams_.Set("indexPrefix", indexPrefix) return c } // PageSize sets the optional parameter "pageSize": The maximum number // of log service index resources to return in one operation. func (c *ProjectsLogServicesIndexesListCall) PageSize(pageSize int64) *ProjectsLogServicesIndexesListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": An opaque token, // returned as `nextPageToken` by a prior `ListLogServiceIndexes` // operation. If `pageToken` is supplied, then the other fields of this // request are ignored, and instead the previous `ListLogServiceIndexes` // operation is continued. func (c *ProjectsLogServicesIndexesListCall) PageToken(pageToken string) *ProjectsLogServicesIndexesListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesIndexesListCall) Fields(s ...googleapi.Field) *ProjectsLogServicesIndexesListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogServicesIndexesListCall) IfNoneMatch(entityTag string) *ProjectsLogServicesIndexesListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesIndexesListCall) Context(ctx context.Context) *ProjectsLogServicesIndexesListCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesIndexesListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/indexes") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.indexes.list" call. // Exactly one of *ListLogServiceIndexesResponse or error will be // non-nil. Any non-2xx status code is an error. Response headers are in // either *ListLogServiceIndexesResponse.ServerResponse.Header or (if a // response was returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogServicesIndexesListCall) Do(opts ...googleapi.CallOption) (*ListLogServiceIndexesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogServiceIndexesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists the current index values for a log service.", // "httpMethod": "GET", // "id": "logging.projects.logServices.indexes.list", // "parameterOrder": [ // "projectsId", // "logServicesId" // ], // "parameters": { // "depth": { // "description": "A non-negative integer that limits the number of levels of the index hierarchy that are returned. If `depth` is 1 (default), only the first index key value is returned. If `depth` is 2, both primary and secondary key values are returned. If `depth` is 0, the depth is the number of slash-separators in the `indexPrefix` field, not counting a slash appearing as the last character of the prefix. If the `indexPrefix` field is empty, the default depth is 1. It is an error for `depth` to be any positive value less than the number of components in `indexPrefix`.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "indexPrefix": { // "description": "Restricts the index values returned to be those with a specified prefix for each index key. This field has the form `\"/prefix1/prefix2/...\"`, in order corresponding to the `LogService indexKeys`. Non-empty prefixes must begin with `/`. For example, App Engine's two keys are the module ID and the version ID. Following is the effect of using various values for `indexPrefix`: + `\"/Mod/\"` retrieves `/Mod/10` and `/Mod/11` but not `/ModA/10`. + `\"/Mod` retrieves `/Mod/10`, `/Mod/11` and `/ModA/10` but not `/XXX/33`. + `\"/Mod/1\"` retrieves `/Mod/10` and `/Mod/11` but not `/ModA/10`. + `\"/Mod/10/\"` retrieves `/Mod/10` only. + An empty prefix or `\"/\"` retrieves all values.", // "location": "query", // "type": "string" // }, // "logServicesId": { // "description": "Part of `serviceName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "pageSize": { // "description": "The maximum number of log service index resources to return in one operation.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "An opaque token, returned as `nextPageToken` by a prior `ListLogServiceIndexes` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServiceIndexes` operation is continued.", // "location": "query", // "type": "string" // }, // "projectsId": { // "description": "Part of `serviceName`. The resource name of a log service whose service indexes are requested. Example: `\"projects/my-project-id/logServices/appengine.googleapis.com\"`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/indexes", // "response": { // "$ref": "ListLogServiceIndexesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsLogServicesIndexesListCall) Pages(ctx context.Context, f func(*ListLogServiceIndexesResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "logging.projects.logServices.sinks.create": type ProjectsLogServicesSinksCreateCall struct { s *Service projectsId string logServicesId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a log service sink. All log entries from a specified // log service are written to the destination. func (r *ProjectsLogServicesSinksService) Create(projectsId string, logServicesId string, logsink *LogSink) *ProjectsLogServicesSinksCreateCall { c := &ProjectsLogServicesSinksCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesSinksCreateCall) Fields(s ...googleapi.Field) *ProjectsLogServicesSinksCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesSinksCreateCall) Context(ctx context.Context) *ProjectsLogServicesSinksCreateCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesSinksCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.sinks.create" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogServicesSinksCreateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a log service sink. All log entries from a specified log service are written to the destination.", // "httpMethod": "POST", // "id": "logging.projects.logServices.sinks.create", // "parameterOrder": [ // "projectsId", // "logServicesId" // ], // "parameters": { // "logServicesId": { // "description": "Part of `serviceName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `serviceName`. The resource name of the log service to which the sink is bound.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logServices.sinks.delete": type ProjectsLogServicesSinksDeleteCall struct { s *Service projectsId string logServicesId string sinksId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a log service sink. After deletion, no new log // entries are written to the destination. func (r *ProjectsLogServicesSinksService) Delete(projectsId string, logServicesId string, sinksId string) *ProjectsLogServicesSinksDeleteCall { c := &ProjectsLogServicesSinksDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesSinksDeleteCall) Fields(s ...googleapi.Field) *ProjectsLogServicesSinksDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesSinksDeleteCall) Context(ctx context.Context) *ProjectsLogServicesSinksDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesSinksDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.sinks.delete" call. // Exactly one of *Empty or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Empty.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogServicesSinksDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Empty{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a log service sink. After deletion, no new log entries are written to the destination.", // "httpMethod": "DELETE", // "id": "logging.projects.logServices.sinks.delete", // "parameterOrder": [ // "projectsId", // "logServicesId", // "sinksId" // ], // "parameters": { // "logServicesId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the log service sink to delete.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}", // "response": { // "$ref": "Empty" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logServices.sinks.get": type ProjectsLogServicesSinksGetCall struct { s *Service projectsId string logServicesId string sinksId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets a log service sink. func (r *ProjectsLogServicesSinksService) Get(projectsId string, logServicesId string, sinksId string) *ProjectsLogServicesSinksGetCall { c := &ProjectsLogServicesSinksGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesSinksGetCall) Fields(s ...googleapi.Field) *ProjectsLogServicesSinksGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogServicesSinksGetCall) IfNoneMatch(entityTag string) *ProjectsLogServicesSinksGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesSinksGetCall) Context(ctx context.Context) *ProjectsLogServicesSinksGetCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesSinksGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.sinks.get" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogServicesSinksGetCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets a log service sink.", // "httpMethod": "GET", // "id": "logging.projects.logServices.sinks.get", // "parameterOrder": [ // "projectsId", // "logServicesId", // "sinksId" // ], // "parameters": { // "logServicesId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the log service sink to return.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}", // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.logServices.sinks.list": type ProjectsLogServicesSinksListCall struct { s *Service projectsId string logServicesId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists log service sinks associated with a log service. func (r *ProjectsLogServicesSinksService) List(projectsId string, logServicesId string) *ProjectsLogServicesSinksListCall { c := &ProjectsLogServicesSinksListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesSinksListCall) Fields(s ...googleapi.Field) *ProjectsLogServicesSinksListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogServicesSinksListCall) IfNoneMatch(entityTag string) *ProjectsLogServicesSinksListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesSinksListCall) Context(ctx context.Context) *ProjectsLogServicesSinksListCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesSinksListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.sinks.list" call. // Exactly one of *ListLogServiceSinksResponse or error will be non-nil. // Any non-2xx status code is an error. Response headers are in either // *ListLogServiceSinksResponse.ServerResponse.Header or (if a response // was returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogServicesSinksListCall) Do(opts ...googleapi.CallOption) (*ListLogServiceSinksResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogServiceSinksResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists log service sinks associated with a log service.", // "httpMethod": "GET", // "id": "logging.projects.logServices.sinks.list", // "parameterOrder": [ // "projectsId", // "logServicesId" // ], // "parameters": { // "logServicesId": { // "description": "Part of `serviceName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `serviceName`. The log service whose sinks are wanted.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks", // "response": { // "$ref": "ListLogServiceSinksResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.logServices.sinks.update": type ProjectsLogServicesSinksUpdateCall struct { s *Service projectsId string logServicesId string sinksId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Update: Updates a log service sink. If the sink does not exist, it is // created. func (r *ProjectsLogServicesSinksService) Update(projectsId string, logServicesId string, sinksId string, logsink *LogSink) *ProjectsLogServicesSinksUpdateCall { c := &ProjectsLogServicesSinksUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logServicesId = logServicesId c.sinksId = sinksId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogServicesSinksUpdateCall) Fields(s ...googleapi.Field) *ProjectsLogServicesSinksUpdateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogServicesSinksUpdateCall) Context(ctx context.Context) *ProjectsLogServicesSinksUpdateCall { c.ctx_ = ctx return c } func (c *ProjectsLogServicesSinksUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("PUT", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logServicesId": c.logServicesId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logServices.sinks.update" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogServicesSinksUpdateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Updates a log service sink. If the sink does not exist, it is created.", // "httpMethod": "PUT", // "id": "logging.projects.logServices.sinks.update", // "parameterOrder": [ // "projectsId", // "logServicesId", // "sinksId" // ], // "parameters": { // "logServicesId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the log service sink to update.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logs.delete": type ProjectsLogsDeleteCall struct { s *Service projectsId string logsId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a log and all its log entries. The log will reappear // if it receives new entries. func (r *ProjectsLogsService) Delete(projectsId string, logsId string) *ProjectsLogsDeleteCall { c := &ProjectsLogsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLogsDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsDeleteCall) Context(ctx context.Context) *ProjectsLogsDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsLogsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.delete" call. // Exactly one of *Empty or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Empty.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Empty{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a log and all its log entries. The log will reappear if it receives new entries.", // "httpMethod": "DELETE", // "id": "logging.projects.logs.delete", // "parameterOrder": [ // "projectsId", // "logsId" // ], // "parameters": { // "logsId": { // "description": "Part of `logName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `logName`. The resource name of the log to be deleted.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}", // "response": { // "$ref": "Empty" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logs.list": type ProjectsLogsListCall struct { s *Service projectsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists the logs in the project. Only logs that have entries are // listed. func (r *ProjectsLogsService) List(projectsId string) *ProjectsLogsListCall { c := &ProjectsLogsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId return c } // PageSize sets the optional parameter "pageSize": The maximum number // of results to return. func (c *ProjectsLogsListCall) PageSize(pageSize int64) *ProjectsLogsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": An opaque token, // returned as `nextPageToken` by a prior `ListLogs` operation. If // `pageToken` is supplied, then the other fields of this request are // ignored, and instead the previous `ListLogs` operation is continued. func (c *ProjectsLogsListCall) PageToken(pageToken string) *ProjectsLogsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // ServiceIndexPrefix sets the optional parameter "serviceIndexPrefix": // The purpose of this field is to restrict the listed logs to those // with entries of a certain kind. If `serviceName` is the name of a log // service, then this field may contain values for the log service's // indexes. Only logs that have entries whose indexes include the values // are listed. The format for this field is "/val1/val2.../valN", // where `val1` is a value for the first index, `val2` for the second // index, etc. An empty value (a single slash) for an index matches all // values, and you can omit values for later indexes entirely. func (c *ProjectsLogsListCall) ServiceIndexPrefix(serviceIndexPrefix string) *ProjectsLogsListCall { c.urlParams_.Set("serviceIndexPrefix", serviceIndexPrefix) return c } // ServiceName sets the optional parameter "serviceName": If not empty, // this field must be a log service name such as // "compute.googleapis.com". Only logs associated with that that log // service are listed. func (c *ProjectsLogsListCall) ServiceName(serviceName string) *ProjectsLogsListCall { c.urlParams_.Set("serviceName", serviceName) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsListCall) Fields(s ...googleapi.Field) *ProjectsLogsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogsListCall) IfNoneMatch(entityTag string) *ProjectsLogsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsListCall) Context(ctx context.Context) *ProjectsLogsListCall { c.ctx_ = ctx return c } func (c *ProjectsLogsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.list" call. // Exactly one of *ListLogsResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListLogsResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogsListCall) Do(opts ...googleapi.CallOption) (*ListLogsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists the logs in the project. Only logs that have entries are listed.", // "httpMethod": "GET", // "id": "logging.projects.logs.list", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "pageSize": { // "description": "The maximum number of results to return.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "An opaque token, returned as `nextPageToken` by a prior `ListLogs` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogs` operation is continued.", // "location": "query", // "type": "string" // }, // "projectsId": { // "description": "Part of `projectName`. The resource name of the project whose logs are requested. If both `serviceName` and `serviceIndexPrefix` are empty, then all logs with entries in this project are listed.", // "location": "path", // "required": true, // "type": "string" // }, // "serviceIndexPrefix": { // "description": "The purpose of this field is to restrict the listed logs to those with entries of a certain kind. If `serviceName` is the name of a log service, then this field may contain values for the log service's indexes. Only logs that have entries whose indexes include the values are listed. The format for this field is `\"/val1/val2.../valN\"`, where `val1` is a value for the first index, `val2` for the second index, etc. An empty value (a single slash) for an index matches all values, and you can omit values for later indexes entirely.", // "location": "query", // "type": "string" // }, // "serviceName": { // "description": "If not empty, this field must be a log service name such as `\"compute.googleapis.com\"`. Only logs associated with that that log service are listed.", // "location": "query", // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs", // "response": { // "$ref": "ListLogsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsLogsListCall) Pages(ctx context.Context, f func(*ListLogsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "logging.projects.logs.entries.write": type ProjectsLogsEntriesWriteCall struct { s *Service projectsId string logsId string writelogentriesrequest *WriteLogEntriesRequest urlParams_ gensupport.URLParams ctx_ context.Context } // Write: Writes log entries to Cloud Logging. Each entry consists of a // `LogEntry` object. You must fill in all the fields of the object, // including one of the payload fields. You may supply a map, // `commonLabels`, that holds default (key, value) data for the // `entries[].metadata.labels` map in each entry, saving you the trouble // of creating identical copies for each entry. func (r *ProjectsLogsEntriesService) Write(projectsId string, logsId string, writelogentriesrequest *WriteLogEntriesRequest) *ProjectsLogsEntriesWriteCall { c := &ProjectsLogsEntriesWriteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId c.writelogentriesrequest = writelogentriesrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsEntriesWriteCall) Fields(s ...googleapi.Field) *ProjectsLogsEntriesWriteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsEntriesWriteCall) Context(ctx context.Context) *ProjectsLogsEntriesWriteCall { c.ctx_ = ctx return c } func (c *ProjectsLogsEntriesWriteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.writelogentriesrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/entries:write") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.entries.write" call. // Exactly one of *WriteLogEntriesResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *WriteLogEntriesResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogsEntriesWriteCall) Do(opts ...googleapi.CallOption) (*WriteLogEntriesResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &WriteLogEntriesResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Writes log entries to Cloud Logging. Each entry consists of a `LogEntry` object. You must fill in all the fields of the object, including one of the payload fields. You may supply a map, `commonLabels`, that holds default (key, value) data for the `entries[].metadata.labels` map in each entry, saving you the trouble of creating identical copies for each entry.", // "httpMethod": "POST", // "id": "logging.projects.logs.entries.write", // "parameterOrder": [ // "projectsId", // "logsId" // ], // "parameters": { // "logsId": { // "description": "Part of `logName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `logName`. The resource name of the log that will receive the log entries.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/entries:write", // "request": { // "$ref": "WriteLogEntriesRequest" // }, // "response": { // "$ref": "WriteLogEntriesResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.write" // ] // } } // method id "logging.projects.logs.sinks.create": type ProjectsLogsSinksCreateCall struct { s *Service projectsId string logsId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a log sink. All log entries for a specified log are // written to the destination. func (r *ProjectsLogsSinksService) Create(projectsId string, logsId string, logsink *LogSink) *ProjectsLogsSinksCreateCall { c := &ProjectsLogsSinksCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsSinksCreateCall) Fields(s ...googleapi.Field) *ProjectsLogsSinksCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsSinksCreateCall) Context(ctx context.Context) *ProjectsLogsSinksCreateCall { c.ctx_ = ctx return c } func (c *ProjectsLogsSinksCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.sinks.create" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogsSinksCreateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a log sink. All log entries for a specified log are written to the destination.", // "httpMethod": "POST", // "id": "logging.projects.logs.sinks.create", // "parameterOrder": [ // "projectsId", // "logsId" // ], // "parameters": { // "logsId": { // "description": "Part of `logName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `logName`. The resource name of the log to which to the sink is bound.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/sinks", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logs.sinks.delete": type ProjectsLogsSinksDeleteCall struct { s *Service projectsId string logsId string sinksId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a log sink. After deletion, no new log entries are // written to the destination. func (r *ProjectsLogsSinksService) Delete(projectsId string, logsId string, sinksId string) *ProjectsLogsSinksDeleteCall { c := &ProjectsLogsSinksDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsSinksDeleteCall) Fields(s ...googleapi.Field) *ProjectsLogsSinksDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsSinksDeleteCall) Context(ctx context.Context) *ProjectsLogsSinksDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsLogsSinksDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.sinks.delete" call. // Exactly one of *Empty or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Empty.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogsSinksDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Empty{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a log sink. After deletion, no new log entries are written to the destination.", // "httpMethod": "DELETE", // "id": "logging.projects.logs.sinks.delete", // "parameterOrder": [ // "projectsId", // "logsId", // "sinksId" // ], // "parameters": { // "logsId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the log sink to delete.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}", // "response": { // "$ref": "Empty" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.logs.sinks.get": type ProjectsLogsSinksGetCall struct { s *Service projectsId string logsId string sinksId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets a log sink. func (r *ProjectsLogsSinksService) Get(projectsId string, logsId string, sinksId string) *ProjectsLogsSinksGetCall { c := &ProjectsLogsSinksGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsSinksGetCall) Fields(s ...googleapi.Field) *ProjectsLogsSinksGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogsSinksGetCall) IfNoneMatch(entityTag string) *ProjectsLogsSinksGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsSinksGetCall) Context(ctx context.Context) *ProjectsLogsSinksGetCall { c.ctx_ = ctx return c } func (c *ProjectsLogsSinksGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.sinks.get" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogsSinksGetCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets a log sink.", // "httpMethod": "GET", // "id": "logging.projects.logs.sinks.get", // "parameterOrder": [ // "projectsId", // "logsId", // "sinksId" // ], // "parameters": { // "logsId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the log sink to return.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}", // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.logs.sinks.list": type ProjectsLogsSinksListCall struct { s *Service projectsId string logsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists log sinks associated with a log. func (r *ProjectsLogsSinksService) List(projectsId string, logsId string) *ProjectsLogsSinksListCall { c := &ProjectsLogsSinksListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsSinksListCall) Fields(s ...googleapi.Field) *ProjectsLogsSinksListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLogsSinksListCall) IfNoneMatch(entityTag string) *ProjectsLogsSinksListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsSinksListCall) Context(ctx context.Context) *ProjectsLogsSinksListCall { c.ctx_ = ctx return c } func (c *ProjectsLogsSinksListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.sinks.list" call. // Exactly one of *ListLogSinksResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListLogSinksResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsLogsSinksListCall) Do(opts ...googleapi.CallOption) (*ListLogSinksResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogSinksResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists log sinks associated with a log.", // "httpMethod": "GET", // "id": "logging.projects.logs.sinks.list", // "parameterOrder": [ // "projectsId", // "logsId" // ], // "parameters": { // "logsId": { // "description": "Part of `logName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `logName`. The log whose sinks are wanted. For example, `\"compute.google.com/syslog\"`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/sinks", // "response": { // "$ref": "ListLogSinksResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.logs.sinks.update": type ProjectsLogsSinksUpdateCall struct { s *Service projectsId string logsId string sinksId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Update: Updates a log sink. If the sink does not exist, it is // created. func (r *ProjectsLogsSinksService) Update(projectsId string, logsId string, sinksId string, logsink *LogSink) *ProjectsLogsSinksUpdateCall { c := &ProjectsLogsSinksUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsId = logsId c.sinksId = sinksId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLogsSinksUpdateCall) Fields(s ...googleapi.Field) *ProjectsLogsSinksUpdateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLogsSinksUpdateCall) Context(ctx context.Context) *ProjectsLogsSinksUpdateCall { c.ctx_ = ctx return c } func (c *ProjectsLogsSinksUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("PUT", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "logsId": c.logsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.logs.sinks.update" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsLogsSinksUpdateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Updates a log sink. If the sink does not exist, it is created.", // "httpMethod": "PUT", // "id": "logging.projects.logs.sinks.update", // "parameterOrder": [ // "projectsId", // "logsId", // "sinksId" // ], // "parameters": { // "logsId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `sinkName`. The resource name of the sink to update.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.metrics.create": type ProjectsMetricsCreateCall struct { s *Service projectsId string logmetric *LogMetric urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a logs-based metric. func (r *ProjectsMetricsService) Create(projectsId string, logmetric *LogMetric) *ProjectsMetricsCreateCall { c := &ProjectsMetricsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logmetric = logmetric return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsMetricsCreateCall) Fields(s ...googleapi.Field) *ProjectsMetricsCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsMetricsCreateCall) Context(ctx context.Context) *ProjectsMetricsCreateCall { c.ctx_ = ctx return c } func (c *ProjectsMetricsCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logmetric) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/metrics") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.metrics.create" call. // Exactly one of *LogMetric or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *LogMetric.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsMetricsCreateCall) Do(opts ...googleapi.CallOption) (*LogMetric, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogMetric{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a logs-based metric.", // "httpMethod": "POST", // "id": "logging.projects.metrics.create", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "projectsId": { // "description": "Part of `projectName`. The resource name of the project in which to create the metric.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/metrics", // "request": { // "$ref": "LogMetric" // }, // "response": { // "$ref": "LogMetric" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.write" // ] // } } // method id "logging.projects.metrics.delete": type ProjectsMetricsDeleteCall struct { s *Service projectsId string metricsId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a logs-based metric. func (r *ProjectsMetricsService) Delete(projectsId string, metricsId string) *ProjectsMetricsDeleteCall { c := &ProjectsMetricsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.metricsId = metricsId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsMetricsDeleteCall) Fields(s ...googleapi.Field) *ProjectsMetricsDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsMetricsDeleteCall) Context(ctx context.Context) *ProjectsMetricsDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsMetricsDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/metrics/{metricsId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "metricsId": c.metricsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.metrics.delete" call. // Exactly one of *Empty or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Empty.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsMetricsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Empty{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a logs-based metric.", // "httpMethod": "DELETE", // "id": "logging.projects.metrics.delete", // "parameterOrder": [ // "projectsId", // "metricsId" // ], // "parameters": { // "metricsId": { // "description": "Part of `metricName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `metricName`. The resource name of the metric to delete.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/metrics/{metricsId}", // "response": { // "$ref": "Empty" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.write" // ] // } } // method id "logging.projects.metrics.get": type ProjectsMetricsGetCall struct { s *Service projectsId string metricsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets a logs-based metric. func (r *ProjectsMetricsService) Get(projectsId string, metricsId string) *ProjectsMetricsGetCall { c := &ProjectsMetricsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.metricsId = metricsId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsMetricsGetCall) Fields(s ...googleapi.Field) *ProjectsMetricsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsMetricsGetCall) IfNoneMatch(entityTag string) *ProjectsMetricsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsMetricsGetCall) Context(ctx context.Context) *ProjectsMetricsGetCall { c.ctx_ = ctx return c } func (c *ProjectsMetricsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/metrics/{metricsId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "metricsId": c.metricsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.metrics.get" call. // Exactly one of *LogMetric or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *LogMetric.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsMetricsGetCall) Do(opts ...googleapi.CallOption) (*LogMetric, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogMetric{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets a logs-based metric.", // "httpMethod": "GET", // "id": "logging.projects.metrics.get", // "parameterOrder": [ // "projectsId", // "metricsId" // ], // "parameters": { // "metricsId": { // "description": "Part of `metricName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `metricName`. The resource name of the desired metric.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/metrics/{metricsId}", // "response": { // "$ref": "LogMetric" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.metrics.list": type ProjectsMetricsListCall struct { s *Service projectsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists the logs-based metrics associated with a project. func (r *ProjectsMetricsService) List(projectsId string) *ProjectsMetricsListCall { c := &ProjectsMetricsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId return c } // PageSize sets the optional parameter "pageSize": The maximum number // of `LogMetric` objects to return in one operation. func (c *ProjectsMetricsListCall) PageSize(pageSize int64) *ProjectsMetricsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": An opaque token, // returned as `nextPageToken` by a prior `ListLogMetrics` operation. If // `pageToken` is supplied, then the other fields of this request are // ignored, and instead the previous `ListLogMetrics` operation is // continued. func (c *ProjectsMetricsListCall) PageToken(pageToken string) *ProjectsMetricsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsMetricsListCall) Fields(s ...googleapi.Field) *ProjectsMetricsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsMetricsListCall) IfNoneMatch(entityTag string) *ProjectsMetricsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsMetricsListCall) Context(ctx context.Context) *ProjectsMetricsListCall { c.ctx_ = ctx return c } func (c *ProjectsMetricsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/metrics") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.metrics.list" call. // Exactly one of *ListLogMetricsResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListLogMetricsResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsMetricsListCall) Do(opts ...googleapi.CallOption) (*ListLogMetricsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListLogMetricsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists the logs-based metrics associated with a project.", // "httpMethod": "GET", // "id": "logging.projects.metrics.list", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "pageSize": { // "description": "The maximum number of `LogMetric` objects to return in one operation.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "An opaque token, returned as `nextPageToken` by a prior `ListLogMetrics` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogMetrics` operation is continued.", // "location": "query", // "type": "string" // }, // "projectsId": { // "description": "Part of `projectName`. The resource name for the project whose metrics are wanted.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/metrics", // "response": { // "$ref": "ListLogMetricsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsMetricsListCall) Pages(ctx context.Context, f func(*ListLogMetricsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "logging.projects.metrics.update": type ProjectsMetricsUpdateCall struct { s *Service projectsId string metricsId string logmetric *LogMetric urlParams_ gensupport.URLParams ctx_ context.Context } // Update: Creates or updates a logs-based metric. func (r *ProjectsMetricsService) Update(projectsId string, metricsId string, logmetric *LogMetric) *ProjectsMetricsUpdateCall { c := &ProjectsMetricsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.metricsId = metricsId c.logmetric = logmetric return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsMetricsUpdateCall) Fields(s ...googleapi.Field) *ProjectsMetricsUpdateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsMetricsUpdateCall) Context(ctx context.Context) *ProjectsMetricsUpdateCall { c.ctx_ = ctx return c } func (c *ProjectsMetricsUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logmetric) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/metrics/{metricsId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("PUT", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "metricsId": c.metricsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.metrics.update" call. // Exactly one of *LogMetric or error will be non-nil. Any non-2xx // status code is an error. Response headers are in either // *LogMetric.ServerResponse.Header or (if a response was returned at // all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified // to check whether the returned error was because // http.StatusNotModified was returned. func (c *ProjectsMetricsUpdateCall) Do(opts ...googleapi.CallOption) (*LogMetric, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogMetric{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates or updates a logs-based metric.", // "httpMethod": "PUT", // "id": "logging.projects.metrics.update", // "parameterOrder": [ // "projectsId", // "metricsId" // ], // "parameters": { // "metricsId": { // "description": "Part of `metricName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // }, // "projectsId": { // "description": "Part of `metricName`. The resource name of the metric to update.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/metrics/{metricsId}", // "request": { // "$ref": "LogMetric" // }, // "response": { // "$ref": "LogMetric" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.write" // ] // } } // method id "logging.projects.sinks.create": type ProjectsSinksCreateCall struct { s *Service projectsId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Create: Creates a project sink. A logs filter determines which log // entries are written to the destination. func (r *ProjectsSinksService) Create(projectsId string, logsink *LogSink) *ProjectsSinksCreateCall { c := &ProjectsSinksCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsSinksCreateCall) Fields(s ...googleapi.Field) *ProjectsSinksCreateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsSinksCreateCall) Context(ctx context.Context) *ProjectsSinksCreateCall { c.ctx_ = ctx return c } func (c *ProjectsSinksCreateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("POST", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.sinks.create" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsSinksCreateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Creates a project sink. A logs filter determines which log entries are written to the destination.", // "httpMethod": "POST", // "id": "logging.projects.sinks.create", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "projectsId": { // "description": "Part of `projectName`. The resource name of the project to which the sink is bound.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/sinks", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.sinks.delete": type ProjectsSinksDeleteCall struct { s *Service projectsId string sinksId string urlParams_ gensupport.URLParams ctx_ context.Context } // Delete: Deletes a project sink. After deletion, no new log entries // are written to the destination. func (r *ProjectsSinksService) Delete(projectsId string, sinksId string) *ProjectsSinksDeleteCall { c := &ProjectsSinksDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsSinksDeleteCall) Fields(s ...googleapi.Field) *ProjectsSinksDeleteCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsSinksDeleteCall) Context(ctx context.Context) *ProjectsSinksDeleteCall { c.ctx_ = ctx return c } func (c *ProjectsSinksDeleteCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("DELETE", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.sinks.delete" call. // Exactly one of *Empty or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *Empty.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsSinksDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &Empty{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Deletes a project sink. After deletion, no new log entries are written to the destination.", // "httpMethod": "DELETE", // "id": "logging.projects.sinks.delete", // "parameterOrder": [ // "projectsId", // "sinksId" // ], // "parameters": { // "projectsId": { // "description": "Part of `sinkName`. The resource name of the project sink to delete.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/sinks/{sinksId}", // "response": { // "$ref": "Empty" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } } // method id "logging.projects.sinks.get": type ProjectsSinksGetCall struct { s *Service projectsId string sinksId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // Get: Gets a project sink. func (r *ProjectsSinksService) Get(projectsId string, sinksId string) *ProjectsSinksGetCall { c := &ProjectsSinksGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.sinksId = sinksId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsSinksGetCall) Fields(s ...googleapi.Field) *ProjectsSinksGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsSinksGetCall) IfNoneMatch(entityTag string) *ProjectsSinksGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsSinksGetCall) Context(ctx context.Context) *ProjectsSinksGetCall { c.ctx_ = ctx return c } func (c *ProjectsSinksGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.sinks.get" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsSinksGetCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Gets a project sink.", // "httpMethod": "GET", // "id": "logging.projects.sinks.get", // "parameterOrder": [ // "projectsId", // "sinksId" // ], // "parameters": { // "projectsId": { // "description": "Part of `sinkName`. The resource name of the project sink to return.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/sinks/{sinksId}", // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.sinks.list": type ProjectsSinksListCall struct { s *Service projectsId string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context } // List: Lists project sinks associated with a project. func (r *ProjectsSinksService) List(projectsId string) *ProjectsSinksListCall { c := &ProjectsSinksListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsSinksListCall) Fields(s ...googleapi.Field) *ProjectsSinksListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsSinksListCall) IfNoneMatch(entityTag string) *ProjectsSinksListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsSinksListCall) Context(ctx context.Context) *ProjectsSinksListCall { c.ctx_ = ctx return c } func (c *ProjectsSinksListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/sinks") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("GET", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.sinks.list" call. // Exactly one of *ListSinksResponse or error will be non-nil. Any // non-2xx status code is an error. Response headers are in either // *ListSinksResponse.ServerResponse.Header or (if a response was // returned at all) in error.(*googleapi.Error).Header. Use // googleapi.IsNotModified to check whether the returned error was // because http.StatusNotModified was returned. func (c *ProjectsSinksListCall) Do(opts ...googleapi.CallOption) (*ListSinksResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &ListSinksResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Lists project sinks associated with a project.", // "httpMethod": "GET", // "id": "logging.projects.sinks.list", // "parameterOrder": [ // "projectsId" // ], // "parameters": { // "projectsId": { // "description": "Part of `projectName`. The project whose sinks are wanted.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/sinks", // "response": { // "$ref": "ListSinksResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/cloud-platform.read-only", // "https://www.googleapis.com/auth/logging.admin", // "https://www.googleapis.com/auth/logging.read" // ] // } } // method id "logging.projects.sinks.update": type ProjectsSinksUpdateCall struct { s *Service projectsId string sinksId string logsink *LogSink urlParams_ gensupport.URLParams ctx_ context.Context } // Update: Updates a project sink. If the sink does not exist, it is // created. The destination, filter, or both may be updated. func (r *ProjectsSinksService) Update(projectsId string, sinksId string, logsink *LogSink) *ProjectsSinksUpdateCall { c := &ProjectsSinksUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.projectsId = projectsId c.sinksId = sinksId c.logsink = logsink return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsSinksUpdateCall) Fields(s ...googleapi.Field) *ProjectsSinksUpdateCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsSinksUpdateCall) Context(ctx context.Context) *ProjectsSinksUpdateCall { c.ctx_ = ctx return c } func (c *ProjectsSinksUpdateCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.logsink) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta3/projects/{projectsId}/sinks/{sinksId}") urls += "?" + c.urlParams_.Encode() req, _ := http.NewRequest("PUT", urls, body) req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "projectsId": c.projectsId, "sinksId": c.sinksId, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "logging.projects.sinks.update" call. // Exactly one of *LogSink or error will be non-nil. Any non-2xx status // code is an error. Response headers are in either // *LogSink.ServerResponse.Header or (if a response was returned at all) // in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to // check whether the returned error was because http.StatusNotModified // was returned. func (c *ProjectsSinksUpdateCall) Do(opts ...googleapi.CallOption) (*LogSink, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &LogSink{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := json.NewDecoder(res.Body).Decode(target); err != nil { return nil, err } return ret, nil // { // "description": "Updates a project sink. If the sink does not exist, it is created. The destination, filter, or both may be updated.", // "httpMethod": "PUT", // "id": "logging.projects.sinks.update", // "parameterOrder": [ // "projectsId", // "sinksId" // ], // "parameters": { // "projectsId": { // "description": "Part of `sinkName`. The resource name of the project sink to update.", // "location": "path", // "required": true, // "type": "string" // }, // "sinksId": { // "description": "Part of `sinkName`. See documentation of `projectsId`.", // "location": "path", // "required": true, // "type": "string" // } // }, // "path": "v1beta3/projects/{projectsId}/sinks/{sinksId}", // "request": { // "$ref": "LogSink" // }, // "response": { // "$ref": "LogSink" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform", // "https://www.googleapis.com/auth/logging.admin" // ] // } }
apache-2.0
socaa/kubernetes
pkg/registry/thirdpartyresourcedata/codec_test.go
5038
/* Copyright 2015 The Kubernetes 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. */ package thirdpartyresourcedata import ( "encoding/json" "reflect" "testing" "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" "k8s.io/kubernetes/pkg/apis/experimental" "k8s.io/kubernetes/pkg/runtime" ) type Foo struct { unversioned.TypeMeta `json:",inline"` api.ObjectMeta `json:"metadata,omitempty" description:"standard object metadata"` SomeField string `json:"someField"` OtherField int `json:"otherField"` } type FooList struct { unversioned.TypeMeta `json:",inline"` unversioned.ListMeta `json:"metadata,omitempty" description:"standard list metadata; see http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata"` items []Foo `json:"items"` } func TestCodec(t *testing.T) { tests := []struct { obj *Foo expectErr bool name string }{ { obj: &Foo{ObjectMeta: api.ObjectMeta{Name: "bar"}}, expectErr: true, name: "missing kind", }, { obj: &Foo{ObjectMeta: api.ObjectMeta{Name: "bar"}, TypeMeta: unversioned.TypeMeta{Kind: "Foo"}}, name: "basic", }, { obj: &Foo{ObjectMeta: api.ObjectMeta{Name: "bar", ResourceVersion: "baz"}, TypeMeta: unversioned.TypeMeta{Kind: "Foo"}}, name: "resource version", }, { obj: &Foo{ ObjectMeta: api.ObjectMeta{ Name: "bar", CreationTimestamp: unversioned.Time{time.Unix(100, 0)}, }, TypeMeta: unversioned.TypeMeta{Kind: "Foo"}, }, name: "creation time", }, { obj: &Foo{ ObjectMeta: api.ObjectMeta{ Name: "bar", ResourceVersion: "baz", Labels: map[string]string{"foo": "bar", "baz": "blah"}, }, TypeMeta: unversioned.TypeMeta{Kind: "Foo"}, }, name: "labels", }, } for _, test := range tests { codec := thirdPartyResourceDataCodec{kind: "Foo"} data, err := json.Marshal(test.obj) if err != nil { t.Errorf("[%s] unexpected error: %v", test.name, err) continue } obj, err := codec.Decode(data) if err != nil && !test.expectErr { t.Errorf("[%s] unexpected error: %v", test.name, err) continue } if test.expectErr { if err == nil { t.Errorf("[%s] unexpected non-error", test.name) } continue } rsrcObj, ok := obj.(*experimental.ThirdPartyResourceData) if !ok { t.Errorf("[%s] unexpected object: %v", test.name, obj) continue } if !reflect.DeepEqual(rsrcObj.ObjectMeta, test.obj.ObjectMeta) { t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, rsrcObj.ObjectMeta, test.obj.ObjectMeta) } var output Foo if err := json.Unmarshal(rsrcObj.Data, &output); err != nil { t.Errorf("[%s] unexpected error: %v", test.name, err) continue } if !reflect.DeepEqual(&output, test.obj) { t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, test.obj, &output) } data, err = codec.Encode(rsrcObj) if err != nil { t.Errorf("[%s] unexpected error: %v", test.name, err) } var output2 Foo if err := json.Unmarshal(data, &output2); err != nil { t.Errorf("[%s] unexpected error: %v", test.name, err) continue } if !reflect.DeepEqual(&output2, test.obj) { t.Errorf("[%s]\nexpected\n%v\nsaw\n%v\n", test.name, test.obj, &output2) } } } func TestCreater(t *testing.T) { creater := NewObjectCreator("creater version", api.Scheme) tests := []struct { name string version string kind string expectedObj runtime.Object expectErr bool }{ { name: "valid ThirdPartyResourceData creation", version: "creater version", kind: "ThirdPartyResourceData", expectedObj: &experimental.ThirdPartyResourceData{}, expectErr: false, }, { name: "invalid ThirdPartyResourceData creation", version: "invalid version", kind: "ThirdPartyResourceData", expectedObj: nil, expectErr: true, }, { name: "valid ListOptions creation", version: "v1", kind: "ListOptions", expectedObj: &v1.ListOptions{}, expectErr: false, }, } for _, test := range tests { out, err := creater.New(test.version, test.kind) if err != nil && !test.expectErr { t.Errorf("[%s] unexpected error: %v", test.name, err) } if err == nil && test.expectErr { t.Errorf("[%s] unexpected non-error", test.name) } if !reflect.DeepEqual(test.expectedObj, out) { t.Errorf("[%s] unexpected error: expect: %v, got: %v", test.expectedObj, out) } } }
apache-2.0
aaronzirbes/incubator-groovy
src/main/org/codehaus/groovy/ast/stmt/ReturnStatement.java
2280
/* * 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.codehaus.groovy.ast.stmt; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; /** * A return statement * * @author <a href="mailto:[email protected]">James Strachan</a> */ public class ReturnStatement extends Statement { /** * Only used for synthetic return statements emitted by the compiler. * For comparisons use isReturningNullOrVoid() instead. */ public static final ReturnStatement RETURN_NULL_OR_VOID = new ReturnStatement(ConstantExpression.NULL); private Expression expression; public ReturnStatement(ExpressionStatement statement) { this(statement.getExpression()); setStatementLabel(statement.getStatementLabel()); } public ReturnStatement(Expression expression) { this.expression = expression; } public void visit(GroovyCodeVisitor visitor) { visitor.visitReturnStatement(this); } public Expression getExpression() { return expression; } public String getText() { return "return " + expression.getText(); } public void setExpression(Expression expression) { this.expression = expression; } public boolean isReturningNullOrVoid() { return expression instanceof ConstantExpression && ((ConstantExpression)expression).isNullExpression(); } }
apache-2.0
Helena-High/school-app
node_modules/react-native/ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java
4366
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.views.scroll; import javax.annotation.Nullable; import android.graphics.Color; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.views.view.ReactClippingViewGroupHelper; /** * View manager for {@link ReactHorizontalScrollView} components. * * <p>Note that {@link ReactScrollView} and {@link ReactHorizontalScrollView} are exposed to JS * as a single ScrollView component, configured via the {@code horizontal} boolean property. */ public class ReactHorizontalScrollViewManager extends ViewGroupManager<ReactHorizontalScrollView> implements ReactScrollViewCommandHelper.ScrollCommandHandler<ReactHorizontalScrollView> { private static final String REACT_CLASS = "AndroidHorizontalScrollView"; private @Nullable FpsListener mFpsListener = null; public ReactHorizontalScrollViewManager() { this(null); } public ReactHorizontalScrollViewManager(@Nullable FpsListener fpsListener) { mFpsListener = fpsListener; } @Override public String getName() { return REACT_CLASS; } @Override public ReactHorizontalScrollView createViewInstance(ThemedReactContext context) { return new ReactHorizontalScrollView(context, mFpsListener); } @ReactProp(name = "scrollEnabled", defaultBoolean = true) public void setScrollEnabled(ReactHorizontalScrollView view, boolean value) { view.setScrollEnabled(value); } @ReactProp(name = "showsHorizontalScrollIndicator") public void setShowsHorizontalScrollIndicator(ReactHorizontalScrollView view, boolean value) { view.setHorizontalScrollBarEnabled(value); } @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) public void setRemoveClippedSubviews(ReactHorizontalScrollView view, boolean removeClippedSubviews) { view.setRemoveClippedSubviews(removeClippedSubviews); } /** * Computing momentum events is potentially expensive since we post a runnable on the UI thread * to see when it is done. We only do that if {@param sendMomentumEvents} is set to true. This * is handled automatically in js by checking if there is a listener on the momentum events. * * @param view * @param sendMomentumEvents */ @ReactProp(name = "sendMomentumEvents") public void setSendMomentumEvents(ReactHorizontalScrollView view, boolean sendMomentumEvents) { view.setSendMomentumEvents(sendMomentumEvents); } /** * Tag used for logging scroll performance on this scroll view. Will force momentum events to be * turned on (see setSendMomentumEvents). * * @param view * @param scrollPerfTag */ @ReactProp(name = "scrollPerfTag") public void setScrollPerfTag(ReactHorizontalScrollView view, String scrollPerfTag) { view.setScrollPerfTag(scrollPerfTag); } @ReactProp(name = "pagingEnabled") public void setPagingEnabled(ReactHorizontalScrollView view, boolean pagingEnabled) { view.setPagingEnabled(pagingEnabled); } @Override public void receiveCommand( ReactHorizontalScrollView scrollView, int commandId, @Nullable ReadableArray args) { ReactScrollViewCommandHelper.receiveCommand(this, scrollView, commandId, args); } @Override public void scrollTo( ReactHorizontalScrollView scrollView, ReactScrollViewCommandHelper.ScrollToCommandData data) { if (data.mAnimated) { scrollView.smoothScrollTo(data.mDestX, data.mDestY); } else { scrollView.scrollTo(data.mDestX, data.mDestY); } } /** * When set, fills the rest of the scrollview with a color to avoid setting a background and * creating unnecessary overdraw. * @param view * @param color */ @ReactProp(name = "endFillColor", defaultInt = Color.TRANSPARENT, customType = "Color") public void setBottomFillColor(ReactHorizontalScrollView view, int color) { view.setEndFillColor(color); } }
apache-2.0
ryanrhymes/openblas
lib/OpenBLAS-0.2.19/lapack-netlib/TESTING/MATGEN/dlaror.f
9092
*> \brief \b DLAROR * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE DLAROR( SIDE, INIT, M, N, A, LDA, ISEED, X, INFO ) * * .. Scalar Arguments .. * CHARACTER INIT, SIDE * INTEGER INFO, LDA, M, N * .. * .. Array Arguments .. * INTEGER ISEED( 4 ) * DOUBLE PRECISION A( LDA, * ), X( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> DLAROR pre- or post-multiplies an M by N matrix A by a random *> orthogonal matrix U, overwriting A. A may optionally be initialized *> to the identity matrix before multiplying by U. U is generated using *> the method of G.W. Stewart (SIAM J. Numer. Anal. 17, 1980, 403-409). *> \endverbatim * * Arguments: * ========== * *> \param[in] SIDE *> \verbatim *> SIDE is CHARACTER*1 *> Specifies whether A is multiplied on the left or right by U. *> = 'L': Multiply A on the left (premultiply) by U *> = 'R': Multiply A on the right (postmultiply) by U' *> = 'C' or 'T': Multiply A on the left by U and the right *> by U' (Here, U' means U-transpose.) *> \endverbatim *> *> \param[in] INIT *> \verbatim *> INIT is CHARACTER*1 *> Specifies whether or not A should be initialized to the *> identity matrix. *> = 'I': Initialize A to (a section of) the identity matrix *> before applying U. *> = 'N': No initialization. Apply U to the input matrix A. *> *> INIT = 'I' may be used to generate square or rectangular *> orthogonal matrices: *> *> For M = N and SIDE = 'L' or 'R', the rows will be orthogonal *> to each other, as will the columns. *> *> If M < N, SIDE = 'R' produces a dense matrix whose rows are *> orthogonal and whose columns are not, while SIDE = 'L' *> produces a matrix whose rows are orthogonal, and whose first *> M columns are orthogonal, and whose remaining columns are *> zero. *> *> If M > N, SIDE = 'L' produces a dense matrix whose columns *> are orthogonal and whose rows are not, while SIDE = 'R' *> produces a matrix whose columns are orthogonal, and whose *> first M rows are orthogonal, and whose remaining rows are *> zero. *> \endverbatim *> *> \param[in] M *> \verbatim *> M is INTEGER *> The number of rows of A. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of columns of A. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is DOUBLE PRECISION array, dimension (LDA, N) *> On entry, the array A. *> On exit, overwritten by U A ( if SIDE = 'L' ), *> or by A U ( if SIDE = 'R' ), *> or by U A U' ( if SIDE = 'C' or 'T'). *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,M). *> \endverbatim *> *> \param[in,out] ISEED *> \verbatim *> ISEED is INTEGER array, dimension (4) *> On entry ISEED specifies the seed of the random number *> generator. The array elements should be between 0 and 4095; *> if not they will be reduced mod 4096. Also, ISEED(4) must *> be odd. The random number generator uses a linear *> congruential sequence limited to small integers, and so *> should produce machine independent random numbers. The *> values of ISEED are changed on exit, and can be used in the *> next call to DLAROR to continue the same random number *> sequence. *> \endverbatim *> *> \param[out] X *> \verbatim *> X is DOUBLE PRECISION array, dimension (3*MAX( M, N )) *> Workspace of length *> 2*M + N if SIDE = 'L', *> 2*N + M if SIDE = 'R', *> 3*N if SIDE = 'C' or 'T'. *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> An error flag. It is set to: *> = 0: normal return *> < 0: if INFO = -k, the k-th argument had an illegal value *> = 1: if the random numbers generated by DLARND are bad. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup double_matgen * * ===================================================================== SUBROUTINE DLAROR( SIDE, INIT, M, N, A, LDA, ISEED, X, INFO ) * * -- LAPACK auxiliary routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER INIT, SIDE INTEGER INFO, LDA, M, N * .. * .. Array Arguments .. INTEGER ISEED( 4 ) DOUBLE PRECISION A( LDA, * ), X( * ) * .. * * ===================================================================== * * .. Parameters .. DOUBLE PRECISION ZERO, ONE, TOOSML PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0, $ TOOSML = 1.0D-20 ) * .. * .. Local Scalars .. INTEGER IROW, ITYPE, IXFRM, J, JCOL, KBEG, NXFRM DOUBLE PRECISION FACTOR, XNORM, XNORMS * .. * .. External Functions .. LOGICAL LSAME DOUBLE PRECISION DLARND, DNRM2 EXTERNAL LSAME, DLARND, DNRM2 * .. * .. External Subroutines .. EXTERNAL DGEMV, DGER, DLASET, DSCAL, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC ABS, SIGN * .. * .. Executable Statements .. * INFO = 0 IF( N.EQ.0 .OR. M.EQ.0 ) $ RETURN * ITYPE = 0 IF( LSAME( SIDE, 'L' ) ) THEN ITYPE = 1 ELSE IF( LSAME( SIDE, 'R' ) ) THEN ITYPE = 2 ELSE IF( LSAME( SIDE, 'C' ) .OR. LSAME( SIDE, 'T' ) ) THEN ITYPE = 3 END IF * * Check for argument errors. * IF( ITYPE.EQ.0 ) THEN INFO = -1 ELSE IF( M.LT.0 ) THEN INFO = -3 ELSE IF( N.LT.0 .OR. ( ITYPE.EQ.3 .AND. N.NE.M ) ) THEN INFO = -4 ELSE IF( LDA.LT.M ) THEN INFO = -6 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'DLAROR', -INFO ) RETURN END IF * IF( ITYPE.EQ.1 ) THEN NXFRM = M ELSE NXFRM = N END IF * * Initialize A to the identity matrix if desired * IF( LSAME( INIT, 'I' ) ) $ CALL DLASET( 'Full', M, N, ZERO, ONE, A, LDA ) * * If no rotation possible, multiply by random +/-1 * * Compute rotation by computing Householder transformations * H(2), H(3), ..., H(nhouse) * DO 10 J = 1, NXFRM X( J ) = ZERO 10 CONTINUE * DO 30 IXFRM = 2, NXFRM KBEG = NXFRM - IXFRM + 1 * * Generate independent normal( 0, 1 ) random numbers * DO 20 J = KBEG, NXFRM X( J ) = DLARND( 3, ISEED ) 20 CONTINUE * * Generate a Householder transformation from the random vector X * XNORM = DNRM2( IXFRM, X( KBEG ), 1 ) XNORMS = SIGN( XNORM, X( KBEG ) ) X( KBEG+NXFRM ) = SIGN( ONE, -X( KBEG ) ) FACTOR = XNORMS*( XNORMS+X( KBEG ) ) IF( ABS( FACTOR ).LT.TOOSML ) THEN INFO = 1 CALL XERBLA( 'DLAROR', INFO ) RETURN ELSE FACTOR = ONE / FACTOR END IF X( KBEG ) = X( KBEG ) + XNORMS * * Apply Householder transformation to A * IF( ITYPE.EQ.1 .OR. ITYPE.EQ.3 ) THEN * * Apply H(k) from the left. * CALL DGEMV( 'T', IXFRM, N, ONE, A( KBEG, 1 ), LDA, $ X( KBEG ), 1, ZERO, X( 2*NXFRM+1 ), 1 ) CALL DGER( IXFRM, N, -FACTOR, X( KBEG ), 1, X( 2*NXFRM+1 ), $ 1, A( KBEG, 1 ), LDA ) * END IF * IF( ITYPE.EQ.2 .OR. ITYPE.EQ.3 ) THEN * * Apply H(k) from the right. * CALL DGEMV( 'N', M, IXFRM, ONE, A( 1, KBEG ), LDA, $ X( KBEG ), 1, ZERO, X( 2*NXFRM+1 ), 1 ) CALL DGER( M, IXFRM, -FACTOR, X( 2*NXFRM+1 ), 1, X( KBEG ), $ 1, A( 1, KBEG ), LDA ) * END IF 30 CONTINUE * X( 2*NXFRM ) = SIGN( ONE, DLARND( 3, ISEED ) ) * * Scale the matrix A by D. * IF( ITYPE.EQ.1 .OR. ITYPE.EQ.3 ) THEN DO 40 IROW = 1, M CALL DSCAL( N, X( NXFRM+IROW ), A( IROW, 1 ), LDA ) 40 CONTINUE END IF * IF( ITYPE.EQ.2 .OR. ITYPE.EQ.3 ) THEN DO 50 JCOL = 1, N CALL DSCAL( M, X( NXFRM+JCOL ), A( 1, JCOL ), 1 ) 50 CONTINUE END IF RETURN * * End of DLAROR * END
bsd-3-clause
zcbenz/cefode-chromium
third_party/mesa/MesaLib/src/gallium/drivers/i965/brw_draw.c
7116
/************************************************************************** * * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas. * All Rights Reserved. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 "util/u_inlines.h" #include "util/u_prim.h" #include "util/u_upload_mgr.h" #include "brw_draw.h" #include "brw_defines.h" #include "brw_context.h" #include "brw_state.h" #include "brw_debug.h" #include "brw_batchbuffer.h" static uint32_t prim_to_hw_prim[PIPE_PRIM_POLYGON+1] = { _3DPRIM_POINTLIST, _3DPRIM_LINELIST, _3DPRIM_LINELOOP, _3DPRIM_LINESTRIP, _3DPRIM_TRILIST, _3DPRIM_TRISTRIP, _3DPRIM_TRIFAN, _3DPRIM_QUADLIST, _3DPRIM_QUADSTRIP, _3DPRIM_POLYGON }; /* When the primitive changes, set a state bit and re-validate. Not * the nicest and would rather deal with this by having all the * programs be immune to the active primitive (ie. cope with all * possibilities). That may not be realistic however. */ static int brw_set_prim(struct brw_context *brw, unsigned prim ) { if (BRW_DEBUG & DEBUG_PRIMS) debug_printf("PRIM: %s\n", u_prim_name(prim)); if (prim != brw->primitive) { unsigned reduced_prim; brw->primitive = prim; brw->state.dirty.brw |= BRW_NEW_PRIMITIVE; reduced_prim = u_reduced_prim(prim); if (reduced_prim != brw->reduced_primitive) { brw->reduced_primitive = reduced_prim; brw->state.dirty.brw |= BRW_NEW_REDUCED_PRIMITIVE; } } return prim_to_hw_prim[prim]; } static int brw_emit_prim(struct brw_context *brw, unsigned start, unsigned count, boolean indexed, uint32_t hw_prim) { struct brw_3d_primitive prim_packet; int ret; if (BRW_DEBUG & DEBUG_PRIMS) debug_printf("%s start %d count %d indexed %d hw_prim %d\n", __FUNCTION__, start, count, indexed, hw_prim); prim_packet.header.opcode = CMD_3D_PRIM; prim_packet.header.length = sizeof(prim_packet)/4 - 2; prim_packet.header.pad = 0; prim_packet.header.topology = hw_prim; prim_packet.header.indexed = indexed; prim_packet.verts_per_instance = count; prim_packet.start_vert_location = start; if (indexed) prim_packet.start_vert_location += brw->ib.start_vertex_offset; prim_packet.instance_count = 1; prim_packet.start_instance_location = 0; prim_packet.base_vert_location = 0; /* prim->basevertex; XXX: add this to gallium */ /* If we're set to always flush, do it before and after the primitive emit. * We want to catch both missed flushes that hurt instruction/state cache * and missed flushes of the render cache as it heads to other parts of * the besides the draw code. */ if (0) { BEGIN_BATCH(1, IGNORE_CLIPRECTS); OUT_BATCH((CMD_MI_FLUSH << 16) | BRW_FLUSH_STATE_CACHE); ADVANCE_BATCH(); } if (prim_packet.verts_per_instance) { ret = brw_batchbuffer_data( brw->batch, &prim_packet, sizeof(prim_packet), LOOP_CLIPRECTS); if (ret) return ret; } if (0) { BEGIN_BATCH(1, IGNORE_CLIPRECTS); OUT_BATCH((CMD_MI_FLUSH << 16) | BRW_FLUSH_STATE_CACHE); ADVANCE_BATCH(); } return 0; } /* May fail if out of video memory for texture or vbo upload, or on * fallback conditions. */ static int try_draw_range_elements(struct brw_context *brw, boolean indexed, unsigned hw_prim, unsigned start, unsigned count) { int ret; ret = brw_validate_state(brw); if (ret) return ret; /* Check that we can fit our state in with our existing batchbuffer, or * flush otherwise. */ ret = brw->sws->check_aperture_space(brw->sws, brw->state.validated_bos, brw->state.validated_bo_count); if (ret) return ret; ret = brw_upload_state(brw); if (ret) return ret; ret = brw_emit_prim(brw, start, count, indexed, hw_prim); if (ret) return ret; if (brw->flags.always_flush_batch) brw_context_flush( brw ); return 0; } static void brw_draw_vbo(struct pipe_context *pipe, const struct pipe_draw_info *info) { struct brw_context *brw = brw_context(pipe); int ret; uint32_t hw_prim; hw_prim = brw_set_prim(brw, info->mode); if (BRW_DEBUG & DEBUG_PRIMS) debug_printf("PRIM: %s start %d count %d index_buffer %p\n", u_prim_name(info->mode), info->start, info->count, (void *) brw->curr.index_buffer); assert(info->index_bias == 0); /* Potentially trigger upload of new index buffer range. * XXX: do we really care? */ if (brw->curr.min_index != info->min_index || brw->curr.max_index != info->max_index) { brw->curr.min_index = info->min_index; brw->curr.max_index = info->max_index; brw->state.dirty.mesa |= PIPE_NEW_INDEX_RANGE; } /* Make a first attempt at drawing: */ ret = try_draw_range_elements(brw, info->indexed, hw_prim, info->start, info->count); /* Otherwise, flush and retry: */ if (ret != 0) { brw_context_flush( brw ); ret = try_draw_range_elements(brw, info->indexed, hw_prim, info->start, info->count); assert(ret == 0); } } boolean brw_draw_init( struct brw_context *brw ) { /* Register our drawing function: */ brw->base.draw_vbo = brw_draw_vbo; /* Create helpers for uploading data in user buffers: */ brw->vb.upload_vertex = u_upload_create( &brw->base, 128 * 1024, 64, PIPE_BIND_VERTEX_BUFFER ); if (brw->vb.upload_vertex == NULL) return FALSE; brw->vb.upload_index = u_upload_create( &brw->base, 32 * 1024, 64, PIPE_BIND_INDEX_BUFFER ); if (brw->vb.upload_index == NULL) return FALSE; return TRUE; } void brw_draw_cleanup( struct brw_context *brw ) { u_upload_destroy( brw->vb.upload_vertex ); u_upload_destroy( brw->vb.upload_index ); bo_reference(&brw->ib.bo, NULL); }
bsd-3-clause
sencha/chromium-spacewalk
ui/gfx/font_render_params.h
3358
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_FONT_RENDER_PARAMS_H_ #define UI_GFX_FONT_RENDER_PARAMS_H_ #include <string> #include <vector> #include "ui/gfx/gfx_export.h" namespace gfx { // A collection of parameters describing how text should be rendered on Linux. struct GFX_EXPORT FontRenderParams { FontRenderParams(); ~FontRenderParams(); // Level of hinting to be applied. enum Hinting { HINTING_NONE = 0, HINTING_SLIGHT, HINTING_MEDIUM, HINTING_FULL, }; // Different subpixel orders to be used for subpixel rendering. enum SubpixelRendering { SUBPIXEL_RENDERING_NONE = 0, SUBPIXEL_RENDERING_RGB, SUBPIXEL_RENDERING_BGR, SUBPIXEL_RENDERING_VRGB, SUBPIXEL_RENDERING_VBGR, }; // Antialiasing (grayscale if |subpixel_rendering| is SUBPIXEL_RENDERING_NONE // and RGBA otherwise). bool antialiasing; // Should subpixel positioning (i.e. fractional X positions for glyphs) be // used? // TODO(derat): Remove this; we don't set it in the browser and mostly ignore // it in Blink: http://crbug.com/396659 bool subpixel_positioning; // Should FreeType's autohinter be used (as opposed to Freetype's bytecode // interpreter, which uses fonts' own hinting instructions)? bool autohinter; // Should embedded bitmaps in fonts should be used? bool use_bitmaps; // Hinting level. Hinting hinting; // Whether subpixel rendering should be used or not, and if so, the display's // subpixel order. SubpixelRendering subpixel_rendering; }; // A query used to determine the appropriate FontRenderParams. struct GFX_EXPORT FontRenderParamsQuery { explicit FontRenderParamsQuery(bool for_web_contents); ~FontRenderParamsQuery(); bool is_empty() const { return families.empty() && pixel_size <= 0 && point_size <= 0 && style < 0; } // True if rendering text for the web. // TODO(derat): Remove this once FontRenderParams::subpixel_positioning is // gone: http://crbug.com/396659 bool for_web_contents; // Requested font families, or empty if unset. std::vector<std::string> families; // Font size in pixels or points, or 0 if unset. int pixel_size; int point_size; // gfx::Font::FontStyle bit field, or -1 if unset. int style; }; // Returns the appropriate parameters for rendering the font described by // |query|. If |family_out| is non-NULL, it will be updated to contain the // recommended font family from |query.families|. GFX_EXPORT FontRenderParams GetFontRenderParams( const FontRenderParamsQuery& query, std::string* family_out); // Clears GetFontRenderParams()'s cache. Intended to be called by tests that are // changing Fontconfig's configuration. // TODO(derat): This is only defined for Linux, but OS_LINUX doesn't seem to be // set when font_render_params_linux_unittest.cc includes this header. Figure // out what's going on here. GFX_EXPORT void ClearFontRenderParamsCacheForTest(); #if defined(OS_CHROMEOS) // Sets the device scale factor for FontRenderParams to decide // if it should enable subpixel positioning. GFX_EXPORT void SetFontRenderParamsDeviceScaleFactor( float device_scale_factor); #endif } // namespace gfx #endif // UI_GFX_FONT_RENDER_PARAMS_H_
bsd-3-clause
charliehq/mongoid
lib/mongoid/validatable/uniqueness.rb
10323
# encoding: utf-8 module Mongoid module Validatable # Validates whether or not a field is unique against the documents in the # database. # # @example Define the uniqueness validator. # # class Person # include Mongoid::Document # field :title # # validates_uniqueness_of :title # end class UniquenessValidator < ActiveModel::EachValidator include Queryable attr_reader :klass # Unfortunately, we have to tie Uniqueness validators to a class. # # @example Setup the validator. # UniquenessValidator.new.setup(Person) # # @param [ Class ] klass The class getting validated. # # @since 1.0.0 def setup(klass) @klass = klass end # Validate the document for uniqueness violations. # # @example Validate the document. # validate_each(person, :title, "Sir") # # @param [ Document ] document The document to validate. # @param [ Symbol ] attribute The field to validate on. # @param [ Object ] value The value of the field. # # @return [ Errors ] The errors. # # @since 1.0.0 def validate_each(document, attribute, value) with_query(document) do attrib, val = to_validate(document, attribute, value) return unless validation_required?(document, attrib) if document.embedded? validate_embedded(document, attrib, val) else validate_root(document, attrib, val) end end end private # Add the error to the document. # # @api private # # @example Add the error. # validator.add_error(doc, :name, "test") # # @param [ Document ] document The document to validate. # @param [ Symbol ] attribute The name of the attribute. # @param [ Object ] value The value of the object. # # @since 2.4.10 def add_error(document, attribute, value) document.errors.add( attribute, :taken, options.except(:case_sensitive, :scope).merge(value: value) ) end # Should the uniqueness validation be case sensitive? # # @api private # # @example Is the validation case sensitive? # validator.case_sensitive? # # @return [ true, false ] If the validation is case sensitive. # # @since 2.3.0 def case_sensitive? !(options[:case_sensitive] == false) end # Create the validation criteria. # # @api private # # @example Create the criteria. # validator.create_criteria(User, user, :name, "syd") # # @param [ Class, Proxy ] base The base to execute the criteria from. # @param [ Document ] document The document to validate. # @param [ Symbol ] attribute The name of the attribute. # @param [ Object ] value The value of the object. # # @return [ Criteria ] The criteria. # # @since 2.4.10 def create_criteria(base, document, attribute, value) criteria = scope(base.unscoped, document, attribute) criteria.selector.update(criterion(document, attribute, value.mongoize)) criteria end # Get the default criteria for checking uniqueness. # # @api private # # @example Get the criteria. # validator.criterion(person, :title, "Sir") # # @param [ Document ] document The document to validate. # @param [ Symbol ] attribute The name of the attribute. # @param [ Object ] value The value of the object. # # @return [ Criteria ] The uniqueness criteria. # # @since 2.3.0 def criterion(document, attribute, value) field = document.database_field_name(attribute) if localized?(document, field) conditions = value.inject([]) { |acc, (k,v)| acc << { "#{field}.#{k}" => filter(v) } } selector = { "$or" => conditions } else selector = { field => filter(value) } end if document.persisted? && !document.embedded? selector.merge!(_id: { "$ne" => document.id }) end selector end # Filter the value based on whether the check is case sensitive or not. # # @api private # # @example Filter the value. # validator.filter("testing") # # @param [ Object ] value The value to filter. # # @return [ Object, Regexp ] The value, filtered or not. # # @since 2.3.0 def filter(value) !case_sensitive? && value ? /\A#{Regexp.escape(value.to_s)}$/i : value end # Scope the criteria to the scope options provided. # # @api private # # @example Scope the criteria. # validator.scope(criteria, document) # # @param [ Criteria ] criteria The criteria to scope. # @param [ Document ] document The document being validated. # # @return [ Criteria ] The scoped criteria. # # @since 2.3.0 def scope(criteria, document, attribute) Array.wrap(options[:scope]).each do |item| name = document.database_field_name(item) criteria = criteria.where(item => document.attributes[name]) end criteria = criteria.with(document.persistence_options) criteria end # Should validation be skipped? # # @api private # # @example Should the validation be skipped? # validator.skip_validation?(doc) # # @param [ Document ] document The embedded document. # # @return [ true, false ] If the validation should be skipped. # # @since 2.3.0 def skip_validation?(document) !document._parent || document.embedded_one? end # Scope reference has changed? # # @api private # # @example Has scope reference changed? # validator.scope_value_changed?(doc) # # @param [ Document ] document The embedded document. # # @return [ true, false ] If the scope reference has changed. # # @since def scope_value_changed?(document) Array.wrap(options[:scope]).any? do |item| document.send("attribute_changed?", item.to_s) end end # Get the name of the field and the value to validate. This is for the # case when we validate a relation via the relation name and not the key, # we need to send the key name and value to the db, not the relation # object. # # @api private # # @example Get the name and key to validate. # validator.to_validate(doc, :parent, Parent.new) # # @param [ Document ] document The doc getting validated. # @param [ Symbol ] attribute The attribute getting validated. # @param [ Object ] value The value of the attribute. # # @return [ Array<Object, Object> ] The field and value. # # @since 2.4.4 def to_validate(document, attribute, value) metadata = document.relations[attribute.to_s] if metadata && metadata.stores_foreign_key? [ metadata.foreign_key, value.id ] else [ attribute, value ] end end # Validate an embedded document. # # @api private # # @example Validate the embedded document. # validator.validate_embedded(doc, :name, "test") # # @param [ Document ] document The document. # @param [ Symbol ] attribute The attribute name. # @param [ Object ] value The value. # # @since 2.4.10 def validate_embedded(document, attribute, value) return if skip_validation?(document) relation = document._parent.send(document.metadata_name) criteria = create_criteria(relation, document, attribute, value) add_error(document, attribute, value) if criteria.count > 1 end # Validate a root document. # # @api private # # @example Validate the root document. # validator.validate_root(doc, :name, "test") # # @param [ Document ] document The document. # @param [ Symbol ] attribute The attribute name. # @param [ Object ] value The value. # # @since 2.4.10 def validate_root(document, attribute, value) criteria = create_criteria(klass || document.class, document, attribute, value) if criteria.with(persistence_options(criteria)).exists? add_error(document, attribute, value) end end # Are we required to validate the document? # # @example Is validation needed? # validator.validation_required?(doc, :field) # # @param [ Document ] document The document getting validated. # @param [ Symbol ] attribute The attribute to validate. # # @return [ true, false ] If we need to validate. # # @since 2.4.4 def validation_required?(document, attribute) document.new_record? || document.send("attribute_changed?", attribute.to_s) || scope_value_changed?(document) end # Get the persistence options to perform to check, merging with any # existing. # # @api private # # @example Get the persistence options. # validator.persistence_options(criteria) # # @param [ Criteria ] criteria The criteria. # # @return [ Hash ] The persistence options. # # @since 3.0.23 def persistence_options(criteria) (criteria.persistence_options || {}).merge!(read: :primary) end # Is the attribute localized? # # @api private # # @example Is the attribute localized? # validator.localized?(doc, :field) # # @param [ Document ] document The document getting validated. # @param [ Symbol ] attribute The attribute to validate. # # @return [ true, false ] If the attribute is localized. # # @since 4.0.0 def localized?(document, attribute) document.fields[document.database_field_name(attribute)].try(:localized?) end end end end
mit
luoxiaoshenghustedu/actor-platform
actor-apps/runtime-js/src/main/java/im/actor/runtime/js/crypto/RsaKey.java
393
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.runtime.js.crypto; import com.google.gwt.core.client.JavaScriptObject; public class RsaKey extends JavaScriptObject { protected RsaKey() { } public final native String getPrivateKey()/*-{ return this.privateKey; }-*/; public final native String getPublicKey()/*-{ return this.publicKey; }-*/; }
mit
swgillespie/coreclr
src/mscorlib/src/System/Threading/ThreadStart.cs
862
// 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. // /*============================================================================= ** ** ** ** Purpose: This class is a Delegate which defines the start method ** for starting a thread. That method must match this delegate. ** ** =============================================================================*/ namespace System.Threading { using System.Security.Permissions; using System.Threading; // Define the delegate // NOTE: If you change the signature here, there is code in COMSynchronization // that invokes this delegate in native. [System.Runtime.InteropServices.ComVisible(true)] public delegate void ThreadStart(); }
mit
komejo/d8demo-dev
web/core/modules/migrate_drupal/src/Tests/Table/d7/FieldDataFieldInteger.php
2545
<?php /** * @file * Contains \Drupal\migrate_drupal\Tests\Table\d7\FieldDataFieldInteger. * * THIS IS A GENERATED FILE. DO NOT EDIT. * * @see core/scripts/migrate-db.sh * @see https://www.drupal.org/sandbox/benjy/2405029 */ namespace Drupal\migrate_drupal\Tests\Table\d7; use Drupal\migrate_drupal\Tests\Dump\DrupalDumpBase; /** * Generated file to represent the field_data_field_integer table. */ class FieldDataFieldInteger extends DrupalDumpBase { public function load() { $this->createTable("field_data_field_integer", array( 'primary key' => array( 'entity_type', 'deleted', 'entity_id', 'language', 'delta', ), 'fields' => array( 'entity_type' => array( 'type' => 'varchar', 'not null' => TRUE, 'length' => '128', 'default' => '', ), 'bundle' => array( 'type' => 'varchar', 'not null' => TRUE, 'length' => '128', 'default' => '', ), 'deleted' => array( 'type' => 'int', 'not null' => TRUE, 'length' => '11', 'default' => '0', ), 'entity_id' => array( 'type' => 'int', 'not null' => TRUE, 'length' => '10', 'unsigned' => TRUE, ), 'revision_id' => array( 'type' => 'int', 'not null' => FALSE, 'length' => '10', 'unsigned' => TRUE, ), 'language' => array( 'type' => 'varchar', 'not null' => TRUE, 'length' => '32', 'default' => '', ), 'delta' => array( 'type' => 'int', 'not null' => TRUE, 'length' => '10', 'unsigned' => TRUE, ), 'field_integer_value' => array( 'type' => 'int', 'not null' => FALSE, 'length' => '11', ), ), 'mysql_character_set' => 'utf8', )); $this->database->insert("field_data_field_integer")->fields(array( 'entity_type', 'bundle', 'deleted', 'entity_id', 'revision_id', 'language', 'delta', 'field_integer_value', )) ->values(array( 'entity_type' => 'node', 'bundle' => 'test_content_type', 'deleted' => '0', 'entity_id' => '1', 'revision_id' => '1', 'language' => 'und', 'delta' => '0', 'field_integer_value' => '5', ))->execute(); } } #216fa7f54876d42ec80a9e6b2aa53991
mit
cdmihai/msbuild
src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs
909
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.Logging.StructuredLogger { /// <summary> /// Class representation of a logged item group entry. /// </summary> internal class ItemGroup : TaskParameter { /// <summary> /// Initializes a new instance of the <see cref="ItemGroup"/> class. /// </summary> /// <param name="message">The message from the logger.</param> /// <param name="prefix">The prefix string (e.g. 'Added item(s): ').</param> /// <param name="itemAttributeName">Name of the item attribute ('Include' or 'Remove').</param> public ItemGroup(string message, string prefix, string itemAttributeName) : base(message, prefix, false, itemAttributeName) { } } }
mit
koct9i/linux
drivers/power/supply/axp288_fuel_gauge.c
23206
// SPDX-License-Identifier: GPL-2.0-only /* * axp288_fuel_gauge.c - Xpower AXP288 PMIC Fuel Gauge Driver * * Copyright (C) 2016-2017 Hans de Goede <[email protected]> * Copyright (C) 2014 Intel Corporation * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include <linux/dmi.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/device.h> #include <linux/regmap.h> #include <linux/jiffies.h> #include <linux/interrupt.h> #include <linux/mfd/axp20x.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/iio/consumer.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <asm/unaligned.h> #define PS_STAT_VBUS_TRIGGER (1 << 0) #define PS_STAT_BAT_CHRG_DIR (1 << 2) #define PS_STAT_VBAT_ABOVE_VHOLD (1 << 3) #define PS_STAT_VBUS_VALID (1 << 4) #define PS_STAT_VBUS_PRESENT (1 << 5) #define CHRG_STAT_BAT_SAFE_MODE (1 << 3) #define CHRG_STAT_BAT_VALID (1 << 4) #define CHRG_STAT_BAT_PRESENT (1 << 5) #define CHRG_STAT_CHARGING (1 << 6) #define CHRG_STAT_PMIC_OTP (1 << 7) #define CHRG_CCCV_CC_MASK 0xf /* 4 bits */ #define CHRG_CCCV_CC_BIT_POS 0 #define CHRG_CCCV_CC_OFFSET 200 /* 200mA */ #define CHRG_CCCV_CC_LSB_RES 200 /* 200mA */ #define CHRG_CCCV_ITERM_20P (1 << 4) /* 20% of CC */ #define CHRG_CCCV_CV_MASK 0x60 /* 2 bits */ #define CHRG_CCCV_CV_BIT_POS 5 #define CHRG_CCCV_CV_4100MV 0x0 /* 4.10V */ #define CHRG_CCCV_CV_4150MV 0x1 /* 4.15V */ #define CHRG_CCCV_CV_4200MV 0x2 /* 4.20V */ #define CHRG_CCCV_CV_4350MV 0x3 /* 4.35V */ #define CHRG_CCCV_CHG_EN (1 << 7) #define FG_CNTL_OCV_ADJ_STAT (1 << 2) #define FG_CNTL_OCV_ADJ_EN (1 << 3) #define FG_CNTL_CAP_ADJ_STAT (1 << 4) #define FG_CNTL_CAP_ADJ_EN (1 << 5) #define FG_CNTL_CC_EN (1 << 6) #define FG_CNTL_GAUGE_EN (1 << 7) #define FG_15BIT_WORD_VALID (1 << 15) #define FG_15BIT_VAL_MASK 0x7fff #define FG_REP_CAP_VALID (1 << 7) #define FG_REP_CAP_VAL_MASK 0x7F #define FG_DES_CAP1_VALID (1 << 7) #define FG_DES_CAP_RES_LSB 1456 /* 1.456mAhr */ #define FG_DES_CC_RES_LSB 1456 /* 1.456mAhr */ #define FG_OCV_CAP_VALID (1 << 7) #define FG_OCV_CAP_VAL_MASK 0x7F #define FG_CC_CAP_VALID (1 << 7) #define FG_CC_CAP_VAL_MASK 0x7F #define FG_LOW_CAP_THR1_MASK 0xf0 /* 5% tp 20% */ #define FG_LOW_CAP_THR1_VAL 0xa0 /* 15 perc */ #define FG_LOW_CAP_THR2_MASK 0x0f /* 0% to 15% */ #define FG_LOW_CAP_WARN_THR 14 /* 14 perc */ #define FG_LOW_CAP_CRIT_THR 4 /* 4 perc */ #define FG_LOW_CAP_SHDN_THR 0 /* 0 perc */ #define NR_RETRY_CNT 3 #define DEV_NAME "axp288_fuel_gauge" /* 1.1mV per LSB expressed in uV */ #define VOLTAGE_FROM_ADC(a) ((a * 11) / 10) /* properties converted to uV, uA */ #define PROP_VOLT(a) ((a) * 1000) #define PROP_CURR(a) ((a) * 1000) #define AXP288_FG_INTR_NUM 6 enum { QWBTU_IRQ = 0, WBTU_IRQ, QWBTO_IRQ, WBTO_IRQ, WL2_IRQ, WL1_IRQ, }; enum { BAT_TEMP = 0, PMIC_TEMP, SYSTEM_TEMP, BAT_CHRG_CURR, BAT_D_CURR, BAT_VOLT, IIO_CHANNEL_NUM }; struct axp288_fg_info { struct platform_device *pdev; struct regmap *regmap; struct regmap_irq_chip_data *regmap_irqc; int irq[AXP288_FG_INTR_NUM]; struct iio_channel *iio_channel[IIO_CHANNEL_NUM]; struct power_supply *bat; struct mutex lock; int status; int max_volt; struct dentry *debug_file; }; static enum power_supply_property fuel_gauge_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, POWER_SUPPLY_PROP_VOLTAGE_OCV, POWER_SUPPLY_PROP_CURRENT_NOW, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_CHARGE_FULL, POWER_SUPPLY_PROP_CHARGE_NOW, }; static int fuel_gauge_reg_readb(struct axp288_fg_info *info, int reg) { int ret, i; unsigned int val; for (i = 0; i < NR_RETRY_CNT; i++) { ret = regmap_read(info->regmap, reg, &val); if (ret == -EBUSY) continue; else break; } if (ret < 0) { dev_err(&info->pdev->dev, "axp288 reg read err:%d\n", ret); return ret; } return val; } static int fuel_gauge_reg_writeb(struct axp288_fg_info *info, int reg, u8 val) { int ret; ret = regmap_write(info->regmap, reg, (unsigned int)val); if (ret < 0) dev_err(&info->pdev->dev, "axp288 reg write err:%d\n", ret); return ret; } static int fuel_gauge_read_15bit_word(struct axp288_fg_info *info, int reg) { unsigned char buf[2]; int ret; ret = regmap_bulk_read(info->regmap, reg, buf, 2); if (ret < 0) { dev_err(&info->pdev->dev, "Error reading reg 0x%02x err: %d\n", reg, ret); return ret; } ret = get_unaligned_be16(buf); if (!(ret & FG_15BIT_WORD_VALID)) { dev_err(&info->pdev->dev, "Error reg 0x%02x contents not valid\n", reg); return -ENXIO; } return ret & FG_15BIT_VAL_MASK; } static int fuel_gauge_read_12bit_word(struct axp288_fg_info *info, int reg) { unsigned char buf[2]; int ret; ret = regmap_bulk_read(info->regmap, reg, buf, 2); if (ret < 0) { dev_err(&info->pdev->dev, "Error reading reg 0x%02x err: %d\n", reg, ret); return ret; } /* 12-bit data values have upper 8 bits in buf[0], lower 4 in buf[1] */ return (buf[0] << 4) | ((buf[1] >> 4) & 0x0f); } #ifdef CONFIG_DEBUG_FS static int fuel_gauge_debug_show(struct seq_file *s, void *data) { struct axp288_fg_info *info = s->private; int raw_val, ret; seq_printf(s, " PWR_STATUS[%02x] : %02x\n", AXP20X_PWR_INPUT_STATUS, fuel_gauge_reg_readb(info, AXP20X_PWR_INPUT_STATUS)); seq_printf(s, "PWR_OP_MODE[%02x] : %02x\n", AXP20X_PWR_OP_MODE, fuel_gauge_reg_readb(info, AXP20X_PWR_OP_MODE)); seq_printf(s, " CHRG_CTRL1[%02x] : %02x\n", AXP20X_CHRG_CTRL1, fuel_gauge_reg_readb(info, AXP20X_CHRG_CTRL1)); seq_printf(s, " VLTF[%02x] : %02x\n", AXP20X_V_LTF_DISCHRG, fuel_gauge_reg_readb(info, AXP20X_V_LTF_DISCHRG)); seq_printf(s, " VHTF[%02x] : %02x\n", AXP20X_V_HTF_DISCHRG, fuel_gauge_reg_readb(info, AXP20X_V_HTF_DISCHRG)); seq_printf(s, " CC_CTRL[%02x] : %02x\n", AXP20X_CC_CTRL, fuel_gauge_reg_readb(info, AXP20X_CC_CTRL)); seq_printf(s, "BATTERY CAP[%02x] : %02x\n", AXP20X_FG_RES, fuel_gauge_reg_readb(info, AXP20X_FG_RES)); seq_printf(s, " FG_RDC1[%02x] : %02x\n", AXP288_FG_RDC1_REG, fuel_gauge_reg_readb(info, AXP288_FG_RDC1_REG)); seq_printf(s, " FG_RDC0[%02x] : %02x\n", AXP288_FG_RDC0_REG, fuel_gauge_reg_readb(info, AXP288_FG_RDC0_REG)); seq_printf(s, " FG_OCV[%02x] : %04x\n", AXP288_FG_OCVH_REG, fuel_gauge_read_12bit_word(info, AXP288_FG_OCVH_REG)); seq_printf(s, " FG_DES_CAP[%02x] : %04x\n", AXP288_FG_DES_CAP1_REG, fuel_gauge_read_15bit_word(info, AXP288_FG_DES_CAP1_REG)); seq_printf(s, " FG_CC_MTR[%02x] : %04x\n", AXP288_FG_CC_MTR1_REG, fuel_gauge_read_15bit_word(info, AXP288_FG_CC_MTR1_REG)); seq_printf(s, " FG_OCV_CAP[%02x] : %02x\n", AXP288_FG_OCV_CAP_REG, fuel_gauge_reg_readb(info, AXP288_FG_OCV_CAP_REG)); seq_printf(s, " FG_CC_CAP[%02x] : %02x\n", AXP288_FG_CC_CAP_REG, fuel_gauge_reg_readb(info, AXP288_FG_CC_CAP_REG)); seq_printf(s, " FG_LOW_CAP[%02x] : %02x\n", AXP288_FG_LOW_CAP_REG, fuel_gauge_reg_readb(info, AXP288_FG_LOW_CAP_REG)); seq_printf(s, "TUNING_CTL0[%02x] : %02x\n", AXP288_FG_TUNE0, fuel_gauge_reg_readb(info, AXP288_FG_TUNE0)); seq_printf(s, "TUNING_CTL1[%02x] : %02x\n", AXP288_FG_TUNE1, fuel_gauge_reg_readb(info, AXP288_FG_TUNE1)); seq_printf(s, "TUNING_CTL2[%02x] : %02x\n", AXP288_FG_TUNE2, fuel_gauge_reg_readb(info, AXP288_FG_TUNE2)); seq_printf(s, "TUNING_CTL3[%02x] : %02x\n", AXP288_FG_TUNE3, fuel_gauge_reg_readb(info, AXP288_FG_TUNE3)); seq_printf(s, "TUNING_CTL4[%02x] : %02x\n", AXP288_FG_TUNE4, fuel_gauge_reg_readb(info, AXP288_FG_TUNE4)); seq_printf(s, "TUNING_CTL5[%02x] : %02x\n", AXP288_FG_TUNE5, fuel_gauge_reg_readb(info, AXP288_FG_TUNE5)); ret = iio_read_channel_raw(info->iio_channel[BAT_TEMP], &raw_val); if (ret >= 0) seq_printf(s, "axp288-batttemp : %d\n", raw_val); ret = iio_read_channel_raw(info->iio_channel[PMIC_TEMP], &raw_val); if (ret >= 0) seq_printf(s, "axp288-pmictemp : %d\n", raw_val); ret = iio_read_channel_raw(info->iio_channel[SYSTEM_TEMP], &raw_val); if (ret >= 0) seq_printf(s, "axp288-systtemp : %d\n", raw_val); ret = iio_read_channel_raw(info->iio_channel[BAT_CHRG_CURR], &raw_val); if (ret >= 0) seq_printf(s, "axp288-chrgcurr : %d\n", raw_val); ret = iio_read_channel_raw(info->iio_channel[BAT_D_CURR], &raw_val); if (ret >= 0) seq_printf(s, "axp288-dchrgcur : %d\n", raw_val); ret = iio_read_channel_raw(info->iio_channel[BAT_VOLT], &raw_val); if (ret >= 0) seq_printf(s, "axp288-battvolt : %d\n", raw_val); return 0; } DEFINE_SHOW_ATTRIBUTE(fuel_gauge_debug); static void fuel_gauge_create_debugfs(struct axp288_fg_info *info) { info->debug_file = debugfs_create_file("fuelgauge", 0666, NULL, info, &fuel_gauge_debug_fops); } static void fuel_gauge_remove_debugfs(struct axp288_fg_info *info) { debugfs_remove(info->debug_file); } #else static inline void fuel_gauge_create_debugfs(struct axp288_fg_info *info) { } static inline void fuel_gauge_remove_debugfs(struct axp288_fg_info *info) { } #endif static void fuel_gauge_get_status(struct axp288_fg_info *info) { int pwr_stat, fg_res, curr, ret; pwr_stat = fuel_gauge_reg_readb(info, AXP20X_PWR_INPUT_STATUS); if (pwr_stat < 0) { dev_err(&info->pdev->dev, "PWR STAT read failed:%d\n", pwr_stat); return; } /* Report full if Vbus is valid and the reported capacity is 100% */ if (!(pwr_stat & PS_STAT_VBUS_VALID)) goto not_full; fg_res = fuel_gauge_reg_readb(info, AXP20X_FG_RES); if (fg_res < 0) { dev_err(&info->pdev->dev, "FG RES read failed: %d\n", fg_res); return; } if (!(fg_res & FG_REP_CAP_VALID)) goto not_full; fg_res &= ~FG_REP_CAP_VALID; if (fg_res == 100) { info->status = POWER_SUPPLY_STATUS_FULL; return; } /* * Sometimes the charger turns itself off before fg-res reaches 100%. * When this happens the AXP288 reports a not-charging status and * 0 mA discharge current. */ if (fg_res < 90 || (pwr_stat & PS_STAT_BAT_CHRG_DIR)) goto not_full; ret = iio_read_channel_raw(info->iio_channel[BAT_D_CURR], &curr); if (ret < 0) { dev_err(&info->pdev->dev, "FG get current failed: %d\n", ret); return; } if (curr == 0) { info->status = POWER_SUPPLY_STATUS_FULL; return; } not_full: if (pwr_stat & PS_STAT_BAT_CHRG_DIR) info->status = POWER_SUPPLY_STATUS_CHARGING; else info->status = POWER_SUPPLY_STATUS_DISCHARGING; } static int fuel_gauge_get_vbatt(struct axp288_fg_info *info, int *vbatt) { int ret = 0, raw_val; ret = iio_read_channel_raw(info->iio_channel[BAT_VOLT], &raw_val); if (ret < 0) goto vbatt_read_fail; *vbatt = VOLTAGE_FROM_ADC(raw_val); vbatt_read_fail: return ret; } static int fuel_gauge_get_current(struct axp288_fg_info *info, int *cur) { int ret, discharge; /* First check discharge current, so that we do only 1 read on bat. */ ret = iio_read_channel_raw(info->iio_channel[BAT_D_CURR], &discharge); if (ret < 0) return ret; if (discharge > 0) { *cur = -1 * discharge; return 0; } return iio_read_channel_raw(info->iio_channel[BAT_CHRG_CURR], cur); } static int fuel_gauge_get_vocv(struct axp288_fg_info *info, int *vocv) { int ret; ret = fuel_gauge_read_12bit_word(info, AXP288_FG_OCVH_REG); if (ret >= 0) *vocv = VOLTAGE_FROM_ADC(ret); return ret; } static int fuel_gauge_battery_health(struct axp288_fg_info *info) { int ret, vocv, health = POWER_SUPPLY_HEALTH_UNKNOWN; ret = fuel_gauge_get_vocv(info, &vocv); if (ret < 0) goto health_read_fail; if (vocv > info->max_volt) health = POWER_SUPPLY_HEALTH_OVERVOLTAGE; else health = POWER_SUPPLY_HEALTH_GOOD; health_read_fail: return health; } static int fuel_gauge_get_property(struct power_supply *ps, enum power_supply_property prop, union power_supply_propval *val) { struct axp288_fg_info *info = power_supply_get_drvdata(ps); int ret = 0, value; mutex_lock(&info->lock); switch (prop) { case POWER_SUPPLY_PROP_STATUS: fuel_gauge_get_status(info); val->intval = info->status; break; case POWER_SUPPLY_PROP_HEALTH: val->intval = fuel_gauge_battery_health(info); break; case POWER_SUPPLY_PROP_VOLTAGE_NOW: ret = fuel_gauge_get_vbatt(info, &value); if (ret < 0) goto fuel_gauge_read_err; val->intval = PROP_VOLT(value); break; case POWER_SUPPLY_PROP_VOLTAGE_OCV: ret = fuel_gauge_get_vocv(info, &value); if (ret < 0) goto fuel_gauge_read_err; val->intval = PROP_VOLT(value); break; case POWER_SUPPLY_PROP_CURRENT_NOW: ret = fuel_gauge_get_current(info, &value); if (ret < 0) goto fuel_gauge_read_err; val->intval = PROP_CURR(value); break; case POWER_SUPPLY_PROP_PRESENT: ret = fuel_gauge_reg_readb(info, AXP20X_PWR_OP_MODE); if (ret < 0) goto fuel_gauge_read_err; if (ret & CHRG_STAT_BAT_PRESENT) val->intval = 1; else val->intval = 0; break; case POWER_SUPPLY_PROP_CAPACITY: ret = fuel_gauge_reg_readb(info, AXP20X_FG_RES); if (ret < 0) goto fuel_gauge_read_err; if (!(ret & FG_REP_CAP_VALID)) dev_err(&info->pdev->dev, "capacity measurement not valid\n"); val->intval = (ret & FG_REP_CAP_VAL_MASK); break; case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: ret = fuel_gauge_reg_readb(info, AXP288_FG_LOW_CAP_REG); if (ret < 0) goto fuel_gauge_read_err; val->intval = (ret & 0x0f); break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_CHARGE_NOW: ret = fuel_gauge_read_15bit_word(info, AXP288_FG_CC_MTR1_REG); if (ret < 0) goto fuel_gauge_read_err; val->intval = ret * FG_DES_CAP_RES_LSB; break; case POWER_SUPPLY_PROP_CHARGE_FULL: ret = fuel_gauge_read_15bit_word(info, AXP288_FG_DES_CAP1_REG); if (ret < 0) goto fuel_gauge_read_err; val->intval = ret * FG_DES_CAP_RES_LSB; break; case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN: val->intval = PROP_VOLT(info->max_volt); break; default: mutex_unlock(&info->lock); return -EINVAL; } mutex_unlock(&info->lock); return 0; fuel_gauge_read_err: mutex_unlock(&info->lock); return ret; } static int fuel_gauge_set_property(struct power_supply *ps, enum power_supply_property prop, const union power_supply_propval *val) { struct axp288_fg_info *info = power_supply_get_drvdata(ps); int ret = 0; mutex_lock(&info->lock); switch (prop) { case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: if ((val->intval < 0) || (val->intval > 15)) { ret = -EINVAL; break; } ret = fuel_gauge_reg_readb(info, AXP288_FG_LOW_CAP_REG); if (ret < 0) break; ret &= 0xf0; ret |= (val->intval & 0xf); ret = fuel_gauge_reg_writeb(info, AXP288_FG_LOW_CAP_REG, ret); break; default: ret = -EINVAL; break; } mutex_unlock(&info->lock); return ret; } static int fuel_gauge_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { int ret; switch (psp) { case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN: ret = 1; break; default: ret = 0; } return ret; } static irqreturn_t fuel_gauge_thread_handler(int irq, void *dev) { struct axp288_fg_info *info = dev; int i; for (i = 0; i < AXP288_FG_INTR_NUM; i++) { if (info->irq[i] == irq) break; } if (i >= AXP288_FG_INTR_NUM) { dev_warn(&info->pdev->dev, "spurious interrupt!!\n"); return IRQ_NONE; } switch (i) { case QWBTU_IRQ: dev_info(&info->pdev->dev, "Quit Battery under temperature in work mode IRQ (QWBTU)\n"); break; case WBTU_IRQ: dev_info(&info->pdev->dev, "Battery under temperature in work mode IRQ (WBTU)\n"); break; case QWBTO_IRQ: dev_info(&info->pdev->dev, "Quit Battery over temperature in work mode IRQ (QWBTO)\n"); break; case WBTO_IRQ: dev_info(&info->pdev->dev, "Battery over temperature in work mode IRQ (WBTO)\n"); break; case WL2_IRQ: dev_info(&info->pdev->dev, "Low Batt Warning(2) INTR\n"); break; case WL1_IRQ: dev_info(&info->pdev->dev, "Low Batt Warning(1) INTR\n"); break; default: dev_warn(&info->pdev->dev, "Spurious Interrupt!!!\n"); } power_supply_changed(info->bat); return IRQ_HANDLED; } static void fuel_gauge_external_power_changed(struct power_supply *psy) { struct axp288_fg_info *info = power_supply_get_drvdata(psy); power_supply_changed(info->bat); } static const struct power_supply_desc fuel_gauge_desc = { .name = DEV_NAME, .type = POWER_SUPPLY_TYPE_BATTERY, .properties = fuel_gauge_props, .num_properties = ARRAY_SIZE(fuel_gauge_props), .get_property = fuel_gauge_get_property, .set_property = fuel_gauge_set_property, .property_is_writeable = fuel_gauge_property_is_writeable, .external_power_changed = fuel_gauge_external_power_changed, }; static void fuel_gauge_init_irq(struct axp288_fg_info *info) { int ret, i, pirq; for (i = 0; i < AXP288_FG_INTR_NUM; i++) { pirq = platform_get_irq(info->pdev, i); info->irq[i] = regmap_irq_get_virq(info->regmap_irqc, pirq); if (info->irq[i] < 0) { dev_warn(&info->pdev->dev, "regmap_irq get virq failed for IRQ %d: %d\n", pirq, info->irq[i]); info->irq[i] = -1; goto intr_failed; } ret = request_threaded_irq(info->irq[i], NULL, fuel_gauge_thread_handler, IRQF_ONESHOT, DEV_NAME, info); if (ret) { dev_warn(&info->pdev->dev, "request irq failed for IRQ %d: %d\n", pirq, info->irq[i]); info->irq[i] = -1; goto intr_failed; } else { dev_info(&info->pdev->dev, "HW IRQ %d -> VIRQ %d\n", pirq, info->irq[i]); } } return; intr_failed: for (; i > 0; i--) { free_irq(info->irq[i - 1], info); info->irq[i - 1] = -1; } } /* * Some devices have no battery (HDMI sticks) and the axp288 battery's * detection reports one despite it not being there. */ static const struct dmi_system_id axp288_fuel_gauge_blacklist[] = { { /* ACEPC T8 Cherry Trail Z8350 mini PC */ .matches = { DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "To be filled by O.E.M."), DMI_EXACT_MATCH(DMI_BOARD_NAME, "Cherry Trail CR"), DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "T8"), /* also match on somewhat unique bios-version */ DMI_EXACT_MATCH(DMI_BIOS_VERSION, "1.000"), }, }, { /* ACEPC T11 Cherry Trail Z8350 mini PC */ .matches = { DMI_EXACT_MATCH(DMI_BOARD_VENDOR, "To be filled by O.E.M."), DMI_EXACT_MATCH(DMI_BOARD_NAME, "Cherry Trail CR"), DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "T11"), /* also match on somewhat unique bios-version */ DMI_EXACT_MATCH(DMI_BIOS_VERSION, "1.000"), }, }, { /* Intel Cherry Trail Compute Stick, Windows version */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Intel Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "STK1AW32SC"), }, }, { /* Intel Cherry Trail Compute Stick, version without an OS */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Intel Corporation"), DMI_MATCH(DMI_PRODUCT_NAME, "STK1A32SC"), }, }, { /* Meegopad T08 */ .matches = { DMI_MATCH(DMI_SYS_VENDOR, "Default string"), DMI_MATCH(DMI_BOARD_VENDOR, "To be filled by OEM."), DMI_MATCH(DMI_BOARD_NAME, "T3 MRD"), DMI_MATCH(DMI_BOARD_VERSION, "V1.1"), }, }, { /* ECS EF20EA */ .matches = { DMI_MATCH(DMI_PRODUCT_NAME, "EF20EA"), }, }, {} }; static int axp288_fuel_gauge_probe(struct platform_device *pdev) { int i, ret = 0; struct axp288_fg_info *info; struct axp20x_dev *axp20x = dev_get_drvdata(pdev->dev.parent); struct power_supply_config psy_cfg = {}; static const char * const iio_chan_name[] = { [BAT_TEMP] = "axp288-batt-temp", [PMIC_TEMP] = "axp288-pmic-temp", [SYSTEM_TEMP] = "axp288-system-temp", [BAT_CHRG_CURR] = "axp288-chrg-curr", [BAT_D_CURR] = "axp288-chrg-d-curr", [BAT_VOLT] = "axp288-batt-volt", }; unsigned int val; if (dmi_check_system(axp288_fuel_gauge_blacklist)) return -ENODEV; /* * On some devices the fuelgauge and charger parts of the axp288 are * not used, check that the fuelgauge is enabled (CC_CTRL != 0). */ ret = regmap_read(axp20x->regmap, AXP20X_CC_CTRL, &val); if (ret < 0) return ret; if (val == 0) return -ENODEV; info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; info->pdev = pdev; info->regmap = axp20x->regmap; info->regmap_irqc = axp20x->regmap_irqc; info->status = POWER_SUPPLY_STATUS_UNKNOWN; platform_set_drvdata(pdev, info); mutex_init(&info->lock); for (i = 0; i < IIO_CHANNEL_NUM; i++) { /* * Note cannot use devm_iio_channel_get because x86 systems * lack the device<->channel maps which iio_channel_get will * try to use when passed a non NULL device pointer. */ info->iio_channel[i] = iio_channel_get(NULL, iio_chan_name[i]); if (IS_ERR(info->iio_channel[i])) { ret = PTR_ERR(info->iio_channel[i]); dev_dbg(&pdev->dev, "error getting iiochan %s: %d\n", iio_chan_name[i], ret); /* Wait for axp288_adc to load */ if (ret == -ENODEV) ret = -EPROBE_DEFER; goto out_free_iio_chan; } } ret = fuel_gauge_reg_readb(info, AXP288_FG_DES_CAP1_REG); if (ret < 0) goto out_free_iio_chan; if (!(ret & FG_DES_CAP1_VALID)) { dev_err(&pdev->dev, "axp288 not configured by firmware\n"); ret = -ENODEV; goto out_free_iio_chan; } ret = fuel_gauge_reg_readb(info, AXP20X_CHRG_CTRL1); if (ret < 0) goto out_free_iio_chan; switch ((ret & CHRG_CCCV_CV_MASK) >> CHRG_CCCV_CV_BIT_POS) { case CHRG_CCCV_CV_4100MV: info->max_volt = 4100; break; case CHRG_CCCV_CV_4150MV: info->max_volt = 4150; break; case CHRG_CCCV_CV_4200MV: info->max_volt = 4200; break; case CHRG_CCCV_CV_4350MV: info->max_volt = 4350; break; } psy_cfg.drv_data = info; info->bat = power_supply_register(&pdev->dev, &fuel_gauge_desc, &psy_cfg); if (IS_ERR(info->bat)) { ret = PTR_ERR(info->bat); dev_err(&pdev->dev, "failed to register battery: %d\n", ret); goto out_free_iio_chan; } fuel_gauge_create_debugfs(info); fuel_gauge_init_irq(info); return 0; out_free_iio_chan: for (i = 0; i < IIO_CHANNEL_NUM; i++) if (!IS_ERR_OR_NULL(info->iio_channel[i])) iio_channel_release(info->iio_channel[i]); return ret; } static const struct platform_device_id axp288_fg_id_table[] = { { .name = DEV_NAME }, {}, }; MODULE_DEVICE_TABLE(platform, axp288_fg_id_table); static int axp288_fuel_gauge_remove(struct platform_device *pdev) { struct axp288_fg_info *info = platform_get_drvdata(pdev); int i; power_supply_unregister(info->bat); fuel_gauge_remove_debugfs(info); for (i = 0; i < AXP288_FG_INTR_NUM; i++) if (info->irq[i] >= 0) free_irq(info->irq[i], info); for (i = 0; i < IIO_CHANNEL_NUM; i++) iio_channel_release(info->iio_channel[i]); return 0; } static struct platform_driver axp288_fuel_gauge_driver = { .probe = axp288_fuel_gauge_probe, .remove = axp288_fuel_gauge_remove, .id_table = axp288_fg_id_table, .driver = { .name = DEV_NAME, }, }; module_platform_driver(axp288_fuel_gauge_driver); MODULE_AUTHOR("Ramakrishna Pallala <[email protected]>"); MODULE_AUTHOR("Todd Brandt <[email protected]>"); MODULE_DESCRIPTION("Xpower AXP288 Fuel Gauge Driver"); MODULE_LICENSE("GPL");
gpl-2.0
Evervolv/android_kernel_htc_msm8974
drivers/staging/rtl8192u/r8180_93cx6.c
3214
/* This files contains card eeprom (93c46 or 93c56) programming routines, memory is addressed by 16 bits words. This is part of rtl8180 OpenSource driver. Copyright (C) Andrea Merello 2004 <[email protected]> Released under the terms of GPL (General Public Licence) Parts of this driver are based on the GPL part of the official realtek driver. Parts of this driver are based on the rtl8180 driver skeleton from Patric Schenke & Andres Salomon. Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver. We want to tanks the Authors of those projects and the Ndiswrapper project Authors. */ #include "r8180_93cx6.h" void eprom_cs(struct net_device *dev, short bit) { if(bit) write_nic_byte_E(dev, EPROM_CMD, (1<<EPROM_CS_SHIFT) | \ read_nic_byte_E(dev, EPROM_CMD)); else write_nic_byte_E(dev, EPROM_CMD, read_nic_byte_E(dev, EPROM_CMD)\ &~(1<<EPROM_CS_SHIFT)); force_pci_posting(dev); udelay(EPROM_DELAY); } void eprom_ck_cycle(struct net_device *dev) { write_nic_byte_E(dev, EPROM_CMD, (1<<EPROM_CK_SHIFT) | read_nic_byte_E(dev,EPROM_CMD)); force_pci_posting(dev); udelay(EPROM_DELAY); write_nic_byte_E(dev, EPROM_CMD, read_nic_byte_E(dev, EPROM_CMD) &~ (1<<EPROM_CK_SHIFT)); force_pci_posting(dev); udelay(EPROM_DELAY); } void eprom_w(struct net_device *dev,short bit) { if(bit) write_nic_byte_E(dev, EPROM_CMD, (1<<EPROM_W_SHIFT) | \ read_nic_byte_E(dev,EPROM_CMD)); else write_nic_byte_E(dev, EPROM_CMD, read_nic_byte_E(dev,EPROM_CMD)\ &~(1<<EPROM_W_SHIFT)); force_pci_posting(dev); udelay(EPROM_DELAY); } short eprom_r(struct net_device *dev) { short bit; bit=(read_nic_byte_E(dev, EPROM_CMD) & (1<<EPROM_R_SHIFT) ); udelay(EPROM_DELAY); if(bit) return 1; return 0; } void eprom_send_bits_string(struct net_device *dev, short b[], int len) { int i; for(i=0; i<len; i++){ eprom_w(dev, b[i]); eprom_ck_cycle(dev); } } u32 eprom_read(struct net_device *dev, u32 addr) { struct r8192_priv *priv = ieee80211_priv(dev); short read_cmd[]={1,1,0}; short addr_str[8]; int i; int addr_len; u32 ret; ret=0; write_nic_byte_E(dev, EPROM_CMD, (EPROM_CMD_PROGRAM<<EPROM_CMD_OPERATING_MODE_SHIFT)); force_pci_posting(dev); udelay(EPROM_DELAY); if (priv->epromtype==EPROM_93c56){ addr_str[7]=addr & 1; addr_str[6]=addr & (1<<1); addr_str[5]=addr & (1<<2); addr_str[4]=addr & (1<<3); addr_str[3]=addr & (1<<4); addr_str[2]=addr & (1<<5); addr_str[1]=addr & (1<<6); addr_str[0]=addr & (1<<7); addr_len=8; }else{ addr_str[5]=addr & 1; addr_str[4]=addr & (1<<1); addr_str[3]=addr & (1<<2); addr_str[2]=addr & (1<<3); addr_str[1]=addr & (1<<4); addr_str[0]=addr & (1<<5); addr_len=6; } eprom_cs(dev, 1); eprom_ck_cycle(dev); eprom_send_bits_string(dev, read_cmd, 3); eprom_send_bits_string(dev, addr_str, addr_len); eprom_w(dev, 0); for(i=0;i<16;i++){ eprom_ck_cycle(dev); ret |= (eprom_r(dev)<<(15-i)); } eprom_cs(dev, 0); eprom_ck_cycle(dev); write_nic_byte_E(dev, EPROM_CMD, (EPROM_CMD_NORMAL<<EPROM_CMD_OPERATING_MODE_SHIFT)); return ret; }
gpl-2.0
cipibad/openrtd_2012
toolchain_mipsel/include/linux/hdlc.h
6623
/* * Generic HDLC support routines for Linux * * Copyright (C) 1999-2003 Krzysztof Halasa <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. */ #ifndef __HDLC_H #define __HDLC_H #define GENERIC_HDLC_VERSION 4 /* For synchronization with sethdlc utility */ #define CLOCK_DEFAULT 0 /* Default setting */ #define CLOCK_EXT 1 /* External TX and RX clock - DTE */ #define CLOCK_INT 2 /* Internal TX and RX clock - DCE */ #define CLOCK_TXINT 3 /* Internal TX and external RX clock */ #define CLOCK_TXFROMRX 4 /* TX clock derived from external RX clock */ #define ENCODING_DEFAULT 0 /* Default setting */ #define ENCODING_NRZ 1 #define ENCODING_NRZI 2 #define ENCODING_FM_MARK 3 #define ENCODING_FM_SPACE 4 #define ENCODING_MANCHESTER 5 #define PARITY_DEFAULT 0 /* Default setting */ #define PARITY_NONE 1 /* No parity */ #define PARITY_CRC16_PR0 2 /* CRC16, initial value 0x0000 */ #define PARITY_CRC16_PR1 3 /* CRC16, initial value 0xFFFF */ #define PARITY_CRC16_PR0_CCITT 4 /* CRC16, initial 0x0000, ITU-T version */ #define PARITY_CRC16_PR1_CCITT 5 /* CRC16, initial 0xFFFF, ITU-T version */ #define PARITY_CRC32_PR0_CCITT 6 /* CRC32, initial value 0x00000000 */ #define PARITY_CRC32_PR1_CCITT 7 /* CRC32, initial value 0xFFFFFFFF */ #define LMI_DEFAULT 0 /* Default setting */ #define LMI_NONE 1 /* No LMI, all PVCs are static */ #define LMI_ANSI 2 /* ANSI Annex D */ #define LMI_CCITT 3 /* ITU-T Annex A */ #define HDLC_MAX_MTU 1500 /* Ethernet 1500 bytes */ #define HDLC_MAX_MRU (HDLC_MAX_MTU + 10 + 14 + 4) /* for ETH+VLAN over FR */ #ifdef __KERNEL__ #include <linux/skbuff.h> #include <linux/netdevice.h> #include <net/syncppp.h> #include <linux/hdlc/ioctl.h> typedef struct { /* Used in Cisco and PPP mode */ u8 address; u8 control; u16 protocol; }__attribute__ ((packed)) hdlc_header; typedef struct { u32 type; /* code */ u32 par1; u32 par2; u16 rel; /* reliability */ u32 time; }__attribute__ ((packed)) cisco_packet; #define CISCO_PACKET_LEN 18 #define CISCO_BIG_PACKET_LEN 20 typedef struct pvc_device_struct { struct net_device *master; struct net_device *main; struct net_device *ether; /* bridged Ethernet interface */ struct pvc_device_struct *next; /* Sorted in ascending DLCI order */ int dlci; int open_count; struct { unsigned int new: 1; unsigned int active: 1; unsigned int exist: 1; unsigned int deleted: 1; unsigned int fecn: 1; unsigned int becn: 1; }state; }pvc_device; typedef struct hdlc_device_struct { /* To be initialized by hardware driver */ struct net_device_stats stats; /* used by HDLC layer to take control over HDLC device from hw driver*/ int (*attach)(struct net_device *dev, unsigned short encoding, unsigned short parity); /* hardware driver must handle this instead of dev->hard_start_xmit */ int (*xmit)(struct sk_buff *skb, struct net_device *dev); /* Things below are for HDLC layer internal use only */ struct { int (*open)(struct net_device *dev); void (*close)(struct net_device *dev); /* if open & DCD */ void (*start)(struct net_device *dev); /* if open & !DCD */ void (*stop)(struct net_device *dev); void (*detach)(struct hdlc_device_struct *hdlc); int (*netif_rx)(struct sk_buff *skb); unsigned short (*type_trans)(struct sk_buff *skb, struct net_device *dev); int id; /* IF_PROTO_HDLC/CISCO/FR/etc. */ }proto; int carrier; int open; spinlock_t state_lock; union { struct { fr_proto settings; pvc_device *first_pvc; int dce_pvc_count; struct timer_list timer; unsigned long last_poll; int reliable; int dce_changed; int request; int fullrep_sent; u32 last_errors; /* last errors bit list */ u8 n391cnt; u8 txseq; /* TX sequence number */ u8 rxseq; /* RX sequence number */ }fr; struct { cisco_proto settings; struct timer_list timer; unsigned long last_poll; int up; int request_sent; u32 txseq; /* TX sequence number */ u32 rxseq; /* RX sequence number */ }cisco; struct { raw_hdlc_proto settings; }raw_hdlc; struct { struct ppp_device pppdev; struct ppp_device *syncppp_ptr; int (*old_change_mtu)(struct net_device *dev, int new_mtu); }ppp; }state; void *priv; }hdlc_device; int hdlc_raw_ioctl(struct net_device *dev, struct ifreq *ifr); int hdlc_raw_eth_ioctl(struct net_device *dev, struct ifreq *ifr); int hdlc_cisco_ioctl(struct net_device *dev, struct ifreq *ifr); int hdlc_ppp_ioctl(struct net_device *dev, struct ifreq *ifr); int hdlc_fr_ioctl(struct net_device *dev, struct ifreq *ifr); int hdlc_x25_ioctl(struct net_device *dev, struct ifreq *ifr); /* Exported from hdlc.o */ /* Called by hardware driver when a user requests HDLC service */ int hdlc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd); /* Must be used by hardware driver on module startup/exit */ int register_hdlc_device(struct net_device *dev); void unregister_hdlc_device(struct net_device *dev); struct net_device *alloc_hdlcdev(void *priv); static __inline__ hdlc_device* dev_to_hdlc(struct net_device *dev) { return netdev_priv(dev); } static __inline__ pvc_device* dev_to_pvc(struct net_device *dev) { return (pvc_device*)dev->priv; } static __inline__ void debug_frame(const struct sk_buff *skb) { int i; for (i=0; i < skb->len; i++) { if (i == 100) { printk("...\n"); return; } printk(" %02X", skb->data[i]); } printk("\n"); } /* Must be called by hardware driver when HDLC device is being opened */ int hdlc_open(struct net_device *dev); /* Must be called by hardware driver when HDLC device is being closed */ void hdlc_close(struct net_device *dev); /* Called by hardware driver when DCD line level changes */ void hdlc_set_carrier(int on, struct net_device *dev); /* May be used by hardware driver to gain control over HDLC device */ static __inline__ void hdlc_proto_detach(hdlc_device *hdlc) { if (hdlc->proto.detach) hdlc->proto.detach(hdlc); hdlc->proto.detach = NULL; } static __inline__ struct net_device_stats *hdlc_stats(struct net_device *dev) { return &dev_to_hdlc(dev)->stats; } static __inline__ unsigned short hdlc_type_trans(struct sk_buff *skb, struct net_device *dev) { hdlc_device *hdlc = dev_to_hdlc(dev); skb->mac.raw = skb->data; skb->dev = dev; if (hdlc->proto.type_trans) return hdlc->proto.type_trans(skb, dev); else return htons(ETH_P_HDLC); } #endif /* __KERNEL */ #endif /* __HDLC_H */
gpl-2.0
jameshilliard/m8-3.4.0-gb1fa77f
drivers/scsi/aic7xxx/aic7xxx_pci.c
51214
/* * Product specific probe and attach routines for: * 3940, 2940, aic7895, aic7890, aic7880, * aic7870, aic7860 and aic7850 SCSI controllers * * Copyright (c) 1994-2001 Justin T. Gibbs. * Copyright (c) 2000-2001 Adaptec Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * NO WARRANTY * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * $Id: //depot/aic7xxx/aic7xxx/aic7xxx_pci.c#79 $ */ #ifdef __linux__ #include "aic7xxx_osm.h" #include "aic7xxx_inline.h" #include "aic7xxx_93cx6.h" #else #include <dev/aic7xxx/aic7xxx_osm.h> #include <dev/aic7xxx/aic7xxx_inline.h> #include <dev/aic7xxx/aic7xxx_93cx6.h> #endif #include "aic7xxx_pci.h" static inline uint64_t ahc_compose_id(u_int device, u_int vendor, u_int subdevice, u_int subvendor) { uint64_t id; id = subvendor | (subdevice << 16) | ((uint64_t)vendor << 32) | ((uint64_t)device << 48); return (id); } #define AHC_PCI_IOADDR PCIR_MAPS #define AHC_PCI_MEMADDR (PCIR_MAPS + 4) #define DEVID_9005_TYPE(id) ((id) & 0xF) #define DEVID_9005_TYPE_HBA 0x0 #define DEVID_9005_TYPE_AAA 0x3 #define DEVID_9005_TYPE_SISL 0x5 #define DEVID_9005_TYPE_MB 0xF #define DEVID_9005_MAXRATE(id) (((id) & 0x30) >> 4) #define DEVID_9005_MAXRATE_U160 0x0 #define DEVID_9005_MAXRATE_ULTRA2 0x1 #define DEVID_9005_MAXRATE_ULTRA 0x2 #define DEVID_9005_MAXRATE_FAST 0x3 #define DEVID_9005_MFUNC(id) (((id) & 0x40) >> 6) #define DEVID_9005_CLASS(id) (((id) & 0xFF00) >> 8) #define DEVID_9005_CLASS_SPI 0x0 #define SUBID_9005_TYPE(id) ((id) & 0xF) #define SUBID_9005_TYPE_MB 0xF #define SUBID_9005_TYPE_CARD 0x0 #define SUBID_9005_TYPE_LCCARD 0x1 #define SUBID_9005_TYPE_RAID 0x3 #define SUBID_9005_TYPE_KNOWN(id) \ ((((id) & 0xF) == SUBID_9005_TYPE_MB) \ || (((id) & 0xF) == SUBID_9005_TYPE_CARD) \ || (((id) & 0xF) == SUBID_9005_TYPE_LCCARD) \ || (((id) & 0xF) == SUBID_9005_TYPE_RAID)) #define SUBID_9005_MAXRATE(id) (((id) & 0x30) >> 4) #define SUBID_9005_MAXRATE_ULTRA2 0x0 #define SUBID_9005_MAXRATE_ULTRA 0x1 #define SUBID_9005_MAXRATE_U160 0x2 #define SUBID_9005_MAXRATE_RESERVED 0x3 #define SUBID_9005_SEEPTYPE(id) \ ((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \ ? ((id) & 0xC0) >> 6 \ : ((id) & 0x300) >> 8) #define SUBID_9005_SEEPTYPE_NONE 0x0 #define SUBID_9005_SEEPTYPE_1K 0x1 #define SUBID_9005_SEEPTYPE_2K_4K 0x2 #define SUBID_9005_SEEPTYPE_RESERVED 0x3 #define SUBID_9005_AUTOTERM(id) \ ((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \ ? (((id) & 0x400) >> 10) == 0 \ : (((id) & 0x40) >> 6) == 0) #define SUBID_9005_NUMCHAN(id) \ ((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \ ? ((id) & 0x300) >> 8 \ : ((id) & 0xC00) >> 10) #define SUBID_9005_LEGACYCONN(id) \ ((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \ ? 0 \ : ((id) & 0x80) >> 7) #define SUBID_9005_MFUNCENB(id) \ ((SUBID_9005_TYPE(id) == SUBID_9005_TYPE_MB) \ ? ((id) & 0x800) >> 11 \ : ((id) & 0x1000) >> 12) #define SUBID_9005_CARD_SCSIWIDTH_MASK 0x2000 #define SUBID_9005_CARD_PCIWIDTH_MASK 0x4000 #define SUBID_9005_CARD_SEDIFF_MASK 0x8000 static ahc_device_setup_t ahc_aic785X_setup; static ahc_device_setup_t ahc_aic7860_setup; static ahc_device_setup_t ahc_apa1480_setup; static ahc_device_setup_t ahc_aic7870_setup; static ahc_device_setup_t ahc_aic7870h_setup; static ahc_device_setup_t ahc_aha394X_setup; static ahc_device_setup_t ahc_aha394Xh_setup; static ahc_device_setup_t ahc_aha494X_setup; static ahc_device_setup_t ahc_aha494Xh_setup; static ahc_device_setup_t ahc_aha398X_setup; static ahc_device_setup_t ahc_aic7880_setup; static ahc_device_setup_t ahc_aic7880h_setup; static ahc_device_setup_t ahc_aha2940Pro_setup; static ahc_device_setup_t ahc_aha394XU_setup; static ahc_device_setup_t ahc_aha394XUh_setup; static ahc_device_setup_t ahc_aha398XU_setup; static ahc_device_setup_t ahc_aic7890_setup; static ahc_device_setup_t ahc_aic7892_setup; static ahc_device_setup_t ahc_aic7895_setup; static ahc_device_setup_t ahc_aic7895h_setup; static ahc_device_setup_t ahc_aic7896_setup; static ahc_device_setup_t ahc_aic7899_setup; static ahc_device_setup_t ahc_aha29160C_setup; static ahc_device_setup_t ahc_raid_setup; static ahc_device_setup_t ahc_aha394XX_setup; static ahc_device_setup_t ahc_aha494XX_setup; static ahc_device_setup_t ahc_aha398XX_setup; static const struct ahc_pci_identity ahc_pci_ident_table[] = { { ID_AHA_2902_04_10_15_20C_30C, ID_ALL_MASK, "Adaptec 2902/04/10/15/20C/30C SCSI adapter", ahc_aic785X_setup }, { ID_AHA_2930CU, ID_ALL_MASK, "Adaptec 2930CU SCSI adapter", ahc_aic7860_setup }, { ID_AHA_1480A & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 1480A Ultra SCSI adapter", ahc_apa1480_setup }, { ID_AHA_2940AU_0 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2940A Ultra SCSI adapter", ahc_aic7860_setup }, { ID_AHA_2940AU_CN & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2940A/CN Ultra SCSI adapter", ahc_aic7860_setup }, { ID_AHA_2930C_VAR & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2930C Ultra SCSI adapter (VAR)", ahc_aic7860_setup }, { ID_AHA_2940, ID_ALL_MASK, "Adaptec 2940 SCSI adapter", ahc_aic7870_setup }, { ID_AHA_3940, ID_ALL_MASK, "Adaptec 3940 SCSI adapter", ahc_aha394X_setup }, { ID_AHA_398X, ID_ALL_MASK, "Adaptec 398X SCSI RAID adapter", ahc_aha398X_setup }, { ID_AHA_2944, ID_ALL_MASK, "Adaptec 2944 SCSI adapter", ahc_aic7870h_setup }, { ID_AHA_3944, ID_ALL_MASK, "Adaptec 3944 SCSI adapter", ahc_aha394Xh_setup }, { ID_AHA_4944, ID_ALL_MASK, "Adaptec 4944 SCSI adapter", ahc_aha494Xh_setup }, { ID_AHA_2940U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2940 Ultra SCSI adapter", ahc_aic7880_setup }, { ID_AHA_3940U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 3940 Ultra SCSI adapter", ahc_aha394XU_setup }, { ID_AHA_2944U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2944 Ultra SCSI adapter", ahc_aic7880h_setup }, { ID_AHA_3944U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 3944 Ultra SCSI adapter", ahc_aha394XUh_setup }, { ID_AHA_398XU & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 398X Ultra SCSI RAID adapter", ahc_aha398XU_setup }, { ID_AHA_4944U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 4944 Ultra SCSI adapter", ahc_aic7880h_setup }, { ID_AHA_2930U & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2930 Ultra SCSI adapter", ahc_aic7880_setup }, { ID_AHA_2940U_PRO & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2940 Pro Ultra SCSI adapter", ahc_aha2940Pro_setup }, { ID_AHA_2940U_CN & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec 2940/CN Ultra SCSI adapter", ahc_aic7880_setup }, { ID_9005_SISL_ID, ID_9005_SISL_MASK, NULL, NULL }, { ID_AHA_2930U2, ID_ALL_MASK, "Adaptec 2930 Ultra2 SCSI adapter", ahc_aic7890_setup }, { ID_AHA_2940U2B, ID_ALL_MASK, "Adaptec 2940B Ultra2 SCSI adapter", ahc_aic7890_setup }, { ID_AHA_2940U2_OEM, ID_ALL_MASK, "Adaptec 2940 Ultra2 SCSI adapter (OEM)", ahc_aic7890_setup }, { ID_AHA_2940U2, ID_ALL_MASK, "Adaptec 2940 Ultra2 SCSI adapter", ahc_aic7890_setup }, { ID_AHA_2950U2B, ID_ALL_MASK, "Adaptec 2950 Ultra2 SCSI adapter", ahc_aic7890_setup }, { ID_AIC7890_ARO, ID_ALL_MASK, "Adaptec aic7890/91 Ultra2 SCSI adapter (ARO)", ahc_aic7890_setup }, { ID_AAA_131U2, ID_ALL_MASK, "Adaptec AAA-131 Ultra2 RAID adapter", ahc_aic7890_setup }, { ID_AHA_29160, ID_ALL_MASK, "Adaptec 29160 Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AHA_29160_CPQ, ID_ALL_MASK, "Adaptec (Compaq OEM) 29160 Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AHA_29160N, ID_ALL_MASK, "Adaptec 29160N Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AHA_29160C, ID_ALL_MASK, "Adaptec 29160C Ultra160 SCSI adapter", ahc_aha29160C_setup }, { ID_AHA_29160B, ID_ALL_MASK, "Adaptec 29160B Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AHA_19160B, ID_ALL_MASK, "Adaptec 19160B Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AIC7892_ARO, ID_ALL_MASK, "Adaptec aic7892 Ultra160 SCSI adapter (ARO)", ahc_aic7892_setup }, { ID_AHA_2915_30LP, ID_ALL_MASK, "Adaptec 2915/30LP Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AHA_2940U_DUAL, ID_ALL_MASK, "Adaptec 2940/DUAL Ultra SCSI adapter", ahc_aic7895_setup }, { ID_AHA_3940AU, ID_ALL_MASK, "Adaptec 3940A Ultra SCSI adapter", ahc_aic7895_setup }, { ID_AHA_3944AU, ID_ALL_MASK, "Adaptec 3944A Ultra SCSI adapter", ahc_aic7895h_setup }, { ID_AIC7895_ARO, ID_AIC7895_ARO_MASK, "Adaptec aic7895 Ultra SCSI adapter (ARO)", ahc_aic7895_setup }, { ID_AHA_3950U2B_0, ID_ALL_MASK, "Adaptec 3950B Ultra2 SCSI adapter", ahc_aic7896_setup }, { ID_AHA_3950U2B_1, ID_ALL_MASK, "Adaptec 3950B Ultra2 SCSI adapter", ahc_aic7896_setup }, { ID_AHA_3950U2D_0, ID_ALL_MASK, "Adaptec 3950D Ultra2 SCSI adapter", ahc_aic7896_setup }, { ID_AHA_3950U2D_1, ID_ALL_MASK, "Adaptec 3950D Ultra2 SCSI adapter", ahc_aic7896_setup }, { ID_AIC7896_ARO, ID_ALL_MASK, "Adaptec aic7896/97 Ultra2 SCSI adapter (ARO)", ahc_aic7896_setup }, { ID_AHA_3960D, ID_ALL_MASK, "Adaptec 3960D Ultra160 SCSI adapter", ahc_aic7899_setup }, { ID_AHA_3960D_CPQ, ID_ALL_MASK, "Adaptec (Compaq OEM) 3960D Ultra160 SCSI adapter", ahc_aic7899_setup }, { ID_AIC7899_ARO, ID_ALL_MASK, "Adaptec aic7899 Ultra160 SCSI adapter (ARO)", ahc_aic7899_setup }, { ID_AIC7850 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7850 SCSI adapter", ahc_aic785X_setup }, { ID_AIC7855 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7855 SCSI adapter", ahc_aic785X_setup }, { ID_AIC7859 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7859 SCSI adapter", ahc_aic7860_setup }, { ID_AIC7860 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7860 Ultra SCSI adapter", ahc_aic7860_setup }, { ID_AIC7870 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7870 SCSI adapter", ahc_aic7870_setup }, { ID_AIC7880 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7880 Ultra SCSI adapter", ahc_aic7880_setup }, { ID_AIC7890 & ID_9005_GENERIC_MASK, ID_9005_GENERIC_MASK, "Adaptec aic7890/91 Ultra2 SCSI adapter", ahc_aic7890_setup }, { ID_AIC7892 & ID_9005_GENERIC_MASK, ID_9005_GENERIC_MASK, "Adaptec aic7892 Ultra160 SCSI adapter", ahc_aic7892_setup }, { ID_AIC7895 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7895 Ultra SCSI adapter", ahc_aic7895_setup }, { ID_AIC7896 & ID_9005_GENERIC_MASK, ID_9005_GENERIC_MASK, "Adaptec aic7896/97 Ultra2 SCSI adapter", ahc_aic7896_setup }, { ID_AIC7899 & ID_9005_GENERIC_MASK, ID_9005_GENERIC_MASK, "Adaptec aic7899 Ultra160 SCSI adapter", ahc_aic7899_setup }, { ID_AIC7810 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7810 RAID memory controller", ahc_raid_setup }, { ID_AIC7815 & ID_DEV_VENDOR_MASK, ID_DEV_VENDOR_MASK, "Adaptec aic7815 RAID memory controller", ahc_raid_setup } }; static const u_int ahc_num_pci_devs = ARRAY_SIZE(ahc_pci_ident_table); #define AHC_394X_SLOT_CHANNEL_A 4 #define AHC_394X_SLOT_CHANNEL_B 5 #define AHC_398X_SLOT_CHANNEL_A 4 #define AHC_398X_SLOT_CHANNEL_B 8 #define AHC_398X_SLOT_CHANNEL_C 12 #define AHC_494X_SLOT_CHANNEL_A 4 #define AHC_494X_SLOT_CHANNEL_B 5 #define AHC_494X_SLOT_CHANNEL_C 6 #define AHC_494X_SLOT_CHANNEL_D 7 #define DEVCONFIG 0x40 #define PCIERRGENDIS 0x80000000ul #define SCBSIZE32 0x00010000ul #define REXTVALID 0x00001000ul #define MPORTMODE 0x00000400ul #define RAMPSM 0x00000200ul #define VOLSENSE 0x00000100ul #define PCI64BIT 0x00000080ul #define SCBRAMSEL 0x00000080ul #define MRDCEN 0x00000040ul #define EXTSCBTIME 0x00000020ul #define EXTSCBPEN 0x00000010ul #define BERREN 0x00000008ul #define DACEN 0x00000004ul #define STPWLEVEL 0x00000002ul #define DIFACTNEGEN 0x00000001ul #define CSIZE_LATTIME 0x0c #define CACHESIZE 0x0000003ful #define LATTIME 0x0000ff00ul #define DPE 0x80 #define SSE 0x40 #define RMA 0x20 #define RTA 0x10 #define STA 0x08 #define DPR 0x01 static int ahc_9005_subdevinfo_valid(uint16_t vendor, uint16_t device, uint16_t subvendor, uint16_t subdevice); static int ahc_ext_scbram_present(struct ahc_softc *ahc); static void ahc_scbram_config(struct ahc_softc *ahc, int enable, int pcheck, int fast, int large); static void ahc_probe_ext_scbram(struct ahc_softc *ahc); static void check_extport(struct ahc_softc *ahc, u_int *sxfrctl1); static void ahc_parse_pci_eeprom(struct ahc_softc *ahc, struct seeprom_config *sc); static void configure_termination(struct ahc_softc *ahc, struct seeprom_descriptor *sd, u_int adapter_control, u_int *sxfrctl1); static void ahc_new_term_detect(struct ahc_softc *ahc, int *enableSEC_low, int *enableSEC_high, int *enablePRI_low, int *enablePRI_high, int *eeprom_present); static void aic787X_cable_detect(struct ahc_softc *ahc, int *internal50_present, int *internal68_present, int *externalcable_present, int *eeprom_present); static void aic785X_cable_detect(struct ahc_softc *ahc, int *internal50_present, int *externalcable_present, int *eeprom_present); static void write_brdctl(struct ahc_softc *ahc, uint8_t value); static uint8_t read_brdctl(struct ahc_softc *ahc); static void ahc_pci_intr(struct ahc_softc *ahc); static int ahc_pci_chip_init(struct ahc_softc *ahc); static int ahc_9005_subdevinfo_valid(uint16_t device, uint16_t vendor, uint16_t subdevice, uint16_t subvendor) { int result; result = 0; if (vendor == 0x9005 && subvendor == 0x9005 && subdevice != device && SUBID_9005_TYPE_KNOWN(subdevice) != 0) { switch (SUBID_9005_TYPE(subdevice)) { case SUBID_9005_TYPE_MB: break; case SUBID_9005_TYPE_CARD: case SUBID_9005_TYPE_LCCARD: if (DEVID_9005_TYPE(device) == DEVID_9005_TYPE_HBA) result = 1; break; case SUBID_9005_TYPE_RAID: break; default: break; } } return (result); } const struct ahc_pci_identity * ahc_find_pci_device(ahc_dev_softc_t pci) { uint64_t full_id; uint16_t device; uint16_t vendor; uint16_t subdevice; uint16_t subvendor; const struct ahc_pci_identity *entry; u_int i; vendor = ahc_pci_read_config(pci, PCIR_DEVVENDOR, 2); device = ahc_pci_read_config(pci, PCIR_DEVICE, 2); subvendor = ahc_pci_read_config(pci, PCIR_SUBVEND_0, 2); subdevice = ahc_pci_read_config(pci, PCIR_SUBDEV_0, 2); full_id = ahc_compose_id(device, vendor, subdevice, subvendor); if (ahc_get_pci_function(pci) > 0 && ahc_9005_subdevinfo_valid(vendor, device, subvendor, subdevice) && SUBID_9005_MFUNCENB(subdevice) == 0) return (NULL); for (i = 0; i < ahc_num_pci_devs; i++) { entry = &ahc_pci_ident_table[i]; if (entry->full_id == (full_id & entry->id_mask)) { if (entry->name == NULL) return (NULL); return (entry); } } return (NULL); } int ahc_pci_config(struct ahc_softc *ahc, const struct ahc_pci_identity *entry) { u_int command; u_int our_id; u_int sxfrctl1; u_int scsiseq; u_int dscommand0; uint32_t devconfig; int error; uint8_t sblkctl; our_id = 0; error = entry->setup(ahc); if (error != 0) return (error); ahc->chip |= AHC_PCI; ahc->description = entry->name; pci_set_power_state(ahc->dev_softc, AHC_POWER_STATE_D0); error = ahc_pci_map_registers(ahc); if (error != 0) return (error); ahc_intr_enable(ahc, FALSE); devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) { if (bootverbose) printk("%s: Enabling 39Bit Addressing\n", ahc_name(ahc)); devconfig |= DACEN; } devconfig |= PCIERRGENDIS; ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, devconfig, 4); command = ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, 2); command |= PCIM_CMD_BUSMASTEREN; ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, command, 2); ahc->flags |= AHC_PAGESCBS; error = ahc_softc_init(ahc); if (error != 0) return (error); if ((ahc->flags & AHC_DISABLE_PCI_PERR) != 0) ahc->seqctl |= FAILDIS; ahc->bus_intr = ahc_pci_intr; ahc->bus_chip_init = ahc_pci_chip_init; if ((ahc_inb(ahc, HCNTRL) & POWRDN) == 0) { ahc_pause(ahc); if ((ahc->features & AHC_ULTRA2) != 0) our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID; else our_id = ahc_inb(ahc, SCSIID) & OID; sxfrctl1 = ahc_inb(ahc, SXFRCTL1) & STPWEN; scsiseq = ahc_inb(ahc, SCSISEQ); } else { sxfrctl1 = STPWEN; our_id = 7; scsiseq = 0; } error = ahc_reset(ahc, FALSE); if (error != 0) return (ENXIO); if ((ahc->features & AHC_DT) != 0) { u_int sfunct; sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE; ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE); ahc_outb(ahc, OPTIONMODE, OPTIONMODE_DEFAULTS|AUTOACKEN|BUSFREEREV|EXPPHASEDIS); ahc_outb(ahc, SFUNCT, sfunct); ahc_outb(ahc, CRCCONTROL1, CRCVALCHKEN|CRCENDCHKEN|CRCREQCHKEN |TARGCRCENDEN); } dscommand0 = ahc_inb(ahc, DSCOMMAND0); dscommand0 |= MPARCKEN|CACHETHEN; if ((ahc->features & AHC_ULTRA2) != 0) { dscommand0 &= ~DPARCKEN; } if ((ahc->bugs & AHC_CACHETHEN_DIS_BUG) != 0) dscommand0 |= CACHETHEN; if ((ahc->bugs & AHC_CACHETHEN_BUG) != 0) dscommand0 &= ~CACHETHEN; ahc_outb(ahc, DSCOMMAND0, dscommand0); ahc->pci_cachesize = ahc_pci_read_config(ahc->dev_softc, CSIZE_LATTIME, 1) & CACHESIZE; ahc->pci_cachesize *= 4; if ((ahc->bugs & AHC_PCI_2_1_RETRY_BUG) != 0 && ahc->pci_cachesize == 4) { ahc_pci_write_config(ahc->dev_softc, CSIZE_LATTIME, 0, 1); ahc->pci_cachesize = 0; } if ((ahc->features & AHC_ULTRA) != 0) { uint32_t devconfig; devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); if ((devconfig & REXTVALID) == 0) ahc->features &= ~AHC_ULTRA; } check_extport(ahc, &sxfrctl1); sblkctl = ahc_inb(ahc, SBLKCTL); ahc_outb(ahc, SBLKCTL, (sblkctl & ~(DIAGLEDEN|DIAGLEDON))); if ((ahc->features & AHC_ULTRA2) != 0) { ahc_outb(ahc, DFF_THRSH, RD_DFTHRSH_MAX|WR_DFTHRSH_MAX); } else { ahc_outb(ahc, DSPCISTATUS, DFTHRSH_100); } if (ahc->flags & AHC_USEDEFAULTS) { if ((ahc->flags & AHC_NO_BIOS_INIT) == 0 && scsiseq != 0) { printk("%s: Using left over BIOS settings\n", ahc_name(ahc)); ahc->flags &= ~AHC_USEDEFAULTS; ahc->flags |= AHC_BIOS_ENABLED; } else { our_id = 0x07; sxfrctl1 = STPWEN; } ahc_outb(ahc, SCSICONF, our_id|ENSPCHK|RESET_SCSI); ahc->our_id = our_id; } ahc_probe_ext_scbram(ahc); if ((sxfrctl1 & STPWEN) != 0) ahc->flags |= AHC_TERM_ENB_A; ahc->bus_softc.pci_softc.devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); ahc->bus_softc.pci_softc.command = ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, 1); ahc->bus_softc.pci_softc.csize_lattime = ahc_pci_read_config(ahc->dev_softc, CSIZE_LATTIME, 1); ahc->bus_softc.pci_softc.dscommand0 = ahc_inb(ahc, DSCOMMAND0); ahc->bus_softc.pci_softc.dspcistatus = ahc_inb(ahc, DSPCISTATUS); if ((ahc->features & AHC_DT) != 0) { u_int sfunct; sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE; ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE); ahc->bus_softc.pci_softc.optionmode = ahc_inb(ahc, OPTIONMODE); ahc->bus_softc.pci_softc.targcrccnt = ahc_inw(ahc, TARGCRCCNT); ahc_outb(ahc, SFUNCT, sfunct); ahc->bus_softc.pci_softc.crccontrol1 = ahc_inb(ahc, CRCCONTROL1); } if ((ahc->features & AHC_MULTI_FUNC) != 0) ahc->bus_softc.pci_softc.scbbaddr = ahc_inb(ahc, SCBBADDR); if ((ahc->features & AHC_ULTRA2) != 0) ahc->bus_softc.pci_softc.dff_thrsh = ahc_inb(ahc, DFF_THRSH); error = ahc_init(ahc); if (error != 0) return (error); ahc->init_level++; return ahc_pci_map_int(ahc); } static int ahc_ext_scbram_present(struct ahc_softc *ahc) { u_int chip; int ramps; int single_user; uint32_t devconfig; chip = ahc->chip & AHC_CHIPID_MASK; devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); single_user = (devconfig & MPORTMODE) != 0; if ((ahc->features & AHC_ULTRA2) != 0) ramps = (ahc_inb(ahc, DSCOMMAND0) & RAMPS) != 0; else if (chip == AHC_AIC7895 || chip == AHC_AIC7895C) ramps = 0; else if (chip >= AHC_AIC7870) ramps = (devconfig & RAMPSM) != 0; else ramps = 0; if (ramps && single_user) return (1); return (0); } static void ahc_scbram_config(struct ahc_softc *ahc, int enable, int pcheck, int fast, int large) { uint32_t devconfig; if (ahc->features & AHC_MULTI_FUNC) { ahc_outb(ahc, SCBBADDR, ahc_get_pci_function(ahc->dev_softc)); } ahc->flags &= ~AHC_LSCBS_ENABLED; if (large) ahc->flags |= AHC_LSCBS_ENABLED; devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); if ((ahc->features & AHC_ULTRA2) != 0) { u_int dscommand0; dscommand0 = ahc_inb(ahc, DSCOMMAND0); if (enable) dscommand0 &= ~INTSCBRAMSEL; else dscommand0 |= INTSCBRAMSEL; if (large) dscommand0 &= ~USCBSIZE32; else dscommand0 |= USCBSIZE32; ahc_outb(ahc, DSCOMMAND0, dscommand0); } else { if (fast) devconfig &= ~EXTSCBTIME; else devconfig |= EXTSCBTIME; if (enable) devconfig &= ~SCBRAMSEL; else devconfig |= SCBRAMSEL; if (large) devconfig &= ~SCBSIZE32; else devconfig |= SCBSIZE32; } if (pcheck) devconfig |= EXTSCBPEN; else devconfig &= ~EXTSCBPEN; ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, devconfig, 4); } static void ahc_probe_ext_scbram(struct ahc_softc *ahc) { int num_scbs; int test_num_scbs; int enable; int pcheck; int fast; int large; enable = FALSE; pcheck = FALSE; fast = FALSE; large = FALSE; num_scbs = 0; if (ahc_ext_scbram_present(ahc) == 0) goto done; ahc_scbram_config(ahc, TRUE, pcheck, fast, large); num_scbs = ahc_probe_scbs(ahc); if (num_scbs == 0) { goto done; } enable = TRUE; ahc_outb(ahc, SEQCTL, 0); ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, CLRINT, CLRBRKADRINT); ahc_scbram_config(ahc, enable, TRUE, fast, large); num_scbs = ahc_probe_scbs(ahc); if ((ahc_inb(ahc, INTSTAT) & BRKADRINT) == 0 || (ahc_inb(ahc, ERROR) & MPARERR) == 0) pcheck = TRUE; ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, CLRINT, CLRBRKADRINT); ahc_scbram_config(ahc, enable, pcheck, TRUE, large); test_num_scbs = ahc_probe_scbs(ahc); if (test_num_scbs == num_scbs && ((ahc_inb(ahc, INTSTAT) & BRKADRINT) == 0 || (ahc_inb(ahc, ERROR) & MPARERR) == 0)) fast = TRUE; if ((ahc->features & AHC_LARGE_SCBS) != 0) { ahc_scbram_config(ahc, enable, pcheck, fast, TRUE); test_num_scbs = ahc_probe_scbs(ahc); if (test_num_scbs >= num_scbs) { large = TRUE; num_scbs = test_num_scbs; if (num_scbs >= 64) { ahc->flags |= AHC_SCB_BTT; } } } done: ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS); ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, CLRINT, CLRBRKADRINT); if (bootverbose && enable) { printk("%s: External SRAM, %s access%s, %dbytes/SCB\n", ahc_name(ahc), fast ? "fast" : "slow", pcheck ? ", parity checking enabled" : "", large ? 64 : 32); } ahc_scbram_config(ahc, enable, pcheck, fast, large); } int ahc_pci_test_register_access(struct ahc_softc *ahc) { int error; u_int status1; uint32_t cmd; uint8_t hcntrl; error = EIO; cmd = ahc_pci_read_config(ahc->dev_softc, PCIR_COMMAND, 2); ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, cmd & ~PCIM_CMD_SERRESPEN, 2); hcntrl = ahc_inb(ahc, HCNTRL); if (hcntrl == 0xFF) goto fail; if ((hcntrl & CHIPRST) != 0) { ahc->flags |= AHC_NO_BIOS_INIT; } hcntrl &= ~CHIPRST; ahc_outb(ahc, HCNTRL, hcntrl|PAUSE); while (ahc_is_paused(ahc) == 0) ; status1 = ahc_pci_read_config(ahc->dev_softc, PCIR_STATUS + 1, 1); ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1, status1, 1); ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, SEQCTL, PERRORDIS); ahc_outb(ahc, SCBPTR, 0); ahc_outl(ahc, SCB_BASE, 0x5aa555aa); if (ahc_inl(ahc, SCB_BASE) != 0x5aa555aa) goto fail; status1 = ahc_pci_read_config(ahc->dev_softc, PCIR_STATUS + 1, 1); if ((status1 & STA) != 0) goto fail; error = 0; fail: status1 = ahc_pci_read_config(ahc->dev_softc, PCIR_STATUS + 1, 1); ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1, status1, 1); ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS); ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, cmd, 2); return (error); } static void check_extport(struct ahc_softc *ahc, u_int *sxfrctl1) { struct seeprom_descriptor sd; struct seeprom_config *sc; int have_seeprom; int have_autoterm; sd.sd_ahc = ahc; sd.sd_control_offset = SEECTL; sd.sd_status_offset = SEECTL; sd.sd_dataout_offset = SEECTL; sc = ahc->seep_config; if (ahc->flags & AHC_LARGE_SEEPROM) sd.sd_chip = C56_66; else sd.sd_chip = C46; sd.sd_MS = SEEMS; sd.sd_RDY = SEERDY; sd.sd_CS = SEECS; sd.sd_CK = SEECK; sd.sd_DO = SEEDO; sd.sd_DI = SEEDI; have_seeprom = ahc_acquire_seeprom(ahc, &sd); if (have_seeprom) { if (bootverbose) printk("%s: Reading SEEPROM...", ahc_name(ahc)); for (;;) { u_int start_addr; start_addr = 32 * (ahc->channel - 'A'); have_seeprom = ahc_read_seeprom(&sd, (uint16_t *)sc, start_addr, sizeof(*sc)/2); if (have_seeprom) have_seeprom = ahc_verify_cksum(sc); if (have_seeprom != 0 || sd.sd_chip == C56_66) { if (bootverbose) { if (have_seeprom == 0) printk ("checksum error\n"); else printk ("done.\n"); } break; } sd.sd_chip = C56_66; } ahc_release_seeprom(&sd); if (sd.sd_chip == C56_66) ahc->flags |= AHC_LARGE_SEEPROM; } if (!have_seeprom) { ahc_outb(ahc, SCBPTR, 2); if (ahc_inb(ahc, SCB_BASE) == 'A' && ahc_inb(ahc, SCB_BASE + 1) == 'D' && ahc_inb(ahc, SCB_BASE + 2) == 'P' && ahc_inb(ahc, SCB_BASE + 3) == 'T') { uint16_t *sc_data; int i; sc_data = (uint16_t *)sc; for (i = 0; i < 32; i++, sc_data++) { int j; j = i * 2; *sc_data = ahc_inb(ahc, SRAM_BASE + j) | ahc_inb(ahc, SRAM_BASE + j + 1) << 8; } have_seeprom = ahc_verify_cksum(sc); if (have_seeprom) ahc->flags |= AHC_SCB_CONFIG_USED; } ahc_outb(ahc, CLRINT, CLRPARERR); ahc_outb(ahc, CLRINT, CLRBRKADRINT); } if (!have_seeprom) { if (bootverbose) printk("%s: No SEEPROM available.\n", ahc_name(ahc)); ahc->flags |= AHC_USEDEFAULTS; kfree(ahc->seep_config); ahc->seep_config = NULL; sc = NULL; } else { ahc_parse_pci_eeprom(ahc, sc); } have_autoterm = have_seeprom; if ((ahc->features & AHC_SPIOCAP) != 0) { if ((ahc_inb(ahc, SPIOCAP) & SSPIOCPS) == 0) have_autoterm = FALSE; } if (have_autoterm) { ahc->flags |= AHC_HAS_TERM_LOGIC; ahc_acquire_seeprom(ahc, &sd); configure_termination(ahc, &sd, sc->adapter_control, sxfrctl1); ahc_release_seeprom(&sd); } else if (have_seeprom) { *sxfrctl1 &= ~STPWEN; if ((sc->adapter_control & CFSTERM) != 0) *sxfrctl1 |= STPWEN; if (bootverbose) printk("%s: Low byte termination %sabled\n", ahc_name(ahc), (*sxfrctl1 & STPWEN) ? "en" : "dis"); } } static void ahc_parse_pci_eeprom(struct ahc_softc *ahc, struct seeprom_config *sc) { int i; int max_targ = sc->max_targets & CFMAXTARG; u_int scsi_conf; uint16_t discenable; uint16_t ultraenb; discenable = 0; ultraenb = 0; if ((sc->adapter_control & CFULTRAEN) != 0) { for (i = 0; i < max_targ; i++) { if ((sc->device_flags[i] & CFSYNCHISULTRA) != 0) { ahc->flags |= AHC_NEWEEPROM_FMT; break; } } } for (i = 0; i < max_targ; i++) { u_int scsirate; uint16_t target_mask; target_mask = 0x01 << i; if (sc->device_flags[i] & CFDISC) discenable |= target_mask; if ((ahc->flags & AHC_NEWEEPROM_FMT) != 0) { if ((sc->device_flags[i] & CFSYNCHISULTRA) != 0) ultraenb |= target_mask; } else if ((sc->adapter_control & CFULTRAEN) != 0) { ultraenb |= target_mask; } if ((sc->device_flags[i] & CFXFER) == 0x04 && (ultraenb & target_mask) != 0) { sc->device_flags[i] &= ~CFXFER; ultraenb &= ~target_mask; } if ((ahc->features & AHC_ULTRA2) != 0) { u_int offset; if (sc->device_flags[i] & CFSYNCH) offset = MAX_OFFSET_ULTRA2; else offset = 0; ahc_outb(ahc, TARG_OFFSET + i, offset); scsirate = (sc->device_flags[i] & CFXFER) | ((ultraenb & target_mask) ? 0x8 : 0x0); if (sc->device_flags[i] & CFWIDEB) scsirate |= WIDEXFER; } else { scsirate = (sc->device_flags[i] & CFXFER) << 4; if (sc->device_flags[i] & CFSYNCH) scsirate |= SOFS; if (sc->device_flags[i] & CFWIDEB) scsirate |= WIDEXFER; } ahc_outb(ahc, TARG_SCSIRATE + i, scsirate); } ahc->our_id = sc->brtime_id & CFSCSIID; scsi_conf = (ahc->our_id & 0x7); if (sc->adapter_control & CFSPARITY) scsi_conf |= ENSPCHK; if (sc->adapter_control & CFRESETB) scsi_conf |= RESET_SCSI; ahc->flags |= (sc->adapter_control & CFBOOTCHAN) >> CFBOOTCHANSHIFT; if (sc->bios_control & CFEXTEND) ahc->flags |= AHC_EXTENDED_TRANS_A; if (sc->bios_control & CFBIOSEN) ahc->flags |= AHC_BIOS_ENABLED; if (ahc->features & AHC_ULTRA && (ahc->flags & AHC_NEWEEPROM_FMT) == 0) { if (!(sc->adapter_control & CFULTRAEN)) ultraenb = 0; } if (sc->signature == CFSIGNATURE || sc->signature == CFSIGNATURE2) { uint32_t devconfig; devconfig = ahc_pci_read_config(ahc->dev_softc, DEVCONFIG, 4); devconfig &= ~STPWLEVEL; if ((sc->bios_control & CFSTPWLEVEL) != 0) devconfig |= STPWLEVEL; ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, devconfig, 4); } ahc_outb(ahc, SCSICONF, scsi_conf); ahc_outb(ahc, DISC_DSB, ~(discenable & 0xff)); ahc_outb(ahc, DISC_DSB + 1, ~((discenable >> 8) & 0xff)); ahc_outb(ahc, ULTRA_ENB, ultraenb & 0xff); ahc_outb(ahc, ULTRA_ENB + 1, (ultraenb >> 8) & 0xff); } static void configure_termination(struct ahc_softc *ahc, struct seeprom_descriptor *sd, u_int adapter_control, u_int *sxfrctl1) { uint8_t brddat; brddat = 0; *sxfrctl1 = 0; SEEPROM_OUTB(sd, sd->sd_MS | sd->sd_CS); if ((adapter_control & CFAUTOTERM) != 0 || (ahc->features & AHC_NEW_TERMCTL) != 0) { int internal50_present; int internal68_present; int externalcable_present; int eeprom_present; int enableSEC_low; int enableSEC_high; int enablePRI_low; int enablePRI_high; int sum; enableSEC_low = 0; enableSEC_high = 0; enablePRI_low = 0; enablePRI_high = 0; if ((ahc->features & AHC_NEW_TERMCTL) != 0) { ahc_new_term_detect(ahc, &enableSEC_low, &enableSEC_high, &enablePRI_low, &enablePRI_high, &eeprom_present); if ((adapter_control & CFSEAUTOTERM) == 0) { if (bootverbose) printk("%s: Manual SE Termination\n", ahc_name(ahc)); enableSEC_low = (adapter_control & CFSELOWTERM); enableSEC_high = (adapter_control & CFSEHIGHTERM); } if ((adapter_control & CFAUTOTERM) == 0) { if (bootverbose) printk("%s: Manual LVD Termination\n", ahc_name(ahc)); enablePRI_low = (adapter_control & CFSTERM); enablePRI_high = (adapter_control & CFWSTERM); } internal50_present = 0; internal68_present = 1; externalcable_present = 1; } else if ((ahc->features & AHC_SPIOCAP) != 0) { aic785X_cable_detect(ahc, &internal50_present, &externalcable_present, &eeprom_present); internal68_present = 0; } else { aic787X_cable_detect(ahc, &internal50_present, &internal68_present, &externalcable_present, &eeprom_present); } if ((ahc->features & AHC_WIDE) == 0) internal68_present = 0; if (bootverbose && (ahc->features & AHC_ULTRA2) == 0) { printk("%s: internal 50 cable %s present", ahc_name(ahc), internal50_present ? "is":"not"); if ((ahc->features & AHC_WIDE) != 0) printk(", internal 68 cable %s present", internal68_present ? "is":"not"); printk("\n%s: external cable %s present\n", ahc_name(ahc), externalcable_present ? "is":"not"); } if (bootverbose) printk("%s: BIOS eeprom %s present\n", ahc_name(ahc), eeprom_present ? "is" : "not"); if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0) { internal50_present = 0; } if ((ahc->features & AHC_ULTRA2) == 0 && (internal50_present != 0) && (internal68_present != 0) && (externalcable_present != 0)) { printk("%s: Illegal cable configuration!!. " "Only two connectors on the " "adapter may be used at a " "time!\n", ahc_name(ahc)); internal50_present = 0; internal68_present = 0; externalcable_present = 0; } if ((ahc->features & AHC_WIDE) != 0 && ((externalcable_present == 0) || (internal68_present == 0) || (enableSEC_high != 0))) { brddat |= BRDDAT6; if (bootverbose) { if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0) printk("%s: 68 pin termination " "Enabled\n", ahc_name(ahc)); else printk("%s: %sHigh byte termination " "Enabled\n", ahc_name(ahc), enableSEC_high ? "Secondary " : ""); } } sum = internal50_present + internal68_present + externalcable_present; if (sum < 2 || (enableSEC_low != 0)) { if ((ahc->features & AHC_ULTRA2) != 0) brddat |= BRDDAT5; else *sxfrctl1 |= STPWEN; if (bootverbose) { if ((ahc->flags & AHC_INT50_SPEEDFLEX) != 0) printk("%s: 50 pin termination " "Enabled\n", ahc_name(ahc)); else printk("%s: %sLow byte termination " "Enabled\n", ahc_name(ahc), enableSEC_low ? "Secondary " : ""); } } if (enablePRI_low != 0) { *sxfrctl1 |= STPWEN; if (bootverbose) printk("%s: Primary Low Byte termination " "Enabled\n", ahc_name(ahc)); } ahc_outb(ahc, SXFRCTL1, *sxfrctl1); if (enablePRI_high != 0) { brddat |= BRDDAT4; if (bootverbose) printk("%s: Primary High Byte " "termination Enabled\n", ahc_name(ahc)); } write_brdctl(ahc, brddat); } else { if ((adapter_control & CFSTERM) != 0) { *sxfrctl1 |= STPWEN; if (bootverbose) printk("%s: %sLow byte termination Enabled\n", ahc_name(ahc), (ahc->features & AHC_ULTRA2) ? "Primary " : ""); } if ((adapter_control & CFWSTERM) != 0 && (ahc->features & AHC_WIDE) != 0) { brddat |= BRDDAT6; if (bootverbose) printk("%s: %sHigh byte termination Enabled\n", ahc_name(ahc), (ahc->features & AHC_ULTRA2) ? "Secondary " : ""); } ahc_outb(ahc, SXFRCTL1, *sxfrctl1); if ((ahc->features & AHC_WIDE) != 0) write_brdctl(ahc, brddat); } SEEPROM_OUTB(sd, sd->sd_MS); } static void ahc_new_term_detect(struct ahc_softc *ahc, int *enableSEC_low, int *enableSEC_high, int *enablePRI_low, int *enablePRI_high, int *eeprom_present) { uint8_t brdctl; brdctl = read_brdctl(ahc); *eeprom_present = brdctl & BRDDAT7; *enableSEC_high = (brdctl & BRDDAT6); *enableSEC_low = (brdctl & BRDDAT5); *enablePRI_high = (brdctl & BRDDAT4); *enablePRI_low = (brdctl & BRDDAT3); } static void aic787X_cable_detect(struct ahc_softc *ahc, int *internal50_present, int *internal68_present, int *externalcable_present, int *eeprom_present) { uint8_t brdctl; write_brdctl(ahc, 0); brdctl = read_brdctl(ahc); *internal50_present = (brdctl & BRDDAT6) ? 0 : 1; *internal68_present = (brdctl & BRDDAT7) ? 0 : 1; write_brdctl(ahc, BRDDAT5); brdctl = read_brdctl(ahc); *externalcable_present = (brdctl & BRDDAT6) ? 0 : 1; *eeprom_present = (brdctl & BRDDAT7) ? 1 : 0; } static void aic785X_cable_detect(struct ahc_softc *ahc, int *internal50_present, int *externalcable_present, int *eeprom_present) { uint8_t brdctl; uint8_t spiocap; spiocap = ahc_inb(ahc, SPIOCAP); spiocap &= ~SOFTCMDEN; spiocap |= EXT_BRDCTL; ahc_outb(ahc, SPIOCAP, spiocap); ahc_outb(ahc, BRDCTL, BRDRW|BRDCS); ahc_flush_device_writes(ahc); ahc_delay(500); ahc_outb(ahc, BRDCTL, 0); ahc_flush_device_writes(ahc); ahc_delay(500); brdctl = ahc_inb(ahc, BRDCTL); *internal50_present = (brdctl & BRDDAT5) ? 0 : 1; *externalcable_present = (brdctl & BRDDAT6) ? 0 : 1; *eeprom_present = (ahc_inb(ahc, SPIOCAP) & EEPROM) ? 1 : 0; } int ahc_acquire_seeprom(struct ahc_softc *ahc, struct seeprom_descriptor *sd) { int wait; if ((ahc->features & AHC_SPIOCAP) != 0 && (ahc_inb(ahc, SPIOCAP) & SEEPROM) == 0) return (0); SEEPROM_OUTB(sd, sd->sd_MS); wait = 1000; while (--wait && ((SEEPROM_STATUS_INB(sd) & sd->sd_RDY) == 0)) { ahc_delay(1000); } if ((SEEPROM_STATUS_INB(sd) & sd->sd_RDY) == 0) { SEEPROM_OUTB(sd, 0); return (0); } return(1); } void ahc_release_seeprom(struct seeprom_descriptor *sd) { SEEPROM_OUTB(sd, 0); } static void write_brdctl(struct ahc_softc *ahc, uint8_t value) { uint8_t brdctl; if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7895) { brdctl = BRDSTB; if (ahc->channel == 'B') brdctl |= BRDCS; } else if ((ahc->features & AHC_ULTRA2) != 0) { brdctl = 0; } else { brdctl = BRDSTB|BRDCS; } ahc_outb(ahc, BRDCTL, brdctl); ahc_flush_device_writes(ahc); brdctl |= value; ahc_outb(ahc, BRDCTL, brdctl); ahc_flush_device_writes(ahc); if ((ahc->features & AHC_ULTRA2) != 0) brdctl |= BRDSTB_ULTRA2; else brdctl &= ~BRDSTB; ahc_outb(ahc, BRDCTL, brdctl); ahc_flush_device_writes(ahc); if ((ahc->features & AHC_ULTRA2) != 0) brdctl = 0; else brdctl &= ~BRDCS; ahc_outb(ahc, BRDCTL, brdctl); } static uint8_t read_brdctl(struct ahc_softc *ahc) { uint8_t brdctl; uint8_t value; if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7895) { brdctl = BRDRW; if (ahc->channel == 'B') brdctl |= BRDCS; } else if ((ahc->features & AHC_ULTRA2) != 0) { brdctl = BRDRW_ULTRA2; } else { brdctl = BRDRW|BRDCS; } ahc_outb(ahc, BRDCTL, brdctl); ahc_flush_device_writes(ahc); value = ahc_inb(ahc, BRDCTL); ahc_outb(ahc, BRDCTL, 0); return (value); } static void ahc_pci_intr(struct ahc_softc *ahc) { u_int error; u_int status1; error = ahc_inb(ahc, ERROR); if ((error & PCIERRSTAT) == 0) return; status1 = ahc_pci_read_config(ahc->dev_softc, PCIR_STATUS + 1, 1); printk("%s: PCI error Interrupt at seqaddr = 0x%x\n", ahc_name(ahc), ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8)); if (status1 & DPE) { ahc->pci_target_perr_count++; printk("%s: Data Parity Error Detected during address " "or write data phase\n", ahc_name(ahc)); } if (status1 & SSE) { printk("%s: Signal System Error Detected\n", ahc_name(ahc)); } if (status1 & RMA) { printk("%s: Received a Master Abort\n", ahc_name(ahc)); } if (status1 & RTA) { printk("%s: Received a Target Abort\n", ahc_name(ahc)); } if (status1 & STA) { printk("%s: Signaled a Target Abort\n", ahc_name(ahc)); } if (status1 & DPR) { printk("%s: Data Parity Error has been reported via PERR#\n", ahc_name(ahc)); } ahc_pci_write_config(ahc->dev_softc, PCIR_STATUS + 1, status1, 1); if ((status1 & (DPE|SSE|RMA|RTA|STA|DPR)) == 0) { printk("%s: Latched PCIERR interrupt with " "no status bits set\n", ahc_name(ahc)); } else { ahc_outb(ahc, CLRINT, CLRPARERR); } if (ahc->pci_target_perr_count > AHC_PCI_TARGET_PERR_THRESH) { printk( "%s: WARNING WARNING WARNING WARNING\n" "%s: Too many PCI parity errors observed as a target.\n" "%s: Some device on this bus is generating bad parity.\n" "%s: This is an error *observed by*, not *generated by*, this controller.\n" "%s: PCI parity error checking has been disabled.\n" "%s: WARNING WARNING WARNING WARNING\n", ahc_name(ahc), ahc_name(ahc), ahc_name(ahc), ahc_name(ahc), ahc_name(ahc), ahc_name(ahc)); ahc->seqctl |= FAILDIS; ahc_outb(ahc, SEQCTL, ahc->seqctl); } ahc_unpause(ahc); } static int ahc_pci_chip_init(struct ahc_softc *ahc) { ahc_outb(ahc, DSCOMMAND0, ahc->bus_softc.pci_softc.dscommand0); ahc_outb(ahc, DSPCISTATUS, ahc->bus_softc.pci_softc.dspcistatus); if ((ahc->features & AHC_DT) != 0) { u_int sfunct; sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE; ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE); ahc_outb(ahc, OPTIONMODE, ahc->bus_softc.pci_softc.optionmode); ahc_outw(ahc, TARGCRCCNT, ahc->bus_softc.pci_softc.targcrccnt); ahc_outb(ahc, SFUNCT, sfunct); ahc_outb(ahc, CRCCONTROL1, ahc->bus_softc.pci_softc.crccontrol1); } if ((ahc->features & AHC_MULTI_FUNC) != 0) ahc_outb(ahc, SCBBADDR, ahc->bus_softc.pci_softc.scbbaddr); if ((ahc->features & AHC_ULTRA2) != 0) ahc_outb(ahc, DFF_THRSH, ahc->bus_softc.pci_softc.dff_thrsh); return (ahc_chip_init(ahc)); } #ifdef CONFIG_PM void ahc_pci_resume(struct ahc_softc *ahc) { ahc_pci_write_config(ahc->dev_softc, DEVCONFIG, ahc->bus_softc.pci_softc.devconfig, 4); ahc_pci_write_config(ahc->dev_softc, PCIR_COMMAND, ahc->bus_softc.pci_softc.command, 1); ahc_pci_write_config(ahc->dev_softc, CSIZE_LATTIME, ahc->bus_softc.pci_softc.csize_lattime, 1); if ((ahc->flags & AHC_HAS_TERM_LOGIC) != 0) { struct seeprom_descriptor sd; u_int sxfrctl1; sd.sd_ahc = ahc; sd.sd_control_offset = SEECTL; sd.sd_status_offset = SEECTL; sd.sd_dataout_offset = SEECTL; ahc_acquire_seeprom(ahc, &sd); configure_termination(ahc, &sd, ahc->seep_config->adapter_control, &sxfrctl1); ahc_release_seeprom(&sd); } } #endif static int ahc_aic785X_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; uint8_t rev; pci = ahc->dev_softc; ahc->channel = 'A'; ahc->chip = AHC_AIC7850; ahc->features = AHC_AIC7850_FE; ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG; rev = ahc_pci_read_config(pci, PCIR_REVID, 1); if (rev >= 1) ahc->bugs |= AHC_PCI_2_1_RETRY_BUG; ahc->instruction_ram_size = 512; return (0); } static int ahc_aic7860_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; uint8_t rev; pci = ahc->dev_softc; ahc->channel = 'A'; ahc->chip = AHC_AIC7860; ahc->features = AHC_AIC7860_FE; ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG; rev = ahc_pci_read_config(pci, PCIR_REVID, 1); if (rev >= 1) ahc->bugs |= AHC_PCI_2_1_RETRY_BUG; ahc->instruction_ram_size = 512; return (0); } static int ahc_apa1480_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7860_setup(ahc); if (error != 0) return (error); ahc->features |= AHC_REMOVABLE; return (0); } static int ahc_aic7870_setup(struct ahc_softc *ahc) { ahc->channel = 'A'; ahc->chip = AHC_AIC7870; ahc->features = AHC_AIC7870_FE; ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG; ahc->instruction_ram_size = 512; return (0); } static int ahc_aic7870h_setup(struct ahc_softc *ahc) { int error = ahc_aic7870_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aha394X_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7870_setup(ahc); if (error == 0) error = ahc_aha394XX_setup(ahc); return (error); } static int ahc_aha394Xh_setup(struct ahc_softc *ahc) { int error = ahc_aha394X_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aha398X_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7870_setup(ahc); if (error == 0) error = ahc_aha398XX_setup(ahc); return (error); } static int ahc_aha494X_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7870_setup(ahc); if (error == 0) error = ahc_aha494XX_setup(ahc); return (error); } static int ahc_aha494Xh_setup(struct ahc_softc *ahc) { int error = ahc_aha494X_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aic7880_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; uint8_t rev; pci = ahc->dev_softc; ahc->channel = 'A'; ahc->chip = AHC_AIC7880; ahc->features = AHC_AIC7880_FE; ahc->bugs |= AHC_TMODE_WIDEODD_BUG; rev = ahc_pci_read_config(pci, PCIR_REVID, 1); if (rev >= 1) { ahc->bugs |= AHC_PCI_2_1_RETRY_BUG; } else { ahc->bugs |= AHC_CACHETHEN_BUG|AHC_PCI_MWI_BUG; } ahc->instruction_ram_size = 512; return (0); } static int ahc_aic7880h_setup(struct ahc_softc *ahc) { int error = ahc_aic7880_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aha2940Pro_setup(struct ahc_softc *ahc) { ahc->flags |= AHC_INT50_SPEEDFLEX; return (ahc_aic7880_setup(ahc)); } static int ahc_aha394XU_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7880_setup(ahc); if (error == 0) error = ahc_aha394XX_setup(ahc); return (error); } static int ahc_aha394XUh_setup(struct ahc_softc *ahc) { int error = ahc_aha394XU_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aha398XU_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7880_setup(ahc); if (error == 0) error = ahc_aha398XX_setup(ahc); return (error); } static int ahc_aic7890_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; uint8_t rev; pci = ahc->dev_softc; ahc->channel = 'A'; ahc->chip = AHC_AIC7890; ahc->features = AHC_AIC7890_FE; ahc->flags |= AHC_NEWEEPROM_FMT; rev = ahc_pci_read_config(pci, PCIR_REVID, 1); if (rev == 0) ahc->bugs |= AHC_AUTOFLUSH_BUG|AHC_CACHETHEN_BUG; ahc->instruction_ram_size = 768; return (0); } static int ahc_aic7892_setup(struct ahc_softc *ahc) { ahc->channel = 'A'; ahc->chip = AHC_AIC7892; ahc->features = AHC_AIC7892_FE; ahc->flags |= AHC_NEWEEPROM_FMT; ahc->bugs |= AHC_SCBCHAN_UPLOAD_BUG; ahc->instruction_ram_size = 1024; return (0); } static int ahc_aic7895_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; uint8_t rev; pci = ahc->dev_softc; ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A'; rev = ahc_pci_read_config(pci, PCIR_REVID, 1); if (rev >= 4) { ahc->chip = AHC_AIC7895C; ahc->features = AHC_AIC7895C_FE; } else { u_int command; ahc->chip = AHC_AIC7895; ahc->features = AHC_AIC7895_FE; command = ahc_pci_read_config(pci, PCIR_COMMAND, 1); command |= PCIM_CMD_MWRICEN; ahc_pci_write_config(pci, PCIR_COMMAND, command, 1); ahc->bugs |= AHC_PCI_MWI_BUG; } ahc->bugs |= AHC_TMODE_WIDEODD_BUG|AHC_PCI_2_1_RETRY_BUG | AHC_CACHETHEN_BUG; #if 0 uint32_t devconfig; ahc_pci_write_config(pci, CSIZE_LATTIME, 0, 1); devconfig = ahc_pci_read_config(pci, DEVCONFIG, 1); devconfig |= MRDCEN; ahc_pci_write_config(pci, DEVCONFIG, devconfig, 1); #endif ahc->flags |= AHC_NEWEEPROM_FMT; ahc->instruction_ram_size = 512; return (0); } static int ahc_aic7895h_setup(struct ahc_softc *ahc) { int error = ahc_aic7895_setup(ahc); ahc->features |= AHC_HVD; return error; } static int ahc_aic7896_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; pci = ahc->dev_softc; ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A'; ahc->chip = AHC_AIC7896; ahc->features = AHC_AIC7896_FE; ahc->flags |= AHC_NEWEEPROM_FMT; ahc->bugs |= AHC_CACHETHEN_DIS_BUG; ahc->instruction_ram_size = 768; return (0); } static int ahc_aic7899_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; pci = ahc->dev_softc; ahc->channel = ahc_get_pci_function(pci) == 1 ? 'B' : 'A'; ahc->chip = AHC_AIC7899; ahc->features = AHC_AIC7899_FE; ahc->flags |= AHC_NEWEEPROM_FMT; ahc->bugs |= AHC_SCBCHAN_UPLOAD_BUG; ahc->instruction_ram_size = 1024; return (0); } static int ahc_aha29160C_setup(struct ahc_softc *ahc) { int error; error = ahc_aic7899_setup(ahc); if (error != 0) return (error); ahc->features |= AHC_REMOVABLE; return (0); } static int ahc_raid_setup(struct ahc_softc *ahc) { printk("RAID functionality unsupported\n"); return (ENXIO); } static int ahc_aha394XX_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; pci = ahc->dev_softc; switch (ahc_get_pci_slot(pci)) { case AHC_394X_SLOT_CHANNEL_A: ahc->channel = 'A'; break; case AHC_394X_SLOT_CHANNEL_B: ahc->channel = 'B'; break; default: printk("adapter at unexpected slot %d\n" "unable to map to a channel\n", ahc_get_pci_slot(pci)); ahc->channel = 'A'; } return (0); } static int ahc_aha398XX_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; pci = ahc->dev_softc; switch (ahc_get_pci_slot(pci)) { case AHC_398X_SLOT_CHANNEL_A: ahc->channel = 'A'; break; case AHC_398X_SLOT_CHANNEL_B: ahc->channel = 'B'; break; case AHC_398X_SLOT_CHANNEL_C: ahc->channel = 'C'; break; default: printk("adapter at unexpected slot %d\n" "unable to map to a channel\n", ahc_get_pci_slot(pci)); ahc->channel = 'A'; break; } ahc->flags |= AHC_LARGE_SEEPROM; return (0); } static int ahc_aha494XX_setup(struct ahc_softc *ahc) { ahc_dev_softc_t pci; pci = ahc->dev_softc; switch (ahc_get_pci_slot(pci)) { case AHC_494X_SLOT_CHANNEL_A: ahc->channel = 'A'; break; case AHC_494X_SLOT_CHANNEL_B: ahc->channel = 'B'; break; case AHC_494X_SLOT_CHANNEL_C: ahc->channel = 'C'; break; case AHC_494X_SLOT_CHANNEL_D: ahc->channel = 'D'; break; default: printk("adapter at unexpected slot %d\n" "unable to map to a channel\n", ahc_get_pci_slot(pci)); ahc->channel = 'A'; } ahc->flags |= AHC_LARGE_SEEPROM; return (0); }
gpl-2.0
ghmajx/asuswrt-merlin
release/src-rt/linux/linux-2.6/drivers/infiniband/ulp/ipoib/ipoib_cm.c
37955
/* * Copyright (c) 2006 Mellanox Technologies. All rights reserved * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * 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. * * $Id$ */ #include <rdma/ib_cm.h> #include <rdma/ib_cache.h> #include <net/dst.h> #include <net/icmp.h> #include <linux/icmpv6.h> #include <linux/delay.h> #ifdef CONFIG_INFINIBAND_IPOIB_DEBUG_DATA static int data_debug_level; module_param_named(cm_data_debug_level, data_debug_level, int, 0644); MODULE_PARM_DESC(cm_data_debug_level, "Enable data path debug tracing for connected mode if > 0"); #endif #include "ipoib.h" #define IPOIB_CM_IETF_ID 0x1000000000000000ULL #define IPOIB_CM_RX_UPDATE_TIME (256 * HZ) #define IPOIB_CM_RX_TIMEOUT (2 * 256 * HZ) #define IPOIB_CM_RX_DELAY (3 * 256 * HZ) #define IPOIB_CM_RX_UPDATE_MASK (0x3) static struct ib_qp_attr ipoib_cm_err_attr = { .qp_state = IB_QPS_ERR }; #define IPOIB_CM_RX_DRAIN_WRID 0x7fffffff static struct ib_send_wr ipoib_cm_rx_drain_wr = { .wr_id = IPOIB_CM_RX_DRAIN_WRID, .opcode = IB_WR_SEND, }; static int ipoib_cm_tx_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event); static void ipoib_cm_dma_unmap_rx(struct ipoib_dev_priv *priv, int frags, u64 mapping[IPOIB_CM_RX_SG]) { int i; ib_dma_unmap_single(priv->ca, mapping[0], IPOIB_CM_HEAD_SIZE, DMA_FROM_DEVICE); for (i = 0; i < frags; ++i) ib_dma_unmap_single(priv->ca, mapping[i + 1], PAGE_SIZE, DMA_FROM_DEVICE); } static int ipoib_cm_post_receive(struct net_device *dev, int id) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_recv_wr *bad_wr; int i, ret; priv->cm.rx_wr.wr_id = id | IPOIB_CM_OP_SRQ; for (i = 0; i < IPOIB_CM_RX_SG; ++i) priv->cm.rx_sge[i].addr = priv->cm.srq_ring[id].mapping[i]; ret = ib_post_srq_recv(priv->cm.srq, &priv->cm.rx_wr, &bad_wr); if (unlikely(ret)) { ipoib_warn(priv, "post srq failed for buf %d (%d)\n", id, ret); ipoib_cm_dma_unmap_rx(priv, IPOIB_CM_RX_SG - 1, priv->cm.srq_ring[id].mapping); dev_kfree_skb_any(priv->cm.srq_ring[id].skb); priv->cm.srq_ring[id].skb = NULL; } return ret; } static struct sk_buff *ipoib_cm_alloc_rx_skb(struct net_device *dev, int id, int frags, u64 mapping[IPOIB_CM_RX_SG]) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct sk_buff *skb; int i; skb = dev_alloc_skb(IPOIB_CM_HEAD_SIZE + 12); if (unlikely(!skb)) return NULL; /* * IPoIB adds a 4 byte header. So we need 12 more bytes to align the * IP header to a multiple of 16. */ skb_reserve(skb, 12); mapping[0] = ib_dma_map_single(priv->ca, skb->data, IPOIB_CM_HEAD_SIZE, DMA_FROM_DEVICE); if (unlikely(ib_dma_mapping_error(priv->ca, mapping[0]))) { dev_kfree_skb_any(skb); return NULL; } for (i = 0; i < frags; i++) { struct page *page = alloc_page(GFP_ATOMIC); if (!page) goto partial_error; skb_fill_page_desc(skb, i, page, 0, PAGE_SIZE); mapping[i + 1] = ib_dma_map_page(priv->ca, skb_shinfo(skb)->frags[i].page, 0, PAGE_SIZE, DMA_FROM_DEVICE); if (unlikely(ib_dma_mapping_error(priv->ca, mapping[i + 1]))) goto partial_error; } priv->cm.srq_ring[id].skb = skb; return skb; partial_error: ib_dma_unmap_single(priv->ca, mapping[0], IPOIB_CM_HEAD_SIZE, DMA_FROM_DEVICE); for (; i > 0; --i) ib_dma_unmap_single(priv->ca, mapping[i], PAGE_SIZE, DMA_FROM_DEVICE); dev_kfree_skb_any(skb); return NULL; } static void ipoib_cm_start_rx_drain(struct ipoib_dev_priv* priv) { struct ib_send_wr *bad_wr; struct ipoib_cm_rx *p; /* We only reserved 1 extra slot in CQ for drain WRs, so * make sure we have at most 1 outstanding WR. */ if (list_empty(&priv->cm.rx_flush_list) || !list_empty(&priv->cm.rx_drain_list)) return; /* * QPs on flush list are error state. This way, a "flush * error" WC will be immediately generated for each WR we post. */ p = list_entry(priv->cm.rx_flush_list.next, typeof(*p), list); if (ib_post_send(p->qp, &ipoib_cm_rx_drain_wr, &bad_wr)) ipoib_warn(priv, "failed to post drain wr\n"); list_splice_init(&priv->cm.rx_flush_list, &priv->cm.rx_drain_list); } static void ipoib_cm_rx_event_handler(struct ib_event *event, void *ctx) { struct ipoib_cm_rx *p = ctx; struct ipoib_dev_priv *priv = netdev_priv(p->dev); unsigned long flags; if (event->event != IB_EVENT_QP_LAST_WQE_REACHED) return; spin_lock_irqsave(&priv->lock, flags); list_move(&p->list, &priv->cm.rx_flush_list); p->state = IPOIB_CM_RX_FLUSH; ipoib_cm_start_rx_drain(priv); spin_unlock_irqrestore(&priv->lock, flags); } static struct ib_qp *ipoib_cm_create_rx_qp(struct net_device *dev, struct ipoib_cm_rx *p) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_qp_init_attr attr = { .event_handler = ipoib_cm_rx_event_handler, .send_cq = priv->cq, /* For drain WR */ .recv_cq = priv->cq, .srq = priv->cm.srq, .cap.max_send_wr = 1, /* For drain WR */ .cap.max_send_sge = 1, /* FIXME: 0 Seems not to work */ .sq_sig_type = IB_SIGNAL_ALL_WR, .qp_type = IB_QPT_RC, .qp_context = p, }; return ib_create_qp(priv->pd, &attr); } static int ipoib_cm_modify_rx_qp(struct net_device *dev, struct ib_cm_id *cm_id, struct ib_qp *qp, unsigned psn) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_qp_attr qp_attr; int qp_attr_mask, ret; qp_attr.qp_state = IB_QPS_INIT; ret = ib_cm_init_qp_attr(cm_id, &qp_attr, &qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to init QP attr for INIT: %d\n", ret); return ret; } ret = ib_modify_qp(qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify QP to INIT: %d\n", ret); return ret; } qp_attr.qp_state = IB_QPS_RTR; ret = ib_cm_init_qp_attr(cm_id, &qp_attr, &qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to init QP attr for RTR: %d\n", ret); return ret; } qp_attr.rq_psn = psn; ret = ib_modify_qp(qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify QP to RTR: %d\n", ret); return ret; } /* * Current Mellanox HCA firmware won't generate completions * with error for drain WRs unless the QP has been moved to * RTS first. This work-around leaves a window where a QP has * moved to error asynchronously, but this will eventually get * fixed in firmware, so let's not error out if modify QP * fails. */ qp_attr.qp_state = IB_QPS_RTS; ret = ib_cm_init_qp_attr(cm_id, &qp_attr, &qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to init QP attr for RTS: %d\n", ret); return 0; } ret = ib_modify_qp(qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify QP to RTS: %d\n", ret); return 0; } return 0; } static int ipoib_cm_send_rep(struct net_device *dev, struct ib_cm_id *cm_id, struct ib_qp *qp, struct ib_cm_req_event_param *req, unsigned psn) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_cm_data data = {}; struct ib_cm_rep_param rep = {}; data.qpn = cpu_to_be32(priv->qp->qp_num); data.mtu = cpu_to_be32(IPOIB_CM_BUF_SIZE); rep.private_data = &data; rep.private_data_len = sizeof data; rep.flow_control = 0; rep.rnr_retry_count = req->rnr_retry_count; rep.target_ack_delay = 20; /* FIXME */ rep.srq = 1; rep.qp_num = qp->qp_num; rep.starting_psn = psn; return ib_send_cm_rep(cm_id, &rep); } static int ipoib_cm_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event) { struct net_device *dev = cm_id->context; struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_cm_rx *p; unsigned psn; int ret; ipoib_dbg(priv, "REQ arrived\n"); p = kzalloc(sizeof *p, GFP_KERNEL); if (!p) return -ENOMEM; p->dev = dev; p->id = cm_id; cm_id->context = p; p->state = IPOIB_CM_RX_LIVE; p->jiffies = jiffies; INIT_LIST_HEAD(&p->list); p->qp = ipoib_cm_create_rx_qp(dev, p); if (IS_ERR(p->qp)) { ret = PTR_ERR(p->qp); goto err_qp; } psn = random32() & 0xffffff; ret = ipoib_cm_modify_rx_qp(dev, cm_id, p->qp, psn); if (ret) goto err_modify; spin_lock_irq(&priv->lock); queue_delayed_work(ipoib_workqueue, &priv->cm.stale_task, IPOIB_CM_RX_DELAY); /* Add this entry to passive ids list head, but do not re-add it * if IB_EVENT_QP_LAST_WQE_REACHED has moved it to flush list. */ p->jiffies = jiffies; if (p->state == IPOIB_CM_RX_LIVE) list_move(&p->list, &priv->cm.passive_ids); spin_unlock_irq(&priv->lock); ret = ipoib_cm_send_rep(dev, cm_id, p->qp, &event->param.req_rcvd, psn); if (ret) { ipoib_warn(priv, "failed to send REP: %d\n", ret); if (ib_modify_qp(p->qp, &ipoib_cm_err_attr, IB_QP_STATE)) ipoib_warn(priv, "unable to move qp to error state\n"); } return 0; err_modify: ib_destroy_qp(p->qp); err_qp: kfree(p); return ret; } static int ipoib_cm_rx_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event) { struct ipoib_cm_rx *p; struct ipoib_dev_priv *priv; switch (event->event) { case IB_CM_REQ_RECEIVED: return ipoib_cm_req_handler(cm_id, event); case IB_CM_DREQ_RECEIVED: p = cm_id->context; ib_send_cm_drep(cm_id, NULL, 0); /* Fall through */ case IB_CM_REJ_RECEIVED: p = cm_id->context; priv = netdev_priv(p->dev); if (ib_modify_qp(p->qp, &ipoib_cm_err_attr, IB_QP_STATE)) ipoib_warn(priv, "unable to move qp to error state\n"); /* Fall through */ default: return 0; } } /* Adjust length of skb with fragments to match received data */ static void skb_put_frags(struct sk_buff *skb, unsigned int hdr_space, unsigned int length, struct sk_buff *toskb) { int i, num_frags; unsigned int size; /* put header into skb */ size = min(length, hdr_space); skb->tail += size; skb->len += size; length -= size; num_frags = skb_shinfo(skb)->nr_frags; for (i = 0; i < num_frags; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (length == 0) { /* don't need this page */ skb_fill_page_desc(toskb, i, frag->page, 0, PAGE_SIZE); --skb_shinfo(skb)->nr_frags; } else { size = min(length, (unsigned) PAGE_SIZE); frag->size = size; skb->data_len += size; skb->truesize += size; skb->len += size; length -= size; } } } void ipoib_cm_handle_rx_wc(struct net_device *dev, struct ib_wc *wc) { struct ipoib_dev_priv *priv = netdev_priv(dev); unsigned int wr_id = wc->wr_id & ~IPOIB_CM_OP_SRQ; struct sk_buff *skb, *newskb; struct ipoib_cm_rx *p; unsigned long flags; u64 mapping[IPOIB_CM_RX_SG]; int frags; ipoib_dbg_data(priv, "cm recv completion: id %d, status: %d\n", wr_id, wc->status); if (unlikely(wr_id >= ipoib_recvq_size)) { if (wr_id == (IPOIB_CM_RX_DRAIN_WRID & ~IPOIB_CM_OP_SRQ)) { spin_lock_irqsave(&priv->lock, flags); list_splice_init(&priv->cm.rx_drain_list, &priv->cm.rx_reap_list); ipoib_cm_start_rx_drain(priv); queue_work(ipoib_workqueue, &priv->cm.rx_reap_task); spin_unlock_irqrestore(&priv->lock, flags); } else ipoib_warn(priv, "cm recv completion event with wrid %d (> %d)\n", wr_id, ipoib_recvq_size); return; } skb = priv->cm.srq_ring[wr_id].skb; if (unlikely(wc->status != IB_WC_SUCCESS)) { ipoib_dbg(priv, "cm recv error " "(status=%d, wrid=%d vend_err %x)\n", wc->status, wr_id, wc->vendor_err); ++priv->stats.rx_dropped; goto repost; } if (!likely(wr_id & IPOIB_CM_RX_UPDATE_MASK)) { p = wc->qp->qp_context; if (p && time_after_eq(jiffies, p->jiffies + IPOIB_CM_RX_UPDATE_TIME)) { spin_lock_irqsave(&priv->lock, flags); p->jiffies = jiffies; /* Move this entry to list head, but do not re-add it * if it has been moved out of list. */ if (p->state == IPOIB_CM_RX_LIVE) list_move(&p->list, &priv->cm.passive_ids); spin_unlock_irqrestore(&priv->lock, flags); } } frags = PAGE_ALIGN(wc->byte_len - min(wc->byte_len, (unsigned)IPOIB_CM_HEAD_SIZE)) / PAGE_SIZE; newskb = ipoib_cm_alloc_rx_skb(dev, wr_id, frags, mapping); if (unlikely(!newskb)) { /* * If we can't allocate a new RX buffer, dump * this packet and reuse the old buffer. */ ipoib_dbg(priv, "failed to allocate receive buffer %d\n", wr_id); ++priv->stats.rx_dropped; goto repost; } ipoib_cm_dma_unmap_rx(priv, frags, priv->cm.srq_ring[wr_id].mapping); memcpy(priv->cm.srq_ring[wr_id].mapping, mapping, (frags + 1) * sizeof *mapping); ipoib_dbg_data(priv, "received %d bytes, SLID 0x%04x\n", wc->byte_len, wc->slid); skb_put_frags(skb, IPOIB_CM_HEAD_SIZE, wc->byte_len, newskb); skb->protocol = ((struct ipoib_header *) skb->data)->proto; skb_reset_mac_header(skb); skb_pull(skb, IPOIB_ENCAP_LEN); dev->last_rx = jiffies; ++priv->stats.rx_packets; priv->stats.rx_bytes += skb->len; skb->dev = dev; /* XXX get correct PACKET_ type here */ skb->pkt_type = PACKET_HOST; netif_receive_skb(skb); repost: if (unlikely(ipoib_cm_post_receive(dev, wr_id))) ipoib_warn(priv, "ipoib_cm_post_receive failed " "for buf %d\n", wr_id); } static inline int post_send(struct ipoib_dev_priv *priv, struct ipoib_cm_tx *tx, unsigned int wr_id, u64 addr, int len) { struct ib_send_wr *bad_wr; priv->tx_sge.addr = addr; priv->tx_sge.length = len; priv->tx_wr.wr_id = wr_id; return ib_post_send(tx->qp, &priv->tx_wr, &bad_wr); } void ipoib_cm_send(struct net_device *dev, struct sk_buff *skb, struct ipoib_cm_tx *tx) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_tx_buf *tx_req; u64 addr; if (unlikely(skb->len > tx->mtu)) { ipoib_warn(priv, "packet len %d (> %d) too long to send, dropping\n", skb->len, tx->mtu); ++priv->stats.tx_dropped; ++priv->stats.tx_errors; ipoib_cm_skb_too_long(dev, skb, tx->mtu - IPOIB_ENCAP_LEN); return; } ipoib_dbg_data(priv, "sending packet: head 0x%x length %d connection 0x%x\n", tx->tx_head, skb->len, tx->qp->qp_num); /* * We put the skb into the tx_ring _before_ we call post_send() * because it's entirely possible that the completion handler will * run before we execute anything after the post_send(). That * means we have to make sure everything is properly recorded and * our state is consistent before we call post_send(). */ tx_req = &tx->tx_ring[tx->tx_head & (ipoib_sendq_size - 1)]; tx_req->skb = skb; addr = ib_dma_map_single(priv->ca, skb->data, skb->len, DMA_TO_DEVICE); if (unlikely(ib_dma_mapping_error(priv->ca, addr))) { ++priv->stats.tx_errors; dev_kfree_skb_any(skb); return; } tx_req->mapping = addr; if (unlikely(post_send(priv, tx, tx->tx_head & (ipoib_sendq_size - 1), addr, skb->len))) { ipoib_warn(priv, "post_send failed\n"); ++priv->stats.tx_errors; ib_dma_unmap_single(priv->ca, addr, skb->len, DMA_TO_DEVICE); dev_kfree_skb_any(skb); } else { dev->trans_start = jiffies; ++tx->tx_head; if (tx->tx_head - tx->tx_tail == ipoib_sendq_size) { ipoib_dbg(priv, "TX ring 0x%x full, stopping kernel net queue\n", tx->qp->qp_num); netif_stop_queue(dev); set_bit(IPOIB_FLAG_NETIF_STOPPED, &tx->flags); } } } static void ipoib_cm_handle_tx_wc(struct net_device *dev, struct ipoib_cm_tx *tx, struct ib_wc *wc) { struct ipoib_dev_priv *priv = netdev_priv(dev); unsigned int wr_id = wc->wr_id; struct ipoib_tx_buf *tx_req; unsigned long flags; ipoib_dbg_data(priv, "cm send completion: id %d, status: %d\n", wr_id, wc->status); if (unlikely(wr_id >= ipoib_sendq_size)) { ipoib_warn(priv, "cm send completion event with wrid %d (> %d)\n", wr_id, ipoib_sendq_size); return; } tx_req = &tx->tx_ring[wr_id]; ib_dma_unmap_single(priv->ca, tx_req->mapping, tx_req->skb->len, DMA_TO_DEVICE); /* FIXME: is this right? Shouldn't we only increment on success? */ ++priv->stats.tx_packets; priv->stats.tx_bytes += tx_req->skb->len; dev_kfree_skb_any(tx_req->skb); spin_lock_irqsave(&priv->tx_lock, flags); ++tx->tx_tail; if (unlikely(test_bit(IPOIB_FLAG_NETIF_STOPPED, &tx->flags)) && tx->tx_head - tx->tx_tail <= ipoib_sendq_size >> 1) { clear_bit(IPOIB_FLAG_NETIF_STOPPED, &tx->flags); netif_wake_queue(dev); } if (wc->status != IB_WC_SUCCESS && wc->status != IB_WC_WR_FLUSH_ERR) { struct ipoib_neigh *neigh; ipoib_dbg(priv, "failed cm send event " "(status=%d, wrid=%d vend_err %x)\n", wc->status, wr_id, wc->vendor_err); spin_lock(&priv->lock); neigh = tx->neigh; if (neigh) { neigh->cm = NULL; list_del(&neigh->list); if (neigh->ah) ipoib_put_ah(neigh->ah); ipoib_neigh_free(dev, neigh); tx->neigh = NULL; } /* queue would be re-started anyway when TX is destroyed, * but it makes sense to do it ASAP here. */ if (test_and_clear_bit(IPOIB_FLAG_NETIF_STOPPED, &tx->flags)) netif_wake_queue(dev); if (test_and_clear_bit(IPOIB_FLAG_INITIALIZED, &tx->flags)) { list_move(&tx->list, &priv->cm.reap_list); queue_work(ipoib_workqueue, &priv->cm.reap_task); } clear_bit(IPOIB_FLAG_OPER_UP, &tx->flags); spin_unlock(&priv->lock); } spin_unlock_irqrestore(&priv->tx_lock, flags); } static void ipoib_cm_tx_completion(struct ib_cq *cq, void *tx_ptr) { struct ipoib_cm_tx *tx = tx_ptr; int n, i; ib_req_notify_cq(cq, IB_CQ_NEXT_COMP); do { n = ib_poll_cq(cq, IPOIB_NUM_WC, tx->ibwc); for (i = 0; i < n; ++i) ipoib_cm_handle_tx_wc(tx->dev, tx, tx->ibwc + i); } while (n == IPOIB_NUM_WC); } int ipoib_cm_dev_open(struct net_device *dev) { struct ipoib_dev_priv *priv = netdev_priv(dev); int ret; if (!IPOIB_CM_SUPPORTED(dev->dev_addr)) return 0; priv->cm.id = ib_create_cm_id(priv->ca, ipoib_cm_rx_handler, dev); if (IS_ERR(priv->cm.id)) { printk(KERN_WARNING "%s: failed to create CM ID\n", priv->ca->name); ret = PTR_ERR(priv->cm.id); goto err_cm; } ret = ib_cm_listen(priv->cm.id, cpu_to_be64(IPOIB_CM_IETF_ID | priv->qp->qp_num), 0, NULL); if (ret) { printk(KERN_WARNING "%s: failed to listen on ID 0x%llx\n", priv->ca->name, IPOIB_CM_IETF_ID | priv->qp->qp_num); goto err_listen; } return 0; err_listen: ib_destroy_cm_id(priv->cm.id); err_cm: priv->cm.id = NULL; return ret; } void ipoib_cm_dev_stop(struct net_device *dev) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_cm_rx *p, *n; unsigned long begin; LIST_HEAD(list); int ret; if (!IPOIB_CM_SUPPORTED(dev->dev_addr) || !priv->cm.id) return; ib_destroy_cm_id(priv->cm.id); priv->cm.id = NULL; spin_lock_irq(&priv->lock); while (!list_empty(&priv->cm.passive_ids)) { p = list_entry(priv->cm.passive_ids.next, typeof(*p), list); list_move(&p->list, &priv->cm.rx_error_list); p->state = IPOIB_CM_RX_ERROR; spin_unlock_irq(&priv->lock); ret = ib_modify_qp(p->qp, &ipoib_cm_err_attr, IB_QP_STATE); if (ret) ipoib_warn(priv, "unable to move qp to error state: %d\n", ret); spin_lock_irq(&priv->lock); } /* Wait for all RX to be drained */ begin = jiffies; while (!list_empty(&priv->cm.rx_error_list) || !list_empty(&priv->cm.rx_flush_list) || !list_empty(&priv->cm.rx_drain_list)) { if (time_after(jiffies, begin + 5 * HZ)) { ipoib_warn(priv, "RX drain timing out\n"); /* * assume the HW is wedged and just free up everything. */ list_splice_init(&priv->cm.rx_flush_list, &list); list_splice_init(&priv->cm.rx_error_list, &list); list_splice_init(&priv->cm.rx_drain_list, &list); break; } spin_unlock_irq(&priv->lock); msleep(1); ipoib_drain_cq(dev); spin_lock_irq(&priv->lock); } list_splice_init(&priv->cm.rx_reap_list, &list); spin_unlock_irq(&priv->lock); list_for_each_entry_safe(p, n, &list, list) { ib_destroy_cm_id(p->id); ib_destroy_qp(p->qp); kfree(p); } cancel_delayed_work(&priv->cm.stale_task); } static int ipoib_cm_rep_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event) { struct ipoib_cm_tx *p = cm_id->context; struct ipoib_dev_priv *priv = netdev_priv(p->dev); struct ipoib_cm_data *data = event->private_data; struct sk_buff_head skqueue; struct ib_qp_attr qp_attr; int qp_attr_mask, ret; struct sk_buff *skb; p->mtu = be32_to_cpu(data->mtu); if (p->mtu <= IPOIB_ENCAP_LEN) { ipoib_warn(priv, "Rejecting connection: mtu %d <= %d\n", p->mtu, IPOIB_ENCAP_LEN); return -EINVAL; } qp_attr.qp_state = IB_QPS_RTR; ret = ib_cm_init_qp_attr(cm_id, &qp_attr, &qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to init QP attr for RTR: %d\n", ret); return ret; } qp_attr.rq_psn = 0 /* FIXME */; ret = ib_modify_qp(p->qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify QP to RTR: %d\n", ret); return ret; } qp_attr.qp_state = IB_QPS_RTS; ret = ib_cm_init_qp_attr(cm_id, &qp_attr, &qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to init QP attr for RTS: %d\n", ret); return ret; } ret = ib_modify_qp(p->qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify QP to RTS: %d\n", ret); return ret; } skb_queue_head_init(&skqueue); spin_lock_irq(&priv->lock); set_bit(IPOIB_FLAG_OPER_UP, &p->flags); if (p->neigh) while ((skb = __skb_dequeue(&p->neigh->queue))) __skb_queue_tail(&skqueue, skb); spin_unlock_irq(&priv->lock); while ((skb = __skb_dequeue(&skqueue))) { skb->dev = p->dev; if (dev_queue_xmit(skb)) ipoib_warn(priv, "dev_queue_xmit failed " "to requeue packet\n"); } ret = ib_send_cm_rtu(cm_id, NULL, 0); if (ret) { ipoib_warn(priv, "failed to send RTU: %d\n", ret); return ret; } return 0; } static struct ib_qp *ipoib_cm_create_tx_qp(struct net_device *dev, struct ib_cq *cq) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_qp_init_attr attr = {}; attr.recv_cq = priv->cq; attr.srq = priv->cm.srq; attr.cap.max_send_wr = ipoib_sendq_size; attr.cap.max_send_sge = 1; attr.sq_sig_type = IB_SIGNAL_ALL_WR; attr.qp_type = IB_QPT_RC; attr.send_cq = cq; return ib_create_qp(priv->pd, &attr); } static int ipoib_cm_send_req(struct net_device *dev, struct ib_cm_id *id, struct ib_qp *qp, u32 qpn, struct ib_sa_path_rec *pathrec) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_cm_data data = {}; struct ib_cm_req_param req = {}; data.qpn = cpu_to_be32(priv->qp->qp_num); data.mtu = cpu_to_be32(IPOIB_CM_BUF_SIZE); req.primary_path = pathrec; req.alternate_path = NULL; req.service_id = cpu_to_be64(IPOIB_CM_IETF_ID | qpn); req.qp_num = qp->qp_num; req.qp_type = qp->qp_type; req.private_data = &data; req.private_data_len = sizeof data; req.flow_control = 0; req.starting_psn = 0; /* FIXME */ /* * Pick some arbitrary defaults here; we could make these * module parameters if anyone cared about setting them. */ req.responder_resources = 4; req.remote_cm_response_timeout = 20; req.local_cm_response_timeout = 20; req.retry_count = 0; /* RFC draft warns against retries */ req.rnr_retry_count = 0; /* RFC draft warns against retries */ req.max_cm_retries = 15; req.srq = 1; return ib_send_cm_req(id, &req); } static int ipoib_cm_modify_tx_init(struct net_device *dev, struct ib_cm_id *cm_id, struct ib_qp *qp) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_qp_attr qp_attr; int qp_attr_mask, ret; ret = ib_find_cached_pkey(priv->ca, priv->port, priv->pkey, &qp_attr.pkey_index); if (ret) { ipoib_warn(priv, "pkey 0x%x not in cache: %d\n", priv->pkey, ret); return ret; } qp_attr.qp_state = IB_QPS_INIT; qp_attr.qp_access_flags = IB_ACCESS_LOCAL_WRITE; qp_attr.port_num = priv->port; qp_attr_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS | IB_QP_PKEY_INDEX | IB_QP_PORT; ret = ib_modify_qp(qp, &qp_attr, qp_attr_mask); if (ret) { ipoib_warn(priv, "failed to modify tx QP to INIT: %d\n", ret); return ret; } return 0; } static int ipoib_cm_tx_init(struct ipoib_cm_tx *p, u32 qpn, struct ib_sa_path_rec *pathrec) { struct ipoib_dev_priv *priv = netdev_priv(p->dev); int ret; p->tx_ring = kzalloc(ipoib_sendq_size * sizeof *p->tx_ring, GFP_KERNEL); if (!p->tx_ring) { ipoib_warn(priv, "failed to allocate tx ring\n"); ret = -ENOMEM; goto err_tx; } p->cq = ib_create_cq(priv->ca, ipoib_cm_tx_completion, NULL, p, ipoib_sendq_size + 1, 0); if (IS_ERR(p->cq)) { ret = PTR_ERR(p->cq); ipoib_warn(priv, "failed to allocate tx cq: %d\n", ret); goto err_cq; } ret = ib_req_notify_cq(p->cq, IB_CQ_NEXT_COMP); if (ret) { ipoib_warn(priv, "failed to request completion notification: %d\n", ret); goto err_req_notify; } p->qp = ipoib_cm_create_tx_qp(p->dev, p->cq); if (IS_ERR(p->qp)) { ret = PTR_ERR(p->qp); ipoib_warn(priv, "failed to allocate tx qp: %d\n", ret); goto err_qp; } p->id = ib_create_cm_id(priv->ca, ipoib_cm_tx_handler, p); if (IS_ERR(p->id)) { ret = PTR_ERR(p->id); ipoib_warn(priv, "failed to create tx cm id: %d\n", ret); goto err_id; } ret = ipoib_cm_modify_tx_init(p->dev, p->id, p->qp); if (ret) { ipoib_warn(priv, "failed to modify tx qp to rtr: %d\n", ret); goto err_modify; } ret = ipoib_cm_send_req(p->dev, p->id, p->qp, qpn, pathrec); if (ret) { ipoib_warn(priv, "failed to send cm req: %d\n", ret); goto err_send_cm; } ipoib_dbg(priv, "Request connection 0x%x for gid " IPOIB_GID_FMT " qpn 0x%x\n", p->qp->qp_num, IPOIB_GID_ARG(pathrec->dgid), qpn); return 0; err_send_cm: err_modify: ib_destroy_cm_id(p->id); err_id: p->id = NULL; ib_destroy_qp(p->qp); err_req_notify: err_qp: p->qp = NULL; ib_destroy_cq(p->cq); err_cq: p->cq = NULL; err_tx: return ret; } static void ipoib_cm_tx_destroy(struct ipoib_cm_tx *p) { struct ipoib_dev_priv *priv = netdev_priv(p->dev); struct ipoib_tx_buf *tx_req; ipoib_dbg(priv, "Destroy active connection 0x%x head 0x%x tail 0x%x\n", p->qp ? p->qp->qp_num : 0, p->tx_head, p->tx_tail); if (p->id) ib_destroy_cm_id(p->id); if (p->qp) ib_destroy_qp(p->qp); if (p->cq) ib_destroy_cq(p->cq); if (test_bit(IPOIB_FLAG_NETIF_STOPPED, &p->flags)) netif_wake_queue(p->dev); if (p->tx_ring) { while ((int) p->tx_tail - (int) p->tx_head < 0) { tx_req = &p->tx_ring[p->tx_tail & (ipoib_sendq_size - 1)]; ib_dma_unmap_single(priv->ca, tx_req->mapping, tx_req->skb->len, DMA_TO_DEVICE); dev_kfree_skb_any(tx_req->skb); ++p->tx_tail; } kfree(p->tx_ring); } kfree(p); } static int ipoib_cm_tx_handler(struct ib_cm_id *cm_id, struct ib_cm_event *event) { struct ipoib_cm_tx *tx = cm_id->context; struct ipoib_dev_priv *priv = netdev_priv(tx->dev); struct net_device *dev = priv->dev; struct ipoib_neigh *neigh; int ret; switch (event->event) { case IB_CM_DREQ_RECEIVED: ipoib_dbg(priv, "DREQ received.\n"); ib_send_cm_drep(cm_id, NULL, 0); break; case IB_CM_REP_RECEIVED: ipoib_dbg(priv, "REP received.\n"); ret = ipoib_cm_rep_handler(cm_id, event); if (ret) ib_send_cm_rej(cm_id, IB_CM_REJ_CONSUMER_DEFINED, NULL, 0, NULL, 0); break; case IB_CM_REQ_ERROR: case IB_CM_REJ_RECEIVED: case IB_CM_TIMEWAIT_EXIT: ipoib_dbg(priv, "CM error %d.\n", event->event); spin_lock_irq(&priv->tx_lock); spin_lock(&priv->lock); neigh = tx->neigh; if (neigh) { neigh->cm = NULL; list_del(&neigh->list); if (neigh->ah) ipoib_put_ah(neigh->ah); ipoib_neigh_free(dev, neigh); tx->neigh = NULL; } if (test_and_clear_bit(IPOIB_FLAG_INITIALIZED, &tx->flags)) { list_move(&tx->list, &priv->cm.reap_list); queue_work(ipoib_workqueue, &priv->cm.reap_task); } spin_unlock(&priv->lock); spin_unlock_irq(&priv->tx_lock); break; default: break; } return 0; } struct ipoib_cm_tx *ipoib_cm_create_tx(struct net_device *dev, struct ipoib_path *path, struct ipoib_neigh *neigh) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ipoib_cm_tx *tx; tx = kzalloc(sizeof *tx, GFP_ATOMIC); if (!tx) return NULL; neigh->cm = tx; tx->neigh = neigh; tx->path = path; tx->dev = dev; list_add(&tx->list, &priv->cm.start_list); set_bit(IPOIB_FLAG_INITIALIZED, &tx->flags); queue_work(ipoib_workqueue, &priv->cm.start_task); return tx; } void ipoib_cm_destroy_tx(struct ipoib_cm_tx *tx) { struct ipoib_dev_priv *priv = netdev_priv(tx->dev); if (test_and_clear_bit(IPOIB_FLAG_INITIALIZED, &tx->flags)) { list_move(&tx->list, &priv->cm.reap_list); queue_work(ipoib_workqueue, &priv->cm.reap_task); ipoib_dbg(priv, "Reap connection for gid " IPOIB_GID_FMT "\n", IPOIB_GID_ARG(tx->neigh->dgid)); tx->neigh = NULL; } } static void ipoib_cm_tx_start(struct work_struct *work) { struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv, cm.start_task); struct net_device *dev = priv->dev; struct ipoib_neigh *neigh; struct ipoib_cm_tx *p; unsigned long flags; int ret; struct ib_sa_path_rec pathrec; u32 qpn; spin_lock_irqsave(&priv->tx_lock, flags); spin_lock(&priv->lock); while (!list_empty(&priv->cm.start_list)) { p = list_entry(priv->cm.start_list.next, typeof(*p), list); list_del_init(&p->list); neigh = p->neigh; qpn = IPOIB_QPN(neigh->neighbour->ha); memcpy(&pathrec, &p->path->pathrec, sizeof pathrec); spin_unlock(&priv->lock); spin_unlock_irqrestore(&priv->tx_lock, flags); ret = ipoib_cm_tx_init(p, qpn, &pathrec); spin_lock_irqsave(&priv->tx_lock, flags); spin_lock(&priv->lock); if (ret) { neigh = p->neigh; if (neigh) { neigh->cm = NULL; list_del(&neigh->list); if (neigh->ah) ipoib_put_ah(neigh->ah); ipoib_neigh_free(dev, neigh); } list_del(&p->list); kfree(p); } } spin_unlock(&priv->lock); spin_unlock_irqrestore(&priv->tx_lock, flags); } static void ipoib_cm_tx_reap(struct work_struct *work) { struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv, cm.reap_task); struct ipoib_cm_tx *p; spin_lock_irq(&priv->tx_lock); spin_lock(&priv->lock); while (!list_empty(&priv->cm.reap_list)) { p = list_entry(priv->cm.reap_list.next, typeof(*p), list); list_del(&p->list); spin_unlock(&priv->lock); spin_unlock_irq(&priv->tx_lock); ipoib_cm_tx_destroy(p); spin_lock_irq(&priv->tx_lock); spin_lock(&priv->lock); } spin_unlock(&priv->lock); spin_unlock_irq(&priv->tx_lock); } static void ipoib_cm_skb_reap(struct work_struct *work) { struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv, cm.skb_task); struct net_device *dev = priv->dev; struct sk_buff *skb; unsigned mtu = priv->mcast_mtu; spin_lock_irq(&priv->tx_lock); spin_lock(&priv->lock); while ((skb = skb_dequeue(&priv->cm.skb_queue))) { spin_unlock(&priv->lock); spin_unlock_irq(&priv->tx_lock); if (skb->protocol == htons(ETH_P_IP)) icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, htonl(mtu)); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) else if (skb->protocol == htons(ETH_P_IPV6)) icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu, dev); #endif dev_kfree_skb_any(skb); spin_lock_irq(&priv->tx_lock); spin_lock(&priv->lock); } spin_unlock(&priv->lock); spin_unlock_irq(&priv->tx_lock); } void ipoib_cm_skb_too_long(struct net_device* dev, struct sk_buff *skb, unsigned int mtu) { struct ipoib_dev_priv *priv = netdev_priv(dev); int e = skb_queue_empty(&priv->cm.skb_queue); if (skb->dst) skb->dst->ops->update_pmtu(skb->dst, mtu); skb_queue_tail(&priv->cm.skb_queue, skb); if (e) queue_work(ipoib_workqueue, &priv->cm.skb_task); } static void ipoib_cm_rx_reap(struct work_struct *work) { struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv, cm.rx_reap_task); struct ipoib_cm_rx *p, *n; LIST_HEAD(list); spin_lock_irq(&priv->lock); list_splice_init(&priv->cm.rx_reap_list, &list); spin_unlock_irq(&priv->lock); list_for_each_entry_safe(p, n, &list, list) { ib_destroy_cm_id(p->id); ib_destroy_qp(p->qp); kfree(p); } } static void ipoib_cm_stale_task(struct work_struct *work) { struct ipoib_dev_priv *priv = container_of(work, struct ipoib_dev_priv, cm.stale_task.work); struct ipoib_cm_rx *p; int ret; spin_lock_irq(&priv->lock); while (!list_empty(&priv->cm.passive_ids)) { /* List is sorted by LRU, start from tail, * stop when we see a recently used entry */ p = list_entry(priv->cm.passive_ids.prev, typeof(*p), list); if (time_before_eq(jiffies, p->jiffies + IPOIB_CM_RX_TIMEOUT)) break; list_move(&p->list, &priv->cm.rx_error_list); p->state = IPOIB_CM_RX_ERROR; spin_unlock_irq(&priv->lock); ret = ib_modify_qp(p->qp, &ipoib_cm_err_attr, IB_QP_STATE); if (ret) ipoib_warn(priv, "unable to move qp to error state: %d\n", ret); spin_lock_irq(&priv->lock); } if (!list_empty(&priv->cm.passive_ids)) queue_delayed_work(ipoib_workqueue, &priv->cm.stale_task, IPOIB_CM_RX_DELAY); spin_unlock_irq(&priv->lock); } static ssize_t show_mode(struct device *d, struct device_attribute *attr, char *buf) { struct ipoib_dev_priv *priv = netdev_priv(to_net_dev(d)); if (test_bit(IPOIB_FLAG_ADMIN_CM, &priv->flags)) return sprintf(buf, "connected\n"); else return sprintf(buf, "datagram\n"); } static ssize_t set_mode(struct device *d, struct device_attribute *attr, const char *buf, size_t count) { struct net_device *dev = to_net_dev(d); struct ipoib_dev_priv *priv = netdev_priv(dev); /* flush paths if we switch modes so that connections are restarted */ if (IPOIB_CM_SUPPORTED(dev->dev_addr) && !strcmp(buf, "connected\n")) { set_bit(IPOIB_FLAG_ADMIN_CM, &priv->flags); ipoib_warn(priv, "enabling connected mode " "will cause multicast packet drops\n"); ipoib_flush_paths(dev); return count; } if (!strcmp(buf, "datagram\n")) { clear_bit(IPOIB_FLAG_ADMIN_CM, &priv->flags); dev->mtu = min(priv->mcast_mtu, dev->mtu); ipoib_flush_paths(dev); return count; } return -EINVAL; } static DEVICE_ATTR(mode, S_IWUSR | S_IRUGO, show_mode, set_mode); int ipoib_cm_add_mode_attr(struct net_device *dev) { return device_create_file(&dev->dev, &dev_attr_mode); } int ipoib_cm_dev_init(struct net_device *dev) { struct ipoib_dev_priv *priv = netdev_priv(dev); struct ib_srq_init_attr srq_init_attr = { .attr = { .max_wr = ipoib_recvq_size, .max_sge = IPOIB_CM_RX_SG } }; int ret, i; INIT_LIST_HEAD(&priv->cm.passive_ids); INIT_LIST_HEAD(&priv->cm.reap_list); INIT_LIST_HEAD(&priv->cm.start_list); INIT_LIST_HEAD(&priv->cm.rx_error_list); INIT_LIST_HEAD(&priv->cm.rx_flush_list); INIT_LIST_HEAD(&priv->cm.rx_drain_list); INIT_LIST_HEAD(&priv->cm.rx_reap_list); INIT_WORK(&priv->cm.start_task, ipoib_cm_tx_start); INIT_WORK(&priv->cm.reap_task, ipoib_cm_tx_reap); INIT_WORK(&priv->cm.skb_task, ipoib_cm_skb_reap); INIT_WORK(&priv->cm.rx_reap_task, ipoib_cm_rx_reap); INIT_DELAYED_WORK(&priv->cm.stale_task, ipoib_cm_stale_task); skb_queue_head_init(&priv->cm.skb_queue); priv->cm.srq = ib_create_srq(priv->pd, &srq_init_attr); if (IS_ERR(priv->cm.srq)) { ret = PTR_ERR(priv->cm.srq); priv->cm.srq = NULL; return ret; } priv->cm.srq_ring = kzalloc(ipoib_recvq_size * sizeof *priv->cm.srq_ring, GFP_KERNEL); if (!priv->cm.srq_ring) { printk(KERN_WARNING "%s: failed to allocate CM ring (%d entries)\n", priv->ca->name, ipoib_recvq_size); ipoib_cm_dev_cleanup(dev); return -ENOMEM; } for (i = 0; i < IPOIB_CM_RX_SG; ++i) priv->cm.rx_sge[i].lkey = priv->mr->lkey; priv->cm.rx_sge[0].length = IPOIB_CM_HEAD_SIZE; for (i = 1; i < IPOIB_CM_RX_SG; ++i) priv->cm.rx_sge[i].length = PAGE_SIZE; priv->cm.rx_wr.next = NULL; priv->cm.rx_wr.sg_list = priv->cm.rx_sge; priv->cm.rx_wr.num_sge = IPOIB_CM_RX_SG; for (i = 0; i < ipoib_recvq_size; ++i) { if (!ipoib_cm_alloc_rx_skb(dev, i, IPOIB_CM_RX_SG - 1, priv->cm.srq_ring[i].mapping)) { ipoib_warn(priv, "failed to allocate receive buffer %d\n", i); ipoib_cm_dev_cleanup(dev); return -ENOMEM; } if (ipoib_cm_post_receive(dev, i)) { ipoib_warn(priv, "ipoib_ib_post_receive failed for buf %d\n", i); ipoib_cm_dev_cleanup(dev); return -EIO; } } priv->dev->dev_addr[0] = IPOIB_FLAGS_RC; return 0; } void ipoib_cm_dev_cleanup(struct net_device *dev) { struct ipoib_dev_priv *priv = netdev_priv(dev); int i, ret; if (!priv->cm.srq) return; ipoib_dbg(priv, "Cleanup ipoib connected mode.\n"); ret = ib_destroy_srq(priv->cm.srq); if (ret) ipoib_warn(priv, "ib_destroy_srq failed: %d\n", ret); priv->cm.srq = NULL; if (!priv->cm.srq_ring) return; for (i = 0; i < ipoib_recvq_size; ++i) if (priv->cm.srq_ring[i].skb) { ipoib_cm_dma_unmap_rx(priv, IPOIB_CM_RX_SG - 1, priv->cm.srq_ring[i].mapping); dev_kfree_skb_any(priv->cm.srq_ring[i].skb); priv->cm.srq_ring[i].skb = NULL; } kfree(priv->cm.srq_ring); priv->cm.srq_ring = NULL; }
gpl-2.0
zhengsjembest/linux_am335x
linux-3.2.0-psp04.06.00.08.sdk/arch/arm/mach-omap2/prminst33xx.h
1200
/* * AM33XX Power/Reset Management (PRM) function prototypes * * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation version 2. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __ARCH_ASM_MACH_OMAP2_PRMINST33XX_H #define __ARCH_ASM_MACH_OMAP2_PRMINST33XX_H extern u32 am33xx_prminst_read_inst_reg(s16 inst, u16 idx); extern void am33xx_prminst_write_inst_reg(u32 val, s16 inst, u16 idx); extern u32 am33xx_prminst_rmw_inst_reg_bits(u32 mask, u32 bits, s16 inst, s16 idx); extern u32 am33xx_prminst_is_hardreset_asserted(s16 domain, s16 idx, u32 mask); extern int am33xx_prminst_assert_hardreset(s16 prm_mod, u8 shift); extern int am33xx_prminst_deassert_hardreset(s16 prm_mod, u8 rst_shift, u8 st_shift); extern void am33xx_prm_global_warm_sw_reset(void); #endif
gpl-2.0
fwmiller/Conserver-Freescale-Linux-U-boot
rpm/BUILD/u-boot-2009.08/drivers/net/lan91c96.c
22741
/*------------------------------------------------------------------------ * lan91c96.c * This is a driver for SMSC's LAN91C96 single-chip Ethernet device, based * on the SMC91111 driver from U-boot. * * (C) Copyright 2002 * Sysgo Real-Time Solutions, GmbH <www.elinos.com> * Rolf Offermanns <[email protected]> * * Copyright (C) 2001 Standard Microsystems Corporation (SMSC) * Developed by Simple Network Magic Corporation (SNMC) * Copyright (C) 1996 by Erik Stahlman (ES) * * 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 * * Information contained in this file was obtained from the LAN91C96 * manual from SMC. To get a copy, if you really want one, you can find * information under www.smsc.com. * * * "Features" of the SMC chip: * 6144 byte packet memory. ( for the 91C96 ) * EEPROM for configuration * AUI/TP selection ( mine has 10Base2/10BaseT select ) * * Arguments: * io = for the base address * irq = for the IRQ * * author: * Erik Stahlman ( [email protected] ) * Daris A Nevil ( [email protected] ) * * * Hardware multicast code from Peter Cammaert ( [email protected] ) * * Sources: * o SMSC LAN91C96 databook (www.smsc.com) * o smc91111.c (u-boot driver) * o smc9194.c (linux kernel driver) * o lan91c96.c (Intel Diagnostic Manager driver) * * History: * 04/30/03 Mathijs Haarman Modified smc91111.c (u-boot version) * for lan91c96 *--------------------------------------------------------------------------- */ #include <common.h> #include <command.h> #include "lan91c96.h" #include <net.h> /*------------------------------------------------------------------------ * * Configuration options, for the experienced user to change. * -------------------------------------------------------------------------*/ /* Use power-down feature of the chip */ #define POWER_DOWN 0 /* * Wait time for memory to be free. This probably shouldn't be * tuned that much, as waiting for this means nothing else happens * in the system */ #define MEMORY_WAIT_TIME 16 #define SMC_DEBUG 0 #if (SMC_DEBUG > 2 ) #define PRINTK3(args...) printf(args) #else #define PRINTK3(args...) #endif #if SMC_DEBUG > 1 #define PRINTK2(args...) printf(args) #else #define PRINTK2(args...) #endif #ifdef SMC_DEBUG #define PRINTK(args...) printf(args) #else #define PRINTK(args...) #endif /*------------------------------------------------------------------------ * * The internal workings of the driver. If you are changing anything * here with the SMC stuff, you should have the datasheet and know * what you are doing. * *------------------------------------------------------------------------ */ #define CARDNAME "LAN91C96" #define SMC_BASE_ADDRESS CONFIG_LAN91C96_BASE #define SMC_DEV_NAME "LAN91C96" #define SMC_ALLOC_MAX_TRY 5 #define SMC_TX_TIMEOUT 30 #define ETH_ZLEN 60 #ifdef CONFIG_LAN91C96_USE_32_BIT #define USE_32_BIT 1 #else #undef USE_32_BIT #endif /*----------------------------------------------------------------- * * The driver can be entered at any of the following entry points. * *----------------------------------------------------------------- */ extern int eth_init (bd_t * bd); extern void eth_halt (void); extern int eth_rx (void); extern int eth_send (volatile void *packet, int length); #if 0 static int smc_hw_init (void); #endif /* * This is called by register_netdev(). It is responsible for * checking the portlist for the SMC9000 series chipset. If it finds * one, then it will initialize the device, find the hardware information, * and sets up the appropriate device parameters. * NOTE: Interrupts are *OFF* when this procedure is called. * * NB:This shouldn't be static since it is referred to externally. */ int smc_init (void); /* * This is called by unregister_netdev(). It is responsible for * cleaning up before the driver is finally unregistered and discarded. */ void smc_destructor (void); /* * The kernel calls this function when someone wants to use the device, * typically 'ifconfig ethX up'. */ static int smc_open (bd_t *bd); /* * This is called by the kernel in response to 'ifconfig ethX down'. It * is responsible for cleaning up everything that the open routine * does, and maybe putting the card into a powerdown state. */ static int smc_close (void); /* * This is a separate procedure to handle the receipt of a packet, to * leave the interrupt code looking slightly cleaner */ static int smc_rcv (void); /* See if a MAC address is defined in the current environment. If so use it. If not . print a warning and set the environment and other globals with the default. . If an EEPROM is present it really should be consulted. */ int smc_get_ethaddr(bd_t *bd); int get_rom_mac(unsigned char *v_rom_mac); /* ------------------------------------------------------------ * Internal routines * ------------------------------------------------------------ */ static unsigned char smc_mac_addr[] = { 0xc0, 0x00, 0x00, 0x1b, 0x62, 0x9c }; /* * This function must be called before smc_open() if you want to override * the default mac address. */ void smc_set_mac_addr (const unsigned char *addr) { int i; for (i = 0; i < sizeof (smc_mac_addr); i++) { smc_mac_addr[i] = addr[i]; } } /* * smc_get_macaddr is no longer used. If you want to override the default * mac address, call smc_get_mac_addr as a part of the board initialisation. */ #if 0 void smc_get_macaddr (byte * addr) { /* MAC ADDRESS AT FLASHBLOCK 1 / OFFSET 0x10 */ unsigned char *dnp1110_mac = (unsigned char *) (0xE8000000 + 0x20010); int i; for (i = 0; i < 6; i++) { addr[0] = *(dnp1110_mac + 0); addr[1] = *(dnp1110_mac + 1); addr[2] = *(dnp1110_mac + 2); addr[3] = *(dnp1110_mac + 3); addr[4] = *(dnp1110_mac + 4); addr[5] = *(dnp1110_mac + 5); } } #endif /* 0 */ /*********************************************** * Show available memory * ***********************************************/ void dump_memory_info (void) { word mem_info; word old_bank; old_bank = SMC_inw (LAN91C96_BANK_SELECT) & 0xF; SMC_SELECT_BANK (0); mem_info = SMC_inw (LAN91C96_MIR); PRINTK2 ("Memory: %4d available\n", (mem_info >> 8) * 2048); SMC_SELECT_BANK (old_bank); } /* * A rather simple routine to print out a packet for debugging purposes. */ #if SMC_DEBUG > 2 static void print_packet (byte *, int); #endif /* #define tx_done(dev) 1 */ /* this does a soft reset on the device */ static void smc_reset (void); /* Enable Interrupts, Receive, and Transmit */ static void smc_enable (void); /* this puts the device in an inactive state */ static void smc_shutdown (void); static int poll4int (byte mask, int timeout) { int tmo = get_timer (0) + timeout * CONFIG_SYS_HZ; int is_timeout = 0; word old_bank = SMC_inw (LAN91C96_BANK_SELECT); PRINTK2 ("Polling...\n"); SMC_SELECT_BANK (2); while ((SMC_inw (LAN91C96_INT_STATS) & mask) == 0) { if (get_timer (0) >= tmo) { is_timeout = 1; break; } } /* restore old bank selection */ SMC_SELECT_BANK (old_bank); if (is_timeout) return 1; else return 0; } /* * Function: smc_reset( void ) * Purpose: * This sets the SMC91111 chip to its normal state, hopefully from whatever * mess that any other DOS driver has put it in. * * Maybe I should reset more registers to defaults in here? SOFTRST should * do that for me. * * Method: * 1. send a SOFT RESET * 2. wait for it to finish * 3. enable autorelease mode * 4. reset the memory management unit * 5. clear all interrupts * */ static void smc_reset (void) { PRINTK2 ("%s:smc_reset\n", SMC_DEV_NAME); /* This resets the registers mostly to defaults, but doesn't affect EEPROM. That seems unnecessary */ SMC_SELECT_BANK (0); SMC_outw (LAN91C96_RCR_SOFT_RST, LAN91C96_RCR); udelay (10); /* Disable transmit and receive functionality */ SMC_outw (0, LAN91C96_RCR); SMC_outw (0, LAN91C96_TCR); /* set the control register */ SMC_SELECT_BANK (1); SMC_outw (SMC_inw (LAN91C96_CONTROL) | LAN91C96_CTR_BIT_8, LAN91C96_CONTROL); /* Disable all interrupts */ SMC_outb (0, LAN91C96_INT_MASK); } /* * Function: smc_enable * Purpose: let the chip talk to the outside work * Method: * 1. Initialize the Memory Configuration Register * 2. Enable the transmitter * 3. Enable the receiver */ static void smc_enable () { PRINTK2 ("%s:smc_enable\n", SMC_DEV_NAME); SMC_SELECT_BANK (0); /* Initialize the Memory Configuration Register. See page 49 of the LAN91C96 data sheet for details. */ SMC_outw (LAN91C96_MCR_TRANSMIT_PAGES, LAN91C96_MCR); /* Initialize the Transmit Control Register */ SMC_outw (LAN91C96_TCR_TXENA, LAN91C96_TCR); /* Initialize the Receive Control Register * FIXME: * The promiscuous bit set because I could not receive ARP reply * packets from the server when I send a ARP request. It only works * when I set the promiscuous bit */ SMC_outw (LAN91C96_RCR_RXEN | LAN91C96_RCR_PRMS, LAN91C96_RCR); } /* * Function: smc_shutdown * Purpose: closes down the SMC91xxx chip. * Method: * 1. zero the interrupt mask * 2. clear the enable receive flag * 3. clear the enable xmit flags * * TODO: * (1) maybe utilize power down mode. * Why not yet? Because while the chip will go into power down mode, * the manual says that it will wake up in response to any I/O requests * in the register space. Empirical results do not show this working. */ static void smc_shutdown () { PRINTK2 (CARDNAME ":smc_shutdown\n"); /* no more interrupts for me */ SMC_SELECT_BANK (2); SMC_outb (0, LAN91C96_INT_MASK); /* and tell the card to stay away from that nasty outside world */ SMC_SELECT_BANK (0); SMC_outb (0, LAN91C96_RCR); SMC_outb (0, LAN91C96_TCR); } /* * Function: smc_hardware_send_packet(struct net_device * ) * Purpose: * This sends the actual packet to the SMC9xxx chip. * * Algorithm: * First, see if a saved_skb is available. * ( this should NOT be called if there is no 'saved_skb' * Now, find the packet number that the chip allocated * Point the data pointers at it in memory * Set the length word in the chip's memory * Dump the packet to chip memory * Check if a last byte is needed ( odd length packet ) * if so, set the control flag right * Tell the card to send it * Enable the transmit interrupt, so I know if it failed * Free the kernel data if I actually sent it. */ static int smc_send_packet (volatile void *packet, int packet_length) { byte packet_no; unsigned long ioaddr; byte *buf; int length; int numPages; int try = 0; int time_out; byte status; PRINTK3 ("%s:smc_hardware_send_packet\n", SMC_DEV_NAME); length = ETH_ZLEN < packet_length ? packet_length : ETH_ZLEN; /* allocate memory ** The MMU wants the number of pages to be the number of 256 bytes ** 'pages', minus 1 ( since a packet can't ever have 0 pages :) ) ** ** The 91C111 ignores the size bits, but the code is left intact ** for backwards and future compatibility. ** ** Pkt size for allocating is data length +6 (for additional status ** words, length and ctl!) ** ** If odd size then last byte is included in this header. */ numPages = ((length & 0xfffe) + 6); numPages >>= 8; /* Divide by 256 */ if (numPages > 7) { printf ("%s: Far too big packet error. \n", SMC_DEV_NAME); return 0; } /* now, try to allocate the memory */ SMC_SELECT_BANK (2); SMC_outw (LAN91C96_MMUCR_ALLOC_TX | numPages, LAN91C96_MMU); again: try++; time_out = MEMORY_WAIT_TIME; do { status = SMC_inb (LAN91C96_INT_STATS); if (status & LAN91C96_IST_ALLOC_INT) { SMC_outb (LAN91C96_IST_ALLOC_INT, LAN91C96_INT_STATS); break; } } while (--time_out); if (!time_out) { PRINTK2 ("%s: memory allocation, try %d failed ...\n", SMC_DEV_NAME, try); if (try < SMC_ALLOC_MAX_TRY) goto again; else return 0; } PRINTK2 ("%s: memory allocation, try %d succeeded ...\n", SMC_DEV_NAME, try); /* I can send the packet now.. */ ioaddr = SMC_BASE_ADDRESS; buf = (byte *) packet; /* If I get here, I _know_ there is a packet slot waiting for me */ packet_no = SMC_inb (LAN91C96_ARR); if (packet_no & LAN91C96_ARR_FAILED) { /* or isn't there? BAD CHIP! */ printf ("%s: Memory allocation failed. \n", SMC_DEV_NAME); return 0; } /* we have a packet address, so tell the card to use it */ SMC_outb (packet_no, LAN91C96_PNR); /* point to the beginning of the packet */ SMC_outw (LAN91C96_PTR_AUTO_INCR, LAN91C96_POINTER); PRINTK3 ("%s: Trying to xmit packet of length %x\n", SMC_DEV_NAME, length); #if SMC_DEBUG > 2 printf ("Transmitting Packet\n"); print_packet (buf, length); #endif /* send the packet length ( +6 for status, length and ctl byte ) and the status word ( set to zeros ) */ #ifdef USE_32_BIT SMC_outl ((length + 6) << 16, LAN91C96_DATA_HIGH); #else SMC_outw (0, LAN91C96_DATA_HIGH); /* send the packet length ( +6 for status words, length, and ctl */ SMC_outw ((length + 6), LAN91C96_DATA_HIGH); #endif /* USE_32_BIT */ /* send the actual data * I _think_ it's faster to send the longs first, and then * mop up by sending the last word. It depends heavily * on alignment, at least on the 486. Maybe it would be * a good idea to check which is optimal? But that could take * almost as much time as is saved? */ #ifdef USE_32_BIT SMC_outsl (LAN91C96_DATA_HIGH, buf, length >> 2); if (length & 0x2) SMC_outw (*((word *) (buf + (length & 0xFFFFFFFC))), LAN91C96_DATA_HIGH); #else SMC_outsw (LAN91C96_DATA_HIGH, buf, (length) >> 1); #endif /* USE_32_BIT */ /* Send the last byte, if there is one. */ if ((length & 1) == 0) { SMC_outw (0, LAN91C96_DATA_HIGH); } else { SMC_outw (buf[length - 1] | 0x2000, LAN91C96_DATA_HIGH); } /* and let the chipset deal with it */ SMC_outw (LAN91C96_MMUCR_ENQUEUE, LAN91C96_MMU); /* poll for TX INT */ if (poll4int (LAN91C96_MSK_TX_INT, SMC_TX_TIMEOUT)) { /* sending failed */ PRINTK2 ("%s: TX timeout, sending failed...\n", SMC_DEV_NAME); /* release packet */ SMC_outw (LAN91C96_MMUCR_RELEASE_TX, LAN91C96_MMU); /* wait for MMU getting ready (low) */ while (SMC_inw (LAN91C96_MMU) & LAN91C96_MMUCR_NO_BUSY) { udelay (10); } PRINTK2 ("MMU ready\n"); return 0; } else { /* ack. int */ SMC_outw (LAN91C96_IST_TX_INT, LAN91C96_INT_STATS); PRINTK2 ("%s: Sent packet of length %d \n", SMC_DEV_NAME, length); /* release packet */ SMC_outw (LAN91C96_MMUCR_RELEASE_TX, LAN91C96_MMU); /* wait for MMU getting ready (low) */ while (SMC_inw (LAN91C96_MMU) & LAN91C96_MMUCR_NO_BUSY) { udelay (10); } PRINTK2 ("MMU ready\n"); } return length; } /*------------------------------------------------------------------------- * smc_destructor( struct net_device * dev ) * Input parameters: * dev, pointer to the device structure * * Output: * None. *-------------------------------------------------------------------------- */ void smc_destructor () { PRINTK2 (CARDNAME ":smc_destructor\n"); } /* * Open and Initialize the board * * Set up everything, reset the card, etc .. * */ static int smc_open (bd_t *bd) { int i, err; /* used to set hw ethernet address */ PRINTK2 ("%s:smc_open\n", SMC_DEV_NAME); /* reset the hardware */ smc_reset (); smc_enable (); SMC_SELECT_BANK (1); err = smc_get_ethaddr (bd); /* set smc_mac_addr, and sync it with u-boot globals */ if (err < 0) return -1; #ifdef USE_32_BIT for (i = 0; i < 6; i += 2) { word address; address = smc_mac_addr[i + 1] << 8; address |= smc_mac_addr[i]; SMC_outw (address, LAN91C96_IA0 + i); } #else for (i = 0; i < 6; i++) SMC_outb (smc_mac_addr[i], LAN91C96_IA0 + i); #endif return 0; } /*------------------------------------------------------------- * * smc_rcv - receive a packet from the card * * There is ( at least ) a packet waiting to be read from * chip-memory. * * o Read the status * o If an error, record it * o otherwise, read in the packet *------------------------------------------------------------- */ static int smc_rcv () { int packet_number; word status; word packet_length; int is_error = 0; #ifdef USE_32_BIT dword stat_len; #endif SMC_SELECT_BANK (2); packet_number = SMC_inw (LAN91C96_FIFO); if (packet_number & LAN91C96_FIFO_RXEMPTY) { return 0; } PRINTK3 ("%s:smc_rcv\n", SMC_DEV_NAME); /* start reading from the start of the packet */ SMC_outw (LAN91C96_PTR_READ | LAN91C96_PTR_RCV | LAN91C96_PTR_AUTO_INCR, LAN91C96_POINTER); /* First two words are status and packet_length */ #ifdef USE_32_BIT stat_len = SMC_inl (LAN91C96_DATA_HIGH); status = stat_len & 0xffff; packet_length = stat_len >> 16; #else status = SMC_inw (LAN91C96_DATA_HIGH); packet_length = SMC_inw (LAN91C96_DATA_HIGH); #endif packet_length &= 0x07ff; /* mask off top bits */ PRINTK2 ("RCV: STATUS %4x LENGTH %4x\n", status, packet_length); if (!(status & FRAME_FILTER)) { /* Adjust for having already read the first two words */ packet_length -= 4; /*4; */ /* set odd length for bug in LAN91C111, */ /* which never sets RS_ODDFRAME */ /* TODO ? */ #ifdef USE_32_BIT PRINTK3 (" Reading %d dwords (and %d bytes) \n", packet_length >> 2, packet_length & 3); /* QUESTION: Like in the TX routine, do I want to send the DWORDs or the bytes first, or some mixture. A mixture might improve already slow PIO performance */ SMC_insl (LAN91C96_DATA_HIGH, NetRxPackets[0], packet_length >> 2); /* read the left over bytes */ if (packet_length & 3) { int i; byte *tail = (byte *) (NetRxPackets[0] + (packet_length & ~3)); dword leftover = SMC_inl (LAN91C96_DATA_HIGH); for (i = 0; i < (packet_length & 3); i++) *tail++ = (byte) (leftover >> (8 * i)) & 0xff; } #else PRINTK3 (" Reading %d words and %d byte(s) \n", (packet_length >> 1), packet_length & 1); SMC_insw (LAN91C96_DATA_HIGH, NetRxPackets[0], packet_length >> 1); #endif /* USE_32_BIT */ #if SMC_DEBUG > 2 printf ("Receiving Packet\n"); print_packet (NetRxPackets[0], packet_length); #endif } else { /* error ... */ /* TODO ? */ is_error = 1; } while (SMC_inw (LAN91C96_MMU) & LAN91C96_MMUCR_NO_BUSY) udelay (1); /* Wait until not busy */ /* error or good, tell the card to get rid of this packet */ SMC_outw (LAN91C96_MMUCR_RELEASE_RX, LAN91C96_MMU); while (SMC_inw (LAN91C96_MMU) & LAN91C96_MMUCR_NO_BUSY) udelay (1); /* Wait until not busy */ if (!is_error) { /* Pass the packet up to the protocol layers. */ NetReceive (NetRxPackets[0], packet_length); return packet_length; } else { return 0; } } /*---------------------------------------------------- * smc_close * * this makes the board clean up everything that it can * and not talk to the outside world. Caused by * an 'ifconfig ethX down' * -----------------------------------------------------*/ static int smc_close () { PRINTK2 ("%s:smc_close\n", SMC_DEV_NAME); /* clear everything */ smc_shutdown (); return 0; } #if SMC_DEBUG > 2 static void print_packet (byte * buf, int length) { #if 0 int i; int remainder; int lines; printf ("Packet of length %d \n", length); lines = length / 16; remainder = length % 16; for (i = 0; i < lines; i++) { int cur; for (cur = 0; cur < 8; cur++) { byte a, b; a = *(buf++); b = *(buf++); printf ("%02x%02x ", a, b); } printf ("\n"); } for (i = 0; i < remainder / 2; i++) { byte a, b; a = *(buf++); b = *(buf++); printf ("%02x%02x ", a, b); } printf ("\n"); #endif /* 0 */ } #endif /* SMC_DEBUG > 2 */ int eth_init (bd_t * bd) { return (smc_open(bd)); } void eth_halt () { smc_close (); } int eth_rx () { return smc_rcv (); } int eth_send (volatile void *packet, int length) { return smc_send_packet (packet, length); } #if 0 /*------------------------------------------------------------------------- * smc_hw_init() * * Function: * Reset and enable the device, check if the I/O space location * is correct * * Input parameters: * None * * Output: * 0 --> success * 1 --> error *-------------------------------------------------------------------------- */ static int smc_hw_init () { unsigned short status_test; /* The attribute register of the LAN91C96 is located at address 0x0e000000 on the lubbock platform */ volatile unsigned *attaddr = (unsigned *) (0x0e000000); /* first reset, then enable the device. Sequence is critical */ attaddr[LAN91C96_ECOR] |= LAN91C96_ECOR_SRESET; udelay (100); attaddr[LAN91C96_ECOR] &= ~LAN91C96_ECOR_SRESET; attaddr[LAN91C96_ECOR] |= LAN91C96_ECOR_ENABLE; /* force 16-bit mode */ attaddr[LAN91C96_ECSR] &= ~LAN91C96_ECSR_IOIS8; udelay (100); /* check if the I/O address is correct, the upper byte of the bank select register should read 0x33 */ status_test = SMC_inw (LAN91C96_BANK_SELECT); if ((status_test & 0xFF00) != 0x3300) { printf ("Failed to initialize ethernetchip\n"); return 1; } return 0; } #endif /* 0 */ /* smc_get_ethaddr (bd_t * bd) * * This checks both the environment and the ROM for an ethernet address. If * found, the environment takes precedence. */ int smc_get_ethaddr (bd_t * bd) { uchar v_mac[6]; if (!eth_getenv_enetaddr("ethaddr", v_mac)) { /* get ROM mac value if any */ if (!get_rom_mac(v_mac)) { printf("\n*** ERROR: ethaddr is NOT set !!\n"); return -1; } eth_setenv_enetaddr("ethaddr", v_mac); } smc_set_mac_addr(v_mac); /* use old function to update smc default */ PRINTK("Using MAC Address %pM\n", v_mac); return 0; } /* * get_rom_mac() * Note, this has omly been tested for the OMAP730 P2. */ int get_rom_mac (unsigned char *v_rom_mac) { #ifdef HARDCODE_MAC /* used for testing or to supress run time warnings */ char hw_mac_addr[] = { 0x02, 0x80, 0xad, 0x20, 0x31, 0xb8 }; memcpy (v_rom_mac, hw_mac_addr, 6); return (1); #else int i; SMC_SELECT_BANK (1); for (i=0; i<6; i++) { v_rom_mac[i] = SMC_inb (LAN91C96_IA0 + i); } return (1); #endif }
gpl-2.0
tsammons/SMART-GH
android/scripts/deploy-maps.sh
607
# either plugin your device and copy the files via USB-detected-device or use the following method # when starting an ssh server like sshdroid URL=192.168.0.102 GH=/sdcard/graphhopper/maps/ # if you install sshdroid you can scp your files to your android device # wget http://mapsforge.googlecode.com/files/berlin.map # alternatives: http://download.mapsforge.org/maps/ scp -P 2222 berlin.map root@$URL:$GH # wget http://download.geofabrik.de/osm/europe/germany/berlin.osm.bz2 # bunzip2 berlin.osm.bz2 # cd ../graphhopper # ./run.sh /media/SAMSUNG/maps/berlin.osm scp -r -P 2222 berlin-gh/ root@$URL:$GH
apache-2.0
AzureAutomationTeam/azure-powershell
src/StackAdmin/Resources/Commands.ResourceManager/Cmdlets/SdkModels/Deployments/PSResourceGroupDeployment.cs
2004
// ---------------------------------------------------------------------------------- // // 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; using System.Collections.Generic; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkExtensions; namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.SdkModels { public class PSResourceGroupDeployment { public string DeploymentName { get; set; } public string CorrelationId { get; set; } public string ResourceGroupName { get; set; } public string ProvisioningState { get; set; } public DateTime Timestamp { get; set; } public DeploymentMode Mode { get; set; } public TemplateLink TemplateLink { get; set; } public string TemplateLinkString { get; set; } public string DeploymentDebugLogLevel { get; set; } public Dictionary<string, DeploymentVariable> Parameters { get; set; } public string ParametersString { get { return ResourcesExtensions.ConstructDeploymentVariableTable(Parameters); } } public Dictionary<string, DeploymentVariable> Outputs { get; set; } public string OutputsString { get { return ResourcesExtensions.ConstructDeploymentVariableTable(Outputs); } } } }
apache-2.0
esacosta/u-mooc
edu-courses/assets/js/activity-1.4.js
3756
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Usage instructions: Create a single array variable named 'activity'. This // represents explanatory text and one or more questions to present to the // student. Each element in the array should itself be either // // -- a string containing a set of complete HTML elements. That is, if the // string contains an open HTML tag (such as <form>), it must also have the // corresponding close tag (such as </form>). You put the actual question // text in a string. // // -- a JavaScript object representing the answer information for a question. // That is, the object contains properties such as the type of question, a // regular expression indicating the correct answer, a string to show in // case of either correct or incorrect answers or to show when the student // asks for help. For more information on how to specify the object, please // see http://code.google.com/p/course-builder/wiki/CreateActivities. var activity = [ '<table border="1"><tr><td><b>Search Tips:</b><p><ul><li>In the last video you learned how to select effective keywords. Remember to think about the words you think will be in your desired results page.<p> <li>Determine the most important words in your search as well as potential synonyms.</ul><p> </tr></td></table>', 'You received this letter from a friend. <p><font style="font-style:italic;">Hi, I am a chef and a food blogger. Recently, I wanted to write about this really yummy French sandwich with tuna and peppers and anchovies and stuff called a Pom Mignon, or something like that. For the life of me, I don’t know precisely what it is called. I spent half an hour last night typing every possible spelling I could think of into Google, but could not find it. What do I do now? <p>Thank you,<br>L.</font><p>Given what you know about this problem, what query would you use to solve it?<p>', { questionType: 'freetext', showAnswerPrompt: 'Compare with Expert', showAnswerOutput: 'Our expert says: Different people have different styles for searching for information. Here is how I identified the sandwich--though it is not the only way to arrive at an answer.\n\nI searched for [french sandwich tuna peppers anchovies]. \n\nRemember how Dan talked about thinking about what you want to find? What words will be on the kind of page you want to appear? \n\nSo, ask yourself what kind of page is likely to:\n\n1. Give the name of this sandwich?\n2. Be a common resource on the web?\n3. Make use of the other information you have about the sandwich--since the name was obviously a dead-end?\n\nI thought of a recipe! A recipe lists all of the ingredients. In this case, the chef knew several of the ingredients, but did not connect the fact that she knew them to the idea that she could use them in a basic web search.\n\nScroll down to continue. ', outputHeight: '300px' }, '<br><br>Can you find the name of the sandwich in the results below?<br>', '<br><img src="assets/img/Image10.1.png"<p>', '<br>What\'s the name of the sandwich?<br>', { questionType: 'freetext', showAnswerPrompt: 'Check Answer', showAnswerOutput: 'Pan Bagnat!'}, ];
apache-2.0
DreamHill/flatbuffers
docs/html/md__go_usage.html
8901
<!-- HTML header for doxygen 1.8.6--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>FlatBuffers: Use in Go</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet"> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea" style="height: 110px;"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="commonprojectlogo"> <img alt="Logo" src="fpl_logo_small.png"/> </td> <td style="padding-left: 0.5em;"> <div id="projectname">FlatBuffers </div> <div style="font-size:12px;"> An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>. </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('md__go_usage.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">Use in Go </div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><p>There's experimental support for reading FlatBuffers in Go. Generate code for Go with the <code>-g</code> option to <code>flatc</code>.</p> <p>See <code>go_test.go</code> for an example. You import the generated code, read a FlatBuffer binary file into a <code>[]byte</code>, which you pass to the <code>GetRootAsMonster</code> function:</p> <div class="fragment"><div class="line"><span class="keyword">import</span> (</div> <div class="line"> example <span class="stringliteral">&quot;MyGame/Example&quot;</span></div> <div class="line"> flatbuffers <span class="stringliteral">&quot;github.com/google/flatbuffers/go&quot;</span></div> <div class="line"></div> <div class="line"> io/ioutil</div> <div class="line">)</div> <div class="line"></div> <div class="line">buf, err := ioutil.ReadFile(<span class="stringliteral">&quot;monster.dat&quot;</span>)</div> <div class="line"><span class="comment">// handle err</span></div> <div class="line">monster := example.GetRootAsMonster(buf, 0)</div> </div><!-- fragment --><p>Now you can access values like this:</p> <div class="fragment"><div class="line">hp := monster.Hp()</div> <div class="line">pos := monster.Pos(nil)</div> </div><!-- fragment --><p>Note that whenever you access a new object like in the <code>Pos</code> example above, a new temporary accessor object gets created. If your code is very performance sensitive (you iterate through a lot of objects), you can replace nil with a pointer to a <code>Vec3</code> object you've already created. This allows you to reuse it across many calls and reduce the amount of object allocation (and thus garbage collection) your program does.</p> <p>To access vectors you pass an extra index to the vector field accessor. Then a second method with the same name suffixed by <code>Length</code> let's you know the number of elements you can access:</p> <div class="fragment"><div class="line"><span class="keywordflow">for</span> i := 0; i &lt; monster.InventoryLength(); i++ {</div> <div class="line"> monster.Inventory(i) <span class="comment">// do something here</span></div> <div class="line">}</div> </div><!-- fragment --><p>You can also construct these buffers in Go using the functions found in the generated code, and the FlatBufferBuilder class:</p> <div class="fragment"><div class="line">builder := flatbuffers.NewBuilder(0)</div> </div><!-- fragment --><p>Create strings:</p> <div class="fragment"><div class="line">str := builder.CreateString(<span class="stringliteral">&quot;MyMonster&quot;</span>)</div> </div><!-- fragment --><p>Create a table with a struct contained therein:</p> <div class="fragment"><div class="line">example.MonsterStart(builder)</div> <div class="line">example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6))</div> <div class="line">example.MonsterAddHp(builder, 80)</div> <div class="line">example.MonsterAddName(builder, str)</div> <div class="line">example.MonsterAddInventory(builder, inv)</div> <div class="line">example.MonsterAddTest_Type(builder, 1)</div> <div class="line">example.MonsterAddTest(builder, mon2)</div> <div class="line">example.MonsterAddTest4(builder, test4s)</div> <div class="line">mon := example.MonsterEnd(builder)</div> </div><!-- fragment --><p>Unlike C++, Go does not support table creation functions like 'createMonster()'. This is to create the buffer without using temporary object allocation (since the <code>Vec3</code> is an inline component of <code>Monster</code>, it has to be created right where it is added, whereas the name and the inventory are not inline, and <b>must</b> be created outside of the table creation sequence). Structs do have convenient methods that allow you to construct them in one call. These also have arguments for nested structs, e.g. if a struct has a field <code>a</code> and a nested struct field <code>b</code> (which has fields <code>c</code> and <code>d</code>), then the arguments will be <code>a</code>, <code>c</code> and <code>d</code>.</p> <p>Vectors also use this start/end pattern to allow vectors of both scalar types and structs:</p> <div class="fragment"><div class="line">example.MonsterStartInventoryVector(builder, 5)</div> <div class="line"><span class="keywordflow">for</span> i := 4; i &gt;= 0; i-- {</div> <div class="line"> builder.PrependByte(byte(i))</div> <div class="line">}</div> <div class="line">inv := builder.EndVector(5)</div> </div><!-- fragment --><p>The generated method 'StartInventoryVector' is provided as a convenience function which calls 'StartVector' with the correct element size of the vector type which in this case is 'ubyte' or 1 byte per vector element. You pass the number of elements you want to write. You write the elements backwards since the buffer is being constructed back to front. Use the correct <code>Prepend</code> call for the type, or <code>PrependUOffsetT</code> for offsets. You then pass <code>inv</code> to the corresponding <code>Add</code> call when you construct the table containing it afterwards.</p> <p>There are <code>Prepend</code> functions for all the scalar types. You use <code>PrependUOffset</code> for any previously constructed objects (such as other tables, strings, vectors). For structs, you use the appropriate <code>create</code> function in-line, as shown above in the <code>Monster</code> example.</p> <p>Once you're done constructing a buffer, you call <code>Finish</code> with the root object offset (<code>mon</code> in the example above). Your data now resides in Builder.Bytes. Important to note is that the real data starts at the index indicated by Head(), for Offset() bytes (this is because the buffer is constructed backwards). If you wanted to read the buffer right after creating it (using <code>GetRootAsMonster</code> above), the second argument, instead of <code>0</code> would thus also be <code>Head()</code>.</p> <h2>Text Parsing</h2> <p>There currently is no support for parsing text (Schema's and JSON) directly from Go, though you could use the C++ parser through cgo. Please see the C++ documentation for more on text parsing. </p> </div></div><!-- contents --> </div><!-- doc-content --> <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-49880327-7', 'auto'); ga('send', 'pageview'); </script> </body> </html>
apache-2.0
plantain-00/TypeScript
tests/baselines/reference/noImplicitReturnsWithoutReturnExpression.js
820
//// [noImplicitReturnsWithoutReturnExpression.ts] function isMissingReturnExpression(): number { return; } function isMissingReturnExpression2(): any { return; } function isMissingReturnExpression3(): number|void { return; } function isMissingReturnExpression4(): void { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } } //// [noImplicitReturnsWithoutReturnExpression.js] function isMissingReturnExpression() { return; } function isMissingReturnExpression2() { return; } function isMissingReturnExpression3() { return; } function isMissingReturnExpression4() { return; } function isMissingReturnExpression5(x) { if (x) { return 0; } else { return; } }
apache-2.0
cdcabrera/spksrc
spk/lirc/src/dsm-control.sh
4844
#!/bin/sh # Package PACKAGE="lirc" DNAME="LIRC" # Others INSTALL_DIR="/usr/local/${PACKAGE}" INSTALLER_SCRIPT=`dirname $0`/installer PATH="${PATH}:${INSTALL_DIR}/bin:/usr/local/bin:/bin:/usr/bin:/usr/syno/bin" DAEMON="${INSTALL_DIR}/sbin/lircd" PID_FILE="${INSTALL_DIR}/var/lircd.pid" CONF_FILE="${INSTALL_DIR}/etc/lirc/lircd.conf" IREXEC="${INSTALL_DIR}/bin/irexec" LIRCRC_FILE="${INSTALL_DIR}/etc/lirc/lircrc" LOG_FILE="${INSTALL_DIR}/var/log/lircd" VERSION_FILE="${INSTALL_DIR}/etc/DSM_VERSION" SELECTED_LIRC_DRIVER=@driver@ load_unload_drivers () { case $1 in load) case $2 in mceusb) insmod ${INSTALL_DIR}/lib/modules/lirc_dev.ko insmod ${INSTALL_DIR}/lib/modules/lirc_${2}.ko ;; uirt) insmod ${INSTALL_DIR}/lib/modules/lirc_dev.ko insmod /lib/modules/usbserial.ko insmod /lib/modules/ftdi_sio.ko stty -F /dev/usb/ttyUSB0 1200 sane evenp parenb cs7 -crtscts LIRC_STARTUP_PARAMS="--device=/dev/usb/ttyUSB0 --driver=usb_uirt_raw" ;; uirt2) insmod ${INSTALL_DIR}/lib/modules/lirc_dev.ko insmod /lib/modules/usbserial.ko insmod /lib/modules/ftdi_sio.ko stty -F /dev/usb/ttyUSB0 1200 sane evenp parenb cs7 -crtscts LIRC_STARTUP_PARAMS="--device=/dev/usb/ttyUSB0 --driver=uirt2_raw" ;; irtoy) # Not yet supported. Here for example only. ;; *) # Not yet supported. ;; esac ;; unload) case $2 in mceusb) rmmod ${INSTALL_DIR}/lib/modules/lirc_${2}.ko rmmod ${INSTALL_DIR}/lib/modules/lirc_dev.ko ;; uirt|uirt2) rmmod /lib/modules/ftdi_sio.ko rmmod /lib/modules/usbserial.ko rmmod ${INSTALL_DIR}/lib/modules/lirc_dev.ko ;; irtoy) # Not yet supported. Here for example only. ;; *) # Not yet supported. ;; esac ;; esac } start_daemon () { # Call function to load driver - validation happens inside load_unload_drivers load $SELECTED_LIRC_DRIVER ${DAEMON} ${LIRC_STARTUP_PARAMS} ${CONF_FILE} --pidfile=${PID_FILE} --logfile=${LOG_FILE} if [ -e ${LIRCRC_FILE} ]; then ${IREXEC} -d ${LIRCRC_FILE} fi } stop_daemon () { killall irexec >/dev/null 2>&1 if daemon_status; then echo Stopping ${DNAME} ... kill `cat ${PID_FILE}` wait_for_status 1 20 || kill -9 `cat ${PID_FILE}` else echo ${DNAME} is not running exit 0 fi test -e ${PID_FILE} || rm -f ${PID_FILE} # Call function to unload driver - validation happens inside load_unload_drivers unload $SELECTED_LIRC_DRIVER } daemon_status () { if [ -f ${PID_FILE} ] && kill -0 `cat ${PID_FILE}` > /dev/null 2>&1; then return fi rm -f ${PID_FILE} return 1 } wait_for_status () { counter=$2 while [ ${counter} -gt 0 ]; do daemon_status [ $? -eq $1 ] && return let counter=counter-1 sleep 1 done return 1 } check_dsm_version () { if [ -f ${VERSION_FILE} ]; then diff -qw /etc.defaults/VERSION ${VERSION_FILE} 2>&1 >/dev/null if [ $? -ne 0 ]; then echo -n "DSM version has changed, re-running driver setup..." . ${INSTALLER_SCRIPT} lirc_install_drivers ${SELECTED_LIRC_DRIVER} cp /etc.defaults/VERSION ${VERSION_FILE} echo done. fi else echo "First time starting, capturing DSM version" cp /etc.defaults/VERSION ${VERSION_FILE} fi } case $1 in start) if daemon_status; then echo ${DNAME} is already running exit 0 else # Check if DSM was upgraded check_dsm_version echo Starting ${DNAME} ... start_daemon exit $? fi ;; stop) stop_daemon exit $? ;; restart) stop_daemon start_daemon exit $? ;; status) if daemon_status; then echo ${DNAME} is running exit 0 else echo ${DNAME} is not running exit 1 fi ;; log) echo ${LOG_FILE} ;; driver) echo ${SELECTED_LIRC_DRIVER} ;; *) exit 1 ;; esac
bsd-3-clause
nwjs/chromium.src
third_party/blink/web_tests/external/wpt/css/CSS2/floats/overhanging-float-paint-order.html
840
<!DOCTYPE html> <link rel="help" href="https://drafts.csswg.org/css2/visuren.html#float-position"> <link rel="help" href="https://drafts.csswg.org/css2/zindex.html"> <link rel="match" href="overhanging-float-paint-order-ref.html"> <style> #first-container { width: 100px; height: 60px; } #red-first-float { width: 100px; height: 60px; background-color: red; float: left; } #container { width: 100px; height: 80px; } #blue-second-float-overhanging { width: 100px; height: 60px; background-color: blue; float: left; margin-top: -20px; } #green-third-float { width: 100px; height: 80px; background-color: green; float: left; margin-top: -100px; } </style> <div id="red-first-float"></div> <div id="container"> <div id="blue-second-float-overhanging"></div> <div id="green-third-float"></div> </div>
bsd-3-clause
KitKatXperience/platform_external_chromium_org
sync/util/cryptographer.cc
10916
// 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 "sync/util/cryptographer.h" #include <algorithm> #include "base/base64.h" #include "base/basictypes.h" #include "base/logging.h" #include "sync/protocol/nigori_specifics.pb.h" #include "sync/util/encryptor.h" namespace syncer { const char kNigoriTag[] = "google_chrome_nigori"; // We name a particular Nigori instance (ie. a triplet consisting of a hostname, // a username, and a password) by calling Permute on this string. Since the // output of Permute is always the same for a given triplet, clients will always // assign the same name to a particular triplet. const char kNigoriKeyName[] = "nigori-key"; Cryptographer::Cryptographer(Encryptor* encryptor) : encryptor_(encryptor) { DCHECK(encryptor); } Cryptographer::~Cryptographer() {} void Cryptographer::Bootstrap(const std::string& restored_bootstrap_token) { if (is_initialized()) { NOTREACHED(); return; } std::string serialized_nigori_key = UnpackBootstrapToken(restored_bootstrap_token); if (serialized_nigori_key.empty()) return; ImportNigoriKey(serialized_nigori_key); } bool Cryptographer::CanDecrypt(const sync_pb::EncryptedData& data) const { return nigoris_.end() != nigoris_.find(data.key_name()); } bool Cryptographer::CanDecryptUsingDefaultKey( const sync_pb::EncryptedData& data) const { return !default_nigori_name_.empty() && data.key_name() == default_nigori_name_; } bool Cryptographer::Encrypt( const ::google::protobuf::MessageLite& message, sync_pb::EncryptedData* encrypted) const { DCHECK(encrypted); if (default_nigori_name_.empty()) { LOG(ERROR) << "Cryptographer not ready, failed to encrypt."; return false; } std::string serialized; if (!message.SerializeToString(&serialized)) { LOG(ERROR) << "Message is invalid/missing a required field."; return false; } return EncryptString(serialized, encrypted); } bool Cryptographer::EncryptString( const std::string& serialized, sync_pb::EncryptedData* encrypted) const { if (CanDecryptUsingDefaultKey(*encrypted)) { const std::string& original_serialized = DecryptToString(*encrypted); if (original_serialized == serialized) { DVLOG(2) << "Re-encryption unnecessary, encrypted data already matches."; return true; } } NigoriMap::const_iterator default_nigori = nigoris_.find(default_nigori_name_); if (default_nigori == nigoris_.end()) { LOG(ERROR) << "Corrupt default key."; return false; } encrypted->set_key_name(default_nigori_name_); if (!default_nigori->second->Encrypt(serialized, encrypted->mutable_blob())) { LOG(ERROR) << "Failed to encrypt data."; return false; } return true; } bool Cryptographer::Decrypt(const sync_pb::EncryptedData& encrypted, ::google::protobuf::MessageLite* message) const { DCHECK(message); std::string plaintext = DecryptToString(encrypted); return message->ParseFromString(plaintext); } std::string Cryptographer::DecryptToString( const sync_pb::EncryptedData& encrypted) const { NigoriMap::const_iterator it = nigoris_.find(encrypted.key_name()); if (nigoris_.end() == it) { NOTREACHED() << "Cannot decrypt message"; return std::string(); // Caller should have called CanDecrypt(encrypt). } std::string plaintext; if (!it->second->Decrypt(encrypted.blob(), &plaintext)) { return std::string(); } return plaintext; } bool Cryptographer::GetKeys(sync_pb::EncryptedData* encrypted) const { DCHECK(encrypted); DCHECK(!nigoris_.empty()); // Create a bag of all the Nigori parameters we know about. sync_pb::NigoriKeyBag bag; for (NigoriMap::const_iterator it = nigoris_.begin(); it != nigoris_.end(); ++it) { const Nigori& nigori = *it->second; sync_pb::NigoriKey* key = bag.add_key(); key->set_name(it->first); nigori.ExportKeys(key->mutable_user_key(), key->mutable_encryption_key(), key->mutable_mac_key()); } // Encrypt the bag with the default Nigori. return Encrypt(bag, encrypted); } bool Cryptographer::AddKey(const KeyParams& params) { // Create the new Nigori and make it the default encryptor. scoped_ptr<Nigori> nigori(new Nigori); if (!nigori->InitByDerivation(params.hostname, params.username, params.password)) { NOTREACHED(); // Invalid username or password. return false; } return AddKeyImpl(nigori.Pass(), true); } bool Cryptographer::AddNonDefaultKey(const KeyParams& params) { DCHECK(is_initialized()); // Create the new Nigori and add it to the keybag. scoped_ptr<Nigori> nigori(new Nigori); if (!nigori->InitByDerivation(params.hostname, params.username, params.password)) { NOTREACHED(); // Invalid username or password. return false; } return AddKeyImpl(nigori.Pass(), false); } bool Cryptographer::AddKeyFromBootstrapToken( const std::string restored_bootstrap_token) { // Create the new Nigori and make it the default encryptor. std::string serialized_nigori_key = UnpackBootstrapToken( restored_bootstrap_token); return ImportNigoriKey(serialized_nigori_key); } bool Cryptographer::AddKeyImpl(scoped_ptr<Nigori> initialized_nigori, bool set_as_default) { std::string name; if (!initialized_nigori->Permute(Nigori::Password, kNigoriKeyName, &name)) { NOTREACHED(); return false; } nigoris_[name] = make_linked_ptr(initialized_nigori.release()); // Check if the key we just added can decrypt the pending keys and add them // too if so. if (pending_keys_.get() && CanDecrypt(*pending_keys_)) { sync_pb::NigoriKeyBag pending_bag; Decrypt(*pending_keys_, &pending_bag); InstallKeyBag(pending_bag); SetDefaultKey(pending_keys_->key_name()); pending_keys_.reset(); } // The just-added key takes priority over the pending keys as default. if (set_as_default) SetDefaultKey(name); return true; } void Cryptographer::InstallKeys(const sync_pb::EncryptedData& encrypted) { DCHECK(CanDecrypt(encrypted)); sync_pb::NigoriKeyBag bag; if (!Decrypt(encrypted, &bag)) return; InstallKeyBag(bag); } void Cryptographer::SetDefaultKey(const std::string& key_name) { DCHECK(nigoris_.end() != nigoris_.find(key_name)); default_nigori_name_ = key_name; } void Cryptographer::SetPendingKeys(const sync_pb::EncryptedData& encrypted) { DCHECK(!CanDecrypt(encrypted)); DCHECK(!encrypted.blob().empty()); pending_keys_.reset(new sync_pb::EncryptedData(encrypted)); } const sync_pb::EncryptedData& Cryptographer::GetPendingKeys() const { DCHECK(has_pending_keys()); return *(pending_keys_.get()); } bool Cryptographer::DecryptPendingKeys(const KeyParams& params) { Nigori nigori; if (!nigori.InitByDerivation(params.hostname, params.username, params.password)) { NOTREACHED(); return false; } std::string plaintext; if (!nigori.Decrypt(pending_keys_->blob(), &plaintext)) return false; sync_pb::NigoriKeyBag bag; if (!bag.ParseFromString(plaintext)) { NOTREACHED(); return false; } InstallKeyBag(bag); const std::string& new_default_key_name = pending_keys_->key_name(); SetDefaultKey(new_default_key_name); pending_keys_.reset(); return true; } bool Cryptographer::GetBootstrapToken(std::string* token) const { DCHECK(token); std::string unencrypted_token = GetDefaultNigoriKey(); if (unencrypted_token.empty()) return false; std::string encrypted_token; if (!encryptor_->EncryptString(unencrypted_token, &encrypted_token)) { NOTREACHED(); return false; } if (!base::Base64Encode(encrypted_token, token)) { NOTREACHED(); return false; } return true; } std::string Cryptographer::UnpackBootstrapToken( const std::string& token) const { if (token.empty()) return std::string(); std::string encrypted_data; if (!base::Base64Decode(token, &encrypted_data)) { DLOG(WARNING) << "Could not decode token."; return std::string(); } std::string unencrypted_token; if (!encryptor_->DecryptString(encrypted_data, &unencrypted_token)) { DLOG(WARNING) << "Decryption of bootstrap token failed."; return std::string(); } return unencrypted_token; } void Cryptographer::InstallKeyBag(const sync_pb::NigoriKeyBag& bag) { int key_size = bag.key_size(); for (int i = 0; i < key_size; ++i) { const sync_pb::NigoriKey key = bag.key(i); // Only use this key if we don't already know about it. if (nigoris_.end() == nigoris_.find(key.name())) { scoped_ptr<Nigori> new_nigori(new Nigori); if (!new_nigori->InitByImport(key.user_key(), key.encryption_key(), key.mac_key())) { NOTREACHED(); continue; } nigoris_[key.name()] = make_linked_ptr(new_nigori.release()); } } } bool Cryptographer::KeybagIsStale( const sync_pb::EncryptedData& encrypted_bag) const { if (!is_ready()) return false; if (encrypted_bag.blob().empty()) return true; if (!CanDecrypt(encrypted_bag)) return false; if (!CanDecryptUsingDefaultKey(encrypted_bag)) return true; sync_pb::NigoriKeyBag bag; if (!Decrypt(encrypted_bag, &bag)) { LOG(ERROR) << "Failed to decrypt keybag for stale check. " << "Assuming keybag is corrupted."; return true; } if (static_cast<size_t>(bag.key_size()) < nigoris_.size()) return true; return false; } std::string Cryptographer::GetDefaultNigoriKey() const { if (!is_initialized()) return std::string(); NigoriMap::const_iterator iter = nigoris_.find(default_nigori_name_); if (iter == nigoris_.end()) return std::string(); sync_pb::NigoriKey key; if (!iter->second->ExportKeys(key.mutable_user_key(), key.mutable_encryption_key(), key.mutable_mac_key())) return std::string(); return key.SerializeAsString(); } bool Cryptographer::ImportNigoriKey(const std::string serialized_nigori_key) { if (serialized_nigori_key.empty()) return false; sync_pb::NigoriKey key; if (!key.ParseFromString(serialized_nigori_key)) return false; scoped_ptr<Nigori> nigori(new Nigori); if (!nigori->InitByImport(key.user_key(), key.encryption_key(), key.mac_key())) { NOTREACHED(); return false; } if (!AddKeyImpl(nigori.Pass(), true)) return false; return true; } } // namespace syncer
bsd-3-clause