content
stringlengths
10
4.9M
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ota-provider-common/OTAProviderExample.h> #include <app-common/zap-generated/cluster-id.h> #include <app-common/zap-generated/command-id.h> #include <app/CommandPathParams.h> #include <app/clusters/ota-provider/ota-provider-delegate.h> #include <app/util/af.h> #include <lib/core/CHIPTLV.h> #include <lib/support/CHIPMemString.h> #include <lib/support/RandUtils.h> #include <protocols/secure_channel/PASESession.h> // For chip::kTestDeviceNodeId #include <string.h> using chip::ByteSpan; using chip::Span; using chip::app::CommandPathFlags; using chip::app::CommandPathParams; using chip::app::clusters::OTAProviderDelegate; using chip::TLV::ContextTag; using chip::TLV::TLVWriter; constexpr uint8_t kUpdateTokenLen = 32; // must be between 8 and 32 constexpr uint8_t kUpdateTokenStrLen = kUpdateTokenLen * 2 + 1; // Hex string needs 2 hex chars for every byte constexpr size_t kUriMaxLen = 256; void GetUpdateTokenString(const chip::ByteSpan & token, char * buf, size_t bufSize) { const uint8_t * tokenData = static_cast<const uint8_t *>(token.data()); size_t minLength = chip::min(token.size(), bufSize); for (size_t i = 0; i < (minLength / 2) - 1; ++i) { snprintf(&buf[i * 2], bufSize, "%02X", tokenData[i]); } } void GenerateUpdateToken(uint8_t * buf, size_t bufSize) { for (size_t i = 0; i < bufSize; ++i) { buf[i] = chip::GetRandU8(); } } bool GenerateBdxUri(const Span<char> & fileDesignator, Span<char> outUri, size_t availableSize) { static constexpr char bdxPrefix[] = "bdx://"; chip::NodeId nodeId = chip::kTestDeviceNodeId; // TODO: read this dynamically size_t nodeIdHexStrLen = sizeof(nodeId) * 2; size_t expectedLength = strlen(bdxPrefix) + nodeIdHexStrLen + fileDesignator.size(); if (expectedLength >= availableSize) { return false; } size_t written = static_cast<size_t>(snprintf(outUri.data(), availableSize, "%s" ChipLogFormatX64 "%s", bdxPrefix, ChipLogValueX64(nodeId), fileDesignator.data())); return expectedLength == written; } OTAProviderExample::OTAProviderExample() { memset(mOTAFilePath, 0, kFilepathBufLen); } void OTAProviderExample::SetOTAFilePath(const char * path) { if (path != nullptr) { chip::Platform::CopyString(mOTAFilePath, path); } else { memset(mOTAFilePath, 0, kFilepathBufLen); } } EmberAfStatus OTAProviderExample::HandleQueryImage(chip::app::CommandHandler * commandObj, uint16_t vendorId, uint16_t productId, uint16_t imageType, uint16_t hardwareVersion, uint32_t currentVersion, uint8_t protocolsSupported, const chip::Span<const char> & location, bool clientCanConsent, const chip::ByteSpan & metadataForServer) { // TODO: add confiuration for returning BUSY status EmberAfOTAQueryStatus queryStatus = (strlen(mOTAFilePath) ? EMBER_ZCL_OTA_QUERY_STATUS_UPDATE_AVAILABLE : EMBER_ZCL_OTA_QUERY_STATUS_NOT_AVAILABLE); uint32_t delayedActionTimeSec = 0; uint32_t softwareVersion = currentVersion + 1; // This implementation will always indicate that an update is available // (if the user provides a file). bool userConsentNeeded = false; uint8_t updateToken[kUpdateTokenLen] = { 0 }; char strBuf[kUpdateTokenStrLen] = { 0 }; char uriBuf[kUriMaxLen] = { 0 }; GenerateUpdateToken(updateToken, kUpdateTokenLen); GetUpdateTokenString(ByteSpan(updateToken), strBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "generated updateToken: %s", strBuf); if (strlen(mOTAFilePath)) { // Only doing BDX transport for now GenerateBdxUri(Span<char>(mOTAFilePath, strlen(mOTAFilePath)), Span<char>(uriBuf, 0), kUriMaxLen); ChipLogDetail(SoftwareUpdate, "generated URI: %s", uriBuf); } CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID, ZCL_QUERY_IMAGE_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) }; TLVWriter * writer = nullptr; uint8_t tagNum = 0; VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), queryStatus) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutString(ContextTag(tagNum++), uriBuf) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), softwareVersion) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(tagNum++), userConsentNeeded) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->PutBytes(ContextTag(tagNum++), updateToken, kUpdateTokenLen) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); // metadata VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); return EMBER_ZCL_STATUS_SUCCESS; } EmberAfStatus OTAProviderExample::HandleApplyUpdateRequest(chip::app::CommandHandler * commandObj, const chip::ByteSpan & updateToken, uint32_t newVersion) { // TODO: handle multiple transfers by tracking updateTokens // TODO: add configuration for sending different updateAction and delayedActionTime values EmberAfOTAApplyUpdateAction updateAction = EMBER_ZCL_OTA_APPLY_UPDATE_ACTION_PROCEED; // For now, just allow any update request uint32_t delayedActionTimeSec = 0; char tokenBuf[kUpdateTokenStrLen] = { 0 }; GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, newVersion); VerifyOrReturnError(commandObj != nullptr, EMBER_ZCL_STATUS_INVALID_VALUE); CommandPathParams cmdParams = { emberAfCurrentEndpoint(), 0 /* mGroupId */, ZCL_OTA_PROVIDER_CLUSTER_ID, ZCL_APPLY_UPDATE_REQUEST_RESPONSE_COMMAND_ID, (CommandPathFlags::kEndpointIdValid) }; TLVWriter * writer = nullptr; VerifyOrReturnError((commandObj->PrepareCommand(cmdParams) == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((writer = commandObj->GetCommandDataElementTLVWriter()) != nullptr, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(0), updateAction) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError(writer->Put(ContextTag(1), delayedActionTimeSec) == CHIP_NO_ERROR, EMBER_ZCL_STATUS_FAILURE); VerifyOrReturnError((commandObj->FinishCommand() == CHIP_NO_ERROR), EMBER_ZCL_STATUS_FAILURE); return EMBER_ZCL_STATUS_SUCCESS; } EmberAfStatus OTAProviderExample::HandleNotifyUpdateApplied(const chip::ByteSpan & updateToken, uint32_t currentVersion) { char tokenBuf[kUpdateTokenStrLen] = { 0 }; GetUpdateTokenString(updateToken, tokenBuf, kUpdateTokenStrLen); ChipLogDetail(SoftwareUpdate, "%s: token: %s, version: %" PRIu32, __FUNCTION__, tokenBuf, currentVersion); emberAfSendImmediateDefaultResponse(EMBER_ZCL_STATUS_SUCCESS); return EMBER_ZCL_STATUS_SUCCESS; }
def ydim(self) -> int: if (sdims := self.spatial_dims) is not None: return self._xx.dims.index(sdims[0]) raise ValueError("Can't locate spatial dimensions")
<filename>src/server/components/personnel/relations/personnel-work-exp.model.ts import { Table, Column, Model, PrimaryKey, Unique, AutoIncrement, ForeignKey, BelongsTo, NotEmpty } from 'sequelize-typescript'; import Personnel from "../personnel.model"; import {IPersonnel} from "../personnel.interface"; import IWorkExp from './personnel-work-exp.interface'; @Table({ tableName: 'staff-work-exp' }) export default class WorkExp extends Model<WorkExp> implements IWorkExp { @AutoIncrement @Unique @PrimaryKey @Column id: number; @NotEmpty @Column @ForeignKey(() => Personnel) personnelId: number; @BelongsTo(() => Personnel) personnel: IPersonnel; @Column amountD: number; @Column amountM: number; @Column amountY: number; @Column typeId: number; }
package com.lcg.multijetty; import org.eclipse.jetty.server.*; import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.util.thread.ThreadPool; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.server.Ssl; import org.springframework.context.annotation.Bean; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; @SpringBootApplication public class MultipleJettyApplication { public static void main(String[] args) { SpringApplication.run(MultipleJettyApplication.class, args); } @Bean public JettyServletWebServerFactory servers() { JettyServletWebServerFactory serverFactory = new JettyServletWebServerFactory(); Ssl ssl = new Ssl(); ssl.setEnabled(true); ssl.setKeyStore("classpath:test.keystore"); ssl.setKeyAlias("test"); ssl.setProtocol("TLS"); ssl.setKeyStoreType("JKS"); ssl.setKeyPassword("<PASSWORD>"); ssl.setKeyStorePassword("<PASSWORD>"); serverFactory.setSsl(ssl); serverFactory.addServerCustomizers(customizer -> { HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSendServerVersion(false); List<ConnectionFactory> connectionFactories = new ArrayList<>(); connectionFactories.add(new HttpConnectionFactory(httpConfiguration)); ServerConnector connector = new ServerConnector(customizer.getServer(), 5, 5, connectionFactories.toArray(new ConnectionFactory[0])); InetSocketAddress address = new InetSocketAddress(serverFactory.getAddress(), 8890); connector.setHost(address.getHostString()); connector.setPort(address.getPort()); customizer.getServer().addConnector(connector); }); return serverFactory; } }
As Toronto Maple Leafs management continues to reshape its struggling roster, they locked up another quality offensive prospect Thursday by signing forward Andreas Johnson. The diminutive dangler joins a promising stable of Swedish prospects in the Leafs system including William Nylander, Petter Granberg and Viktor Loov. Johnson, a skilled speedster who possesses serious upside, has shown excellent progression since being selected late in the 2013 draft. The Leafs are hoping he can join the likes of countrymen Henrik Zetterberg and Patric Hornqvist as seventh-round picks that turn out to be hidden gems. With that in mind, here’s what you need to know about Andreas Johnson. Age: 20 From: Gavle, Sweden Height: 5-foot-9 Weight: 172 pounds Position: Right Wing Shoots: Left Drafted: 202nd overall by Maple Leafs in 2013 Contract status: Three-year, entry-level deal. Set to be RFA in 2018 He has been tearing it up in the Swedish Hockey League… Johnson has spent the last two seasons with Frolunda’s senior squad in the SHL where he has progressed at a rapid pace. In 2013-14 he had 15 goals, nine assists in 44 games and was named the league’s Rookie of the Year. He followed that up by improving his numbers in all offensive categories in 2014-15 finishing with a team-high 22 goals and adding 13 assists in 55 games. For a 20-year-old to put up numbers like this in the Swedish League is impressive. His 22 goals ranked fifth in the SHL and was first with nine game-winning goals, proving he can bury the puck in pressure situations. Here are some highlights from his awarding-winning rookie campaign. He will likely remain in Sweden for the time being… Leafs management will want him to get acclimatized to the North American game by spending some time in the American Hockey League with the Toronto Marlies, but that’s unlikely to happen right away next season. A week before signing his deal with the Leafs, Johnson told Swedish media he plans on staying in Sweden for the 2015-16 campaign and confirmed that Friday. Johnson knows he has to continue to develop on and off the ice and he said via his team’s website that he feels it will be positive for him to remain with Frolunda for another year. However, this doesn’t mean he won’t play for a Toronto team at some point next season. Fellow Leafs prospect Nylander did the same thing last year, splitting 2014-15 between MODO in the SHL and the Marlies. Sportsnet’s Elliotte Friedman told Dean Blundell & Co. Friday he feels Johnson has a decent shot at breaking into the NHL in the future. Johnson will attend Leafs’ development camp in July. He can come up big in a shootout… Apart from the 2013-14 season where they went 9-4 in the shootout, the Leafs have historically performed poorly in the post-overtime skills competition. Johnson would be able to help in that area when you consider he has moves like this in his arsenal. He won silver with Sweden at the 2014 WJC… One year before Nylander lit it up for Sweden at the Air Canada Centre in 2015, Johnson helped lead his country to a second place finish, registering six points in seven games at the 2014 tournament in Malmo.
def nest_fields(df: pd.DataFrame, grouping: str, new_column: str) -> pd.DataFrame: return (df.groupby(grouping) .apply(lambda row: row.replace({np.nan: None}).to_dict('records')) .reset_index() .rename(columns={0: new_column}))
package com.mangal.demoserver.Common; import com.mangal.demoserver.Model.Request; import com.mangal.demoserver.Model.User; public class Common { public static User cureentUser; public static final String UPDATE ="Update"; public static final String DELETE ="Delete"; public static final int PICK_IMAGE_REQUEST=71; public static Request currentUser; public static Request currentRequest; public static String convertCodeToStatus(String code) { if(code.equals("0")) return "Placed"; else if(code.equals("1")) return "On my way"; else return "Shipped"; } }
<reponame>matthewvanderson/MagicBot import os import coc from dotenv import load_dotenv load_dotenv() COC_EMAIL = os.getenv("COC_EMAIL") COC_PASSWORD = os.getenv("COC_PASSWORD") DB_LOGIN = os.getenv("DB_LOGIN") LINK_API_USER = os.getenv("LINK_API_USER") LINK_API_PW = os.getenv("LINK_API_PW") from disnake import utils coc_client = coc.login(COC_EMAIL, COC_PASSWORD, client=coc.EventsClient, key_count=10, key_names="DiscordBot", throttle_limit = 25) import certifi ca = certifi.where() import motor.motor_asyncio client = motor.motor_asyncio.AsyncIOMotorClient(DB_LOGIN) import disnake #from coc_client import utils from coc.ext import discordlinks link_client = discordlinks.login(LINK_API_USER, LINK_API_PW) async def player_handle(ctx, tag): try: clashPlayer = await coc_client.get_player(tag) except: embed = disnake.Embed(description=f"{tag} is not a valid player tag.", color=disnake.Color.red()) return await ctx.send(embed=embed) async def getTags(ctx, ping): if (ping.startswith('<@') and ping.endswith('>')): ping = ping[2:len(ping) - 1] if (ping.startswith('!')): ping = ping[1:len(ping)] id = ping tags = await link_client.get_linked_players(id) return tags async def getPlayer(playerTag): #print(playerTag) try: #print("here") clashPlayer = await coc_client.get_player(playerTag) #print(clashPlayer.name) return clashPlayer except: return None async def getClan(clanTag): try: clan = await coc_client.get_clan(clanTag) return clan except: return None async def verifyPlayer(playerTag, playerToken): verified = await coc_client.verify_player_token(playerTag, playerToken) return verified async def getClanWar(clanTag): try: war = await coc_client.get_clan_war(clanTag) return war except: return None async def pingToMember(ctx, ping): ping = str(ping) if (ping.startswith('<@') and ping.endswith('>')): ping = ping[2:len(ping) - 1] if (ping.startswith('!')): ping = ping[1:len(ping)] try: member = await ctx.guild.fetch_member(ping) return member except: return None async def pingToRole(ctx, ping): ping = str(ping) if (ping.startswith('<@') and ping.endswith('>')): ping = ping[2:len(ping) - 1] if (ping.startswith('&')): ping = ping[1:len(ping)] try: roles = await ctx.guild.fetch_roles() role = utils.get(roles, id=int(ping)) return role except: return None async def pingToChannel(ctx, ping): ping = str(ping) if (ping.startswith('<#') and ping.endswith('>')): ping = ping[2:len(ping) - 1] try: channel = ctx.guild.get_channel(int(ping)) return channel except: return None
<filename>src/components/Activities/Activity1/index.tsx import React from 'react'; import '../../styles/Activity1.scss'; import Game1EndScreen from '../../../assets/activity1/game1-endscreen.svg'; import ComputerSvg from '../../../assets/activity1/search-highlighted-computer.svg'; import Carousel from '../../shared/Carousel'; import Computer from '../../shared/Computer'; import { TextBubbleStyles } from '../../shared/PlaynetConstants'; import { SoundTrack } from '../../shared/soundtrack'; import TransitionSlide from '../../shared/TransitionSlide'; import ComputerConversation from './ComputerConversation'; import CipherGame, { SuccessCipherGameState } from './Game1'; import AmbiguousPhrasingGame from './Game2'; import TextBubble from './TextBubble'; // gets all files that end in .jpg .svg or .png from given folder const activity1Images = require.context('../../../assets/activity1/', true, /\.(svg|jpg|png)$/); const paths = activity1Images.keys(); const requiredImages = paths.map(path => activity1Images(path).default); const sharedImages = require.context('../../../assets/shared/', true, /\.(svg|jpg|png)$/); const sharedImagesPaths = sharedImages.keys(); requiredImages.push(... (sharedImagesPaths.map(path => sharedImages(path).default))); function Activity1(): JSX.Element { const timeBtwnWords = 3000; const content = [ { child: <img src={ComputerSvg} width='40%' alt='Image of Youtube on Computer' />, bottomText: 'How does YouTube bring you the videos you want?', bottomText2: 'Let\'s dive into what happens in the search bar.', animationTime: 5.5, soundtrack: SoundTrack.Activity1_1, }, { child: <div className='content'> <div id='binary-text-bubble'> <TextBubble textBubbleStyle={TextBubbleStyles.LARGE} text='1101010100' /> </div> <img src={ComputerSvg} width='214px' alt='Image of Youtube on Computer' /> </div>, bottomText: 'Computers don\'t know English...', bottomText2: 'So how does it know what you are saying?', animationTime: 4.5, soundtrack: SoundTrack.Activity1_2, }, { bottomText: 'Computers have to learn just like how we do: by trial and error!', child: <ComputerConversation timeBtwnWords={timeBtwnWords} />, animationTime: Math.max(3 * timeBtwnWords / 1000, 4.5), soundtrack: SoundTrack.Activity1_3, }, { child: <TransitionSlide buttonText={'Play Game'}> <div>Imagine that you are a computer trying to learn what the alien wants.</div> <div>Can you figure out what the alien wants and keep it happy?</div> <p>Note: we don&apos;t know what the alien is saying. We will need to guess!</p> </TransitionSlide>, showNext: false, animationTime: 5.3, soundtrack: SoundTrack.Activity1_4, }, { topText: 'Try to guess what image the alien wants.', child: <CipherGame numStars={0} skips={5} />, showNext: false, hasSound: true, hasGameSound: true, }, { topText: 'Try to guess what image the alien wants.', child: <SuccessCipherGameState numStars={1} />, showNext: false, hasSound: true, animationTime: 2.5, soundtrack: SoundTrack.Activity1_G1_Center, }, { topText: 'Try to guess what image the alien wants.', child: <CipherGame numStars={1} skips={3} />, showNext: false, hasSound: true, hasGameSound: true, }, { topText: 'Try to guess what image the alien wants.', child: <SuccessCipherGameState numStars={2} />, showNext: false, hasSound: true, animationTime: 2.5, soundtrack: SoundTrack.Activity1_G1_Center, }, { topText: 'Try to guess what image the alien wants.', child: <CipherGame numStars={2} skips={1} />, showNext: false, hasSound: true, hasGameSound: true, }, { bottomText: 'Good news, we just found a translator that can help us understand the alien!', child: <div> <img src={Game1EndScreen} /> </div>, animationTime: 4.5, soundtrack: SoundTrack.Activity1_G1_G2, }, { child: <TransitionSlide buttonText={'Play Game'}> <div>But even if we know what the alien is saying... can you figure out what they mean?</div> <p>Note: One sentence can mean two things, so we might need to guess!</p> </TransitionSlide>, showNext: false, animationTime: 9.5, soundtrack: SoundTrack.Activity1_G2_Intro, }, { topText: 'Try to guess what the alien is talking about.', child: <AmbiguousPhrasingGame />, showNext: false, hasSound: true, hasGameSound: true, }, { child: <> <h2 id={'body-text'}> Being a computer sure isn&apos;t easy... next time you use a search bar, </h2> <h2 id={'body-text'}> now you know what it has to deal with! </h2> <Computer> <> <p> Computers in the real world use artificial intelligence (AI) to remember what they learn from trial and error. They can share what they learn with other computers to give us a better searching experience. </p> When you&apos;re older, you&apos;ll get the chance to learn how to code so that you can learn how AI works in more detail! </> </Computer> </>, hasSound: false, // animationTime: 6, // soundtrack: SoundTrack.Activity1_End, }, ]; return ( <Carousel title={'Lost in Translation'} hasSound={true} imagesToPreload={requiredImages}> {content} </Carousel> ); } export default Activity1;
<gh_stars>1-10 package com.aspose.barcode.examples.TwoD_barcodes.utility_features; import java.awt.Font; import java.io.IOException; import com.aspose.barcode.BarCodeImageFormat; import com.aspose.barcode.generation.CodeLocation; import com.aspose.barcode.examples.Utils; import com.aspose.barcode.generation.BarcodeGenerator; public class HidingCodeTextThatIsTooLongToDisplay { public static void main(String[] args) throws IOException { // The path to the resource directory. String dataDir = Utils.getDataDir(HidingCodeTextThatIsTooLongToDisplay.class) + "2DBarcode/UtilityFeatures/"; hideTheBarcodeCodeText(dataDir); reduceTheCodeTextFontSize(dataDir); } public static void hideTheBarcodeCodeText(String dataDir) throws IOException { // ExStart: hideTheBarcodeCodeText BarcodeGenerator generator = new BarcodeGenerator(com.aspose.barcode.EncodeTypes.MACRO_PDF_417); generator.setCodeText( "The quick brown fox jumps over the lazy dog\n The quick brown fox jumps over the lazy dog\n"); generator.getParameters().getBarcode().getCodeTextParameters().setLocation(CodeLocation.BELOW); generator.save(dataDir + "datamatrix.bmp", BarCodeImageFormat.BMP); // ExEnd: hideTheBarcodeCodeText } public static void reduceTheCodeTextFontSize(String dataDir) throws IOException { // ExStart: reduceTheCodeTextFontSize BarcodeGenerator generator = new BarcodeGenerator(com.aspose.barcode.EncodeTypes.DATA_MATRIX); generator.setCodeText( "The quick brown fox jumps over the lazy dog\n The quick brown fox jumps over the lazy dog\n"); generator.getParameters().getBarcode().getCodeTextParameters().setLocation(CodeLocation.NONE); generator.getParameters().getBarcode().getCodeTextParameters().getFont().setFamilyName("Serif"); generator.getParameters().getBarcode().getCodeTextParameters().getFont().setStyle(20); generator.save(dataDir + "reduceFontSize.bmp", BarCodeImageFormat.BMP); // ExEnd: reduceTheCodeTextFontSize } }
Synthesis, DNA binding, and cleaving properties of an ellipticine-salen.copper conjugate. The synthesis of a DNA-cutting agent that conjugates an ellipticine chromophore and a copper complex of bis(salicylidene)ethylenediamine, referred to as a salen, is reported. The presence of the salen.Cu complex allows cleavage of DNA via oxygen-based radicals, and the ellipticine moiety serves as a DNA anchor. Spectroscopic measurements indicate that the intercalation geometry of the ellipticine chromophore is preserved with the hybrid. The cleavage is much more efficient with the conjugate than with the Schiff base copper complex alone.
def _file_to_dict(self): parameters = {} try: for line in self._autosave_file_lines(): try: p, v = line.split(self.autosave_separator, 1) parameters[p] = v.strip() except ValueError: print_and_log("ValueError when reading autosave file, ignoring line: '{}'".format(line)) except (IOError, ValueError) as e: print_and_log("Error while reading autosave file at '{}': {}: {}" .format(self._filepath, e.__class__.__name__, e)) return parameters
<reponame>kiranmaragoni/parental-control {-# LANGUAGE OverloadedStrings #-} module Lib where import Checking import CliOpts import Config import Control.Concurrent import Control.Monad import StateLogger import System.Directory import System.Environment import System.FilePath import System.IO import System.Process import Database.SQLite.Simple someFunc :: IO () someFunc = do args <- getArgs (opts, _) <- compilerOpts (args) config <- readConfig $ optConfigFilePath opts let stateFile = (statePath config) ++ "/state" s <- loadState stateFile state <- newMVar s -- putStrLn $ optStateFile opts -- let (Just val) = config createDirectoryIfMissing True (statePath config) conn <- open ((statePath config) ++ "/log.db") -- Open data base file execute_ conn "CREATE TABLE IF NOT EXISTS log (tm TIMESTAMP, user TEXT)" forkIO $ stateLoggerLoop stateFile state checkingLoop config conn state
/** * \headerfile Stopwatch.h * * \brief simple timing of function calls. * * Mimics the behavior of tic/toc of Matlab and throws an error if toc() is called without starting a timer before. * * Example: * Stopwatch::tic(); starts timer A * * Stopwatch::tic(); starts timer B * method1(); * double time1 = Stopwatch::toc(); stops timer B and returns time elapsed since timer B started * * Stopwatch::tic(); starts timer C * method2(); * double time2 = Stopwatch::toc(); stops timer C * * Stopwatch::toc("finished"); stops timer A, thus this is approx. time1 + time2. and outputs a message. * * \author behley */ #ifndef STOPWATCH_H_ #define STOPWATCH_H_ #include <chrono> #include <string> #include <vector> namespace rv { class Stopwatch { public: /** \brief starts a timer. **/ static void tic(); /** \brief stops the last timer started and outputs \a msg **/ static double toc(); /** \brief number of active stopwatches. **/ static size_t active() { return stimes.size(); } protected: static std::vector<std::chrono::system_clock::time_point> stimes; }; } #endif /* STOPWATCH_H_ */
<filename>pipeline_cortical_thickness.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os from dependencies import FILEDIR, ROOTDIR from utils import CreateTemplate from utils import AtroposSegmentation from utils.HelperFunctions import Output, FileOperations, Imaging if __name__ == "__main__": try: Imaging.set_viewer() print("viewer set!") except Exception: Output.msg_box(text="Something went wrong with defining the standard location for ITK-snap!", title="Problem defining ITKSnap location") # Get files ready to analyse using the functions in the HelperFunctions.py module # subjects2analyse = list(FileOperations.list_folders(os.path.join(ROOTDIR, FILEDIR, 'patients'), prefix='[\d+]')) group_template = os.path.join(ROOTDIR, FILEDIR, 'group_template.nii.gz') # if not os.path.isfile(group_template): # CreateTemplate.all_subjects(subjects=subjects2analyse, output_dir=FILEDIR) # imaging, fileID = PreprocessT1MRI.create_list_of_subjects(subjects=subjects2analyse) # PreprocessT1MRI.preprocessMRIbatch(imaging=imaging, template_sequence=group_template, fileID=fileID) imaging_preproc, ID = AtroposSegmentation.preprocessed_subjects(folder=os.path.join(ROOTDIR, FILEDIR, 'preprocessed')) AtroposSegmentation.create_mask(imaging_preproc, fileID=ID) # creates mask because of threshold_image problem AtroposSegmentation.segmentationAtropos(imaging=imaging_preproc, template_sequence=group_template, fileID=ID)
def wrap_description(description, column_width): d_lines = textwrap.wrap(description, column_width) if len(d_lines) < 9: d_lines += [""] * (9 - len(d_lines)) return d_lines
<gh_stars>1-10 #pragma once #include "BasicTypes.h" #include "BoxTypes.h" namespace formulae{ namespace node { hlist_t makeChar(style_t st, family_t fam, charCode_t ch); std::tuple<NodeRef, dist_t, bool> makeNucChar(style_t st, bool isOp, family_t fam, charCode_t ch);}}
<filename>wp-content/themes/portfolio/react-src/src/sections/Footer/index.tsx import React from 'react' import {inject, observer} from 'mobx-react' import {Container, Row, Col} from 'react-bootstrap'; import {SocialMediaStore} from '../../stores/SocialMedia' import SocialMediaButton from '../../components/Misc/SocialMediaButton' import './index.scss' interface Props { SocialMediaStore?: SocialMediaStore } @inject('SocialMediaStore') @observer class Footer extends React.Component<Props> { componentWillMount() { if (!this.props.SocialMediaStore.fetching) { this.props.SocialMediaStore.fetch() console.log('Fetching from Footer'); } } private get currentYear() { return (new Date()).getFullYear() } renderSocialMediaButtonList() { return this.props.SocialMediaStore.accounts.map(account => { return ( <li key={account.name}> <SocialMediaButton link={account.link} iconClasses={account.iconClasses}/> </li> ) }); } render() { return ( <footer> <Container> <Row> <Col sm={6}> <div className="copyright-text"> <p>CopyRight © {this.currentYear} <NAME> All Rights Reserved</p> </div> </Col> <Col sm={6}> <div className="pull-right"> <ul> {this.renderSocialMediaButtonList()} </ul> </div> </Col> </Row> </Container> </footer> ) } } export default Footer;
#pragma once #include "il2cpp.h" bool FieldFader__get_IsBusy (FieldFader_o* __this, const MethodInfo* method_info); void FieldFader__OnUpdate (FieldFader_o* __this, float deltaTime, const MethodInfo* method_info); void FieldFader__FadeOut (FieldFader_o* __this, int32_t type, float time, const MethodInfo* method_info); void FieldFader__FadeIn (FieldFader_o* __this, int32_t type, float time, const MethodInfo* method_info); void FieldFader__PlayAnimation (FieldFader_o* __this, int32_t type, float time, const MethodInfo* method_info); void FieldFader__SetActiveFade (FieldFader_o* __this, int32_t type, const MethodInfo* method_info); void FieldFader___ctor (FieldFader_o* __this, const MethodInfo* method_info);
<reponame>FreakStar03/MedAlthea from PyQt5 import QtCore, QtGui, QtWidgets class Ui_addMedical(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(900, 850) self.widget = QtWidgets.QWidget(Dialog) self.widget.setGeometry(QtCore.QRect(0, 0, 900, 850)) self.widget.setStyleSheet("background-color: rgb(255, 255, 255);") self.widget.setObjectName("widget") self.medicalName = QtWidgets.QLineEdit(self.widget) self.medicalName.setGeometry(QtCore.QRect(70, 310, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.medicalName.setFont(font) self.medicalName.setStyleSheet("border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.medicalName.setText("") self.medicalName.setObjectName("medicalName") self.email = QtWidgets.QLineEdit(self.widget) self.email.setGeometry(QtCore.QRect(70, 400, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.email.setFont(font) self.email.setStyleSheet("border:2px solid rgb(85, 0, 255);\n" "border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.email.setText("") self.email.setObjectName("email") self.pincode = QtWidgets.QLineEdit(self.widget) self.pincode.setGeometry(QtCore.QRect(70, 490, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.pincode.setFont(font) self.pincode.setStyleSheet("border:2px solid rgb(85, 0, 255);\n" "border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.pincode.setText("") self.pincode.setObjectName("pincode") self.submit = QtWidgets.QPushButton(self.widget) self.submit.setGeometry(QtCore.QRect(280, 650, 321, 51)) font = QtGui.QFont() font.setPointSize(24) self.submit.setFont(font) self.submit.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.submit.setStyleSheet("border-radius:20px;\n" "background-color: rgb(0, 153, 112);\n" "color: rgb(255, 255, 255);") self.submit.setObjectName("submit") self.phoneNumber = QtWidgets.QLineEdit(self.widget) self.phoneNumber.setGeometry(QtCore.QRect(450, 310, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.phoneNumber.setFont(font) self.phoneNumber.setStyleSheet("border:2px solid rgb(85, 0, 255);\n" "border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.phoneNumber.setText("") self.phoneNumber.setObjectName("phoneNumber") self.address = QtWidgets.QLineEdit(self.widget) self.address.setGeometry(QtCore.QRect(450, 400, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.address.setFont(font) self.address.setStyleSheet("border:2px solid rgb(85, 0, 255);\n" "border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.address.setText("") self.address.setObjectName("address") self.frame = QtWidgets.QFrame(self.widget) self.frame.setGeometry(QtCore.QRect(0, 0, 900, 71)) self.frame.setStyleSheet("background-color: rgb(0, 153, 112);") self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.back = QtWidgets.QPushButton(self.frame) self.back.setGeometry(QtCore.QRect(16, 15, 91, 41)) font = QtGui.QFont() font.setPointSize(18) self.back.setFont(font) self.back.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.back.setStyleSheet("border-radius:10px;\n" "background-color: rgb(255, 255, 255);\n" "color: rgb(0, 153, 112);;") self.back.setObjectName("back") self.website = QtWidgets.QLineEdit(self.widget) self.website.setGeometry(QtCore.QRect(450, 490, 330, 50)) font = QtGui.QFont() font.setPointSize(18) self.website.setFont(font) self.website.setStyleSheet("border:2px solid rgb(85, 0, 255);\n" "border-radius:20px;\n" "border:2px solid black;\n" "padding:10px;\n" "color: rgb(52, 52, 52);\n" "\n" "") self.website.setText("") self.website.setObjectName("website") self.addPhoto = QtWidgets.QPushButton(self.widget) self.addPhoto.setGeometry(QtCore.QRect(330, 560, 221, 41)) font = QtGui.QFont() font.setPointSize(16) self.addPhoto.setFont(font) self.addPhoto.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.addPhoto.setStyleSheet("border-radius:20px;\n" "background-color: rgb(0, 153, 112);\n" "color: rgb(255, 255, 255);") self.addPhoto.setObjectName("addPhoto") self.label = QtWidgets.QLabel(self.widget) self.label.setGeometry(QtCore.QRect(260, 140, 401, 81)) font = QtGui.QFont() font.setPointSize(30) font.setBold(True) self.label.setFont(font) self.label.setLayoutDirection(QtCore.Qt.LeftToRight) self.label.setStyleSheet("color:rgb(0, 153, 112);\n" "") self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setOpenExternalLinks(False) self.label.setObjectName("label") self.message = QtWidgets.QLabel(self.widget) self.message.setGeometry(QtCore.QRect(337, 615, 221, 31)) self.message.setStyleSheet("color: rgb(255, 21, 0);") self.message.setText("") self.message.setAlignment(QtCore.Qt.AlignCenter) self.message.setObjectName("message") self.phoneMessage = QtWidgets.QLabel(self.widget) self.phoneMessage.setGeometry(QtCore.QRect(470, 360, 291, 31)) self.phoneMessage.setStyleSheet("color: rgb(255, 21, 0);") self.phoneMessage.setText("") self.phoneMessage.setAlignment(QtCore.Qt.AlignCenter) self.phoneMessage.setObjectName("phoneMessage") self.emailMessage = QtWidgets.QLabel(self.widget) self.emailMessage.setGeometry(QtCore.QRect(90, 450, 271, 31)) self.emailMessage.setStyleSheet("color: rgb(255, 21, 0);") self.emailMessage.setText("") self.emailMessage.setAlignment(QtCore.Qt.AlignCenter) self.emailMessage.setObjectName("emailMessage") self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.medicalName.setPlaceholderText(_translate("Dialog", "Name*")) self.email.setPlaceholderText(_translate("Dialog", "Email*")) self.pincode.setPlaceholderText(_translate("Dialog", "Pincode*")) self.submit.setText(_translate("Dialog", "Create")) self.phoneNumber.setPlaceholderText(_translate("Dialog", "Phone*")) self.address.setPlaceholderText(_translate("Dialog", "Address*")) self.back.setText(_translate("Dialog", "Back")) self.website.setPlaceholderText(_translate("Dialog", "Website")) self.addPhoto.setText(_translate("Dialog", "Add photo")) self.label.setToolTip(_translate("Dialog", "<html><head/><body><p align=\"center\"><br/></p></body></html>")) self.label.setWhatsThis(_translate("Dialog", "<html><head/><body><p align=\"center\"><br/></p></body></html>")) self.label.setText(_translate("Dialog", "Create Medical Account"))
# Copyright 2019 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. """Template based text parser. This module implements a parser, intended to be used for converting human readable text, such as command output from a router CLI, into a list of records, containing values extracted from the input text. A simple template language is used to describe a state machine to parse a specific type of text input, returning a record of values for each input entity. https://github.com/google/textfsm """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json from absl import flags import textfsm from textfsm import TextFSMError # pylint: disable=unused-import from textfsm import TextFSMTemplateError # pylint: disable=unused-import from textfsm import Usage # pylint: disable=unused-import FLAGS = flags.FLAGS class TextFSMOptions(textfsm.TextFSMOptions): """Additional options to TextFSMOptionsBase.""" class Blank(textfsm.TextFSMOptions.OptionBase): """Value is always blank.""" def OnCreateOptions(self): if len(self.value.options) != 1: raise textfsm.TextFSMTemplateError( 'Blank is a mutually exclusive option.') def OnSaveRecord(self): self.value.value = '' class Verbose(textfsm.TextFSMOptions.OptionBase): """Value only shown in 'verbose' mode.""" def OnCreateOptions(self): if 'Key' in self.value.OptionNames(): raise textfsm.TextFSMTemplateError( 'Options "Key" and "Verbose" are mutually exclusive') def OnGetValue(self): # pylint: disable=protected-access if not self.value.fsm._verbose: raise textfsm.SkipValue def OnSaveRecord(self): # pylint: disable=protected-access if not self.value.fsm._verbose: raise textfsm.SkipValue class Key(textfsm.TextFSMOptions.OptionBase): """Value is a key in the row.""" def OnCreateOptions(self): if 'Verbose' in self.value.OptionNames(): raise textfsm.TextFSMTemplateError( 'Options "Key" and "Verbose" are mutually exclusive') class TextFSM(textfsm.TextFSM): """Adds support for additional options to TextFSM. Options useful for formatting and displaying of the data. """ def __init__(self, template, verbose=True, options_class=TextFSMOptions): """Initialises and also parses the template file.""" # Display 'all' or 'only some' of the columns. # For real estate challenged displays. self._verbose = verbose super(TextFSM, self).__init__(template, options_class=options_class) def Dump(self): """Dump the table in a pseudo-JSON format. ParseText() must have previously been called in order to populate the internal result. Returns: A str. The first line is a JSON representation of the header. The following lines are JSON representations of each row. """ output = [json.dumps(self.header, separators=(',', ':'))] for row in self._result: output.append(json.dumps(row, separators=(',', ':'))) return '\n'.join(output)
. Traditional Chinese medicine(TCM) is a complex system with multiple chemical compositions. The most significant character of TCM is that the chemical compositions interact with each other by multi-target synergism to treat diseases. Previous reports mainly focused on the investigation of single signaling pathway detection or the phenotypic analysis of proteomics difference; however, no studies have been conducted on the identification of direct targets of TCM. Therefore, it is difficult to analyze the molecular mechanism of traditional Chinese medicine from the target source, and it is difficult to explain its traditional efficacy scientifically, thus seriously affecting its clinical application and internationalization. In this article, we discussed the methodology for the identification of direct TCM targets(groups), and presented the strategy for preparation of TCM chemical composition solid coupling beads, as well as of enrichment and identification strategy of target proteins based on photosensitive coupling technique. We also discussed the advantages and limitations of this strategy, and put forward some new ideas for the future developments. We hope this article can provide some guidance and reference significance for the researchers on TCM pharmacology study, especially on target identification.
Pharmacological actions and underlying mechanisms of Catechin: A review. BACKGROUND Catechin is a phytochemical and is a major component of our daily use beverages, which has shown great potential in improving general health and fighting against several medical conditions. Clinical studies have confirmed its effectiveness in conditions ranging from acute upper respiratory tract infection, neuroprotection, to cardio-protection effects. Though most studies relate their potential to anti-oxidative action and radical scavenging action, still the mechanism of action is not clearly understood. OBJECTIVE The present review article is focused on addressing various pharmacological actions and underlying mechanisms of catechin. Additionally, we will try to figure out the major adverse effect and success in trials with catechin and lead to a conclusion for its effectiveness. METHODS This review article is based on the recent/ most cited papers of PubMed and Scopus databases. DESCRIPTION Catechin can regulate Nrf2 and NFkB pathways in ways that impact oxidative stress and inflammation by influencing gene expression. Other pathways like MAPKs and COMT and receptor tyrosine kinase are also affected by catechin and EGCG that alter their action and barge the cellular activity. This review article explored the structural aspect of catechin and its different isomers and analogs. It also evaluated its various therapeutic and pharmacological arrays . CONCLUSION Catechin and its stereo-isomers have shown their effectiveness as anti-inflammatory, anti-diabetic, anti-cancer, anti-neuroprotective, bactericidal, memory enhancer, anti-arthritis, and hepato-protective mainly through its activity to alter the pathway by NF-κB, Nrf-2, TLR4/NF-κB, COMT, and MAPKs.
<gh_stars>0 package claire.sample; public class SungJuckV6DT0 extends SungJuckV6V0 { public SungJuckV6DT0() { } public SungJuckV6DT0(String name, int kor, int eng, int mat) { // SungJuckV6V0의 생성자 호출 super(name, kor, eng, mat); } }
<filename>app/src/main/java/com/example/quizgame/QuizSession.java package com.example.quizgame; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONException; public class QuizSession extends AppCompatActivity { Button response1; Button response2; Button response3; Button response4; TextView responseView ; Question q; public void buttonClickEvent(final Button b){ q.incrementQuestionCount(); if(b.getText() == q.getCorrect_answer()){ b.setBackgroundColor(Color.GREEN); q.incrementCorrectAnswerCount(); } else b.setBackgroundColor(Color.RED); new Handler().postDelayed(new Runnable() { @Override public void run() { b.setBackgroundColor(Color.LTGRAY); if(q.getQuestionCount() != 10) q.writeResponse(responseView,response1,response2,response3,response4); } }, 300); if(q.getQuestionCount() == 10){ Intent intent = new Intent(this,MainActivity.class); intent.putExtra("sessionResult","hai ottenuto " + q.getCorrectAnswerCount() + " punti"); startActivity(intent); } } public void response1Click(View view) { buttonClickEvent(response1); } public void response2Click(View view) { buttonClickEvent(response2); } public void response3Click(View view) { buttonClickEvent(response3); } public void response4Click(View view) { buttonClickEvent(response4); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); responseView = findViewById(R.id.responseView); response1 = findViewById(R.id.response1); response2 = findViewById(R.id.response2); response3 = findViewById(R.id.response3); response4 = findViewById(R.id.response4); try { q = new Question(getIntent().getStringExtra("questions")); } catch (JSONException e) { e.printStackTrace(); } q.resetQuestionCount(); q.resetCorrectAnswerCount(); q.writeResponse(responseView,response1,response2,response3,response4); } }
<gh_stars>1-10 #include "WebServerSTPlus.h" const char legalChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890/.-_~"; /***********************************************************************************//** * @brief WebServerSTPlus() Initializer * Once the WebServer is initialezed network communications are active * @param[in] mac - The mac address of the WebServer; must be unique on network * @param[in] ip - The ip address for the WebServer if DHCP is not used * @param[in] gateway - Set the networks gateway * @param[in] subnet - Set the networks subnet mask * @param[in] UseDHCP - Attempt to connect using DHCP (IP Address will be dynamic) * @param[in] Port - The network port number to use (HTML is always 80) * @notes * Requires Arduino Ethernet Library - include <Ethernet.h> * * <B>Example:</B>@code{.cpp} * WebServerSTPlus *webserver; * webserver = new WebServerSTPlus(mac,ip,gateway,subnet,false,80); @endcode **************************************************************************************/ WebServerSTPlus::WebServerSTPlus(byte mac[], IPAddress ip, IPAddress gateway, IPAddress subnet, bool UseDHCP, int Port) { server = new EthernetServer(Port); // Create EthernetServer object digitalWrite(W5100_CSPIN,HIGH); // disable w5100 SPI while starting SD DB1((F("Starting SD.."))); if(!SD.begin(SD_CSPIN)) DB1L((F("failed"))); else DB1L((F("ok"))); //---------- Start Ethernet Connection -------------------------------- if(UseDHCP){ if (Ethernet.begin(mac) == 0) { DB1L(("Failed to configure Ethernet using DHCP")); UseDHCP = false; } //Default to Static Settings } if(!UseDHCP) Ethernet.begin(mac, ip, gateway, gateway, subnet); DB1(("Server IP address: ")); // Print local IP address for (byte b = 0; b < 4; b++) { DB1((Ethernet.localIP()[b], DEC)); DB1((".")); } DB1L(()); delay(2000); server->begin(); unsigned long thisTime = millis(); for(int i=0;i<MAX_SOCK_NUM;i++) { connectTime[i] = thisTime; } DB1L((F("Ready"))); } /***********************************************************************************//** * @brief doloop() * Trigger function - needs to be called inside the main sketch loop() **************************************************************************************/ void WebServerSTPlus::doloop(char *nc_code) { EthernetClient client = server->available(); if(client) { boolean currentLineIsBlank = true; boolean currentLineIsGet = true; int tCount = 0; char tBuf[256]; int r,t; char *pch; char ext[5] = ""; char methodBuffer[8]; char requestBuffer[238]; char pageBuffer[48]; char paramBuffer[238]; char protocolBuffer[9]; char fileName[32]; char fileType[4]; int clientCount = 0; int loopCount = 0; // this controls the timeout requestNumber++; DB1((F("\r\nClient request #"))); DB1((requestNumber)); DB1((F(": "))); while (client.connected()) { while(client.available()) { // if packet, reset loopCount // loopCount = 0; char c = client.read(); if(currentLineIsGet && tCount < 255) { tBuf[tCount] = c; tCount++; tBuf[tCount] = 0; } if (c == '\n' && currentLineIsBlank) { DB1L((tBuf)); while(client.available()) client.read(); int scanCount = sscanf(tBuf,"%7s %237s %8s",methodBuffer,requestBuffer,protocolBuffer); if(scanCount != 3) { DB1L((F("bad request"))); sendBadRequest(client); return; } // Process ?nc= (numeric control) tags pch = strtok(requestBuffer,"?"); if(pch != NULL) { //strncpy(fileName,pch,31); //strncpy(tBuf,pch,255); strcpy(fileName,pch); strcpy(tBuf,pch); pch = strtok(NULL,"?"); if(pch != NULL) { // Process URL parameters strcpy(paramBuffer,pch); // Numeric Control (nc=) if( strncmp(pch,"nc=",3) == 0 ) { strcpy(nc_code,pch+3); DB1((F("param nc_code: ")));DB1L((nc_code)); // File Write (fw=) } else if ( strncmp(pch,"fw=",3) == 0 ) { //strcpy(paramBuffer,pch+3); urldecode(paramBuffer,pch+3); sdWrite(fileName,paramBuffer,WRITE); // File Append (fa=) } else if ( strncmp(pch,"fa=",3) == 0 ) { //strcpy(paramBuffer,pch+3); urldecode(paramBuffer,pch+3); sdWrite(fileName,paramBuffer,APPEND); // Undefined } else { DB1((F("undefined param: ")));DB1L((paramBuffer)); } client.stop(); return; } else { paramBuffer[0] = 0; } } strtoupper(requestBuffer); strtoupper(tBuf); DB1((F("method = "))); DB1L((methodBuffer)); if(strcmp(methodBuffer,"GET") != 0 && strcmp(methodBuffer,"HEAD") != 0) { sendBadRequest(client); return; } for(int x = 0; x < strlen(requestBuffer); x++) { if(strchr(legalChars,requestBuffer[x]) == NULL) { DB1L((F("bad character"))); sendBadRequest(client); return; } } DB1((F("params = "))); DB1L((paramBuffer)); DB1((F("protocol = "))); DB1L((protocolBuffer)); // if dynamic page name (this code looks in-complete if(strcmp(requestBuffer,"/MYTEST.PHP") == 0) { DB1L((F("dynamic page"))); } else { //----------- PARSE ---------------------- // Home page if(strcmp(fileName,"/") == 0) { strcpy(fileName,"/INDEX.HTM"); } //vvv[ File Name (Modify for SFN-8.3) ]vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv DB1((F("SD file = "))); DB1L((fileName)); pch = strrchr(fileName,'.'); //ptr to extension if (pch!=NULL) { int extlen = strlen(pch); //record original extension length memcpy(ext,pch,4);pch[0]='\0'; //ext=4-digit copy, truncate name strcpy(fileType,ext+1); //Copy file type strtoupper(fileType); //All-caps for matching if(extlen>4) strcat(fileName,"~1"); //Truncate files with long ext } pch = strrchr(fileName,'/'); //ptr to filename if (pch!=NULL) { if (strlen(pch)>9) { pch[7]='~';pch[8]='1';pch[9]='\0'; //Truncate fileName to 8-digits } } strcat(fileName,ext); //Concate extension DB1((F("SD Mod file(FSN-8.3) = "))); DB1L((fileName)); //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Check FileName if(strlen(fileName) > 30) { DB1L((F("filename too long"))); sendBadRequest(client); return; } else if(strlen(fileType) > 3 || strlen(fileType) < 1) { DB1((F("fileType '")));DB1((fileType)); DB1((F("' is wrong size of")));DB1((strlen(fileType))); DB1L((F("file type invalid size"))); sendBadRequest(client); return; } else { DB1L((F("filename format ok"))); if(SD.exists(fileName)) { // SRAM check DB1((F("SRAM = "))); DB1L((freeRam())); DB1((F("file found.."))); File myFile = SD.open(fileName); if(!myFile) { DB1L((F("open error"))); sendFileNotFound(client); return; } else DB1((F("opened.."))); strcpy_P(tBuf,PSTR("HTTP/1.0 200 OK\r\nContent-Type: ")); // send Content-Type if(strcmp(fileType,"HTM") == 0) strcat_P(tBuf,PSTR("text/html")); else if(strcmp(fileType,"PHP") == 0) strcat_P(tBuf,PSTR("text/html")); else if(strcmp(fileType,"TXT") == 0) strcat_P(tBuf,PSTR("text/plain")); else if(strcmp(fileType,"CSS") == 0) strcat_P(tBuf,PSTR("text/css")); else if(strcmp(fileType,"GIF") == 0) strcat_P(tBuf,PSTR("image/gif")); else if(strcmp(fileType,"JPG") == 0) strcat_P(tBuf,PSTR("image/jpeg")); else if(strcmp(fileType,"JS") == 0) strcat_P(tBuf,PSTR("application/javascript")); else if(strcmp(fileType,"ICO") == 0) strcat_P(tBuf,PSTR("image/x-icon")); else if(strcmp(fileType,"PNG") == 0) strcat_P(tBuf,PSTR("image/png")); else if(strcmp(fileType,"PDF") == 0) strcat_P(tBuf,PSTR("application/pdf")); else if(strcmp(fileType,"ZIP") == 0) strcat_P(tBuf,PSTR("application/zip")); else strcat_P(tBuf,PSTR("text/plain")); strcat_P(tBuf,PSTR("\r\nConnection: close\r\n\r\n")); client.write(tBuf); if(strcmp(methodBuffer,"GET") == 0) { DB1((F("send.."))); while(myFile.available()) { clientCount = myFile.read(tBuf,64); client.write((byte*)tBuf,clientCount); } } myFile.close(); DB1L((F("closed"))); client.stop(); DB1L((F("disconnected"))); return; } else { DB1L((F("File not found"))); sendFileNotFound(client); root = SD.open("/"); printDirectory(root, 3); return; } } } pch = strtok(paramBuffer,"&"); while(pch != NULL) { if(strncmp(pch,"t=",2) == 0) { t = atoi(pch+2); DB1(("t=")); DB1L((t,DEC)); } if(strncmp(pch,"r=",2) == 0) { r = atoi(pch+2); DB1(("r=")); DB1L((r,DEC)); } pch = strtok(NULL,"& "); } DB1L((F("Sending response"))); strcpy_P(tBuf,PSTR("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")); client.write(tBuf); if(strcmp(methodBuffer,"GET") == 0) { strcpy_P(tBuf,PSTR("<html><head><script type=\"text/javascript\">")); client.write(tBuf); strcpy_P(tBuf,PSTR("function show_alert() {alert(\"This is an alert\");}")); client.write(tBuf); strcpy_P(tBuf,PSTR("</script></head>")); client.write(tBuf); strcpy_P(tBuf,PSTR("<body><H1>TEST</H1><form method=GET onSubmit=\"show_alert()\">")); client.write(tBuf); strcpy_P(tBuf,PSTR("T: <input type=text name=t><br>")); client.write(tBuf); strcpy_P(tBuf,PSTR("R: <input type=text name=r><br><input type=submit></form></body></html>")); client.write(tBuf); } client.stop(); } else if (c == '\n') { currentLineIsBlank = true; currentLineIsGet = false; } else if (c != '\r') { currentLineIsBlank = false; } } loopCount++; if(loopCount > 1000) { // if 1000ms has passed since last packet client.stop(); // close connection DB1L(("\r\nTimeout")); } // delay 1ms for timeout timing delay(1); } DB1L((F("disconnected"))); } } //----------------------- UTILITY ---------------------------------------- /***********************************************************************************//** * @brief strtoupper(text) * Change all characters to upper-case **************************************************************************************/ void WebServerSTPlus::strtoupper(char* aBuf) { for(int x = 0; x<strlen(aBuf);x++) { aBuf[x] = toupper(aBuf[x]); } } /***********************************************************************************//** * @brief urldecode(return, request-text) * Decode %xx URL encodes back into their original characters **************************************************************************************/ void WebServerSTPlus::urldecode(char *dst, const char *src) { char a, b; while (*src) { // If %dd found if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) { if (a >= 'a') { a -= 'a'-'A'; } if (a >= 'A') { a -= ('A' - 10);} else { a -= '0';} if (b >= 'a') { b -= 'a'-'A';} if (b >= 'A') { b -= ('A' - 10);} else { b -= '0';} *dst++ = 16*a+b; src+=3; } else { *dst++ = *src++; } } *dst++ = '\0'; } /***********************************************************************************//** * @brief freeRam() * @return Returns the amount of free RAM memory on the Arduino **************************************************************************************/ int WebServerSTPlus::freeRam() { extern int __heap_start,*__brkval; int v; return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int) __brkval); } /***********************************************************************************//** * @brief checkSockStatus() * **************************************************************************************/ void WebServerSTPlus::checkSockStatus() { unsigned long thisTime = millis(); for (int i = 0; i < MAX_SOCK_NUM; i++) { uint8_t s = W5100.readSnSR(i); if((s == 0x17) || (s == 0x1C)) { if(thisTime - connectTime[i] > 30000UL) { DB1((F("\r\nSocket frozen: "))); DB1L((i)); close(i); } } else connectTime[i] = thisTime; socketStat[i] = W5100.readSnSR(i); } } /***********************************************************************************//** * @brief ShowSockStatus() * **************************************************************************************/ void WebServerSTPlus::ShowSockStatus() { for (int i = 0; i < MAX_SOCK_NUM; i++) { DB1((F("Socket#"))); DB1((i)); uint8_t s = W5100.readSnSR(i); socketStat[i] = s; DB1((F(":0x"))); DB1((s,16)); DB1((F(" "))); DB1((W5100.readSnPORT(i))); DB1((F(" D:"))); uint8_t dip[4]; W5100.readSnDIPR(i, dip); for (int j=0; j<4; j++) { DB1((dip[j],10)); if (j<3) DB1((".")); } DB1((F("("))); DB1((W5100.readSnDPORT(i))); DB1L((F(")"))); } } //----------------------- STATUS MESSAGES -------------------------------- /***********************************************************************************//** * @brief sendBadRequest(client) * send a "BAD REQUEST" html page **************************************************************************************/ void WebServerSTPlus::sendBadRequest(EthernetClient thisClient) { char tBuf[64]; strcpy_P(tBuf,PSTR("HTTP/1.0 400 Bad Request\r\n")); thisClient.write(tBuf); strcpy_P(tBuf,PSTR("Content-Type: text/html\r\nConnection: close\r\n\r\n")); thisClient.write(tBuf); strcpy_P(tBuf,PSTR("<html><body><H1>BAD REQUEST</H1></body></html>")); thisClient.write(tBuf); thisClient.stop(); DB1L((F("disconnected"))); } /***********************************************************************************//** * @brief sendBadRequest(client) * send a "FILE NOT FOUND" html page **************************************************************************************/ void WebServerSTPlus::sendFileNotFound(EthernetClient thisClient) { char tBuf[64]; strcpy_P(tBuf,PSTR("HTTP/1.0 404 File Not Found\r\n")); thisClient.write(tBuf); strcpy_P(tBuf,PSTR("Content-Type: text/html\r\nConnection: close\r\n\r\n")); thisClient.write(tBuf); strcpy_P(tBuf,PSTR("<html><body><H1>FILE NOT FOUND</H1></body></html>")); thisClient.write(tBuf); thisClient.stop(); DB1L((F("disconnected"))); } //----------------------------- SD Utility ------------------------------------------------------------ /***********************************************************************************//** * @brief printDirectory(dir,numTabs) * List the files in the 'dir' path of the SD-card on the Serial Monitor **************************************************************************************/ void WebServerSTPlus::printDirectory(File dir, int numTabs) { while (true) { File entry = dir.openNextFile(); if (! entry) { // no more files break; } for (uint8_t i = 0; i < numTabs; i++) { Serial.print('\t'); } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs + 1); } else { // files have sizes, directories do not Serial.print("\t\t"); Serial.println(entry.size(), DEC); } entry.close(); } } /***********************************************************************************//** * @brief sdWrite(fileName,text,type) * @param fileName The full path and fileName to write to on the SD-Card * @param text The text to be written * @param WriteType 'WRITE' or 'APPEND' * @notes * 'fileName' will be automatically parsed to the 8.3-SFN standard **************************************************************************************/ void WebServerSTPlus::sdWrite(char* fileName, char* text, sdWriteType WriteType) { DB1((F("WebServerSTPlus::sdWrite( '")));DB1((fileName));DB1((F("','")));DB1((text));DB1L((F("')"))); char *pch; char ext[5] = ""; char fileType[4]; //vvv[ File Name (Modify for SFN-8.3) ]vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv DB1((F("SD file = "))); DB1L((fileName)); pch = strrchr(fileName,'.'); //ptr to extension if (pch!=NULL) { int extlen = strlen(pch); //record original extension length memcpy(ext,pch,4);pch[0]='\0'; //ext=4-digit copy, truncate name strcpy(fileType,ext+1); //Copy file type strtoupper(fileType); //All-caps for matching if(extlen>4) strcat(fileName,"~1"); //Truncate files with long ext } pch = strrchr(fileName,'/'); //ptr to filename if (pch!=NULL) { if (strlen(pch)>9) { pch[7]='~';pch[8]='1';pch[9]='\0'; //Truncate fileName to 8-digits } } strcat(fileName,ext); //Concate extension DB1((F("SD Mod file(FSN-8.3) = "))); DB1L((fileName)); //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ if( WriteType==WRITE ) { DB1((F("WRITE "))); File myFile = SD.open(fileName,O_CREAT | O_TRUNC | O_WRITE); myFile.write(text,strlen(text)); myFile.close(); DB1L((F("complete..."))); } else if( WriteType==APPEND ) { DB1((F("APPEND "))); if(!SD.exists(fileName)) { DB1L((F("file not found..."))); return; } DB1((F("file found.."))); File myFile = SD.open(fileName,O_WRITE | O_APPEND); myFile.write(text,strlen(text)); myFile.close(); DB1L((F("complete..."))); } }
package com.gb.billsharing.service; import com.gb.billsharing.model.Expense; import com.gb.billsharing.model.User; public class NotificationServiceImpl implements NotificationService { @Override public void notifyUser(User user, Expense expense) { System.out.println("Notified"); } }
Initial experience of robotic single port plus one (SP + 1) distal pancreatectomy using the da Vinci SP system: A report of three cases with video. Introduction With the advances of laparoscopic techniques, many efforts to reduce the number of the trocar site in abdominal surgery has been made. However, laparoscopic single-site distal pancreatectomy is regarded as difficult and technically demanding. Robotic surgical system was introduced to overcome the limitation of conventional laparoscopic surgery. The da Vinci surgical system released its new pure single-port platform, the da Vinci SP, offering improvements and refinements for established robotic single-site procedures. We report our initial experience of robotic single port plus one port (SP + 1) distal pancreatectomy using the da Vinci SP system. To our knowledge, this is the first report in Korea using the da Vinci SP system for distal pancreatectomy. Methods We reviewed the medical records of three patients in whom robotic single port plus one port (SP + 1) distal pancreatectomy was carried out. Robotic distal pancreatectomy was performed using the da Vinci SP system with one additional port. An additional robotic 12-mm-port was placed on the left side of the da Vinci SP system and was used for applying energy device such as Thunderbeat and endo-GIA stapling. Results The median age was 70 years (range 65-77). Pathological diagnosis included pancreas serous cystadenoma, neuroendocrine tumor and unsuspected pancreatic cancer. Median operation time was 245 minutes (range 135-265 minutes). All patients underwent combined splenectomy. There was no clinically relevant postoperative pancreatic fistula. Length of hospital stay was median 10 days after surgery. Conclusions Robotic single port distal pancreatectomy using the da Vinci SP system is safe and feasible with acceptable perioperative outcomes.
<reponame>trillaura/hugepages-afpacket<filename>src/utils/perf.c #include "perf.h" unsigned long long rdclock(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000000000ULL + ts.tv_nsec; } static void update_stats(struct stats *stats, uint64_t val) { double delta; stats->n++; delta = val - stats->mean; stats->mean += delta / stats->n; stats->M2 += delta * (val - stats->mean); } static double avg_stats(struct stats *stats) { return stats->mean; } /* perf_event_open syscall wrapper */ long sys_perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) { return syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags); } static inline pid_t gettid() { return syscall(SYS_gettid); } static struct perf_event_attr default_attrs[] = { {.type = PERF_TYPE_SOFTWARE,.config = PERF_COUNT_SW_PAGE_FAULTS}, {.type = PERF_TYPE_HW_CACHE,.config = (PERF_COUNT_HW_CACHE_DTLB | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16))}, {.type = PERF_TYPE_HW_CACHE,.config = (PERF_COUNT_HW_CACHE_DTLB | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16))}, {.type = PERF_TYPE_HW_CACHE,.config = (PERF_COUNT_HW_CACHE_DTLB | (PERF_COUNT_HW_CACHE_OP_WRITE << 8) | (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16))}, {.type = PERF_TYPE_HW_CACHE,.config = (PERF_COUNT_HW_CACHE_DTLB | (PERF_COUNT_HW_CACHE_OP_WRITE << 8) | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16))}, {.type = PERF_TYPE_HARDWARE,.config = PERF_COUNT_HW_REF_CPU_CYCLES}, {.type = PERF_TYPE_HARDWARE,.config = PERF_COUNT_HW_INSTRUCTIONS}, {.type = PERF_TYPE_HARDWARE,.config = PERF_COUNT_HW_CACHE_MISSES}, {.type = PERF_TYPE_HARDWARE,.config = PERF_COUNT_HW_CACHE_REFERENCES}, //{.type = PERF_TYPE_HARDWARE,.config = PERF_COUNT_HW_REF_CPU_CYCLES}, /* PERF_COUNT_HW_REF_CPU_CYCLES (since Linux 3.3) * Total cycles; not affected by CPU frequency scaling. * */ }; int get_counters() { return __LIBPERF_ARRAY_SIZE(default_attrs); } char *get_counter(int i) { char counters[9][20]= { "page-faults", "dTLB-loads", "dTLB-load-misses", "dTLB-stores", "dTLB-store-misses", "cycles", "instructions", "cache-misses", "cache-references" }; char *s = strdup(counters[i]); return s; } /* thread safe */ /* sets up a set of fd's for profiling code to read from */ struct libperf_data *libperf_initialize(pid_t pid, int cpu) { int nr_counters = __LIBPERF_ARRAY_SIZE(default_attrs); int i; struct libperf_data *pd = malloc(sizeof(struct libperf_data)); if (pd == NULL) { perror("malloc"); exit(EXIT_FAILURE); } if (pid == -1) pid = getpid(); // TODO or gettid() ? pd->group = -1; for (i = 0; i < (int) __LIBPERF_ARRAY_SIZE(pd->fds); i++) pd->fds[i] = -1; pd->pid = pid; pd->cpu = cpu; struct perf_event_attr *attrs = malloc(nr_counters * sizeof(struct perf_event_attr)); if (attrs == NULL) { perror("malloc"); exit(EXIT_FAILURE); } memcpy(attrs, default_attrs, sizeof(default_attrs)); pd->attrs = attrs; for (i = 0; i < nr_counters; i++) { attrs[i].size = sizeof(struct perf_event_attr); attrs[i].inherit = 1; attrs[i].disabled = 1; attrs[i].enable_on_exec = 0; pd->fds[i] = sys_perf_event_open(&attrs[i], pid, cpu, -1, 0); if (pd->fds[i] < 0) { fprintf(stderr, "At event %d/%d\n", i, nr_counters); perror("sys_perf_event_open"); exit(EXIT_FAILURE); } } pd->wall_start = rdclock(); return pd; } uint64_t get_cpuclock_counter(struct libperf_data *pd) { int *fds = pd->fds; int CPUCLOCK = 5; uint64_t count[3]; uint64_t clock; assert(fds[CPUCLOCK] >= 0); clock = read(fds[CPUCLOCK], count, sizeof(uint64_t)); assert(clock == sizeof(uint64_t)); return count[0]; } /* thread safe */ /* pass in int* from initialize function */ /* reads from fd's, prints out stats, and closes them all */ void libperf_finalize(struct libperf_data *pd) { int i, result, nr_counters = __LIBPERF_ARRAY_SIZE(default_attrs); int *fds = pd->fds; uint64_t count[3]; /* potentially 3 values */ struct stats event_stats[nr_counters]; struct stats walltime_nsecs_stats; walltime_nsecs_stats.n = 0; walltime_nsecs_stats.mean = 0; for (i = 0; i < nr_counters; i++) { assert(fds[i] >= 0); result = read(fds[i], count, sizeof(uint64_t)); assert(result == sizeof(uint64_t)); update_stats(&event_stats[i], count[0]); close(fds[i]); fds[i] = -1; fprintf(stderr, "%14.0f %s\n", avg_stats(&event_stats[i]), get_counter(i)); } update_stats(&walltime_nsecs_stats, rdclock() - pd->wall_start); fprintf(stderr, "%14.9f elapsed time\n", avg_stats(&walltime_nsecs_stats) / 1e9); free(pd->attrs); free(pd); } uint64_t libperf_readcounter(struct libperf_data *pd, int counter) { uint64_t value; assert(counter >= 0 && counter < __LIBPERF_MAX_COUNTERS); if (counter == __LIBPERF_MAX_COUNTERS) return (uint64_t) (rdclock() - pd->wall_start); assert(read(pd->fds[counter], &value, sizeof(uint64_t)) == sizeof(uint64_t)); return value; } int libperf_enablecounter(struct libperf_data *pd, int counter) { assert(counter >= 0 && counter < __LIBPERF_MAX_COUNTERS); if (pd->fds[counter] == -1) assert((pd->fds[counter] = sys_perf_event_open(&(pd->attrs[counter]), pd->pid, pd->cpu, pd->group, 0)) != -1); return ioctl(pd->fds[counter], PERF_EVENT_IOC_ENABLE); } int libperf_disablecounter(struct libperf_data *pd, int counter) { assert(counter >= 0 && counter < __LIBPERF_MAX_COUNTERS); if (pd->fds[counter] == -1) return 0; return ioctl(pd->fds[counter], PERF_EVENT_IOC_DISABLE); } void libperf_close(struct libperf_data *pd) { int i, nr_counters = __LIBPERF_ARRAY_SIZE(default_attrs); for (i = 0; i < nr_counters; i++) { assert(pd->fds[i] >= 0); close(pd->fds[i]); } free(pd->attrs); free(pd); }
<reponame>jjhenkel/dockerizeme import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.ops import gen_nn_ops @ops.RegisterGradient("GuidedRelu") def _GuidedReluGrad(op, grad): return tf.select(0. < grad, gen_nn_ops._relu_grad(grad, op.outputs[0]), tf.zeros(grad.get_shape())) if __name__ == '__main__': with tf.Session() as sess: g = tf.get_default_graph() x = tf.constant([10., 2.]) with g.gradient_override_map({'Relu': 'GuidedRelu'}): y = tf.nn.relu(x) z = tf.reduce_sum(-y ** 2) tf.initialize_all_variables().run() print x.eval(), y.eval(), z.eval(), tf.gradients(z, x)[0].eval() # > [ 10. 2.] [ 10. 2.] -104.0 [ 0. 0.]
def MACD(close ,fastperiod=26 , slowperiod=12 , signalperiod=9 ): slow = close.ewm(span=slowperiod, adjust=False).mean() fast = close.ewm(span=fastperiod, adjust=False).mean() macd = fast - slow macdsignal = macd.ewm(span=signalperiod , adjust=False).mean() return macd , macdsignal
Any good news should be savored by the Eagles these days, and Philadelphia got a much needed boost after an MRI exam Monday revealed that defensive end Trent Cole's calf injury is not as severe as originally feared, NFL Network's Albert Breer reported. Citing a league source, Breer reported Cole suffered a Grade 2 calf strain during the Eagles' Sunday 24-23 loss to the San Francisco 49ers, an injury that should sideline him for a few weeks. Breer originally reported, citing a league source, that the injury to Cole "definitely could be serious." Cole, in his seventh season, had one sack in each of the Eagles' first three games this season. In the previous four years, Cole had a total of 44 sacks, and he's got 60 career sacks.
WASHINGTON (CNN) -- One of the main stumbling blocks to talk with Iran has been the condition that Iran suspends its uranium enrichment. Now, the Obama administration may take that option off the table, at least for now. This is from an Iranian nuclear plant in the central province of Isfahan on April 9. The United States and its European allies, which have just invited Iran to a fresh round of nuclear talks, are coming to the realization that if Iran's nuclear program isn't quite at the point of no return, it will be soon. With 5,500 centrifuges, roughly enough for about two weapons worth of uranium a year, Iran isn't going to just shut down its enrichment facility as a goodwill gesture. For years, Iran has been willing to endure sanctions and economic isolation. What it hasn't been willing to do is suspend enrichment. Iran maintains enriching uranium for nuclear energy is its right. Now the West seems to have come around to Iran's way of thinking. Last week during a speech on proliferation in Prague, Czech Republic, President Obama admitted as much when he said, "We will support Iran's right to peaceful nuclear energy with rigorous inspections." The International Atomic Energy Agency, the U.N. nuclear watchdog, has long argued to allow Iran to maintain a small face-saving nuclear enrichment program under the guise of "research and development." Allowing such a program under the Non-Proliferation Treaty, at least while negotiations continue, would involve strict IAEA inspections -- something which may give the international community the kind of insight into Iran's nuclear program which it has long sought. It would also give Iran the cover to come back to the table without claiming it never gave in to the West. Rather, Tehran can boast the international community came around to its point of view. Preventing Iranian enrichment may be an ultimate pipe dream, but officials hope the right package of incentives, coupled with the threat of tougher sanctions, which could cripple its stumbling economy, could deter Tehran from developing a nuclear bomb. If adopted, the new strategy will undoubtedly be condemned by Israel, which has warned the U.S. that it has until the end of the year to put an end to Iran's uranium production before it takes matters into its own hands. However, moving beyond the issue of enrichment helps Obama inch closer toward engagement with Iran, something he promised during the campaign and has begun to undertake with small, albeit significant, steps, most noticeably his New Year's message to the Iranian people. Those who watch Iran closely say Obama's outreach is being warmly received in the region. While the response from spiritual leader Ayatollah Khamanei and President Mahmoud Ahmadinejad seems vague at first glance, experts argue the regime is being quite conciliatory, even flirting with the U.S. overtures and opening the door for talks. Now the administration is taking another leap, inviting Iran to several meetings on Afghanistan as a way to engage on issues of mutual interest. The U.S. is also seriously considering allowing U.S. diplomats around the world to interact with their Iranian counterparts and setting up a U.S. interests section in Iran. Officials say not to expect any dramatic breakthroughs before the Iranians head to the polls to elect a new president in June. But Obama's conservative critics, including several Republican lawmakers, worry Obama is making it too easy for Iran to come back to the table and is giving credibility to Iran's defiant Ahmadinejad in his bid for re-election. The goal of stopping Iran from building a nuclear weapon remains, but the tactics are shifting and the rules of the game have changed. Obama and his advisers are betting that by finally giving Iran what it thinks it wants, the U.S. and its allies will get what they need -- a way to bring Iran to the table and start meaningful negotiations, which have eluded them for the past four years. All About Iran • Nuclear Proliferation • Barack Obama
<filename>LPsolver_v1.5/glpk/patches_global.h #ifndef _PATCHES_GLOBAL_H #define _PATCHES_GLOBAL_H #include "postgres.h" #include "lib/stringinfo.h" #define free(ptr) pfree(ptr) #define malloc(size) palloc0(size) #define realloc(ptr,size) realloc(ptr,size) // Renaming of types/functions #define bool pg_glpk_bool #define connect pg_glpk_connect #define abort abort_patched extern void abort_patched(void); // Undefines #undef true #undef false #undef DEBUG1 #undef DEBUG2 #undef DEBUG3 #undef DEBUG4 #undef Assert #endif
/** Deinitializes ES objects created during test execution */ void MultisampleTextureFunctionalTestsBlittingToMultisampledFBOIsForbiddenTest::deinit() { const glw::Functions& gl = m_context.getRenderContext().getFunctions(); if (fbo_draw_id != 0) { gl.deleteFramebuffers(1, &fbo_draw_id); fbo_draw_id = 0; } if (fbo_read_id != 0) { gl.deleteFramebuffers(1, &fbo_read_id); fbo_read_id = 0; } if (dst_to_id != 0) { gl.deleteTextures(1, &dst_to_id); dst_to_id = 0; } if (src_to_id != 0) { gl.deleteTextures(1, &src_to_id); src_to_id = 0; } TestCase::deinit(); }
/* * 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. */ /*! * \file touch_extractor.cc * \brief Extract feature of touch pattern of axes in lowered IR */ #include "touch_extractor.h" #include <algorithm> #include <cmath> #include <set> #include <unordered_map> namespace tvm { namespace autotvm { int ParallelLevel(AnnotationType ann) { switch (ann) { case kBlockX: case kBlockY: case kBlockZ: return 2; case kThreadX: case kThreadY: case kThreadZ: case kParallel: return 1; default: return 0; } } // get touch pattern from index expression class IndexParser : public ExprVisitor { public: void Parse(PrimExpr expr) { pattern_map.clear(); this->VisitExpr(expr); } void VisitExpr_(const VarNode* op) final { // TODO(lmzheng): handle more index types (multiple occurrence) if (pattern_map.count(op) == 0) { pattern_map[op] = TouchPattern(); pattern_map[op].stride = next_stride_; next_stride_ = 1; } } void VisitExpr_(const MulNode* op) final { if (op->a.as<VarNode>()) { if (const auto stride = op->b.as<IntImmNode>()) { next_stride_ = stride->value; } } ExprVisitor::VisitExpr_(op); } std::unordered_map<const VarNode*, TouchPattern> pattern_map; private: int64_t next_stride_ = 1; }; // extract iter vars and their touch pattern from ir bool TouchExtractor::EnterItervar_(Var var, int64_t length, AnnotationType ann_type) { // do not insert duplicated occurrences of virtual thread if (ann_type == kVirtualThread && itervar_map.count(var) != 0) { skip_stack_size_.push_back(itervar_stack_.size()); return true; } else { itervar_stack_.push_back(var); topdown_product_ *= length; if (itervar_map.count(var) != 0) { // find two duplicated axes // these happens when we create tvm.thread_axis("threadIdx.x") once and // bind it twice. Here we treat them as two axes // so we create a snapshot for the old one and freeze it Var old = Var(var.get()->name_hint); itervar_map.insert({old, itervar_map[var]}); itervar_map.erase(var); } itervar_map.insert( {var, ItervarFeature(var, length, static_cast<int>(itervar_stack_.size()), ann_type, topdown_product_, static_cast<int>(itervar_counter_++))}); } return true; } void TouchExtractor::ExitItervar_() { if (!skip_stack_size_.empty() && skip_stack_size_.back() == itervar_stack_.size()) { skip_stack_size_.pop_back(); return; } Var var = itervar_stack_.back(); // update count and reuse ratio for upper iter vars (includes self) for (auto kv : itervar_map[var].touch_feature) { if (kv.second.stride != 0) { // multiply count for (auto stack_var : itervar_stack_) { auto touch_pattern = itervar_map[stack_var].touch_feature.find(kv.first); ICHECK(touch_pattern != itervar_map[stack_var].touch_feature.end()); touch_pattern->second.count *= itervar_map[var].length; } } else { // multiply reuse ratio for (auto stack_var : itervar_stack_) { auto touch_pattern = itervar_map[stack_var].touch_feature.find(kv.first); ICHECK(touch_pattern != itervar_map[stack_var].touch_feature.end()); touch_pattern->second.reuse *= itervar_map[var].length; } } } itervar_stack_.pop_back(); int64_t length = itervar_map[var].length; if (length != 0) topdown_product_ /= length; int64_t bottomup_product = -1; for (auto kv : itervar_map[var].touch_feature) { bottomup_product = std::max(bottomup_product, kv.second.count * kv.second.reuse); } itervar_map[var].bottomup_product = bottomup_product; // push base to upper parallel axis int para_level = ParallelLevel(itervar_map[var].ann); // if is the separate line of parallel level, push the base to upper parallel level if (!itervar_stack_.empty() && ParallelLevel(itervar_map[itervar_stack_.back()].ann) == para_level + 1) { for (auto kv : itervar_map[var].touch_feature) { for (auto stack_var : itervar_stack_) { if (ParallelLevel(itervar_map[stack_var].ann) == para_level + 1) { auto touch_pattern = itervar_map[stack_var].touch_feature.find(kv.first); ICHECK(touch_pattern != itervar_map[stack_var].touch_feature.end()); touch_pattern->second.thread_reuse = -kv.second.reuse; touch_pattern->second.thread_count = -kv.second.count; // NOTE: use minus as a flag to denote it is a base, // indicating it is not the final value } } } } for (auto kv : itervar_map[var].touch_feature) { if (kv.second.thread_count < 0) { itervar_map[var].touch_feature[kv.first].thread_count = kv.second.count / (-kv.second.thread_count); itervar_map[var].touch_feature[kv.first].thread_reuse = kv.second.reuse / (-kv.second.thread_reuse); } } } void TouchExtractor::EnterMem_(Var buffer_var, PrimExpr index) { std::string name = buffer_var.get()->name_hint; TouchedBuffer buf = name + "_" + std::to_string(buffer_counter_[name]++); // extract touch pattern from index IndexParser parser; parser.Parse(index); // push up mem access info for (auto var : itervar_stack_) { auto x = parser.pattern_map.find(var.get()); if (x != parser.pattern_map.end()) { itervar_map[var].touch_feature[buf] = x->second; } else { itervar_map[var].touch_feature[buf] = TouchPattern(); } } } void TouchExtractor::ExitMem_() {} /*! * \brief Get axis-based feature for all axes * \param stmt The statement to be extracted * \param bool Whether take log for numerical feature * \param ret_feature The buffer where the return value is stored * * \note The format of return value is * (( * ('_itervar_', var), * ('_attr_', length, nest_level, topdown, bottomup, one_hot_annotation), * ('_arith_', add_ct, mul_ct, div_ct), * ('data_vec_0', stride, mod, count, reuse, thread_count, thread_reuse), * ('conv_0', stride, mod, count, reuse, thread_count, thread_reuse), * ), * ( * ('_itervar_', var2), * ('_attr_', length, nest_level, one_hot_annotation), * ('_arith_', add_ct, mul_ct, div_ct), * ('kernel_vec_0', stride, mod, count, reuse, thread_count, thread_reuse), * ('conv_1', stride, mod, count, reuse, thread_count, thread_reuse), * )) * * Itervars are sorted according to their first occurrence position in IR. * Buffers touched by an itervar are sorted by their unique names. * * \note If you want to flatten these features as the input of your model, * You can use the faster one GetItervarFeatureFlatten below. */ void GetItervarFeature(Stmt stmt, bool take_log, Array<Array<Array<PrimExpr> > >* ret_feature) { // extract TouchExtractor touch_analyzer; touch_analyzer.Analyze(stmt); // sort according to order std::vector<Var> vars; for (auto kv : touch_analyzer.itervar_map) { vars.push_back(kv.first); } std::sort(vars.begin(), vars.end(), [&](const Var& lhs, const Var& rhs) -> bool { return touch_analyzer.itervar_map[lhs].order < touch_analyzer.itervar_map[rhs].order; }); // whether take log for numerical feature std::function<double(int64_t)> trans; if (take_log) { trans = [](int64_t x) { if (x < 0) return -std::log(-x + 1) / std::log(2); x = x + 1; return std::log(x) / std::log(2); }; } else { trans = [](int64_t x) { return x; }; } // serialize for front end for (auto var : vars) { Array<Array<PrimExpr> > feature_row; ItervarFeature& fea = touch_analyzer.itervar_map[var]; feature_row.push_back(Array<PrimExpr>{tvm::tir::StringImm("_itervar_"), var}); Array<PrimExpr> attr{ tvm::tir::StringImm("_attr_"), FloatImm(DataType::Float(32), trans(fea.length)), IntImm(DataType::Int(32), fea.nest_level), FloatImm(DataType::Float(32), trans(fea.topdown_product)), FloatImm(DataType::Float(32), trans(fea.bottomup_product)), }; // one hot annotation for (int i = 0; i < kNum; i++) { attr.push_back(i == fea.ann); } feature_row.push_back(attr); // arithmetic feature_row.push_back(Array<PrimExpr>{ tvm::tir::StringImm("_arith_"), FloatImm(DataType::Float(32), trans(fea.add_ct)), FloatImm(DataType::Float(32), trans(fea.mul_ct)), FloatImm(DataType::Float(32), trans(fea.div_ct)), }); // touch map std::vector<TouchedBuffer> bufs; for (auto kv : fea.touch_feature) { bufs.push_back(kv.first); } std::sort(bufs.begin(), bufs.end()); for (auto k : bufs) { TouchPattern& v = fea.touch_feature[k]; feature_row.push_back(Array<PrimExpr>{ tvm::tir::StringImm(k), FloatImm(DataType::Float(32), trans(v.stride)), FloatImm(DataType::Float(32), trans(v.mod)), FloatImm(DataType::Float(32), trans(v.count)), FloatImm(DataType::Float(32), trans(v.reuse)), FloatImm(DataType::Float(32), trans(v.thread_count)), FloatImm(DataType::Float(32), trans(v.thread_reuse)), }); } ret_feature->push_back(feature_row); } } /*! * \brief Get axis-based feature for all axes and flatten them into a one-dimensional vector. * \param stmt The statement to be extracted * \param bool Whether take log for numerical feature * \param ret_feature The buffer where the return value is stored * * \note See GetItervarFeature for more details about the return value. * This is an optimized version of GetItervarFeature + Flatten. This runs much faster. */ void GetItervarFeatureFlatten(Stmt stmt, bool take_log, std::vector<float>* ret_feature) { // extract touch feature TouchExtractor touch_analyzer; touch_analyzer.Analyze(stmt); // sort according to order std::vector<Var> vars; for (auto kv : touch_analyzer.itervar_map) { vars.push_back(kv.first); } std::sort(vars.begin(), vars.end(), [&](const Var& lhs, const Var& rhs) -> bool { return touch_analyzer.itervar_map[lhs].order < touch_analyzer.itervar_map[rhs].order; }); // whether take log for numerical feature std::function<float(int64_t)> trans; if (take_log) { trans = [](int64_t x) { if (x < 0) return -std::log(-x + 1) / std::log(2); x = x + 1; return std::log(x) / std::log(2); }; } else { trans = [](int64_t x) { return x; }; } // serialize for front end for (auto var : vars) { ItervarFeature& fea = touch_analyzer.itervar_map[var]; ret_feature->push_back(trans(fea.length)); ret_feature->push_back(fea.nest_level); ret_feature->push_back(trans(fea.topdown_product)); ret_feature->push_back(trans(fea.bottomup_product)); // one hot annotation for (int i = 0; i < kNum; i++) { ret_feature->push_back(i == fea.ann); } // arithmetic ret_feature->push_back(trans(fea.add_ct)); ret_feature->push_back(trans(fea.mul_ct)); ret_feature->push_back(trans(fea.div_ct)); // touch map std::vector<TouchedBuffer> bufs; for (auto kv : fea.touch_feature) { bufs.push_back(kv.first); } std::sort(bufs.begin(), bufs.end()); for (auto k : bufs) { TouchPattern& v = fea.touch_feature[k]; ret_feature->push_back(trans(v.stride)); ret_feature->push_back(trans(v.mod)); ret_feature->push_back(trans(v.count)); ret_feature->push_back(trans(v.reuse)); ret_feature->push_back(trans(v.thread_count)); ret_feature->push_back(trans(v.thread_reuse)); } } } /*! * \brief Get curve sample feature (relation feature) and flatten them into a one-dimensional * vector. \param stmt The statement to be extracted \param sample_n The number of points used for * sampling a curve (along one dimension) \param ret_feature The buffer where the return value is * stored */ void GetCurveSampleFeatureFlatten(Stmt stmt, int sample_n, std::vector<float>* ret_feature) { // extract touch feature TouchExtractor touch_ext; touch_ext.Analyze(stmt); // sort according to order std::vector<Var> vars; for (auto kv : touch_ext.itervar_map) { vars.push_back(kv.first); } std::sort(vars.begin(), vars.end(), [&](const Var& lhs, const Var& rhs) -> bool { return touch_ext.itervar_map[lhs].order < touch_ext.itervar_map[rhs].order; }); int max_depth = 0; std::map<TouchedBuffer, std::vector<double> > reuse_curve; std::map<TouchedBuffer, std::vector<double> > count_curve; std::map<TouchedBuffer, std::vector<double> > topdown_curve; std::map<TouchedBuffer, std::vector<double> > bottomup_curve; std::set<TouchedBuffer> innermost_buffers; std::set<std::string> added; // find maximum depth of loop nest for (auto var : vars) { ItervarFeature& fea = touch_ext.itervar_map[var]; max_depth = std::max(max_depth, fea.nest_level); } // mark inner most buffer for (auto iter = vars.rbegin(); iter != vars.rend(); iter++) { auto var = *iter; ItervarFeature& fea = touch_ext.itervar_map[var]; if (fea.nest_level == max_depth) { for (auto kv : fea.touch_feature) { // delete buffer no (e.g. 'A_0' -> 'A', 'A_1' -> 'A') std::string raw_name = kv.first.substr(0, kv.first.rfind("_")); // delete memory scope (e.g. 'A.local' -> 'A', 'A.shared' -> 'A') size_t pos = raw_name.find("."); if (pos < kv.first.size()) raw_name = raw_name.substr(0, pos); // If there are multiple innermost buffers that are derived from a same raw buffer // We only record the last occurrence (note the `iter` is in reverse order) // e.g. `A.local`, `A.shared` are derived from `A`, if they all occurred at the inner most // level, we will only record the last occurrence, if (added.find(raw_name) == added.end()) { innermost_buffers.insert(kv.first); added.insert(raw_name); } } } } // pad the first point (zero) for all curves for (auto buf : innermost_buffers) { reuse_curve[buf].push_back(0); count_curve[buf].push_back(0); topdown_curve[buf].push_back(0); bottomup_curve[buf].push_back(0); } // extract curves for (auto var : vars) { ItervarFeature& fea = touch_ext.itervar_map[var]; for (auto kv : fea.touch_feature) { if (innermost_buffers.find(kv.first) != innermost_buffers.end()) { reuse_curve[kv.first].emplace_back(std::log(kv.second.reuse) / std::log(2)); count_curve[kv.first].emplace_back(std::log(kv.second.count) / std::log(2)); topdown_curve[kv.first].emplace_back(std::log(fea.topdown_product) / std::log(2)); bottomup_curve[kv.first].emplace_back(std::log(fea.bottomup_product) / std::log(2)); } } } // sample relation in the curve auto sample_curve = [&](const std::vector<double>& x, const std::vector<double>& y, double weight) { for (int i = 0; i < sample_n; i++) { double xx = i * weight; for (int j = static_cast<int>(x.size()) - 1; j >= 0; j--) { if (xx > x[j] - 1e-6) { ret_feature->emplace_back(y[j]); ret_feature->emplace_back(xx - x[j]); break; } } } }; // serialize to frontend for (auto k : innermost_buffers) { std::vector<double>& count = count_curve[k]; std::vector<double>& reuse = reuse_curve[k]; std::vector<double>& top_down = topdown_curve[k]; std::sort(count.begin(), count.end()); std::sort(reuse.begin(), reuse.end()); std::sort(top_down.begin(), top_down.end()); sample_curve(count, reuse, 1); sample_curve(reuse, count, 1); sample_curve(count, top_down, 1); sample_curve(top_down, count, 1); } } // register API for front end TVM_REGISTER_GLOBAL("autotvm.feature.GetItervarFeature") .set_body([](TVMArgs args, TVMRetValue* ret) { Stmt stmt = args[0]; bool take_log = args[1]; Array<Array<Array<PrimExpr> > > ret_feature; GetItervarFeature(stmt, take_log, &ret_feature); *ret = ret_feature; }); TVM_REGISTER_GLOBAL("autotvm.feature.GetItervarFeatureFlatten") .set_body([](TVMArgs args, TVMRetValue* ret) { Stmt stmt = args[0]; bool take_log = args[1]; std::vector<float> ret_feature; GetItervarFeatureFlatten(stmt, take_log, &ret_feature); TVMByteArray arr; arr.size = sizeof(float) * ret_feature.size(); arr.data = reinterpret_cast<char*>(ret_feature.data()); *ret = arr; }); TVM_REGISTER_GLOBAL("autotvm.feature.GetCurveSampleFeatureFlatten") .set_body([](TVMArgs args, TVMRetValue* ret) { Stmt stmt = args[0]; int sample_n = args[1]; std::vector<float> ret_feature; GetCurveSampleFeatureFlatten(stmt, sample_n, &ret_feature); TVMByteArray arr; arr.size = sizeof(float) * ret_feature.size(); arr.data = reinterpret_cast<char*>(ret_feature.data()); *ret = arr; }); } // namespace autotvm } // namespace tvm
const MAX_VEC_SIZE: usize = 4; #[derive(Debug, Clone, PartialEq)] pub struct VecIter<T: Copy> { items: [T; MAX_VEC_SIZE], end: usize, pos: usize, } impl<T: Copy> VecIter<T> { #[inline] pub(crate) fn new(items: [T; MAX_VEC_SIZE], num_items: usize) -> Self { debug_assert!(num_items <= MAX_VEC_SIZE); Self { items, end: num_items, pos: 0, } } #[inline] pub fn len(&self) -> usize { debug_assert!(self.pos <= self.end); self.end.saturating_sub(self.pos) } #[inline] pub fn is_empty(&self) -> bool { self.pos >= self.end } } impl<T: Copy> Iterator for VecIter<T> { type Item = T; #[inline] fn next(&mut self) -> Option<Self::Item> { if self.pos >= self.end { return None; } let p = self.pos; self.pos += 1; Some(self.items[p]) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let len = self.len(); (len, Some(len)) } #[inline] fn count(self) -> usize { self.len() } #[inline] fn last(self) -> Option<Self::Item> { if self.pos >= self.end { None } else { Some(self.items[self.end - 1]) } } #[inline] fn nth(&mut self, n: usize) -> Option<Self::Item> { if n > MAX_VEC_SIZE || self.pos + n >= self.end { self.pos = self.end; return None; } self.pos += n; let p = self.pos; self.pos += 1; Some(self.items[p]) } } impl<T: Copy> std::iter::ExactSizeIterator for VecIter<T> {} impl<T: Copy> std::iter::DoubleEndedIterator for VecIter<T> { #[inline] fn next_back(&mut self) -> Option<T> { if self.pos >= self.end { return None; } self.end -= 1; Some(self.items[self.end]) } } impl<T: Copy> std::iter::FusedIterator for VecIter<T> {} #[cfg(test)] #[allow(clippy::cognitive_complexity)] mod tests { use super::super::*; // test each size separately since when they're this small they all have // edge-cases... #[test] fn test_vec_iter2() { let v2i = vec2(100.0, 4.0).into_iter(); assert_eq!(v2i.len(), 2); assert_eq!(&v2i.clone().collect::<Vec<_>>(), &[100.0, 4.0]); assert_eq!(&v2i.clone().rev().collect::<Vec<_>>(), &[4.0, 100.0]); { let mut v2ia = v2i.clone(); assert_eq!(v2ia.next(), Some(100.0)); assert_eq!(v2ia.len(), 1); assert_eq!(v2ia.next_back(), Some(4.0)); assert_eq!(v2ia.len(), 0); assert_eq!(v2ia.next_back(), None); } { let mut v2ia = v2i.clone(); assert_eq!(v2ia.nth(1), Some(4.0)); assert_eq!(v2ia.len(), 0); assert_eq!(v2ia.next(), None); } { let mut v2ia = v2i.clone(); assert_eq!(v2ia.nth(1), Some(4.0)); assert_eq!(v2ia.len(), 0); assert_eq!(v2ia.next_back(), None); } } #[test] fn test_vec_iter3() { let vi = vec3(100.0, 4.0, 6.0).into_iter(); assert_eq!(vi.len(), 3); assert_eq!(&vi.clone().collect::<Vec<_>>(), &[100.0, 4.0, 6.0]); assert_eq!(&vi.clone().rev().collect::<Vec<_>>(), &[6.0, 4.0, 100.0]); { let mut via = vi.clone(); assert_eq!(via.next(), Some(100.0)); assert_eq!(via.len(), 2); assert_eq!(via.next_back(), Some(6.0)); assert_eq!(via.len(), 1); let mut vib = via.clone(); assert_eq!(vib.next_back(), Some(4.0)); assert_eq!(vib.len(), 0); assert_eq!(vib.next_back(), None); let mut vib = via.clone(); assert_eq!(vib.next(), Some(4.0)); assert_eq!(vib.len(), 0); assert_eq!(vib.next(), None); } { let mut via = vi.clone(); assert_eq!(via.nth(1), Some(4.0)); assert_eq!(via.len(), 1); let mut vib = via.clone(); assert_eq!(vib.nth(1), None); assert_eq!(vib.len(), 0); let mut vib = via.clone(); assert_eq!(vib.next(), Some(6.0)); assert_eq!(vib.len(), 0); let mut vib = via.clone(); assert_eq!(vib.next_back(), Some(6.0)); assert_eq!(vib.len(), 0); } } #[test] fn test_vec_iter4() { let vi = vec4(100.0, 4.0, 6.0, 15.0).into_iter(); assert_eq!(vi.len(), 4); assert_eq!(&vi.clone().collect::<Vec<_>>(), &[100.0, 4.0, 6.0, 15.0]); assert_eq!(&vi.clone().rev().collect::<Vec<_>>(), &[15.0, 6.0, 4.0, 100.0]); { let mut via = vi.clone(); assert_eq!(via.next(), Some(100.0)); assert_eq!(via.len(), 3); assert_eq!(via.next_back(), Some(15.0)); assert_eq!(via.len(), 2); let mut vib = via.clone(); assert_eq!(vib.next_back(), Some(6.0)); assert_eq!(vib.len(), 1); assert_eq!(vib.nth(0), Some(4.0)); assert_eq!(vib.len(), 0); assert_eq!(vib.next_back(), None); let mut vib = via.clone(); assert_eq!(vib.next(), Some(4.0)); assert_eq!(vib.len(), 1); assert_eq!(vib.next(), Some(6.0)); assert_eq!(vib.len(), 0); assert_eq!(vib.next(), None); } { let mut via = vi.clone(); assert_eq!(via.nth(1), Some(4.0)); assert_eq!(via.len(), 2); let mut vib = via.clone(); assert_eq!(vib.nth(1), Some(15.0)); assert_eq!(vib.len(), 0); let mut vib = via.clone(); assert_eq!(vib.next(), Some(6.0)); assert_eq!(vib.len(), 1); assert_eq!(vib.next_back(), Some(15.0)); assert_eq!(vib.len(), 0); } } }
/** * Mapper implementation using Jackson. TODO: Configure Mapper via a * tm-mapper-defaults.json file under resources/config/. * * For recursive dependencies check @JsonFilter : http://www.theotherian.com/2014/02/jackson-mixins-and-modules-external-classes.html * * NOTE: getters and setters are used when serializing/deserializing a model. Also for attributes set using the generic * set/get methods jsonanygetter and jsonanysetter annotations are used. */ public abstract class JacksonMapper<M extends Model> extends BaseMapper<M> { public static final String KEY_CLASS = "@c"; protected ObjectMapper mapper; public abstract ObjectMapper initMapper(); public ObjectMapper getMapper() { if (mapper == null) { mapper = initMapper(); } return mapper; } public void setMapper(ObjectMapper mapper) { this.mapper = mapper; } @Override public Object serialize(M src) { try { return getMapper().writeValueAsString(src); } catch (JsonProcessingException e) { return reThrow(e); } } @Override public M deserialize(Object src) { // new TypeReference<Map<String, Object> // http://stackoverflow.com/questions/11936620/jackson-deserialising-json-string-typereference-vs-typefactory-constructcoll // http://stackoverflow.com/questions/14362247/jackson-adding-extra-fields-to-an-object-in-serialization try { // TODO: Cache model class to avoid forName(). // return (M)getMapper().readValue(src.toString(), Model.class); Class modelClass = Model.class; if (getTugConfig() != null) { modelClass = Class.forName((String) getTugConfig().getModel().get("class")); } // return (M) getMapper().readValue(src.toString(), modelClass); } catch (Exception e) { return (M) reThrow(e); } } @Override public Object serialize(Object src) { try { return getMapper().writeValueAsString(src); } catch (JsonProcessingException e) { return reThrow(e); } } @Override public <T> T deserialize(Object src, Class<T> destClass) { try { return getMapper().readValue(src.toString(), destClass); } catch (Exception e) { return (T) reThrow(e); } } public void updateModel(Object src, M dest) { // https://www.google.ro/search?q=screw+him&oq=screw+him&aqs=chrome..69i57j0l5.3257j0j4&sourceid=chrome&ie=UTF-8#q=jackson+serialize+on+existing+object&* // ATTENTION: Always specify the base Model.class on which the annotations are added. // https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=jackson+polymorphic+not+subtype+of&* // getMapper().readValue(src.toString(), Config.class); // Works if you remove defaultImpl = Model.class // ALTERNATIVE: use Model#merge and Mapper#deserialize. // Model srcModel = deserialize(src); // dest.merge(srcModel); try { // getMapper().readerForUpdating(dest).forType(Model.class).readValue((String) src); if (src instanceof String) { getMapper().readerForUpdating(dest).readValue((String) src); } else if (src instanceof Model) { updateModel(serialize((M) src), dest); } } catch (Exception e) { reThrow(e); } } @Override public <T> T convert(Object src, Class<T> destClass) { return (T) getMapper().convertValue(src, destClass); // getMapper().writeValueAsString(src) // getMapper().convertValue(src, Object.class) } /** * Used in debug/development mode to have access to a pretty print of the actual model or object. */ public String toPrettyString(Object src) { try { // return getMapper().writeValueAsString(fromValue); return JacksonMappers.getPrettyPrintMapper().getMapper().writeValueAsString(src); } catch (JsonProcessingException e) { return (String) reThrow(e); } } public Object reThrow(Exception e) { if (e instanceof JsonProcessingException) { StringBuilder mes = new StringBuilder(); JsonProcessingException jpe = (JsonProcessingException) e; if (jpe.getLocation() != null) { mes.append("********** JSON ERROR ON LINE: " + jpe.getLocation().getLineNr() + " **********. "); Object source = jpe.getLocation().getSourceRef(); if (source instanceof FileInputStream) { try { Field path = FileInputStream.class.getDeclaredField("path"); path.setAccessible(true); mes.append("In file " + (String) path.get(source)); } catch (Exception e1) { e1.printStackTrace(); } } } mes.append(e.getMessage()); throw new RuntimeException(mes.toString(), e); } throw new RuntimeException(e); } }
// SPDX-License-Identifier: MIT // // Copyright (c) 2021 <NAME> #include <assert.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <umod/umodpack.h> #include "instruments.h" #include "song.h" #include "patterns.h" int save_pack(const char *path) { int ret = -1; FILE *f = fopen(path, "wb+"); if (f == NULL) return -1; fprintf(f, "UMOD"); uint32_t num_songs = song_total_number(); fwrite(&num_songs, sizeof(num_songs), 1, f); uint32_t num_patterns = pattern_total_number(); fwrite(&num_patterns, sizeof(num_patterns), 1, f); uint32_t num_instruments = instrument_total_number(); fwrite(&num_instruments, sizeof(num_instruments), 1, f); // Leave this empty for now uint32_t *song_offset_array = malloc(num_songs * sizeof(uint32_t)); uint32_t *pattern_offset_array = malloc(num_patterns * sizeof(uint32_t)); uint32_t *instrument_offset_array = malloc(num_instruments * sizeof(uint32_t)); if ((song_offset_array == NULL) || (pattern_offset_array == NULL) || (instrument_offset_array == NULL)) goto cleanup; uint32_t empty = 0; // Songs long song_offsets = ftell(f); for (uint32_t i = 0; i < num_songs; i++) fwrite(&empty, sizeof(empty), 1, f); // Patterns long pattern_offsets = ftell(f); assert(num_patterns <= UINT16_MAX); for (uint32_t i = 0; i < num_patterns; i++) fwrite(&empty, sizeof(empty), 1, f); // Samples long instrument_offsets = ftell(f); for (uint32_t i = 0; i < num_instruments; i++) fwrite(&empty, sizeof(empty), 1, f); // Write songs for (uint32_t i = 0; i < num_songs; i++) { song_offset_array[i] = ftell(f); const int *data; size_t length; song_get(i, &data, &length); uint16_t length_ = length; fwrite(&length_, sizeof(length_), 1, f); for (size_t p = 0; p < length; p++) { uint16_t val = data[p]; fwrite(&val, sizeof(val), 1, f); } // Align next element to 32 bit { long align = (4 - (ftell(f) & 3)) & 3; uint8_t val = 0; while (align > 0) { fwrite(&val, sizeof(val), 1, f); align--; } } } // Write patterns for (uint32_t i = 0; i < num_patterns; i++) { pattern_offset_array[i] = ftell(f); int channels, rows; pattern_get_dimensions(i, &channels, &rows); uint8_t value; value = channels; fwrite(&value, sizeof(value), 1, f); value = rows; fwrite(&value, sizeof(value), 1, f); for (int r = 0; r < rows; r++) { for (int c = 0; c < channels; c++) { int note, instrument, volume, effect, effect_params; pattern_step_get(i, r, c, &note, &instrument, &volume, &effect, &effect_params); uint8_t flags = 0; if (instrument != -1) flags |= STEP_HAS_INSTRUMENT; if (note != -1) flags |= STEP_HAS_NOTE; if (volume != -1) flags |= STEP_HAS_VOLUME; if (effect != -1) flags |= STEP_HAS_EFFECT; fwrite(&flags, sizeof(flags), 1, f); if (instrument != -1) { assert(instrument <= UINT16_MAX); value = instrument & 0xFF; fwrite(&value, sizeof(value), 1, f); value = instrument >> 8; fwrite(&value, sizeof(value), 1, f); } if (note != -1) { assert(note <= UINT8_MAX); value = note; fwrite(&value, sizeof(value), 1, f); } if (volume != -1) { assert(volume <= UINT8_MAX); value = volume; fwrite(&value, sizeof(value), 1, f); } if (effect != -1) { assert(effect <= UINT8_MAX); assert(effect_params <= UINT8_MAX); value = effect; fwrite(&value, sizeof(value), 1, f); value = effect_params; fwrite(&value, sizeof(value), 1, f); } } } // Align next element to 32 bit { long align = (4 - (ftell(f) & 3)) & 3; uint8_t val = 0; while (align > 0) { fwrite(&val, sizeof(val), 1, f); align--; } } } // Write instruments for (uint32_t i = 0; i < num_instruments; i++) { instrument_offset_array[i] = ftell(f); int8_t *data; size_t size, loop_start, loop_length; int volume, finetune; uint32_t frequency; instrument_get(i, &data, &size, &volume, &finetune, &loop_start, &loop_length, &frequency); int looping = 0; if (loop_length > 0) looping = 1; int loop_at_the_end = 1; if ((loop_start + loop_length) < size) loop_at_the_end = 0; uint32_t size_value; size_value = size; fwrite(&size_value, sizeof(size_value), 1, f); if ((looping == 1) && (loop_at_the_end == 0)) { // If the loop isn't at the end, copy it to the end after the // complete waveform. size_value = size; fwrite(&size_value, sizeof(size_value), 1, f); size_value = size + loop_length; fwrite(&size_value, sizeof(size_value), 1, f); } else { size_value = loop_start; fwrite(&size_value, sizeof(size_value), 1, f); size_value = loop_start + loop_length; fwrite(&size_value, sizeof(size_value), 1, f); } size_value = frequency; fwrite(&size_value, sizeof(size_value), 1, f); uint8_t value; value = volume; fwrite(&value, sizeof(value), 1, f); value = finetune; fwrite(&value, sizeof(value), 1, f); for (size_t j = 0; j < size; j++) { int8_t sample = data[j]; fwrite(&sample, sizeof(sample), 1, f); } // Write some more samples to help with mixer optimizations if (looping) { // Repeat loop if (loop_at_the_end) { // The only thing needed is to add the buffer size_t j = loop_start; for (int s = 0; s < UMODPACK_INSTRUMENT_EXTRA_SAMPLES; s++) { int8_t sample = data[j]; fwrite(&sample, sizeof(sample), 1, f); j++; if (j == (loop_start + loop_length)) j = loop_start; } } else { // First, copy the loop again for (size_t j = loop_start; j <= (loop_start + loop_length); j++) { int8_t sample = data[j]; fwrite(&sample, sizeof(sample), 1, f); } // Then, add the buffer size_t j = loop_start; for (int s = 0; s < UMODPACK_INSTRUMENT_EXTRA_SAMPLES; s++) { int8_t sample = data[j]; fwrite(&sample, sizeof(sample), 1, f); j++; if (j == (loop_start + loop_length)) j = loop_start; } } } else { // Write zeroes as buffer for (int s = 0; s < UMODPACK_INSTRUMENT_EXTRA_SAMPLES; s++) { int8_t sample = 0; fwrite(&sample, sizeof(sample), 1, f); } } // Align next element to 32 bit { long align = (4 - (ftell(f) & 3)) & 3; uint8_t val = 0; while (align > 0) { fwrite(&val, sizeof(val), 1, f); align--; } } } // Fill empty fields uint32_t offset; fseek(f, song_offsets, SEEK_SET); for (uint32_t i = 0; i < num_songs; i++) { offset = song_offset_array[i]; fwrite(&offset, sizeof(offset), 1, f); } fseek(f, pattern_offsets, SEEK_SET); for (uint32_t i = 0; i < num_patterns; i++) { offset = pattern_offset_array[i]; fwrite(&offset, sizeof(offset), 1, f); } fseek(f, instrument_offsets, SEEK_SET); for (uint32_t i = 0; i < num_instruments; i++) { offset = instrument_offset_array[i]; fwrite(&offset, sizeof(offset), 1, f); } ret = 0; cleanup: fclose(f); free(song_offset_array); free(pattern_offset_array); free(instrument_offset_array); return ret; }
<filename>components/table/techInfoTable/ITechInfoTableProps.ts import { Image } from '@prisma/client'; interface ITechInfoTableProps { image: Image; exposure: string | null; } export default ITechInfoTableProps;
def findPolicySet(self, policySetIdReference, common): policySet = self.policySetMap.get(policySetIdReference, None) if policySet is None: policySet = self._findPolicyFromReference(policySetIdReference, common) policySet = self.policySetMap.get(policySetIdReference, None) if policySet is None: raise XMLParseError("Referenced PolicySet of ID %r not found" % policySetIdReference) return policySet
<reponame>StarForger/neb-mc-rcon package cmd var ( BuildVersion string = "" )
<filename>gk2-lab2/vertexTypes.cpp<gh_stars>0 #include "vertexTypes.h" using namespace DirectX; using namespace mini; const D3D11_INPUT_ELEMENT_DESC VertexPositionColor::Layout[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, offsetof(VertexPositionColor, position), 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPositionColor, color), D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC VertexPositionNormal::Layout[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, offsetof(VertexPositionNormal, position), 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexPositionNormal, normal), D3D11_INPUT_PER_VERTEX_DATA, 0 } };
import gzip from lxml import etree from tqdm import tqdm import faiss import json import numpy as np import rltk from itertools import islice from sklearn.metrics import ndcg_score import time """ A scrpit contains some functions to help make predictions """ ############################################ for CSKG nodes ################################################################## def load_truth(input_file): """ Load the data from cue-target.xml (A cue to target file, the cue are sorted in alphabetical order and within a cue the targets are in decreasing order of similarity.) Here we regard this file as ground turth data Parameters ---------- input_file : str The file path of cue-target.xml Returns ------- ground_truth: dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity example for a key: 'turtle': ['slow','shell','tortoise','animal',...] """ tree = etree.parse(input_file) root = tree.getroot() # create a dict to store ground truth sets, # example : `p={'car': ['wheel', 'driver', ...], 'book`: [...]}` USF_FAN_dict = {} for cue_ele in root: key = cue_ele.get('word').lower() USF_FAN_dict[key] = [] for word_ele in cue_ele: USF_FAN_dict[key].append(word_ele.get('word').lower()) return USF_FAN_dict def load_cskg(input_file): """ Load the data from cskg_connected.tsv (A tsv file contains the raw cskg's information, each line's format is: id node1 relation node2 node1;label node2;label relation;label relation;dimension source sentence) Parameters ---------- input_file : str The file path of cskg_connected.tsv Returns ------- CSKG_label_dict: dict A dictionary whose key is the label of the node, value is a list of node IDs, whode node's label is the corresponding key. example for a key: 'turtle': ['Q1705322', '/c/en/turtle', ...], 'book`: [ 'Q997698','/c/en/book/v', ...] CSKG_inv_dict: dict A inverted index dictionary recording the correspondence between the ID and label of each node. The key is the node ID, the value is the node's label corresponding to the ID example for some keys: 'Q1705322':'turtle', '/c/en/turtle', 'Q997698':'book' """ CSKG_label_dict = {} CSKG_inv_dict = {} with open(input_file) as f: for line in islice(f, 1, None): # ignore first line(header) content = line.split('\t') node1_id = content[1] # node 1 id node2_id = content[3] # node 2 id node1_lbl = content[4] # node 1 label node2_lbl = content[5] # node 2 label # There might exists labels with multiple terms => CSKG_label_dict['allay|ease|relieve|still'], # in this case we only use first term "allay" node1_lbl = node1_lbl.split('|')[0] node2_lbl = node2_lbl.split('|')[0] CSKG_label_dict[node1_lbl] = CSKG_label_dict.get(node1_lbl,set()) CSKG_label_dict[node1_lbl].add(node1_id) CSKG_label_dict[node2_lbl] = CSKG_label_dict.get(node2_lbl,set()) CSKG_label_dict[node2_lbl].add(node2_id) CSKG_inv_dict[node1_id] = node1_lbl CSKG_inv_dict[node2_id] = node2_lbl for k in CSKG_label_dict.keys(): # convert set to list CSKG_label_dict[k] = list(CSKG_label_dict[k]) return CSKG_label_dict,CSKG_inv_dict def get_ground_truth(USF_FAN_dict,CSKG_label_dict): """ Generate the ground turth for following analysis Parameters ---------- USF_FAN_dict : dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity example for a key: 'turtle': ['slow','shell','tortoise','animal',...] CSKG_label_dict: dict: A dictionary whose key is the label of the node, value is a list of node IDs, whode node's label is the corresponding key. Returns ------- ground_truth: dict A dictionary whose key is both in USF_FAN and CSKG, value the same value as the USF_FAN_dict for the cue """ ground_truth = {} for cue in USF_FAN_dict: if cue in CSKG_label_dict: ground_truth[cue] = USF_FAN_dict[cue] return ground_truth def txt_emb_load(input_file): """ Load the data from bert-nli-large-embeddings.tsv.gz. (A tsv file in .gz format contains the text embedding for nodes. each line's format is: node property value) Mention ---------- Due to the large size of thie file, we first use `wc -l bert-nli-large-embeddings.tsv` to get the # of lines of this file and use tqdm module to show processing Parameters ---------- input_file : str The file path of bert-nli-large-embeddings.tsv.gz. Returns ------- text_embed_dict: dict A dictionary whose key is the Node ID, value is the text embeddings for such node. example: 'wn:zidovudine.n.01':[-0.17918809,-0.13626638,0.4172361,-0.5083385,-0.22449987,...] """ file_length = 2161049 # see mention text_embed_dict = {} with gzip.open(input_file, 'rb') as f: for line in tqdm(islice(f, 1, None),total=file_length-1,ncols=80): # ignore the header line = line.decode() node,prop,value = line.split('\t') value = value.split(',') embedding = [ float(i) for i in value] text_embed_dict[node] = embedding return text_embed_dict def graph_emb_load(input_file): """ Load CKSG node embeddings. (here we use trans_log_dot_0.1.tsv.gz, a tsv file in .gz format contains the graph embedding for nodes. each line includes node id and embeddings. Parameters ---------- input_file : str The file path of CKSG node embeddings Returns ------- graph_embed_dict: dict A dictionary whose key is the Node ID, value is the graph embeddings for such node. example: 'wn:zidovudine.n.01': [-0.23314859,-0.35881421,0.331990957,-0.112634301,0.047500141,0.567292035,...] """ graph_embed_dict = {} with gzip.open(input_file,'rt') as f: for index,line in enumerate(f): line = line.split('\t') node_id = line[0] value = [ float(i) for i in line[1:]] graph_embed_dict[node_id] = value return graph_embed_dict def get_label_emb(node_emb_dict,CSKG_label_dict): """ Calculate the average embeddings for labels on CSKG Parameters ---------- node_emb_dict : dict A dictionary whose key is the Node ID, value is the graph embeddings for such node. CSKG_label_dict: dict A dictionary whose key is the label of the node, value is a list of node IDs. Returns ------- label_emb_dict: dict A dictionary whose key is the Node label, value is the average embedding for such node. example: 'turtle': [-0.23314859,-0.35881421,0.331990957,-0.112634301,0.047500141,0.567292035,...] """ avg_embeddings = {} for label in CSKG_label_dict: list_node = CSKG_label_dict[label] num_node = len(list_node) sum_embedding = node_emb_dict.get(list_node[0],[]) # get first node's embedding as the initial embedding if not sum_embedding: # no embdding for such node id: continue for node in list_node[1:]: embedding = node_emb_dict.get(node,[]) if not embedding: num_node-=1 continue sum_embedding = list(map(lambda x,y : x+y ,sum_embedding,embedding)) avg_emb = [i/num_node for i in sum_embedding] avg_embeddings[label] = avg_emb return avg_embeddings def build_index(label_emb): """ Build a Faiss index for label embddings for future neighbor searching, here since cosine similarity will be adapted, FlatIndex is used Parameters ---------- label_emb : dict A dictionary whose key is the Node label, value is the average embeddings for such node. Returns ------- vec_index: faiss.swigfaiss_avx2.IndexFlat A IndexFlat that keeps the index for the label embeddings. The index number of each label is determined according to the order of adding, for example, the first index is 0. label_ix_dict: dict A dictionary whose key is the index number, value is the label. This dictionary is aimed at recording each label's position for future mapping. """ label_ix_dict = {} node_embeddings = [] index = 0 for key,value in label_emb.items(): label_ix_dict[index] = key index+=1 node_embeddings.append(value) # entity_embeddings => matrix X contains all labels' embeddings X = np.array(node_embeddings).astype(np.float32) # float32 dimension = X.shape[1] # build index (METRIC_INNER_PRODUCT => cos ) vec_index = faiss.index_factory(dimension, "Flat", faiss.METRIC_INNER_PRODUCT) faiss.normalize_L2(X) # normalize all vectors in order to get cos sim # add vectors to inde vec_index.add(X) return vec_index,label_ix_dict def create_queryset(ground_truth,label_emb_dict): """ Create queryset for CSKG's labels according to USF_FAN's cues Parameters ---------- ground_truth : dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity label_emb_dict: dict A dictionary whose key is the node's label, value is the average embedding for such node. Returns ------- query_dict: dict A dictionary whose key is both in ground_truth and CSKG, value is the graph embedding value for labels on CSKG nodes """ query_dict = {} for cue in ground_truth: # convert the label's embedding to the same foramt as faiss for future searching label_embedding = label_emb_dict[cue] query_mat = np.array(label_embedding).reshape((1,-1)).astype(np.float32) faiss.normalize_L2(query_mat) query_dict[cue] = query_mat return query_dict def get_label_neighbor(label_vec,vec_index,label_ix_dict,X,include=False): """ Search neighbors for a label according to cosine similarity among labels' embedding Parameters ---------- label_vec: np.ndarray a normalized vector whose shape is 1 x n , this vector is the embedding value for a label vec_index: faiss.swigfaiss_avx2.IndexFlat A IndexFlat that keeps the index for the label embeddings. The index number of each label is determined according to the order of adding, for example, the first index is 0. label_ix_dict: dict A dictionary whose key is the index number, value is the label. This dictionary is aimed at recording each label's order for future mapping. X: int how many similar targets should be returned include: boolean [default:False] When do searching, whether include the label itself, if set True, then the first neighbor is the label itself Returns ------- neighbors: list A list containing the label's similar targets in decreasing order of cosine similarity. each item in the list is a tuple, format is (target, similarity to the label) """ neighbors = [] cos_sim, index = vec_index.search(label_vec, X+1) for ix in index[0][:]: # ignore itself index is 1x(X+1) so need to use index[0] get the list target = label_ix_dict[ix] neighbors.append(target) if include: relevance = cos_sim[0][:X] neighbors = list(zip(neighbors[:X],relevance)) return neighbors else: relevance = cos_sim[0][1:X+1] neighbors = list(zip(neighbors[1:],relevance)) return neighbors def neighbor_search(query_dict,ground_truth,vec_index,label_ix_dict,X): """ Search neighbors for queryset according to cosine similarity among labels' embedding Parameters ---------- query_dict : dict A dictionary whose key is both in ground_truth and CSKG, value is the embedding value according to CSKG ground_truth: dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity vec_index: faiss.swigfaiss_avx2.IndexFlat A IndexFlat that keeps the index for the label embeddings. The index number of each label is determined according to the order of adding, for example, the first index is 0. label_ix_dict: dict A dictionary whose key is the index number, value is the label. This dictionary is aimed at recording each label's order for future mapping. X: int Indicates how many times the data is extracted from CSKG according to the ground truth's label's targets number example: if we set X = 1 , and for a cue 'turtle' in USF_FAN_dict, there exists 18 similar targets for this cue, then we will search 18 similar labels for 'turtle' in CSKG Returns ------- neighbor_dict: dict A dictionary whose key is a label in CSKG, value is a list containing the label's similar targets in decreasing order of cosine similarity, each item in the list is a tuple, first item is the similar target, and second one is the similarity to the label. example: {'a': [('s', 0.9048489),('more', 0.88388747),('c', 0.8800387)...]...} """ neighbor_dict = {} for query_label in tqdm(query_dict,total=len(query_dict),ncols=80): #number of target for this label/cue in ground turth target_num = len(ground_truth[query_label]) # query label's embedding on CSKG label_vec = query_dict[query_label] # searched targets neighbors = get_label_neighbor(label_vec,vec_index,label_ix_dict,X*target_num) neighbor_dict[query_label] = neighbors return neighbor_dict def adp_neighbor_search(query_dict,ground_truth,vec_index,label_ix_dict,X,threshold=0.8): """ Advanced Search neighbors for queryset according to cosine similarity among labels' embedding, when returned target has a high levenshtein similarity or contains the label , then disgard it. example: lev_sim('give up', 'giveing up') > 0.8, disgard it; cue: 'turtle', target: 'green turtle' , disgard it Parameters ---------- query_dict : dict A dictionary whose key is both in ground_truth and CSKG, value is the embedding value according to CSKG ground_truth: dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity vec_index: faiss.swigfaiss_avx2.IndexFlat A IndexFlat that keeps the index for the label embeddings. The index number of each label is determined according to the order of adding, for example, the first index is 0. label_ix_dict: dict A dictionary whose key is the index number, value is the label. This dictionary is aimed at recording each label's order for future mapping. X: int Indicates how many times the data is extracted from CSKG according to the ground truth's label's targets number example: if we set X = 1 , and for a cue 'turtle' in USF_FAN_dict, there exists 18 similar targets for this cue, then we will search 18 similar labels for 'turtle' in CSKG threshold: float [default:0.8] If the return target has a similarity equal or more than 0.8 with cue, then disgard this one Returns ------- neighbor_dict: dict A dictionary whose key is a label in CSKG, value is a list containing the label's similar targets in decreasing order of cosine similarity, each item in the list is a tuple, first item is the similar target, and second one is the similarity to the label. example: {'a': [('s', 0.9048489),('more', 0.88388747),('c', 0.8800387)...]...} """ neighbor_dict = {} for query_label in tqdm(query_dict,total=len(query_dict),ncols=80): neighbor_dict[query_label] = [] #number of target for this label/cue in ground turth target_num = len(ground_truth[query_label]) iter_times = 1 while len(neighbor_dict[query_label]) < target_num: neighbor_dict[query_label] = [] # query label's embedding on CSKG label_vec = query_dict[query_label] # searched targets neighbors = get_label_neighbor(label_vec,vec_index,label_ix_dict,500*iter_times) for target,sim in neighbors: if rltk.similarity.levenshtein.levenshtein_similarity(target,query_label) < threshold \ and query_label not in target: neighbor_dict[query_label].append((target,sim)) iter_times+=1 neighbor_dict[query_label] = neighbor_dict[query_label][:target_num*X] return neighbor_dict def get_pred_dict(neighbor_dict): """ Generate the same foramt with ground turth for future analysis Parameters ---------- neighbor_dict : dict A dictionary whose key is a label in CSKG, value is a list containing the label's similar targets in decreasing order of cosine similarity, each item in the list is a tuple, first item is the similar target, and second one is the similarity to the label. example: {'a': [('s', 0.9048489),('more', 0.88388747),('c', 0.8800387)...]...} Rreturn ---------- pred_dict: dict A dictionary whose key is a cue's label, value is a list containing cue's similar targets in decreasing order of similarity generated by faiss neighbor searching """ pred_dict = {} for label in neighbor_dict: pred_dict[label] = [i[0] for i in neighbor_dict[label]] return pred_dict def export_cue_targets(cue_targets,output_file): """ Export cur and targets to a json file Parameters ---------- cue_targets: dict A dictionary whose key is the cue/label, value is a list of the similar targets to the cue/label """ with open(output_file,'w') as f: json.dump(cue_targets,f) return #########################################################################################################################
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ import * as Immutable from 'immutable'; import type { Store } from 'stores/StoreTypes'; import { QueriesActions, QueriesStore } from 'views/stores/QueriesStore'; import { ViewStore } from 'views/stores/ViewStore'; import { GlobalOverrideActions, GlobalOverrideStore } from 'views/stores/GlobalOverrideStore'; import SearchActions from 'views/actions/SearchActions'; import Query from '../queries/Query'; import View from '../views/View'; import GlobalOverride from '../search/GlobalOverride'; import type { ElasticsearchQueryString, QueryId } from '../queries/Query'; function connectToStore<State>(store: Store<State>, updateFn: (state: State) => unknown): void { updateFn(store.getInitialState()); store.listen(updateFn); } export default class QueryManipulationHandler { queries: Immutable.OrderedMap<QueryId, Query>; view: View; globalOverride: GlobalOverride | undefined | null; constructor() { connectToStore(QueriesStore, (queries) => { this.queries = queries; }); connectToStore(ViewStore, ({ view }) => { this.view = view; }); connectToStore(GlobalOverrideStore, (globalOverride) => { this.globalOverride = globalOverride; }); } _queryStringFromActiveQuery = (queryId: QueryId): string => { const query = this.queries.get(queryId); return query.query.query_string; }; _queryStringFromGlobalOverride = () => { const { query_string: queryString }: ElasticsearchQueryString = this.globalOverride && this.globalOverride.query ? this.globalOverride.query : { type: 'elasticsearch', query_string: '' }; return queryString; }; currentQueryString = (queryId: QueryId) => (this.view.type === View.Type.Search ? this._queryStringFromActiveQuery(queryId) : this._queryStringFromGlobalOverride()); updateQueryString = (queryId: QueryId, queryString: string) => (this.view.type === View.Type.Search ? QueriesActions.query(queryId, queryString) : GlobalOverrideActions.query(queryString).then(SearchActions.refresh)); }
Newton polygon stratification of the Torelli locus in PEL-type Shimura varieties We study the intersection of the Torelli locus with the Newton polygon stratification of the modulo $p$ reduction of certain PEL-type Shimura varieties. We develop a clutching method to show that the intersection of the Torelli locus with some Newton polygon strata is non-empty and has the expected codimension. This yields results about the Newton polygon stratification of Hurwitz spaces of cyclic covers of the projective line. The clutching method allows us to guarantee the existence of a smooth curve whose Newton polygon is the amalgamate sum of two other Newton polygons, under certain compatibility conditions. As an application, we produce infinitely many new examples of Newton polygons that occur for Jacobians of smooth curves in characteristic $p$. Most of these arise in inductive systems which demonstrate unlikely intersections of the Torelli locus with the Newton polygon stratification. As another application, for the PEL-type Shimura varieties associated to the twenty special families of cyclic covers of the projective line found by Moonen, we prove that all Newton polygon strata intersect the open Torelli locus (assuming $p$ sufficiently large for certain supersingular cases).
// This function initializes the decoder for reading a new image. static WORD init_exp( WORD size ) { curr_size = size + 1; top_slot = 1 << curr_size; clear = 1 << size; ending = clear + 1; slot = newcodes= ending + 1; navail_bytes = 0; nbits_left = 0; return(0); }
def average_by_events(epochs, method='mean'): picks_dict = {'picks': ['eeg', 'misc']} \ if isinstance(epochs, Epochs) else {} evokeds = [] for event_type in epochs.event_id.keys(): evoked = epochs[event_type].average(**picks_dict, method=method) evoked.comment = event_type evokeds.append(evoked) return evokeds
def process(cls, input_payload): alerts = [] payload = copy(input_payload) rules = [rule_attrs for rule_attrs in cls.__rules.values() if rule_attrs.logs is None or payload.log_source in rule_attrs.logs] if not rules: LOGGER.debug('No rules to process for %s', payload) return alerts for record in payload.records: for rule in rules: has_sub_keys = cls.process_subkeys(record, payload.type, rule) if not has_sub_keys: continue matcher_result = cls.match_event(record, rule) if not matcher_result: continue types_result = None if rule.datatypes: types_result = cls.match_types(record, payload.normalized_types, rule.datatypes) if types_result: record_copy = record.copy() record_copy['normalized_types'] = types_result else: record_copy = record rule_result = cls.process_rule(record_copy, rule) if rule_result: LOGGER.info('Rule [%s] triggered an alert on log type [%s] from entity \'%s\' ' 'in service \'%s\'', rule.rule_name, payload.log_source, payload.entity, payload.service()) alert = { 'record': record_copy, 'rule_name': rule.rule_name, 'rule_description': rule.rule_function.__doc__ or DEFAULT_RULE_DESCRIPTION, 'log_source': str(payload.log_source), 'log_type': payload.type, 'outputs': rule.outputs, 'source_service': payload.service(), 'source_entity': payload.entity} alerts.append(alert) return alerts
// BucketService tests all the service functions. func BucketService( init func(BucketFields, *testing.T) (influxdb.BucketService, string, func()), t *testing.T, opts ...BucketSvcOpts) { tests := []struct { name string fn bucketServiceF }{ { name: "CreateBucket", fn: CreateBucket, }, { name: "IDUnique", fn: IDUnique, }, { name: "FindBucketByID", fn: FindBucketByID, }, { name: "FindBuckets", fn: FindBuckets, }, { name: "FindBucket", fn: FindBucket, }, { name: "UpdateBucket", fn: UpdateBucket, }, { name: "DeleteBucket", fn: DeleteBucket, }, } for _, tt := range tests { if tt.name == "IDUnique" && len(opts) > 0 && opts[0].NoHooks { continue } t.Run(tt.name, func(t *testing.T) { tt.fn(init, t) }) } }
def do__dir_triggers(self, arg, opts): self.do__dir_(arg, opts, 'triggers', self._str_trigger)
/**HEADER******************************************************************** * * Copyright (c) 2008-2015 Freescale Semiconductor; * All Rights Reserved * * Copyright (c) 1989-2008 ARC International; * All Rights Reserved * *************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 OR ITS 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. * ************************************************************************** * * $FileName: ehci_main.c$ * $Version : 3.8.43.0$ * $Date : Oct-4-2012$ * * Comments: * * This file contains the main low-level Host API functions specific to * the VUSB chip. * *END************************************************************************/ #include "usb_host_config.h" #if USBCFG_HOST_EHCI #include "usb.h" #include "usb_host_stack_interface.h" #include "usb_host_common.h" #include "usb_host.h" #include "ehci_prv.h" #include "usb_host_dev_mng.h" #include "fsl_usb_ehci_hal.h" #if USBCFG_EHCI_PIN_DETECT_ENABLE #define MAX_EHCI_DEV_NUM 2 #include "usb_pin_detect.h" usb_pin_detect_service_t host_pin_detect_service[MAX_EHCI_DEV_NUM]; #endif #define USBCFG_EHCI_HOST_ENABLE_TASK 1 #if USBCFG_EHCI_HOST_ENABLE_TASK // EHCI event bits #define EHCI_EVENT_ATTACH 0x01 #define EHCI_EVENT_RESET 0x02 #define EHCI_EVENT_TOK_DONE 0x04 #define EHCI_EVENT_SOF_TOK 0x08 #define EHCI_EVENT_DETACH 0x10 #define EHCI_EVENT_SYS_ERROR 0x20 #define EHCI_EVENT_ID_CHANGE 0x40 //qtd software default timeout is 30*100ms = 3S #define QTD_TIMEOUT_DEFAULT 100 #if !(USE_RTOS) #define USB_EHCI_HOST_TASK_ADDRESS _usb_ehci_host_task #else #define USB_EHCI_HOST_TASK_ADDRESS _usb_ehci_host_task_stun #endif #define USB_EHCI_HOST_TASK_STACKSIZE 1600 #define USB_EHCI_HOST_TASK_NAME "EHCI HOST Task" #if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && USE_RTOS) /* USB stack running on MQX */ #define USB_NONBLOCKING_MODE 0 #elif ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (!USE_RTOS)) /* USB stack running on BM */ #define USB_NONBLOCKING_MODE 1 #endif #endif #if defined( __ICCARM__ ) #pragma data_alignment=4096 __no_init static uint8_t usbhs_perodic_list[4096]; #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((aligned(4096))) static uint8_t usbhs_perodic_list[4096]; #else #error Unsupported compiler, please use IAR, Keil or arm gcc compiler and rebuild the project. #endif #ifdef __USB_OTG__ #include "otgapi.h" extern USB_OTG_STATE_STRUCT_PTR usb_otg_state_struct_ptr; #endif extern usb_host_state_struct_t g_usb_host[2]; static uint8_t uframe_max[8] = {125, 125, 125, 125, 125, 125, 125, 25}; #define USBHS_USBMODE_CM_HOST_MASK USBHS_USBMODE_CM(3) #if USBCFG_EHCI_HS_DISCONNECT_ENABLE extern void bsp_usb_hs_disconnect_detection_disable(uint8_t controller_id); extern void bsp_usb_hs_disconnect_detection_enable(uint8_t controller_id); #endif extern usb_status usb_host_ehci_phy_init( uint8_t controller_id); static usb_status _usb_ehci_commit_high_speed_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr); static usb_status _usb_ehci_commit_split_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr); static usb_status _usb_ehci_commit_split_iso_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr); static usb_status _usb_ehci_commit_split_interrupt_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr); static usb_status _usb_ehci_allocate_high_speed_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t time_for_action, uint8_t* bandwidth_slots, uint32_t start_uframe ); static usb_status _usb_ehci_allocate_fsls_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t time_for_nohs, uint32_t frame_start, uint8_t uframe_start, uint8_t uframe_end, uint8_t* num_transaction ); static usb_status _usb_ehci_hs_sum_fsls_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t* uframe_bandwidth, uint32_t frame); static usb_status _usb_ehci_hs_sum_hs_bandwidth(usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t* uframe_bandwidth, uint32_t uframe); static void link_interrupt_qh_to_periodiclist(usb_host_handle handle, ehci_qh_struct_t* qh_ptr, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t slot_number); static void unlink_interrupt_qh_from_periodiclist(usb_host_handle handle, ehci_qh_struct_t* qh_ptr, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t slot_number); void _usb_ehci_get_qtd(usb_host_handle handle, ehci_qtd_struct_t** qtd_ptr); void _usb_ehci_free_qtd(usb_host_handle handle, ehci_qtd_struct_t* qtd); void _usb_ehci_get_qh(usb_host_handle handle, ehci_qh_struct_t** qh_ptr); void _usb_ehci_free_qh(usb_host_handle handle, ehci_qh_struct_t* qh); void init_the_volatile_struct_to_zero(void* struct_ptr, uint32_t size); extern uint8_t soc_get_usb_vector_number(uint8_t controller_id); extern uint32_t soc_get_usb_base_address(uint8_t controller_id); extern uint32_t soc_get_usb_host_int_level(uint8_t controller_id); #if USBCFG_EHCI_PIN_DETECT_ENABLE /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_host_register_pin_detect_service * @return USB_OK on successful. * Comments : * get id detector pin status *END*-----------------------------------------------------------------*/ usb_status usb_host_register_pin_detect_service ( /* [IN] type of event or endpoint number to service */ uint8_t controller_id, /* [IN] Pointer to the service's callback function */ usb_pin_detect_service_t service, /*[IN] User Argument to be passed to Services when invoked.*/ void* arg ) { if (controller_id < USB_CONTROLLER_EHCI_0) { return USBERR_INVALID_DEVICE_NUM; } if (service != NULL) { host_pin_detect_service[controller_id - USB_CONTROLLER_EHCI_0] = service; } return USB_OK; } #endif #if USBCFG_HOST_COMPLIANCE_TEST #include "usb_host_ch9.h" #define SINGLE_STEP_SLEEP_COUNT 15000 #define USB_HIGH_SPEED 0x01 #define USB_FULL_SPEED 0x02 #define USB_LOW_SPEED 0x03 /* controller port test mode */ #define PORTSC_PTC_TEST_MODE_DISABLE 0x00 #define PORTSC_PTC_TEST_J 0x01 #define PORTSC_PTC_TEST_K 0x02 #define PORTSC_PTC_SE0_NAK 0x03 #define PORTSC_PTC_TEST_PACKET 0x04 #define PORTSC_PTC_FORCE_ENABLE_HS 0x05 #define PORTSC_PTC_FORCE_ENABLE_FS 0x06 #define PORTSC_PTC_FORCE_ENABLE_LS 0x07 /* Other test */ #define HSET_TEST_SUSPEND_RESUME 0x08 #define HSET_TEST_GET_DEV_DESC 0x09 #define HSET_TEST_GET_DEV_DESC_DATA 0x0A #define TEST_DEVICE_VID 0x1A0A static uint8_t single_step_desc_data_on=0; void set_single_step_desc_data_on(void) { single_step_desc_data_on = 1; } void clear_single_step_desc_data_on(void) { single_step_desc_data_on = 0; } /*FUNCTION*---------------------------------------------------------------- * * Function Name : _usb_dci_usbhs_set_test_mode * Returned Value : None * Comments : * sets/resets the test mode * *END*--------------------------------------------------------------------*/ usb_status _usb_usbhs_set_test_mode ( /* [IN] Handle to the USB device */ usb_host_handle handle, /* [IN] Test mode */ uint16_t test_mode ) { /* Body */ usb_host_state_struct_t* host_ptr = handle; usb_ehci_host_state_struct_t* usb_host_ptr = host_ptr->controller_handle; uint32_t port_control; port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_control &= ~(uint32_t)(0xf << 16); port_control |= (uint32_t)((uint32_t)test_mode <<16); usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, port_control); // USB_PRINTF(" 0x%x 0x%x\n",test_mode, // usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase)); return USB_OK; } /* EndBody */ usb_status _usb_usbhs_kill_per_sched(usb_host_handle handle) { usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; usb_hal_ehci_disable_usb_cmd_periodic_sched(usb_host_ptr->usbRegBase); return USB_OK; } /* EndBody */ static void test_j(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; _usb_usbhs_set_test_mode(dev_ptr->host, PORTSC_PTC_TEST_J); } static void test_k(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; _usb_usbhs_set_test_mode(dev_ptr->host, PORTSC_PTC_TEST_K); } static void test_se0_nak(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; _usb_usbhs_set_test_mode(dev_ptr->host, PORTSC_PTC_SE0_NAK); } static void test_packet(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; _usb_usbhs_set_test_mode(dev_ptr->host, PORTSC_PTC_TEST_PACKET); } static void test_force_enable(usb_device_instance_handle dev_handle, uint32_t forcemode) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; uint32_t ptc_fmode; switch (forcemode) { case USB_HIGH_SPEED: ptc_fmode = PORTSC_PTC_FORCE_ENABLE_HS; break; case USB_FULL_SPEED: ptc_fmode = PORTSC_PTC_FORCE_ENABLE_FS; break; case USB_LOW_SPEED: ptc_fmode = PORTSC_PTC_FORCE_ENABLE_LS; break; default: USB_PRINTF("unknown speed mode %d\n", forcemode); return; } _usb_usbhs_set_test_mode(dev_ptr->host, ptc_fmode); } static void test_suspend_resume(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; usb_host_state_struct_t* host_ptr = (usb_host_state_struct_t*)dev_ptr->host; OS_Time_delay(15000); _usb_ehci_bus_suspend (host_ptr->controller_handle); OS_Time_delay(15000); /* Wait for 15s */ _usb_ehci_bus_resume (host_ptr->controller_handle); } static void test_single_step_get_dev_desc(usb_device_instance_handle dev_handle) { static uint8_t buffer[USB_DESC_LEN_DEV]; dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; usb_host_state_struct_t* host_ptr = (usb_host_state_struct_t*)dev_ptr->host; usb_status status; _usb_usbhs_kill_per_sched(host_ptr->controller_handle); OS_Time_delay(SINGLE_STEP_SLEEP_COUNT); /* SOF for 15s */ status = _usb_host_ch9_get_descriptor(dev_handle, USB_DESC_TYPE_DEV << 8, 0, USB_DESC_LEN_DEV, buffer); } #define SINGLE_STEP_PHASE_SETUP 0 #define SINGLE_STEP_PHASE_DATA 1 #define SINGLE_STEP_PHASE_STATUS 2 #define SINGLE_STEP_PHASE_NONE 0xFF uint32_t _usb_ehci_init_single_step_qtd_link ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { ehci_qtd_struct_t* qtd_ptr; ehci_qtd_struct_t* prev_qtd_ptr; ehci_qtd_struct_t* first_qtd_ptr = NULL; uint32_t pid_code; uint32_t next_pidcode; uint32_t data_toggle, token; uint32_t total_length; unsigned char * buff_ptr; static uint32_t phase_state = SINGLE_STEP_PHASE_NONE; if(phase_state == SINGLE_STEP_PHASE_NONE) { _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } data_toggle = ((uint32_t)pipe_descr_ptr->common.nextdata01 << EHCI_QTD_DATA_TOGGLE_BIT_POS); prev_qtd_ptr = first_qtd_ptr = qtd_ptr; pid_code = EHCI_QTD_PID_SETUP; token = (((uint32_t)8 << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | pid_code | EHCI_QTD_STATUS_ACTIVE); /* Initialize a QTD for Setup phase */ _usb_ehci_init_qtd(handle, qtd_ptr, (uint8_t *)&current_pipe_tr_struct_ptr->setup_packet, token); qtd_ptr->length = 8; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; phase_state = SINGLE_STEP_PHASE_SETUP; return ((uint32_t)first_qtd_ptr); } /* Get a QTD from the queue for the data phase or a status phase */ if(phase_state == SINGLE_STEP_PHASE_SETUP) { _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } /* The data phase QTD chained to the Setup QTD */ prev_qtd_ptr = first_qtd_ptr = qtd_ptr; usb_hal_ehci_link_qtd(prev_qtd_ptr, (uint32_t)qtd_ptr); prev_qtd_ptr->next = qtd_ptr; data_toggle = (uint32_t)(EHCI_QTD_DATA_TOGGLE); if (current_pipe_tr_struct_ptr->send_phase) { total_length = current_pipe_tr_struct_ptr->tx_length; buff_ptr = current_pipe_tr_struct_ptr->tx_buffer; pid_code = EHCI_QTD_PID_OUT; next_pidcode = EHCI_QTD_PID_IN; } else { total_length = current_pipe_tr_struct_ptr->rx_length; buff_ptr = current_pipe_tr_struct_ptr->rx_buffer; pid_code = EHCI_QTD_PID_IN; next_pidcode = EHCI_QTD_PID_OUT; } if (total_length) { token = ((total_length << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | pid_code | EHCI_QTD_STATUS_ACTIVE); _usb_ehci_init_qtd(handle, qtd_ptr, buff_ptr, token); qtd_ptr->length = total_length; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; /* Use the QTD to chain the next QTD */ prev_qtd_ptr = qtd_ptr; } phase_state = SINGLE_STEP_PHASE_DATA; return ((uint32_t)first_qtd_ptr); } if(phase_state == SINGLE_STEP_PHASE_DATA) { /* Get a QTD for the queue for status phase */ _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } prev_qtd_ptr = first_qtd_ptr = qtd_ptr; usb_hal_ehci_link_qtd(prev_qtd_ptr, (uint32_t)qtd_ptr); prev_qtd_ptr->next = qtd_ptr; token = ((0 << EHCI_QTD_LENGTH_BIT_POS) | (EHCI_QTD_DATA_TOGGLE) | EHCI_QTD_IOC | next_pidcode | EHCI_QTD_STATUS_ACTIVE); _usb_ehci_init_qtd(handle, qtd_ptr, NULL, token); qtd_ptr->length = 0; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; phase_state = SINGLE_STEP_PHASE_STATUS; first_qtd_ptr = qtd_ptr; } return ((uint32_t)first_qtd_ptr); } /* EndBody */ static void test_single_step_get_dev_desc_data(usb_device_instance_handle dev_handle) { dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; usb_host_state_struct_t* host_ptr = (usb_host_state_struct_t*)dev_ptr->host; usb_status status; static uint8_t buffer[USB_DESC_LEN_DEV]; int result; set_single_step_desc_data_on(); status = _usb_host_ch9_get_descriptor(dev_handle, USB_DESC_TYPE_DEV << 8, 0, USB_DESC_LEN_DEV, buffer); if (status != USB_OK) { USB_PRINTF ("the setup transaction failed %d\r\n", status); } else { USB_PRINTF ( "the setup transaction passed\r\n"); } _usb_usbhs_kill_per_sched(host_ptr->controller_handle); OS_Time_delay(SINGLE_STEP_SLEEP_COUNT); status = _usb_host_ch9_get_descriptor(dev_handle, USB_DESC_TYPE_DEV << 8, 0, USB_DESC_LEN_DEV, buffer); if (status != USB_OK) { USB_PRINTF ("the data transaction failed %d\r\n", status); } else { USB_PRINTF ( "the data transaction passed\r\n"); } status = _usb_host_ch9_get_descriptor(dev_handle, USB_DESC_TYPE_DEV << 8, 0, USB_DESC_LEN_DEV, buffer); if (status != USB_OK) { USB_PRINTF ("the status transaction failed %d\r\n", status); } else { USB_PRINTF ( "the status transaction passed\r\n"); } clear_single_step_desc_data_on(); OS_Time_delay(SINGLE_STEP_SLEEP_COUNT); /* SOF for 15s */ USB_PRINTF ( "test_single_step_get_dev_desc_data finished\r\n"); } /*FUNCTION*---------------------------------------------------------------- * * Function Name : usb_test_mode_init * Returned Value : None * Comments : * This function is called by common class to initialize the class driver. It * is called in response to a select interface call by application * *END*--------------------------------------------------------------------*/ usb_status usb_ehci_test_mode_init (usb_device_instance_handle dev_handle) { /* Body */ uint16_t dev_Vendor, dev_Product; dev_instance_t* dev_ptr = (dev_instance_t*)dev_handle; dev_Vendor = USB_SHORT_UNALIGNED_LE_TO_HOST(dev_ptr->dev_descriptor.idVendor); dev_Product = USB_SHORT_UNALIGNED_LE_TO_HOST(dev_ptr->dev_descriptor.idProduct); USB_PRINTF("\r\n usb_ehci_test_mode_init dev_Product:0x%x\r\n", dev_Product); switch (dev_Product){ case 0x0101: test_se0_nak(dev_handle); break; case 0x0102: test_j(dev_handle); break; case 0x0103: test_k(dev_handle); break; case 0x0104: test_packet(dev_handle); break; case 0x0105: USB_PRINTF("Force FS/FS/LS ?\r\n"); test_force_enable(dev_handle, USB_HIGH_SPEED); break; case 0x0106: test_suspend_resume(dev_handle); break; case 0x0107: USB_PRINTF( "Begin SINGLE_STEP_GET_DEVICE_DESCRIPTOR\r\n"); test_single_step_get_dev_desc(dev_handle); break; case 0x0108: USB_PRINTF("Begin SINGLE_STEP_GET_DEVICE_DESCRIPTOR_DATA\r\n"); test_single_step_get_dev_desc_data(dev_handle); break; default: return USBERR_ERROR; } return USB_OK; } /* Endbody */ /* EOF */ #endif /************************************************************************** Local Functions. Note intended to be called from outside this file **************************************************************************/ /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_send_data * Returned Value : None * Comments : * Send the data *END*-----------------------------------------------------------------*/ usb_status usb_ehci_send_data ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] The pipe descriptor to queue */ pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_status status; status = _usb_ehci_queue_pkts(handle, (ehci_pipe_struct_t*) pipe_descr_ptr, (tr_struct_t*) current_pipe_tr_struct_ptr); return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_send_setup * Returned Value : usb_status * Comments : * Send Setup packet *END*-----------------------------------------------------------------*/ usb_status usb_ehci_send_setup ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] The pipe descriptor to queue */ pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_status status; status = _usb_ehci_queue_pkts(handle, (ehci_pipe_struct_t*) pipe_descr_ptr, (tr_struct_t*) current_pipe_tr_struct_ptr); return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_recv_data * Returned Value : None * Comments : * Receive data *END*-----------------------------------------------------------------*/ usb_status usb_ehci_recv_data ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] The pipe descriptor to queue */ pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_status status; status = _usb_ehci_queue_pkts(handle, (ehci_pipe_struct_t*) pipe_descr_ptr, (tr_struct_t*) current_pipe_tr_struct_ptr); return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_queue_pkts * Returned Value : status of the transfer queuing. * Comments : * Queue the packet in the hardware *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_queue_pkts ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_status status; if (pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE ) { current_pipe_tr_struct_ptr->setup_first_phase = 0; } switch (pipe_descr_ptr->common.pipetype) { #if USBCFG_EHCI_MAX_ITD_DESCRS || USBCFG_EHCI_MAX_SITD_DESCRS case USB_ISOCHRONOUS_PIPE: status = _usb_ehci_add_isochronous_xfer_to_periodic_schedule_list(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); break; #endif #ifdef USBCFG_EHCI_MAX_QTD_DESCRS case USB_INTERRUPT_PIPE: status = _usb_ehci_add_interrupt_xfer_to_periodic_list(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); break; case USB_CONTROL_PIPE: case USB_BULK_PIPE: status = _usb_ehci_add_xfer_to_asynch_schedule_list(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); break; #endif default: status = USB_STATUS_ERROR; break; } return status; } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_update_active_async * Returned Value : None * Comments : * Link the qtd to the qh for interrupt/Bulk/Control transfers. *END*-----------------------------------------------------------------*/ void _usb_ehci_update_active_async ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; qh_ptr = usb_host_ptr->active_async_list_ptr; if (qh_ptr == NULL) { EHCI_MEM_WRITE(usb_host_ptr->dummy_qh->horiz_link_ptr, (((uint32_t)usb_host_ptr->dummy_qh & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))) } else { EHCI_MEM_WRITE(qh_ptr->horiz_link_ptr, (( (uint32_t)usb_host_ptr->dummy_qh->horiz_link_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))) EHCI_MEM_WRITE(usb_host_ptr->dummy_qh->horiz_link_ptr, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))) } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_link_qtd_to_qh * Returned Value : None * Comments : * Link the qtd to the qh for interrupt/Bulk/Control transfers. *END*-----------------------------------------------------------------*/ void _usb_ehci_link_qtd_to_qh ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the queue head to initialize */ ehci_qh_struct_t* qh_ptr, /* [IN] the first QTD to queue for this Queue head */ ehci_qtd_struct_t* qtd_ptr ) { ehci_qtd_struct_t* temp_qtd_ptr; temp_qtd_ptr = (ehci_qtd_struct_t*)qh_ptr->qtd_head; if (( ((uint32_t)temp_qtd_ptr) & EHCI_QTD_T_BIT) || (temp_qtd_ptr == NULL)) { qh_ptr->qtd_head = qtd_ptr; } else { while ((temp_qtd_ptr != NULL) && (!(usb_hal_ehci_get_next_qtd_ptr(temp_qtd_ptr) & EHCI_QTD_T_BIT))) { temp_qtd_ptr = (ehci_qtd_struct_t*)usb_hal_ehci_get_next_qtd_ptr(temp_qtd_ptr); } //EHCI_MEM_WRITE(temp_qtd_ptr->next_qtd_ptr, (uint32_t)qtd_ptr); usb_hal_ehci_link_qtd(temp_qtd_ptr,(uint32_t)qtd_ptr); temp_qtd_ptr->next = qtd_ptr; } if (usb_hal_ehci_get_next_qtd_link_ptr(qh_ptr)& EHCI_QTD_T_BIT) { //EHCI_MEM_WRITE(qh_ptr->alt_next_qtd_link_ptr, EHCI_QTD_T_BIT); usb_hal_ehci_set_qh_next_alt_qtd_link_terminate(qh_ptr); //EHCI_MEM_WRITE(qh_ptr->next_qtd_link_ptr, (uint32_t)qtd_ptr); usb_hal_ehci_set_qh_next_qtd_link_ptr(qh_ptr, (uint32_t)qtd_ptr); } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_link_qh_to_active_list * Returned Value : None * Comments : * Link the qtd to the qh for interrupt/Bulk/Control transfers. *END*-----------------------------------------------------------------*/ void _usb_ehci_link_qh_to_async_active_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the queue head to initialize */ ehci_qh_struct_t* qh_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; if (usb_host_ptr->active_async_list_ptr == NULL) { usb_host_ptr->active_async_list_ptr = qh_ptr; usb_host_ptr->active_async_list_tail_ptr = qh_ptr; //EHCI_MEM_WRITE(qh_ptr->horiz_link_ptr, (( (uint32_t)usb_host_ptr->dummy_qh->horiz_link_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_hal_ehci_set_qh_horiz_link_ptr(qh_ptr, (( (uint32_t)usb_host_ptr->dummy_qh->horiz_link_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); //EHCI_MEM_WRITE(usb_host_ptr->dummy_qh->horiz_link_ptr, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_hal_ehci_set_qh_horiz_link_ptr(usb_host_ptr->dummy_qh, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); //_usb_ehci_update_active_async(handle); } else { //EHCI_MEM_WRITE(qh_ptr->horiz_link_ptr, (( (uint32_t)usb_host_ptr->active_async_list_tail_ptr->horiz_link_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_hal_ehci_set_qh_horiz_link_ptr(qh_ptr, (( (uint32_t)usb_host_ptr->active_async_list_tail_ptr->horiz_link_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); //EHCI_MEM_WRITE(usb_host_ptr->active_async_list_tail_ptr->horiz_link_ptr, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_hal_ehci_set_qh_horiz_link_ptr(usb_host_ptr->active_async_list_tail_ptr, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_host_ptr->active_async_list_tail_ptr->next = qh_ptr; usb_host_ptr->active_async_list_tail_ptr = qh_ptr; } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_unlink_qh_from_active_list * Returned Value : None * Comments : * Link the qtd to the qh for interrupt/Bulk/Control transfers. *END*-----------------------------------------------------------------*/ void _usb_ehci_unlink_qh_from_async_active_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the queue head to initialize */ ehci_qh_struct_t* qh_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* cur_qh; ehci_qh_struct_t* prev_qh; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; if (usb_host_ptr->active_async_list_ptr == qh_ptr) { //EHCI_MEM_WRITE(usb_host_ptr->dummy_qh->horiz_link_ptr, EHCI_MEM_READ((uint32_t)qh_ptr->horiz_link_ptr)); usb_hal_ehci_set_qh_horiz_link_ptr(usb_host_ptr->dummy_qh, usb_hal_ehci_get_qh_horiz_link_ptr(qh_ptr)); usb_host_ptr->active_async_list_ptr = qh_ptr->next; //_usb_ehci_update_active_async(handle); if (usb_host_ptr->active_async_list_tail_ptr == qh_ptr) { usb_host_ptr->active_async_list_ptr = NULL; usb_host_ptr->active_async_list_tail_ptr = NULL; } } else { cur_qh = prev_qh = usb_host_ptr->active_async_list_ptr; while ((cur_qh != NULL) && (cur_qh != qh_ptr)) { prev_qh = cur_qh; cur_qh = cur_qh->next; } if(cur_qh == qh_ptr) { prev_qh->next = qh_ptr->next; //EHCI_MEM_WRITE(prev_qh->horiz_link_ptr, EHCI_MEM_READ((uint32_t)qh_ptr->horiz_link_ptr)); usb_hal_ehci_set_qh_horiz_link_ptr(prev_qh, usb_hal_ehci_get_qh_horiz_link_ptr(qh_ptr)); if (usb_host_ptr->active_async_list_tail_ptr == qh_ptr) { usb_host_ptr->active_async_list_tail_ptr = prev_qh; } } } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_init_Q_HEAD * Returned Value : None * Comments : * Initialize the Queue Head. This routine initializes a queue head * for interrupt/Bulk/Control transfers. *END*-----------------------------------------------------------------*/ void _usb_ehci_init_qh ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the queue head to initialize */ ehci_qh_struct_t* qh_ptr ) { uint32_t control_ep_flag = 0, split_completion_mask = pipe_descr_ptr->complete_split; uint32_t interrupt_schedule_mask = pipe_descr_ptr->start_split; uint32_t data_toggle_control = 0; uint32_t temp; uint32_t h_bit = 0; uint8_t mult = 1; uint8_t speed; uint8_t address; uint8_t hub_no; uint8_t port_no; /****************************************************************************** PREPARE THE BASIC FIELDS OF A QUEUE HEAD DEPENDING UPON THE PIPE TYPE *******************************************************************************/ //OS_Mem_zero(qh_ptr, sizeof(ehci_qh_struct_t)); init_the_volatile_struct_to_zero(qh_ptr, sizeof(ehci_qh_struct_t)); speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); switch (pipe_descr_ptr->common.pipetype) { case USB_CONTROL_PIPE: if (speed != USB_SPEED_HIGH) { control_ep_flag = 1; } data_toggle_control = 1; /* Data toggle in qTD */ break; case USB_INTERRUPT_PIPE: data_toggle_control = 0; /* Data toggle in QH */ break; case USB_BULK_PIPE: data_toggle_control = 0; /* Data toggle in QH */ break; default: break; } if (speed == USB_SPEED_HIGH) { mult = pipe_descr_ptr->common.trs_per_uframe; } usb_hal_ehci_init_qh(qh_ptr); address = (usb_host_dev_mng_get_address(pipe_descr_ptr->common.dev_instance)) & 0x7F; if (usb_host_dev_mng_get_hub_speed(pipe_descr_ptr->common.dev_instance) != USB_SPEED_HIGH) { hub_no = (usb_host_dev_mng_get_hs_hub_no(pipe_descr_ptr->common.dev_instance)) & 0x7F; port_no = (usb_host_dev_mng_get_hs_port_no(pipe_descr_ptr->common.dev_instance)) & 0x7F; } else { hub_no = (usb_host_dev_mng_get_hubno(pipe_descr_ptr->common.dev_instance)) & 0x7F; port_no = (usb_host_dev_mng_get_portno(pipe_descr_ptr->common.dev_instance)) & 0x7F; } /* Initialize the endpoint capabilities registers */ temp = ( ((uint32_t)pipe_descr_ptr->common.nak_count << EHCI_QH_NAK_COUNT_RL_BITS_POS) | (control_ep_flag << EHCI_QH_EP_CTRL_FLAG_BIT_POS) | ((uint32_t)pipe_descr_ptr->common.max_packet_size << EHCI_QH_MAX_PKT_SIZE_BITS_POS) | (h_bit << EHCI_QH_HEAD_RECLAMATION_BIT_POS) | (data_toggle_control << EHCI_QH_DTC_BIT_POS) | ((uint32_t)(speed & 0x3) << EHCI_QH_SPEED_BITS_POS) | ((uint32_t)pipe_descr_ptr->common.endpoint_number << EHCI_QH_EP_NUM_BITS_POS) | address ); //EHCI_MEM_WRITE(qh_ptr->ep_capab_charac1, temp); usb_hal_ehci_set_ep_capab_charac1(qh_ptr, temp); temp = ( ((uint32_t)mult << EHCI_QH_HIGH_BW_MULT_BIT_POS) | ((uint32_t)port_no << EHCI_QH_HUB_PORT_NUM_BITS_POS) | ((uint32_t)hub_no << EHCI_QH_HUB_ADDR_BITS_POS) | ((uint32_t)split_completion_mask << EHCI_QH_SPLIT_COMPLETION_MASK_BITS_POS) | (uint32_t)interrupt_schedule_mask ); //EHCI_MEM_WRITE(qh_ptr->ep_capab_charac2,temp); usb_hal_ehci_set_ep_capab_charac2(qh_ptr, temp); //EHCI_MEM_WRITE(qh_ptr->next_qtd_link_ptr, EHCI_QTD_T_BIT); usb_hal_ehci_set_qh_next_qtd_link_terminate(qh_ptr); //EHCI_MEM_WRITE(qh_ptr->horiz_link_ptr, EHCI_QUEUE_HEAD_POINTER_T_BIT); usb_hal_ehci_set_qh_horiz_link_ptr_head_pointer_terminate(qh_ptr); return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_init_QTD * Returned Value : None * Comments : * Initialize the QTD *END*-----------------------------------------------------------------*/ void _usb_ehci_init_qtd ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the address of the QTD to initialize */ ehci_qtd_struct_t* qtd_ptr, /* The buffer start address for the QTD */ uint8_t* buffer_start_address, /* The token value */ uint32_t token ) { /* Zero the QTD. Leave the scratch pointer */ init_the_volatile_struct_to_zero(qtd_ptr, sizeof(ehci_qtd_struct_t)); qtd_ptr->qtd_timer = QTD_TIMEOUT_DEFAULT; /* Set the Terminate bit */ usb_hal_ehci_set_qtd_terminate_bit(qtd_ptr); /* Set the Terminate bit */ usb_hal_ehci_set_alt_next_qtd_terminate_bit(qtd_ptr); usb_hal_ehci_set_qtd_buffer_page_pointer(qtd_ptr, (uint32_t)buffer_start_address); usb_hal_ehci_set_qtd_token(qtd_ptr,token); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_init_Q_element * Returned Value : None * Comments : * Initialize the Queue Element descriptor(s) *END*-----------------------------------------------------------------*/ uint32_t _usb_ehci_init_qtd_link ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { ehci_qtd_struct_t* qtd_ptr; ehci_qtd_struct_t* prev_qtd_ptr; ehci_qtd_struct_t* first_qtd_ptr = NULL; uint32_t pid_code; uint32_t next_pidcode; uint32_t data_toggle, token; uint32_t total_length, qtd_length; unsigned char * buff_ptr; _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } data_toggle = ((uint32_t)pipe_descr_ptr->common.nextdata01 << EHCI_QTD_DATA_TOGGLE_BIT_POS); prev_qtd_ptr = first_qtd_ptr = qtd_ptr; //current_pipe_tr_struct_ptr->hw_transaction_head = qtd_ptr; if (pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE) { pid_code = EHCI_QTD_PID_SETUP; token = (((uint32_t)8 << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | pid_code | EHCI_QTD_STATUS_ACTIVE); /* Initialize a QTD for Setup phase */ _usb_ehci_init_qtd(handle, qtd_ptr, (uint8_t *)&current_pipe_tr_struct_ptr->setup_packet, token); qtd_ptr->length = 8; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; /* Get a QTD from the queue for the data phase or a status phase */ _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } /* The data phase QTD chained to the Setup QTD */ //EHCI_MEM_WRITE(prev_qtd_ptr->next_qtd_ptr, (uint32_t)qtd_ptr); usb_hal_ehci_link_qtd(prev_qtd_ptr, (uint32_t)qtd_ptr); prev_qtd_ptr->next = qtd_ptr; data_toggle = (uint32_t)(EHCI_QTD_DATA_TOGGLE); if (current_pipe_tr_struct_ptr->send_phase) { total_length = current_pipe_tr_struct_ptr->tx_length; buff_ptr = current_pipe_tr_struct_ptr->tx_buffer; pid_code = EHCI_QTD_PID_OUT; next_pidcode = EHCI_QTD_PID_IN; } else { total_length = current_pipe_tr_struct_ptr->rx_length; buff_ptr = current_pipe_tr_struct_ptr->rx_buffer; pid_code = EHCI_QTD_PID_IN; next_pidcode = EHCI_QTD_PID_OUT; } if (total_length) { token = ((uint32_t)total_length << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | pid_code | EHCI_QTD_STATUS_ACTIVE; _usb_ehci_init_qtd(handle, qtd_ptr, buff_ptr, token); qtd_ptr->length = total_length; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; /* Use the QTD to chain the next QTD */ prev_qtd_ptr = qtd_ptr; /* Get a QTD from the queue for status phase */ _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { while (first_qtd_ptr != NULL) { qtd_ptr = first_qtd_ptr; first_qtd_ptr = (ehci_qtd_struct_t*)(usb_hal_ehci_get_next_qtd_ptr(first_qtd_ptr)& USBHS_TD_ADDR_MASK); _usb_ehci_free_qtd(handle, qtd_ptr); } return USBERR_ERROR; } /* Chain the status phase QTD to the data phase QTD */ //EHCI_MEM_WRITE(prev_qtd_ptr->next_qtd_ptr,(uint32_t)qtd_ptr); usb_hal_ehci_link_qtd(prev_qtd_ptr, (uint32_t)qtd_ptr); prev_qtd_ptr->next = qtd_ptr; } /* Zero length IN */ /* Initialize the QTD for the status phase -- Zero length opposite ** direction packet */ token = ((0 << EHCI_QTD_LENGTH_BIT_POS) | (EHCI_QTD_DATA_TOGGLE) | EHCI_QTD_IOC | next_pidcode | EHCI_QTD_STATUS_ACTIVE); _usb_ehci_init_qtd(handle, qtd_ptr, NULL, token); qtd_ptr->length = 0; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; } else { if (pipe_descr_ptr->common.direction) { total_length = current_pipe_tr_struct_ptr->tx_length; buff_ptr = current_pipe_tr_struct_ptr->tx_buffer; pid_code = EHCI_QTD_PID_OUT; } else { total_length = current_pipe_tr_struct_ptr->rx_length; buff_ptr = current_pipe_tr_struct_ptr->rx_buffer; pid_code = EHCI_QTD_PID_IN; } do { if (total_length > VUSB_EP_MAX_LENGTH_TRANSFER) { /* Split OUT transaction to more shorter transactions */ token = ((VUSB_EP_MAX_LENGTH_TRANSFER << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | pid_code | EHCI_QTD_DEFAULT_CERR_VALUE | EHCI_QTD_STATUS_ACTIVE); qtd_length = VUSB_EP_MAX_LENGTH_TRANSFER; total_length -= VUSB_EP_MAX_LENGTH_TRANSFER; } else { token = ((total_length << EHCI_QTD_LENGTH_BIT_POS) | data_toggle | EHCI_QTD_IOC | pid_code | EHCI_QTD_DEFAULT_CERR_VALUE | EHCI_QTD_STATUS_ACTIVE); qtd_length = total_length; total_length = 0; } /* Initialize the QTD for the OUT data transaction */ _usb_ehci_init_qtd(handle, qtd_ptr, buff_ptr, token); qtd_ptr->length = qtd_length; qtd_ptr->pipe = (void *)pipe_descr_ptr; qtd_ptr->tr = (void *)current_pipe_tr_struct_ptr; buff_ptr += qtd_length; if (total_length) { /* Use the QTD to chain the next QTD */ prev_qtd_ptr = qtd_ptr; /* Get a QTD from the queue for status phase */ _usb_ehci_get_qtd(handle, &qtd_ptr); if (!qtd_ptr) { return USB_STATUS_TRANSFER_IN_PROGRESS; } /* Chain the status phase QTD to the data phase QTD */ //EHCI_MEM_WRITE(prev_qtd_ptr->next_qtd_ptr,(uint32_t) qtd_ptr); usb_hal_ehci_link_qtd(prev_qtd_ptr, (uint32_t)qtd_ptr); prev_qtd_ptr->next = qtd_ptr; } } while (total_length); } return ((uint32_t)first_qtd_ptr); } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_add_xfer_to_asynch_schedule_list * Returned Value : USB Status * Comments : * Queue the packet in the EHCI hardware Asynchronous schedule list *END*-----------------------------------------------------------------*/ uint32_t _usb_ehci_add_xfer_to_asynch_schedule_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr=NULL; ehci_qtd_struct_t* first_qtd_ptr; bool init_async_list = FALSE; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; #if USBCFG_HOST_COMPLIANCE_TEST if (single_step_desc_data_on) { first_qtd_ptr = (ehci_qtd_struct_t*)_usb_ehci_init_single_step_qtd_link(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); } else { first_qtd_ptr = (ehci_qtd_struct_t*)_usb_ehci_init_qtd_link(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); } #else first_qtd_ptr = (ehci_qtd_struct_t*)_usb_ehci_init_qtd_link(handle, pipe_descr_ptr, current_pipe_tr_struct_ptr); #endif current_pipe_tr_struct_ptr->transfered_length = 0; /* nothing was transferred yet */ /* If the Asynch Schedule is disabled then initialize a new list */ if (((!(usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase) & EHCI_USBCMD_ASYNC_SCHED_ENABLE)) && (!(usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_ASYNCH_SCHEDULE)) ) || (!usb_host_ptr->active_async_list_ptr)) { init_async_list = TRUE; } qh_ptr = pipe_descr_ptr->qh_for_this_pipe; if (!pipe_descr_ptr->actived) { _usb_ehci_init_qh(handle, pipe_descr_ptr, qh_ptr); qh_ptr->pipe = (void*)pipe_descr_ptr; qh_ptr->next = NULL; _usb_ehci_link_qtd_to_qh(handle, qh_ptr, first_qtd_ptr); _usb_ehci_link_qh_to_async_active_list(handle, qh_ptr); pipe_descr_ptr->actived = 1; } else { usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); while (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_ASYNCH_SCHEDULE) { } _usb_ehci_link_qtd_to_qh(handle, qh_ptr, first_qtd_ptr); /* Enable the Asynchronous schedule */ //EHCI_REG_SET_BITS(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,EHCI_USBCMD_ASYNC_SCHED_ENABLE); usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } if (init_async_list) { /* Write the QH address to the Current Async List Address */ //EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.CURR_ASYNC_LIST_ADDR, (uint32_t)usb_host_ptr->dummy_qh); usb_hal_ehci_set_qh_to_curr_async_list(usb_host_ptr->usbRegBase, (uint32_t)usb_host_ptr->dummy_qh); /* Enable the Asynchronous schedule */ //EHCI_REG_SET_BITS(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,EHCI_USBCMD_ASYNC_SCHED_ENABLE); usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_add_interrupt_xfer_to_periodic_list * Returned Value : None * Comments : * Queue the transfer in the EHCI hardware Periodic schedule list *END*-----------------------------------------------------------------*/ uint32_t _usb_ehci_add_interrupt_xfer_to_periodic_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* pipe_tr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr = NULL; ehci_qtd_struct_t* first_qtd_ptr; uint32_t cmd_val,sts_val; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* Initialize the QTDs for the Queue Head */ first_qtd_ptr = (ehci_qtd_struct_t*)_usb_ehci_init_qtd_link(handle, pipe_descr_ptr, pipe_tr_ptr); #ifdef DEBUG_INFO { uint32_t token = usb_hal_ehci_get_qtd_token(first_qtd_ptr); USB_PRINTF("QTD queued Top QTD Token=%x\n" " Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n", token (token&0xFF), (token >> 8)&0x3, (token >> 10) &0x3, (token >> 12)&0x7, (token >> 15)&0x1, (token >> 16)&0x7FFF, (token&EHCI_QTD_DATA_TOGGLE) >>31); } #endif qh_ptr = (ehci_qh_struct_t*) pipe_descr_ptr->qh_for_this_pipe; if (!pipe_descr_ptr->actived) { qh_ptr->pipe = (void*)pipe_descr_ptr; _usb_ehci_link_qtd_to_qh(handle, qh_ptr, first_qtd_ptr); //_usb_ehci_link_qh_to_active_list(handle, qh_ptr, 1); pipe_descr_ptr->actived = 1; } else { _usb_ehci_link_qtd_to_qh(handle, qh_ptr, first_qtd_ptr); } #ifdef DEBUG_INFO { uint32_t token = usb_hal_ehci_get_qtd_token(first_qtd_ptr); USB_PRINTF("_usb_ehci_add_interrupt_xfer_to_periodic_list: QH =%x\n" " Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n", token, (token&0xFF), (token >> 8)&0x3, (token >> 10) &0x3, (token >> 12)&0x7, (token >> 15)&0x1, (token>> 16)&0x7FFF, (token)&EHCI_QTD_DATA_TOGGLE) >>31); } #endif /**************************************************************************** if periodic schedule is not already enabled, enable it. ****************************************************************************/ sts_val = usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase); if(!(sts_val & EHCI_STS_PERIODIC_SCHEDULE)) { cmd_val = usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase); /**************************************************************************** write the address of the periodic list in to the periodic base register ****************************************************************************/ usb_hal_ehci_set_periodic_list_base_addr(usb_host_ptr->usbRegBase, (uint32_t) usb_host_ptr->periodic_list_base_addr); /**************************************************************************** enable the schedule now. ****************************************************************************/ if (!(cmd_val & EHCI_USBCMD_PERIODIC_SCHED_ENABLE)) { //EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,(cmd_val | EHCI_USBCMD_PERIODIC_SCHED_ENABLE)); usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, (cmd_val | EHCI_USBCMD_PERIODIC_SCHED_ENABLE)); } /**************************************************************************** wait until we can enable the periodic schedule. ****************************************************************************/ while (!(usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_PERIODIC_SCHEDULE)) { } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_port_change * Returned Value : None * Comments : * Process port change *END*-----------------------------------------------------------------*/ bool _usb_ehci_process_port_change ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; uint8_t i, total_port_numbers; uint32_t port_control, status; //USB_EHCI_HOST_INIT_STRUCT_PTR param; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; //param = (USB_EHCI_HOST_INIT_STRUCT_PTR) usb_host_ptr->INIT_PARAM; //cap_dev_ptr = (vusb20_reg_struct_t*) param->CAP_BASE_PTR; total_port_numbers = (uint8_t)(usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & EHCI_HCS_PARAMS_N_PORTS); for (i = 0; i < total_port_numbers; i++) { port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); if (port_control & EHCI_PORTSCX_CONNECT_STATUS_CHANGE) { /* Turn on the 125 usec uframe interrupt. This effectively ** starts the timer to count 125 usecs */ usb_hal_ehci_enable_interrupts(usb_host_ptr->usbRegBase, EHCI_INTR_SOF_UFRAME_EN); do { if (port_control & EHCI_PORTSCX_CONNECT_STATUS_CHANGE) { usb_host_ptr->uframe_count = 0; port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); port_control |= EHCI_PORTSCX_CONNECT_STATUS_CHANGE; usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, port_control); } /* Endif */ status = (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & usb_hal_ehci_get_interrupt_enable_status(usb_host_ptr->usbRegBase)); if (status & EHCI_STS_SOF_COUNT) { /* Increment the 125 usecs count */ usb_host_ptr->uframe_count++; usb_hal_ehci_clear_usb_interrupt_status(usb_host_ptr->usbRegBase, status); } /* Endif */ port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); } while (usb_host_ptr->uframe_count != 2); /* Turn off the 125 usec uframe interrupt. This effectively ** stops the timer to count 125 usecs */ usb_hal_ehci_disable_interrupts(usb_host_ptr->usbRegBase,EHCI_INTR_SOF_UFRAME_EN); port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); usb_host_ptr->uframe_count = 0; /* We waited to check for stable current connect status */ if (port_control & EHCI_PORTSCX_CURRENT_CONNECT_STATUS) { /* Attach on port i */ /* send change report to the hub-driver */ /* The hub driver does GetPortStatus and identifies the new connect */ /* reset and enable the port */ _usb_ehci_reset_and_enable_port(handle, i); #if USBCFG_EHCI_HS_DISCONNECT_ENABLE /*enable HS disconnect detection */ port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); if(port_control & EHCI_PORTSCX_PORT_HIGH_SPEED) { bsp_usb_hs_disconnect_detection_enable(usb_host_ptr->controller_id); } #endif } else { /* Detach on port i */ /* send change report to the hub-driver */ #if USBCFG_EHCI_HS_DISCONNECT_ENABLE /* disable HS disconnect detection */ bsp_usb_hs_disconnect_detection_disable(usb_host_ptr->controller_id); #endif /* clear the connect status change */ port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); port_control |= EHCI_PORTSCX_CONNECT_STATUS_CHANGE; usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, port_control); /* Disable the asynch and periodic schedules */ usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); usb_hal_ehci_disable_usb_cmd_periodic_sched(usb_host_ptr->usbRegBase); /* call device detach (host pointer, speed, hub #, port #) */ #if USBCFG_EHCI_HOST_ENABLE_TASK usb_host_ptr->devices_inserted = 0; OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_DETACH); #else usb_host_dev_mng_detach((void*)usb_host_ptr->upper_layer_handle, 0, (uint8_t)((i + 1))); #endif usb_hal_ehcit_gpt_timer_stop(usb_host_ptr->usbRegBase,0); /* Endif */ if (!i) { return TRUE; } /* Endif */ } /* Endif */ } /* Endif */ if (port_control & EHCI_PORTSCX_PORT_FORCE_RESUME) { port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_PORT_FORCE_RESUME); _usb_host_call_service((usb_host_handle)usb_host_ptr, USB_SERVICE_HOST_RESUME, 0); } /* Endif */ if ((usb_host_ptr->is_resetting != FALSE) && (port_control & EHCI_PORTSCX_PORT_ENABLE)) { usb_host_ptr->is_resetting = FALSE; /* reset process complete */ /* Report the change to the hub driver and enumerate */ usb_host_ptr->temp_speed = ((port_control & USBHS_SPEED_MASK) >> USBHS_SPEED_BIT_POS); //usb_host_ptr->SPEED = USB_SPEED_HIGH; usb_host_ptr->port_num = (uint32_t)(i + 1); /* Now wait for reset recovery */ usb_host_ptr->reset_recovery_timer = (USB_RESET_RECOVERY_DELAY*8); /* Turn on the 125 usec uframe interrupt. This effectively ** starts the timer to count 125 usecs */ usb_hal_ehci_enable_interrupts(usb_host_ptr->usbRegBase, EHCI_INTR_SOF_UFRAME_EN); } /* Endif */ } /* Endfor */ return FALSE; } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_reset_and_enable_port * Returned Value : None * Comments : * Reset and enabled the port *END*-----------------------------------------------------------------*/ void _usb_ehci_reset_and_enable_port ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the port number */ uint8_t port_number ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; uint32_t port_status_control; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* Check the line status bit in the PORTSC register */ port_status_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_status_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); /* reset should wait for 100 Ms debouce period before starting*/ #ifdef __USB_OTG__ if ((usb_otg_state_struct_ptr->STATE_STRUCT_PTR->STATE != A_SUSPEND) && (usb_otg_state_struct_ptr->STATE_STRUCT_PTR->STATE != B_WAIT_ACON)) #endif { uint32_t i; for (i = 0; i < USB_DEBOUNCE_DELAY; i++) { _usb_host_delay(handle, 1); //wait 1 msec /* Check the line status bit in the PORTSC register */ if (!(usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase) & EHCI_PORTSCX_CURRENT_CONNECT_STATUS)) { break; } } /* Endfor */ } usb_host_ptr->is_resetting = TRUE; /* ** Start the reset process */ usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, (port_status_control | EHCI_PORTSCX_PORT_RESET)); /* Wait for Reset complete */ do { port_status_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); } while (port_status_control & EHCI_PORTSCX_PORT_RESET); } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_host_process_reset_recovery_done * Returned Value : None * Comments : * Reset and enabled the port *END*-----------------------------------------------------------------*/ void _usb_host_process_reset_recovery_done ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* call device attach (host pointer, speed, hub #, port #) */ #if USBCFG_EHCI_HOST_ENABLE_TASK usb_host_ptr->devices_inserted = 1; if(usb_host_ptr->devices_attached == 0) { OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_DETACH); } OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ATTACH); #else usb_device_instance_handle dev_handle = NULL; usb_host_dev_mng_attach((void*)usb_host_ptr->upper_layer_handle, NULL, (uint8_t)(usb_host_ptr->temp_speed), 0, (uint8_t)(usb_host_ptr->port_num), 1, &dev_handle); #endif /* Endif */ /* Turn off the 125 usec uframe interrupt. This effectively ** stops the timer to count 125 usecs */ usb_hal_ehci_disable_interrupts(usb_host_ptr->usbRegBase, EHCI_INTR_SOF_UFRAME_EN); usb_hal_ehcit_gpt_timer_run(usb_host_ptr->usbRegBase, 0); } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_isr * Returned Value : None * Comments : * Service all the interrupts in the VUSB1.1 hardware *END*-----------------------------------------------------------------*/ void _usb_ehci_isr ( /* [IN] the USB Host state structure */ void ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; uint32_t status; usb_host_ptr = (usb_ehci_host_state_struct_t*)(g_usb_host[0].controller_handle); /* We use a while loop to process all the interrupts while we are in the ** loop so that we don't miss any interrupts */ while (TRUE) { /* Check if any of the enabled interrupts are asserted */ status = (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & usb_hal_ehci_get_interrupt_enable_status(usb_host_ptr->usbRegBase)); if (!status) { #if USBCFG_EHCI_PIN_DETECT_ENABLE /* will check otgsc id change interrupt */ status = (((usb_hal_ehci_get_otg_status(usb_host_ptr->usbRegBase)& USBHS_OTGSC_IDIE_MASK) >> USBHS_OTGSC_IDIE_SHIFT)) && (((usb_hal_ehci_get_otg_status(usb_host_ptr->usbRegBase)& USBHS_OTGSC_IDIS_MASK) >> USBHS_OTGSC_IDIS_SHIFT)); if (status) { usb_hal_ehci_clear_otg_interrupts(usb_host_ptr->usbRegBase, USBHS_OTGSC_IDIS_MASK); #if USBCFG_EHCI_HOST_ENABLE_TASK OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE); #else /* will wait for device detached if the device is attached */ if (usb_host_ptr->devices_attached) return; if( host_pin_detect_service[usb_host_ptr->controller_id - USB_CONTROLLER_EHCI_0] != NULL) host_pin_detect_service[usb_host_ptr->controller_id - USB_CONTROLLER_EHCI_0](USB_HOST_ID_CHANGE); #endif return; } #endif break; } /* Endif */ /* Clear all enabled interrupts */ usb_hal_ehci_clear_usb_interrupt_status(usb_host_ptr->usbRegBase, status); if (status & EHCI_STS_SOF_COUNT) { /* Waiting for an interval of 10 ms for reset recovery */ if (usb_host_ptr->reset_recovery_timer) { usb_host_ptr->reset_recovery_timer--; if (!usb_host_ptr->reset_recovery_timer) { _usb_host_process_reset_recovery_done((usb_host_handle)usb_host_ptr); } /* Endif */ } /* Endif */ } /* Endif */ if (status & EHCI_STS_ASYNCH_ADVANCE) { /* Process the asynch advance */ } /* Endif */ if (status & EHCI_STS_HOST_SYS_ERROR) { /* Host system error. Controller halted. Inform the upper layers */ #if USBCFG_EHCI_HOST_ENABLE_TASK OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_SYS_ERROR); #else _usb_host_call_service((usb_host_handle)usb_host_ptr, USB_SERVICE_SYSTEM_ERROR, 0); #endif } /* Endif */ if (status & EHCI_STS_FRAME_LIST_ROLLOVER) { /* Process frame list rollover */ } /* Endif */ if (status & EHCI_STS_RECLAIMATION) { /* Process reclamation */ } /* Endif */ if (status & EHCI_STS_NAK) { #if USBCFG_EHCI_HOST_ENABLE_TASK OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE); #else _usb_ehci_process_tr_complete((usb_host_handle)usb_host_ptr); #endif } if (status & (EHCI_STS_USB_INTERRUPT | EHCI_STS_USB_ERROR)) { /* Process the USB transaction completion and transaction error ** interrupt */ #if USBCFG_EHCI_HOST_ENABLE_TASK OS_Event_set(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE); #else _usb_ehci_process_tr_complete((usb_host_handle)usb_host_ptr); #endif #ifdef DEBUG_INFO USB_PRINTF("TR completed\n"); #endif } /* Endif */ if (status & EHCI_STS_TIMER0) { _usb_ehci_process_timer((usb_host_handle)usb_host_ptr); } if (status & EHCI_STS_PORT_CHANGE) { /* Process the port change detect */ if (_usb_ehci_process_port_change((usb_host_handle)usb_host_ptr)) { /* There was a detach on port 0 so we should return */ return; } /* Endif */ /* Should return if there was a detach on OTG port */ } /* Endif */ } /* EndWhile */ } /* Endbody */ #if USBCFG_EHCI_HOST_ENABLE_TASK static void _usb_ehci_host_task(void* handle) { static usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; if (usb_host_ptr->devices_attached) { #if (USB_NONBLOCKING_MODE == 0) #if USBCFG_EHCI_PIN_DETECT_ENABLE OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE|EHCI_EVENT_TOK_DONE|EHCI_EVENT_SYS_ERROR|EHCI_EVENT_DETACH, FALSE,5); #else OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE|EHCI_EVENT_SYS_ERROR|EHCI_EVENT_DETACH, FALSE,5); #endif #else //OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE|EHCI_EVENT_SYS_ERROR|EHCI_EVENT_DETACH, FALSE,0); #endif if ((OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_DETACH))) { OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_DETACH); usb_host_dev_mng_detach((void*)usb_host_ptr->upper_layer_handle, 0, (uint8_t)(1)); usb_host_ptr->devices_attached = 0; OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, 0xFE); return; } if ((OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_SYS_ERROR))) { OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_SYS_ERROR); _usb_host_call_service((usb_host_handle)usb_host_ptr, USB_SERVICE_SYSTEM_ERROR, 0); } if ((OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE))) { OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_TOK_DONE); _usb_ehci_process_tr_complete((usb_host_handle)usb_host_ptr); } } else { #if (USB_NONBLOCKING_MODE == 0) #if USBCFG_EHCI_PIN_DETECT_ENABLE OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE|EHCI_EVENT_ATTACH, FALSE,5); #else OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ATTACH, FALSE,5); #endif #else //OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ATTACH, FALSE,0); #endif if ((OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ATTACH))) { OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ATTACH); if(usb_host_ptr->devices_inserted) { usb_device_instance_handle dev_handle = NULL; usb_host_dev_mng_attach((void*)usb_host_ptr->upper_layer_handle, NULL, (uint8_t)(usb_host_ptr->temp_speed), 0, (uint8_t)(usb_host_ptr->port_num), 1, &dev_handle); if(NULL != dev_handle) { usb_host_ptr->devices_attached = 0x01; } } } } #if USBCFG_EHCI_PIN_DETECT_ENABLE #if 0 #if (USB_NONBLOCKING_MODE == 0) OS_Event_wait(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE, FALSE,5); #else #endif #endif if ((OS_Event_check_bit(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE)) && (!usb_host_ptr->devices_attached)) { OS_Time_delay(50); OS_Event_clear(usb_host_ptr->ehci_event_ptr, EHCI_EVENT_ID_CHANGE); if( host_pin_detect_service[usb_host_ptr->controller_id - USB_CONTROLLER_EHCI_0] != NULL) { host_pin_detect_service[usb_host_ptr->controller_id - USB_CONTROLLER_EHCI_0](USB_HOST_ID_CHANGE); } } #endif } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_task_stun * Returned Value : none * Comments : * KHCI task *END*-----------------------------------------------------------------*/ #if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (USE_RTOS)) static void _usb_ehci_host_task_stun(void* handle) { while (1) { _usb_ehci_host_task(handle); } } #endif /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_task_create * Returned Value : error or USB_OK * Comments : * Create KHCI task *END*-----------------------------------------------------------------*/ uint32_t ehci_host_task_id; static usb_status _usb_ehci_host_task_create(usb_host_handle handle) { //usb_status status; //ehci_host_task_id = _task_create_blocked(0, 0, (uint32_t)&task_template); ehci_host_task_id = OS_Task_create(USB_EHCI_HOST_TASK_ADDRESS, (void*)handle, (uint32_t)USBCFG_HOST_EHCI_TASK_PRIORITY, USB_EHCI_HOST_TASK_STACKSIZE, USB_EHCI_HOST_TASK_NAME, NULL); if (ehci_host_task_id == (uint32_t)OS_TASK_ERROR) { return USBERR_ERROR; } return USB_OK; } #endif /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_preinit * Returned Value : error or USB_OK * Comments : * Allocate the structures for EHCI *END*-----------------------------------------------------------------*/ usb_status usb_ehci_preinit(usb_host_handle upper_layer_handle, usb_host_handle *handle) { usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*) OS_Mem_alloc_zero(sizeof(usb_ehci_host_state_struct_t)); ehci_pipe_struct_t* p; ehci_pipe_struct_t* pp; int i; if (NULL != usb_host_ptr) { /* Allocate the USB Host Pipe Descriptors */ usb_host_ptr->pipe_descriptor_base_ptr = (pipe_struct_t*)OS_Mem_alloc_zero(sizeof(ehci_pipe_struct_t) * USBCFG_HOST_MAX_PIPES); if (usb_host_ptr->pipe_descriptor_base_ptr == NULL) { OS_Mem_free(usb_host_ptr); return USBERR_ALLOC; } OS_Mem_zero(usb_host_ptr->pipe_descriptor_base_ptr, sizeof(ehci_pipe_struct_t) * USBCFG_HOST_MAX_PIPES); p = (ehci_pipe_struct_t*) usb_host_ptr->pipe_descriptor_base_ptr; pp = NULL; for (i = 0; i < USBCFG_HOST_MAX_PIPES; i++) { if (pp != NULL) { pp->common.next = (pipe_struct_t*) p; } pp = p; p++; } //usb_host_ptr->PIPE_SIZE = sizeof(ehci_pipe_struct_t); //usb_host_ptr->TR_SIZE = sizeof(EHCI_TR_STRUCT); usb_host_ptr->upper_layer_handle = upper_layer_handle; *handle = (usb_host_handle) usb_host_ptr; } /* Endif */ else { *handle = NULL; return USBERR_ALLOC; } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_init * Returned Value : error or USB_OK * Comments : * Initialize the VUSB_HS controller *END*-----------------------------------------------------------------*/ usb_status usb_ehci_init(uint8_t controller_id, usb_host_handle handle) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; //USB_EHCI_HOST_INIT_STRUCT_PTR param; ehci_qh_struct_t* qh_ptr; ehci_qtd_struct_t* qtd_ptr; uint8_t vector; uint32_t i, frame_list_size_bits; #ifndef __USB_OTG__ uint32_t port_control[16]; uint8_t portn = 0; #endif uint32_t total_xtd_struct_memory = 0; uint32_t endian; uint32_t temp = 0; endian = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; //param = (USB_EHCI_HOST_INIT_STRUCT_PTR) usb_host_ptr->INIT_PARAM; //if (param == NULL) // return USBERR_INIT_DATA; /* Get the base address of the VUSB_HS registers */ usb_host_ptr->usbRegBase = soc_get_usb_base_address(controller_id); usb_host_ptr->controller_id = controller_id; usb_host_ptr->devices_inserted = 0; usb_host_ptr->devices_attached = 0; usb_host_ptr->mutex = OS_Mutex_create(); if (usb_host_ptr->mutex == NULL) { USB_PRINTF("ehci host create mutex failed\n"); return USBERR_ALLOC; } #if USBCFG_EHCI_HOST_ENABLE_TASK usb_host_ptr->ehci_event_ptr = OS_Event_create(0); if (usb_host_ptr->ehci_event_ptr == NULL) { USB_PRINTF(" Event create failed in usb_ehci_init\n"); return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } /* Endif */ _usb_ehci_host_task_create(usb_host_ptr); #endif usb_host_ehci_phy_init(controller_id); temp = usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase); temp |= USBHS_USBCMD_RST_MASK; usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, temp); while (usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase) & USBHS_USBCMD_RST_MASK) { /* delay while resetting USB controller */ } usb_hal_ehci_set_usb_mode(usb_host_ptr->usbRegBase, USBHS_USBMODE_CM_HOST_MASK); temp = USBHS_USBCMD_ASP(3) | USBHS_USBCMD_ITC(0); usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, temp); /* setup interrupt */ OS_intr_init((IRQn_Type)soc_get_usb_vector_number(controller_id), soc_get_usb_host_int_level(controller_id), 0, TRUE); /* Stop the controller */ usb_hal_ehci_initiate_detach_event(usb_host_ptr->usbRegBase); /* Configure the VUSBHS has a host controller */ usb_hal_ehci_set_usb_mode(usb_host_ptr->usbRegBase,USBHS_MODE_CTRL_MODE_HOST); usb_hal_ehci_set_usb_mode(usb_host_ptr->usbRegBase,USBHS_MODE_CTRL_MODE_HOST | endian); /* Stop the controller */ usb_hal_ehci_initiate_detach_event(usb_host_ptr->usbRegBase); /* Get the interrupt vector number for the VUSB_HS host */ vector = soc_get_usb_vector_number(controller_id); portn = usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & 0x0000000f; for (i = 0; i < portn; i++) { port_control[i] = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); } #ifndef __USB_OTG__ OS_install_isr(vector, _usb_ehci_isr, (void *)usb_host_ptr); #endif /* __USB_OTG__ */ while (!(usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_HC_HALTED)) { /* Wait for the controller to stop */ } /* Reset the controller to get default values */ usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, EHCI_CMD_CTRL_RESET); while (usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase) & EHCI_CMD_CTRL_RESET) { /* Wait for the controller reset to complete */ } /* EndWhile */ /* Configure the VUSBHS has a host controller */ usb_hal_ehci_set_usb_mode(usb_host_ptr->usbRegBase,USBHS_MODE_CTRL_MODE_HOST | endian); //EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.CTRLDSSEGMENT,0); /******************************************************************* Set the size of frame list in CMD register *******************************************************************/ if (USBCFG_EHCI_FRAME_LIST_SIZE > 512) { usb_host_ptr->frame_list_size = 1024; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_1024; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 256) { usb_host_ptr->frame_list_size = 512; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_512; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 128) { usb_host_ptr->frame_list_size = 256; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_256; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 64) { usb_host_ptr->frame_list_size = 128; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_128; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 32) { usb_host_ptr->frame_list_size = 64; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_64; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 16) { usb_host_ptr->frame_list_size = 32; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_32; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 8) { usb_host_ptr->frame_list_size = 16; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_16; } else if (USBCFG_EHCI_FRAME_LIST_SIZE > 0) { usb_host_ptr->frame_list_size = 8; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_8; } else { usb_host_ptr->frame_list_size = 1024; frame_list_size_bits = EHCI_CMD_FRAME_SIZE_1024; } if ((!(usb_hal_ehci_get_hccparams(usb_host_ptr->usbRegBase) & EHCI_HCC_PARAMS_PGM_FRM_LIST_FLAG)) && (frame_list_size_bits != EHCI_CMD_FRAME_SIZE_1024)) { /* Cannot shrink frame list size because it is unsupported by silicon vendor */ return USB_log_error(__FILE__,__LINE__,USBERR_INIT_FAILED); } /* ** ALL CONTROLLER DRIVER MEMORY NEEDS are allocated here. */ total_xtd_struct_memory += (USBCFG_EHCI_MAX_QH_DESCRS * sizeof(ehci_qh_struct_t))+32; total_xtd_struct_memory += (USBCFG_EHCI_MAX_QTD_DESCRS * sizeof(ehci_qtd_struct_t)); #if USBCFG_EHCI_MAX_ITD_DESCRS /*memory required by high-speed Iso transfers */ total_xtd_struct_memory += (USBCFG_EHCI_MAX_ITD_DESCRS * sizeof(ehci_itd_struct_t)); #endif #if USBCFG_EHCI_MAX_SITD_DESCRS /*memory required by full-speed Iso transfers */ total_xtd_struct_memory += (USBCFG_EHCI_MAX_SITD_DESCRS * sizeof(ehci_sitd_struct_t)); #endif usb_host_ptr->xtd_struct_base_addr = (void*)OS_Mem_alloc_uncached(total_xtd_struct_memory); if (!usb_host_ptr->xtd_struct_base_addr) { return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } OS_Mem_zero(usb_host_ptr->xtd_struct_base_addr, total_xtd_struct_memory); /* allocate space for frame list aligned at 4kB boundary */ usb_host_ptr->periodic_list_base_addr = (void*)usbhs_perodic_list; if (!usb_host_ptr->periodic_list_base_addr) { OS_Mem_free(usb_host_ptr->xtd_struct_base_addr); return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } /* memzero the whole memory */ OS_Mem_zero(usb_host_ptr->periodic_list_base_addr, sizeof(usbhs_perodic_list)); /* ** NON-PERIODIC MEMORY DISTRIBUTION STUFF */ usb_host_ptr->async_list_base_addr = usb_host_ptr->qh_base_ptr = (ehci_qh_struct_t*)USB_MEM64_ALIGN((uint32_t)usb_host_ptr->xtd_struct_base_addr); usb_host_ptr->qtd_base_ptr = (ehci_qtd_struct_t*)((uint32_t)usb_host_ptr->qh_base_ptr + (USBCFG_EHCI_MAX_QH_DESCRS * sizeof(ehci_qh_struct_t))); /* the first qh is used as dummy qh which is assigned to host's CURR_ASYNC_LIST_ADDR */ qh_ptr = usb_host_ptr->qh_base_ptr; usb_hal_ehci_set_qh_horiz_link_ptr(qh_ptr, (((uint32_t)qh_ptr & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); temp = usb_hal_ehci_get_ep_capab_charac1(qh_ptr); temp |= (1 << (EHCI_QH_HEAD_RECLAMATION_BIT_POS)); usb_hal_ehci_set_ep_capab_charac1(qh_ptr, temp); usb_hal_ehci_set_qh_next_alt_qtd_link_terminate(qh_ptr); usb_hal_ehci_set_qh_next_qtd_link_terminate(qh_ptr); usb_host_ptr->dummy_qh = qh_ptr; qh_ptr++; for (i = 1; i < USBCFG_EHCI_MAX_QH_DESCRS; i++) { /* Set the dTD to be invalid */ usb_hal_ehci_set_qh_horiz_link_ptr_head_pointer_terminate(qh_ptr); _usb_ehci_free_qh((usb_host_handle)usb_host_ptr, qh_ptr); qh_ptr++; } /* Endfor */ qtd_ptr = usb_host_ptr->qtd_base_ptr; /* Enqueue all the QTDs */ for (i = 0; i < USBCFG_EHCI_MAX_QTD_DESCRS; i++) { _usb_ehci_free_qtd((usb_host_handle)usb_host_ptr, qtd_ptr); qtd_ptr++; } /* Endfor */ /* ** BANDWIDTH MEMORY DISTRIBUTION STUFF */ /********************************************************************* Allocating the memory to store periodic bandwidth. A periodic BW list is a two dimensional array with dimension (frame list size x 8 u frames). Also note that the following could be a large allocation of memory The max value stored in a location will be 125 micro seconds and so we use uint8_t *********************************************************************/ #if EHCI_BANDWIDTH_RECORD_ENABLE usb_host_ptr->periodic_frame_list_bw_ptr = (void*)OS_Mem_alloc_uncached(usb_host_ptr->frame_list_size * 8 * sizeof(uint8_t)); if (!usb_host_ptr->periodic_frame_list_bw_ptr) { OS_Mem_free(usb_host_ptr->xtd_struct_base_addr); return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } OS_Mem_zero(usb_host_ptr->periodic_frame_list_bw_ptr, usb_host_ptr->frame_list_size * 8 * sizeof(uint8_t)); #endif /*make sure that periodic list is uninitialized */ usb_host_ptr->periodic_list_initialized = FALSE; /* Initialize the list of active structures to NULL initially */ usb_host_ptr->active_async_list_ptr = NULL; usb_host_ptr->active_interrupt_periodic_list_ptr = NULL; #if USBCFG_EHCI_MAX_ITD_DESCRS /* ** HIGH SPEED ISO TRANSFERS MEMORY ALLOCATION STUFF */ usb_host_ptr->itd_base_ptr = (ehci_itd_struct_t*)((uint32_t)usb_host_ptr->qtd_base_ptr + (USBCFG_EHCI_MAX_QTD_DESCRS * sizeof(ehci_qtd_struct_t))); usb_host_ptr->itd_list_initialized = FALSE; /***************************************************************************** ITD QUEUING PREPARATION *****************************************************************************/ /* memory for doubly link list of nodes that keep active ITDs. Head and Tail point to same place when list is empty */ usb_host_ptr->active_iso_itd_periodic_list_head_ptr = (list_node_struct_t*)OS_Mem_alloc_uncached(sizeof(list_node_struct_t) * USBCFG_EHCI_MAX_ITD_DESCRS); usb_host_ptr->active_iso_itd_periodic_list_tail_ptr = usb_host_ptr->active_iso_itd_periodic_list_head_ptr; if (!usb_host_ptr->active_iso_itd_periodic_list_head_ptr) { OS_Mem_free(usb_host_ptr->xtd_struct_base_addr); #if EHCI_BANDWIDTH_RECORD_ENABLE OS_Mem_free(usb_host_ptr->periodic_frame_list_bw_ptr); #endif return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } OS_Mem_zero(usb_host_ptr->active_iso_itd_periodic_list_head_ptr, sizeof(list_node_struct_t) * USBCFG_EHCI_MAX_ITD_DESCRS); #endif #if USBCFG_EHCI_MAX_SITD_DESCRS /* ** FULL SPEED ISO TRANSFERS MEMORY ALLOCATION STUFF */ /* Allocate the Split-transactions Isochronous Transfer Descriptors: ** 32 bytes aligned */ #if USBCFG_EHCI_MAX_ITD_DESCRS usb_host_ptr->sitd_base_ptr = (ehci_sitd_struct_t*)((uint32_t)usb_host_ptr->itd_base_ptr + (USBCFG_EHCI_MAX_ITD_DESCRS * sizeof(ehci_itd_struct_t))); #else usb_host_ptr->sitd_base_ptr = (ehci_sitd_struct_t*)((uint32_t)usb_host_ptr->qtd_base_ptr + (USBCFG_EHCI_MAX_QTD_DESCRS * sizeof(ehci_qtd_struct_t))); #endif usb_host_ptr->sitd_list_initialized = FALSE; /***************************************************************************** SITD QUEUING PREPARATION *****************************************************************************/ /* memory for doubly link list of nodes that keep active SITDs. Head and Tail point to same place when list is empty */ usb_host_ptr->active_iso_sitd_periodic_list_head_ptr = (list_node_struct_t*)OS_Mem_alloc_uncached(sizeof(list_node_struct_t) * USBCFG_EHCI_MAX_SITD_DESCRS); usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr = usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; if (!usb_host_ptr->active_iso_sitd_periodic_list_head_ptr) { OS_Mem_free(usb_host_ptr->xtd_struct_base_addr); #if EHCI_BANDWIDTH_RECORD_ENABLE OS_Mem_free(usb_host_ptr->periodic_frame_list_bw_ptr); #endif OS_Mem_free(usb_host_ptr->active_iso_itd_periodic_list_head_ptr); return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } OS_Mem_zero(usb_host_ptr->active_iso_sitd_periodic_list_head_ptr, sizeof(list_node_struct_t) * USBCFG_EHCI_MAX_SITD_DESCRS); #endif /* ** HARDWARE REGISTERS INITIALIZATION STUFF */ #if 0 /* 4-Gigabyte segment where all of the interface data structures are allocated. */ /* If no 64-bit addressing capability then this is zero */ if ((usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & EHCI_HCC_PARAMS_64_BIT_ADDR_CAP)) { EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.CTRLDSSEGMENT,0); } else { EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.CTRLDSSEGMENT,EHCI_DATA_STRUCTURE_BASE_ADDRESS); } /* Endif */ #endif #ifndef __USB_OTG__ if (usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & USBHS_HCS_PARAMS_PORT_POWER_CONTROL_FLAG) { for (i = 0; i < portn; i++) { port_control[i] &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); //Do not accidentally clear w1c bits by writing 1 back usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, port_control[i] | EHCI_PORTSCX_PORT_POWER); #if 0 if (usb_host_ptr->SPEED == USB_SPEED_FULL) { EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.PORTSCX[i],port_control[i] | EHCI_PORTSCX_PORT_POWER | VUSBHS_PORTSCX_PORT_PFSC); } else { //usb_host_ptr->SPEED == USB_SPEED_HIGH EHCI_REG_WRITE(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.PORTSCX[i],port_control[i] | EHCI_PORTSCX_PORT_POWER); } #endif } } /* Endif */ #endif /* start the controller, setup the frame list size */ usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, (EHCI_INTR_NO_THRESHOLD_IMMEDIATE | frame_list_size_bits | EHCI_CMD_RUN_STOP)); /* route all ports to the EHCI controller */ usb_hal_ehci_set_usb_config(usb_host_ptr->usbRegBase, 1); usb_hal_ehci_enable_interrupts(usb_host_ptr->usbRegBase, USBHS_HOST_INTR_EN_BITS); #if USBCFG_EHCI_PIN_DETECT_ENABLE usb_hal_ehci_disable_otg_interrupts(usb_host_ptr->usbRegBase, 0xff000000); usb_hal_ehci_enable_otg_interrupts(usb_host_ptr->usbRegBase, USBHS_OTGSC_IDIE_MASK); #endif usb_hal_ehci_set_gpt_timer(usb_host_ptr->usbRegBase, 0, 100); return USB_OK; } /* EndBody */ void init_the_volatile_struct_to_zero(void* struct_ptr, uint32_t size) { volatile uint32_t* temp_ptr; temp_ptr = (uint32_t*)struct_ptr; size = size/4; while(size-- > 0) { *(temp_ptr++) = 0; } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_get_QTD * Returned Value : void * Comments : * Get an QTD from the free QTD ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_get_qtd ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the QTD to enqueue */ ehci_qtd_struct_t** qtd_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qtd_struct_t* qtd; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); if (usb_host_ptr->qtd_entries == 0) { #if _DEBUG USB_PRINTF("no qtd available\n"); #endif USB_EHCI_Host_unlock(); *qtd_ptr = NULL; return ; } EHCI_QTD_QGET(usb_host_ptr->qtd_head, usb_host_ptr->qtd_tail, qtd) if (!qtd) { #if _DEBUG USB_PRINTF("get qtd error\n"); #endif USB_EHCI_Host_unlock(); *qtd_ptr = NULL; return; } usb_hal_ehci_set_qtd_terminate_bit(qtd); *qtd_ptr = qtd; usb_host_ptr->qtd_entries--; USB_EHCI_Host_unlock(); return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_QTD * Returned Value : void * Comments : * Enqueues an QTD onto the free QTD ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_free_qtd ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the QTD to enqueue */ ehci_qtd_struct_t* qtd ) { usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); usb_hal_ehci_set_qtd_terminate_bit(qtd); EHCI_QTD_QADD(usb_host_ptr->qtd_head, usb_host_ptr->qtd_tail, qtd); usb_host_ptr->qtd_entries++; USB_EHCI_Host_unlock(); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_get_qh * Returned Value : void * Comments : * Get an QTD from the free qh ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_get_qh ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the QTD to enqueue */ ehci_qh_struct_t** qh_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); if (usb_host_ptr->qh_entries == 0) { #if _DEBUG USB_PRINTF("no qh available\n"); #endif USB_EHCI_Host_unlock(); *qh_ptr = NULL; return ; } EHCI_QH_QGET(usb_host_ptr->qh_head, usb_host_ptr->qh_tail, qh) if (!qh) { #if _DEBUG USB_PRINTF("get qh error\n"); #endif USB_EHCI_Host_unlock(); return; } *qh_ptr = qh; usb_host_ptr->qh_entries--; USB_EHCI_Host_unlock(); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_QH * Returned Value : void * Comments : * Enqueues a QH onto the free QH ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_free_qh ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the QH to enqueue */ ehci_qh_struct_t* qh ) { usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); /* ** Add the QH to the free QH queue and increment the tail to the next descriptor */ EHCI_QH_QADD(usb_host_ptr->qh_head, usb_host_ptr->qh_tail, qh); usb_host_ptr->qh_entries++; // USB_PRINTF("\nQH Add 0x%x, #entries=%d",qh_ptr,usb_host_ptr->qh_entries); USB_EHCI_Host_unlock(); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_resources * Returned Value : none * Comments : * Frees the controller specific resources for a given pipe *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_free_resources ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr; ehci_qh_struct_t* temp_qh_ptr = NULL; ehci_pipe_struct_t* pipe_descr_ptr = (ehci_pipe_struct_t*) pipe_ptr; uint32_t need_enable_async_list = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; qh_ptr = pipe_descr_ptr->qh_for_this_pipe; if ((pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE) || (pipe_descr_ptr->common.pipetype == USB_BULK_PIPE)) { USB_EHCI_Host_lock(); temp_qh_ptr = (ehci_qh_struct_t*)usb_hal_ehci_get_curr_async_list(usb_host_ptr->usbRegBase); if(qh_ptr == temp_qh_ptr) { temp_qh_ptr = (ehci_qh_struct_t*)((uint32_t)temp_qh_ptr->horiz_link_ptr & EHCI_HORIZ_PHY_ADDRESS_MASK); if(qh_ptr == temp_qh_ptr) { temp_qh_ptr = usb_host_ptr->dummy_qh; } usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); while (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_ASYNCH_SCHEDULE) { } /* Write the QH address to the Current Async List Address */ usb_hal_ehci_set_qh_to_curr_async_list(usb_host_ptr->usbRegBase, (uint32_t)temp_qh_ptr); need_enable_async_list = 1; } _usb_ehci_unlink_qh_from_async_active_list(handle, qh_ptr); _usb_ehci_free_qh(handle, qh_ptr); if (usb_host_ptr->active_async_list_ptr == NULL) { /* If the head is the only one in the queue, disable asynchronous queue */ usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } else if(need_enable_async_list > 0) { /* Enable the Asynchronous schedule */ usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } USB_EHCI_Host_unlock(); } else if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { _usb_ehci_close_interrupt_pipe(handle, pipe_descr_ptr); } else if(pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) { _usb_ehci_close_isochronous_pipe(handle,pipe_descr_ptr); } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_tr_complete * Returned Value : None * Comments : * Process the Transaction Done interrupt on the EHCI hardware. Note that this * routine should be improved later. It is needless to search all the lists * since interrupt will belong to only one of them at one time. * *END*-----------------------------------------------------------------*/ void _usb_ehci_process_tr_complete ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* active_list_member_ptr; //qh_link_node_t* active_async_list; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /*************************************************************************** SEARCH THE NON PERIODIC LIST FIRST ***************************************************************************/ /*************************************************************************** SEARCH THE HIGH SPEED ISOCHRONOUS LIST ***************************************************************************/ if(usb_host_ptr->high_speed_iso_queue_active) { #if USBCFG_EHCI_MAX_ITD_DESCRS _usb_ehci_process_itd_tr_complete(handle); #endif //USBCFG_EHCI_MAX_ITD_DESCRS } /*************************************************************************** SEARCH THE FULL SPEED ISOCHRONOUS LIST ***************************************************************************/ if(usb_host_ptr->full_speed_iso_queue_active) { #if USBCFG_EHCI_MAX_SITD_DESCRS _usb_ehci_process_sitd_tr_complete(handle); #endif //USBCFG_EHCI_MAX_SITD_DESCRS } /* Get the head of the active queue head */ //active_async_list = usb_host_ptr->active_async_list;//active_async_list_ptr; if(usb_host_ptr->active_async_list_ptr) { _usb_ehci_process_qh_list_tr_complete(handle, usb_host_ptr->active_async_list_ptr); } /*************************************************************************** SEARCH THE INTERRUPT LIST ***************************************************************************/ /* Get the head of the active structures for periodic list*/ active_list_member_ptr = usb_host_ptr->active_interrupt_periodic_list_ptr; if(active_list_member_ptr) { _usb_ehci_process_qh_interrupt_tr_complete(handle, active_list_member_ptr); } } /* Endbody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_qh_list_tr_complete * Returned Value : None * Comments : * Search the asynchronous or interrupt list to see which QTD had finished and * Process the interrupt. * *END*-----------------------------------------------------------------*/ void _usb_ehci_process_qh_list_tr_complete ( /* [IN] the USB Host state structure */ usb_host_handle handle, ehci_qh_struct_t* active_qh_node_list ) { ehci_qh_struct_t* qh_ptr; ehci_qtd_struct_t* qtd_ptr; ehci_qtd_struct_t* temp_qtd_ptr; ehci_pipe_struct_t* pipe_descr_ptr = NULL; tr_struct_t* pipe_tr_struct_ptr = NULL; uint32_t req_bytes = 0; uint32_t remaining_bytes = 0; uint32_t status = 0, qtd_timeout; uint8_t* buffer_ptr = NULL; /* Check all transfer descriptors on all active queue heads */ do { /* Get the queue head from the active list */ qh_ptr = active_qh_node_list; /* Get the first QTD for this Queue head */ qtd_ptr = active_qh_node_list->qtd_head; if (!(qtd_ptr->qtd_timer)) { qtd_timeout = 1; } else { qtd_timeout = 0; } pipe_descr_ptr = (ehci_pipe_struct_t*)active_qh_node_list->pipe; active_qh_node_list = active_qh_node_list->next; while ((!(((uint32_t)qtd_ptr) & EHCI_QTD_T_BIT)) && (qtd_ptr != NULL)) { /* This is a valid qTD */ if ((!(usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_ACTIVE)) || qtd_timeout) { qtd_ptr->qtd_timer = 0; #if 0 uint32_t token = usb_hal_ehci_get_qtd_token(g_usb_instance_echi.instance,QTD_ptr); USB_PRINTF("QTD done Token=%x\n" " Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n", token, ((token)&0xFF), ((token) >> 8)&0x3, ((token) >> 10) &0x3, ((token) >> 12)&0x7, ((token) >> 15)&0x1, ((token) >> 16)&0x7FFF, ((token)&EHCI_QTD_DATA_TOGGLE) >>31); #endif /* Get the pipe descriptor for this transfer */ pipe_tr_struct_ptr = (tr_struct_t*)qtd_ptr->tr; if (pipe_tr_struct_ptr == NULL) { #if _DEBUG USB_PRINTF("can't find tr by qtd\n"); #endif return; } pipe_tr_struct_ptr->status = 0; /* Check for errors */ if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_ERROR_BITS_MASK) { pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_ERROR_BITS_MASK); usb_hal_ehci_clear_qtd_token_bits(qtd_ptr, EHCI_QTD_ERROR_BITS_MASK); } /* Check if STALL or endpoint halted because of errors */ if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_HALTED) { /* save error count */ pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_CERR_BITS_MASK); pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_HALTED); usb_hal_ehci_clear_qtd_token_bits(qtd_ptr, EHCI_QTD_STATUS_HALTED); //qh_ptr->status = 0; usb_hal_ehci_clear_qh_status(qh_ptr); } if (pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE) { if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_PID_SETUP) { pipe_tr_struct_ptr->setup_first_phase = TRUE; req_bytes = remaining_bytes = 0; } else if (pipe_tr_struct_ptr->setup_first_phase) { pipe_tr_struct_ptr->setup_first_phase = FALSE; if (pipe_tr_struct_ptr->send_phase) { buffer_ptr = pipe_tr_struct_ptr->tx_buffer; req_bytes = pipe_tr_struct_ptr->tx_length; //pipe_tr_struct_ptr->send_phase = FALSE; } else { buffer_ptr = pipe_tr_struct_ptr->rx_buffer; req_bytes = pipe_tr_struct_ptr->rx_length; } remaining_bytes = ((usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_LENGTH_BIT_MASK) >> EHCI_QTD_LENGTH_BIT_POS); } else { //handshake phase, do nothing and setup that we have not received any data in this phase req_bytes = remaining_bytes = 0; } } else { remaining_bytes = ((usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_LENGTH_BIT_MASK) >> EHCI_QTD_LENGTH_BIT_POS); req_bytes = 0; if (pipe_descr_ptr->common.direction) { buffer_ptr = pipe_tr_struct_ptr->tx_buffer; if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC) { if(pipe_tr_struct_ptr->tx_length>0) { req_bytes = ((pipe_tr_struct_ptr->tx_length-1) % VUSB_EP_MAX_LENGTH_TRANSFER) + 1; } } else { req_bytes = VUSB_EP_MAX_LENGTH_TRANSFER; } } else { buffer_ptr = pipe_tr_struct_ptr->rx_buffer; if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC) { if(pipe_tr_struct_ptr->rx_length>0) { req_bytes = ((pipe_tr_struct_ptr->rx_length-1) % VUSB_EP_MAX_LENGTH_TRANSFER) + 1; } } else { req_bytes = VUSB_EP_MAX_LENGTH_TRANSFER; } } } pipe_tr_struct_ptr->transfered_length += (req_bytes - remaining_bytes); if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC) { status = USB_STATUS_TRANSFER_DONE; if(EHCI_QTD_STATUS_HALTED & pipe_tr_struct_ptr->status) { if(EHCI_QTD_STATUS_BABBLE_DETECTED & pipe_tr_struct_ptr->status) { pipe_tr_struct_ptr->status = USBERR_TR_FAILED; } else if(0 == (EHCI_QTD_CERR_BITS_MASK & pipe_tr_struct_ptr->status)) { pipe_tr_struct_ptr->status = USBERR_TR_FAILED; } else { pipe_tr_struct_ptr->status = USBERR_ENDPOINT_STALLED; } } else { pipe_tr_struct_ptr->status = USB_OK; } if(qtd_timeout == 1) { pipe_tr_struct_ptr->status = USBERR_TR_FAILED; } } temp_qtd_ptr = qtd_ptr; qtd_ptr = (ehci_qtd_struct_t*)usb_hal_ehci_get_next_qtd_ptr( qtd_ptr); qh_ptr->qtd_head = qtd_ptr; if (usb_hal_ehci_get_next_qtd_link_ptr( qh_ptr) & EHCI_QTD_T_BIT) { /* No alternate descriptor */ usb_hal_ehci_set_qh_next_alt_qtd_link_terminate(qh_ptr); } if (status == USB_STATUS_TRANSFER_DONE) { if (_usb_host_unlink_tr(pipe_descr_ptr, pipe_tr_struct_ptr) != USB_OK) { #if _DEBUG USB_PRINTF("_usb_host_unlink_tr in _usb_ehci_process_qh_list_tr_complete failed\n"); #endif } if (pipe_tr_struct_ptr->callback != NULL) { pipe_tr_struct_ptr->callback((void*)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer_ptr, pipe_tr_struct_ptr->transfered_length, pipe_tr_struct_ptr->status); } status = 0; } _usb_ehci_free_qtd(handle, temp_qtd_ptr); } else { //qtd_ptr = (ehci_qtd_struct_t*)EHCI_MEM_READ(qtd_ptr->next_qtd_ptr); break; } } } while (active_qh_node_list); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_qh_interrupt_tr_complete * Returned Value : None * Comments : * Search the interrupt list to see which QTD had finished and * Process the interrupt. * *END*-----------------------------------------------------------------*/ void _usb_ehci_process_qh_interrupt_tr_complete ( /* [IN] the USB Host state structure */ usb_host_handle handle, ehci_qh_struct_t* active_list_member_ptr ) { ehci_qh_struct_t* qh_ptr; ehci_qtd_struct_t* qtd_ptr; ehci_qtd_struct_t* temp_qtd_ptr; ehci_pipe_struct_t* pipe_descr_ptr = NULL; tr_struct_t* pipe_tr_struct_ptr = NULL; uint32_t total_req_bytes = 0; uint32_t remaining_bytes = 0; uint32_t status = 0; uint8_t* buffer_ptr = NULL; do { qh_ptr = active_list_member_ptr; qtd_ptr = active_list_member_ptr->qtd_head; while ((!(((uint32_t)qtd_ptr) & EHCI_QTD_T_BIT)) && (qtd_ptr != NULL)) { #ifdef DEBUG_INFO uint32_t token = usb_hal_ehci_get_qtd_token(qtd_ptr); USB_PRINTF("_usb_ehci_process_qh_interrupt_tr_complete: QTD =%x\n" " Status=%x,PID code=%x,error code=%x,page=%x,IOC=%x,Bytes=%x,Toggle=%x\n", token, (token&0xFF), (token >> 8)&0x3, (token >> 10) &0x3, (token >> 12)&0x7, (token >> 15)&0x1, (token >> 16)&0x7FFF, (token&EHCI_QTD_DATA_TOGGLE) >>31); #endif if (!(usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_ACTIVE)) { pipe_descr_ptr = (ehci_pipe_struct_t*)qtd_ptr->pipe; pipe_tr_struct_ptr = (tr_struct_t*) qtd_ptr->tr; /* Check for errors */ if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_ERROR_BITS_MASK) { pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_ERROR_BITS_MASK); usb_hal_ehci_clear_qtd_token_bits( qtd_ptr, EHCI_QTD_ERROR_BITS_MASK); } /* Check if STALL or endpoint halted because of errors */ if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_HALTED) { /* save error count */ pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_CERR_BITS_MASK); pipe_tr_struct_ptr->status |= (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_STATUS_HALTED); usb_hal_ehci_clear_qtd_token_bits( qtd_ptr, EHCI_QTD_STATUS_HALTED); usb_hal_ehci_clear_qh_status( qh_ptr); } if (pipe_descr_ptr->common.direction) { total_req_bytes = pipe_tr_struct_ptr->tx_length; buffer_ptr = pipe_tr_struct_ptr->tx_buffer; } else { total_req_bytes = pipe_tr_struct_ptr->rx_length; buffer_ptr = pipe_tr_struct_ptr->rx_buffer; } remaining_bytes = ((usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_LENGTH_BIT_MASK) >> EHCI_QTD_LENGTH_BIT_POS); #ifdef DEBUG_INFO USB_PRINTF("_usb_ehci_process_qh_interrupt_tr_complete: Requested Bytes = %d\ ,Remaining bytes = %d,",total_req_bytes,remaining_bytes); #endif if (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC) { status = USB_STATUS_TRANSFER_DONE; if(EHCI_QTD_STATUS_HALTED & pipe_tr_struct_ptr->status) { if(EHCI_QTD_STATUS_BABBLE_DETECTED & pipe_tr_struct_ptr->status) { pipe_tr_struct_ptr->status = USBERR_TR_FAILED; } else if(0 == (EHCI_QTD_CERR_BITS_MASK & pipe_tr_struct_ptr->status)) { pipe_tr_struct_ptr->status = USBERR_TR_FAILED; } else { pipe_tr_struct_ptr->status = USBERR_ENDPOINT_STALLED; } } else { pipe_tr_struct_ptr->status = USB_OK; } } temp_qtd_ptr = qtd_ptr; qtd_ptr = (ehci_qtd_struct_t*)usb_hal_ehci_get_next_qtd_ptr(qtd_ptr); /* Queue the transfer onto the relevant queue head */ /* should remove this line here !!!!*/ usb_hal_ehci_set_qh_next_qtd_link_ptr( qh_ptr, (uint32_t)qtd_ptr); active_list_member_ptr->qtd_head = qtd_ptr; /* Dequeue the used QTD */ _usb_ehci_free_qtd(handle, temp_qtd_ptr); if (status == USB_STATUS_TRANSFER_DONE) { if (_usb_host_unlink_tr(pipe_descr_ptr, pipe_tr_struct_ptr) != USB_OK) { #if _DEBUG USB_PRINTF("_usb_host_unlink_tr in _usb_ehci_process_qh_interrupt_tr_complete failed\n"); #endif } if (pipe_tr_struct_ptr->callback != NULL) { pipe_tr_struct_ptr->callback((void *)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer_ptr, (total_req_bytes - remaining_bytes), pipe_tr_struct_ptr->status); } status = 0; } } else { break; } } active_list_member_ptr = active_list_member_ptr->next; } while (active_list_member_ptr); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_host_delay * Returned Value : None * Comments : * Delay for specified number of milliseconds. *END*-----------------------------------------------------------------*/ void _usb_host_delay ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] time to wait in ms */ uint32_t delay ) { /* Body */ uint32_t start_frame=0,curr_frame=0,diff =0,i=0,j=0; /* Get the frame number (not the uframe number */ start_frame = usb_ehci_get_frame_number(handle); /*wait till frame number exceeds by delay mili seconds.*/ do { curr_frame = usb_ehci_get_frame_number(handle); i++; if(curr_frame != start_frame) { diff++; start_frame = curr_frame; j++; } }while(diff < delay); } /* Endbody */ uint32_t _get_roundup_pow2(uint32_t data) { uint8_t i = 0; if((data == 1) || (data == 0 )) { return data; } while (data != 1) { data = data >> 1; i++; } return 1 << (i); } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_open_pipe * Returned Value : USB Status * Comments : * When opening a pipe, this callback ensures for iso / int pipes * to allocate bandwidth. *END*-----------------------------------------------------------------*/ usb_status usb_ehci_open_pipe ( /* [IN] the USB Host state structure */ usb_host_handle handle, usb_pipe_handle* pipe_handle_ptr, /* The pipe descriptor to queue */ pipe_init_struct_t* pipe_init_ptr ) { usb_status error; usb_ehci_host_state_struct_t* usb_host_ptr; ehci_pipe_struct_t* ehci_pipe_ptr; pipe_struct_t* pipe_ptr = NULL; ehci_qh_struct_t* qHead = NULL; uint8_t speed = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; USB_EHCI_Host_lock(); for (ehci_pipe_ptr = (ehci_pipe_struct_t*)usb_host_ptr->pipe_descriptor_base_ptr; ehci_pipe_ptr != NULL; ehci_pipe_ptr = (ehci_pipe_struct_t*)ehci_pipe_ptr->common.next) { pipe_ptr = &ehci_pipe_ptr->common; if (!pipe_ptr->open) { pipe_ptr->open = TRUE; break; } } USB_EHCI_Host_unlock(); if (ehci_pipe_ptr == NULL) { #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("_usb_khci_open_pipe failed"); #endif return USB_log_error(__FILE__,__LINE__,USBERR_OPEN_PIPE_FAILED); } pipe_ptr->endpoint_number = pipe_init_ptr->endpoint_number; pipe_ptr->direction = pipe_init_ptr->direction; pipe_ptr->pipetype = pipe_init_ptr->pipetype; pipe_ptr->max_packet_size = pipe_init_ptr->max_packet_size & PACKET_SIZE_MASK; pipe_ptr->flags = pipe_init_ptr->flags; pipe_ptr->nak_count = pipe_init_ptr->nak_count; pipe_ptr->nextdata01 = 0; pipe_ptr->tr_list_ptr = NULL; pipe_ptr->dev_instance = pipe_init_ptr->dev_instance; pipe_ptr->trs_per_uframe = 1 + pipe_init_ptr->trs_per_uframe; ehci_pipe_ptr->last_frame_index = 0xFFFF; if(pipe_ptr->trs_per_uframe > 3) { pipe_ptr->trs_per_uframe = 3; } speed = usb_host_dev_mng_get_speed(ehci_pipe_ptr->common.dev_instance); if (pipe_ptr->pipetype == USB_ISOCHRONOUS_PIPE) { pipe_ptr->interval = 1 << (pipe_init_ptr->interval - 1); } else { if(speed == USB_SPEED_HIGH) { if(pipe_ptr->pipetype == USB_INTERRUPT_PIPE) { if(pipe_init_ptr->interval <= 8) { pipe_ptr->interval = 1 << (pipe_init_ptr->interval - 1); } else { pipe_ptr->interval = 128; } } else { pipe_ptr->interval = _get_roundup_pow2(pipe_init_ptr->interval); } } else { pipe_ptr->interval = _get_roundup_pow2(pipe_init_ptr->interval); } } if ((pipe_init_ptr->pipetype == USB_INTERRUPT_PIPE) || ((pipe_init_ptr->pipetype == USB_ISOCHRONOUS_PIPE))) { if (usb_host_ptr->temp_speed == USB_SPEED_HIGH) { /* Call the low-level routine to send a setup packet */ error = _usb_ehci_allocate_bandwidth (handle, (pipe_struct_t*)ehci_pipe_ptr); if (error != USB_OK) { pipe_ptr->open = FALSE; return USBERR_BANDWIDTH_ALLOC_FAILED; } } else { error = _usb_ehci_fsls_allocate_bandwidth(handle, (pipe_struct_t*)ehci_pipe_ptr); if (error != USB_OK) { pipe_ptr->open = FALSE; return USBERR_BANDWIDTH_ALLOC_FAILED; } } } else { _usb_ehci_get_qh(handle, &qHead); if (qHead == NULL) { pipe_ptr->open = FALSE; return USBERR_BANDWIDTH_ALLOC_FAILED; } ehci_pipe_ptr->qh_for_this_pipe = qHead; } *pipe_handle_ptr = ehci_pipe_ptr; return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_close_pipe * Returned Value : error or USB_OK * Comments : * The function to open a pipe *END*-----------------------------------------------------------------*/ usb_status usb_ehci_close_pipe ( usb_host_handle handle, /* [in] Handle of opened pipe */ usb_pipe_handle pipe_handle ) { usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*) handle; ehci_pipe_struct_t* ehci_pipe_ptr_temp = NULL; pipe_struct_t* pipe_ptr = NULL; uint32_t offset = (uint32_t)&(((ehci_pipe_struct_t*)0)->actived); uint32_t offset_zero_set = (uint32_t)&(((ehci_pipe_struct_t*)0)->current_nak_count); uint8_t matched = (uint8_t)FALSE; ehci_pipe_ptr_temp = (ehci_pipe_struct_t*)pipe_handle; pipe_ptr = &ehci_pipe_ptr_temp->common; USB_EHCI_Host_lock(); if ((pipe_ptr != NULL) && (pipe_ptr->open == (uint8_t)TRUE)) { for (ehci_pipe_ptr_temp = (ehci_pipe_struct_t*)usb_host_ptr->pipe_descriptor_base_ptr; ehci_pipe_ptr_temp != NULL; ehci_pipe_ptr_temp = (ehci_pipe_struct_t*)ehci_pipe_ptr_temp->common.next) { pipe_ptr = &ehci_pipe_ptr_temp->common; if ((pipe_ptr->open) && (ehci_pipe_ptr_temp == pipe_handle)) { matched = (uint8_t)TRUE; break; } } if (matched) { _usb_ehci_free_resources(handle, (pipe_struct_t*)ehci_pipe_ptr_temp); OS_Mem_zero((void*)((uint32_t)ehci_pipe_ptr_temp + offset_zero_set), offset - offset_zero_set + 1); pipe_ptr->open = (uint8_t)FALSE; pipe_ptr->dev_instance = NULL; pipe_ptr->endpoint_number = 0; pipe_ptr->direction = 0; pipe_ptr->pipetype = 0; pipe_ptr->max_packet_size = 0; pipe_ptr->interval = 0; pipe_ptr->flags = 0; pipe_ptr->nak_count = 0; pipe_ptr->nextdata01 = 0; pipe_ptr->tr_list_ptr = NULL; pipe_ptr->trs_per_uframe = 0; } else { #if _DEBUG USB_PRINTF("usb_ehci_close_pipe can't find target pipe\n"); #endif USB_EHCI_Host_unlock(); return USBERR_INVALID_PIPE_HANDLE; } } else { #if _DEBUG USB_PRINTF("usb_ehci_close_pipe invalid pipe \n"); #endif USB_EHCI_Host_unlock(); return USBERR_INVALID_PIPE_HANDLE; } USB_EHCI_Host_unlock(); return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_update_dev_address * Returned Value : USB Status * Comments : * Update the queue in the EHCI hardware Asynchronous schedule list * to reflect new device address. *END*-----------------------------------------------------------------*/ usb_status usb_ehci_update_dev_address ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr ) { ehci_qh_struct_t* qh_ptr = NULL;//, QH_prev_ptr = NULL; bool active_async; ehci_pipe_struct_t* pipe_descr_ptr = (ehci_pipe_struct_t*) pipe_ptr; uint32_t temp; uint8_t address; usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*) handle; qh_ptr = pipe_descr_ptr->qh_for_this_pipe; #if 0 while ((EHCI_MEM_READ(qh_ptr->horiz_link_ptr) & EHCI_QH_HORIZ_PHY_ADDRESS_MASK) != (uint32_t) usb_host_ptr->active_async_list_ptr) { //QH_prev_ptr = qh_ptr; qh_ptr = (void *) EHCI_MEM_READ((qh_ptr->horiz_link_ptr) & EHCI_QH_HORIZ_PHY_ADDRESS_MASK); if (qh_ptr == pipe_descr_ptr->qh_for_this_pipe) { break; } } #endif /* Queue head is already on the active list. Simply update the queue */ active_async = usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase) & EHCI_USBCMD_ASYNC_SCHED_ENABLE; if (active_async) { /* stop async schedule */ usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); while (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_ASYNCH_SCHEDULE) { } } //_usb_ehci_init_qh(handle, pipe_descr_ptr, qh_ptr, QH_prev_ptr, (void *)EHCI_MEM_READ(qh_ptr->next_qtd_link_ptr)); address = (usb_host_dev_mng_get_address(pipe_descr_ptr->common.dev_instance)) & 0x7F; temp = usb_hal_ehci_get_ep_capab_charac1(qh_ptr); temp &= (uint32_t)(~(uint32_t)(0x07FF007F)); /* Initialize the endpoint capabilities registers */ temp |= (uint32_t)pipe_descr_ptr->common.max_packet_size << EHCI_QH_MAX_PKT_SIZE_BITS_POS | address; usb_hal_ehci_set_ep_capab_charac1(qh_ptr, temp); if (active_async) { usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_timer * Returned Value : USB Status * Comments : * Updates Asynchronous list QTDs timer information. Removes QTDs * with timeout. *END*-----------------------------------------------------------------*/ void _usb_ehci_process_timer ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr; ehci_qh_struct_t* active_qh_node_list; ehci_qtd_struct_t* qtd_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; active_qh_node_list = usb_host_ptr->active_async_list_ptr; do { if(active_qh_node_list == NULL) { break; } /* Get the queue head from the active list */ qh_ptr = active_qh_node_list; /* Get the first QTD for this Queue head */ qtd_ptr = qh_ptr->qtd_head; active_qh_node_list = active_qh_node_list->next; while ((!(((uint32_t)qtd_ptr) & EHCI_QTD_T_BIT)) && (qtd_ptr != NULL)) { if (qtd_ptr->qtd_timer > 0) { if (!--qtd_ptr->qtd_timer) { _usb_ehci_process_qh_list_tr_complete(handle, usb_host_ptr->active_async_list_ptr); } } qtd_ptr = (ehci_qtd_struct_t*)usb_hal_ehci_get_next_qtd_ptr( qtd_ptr); } } while (active_qh_node_list); } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_cancel_transfer * Returned Value : None * Comments : * Cancel a transfer *END*-----------------------------------------------------------------*/ usb_status usb_ehci_cancel_transfer ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* current_pipe_tr_struct_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr; ehci_qtd_struct_t* qtd_ptr; ehci_qtd_struct_t* temp_qtd_ptr; ehci_qtd_struct_t* start_qtd_ptr; ehci_qh_struct_t* active_list_member_ptr = NULL; ehci_qtd_struct_t* prev_qtd_ptr = NULL; tr_struct_t* temp_tr = NULL; uint32_t temp = 0; ehci_pipe_struct_t* pipe_descr_ptr = (ehci_pipe_struct_t*) pipe_ptr; uint8_t* buffer_address; uint8_t* temp_qtd_tx_buffer; uint8_t* temp_qtd_rx_buffer; void* tmp_tr; void* tmp_callback_param; usb_host_ptr = (usb_ehci_host_state_struct_t*) handle; if (pipe_descr_ptr->common.open == 0) { return USB_OK; } if (((pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE)) || ((pipe_descr_ptr->common.pipetype == USB_BULK_PIPE))) { active_list_member_ptr = usb_host_ptr->active_async_list_ptr; } else if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { active_list_member_ptr = usb_host_ptr->active_interrupt_periodic_list_ptr; } while ((!active_list_member_ptr) && ((active_list_member_ptr != pipe_descr_ptr->qh_for_this_pipe))) { active_list_member_ptr = active_list_member_ptr->next; } if (active_list_member_ptr == NULL) { #if _DEBUG USB_PRINTF("can't find target qh in usb_ehci_cancel_transfer\n"); #endif return USBERR_INVALID_PIPE_HANDLE; } if ((pipe_descr_ptr->common.pipetype == USB_CONTROL_PIPE) || (pipe_descr_ptr->common.pipetype == USB_BULK_PIPE)) { qh_ptr = pipe_descr_ptr->qh_for_this_pipe; qtd_ptr = qh_ptr->qtd_head; prev_qtd_ptr = NULL; start_qtd_ptr = NULL; /* remove all the qtd except the tr which is partial completed */ while ((((uint32_t)qtd_ptr & EHCI_QTD_T_BIT) == 0 ) && (qtd_ptr != NULL)) { temp_tr = (tr_struct_t*)(qtd_ptr->tr); if((NULL == current_pipe_tr_struct_ptr) || (current_pipe_tr_struct_ptr == temp_tr)) { /* Set Asynch_Enable bit = 0 */ usb_hal_echi_disable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); while (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_ASYNCH_SCHEDULE) { } while(0 == (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC)) { temp_qtd_ptr = qtd_ptr->next; /* Dequeue the used QTD */ _usb_ehci_free_qtd(handle, qtd_ptr); qtd_ptr = temp_qtd_ptr; } temp_qtd_ptr = qtd_ptr->next; /* Dequeue the used QTD */ _usb_ehci_free_qtd(handle, qtd_ptr); qtd_ptr = temp_qtd_ptr; if((NULL!= temp_tr) && (NULL != temp_tr->callback)) { if (USB_CONTROL_PIPE == pipe_descr_ptr->common.pipetype) { buffer_address = temp_tr->send_phase ? temp_tr->tx_buffer : temp_tr->rx_buffer; } else if (USB_BULK_PIPE == pipe_descr_ptr->common.pipetype) { buffer_address = (USB_SEND == pipe_descr_ptr->common.direction) ? temp_tr->tx_buffer : temp_tr->rx_buffer; } else { buffer_address = NULL; } temp_tr->callback((void*)temp_tr, temp_tr->callback_param, buffer_address, 0, USBERR_TR_CANCEL); } if(NULL != prev_qtd_ptr) { prev_qtd_ptr->next = qtd_ptr; if(NULL == qtd_ptr) { usb_hal_ehci_set_qtd_terminate_bit( prev_qtd_ptr); } else { usb_hal_ehci_link_qtd( prev_qtd_ptr, (uint32_t)qtd_ptr); } } if(NULL == start_qtd_ptr) { start_qtd_ptr = qtd_ptr; } usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } else { if(NULL == start_qtd_ptr) { start_qtd_ptr = qtd_ptr; } while(0 == (usb_hal_ehci_get_qtd_token(qtd_ptr) & EHCI_QTD_IOC)) { qtd_ptr = qtd_ptr->next; } prev_qtd_ptr = qtd_ptr; qtd_ptr = qtd_ptr->next; } } if (NULL != start_qtd_ptr) { usb_hal_ehci_set_qh_next_qtd_link_ptr(qh_ptr, (uint32_t)start_qtd_ptr); } else { usb_hal_ehci_set_qh_next_qtd_link_terminate(qh_ptr); } qh_ptr->qtd_head = start_qtd_ptr; usb_hal_ehci_enable_usb_cmd_async_sched(usb_host_ptr->usbRegBase); } /* Endif */ /**************************************************************************** SGARG: Add the ability to cancel the transfers for the interrupt pipe. Note that interrupts QHs are in the periodic list and they must be unlinked from all the possible frame lists that are linked to them. *****************************************************************************/ else if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { /* Get the queue head for this pipe */ qh_ptr = pipe_descr_ptr->qh_for_this_pipe; /* Get the first QTD for this Queue head */ qtd_ptr = qh_ptr->qtd_head; if ((((uint32_t)qtd_ptr & EHCI_QTD_T_BIT) == 0 ) && (qtd_ptr != NULL)) { /* Now we can disable the QTD list from this QH */ usb_hal_ehci_set_qh_next_qtd_link_terminate(qh_ptr); /* start pointer points to the first QTD in the final list*/ start_qtd_ptr = NULL; /* previous pointer points to NULL in the beginning */ prev_qtd_ptr = NULL; do { if ((NULL == current_pipe_tr_struct_ptr) || (qtd_ptr->tr == (void*)current_pipe_tr_struct_ptr)) { /* if list already started we connect previous QTD with next one*/ if(prev_qtd_ptr != NULL) { usb_hal_ehci_link_qtd(prev_qtd_ptr, usb_hal_ehci_get_next_qtd_ptr(qtd_ptr)); prev_qtd_ptr->next = qtd_ptr->next; } /* if list already started we link previous pointer*/ temp_qtd_ptr = qtd_ptr; /* advance the QTD pointer */ qtd_ptr = (ehci_qtd_struct_t*) usb_hal_ehci_get_next_qtd_ptr(qtd_ptr); /* Dequeue the used QTD */ _usb_ehci_free_qtd(handle, temp_qtd_ptr); if((NULL!= temp_qtd_ptr->tr) && (NULL != ((tr_struct_t*)temp_qtd_ptr->tr)->callback)) { tmp_tr = temp_qtd_ptr->tr; tmp_callback_param = ((tr_struct_t*)temp_qtd_ptr->tr)->callback_param; temp_qtd_tx_buffer = ((tr_struct_t*)temp_qtd_ptr->tr)->tx_buffer; temp_qtd_rx_buffer = ((tr_struct_t*)temp_qtd_ptr->tr)->rx_buffer; ((tr_struct_t*)temp_qtd_ptr->tr)->callback(tmp_tr, tmp_callback_param, (USB_SEND == pipe_descr_ptr->common.direction) ? temp_qtd_tx_buffer : temp_qtd_rx_buffer, 0, USBERR_TR_CANCEL); } } else { if(start_qtd_ptr == NULL) { /* Initialize the start pointer */ start_qtd_ptr = qtd_ptr; } /* store the previous qtd pointer */ prev_qtd_ptr = qtd_ptr; /* advance the QTD pointer */ qtd_ptr = (ehci_qtd_struct_t*) usb_hal_ehci_get_next_qtd_ptr(qtd_ptr); } } while ((((uint32_t)qtd_ptr & EHCI_QTD_T_BIT) == 0 ) && (qtd_ptr != NULL)); if(start_qtd_ptr != NULL) { /* Queue the transfer onto the relevant queue head */ usb_hal_ehci_set_qh_next_qtd_link_ptr(qh_ptr, (uint32_t)start_qtd_ptr); } qh_ptr->qtd_head = start_qtd_ptr; /* Clear all error conditions */ temp = usb_hal_ehci_get_qh_status(qh_ptr); usb_hal_ehci_set_qh_status(qh_ptr, temp & EHCI_QH_TR_OVERLAY_DT_BIT); } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_calculate_uframe_tr_time * Returned Value : bus time in nanoseconds or -1 if error * Comments : * Calculate the high speed bus transaction time (USB2.0 Spec 5.11.3) * in micro seconds for given number of bytes and type of pipe. Handshake time is included in this and worst case bt stuffing time is take in to account. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_calculate_time ( uint8_t speed, uint8_t pipetype, uint8_t direction, uint32_t bytes ) { uint32_t uframe_tr_time = 0; if (speed == USB_SPEED_HIGH) { /****************************************************************** The following formulae taken from USB specification are used Non-Isochronous Transfer (Handshake Included) = (55 * 8 * 2.083) + (2.083 * Floor(3.167 + BitStuffTime(Data_bc))) + Host_Delay Isochronous Transfer (No Handshake) = (38 * 8 * 2.083) + (2.083 * Floor(3.167 + BitStuffTime(Data_bc))) + Host_Delay ******************************************************************/ if (pipetype == USB_ISOCHRONOUS_PIPE) { /****************************************************************** Host delay has been taken as 3 nano seconds (3000 pico seconds to guess). Linux code takes a rough guess of 5 nano seconds. ******************************************************************/ uframe_tr_time = 38 * 8 * 2083 + 2083 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } else { /****************************************************************** Host delay has been taken as 3 nano seconds (3000 pico seconds to guess). Linux code takes a rough guess of 5 nano seconds. ******************************************************************/ uframe_tr_time = 55 * 8 * 2083 + 2083 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } } else if (speed == USB_SPEED_FULL) { if (pipetype == USB_ISOCHRONOUS_PIPE) { if (direction == USB_RECV) { uframe_tr_time = 7268000 + 83540 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } else { uframe_tr_time = 6265000 + 83540 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } } else { uframe_tr_time = 9107000 + 83540 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } } else if (speed == USB_SPEED_LOW) { if (direction == USB_RECV) { uframe_tr_time = 64060000 + 2000 * HUB_LS_SETUP + 676670 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } else { uframe_tr_time = 64107000 + 2000 * HUB_LS_SETUP + 667000 * ((3167 + BitStuffTime(1000*bytes))/1000) + VUSB_HS_DELAY; } } /****************************************************************** convert the times back to micro seconds ******************************************************************/ uframe_tr_time = uframe_tr_time/1000000; /****************************************************************** if time is less than 1 micro seconds we take an assumption of 1 Micro sec. This is true for transfers that are few bytes esp. Interrupt transfers. Actually if the bytes are less than 36 bytes, it will always be less than 1 Micro seconds. ******************************************************************/ if(uframe_tr_time < 1) {uframe_tr_time = 1;} return uframe_tr_time; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_get_frame_number * Returned Value : uint32_t * Comments : * Get the frame number *END*-----------------------------------------------------------------*/ uint32_t usb_ehci_get_frame_number ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* Get the frame number (not the uframe number */ return((usb_hal_ehci_get_frame_index(usb_host_ptr->usbRegBase) & 0x1FFF)>> 3); } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_get_micro_frame_number * Returned Value : uint32_t * Comments : * Get the micro frame number *END*-----------------------------------------------------------------*/ uint32_t usb_ehci_get_micro_frame_number ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* Get the uframe number */ return(usb_hal_ehci_get_frame_index(usb_host_ptr->usbRegBase) & 0x07); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_init_periodic_list * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at the type of transfer (Iso or Periodic) and allocate the slots in periodic list. Once all slots are found, it updates the bandwidth list to reflect the change. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_init_periodic_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; uint32_t* temp_periodic_list_ptr = NULL; ehci_itd_struct_t* itd_ptr; void* prev_ptr; list_node_struct_t* temp_itd_node_ptr; list_node_struct_t* temp_sitd_node_ptr; ehci_sitd_struct_t* sitd_ptr; ehci_pipe_struct_t* pipe_descr_ptr = (ehci_pipe_struct_t*) pipe_ptr; uint8_t speed; uint32_t i; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); if(!usb_host_ptr->periodic_list_initialized) { /* Set T-Bits of all elements in periodic frame list to 1 */ temp_periodic_list_ptr = (uint32_t *)usb_host_ptr->periodic_list_base_addr; for (i=0;i<usb_host_ptr->frame_list_size; i++) { EHCI_MEM_WRITE(*temp_periodic_list_ptr,EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT) temp_periodic_list_ptr++; } usb_host_ptr->periodic_list_initialized = TRUE; } /******************************************************************************* Initialize the ITDS list if this is High speed pipe. *******************************************************************************/ if ((!usb_host_ptr->itd_list_initialized) && (speed == USB_SPEED_HIGH)) { /* Enqueue all the ITDs */ itd_ptr = usb_host_ptr->itd_base_ptr; #if USBCFG_EHCI_MAX_ITD_DESCRS /* Enqueue all the ITDs */ for (i=0; i<USBCFG_EHCI_MAX_ITD_DESCRS; i++) { /* Set the dTD to be invalid */ usb_hal_ehci_set_ITD_terminate_bit(itd_ptr); /* Set the Reserved fields to 0 */ itd_ptr->scratch_ptr = (ehci_itd_struct_t *)usb_host_ptr; _usb_ehci_free_ITD((usb_host_handle)usb_host_ptr, itd_ptr); itd_ptr++; } /* initialize all nodes and link them */ temp_itd_node_ptr = (list_node_struct_t*) usb_host_ptr->active_iso_itd_periodic_list_head_ptr; prev_ptr = NULL; for(i=0;i<USBCFG_EHCI_MAX_ITD_DESCRS;i++) { /* next node is not an active node */ temp_itd_node_ptr->next_active = FALSE; /* previous node connection */ temp_itd_node_ptr->prev = (list_node_struct_t *)prev_ptr; /* move pointer */ prev_ptr = temp_itd_node_ptr; /* move next */ temp_itd_node_ptr++; /* store the next pointer in previous node */ ((list_node_struct_t*) prev_ptr)->next = temp_itd_node_ptr; } #endif usb_host_ptr->itd_list_initialized = TRUE; } /******************************************************************************* Initialize the SITDS list if this is full speed or low speed pipe. *******************************************************************************/ if ((!usb_host_ptr->sitd_list_initialized) && (speed != USB_SPEED_HIGH)) { sitd_ptr = usb_host_ptr->sitd_base_ptr; #if USBCFG_EHCI_MAX_SITD_DESCRS /* Enqueue all the SITDs */ for (i = 0; i < USBCFG_EHCI_MAX_SITD_DESCRS; i++) { /* Set the dTD to be invalid */ usb_hal_ehci_set_sitd_next_link_terminate_bit(sitd_ptr); /* Set the Reserved fields to 0 */ sitd_ptr->scratch_ptr = (ehci_sitd_struct_t*)usb_host_ptr; _usb_ehci_free_SITD((usb_host_handle)usb_host_ptr, sitd_ptr); sitd_ptr++; } /* initialize all nodes and link them */ temp_sitd_node_ptr = (list_node_struct_t*)usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; prev_ptr = NULL; for(i = 0; i < USBCFG_EHCI_MAX_SITD_DESCRS; i++) { /* next node is not an active node */ temp_sitd_node_ptr->next_active = FALSE; /* previous node connection */ temp_sitd_node_ptr->prev = (list_node_struct_t*)prev_ptr; /* move pointer */ prev_ptr = temp_sitd_node_ptr; /* move next */ temp_sitd_node_ptr++; /* store the next pointer in previous node */ ((list_node_struct_t*) prev_ptr)->next = temp_sitd_node_ptr; } #endif usb_host_ptr->sitd_list_initialized = TRUE; } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_fsls_allocate_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the bandwidth when ehci work as FS/LS. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_fsls_allocate_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr ) { usb_status status = USB_OK; uint32_t think_time = 0; uint16_t time_for_nohs = 0; uint16_t frame_index; uint16_t uframe_index; uint32_t i = 0, j = 0; usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr = NULL; ehci_pipe_struct_t* pipe_descr_ptr; uint32_t uframe_bandwidth[8]; uint32_t start_uframe = 0; uint8_t num_fsls = 0; uint8_t break_label = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; pipe_descr_ptr = (ehci_pipe_struct_t*)pipe_ptr; status = _usb_ehci_init_periodic_list(handle, pipe_ptr); if (USB_OK != status) { #if _DEBUG USB_PRINTF("_usb_ehci_init_periodic_list failed\n"); #endif return status; } think_time = 666 * (uint32_t)usb_host_dev_mng_get_hub_thinktime(pipe_descr_ptr->common.dev_instance) / 8 / 1000; if (think_time < MIN_THINK_TIME) { think_time = MIN_THINK_TIME; } time_for_nohs = think_time + _usb_ehci_calculate_time( usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance) , pipe_descr_ptr->common.pipetype , pipe_descr_ptr->common.direction , pipe_descr_ptr->common.max_packet_size); num_fsls = (pipe_descr_ptr->common.max_packet_size + 187) / 188; if (num_fsls == 0) { num_fsls = 1; } for (uframe_index = 0; uframe_index < 8; ++uframe_index) { for (frame_index = 0; frame_index < pipe_descr_ptr->common.interval; ++frame_index) { for (i = frame_index; i < usb_host_ptr->frame_list_size; i += pipe_descr_ptr->common.interval) { /* is slots engough for num_fsls ? */ if (8 - uframe_index < num_fsls) { break_label = 1; } if (0 == break_label) { /* is the bandwidth for uframe_index is full? */ status = _usb_ehci_fsls_sum_bandwidth(handle, pipe_descr_ptr, uframe_bandwidth, i); for (j = 0; j < 7; ++j) { if (uframe_bandwidth[j] > uframe_max[j]) { uframe_bandwidth[j + 1] += (uframe_bandwidth[j] - uframe_max[j]); uframe_bandwidth[j] = uframe_max[j]; } } if (uframe_bandwidth[uframe_index] > uframe_max[uframe_index]) { break_label = 1; } if (0 == break_label) { /* for iso the bandwidth must be full */ if (pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) { for (j = uframe_index; j < uframe_index + (pipe_descr_ptr->common.max_packet_size / 188); ++j) { if (uframe_bandwidth[j] > 0) { break_label = 1; break; } } } if (0 == break_label) { /* is the bandwidth enough for the pipe? */ uframe_bandwidth[uframe_index] += time_for_nohs; for (j = uframe_index; j < 7; ++j) { if (uframe_bandwidth[j] > uframe_max[j]) { uframe_bandwidth[j + 1] += (uframe_bandwidth[j] - uframe_max[j]); uframe_bandwidth[j] = uframe_max[j]; } } if (uframe_bandwidth[7] > uframe_max[7]) { break_label = 1; } } } } if (1 == break_label) { break; } } if (i >= usb_host_ptr->frame_list_size) { break; } } if (frame_index < pipe_descr_ptr->common.interval) { start_uframe = uframe_index; break; } } if (uframe_index >= 8) { return USBERR_BANDWIDTH_ALLOC_FAILED; } /* start_split, complete_split, bwidth, start_frame, start_uframe */ start_uframe = uframe_index; pipe_descr_ptr->start_split = 0; pipe_descr_ptr->complete_split = 0; if (pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) { if (pipe_descr_ptr->common.direction == USB_RECV) { pipe_descr_ptr->start_split = (0x01 << start_uframe); for (j = start_uframe + 2; ((j < start_uframe + 2 + num_fsls) && (j < 8)); ++j) { pipe_descr_ptr->complete_split |= (uint8_t)(0x01 << j); } } else { for (j = start_uframe; ((j < start_uframe + num_fsls) && (j < 8)); ++j) { pipe_descr_ptr->start_split |= (uint8_t)(0x01 << j); } pipe_descr_ptr->complete_split = 0; } } else { pipe_descr_ptr->start_split = (0x01 << start_uframe); for (j = start_uframe + 1; ((j < start_uframe + 1 + 3) && (j < 8)); ++j) { pipe_descr_ptr->complete_split |= (uint8_t)(0x01 << j); } } pipe_descr_ptr->bwidth = (uint16_t)time_for_nohs; pipe_descr_ptr->start_frame = frame_index; pipe_descr_ptr->start_uframe = start_uframe; if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { /****************************************************************** Allocate a new queue head *******************************************************************/ _usb_ehci_get_qh(handle, &qh_ptr); if (qh_ptr == NULL) { return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } _usb_ehci_init_qh(handle, pipe_descr_ptr, qh_ptr); qh_ptr->interval = pipe_descr_ptr->common.interval; for (frame_index = pipe_descr_ptr->start_frame; frame_index < usb_host_ptr->frame_list_size; frame_index += pipe_descr_ptr->common.interval) { link_interrupt_qh_to_periodiclist(handle, qh_ptr, pipe_descr_ptr, frame_index); } if (usb_host_ptr->active_interrupt_periodic_list_ptr == NULL) { usb_host_ptr->active_interrupt_periodic_list_ptr = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } else { usb_host_ptr->active_interrupt_periodic_list_tail_ptr->next = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } //pipe_descr_ptr->actived = 1; pipe_descr_ptr->qh_for_this_pipe = qh_ptr; } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_fsls_sum_bandwidth * Returned Value : USB_OK or error * Comments : * Sum bandwidth when ehci works as FS/LS. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_fsls_sum_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t* uframe_bandwidth, uint32_t frame ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_pipe_struct_t* ehci_pipe_ptr; uint32_t interval; pipe_struct_t* pipe_ptr = NULL; uint8_t i = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; for (i = 0; i < 8; ++i) { uframe_bandwidth[i] = 0; } for (ehci_pipe_ptr = (ehci_pipe_struct_t*)usb_host_ptr->pipe_descriptor_base_ptr; ehci_pipe_ptr != NULL; ehci_pipe_ptr = (ehci_pipe_struct_t*)ehci_pipe_ptr->common.next) { pipe_ptr = &ehci_pipe_ptr->common; if ((pipe_ptr->open == (uint8_t)TRUE) && (ehci_pipe_ptr != pipe_descr_ptr)) { interval = ehci_pipe_ptr->common.interval; if ((ehci_pipe_ptr->common.pipetype == USB_INTERRUPT_PIPE) || (ehci_pipe_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE)) { if ((frame >= ehci_pipe_ptr->start_frame) && ((frame - ehci_pipe_ptr->start_frame) % interval == 0)) { uframe_bandwidth[ehci_pipe_ptr->start_uframe] += ehci_pipe_ptr->bwidth; } } } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_allocate_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at the type of transfer (Iso or Periodic) and allocate the slots in periodic list. Once all slots are found, it updates the bandwidth list to reflect the change. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_allocate_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ pipe_struct_t* pipe_ptr ) { usb_status status = USB_OK; ehci_pipe_struct_t* pipe_descr_ptr = (ehci_pipe_struct_t*) pipe_ptr; uint8_t speed; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); /******************************************************************************* Initialize the periodic list if it is not initialized already. Note that this code could have been put under Host_init routine but since host must initialize witthin 1 mili second under OTG timing restrictions, this code has been moved here. *******************************************************************************/ status = _usb_ehci_init_periodic_list(handle, pipe_ptr); if (USB_OK != status) { #if _DEBUG USB_PRINTF("_usb_ehci_init_periodic_list failed\n"); #endif return status; } /******************************************************************************* Go Through the PERIODIC_FRAME_LIST_BW record to find the available slots. Here starts the complexity of the process. See the following from USB specifications. An isochronous endpoint must specify its required bus access period. Full-/high-speed endpoints must specify a desired period as (2^(bInterval-1)) x F, where bInterval is in the range one to (and including) 16 and F is 125 µs for high-speed and 1ms for full-speed. This allows full-/high-speed isochronous transfers to have rates slower than one transaction per (micro)frame. An endpoint for an interrupt pipe specifies its desired bus access period. A full-speed endpoint can specify a desired period from 1 ms to 255 ms. Low-speed endpoints are limited to specifying only 10 ms to 255 ms. High-speed endpoints can specify a desired period (2^(bInterval-1))x125 µs, where bInterval is in the range 1 to (including) 16. For high speed interrupts, Since we must have slots available at uframe_interval periods, if we can not find any slot starting from anywhere in Micro frame number 1 to Micro frame number equal to uframe_interval....till the end of periodic list we are out of bandwidth. For low and full speed device we do the same starting from frame 1 to frame frame_interval. ********************************************************************************/ /************************************************************************* If it is a high speed interrupt, allocate the slots at micro frame interval. Or if low or full speed, allocate slots at frame intervals. Note that the possible values of the interval for high speed are 1,2,4,8,16. **************************************************************************/ if (speed == USB_SPEED_HIGH) { status = _usb_ehci_commit_high_speed_bandwidth(handle, pipe_descr_ptr); if (USB_OK != status) { #if _DEBUG USB_PRINTF("alloc high speed bandwidth failed\n"); #endif return status; } } else { /*************************************************************************** Find the possible SS and CS that this endpoint could have. Check the periodic list for each such slot. If it fails, restart searching the periodic list for new slot. ****************************************************************************/ /******************************************************************** It is no simple game as it sounds in the code here. We should consider the time taken by the transaction and set the start split and complete split transactions for low and full speed devices. Read the following rules carefully to understand the code simplifying assumptions. ********************************************************************/ /******************************************************************** We are allowed to use only 80% of a frame for full speed and low speed periodic transfers. This is to provide space for Bulk and Control transfers. This means that if a frame slot exceeds .8x1000 micro seconds ,it is out of space. Since this transaction is a low or full speed transaction we need to find which start split and complete split could be scheduled. The following rules are followed in this code. See section 11.18 in USB specs for details. Y0-Y7 refers to micro frames on B bus which is 1 Microframe behind H Bus. 1) Host never schedules a start split in Y6. If We can not schedule the SS in H0-H6 for OUT, we will move to next frame. For IN transactions we must schedule SS early enough to ensure that all CS are scheduled within H7. Simplification is that we don't want to cross the microframe boundary in our implementation of CS. ISO OUT ======== 2) for Iso OUTs we must determine how many 188 bytes chunks it will take and schedule each of them in a Microframe. Each such microframe (also called budgeted microframe) should have a SS in previous micro frame. We always try to do a SS in H0-H6. If this is not possible we just move over to next frame. 3) There is no complete split scheduled for Iso OUT ISO IN ======= 4) For ISO IN, we must schedule a complete split in each micro frame following the micro frame in which transaction is budgeted. Also if the last micro frame in which complete-split is scheduled is less that Y6, we schedule two more in Y6 and Y7. 5)We take a simplyfying assumption that we budget the transaction between H0-H5 and schedule a complete split in rest of the micro frames till H7. Interrupt IN/OUT ================ 6)For interrupt IN/OUT host must schedule a complete split in the next two micro frames after transaction is budgeted. An additional complete split must be scheduled in the 3rd micro frame unless the transaction was budgeted to start in Y6. 7)We make a simplyfying assumption that if the transaction is not within H0-H4, we will go to the next frame (we will never schedule interrupt transactions to the H5-H7). This will allow us to schedule 3 CS in H5-H7 and 1 SS in the H0-H3. 8)Max data size for low speed interrupt is 8 bytes Max data size for full speed interrupt is 64 bytes This means that we will never need more than a Microframe for an Interrupt OUT or IN. 9) Host never schedules for than 16 SS (start splits) in a Micro frame for a given TT. ********************************************************************/ status = _usb_ehci_commit_split_bandwidth(handle, pipe_descr_ptr); if (USB_OK != status) { #if _DEBUG USB_PRINTF("alloc low/full speed bandwidth failed\n"); #endif return status; } } return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_commit_high_speed_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at used bandwidth and finds slots for this pipe at the asked interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_commit_high_speed_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr = NULL; uint32_t i, j; uint32_t time_for_action; uint8_t interval = pipe_descr_ptr->common.interval; uint8_t bandwidth_slots[8] = {0, 0, 0, 0, 0, 0, 0, 0}; uint32_t start_num = 0; usb_status status; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; time_for_action = _usb_ehci_calculate_time( USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, pipe_descr_ptr->common.direction, pipe_descr_ptr->common.max_packet_size * pipe_descr_ptr->common.trs_per_uframe ); for (i = 0; (i < interval) && (i < usb_host_ptr->frame_list_size * 8); i++) { for (j = 0; j < 8; ++j) { bandwidth_slots[j] = 0; } status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_action, bandwidth_slots, i); if (status == USB_OK) { start_num = i; break; } } if (status == USB_OK) { pipe_descr_ptr->bwidth = (uint16_t)time_for_action; pipe_descr_ptr->start_uframe = start_num; pipe_descr_ptr->start_split = (1 << (start_num%8)); if (pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) { for(j = 0; j < 8; j++) { pipe_descr_ptr->bwidth_slots[j] = (uint8_t)bandwidth_slots[j]; } #if EHCI_BANDWIDTH_RECORD_ENABLE for (i = start_num; i < usb_host_ptr->frame_list_size * 8; i += interval) { usb_host_ptr->periodic_frame_list_bw_ptr[i] += time_for_action; } #endif } if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { _usb_ehci_get_qh(handle, &qh_ptr); if (qh_ptr == NULL) { return USBERR_BANDWIDTH_ALLOC_FAILED; } _usb_ehci_init_qh(handle, pipe_descr_ptr, qh_ptr); qh_ptr->interval = interval; pipe_descr_ptr->qh_for_this_pipe = qh_ptr; for (i = start_num; i < usb_host_ptr->frame_list_size * 8; i += interval) { #if EHCI_BANDWIDTH_RECORD_ENABLE usb_host_ptr->periodic_frame_list_bw_ptr[i] += time_for_action; #endif link_interrupt_qh_to_periodiclist(handle, qh_ptr, pipe_descr_ptr, i/8); } if (usb_host_ptr->active_interrupt_periodic_list_ptr == NULL) { usb_host_ptr->active_interrupt_periodic_list_ptr = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } else { usb_host_ptr->active_interrupt_periodic_list_tail_ptr->next = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_commit_split_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at used bandwidth and finds slots for this pipe at the asked interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_commit_split_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { usb_status status = USB_OK; switch (pipe_descr_ptr->common.pipetype) { case USB_ISOCHRONOUS_PIPE: status = _usb_ehci_commit_split_iso_bandwidth(handle, pipe_descr_ptr); break; case USB_INTERRUPT_PIPE: status = _usb_ehci_commit_split_interrupt_bandwidth(handle, pipe_descr_ptr); break; default: break; } return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_commit_split_iso_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling split iso transactions on this pipe. This routine looks at used bandwidth and finds slots for this pipe at the asked interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_commit_split_iso_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr ) { #if EHCI_BANDWIDTH_RECORD_ENABLE usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; #endif uint32_t frame_index = 0; uint32_t uframe_index = 0; uint32_t time_for_nohs; uint16_t time_for_cs; uint16_t time_for_ss; uint8_t uframe_done = 0; uint8_t uframe_end = 0; uint8_t bandwidth_slots_ss[8] = {0, 0, 0, 0, 0, 0, 0, 0}; uint8_t bandwidth_slots_cs[8] = {0, 0, 0, 0, 0, 0, 0, 0}; usb_status status; uint32_t tmp = 0; uint32_t i = 0; uint8_t num_fsls; uint8_t num_fsls_result = 0; uint32_t think_time = 0; uint32_t interval = pipe_descr_ptr->common.interval; think_time = 666 * usb_host_dev_mng_get_hub_thinktime(pipe_descr_ptr->common.dev_instance) / 8 / 1000; if (think_time < MIN_THINK_TIME) { think_time = MIN_THINK_TIME; } time_for_nohs = think_time + _usb_ehci_calculate_time(usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance) , pipe_descr_ptr->common.pipetype , pipe_descr_ptr->common.direction , pipe_descr_ptr->common.max_packet_size); if (pipe_descr_ptr->common.direction == USB_RECV) { time_for_ss = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, 1); time_for_cs = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, pipe_descr_ptr->common.max_packet_size); } else { time_for_ss = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, pipe_descr_ptr->common.max_packet_size); time_for_cs = 0; } uframe_end = 5; uframe_done = 7; for (uframe_index = 0; uframe_index <= uframe_end; ++uframe_index) { for (frame_index = 0; frame_index < interval; ++frame_index) { num_fsls = (pipe_descr_ptr->common.max_packet_size + 187) / 188; if (num_fsls == 0) { num_fsls = 1; } num_fsls_result = num_fsls; status = _usb_ehci_allocate_fsls_bandwidth(handle, pipe_descr_ptr, time_for_nohs, frame_index, uframe_index + 1, uframe_done, &num_fsls_result); if (status != USB_OK) { continue; } if (pipe_descr_ptr->common.direction == USB_RECV) { for (i = 0; i < 8; ++i) { bandwidth_slots_ss[i] = 0; } status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_ss, bandwidth_slots_ss, frame_index * 8 + uframe_index); if (status != USB_OK) { continue; } tmp = frame_index * 8 + uframe_index + 2; for (i = 0; i < 8; ++i) { bandwidth_slots_cs[i] = 0; } for (i = tmp; ((i < (tmp + num_fsls_result)) && (i < (frame_index * 8 + 8))); ++i) { status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_cs, bandwidth_slots_cs, i); if (status != USB_OK) { break; /* fail */ } } } else { tmp = frame_index * 8 + uframe_index; for (i = 0; i < 8; ++i) { bandwidth_slots_ss[i] = 0; } for (i = tmp; ((i < (tmp + num_fsls)) && (i < (frame_index * 8 + 8))); ++i) { status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_ss, bandwidth_slots_ss, i); if (status != USB_OK) { break; /* fail */ } } } if (status == USB_OK) { break; } } if (status == USB_OK) { break; } } if (status != USB_OK) { return status; } if (num_fsls_result > 6) { return USBERR_BANDWIDTH_ALLOC_FAILED; } pipe_descr_ptr->bwidth = (uint16_t)time_for_nohs; pipe_descr_ptr->ss_bwidth = (uint16_t)time_for_ss; pipe_descr_ptr->cs_bwidth = (uint16_t)time_for_cs; pipe_descr_ptr->start_frame = frame_index; pipe_descr_ptr->start_uframe = uframe_index; for (i = 0; i < 8; ++i) { pipe_descr_ptr->fsls_bwidth[i] = 0; } /* ISO occupies all occupied uframe bandwidth except for the last uframe */ for (i = uframe_index + 1; i < uframe_index + num_fsls_result; ++i) { pipe_descr_ptr->fsls_bwidth[i] = uframe_max[i]; } /******************************************************************** When Bandwidth is available, For ISOCHRONOUS full speed TRANSACTIONS, we just need to store the SS and CS positions inside frames. ********************************************************************/ pipe_descr_ptr->start_split = 0; pipe_descr_ptr->complete_split = 0; tmp = 0; for (i = 0; i < 8; ++i) { if (bandwidth_slots_ss[i]) { ++tmp; pipe_descr_ptr->start_split |= (uint8_t)(0x01 << i); } } for (i = 0; i < 8; ++i) { if (bandwidth_slots_cs[i]) { pipe_descr_ptr->complete_split |= (uint8_t)(0x01 << i); } } pipe_descr_ptr->no_of_start_split = tmp; #if EHCI_BANDWIDTH_RECORD_ENABLE for (frame_index = pipe_descr_ptr->start_frame; frame_index < usb_host_ptr->frame_list_size; frame_index += interval) { for (i = 0; i < 8; ++i) { if (bandwidth_slots_ss[i]) { usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + i] += pipe_descr_ptr->ss_bwidth; } } for (i = 0; i < 8; ++i) { if (bandwidth_slots_cs[i]) { usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + i] += pipe_descr_ptr->cs_bwidth; } } } #endif return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_commit_split_interrupt_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling split interrupt transactions on this pipe. This routine looks at used bandwidth and finds slots for this pipe at the asked interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_commit_split_interrupt_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; uint32_t frame_index = 0; uint32_t uframe_index = 0; uint8_t speed; uint32_t time_for_nohs; uint32_t time_for_cs; uint32_t time_for_ss; uint8_t uframe_end = 0; uint8_t num_fsls = 0; usb_status status; uint32_t i = 0; uint32_t think_time = 0; uint32_t interval = pipe_descr_ptr->common.interval; ehci_qh_struct_t* qh_ptr = NULL; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); think_time = 666 * usb_host_dev_mng_get_hub_thinktime(pipe_descr_ptr->common.dev_instance) / 8 / 1000; if (think_time < MIN_THINK_TIME) { think_time = MIN_THINK_TIME; } time_for_nohs = think_time + _usb_ehci_calculate_time(speed, pipe_descr_ptr->common.pipetype, pipe_descr_ptr->common.direction, pipe_descr_ptr->common.max_packet_size); if (pipe_descr_ptr->common.direction == USB_RECV) { time_for_ss = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, 1); time_for_cs = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, pipe_descr_ptr->common.max_packet_size) + _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, 0); } else { time_for_ss = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, pipe_descr_ptr->common.max_packet_size) + _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, 1); time_for_cs = _usb_ehci_calculate_time(USB_SPEED_HIGH, pipe_descr_ptr->common.pipetype, USB_RECV, 0); } uframe_end = 4; for (uframe_index = 0; uframe_index < uframe_end; ++uframe_index) { for (frame_index = 0; frame_index < interval; ++frame_index) { status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_ss, NULL, frame_index * 8 + uframe_index); if (status != USB_OK) { continue; } num_fsls = 1; status = _usb_ehci_allocate_fsls_bandwidth( handle, pipe_descr_ptr, time_for_nohs, frame_index, uframe_index + 1, uframe_index + 3, &num_fsls); if (status != USB_OK) { continue; } for (i = uframe_index + 2; ((i <= uframe_index + 1 + num_fsls) && (i < 8)); ++i) { status = _usb_ehci_allocate_high_speed_bandwidth( handle, pipe_descr_ptr, time_for_cs, NULL, frame_index * 8 + i); if (status != USB_OK) { break; /* fail */ } } if (status == USB_OK) { break; } } if (status == USB_OK) { break; } } pipe_descr_ptr->bwidth = (uint16_t)time_for_nohs; pipe_descr_ptr->ss_bwidth = (uint16_t)time_for_ss; pipe_descr_ptr->cs_bwidth = (uint16_t)time_for_cs; pipe_descr_ptr->start_frame = frame_index; pipe_descr_ptr->start_uframe = uframe_index; for (i = 0; i < 8; ++i) { pipe_descr_ptr->fsls_bwidth[i] = 0; } for (i = uframe_index + 1; i <= uframe_index + num_fsls; ++i) { pipe_descr_ptr->fsls_bwidth[i] = time_for_nohs; } pipe_descr_ptr->start_split = 0; pipe_descr_ptr->complete_split = 0; pipe_descr_ptr->start_split |= (uint8_t)(1 << uframe_index); for (i = uframe_index + 2; ((i <= uframe_index + 1 + num_fsls) && (i < 8)); ++i) { pipe_descr_ptr->complete_split |= (uint8_t)(0x01 << i); } #if EHCI_BANDWIDTH_RECORD_ENABLE for (frame_index = pipe_descr_ptr->start_frame; frame_index < usb_host_ptr->frame_list_size; frame_index += interval) { usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + pipe_descr_ptr->start_uframe] += pipe_descr_ptr->ss_bwidth; usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + pipe_descr_ptr->start_uframe + 1] += pipe_descr_ptr->cs_bwidth; usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + pipe_descr_ptr->start_uframe + 2] += pipe_descr_ptr->cs_bwidth; usb_host_ptr->periodic_frame_list_bw_ptr[frame_index * 8 + pipe_descr_ptr->start_uframe + 3] += pipe_descr_ptr->cs_bwidth; } #endif /****************************************************************** Allocate a new queue head *******************************************************************/ _usb_ehci_get_qh(handle, &qh_ptr); if (qh_ptr == NULL) { return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } _usb_ehci_init_qh(handle, pipe_descr_ptr, qh_ptr); qh_ptr->interval = interval; if(speed != USB_SPEED_HIGH) { qh_ptr->interval = qh_ptr->interval << 3; } for (frame_index = pipe_descr_ptr->start_frame; frame_index < usb_host_ptr->frame_list_size; frame_index += interval) { link_interrupt_qh_to_periodiclist(handle, qh_ptr, pipe_descr_ptr, frame_index); } if (usb_host_ptr->active_interrupt_periodic_list_ptr == NULL) { usb_host_ptr->active_interrupt_periodic_list_ptr = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } else { usb_host_ptr->active_interrupt_periodic_list_tail_ptr->next = qh_ptr; usb_host_ptr->active_interrupt_periodic_list_tail_ptr = qh_ptr; } //pipe_descr_ptr->actived = 1; pipe_descr_ptr->qh_for_this_pipe = qh_ptr; return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_allocate_high_speed_bandwidth * Returned Value : USB_OK or error * Comments : * Judge whether the bandwidth is enough for the high speed pipe at the pipe interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_allocate_high_speed_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t time_for_action, uint8_t* bandwidth_slots, uint32_t start_uframe ) { usb_ehci_host_state_struct_t* usb_host_ptr; uint32_t j; uint8_t slot_found = 1; uint32_t uframe_bw = 0; uint32_t interval = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; slot_found = 1; if (usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance) == USB_SPEED_HIGH) { interval = pipe_descr_ptr->common.interval; } else { interval = pipe_descr_ptr->common.interval * 8; } for (j = start_uframe; j < usb_host_ptr->frame_list_size * 8; j += interval) { if (bandwidth_slots != NULL) { bandwidth_slots[j % 8] = 1; } #if EHCI_BANDWIDTH_RECORD_ENABLE uframe_bw = usb_host_ptr->periodic_frame_list_bw_ptr[j]; #else _usb_ehci_hs_sum_hs_bandwidth(handle, pipe_descr_ptr, &uframe_bw, j); #endif if((uframe_bw + time_for_action) > 100) { slot_found = 0; break; } } if (slot_found == 1) { return USB_OK; } return USBERR_BANDWIDTH_ALLOC_FAILED; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_allocate_fsls_bandwidth * Returned Value : USB_OK or error * Comments : * Judge whether the bandwidth is enough for the fs/ls speed pipe at the pipe interval. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_allocate_fsls_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t time_for_nohs, uint32_t frame_start, uint8_t uframe_start, uint8_t uframe_end, uint8_t* num_transaction ) { uint32_t i = 0; uint32_t frame_index = 0; usb_ehci_host_state_struct_t* usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; uint32_t uframe_bw_tmp[8]; uint32_t interval = pipe_descr_ptr->common.interval; uint8_t num = 0; num = *num_transaction; num += 2; /* 2 more slots is OK? */ if (uframe_end - uframe_start + 1 < num) { /* 1 more slots is OK? */ if ((uframe_end - uframe_start + 1) < (num - 1)) { return USBERR_BANDWIDTH_ALLOC_FAILED; } else { num -= 1; } } for (frame_index = frame_start; frame_index < usb_host_ptr->frame_list_size; frame_index += interval) { _usb_ehci_hs_sum_fsls_bandwidth(handle, pipe_descr_ptr, uframe_bw_tmp, frame_index); for (i = 0; i < 7; ++i) { if (uframe_bw_tmp[i] > uframe_max[i]) { uframe_bw_tmp[i + 1] += (uframe_bw_tmp[i] - uframe_max[i]); uframe_bw_tmp[i] = uframe_max[i]; } } if (uframe_bw_tmp[uframe_start] >= uframe_max[uframe_start]) { return USBERR_BANDWIDTH_ALLOC_FAILED; } /* for slots that is not last for this pipe */ for (i = uframe_start; ((i < (uframe_start + num - 1)) && (i <= uframe_end)); ++i) { if ((pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) && (uframe_bw_tmp[i] > 0)) { return USBERR_BANDWIDTH_ALLOC_FAILED; } else if ((pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) && (uframe_bw_tmp[i] + time_for_nohs > uframe_max[i])) { return USBERR_BANDWIDTH_ALLOC_FAILED; } } /* for slots that is last for this pipe */ if ((pipe_descr_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE) && (uframe_bw_tmp[i] > uframe_max[i])) { return USBERR_BANDWIDTH_ALLOC_FAILED; } else if ((pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) && (uframe_bw_tmp[i] + time_for_nohs > uframe_max[i])) { return USBERR_BANDWIDTH_ALLOC_FAILED; } *num_transaction = num; #if 0 uframe_bw_tmp[uframe_start] += time_for_nohs; for (i = uframe_start + 1; i <= uframe_end; ++i) { if (uframe_bw_tmp[i - 1] > 100) { uframe_bw_tmp[i] += (uframe_bw_tmp[i - 1] - 100); uframe_bw_tmp[i - 1] = 100; } else { break; } } if (uframe_bw_tmp[uframe_end] > 100) { return USBERR_BANDWIDTH_ALLOC_FAILED; } if (*num_transaction < (i - uframe_start)) *num_transaction = (i - uframe_start); #endif } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_get_dev_hs_hub_no * Returned Value : highspeed hub no * Comments : * get the dev_handle's high speed hub no *END*-----------------------------------------------------------------*/ static uint8_t _usb_get_dev_hs_hub_no(usb_device_instance_handle dev_handle) { if (usb_host_dev_mng_get_hub_speed(dev_handle) != USB_SPEED_HIGH) { return (usb_host_dev_mng_get_hs_hub_no(dev_handle)) & 0x7F; } else { return (usb_host_dev_mng_get_hubno(dev_handle)) & 0x7F; } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_sum_fsls_bandwidth * Returned Value : USB_OK or error * Comments : * sum the used fs/ls bandwidth for a frame. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_hs_sum_fsls_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t* uframe_bandwidth, uint32_t frame ) { uint32_t i = 0; usb_ehci_host_state_struct_t* usb_host_ptr; ehci_pipe_struct_t* ehci_pipe_ptr; uint8_t speed; uint32_t interval; pipe_struct_t* pipe_ptr = NULL; uint8_t hs_hub_no = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; hs_hub_no = _usb_get_dev_hs_hub_no(pipe_descr_ptr->common.dev_instance); for (i = 0; i < 8; ++i) { uframe_bandwidth[i] = 0; } for (ehci_pipe_ptr = (ehci_pipe_struct_t*)usb_host_ptr->pipe_descriptor_base_ptr; ehci_pipe_ptr != NULL; ehci_pipe_ptr = (ehci_pipe_struct_t*)ehci_pipe_ptr->common.next) { pipe_ptr = &ehci_pipe_ptr->common; if ((pipe_ptr->open == (uint8_t)TRUE) && (ehci_pipe_ptr != pipe_descr_ptr) && (hs_hub_no == _usb_get_dev_hs_hub_no(ehci_pipe_ptr->common.dev_instance))) { speed = usb_host_dev_mng_get_speed(ehci_pipe_ptr->common.dev_instance); interval = ehci_pipe_ptr->common.interval; if (speed != USB_SPEED_HIGH) { if ((ehci_pipe_ptr->common.pipetype == USB_INTERRUPT_PIPE) || (ehci_pipe_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE)) { if ((frame >= ehci_pipe_ptr->start_frame) && ((frame - ehci_pipe_ptr->start_frame) % interval == 0)) { for (i = 0; i < 8; ++i) { uframe_bandwidth[i] += ehci_pipe_ptr->fsls_bwidth[i]; } } } } } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_sum_hs_bandwidth * Returned Value : USB_OK or error * Comments : * sum the used hs bandwidth for a microframe. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_hs_sum_hs_bandwidth ( usb_host_handle handle, ehci_pipe_struct_t* pipe_descr_ptr, uint32_t* uframe_bandwidth, uint32_t uframe ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_pipe_struct_t* ehci_pipe_ptr; uint8_t speed; uint32_t interval; pipe_struct_t* pipe_ptr = NULL; uint32_t tmp = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; *uframe_bandwidth = 0; for (ehci_pipe_ptr = (ehci_pipe_struct_t*)usb_host_ptr->pipe_descriptor_base_ptr; ehci_pipe_ptr != NULL; ehci_pipe_ptr = (ehci_pipe_struct_t*)ehci_pipe_ptr->common.next) { pipe_ptr = &ehci_pipe_ptr->common; if ((pipe_ptr->open == (uint8_t)TRUE) && (ehci_pipe_ptr != pipe_descr_ptr)) { speed = usb_host_dev_mng_get_speed(ehci_pipe_ptr->common.dev_instance); interval = ehci_pipe_ptr->common.interval; if ((ehci_pipe_ptr->common.pipetype == USB_INTERRUPT_PIPE) || (ehci_pipe_ptr->common.pipetype == USB_ISOCHRONOUS_PIPE)) { if (speed != USB_SPEED_HIGH) { if (((uframe / 8) >= ehci_pipe_ptr->start_frame) && (((uframe / 8) - ehci_pipe_ptr->start_frame) % interval == 0)) { tmp = (uframe & 0x00000007); if ((uint8_t)(ehci_pipe_ptr->start_split) & ((uint8_t)(0x01 << tmp))) { *uframe_bandwidth += ehci_pipe_ptr->ss_bwidth; } else if ((uint8_t)ehci_pipe_ptr->complete_split & (uint8_t)(0x01 << tmp)) { *uframe_bandwidth += ehci_pipe_ptr->cs_bwidth; } } } else { if (( uframe >= ehci_pipe_ptr->start_uframe) && ((uframe - ehci_pipe_ptr->start_uframe) % interval == 0)) { *uframe_bandwidth += ehci_pipe_ptr->bwidth; } } } } } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_high_speed_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at the BW list and finds regular slots at the asked interval starting from 'start' slot number. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_free_high_speed_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr = NULL; uint32_t i; uint8_t interval = pipe_descr_ptr->common.interval; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; qh_ptr = pipe_descr_ptr->qh_for_this_pipe; #if EHCI_BANDWIDTH_RECORD_ENABLE for (i = pipe_descr_ptr->start_uframe; i < (usb_host_ptr->frame_list_size * 8); i+= interval) { usb_host_ptr->periodic_frame_list_bw_ptr[i] -= pipe_descr_ptr->bwidth; } #endif if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { for (i = pipe_descr_ptr->start_uframe; i < (usb_host_ptr->frame_list_size * 8); i+= interval) { unlink_interrupt_qh_from_periodiclist(handle, qh_ptr, pipe_descr_ptr, i/8); } _usb_ehci_free_qh(handle, qh_ptr); } for (i = 0; i < 8; ++i) { pipe_descr_ptr->bwidth_slots[i] = 0; } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_split_bandwidth * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at the BW list and finds regular slots at the asked interval starting from 'start' slot number. *END*-----------------------------------------------------------------*/ static usb_status _usb_ehci_free_split_bandwidth ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_qh_struct_t* qh_ptr = NULL; uint32_t i; #if EHCI_BANDWIDTH_RECORD_ENABLE uint32_t j; #endif uint8_t interval = pipe_descr_ptr->common.interval; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; qh_ptr = pipe_descr_ptr->qh_for_this_pipe; #if EHCI_BANDWIDTH_RECORD_ENABLE for (i = pipe_descr_ptr->start_frame; i < usb_host_ptr->frame_list_size; i += interval) { for (j = 0; j < 8; ++j) { if (pipe_descr_ptr->start_split & (0x01 << j)) { usb_host_ptr->periodic_frame_list_bw_ptr[i * 8 + j] -= pipe_descr_ptr->ss_bwidth; } } for (j = 0; j < 8; ++j) { if (pipe_descr_ptr->complete_split& (0x01 << j)) { usb_host_ptr->periodic_frame_list_bw_ptr[i* 8 + j] -= pipe_descr_ptr->cs_bwidth; } } } #endif if (pipe_descr_ptr->common.pipetype == USB_INTERRUPT_PIPE) { for (i = pipe_descr_ptr->start_frame; i < usb_host_ptr->frame_list_size; i += interval) { unlink_interrupt_qh_from_periodiclist(handle, qh_ptr, pipe_descr_ptr, i); } _usb_ehci_free_qh(handle, qh_ptr); } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_commit_bandwidth_slots * Returned Value : USB_OK or error * Comments : * Allocates the slots for scheduling transactions on this pipe. This routine looks at the BW list and finds regular slots at the asked interval starting from 'start' slot number. *END*-----------------------------------------------------------------*/ static uint32_t _usb_ehci_get_link_obj_interval ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ volatile uint32_t* link_obj ) { ehci_itd_struct_t* itd_ptr = NULL; ehci_sitd_struct_t* sitd_ptr = NULL; ehci_qh_struct_t* qh_ptr = NULL; uint32_t item_type; item_type = EHCI_GET_TYPE(link_obj); if (item_type == EHCI_ELEMENT_TYPE_ITD) { itd_ptr = (ehci_itd_struct_t*)(EHCI_MEM_READ(*link_obj) & EHCI_HORIZ_PHY_ADDRESS_MASK); return itd_ptr->interval; } else if (item_type == EHCI_ELEMENT_TYPE_SITD) { sitd_ptr = (ehci_sitd_struct_t*)(EHCI_MEM_READ(*link_obj) & EHCI_HORIZ_PHY_ADDRESS_MASK); return sitd_ptr->interval; } else if (item_type == EHCI_ELEMENT_TYPE_QH) { qh_ptr = (ehci_qh_struct_t*)(EHCI_MEM_READ(*link_obj) & EHCI_HORIZ_PHY_ADDRESS_MASK); return qh_ptr->interval; } return (uint32_t)-1; } /*FUNCTION*------------------------------------------------------------- * * Function Name : link_interrupt_qh_to_periodiclist * Returned Value : USB_OK or error * Comments : * Links the QH to the given slot in periodic list. If pipe is a high speed, slot number is the micro frame number to link QH in. If pipe is a low speed, slot number is the frame number to link QH in. In all cases, we link in frame except that we also update the microframe schedule mask number. *END*-----------------------------------------------------------------*/ static void link_interrupt_qh_to_periodiclist ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* QH that will be scheduled. */ ehci_qh_struct_t* qh_ptr, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* slot in which this QH should be scheduled */ uint32_t slot_number ) { usb_ehci_host_state_struct_t* usb_host_ptr; volatile uint32_t* transfer_data_struct_ptr = NULL; volatile uint32_t* prev_transfer_data_struct_ptr = NULL; uint32_t interval; //ehci_qh_struct_t* active_qh_list; uint8_t break_label = 0; usb_host_ptr = (usb_ehci_host_state_struct_t*) handle; //active_qh_list = usb_host_ptr->active_interrupt_periodic_list_ptr; transfer_data_struct_ptr = (volatile uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += slot_number; if (usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT) { /* this item is the first one in this frame */ //EHCI_MEM_WRITE(*transfer_data_struct_ptr,((uint32_t)qh_ptr | (EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS))); usb_hal_ehci_set_periodic_list_addr( transfer_data_struct_ptr, qh_ptr); } else { /* insert item into the link */ while (!(usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_QUEUE_HEAD_POINTER_T_BIT)) { if ((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) != (uint32_t)qh_ptr) { interval = _usb_ehci_get_link_obj_interval(handle, transfer_data_struct_ptr); if (interval >= qh_ptr->interval) { prev_transfer_data_struct_ptr = transfer_data_struct_ptr; transfer_data_struct_ptr = (uint32_t *)(usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); if ((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_QUEUE_HEAD_POINTER_T_BIT)) { usb_hal_ehci_set_periodic_list_addr( transfer_data_struct_ptr, qh_ptr); } } else { if (prev_transfer_data_struct_ptr == NULL) { /* should insert this item as the first one */ usb_hal_ehci_set_qh_horiz_link_ptr( qh_ptr, usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) | EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS); usb_hal_ehci_set_periodic_list_addr( transfer_data_struct_ptr, qh_ptr); } else { /* should insert this item after prev one */ usb_hal_ehci_set_qh_horiz_link_ptr( qh_ptr, usb_hal_ehci_get_periodic_list_addr( prev_transfer_data_struct_ptr) | EHCI_FRAME_LIST_ELEMENT_TYPE_QH << EHCI_QH_ELEMENT_TYPE_BIT_POS); usb_hal_ehci_set_periodic_list_addr( prev_transfer_data_struct_ptr, qh_ptr); break_label = 1; } } } else { break_label = 1; } if (1 == break_label) { break; } } } return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : unlink_interrupt_qh_from_periodiclist * Returned Value : USB_OK or error * Comments : * Links the QH to the given slot in periodic list. If pipe is a high speed, slot number is the micro frame number to link QH in. If pipe is a low speed, slot number is the frame number to link QH in. In all cases, we link in frame except that we also update the microframe schedule mask number. *END*-----------------------------------------------------------------*/ static void unlink_interrupt_qh_from_periodiclist ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* QH that will be scheduled. */ ehci_qh_struct_t* qh_ptr, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* slot in which this QH should be scheduled */ uint32_t slot_number ) { usb_ehci_host_state_struct_t* usb_host_ptr; uint32_t* transfer_data_struct_ptr = NULL; uint32_t* prev_transfer_data_struct_ptr = NULL; uint32_t* next_transfer_data_struct_ptr = NULL; //uint32_t interval; ehci_qh_struct_t* cur_qh; ehci_qh_struct_t* prev_qh; usb_host_ptr = (usb_ehci_host_state_struct_t*) handle; transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += slot_number; if (usb_host_ptr->active_interrupt_periodic_list_ptr == qh_ptr) { usb_host_ptr->active_interrupt_periodic_list_ptr = qh_ptr->next; if (usb_host_ptr->active_interrupt_periodic_list_tail_ptr == qh_ptr) { usb_host_ptr->active_interrupt_periodic_list_tail_ptr = NULL; } } else { if(NULL != usb_host_ptr->active_interrupt_periodic_list_ptr) { cur_qh = prev_qh = usb_host_ptr->active_interrupt_periodic_list_ptr; while ((cur_qh != NULL) && (cur_qh != qh_ptr)) { prev_qh = cur_qh; cur_qh = cur_qh->next; } if(cur_qh == qh_ptr) { prev_qh->next = qh_ptr->next; if (usb_host_ptr->active_interrupt_periodic_list_tail_ptr == qh_ptr) { usb_host_ptr->active_interrupt_periodic_list_tail_ptr = prev_qh; } } } } if ((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) == (uint32_t)qh_ptr) { /* this item is the first one in the frame list */ next_transfer_data_struct_ptr = (uint32_t*)usb_hal_ehci_get_qh_horiz_link_ptr( qh_ptr); usb_hal_ehci_set_transfer_data_struct( transfer_data_struct_ptr, ((uint32_t)next_transfer_data_struct_ptr)); } else { while (!(usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_QUEUE_HEAD_POINTER_T_BIT)) { if ((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) != (uint32_t)qh_ptr) { prev_transfer_data_struct_ptr = transfer_data_struct_ptr; transfer_data_struct_ptr = (uint32_t *)(usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); } else { if (prev_transfer_data_struct_ptr == NULL) { } else { usb_hal_ehci_set_transfer_data_struct( transfer_data_struct_ptr, (uint32_t)usb_hal_ehci_get_qh_horiz_link_ptr( qh_ptr)); } } } } return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : unlink_periodic_data_structure_from_frame * Returned Value : None * Comments : * unlinks the data structure from periodic list *END*-----------------------------------------------------------------*/ void unlink_periodic_data_structure_from_frame( volatile uint32_t *prev_transfer_data_struct_ptr, volatile uint32_t *transfer_data_struct_ptr ) { ehci_itd_struct_t* itd_ptr; ehci_sitd_struct_t* sitd_ptr; ehci_fstn_struct_t* FSTN_ptr; ehci_qh_struct_t* qh_ptr; uint32_t next=0; /************************************************************** Find the void *to the next structure to be pointed in the list **************************************************************/ switch (EHCI_GET_TYPE(transfer_data_struct_ptr)) { case EHCI_ELEMENT_TYPE_ITD: itd_ptr = (ehci_itd_struct_t*)((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); next = usb_hal_ehci_get_itd_next_link_pointer( itd_ptr); break; case EHCI_ELEMENT_TYPE_QH: qh_ptr = (ehci_qh_struct_t*)((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); next = usb_hal_ehci_get_qh_horiz_link_ptr( qh_ptr); break; case EHCI_ELEMENT_TYPE_SITD: sitd_ptr = (ehci_sitd_struct_t*)((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); next = usb_hal_ehci_get_sitd_next_link_pointer( sitd_ptr); break; case EHCI_ELEMENT_TYPE_FSTN: FSTN_ptr = (ehci_fstn_struct_t*)((usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); next = usb_hal_ehci_get_fstn_normal_path_link_ptr( FSTN_ptr); break; default: break; } /************************************************************** Assign the previous to new one **************************************************************/ if(prev_transfer_data_struct_ptr != transfer_data_struct_ptr) { switch (EHCI_GET_TYPE(prev_transfer_data_struct_ptr)) { case EHCI_ELEMENT_TYPE_ITD: itd_ptr = (ehci_itd_struct_t*)((usb_hal_ehci_get_periodic_list_addr( prev_transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); usb_hal_ehci_set_itd_next_link_pointer( itd_ptr, next); break; case EHCI_ELEMENT_TYPE_QH: qh_ptr = (ehci_qh_struct_t*)((usb_hal_ehci_get_periodic_list_addr( prev_transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); usb_hal_ehci_set_qh_horiz_link_ptr( qh_ptr, next); break; case EHCI_ELEMENT_TYPE_SITD: sitd_ptr = (ehci_sitd_struct_t*)((usb_hal_ehci_get_periodic_list_addr( prev_transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); usb_hal_ehci_set_sitd_next_link_pointer( sitd_ptr, next); break; case EHCI_ELEMENT_TYPE_FSTN: FSTN_ptr = (ehci_fstn_struct_t*)((usb_hal_ehci_get_periodic_list_addr( prev_transfer_data_struct_ptr)) & EHCI_HORIZ_PHY_ADDRESS_MASK); usb_hal_ehci_set_fstn_normal_path_link_ptr( FSTN_ptr, next); break; default: break; } } else { EHCI_MEM_WRITE(*prev_transfer_data_struct_ptr,next) } return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_close_interrupt_pipe * Returned Value : None * Comments : * Close the Interrupt pipe and update the bandwidth list. Here are the notes. In EHCI, closing an interrupt pipe involves removing the queue head from the periodic list to make sure that none of the frames refer to this queue head any more. It is also important to remember that we must start removing the queue head link from a safe place which is not currently being executed by EHCi controller. Apart from this we should free all QTDs associated with it and QH Managements structure. *END*-----------------------------------------------------------------*/ void _usb_ehci_close_interrupt_pipe ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { uint8_t speed; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); //usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /**************************************************************************** Obtain the QH for this pipe ****************************************************************************/ //qh_ptr = (ehci_qh_struct_t*) pipe_descr_ptr->qh_for_this_pipe; /**************************************************************************** First Search the periodic list and unlink this QH from the list. ****************************************************************************/ //periodic_list_base_ptr = (volatile uint32_t *)(usb_host_ptr->periodic_list_base_addr); /******************************************************************* Start from fram 0 till end of the list and unlink the QH if found. Note that we should not unlink when the QH is active but current code does not take this in account. ********************************************************************/ /* Get frame list size and interval */ if (speed == USB_SPEED_HIGH) { _usb_ehci_free_high_speed_bandwidth(handle, pipe_descr_ptr); } else { _usb_ehci_free_split_bandwidth(handle, pipe_descr_ptr); } return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_link_structure_in_periodic_list * Returned Value : None * Comments : * This routine adds the given list of ITD or SITD structures in * periodic list starting at the earliest available slot in the slots (micro frames) * allocated for the given pipe. *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_link_structure_in_periodic_list ( /* [IN] the USB_dev_initialize state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, uint32_t *struct_to_link_list, /* [IN] this is one more than actual length */ uint32_t no_of_structs ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_itd_struct_t* itd_ptr; ehci_sitd_struct_t* sitd_ptr; uint32_t i; uint32_t earliest_frame_slot; uint32_t current_frame_number; uint32_t *transfer_data_struct_ptr = NULL; uint8_t speed; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* we can not have interrupts when adding data structures to the hardware list */ USB_EHCI_Host_lock(); /********************************************************************** What frame number controller is executing at the moment. We start from the slot allocated to this pipe after this frame number. **********************************************************************/ current_frame_number = usb_ehci_get_frame_number(handle) % usb_host_ptr->frame_list_size; if (pipe_descr_ptr->last_frame_index == 0xFFFF) { pipe_descr_ptr->last_frame_index = current_frame_number; } #if 0 /********************************************************************** Loop the periodic list and find the earliest frame higher than this frame number.We take a margin of 3 frames for safety. **********************************************************************/ if(speed == USB_SPEED_HIGH) { i = pipe_descr_ptr->start_uframe; /* note that i is microframe number */ while(i/8 < (current_frame_number + 3) % usb_host_ptr->frame_list_size) { i += pipe_descr_ptr->common.interval; } /********************************************************************** If earliest microframe where we could schedule is more than the size of periodic list, we schedule at the start slot **********************************************************************/ earliest_frame_slot = (i/8) % usb_host_ptr->frame_list_size; /********************************************************************** Link all structures in periodic list. Note that ITds are added in the beginning in the list. Interrupts QH are linked to multiple lists so they are always added at the end. **********************************************************************/ /***************************************************************** transfer_data_struct_ptr is the void *to earliest frame slot. *****************************************************************/ transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; for(i = 0; i < no_of_structs; i++) { itd_ptr = (ehci_itd_struct_t*) (struct_to_link_list[i]); /* store the frame list pointer */ itd_ptr->frame_list_ptr = transfer_data_struct_ptr; /* save the next one */ /*next_data_struct = (*transfer_data_struct_ptr);*/ /*restore the previous link back */ usb_hal_ehci_set_itd_next_link_pointer( itd_ptr, usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)); #ifdef __USB_OTG__ #ifdef HOST_TESTING USB_mem_copy((unsigned char *)itd_ptr, &usb_otg_state_struct_ptr->ITD_QUEUE_LOG[usb_otg_state_struct_ptr->LOG_FRAME_COUNT] ,80); usb_otg_state_struct_ptr->LOG_FRAME_COUNT++; if(usb_otg_state_struct_ptr->LOG_FRAME_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_FRAME_COUNT = 0; #endif #endif /* add this one to the start of the frame list pointer */ usb_hal_ehci_add_frame_list_pointer_itd( transfer_data_struct_ptr, itd_ptr); earliest_frame_slot += (pipe_descr_ptr->common.interval / 8 > 1) ? pipe_descr_ptr->common.interval / 8 : 1; /* if we did not reach the end of the list we move on*/ if(earliest_frame_slot < usb_host_ptr->frame_list_size) { /* move to next frame interval */ transfer_data_struct_ptr += (pipe_descr_ptr->common.interval / 8 > 1) ? (pipe_descr_ptr->common.interval / 8) : 1; } else { /* start from the first frame allocated to this pipe */ earliest_frame_slot = pipe_descr_ptr->start_uframe/8; transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; } } /* end for loop */ } /****************************************************************************** For full speed we connect SITDs in periodic list ******************************************************************************/ else { i = pipe_descr_ptr->start_frame; /* note that i is frame number */ if(((i > current_frame_number)? (i-current_frame_number):(current_frame_number - i)) > 5) { i = 0; /* we take a safety margin of 3 frames (3 milliseconds) to find the right slot */ while(i < (current_frame_number + 3) % usb_host_ptr->frame_list_size) { i += pipe_descr_ptr->common.interval; } } else i += pipe_descr_ptr->common.interval; /********************************************************************** If eariest microframe where we could schedule is more than the size of periodic list, we schedule at the start slot **********************************************************************/ earliest_frame_slot = i % usb_host_ptr->frame_list_size; pipe_descr_ptr->start_frame = earliest_frame_slot; if(pipe_descr_ptr->start_frame == usb_host_ptr->frame_list_size) pipe_descr_ptr->start_frame = 0; /********************************************************************** Link all structures in periodic list. Note that SITds are added in the beginning in the list. Interrupts QH are linked to multiple lists so they are always added at the end. **********************************************************************/ /***************************************************************** transfer_data_struct_ptr is the void *to earliest frame slot. *****************************************************************/ transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; for(i = 0; i < no_of_structs; i++) { sitd_ptr = (ehci_sitd_struct_t*) (struct_to_link_list[i]); /* store the frame list pointer */ sitd_ptr->frame_list_ptr = transfer_data_struct_ptr; /*restore the previous link back */ usb_hal_ehci_set_sitd_next_link_pointer( sitd_ptr, usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)); #ifdef __USB_OTG__ #ifdef HOST_TESTING USB_mem_copy((unsigned char *)sitd_ptr, &usb_otg_state_struct_ptr->SITD_QUEUE_LOG[usb_otg_state_struct_ptr->LOG_FRAME_COUNT] ,44); usb_otg_state_struct_ptr->LOG_FRAME_COUNT++; if(usb_otg_state_struct_ptr->LOG_FRAME_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_FRAME_COUNT = 0; #endif #endif /* add this one to the start of the frame list pointer */ usb_hal_ehci_add_frame_list_pointer_sitd( transfer_data_struct_ptr, sitd_ptr); earliest_frame_slot += pipe_descr_ptr->common.interval; /* if we did not reach the end of the list we move on*/ if(earliest_frame_slot < usb_host_ptr->frame_list_size) { /* move to next frame interval */ transfer_data_struct_ptr += pipe_descr_ptr->common.interval; } else { /* start from the first frame allocated to this pipe */ earliest_frame_slot = (pipe_descr_ptr->start_frame + 3) % usb_host_ptr->frame_list_size; transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; } } /* end for loop */ } #else /********************************************************************** Loop the periodic list and find the earliest frame higher than this frame number.We take a margin of 3 frames for safety. **********************************************************************/ if(speed == USB_SPEED_HIGH) { i = pipe_descr_ptr->start_uframe; /* note that i is microframe number */ if (pipe_descr_ptr->last_frame_index > current_frame_number) { if ((pipe_descr_ptr->last_frame_index) > (current_frame_number + USBCFG_EHCI_ITD_THRESHOLD)) { pipe_descr_ptr->last_frame_index = current_frame_number + 2; } } else { if ((pipe_descr_ptr->last_frame_index + usb_host_ptr->frame_list_size) > (current_frame_number + USBCFG_EHCI_ITD_THRESHOLD)) { pipe_descr_ptr->last_frame_index = current_frame_number + 2; } } //i = pipe_descr_ptr->last_frame_index << 3; pipe_descr_ptr->last_frame_index = (pipe_descr_ptr->last_frame_index + 1) % usb_host_ptr->frame_list_size; while ((i>>3) < pipe_descr_ptr->last_frame_index) { i += pipe_descr_ptr->common.interval; } /********************************************************************** If eariest microframe where we could schedule is more than the size of periodic list, we schedule at the start slot **********************************************************************/ earliest_frame_slot = (i>>3) % usb_host_ptr->frame_list_size; /********************************************************************** Link all structures in periodic list. Note that ITds are added in the beginning in the list. Interrupts QH are linked to multiple lists so they are always added at the end. **********************************************************************/ /***************************************************************** transfer_data_struct_ptr is the void *to earliest frame slot. *****************************************************************/ transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; for(i = 0; i < no_of_structs; i++) { pipe_descr_ptr->last_frame_index = earliest_frame_slot; itd_ptr = (ehci_itd_struct_t*) (struct_to_link_list[i]); /* store the frame list pointer */ itd_ptr->frame_list_ptr = transfer_data_struct_ptr; /* save the next one */ /*restore the previous link back */ usb_hal_ehci_set_itd_next_link_pointer( itd_ptr, usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)); #ifdef __USB_OTG__ #ifdef HOST_TESTING USB_mem_copy((unsigned char *)itd_ptr, &usb_otg_state_struct_ptr->ITD_QUEUE_LOG[usb_otg_state_struct_ptr->LOG_FRAME_COUNT] ,80); usb_otg_state_struct_ptr->LOG_FRAME_COUNT++; if(usb_otg_state_struct_ptr->LOG_FRAME_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_FRAME_COUNT = 0; #endif #endif /* add this one to the start of the frame list pointer */ usb_hal_ehci_add_frame_list_pointer_itd( transfer_data_struct_ptr, itd_ptr); earliest_frame_slot += (pipe_descr_ptr->common.interval / 8 > 1) ? pipe_descr_ptr->common.interval / 8 : 1; /* if we did not reach the end of the list we move on*/ if(earliest_frame_slot < usb_host_ptr->frame_list_size) { /* move to next frame interval */ transfer_data_struct_ptr += (pipe_descr_ptr->common.interval / 8 > 1) ? (pipe_descr_ptr->common.interval / 8) : 1; } else { /* start from the first frame allocated to this pipe */ earliest_frame_slot = pipe_descr_ptr->start_uframe/8; transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; } } /* end for loop */ } /****************************************************************************** For full speed we connect SITDs in periodic list ******************************************************************************/ else { i = pipe_descr_ptr->start_frame; /* note that i is frame nubmer */ if (pipe_descr_ptr->last_frame_index > current_frame_number) { if ((pipe_descr_ptr->last_frame_index) > (current_frame_number + USBCFG_EHCI_ITD_THRESHOLD)) { pipe_descr_ptr->last_frame_index = current_frame_number + 2; } } else { if ((pipe_descr_ptr->last_frame_index + usb_host_ptr->frame_list_size) > (current_frame_number + USBCFG_EHCI_ITD_THRESHOLD)) { pipe_descr_ptr->last_frame_index = current_frame_number + 2; } } //i = pipe_descr_ptr->last_frame_index; pipe_descr_ptr->last_frame_index = (pipe_descr_ptr->last_frame_index + 1) % usb_host_ptr->frame_list_size; while (i < pipe_descr_ptr->last_frame_index) { i += pipe_descr_ptr->common.interval; } /********************************************************************** If eariest microframe where we could schedule is more than the size of periodic list, we schedule at the start slot **********************************************************************/ earliest_frame_slot = i % usb_host_ptr->frame_list_size; /********************************************************************** Link all structures in periodic list. Note that SITds are added in the beginning in the list. Interrupts QH are linked to multiple lists so they are always added at the end. **********************************************************************/ /***************************************************************** transfer_data_struct_ptr is the void *to earliest frame slot. *****************************************************************/ transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; for(i = 0; i < no_of_structs; i++) { pipe_descr_ptr->last_frame_index = earliest_frame_slot; sitd_ptr = (ehci_sitd_struct_t*) (struct_to_link_list[i]); /* store the frame list pointer */ sitd_ptr->frame_list_ptr = transfer_data_struct_ptr; /*restore the previous link back */ usb_hal_ehci_set_sitd_next_link_pointer( sitd_ptr, usb_hal_ehci_get_periodic_list_addr( transfer_data_struct_ptr)); #ifdef __USB_OTG__ #ifdef HOST_TESTING USB_mem_copy((unsigned char *)sitd_ptr, &usb_otg_state_struct_ptr->SITD_QUEUE_LOG[usb_otg_state_struct_ptr->LOG_FRAME_COUNT] ,44); usb_otg_state_struct_ptr->LOG_FRAME_COUNT++; if(usb_otg_state_struct_ptr->LOG_FRAME_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_FRAME_COUNT = 0; #endif #endif /* add this one to the start of the frame list pointer */ usb_hal_ehci_add_frame_list_pointer_sitd( transfer_data_struct_ptr, sitd_ptr); earliest_frame_slot += pipe_descr_ptr->common.interval; /* if we did not reach the end of the list we move on*/ if(earliest_frame_slot < usb_host_ptr->frame_list_size) { /* move to next frame interval */ transfer_data_struct_ptr += pipe_descr_ptr->common.interval; } else { /* start from the first frame allocated to this pipe */ earliest_frame_slot = (pipe_descr_ptr->start_frame) % usb_host_ptr->frame_list_size; transfer_data_struct_ptr = (uint32_t *)(usb_host_ptr->periodic_list_base_addr); transfer_data_struct_ptr += earliest_frame_slot; } } /* end for loop */ } #endif USB_EHCI_Host_unlock(); return USB_OK; } #if USBCFG_EHCI_MAX_ITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_add_ITD * Returned Value : None * Comments : * Adds Isochronous transfer desriptors to the Periodic list for the given pipe. * *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_add_ITD ( /* [IN] the USB_dev_initialize state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* pipe_tr_ptr ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; ehci_itd_struct_t* itd_ptr; uint32_t total_length = 0, pg_select,remaining_length; uint32_t length_scheduled; unsigned char *buff_ptr,*curr_page_ptr=NULL; uint8_t itd_direction_bit; uint32_t no_of_itds=0,no_of_uframes=0; uint32_t i,j,offset,next; uint8_t max_slots_per_frame=0; uint32_t struct_to_link_list[USBCFG_EHCI_MAX_ITD_DESCRS]; usb_status status; uint8_t address; address = (usb_host_dev_mng_get_address(pipe_descr_ptr->common.dev_instance)) & 0x7F; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /*assert max packet size, interval, buffers, length etc.*/ /****************************************************************************** This list will contain all ITDs that will be linked in periodic list. We ensure that all fields inside it are NULL before we try to link it. ******************************************************************************/ next = 0; OS_Mem_zero(struct_to_link_list, USBCFG_EHCI_MAX_ITD_DESCRS * sizeof(uint32_t)); /****************************************************************************** A client buffer request to an isochronous endpoint may span 1 to N microframes. When N is larger than one, system software may have to use multiple iTDs to read or write data with the buffer (if N is larger than eight, it must use more than one iTD). Each iTD can be initialized to service up to 24 transactions, organized into eight groups of up to three transactions each. Each group maps to one micro-frame's worth of transactions. The EHCI controller does not provide per-transaction results within a micro-frame. It treats the per-micro-frame transactions as a single logical transfer. *******************************************************************************/ /******************************************************************************* find out how big is the transaction *******************************************************************************/ if (pipe_descr_ptr->common.direction == USB_SEND) { total_length = pipe_tr_ptr->tx_length; buff_ptr = pipe_tr_ptr->tx_buffer; /*see EHCI specs. direction is 0 for an ISO OUT */ itd_direction_bit = 0; } else { total_length = pipe_tr_ptr->rx_length; buff_ptr = pipe_tr_ptr->rx_buffer; itd_direction_bit = 1; } /******************************************************************************* How many micro frame this transaction will it take? If some bytes are remaining we increase it by 1. *******************************************************************************/ no_of_uframes = ((total_length%(pipe_descr_ptr->common.max_packet_size*pipe_descr_ptr->common.trs_per_uframe)) > 0) ? (total_length/(pipe_descr_ptr->common.max_packet_size*pipe_descr_ptr->common.trs_per_uframe) + 1): (total_length/(pipe_descr_ptr->common.max_packet_size*pipe_descr_ptr->common.trs_per_uframe)); /********************************************************************************** How many micro frame slots (per frame) this transaction will take?. We cannot use all 8 microframe slots of a ITD because this ITD should execute only in the micro frames allocated to it. **********************************************************************************/ for(j = 0; j < 8; j++) { if(pipe_descr_ptr->bwidth_slots[j]) { max_slots_per_frame++; } } no_of_itds = ((no_of_uframes%max_slots_per_frame) > 0)? ((no_of_uframes/max_slots_per_frame) + 1) : (no_of_uframes/max_slots_per_frame); /* error check */ if (no_of_itds >= usb_host_ptr->itd_entries) { return USB_log_error(__FILE__,__LINE__,USBERR_TRANSFER_IN_PROGRESS); } /******************************************************************************* Allocate as many ITDs and schedule it in periodic list *******************************************************************************/ remaining_length = total_length; length_scheduled = 0; //curr_page_ptr = buff_ptr; /* save on how many ITDS are required for this transfer */ pipe_tr_ptr->no_of_itds_sitds = no_of_itds; for(i = 0; i < no_of_itds; i++) { USB_EHCI_Host_lock(); /********************************************************************* Get an ITD from the queue **********************************************************************/ EHCI_ITD_QGET(usb_host_ptr->itd_head, usb_host_ptr->itd_tail, itd_ptr) if (!itd_ptr) { USB_EHCI_Host_unlock(); return USB_STATUS_TRANSFER_IN_PROGRESS; } /* Endif */ usb_host_ptr->itd_entries--; /********************************************************************* Add the ITD to the list of active ITDS (note that it is assumed that space is available in the queue because itd_ptr was allocated and number of nodes available always match the number of ITD_ENTRIES **********************************************************************/ EHCI_ACTIVE_QUEUE_ADD_NODE(usb_host_ptr->active_iso_itd_periodic_list_tail_ptr,(void* )itd_ptr); USB_EHCI_Host_unlock(); /********************************************************************* Zero the ITD. Leave everything else expect first 16 int bytes (which are defined by EHCI specs). Fill the necessary fields. **********************************************************************/ init_the_volatile_struct_to_zero(itd_ptr, 16*sizeof(uint32_t)); /* Initialize the ITD private fields*/ itd_ptr->pipe_descr_for_this_itd = pipe_descr_ptr; itd_ptr->pipe_tr_descr_for_this_itd = pipe_tr_ptr; itd_ptr->scratch_ptr = (ehci_itd_struct_t*)handle; /* Set the Terminate bit */ usb_hal_ehci_set_ITD_terminate_bit(itd_ptr); /*store endpoint number and device address */ usb_hal_ehci_store_endpoint_number_and_device_addr(itd_ptr, ((uint32_t)pipe_descr_ptr->common.endpoint_number << EHCI_ITD_EP_BIT_POS) | address); /*store max packet size and direction */ usb_hal_ehci_store_max_packet_size_and_direction(itd_ptr, pipe_descr_ptr->common.max_packet_size | (uint32_t)itd_direction_bit << EHCI_ITD_DIRECTION_BIT_POS); /*A High-Bandwidth transaction is allowed only if the length of bytes to schedule are same or more than mutiple bandwidth factor times the Max packet size */ if(remaining_length >= pipe_descr_ptr->common.trs_per_uframe * pipe_descr_ptr->common.max_packet_size) { //EHCI_MEM_WRITE(itd_ptr->buffer_page_ptr_list[2],pipe_descr_ptr->common.trs_per_uframe); usb_hal_ehci_set_transaction_number_per_micro_frame(itd_ptr, pipe_descr_ptr->common.trs_per_uframe); } else { //EHCI_MEM_WRITE(itd_ptr->buffer_page_ptr_list[2],1); usb_hal_ehci_set_transaction_number_per_micro_frame(itd_ptr, 1); } /*initialize the number of transactions on this ITD */ itd_ptr->number_of_transactions = 0; /********************************************************************* One ITD can address 7 4K pages. Find how many pages this transaction will take and schedule each of them in this ITD. It is assumed that buffer is large enough for the given transaction and we don't check for its validity here. ***********************************************************************/ pg_select = 0; /************************************************************** Prepare the ITD for the slots that are scheduled for it. **************************************************************/ for(j = 0; j < 8; j++) { /*only if this micro frame is allocated to this pipe*/ if(pipe_descr_ptr->bwidth_slots[j]) { /********************************************************************* Set the location of Page 0 (4K aligned) *********************************************************************/ //EHCI_MEM_WRITE(itd_ptr->buffer_page_ptr_list[pg_select],(EHCI_MEM_READ(itd_ptr->buffer_page_ptr_list[pg_select] ) | (uint32_t)buff_ptr) & 0xFFFFF000); usb_hal_ehci_set_buffer_page_pointer(itd_ptr, pg_select, ((usb_hal_ehci_get_buffer_page_pointer(itd_ptr, pg_select) & EHCI_ITD_BUFFER_OFFSET) | ((uint32_t)buff_ptr & EHCI_ITD_BUFFER_POINTER))); offset = (uint32_t)buff_ptr & EHCI_ITD_BUFFER_OFFSET; /************************************************************** For IN transaction, we always use Max packet size but for an OUT we can use the length remained in the buffer if it is less than a maxk packet size. **************************************************************/ if (pipe_descr_ptr->common.direction == USB_SEND) { length_scheduled = (pipe_descr_ptr->common.trs_per_uframe * pipe_descr_ptr->common.max_packet_size > remaining_length) ? remaining_length : pipe_descr_ptr->common.trs_per_uframe * pipe_descr_ptr->common.max_packet_size; remaining_length -= length_scheduled; } else { /* on a ISO IN, we still schedule Max packet size but makes sure that remaining length is set to 0 so no more slots are scheduled */ length_scheduled = (uint32_t)(pipe_descr_ptr->common.trs_per_uframe * pipe_descr_ptr->common.max_packet_size); remaining_length = (length_scheduled > remaining_length) ? 0 : (remaining_length - length_scheduled); } /************************************************************** Fill the fields inside ITD **************************************************************/ usb_hal_ehci_set_transcation_status_and_control_bit(itd_ptr,j, ((length_scheduled << EHCI_ITD_LENGTH_BIT_POS) | (pg_select << EHCI_ITD_PG_SELECT_BIT_POS) | EHCI_ITD_IOC_BIT | offset)); usb_hal_ehci_set_transcation_status_active_bit(itd_ptr,j); /*update the transaction number queued*/ itd_ptr->number_of_transactions++; /* move buffer pointer */ buff_ptr += length_scheduled; /* if remaining length is 0 we break from the loop because we don't need to schedule any more slots*/ if(remaining_length == 0) { if(((uint32_t)buff_ptr & EHCI_ITD_BUFFER_POINTER) != ((uint32_t)curr_page_ptr & EHCI_ITD_BUFFER_POINTER)) { pg_select++; if (pg_select < 7) { usb_hal_ehci_set_buffer_page_pointer(itd_ptr, pg_select, ((usb_hal_ehci_get_buffer_page_pointer(itd_ptr, pg_select) & EHCI_ITD_BUFFER_OFFSET) | ((uint32_t)buff_ptr & EHCI_ITD_BUFFER_POINTER))); } } break; } /************************************************************** if a page boundary has been crossed we move to next page **************************************************************/ if(((uint32_t)buff_ptr & EHCI_ITD_BUFFER_POINTER) != ((uint32_t)curr_page_ptr & EHCI_ITD_BUFFER_POINTER)) { pg_select++; /* move the page count*/ curr_page_ptr = buff_ptr; /* start with this page now*/ } } } /*end for loop */ usb_hal_ehci_set_itd_length_scheduled(itd_ptr, length_scheduled); /********************************************************************** ITD ready. We store it in out list of ITDs **********************************************************************/ #ifdef __USB_OTG__ #ifdef HOST_TESTING usb_otg_state_struct_ptr->NEXT_LINK[usb_otg_state_struct_ptr->NEXT_LINK_COUNT] = EHCI_MEM_READ(itd_ptr->next_link_ptr); usb_otg_state_struct_ptr->NEXT_LINK_COUNT++; if(usb_otg_state_struct_ptr->NEXT_LINK_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->NEXT_LINK_COUNT = 0; #endif #endif struct_to_link_list[next] = (uint32_t)itd_ptr; next++; } /*end for loop*/ /********************************************************************** List ready. We link it into periodic list now. **********************************************************************/ status = _usb_ehci_link_structure_in_periodic_list(handle,pipe_descr_ptr,struct_to_link_list,next); if(status == USB_OK) { usb_host_ptr->high_speed_iso_queue_active = TRUE; } return status; } /* EndBody */ #endif //USBCFG_EHCI_MAX_ITD_DESCRS #if USBCFG_EHCI_MAX_SITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_add_SITD * Returned Value : None * Comments : * Adds Isochronous transfer desriptors to the Periodic list for the given full speed pipe. * *END*-----------------------------------------------------------------*/ usb_status _usb_ehci_add_SITD ( /* [IN] the USB_dev_initialize state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* pipe_tr_ptr ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; ehci_sitd_struct_t* sitd_ptr; uint32_t total_length = 0, pg_select,remaining_length; uint32_t length_scheduled; unsigned char *buff_ptr; uint8_t sitd_direction_bit, tp_bits=0; uint32_t no_of_sitds=0; uint32_t i,next; uint32_t struct_to_link_list[USBCFG_EHCI_MAX_SITD_DESCRS]; usb_status status; uint8_t address; uint8_t hub_no; uint8_t port_no; address = (usb_host_dev_mng_get_address(pipe_descr_ptr->common.dev_instance)) & 0x7F; if (usb_host_dev_mng_get_hub_speed(pipe_descr_ptr->common.dev_instance) != USB_SPEED_HIGH) { hub_no = (usb_host_dev_mng_get_hs_hub_no(pipe_descr_ptr->common.dev_instance)) & 0x7F; port_no = (usb_host_dev_mng_get_hs_port_no(pipe_descr_ptr->common.dev_instance)) & 0x7F; } else { hub_no = (usb_host_dev_mng_get_hubno(pipe_descr_ptr->common.dev_instance)) & 0x7F; port_no = (usb_host_dev_mng_get_portno(pipe_descr_ptr->common.dev_instance)) & 0x7F; } usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /*assert max packet size, interval, buffers, length etc.*/ /****************************************************************************** This list will contain all SITDs that will be linked in periodic list. We ensure that all fields inside it are NULL before we try to link it. Notice that the following could be a time consuming line if number of SITDS is large. Reconsider removing this line after proper testing. ******************************************************************************/ next = 0; OS_Mem_zero(struct_to_link_list, sizeof(struct_to_link_list)); /******************************************************************************* find out how big is the transaction *******************************************************************************/ if (pipe_descr_ptr->common.direction == USB_SEND) { total_length = pipe_tr_ptr->tx_length; buff_ptr = pipe_tr_ptr->tx_buffer; /*see EHCI specs. direction is 0 for an ISO OUT */ sitd_direction_bit = 0; } else { total_length = pipe_tr_ptr->rx_length; buff_ptr = pipe_tr_ptr->rx_buffer; sitd_direction_bit = 1; } /******************************************************************************* Full speed devices have a minimum frequency of 1 mili second so 1 SITD can completely describe 1 Max_packet_size transaction. Thus number of SITD is same as number of max packet size transactions required for the given transfer. *******************************************************************************/ no_of_sitds = ((total_length%pipe_descr_ptr->common.max_packet_size) > 0) ? (total_length/pipe_descr_ptr->common.max_packet_size + 1): (total_length/pipe_descr_ptr->common.max_packet_size); /* error check , if we are going to run out of SITDS, we reject transfer here itself*/ if (no_of_sitds >= usb_host_ptr->sitd_entries) { return USB_log_error(__FILE__,__LINE__,USBERR_TRANSFER_IN_PROGRESS); } /******************************************************************************* Allocate as many SITDs and schedule it in periodic list *******************************************************************************/ remaining_length = total_length; length_scheduled = 0; /* save on how many SITDS are required for this transfer */ pipe_tr_ptr->no_of_itds_sitds = no_of_sitds; USB_EHCI_Host_lock(); for(i = 0; i < no_of_sitds; i++) { /********************************************************************* Get an SITD from the queue **********************************************************************/ EHCI_SITD_QGET(usb_host_ptr->sitd_head, usb_host_ptr->sitd_tail, sitd_ptr) if (!sitd_ptr) { USB_EHCI_Host_unlock(); return USB_STATUS_TRANSFER_IN_PROGRESS; } /* Endif */ usb_host_ptr->sitd_entries--; /********************************************************************* Zero the SITD. Leave everything else expect first 7 int bytes (which are defined by EHCI specs). Fill the necessary fields. **********************************************************************/ init_the_volatile_struct_to_zero(sitd_ptr, 7*sizeof(uint32_t)); /* Initialize the scratch pointer inside SITD */ sitd_ptr->pipe_descr_for_this_sitd = pipe_descr_ptr; sitd_ptr->pipe_tr_descr_for_this_sitd = pipe_tr_ptr; sitd_ptr->scratch_ptr = (ehci_sitd_struct_t*)handle; /********************************************************************* Add the SITD to the list of active SITDS (note that it is assumed that space is available in the queue because sitd_ptr was allocated and number of nodes available always match the number of SITD_ENTRIES **********************************************************************/ EHCI_ACTIVE_QUEUE_ADD_NODE(usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr,(void *)sitd_ptr); /* Set the Terminate bit */ usb_hal_ehci_set_sitd_next_link_terminate_bit(sitd_ptr); /* Set the Back pointer */ usb_hal_ehci_set_sitd_back_pointer_terminate_bit(sitd_ptr); /*store direction, port number, hub, endpoint number device address etc.*/ usb_hal_ehci_set_sitd_ep_capab_charac(sitd_ptr, \ (((uint32_t)sitd_direction_bit << EHCI_SITD_DIRECTION_BIT_POS) | ((uint32_t)port_no << EHCI_SITD_PORT_NUMBER_BIT_POS) | ((uint32_t)hub_no << EHCI_SITD_HUB_ADDR_BIT_POS) | ((uint32_t)pipe_descr_ptr->common.endpoint_number << EHCI_SITD_EP_ADDR_BIT_POS) | address)); /* store the split transaction schedule */ usb_hal_ehci_set_sitd_uframe_sched_ctl(sitd_ptr, \ (uint32_t)pipe_descr_ptr->complete_split << EHCI_SITD_COMPLETE_SPLIT_MASK_BIT_POS | pipe_descr_ptr->start_split); /*store the buffer pointer 1 and offset*/ /********************************************************************* One SITD can only carry a max of 1023 bytes so two page pointers are enough to describe it. We always set the page select to 0 in SITD and controller will move to next page and update the pg_select bit. ***********************************************************************/ pg_select = 0; /************************************************************** For IN transaction, we always use Max packet size but for an OUT we can use the length remained in the buffer if it is less than a maxk packet size. **************************************************************/ if (pipe_descr_ptr->common.direction == USB_SEND) { length_scheduled = (pipe_descr_ptr->common.max_packet_size > remaining_length) ? remaining_length : pipe_descr_ptr->common.max_packet_size; remaining_length -= length_scheduled; } else { /* on a ISO IN, we still schedule Max packet size but makes sure that remaining length is set to 0 so no more slots are scheduled */ length_scheduled = pipe_descr_ptr->common.max_packet_size; remaining_length = (length_scheduled > remaining_length) ? 0 : (remaining_length - length_scheduled); } /************************************************************** Fill the fields inside SITD **************************************************************/ /*store total bytes to transfer and status. Note that a total of 1023 bytes max can be transferred on a SITD*/ usb_hal_ehci_set_sitd_transfer_state(sitd_ptr, EHCI_SITD_IOC_BIT_SET | \ (pg_select << EHCI_SITD_PAGE_SELECT_BIT_POS) | \ (length_scheduled << EHCI_SITD_TRANSFER_LENGTH_BIT_POS) | \ EHCI_SITD_STATUS_ACTIVE); /* Depending upon if this SITD will carry less than 188 bytes, we have to code the TP bits*/ tp_bits = (uint8_t)((length_scheduled < EHCI_START_SPLIT_MAX_BUDGET) ? EHCI_SITD_TP_ALL : EHCI_SITD_TP_BEGIN); /* next buffer pointer is at 4096 bytes ahead */ usb_hal_ehci_set_sitd_length_scheduled(sitd_ptr, length_scheduled); usb_hal_ehci_set_sitd_buffer_ptr_0(sitd_ptr, (uint32_t)buff_ptr); usb_hal_ehci_set_sitd_buffer_ptr_1(sitd_ptr,(((uint32_t)buff_ptr + 4096) & 0xFFFFF000) | (uint32_t)tp_bits << EHCI_SITD_TP_BIT_POS | pipe_descr_ptr->no_of_start_split); /* move buffer pointer */ buff_ptr += length_scheduled; /********************************************************************** SITD ready. We store it in out list of SITDs **********************************************************************/ struct_to_link_list[next] = (uint32_t)sitd_ptr; next++; } /*end for loop*/ /********************************************************************** List ready. We keep the SITD pointers in our active list of SITds **********************************************************************/ USB_EHCI_Host_unlock(); /********************************************************************** List ready. We link it into periodic list now. **********************************************************************/ status = _usb_ehci_link_structure_in_periodic_list(handle,pipe_descr_ptr,struct_to_link_list,next); if(status == USB_OK) { usb_host_ptr->full_speed_iso_queue_active = TRUE; } return status; } /* EndBody */ #endif //USBCFG_EHCI_MAX_SITD_DESCRS #if USBCFG_EHCI_MAX_ITD_DESCRS || USBCFG_EHCI_MAX_SITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_add_xfer_to_periodic_schedule_list * Returned Value : USB_OK or error * Comments : * Queue the packet in the EHCI hardware Periodic schedule list *END*-----------------------------------------------------------------*/ uint32_t _usb_ehci_add_isochronous_xfer_to_periodic_schedule_list ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr, /* [IN] the transfer parameters struct */ tr_struct_t* pipe_tr_ptr ) { /* Body */ uint32_t cmd_val,sts_val; usb_status status; uint8_t speed; usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); /**************************************************************************** If it is a high-speed device we use ITds for transfer and if it is a full speed device, we use SITds for transfers. ****************************************************************************/ if(speed == USB_SPEED_HIGH) { #if USBCFG_EHCI_MAX_ITD_DESCRS status = _usb_ehci_add_ITD(handle, pipe_descr_ptr, pipe_tr_ptr); #endif //USBCFG_EHCI_MAX_ITD_DESCRS } else { #if USBCFG_EHCI_MAX_SITD_DESCRS status = _usb_ehci_add_SITD(handle, pipe_descr_ptr, pipe_tr_ptr); #endif //USBCFG_EHCI_MAX_SITD_DESCRS } if(status != USB_OK) { return status; } /**************************************************************************** if periodic schedule is not already enabled, enable it. ****************************************************************************/ sts_val = usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase); if(!(sts_val & EHCI_STS_PERIODIC_SCHEDULE)) { cmd_val = usb_hal_ehci_get_usb_cmd(usb_host_ptr->usbRegBase); /**************************************************************************** write the address of the periodic list in to the periodic base register ****************************************************************************/ usb_hal_ehci_set_periodic_list_base_addr(usb_host_ptr->usbRegBase,(uint32_t) usb_host_ptr->periodic_list_base_addr); /**************************************************************************** wait until we can enable the periodic schedule. ****************************************************************************/ while((cmd_val & EHCI_USBCMD_PERIODIC_SCHED_ENABLE) != (usb_hal_ehci_get_usb_interrupt_status(usb_host_ptr->usbRegBase) & EHCI_STS_PERIODIC_SCHEDULE)) { } /**************************************************************************** enable the schedule now. ****************************************************************************/ usb_hal_ehci_set_usb_cmd(usb_host_ptr->usbRegBase, (cmd_val | EHCI_USBCMD_PERIODIC_SCHED_ENABLE)); } return USB_OK; } /* EndBody */ #endif //USBCFG_EHCI_MAX_ITD_DESCRS || USBCFG_EHCI_MAX_SITD_DESCRS #if USBCFG_EHCI_MAX_ITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_itd_tr_complete * Returned Value : None * Comments : * Search the ITD list to see which ITD had finished and * Process the interrupt. * *END*-----------------------------------------------------------------*/ void _usb_ehci_process_itd_tr_complete ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; ehci_itd_struct_t* itd_ptr; ehci_pipe_struct_t* pipe_descr_ptr = NULL; tr_struct_t* pipe_tr_struct_ptr = NULL; uint32_t no_of_scheduled_slots; uint32_t status = 0; unsigned char *buffer_ptr = NULL; list_node_struct_t* node_ptr; list_node_struct_t* prev_node_ptr; list_node_struct_t* next_node_ptr; uint8_t transaction_number; bool pending_transaction; uint32_t length_transmitted; uint32_t *prev_link_ptr = NULL, *next_link_ptr = NULL; prev_link_ptr = prev_link_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; length_transmitted = 0; //UNUSED_ARGUMENT(prev_link_ptr) /****************************************************************** Search the ITD list starting from head till we find inactive nodes. Note that for Head there is no previous node so we can disntiguish it from rest of the list. ******************************************************************/ prev_node_ptr = node_ptr = usb_host_ptr->active_iso_itd_periodic_list_head_ptr; /* loop till current node is active or node is a head node*/ while (((prev_node_ptr->next_active) && (prev_node_ptr->next != NULL)) || ((node_ptr->prev == NULL) && (node_ptr->member != NULL))) { itd_ptr = (ehci_itd_struct_t*)node_ptr->member; #ifdef __USB_OTG__ #ifdef HOST_TESTING /* usb_otg_state_struct_ptr->status_STARTS[usb_otg_state_struct_ptr->LOG_ITD_COUNT] = EHCI_MEM_READ(itd_ptr->status); */ #endif #endif if (!itd_ptr) { continue; } pipe_tr_struct_ptr = (tr_struct_t*) itd_ptr->pipe_tr_descr_for_this_itd; pipe_descr_ptr = (ehci_pipe_struct_t*) itd_ptr->pipe_descr_for_this_itd; /* assume that no transactions are pending on this ITD */ pending_transaction = FALSE; no_of_scheduled_slots = 0; /************************************************************** Check the status of every transaction inside the ITD. **************************************************************/ for(transaction_number = 0; transaction_number < 8; transaction_number++) { /************************************************************** Note that each iteration of this loop checks the micro frame number on which transaction is scheduled. If a micro frame was not allocated for this pipe, we don't need to check it. But caution is that, there could be a transaction that was too small and even though many bandwidth slots are available but this transaction was finished only in 1 of the slots. Thus we also keep a check of how many transactions were allocated for this ITD. **************************************************************/ if ((pipe_descr_ptr->bwidth_slots[transaction_number]) && (no_of_scheduled_slots < itd_ptr->number_of_transactions)) { no_of_scheduled_slots++; status = usb_hal_ehci_get_transcation_status_ctl_list(itd_ptr, transaction_number) & EHCI_ITD_STATUS; /* if transaction is not active and IOC was set we look in to it else we move on */ if ((!(status & EHCI_ITD_STATUS_ACTIVE)) && (usb_hal_ehci_get_transcation_status_ctl_list(itd_ptr, transaction_number) & EHCI_ITD_IOC_BIT)) { length_transmitted += (itd_ptr->tr_status_ctl_list[transaction_number] & EHCI_ITD_LENGTH_TRANSMITTED) >> EHCI_ITD_LENGTH_BIT_POS; } /* if IOC is set and status is active, we have a pending transaction */ else if ((status & EHCI_ITD_STATUS_ACTIVE) && (usb_hal_ehci_get_transcation_status_ctl_list(itd_ptr, transaction_number) & EHCI_ITD_IOC_BIT)) { /* This means that this ITD has a pending transaction */ pending_transaction = TRUE; break; } } } /* If this ITD is done with all transactions, time to free it */ if(!pending_transaction) { /* if we are freeing a head node, we move node_ptr to next head or else we move normally*/ USB_EHCI_Host_lock(); if(node_ptr == usb_host_ptr->active_iso_itd_periodic_list_head_ptr) { /*free this node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_itd_periodic_list_head_ptr, usb_host_ptr->active_iso_itd_periodic_list_tail_ptr, node_ptr) prev_node_ptr = node_ptr = usb_host_ptr->active_iso_itd_periodic_list_head_ptr; } else { /*save next node */ next_node_ptr = node_ptr->next; /*free current node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_itd_periodic_list_head_ptr, usb_host_ptr->active_iso_itd_periodic_list_tail_ptr, node_ptr) /*move to next node now */ node_ptr = next_node_ptr; prev_node_ptr = node_ptr->prev; } #ifdef __USB_OTG__ #ifdef HOST_TESTING usb_otg_state_struct_ptr->status[usb_otg_state_struct_ptr->LOG_ITD_COUNT] = status; USB_mem_copy((uchar_ptr)itd_ptr, &usb_otg_state_struct_ptr->LOG_INTERRUPT_ITDS[usb_otg_state_struct_ptr->LOG_ITD_COUNT] ,8); usb_otg_state_struct_ptr->LOG_ITD_COUNT++; if(usb_otg_state_struct_ptr->LOG_ITD_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_ITD_COUNT = 0; #endif #endif /*remove the ITD from periodic list */ prev_link_ptr = next_link_ptr = itd_ptr->frame_list_ptr; /*iterate the list while we find valid pointers (1 means invalid pointer) */ while((!((uint32_t)next_link_ptr & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT)) && (!(EHCI_MEM_READ(*next_link_ptr) & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT))) { /*if a pointer matches our ITD we remove it from list*/ if((EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) == (uint32_t) itd_ptr) { EHCI_MEM_WRITE(*next_link_ptr, usb_hal_ehci_get_itd_next_link_pointer(itd_ptr)) break; } prev_link_ptr = next_link_ptr; next_link_ptr = (uint32_t *) (EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); } /* subtract on how many ITDs are pending from this transfer */ pipe_tr_struct_ptr->no_of_itds_sitds -= 1; /* if all ITDS are served free the TR INDEX */ if(pipe_tr_struct_ptr->no_of_itds_sitds == 0) { /* Mark TR as unused so that next request can use it */ pipe_tr_struct_ptr->tr_index = 0; } /* get buffer */ if (pipe_descr_ptr->common.direction == USB_SEND) { buffer_ptr = pipe_tr_struct_ptr->tx_buffer; } else { buffer_ptr = pipe_tr_struct_ptr->rx_buffer; } /* free the ITD used */ _usb_ehci_free_ITD((usb_host_handle)usb_host_ptr, itd_ptr); USB_EHCI_Host_unlock(); if (_usb_host_unlink_tr(pipe_descr_ptr, pipe_tr_struct_ptr) != USB_OK) { #if _DEBUG USB_PRINTF("_usb_host_unlink_tr in _usb_ehci_process_qh_list_tr_complete failed\n"); #endif } if (pipe_tr_struct_ptr->callback != NULL) { pipe_tr_struct_ptr->callback( (void *)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer_ptr, length_transmitted, status); } } else { /* move to next ITD in the list */ prev_node_ptr = node_ptr; node_ptr = node_ptr->next; } }/* end while loop */ } /* Endbody */ #endif //USBCFG_EHCI_MAX_ITD_DESCRS #if USBCFG_EHCI_MAX_SITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_process_sitd_tr_complete * Returned Value : None * Comments : * Search the SITD list to see which SITD had finished and * Process the interrupt. * *END*-----------------------------------------------------------------*/ void _usb_ehci_process_sitd_tr_complete ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; ehci_sitd_struct_t* sitd_ptr; ehci_pipe_struct_t* pipe_descr_ptr = NULL; tr_struct_t* pipe_tr_struct_ptr = NULL; uint32_t status = 0; unsigned char *buffer_ptr = NULL; list_node_struct_t* node_ptr; list_node_struct_t* prev_node_ptr; list_node_struct_t* next_node_ptr; uint32_t length_scheduled, length_remaining; uint32_t *prev_link_ptr = NULL, *next_link_ptr = NULL; prev_link_ptr = prev_link_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; //UNUSED_ARGUMENT(prev_link_ptr) /****************************************************************** Search the SITD list starting from head till we find inactive nodes. Note that for Head there is no previous node so we can disntiguish it from rest of the list. ******************************************************************/ prev_node_ptr = node_ptr = usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; /* loop till current node is active or node is a head node*/ while (((prev_node_ptr->next_active) && ((prev_node_ptr->next != NULL))) || ((node_ptr->prev == NULL) && (node_ptr->member != NULL))) { sitd_ptr = (ehci_sitd_struct_t*)node_ptr->member; pipe_tr_struct_ptr = (tr_struct_t*) sitd_ptr->pipe_tr_descr_for_this_sitd; pipe_descr_ptr = (ehci_pipe_struct_t*) sitd_ptr->pipe_descr_for_this_sitd; /*grab the status and check it */ status = usb_hal_ehci_get_sitd_transfer_state(sitd_ptr) & EHCI_SITD_STATUS; /* if transaction is not active we look in to it else we move on */ if(!(status & EHCI_SITD_STATUS_ACTIVE)) { USB_EHCI_Host_lock(); /********************************************************************* Since status is Non active for this SITD, time to delete it. *********************************************************************/ /* if we are freeing a head node, we move node_ptr to next head or else we move normally */ if(node_ptr == usb_host_ptr->active_iso_sitd_periodic_list_head_ptr) { /*free this node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_sitd_periodic_list_head_ptr, usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr, node_ptr) prev_node_ptr = node_ptr = usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; } else { /*save next node */ next_node_ptr = node_ptr->next; /*free current node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_sitd_periodic_list_head_ptr, usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr, node_ptr) /*move to next node now */ node_ptr = next_node_ptr; prev_node_ptr = node_ptr->prev; } if (_usb_host_unlink_tr(pipe_descr_ptr, pipe_tr_struct_ptr) != USB_OK) { #if _DEBUG USB_PRINTF("_usb_host_unlink_tr in _usb_ehci_process_qh_list_tr_complete failed\n"); #endif } /* send callback to app with the status*/ if (pipe_tr_struct_ptr->callback != NULL) { length_scheduled = usb_hal_ehci_get_sitd_length_scheduled(sitd_ptr); length_remaining =((usb_hal_ehci_get_sitd_transfer_state(sitd_ptr) & EHCI_SITD_LENGTH_TRANSMITTED) >> 16); if (pipe_descr_ptr->common.direction == USB_SEND) { buffer_ptr = pipe_tr_struct_ptr->tx_buffer; } else { buffer_ptr = pipe_tr_struct_ptr->rx_buffer; } pipe_tr_struct_ptr->callback( (void *)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer_ptr, length_scheduled - length_remaining, status); } #ifdef __USB_OTG__ #ifdef HOST_TESTING usb_otg_state_struct_ptr->status[usb_otg_state_struct_ptr->LOG_SITD_COUNT] = status; USB_mem_copy((uchar_ptr)sitd_ptr, &usb_otg_state_struct_ptr->LOG_INTERRUPT_SITDS[usb_otg_state_struct_ptr->LOG_SITD_COUNT] ,44); usb_otg_state_struct_ptr->LOG_SITD_COUNT++; if(usb_otg_state_struct_ptr->LOG_SITD_COUNT > HOST_LOG_MOD) usb_otg_state_struct_ptr->LOG_SITD_COUNT = 0; #endif #endif /*remove the SITD from periodic list, TODO: remove prev_link_ptr variable */ prev_link_ptr = next_link_ptr = sitd_ptr->frame_list_ptr; /*iterate the list while we find valid pointers (1 means invalid pointer) */ while((!((uint32_t)next_link_ptr & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT)) && (!(EHCI_MEM_READ(*next_link_ptr) & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT))) { /*if a pointer matches our SITD we remove it from list*/ if((EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) == (uint32_t) sitd_ptr) { EHCI_MEM_WRITE(*next_link_ptr, usb_hal_ehci_get_sitd_next_link_pointer(sitd_ptr)) break; } prev_link_ptr = next_link_ptr; next_link_ptr = (uint32_t *) (EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); } /* free the SITD used */ _usb_ehci_free_SITD((usb_host_handle)usb_host_ptr, sitd_ptr); USB_EHCI_Host_unlock(); /* subtract on how many SITDs are pending from this transfer */ pipe_tr_struct_ptr->no_of_itds_sitds -= 1; /* if all SITDS are served free the TR INDEX */ if(pipe_tr_struct_ptr->no_of_itds_sitds == 0) { /* Mark TR as unused so that next request can use it */ pipe_tr_struct_ptr->tr_index = 0; } } /* else move on to the next node in the queue */ else { prev_node_ptr = node_ptr; node_ptr = node_ptr->next; } }/* end while loop */ } /* Endbody */ #endif //USBCFG_EHCI_MAX_SITD_DESCRS #if USBCFG_EHCI_MAX_ITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_ITD * Returned Value : void * Comments : * Enqueues an ITD onto the free ITD ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_free_ITD ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the ITD to enqueue */ ehci_itd_struct_t* itd_ptr ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); /* ** Add the ITD to the free ITD queue (linked via PRIVATE) and ** increment the tail to the next descriptor */ EHCI_ITD_QADD(usb_host_ptr->itd_head, usb_host_ptr->itd_tail, (ehci_itd_struct_t*)itd_ptr); usb_host_ptr->itd_entries++; USB_EHCI_Host_unlock(); } /* Endbody */ #endif //USBCFG_EHCI_MAX_ITD_DESCRS #if USBCFG_EHCI_MAX_SITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_free_SITD * Returned Value : void * Comments : * Enqueues an SITD onto the free SITD ring. * *END*-----------------------------------------------------------------*/ void _usb_ehci_free_SITD ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* [IN] the SITD to enqueue */ ehci_sitd_struct_t* sitd_ptr ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /* ** This function can be called from any context, and it needs mutual ** exclusion with itself. */ USB_EHCI_Host_lock(); /* ** Add the SITD to the free SITD queue (linked via PRIVATE) and ** increment the tail to the next descriptor */ EHCI_SITD_QADD(usb_host_ptr->sitd_head, usb_host_ptr->sitd_tail, (ehci_sitd_struct_t*)sitd_ptr); usb_host_ptr->sitd_entries++; USB_EHCI_Host_unlock(); } /* Endbody */ #endif //USBCFG_EHCI_MAX_SITD_DESCRS /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_close_isochronous_pipe * Returned Value : None * Comments : * Close the Iso pipe and update the bandwidth list. Here are the notes. In EHCI, closing an ISO pipe involves removing the ITD or SITD from the periodic list to make sure that none of the frames refer to this any more. *END*-----------------------------------------------------------------*/ void _usb_ehci_close_isochronous_pipe ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The pipe descriptor to queue */ ehci_pipe_struct_t* pipe_descr_ptr ) { usb_ehci_host_state_struct_t* usb_host_ptr; ehci_itd_struct_t* itd_ptr; ehci_sitd_struct_t* sitd_ptr = NULL; list_node_struct_t* node_ptr; list_node_struct_t* next_node_ptr; list_node_struct_t* prev_node_ptr = NULL; tr_struct_t* pipe_tr_struct_ptr = NULL; uint32_t *prev_link_ptr=NULL, *next_link_ptr=NULL; uint8_t *buffer; uint8_t speed; speed = usb_host_dev_mng_get_speed(pipe_descr_ptr->common.dev_instance); prev_node_ptr = prev_node_ptr; //UNUSED_ARGUMENT(prev_node_ptr) usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; /**************************************************************************** if this is a HS pipe, search ITDs or else search SITD list to free them. ****************************************************************************/ if(speed == USB_SPEED_HIGH) { #if USBCFG_EHCI_MAX_ITD_DESCRS prev_node_ptr = node_ptr = usb_host_ptr->active_iso_itd_periodic_list_head_ptr; /* loop until we find an invalid node or if this is a head node*/ while (node_ptr->member != NULL) { itd_ptr = (ehci_itd_struct_t*)node_ptr->member; pipe_tr_struct_ptr = (tr_struct_t*)itd_ptr->pipe_tr_descr_for_this_itd; //pipe_descr_ptr = (ehci_pipe_struct_t*) itd_ptr->pipe_descr_for_this_sitd; if(itd_ptr->pipe_descr_for_this_itd == pipe_descr_ptr) { /* if we are freeing a head node, we move node_ptr to next head or else we move normally*/ if(node_ptr == usb_host_ptr->active_iso_itd_periodic_list_head_ptr) { /*free this node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_itd_periodic_list_head_ptr, usb_host_ptr->active_iso_itd_periodic_list_tail_ptr, node_ptr) prev_node_ptr = node_ptr = usb_host_ptr->active_iso_itd_periodic_list_head_ptr; } else { /*save next node */ next_node_ptr = node_ptr->next; /*free current node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_itd_periodic_list_head_ptr, usb_host_ptr->active_iso_itd_periodic_list_tail_ptr, node_ptr) /*move to next node now */ node_ptr = next_node_ptr; prev_node_ptr = node_ptr->prev; } if (pipe_descr_ptr->common.direction == USB_SEND) { buffer = pipe_tr_struct_ptr->tx_buffer; } else { buffer = pipe_tr_struct_ptr->rx_buffer; } pipe_tr_struct_ptr->callback((void *)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer, 0, USBERR_TR_CANCEL); /*remove the ITD from periodic list */ prev_link_ptr = next_link_ptr = itd_ptr->frame_list_ptr; /*iterate the list while we find valid pointers (1 means invalid pointer) */ while(!(EHCI_MEM_READ(*next_link_ptr) & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT)) { /*if a pointer matches our ITD we remove it from list*/ if((EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) == (uint32_t) itd_ptr) { EHCI_MEM_WRITE(*prev_link_ptr,usb_hal_ehci_get_itd_next_link_pointer(itd_ptr)) break; } prev_link_ptr = next_link_ptr; next_link_ptr = (uint32_t *) (EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); } /* free the ITD used */ _usb_ehci_free_ITD((usb_host_handle)usb_host_ptr, itd_ptr); /* subtract on how many ITDs are pending from this transfer */ pipe_tr_struct_ptr->no_of_itds_sitds -= 1; /* if all ITDS are served free the TR INDEX */ if(pipe_tr_struct_ptr->no_of_itds_sitds == 0) { /* Mark TR as unused so that next request can use it */ pipe_tr_struct_ptr->tr_index = 0; } } else { /* move to next ITD in the list */ prev_node_ptr = node_ptr; node_ptr = node_ptr->next; } } /* while */ #endif //USBCFG_EHCI_MAX_ITD_DESCRS } /* end if */ else { #if USBCFG_EHCI_MAX_SITD_DESCRS prev_node_ptr = node_ptr = usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; /* loop until we find an invalid node or if this is a head node*/ while (node_ptr->member != NULL) { sitd_ptr = (ehci_sitd_struct_t*)node_ptr->member; pipe_tr_struct_ptr = (tr_struct_t*)sitd_ptr->pipe_tr_descr_for_this_sitd; //pipe_descr_ptr = (ehci_pipe_struct_t*) sitd_ptr->pipe_descr_for_this_sitd; if(sitd_ptr->pipe_descr_for_this_sitd == pipe_descr_ptr) { /* if we are freeing a head node, we move node_ptr to next head or else we move normally*/ if(node_ptr == usb_host_ptr->active_iso_sitd_periodic_list_head_ptr) { /*free this node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_sitd_periodic_list_head_ptr, usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr, node_ptr) prev_node_ptr = node_ptr = usb_host_ptr->active_iso_sitd_periodic_list_head_ptr; } else { /*save next node */ next_node_ptr = node_ptr->next; /*free current node */ EHCI_QUEUE_FREE_NODE(usb_host_ptr->active_iso_sitd_periodic_list_head_ptr, usb_host_ptr->active_iso_sitd_periodic_list_tail_ptr, node_ptr) /*move to next node now */ node_ptr = next_node_ptr; prev_node_ptr = node_ptr->prev; } if (pipe_descr_ptr->common.direction == USB_SEND) { buffer = pipe_tr_struct_ptr->tx_buffer; } else { buffer = pipe_tr_struct_ptr->rx_buffer; } pipe_tr_struct_ptr->callback((void *)pipe_tr_struct_ptr, pipe_tr_struct_ptr->callback_param, buffer, 0, USBERR_TR_CANCEL); /*remove the SITD from periodic list */ prev_link_ptr = next_link_ptr = sitd_ptr->frame_list_ptr; /*iterate the list while we find valid pointers (1 means invalid pointer) */ while(!(EHCI_MEM_READ(*next_link_ptr) & EHCI_FRAME_LIST_ELEMENT_POINTER_T_BIT)) { /*if a pointer matches our SITD we remove it from list*/ if((EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK) == (uint32_t) sitd_ptr) { EHCI_MEM_WRITE(*prev_link_ptr,usb_hal_ehci_get_sitd_next_link_pointer(sitd_ptr)) break; } prev_link_ptr = next_link_ptr; next_link_ptr = (uint32_t *) (EHCI_MEM_READ(*next_link_ptr) & EHCI_HORIZ_PHY_ADDRESS_MASK); } /* free the ITD used */ _usb_ehci_free_SITD((usb_host_handle)usb_host_ptr, sitd_ptr); /* subtract on how many ITDs are pending from this transfer */ pipe_tr_struct_ptr->no_of_itds_sitds -= 1; /* if all ITDS are served free the TR INDEX */ if(pipe_tr_struct_ptr->no_of_itds_sitds == 0) { /* Mark TR as unused so that next request can use it */ pipe_tr_struct_ptr->tr_index = 0; } } else { /* move to next ITD in the list */ prev_node_ptr = node_ptr; node_ptr = node_ptr->next; } } /* while */ #endif //USBCFG_EHCI_MAX_SITD_DESCRS } if (speed == USB_SPEED_HIGH) { _usb_ehci_free_high_speed_bandwidth(handle, pipe_descr_ptr); } else { _usb_ehci_free_split_bandwidth(handle, pipe_descr_ptr); } #if 0 /******************************************************************** if status is fine we should free the slots now by updating the bandwidth list. ********************************************************************/ frame_list_bw_ptr = usb_host_ptr->periodic_frame_list_bw_ptr; if (speed == USB_SPEED_HIGH) { start = pipe_descr_ptr->start_uframe; for(i = start; i < usb_host_ptr->frame_list_size * 8; i+= interval) { /******************************************************************** We are allowed to use only 80% of a micro frame for periodic transfers. This is to provide space for Bulk and Control transfers. This means that if a micro frame slot exceeds .8 * 125 = 100 micro seconds, it is out of space. ********************************************************************/ uframe = i%8; frame_list_bw_ptr[i] -= pipe_descr_ptr->bwidth; if(frame_list_bw_ptr[i] == 0) pipe_descr_ptr->bwidth_slots[uframe] = 0; } } else { start = pipe_descr_ptr->start_frame; for(i = start; i < usb_host_ptr->frame_list_size; i+= interval) { /******************************************************************** Update the bandwidth in all frames in which transaction is scheduled. ********************************************************************/ for(j = 0; j < 8; j++) { if(pipe_descr_ptr->bwidth_slots[j]) { frame_list_bw_ptr[i*8+j] -= pipe_descr_ptr->bwidth; } } } } #endif return; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_shutdown * Returned Value : None * Comments : * Shutdown and de-initialize the VUSB1.1 hardware * *END*-----------------------------------------------------------------*/ usb_status usb_ehci_shutdown ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; #if USBCFG_EHCI_HOST_ENABLE_TASK if (ehci_host_task_id != (uint32_t)OS_TASK_ERROR) { OS_Task_delete(ehci_host_task_id); } #endif /* Disable interrupts */ usb_hal_ehci_disable_interrupts(usb_host_ptr->usbRegBase, USBHS_HOST_INTR_EN_BITS); /* Stop the controller */ usb_hal_ehci_initiate_detach_event(usb_host_ptr->usbRegBase); /* Reset the controller to get default values */ usb_hal_ehci_reset_controller(usb_host_ptr->usbRegBase); /********************************************************** ensure that periodic list in uninitilized. **********************************************************/ usb_host_ptr->itd_list_initialized = FALSE; usb_host_ptr->sitd_list_initialized = FALSE; usb_host_ptr->periodic_list_initialized = FALSE; usb_host_ptr->periodic_list_base_addr = NULL; /********************************************************** Free all memory occupied by active transfers **********************************************************/ if(NULL != usb_host_ptr->xtd_struct_base_addr) { /* Free all controller non-periodic specific memory */ OS_Mem_free((void *)usb_host_ptr->xtd_struct_base_addr); } #if EHCI_BANDWIDTH_RECORD_ENABLE if(NULL != usb_host_ptr->periodic_frame_list_bw_ptr) { /* Free all controller periodic frame list bandwidth and other specific memory */ OS_Mem_free((void *)usb_host_ptr->periodic_frame_list_bw_ptr); } #endif if(NULL != usb_host_ptr->active_iso_itd_periodic_list_head_ptr) { OS_Mem_free((void *)usb_host_ptr->active_iso_itd_periodic_list_head_ptr); } if(NULL != usb_host_ptr->active_iso_sitd_periodic_list_head_ptr) { OS_Mem_free((void *)usb_host_ptr->active_iso_sitd_periodic_list_head_ptr); } if(NULL != usb_host_ptr->pipe_descriptor_base_ptr) { OS_Mem_free(usb_host_ptr->pipe_descriptor_base_ptr); } #if USBCFG_EHCI_HOST_ENABLE_TASK if (NULL != usb_host_ptr->ehci_event_ptr) { OS_Event_destroy(usb_host_ptr->ehci_event_ptr); } #endif if (usb_host_ptr->mutex != NULL) { OS_Mutex_destroy(usb_host_ptr->mutex); } OS_Mem_free(usb_host_ptr); return USB_OK; } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_ehci_bus_control * Returned Value : None * Comments : * Bus control *END*-----------------------------------------------------------------*/ usb_status usb_ehci_bus_control ( /* [IN] the USB Host state structure */ usb_host_handle handle, /* The operation to be performed on the bus */ uint8_t bControl ) { /* Body */ switch(bControl) { case USB_ASSERT_BUS_RESET: break; case USB_ASSERT_RESUME: break; case USB_SUSPEND_SOF: _usb_ehci_bus_suspend(handle); break; case USB_DEASSERT_BUS_RESET: case USB_RESUME_SOF: case USB_DEASSERT_RESUME: default: break; } /* EndSwitch */ return USB_OK; } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_bus_suspend * Returned Value : None * Comments : * Suspend the bus *END*-----------------------------------------------------------------*/ void _usb_ehci_bus_suspend ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ uint8_t i, total_port_numbers; uint32_t port_control; usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; //param = (USB_EHCI_HOST_INIT_STRUCT_PTR) usb_host_ptr->INIT_PARAM; //cap_dev_ptr = (vusb20_reg_struct_t*) param->CAP_BASE_PTR; //dev_ptr = (vusb20_reg_struct_t*) usb_host_ptr->dev_ptr; total_port_numbers = (uint8_t)((usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & EHCI_HCS_PARAMS_N_PORTS)); USB_EHCI_Host_lock(); /* Suspend all ports */ for (i=0;i<total_port_numbers;i++) { port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); if (port_control & EHCI_PORTSCX_PORT_ENABLE) { port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, (port_control | EHCI_PORTSCX_PORT_SUSPEND)); } /* Endif */ } /* Endfor */ /* Stop the controller SGarg: This should not be done. If the controller is stopped, we will get no attach or detach interrupts and this will stop all operatings including the OTG state machine which is still running assuming that Host is alive. EHCI_REG_CLEAR_BITS(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,EHCI_CMD_RUN_STOP) */ USB_EHCI_Host_unlock(); } /* EndBody */ /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_ehci_bus_resume * Returned Value : None * Comments : * Resume the bus *END*-----------------------------------------------------------------*/ void _usb_ehci_bus_resume ( /* [IN] the USB Host state structure */ usb_host_handle handle ) { /* Body */ uint8_t i, total_port_numbers; uint32_t port_control; usb_ehci_host_state_struct_t* usb_host_ptr; usb_host_ptr = (usb_ehci_host_state_struct_t*)handle; total_port_numbers = (uint8_t)(usb_hal_ehci_get_hcsparams(usb_host_ptr->usbRegBase) & EHCI_HCS_PARAMS_N_PORTS); USB_EHCI_Host_lock(); /* Resume all ports */ for (i=0;i<total_port_numbers;i++) { port_control = usb_hal_ehci_get_port_status(usb_host_ptr->usbRegBase); if (port_control & EHCI_PORTSCX_PORT_ENABLE) { port_control &= (uint32_t)(~(uint32_t)EHCI_PORTSCX_W1C_BITS); usb_hal_ehci_set_port_status(usb_host_ptr->usbRegBase, (port_control | EHCI_PORTSCX_PORT_FORCE_RESUME)); } /* Endif */ } /* Endfor */ /* S Garg: This should not be done. See comments in suspend. Restart the controller EHCI_REG_SET_BITS(dev_ptr->REGISTERS.OPERATIONAL_HOST_REGISTERS.USB_CMD,EHCI_CMD_RUN_STOP) */ USB_EHCI_Host_unlock(); } /* EndBody */ #endif /* EOF */
<filename>jackrabbit-core/src/main/java/org/apache/jackrabbit/core/nodetype/xml/NodeTypeWriter.java<gh_stars>1-10 /* * 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.jackrabbit.core.nodetype.xml; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.List; import javax.jcr.NamespaceException; import javax.jcr.NamespaceRegistry; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.query.qom.QueryObjectModelConstants; import javax.jcr.version.OnParentVersionAction; import javax.xml.parsers.ParserConfigurationException; import org.apache.jackrabbit.commons.query.qom.Operator; import org.apache.jackrabbit.core.util.DOMBuilder; import org.apache.jackrabbit.core.value.InternalValueFactory; import org.apache.jackrabbit.spi.Name; import org.apache.jackrabbit.spi.QNodeDefinition; import org.apache.jackrabbit.spi.QNodeTypeDefinition; import org.apache.jackrabbit.spi.QPropertyDefinition; import org.apache.jackrabbit.spi.QValue; import org.apache.jackrabbit.spi.QValueConstraint; import org.apache.jackrabbit.spi.commons.conversion.DefaultNamePathResolver; import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver; import org.apache.jackrabbit.spi.commons.namespace.NamespaceResolver; import org.apache.jackrabbit.spi.commons.nodetype.constraint.ValueConstraint; import org.apache.jackrabbit.spi.commons.value.ValueFactoryQImpl; /** * Node type definition writer. This class is used to write the * persistent node type definition files used by Jackrabbit. */ public final class NodeTypeWriter { /** * Writes a node type definition file. The file contents are written * to the given output stream and will contain the given node type * definitions. The given namespace registry is used for namespace * mappings. * * @param xml XML output stream * @param registry namespace registry * @param types node types * @throws IOException if the node type definitions cannot * be written * @throws RepositoryException on repository errors */ public static void write( OutputStream xml, QNodeTypeDefinition[] types, NamespaceRegistry registry) throws IOException, RepositoryException { try { NodeTypeWriter writer = new NodeTypeWriter(registry); for (QNodeTypeDefinition type : types) { writer.addNodeTypeDef(type); } writer.write(xml); } catch (ParserConfigurationException e) { IOException e2 = new IOException(e.getMessage()); e2.initCause(e); throw e2; } catch (NamespaceException e) { throw new RepositoryException( "Invalid namespace reference in a node type definition", e); } } /** The node type document builder. */ private final DOMBuilder builder; /** The namespace resolver. */ private final NamePathResolver resolver; private final ValueFactoryQImpl factory; /** * Creates a node type definition file writer. The given namespace * registry is used for the XML namespace bindings. * * @param registry namespace registry * @throws ParserConfigurationException if the node type definition * document cannot be created * @throws RepositoryException if the namespace mappings cannot * be retrieved from the registry */ private NodeTypeWriter(NamespaceRegistry registry) throws ParserConfigurationException, RepositoryException { builder = new DOMBuilder(Constants.NODETYPES_ELEMENT); String[] prefixes = registry.getPrefixes(); for (String prefix : prefixes) { if (!"".equals(prefix)) { String uri = registry.getURI(prefix); builder.setAttribute("xmlns:" + prefix, uri); } } NamespaceResolver nsResolver = new AdditionalNamespaceResolver(registry); resolver = new DefaultNamePathResolver(nsResolver); factory = new ValueFactoryQImpl(InternalValueFactory.getInstance(), resolver); } /** * Builds a node type definition element under the current element. * * @param def node type definition * @throws RepositoryException if the default property values * cannot be serialized * @throws NamespaceException if the node type definition contains * invalid namespace references */ private void addNodeTypeDef(QNodeTypeDefinition def) throws NamespaceException, RepositoryException { builder.startElement(Constants.NODETYPE_ELEMENT); // simple attributes builder.setAttribute( Constants.NAME_ATTRIBUTE, resolver.getJCRName(def.getName())); builder.setAttribute( Constants.ISMIXIN_ATTRIBUTE, def.isMixin()); builder.setAttribute( Constants.ISQUERYABLE_ATTRIBUTE, def.isQueryable()); builder.setAttribute( Constants.ISABSTRACT_ATTRIBUTE, def.isAbstract()); builder.setAttribute( Constants.HASORDERABLECHILDNODES_ATTRIBUTE, def.hasOrderableChildNodes()); // primary item name Name item = def.getPrimaryItemName(); if (item != null) { builder.setAttribute( Constants.PRIMARYITEMNAME_ATTRIBUTE, resolver.getJCRName(item)); } else { builder.setAttribute(Constants.PRIMARYITEMNAME_ATTRIBUTE, ""); } // supertype declarations Name[] supertypes = def.getSupertypes(); if (supertypes.length > 0) { builder.startElement(Constants.SUPERTYPES_ELEMENT); for (Name supertype : supertypes) { builder.addContentElement( Constants.SUPERTYPE_ELEMENT, resolver.getJCRName(supertype)); } builder.endElement(); } // property definitions QPropertyDefinition[] properties = def.getPropertyDefs(); for (QPropertyDefinition property : properties) { addPropDef(property); } // child node definitions QNodeDefinition[] nodes = def.getChildNodeDefs(); for (QNodeDefinition node : nodes) { addChildNodeDef(node); } builder.endElement(); } /** * Builds a property definition element under the current element. * * @param def property definition * @throws RepositoryException if the default values cannot * be serialized * @throws NamespaceException if the property definition contains * invalid namespace references */ private void addPropDef(QPropertyDefinition def) throws NamespaceException, RepositoryException { builder.startElement(Constants.PROPERTYDEFINITION_ELEMENT); // simple attributes builder.setAttribute( Constants.NAME_ATTRIBUTE, resolver.getJCRName(def.getName())); builder.setAttribute( Constants.AUTOCREATED_ATTRIBUTE, def.isAutoCreated()); builder.setAttribute( Constants.MANDATORY_ATTRIBUTE, def.isMandatory()); builder.setAttribute( Constants.PROTECTED_ATTRIBUTE, def.isProtected()); builder.setAttribute( Constants.ONPARENTVERSION_ATTRIBUTE, OnParentVersionAction.nameFromValue(def.getOnParentVersion())); builder.setAttribute( Constants.MULTIPLE_ATTRIBUTE, def.isMultiple()); builder.setAttribute( Constants.ISFULLTEXTSEARCHABLE_ATTRIBUTE, def.isFullTextSearchable()); builder.setAttribute( Constants.ISQUERYORDERABLE_ATTRIBUTE, def.isQueryOrderable()); // TODO do properly... String[] qops = def.getAvailableQueryOperators(); if (qops != null && qops.length > 0) { List<String> ops = Arrays.asList(qops); List<String> defaultOps = Arrays.asList(Operator.getAllQueryOperators()); if (!ops.containsAll(defaultOps)) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < qops.length; i++) { if (i > 0) { sb.append(' '); } if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO)) { sb.append(Constants.EQ_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_NOT_EQUAL_TO)) { sb.append(Constants.NE_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN)) { sb.append(Constants.GT_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO)) { sb.append(Constants.GE_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN)) { sb.append(Constants.LT_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO)) { sb.append(Constants.LE_ENTITY); } else if (qops[i].equals(QueryObjectModelConstants.JCR_OPERATOR_LIKE)) { sb.append(Constants.LIKE_ENTITY); } } builder.setAttribute( Constants.AVAILABLEQUERYOPERATORS_ATTRIBUTE, sb.toString()); } } builder.setAttribute( Constants.REQUIREDTYPE_ATTRIBUTE, PropertyType.nameFromValue(def.getRequiredType())); // value constraints QValueConstraint[] constraints = def.getValueConstraints(); if (constraints != null && constraints.length > 0) { builder.startElement(Constants.VALUECONSTRAINTS_ELEMENT); for (QValueConstraint constraint : constraints) { ValueConstraint vc = ValueConstraint.create( def.getRequiredType(), constraint.getString()); builder.addContentElement( Constants.VALUECONSTRAINT_ELEMENT, vc.getDefinition(resolver)); } builder.endElement(); } // default values QValue[] defaults = def.getDefaultValues(); if (defaults != null && defaults.length > 0) { builder.startElement(Constants.DEFAULTVALUES_ELEMENT); for (QValue v : defaults) { builder.addContentElement( Constants.DEFAULTVALUE_ELEMENT, factory.createValue(v).getString()); } builder.endElement(); } builder.endElement(); } /** * Builds a child node definition element under the current element. * * @param def child node definition * @throws NamespaceException if the child node definition contains * invalid namespace references */ private void addChildNodeDef(QNodeDefinition def) throws NamespaceException { builder.startElement(Constants.CHILDNODEDEFINITION_ELEMENT); // simple attributes builder.setAttribute( Constants.NAME_ATTRIBUTE, resolver.getJCRName(def.getName())); builder.setAttribute( Constants.AUTOCREATED_ATTRIBUTE, def.isAutoCreated()); builder.setAttribute( Constants.MANDATORY_ATTRIBUTE, def.isMandatory()); builder.setAttribute( Constants.PROTECTED_ATTRIBUTE, def.isProtected()); builder.setAttribute( Constants.ONPARENTVERSION_ATTRIBUTE, OnParentVersionAction.nameFromValue(def.getOnParentVersion())); builder.setAttribute( Constants.SAMENAMESIBLINGS_ATTRIBUTE, def.allowsSameNameSiblings()); // default primary type Name type = def.getDefaultPrimaryType(); if (type != null) { builder.setAttribute( Constants.DEFAULTPRIMARYTYPE_ATTRIBUTE, resolver.getJCRName(type)); } else { builder.setAttribute(Constants.DEFAULTPRIMARYTYPE_ATTRIBUTE, ""); } // required primary types Name[] requiredTypes = def.getRequiredPrimaryTypes(); builder.startElement(Constants.REQUIREDPRIMARYTYPES_ELEMENT); for (Name requiredType : requiredTypes) { builder.addContentElement( Constants.REQUIREDPRIMARYTYPE_ELEMENT, resolver.getJCRName(requiredType)); } builder.endElement(); builder.endElement(); } /** * Writes the node type definition document to the given output stream. * * @param xml XML output stream * @throws IOException if the node type document could not be written */ private void write(OutputStream xml) throws IOException { builder.write(xml); } }
Medical professional involvement in smartphone ‘apps’ in dermatology antagonist production, activation of blockade of death receptor Fas (CD95), modulation of dendritic cell properties, increased expression and signalling through the inhibitory Fc receptor, Fc-c RIIB and enhanced steroid sensitivity. In our case, the exact mechanism of action of IVIG remains unclear. IVIG therapy may be considered as a new therapeutic option in resistant forms of IGDA. More case reports and trials are required to demonstrate the efficacy of this treatment in patients with IGDA.
Effect of seeding date, plant density, moisture availability and soil nitrogen fertility on maize kernel breakage susceptibility The objectives of this study were to evaluate seeding date, plant density, moisture availability, and soil N fertility effects on maize (Zea mays L.) kernel breakage susceptibility. Three hybrids within each of three relative maturity (RM) groups (90, 100, 110 days by Minnesota Relative Maturity Rating System) were grown in separate seeding date and plant density studies at Arlington, WI , in 1983 and 1984. Maize was seeded four times at 10-day intervals beginning 1 May. Average densities were 1.75,3.75,5.75, and 7.75 plants m⁻². Hybrids were also evaluated in separate irrigated and dryland trials at Hancock, WI . In a soil N study, grain samples were collected from an experiment at Arlington in which three N rates (0,11, and 22 g m⁻² were applied. Grain was combine-harvested at 25% kernel moisture (except at Hancock where moistures ranged from 21 to 32%) and dried at 82°C in 1983 and 60°C in 1984. Kernel breakage susceptibility, test weight and kernel weight, volume, density, and grain yield were measured. Delayed planting, high plant densities, and low applied N increased kernel breakage susceptibility. At Hancock, higher kernel breakage susceptibility occurred with irrigated- vs. dryland-produced maize. Kernel physical parameters measured were not closely related to kernel breakage susceptibility, except in the soil N study, where the largest range occurred for each variable. The 110-day RM hybrids had lower kernel breakage susceptibility than 90- and 100-day RM hybrids.
def disable_all_buttons(self): for child in self.control_frame.winfo_children(): child.config(state='disabled') child.unbind("<ButtonPress-1>") child.unbind("<ButtonRelease-1>") self.stop_button.config(state='normal') for child in self.target_frame.winfo_children(): child.config(state='disabled') child.unbind("<Return>") child.unbind("<Tab>") self.sync_button.config(state='disabled') for child in self.radiobutton_frame.winfo_children(): child.config(state='disabled')
/* * pgxc_separate_quals * Separate the quals into shippable and unshippable quals. Return the shippable * quals as return value and unshippable quals as local_quals */ static List * pgxc_separate_quals(List *quals, List **unshippabl_quals, bool has_aggs) { ListCell *l; List *shippabl_quals = NIL; bool tmp_has_aggs; bool *tmp_bool_ptr = has_aggs ? &tmp_has_aggs : NULL; *unshippabl_quals = NIL; foreach(l, quals) { Expr *clause = lfirst(l); if (pgxc_is_expr_shippable(clause, tmp_bool_ptr)) shippabl_quals = lappend(shippabl_quals, clause); else *unshippabl_quals = lappend(*unshippabl_quals, clause); } return shippabl_quals; }
<filename>src/ev3dev/sensors/index.ts export * from './ColorSensor' export * from './GyroSensor' export * from './I2CSensor' export * from './InfraredSensor' export * from './LightSensor' export * from './Sensor' export * from './SoundSensor' export * from './TouchSensor' export * from './UltrasonicSensor'
// ToFile saves an elk object to a file func ToFile(elk *Elk, filePath string) error { dataBytes, err := yaml.Marshal(elk) if err != nil { return err } file, err := os.OpenFile( filePath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return err } defer file.Close() _, err = file.Write(dataBytes) if err != nil { return err } return nil }
// skip skips test based on it and/or t func (o *Kb) skip() bool { if o.ItMin >= 0 { if o.it < o.ItMin { if o.Verb { io.Pf(". . . skipping because it < ItMin\n") } return true } } if o.ItMax >= 0 { if o.it > o.ItMax { if o.Verb { io.Pf(". . . skipping because it > ItMax\n") } return true } } if o.Tmin >= 0 { if o.t < o.Tmin { if o.Verb { io.Pf(". . . skipping because t > Tmin\n") } return true } } if o.Tmax >= 0 { if o.t > o.Tmax { if o.Verb { io.Pf(". . . skipping because t > Tmax\n") } return true } } if o.Verb { io.PfYel("\nit=%2d t=%v\n", o.it, o.t) } return false }
import {Inject, Injectable} from "@angular/core"; import {TdDialogService} from "@covalent/core/dialogs"; import "rxjs/add/operator/share"; import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs/Subject"; import {Subscription} from "rxjs/Subscription"; import {KyloNotification, NotificationService} from "../../../services/notification.service"; import {QueryEngine} from "../wrangler"; import {SaveRequest, SaveResponse, SaveResponseStatus} from "../wrangler/api/rest-model"; /** * Event for when a notification is removed. */ export interface RemoveEvent { id: string; notification: KyloNotification; } /** * Handles saving a transformation. */ @Injectable() export class VisualQuerySaveService { /** * Map of save id to notification. */ private notifications: { [k: string]: KyloNotification } = {}; /** * Subject for notification removal. */ private removeSubject = new Subject<RemoveEvent>(); constructor(private $mdDialog: TdDialogService, @Inject("NotificationService") private notificationService: NotificationService) { } /** * Removes the notification for the specified save identifier. */ removeNotification(id: string): void { if (this.notifications[id]) { this.notificationService.removeNotification(this.notifications[id]); delete this.notifications[id]; } } /** * Saves the specified transformation. * * @param request - destination * @param engine - transformation * @returns an observable to tracking the progress */ save(request: SaveRequest, engine: QueryEngine<any>): Observable<SaveResponse> { const save = engine.saveResults(request).share(); save.subscribe(response => this.onSaveNext(request, response), response => this.onSaveError(response)); return save; } /** * Subscribes to notification removal events. */ subscribeRemove(cb: (event: RemoveEvent) => void): Subscription { return this.removeSubject.subscribe(cb); } /** * Gets a notification message for the specified save request. */ private getMessage(request: SaveRequest) { if (request.tableName) { return "Saving transformation to " + request.tableName; } else { return "Preparing transformation for download"; } } /** * Handles save errors. */ private onSaveError(response: SaveResponse) { const notification = this.notifications[response.id]; if (notification) { // Add error notification const error = this.notificationService.addNotification("Failed to save transformation", "error"); if (response.message) { const message = (response.message.length <= 1024) ? response.message : response.message.substr(0, 1021) + "..."; error.callback = () => { this.$mdDialog.openAlert({ title: "Error saving the transformation", message: message, ariaLabel: "Save Failed", closeButton: "Got it!" }); }; } // Remove old notification this.notificationService.removeNotification(notification); delete this.notifications[response.id]; } } /** * Handle save progress. */ private onSaveNext(request: SaveRequest, response: SaveResponse) { // Find or create notification let notification = this.notifications[response.id]; if (notification == null && response.status !== SaveResponseStatus.SUCCESS) { notification = this.notificationService.addNotification(this.getMessage(request), "transform"); notification.loading = (response.status === SaveResponseStatus.PENDING); this.notifications[response.id] = notification; } // Add success notification if (response.status === SaveResponseStatus.SUCCESS) { if (request.tableName) { this.notificationService.addNotification("Transformation saved to " + request.tableName, "grid_on"); } else { const download = this.notificationService.addNotification("Transformation ready for download", "file_download"); download.callback = () => { window.open(response.location, "_blank"); this.removeNotification(download.id); this.removeSubject.next({id: response.id, notification: download}); }; this.notifications[response.id] = download; } // Remove old notification if (notification) { this.notificationService.removeNotification(notification); if (this.notifications[response.id] === notification) { delete this.notifications[response.id]; } } } } }
package com.code.controller; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.UUID; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.code.comm.GcdUtil; import com.code.comm.StringUtils; import com.code.model.FileBean; import com.code.model.FileUploadBean; import com.code.service.IFileImageService; import com.code.service.impl.UploadGoogleCloudServiceImp; import com.google.api.services.storage.Storage; import com.google.api.services.storage.model.StorageObject; @RestController @RequestMapping("/google_cloud") public class BucketController { @Autowired private IFileImageService iFileImage; @RequestMapping(value = "/upload_file", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Map<String,Object> test(MultipartHttpServletRequest request) throws GeneralSecurityException, IOException{ Storage storage = GcdUtil.getStorageConfig(); FileUploadBean ufile = new FileUploadBean(); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = request.getFile(itr.next()); String fileName = DateFormatUtils.format(new Date(), "yyyyMMdd") + "_"+ UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(mpf.getOriginalFilename()); StorageObject object = UploadGoogleCloudServiceImp.uploadFileAndSharePublicly(storage,mpf, "g9bay-file", fileName,mpf.getContentType()); ufile.setSize(mpf.getBytes().length); ufile.setRegdate(DateFormatUtils.format(new Date(), "yyyyMMddhhmmss")); ufile.setType(mpf.getContentType()); ufile.setRandname(fileName); HashMap<String,Object> result =new HashMap<String,Object>(); result.put("OJECT", object); result.put("OUT_REC",ufile); result.put("RANDNAME",fileName); return result; } @RequestMapping(value = "/remove_file", method = RequestMethod.POST) public @ResponseBody Map<String,Object> removeImage(@RequestBody FileBean obj) throws GeneralSecurityException, IOException{ Storage storage = GcdUtil.getStorageConfig(); String sms =""; if(isNullOrBlank(obj.getBucketName()) && isNullOrBlank(obj.getObjectName())){ sms ="Bucket name and object name is require! "; }else{ boolean object = false; object = UploadGoogleCloudServiceImp.deleteBlob(storage, obj.getBucketName(), obj.getObjectName()); if(object){ sms = "file is deleted"; }else{ sms = "file not found"; } } HashMap<String,Object> result =new HashMap<String,Object>(); result.put("SMS", sms); return result; } public static boolean isNullOrBlank(String s) { return (StringUtils.isNull(s) || s.trim().equals("")); } }
package vp.metagram.utils; import android.content.Context; import android.database.MatrixCursor; import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Locale; import vp.tools.io.iDBExport; import vp.tools.io.iDBMetagram; import static vp.metagram.general.functions.repeatSingleQuotes; import static vp.metagram.general.variables.dbMetagram; import static vp.metagram.general.variables.deviceSettings; import static vp.tools.io.iFileSystemUtils.GetExternalDir; public class ExportStatistics { public static void export(Context context, iDBMetagram db, String fileName, long IPK, long FIPK) throws IOException, GeneralSecurityException { if (FIPK < 0) { exportOrder(context,db,fileName,IPK); } else { String sqlText = String.format(Locale.ENGLISH,"Select IPK From Statistics_Orders Where FIPK = %d" , FIPK); MatrixCursor result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { exportOrder(context,db,fileName,result.getLong(result.getColumnIndex("IPK"))); result.moveToNext(); } } } } public static void exportOrder(Context context, iDBMetagram db, String fileName, long IPK) throws IOException, GeneralSecurityException { String dbName = fileName; String dbPath = GetExternalDir(context)+ File.separator + "Metagram" + File.separator + "exports" + File.separator; File dbDir = new File(dbPath); if (!dbDir.exists()) {dbDir.mkdirs();} iDBExport dbExport = new iDBExport(context,dbName,dbPath); for (String indexQuery : iDBExport.indexesQueries) { dbExport.execQuery(indexQuery); } String table; String[] fields; String[] values; String sqlText; MatrixCursor result; table = "Configuration"; fields = new String[] {"name","value"}; values = new String[] {"DeviceID", deviceSettings.DeviceUUI}; dbExport.insert(table,fields,values); sqlText = String.format(Locale.ENGLISH, "Select * from Statistics_Orders Where IPK = %d",IPK); result = db.selectQuery(sqlText); int OrderID = -1; if (result.moveToFirst()) { String creationDate = result.getString(result.getColumnIndex("CreationDate")); OrderID = result.getInt(result.getColumnIndex("StatOrderID")); sqlText = String.format(Locale.ENGLISH,"Insert Into Statistics_Orders(StatOrderID,FIPK, IPK, Username, UserInfo, ExecAgents, BoostSpeed, " + "stopFollowersTracking, stopPostTracking, autoRefresh, intervalInSeconds, CreationDate) " + "Values (%d, %d, %d, '%s', '%s', '%s',%d , %d, %d, %d, %d, datetime('%s') )", result.getInt(result.getColumnIndex("StatOrderID")), result.getLong(result.getColumnIndex("FIPK")), result.getLong(result.getColumnIndex("IPK")), result.getString(result.getColumnIndex("Username")), result.getString(result.getColumnIndex("UserInfo")), result.getString(result.getColumnIndex("ExecAgents")), result.getInt(result.getColumnIndex("BoostSpeed")), result.getInt(result.getColumnIndex("stopFollowersTracking")), result.getInt(result.getColumnIndex("stopPostTracking")), result.getInt(result.getColumnIndex("autoRefresh")), result.getInt(result.getColumnIndex("intervalInSeconds")), creationDate ); dbExport.execQuery(sqlText); } sqlText = String.format(Locale.ENGLISH, "Select * from Statistics_Jobs Where StatOrderID = %d and Status = 'done' Order By StatJobID ASC ",OrderID); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { insertJobToExportedDB(dbExport, result.getInt(result.getColumnIndex("StatJobID")), result.getInt(result.getColumnIndex("StatOrderID")), dbMetagram.AESCipher.decryptFromHexToString(result.getString(result.getColumnIndex("JobDescriptor"))), result.getString(result.getColumnIndex("ThreadName")), result.getInt(result.getColumnIndex("ThreadID")), result.getString(result.getColumnIndex("Status")), result.getLong(result.getColumnIndex("StartTime")), result.getLong(result.getColumnIndex("ReStartTime")), result.getLong(result.getColumnIndex("StopTime")), result.getLong(result.getColumnIndex("EndTime")), dbMetagram.AESCipher.decryptFromHexToString(result.getString(result.getColumnIndex("Result"))), result.getInt(result.getColumnIndex("Used")), result.getString(result.getColumnIndex("CreationDate")) ); result.moveToNext(); } } sqlText = String.format(Locale.ENGLISH, "Select * from Account_Info Where FIPK = %d ",IPK); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { insertAccountInfoToExportedDB(dbExport, result.getInt(result.getColumnIndex("ID")), result.getInt(result.getColumnIndex("StatisticsJobID")), result.getLong(result.getColumnIndex("FIPK")), result.getInt(result.getColumnIndex("FollowersNo")), result.getInt(result.getColumnIndex("FollowingNo")), result.getInt(result.getColumnIndex("PostsNo")), result.getInt(result.getColumnIndex("Used")), result.getString(result.getColumnIndex("CreationDate")) ); result.moveToNext(); } } sqlText = String.format(Locale.ENGLISH, "Select * from Rel_Follower Where FIPK = %d ",IPK); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { insertOthersToExportedDB(dbExport, result.getLong(result.getColumnIndex("FollowerIPK"))); insertFollowerRelationExportedDB(dbExport, result.getLong(result.getColumnIndex("FIPK")), result.getLong(result.getColumnIndex("FollowerIPK")), result.getInt(result.getColumnIndex("Status")), result.getInt(result.getColumnIndex("StatJobID")), result.getString(result.getColumnIndex("CreationDate")) ); result.moveToNext(); } } sqlText = String.format(Locale.ENGLISH, "Select * from Rel_Following Where FIPK = %d ",IPK); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { insertOthersToExportedDB(dbExport, result.getLong(result.getColumnIndex("FollowingIPK"))); insertFollowingRelationExportedDB(dbExport, result.getLong(result.getColumnIndex("FIPK")), result.getLong(result.getColumnIndex("FollowingIPK")), result.getInt(result.getColumnIndex("Status")), result.getInt(result.getColumnIndex("StatJobID")), result.getString(result.getColumnIndex("CreationDate")) ); result.moveToNext(); } } sqlText = String.format(Locale.ENGLISH, "Select * from Engagement Where FIPK = %d ",IPK); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { insertOthersToExportedDB(dbExport, result.getLong(result.getColumnIndex("EngageIPK"))); insertEngagementToExportedDB(dbExport, result.getLong(result.getColumnIndex("FIPK")), result.getLong(result.getColumnIndex("EngageIPK")), result.getInt(result.getColumnIndex("LikeNo")), result.getInt(result.getColumnIndex("CommentNo")), result.getInt(result.getColumnIndex("StatJobID")), result.getString(result.getColumnIndex("ChangeDate")) ); result.moveToNext(); } } sqlText = String.format(Locale.ENGLISH, "Select * from Posts Where FIPK = %d ",IPK); result = db.selectQuery(sqlText); if (result.moveToFirst()) { while ( !result.isAfterLast() ) { long MPK = result.getLong(result.getColumnIndex("MPK")); insertPostToExportedDB(dbExport, result.getLong(result.getColumnIndex("FIPK")), result.getLong(result.getColumnIndex("MPK")), result.getString(result.getColumnIndex("MiniLink")), result.getString(result.getColumnIndex("MID")), result.getInt(result.getColumnIndex("OrderID")), result.getString(result.getColumnIndex("PicUrl")), result.getInt(result.getColumnIndex("Status")), result.getInt(result.getColumnIndex("StatJobID")), result.getInt(result.getColumnIndex("PostType")), result.getString(result.getColumnIndex("CreationDate")) ); String postSqlText = String.format(Locale.ENGLISH, "Select * from Posts_Info Where FMPK = %d", MPK); MatrixCursor postResult = dbMetagram.selectQuery(postSqlText); if (postResult.moveToFirst()) { while ( !postResult.isAfterLast() ) { insertPostInfoToExportedDB(dbExport, postResult.getLong(postResult.getColumnIndex("FMPK")), postResult.getInt(postResult.getColumnIndex("StatJobID")), postResult.getInt(postResult.getColumnIndex("LikeNo")), postResult.getInt(postResult.getColumnIndex("CommentNo")), postResult.getInt(postResult.getColumnIndex("ViewNo")), postResult.getString(postResult.getColumnIndex("CreationDate")) ); postResult.moveToNext(); } } postSqlText = String.format(Locale.ENGLISH,"Select * from Rel_Like where FMPK = %d", MPK); postResult = dbMetagram.selectQuery(postSqlText); if (postResult.moveToFirst()) { while ( !postResult.isAfterLast() ) { insertOthersToExportedDB(dbExport, postResult.getLong(postResult.getColumnIndex("LikerIPK"))); insertLikeRelationExportedDB(dbExport, postResult.getLong(postResult.getColumnIndex("FMPK")), postResult.getLong(postResult.getColumnIndex("LikerIPK")), postResult.getInt(postResult.getColumnIndex("Status")), postResult.getInt(postResult.getColumnIndex("StatJobID")), postResult.getString(postResult.getColumnIndex("CreationDate")) ); postResult.moveToNext(); } } postSqlText = String.format(Locale.ENGLISH,"Select * from Rel_Comment where FMPK = %d", MPK); postResult = dbMetagram.selectQuery(postSqlText); if (postResult.moveToFirst()) { while ( !postResult.isAfterLast() ) { insertOthersToExportedDB(dbExport, postResult.getLong(postResult.getColumnIndex("CommenterIPK"))); insertCommentRelationExportedDB(dbExport, postResult.getLong(postResult.getColumnIndex("CPK")), postResult.getLong(postResult.getColumnIndex("FMPK")), postResult.getLong(postResult.getColumnIndex("CommenterIPK")), postResult.getString(postResult.getColumnIndex("CommentText")), postResult.getInt(postResult.getColumnIndex("Status")), postResult.getInt(postResult.getColumnIndex("StatJobID")), postResult.getString(postResult.getColumnIndex("CreationDate")) ); postResult.moveToNext(); } } result.moveToNext(); } } } public static void insertJobToExportedDB(iDBExport dbExport, int StatJobID, int StatOrderID, String JobDescriptor, String ThreadName, int ThreadID, String Status, long StartTime, long ReStartTime, long StopTime, long EndTime, String Result, int Used, String CreationDate) { String sqlText = String.format(Locale.ENGLISH," Insert Or Ignore Into Statistics_Jobs(StatJobID,StatOrderID,JobDescriptor,ThreadName,ThreadID,Status," + " StartTime, ReStartTime, StopTime, EndTime, Result, Used, CreationDate)" + " Values (%d, %d, '%s', '%s', %d, '%s'," + " %d, %d, %d, %d, '%s', %d, datetime('%s') )", StatJobID,StatOrderID,JobDescriptor, ThreadName, ThreadID, Status, StartTime, ReStartTime, StopTime, EndTime, Result, Used, CreationDate); dbExport.execQuery(sqlText); } public static void insertAccountInfoToExportedDB(iDBExport dbExport, int ID, int StatisticsJobID, long FIPK, int FollowersNo, int FollowingNo, int PostsNo, int Used, String CreationDate ) { String sqlText = String.format(Locale.ENGLISH," Insert Or Ignore Into Account_Info(ID, StatisticsJobID, FIPK, FollowersNo, FollowingNo, PostsNo, Used, CreationDate) " + " Values(%d, %d, %d, %d, %d, %d, %d, datetime('%s') )", ID, StatisticsJobID, FIPK, FollowersNo, FollowingNo, PostsNo, Used, CreationDate); dbExport.execQuery(sqlText); } public static void insertPostToExportedDB(iDBExport dbExport, long FIPK, long MPK, String MiniLink, String MID, int OrderID, String PicUrl, int Status, int StatJobID, int PostType, String CreationDate) { String sqlText = String.format(Locale.ENGLISH," Insert Or Ignore Into Posts(FIPK, MPK, MiniLink, MID, OrderID, PicUrl, Status, StatJobID, PostType, CreationDate) " + " Values (%d, %d, '%s', '%s', %d, '%s', %d, %d, %d, datetime('%s') ) ", FIPK, MPK, MiniLink, MID, OrderID, PicUrl, Status, StatJobID, PostType, CreationDate); dbExport.execQuery(sqlText); } public static void insertPostInfoToExportedDB(iDBExport dbExport, long FMPK, int StatJobID, int LikeNo, int CommentNo, int ViewNo, String CreationDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Posts_Info(FMPK, StatJobID, LikeNo, CommentNo, ViewNo, CreationDate) " + " Values(%d, %d, %d, %d, %d, datetime('%s') )", FMPK, StatJobID, LikeNo, CommentNo, ViewNo, CreationDate); dbExport.execQuery(sqlText); } public static void insertOthersToExportedDB(iDBExport dbExport, long IPK) throws IOException, GeneralSecurityException { String sqlText = String.format(Locale.ENGLISH, "Select * from Others Where IPK = %d",IPK); MatrixCursor result = dbMetagram.selectQuery(sqlText); if (result.moveToNext()) { String Username = result.getString(result.getColumnIndex("Username")); String PictureURL = result.getString(result.getColumnIndex("PictureURL")); sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Others(IPK, Username, PictureURL) " + " Values(%d, '%s', '%s')",IPK, Username, PictureURL); dbExport.execQuery(sqlText); } } public static void insertLikeRelationExportedDB(iDBExport dbExport, long FMPK, long LikerIPK, int Status, int StatJobID, String CreationDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Rel_Like(FMPK, LikerIPK, Status, StatJobID, CreationDate) " + " Values(%d, %d, %d, %d, datetime('%s') )", FMPK, LikerIPK, Status, StatJobID, CreationDate); dbExport.execQuery(sqlText); } public static void insertCommentRelationExportedDB(iDBExport dbExport, long CPK, long FMPK, long CommenterIPK, String CommentText, int Status, int StatJobID, String CreationDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Rel_Comment(CPK, FMPK, CommenterIPK, CommentText, Status, StatJobID, CreationDate) " + " Values(%d, %d, %d, '%s', %d, %d, datetime('%s') )", CPK, FMPK, CommenterIPK, repeatSingleQuotes(CommentText), Status, StatJobID, CreationDate ); dbExport.execQuery(sqlText); } public static void insertFollowerRelationExportedDB(iDBExport dbExport, long FIPK, long FollowerIPK, int Status, int StatJobID, String CreationDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Rel_Follower(FIPK, FollowerIPK, Status, StatJobID, CreationDate) " + " Values(%d, %d, %d, %d, datetime('%s') )", FIPK, FollowerIPK, Status, StatJobID, CreationDate); dbExport.execQuery(sqlText); } public static void insertFollowingRelationExportedDB(iDBExport dbExport, long FIPK, long FollowingIPK, int Status, int StatJobID, String CreationDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Rel_Following(FIPK, FollowingIPK, Status, StatJobID, CreationDate) " + " Values(%d, %d, %d, %d, datetime('%s') )", FIPK, FollowingIPK, Status, StatJobID, CreationDate); dbExport.execQuery(sqlText); } public static void insertEngagementToExportedDB(iDBExport dbExport, long FIPK, long EngageIPK, int LikeNo, int CommentNo, int StatJobID, String ChangeDate) { String sqlText = String.format(Locale.ENGLISH, " Insert Or Ignore Into Engagement(FIPK, EngageIPK, LikeNo, CommentNo, StatJobID, ChangeDate) " + " Values(%d, %d, %d, %d, %d, datetime('%s') )", FIPK, EngageIPK, LikeNo, CommentNo, StatJobID, ChangeDate); dbExport.execQuery(sqlText); } }
// DefaultRates returns the default rate set of the limiter. The only reason to // Provide this method is to facilitate testing. func (tl *TokenLimiter) DefaultRates() *RateSet { defaultRates := NewRateSet() for _, r := range tl.defaultRates.m { defaultRates.Add(r.period, r.average, r.burst) } return defaultRates }
def defaultEventHandler( bot, groupId, creatorId, user, text, dbAction, handledByExtension, event ): return
package action; public class Hex { // Converts a string of hex digits into a byte array of those digits static public byte[] toByteArr(String no) { byte[] number = new byte[no.length()/2]; int i; for (i=0; i<no.length(); i+=2) { int j = Integer.parseInt(no.substring(i,i+2), 16); number[i/2] = (byte)(j & 0x000000ff); } return number; } static public void printHex(byte[] b) {printHex(b, b.length);} static public void printHex(short[] b) {printHex(b, b.length);} static public void printHex(int[] b) {printHex(b, b.length);} static public void printHex(String label, byte[] b) {printHex(label, b, b.length);} static public void printHex(String label, short[] b) {printHex(label, b, b.length);} static public void printHex(String label, int[] b) {printHex(label, b, b.length);} static public String toHexF(String label, byte[] b) {return toHexF(label, b, b.length);} static public String toHexF(String label, short[] b) {return toHexF(label, b, b.length);} static public String toHexF(String label, int[] b) {return toHexF(label, b, b.length);} static public String toHexF(int[] b) {return toHexF(b, b.length);} static public String toHexF(short[] b) {return toHexF(b, b.length);} static public String toHexF(byte[] b) {return toHexF(b, b.length);} static public String toHex(byte[] b) {return toHex(b, b.length);} static public String toHex(short[] b) {return toHex(b, b.length);} static public String toHex(int[] b) {return toHex(b, b.length);} static public void printHex(String label, byte[] b, int len) { System.out.println(label); printHex(b, len); } static public void printHex(String label, short[] b, int len) { System.out.println(label); printHex(b, len); } static public void printHex(String label, int[] b, int len) { System.out.println(label); printHex(b, len); } static public void printHex(byte[] b, int len) {System.out.print(toHexF(b, len));} static public void printHex(short[] b, int len) {System.out.print(toHexF(b, len));} static public void printHex(int[] b, int len) {System.out.print(toHexF(b, len));} static public String toHexF(String label, int[] b, int len) { return label + "\n" + toHexF(b, len); } static public String toHexF(String label, short[] b, int len) { return label + "\n" + toHexF(b, len); } static public String toHexF(String label, byte[] b, int len) { return label + "\n" + toHexF(b, len); } static public String toHexF(byte[] b, int len) { StringBuffer s = new StringBuffer(""); int i; if (b==null) return "<null>"; for (i=0; i<len; i++) { s.append(" " + toHex(b[i])); if (i%16 == 15) s.append("\n"); else if (i% 8 == 7) s.append(" "); else if (i% 4 == 3) s.append(" "); } if (i%16 != 0) s.append("\n"); return s.toString(); } static public String toHexF(short[] b, int len) { StringBuffer s = new StringBuffer(""); int i; if (b==null) return "<null>"; for (i=0; i<len; i++) { s.append(" " + toHex(b[i])); if (i%16 == 7) s.append("\n"); else if (i% 4 == 3) s.append(" "); } if (i%8 != 0) s.append("\n"); return s.toString(); } static public String toHexF(int[] b, int len) { StringBuffer s = new StringBuffer(""); int i; if (b==null) return "<null>"; for (i=0; i<len; i++) { s.append(" " + toHex(b[i])); if (i%4 == 3) s.append("\n"); } if (i%4 != 0) s.append("\n"); return s.toString(); } static public String toHex(int[] b, int len) { if (b==null) return ""; StringBuffer s = new StringBuffer(""); int i; for (i=0; i<len; i++) s.append(toHex(b[i])); return s.toString(); } static public String toHex(short[] b, int len) { if (b==null) return ""; StringBuffer s = new StringBuffer(""); int i; for (i=0; i<len; i++) s.append(toHex(b[i])); return s.toString(); } static public String toHex(byte[] b, int len) { if (b==null) return ""; StringBuffer s = new StringBuffer(""); int i; for (i=0; i<len; i++) s.append(toHex(b[i])); return s.toString(); } static public String toHex(byte b) { Integer I = new Integer((((int)b) << 24) >>> 24); int i = I.intValue(); if ( i < (byte)16 ) return "0"+Integer.toString(i, 16); else return Integer.toString(i, 16); } static public String toHex(short i) { byte b[] = new byte[2]; b[0] = (byte)((i & 0xff00) >>> 8); b[1] = (byte)((i & 0x00ff) ); return toHex(b[0])+toHex(b[1]); } static public String toHex(int i) { byte b[] = new byte[4]; b[0] = (byte)((i & 0xff000000) >>> 24); b[1] = (byte)((i & 0x00ff0000) >>> 16); b[2] = (byte)((i & 0x0000ff00) >>> 8); b[3] = (byte)((i & 0x000000ff) ); return toHex(b[0])+toHex(b[1])+toHex(b[2])+toHex(b[3]); } }
This book is written for those who are in sympathy with the spirit in which it is written. This is not, I believe, the spirit of the main current of European and American civilization. The spirit of this civilization makes itself manifest in the industry, architecture and music of our time, in its fascism and socialism, and it is alien and uncongenial to the author. This is not a value judgment. It is not, it is true, as though he accepted what nowadays passes for architecture as architecture or did not approach what is called modern music with the greatest suspicion (though without under standing its language), but still, the disappearance of the arts does not justify judging disparagingly the human beings who make up this civilization. For in times like these, genuine strong characters simply leave the arts aside and turn to other things and somehow the worth of the individual man finds expression. Not, to be sure, in the way it would at a time of high culture. A culture is like a big organization which assigns each of its members a place where he can work in the spirit of the whole; and it is per fectly fair for his power to be measured by the contribution he succeeds in making to the whole enterprise. In an age without culture on the other hand forces become fragmented and the power of an individual man is used up in overcoming opposing forces and frictional resistances; it does not show in the distance he travels but perhaps only in the heat he generates in overcoming friction. But energy is still energy and even if the spectacle which our age affords us is not the formation of a great cultural work, with the best men contributing to the same great end, so much as the unimpressive spectacle of a crowd whose best members work for purely private ends, still we must not forget that the spectacle is not what matters.
/** * A No-op implementation of the {@link Instrumentation} interface that extracts all {@link ClassFileTransformer transformers} installed * onto the instance and appends the agent jar to the bootstrap class path. */ public class TransformerExtractor implements Instrumentation { @Delegate(excludes = TransformerExtractor.ExcludedListMethods.class) private final Instrumentation delegate; @Getter private static List<ClassFileTransformer> transformers = new ArrayList<>(); public TransformerExtractor(Instrumentation delegate) { this.delegate = delegate; } @Override public void addTransformer(ClassFileTransformer transformer, boolean canRetransform) { transformers.add(transformer); } @Override public void addTransformer(ClassFileTransformer transformer) { transformers.add(transformer); } @Override public boolean isRetransformClassesSupported() { return true; } @Override public boolean isRedefineClassesSupported() { return true; } @Override public void appendToBootstrapClassLoaderSearch(JarFile jarfile) { Injector.createInstrumentation().appendToBootstrapClassLoaderSearch(jarfile); } private abstract class ExcludedListMethods { public abstract void addTransformer(ClassFileTransformer transformer, boolean canRetransform); public abstract void appendToBootstrapClassLoaderSearch(JarFile jarfile); public abstract boolean isRedefineClassesSupported(); public abstract boolean isRetransformClassesSupported(); public abstract void addTransformer(ClassFileTransformer transformer); } }
<reponame>SemihGursoy96dus/ArtificialPBs package com.artificial.cachereader.meta; import com.artificial.cachereader.datastream.Stream; import com.artificial.cachereader.fs.CacheSource; public class OSRSReferenceTable extends ReferenceTable { public OSRSReferenceTable(final CacheSource cache, final int id) { super(cache, id); } @Override protected void decode(Stream data) { this.format = data.getUByte(); if (format >= MINIMUM_FORMAT_FOR_VERSION) { this.version = data.getInt(); } this.flags = data.getUByte(); final int count = data.getUShort(); final int[] ids = getIds(count); for (int id : ids) { entries.put(id, new ArchiveMeta(id)); } if ((flags & FLAG_IDENTIFIERS) == FLAG_IDENTIFIERS) { for (int id : ids) { entries.get(id).setIdentifier(data.getInt()); } } for (int id : ids) { entries.get(id).setCrc(data.getInt()); } if ((flags & FLAG_UNKNOWN_2) == FLAG_UNKNOWN_2) { for (int id : ids) { int value = data.getInt(); } } if ((flags & FLAG_WHIRLPOOL) == FLAG_WHIRLPOOL) { for (int id : ids) { final byte[] rawWhirlpool = entries.get(id).getAndInitializeWhirlpool(); data.getBytes(rawWhirlpool); } } if ((flags & FLAG_UNKNOWN_1) == FLAG_UNKNOWN_1) { for (int id : ids) { int value1 = data.getInt(); int value2 = data.getInt(); } } for (int id : ids) { entries.get(id).setVersion(data.getInt()); } for (int id : ids) { int childCount = data.getUShort(); entries.get(id).setChildCount(childCount); } final int[][] children = new int[ids.length][]; for (int i = 0; i < ids.length; ++i) { ArchiveMeta currentEntry = getEntry(ids[i]); int childCount = currentEntry.getChildCount(); children[i] = getIds(childCount); for (int id : children[i]) { currentEntry.addChild(id); } } if ((flags & FLAG_IDENTIFIERS) == FLAG_IDENTIFIERS) { for (int i = 0; i < ids.length; ++i) { for (int childId : children[i]) { entries.get(ids[i]).getChild(childId).setIdentifier(data.getInt()); } } } } private int[] getIds(int size) { int[] ids = new int[size]; int accumulator = 0; for (int i = 0; i < ids.length; ++i) { int delta = data.getUShort(); accumulator += delta; ids[i] = accumulator; } return ids; } }
/* Returns a fortune cookie fortune to the player */ public class FranklinCommandExecutor implements CommandExecutor { private TrollMachine plugin; private Logger logger = null; private List<UUID> allowedUsers = new ArrayList<UUID>(); public FranklinCommandExecutor(TrollMachine plugin) { this.plugin = plugin; // Store the plugin in situations where you need it. logger = plugin.getLogger(); plugin.getCommand("franklin").setExecutor(this); //allowedUsers.add(UUID.fromString("61d70a19-7338-4e31-a83d-b8c62ba6ec21")); //Entomo //allowedUsers.add(new UUID("558b43b7-173c-4951-bdbd-976adb246c09")); //injudicious allowedUsers.add(plugin.kaitlynUuid); //kaityizzy } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { //verify a player is sending this if (sender instanceof Player) { Player player = (Player)sender; //verify it's kelly, kaity, or me if(allowedUsers.contains(player.getUniqueId())) { // summon the Franklin Location playerLocation = player.getLocation(); // /summon chicken ~ ~ ~ {CustomName:"{\"text\":\"Franklin\"}"} plugin.runCommand(String.format("summon chicken %f %f %f {CustomName:\"{\\\"text\\\":\\\"Franklin\\\"}\"}", playerLocation.getX(), playerLocation.getY() + 3, playerLocation.getZ()), 20L); } else { //set player on Fire player.setFireTicks(7 * 20); // seconds * ticks per second } return true; } else { sender.sendMessage("You must be a player!"); return false; } } }
/** * Utility class for the P4Runtime driver. */ final class P4RuntimeDriverUtils { private static final String DEVICE_ID_PARAM = "device_id="; private static final Logger log = LoggerFactory.getLogger(P4RuntimeDriverUtils.class); private P4RuntimeDriverUtils() { // Hide constructor. } /** * Returns an instance of the interpreter implementation for this device, * null if an interpreter cannot be retrieved. * * @param handler driver handler * @return interpreter or null */ static PiPipelineInterpreter getInterpreter(DriverHandler handler) { final DeviceId deviceId = handler.data().deviceId(); final Device device = handler.get(DeviceService.class).getDevice(deviceId); if (device == null) { log.warn("Unable to find device {}, cannot get interpreter", deviceId); return null; } if (!device.is(PiPipelineInterpreter.class)) { log.warn("Unable to get interpreter for {}, missing behaviour", deviceId); return null; } return device.as(PiPipelineInterpreter.class); } static Long extractP4DeviceId(URI uri) { if (uri == null) { return null; } String[] segments = uri.getRawQuery().split("&"); try { for (String s : segments) { if (s.startsWith(DEVICE_ID_PARAM)) { return Long.parseUnsignedLong( URLDecoder.decode( s.substring(DEVICE_ID_PARAM.length()), "utf-8")); } } } catch (UnsupportedEncodingException e) { log.error("Unable to decode P4Runtime-internal device_id from URI {}: {}", uri, e.toString()); } catch (NumberFormatException e) { log.error("Invalid P4Runtime-internal device_id in URI {}: {}", uri, e.toString()); } log.error("Missing P4Runtime-internal device_id in URI {}", uri); return null; } }
def bilinear_interpolation_of_patch_registration(): print("Beginning bilinear_interpolation_of_patch_registration...") root = "../data/" reg1 = cv2.cvtColor(cv2.imread(root + "NG1_1.jpg"), code=cv2.COLOR_BGRA2RGBA) reg2 = cv2.cvtColor(cv2.imread(root + "OK1_1.jpg"), code=cv2.COLOR_BGRA2RGBA) h, _ = patchreg.alignFeatures(reg1, reg2) height, width = reg1.shape[:2] reg2_aligned = cv2.warpPerspective(reg2, h, (width, height)) w_shape = (1000, 1000, 4) w_step = (500, 500, 4) stack1 = np.concatenate((reg1, reg2_aligned), axis=-1) patches = view_as_windows(stack1, window_shape=w_shape, step=w_step) morphs = patchreg.calcPlateMorphs(patches) id_patches = patchreg.calc_id_patches(img_shape=reg2_aligned.shape, patch_size=1000) map_morphs = np.append(morphs, morphs[:, :, 1, None], axis=2) reg_patches = patchreg.applyMorphs(id_patches, map_morphs) print("reg_patches.shape=", reg_patches.shape) f_img_patches = patches[0:5, 0:5, :1] m_img_patches = patches[0:5, 0:5, 1:] reg_patches = reg_patches[0:5, 0:5, 1:, 500:1500, 500:1500, :] map_patches = reg_patches quilts = bilinear.quilter(map_patches) wquilts = bilinear.bilinear_wquilts(map_patches) qmaps = [q * w for q, w in zip(quilts, wquilts)] tt = qmaps[0] + qmaps[1] + qmaps[2] + qmaps[3] print("tt.shape=", tt.shape) summed = (qmaps[0] + qmaps[1] + qmaps[2] + qmaps[3]).reshape(2, 3000, 3000).astype(np.float32) f_img_quilts = bilinear.quilter(f_img_patches) f_img_recons = [q * w for q, w in zip(f_img_quilts, wquilts)] f_img_recon = (f_img_recons[0] + f_img_recons[1] + f_img_recons[2] + f_img_recons[3]).reshape(3000, 3000, 4).astype(np.uint8) m_img_quilts = bilinear.quilter(m_img_patches) m_img_recons = [q * w for q, w in zip(m_img_quilts, wquilts)] m_img_recon = (m_img_recons[0] + m_img_recons[1] + m_img_recons[2] + m_img_recons[3]).reshape(3000, 3000, 4).astype(np.uint8) print("m_img_recon.shape=", m_img_recon.shape) reg = cv2.remap(m_img_recon, summed[0], summed[1], interpolation=cv2.INTER_LINEAR) print("summed[0].shape=", summed[0].shape) print("summed[1].shape=", summed[1].shape) print("reg.shape=", reg.shape) for j in (0,1): for i, q in enumerate(quilts): plt.subplot(4, 4, i + 1) plt.title("Quilt %s" % i) plt.imshow(q[j].reshape(3000, 3000)) for i, wq in enumerate(wquilts): plt.subplot(4, 4, i + 5) plt.title("Weights %s" % i) plt.imshow(wq.reshape(3000, 3000)) for i, qm in enumerate(qmaps): plt.subplot(4, 4, i + 9) plt.title("Weighted Quilt %s" % i) plt.imshow(qm[j].reshape(3000, 3000)) plt.subplot(4, 4, 13) plt.title("Summed Weighted Quilts") plt.imshow(summed[j].reshape(3000, 3000)) plt.show() plt.gcf().set_size_inches(15, 15) plt.subplot(2, 2, 1) plt.title("Fixed Image") plt.imshow(f_img_recon) plt.grid() plt.subplot(2, 2, 2) plt.title("Moving Image") plt.imshow(m_img_recon) plt.grid() plt.subplot(2, 2, 3) plt.title("Without Patch Transforms") plt.imshow(viz.overlay([f_img_recon, m_img_recon])) plt.subplot(2, 2, 4) plt.title("With Patch Transforms") plt.imshow(viz.overlay([f_img_recon, reg])) plt.grid() plt.savefig(root + "bilinear_overlay.png") plt.show()
<gh_stars>1-10 export function dieOnError() { process.on("unhandledRejection", (reason, error) => { console.error(reason, error) process.exit(1) }) process.on("uncaughtException", error => { console.error(error) process.exit(1) }) }
Transporter-Mediated Drug–Drug Interactions with Oral Antidiabetic Drugs Uptake transporters (e.g., members of the SLC superfamily of solute carriers) and export proteins (e.g., members of the ABC transporter superfamily) are important determinants for the pharmacokinetics of drugs. Alterations of drug transport due to concomitantly administered drugs that interfere with drug transport may alter the kinetics of drug substrates. In vitro and in vivo studies indicate that many drugs used for the treatment of metabolic disorders and cardiovascular diseases (e.g., oral antidiabetic drugs, statins) are substrates for uptake transporters and export proteins expressed in the intestine, the liver and the kidney. Since most patients with type 2 diabetes receive more than one drug, transporter-mediated drug-drug interactions are important molecular mechanisms leading to alterations in oral antidiabetic drug pharmacokinetics with the risk of adverse drug reactions. This review focuses on uptake transporters of the SLCO/SLC21 (OATP) and SLC22 (OCT/OAT) family of solute carriers and export pumps of the ABC (ATP-binding cassette) transporter superfamily (especially P-glycoprotein) as well as the export proteins of the SLC47 (MATE) family and their role for transporter-mediated drug-drug interactions with oral antidiabetic drugs. Introduction Drug effects result from the interplay of multiple processes that influence drug absorption, metabolism and excretion as well as drug response. Although, in past decades, most studies have focused on the importance of drug metabolizing enzymes (e.g., cytochrome P450 monooxygenases), in recent years it became evident that, in addition, transport proteins located in distinct membrane domains are important for drug effects. Furthermore, since all metabolizing enzymes are located intracellularly, the uptake of drugs from the extracellular space across the plasma membrane into the cell is a prerequisite for subsequent metabolism. Generally, transport proteins can be subdivided into two major groups: uptake transporters, mediating the transport of substances and drugs from the outside into cells and export proteins responsible for the translocation of substances or drugs and drug metabolites out of cells. Figure 1. Uptake and export transporters involved in the intestinal absorption (enterocyte) and the hepatic (hepatocyte) and renal (renal epithelium) excretion of oral antidiabetic drugs. Uptake transporters (red): OATP = members of the organic anion transporting polypeptide family; OCT = members of the organic cation transporters; export transporters (blue): MRP2 = multidrug resistance protein 2; BSEP = bile salt export pump; BCRP = breast cancer resistance protein; P-gp = P-glycoprotein; MATE = members of the multidrug and toxin extrusion protein family. Efflux transporters mainly belong to the ATP-binding cassette (ABC) transporter family . These export pumps use energy derived from ATP hydrolysis to mediate substrate transport, often against a concentration gradient. Today, the human ABC superfamily consists of 49 different ABC transporters grouped into 6 different ABC families ). In the focus of the review are the ABCB family member P-glycoprotein (P-gp, ABCB1, ), the bile salt export pump BSEP (ABCB11) and the ABCG family member BCRP (ABCG2). P-gp and BCRP are expressed in enterocytes, hepatocytes and renal epithelial cells (Figure 1; ), whereas the expression of BSEP is restricted to hepatocytes (Figure 1; ). P-gp is the best characterized human drug transporter with a very broad substrate spectrum transporting a variety of different drugs . The ABCG family member BCRP, transports several endogenous compounds and is further capable of transporting a variety of different drugs including statins, calcium channel blockers and antivirals . The MATE transporter family (multidrug and toxin extrusion; gene symbol SLC47) consists of two members, MATE1 (SLC47A1) and MATE2 , which are localized to apical membrane domains. Whereas human MATE1 is strongly expressed in liver and kidney ( Figure 1) and to a lesser extent in several other tissues including skeletal muscle and testis , MATE2 is almost exclusively expressed in the kidney and localized in the luminal membrane of proximal tubular epithelial cells. In contrast to the ATP-driven ABC transporters, MATE proteins are electroneutral transporters using an oppositely directed proton gradient as driving force ( Figure 1). MATE1 and MATE2 have similar substrate and inhibitor specificities which overlap with those of OCTs. Endogenous substrates include organic cations (e.g., creatinine, guanidine) as well as clinically used drugs such as the antimalarial drug quinine , the antineoplastic agent cisplatin and the antidiabetic drug metformin . Detailed information on tissue distribution and substrate spectrum of the respective uptake and export transporters are summarized in the mentioned reviews . After administration and passage through the intestine, oral antidiabetic drugs have to be taken up from the portal venous blood via the basolateral membrane into hepatocytes before they are metabolized, cause drug effects via intrahepatic mechanisms or are transported back into the systemic circulation for extrahepatic effects. So far, little is known on the involvement of oral antidiabetic drugs into intestinal transporter-mediated drug-drug interactions . The characteristics of some widely used oral antidiabetic drugs together with their mode of action, metabolizing enzymes and transport proteins relevant for their membrane translocation or drug-drug interactions are summarized in Table 1. Since patients with type 2 diabetes are commonly treated with more than one drug (in most cases one or more oral antidiabetic drug and additionally a statin and an antihypertensive drug), it is essential to understand the molecular mechanisms underlying drug-drug interactions, which might cause changes in the effect or the pharmacokinetics of these drugs. Aside from metabolizing enzymes it is now well established that also modification of transport function is involved in these drug-drug interactions. Therefore, the role of transport proteins for drug-drug interactions with frequently used oral antidiabetic drugs presented in table 1 are in the focus of this review. Oral Antidiabetic Drugs and OATPs OATP1B1, OATP1B3 and OATP2B1 are localized in the basolateral membrane transporting substances and drugs from the portal venous blood into hepatocytes . OATP2B1 is further expressed in enterocytes and localized there to the luminal membrane mediating the uptake of substances and drugs from the intestinal lumen into the body . Several drugs have been identified as substrates for these OATPs including antibiotics and HMG-CoA-reductase inhibitors (statins) . Repaglinide was one of the first oral antidiabetic drugs shown to interact with hepatic OATPs. More indirect evidence for the involvement of OATP1B1 in repaglinide pharmacokinetics has been published by Niemi and colleagues . In this study they investigated the in vivo effect of cyclosporine, a known inhibitor of CYP3A4 and OATP1B1 on the pharmacokinetics and pharmacodynamics of repaglinide. They found that cyclosporine raised the plasma concentrations of concomitantly administered repaglinide probably by inhibiting its OATP1B1-mediated hepatic uptake and the subsequent metabolism by CYP3A4. In the same year the authors published a second in vivo study demonstrating that a polymorphic variant of the OATP1B1 protein is a major determinant of the interindividual variability in the pharmacokinetics of repaglinide. Interestingly, polymorphic variants of the OATP1B1 protein seem not to have a significant effect on nateglinide, the second frequently used meglitinide derivative and did not influence the pharmacokinetics of rosiglitazone or pioglitazone . Based on these observations, Bachmakov et al. investigated the effect of repaglinide and rosiglitazone on OATP1B1-, OATP1B3-and OATP2B1-mediated transport in vitro . Using stably transfected HEK cells recombinantly overexpressing these OATP family members and BSP as prototypic substrate, they found that both rosiglitazone and repaglinide inhibited the uptake mediated by these three transporters ( Figure 2). Both oral antidiabetic drugs showed a potent uptake inhibition with IC 50 values around 10 µM. In the same study they also used pravastatin as substrate for OATP1B1 and OATP1B3 and they demonstrated that repaglinide at a concentration of 10 µM significantly inhibited OATP1B1-mediated pravastatin uptake, whereas the pravastatin uptake by OATP1B3 was only slightly reduced and significantly inhibited only at a repaglinide concentration of 100 µM ( Figure 3). An interesting observation was made analyzing the effect of rosiglitazone on OATP1B1-and OATP1B3-mediated pravastatin uptake. Whereas repaglinide at a concentration of 10 µM inhibited the uptake, rosiglitazone at the same concentration stimulated pravastatin uptake by OATP1B1 and OATP1B3 and at the same time shows inhibition only at the highest tested concentration of 100 µM (Figure 3). This demonstrated that not only uptake inhibition but also stimulation of drug uptake could be a result of drug-drug interactions. Recently, this stimulatory effect has been analyzed in detail using pravastatin as substrate and non-steroidal anti-inflammatory drugs as interacting substances . In this study the authors showed that ibuprofen stimulated OATP1B1-and OATP1B3-mediated pravastatin uptake likely by an allosteric mechanism without being transported. In the case of rosiglitazone one can assume that at low concentrations the uptake of pravastatin can be stimulated by acting as allosteric modulator and that only at high substrate concentrations a competitive inhibition can be detected. However, the clinical relevance of these findings remains to be clarified. Data are shown as the percentage of OATP1B1-or OATP1B3-mediated pravastatin uptake in the absence of the respective drug (without). *P < 0.05; **P < 0.01 vs. control. (modified from ). Glibenclamide is a frequently prescribed insulin secretagogue stimulating the insulin secretion from pancreatic β-cells. It is extensively metabolized by CYP2C9, CYP2C19 and CYP3A4 and seems to be a substrate for OATP2B1 . Using HEK cells overexpressing OATP2B1 Satoh et al. have shown that grapefruit and citrus juice inhibited OATP2B1-mediated glibenclamide uptake . Since OATP2B1 is also localized in the apical membrane of enterocytes this may result in a reduced intestinal absorption of orally administered glibenclamide and of other drugs that are substrates of OATP2B1. Interestingly, this could not be confirmed in an in vivo study analyzing the effect of clarithromycin and grapefruit juice on the pharmacokinetics of glibenclamide . In this study 12 subjects ingested 250 mg clarithromycin or placebo with 200 mL grapefruit juice three times daily. On day three, they ingested in addition 0.875 mg glibenclamide with sugar water or grapefruit juice and the concentrations of glibenclamide and clarithromycin in plasma, glucose in blood and excretion of the metabolite hydroxyglibenclamide in urine were measured. These analyses demonstrated that clarithromycin increased plasma concentrations of glibenclamide, maybe by inhibiting OATP2B1-mediated uptake and CYP3A4 metabolism in the intestine, but no effect of grapefruit juice on glibenclamide pharmacokinetics could be detected. The results of this study were confirmed in a study by Niemi et al. demonstrating that clarithromycin also increases the plasma concentrations and effects of simultaneously administered repaglinide . An interaction of atorvastatin with glibenclamide has been demonstrated using MDCK cells stably expressing OATP2B1 . In this study the authors investigated the expression of OATP2B1 in human heart samples and analyzed OATP2B1-mediated atorvastatin and glibenclamide transport and transport inhibition by simultaneously administered drugs. They demonstrated that OATP2B1-mediated glibenclamide transport was inhibited not only by atorvastatin but also by simvastatin, cerivastatin and estrone-3-sulfate (E3S), whereas OATP2B1-mediated E3S uptake was inhibited by gemfibrozil. A potential hazardous interaction between gemfibrozil and repaglinide has been described in 2003 by Niemi and coworkers . It was shown that this interaction persists for at least 12 h after administration of gemfibrozil suggesting that not only the inhibition of uptake transporters but also the inhibition of the drug metabolizing enzyme CYP2C8 might by important for this drug-drug interaction. Another study investigated the effects of atorvastatin on repaglinide pharmacokinetics in relation to SLCO1B1 polymorphism and it could be demonstrated that atorvastatin raises repaglinide plasma concentration, probably by inhibiting OATP1B1 . Other OATP-related drug-drug interactions with oral antidiabetic drugs are summarized in Table 2. Taken together, these analyses revealed that OATPs are important molecular targets of transporter-mediated drug-drug interactions since their substrate spectrum includes a variety of frequently prescribed drugs often administered concomitantly with oral antidiabetic drugs. indole-3-propanoicacid, 1,2,3,4,6,7,12,12a-octahydro-9-methoxy-6-(2-methylpropyl)-1,4-dioxo-,1,1-dimethylethyl ester, (3S,6S,12aS)-); MATE, multidrug and toxin extrusion protein; MPP + , 1-methyl-4-phenylpyridinium; MRP, multidrug resistance protein; NTCP, sodiumtaurocholate cotransporting polypeptide; OATP, organic anion transporting polypeptide; OCT, organic cation transporter; PhA, pheophorbide A; P-gp, P-glycoprotein; TCDC, taurochenodeoxycholate. Oral Antidiabetic Drugs and OCTs OCTs are members of the SLC22 family expressed in several tissues including intestine, liver and kidney (Figure 1; ). Since a large number of clinically used drugs are administered orally, of which approximately 40% are cations or weak bases at physiological pH , transport proteins for cations are important determinants of drug pharmacokinetics. Several antidiabetic drugs have been identified as substrates or inhibitors of OCT proteins. These include metformin which is a substrate for OCT1 (K m value = 1 470 µM ), OCT2 (K m value = 990 µM ) and OCT3 (K m value = 2 260 µM ), whereas phenformin , repaglinide and rosiglitazone all interact with OCT1. Furthermore, genetic variations in the SLC22A1 gene encoding OCT1 were associated with altered pharmacokinetics and pharmacodynamics of metformin , which might pose a higher risk for side effects of metformin, especially lactic acidosis ( , for review see ). Several OCTmediated drug-drug interactions have been described using either metformin as a substrate for OCTs or other oral antidiabetic drugs inhibiting OCT-mediated transport. In vivo it has been shown that genetic variations in the SLC22A2 gene encoding human OCT2 are associated with alterations in metformin pharmacokinetics and that in the presence of simultaneously administered cimetidine the renal clearance of metformin was decreased . This uptake inhibition could be confirmed in vitro using HEK and MDCK cells overexpressing OCT1 and OCT2 . For OCT1, the IC 50 value for cimetidine-induced inhibition of metformin uptake was 150 µM , for OCT2 a K i value of 147 µM could be detected for the same drug combination . Other drugs inhibiting OCT-mediated metformin uptake are the BCR-ABL inhibitors imatinib and nilotinib . Imatinib inhibited the uptake with IC 50 values of 1.5 µM, 5.8 µM and 4.4 µM for OCT1, OCT2 and OCT3, respectively whereas nilotinib inhibited the same transporters with IC 50 values of 2.9 µM (OCT1), >30 µM (OCT2) and 0.3 µM (OCT3). Furthermore, in the same study the inhibition of OCT-mediated metformin uptake by the EGFR (epidermal growth factor receptor) inhibitor gefitinib was studied demonstrating an inhibition of OCT1, OCT2 and OCT3 with IC 50 values of 1.1 µM, 24.4 µM and 5.5 µM, respectively. Since the uptake of drugs from blood into the renal tubular cells is a key determinant for renal secretion, inhibition of OCT2-mediated drug transport may influence systemic plasma concentration. For beta-blockers this uptake inhibition has been demonstrated in vitro using MDCK cells recombinantly overexpressing OCT2. In this study, Bachmakov and coworkers showed that OCT2-mediated metformin uptake was significantly inhibited by the beta-blockers bisoprolol, carvedilol, metoprolol and propranolol with IC 50 values of 2.4 µM, 2.3 µM, 50.2 µM and 8.3 µM, respectively . Interestingly, the uptake and the effect of one oral antidiabetic drug can also be inhibited by a second antidiabetic drug. This has been demonstrated in vitro analyzing OCT1-and OCT2-mediated metformin uptake and uptake inhibition by the DPP-4 inhibitor sitagliptin . In this study the authors showed that sitagliptin inhibited OCT1-and OCT2-mediated metformin uptake with IC 50 values of 34.9 µM and 40.8 µM, respectively. Furthermore, the inhibition of metformin-induced activation of AMPK (5' adenosine monophosphate-activated protein kinase) signaling was investigated demonstrating that treatment with sitagliptin in MDCK-OCT1 and HepG2 cells resulted in a reduced level of phosphorylated AMPK with K i values of 38.8 µM and 43.4 µM, respectively. Summarizing these data (in combination with data presented in Table 2) one can assume that, in addition to OATP-mediated interactions, the inhibition of OCT proteins may be an important determinant of oral antidiabetic drug pharmacokinetics. Oral Antidiabetic Drugs and Export Proteins Most export proteins that mediate the export of drugs and drug metabolites out of cells belong to the superfamily of ABC transporters. P-glycoprotein (P-gp) is the best characterized efflux transporter localized in the apical membrane of enterocytes, the bile canalicular membrane and proximal tubule cells of the renal epithelium (Figure 1) mediating the export of a variety of different drugs belonging to various drug classes . In diabetes therapy, several in vivo and in vitro studies have shown that P-gp is also involved in drug-drug interactions. It has been demonstrated in vivo that the macrolide clarithromycin increased the C max and the AUC (area under the plasma concentration time curve) of coadministered glibenclamide and thus could lead to hypoglycaemia due to elevated plasma concentrations of glibenclamide . Further P-gp-mediated drug-drug interactions could be observed in several in vitro studies. Using P-gp overexpressing cells it could be demonstrated that glibenclamide inhibited P-gp-mediated efflux of the model substrate rhodamine 123 . Inhibition of glibenclamide export resulting in increased intracellular accumulation was also detected in the presence of colchicine . Another study conducted by Hemauer and coworkers showed that rosiglitazone and metformin were transported by P-gp using placental inside-out oriented brush border membrane vesicles. Additionally, it was reported that inhibition of P-gp by verapamil markedly decreased the transport of rosiglitazone and metformin . A second well-studied export pump involved in the transport of oral antidiabetic drugs is the breast cancer resistance protein BCRP (gene symbol ABCG2). This transporter is localized in the apical membrane of enterocytes and renal epithelial cells as well as in the canalicular membrane of hepatocytes ( Figure 1). Several in vitro studies have indicated that oral antidiabetic drugs are substrates for BCRP and that coadministration of other drugs may inhibit this BCRP-mediated transport. Like for P-gp, Hemauer et al. provided evidence that BCRP participates in the transport of metformin. They could show that the BCRP inhibitor KO143 lead to a decreased metformin transport . In addition, several studies using cells stably expressing BCRP revealed that glibenclamide export is inhibited by prototypic inhibitors, such as the antibiotic novobiocin or fumitremorgin C . Pollex et al. further investigated the functional consequences of a frequent genetic variation in the ABCG2 gene encoding human BCRP. They found that the variation BCRPp.Q141K (ABCG2c.412C>A) showed a higher Michaelis Menten constant (K m value) and a higher maximal transport rate (V max value) for BCRP-mediated glibenclamide transport as compared to the transport mediated by the wild-type BCRP protein . Interesting and recently characterized transporters responsible for the export of substances and drugs out of cells are members of the MATE family (multidrug and toxin extrusion protein; gene symbol SLC47). As known so far, this family consists of the two members MATE1 and MATE2 (also designated as MATE2-K ). MATE1 is expressed in several tissues including liver and kidney, whereas expression of MATE2 seems to be restricted to renal epithelial cells (Figure 1; ). Unlike ABC transporters, these export proteins use an inward-directed proton gradient for exporting substrates out of cells. Several endogenous substances and drugs have been identified as substrates of these transport proteins with metformin as the best studied oral antidiabetic drug transported by MATE1 and MATE2 . The importance of MATE1 for the pharmacokinetics of metformin has been investigated in Mate1 (-/-) knockout mice . After a single intravenous administration of metformin (5 mg/kg), a two-fold increase in the AUC of metformin in Mate1 (-/-) mice as compared to wild-type mice was detected. Furthermore, the renal clearance of metformin was only 18% of that measured in Mate1 (+/+) mice clearly demonstrating the essential role of MATE1 in the systemic clearance of metformin. Inhibition studies using single-transfected HEK cells recombinantly expressing MATE1 or MATE2 showed that some tyrosine kinase inhibitors (TKIs) are potent inhibitors of MATE-mediated transport . In detail, imatinib, nilotinib, gefitinib and erlotinib inhibited MATE1-and MATE2mediated metformin transport with unbound C max /IC 50 values higher than 0.1, suggesting that this transporter-mediated drug-drug interaction with TKIs may also be relevant in vivo and therefore affect the disposition, efficacy and toxicity of metformin and possibly of other drugs that are substrates for these export proteins. A further analysis of drug interaction studies has been performed by zu Schwabedissen and coworkers . They demonstrated a significant inhibition of MATE1-mediated metformin transport by using single-transfected HeLa cells expressing human MATE1 and a panel of 24 different drugs. Most potent inhibitors (all tested at a concentration of 25 µM) were cimetidine with 21.08 ± 0.81%, trimethoprim with 25.35 ± 0.49% and ritonavir with 25.75 ± 9.91% residual metformin transport. Furthermore, the IC 50 values of MATE1-mediated metformin transport were determined for ritonavir (15.4 ± 2.5 µM), ranitidine (18.9 ± 7.3 µM), rapamycin (3.27 ± 0.46 µM) and mitoxantrone (4.4 ± 1.3 µM). All of these IC 50 values are below the reported peak plasma concentrations, suggesting that these interactions may also play a role in vivo . Another interaction of MATE1-mediated metformin uptake has been analyzed in HEK cells stably expressing MATE1 and the frequently prescribed antibiotic trimethoprim as well as the antimalarial drug chloroquine. The experiments revealed a strong inhibition for both substances with an IC 50 value of 6.2 µM calculated for trimethoprim and a K i value of 2.8 µM for chloroquine . Some studies also investigated the effect of drugs on OCT-and MATE-mediated transport using double-transfected cells recombinantly expressing an uptake transporter of the OCT family together with MATE1 or MATE2 . In order to examine the effect of cimetidine on transcellular metformin transport, an OCT2-MATE1 double-transfected MDCK cell line was used . These experiments demonstrated that the transcellular metformin transport was moderately inhibited by 1 µM cimetidine and almost completely inhibited by 1 mM cimetidine. Interestingly, the intracellular accumulation of metformin was inhibited only by 1 mM cimetidine but was increased by the low concentration of 1 µM cimetidine under the same experimental conditions. These results suggest that low cimetidine concentrations had no inhibitory effect on OCT2-mediated uptake whereas MATE1 was inhibited by intracellular cimetidine resulting in an increased intracellular metformin concentration. Taken together, these studies demonstrated that beside the inhibition of uptake transporters also the inhibition of export proteins may be important and clinically relevant for drugdrug interactions with oral antidiabetic drugs. Furthermore, experimental approaches using doubletransfected cell lines simultaneously expressing an uptake transporter and an export protein indicated a crucial interaction of uptake transporters and export pumps.
// C function void glVertexAttrib1f ( GLuint indx, GLfloat x ) public static void glVertexAttrib1f( int indx, float x ) { checkWebGLContext(); /** * @j2sNative * android.opengl.GLES20.prototype.mContext.vertexAttrib1f(indx, x); */{} }
/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 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 3 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. ============================================================================ $Id: basic_alphabet_interface2.h 4731 2009-08-31 15:10:19Z <EMAIL> $ ==========================================================================*/ #ifndef SEQAN_HEADER_BASIC_ALPHABET_INTERFACE2_H #define SEQAN_HEADER_BASIC_ALPHABET_INTERFACE2_H #include <new> namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// // gapValue, gapValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.gapValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.gapValue@. ..signature:gapValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A gap character. ..remarks.text:This function implements @Function.getValue@. It is recommended to use @Function.gapValue@ rather than $gapValueImpl$. */ template <typename T> inline T const & gapValueImpl(T *) { SEQAN_CHECKPOINT static T const _gap = T(); return _gap; } /** .Function.gapValue: ..cat:Alphabets ..cat:Alignments ..summary:Returns reference to a value that is used as gap character. ..signature:gapValue<TValue>() ..param.TValue:Value type. ..returns:A gap character. ..remarks.text:The function is implemented in @Function.gapValueImpl@. Do not specialize $gapValue$, specialize @Function.gapValueImpl@ instead! ..see:Function.gapValueImpl */ /* template <typename T> inline T const & gapValue() { SEQAN_CHECKPOINT static T * _tag = 0; return gapValueImpl(_tag); } */ template <typename T> inline T gapValue() { SEQAN_CHECKPOINT static T * _tag = 0; return gapValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// // supremumValue, supremumValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.supremumValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.supremumValue@. ..signature:supremumValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A value $inf$ that holds: $inf >= i$ for all values $i$. ..remarks.text:This function implements @Function.supremumValue@. It is recommended to use @Function.supremumValue@ rather than $supremumValueImpl$. */ /* template <typename T> inline T const & supremumValueImpl(T *) { static T const _value = -1; return _value; } */ /** .Function.supremumValue: ..cat:Alphabets ..summary:Supremum for a given type. ..signature:supremumValue<T>() ..param.T:An ordered type. ..returns:A value $inf$ that holds: $inf >= i$ for all values $i$ of type $T$. ..remarks.text:The function is implemented in @Function.supremumValueImpl@. Do not specialize $supremumValue$, specialize @Function.supremumValueImpl@ instead! ..see:Function.supremumValueImpl */ template <typename T> inline T const & supremumValue() { SEQAN_CHECKPOINT T * _tag = 0; return supremumValueImpl(_tag); } template <typename T> inline T const & supremumValue(T) { SEQAN_CHECKPOINT T * _tag = 0; return supremumValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// // infimumValue, infimumValueImpl ////////////////////////////////////////////////////////////////////////////// /** .Function.infimumValueImpl: ..hidefromindex ..cat:Alphabets ..summary:Implements @Function.infimumValue@. ..signature:infimumValueImpl(value_pointer_tag) ..param.value_pointer_tag:A pointer that is used as a tag to specify the value type. ...remarks:The pointer needs not to point to a valid object, so it is possible to use a null pointer here. ..returns:A value $inf$ that holds: $inf <= i$ for all values $i$. ..remarks.text:This function implements @Function.infimumValue@. It is recommended to use @Function.infimumValue@ rather than $infimumValueImpl$. */ /* template <typename T> inline T const & infimumValueImpl(T *) { static T const _value = -1; return _value; } */ /** .Function.infimumValue: ..cat:Alphabets ..summary:Infimum for a given type. ..signature:infimumValue<T>() ..param.T:An ordered type. ..returns:A value $inf$ that holds: $inf <= i$ for all values $i$ of type $T$. ..remarks.text:The function is implemented in @Function.infimumValueImpl@. Do not specialize $infimumValue$, specialize @Function.infimumValueImpl@ instead! ..see:Function.infimumValueImpl ..see:Function.supremumValue */ template <typename T> inline T const & infimumValue() { SEQAN_CHECKPOINT T * _tag = 0; return infimumValueImpl(_tag); } template <typename T> inline T const & infimumValue(T) { SEQAN_CHECKPOINT T * _tag = 0; return infimumValueImpl(_tag); } ////////////////////////////////////////////////////////////////////////////// }// namespace SEQAN_NAMESPACE_MAIN #endif //#ifndef SEQAN_HEADER_...
def _getActiveThread(self,uid): if uid in self.testThreads: testingThread = self.testThreads.get(uid) if testingThread and not testingThread.isAlive(): self.testThreads[uid] = None testingThread = None return testingThread
/************************************************************************/ /* */ /* l i s p _ X e x i t */ /* */ /* Turn off the X window we've been using for display. */ /* */ /************************************************************************/ void lisp_Xexit(DspInterface dsp) { #ifdef SYSVONLY #ifndef LINUX #ifndef MACOSX ioctl(ConnectionNumber(dsp->display_id), I_SETSIG, 0); #endif #endif #endif XDestroySubwindows(dsp->display_id, dsp->LispWindow); XDestroyWindow(dsp->display_id, dsp->LispWindow); XCloseDisplay(dsp->display_id); Lisp_Xinitialized = FALSE; }
<filename>src/test/internal/hardhat-network/provider/node.ts<gh_stars>0 import { Block } from "@ethereumjs/block"; import Common from "@ethereumjs/common"; import { TxData, TypedTransaction } from "@ethereumjs/tx"; import VM from "@ethereumjs/vm"; import { AfterBlockEvent, RunBlockOpts } from "@ethereumjs/vm/dist/runBlock"; import { assert } from "chai"; import { Address, BN, bufferToHex, toBuffer } from "ethereumjs-util"; import { ethers } from "ethers"; import sinon from "sinon"; import { defaultHardhatNetworkParams } from "../../../../src/internal/core/config/default-config"; import { rpcToBlockData } from "../../../../src/internal/hardhat-network/provider/fork/rpcToBlockData"; import { HardhatNode } from "../../../../src/internal/hardhat-network/provider/node"; import { ForkedNodeConfig, NodeConfig, RunCallResult, } from "../../../../src/internal/hardhat-network/provider/node-types"; import { FakeSenderTransaction } from "../../../../src/internal/hardhat-network/provider/transactions/FakeSenderTransaction"; import { getCurrentTimestamp } from "../../../../src/internal/hardhat-network/provider/utils/getCurrentTimestamp"; import { makeForkClient } from "../../../../src/internal/hardhat-network/provider/utils/makeForkClient"; import { HardforkName } from "../../../../src/internal/util/hardforks"; import { HardhatNetworkChainConfig, HardhatNetworkChainsConfig, } from "../../../../src/types"; import { ALCHEMY_URL } from "../../../setup"; import { assertQuantity } from "../helpers/assertions"; import { EMPTY_ACCOUNT_ADDRESS, FORK_TESTS_CACHE_PATH, } from "../helpers/constants"; import { expectErrorAsync } from "../../../helpers/errors"; import { DEFAULT_ACCOUNTS, DEFAULT_ACCOUNTS_ADDRESSES, DEFAULT_BLOCK_GAS_LIMIT, DEFAULT_CHAIN_ID, DEFAULT_HARDFORK, DEFAULT_NETWORK_ID, DEFAULT_NETWORK_NAME, } from "../helpers/providers"; import { assertEqualBlocks } from "./utils/assertEqualBlocks"; /* eslint-disable @typescript-eslint/dot-notation */ interface ForkedBlock { networkName: string; url: string; blockToRun: number; chainId: number; } export function cloneChainsConfig( source: HardhatNetworkChainsConfig ): HardhatNetworkChainsConfig { const clone: HardhatNetworkChainsConfig = new Map(); source.forEach( (sourceChainConfig: HardhatNetworkChainConfig, chainId: number) => { const clonedChainConfig = { ...sourceChainConfig }; clonedChainConfig.hardforkHistory = new Map( sourceChainConfig.hardforkHistory ); clone.set(chainId, clonedChainConfig); } ); return clone; } describe("HardhatNode", () => { const config: NodeConfig = { automine: false, hardfork: DEFAULT_HARDFORK, networkName: DEFAULT_NETWORK_NAME, chainId: DEFAULT_CHAIN_ID, networkId: DEFAULT_NETWORK_ID, blockGasLimit: DEFAULT_BLOCK_GAS_LIMIT, minGasPrice: new BN(0), genesisAccounts: DEFAULT_ACCOUNTS, initialBaseFeePerGas: 10, mempoolOrder: "priority", coinbase: "0x0000000000000000000000000000000000000000", chains: defaultHardhatNetworkParams.chains, }; const gasPrice = 20; let node: HardhatNode; let createTestTransaction: ( txData: TxData & { from: string } ) => FakeSenderTransaction; beforeEach(async () => { [, node] = await HardhatNode.create(config); createTestTransaction = (txData) => { const tx = new FakeSenderTransaction(Address.fromString(txData.from), { gasPrice, ...txData, }); tx.hash(); return tx; }; }); describe("getPendingTransactions", () => { it("returns both pending and queued transactions from TxPool", async () => { const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, }); const tx2 = createTestTransaction({ nonce: 2, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, }); const tx3 = createTestTransaction({ nonce: 3, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.sendTransaction(tx3); const nodePendingTxs = await node.getPendingTransactions(); assert.sameDeepMembers( nodePendingTxs.map((tx) => tx.raw), [tx1, tx2, tx3].map((tx) => tx.raw) ); }); }); describe("mineBlock", () => { async function assertTransactionsWereMined(txs: TypedTransaction[]) { for (const tx of txs) { const txReceipt = await node.getTransactionReceipt(tx.hash()); assert.isDefined(txReceipt); } const block = await node.getLatestBlock(); assert.lengthOf(block.transactions, txs.length); assert.deepEqual( block.transactions.map((tx) => bufferToHex(tx.hash())), txs.map((tx) => bufferToHex(tx.hash())) ); } describe("basic tests", () => { it("can mine an empty block", async () => { const beforeBlock = node.getLatestBlockNumber(); await node.mineBlock(); const currentBlock = node.getLatestBlockNumber(); assert.equal(currentBlock.toString(), beforeBlock.addn(1).toString()); }); it("can mine a block with one transaction", async () => { const tx = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); await node.sendTransaction(tx); await node.mineBlock(); await assertTransactionsWereMined([tx]); const balance = await node.getAccountBalance(EMPTY_ACCOUNT_ADDRESS); assert.equal(balance.toString(), "1234"); }); it("can mine a block with two transactions from different senders", async () => { const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); const tx2 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); await assertTransactionsWereMined([tx1, tx2]); const balance = await node.getAccountBalance(EMPTY_ACCOUNT_ADDRESS); assert.equal(balance.toString(), "2468"); }); it("can keep the transaction ordering when mining a block", async () => { [, node] = await HardhatNode.create({ ...config, mempoolOrder: "fifo", }); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, gasPrice: 42, }); const tx2 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, gasPrice: 84, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); const txReceipt1 = await node.getTransactionReceipt(tx1.hash()); const txReceipt2 = await node.getTransactionReceipt(tx2.hash()); assert.equal(txReceipt1?.transactionIndex, "0x0"); assert.equal(txReceipt2?.transactionIndex, "0x1"); }); it("can mine a block with two transactions from the same sender", async () => { const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); const tx2 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); await assertTransactionsWereMined([tx1, tx2]); const balance = await node.getAccountBalance(EMPTY_ACCOUNT_ADDRESS); assert.equal(balance.toString(), "2468"); }); it("removes the mined transaction from the tx pool", async () => { const tx = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, value: 1234, }); await node.sendTransaction(tx); const pendingTransactionsBefore = await node.getPendingTransactions(); assert.lengthOf(pendingTransactionsBefore, 1); await node.mineBlock(); const pendingTransactionsAfter = await node.getPendingTransactions(); assert.lengthOf(pendingTransactionsAfter, 0); }); it("leaves the transactions in the tx pool that did not fit in a block", async () => { await node.setBlockGasLimit(55_000); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); const expensiveTx2 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 40_000, }); const tx3 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); await node.sendTransaction(tx1); await node.sendTransaction(expensiveTx2); await node.sendTransaction(tx3); const pendingTransactionsBefore = await node.getPendingTransactions(); assert.sameDeepMembers( pendingTransactionsBefore.map((tx) => tx.raw), [tx1, expensiveTx2, tx3].map((tx) => tx.raw) ); await node.mineBlock(); await assertTransactionsWereMined([tx1, tx3]); const pendingTransactionsAfter = await node.getPendingTransactions(); assert.sameDeepMembers( pendingTransactionsAfter.map((tx) => tx.raw), [expensiveTx2.raw] ); }); it("sets correct gasUsed values", async () => { const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 100_000, value: 1234, }); const tx2 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 100_000, value: 1234, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); const tx1Receipt = await node.getTransactionReceipt(tx1.hash()); const tx2Receipt = await node.getTransactionReceipt(tx2.hash()); assertQuantity(tx1Receipt?.gasUsed, 21_000); assertQuantity(tx2Receipt?.gasUsed, 21_000); const block = await node.getLatestBlock(); assert.equal(block.header.gasUsed.toNumber(), 42_000); }); it("assigns miner rewards", async () => { const gasPriceBN = new BN(1); let baseFeePerGas = new BN(0); const pendingBlock = await node.getBlockByNumber("pending"); if (pendingBlock.header.baseFeePerGas !== undefined) { baseFeePerGas = pendingBlock.header.baseFeePerGas; } const miner = node.getCoinbaseAddress(); const initialMinerBalance = await node.getAccountBalance(miner); const oneEther = new BN(10).pow(new BN(18)); const txFee = gasPriceBN.add(baseFeePerGas).muln(21_000); const burnedTxFee = baseFeePerGas.muln(21_000); // the miner reward is 2 ETH plus the tx fee, minus the part // of the fee that is burned const minerReward = oneEther.muln(2).add(txFee).sub(burnedTxFee); const tx = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasPrice: gasPriceBN.add(baseFeePerGas), gasLimit: 21_000, value: 1234, }); await node.sendTransaction(tx); await node.mineBlock(); const minerBalance = await node.getAccountBalance(miner); assert.equal( minerBalance.toString(), initialMinerBalance.add(minerReward).toString() ); }); }); describe("gas limit tests", () => { it("mines only as many transactions as would fit in a block", async () => { await node.setBlockGasLimit(30_000); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, }); const tx2 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); await assertTransactionsWereMined([tx1]); assert.isUndefined(await node.getTransactionReceipt(tx2.hash())); }); it("uses gasLimit value for determining if a new transaction will fit in a block (1 fits)", async () => { await node.setBlockGasLimit(50_000); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); const tx2 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); await assertTransactionsWereMined([tx1]); assert.isUndefined(await node.getTransactionReceipt(tx2.hash())); }); it("uses gasLimit value for determining if a new transaction will fit in a block (2 fit)", async () => { // here the first tx is added, and it uses 21_000 gas // this leaves 31_000 of gas in the block, so the second one is also included await node.setBlockGasLimit(52_000); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); const tx2 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.mineBlock(); await assertTransactionsWereMined([tx1, tx2]); }); it("uses the rest of the txs when one is dropped because of its gas limit", async () => { await node.setBlockGasLimit(50_000); const tx1 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 gasPrice: 40, }); const tx2 = createTestTransaction({ nonce: 1, from: DEFAULT_ACCOUNTS_ADDRESSES[0], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 30_000, // actual gas used is 21_000 gasPrice: 40, }); const tx3 = createTestTransaction({ nonce: 0, from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: EMPTY_ACCOUNT_ADDRESS, gasLimit: 21_000, gasPrice: 20, }); await node.sendTransaction(tx1); await node.sendTransaction(tx2); await node.sendTransaction(tx3); await node.mineBlock(); await assertTransactionsWereMined([tx1, tx3]); assert.isUndefined(await node.getTransactionReceipt(tx2.hash())); }); }); describe("timestamp tests", () => { let clock: sinon.SinonFakeTimers; const assertIncreaseTime = async (expectedTime: number) => { const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); // We check that the time increased at least what we had expected // but allow a little bit of POSITIVE difference(i.e. that the // actual timestamp is a little bit bigger) because time may have ellapsed // We assume that the test CAN NOT have taken more than a second assert.isAtLeast(blockTimestamp, expectedTime); assert.isAtMost(blockTimestamp, expectedTime + 1); }; beforeEach(() => { clock = sinon.useFakeTimers(Date.now()); }); afterEach(() => { clock.restore(); }); it("mines a block with the current timestamp", async () => { clock.tick(15_000); const now = getCurrentTimestamp(); await node.mineBlock(); const block = await node.getLatestBlock(); assert.equal(block.header.timestamp.toNumber(), now); }); it("mines a block with an incremented timestamp if it clashes with the previous block", async () => { const firstBlock = await node.getLatestBlock(); const firstBlockTimestamp = firstBlock.header.timestamp.toNumber(); await node.mineBlock(); const latestBlock = await node.getLatestBlock(); const latestBlockTimestamp = latestBlock.header.timestamp.toNumber(); assert.equal(latestBlockTimestamp, firstBlockTimestamp + 1); }); it("assigns an incremented timestamp to each new block mined within the same second", async () => { const firstBlock = await node.getLatestBlock(); const firstBlockTimestamp = firstBlock.header.timestamp.toNumber(); await node.mineBlock(); const secondBlock = await node.getLatestBlock(); const secondBlockTimestamp = secondBlock.header.timestamp.toNumber(); await node.mineBlock(); const thirdBlock = await node.getLatestBlock(); const thirdBlockTimestamp = thirdBlock.header.timestamp.toNumber(); assert.equal(secondBlockTimestamp, firstBlockTimestamp + 1); assert.equal(thirdBlockTimestamp, secondBlockTimestamp + 1); }); it("mines a block with a preset timestamp", async () => { const now = getCurrentTimestamp(); const timestamp = new BN(now).addn(30); node.setNextBlockTimestamp(timestamp); await node.mineBlock(); const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); assert.equal(blockTimestamp, timestamp.toNumber()); }); it("mines the next block normally after a block with preset timestamp", async () => { const now = getCurrentTimestamp(); const timestamp = new BN(now).addn(30); node.setNextBlockTimestamp(timestamp); await node.mineBlock(); clock.tick(3_000); await node.mineBlock(); const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); assert.equal(blockTimestamp, timestamp.toNumber() + 3); }); it("mines a block with the timestamp passed as a parameter irrespective of the preset timestamp", async () => { const now = getCurrentTimestamp(); const presetTimestamp = new BN(now).addn(30); node.setNextBlockTimestamp(presetTimestamp); const timestamp = new BN(now).addn(60); await node.mineBlock(timestamp); const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); assert.equal(blockTimestamp, timestamp.toNumber()); }); it("mines a block with correct timestamp after time increase", async () => { const now = getCurrentTimestamp(); const delta = 30; node.increaseTime(new BN(delta)); await node.mineBlock(); await assertIncreaseTime(now + delta); }); it("mining a block having increaseTime called twice counts both calls", async () => { const now = getCurrentTimestamp(); const delta = 30; node.increaseTime(new BN(delta)); node.increaseTime(new BN(delta)); await node.mineBlock(); await assertIncreaseTime(now + delta * 2); }); it("mining a block having called increaseTime takes into account 'real' passing time", async () => { const now = getCurrentTimestamp(); const delta = 30; const elapsedTimeInSeconds = 3; node.increaseTime(new BN(delta)); clock.tick(elapsedTimeInSeconds * 1_000); await node.mineBlock(); await assertIncreaseTime(now + delta + elapsedTimeInSeconds); }); describe("when time is increased by 30s", () => { function testPresetTimestamp(offset: number) { it("mines a block with the preset timestamp", async () => { const now = getCurrentTimestamp(); const timestamp = new BN(now).addn(offset); node.increaseTime(new BN(30)); node.setNextBlockTimestamp(timestamp); await node.mineBlock(); const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); assert.equal(blockTimestamp, timestamp.toNumber()); }); it("mining a block with a preset timestamp changes the time offset", async () => { const now = getCurrentTimestamp(); const timestamp = new BN(now).addn(offset); node.increaseTime(new BN(30)); node.setNextBlockTimestamp(timestamp); await node.mineBlock(); clock.tick(3_000); await node.mineBlock(); const block = await node.getLatestBlock(); const blockTimestamp = block.header.timestamp.toNumber(); assert.equal(blockTimestamp, timestamp.toNumber() + 3); }); } describe("when preset timestamp is 20s into the future", () => { testPresetTimestamp(20); }); describe("when preset timestamp is 40s into the future", () => { testPresetTimestamp(40); }); }); }); }); describe("full block", function () { if (ALCHEMY_URL === undefined) { return; } const forkedBlocks: ForkedBlock[] = [ // We don't run this test against spurious dragon because // its receipts contain the state root, and we can't compute it { networkName: "mainnet", url: ALCHEMY_URL, blockToRun: 4370001, chainId: 1, }, { networkName: "mainnet", url: ALCHEMY_URL, blockToRun: 7280001, chainId: 1, }, { networkName: "mainnet", url: ALCHEMY_URL, blockToRun: 9069001, chainId: 1, }, { networkName: "mainnet", url: ALCHEMY_URL, blockToRun: 9300077, chainId: 1, }, { networkName: "kovan", url: ALCHEMY_URL.replace("mainnet", "kovan"), blockToRun: 23115227, chainId: 42, }, { networkName: "rinkeby", url: ALCHEMY_URL.replace("mainnet", "rinkeby"), blockToRun: 8004365, chainId: 4, }, { networkName: "ropsten", url: ALCHEMY_URL.replace("mainnet", "ropsten"), blockToRun: 9812365, // this block has a EIP-2930 tx chainId: 3, }, { networkName: "ropsten", url: ALCHEMY_URL.replace("mainnet", "ropsten"), blockToRun: 10499406, // this block has a EIP-1559 tx chainId: 3, }, ]; for (const { url, blockToRun, networkName, chainId } of forkedBlocks) { const remoteCommon = new Common({ chain: chainId }); const hardfork = remoteCommon.getHardforkByBlockNumber(blockToRun); it(`should run a ${networkName} block from ${hardfork} and produce the same results`, async function () { this.timeout(240000); const forkConfig = { jsonRpcUrl: url, blockNumber: blockToRun - 1, }; const { forkClient } = await makeForkClient(forkConfig); const rpcBlock = await forkClient.getBlockByNumber( new BN(blockToRun), true ); if (rpcBlock === null) { assert.fail(); } const forkedNodeConfig: ForkedNodeConfig = { automine: true, networkName: "mainnet", chainId, networkId: 1, hardfork, forkConfig, forkCachePath: FORK_TESTS_CACHE_PATH, blockGasLimit: rpcBlock.gasLimit.toNumber(), minGasPrice: new BN(0), genesisAccounts: [], mempoolOrder: "priority", coinbase: "0x0000000000000000000000000000000000000000", chains: defaultHardhatNetworkParams.chains, }; const [common, forkedNode] = await HardhatNode.create(forkedNodeConfig); const block = Block.fromBlockData( rpcToBlockData({ ...rpcBlock, // We wipe the receipt root to make sure we get a new one receiptsRoot: Buffer.alloc(32, 0), }), { common, freeze: false, } ); forkedNode["_vmTracer"].disableTracing(); const afterBlockEvent = await runBlockAndGetAfterBlockEvent( forkedNode["_vm"], { block, generate: true, skipBlockValidation: true, } ); const modifiedBlock = afterBlockEvent.block; await forkedNode["_vm"].blockchain.putBlock(modifiedBlock); await forkedNode["_saveBlockAsSuccessfullyRun"]( modifiedBlock, afterBlockEvent ); const newBlock = await forkedNode.getBlockByNumber(new BN(blockToRun)); if (newBlock === undefined) { assert.fail(); } await assertEqualBlocks( newBlock, afterBlockEvent, rpcBlock, forkClient ); }); } }); describe("mineBlocks", function () { it("shouldn't break getLatestBlock()", async function () { const previousLatestBlockNumber = node.getLatestBlockNumber(); await node.mineBlocks(new BN(10)); const latestBlock = await node.getLatestBlock(); assert.equal( latestBlock.header.number.toString(), previousLatestBlockNumber.addn(10).toString() ); }); it("shouldn't break getLatestBlockNumber()", async function () { const previousLatestBlockNumber = node.getLatestBlockNumber(); await node.mineBlocks(new BN(10)); const latestBlockNumber = node.getLatestBlockNumber(); assert.equal( latestBlockNumber.toString(), previousLatestBlockNumber.addn(10).toString() ); }); describe("shouldn't break snapshotting", async function () { it("when doing mineBlocks() before a snapshot", async function () { await node.mineBlocks(new BN(10)); const latestBlockNumberBeforeSnapshot = node.getLatestBlockNumber(); const snapshotId = await node.takeSnapshot(); await node.sendTransaction( createTestTransaction({ from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: Address.fromString( "0x1111111111111111111111111111111111111111" ), gasLimit: 21000, }) ); await node.mineBlocks(new BN(1)); await node.revertToSnapshot(snapshotId); assert.equal( node.getLatestBlockNumber().toString(), latestBlockNumberBeforeSnapshot.toString() ); }); it("when doing mineBlocks() after a snapshot", async function () { const originalLatestBlockNumber = node.getLatestBlockNumber(); await node.sendTransaction( createTestTransaction({ from: DEFAULT_ACCOUNTS_ADDRESSES[1], to: Address.fromString( "0x1111111111111111111111111111111111111111" ), gasLimit: 21000, }) ); const latestBlockNumberBeforeSnapshot = node.getLatestBlockNumber(); assert.equal( latestBlockNumberBeforeSnapshot.toString(), originalLatestBlockNumber.toString() ); const snapshotId = await node.takeSnapshot(); assert.equal( node.getLatestBlockNumber().toString(), originalLatestBlockNumber.toString() ); await node.mineBlocks(new BN(10)); assert.equal( node.getLatestBlockNumber().toString(), latestBlockNumberBeforeSnapshot.addn(10).toString() ); await node.revertToSnapshot(snapshotId); assert.equal( node.getLatestBlockNumber().toString(), latestBlockNumberBeforeSnapshot.toString() ); }); }); }); /** execute a call to method Hello() on contract HelloWorld, deployed to * mainnet years ago, which should return a string, "Hello World". */ async function runCall( gasParams: { gasPrice?: BN; maxFeePerGas?: BN }, block: number, targetNode: HardhatNode ): Promise<string> { const contractInterface = new ethers.utils.Interface([ "function Hello() public pure returns (string)", ]); const callOpts = { to: toBuffer("0xe36613A299bA695aBA8D0c0011FCe95e681f6dD3"), from: toBuffer(DEFAULT_ACCOUNTS_ADDRESSES[0]), value: new BN(0), data: toBuffer(contractInterface.encodeFunctionData("Hello", [])), gasLimit: new BN(1_000_000), }; function decodeResult(runCallResult: RunCallResult) { return contractInterface.decodeFunctionResult( "Hello", bufferToHex(runCallResult.result.value) )[0]; } return decodeResult( await targetNode.runCall({ ...callOpts, ...gasParams }, new BN(block)) ); } describe("should run calls in the right hardfork context", async function () { this.timeout(10000); before(function () { if (ALCHEMY_URL === undefined) { this.skip(); return; } }); const eip1559ActivationBlock = 12965000; // some shorthand for code below: const post1559Block = eip1559ActivationBlock; const blockBefore1559 = eip1559ActivationBlock - 1; const pre1559GasOpts = { gasPrice: new BN(0) }; const post1559GasOpts = { maxFeePerGas: new BN(0) }; const baseNodeConfig: ForkedNodeConfig = { automine: true, networkName: "mainnet", chainId: 1, networkId: 1, hardfork: "london", forkConfig: { jsonRpcUrl: ALCHEMY_URL!, blockNumber: eip1559ActivationBlock, }, forkCachePath: FORK_TESTS_CACHE_PATH, blockGasLimit: 1_000_000, minGasPrice: new BN(0), genesisAccounts: [], chains: defaultHardhatNetworkParams.chains, mempoolOrder: "priority", coinbase: "0x0000000000000000000000000000000000000000", }; describe("when forking with a default hardfork activation history", function () { let hardhatNode: HardhatNode; before(async function () { [, hardhatNode] = await HardhatNode.create(baseNodeConfig); }); it("should accept post-EIP-1559 gas semantics when running in the context of a post-EIP-1559 block", async function () { assert.equal( "Hello World", await runCall(post1559GasOpts, post1559Block, hardhatNode) ); }); it("should accept pre-EIP-1559 gas semantics when running in the context of a pre-EIP-1559 block", async function () { assert.equal( "Hello World", await runCall(pre1559GasOpts, blockBefore1559, hardhatNode) ); }); it("should throw when given post-EIP-1559 gas semantics and when running in the context of a pre-EIP-1559 block", async function () { await expectErrorAsync(async () => { assert.equal( "Hello World", await runCall(post1559GasOpts, blockBefore1559, hardhatNode) ); }, /Cannot run transaction: EIP 1559 is not activated./); }); it("should accept pre-EIP-1559 gas semantics when running in the context of a post-EIP-1559 block", async function () { assert.equal( "Hello World", await runCall(pre1559GasOpts, post1559Block, hardhatNode) ); }); }); describe("when forking with a hardfork activation history that indicates London happened one block early", function () { let nodeWithEarlyLondon: HardhatNode; before(async function () { const nodeConfig = { ...baseNodeConfig, chains: cloneChainsConfig(baseNodeConfig.chains), }; const chainConfig = nodeConfig.chains.get(1) ?? { hardforkHistory: new Map(), }; chainConfig.hardforkHistory.set( HardforkName.LONDON, eip1559ActivationBlock - 1 ); nodeConfig.chains.set(1, chainConfig); [, nodeWithEarlyLondon] = await HardhatNode.create(nodeConfig); }); it("should accept post-EIP-1559 gas semantics when running in the context of the block of the EIP-1559 activation", async function () { assert.equal( "Hello World", await runCall(post1559GasOpts, blockBefore1559, nodeWithEarlyLondon) ); }); it("should throw when given post-EIP-1559 gas semantics and when running in the context of the block before EIP-1559 activation", async function () { await expectErrorAsync(async () => { await runCall( post1559GasOpts, blockBefore1559 - 1, nodeWithEarlyLondon ); }, /Cannot run transaction: EIP 1559 is not activated./); }); it("should accept post-EIP-1559 gas semantics when running in the context of a block after EIP-1559 activation", async function () { assert.equal( "Hello World", await runCall(post1559GasOpts, post1559Block, nodeWithEarlyLondon) ); }); it("should accept pre-EIP-1559 gas semantics when running in the context of the block of the EIP-1559 activation", async function () { assert.equal( "Hello World", await runCall(pre1559GasOpts, blockBefore1559, nodeWithEarlyLondon) ); }); }); describe("when forking with a weird hardfork activation history", function () { let hardhatNode: HardhatNode; before(async function () { const nodeConfig = { ...baseNodeConfig, chains: new Map([ [ 1, { hardforkHistory: new Map([["london", 100]]), }, ], ]), }; [, hardhatNode] = await HardhatNode.create(nodeConfig); }); it("should throw when making a call with a block below the only hardfork activation", async function () { await expectErrorAsync(async () => { await runCall(pre1559GasOpts, 99, hardhatNode); }, /Could not find a hardfork to run for block 99, after having looked for one in the HardhatNode's hardfork activation history/); }); }); describe("when forking WITHOUT a hardfork activation history", function () { let nodeWithoutHardforkHistory: HardhatNode; before(async function () { const nodeCfgWithoutHFHist = { ...baseNodeConfig, chains: cloneChainsConfig(baseNodeConfig.chains), }; nodeCfgWithoutHFHist.chains.set(1, { hardforkHistory: new Map() }); [, nodeWithoutHardforkHistory] = await HardhatNode.create( nodeCfgWithoutHFHist ); }); it("should throw when running in the context of a historical block", async function () { await expectErrorAsync(async () => { await runCall( pre1559GasOpts, blockBefore1559, nodeWithoutHardforkHistory ); }, /node was not configured with a hardfork activation history/); }); }); }); it("should support a historical call in the context of a block added via mineBlocks()", async function () { if (ALCHEMY_URL === undefined) { this.skip(); return; } const nodeConfig: ForkedNodeConfig = { automine: true, networkName: "mainnet", chainId: 1, networkId: 1, hardfork: "london", forkConfig: { jsonRpcUrl: ALCHEMY_URL, blockNumber: 12965000, // eip1559ActivationBlock }, forkCachePath: FORK_TESTS_CACHE_PATH, blockGasLimit: 1_000_000, minGasPrice: new BN(0), genesisAccounts: [], chains: defaultHardhatNetworkParams.chains, mempoolOrder: "priority", coinbase: "0x0000000000000000000000000000000000000000", }; const [, hardhatNode] = await HardhatNode.create(nodeConfig); const oldLatestBlockNumber = hardhatNode.getLatestBlockNumber(); await hardhatNode.mineBlocks(new BN(100)); assert.equal( "Hello World", await runCall( { maxFeePerGas: new BN(0) }, oldLatestBlockNumber.addn(50).toNumber(), hardhatNode ) ); }); }); async function runBlockAndGetAfterBlockEvent( vm: VM, runBlockOpts: RunBlockOpts ): Promise<AfterBlockEvent> { let results: AfterBlockEvent; function handler(event: AfterBlockEvent) { results = event; } try { vm.once("afterBlock", handler); await vm.runBlock(runBlockOpts); } finally { // We need this in case `runBlock` throws before emitting the event. // Otherwise we'd be leaking the listener until the next call to runBlock. vm.removeListener("afterBlock", handler); } return results!; }
<reponame>swashcap/mtrx<filename>src/components/text/Caption.tsx<gh_stars>0 import React from 'react'; import { styled } from '@linaria/react'; import { TextColor } from '../../types'; export interface CaptionProps extends React.HTMLAttributes<HTMLSpanElement> { bold?: boolean; color?: TextColor; } export const Caption = styled.span<CaptionProps>` color: ${({ color }) => color === 'secondary' ? 'var(--color-text-light)' : 'inherit'}; font-size: var(--font-small-size); font-weight: ${({ bold }) => (bold ? '700' : '400')}; line-height: var(--font-small-line-height); `;
/* * Copyright 2020 <NAME>. (http://www.onehippo.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.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.core.MultivaluedMap; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.hippoecm.hst.configuration.HstNodeTypes; import org.hippoecm.hst.configuration.components.HstComponentConfiguration; import org.hippoecm.hst.configuration.experiencepage.ExperiencePageService; import org.hippoecm.hst.configuration.hosting.Mount; import org.hippoecm.hst.configuration.site.HstSite; import org.hippoecm.hst.container.RequestContextProvider; import org.hippoecm.hst.core.parameters.ParametersInfo; import org.hippoecm.hst.core.request.HstRequestContext; import org.hippoecm.hst.pagecomposer.jaxrs.api.PropertyRepresentationFactory; import org.hippoecm.hst.pagecomposer.jaxrs.model.ContainerItemComponentPropertyRepresentation; import org.hippoecm.hst.pagecomposer.jaxrs.model.ContainerItemComponentRepresentation; import org.hippoecm.hst.pagecomposer.jaxrs.services.ContainerItemComponentService; import org.hippoecm.hst.pagecomposer.jaxrs.services.PageComposerContextService; import org.hippoecm.hst.pagecomposer.jaxrs.services.exceptions.ClientError; import org.hippoecm.hst.pagecomposer.jaxrs.services.exceptions.ClientException; import org.hippoecm.hst.pagecomposer.jaxrs.services.exceptions.ServerErrorException; import org.hippoecm.hst.pagecomposer.jaxrs.services.exceptions.UnknownClientException; import org.hippoecm.hst.pagecomposer.jaxrs.util.PageComposerUtil; import org.hippoecm.hst.util.ParametersInfoAnnotationUtils; import org.hippoecm.repository.api.HippoSession; import org.hippoecm.repository.api.WorkflowException; import org.onehippo.cms7.services.HippoServiceRegistry; import org.onehippo.repository.documentworkflow.DocumentWorkflow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.hippoecm.hst.pagecomposer.jaxrs.model.ParametersInfoProcessor.getPopulatedProperties; import static org.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage.XPageUtils.checkoutCorrectBranch; import static org.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage.XPageUtils.getInternalWorkflowSession; import static org.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage.XPageUtils.getObtainEditableInstanceWorkflow; import static org.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage.XPageUtils.getWorkspaceNode; import static org.hippoecm.hst.pagecomposer.jaxrs.services.experiencepage.XPageUtils.validateTimestamp; import static org.hippoecm.hst.pagecomposer.jaxrs.util.MissingParametersInfo.defaultMissingParametersInfo; import static org.hippoecm.hst.pagecomposer.jaxrs.util.PageComposerUtil.executeWithWebsiteClassLoader; public class XPageContainerItemComponentServiceImpl implements ContainerItemComponentService { private static Logger log = LoggerFactory.getLogger(XPageContainerItemComponentServiceImpl.class); private final PageComposerContextService pageComposerContextService; private final List<PropertyRepresentationFactory> propertyPresentationFactories; public XPageContainerItemComponentServiceImpl(final PageComposerContextService pageComposerContextService, final List<PropertyRepresentationFactory> propertyPresentationFactories) { this.pageComposerContextService = pageComposerContextService; this.propertyPresentationFactories = propertyPresentationFactories; } @Override public Set<String> getVariants() throws RepositoryException { final Node currentContainerItem = pageComposerContextService.getRequestContext().getSession() .getNodeByIdentifier(pageComposerContextService.getRequestConfigIdentifier()); final XPageComponentParameters componentParameters = getCurrentHstComponentParameters(currentContainerItem); return componentParameters.getPrefixes(); } @Override public ContainerItemComponentRepresentation getVariant(final String variantId, final String localeString) throws ClientException, RepositoryException, ServerErrorException { try { // just use user session final Node currentContainerItem = pageComposerContextService.getRequestContext().getSession() .getNodeByIdentifier(pageComposerContextService.getRequestConfigIdentifier()); return represent(currentContainerItem, getLocale(localeString), variantId); } catch (ClassNotFoundException e) { throw new ServerErrorException(e); } } @Override public Pair<Set<String>, Boolean> retainVariants(final Set<String> variants, final long versionStamp) throws RepositoryException { try { // use workflow session to write to preview final HippoSession userSession = (HippoSession) pageComposerContextService.getRequestContext().getSession(); DocumentWorkflow documentWorkflow = getObtainEditableInstanceWorkflow(userSession, pageComposerContextService); final boolean isCheckedOut = checkoutCorrectBranch(documentWorkflow, pageComposerContextService); final Session internalWorkflowSession = getInternalWorkflowSession(documentWorkflow); Node containerItem = getWorkspaceContainerItem(versionStamp, internalWorkflowSession, userSession.getUserID()); Set<String> removedVariants = doRetainVariants(containerItem, variants); if (!removedVariants.isEmpty()) { log.info("Modified variants, save unpublished"); updateVersionStamp(containerItem); documentWorkflow.saveUnpublished(); } log.info("Removed variants: {}", removedVariants); return new ImmutablePair<>(removedVariants, isCheckedOut); } catch (WorkflowException e) { throw new UnknownClientException(e.getMessage()); } } private Locale getLocale(final String localeString) { try { return LocaleUtils.toLocale(localeString); } catch (IllegalArgumentException e) { log.warn("Failed to create Locale from string '{}'. Using default locale", localeString); return Locale.getDefault(); } } @Override public Pair<Node, Boolean> deleteVariant(final String variantId, final long versionStamp) throws ClientException, RepositoryException { try { // use workflow session to write to preview final HippoSession userSession = (HippoSession) pageComposerContextService.getRequestContext().getSession(); DocumentWorkflow documentWorkflow = getObtainEditableInstanceWorkflow(userSession, pageComposerContextService); final boolean isCheckedOut = checkoutCorrectBranch(documentWorkflow, pageComposerContextService); final Session internalWorkflowSession = getInternalWorkflowSession(documentWorkflow); Node containerItem = getWorkspaceContainerItem(versionStamp, internalWorkflowSession, userSession.getUserID()); final XPageComponentParameters componentParameters = getCurrentHstComponentParameters(containerItem); if (!componentParameters.hasPrefix(variantId)) { throw new ClientException(String.format("Cannot delete variantId with id='%s'", variantId) , ClientError.ITEM_NOT_FOUND); } deleteVariant(componentParameters, variantId); // trigger the changes on unpublished node to be set componentParameters.setNodeChanges(); updateVersionStamp(containerItem); documentWorkflow.saveUnpublished(); log.info("Variant '{}' deleted successfully", variantId); return new ImmutablePair<>(containerItem, isCheckedOut); } catch (IllegalStateException | IllegalArgumentException | WorkflowException e) { log.warn("Could not delete variantId '{}'", variantId, e); throw new UnknownClientException("Could not delete the variantId"); } catch (RepositoryException e) { log.error("Could not delete variantId '{}'", variantId, e); throw e; } } @Override public Pair<Node, Boolean> updateVariant(final String variantId, final long versionStamp, final MultivaluedMap<String, String> params) throws ClientException, RepositoryException { try { // use workflow session to write to preview final HippoSession userSession = (HippoSession) pageComposerContextService.getRequestContext().getSession(); final DocumentWorkflow documentWorkflow = getObtainEditableInstanceWorkflow(userSession, pageComposerContextService); final boolean isCheckedOut = checkoutCorrectBranch(documentWorkflow, pageComposerContextService); final Session internalWorkflowSession = getInternalWorkflowSession(documentWorkflow); final Node containerItem = getWorkspaceContainerItem(versionStamp, internalWorkflowSession, userSession.getUserID()); final XPageComponentParameters componentParameters = getCurrentHstComponentParameters(containerItem); setParameters(componentParameters, variantId, params); // trigger the changes on unpublished node to be set componentParameters.setNodeChanges(); updateVersionStamp(containerItem); documentWorkflow.saveUnpublished(); log.info("Parameters for '{}' saved successfully.", variantId); return new ImmutablePair<>(containerItem, isCheckedOut); } catch (IllegalStateException | IllegalArgumentException | WorkflowException e) { log.warn("Could not save parameters for variant '{}'", variantId, e); throw new UnknownClientException(e.getMessage()); } catch (RepositoryException e) { log.warn("Could not save parameters for variant '{}'", variantId, e); throw e; } } @Override public Pair<Node, Boolean> moveAndUpdateVariant(final String oldVariantId, final String newVariantId, final long versionStamp, final MultivaluedMap<String, String> params) throws ClientException, RepositoryException { try { // use workflow session to write to preview final HippoSession userSession = (HippoSession) pageComposerContextService.getRequestContext().getSession(); DocumentWorkflow documentWorkflow = getObtainEditableInstanceWorkflow(userSession, pageComposerContextService); final boolean isCheckedOut = checkoutCorrectBranch(documentWorkflow, pageComposerContextService); final Session internalWorkflowSession = getInternalWorkflowSession(documentWorkflow); Node containerItem = getWorkspaceContainerItem(versionStamp, internalWorkflowSession, userSession.getUserID()); final XPageComponentParameters componentParameters = new XPageComponentParameters(containerItem); componentParameters.removePrefix(oldVariantId); componentParameters.removePrefix(newVariantId); setParameters(componentParameters, newVariantId, params); // trigger the changes on unpublished node to be set componentParameters.setNodeChanges(); updateVersionStamp(containerItem); documentWorkflow.saveUnpublished(); log.info("Parameters renamed from '{}' to '{}' and saved successfully.", oldVariantId, newVariantId); return new ImmutablePair<>(containerItem, isCheckedOut); } catch (IllegalStateException | IllegalArgumentException | WorkflowException e) { logParameterSettingFailed(e); throw new UnknownClientException(e.getMessage()); } catch (RepositoryException e) { logParameterSettingFailed(e); log.warn("Unable to set the parameters of component", e); throw e; } } private XPageComponentParameters getCurrentHstComponentParameters(final Node containerItem) throws RepositoryException { return new XPageComponentParameters(containerItem); } /** * Returns the WORKSPACE container item validated against the versionStamp of the parent container: if the parent container has * a different versionStamp than {@code versionStamp} a {@link ClientException} will be thrown. If the {@code versionStamp} * argument is 0, then the versionStamp check is omitted. * * Note that 'pageComposerContextService.getRequestConfigIdentifier()' can return a frozen node : this method returns * the 'workspace' version of that node, and if not found, a ItemNotFoundException will be thrown */ private Node getWorkspaceContainerItem(final long versionStamp, final Session workflowSession, final String cmsUserId) throws RepositoryException { final Node containerItem = getWorkspaceNode(workflowSession, pageComposerContextService.getRequestConfigIdentifier()); final Node container = containerItem.getParent(); validateTimestamp(versionStamp, container, cmsUserId); return containerItem; } /** * Deletes all parameters of a variantId. * * @param componentParameters the component parameters of the current container item * @param variantId the variantId to remove * @throws IllegalStateException when the variantId is the 'default' variantId */ private void deleteVariant(final XPageComponentParameters componentParameters, final String variantId) throws IllegalStateException { if (!componentParameters.removePrefix(variantId)) { throw new IllegalStateException("Variant '" + variantId + "' could not be removed"); } } private void setParameters(final XPageComponentParameters componentParameters, final String prefix, final MultivaluedMap<String, String> parameters) throws IllegalStateException { for (String parameterName : parameters.keySet()) { String parameterValue = parameters.getFirst(parameterName); componentParameters.setValue(prefix, parameterName, parameterValue); } } private void logParameterSettingFailed(final Exception e) { log.warn("Unable to set the parameters of component", e); } /** * Constructs a component node wrapper * * @param componentItemNode JcrNode for a component. * @param locale the locale to get localized names, can be null * @param prefix the parameter prefix * @throws RepositoryException Thrown if the repository exception occurred during reading of the properties. * @throws ClassNotFoundException thrown when this class can't instantiate the component class. */ private ContainerItemComponentRepresentation represent(final Node componentItemNode, final Locale locale, final String prefix) throws RepositoryException, ClassNotFoundException { final String contentPath = getContentPath(); final Mount editingMount = pageComposerContextService.getEditingMount(); final HstSite hstSite = editingMount.getHstSite(); final ExperiencePageService experiencePageService = HippoServiceRegistry.getService(ExperiencePageService.class); // 'componentItemNode' can be frozen node which is supported in experiencePageService.loadExperiencePageComponentItem final HstComponentConfiguration config = experiencePageService.loadExperiencePageComponentItem(componentItemNode, hstSite, PageComposerUtil.getEditingSiteClassLoader()); ParametersInfo parametersInfo = executeWithWebsiteClassLoader(node -> ParametersInfoAnnotationUtils.getParametersInfoAnnotation(config), componentItemNode); if (parametersInfo == null) { parametersInfo = defaultMissingParametersInfo; } List<ContainerItemComponentPropertyRepresentation> properties = getPopulatedProperties(parametersInfo.type(), locale, contentPath, prefix, componentItemNode, config, null, propertyPresentationFactories); ContainerItemComponentRepresentation representation = new ContainerItemComponentRepresentation(); representation.setProperties(properties); return representation; } private String getContentPath() { final HstRequestContext requestContext = RequestContextProvider.get(); if (requestContext != null) { return this.pageComposerContextService.getEditingMount().getContentPath(); } return StringUtils.EMPTY; } /** * Removes all variants that are not provided. * * @param containerItem the container item node * @param variants the variants to keep * @return a list of variants that have been removed * @throws RepositoryException when some repository exception happened */ private Set<String> doRetainVariants(final Node containerItem, final Set<String> variants) throws RepositoryException, IllegalStateException { final Set<String> keepVariants = new HashSet<>(); keepVariants.addAll(variants); final XPageComponentParameters componentParameters = new XPageComponentParameters(containerItem); final Set<String> removed = new HashSet<>(); for (String variant : componentParameters.getPrefixes()) { if (!keepVariants.contains(variant) && componentParameters.removePrefix(variant)) { log.debug("Removed configuration for variant {} of container item {}", variant, containerItem.getIdentifier()); removed.add(variant); } } if (!removed.isEmpty()) { componentParameters.setNodeChanges(); } log.info("Removed variants '{}'", removed.toString()); return removed; } // sets the new timestamp private void updateVersionStamp(final Node containerItem) throws RepositoryException { containerItem.getParent().setProperty(HstNodeTypes.GENERAL_PROPERTY_LAST_MODIFIED, System.currentTimeMillis()); } }
import {Component, Input, OnDestroy, OnInit} from '@angular/core'; import { SearchImageService } from '../service-module/ajaxCallService/search-image.service'; import {Image} from '../image'; import { SearchBooksService } from '../service-module/ajaxCallService/search-books.service'; import { Book } from '../book'; @Component({ selector: 'app-observable-call', templateUrl: './observable-call.component.html', styleUrls: ['./observable-call.component.css'] }) export class ObservableCallComponent implements OnInit, OnDestroy { private searchImage:SearchImageService; constructor(searchImage:SearchImageService, searchBook:SearchBooksService) { console.log('Constructor Call....'); this.searchImage = searchImage; this.searchBook = searchBook; this.isFonty = true; this.myColor = 9; } ngOnInit() { console.log('Make Ajax Call...'); } // for search images service @Input('prop1') myProp1:string; imagesList:Image[] = []; searchValue:string; takeSearchValue(event) { let sv = event.target.value; this.searchValue = sv; } callSearchImageService() { this.searchImage.getImagesFromGiphyServer(this.searchValue).subscribe((images)=> { this.imagesList = images['data']; console.log(images); }); } getMultipleCssClasses(flag:string) { let classes; if(flag == 'reject') { classes = { 'one': true, 'two': false } } else { classes = { 'one': false, 'two': true } } return classes; } // for search books service @Input('prop2') myProp2:string; @Input('prop4') myProp4:string; @Input('prop5') myProp5:string; private searchBook:SearchBooksService; booksList:Book[] = []; callSearchBooksServiceMethodGetAllBooks() { this.searchBook.getAllBooksFromServer().subscribe((book)=> { this.booksList = book['books']; console.log('Books Are :: ',book); }); } isFonty:boolean; myColor:number; category:string; year:string; booking:Book[]; takeCategory(event) { let c = event.target.value; this.category = c; } takeYear(event) { let y = event.target.value; this.year = y; } callSearchBooksServiceMethodFilterBooksByCategoryAndyear(cat:string, yaris:string) { cat = this.category; yaris = this.year; this.searchBook.filterBooksByCategoryAndYearFromServer(cat, yaris).subscribe((data)=> { this.booking = data['books']; console.log('Filter Data Is :: ',data); }); } ngOnDestroy() { console.log('Destroy Ajax Call....'); } }
// handleRegistered handles the registered websocket event func (ws *websocket) handleRegistered(c *astiws.Client, eventName string, payload json.RawMessage) error { ws.processQueue() ws.m.Lock() ws.isConnected = true ws.m.Unlock() astilog.Info("astibrain: brain has connected to bob") return nil }
<reponame>Gerguevara/passportTesting import {MigrationInterface, QueryRunner} from "typeorm"; export class creatingRelationsBtwUserCustomers1641153971721 implements MigrationInterface { name = 'creatingRelationsBtwUserCustomers1641153971721' public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE "user" DROP CONSTRAINT "FK_758b8ce7c18b9d347461b30228d"`); await queryRunner.query(`CREATE SEQUENCE IF NOT EXISTS "customer_id_seq" OWNED BY "customer"."id"`); await queryRunner.query(`ALTER TABLE "customer" ALTER COLUMN "id" SET DEFAULT nextval('"customer_id_seq"')`); await queryRunner.query(`ALTER TABLE "user" ADD CONSTRAINT "FK_758b8ce7c18b9d347461b30228d" FOREIGN KEY ("user_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE "user" DROP CONSTRAINT "FK_758b8ce7c18b9d347461b30228d"`); await queryRunner.query(`ALTER TABLE "customer" ALTER COLUMN "id" DROP DEFAULT`); await queryRunner.query(`DROP SEQUENCE "customer_id_seq"`); await queryRunner.query(`ALTER TABLE "user" ADD CONSTRAINT "FK_758b8ce7c18b9d347461b30228d" FOREIGN KEY ("user_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); } }
def load_wav_to_torch(wav_file, sample_rate): data, sr = librosa.load(wav_file, sample_rate) if len(data.shape) != 1: raise ValueError( f"the audio ({wav_file}) is not single channel." ) return torch.FloatTensor(data).unsqueeze(0), sr
/** * This implementation is motivated from several ideas to get a compact sparse set. * When using a a bucket of BitSet, problems * - smaller sizes of BitSet are not useful, since null references are themselves 64/32 bit references. * - larger sizes of BitSet for truly sparse integers, has overhead of too many zeroes in one BitSet. * <p> * The idea is to only store longs in buckets that have non-zero values where bucket sizes are longs. Bucket size of 64 longs are convenient when using mod operations. * <p> * Each bit in long value in indices array, indicates if a long value is initialized. 64 bits would point to 64 long values ( 1 bucket ). * Each bucket could contain 1-64 longs, we only hold non-zero long values in bucket. */ static class SparseBitSet { // shift used to determine which bucket and index private static final int BUCKET_SHIFT = 12; // shift used to determine which Long value to use in bucket. private static final int LONG_SHIFT = 6; private final int maxValue; private final long[] indices; private final long[][] buckets; SparseBitSet(int maxValue) { this.maxValue = maxValue; int totalBuckets = maxValue >>> BUCKET_SHIFT; indices = new long[totalBuckets + 1]; buckets = new long[totalBuckets + 1][]; } private SparseBitSet(int maxValue, long[] indices, long[][] buckets) { this.maxValue = maxValue; this.indices = indices; this.buckets = buckets; } private static int getIndex(int i) { // logical right shift return i >>> BUCKET_SHIFT; } // This method returns the number of Longs initialized from LSB to the given bitInIndex. // example if longAtIndex (64 bits) 00...1001 and bitInIndex (3) 000...100 // this method will return 1 since only one bit is set in index bits from left side to bitInIndex. private static int getOffset(long longAtIndex, long bitInIndex) { // set all bits to one before // example : 000... 100 will become 000...011 long setAllOnesBeforeBitInIndex = bitInIndex - 1; long offset = (longAtIndex & setAllOnesBeforeBitInIndex); // count of one's set in index to right of bitInIndex -> indicating which long to use in buckets return Long.bitCount(offset); } boolean get(int i) { if (i > maxValue) throw new IllegalArgumentException("Max value initialized is " + maxValue + " given value is " + i); if (i < 0) return false; int index = getIndex(i); long longAtIndex = indices[index]; // find which bit in index will point to the long in buckets long whichLong = i >>> LONG_SHIFT; long bitInIndex = 1L << whichLong;// whichLong % 64 long isLongInitialized = (longAtIndex & bitInIndex); if (isLongInitialized == 0) return false; int offset = getOffset(longAtIndex, bitInIndex); long value = buckets[index][offset]; long whichBitInLong = 1L << i; return (value & whichBitInLong) != 0; } void set(int i) { if (i > maxValue) throw new IllegalArgumentException("Max value initialized is " + maxValue + " given value is " + i); if (i < 0) throw new IllegalArgumentException("Cannot index negative numbers"); int index = getIndex(i); long longAtIndex = indices[index]; // find which bit in index will point to the long in buckets long whichLong = i >>> LONG_SHIFT; long bitInIndex = 1L << whichLong;// whichLong % 64 long whichBitInLong = 1L << i;// i % 64 // if that bit in index is set, means a Long value is initialized to set the (i % 64) boolean isLongInitialized = (longAtIndex & bitInIndex) != 0; if (isLongInitialized) { int offset = getOffset(longAtIndex, bitInIndex); buckets[index][offset] |= whichBitInLong;// or preserves previous set operations in this long. } else if (longAtIndex == 0) { // first set that bit in index long, so that index will be > 0 indices[index] = bitInIndex; buckets[index] = new long[]{whichBitInLong}; } else { // update long value at index indices[index] |= bitInIndex; longAtIndex = indices[index]; // find offset int offset = getOffset(longAtIndex, bitInIndex); int totalLongsInitialized = buckets[index].length; final long[] oldLongs = buckets[index]; long[] newLongs = new long[totalLongsInitialized + 1]; // if offset is 2 means 3 longs are needed starting from 0 // if current longs length is 2 (0,1) then append third long at end // if current longs length is greater than offset, then insert long 0 -> (offset - 1), new long, offset to (length -1) if (offset >= totalLongsInitialized) { // append new long at end int it; for (it = 0; it < totalLongsInitialized; it++) newLongs[it] = oldLongs[it]; newLongs[it] = whichBitInLong; } else { // insert new long in between int it; for (it = 0; it < offset; it++) newLongs[it] = oldLongs[it]; newLongs[offset] = whichBitInLong; for (it = offset; it < totalLongsInitialized; it++) newLongs[it + 1] = oldLongs[it]; } buckets[index] = newLongs; } } void clear(int i) { if (i > maxValue) throw new IllegalArgumentException("Max value initialized is " + maxValue + " given value is " + i); if (i < 0) throw new IllegalArgumentException("Cannot index negative numbers"); int index = getIndex(i); long longAtIndex = indices[index]; // find which bit in index will point to the long in buckets long whichLong = i >>> LONG_SHIFT; long bitInIndex = 1L << whichLong;// whichLong % 64 long whichBitInLong = 1L << i;// i % 64 long isLongInitialized = (longAtIndex & bitInIndex); if (isLongInitialized == 0) return; int offset = getOffset(longAtIndex, bitInIndex); long value = buckets[index][offset]; // unset whichBitInIndex in value // to clear 3rd bit (00100 whichBitInLong) in 00101(value), & with 11011 to get 00001 long updatedValue = value & ~whichBitInLong; if (updatedValue != 0) { buckets[index][offset] = updatedValue; } else { // if updatedValue is 0, then update the bucket removing that long int totalLongsInitialized = buckets[index].length; // if only one long was initialized in the bucket, then make the reference null, indexAtLong 0 if (totalLongsInitialized == 1) { buckets[index] = null; indices[index] = 0; } else { // copy everything over, except the long at the given offset, final long[] oldLongs = buckets[index]; long[] newLongs = new long[totalLongsInitialized - 1]; int it; for (it = 0; it < offset; it++) newLongs[it] = oldLongs[it]; it++; while (it < totalLongsInitialized) { newLongs[it - 1] = oldLongs[it]; it++; } buckets[index] = newLongs; // and unset bit in indexAtLong to indicate that no long is initialized at that offset. longAtIndex &= ~bitInIndex; indices[index] = longAtIndex; } } } int findMaxValue() { // find the last index that is initialized int index = indices.length - 1; while (index > 0) { if (indices[index] != 0) break; index--; } // find the highest bit in indexAtLong to see which is last long init in bucket int highestBitSetInIndexAtLong = 63 - Long.numberOfLeadingZeros(Long.highestOneBit(indices[index])); long[] longs = buckets[index]; long value = longs[longs.length - 1]; long highestBitSetInLong = 63 - Long.numberOfLeadingZeros(Long.highestOneBit(value)); return (int) ((index << BUCKET_SHIFT) + (highestBitSetInIndexAtLong << 6) + highestBitSetInLong); } int cardinality() { int cardinality = 0; int index = 0; while (index < indices.length) { if (indices[index] != 0) { long[] longs = buckets[index]; for (long value : longs) cardinality += Long.bitCount(value); } index++; } return cardinality; } long estimateBitsUsed() { long bucketsUsed = 0; long nullReferences = 0; int index = 0; while (index < indices.length) { if (indices[index] != 0) { bucketsUsed += buckets[index].length; } else { nullReferences++; } index++; } // total bits used // indices array long bitsUsedByIndices = indices.length * 64; long bitsUsedByBucketIndices = buckets.length * 64; long bitsUsedByBuckets = bucketsUsed * 64; long bitsUsedByNullReferences = nullReferences * 64; return bitsUsedByIndices + bitsUsedByBucketIndices + bitsUsedByBuckets + bitsUsedByNullReferences; } private long[] getIndices() { return indices; } private long[][] getBuckets() { return buckets; } /** * * Use this method to compact an existing SparseBitSet. Note any attempts to add a new value greater than the max value will result in exception. * * @param sparseBitSet * @return new SparseBitSet that is compact, does not hold null references beyond the max int value added in the given input. */ static SparseBitSet compact(SparseBitSet sparseBitSet) { int maxValueAdded = sparseBitSet.findMaxValue(); int indexForMaxValueAdded = getIndex(maxValueAdded); int newLength = indexForMaxValueAdded + 1; return cloneSparseBitSetWithNewLength(sparseBitSet, newLength, newLength, maxValueAdded); } static SparseBitSet resize(SparseBitSet sparseBitSet, int newMaxValue) { if (sparseBitSet.findMaxValue() < newMaxValue) { int indexForNewMaxValue = getIndex(newMaxValue); int newLength = indexForNewMaxValue + 1; return cloneSparseBitSetWithNewLength(sparseBitSet, newLength, sparseBitSet.getIndices().length, newMaxValue); } return sparseBitSet; } private static SparseBitSet cloneSparseBitSetWithNewLength(SparseBitSet sparseBitSet, int newLength, int lengthToClone, int newMaxValue) { long[] compactIndices = new long[newLength]; System.arraycopy(sparseBitSet.getIndices(), 0, compactIndices, 0, lengthToClone); long[][] compactBuckets = new long[newLength][]; System.arraycopy(sparseBitSet.getBuckets(), 0, compactBuckets, 0, lengthToClone); return new SparseBitSet(newMaxValue, compactIndices, compactBuckets); } }
// New is the constructor of combined func New(beaconChains ...beaconchain.BeaconChain) beaconchain.BeaconChain { return &combined{ beaconChains: beaconChains, } }
<filename>src/models/get_universe_types_type_id_ok.rs /* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 1.3.8 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ /// GetUniverseTypesTypeIdOk : 200 ok object #[allow(unused_imports)] use serde_json::Value; #[derive(Debug, Serialize, Deserialize)] pub struct GetUniverseTypesTypeIdOk { /// capacity number #[serde(rename = "capacity")] capacity: Option<f32>, /// description string #[serde(rename = "description")] description: String, /// dogma_attributes array #[serde(rename = "dogma_attributes")] dogma_attributes: Option<Vec<::models::GetUniverseTypesTypeIdDogmaAttribute>>, /// dogma_effects array #[serde(rename = "dogma_effects")] dogma_effects: Option<Vec<::models::GetUniverseTypesTypeIdDogmaEffect>>, /// graphic_id integer #[serde(rename = "graphic_id")] graphic_id: Option<i32>, /// group_id integer #[serde(rename = "group_id")] group_id: i32, /// icon_id integer #[serde(rename = "icon_id")] icon_id: Option<i32>, /// This only exists for types that can be put on the market #[serde(rename = "market_group_id")] market_group_id: Option<i32>, /// mass number #[serde(rename = "mass")] mass: Option<f32>, /// name string #[serde(rename = "name")] name: String, /// packaged_volume number #[serde(rename = "packaged_volume")] packaged_volume: Option<f32>, /// portion_size integer #[serde(rename = "portion_size")] portion_size: Option<i32>, /// published boolean #[serde(rename = "published")] published: bool, /// radius number #[serde(rename = "radius")] radius: Option<f32>, /// type_id integer #[serde(rename = "type_id")] type_id: i32, /// volume number #[serde(rename = "volume")] volume: Option<f32> } impl GetUniverseTypesTypeIdOk { /// 200 ok object pub fn new(description: String, group_id: i32, name: String, published: bool, type_id: i32) -> GetUniverseTypesTypeIdOk { GetUniverseTypesTypeIdOk { capacity: None, description: description, dogma_attributes: None, dogma_effects: None, graphic_id: None, group_id: group_id, icon_id: None, market_group_id: None, mass: None, name: name, packaged_volume: None, portion_size: None, published: published, radius: None, type_id: type_id, volume: None } } pub fn set_capacity(&mut self, capacity: f32) { self.capacity = Some(capacity); } pub fn with_capacity(mut self, capacity: f32) -> GetUniverseTypesTypeIdOk { self.capacity = Some(capacity); self } pub fn capacity(&self) -> Option<&f32> { self.capacity.as_ref() } pub fn reset_capacity(&mut self) { self.capacity = None; } pub fn set_description(&mut self, description: String) { self.description = description; } pub fn with_description(mut self, description: String) -> GetUniverseTypesTypeIdOk { self.description = description; self } pub fn description(&self) -> &String { &self.description } pub fn set_dogma_attributes(&mut self, dogma_attributes: Vec<::models::GetUniverseTypesTypeIdDogmaAttribute>) { self.dogma_attributes = Some(dogma_attributes); } pub fn with_dogma_attributes(mut self, dogma_attributes: Vec<::models::GetUniverseTypesTypeIdDogmaAttribute>) -> GetUniverseTypesTypeIdOk { self.dogma_attributes = Some(dogma_attributes); self } pub fn dogma_attributes(&self) -> Option<&Vec<::models::GetUniverseTypesTypeIdDogmaAttribute>> { self.dogma_attributes.as_ref() } pub fn reset_dogma_attributes(&mut self) { self.dogma_attributes = None; } pub fn set_dogma_effects(&mut self, dogma_effects: Vec<::models::GetUniverseTypesTypeIdDogmaEffect>) { self.dogma_effects = Some(dogma_effects); } pub fn with_dogma_effects(mut self, dogma_effects: Vec<::models::GetUniverseTypesTypeIdDogmaEffect>) -> GetUniverseTypesTypeIdOk { self.dogma_effects = Some(dogma_effects); self } pub fn dogma_effects(&self) -> Option<&Vec<::models::GetUniverseTypesTypeIdDogmaEffect>> { self.dogma_effects.as_ref() } pub fn reset_dogma_effects(&mut self) { self.dogma_effects = None; } pub fn set_graphic_id(&mut self, graphic_id: i32) { self.graphic_id = Some(graphic_id); } pub fn with_graphic_id(mut self, graphic_id: i32) -> GetUniverseTypesTypeIdOk { self.graphic_id = Some(graphic_id); self } pub fn graphic_id(&self) -> Option<&i32> { self.graphic_id.as_ref() } pub fn reset_graphic_id(&mut self) { self.graphic_id = None; } pub fn set_group_id(&mut self, group_id: i32) { self.group_id = group_id; } pub fn with_group_id(mut self, group_id: i32) -> GetUniverseTypesTypeIdOk { self.group_id = group_id; self } pub fn group_id(&self) -> &i32 { &self.group_id } pub fn set_icon_id(&mut self, icon_id: i32) { self.icon_id = Some(icon_id); } pub fn with_icon_id(mut self, icon_id: i32) -> GetUniverseTypesTypeIdOk { self.icon_id = Some(icon_id); self } pub fn icon_id(&self) -> Option<&i32> { self.icon_id.as_ref() } pub fn reset_icon_id(&mut self) { self.icon_id = None; } pub fn set_market_group_id(&mut self, market_group_id: i32) { self.market_group_id = Some(market_group_id); } pub fn with_market_group_id(mut self, market_group_id: i32) -> GetUniverseTypesTypeIdOk { self.market_group_id = Some(market_group_id); self } pub fn market_group_id(&self) -> Option<&i32> { self.market_group_id.as_ref() } pub fn reset_market_group_id(&mut self) { self.market_group_id = None; } pub fn set_mass(&mut self, mass: f32) { self.mass = Some(mass); } pub fn with_mass(mut self, mass: f32) -> GetUniverseTypesTypeIdOk { self.mass = Some(mass); self } pub fn mass(&self) -> Option<&f32> { self.mass.as_ref() } pub fn reset_mass(&mut self) { self.mass = None; } pub fn set_name(&mut self, name: String) { self.name = name; } pub fn with_name(mut self, name: String) -> GetUniverseTypesTypeIdOk { self.name = name; self } pub fn name(&self) -> &String { &self.name } pub fn set_packaged_volume(&mut self, packaged_volume: f32) { self.packaged_volume = Some(packaged_volume); } pub fn with_packaged_volume(mut self, packaged_volume: f32) -> GetUniverseTypesTypeIdOk { self.packaged_volume = Some(packaged_volume); self } pub fn packaged_volume(&self) -> Option<&f32> { self.packaged_volume.as_ref() } pub fn reset_packaged_volume(&mut self) { self.packaged_volume = None; } pub fn set_portion_size(&mut self, portion_size: i32) { self.portion_size = Some(portion_size); } pub fn with_portion_size(mut self, portion_size: i32) -> GetUniverseTypesTypeIdOk { self.portion_size = Some(portion_size); self } pub fn portion_size(&self) -> Option<&i32> { self.portion_size.as_ref() } pub fn reset_portion_size(&mut self) { self.portion_size = None; } pub fn set_published(&mut self, published: bool) { self.published = published; } pub fn with_published(mut self, published: bool) -> GetUniverseTypesTypeIdOk { self.published = published; self } pub fn published(&self) -> &bool { &self.published } pub fn set_radius(&mut self, radius: f32) { self.radius = Some(radius); } pub fn with_radius(mut self, radius: f32) -> GetUniverseTypesTypeIdOk { self.radius = Some(radius); self } pub fn radius(&self) -> Option<&f32> { self.radius.as_ref() } pub fn reset_radius(&mut self) { self.radius = None; } pub fn set_type_id(&mut self, type_id: i32) { self.type_id = type_id; } pub fn with_type_id(mut self, type_id: i32) -> GetUniverseTypesTypeIdOk { self.type_id = type_id; self } pub fn type_id(&self) -> &i32 { &self.type_id } pub fn set_volume(&mut self, volume: f32) { self.volume = Some(volume); } pub fn with_volume(mut self, volume: f32) -> GetUniverseTypesTypeIdOk { self.volume = Some(volume); self } pub fn volume(&self) -> Option<&f32> { self.volume.as_ref() } pub fn reset_volume(&mut self) { self.volume = None; } }
<filename>realworld/infra/src/main/java/com/msjc/realworld/infra/dmr/readservice/TagReadService.java package com.msjc.realworld.infra.dmr.readservice; import java.util.List; import org.apache.ibatis.annotations.Mapper; @Mapper public interface TagReadService { List<String> all(); }
/* *---------------------------------------------------------------------- * * printString -- * * Dump the string representation of an object to stdout. This * function is purely for debugging purposes. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void printString( JNIEnv *env, jobject object) { JavaInfo* jcache = JavaGetCache(); jstring string = (*env)->CallObjectMethod(env, object, jcache->toString); const char *str = (*env)->GetStringUTFChars(env, string, NULL); printf("toString: %x '%s'\n", (unsigned int) object, str); (*env)->ReleaseStringUTFChars(env, string, str); (*env)->DeleteLocalRef(env, string); }
def with_masked_annotations(self, annot_types, mask_char=None, shadow=False): masked_seqs = [] for seq in self.seqs: masked_seqs += [seq._masked_annotations(annot_types, mask_char, shadow)] new = self.__class__(data=masked_seqs, info=self.info, name=self.name) return new
<gh_stars>1-10 module AOC.Day01 where import AOC.Common.Prelude import Data.List import Data.Maybe type Input = [Int] parser :: Parser Input parser = many integer one :: Input -> Int one xs = fromMaybe 0 . fmap (\(a, b) -> a * b) . find (\(a, b) -> a + b == 2020) $ (,) <$> xs <*> xs two :: Input -> Int two xs = fromMaybe 0 . fmap (\(a, b, c) -> a * b * c) . find (\(a, b, c) -> a + b + c == 2020) $ (,,) <$> xs <*> xs <*> xs tests :: SpecWith () tests = do let exampleInput = [1721, 979, 366, 299, 675, 1456] describe "examples" $ do it "should solve example part 1" $ do one exampleInput `shouldBe` 514579 it "should solve example part 2" $ do two exampleInput `shouldBe` 241861950 inputFile :: FilePath inputFile = "inputs/day01.txt" commands :: [(Text, IO ())] commands = [] today :: Day [Int] Int Int today = day parser (pure . one) (pure . two) tests inputFile commands
<reponame>bonniech3n/merou from selenium.webdriver.support.select import Select from itests.pages.base import BaseModal, BasePage class ServiceAccountViewPage(BasePage): def click_disable_button(self): button = self.find_element_by_class_name("disable-service-account") button.click() def click_enable_button(self): button = self.find_element_by_class_name("enable-service-account") button.click() def get_disable_modal(self): element = self.find_element_by_id("disableModal") self.wait_until_visible(element) return DisableServiceAccountModal(element) class ServiceAccountCreatePage(BasePage): def _get_new_service_account_form(self): return self.find_element_by_class_name("new-service-account-form") def set_name(self, name): form = self._get_new_service_account_form() field = form.find_element_by_name("name") field.send_keys(name) def submit(self): form = self._get_new_service_account_form() form.submit() class ServiceAccountEnablePage(BasePage): def _get_enable_service_account_form(self): return self.find_element_by_class_name("enable-service-account-form") def select_owner(self, owner): form = self._get_enable_service_account_form() owner_select = form.find_element_by_tag_name("select") Select(owner_select).select_by_visible_text(owner) def submit(self): form = self._get_enable_service_account_form() form.submit() class DisableServiceAccountModal(BaseModal): pass
#pragma version(1) #pragma rs java_package_name(cn.louispeng.imagefilter.renderscript) // 参数化边缘检测效果 #include "Clamp.rsh" #include "YUV.rsh" typedef float3 (*PF) (int32_t, int32_t); // set from the java SDK level rs_allocation gIn; rs_allocation gOut; rs_script gScript; int32_t gDoGrayConversion = 1; int32_t gDoInversion = 1; float gThreshold = 0.25f; float gK00 = 1.0f; float gK01 = 2.0f; float gK02 = 1.0f; // Magic factors static float gThresholdSq; // Static variables static uint32_t _width; static uint32_t _height; static PF processFunction; static float3 _getColor(int32_t x, int32_t y) { int32_t theX = x, theY = y; if (theX < 0) { theX = 0; } else if (theX >= _width) { theX = _width - 1; } if (theY < 0) { theY = 0; } else if (theY >= _height) { theY = _height - 1; } return rsUnpackColor8888(*(const uchar4*)rsGetElementAt(gIn, theX, theY)).rgb; } static float3 ProcessColor(int32_t x, int32_t y) { float3 color1 = 0, color2 = 0, color3 = 0, color4 = 0, color5 = 0, color6 = 0, color7 = 0, color8 = 0; color1 = _getColor(x - 1, y - 1); color2 = _getColor(x, y - 1); color3 = _getColor(x + 1, y - 1); color4 = _getColor(x - 1, y); color5 = _getColor(x + 1, y); color6 = _getColor(x - 1, y + 1); color7 = _getColor(x, y + 1); color8 = _getColor(x + 1, y + 1); float3 rgb = {0, 0, 0}; float colorSum1 = color1.r * gK00 + color2.r * gK01 + color3.r * gK02 + color6.r * (-gK00) + color7.r * (-gK01) + color8.r * (-gK02); float colorSum2 = color1.r * gK00 + color3.r * (-gK00) + color4.r * gK01 + color6.r * gK02 + color5.r * (-gK01) + color8.r * (-gK02); if (gDoInversion == 1) { rgb.r = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 1.0f : 0.0f; } else { rgb.r = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 0.0f : 1.0f; } colorSum1 = color1.g * gK00 + color2.g * gK01 + color3.g * gK02 + color6.g * (-gK00) + color7.g * (-gK01) + color8.g * (-gK02); colorSum2 = color1.g * gK00 + color3.g * (-gK00) + color4.g * gK01 + color6.g * gK02 + color5.g * (-gK01) + color8.g * (-gK02); if (gDoInversion == 1) { rgb.g = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 1.0f : 0.0f; } else { rgb.g = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 0.0f : 1.0f; } colorSum1 = color1.b * gK00 + color2.b * gK01 + color3.b * gK02 + color6.b * (-gK00) + color7.b * (-gK01) + color8.b * (-gK02); colorSum2 = color1.b * gK00 + color3.b * (-gK00) + color4.b * gK01 + color6.b * gK02 + color5.b * (-gK01) + color8.b * (-gK02); if (gDoInversion == 1) { rgb.b = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 1.0f : 0.0f; } else { rgb.b = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 0.0f : 1.0f; } return rgb; } static float3 ProcessGray(int32_t x, int32_t y) { float color1 = 0, color2 = 0, color3 = 0, color4 = 0, color5 = 0, color6 = 0, color7 = 0, color8 = 0; color1 = GetGrayscale(_getColor(x - 1, y - 1)); color2 = GetGrayscale(_getColor(x, y - 1)); color3 = GetGrayscale(_getColor(x + 1, y - 1)); color4 = GetGrayscale(_getColor(x - 1, y)); color5 = GetGrayscale(_getColor(x + 1, y)); color6 = GetGrayscale(_getColor(x - 1, y + 1)); color7 = GetGrayscale(_getColor(x, y + 1)); color8 = GetGrayscale(_getColor(x + 1, y + 1)); float colorSum1 = color1 * gK00 + color2 * gK01 + color3 * gK02 + color6 * (-gK00) + color7 * (-gK01) + color8 * (-gK02); float colorSum2 = color1 * gK00 + color3 * (-gK00) + color4 * gK01 + color5 * (-gK01) + color6 * gK02 + color8 * (-gK02); float color; if (gDoInversion == 1) { color = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 1.0f : 0.0f; } else { color = (((colorSum1 * colorSum1) + (colorSum2 * colorSum2)) > gThresholdSq) ? 0.0f : 1.0f; } float3 rgb = {color, color, color}; return rgb; } static void setup() { _width = rsAllocationGetDimX(gIn); _height = rsAllocationGetDimY(gIn); float gThresholdSqFactor = gThreshold * 2.0f; gThresholdSq = gThresholdSqFactor * gThresholdSqFactor; if (gDoGrayConversion == 1) { processFunction = ProcessGray; } else { processFunction = ProcessColor; } } void filter() { setup(); rsForEach(gScript, gIn, gOut, 0, 0); // for each element of the input allocation, // call root() method on gScript } void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) { *v_out = rsPackColorTo8888(processFunction(x, y)); }
class Classical: """ Written by: Asheka This class contains methods for time series forecasting with arima model, where the parameters (p,d,q) need to input manually. """ def __init__(self, frame): self.frame = frame self._order = 0, 0, 0 def get_get_timeseries(self): """ From a dataframe column with "Average_Water_Level" is selected as timeseries""" a = self.frame my_timeseries = a["Average_Water_Level"] return my_timeseries def adf_test(self, timeseries): """Perform Dickey-Fuller test to check if the data is stationary or not""" print('Results of Dickey-Fuller Test:') dftest = adfuller(timeseries) print('p-value: %f' % dftest[1]) print("ADF statistics:%f" % dftest[0]) if dftest[1] <= 0.05: print("p value less than 0.05. Data is stationary") else: print("p value greater than 0.05.Data is non stationary") return 0 @property # property decorator def my_order(self): return self._order @my_order.setter def my_order(self, new_order): """ order need to be in tuple or in string """ if isinstance(new_order, tuple): self._order = new_order elif isinstance(new_order, str): self._order = tuple(map(int, new_order.split(','))) else: print("enter a valid order") return new_order def my_train_model(self): """ predict for train data set""" train = self.get_get_timeseries()[:50] try: pred_model = ARIMA(train, order=self.my_order).fit() pred_fit = pred_model.predict(start=len(train), end=len(self.frame) - 1) except KeyError: print("no such list with column name") return pred_fit def my_forecast(self): """ Predict data for a time series""" final_model = ARIMA(self.get_get_timeseries(), order=self.my_order).fit() final_fit = (final_model.predict(start=len(self.frame), end=len(self.frame) + 9)) return final_fit def __call__(self): """ Magic method to print the root mean squared error, and co-relation coefficient""" test = self.get_get_timeseries()[50:] errors = np.sqrt(mean_squared_error(test, self.my_train_model())) rsq = test.corr(self.my_train_model()) print("my chosen order (p, d, q) for ARIMA model is {} ".format(self.my_order)) print("model error(rmse) is {} and correlation coefficient is {}".format(errors, rsq)) return -1
<gh_stars>0 import React from 'react' import {IndexBar} from 'antd-mobile' export default () => { const getRandomList = (min: number, max: number): string[] => { return new Array(Math.floor(Math.random() * (max - min) + min)).fill('') } const ItemList = (() => { const charCodeOfA = 'A'.charCodeAt(0) const indexList = Array(26) .fill('') .map((_, i) => String.fromCharCode(charCodeOfA + i)) return indexList })() return ( <div style={{height: '500px'}}> <IndexBar> {ItemList.map(item => { return ( <IndexBar.Panel index={item} title={`标题${item}`} key={`标题${item}`} > {getRandomList(3, 10).map(() => ( <div key={Math.random()}>文本</div> ))} </IndexBar.Panel> ) })} </IndexBar> </div> ) }
/** * set the saveButton and the loadSaveButton */ private void prepareSaveButtons(){ saveButton = new CustomButton(50, 550,WR,HR,"saveButton.png", (byte) 1); saveButton.overlay.addEventHandler(MouseEvent.MOUSE_CLICKED, e->{ String name = CompleteFieldBox.display("Enter a file name", "Enter the name you want to use for the file.\nLeave blank for an automatic file name.", "File name..."); if (name != null) { LevelSaver.saveLevel(movesHistory, currentCampaignLevel, name, currentLevelText.getText()); } }); loadSaveButton = new CustomButton(50, 600, WR,HR,"loadSaveButton.png", (byte) 1); loadSaveButton.overlay.addEventHandler(MouseEvent.MOUSE_CLICKED, e->{ String fileName = CompleteFieldBox.displayFileSelector("Enter file name", "File name :", "File name..."); if (fileName != null && !fileName.equals("")) { ArrayList<Direction> res = LevelSaver.getHistory(fileName, ""); if (res != null) { for (Direction dir : res) { applyMove(dir); } } } }); }
<gh_stars>1-10 #!/bin/env # -*- coding: utf-8 -*- """ This hello-world python module illustrates how to include data files in an ISPy package. The file `package_data' simply contains a list of filenames and/or patterns to be included. This module implements the function `hello' that forwards the contents of `hello.txt' to the standard output. """ from hello import hello
/** * Protocol which prints out the real size of a message. Don't use this layer in * a production stack since the costs are high (just for debugging). * * @author Bela Ban June 13 2001 */ public class SIZE extends Protocol { protected final List<Address> members=new ArrayList<>(); @Property protected boolean print_msg=false; @Property protected boolean raw_buffer=false; // just print the payload size of the message /** Min size in bytes above which msgs should be printed */ protected @Property long min_size; protected Address local_addr; public Object up(Message msg) { if(log.isTraceEnabled()) { int size=raw_buffer? msg.getLength() : msg.size(); if(size >= min_size) { StringBuilder sb=new StringBuilder(local_addr + ".up(): size of message buffer="); sb.append(Util.printBytes(size)).append(", " + numHeaders(msg) + " headers"); if(print_msg) sb.append(", headers=" + msg.printHeaders()); log.trace(sb); } } return up_prot.up(msg); } public void up(MessageBatch batch) { if(log.isTraceEnabled()) { long size=raw_buffer? batch.length() : batch.totalSize(); if(size >= min_size) { StringBuilder sb=new StringBuilder(local_addr + ".up(): size of message batch="); sb.append(Util.printBytes(size)).append(", " + batch.size() + " messages, " + numHeaders(batch) + " headers"); log.trace(sb); } } up_prot.up(batch); } public Object down(Event evt) { switch(evt.getType()) { case Event.SET_LOCAL_ADDRESS: local_addr=evt.getArg(); break; } return down_prot.down(evt); // Pass on to the layer below us } public Object down(Message msg) { if(log.isTraceEnabled()) { int size=raw_buffer? msg.getLength() : msg.size(); if(size >= min_size) { StringBuilder sb=new StringBuilder(local_addr + ".down(): size of message buffer="); sb.append(Util.printBytes(size)).append(", " + numHeaders(msg) + " headers"); if(print_msg) sb.append(", headers=" + msg.printHeaders()); log.trace(sb); } } return down_prot.down(msg); } protected static int numHeaders(Message msg) { return msg == null? 0 : msg.getNumHeaders(); } protected static int numHeaders(MessageBatch batch) { int retval=0; for(Message msg: batch) retval+=numHeaders(msg); return retval; } }
#include <algorithm> #include <iostream> #include <cstring> #include <vector> #include <parallel/algorithm> #include <pam/pam.h> #include <pam/get_time.h> timer init_tm, build_tm, total_tm, aug_tm, sort_tm, reserve_tm, outmost_tm, globle_tm, g_tm; double early; template<typename c_type, typename w_type> struct RangeQuery { using x_type = c_type; using y_type = c_type; using point_type = Point<c_type, w_type>; using point_x = pair<x_type, y_type>; using point_y = pair<y_type, x_type>; using main_entry = pair<point_x, w_type>; struct inner_map_t { using key_t = point_y; using val_t = w_type; static bool comp(key_t a, key_t b) { return a < b;} using aug_t = w_type; inline static aug_t from_entry(key_t k, val_t v) { return v; } inline static aug_t combine(aug_t a, aug_t b) { return a+b; } static aug_t get_empty() { return 0;} }; using inner_map = aug_map<inner_map_t>; struct outer_map_t { using key_t = point_x; using val_t = w_type; static bool comp(key_t a, key_t b) { return a < b;} using aug_t = inner_map; inline static aug_t from_entry(key_t k, val_t v) { return aug_t({make_pair(point_y(k.second, k.first), v)}); } inline static aug_t combine(aug_t a, aug_t b) { return aug_t::map_union(a, b, [](w_type x, w_type y) {return x+y;}); } static aug_t get_empty() { return aug_t();} }; using outer_map = aug_map<outer_map_t>; RangeQuery(sequence<point_type>& points) { construct(points); } ~RangeQuery() { } static void reserve(size_t n) { reserve_tm.start(); outer_map::reserve(n); inner_map::reserve(24*n); reserve_tm.stop(); } static void finish() { outer_map::finish(); inner_map::finish(); } void construct(sequence<point_type>& points) { const size_t n = points.size(); reserve(n); total_tm.start(); auto pointsEle = tabulate(n, [&] (size_t i) -> pair<point_x, w_type> { return make_pair(make_pair(points[i].x, points[i].y), points[i].w); }); range_tree = outer_map(pointsEle); total_tm.stop(); } struct count_t { point_y y1, y2; int r; count_t(point_y y1, point_y y2) : y1(y1), y2(y2), r(0) {} void add_entry(pair<point_x,w_type> e) { if (e.first.second >= y1.first && e.first.second <= y2.first) r += 1; } void add_aug_val(inner_map a) { r += (a.rank(y2) - a.rank(y1));} }; w_type query_count(x_type x1, y_type y1, x_type x2, y_type y2) { count_t qrc(make_pair(y1,x1), make_pair(y2,x2)); range_tree.range_sum(make_pair(x1,y1), make_pair(x2,y2), qrc); return qrc.r; } struct sum_t { point_y y1, y2; int r; sum_t(point_y y1, point_y y2) : y1(y1), y2(y2), r(0) {} void add_entry(pair<point_x,w_type> e) { if (e.first.second >= y1.first && e.first.second <= y2.first) r += e.second; } void add_aug_val(inner_map a) { r += a.aug_range(y1, y2); } }; w_type query_sum(x_type x1, y_type y1, x_type x2, y_type y2) { sum_t qrs(make_pair(y1,x1), make_pair(y2,x2)); range_tree.range_sum(make_pair(x1,y1), make_pair(x2,y2), qrs); return qrs.r; } struct range_t { point_y y1, y2; point_y* out; range_t(point_y y1, point_y y2, point_y* out) : y1(y1), y2(y2), out(out) {} void add_entry(pair<point_x,w_type> e) { if (e.first.second >= y1.first && e.first.second <= y2.first) { *out++ = point_y(e.first.second,e.first.second);} } void add_aug_val(inner_map a) { inner_map r = inner_map::range(a, y1, y2); size_t s = r.size(); inner_map::keys(r,out); out += s; } }; sequence<point_y> query_range(x_type x1, y_type y1, x_type x2, y_type y2) { size_t n = query_count(x1,y1,x2,y2); auto out = sequence<point_y>::uninitialized(n); range_t qr(point_y(y1, x1), point_y(y2, x2), out.data()); range_tree.range_sum(point_x(x1, y1), point_x(x2, y2), qr); return out; } void insert_point(point_type p) { range_tree.insert(make_pair(make_pair(p.x, p.y), p.w)); } void insert_point_lazy(point_type p) { range_tree = outer_map::insert_lazy(std::move(range_tree), make_pair(make_pair(p.x, p.y), p.w)); } void print_status() { cout << "Outer Map: "; outer_map::GC::print_stats(); cout << "Inner Map: "; inner_map::GC::print_stats(); } bool find(point_type p) { return range_tree.find(make_pair(p.x, p.y)); } outer_map range_tree; };